Java Code Examples for org.apache.bcel.classfile.JavaClass#getMethods()
The following examples show how to use
org.apache.bcel.classfile.JavaClass#getMethods() .
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: InvalidJUnitTest.java From spotbugs with GNU Lesser General Public License v2.1 | 6 votes |
private boolean hasTestMethods(JavaClass jClass) { boolean foundTest = false; Method[] methods = jClass.getMethods(); for (Method m : methods) { if (m.isPublic() && m.getName().startsWith("test") && m.getSignature().equals("()V")) { return true; } if (m.getName().startsWith("runTest") && m.getSignature().endsWith("()V")) { return true; } } if (hasSuite(methods)) { return true; } try { JavaClass sClass = jClass.getSuperClass(); if (sClass != null) { return hasTestMethods(sClass); } } catch (ClassNotFoundException e) { AnalysisContext.reportMissingClass(e); } return false; }
Example 2
Source File: MethodFactory.java From spotbugs with GNU Lesser General Public License v2.1 | 6 votes |
@Override public Method analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor) throws CheckedAnalysisException { JavaClass jclass = analysisCache.getClassAnalysis(JavaClass.class, descriptor.getClassDescriptor()); Method[] methodList = jclass.getMethods(); Method result = null; // As a side-effect, cache all of the Methods for this JavaClass for (Method method : methodList) { MethodDescriptor methodDescriptor = DescriptorFactory.instance().getMethodDescriptor( descriptor.getSlashedClassName(), method.getName(), method.getSignature(), method.isStatic()); // Put in cache eagerly analysisCache.eagerlyPutMethodAnalysis(Method.class, methodDescriptor, method); if (methodDescriptor.equals(descriptor)) { result = method; } } return result; }
Example 3
Source File: id.java From commons-bcel with Apache License 2.0 | 6 votes |
public static void main(final String[] argv) throws Exception { JavaClass clazz; if ((clazz = Repository.lookupClass(argv[0])) == null) { clazz = new ClassParser(argv[0]).parse(); // May throw IOException } final ClassGen cg = new ClassGen(clazz); for (final Method method : clazz.getMethods()) { final MethodGen mg = new MethodGen(method, cg.getClassName(), cg.getConstantPool()); cg.replaceMethod(method, mg.getMethod()); } for (final Field field : clazz.getFields()) { final FieldGen fg = new FieldGen(field, cg.getConstantPool()); cg.replaceField(field, fg.getField()); } cg.getJavaClass().dump(clazz.getClassName() + ".clazz"); }
Example 4
Source File: ClassDumper.java From cloud-opensource-java with Apache License 2.0 | 6 votes |
/** * Returns true if {@code parentJavaClass} is not {@code final} and {@code childJavaClass} is not * overriding any {@code final} method of {@code parentJavaClass}. * * @see <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.10">Java * Virtual Machine Specification: 4.10. Verification of class Files</a> */ static boolean hasValidSuperclass(JavaClass childJavaClass, JavaClass parentJavaClass) { if (parentJavaClass.isFinal()) { return false; } for (Method method : childJavaClass.getMethods()) { for (JavaClass parentClass : getClassHierarchy(parentJavaClass)) { for (final Method methodInParent : parentClass.getMethods()) { if (methodInParent.getName().equals(method.getName()) && methodInParent.getSignature().equals(method.getSignature()) && methodInParent.isFinal()) { return false; } } } } return true; }
Example 5
Source File: StaticIvDetector.java From Android_Code_Arbiter with GNU Lesser General Public License v3.0 | 5 votes |
@Override public void visitClassContext(ClassContext classContext) { JavaClass javaClass = classContext.getJavaClass(); Method[] methodList = javaClass.getMethods(); for (Method m : methodList) { try { analyzeMethod(m, classContext); } catch (CFGBuilderException | DataflowAnalysisException e) { AnalysisContext.logError("Cannot analyze method", e); } } }
Example 6
Source File: FindHEmismatch.java From spotbugs with GNU Lesser General Public License v2.1 | 5 votes |
Method findMethod(JavaClass clazz, String name, String sig) { Method[] m = clazz.getMethods(); for (Method aM : m) { if (aM.getName().equals(name) && aM.getSignature().equals(sig)) { return aM; } } return null; }
Example 7
Source File: MethodGenTestCase.java From commons-bcel with Apache License 2.0 | 5 votes |
private MethodGen getMethod(final Class<?> cls, final String name) throws ClassNotFoundException { final JavaClass jc = Repository.lookupClass(cls); final ConstantPoolGen cp = new ConstantPoolGen(jc.getConstantPool()); for (final Method method : jc.getMethods()) { if (method.getName().equals(name)) { return new MethodGen(method, jc.getClassName(), cp); } } Assert.fail("Method " + name + " not found in class " + cls); return null; }
Example 8
Source File: JaxWsEndpointDetector.java From Android_Code_Arbiter with GNU Lesser General Public License v3.0 | 5 votes |
@Override public void visitClassContext(ClassContext classContext) { JavaClass javaClass = classContext.getJavaClass(); for (Method m : javaClass.getMethods()) { for (AnnotationEntry ae : m.getAnnotationEntries()) { //Every method mark with @javax.jws.WebMethod is mark as an Endpoint if (ae.getAnnotationType().equals("Ljavax/jws/WebMethod;")) { bugReporter.reportBug(new BugInstance(this, JAXWS_ENDPOINT_TYPE, Priorities.LOW_PRIORITY) // .addClassAndMethod(javaClass, m)); } } } }
Example 9
Source File: SpringCsrfUnrestrictedRequestMappingDetector.java From Android_Code_Arbiter with GNU Lesser General Public License v3.0 | 5 votes |
@Override public void visitClassContext(ClassContext classContext) { JavaClass javaClass = classContext.getJavaClass(); for (Method method : javaClass.getMethods()) { if (isVulnerable(method)) { bugReporter.reportBug(new BugInstance(this, SPRING_CSRF_UNRESTRICTED_REQUEST_MAPPING_TYPE, Priorities.HIGH_PRIORITY) // .addClassAndMethod(javaClass, method)); } } }
Example 10
Source File: BetterCFGBuilder2.java From spotbugs with GNU Lesser General Public License v2.1 | 5 votes |
/** * Test driver. */ public static void main(String[] argv) throws Exception { if (argv.length != 1) { System.err.println("Usage: " + BetterCFGBuilder2.class.getName() + " <class file>"); System.exit(1); } String methodName = SystemProperties.getProperty("cfgbuilder.method"); JavaClass jclass = new ClassParser(argv[0]).parse(); ClassGen classGen = new ClassGen(jclass); Method[] methodList = jclass.getMethods(); for (Method method : methodList) { if (method.isAbstract() || method.isNative()) { continue; } if (methodName != null && !method.getName().equals(methodName)) { continue; } MethodDescriptor descriptor = DescriptorFactory.instance().getMethodDescriptor(jclass, method); MethodGen methodGen = new MethodGen(method, jclass.getClassName(), classGen.getConstantPool()); CFGBuilder cfgBuilder = new BetterCFGBuilder2(descriptor, methodGen); cfgBuilder.build(); CFG cfg = cfgBuilder.getCFG(); CFGPrinter cfgPrinter = new CFGPrinter(cfg); System.out.println("---------------------------------------------------------------------"); System.out.println("Method: " + SignatureConverter.convertMethodSignature(methodGen)); System.out.println("---------------------------------------------------------------------"); cfgPrinter.print(System.out); } }
Example 11
Source File: ClassGen.java From commons-bcel with Apache License 2.0 | 5 votes |
/** * Initialize with existing class. * @param clazz JavaClass object (e.g. read from file) */ public ClassGen(final JavaClass clazz) { super(clazz.getAccessFlags()); classNameIndex = clazz.getClassNameIndex(); superclass_name_index = clazz.getSuperclassNameIndex(); className = clazz.getClassName(); superClassName = clazz.getSuperclassName(); fileName = clazz.getSourceFileName(); cp = new ConstantPoolGen(clazz.getConstantPool()); major = clazz.getMajor(); minor = clazz.getMinor(); final Attribute[] attributes = clazz.getAttributes(); // J5TODO: Could make unpacking lazy, done on first reference final AnnotationEntryGen[] annotations = unpackAnnotations(attributes); final Method[] methods = clazz.getMethods(); final Field[] fields = clazz.getFields(); final String[] interfaces = clazz.getInterfaceNames(); for (final String interface1 : interfaces) { addInterface(interface1); } for (final Attribute attribute : attributes) { if (!(attribute instanceof Annotations)) { addAttribute(attribute); } } for (final AnnotationEntryGen annotation : annotations) { addAnnotationEntry(annotation); } for (final Method method : methods) { addMethod(method); } for (final Field field : fields) { addField(field); } }
Example 12
Source File: VerifyDialog.java From commons-bcel with Apache License 2.0 | 5 votes |
/** Machine-generated. */ public void pass4Button_ActionPerformed( final java.awt.event.ActionEvent actionEvent ) { pass2Button_ActionPerformed(actionEvent); Color color = Color.green; final Verifier v = VerifierFactory.getVerifier(class_name); VerificationResult vr = v.doPass2(); if (vr.getStatus() == VerificationResult.VERIFIED_OK) { JavaClass jc = null; try { jc = Repository.lookupClass(class_name); final int nr = jc.getMethods().length; for (int i = 0; i < nr; i++) { vr = v.doPass3b(i); if (vr.getStatus() != VerificationResult.VERIFIED_OK) { color = Color.red; break; } } } catch (final ClassNotFoundException ex) { // FIXME: report the error ex.printStackTrace(); } } else { color = Color.yellow; } getPass3Panel().setBackground(color); getPass3Panel().repaint(); }
Example 13
Source File: UselessSubclassMethod.java From spotbugs with GNU Lesser General Public License v2.1 | 5 votes |
private Method findSuperclassMethod(@DottedClassName String superclassName, Method subclassMethod) throws ClassNotFoundException { String methodName = subclassMethod.getName(); Type[] subArgs = null; JavaClass superClass = Repository.lookupClass(superclassName); Method[] methods = superClass.getMethods(); outer: for (Method m : methods) { if (m.getName().equals(methodName)) { if (subArgs == null) { subArgs = Type.getArgumentTypes(subclassMethod.getSignature()); } Type[] superArgs = Type.getArgumentTypes(m.getSignature()); if (subArgs.length == superArgs.length) { for (int j = 0; j < subArgs.length; j++) { if (!superArgs[j].equals(subArgs[j])) { continue outer; } } return m; } } } if (!"Object".equals(superclassName)) { @DottedClassName String superSuperClassName = superClass.getSuperclassName(); if (superSuperClassName.equals(superclassName)) { throw new ClassNotFoundException("superclass of " + superclassName + " is itself"); } return findSuperclassMethod(superSuperClassName, subclassMethod); } return null; }
Example 14
Source File: SpringUnvalidatedRedirectDetector.java From Android_Code_Arbiter with GNU Lesser General Public License v3.0 | 5 votes |
@Override public void visitClassContext(ClassContext classContext) { JavaClass clazz = classContext.getJavaClass(); if (hasRequestMapping(clazz)) { Method[] methods = clazz.getMethods(); for (Method m: methods) { try { analyzeMethod(m, classContext); } catch (CFGBuilderException e){ } } } }
Example 15
Source File: Naming.java From spotbugs with GNU Lesser General Public License v2.1 | 5 votes |
public static @CheckForNull XMethod definedIn(JavaClass clazz, XMethod m) { for (Method m2 : clazz.getMethods()) { if (m.getName().equals(m2.getName()) && m.getSignature().equals(m2.getSignature()) && m.isStatic() == m2.isStatic()) { return XFactory.createXMethod(clazz, m2); } } return null; }
Example 16
Source File: AbstractVerifierTestCase.java From commons-bcel with Apache License 2.0 | 5 votes |
/** * Executes all the verification on the given class. * * @param classname name of the class to verify * @return false if the verification fails, true otherwise */ public boolean doAllPasses(final String classname) { int nbMethods = 0; try { final JavaClass jc = Repository.lookupClass(classname); nbMethods = jc.getMethods().length; } catch (final ClassNotFoundException e) { fail(e.getMessage()); return false; } final Verifier verifier = VerifierFactory.getVerifier(classname); VerificationResult result = verifier.doPass1(); if (result.getStatus() != VerificationResult.VERIFIED_OK) { return false; } result = verifier.doPass2(); if (result.getStatus() != VerificationResult.VERIFIED_OK) { return false; } for (int i = nbMethods; --i >= 0;) { result = verifier.doPass3a(i); if (result.getStatus() != VerificationResult.VERIFIED_OK) { return false; } result = verifier.doPass3b(i); if (result.getStatus() != VerificationResult.VERIFIED_OK) { return false; } } return true; }
Example 17
Source File: BCELifier.java From commons-bcel with Apache License 2.0 | 4 votes |
@Override public void visitJavaClass( final JavaClass clazz ) { String class_name = clazz.getClassName(); final String super_name = clazz.getSuperclassName(); final String package_name = clazz.getPackageName(); final String inter = Utility.printArray(clazz.getInterfaceNames(), false, true); if (!"".equals(package_name)) { class_name = class_name.substring(package_name.length() + 1); _out.println("package " + package_name + ";"); _out.println(); } _out.println("import " + BASE_PACKAGE + ".generic.*;"); _out.println("import " + BASE_PACKAGE + ".classfile.*;"); _out.println("import " + BASE_PACKAGE + ".*;"); _out.println("import java.io.*;"); _out.println(); _out.println("public class " + class_name + "Creator {"); _out.println(" private InstructionFactory _factory;"); _out.println(" private ConstantPoolGen _cp;"); _out.println(" private ClassGen _cg;"); _out.println(); _out.println(" public " + class_name + "Creator() {"); _out.println(" _cg = new ClassGen(\"" + (("".equals(package_name)) ? class_name : package_name + "." + class_name) + "\", \"" + super_name + "\", " + "\"" + clazz.getSourceFileName() + "\", " + printFlags(clazz.getAccessFlags(), FLAGS.CLASS) + ", " + "new String[] { " + inter + " });"); _out.println(" _cg.setMajor(" + clazz.getMajor() +");"); _out.println(" _cg.setMinor(" + clazz.getMinor() +");"); _out.println(); _out.println(" _cp = _cg.getConstantPool();"); _out.println(" _factory = new InstructionFactory(_cg, _cp);"); _out.println(" }"); _out.println(); printCreate(); final Field[] fields = clazz.getFields(); if (fields.length > 0) { _out.println(" private void createFields() {"); _out.println(" FieldGen field;"); for (final Field field : fields) { field.accept(this); } _out.println(" }"); _out.println(); } final Method[] methods = clazz.getMethods(); for (int i = 0; i < methods.length; i++) { _out.println(" private void createMethod_" + i + "() {"); methods[i].accept(this); _out.println(" }"); _out.println(); } printMain(); _out.println("}"); }
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: Pass3aVerifier.java From commons-bcel with Apache License 2.0 | 4 votes |
/** Checks if the constraints of operands of the said instruction(s) are satisfied. */ @Override public void visitINVOKESPECIAL(final INVOKESPECIAL o) { try { // INVOKESPECIAL is a LoadClass; the Class where the referenced method is declared in, // is therefore resolved/verified. // INVOKESPECIAL is an InvokeInstruction, the argument and return types are resolved/verified, // too. So are the allowed method names. final String classname = o.getClassName(constantPoolGen); final JavaClass jc = Repository.lookupClass(classname); final Method m = getMethodRecursive(jc, o); if (m == null) { constraintViolated(o, "Referenced method '"+o.getMethodName(constantPoolGen)+"' with expected signature '"+o.getSignature(constantPoolGen) +"' not found in class '"+jc.getClassName()+"'."); } JavaClass current = Repository.lookupClass(myOwner.getClassName()); if (current.isSuper()) { if ((Repository.instanceOf( current, jc )) && (!current.equals(jc))) { if (! (o.getMethodName(constantPoolGen).equals(Const.CONSTRUCTOR_NAME) )) { // Special lookup procedure for ACC_SUPER classes. int supidx = -1; Method meth = null; while (supidx != 0) { supidx = current.getSuperclassNameIndex(); current = Repository.lookupClass(current.getSuperclassName()); final Method[] meths = current.getMethods(); for (final Method meth2 : meths) { if ( (meth2.getName().equals(o.getMethodName(constantPoolGen))) && (Type.getReturnType(meth2.getSignature()).equals(o.getReturnType(constantPoolGen))) && (objarrayequals(Type.getArgumentTypes(meth2.getSignature()), o.getArgumentTypes(constantPoolGen))) ) { meth = meth2; break; } } if (meth != null) { break; } } if (meth == null) { constraintViolated(o, "ACC_SUPER special lookup procedure not successful: method '"+ o.getMethodName(constantPoolGen)+"' with proper signature not declared in superclass hierarchy."); } } } } } catch (final ClassNotFoundException e) { // FIXME: maybe not the best way to handle this throw new AssertionViolatedException("Missing class: " + e, e); } }
Example 20
Source File: HiddenStaticMethodCheck.java From contribution with GNU Lesser General Public License v2.1 | 4 votes |
/** @see com.puppycrawl.tools.checkstyle.bcel.IObjectSetVisitor */ public void visitObject(Object aJavaClass) { final JavaClass javaClass = (JavaClass) aJavaClass; final String className = javaClass.getClassName(); final JavaClass[] superClasses = javaClass.getSuperClasses(); final Method[] methods = javaClass.getMethods(); // Check all methods for (int i = 0; i < methods.length; i++) { final Method method = methods[i]; // Check that the method is a possible match if (!method.isPrivate() && method.isStatic()) { // Go through all their superclasses for (int j = 0; j < superClasses.length; j++) { final JavaClass superClass = superClasses[j]; final String superClassName = superClass.getClassName(); final Method[] superClassMethods = superClass.getMethods(); // Go through the methods of the superclasses for (int k = 0; k < superClassMethods.length; k++) { final Method superClassMethod = superClassMethods[k]; if (superClassMethod.getName().equals(method.getName()) && !ignore(className, method)) { Type[] methodTypes = method.getArgumentTypes(); Type[] superTypes = superClassMethod. getArgumentTypes(); if (methodTypes.length == superTypes.length) { boolean match = true; for (int arg = 0; arg < methodTypes.length; arg++) { if (!methodTypes[arg].equals(superTypes[arg])) { match = false; } } // Same method parameters if (match) { log( javaClass, 0, "hidden.static.method", new Object[] {method, superClassName}); } } } } } } } }