Java Code Examples for org.apache.bcel.Repository#lookupClass()
The following examples show how to use
org.apache.bcel.Repository#lookupClass() .
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: DeepSubtypeAnalysis.java From spotbugs with GNU Lesser General Public License v2.1 | 6 votes |
public static double isDeepSerializable(@DottedClassName String refSig) throws ClassNotFoundException { if (storedException != null) { throw storedException; } if (isPrimitiveComponentClass(refSig)) { if (DEBUG) { System.out.println("regSig \"" + refSig + "\" is primitive component class"); } return 1.0; } String refName = getComponentClass(refSig); if (Values.DOTTED_JAVA_LANG_OBJECT.equals(refName)) { return 0.99; } JavaClass refJavaClass = Repository.lookupClass(refName); return isDeepSerializable(refJavaClass); }
Example 2
Source File: TransitiveHull.java From commons-bcel with Apache License 2.0 | 6 votes |
public static void main(final String[] argv) { JavaClass java_class; try { if (argv.length == 0) { System.err.println("transitive: No input files specified"); } else { if ((java_class = Repository.lookupClass(argv[0])) == null) { java_class = new ClassParser(argv[0]).parse(); } final TransitiveHull hull = new TransitiveHull(java_class); hull.start(); System.out.println(Arrays.asList(hull.getClassNames())); } } catch (final Exception e) { e.printStackTrace(); } }
Example 3
Source File: OpcodeStack.java From spotbugs with GNU Lesser General Public License v2.1 | 6 votes |
/** Returns null for primitive and arrays */ public @CheckForNull JavaClass getJavaClass() throws ClassNotFoundException { String baseSig; if (isPrimitive() || isArray()) { return null; } baseSig = signature; if (baseSig.length() == 0) { return null; } baseSig = baseSig.substring(1, baseSig.length() - 1); baseSig = baseSig.replace('/', '.'); return Repository.lookupClass(baseSig); }
Example 4
Source File: DeepSubtypeAnalysis.java From spotbugs with GNU Lesser General Public License v2.1 | 6 votes |
public static double isDeepRemote(String refSig) { if (remote == null) { return 0.1; } String refName = getComponentClass(refSig); if (Values.DOTTED_JAVA_LANG_OBJECT.equals(refName)) { return 0.99; } JavaClass refJavaClass; try { refJavaClass = Repository.lookupClass(refName); return Analyze.deepInstanceOf(refJavaClass, remote); } catch (ClassNotFoundException e) { return 0.99; } }
Example 5
Source File: ReferenceDAO.java From cacheonix-core with GNU Lesser General Public License v2.1 | 6 votes |
/** * Finds the definition of the field of a field reference. * @param aFieldRef the reference to a field. * @return the definition of the field for aFieldRef. */ public FieldDefinition findFieldDef(FieldReference aFieldRef) { final String className = aFieldRef.getClassName(); JavaClass javaClass = Repository.lookupClass(className); final String fieldName = aFieldRef.getName(); // search up the class hierarchy for the class containing the // method definition. FieldDefinition result = null; while ((javaClass != null) && (result == null)) { final JavaClassDefinition javaClassDef = (JavaClassDefinition) mJavaClasses.get(javaClass); if (javaClassDef != null) { result = javaClassDef.findFieldDef(fieldName); } //search the parent javaClass = javaClass.getSuperClass(); } return result; }
Example 6
Source File: Analyze.java From spotbugs with GNU Lesser General Public License v2.1 | 6 votes |
public static double isDeepRemote(String refSig) { if (remote == null) { return 0.1; } String refName = getComponentClass(refSig); if (Values.DOTTED_JAVA_LANG_OBJECT.equals(refName)) { return 0.99; } JavaClass refJavaClass; try { refJavaClass = Repository.lookupClass(refName); return deepInstanceOf(refJavaClass, remote); } catch (ClassNotFoundException e) { return 0.99; } }
Example 7
Source File: ReferenceDAO.java From contribution with GNU Lesser General Public License v2.1 | 6 votes |
/** * Finds the definition of the field of a field reference. * @param aFieldRef the reference to a field. * @return the definition of the field for aFieldRef. */ public FieldDefinition findFieldDef(FieldReference aFieldRef) { final String className = aFieldRef.getClassName(); JavaClass javaClass = Repository.lookupClass(className); final String fieldName = aFieldRef.getName(); // search up the class hierarchy for the class containing the // method definition. FieldDefinition result = null; while ((javaClass != null) && (result == null)) { final JavaClassDefinition javaClassDef = (JavaClassDefinition) mJavaClasses.get(javaClass); if (javaClassDef != null) { result = javaClassDef.findFieldDef(fieldName); } //search the parent javaClass = javaClass.getSuperClass(); } return result; }
Example 8
Source File: ObjectType.java From commons-bcel with Apache License 2.0 | 5 votes |
/** * If "this" doesn't reference an interface, it references a class * or a non-existant entity. * @deprecated (since 6.0) this method returns an inaccurate result * if the class or interface referenced cannot * be found: use referencesInterfaceExact() instead */ @Deprecated public boolean referencesInterface() { try { final JavaClass jc = Repository.lookupClass(className); return !jc.isClass(); } catch (final ClassNotFoundException e) { return false; } }
Example 9
Source File: ClassFeatureSet.java From spotbugs with GNU Lesser General Public License v2.1 | 5 votes |
public static void main(String[] args) throws Exception { if (args.length != 2) { System.err.println("Usage: " + ClassFeatureSet.class.getName() + " <class 1> <class 2>"); System.exit(1); } JavaClass a = Repository.lookupClass(args[0]); JavaClass b = Repository.lookupClass(args[1]); ClassFeatureSet aFeatures = new ClassFeatureSet().initialize(a); ClassFeatureSet bFeatures = new ClassFeatureSet().initialize(b); System.out.println("Similarity is " + similarity(aFeatures, bFeatures)); System.out.println("Classes are" + (aFeatures.similarTo(bFeatures) ? "" : " not") + " similar"); }
Example 10
Source File: VerifierAppFrame.java From commons-bcel with Apache License 2.0 | 5 votes |
synchronized void pass3aJList_valueChanged( final ListSelectionEvent e ) { if (e.getValueIsAdjusting()) { return; } final Verifier v = VerifierFactory.getVerifier(current_class); final StringBuilder all3amsg = new StringBuilder(); boolean all3aok = true; boolean rejected = false; for (int i = 0; i < pass3aJList.getModel().getSize(); i++) { if (pass3aJList.isSelectedIndex(i)) { final VerificationResult vr = v.doPass3a(i); if (vr.getStatus() == VerificationResult.VERIFIED_REJECTED) { all3aok = false; rejected = true; } JavaClass jc = null; try { jc = Repository.lookupClass(v.getClassName()); all3amsg.append("Method '").append(jc.getMethods()[i]).append("': ") .append(vr.getMessage().replace('\n', ' ') ).append("\n\n"); } catch (final ClassNotFoundException ex) { // FIXME: handle the error ex.printStackTrace(); } } } pass3aTextPane.setText(all3amsg.toString()); pass3aTextPane.setBackground(all3aok ? Color.green : (rejected ? Color.red : Color.yellow)); }
Example 11
Source File: ReferenceDAO.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
/** * Adds a reference for an invocation in the invoked method definition. * The invocation is of the form class.method(args). * @param aInvokeRef the invocation reference. */ public void addInvokeReference(InvokeReference aInvokeRef) { // find the class for the instruction final String className = aInvokeRef.getClassName(); JavaClass javaClass = Repository.lookupClass(className); final String methodName = aInvokeRef.getName(); final Type[] argTypes = aInvokeRef.getArgTypes(); // search up the class hierarchy for the class containing the // method definition. MethodDefinition narrowest = null; while ((javaClass != null) && (narrowest == null)) { final JavaClassDefinition javaClassDef = (JavaClassDefinition) mJavaClasses.get(javaClass); if (javaClassDef != null) { // find narrowest compatible in the current class narrowest = javaClassDef.findNarrowestMethod( className, methodName, argTypes); if (narrowest != null) { narrowest.addReference(aInvokeRef); } } // search the parent javaClass = javaClass.getSuperClass(); } }
Example 12
Source File: ObjectType.java From ApkToolPlus with Apache License 2.0 | 5 votes |
/** * If "this" doesn't reference an interface, it references a class * or a non-existant entity. */ public boolean referencesInterface(){ JavaClass jc = Repository.lookupClass(class_name); if (jc == null) return false; else return !jc.isClass(); }
Example 13
Source File: FindHEmismatch.java From spotbugs with GNU Lesser General Public License v2.1 | 4 votes |
@Override public void visit(Signature obj) { if (!isApplicationClass) { return; } String sig = obj.getSignature(); String className = findHashedClassInSignature(sig); if (className == null) { return; } if (className.startsWith("java.lang")) { return; } JavaClass type = null; try { type = Repository.lookupClass(className); } catch (ClassNotFoundException e) { AnalysisContext.reportMissingClass(e); } if (type == null) { return; } int priority = NORMAL_PRIORITY; if (sig.indexOf("Hash") >= 0) { priority--; } if (type.isAbstract() || type.isInterface()) { priority++; } if (!AnalysisContext.currentAnalysisContext()/* .getSubtypes() */.isApplicationClass(type)) { priority++; } BugInstance bug = null; if (visitingField()) { bug = new BugInstance(this, "HE_SIGNATURE_DECLARES_HASHING_OF_UNHASHABLE_CLASS", priority).addClass(this) .addVisitedField(this).addTypeOfNamedClass(className).describe(TypeAnnotation.UNHASHABLE_ROLE); } else if (visitingMethod()) { bug = new BugInstance(this, "HE_SIGNATURE_DECLARES_HASHING_OF_UNHASHABLE_CLASS", priority).addClassAndMethod(this) .addTypeOfNamedClass(className).describe(TypeAnnotation.UNHASHABLE_ROLE); } else { bug = new BugInstance(this, "HE_SIGNATURE_DECLARES_HASHING_OF_UNHASHABLE_CLASS", priority).addClass(this) .addClass(this).addTypeOfNamedClass(className).describe(TypeAnnotation.UNHASHABLE_ROLE); } potentialBugs.put(className, bug); }
Example 14
Source File: Pass2Verifier.java From commons-bcel with Apache License 2.0 | 4 votes |
/** * Ensures that <B>final</B> methods are not overridden. * <B>Precondition to run this method: * constant_pool_entries_satisfy_static_constraints() and * every_class_has_an_accessible_superclass() have to be invoked before * (in that order).</B> * * @throws ClassConstraintException otherwise. * @see #constant_pool_entries_satisfy_static_constraints() * @see #every_class_has_an_accessible_superclass() */ private void final_methods_are_not_overridden() { try { final Map<String, String> hashmap = new HashMap<>(); JavaClass jc = Repository.lookupClass(myOwner.getClassName()); int supidx = -1; while (supidx != 0) { supidx = jc.getSuperclassNameIndex(); final Method[] methods = jc.getMethods(); for (final Method method : methods) { final String nameAndSig = method.getName() + method.getSignature(); if (hashmap.containsKey(nameAndSig)) { if (method.isFinal()) { if (!(method.isPrivate())) { throw new ClassConstraintException("Method '" + nameAndSig + "' in class '" + hashmap.get(nameAndSig) + "' overrides the final (not-overridable) definition in class '" + jc.getClassName() + "'."); } addMessage("Method '" + nameAndSig + "' in class '" + hashmap.get(nameAndSig) + "' overrides the final (not-overridable) definition in class '" + jc.getClassName() + "'. This is okay, as the original definition was private; however this constraint leverage"+ " was introduced by JLS 8.4.6 (not vmspec2) and the behavior of the Sun verifiers."); } else { if (!method.isStatic()) { // static methods don't inherit hashmap.put(nameAndSig, jc.getClassName()); } } } else { if (!method.isStatic()) { // static methods don't inherit hashmap.put(nameAndSig, jc.getClassName()); } } } jc = Repository.lookupClass(jc.getSuperclassName()); // Well, for OBJECT this returns OBJECT so it works (could return anything but must not throw an Exception). } } catch (final ClassNotFoundException e) { // FIXME: this might not be the best way to handle missing classes. throw new AssertionViolatedException("Missing class: " + e, e); } }
Example 15
Source File: Hierarchy.java From spotbugs with GNU Lesser General Public License v2.1 | 4 votes |
public static @CheckForNull JavaClassAndMethod findInvocationLeastUpperBound(InvokeInstruction inv, ConstantPoolGen cpg, JavaClassAndMethodChooser methodChooser) throws ClassNotFoundException { if (DEBUG_METHOD_LOOKUP) { System.out.println("Find prototype method for " + SignatureConverter.convertMethodSignature(inv, cpg)); } short opcode = inv.getOpcode(); if (opcode == Const.INVOKESTATIC) { if (methodChooser == INSTANCE_METHOD) { return null; } } else { if (methodChooser == STATIC_METHOD) { return null; } } // Find the method if (opcode == Const.INVOKESPECIAL) { // Non-virtual dispatch return findExactMethod(inv, cpg, methodChooser); } if (opcode == Const.INVOKEDYNAMIC) { return null; } String className = inv.getClassName(cpg); String methodName = inv.getName(cpg); String methodSig = inv.getSignature(cpg); if (DEBUG_METHOD_LOOKUP) { System.out.println("[Class name is " + className + "]"); System.out.println("[Method name is " + methodName + "]"); System.out.println("[Method signature is " + methodSig + "]"); } if (className.startsWith(Values.SIG_ARRAY_PREFIX)) { // Java 1.5 allows array classes to appear as the class name className = Values.DOTTED_JAVA_LANG_OBJECT; } JavaClass jClass = Repository.lookupClass(className); return findInvocationLeastUpperBound(jClass, methodName, methodSig, methodChooser, opcode == Const.INVOKEINTERFACE); }
Example 16
Source File: InstConstraintVisitor.java From ApkToolPlus with Apache License 2.0 | 4 votes |
/** * Ensures the specific preconditions of the said instruction. */ public void visitPUTSTATIC(PUTSTATIC o){ String field_name = o.getFieldName(cpg); JavaClass jc = Repository.lookupClass(o.getClassType(cpg).getClassName()); Field[] fields = jc.getFields(); Field f = null; for (int i=0; i<fields.length; i++){ if (fields[i].getName().equals(field_name)){ f = fields[i]; break; } } if (f == null){ throw new AssertionViolatedException("Field not found?!?"); } Type value = stack().peek(); Type t = Type.getType(f.getSignature()); Type shouldbe = t; if (shouldbe == Type.BOOLEAN || shouldbe == Type.BYTE || shouldbe == Type.CHAR || shouldbe == Type.SHORT){ shouldbe = Type.INT; } if (t instanceof ReferenceType){ ReferenceType rvalue = null; if (value instanceof ReferenceType){ rvalue = (ReferenceType) value; referenceTypeIsInitialized(o, rvalue); } else{ constraintViolated(o, "The stack top type '"+value+"' is not of a reference type as expected."); } // TODO: This can possibly only be checked using Staerk-et-al's "set-of-object types", not // using "wider cast object types" created during verification. // Comment it out if you encounter problems. See also the analogon at visitPUTFIELD. if (!(rvalue.isAssignmentCompatibleWith(shouldbe))){ constraintViolated(o, "The stack top type '"+value+"' is not assignment compatible with '"+shouldbe+"'."); } } else{ if (shouldbe != value){ constraintViolated(o, "The stack top type '"+value+"' is not of type '"+shouldbe+"' as expected."); } } // TODO: Interface fields may be assigned to only once. (Hard to implement in // JustIce's execution model). This may only happen in <clinit>, see Pass 3a. }
Example 17
Source File: InnerClassAccessMap.java From spotbugs with GNU Lesser General Public License v2.1 | 4 votes |
/** * Return a map of inner-class member access method names to the fields that * they access for given class name. * * @param className * the name of the class * @return map of access method names to the fields they access */ private Map<String, InnerClassAccess> getAccessMapForClass(String className) throws ClassNotFoundException { Map<String, InnerClassAccess> map = classToAccessMap.get(className); if (map == null) { map = new HashMap<>(3); if (!className.startsWith("[")) { JavaClass javaClass = Repository.lookupClass(className); Method[] methodList = javaClass.getMethods(); for (Method method : methodList) { String methodName = method.getName(); if (!methodName.startsWith("access$")) { continue; } Code code = method.getCode(); if (code == null) { continue; } if (DEBUG) { System.out.println("Analyzing " + className + "." + method.getName() + " as an inner-class access method..."); } byte[] instructionList = code.getCode(); String methodSig = method.getSignature(); InstructionCallback callback = new InstructionCallback(javaClass, methodName, methodSig, instructionList); // try { new BytecodeScanner().scan(instructionList, callback); // } catch (LookupFailure lf) { // throw lf.getException(); // } InnerClassAccess access = callback.getAccess(); if (DEBUG) { System.out.println((access != null ? "IS" : "IS NOT") + " an inner-class access method"); } if (access != null) { map.put(methodName, access); } } } if (map.size() == 0) { map = Collections.emptyMap(); } else { map = new HashMap<>(map); } classToAccessMap.put(className, map); } return map; }
Example 18
Source File: Pass3bVerifier.java From commons-bcel with Apache License 2.0 | 4 votes |
/** * Pass 3b implements the data flow analysis as described in the Java Virtual * Machine Specification, Second Edition. * Later versions will use LocalVariablesInfo objects to verify if the * verifier-inferred types and the class file's debug information (LocalVariables * attributes) match [TODO]. * * @see org.apache.bcel.verifier.statics.LocalVariablesInfo * @see org.apache.bcel.verifier.statics.Pass2Verifier#getLocalVariablesInfo(int) */ @Override public VerificationResult do_verify() { if (! myOwner.doPass3a(methodNo).equals(VerificationResult.VR_OK)) { return VerificationResult.VR_NOTYET; } // Pass 3a ran before, so it's safe to assume the JavaClass object is // in the BCEL repository. JavaClass jc; try { jc = Repository.lookupClass(myOwner.getClassName()); } catch (final ClassNotFoundException e) { // FIXME: maybe not the best way to handle this throw new AssertionViolatedException("Missing class: " + e, e); } final ConstantPoolGen constantPoolGen = new ConstantPoolGen(jc.getConstantPool()); // Init Visitors final InstConstraintVisitor icv = new InstConstraintVisitor(); icv.setConstantPoolGen(constantPoolGen); final ExecutionVisitor ev = new ExecutionVisitor(); ev.setConstantPoolGen(constantPoolGen); final Method[] methods = jc.getMethods(); // Method no "methodNo" exists, we ran Pass3a before on it! try{ final MethodGen mg = new MethodGen(methods[methodNo], myOwner.getClassName(), constantPoolGen); icv.setMethodGen(mg); ////////////// DFA BEGINS HERE //////////////// if (! (mg.isAbstract() || mg.isNative()) ) { // IF mg HAS CODE (See pass 2) final ControlFlowGraph cfg = new ControlFlowGraph(mg); // Build the initial frame situation for this method. final Frame f = new Frame(mg.getMaxLocals(),mg.getMaxStack()); if ( !mg.isStatic() ) { if (mg.getName().equals(Const.CONSTRUCTOR_NAME)) { Frame.setThis(new UninitializedObjectType(ObjectType.getInstance(jc.getClassName()))); f.getLocals().set(0, Frame.getThis()); } else{ Frame.setThis(null); f.getLocals().set(0, ObjectType.getInstance(jc.getClassName())); } } final Type[] argtypes = mg.getArgumentTypes(); int twoslotoffset = 0; for (int j=0; j<argtypes.length; j++) { if (argtypes[j] == Type.SHORT || argtypes[j] == Type.BYTE || argtypes[j] == Type.CHAR || argtypes[j] == Type.BOOLEAN) { argtypes[j] = Type.INT; } f.getLocals().set(twoslotoffset + j + (mg.isStatic()?0:1), argtypes[j]); if (argtypes[j].getSize() == 2) { twoslotoffset++; f.getLocals().set(twoslotoffset + j + (mg.isStatic()?0:1), Type.UNKNOWN); } } circulationPump(mg,cfg, cfg.contextOf(mg.getInstructionList().getStart()), f, icv, ev); } } catch (final VerifierConstraintViolatedException ce) { ce.extendMessage("Constraint violated in method '"+methods[methodNo]+"':\n",""); return new VerificationResult(VerificationResult.VERIFIED_REJECTED, ce.getMessage()); } catch (final RuntimeException re) { // These are internal errors final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw); re.printStackTrace(pw); throw new AssertionViolatedException("Some RuntimeException occured while verify()ing class '"+jc.getClassName()+ "', method '"+methods[methodNo]+"'. Original RuntimeException's stack trace:\n---\n"+sw+"---\n", re); } return VerificationResult.VR_OK; }
Example 19
Source File: Pass2Verifier.java From ApkToolPlus with Apache License 2.0 | 2 votes |
/** * Ensures that the ConstantCP-subclassed entries of the constant * pool are valid. According to "Yellin: Low Level Security in Java", * this method does not verify the existence of referenced entities * (such as classes) but only the formal correctness (such as well-formed * signatures). * The visitXXX() methods throw ClassConstraintException instances otherwise. * <B>Precondition: index-style cross referencing in the constant * pool must be valid. Simply invoke constant_pool_entries_satisfy_static_constraints() * before.</B> * * @throws ClassConstraintException otherwise. * @see #constant_pool_entries_satisfy_static_constraints() */ private void field_and_method_refs_are_valid(){ JavaClass jc = Repository.lookupClass(myOwner.getClassName()); DescendingVisitor v = new DescendingVisitor(jc, new FAMRAV_Visitor(jc)); v.visit(); }
Example 20
Source File: ObjectType.java From commons-bcel with Apache License 2.0 | 2 votes |
/** * Return true if this type references a class, * false if it references an interface. * @return true if the type references a class, false if * it references an interface * @throws ClassNotFoundException if the class or interface * referenced by this type can't be found */ public boolean referencesClassExact() throws ClassNotFoundException { final JavaClass jc = Repository.lookupClass(className); return jc.isClass(); }