Java Code Examples for org.apache.bcel.generic.Type#getType()
The following examples show how to use
org.apache.bcel.generic.Type#getType() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BCELifier.java From commons-bcel with Apache License 2.0 | 6 votes |
static String printType( final String signature ) { final Type type = Type.getType(signature); final byte t = type.getType(); if (t <= Const.T_VOID) { return "Type." + Const.getTypeName(t).toUpperCase(Locale.ENGLISH); } else if (type.toString().equals("java.lang.String")) { return "Type.STRING"; } else if (type.toString().equals("java.lang.Object")) { return "Type.OBJECT"; } else if (type.toString().equals("java.lang.StringBuffer")) { return "Type.STRINGBUFFER"; } else if (type instanceof ArrayType) { final ArrayType at = (ArrayType) type; return "new ArrayType(" + printType(at.getBasicType()) + ", " + at.getDimensions() + ")"; } else { return "new ObjectType(\"" + Utility.signatureToString(signature, false) + "\")"; } }
Example 2
Source File: BCELifier.java From commons-bcel with Apache License 2.0 | 6 votes |
static String printType( final String signature ) { final Type type = Type.getType(signature); final byte t = type.getType(); if (t <= Const.T_VOID) { return "Type." + Const.getTypeName(t).toUpperCase(Locale.ENGLISH); } else if (type.toString().equals("java.lang.String")) { return "Type.STRING"; } else if (type.toString().equals("java.lang.Object")) { return "Type.OBJECT"; } else if (type.toString().equals("java.lang.StringBuffer")) { return "Type.STRINGBUFFER"; } else if (type instanceof ArrayType) { final ArrayType at = (ArrayType) type; return "new ArrayType(" + printType(at.getBasicType()) + ", " + at.getDimensions() + ")"; } else { return "new ObjectType(\"" + Utility.signatureToString(signature, false) + "\")"; } }
Example 3
Source File: Pass3aVerifier.java From commons-bcel with Apache License 2.0 | 6 votes |
/** Checks if the constraints of operands of the said instruction(s) are satisfied. */ @Override public void visitNEW(final NEW o) { indexValid(o, o.getIndex()); final Constant c = constantPoolGen.getConstant(o.getIndex()); if (! (c instanceof ConstantClass)) { constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '"+c+"'."); } else{ final ConstantUtf8 cutf8 = (ConstantUtf8) (constantPoolGen.getConstant( ((ConstantClass) c).getNameIndex() )); final Type t = Type.getType("L"+cutf8.getBytes()+";"); if (t instanceof ArrayType) { constraintViolated(o, "NEW must not be used to create an array."); } } }
Example 4
Source File: LDAPSSLSocketFactoryGenerator.java From qpid-broker-j with Apache License 2.0 | 5 votes |
/** * Create a static method 'getDefault' returning {@link SocketFactory} * that creates a new instance of the sub-class and calls its no-argument * constructor, the newly created is returned to the caller. * * @param classGen * @param constantPoolGen * @param instructionFactory */ private static void createGetDefaultStaticMethod(ClassGen classGen, ConstantPoolGen constantPoolGen, InstructionFactory instructionFactory) { InstructionList il = new InstructionList(); String methodName = "getDefault"; MethodGen mg = new MethodGen(ACC_STATIC | ACC_PUBLIC, // access flags Type.getType(SSLSocketFactory.class), // return type new Type[0], // argument types - no args new String[0], // arg names - no args methodName, classGen.getClassName(), // method, class il, constantPoolGen); il.append(instructionFactory.createNew(classGen.getClassName())); il.append(InstructionConst.DUP); il.append(instructionFactory.createInvoke(classGen.getClassName(), "<init>", Type.VOID, new Type[] {}, INVOKESPECIAL)); il.append(InstructionConst.ARETURN); mg.setMaxStack(); classGen.addMethod(mg.getMethod()); il.dispose(); }
Example 5
Source File: Pass2Verifier.java From commons-bcel with Apache License 2.0 | 5 votes |
@Override public void visitConstantFieldref(final ConstantFieldref obj) { if (obj.getTag() != Const.CONSTANT_Fieldref) { throw new ClassConstraintException("ConstantFieldref '"+tostring(obj)+"' has wrong tag!"); } final int name_and_type_index = obj.getNameAndTypeIndex(); final ConstantNameAndType cnat = (ConstantNameAndType) (cp.getConstant(name_and_type_index)); final String name = ((ConstantUtf8) (cp.getConstant(cnat.getNameIndex()))).getBytes(); // Field or Method name if (!validFieldName(name)) { throw new ClassConstraintException("Invalid field name '"+name+"' referenced by '"+tostring(obj)+"'."); } final int class_index = obj.getClassIndex(); final ConstantClass cc = (ConstantClass) (cp.getConstant(class_index)); final String className = ((ConstantUtf8) (cp.getConstant(cc.getNameIndex()))).getBytes(); // Class Name in internal form if (! validClassName(className)) { throw new ClassConstraintException("Illegal class name '"+className+"' used by '"+tostring(obj)+"'."); } final String sig = ((ConstantUtf8) (cp.getConstant(cnat.getSignatureIndex()))).getBytes(); // Field or Method sig.(=descriptor) try{ Type.getType(sig); /* Don't need the return value */ } catch (final ClassFormatException cfe) { throw new ClassConstraintException("Illegal descriptor (==signature) '"+sig+"' used by '"+tostring(obj)+"'.", cfe); } }
Example 6
Source File: ExceptionObjectType.java From spotbugs with GNU Lesser General Public License v2.1 | 5 votes |
/** * Initialize object from an exception set. * * @param exceptionSet * the exception set * @return a Type that is a supertype of all of the exceptions in the * exception set */ public static Type fromExceptionSet(ExceptionSet exceptionSet) throws ClassNotFoundException { Type commonSupertype = exceptionSet.getCommonSupertype(); if (commonSupertype.getType() != Const.T_OBJECT) { return commonSupertype; } ObjectType exceptionSupertype = (ObjectType) commonSupertype; String className = exceptionSupertype.getClassName(); if ("java.lang.Throwable".equals(className)) { return exceptionSupertype; } return new ExceptionObjectType(className, exceptionSet); }
Example 7
Source File: FieldStoreTypeDatabase.java From spotbugs with GNU Lesser General Public License v2.1 | 5 votes |
public void purgeBoringEntries() { Collection<FieldDescriptor> keys = new ArrayList<>(getKeys()); for (FieldDescriptor f : keys) { FieldStoreType type = getProperty(f); Type fieldType = Type.getType(f.getSignature()); if (!(fieldType instanceof ReferenceType)) { removeProperty(f); continue; } ReferenceType storeType = type.getLoadType((ReferenceType) fieldType); if (storeType.equals(fieldType)) { removeProperty(f); } } }
Example 8
Source File: FieldSummary.java From spotbugs with GNU Lesser General Public License v2.1 | 5 votes |
public void mergeSummary(XField fieldOperand, OpcodeStack.Item mergeValue) { if (SystemProperties.ASSERTIONS_ENABLED) { String mSignature = mergeValue.getSignature(); Type mergeType = Type.getType(mSignature); Type fieldType = Type.getType(fieldOperand.getSignature()); IncompatibleTypes check = IncompatibleTypes.getPriorityForAssumingCompatible(mergeType, fieldType, false); if (check.getPriority() <= Priorities.NORMAL_PRIORITY) { AnalysisContext.logError(fieldOperand + " not compatible with " + mergeValue, new IllegalArgumentException(check.toString())); } } OpcodeStack.Item oldSummary = summary.get(fieldOperand); if (oldSummary != null) { Item newValue = OpcodeStack.Item.merge(mergeValue, oldSummary); newValue.clearNewlyAllocated(); summary.put(fieldOperand, newValue); } else { if (mergeValue.isNewlyAllocated()) { mergeValue = new OpcodeStack.Item(mergeValue); mergeValue.clearNewlyAllocated(); } summary.put(fieldOperand, mergeValue); } }
Example 9
Source File: LDAPSSLSocketFactoryGenerator.java From qpid-broker-j with Apache License 2.0 | 5 votes |
/** * Creates a static field _sslContext of type {@link SSLSocketFactory}. * * @param classGen * @param constantPoolGen */ private static void createSslContextStaticField(ClassGen classGen, ConstantPoolGen constantPoolGen) { FieldGen fieldGen = new FieldGen(ACC_PRIVATE | ACC_STATIC, Type.getType(SSLSocketFactory.class), SSL_SOCKET_FACTORY_FIELD, constantPoolGen); classGen.addField(fieldGen.getField()); }
Example 10
Source File: StandardTypeMerger.java From spotbugs with GNU Lesser General Public License v2.1 | 4 votes |
@Override public Type mergeTypes(Type a, Type b) throws DataflowAnalysisException { if (a == null) { return b; } if (b == null) { return a; } byte aType = a.getType(), bType = b.getType(); if (aType == T_TOP) { return b; } else if (bType == T_TOP) { return a; } else if (aType == T_BOTTOM || bType == T_BOTTOM) { // is bottom return BottomType.instance(); } else if (isReferenceType(aType) && isReferenceType(bType)) { // Two // object // types! // Handle the Null type, which serves as a special "top" // value for reference types. if (aType == T_NULL) { return b; } else if (bType == T_NULL) { return a; } ReferenceType aRef = (ReferenceType) a; ReferenceType bRef = (ReferenceType) b; return mergeReferenceTypes(aRef, bRef); } else if (isReferenceType(aType) || isReferenceType(bType)) { // meet // non-object // is // bottom return BottomType.instance(); } else if (aType == bType) { return a; } else if (isIntegerType(aType) && isIntegerType(bType)) { // integer types // - use T_INT return Type.INT; } else { // Default - types are incompatible return BottomType.instance(); } }
Example 11
Source File: TypeAnalysis.java From spotbugs with GNU Lesser General Public License v2.1 | 4 votes |
@Override public void initEntryFact(TypeFrame result) { // Make the frame valid result.setValid(); int slot = 0; // Clear the stack slots in the frame result.clearStack(); // Add local for "this" pointer, if present if (!methodGen.isStatic()) { result.setValue(slot++, ObjectTypeFactory.getInstance(methodGen.getClassName())); } // [Added: Support for Generics] // Get a parser that reads the generic signature of the method and // can be used to get the correct GenericObjectType if an argument // has a class type Iterator<String> iter = GenericSignatureParser.getGenericSignatureIterator(method); // Add locals for parameters. // Note that long and double parameters need to be handled // specially because they occupy two locals. Type[] argumentTypes = methodGen.getArgumentTypes(); for (Type argType : argumentTypes) { // Add special "extra" type for long or double params. // These occupy the slot before the "plain" type. if (argType.getType() == Const.T_LONG) { result.setValue(slot++, TypeFrame.getLongExtraType()); } else if (argType.getType() == Const.T_DOUBLE) { result.setValue(slot++, TypeFrame.getDoubleExtraType()); } // [Added: Support for Generics] String s = (iter == null || !iter.hasNext()) ? null : iter.next(); if (s != null && (argType instanceof ObjectType || argType instanceof ArrayType) && !(argType instanceof ExceptionObjectType)) { // replace with a generic version of the type try { Type t = GenericUtilities.getType(s); if (t != null) { argType = t; } } catch (RuntimeException e) { } // degrade gracefully } // Add the plain parameter type. result.setValue(slot++, argType); } // Set remaining locals to BOTTOM; this will cause any // uses of them to be flagged while (slot < methodGen.getMaxLocals()) { result.setValue(slot++, TypeFrame.getBottomType()); } }
Example 12
Source File: BCELPerfTest.java From annotation-tools with MIT License | 4 votes |
byte[] counterAdaptClass(final InputStream is, final String name) throws Exception { JavaClass jc = new ClassParser(is, name + ".class").parse(); ClassGen cg = new ClassGen(jc); ConstantPoolGen cp = cg.getConstantPool(); if (!cg.isInterface()) { FieldGen fg = new FieldGen(ACC_PUBLIC, Type.getType("I"), "_counter", cp); cg.addField(fg.getField()); } Method[] ms = cg.getMethods(); for (int j = 0; j < ms.length; ++j) { MethodGen mg = new MethodGen(ms[j], cg.getClassName(), cp); if (!mg.getName().equals("<init>") && !mg.isStatic() && !mg.isAbstract() && !mg.isNative()) { if (mg.getInstructionList() != null) { InstructionList il = new InstructionList(); il.append(new ALOAD(0)); il.append(new ALOAD(0)); il.append(new GETFIELD(cp.addFieldref(name, "_counter", "I"))); il.append(new ICONST(1)); il.append(new IADD()); il.append(new PUTFIELD(cp.addFieldref(name, "_counter", "I"))); mg.getInstructionList().insert(il); mg.setMaxStack(Math.max(mg.getMaxStack(), 2)); boolean lv = ms[j].getLocalVariableTable() == null; boolean ln = ms[j].getLineNumberTable() == null; if (lv) { mg.removeLocalVariables(); } if (ln) { mg.removeLineNumbers(); } cg.replaceMethod(ms[j], mg.getMethod()); } } } return cg.getJavaClass().getBytes(); }
Example 13
Source File: BCELPerfTest.java From annotation-tools with MIT License | 4 votes |
byte[] counterAdaptClass(final InputStream is, final String name) throws Exception { JavaClass jc = new ClassParser(is, name + ".class").parse(); ClassGen cg = new ClassGen(jc); ConstantPoolGen cp = cg.getConstantPool(); if (!cg.isInterface()) { FieldGen fg = new FieldGen(ACC_PUBLIC, Type.getType("I"), "_counter", cp); cg.addField(fg.getField()); } Method[] ms = cg.getMethods(); for (int j = 0; j < ms.length; ++j) { MethodGen mg = new MethodGen(ms[j], cg.getClassName(), cp); if (!mg.getName().equals("<init>") && !mg.isStatic() && !mg.isAbstract() && !mg.isNative()) { if (mg.getInstructionList() != null) { InstructionList il = new InstructionList(); il.append(new ALOAD(0)); il.append(new ALOAD(0)); il.append(new GETFIELD(cp.addFieldref(name, "_counter", "I"))); il.append(new ICONST(1)); il.append(new IADD()); il.append(new PUTFIELD(cp.addFieldref(name, "_counter", "I"))); mg.getInstructionList().insert(il); mg.setMaxStack(Math.max(mg.getMaxStack(), 2)); boolean lv = ms[j].getLocalVariableTable() == null; boolean ln = ms[j].getLineNumberTable() == null; if (lv) { mg.removeLocalVariables(); } if (ln) { mg.removeLineNumbers(); } cg.replaceMethod(ms[j], mg.getMethod()); } } } return cg.getJavaClass().getBytes(); }
Example 14
Source File: Pass2Verifier.java From commons-bcel with Apache License 2.0 | 4 votes |
@Override public void visitField(final Field obj) { if (jc.isClass()) { int maxone=0; if (obj.isPrivate()) { maxone++; } if (obj.isProtected()) { maxone++; } if (obj.isPublic()) { maxone++; } if (maxone > 1) { throw new ClassConstraintException("Field '"+tostring(obj)+ "' must only have at most one of its ACC_PRIVATE, ACC_PROTECTED, ACC_PUBLIC modifiers set."); } if (obj.isFinal() && obj.isVolatile()) { throw new ClassConstraintException("Field '"+tostring(obj)+ "' must only have at most one of its ACC_FINAL, ACC_VOLATILE modifiers set."); } } else{ // isInterface! if (!obj.isPublic()) { throw new ClassConstraintException("Interface field '"+tostring(obj)+ "' must have the ACC_PUBLIC modifier set but hasn't!"); } if (!obj.isStatic()) { throw new ClassConstraintException("Interface field '"+tostring(obj)+ "' must have the ACC_STATIC modifier set but hasn't!"); } if (!obj.isFinal()) { throw new ClassConstraintException("Interface field '"+tostring(obj)+ "' must have the ACC_FINAL modifier set but hasn't!"); } } if ((obj.getAccessFlags() & ~(Const.ACC_PUBLIC|Const.ACC_PRIVATE|Const.ACC_PROTECTED|Const.ACC_STATIC| Const.ACC_FINAL|Const.ACC_VOLATILE|Const.ACC_TRANSIENT)) > 0) { addMessage("Field '"+tostring(obj)+ "' has access flag(s) other than ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED,"+ " ACC_STATIC, ACC_FINAL, ACC_VOLATILE, ACC_TRANSIENT set (ignored)."); } checkIndex(obj, obj.getNameIndex(), CONST_Utf8); final String name = obj.getName(); if (! validFieldName(name)) { throw new ClassConstraintException("Field '"+tostring(obj)+"' has illegal name '"+obj.getName()+"'."); } // A descriptor is often named signature in BCEL checkIndex(obj, obj.getSignatureIndex(), CONST_Utf8); final String sig = ((ConstantUtf8) (cp.getConstant(obj.getSignatureIndex()))).getBytes(); // Field or Method sig.(=descriptor) try{ Type.getType(sig); /* Don't need the return value */ } catch (final ClassFormatException cfe) { throw new ClassConstraintException("Illegal descriptor (==signature) '"+sig+"' used by '"+tostring(obj)+"'.", cfe); } final String nameanddesc = name+sig; if (field_names_and_desc.contains(nameanddesc)) { throw new ClassConstraintException("No two fields (like '"+tostring(obj)+ "') are allowed have same names and descriptors!"); } if (field_names.contains(name)) { addMessage("More than one field of name '"+name+ "' detected (but with different type descriptors). This is very unusual."); } field_names_and_desc.add(nameanddesc); field_names.add(name); final Attribute[] atts = obj.getAttributes(); for (final Attribute att : atts) { if ((!(att instanceof ConstantValue)) && (!(att instanceof Synthetic)) && (!(att instanceof Deprecated))) { addMessage("Attribute '" + tostring(att) + "' as an attribute of Field '" + tostring(obj) + "' is unknown and will therefore be ignored."); } if (!(att instanceof ConstantValue)) { addMessage("Attribute '" + tostring(att) + "' as an attribute of Field '" + tostring(obj) + "' is not a ConstantValue and is therefore only of use for debuggers and such."); } } }
Example 15
Source File: Pass2Verifier.java From commons-bcel with Apache License 2.0 | 4 votes |
@Override public void visitConstantValue(final ConstantValue obj) {//vmspec2 4.7.2 // Despite its name, this really is an Attribute, // not a constant! checkIndex(obj, obj.getNameIndex(), CONST_Utf8); final String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getBytes(); if (! name.equals("ConstantValue")) { throw new ClassConstraintException( "The ConstantValue attribute '"+tostring(obj)+"' is not correctly named 'ConstantValue' but '"+name+"'."); } final Object pred = carrier.predecessor(); if (pred instanceof Field) { //ConstantValue attributes are quite senseless if the predecessor is not a field. final Field f = (Field) pred; // Field constraints have been checked before -- so we are safe using their type information. final Type field_type = Type.getType(((ConstantUtf8) (cp.getConstant(f.getSignatureIndex()))).getBytes()); final int index = obj.getConstantValueIndex(); if ((index < 0) || (index >= cplen)) { throw new ClassConstraintException("Invalid index '"+index+"' used by '"+tostring(obj)+"'."); } final Constant c = cp.getConstant(index); if (CONST_Long.isInstance(c) && field_type.equals(Type.LONG)) { return; } if (CONST_Float.isInstance(c) && field_type.equals(Type.FLOAT)) { return; } if (CONST_Double.isInstance(c) && field_type.equals(Type.DOUBLE)) { return; } if (CONST_Integer.isInstance(c) && (field_type.equals(Type.INT) || field_type.equals(Type.SHORT) || field_type.equals(Type.CHAR) || field_type.equals(Type.BYTE) || field_type.equals(Type.BOOLEAN))) { return; } if (CONST_String.isInstance(c) && field_type.equals(Type.STRING)) { return; } throw new ClassConstraintException("Illegal type of ConstantValue '"+obj+"' embedding Constant '"+c+ "'. It is referenced by field '"+tostring(f)+"' expecting a different type: '"+field_type+"'."); } }
Example 16
Source File: FindRefComparison.java From spotbugs with GNU Lesser General Public License v2.1 | 4 votes |
private void handleStringComparison(JavaClass jclass, Method method, MethodGen methodGen, RefComparisonTypeFrameModelingVisitor visitor, List<WarningWithProperties> stringComparisonList, Location location, Type lhsType, Type rhsType) { if (DEBUG) { System.out.println("String/String comparison at " + location.getHandle()); } // Compute the priority: // - two static strings => do not report // - dynamic string and anything => high // - static string and unknown => medium // - all other cases => low // System.out.println("Compare " + lhsType + " == " + rhsType); byte type1 = lhsType.getType(); byte type2 = rhsType.getType(); String bugPattern = "ES_COMPARING_STRINGS_WITH_EQ"; // T1 T2 result // S S no-op // D ? high // ? D high // S ? normal // ? S normal WarningPropertySet<WarningProperty> propertySet = new WarningPropertySet<>(); if (type1 == T_STATIC_STRING && type2 == T_STATIC_STRING) { propertySet.addProperty(RefComparisonWarningProperty.COMPARE_STATIC_STRINGS); } else if (type1 == T_DYNAMIC_STRING || type2 == T_DYNAMIC_STRING) { propertySet.addProperty(RefComparisonWarningProperty.DYNAMIC_AND_UNKNOWN); } else if (type2 == T_PARAMETER_STRING || type1 == T_PARAMETER_STRING) { bugPattern = "ES_COMPARING_PARAMETER_STRING_WITH_EQ"; if (methodGen.isPublic() || methodGen.isProtected()) { propertySet.addProperty(RefComparisonWarningProperty.STRING_PARAMETER_IN_PUBLIC_METHOD); } else { propertySet.addProperty(RefComparisonWarningProperty.STRING_PARAMETER); } } else if (type1 == T_STATIC_STRING || type2 == T_STATIC_STRING) { if (lhsType instanceof EmptyStringType || rhsType instanceof EmptyStringType) { propertySet.addProperty(RefComparisonWarningProperty.EMPTY_AND_UNKNOWN); } else { propertySet.addProperty(RefComparisonWarningProperty.STATIC_AND_UNKNOWN); } } else if (visitor.sawStringIntern()) { propertySet.addProperty(RefComparisonWarningProperty.SAW_INTERN); } String sourceFile = jclass.getSourceFileName(); BugInstance instance = new BugInstance(this, bugPattern, BASE_ES_PRIORITY).addClassAndMethod(methodGen, sourceFile) .addType("Ljava/lang/String;").describe(TypeAnnotation.FOUND_ROLE).addSomeSourceForTopTwoStackValues(classContext, method, location); SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext, methodGen, sourceFile, location.getHandle()); WarningWithProperties warn = new WarningWithProperties(instance, propertySet, sourceLineAnnotation, location); stringComparisonList.add(warn); }
Example 17
Source File: FieldAccess.java From spotbugs with GNU Lesser General Public License v2.1 | 2 votes |
/** * Return whether the given FieldInstruction accesses a long or double * field. * * @param fieldIns * the FieldInstruction * @param cpg * the ConstantPoolGen for the method */ protected static boolean isLongOrDouble(FieldInstruction fieldIns, ConstantPoolGen cpg) { Type type = fieldIns.getFieldType(cpg); int code = type.getType(); return code == Const.T_LONG || code == Const.T_DOUBLE; }