Java Code Examples for org.apache.bcel.classfile.Method#isAbstract()

The following examples show how to use org.apache.bcel.classfile.Method#isAbstract() . 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: CloneIdiom.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void visit(Method obj) {
    if (obj.isAbstract() || BCELUtil.isSynthetic(obj)) {
        return;
    }
    if (!obj.isPublic()) {
        return;
    }
    if (!"clone".equals(getMethodName())) {
        return;
    }
    if (!getMethodSig().startsWith("()")) {
        return;
    }
    hasCloneMethod = true;
    cloneIsDeprecated = getXMethod().isDeprecated();
    cloneMethodAnnotation = MethodAnnotation.fromVisitedMethod(this);
    cloneOnlyThrowsException = PruneUnconditionalExceptionThrowerEdges.doesMethodUnconditionallyThrowException(XFactory
            .createXMethod(this));
    // ExceptionTable tbl = obj.getExceptionTable();
    // throwsExceptions = tbl != null && tbl.getNumberOfExceptions() > 0;
}
 
Example 2
Source File: Lookup.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static @CheckForNull JavaClass findSuperImplementor(JavaClass clazz, String name, String signature, BugReporter bugReporter) {
    try {
        JavaClass c = clazz;
        while (true) {
            c = c.getSuperClass();
            if (c == null) {
                return null;
            }
            Method m = findImplementation(c, name, signature);
            if (m != null && !m.isAbstract()) {
                return c;
            }

        }
    } catch (ClassNotFoundException e) {
        bugReporter.reportMissingClass(e);
        return null;
    }
}
 
Example 3
Source File: Lookup.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static @CheckForNull XMethod findSuperImplementorAsXMethod(JavaClass clazz, String name, String signature, BugReporter bugReporter) {
    try {
        JavaClass c = clazz;
        while (true) {
            c = c.getSuperClass();
            if (c == null) {
                return null;
            }
            Method m = findImplementation(c, name, signature);
            if (m != null && !m.isAbstract()) {
                return XFactory.createXMethod(c, m);
            }

        }
    } catch (ClassNotFoundException e) {
        bugReporter.reportMissingClass(e);
        return null;
    }
}
 
Example 4
Source File: LocalVariableTypeTableTestCase.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
private byte[] getBytesFromClass(final String className) throws ClassNotFoundException {
    final JavaClass clazz = getTestClass(className);
    final ConstantPoolGen cp = new ConstantPoolGen(clazz.getConstantPool());

    final Method[] methods = clazz.getMethods();

    for (int i = 0; i < methods.length; i++) {
        final Method method = methods[i];
        if (!method.isNative() && !method.isAbstract()) {
            methods[i] = injection(clazz, method, cp, findFirstStringLocalVariableOffset(method));
        }
    }

    clazz.setConstantPool(cp.getFinalConstantPool());

    return clazz.getBytes();
}
 
Example 5
Source File: FindUselessObjects.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visitClassContext(ClassContext classContext) {
    for (Method method : classContext.getMethodsInCallOrder()) {
        if (method.isAbstract() || method.isNative()) {
            continue;
        }
        try {
            analyzeMethod(classContext, method);
        } catch (CheckedAnalysisException e) {
            reporter.logError("Error analyzing " + method + " (class: " + classContext.getJavaClass().getClassName() + ")", e);
        }
    }
}
 
Example 6
Source File: UncallableMethodOfAnonymousClass.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private boolean skip(Method obj) {
    if (BCELUtil.isSynthetic(obj)) {
        return true;
    }
    if (obj.isPrivate()) {
        return true;
    }
    if (obj.isAbstract()) {
        return true;
    }

    String methodName = obj.getName();
    String sig = obj.getSignature();
    if (Const.CONSTRUCTOR_NAME.equals(methodName)) {
        return true;
    }
    if (Const.STATIC_INITIALIZER_NAME.equals(methodName)) {
        return true;
    }
    if ("()Ljava/lang/Object;".equals(sig) && ("readResolve".equals(methodName) || "writeReplace".equals(methodName))) {
        return true;
    }
    if (methodName.startsWith("access$")) {
        return true;
    }
    if (methodName.length() < 2 || methodName.indexOf('$') >= 0) {
        return true;
    }
    XMethod m = getXMethod();
    for (ClassDescriptor c : m.getAnnotationDescriptors()) {
        if (c.getClassName().indexOf("inject") >= 0) {
            return true;
        }
    }
    return false;
}
 
Example 7
Source File: BetterCFGBuilder2.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 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 8
Source File: Lookup.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static @CheckForNull JavaClass findImplementor(JavaClass[] clazz, String name, String signature) {

        for (JavaClass aClazz : clazz) {
            Method m = findImplementation(aClazz, name, signature);
            if (m != null && !m.isAbstract()) {
                return aClazz;
            }

        }
        return null;
    }
 
Example 9
Source File: maxstack.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] argv) throws Exception {
    for (final String class_name : argv) {
        JavaClass java_class = Repository.lookupClass(class_name);

        if (java_class == null) {
            java_class = new ClassParser(class_name).parse();
        }

        final ConstantPoolGen cp = new ConstantPoolGen(java_class.getConstantPool());

        for (final Method m : java_class.getMethods()) {
            if (!(m.isAbstract() || m.isNative())) {
                final MethodGen mg = new MethodGen(m, class_name, cp);

                final int compiled_stack = mg.getMaxStack();
                final int compiled_locals = mg.getMaxLocals();
                mg.setMaxStack(); // Recompute value
                mg.setMaxLocals();
                final int computed_stack = mg.getMaxStack();
                final int computed_locals = mg.getMaxLocals();

                mg.getInstructionList().dispose(); // Reuse instruction handles

                System.out.println(m);

                if (computed_stack == compiled_stack) {
                    System.out.println("Stack ok(" + computed_stack + ")");
                } else {
                    System.out.println("\nCompiled stack size " + compiled_stack + " computed size " + computed_stack);
                }

                if (computed_locals == compiled_locals) {
                    System.out.println("Locals ok(" + computed_locals + ")");
                } else {
                    System.out.println("\nCompiled locals " + compiled_locals + " computed size " + computed_locals);
                }
            }
        }
    }
}
 
Example 10
Source File: LinkageChecker.java    From cloud-opensource-java with Apache License 2.0 4 votes vote down vote up
private ImmutableList<SymbolProblem> findAbstractParentProblems(
    ClassFile classFile, SuperClassSymbol superClassSymbol) {
  ImmutableList.Builder<SymbolProblem> builder = ImmutableList.builder();
  String superClassName = superClassSymbol.getClassBinaryName();
  if (classDumper.isSystemClass(superClassName)) {
    return ImmutableList.of();
  }

  try {
    String className = classFile.getBinaryName();
    JavaClass implementingClass = classDumper.loadJavaClass(className);
    if (implementingClass.isAbstract()) {
      return ImmutableList.of();
    }

    JavaClass superClass = classDumper.loadJavaClass(superClassName);
    if (!superClass.isAbstract()) {
      return ImmutableList.of();
    }

    JavaClass abstractClass = superClass;

    // Equality of BCEL's Method class is on its name and descriptor field
    Set<Method> implementedMethods = new HashSet<>();
    implementedMethods.addAll(ImmutableList.copyOf(implementingClass.getMethods()));

    while (abstractClass.isAbstract()) {
      for (Method abstractMethod : abstractClass.getMethods()) {
        if (!abstractMethod.isAbstract()) {
          // This abstract method has implementation. Subclass does not have to implement it.
          implementedMethods.add(abstractMethod);
        } else if (!implementedMethods.contains(abstractMethod)) {
          String unimplementedMethodName = abstractMethod.getName();
          String unimplementedMethodDescriptor = abstractMethod.getSignature();

          MethodSymbol missingMethodOnClass =
              new MethodSymbol(
                  className, unimplementedMethodName, unimplementedMethodDescriptor, false);
          builder.add(
              new SymbolProblem(missingMethodOnClass, ErrorType.ABSTRACT_METHOD, classFile));
        }
      }
      abstractClass = abstractClass.getSuperClass();
    }
  } catch (ClassNotFoundException ex) {
    // Missing classes are reported by findSymbolProblem method.
  }
  return builder.build();
}
 
Example 11
Source File: MethodsGeneralPane.java    From ApkToolPlus with Apache License 2.0 4 votes vote down vote up
public void actionPerformed(ActionEvent event) {
	if (event.getSource() == addButton) {
		Method method = new Method();
		if (staticCB.isSelected()) {
			method.isStatic(true);
		}
		if (finalCB.isSelected()) {
			method.isFinal(true);
		}
		if (synchronizedCB.isSelected()) {
			method.isSynchronized(true);
		}
		if (nativeCB.isSelected()) {
			method.isNative(true);
		}
		if (abstractCB.isSelected()) {
			method.isAbstract(true);
		}
		if (strictCB.isSelected()) {
			method.isStrictfp(true);
		}
		int selectedItem = dropdown.getSelectedIndex();

		switch (selectedItem) {
		case 1:
			method.isPublic(true);
			break;
		case 2:
			method.isPrivate(true);
			break;
		case 3:
			method.isProtected(true);
			break;
		}

		String fileName = internalFrame.getFileName();
		int accessFlags = method.getAccessFlags();
		String methodName = name.getText();
		String methodDescriptor = descriptor.getText();
		ClassSaver classSaver = new ClassSaver(ClassSaver.ADD_METHOD, fileName,accessFlags, 
				methodName, methodDescriptor);
		ProgressDialog progressDialog = new ProgressDialog(
				internalFrame.getParentFrame(), null,
				"Adding method...");
		progressDialog.setRunnable(classSaver);
		progressDialog.setVisible(true);
		if (classSaver.exceptionOccured()) {
			ErrorReportWindow er = new ErrorReportWindow(internalFrame
					.getParentFrame(), classSaver.getExceptionVerbose(), "Adding method failed");

			er.pack();
			GUIHelper.centerOnParentWindow(er, internalFrame
					.getParentFrame());
			er.setVisible(true);
		} else {

			internalFrame.getParentFrame().doReload();
		}

	}

}
 
Example 12
Source File: Naming.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void visit(Method obj) {
    String mName = getMethodName();
    if (mName.length() == 1) {
        return;
    }
    if ("isRequestedSessionIdFromURL".equals(mName) || "isRequestedSessionIdFromUrl".equals(mName)) {
        return;
    }
    String sig = getMethodSig();
    if (mName.equals(baseClassName) && "()V".equals(sig)) {
        Code code = obj.getCode();
        Method realVoidConstructor = findVoidConstructor(getThisClass());
        if (code != null && !markedAsNotUsable(obj)) {
            int priority = NORMAL_PRIORITY;
            if (codeDoesSomething(code)) {
                priority--;
            } else if (!obj.isPublic() && getThisClass().isPublic()) {
                priority--;
            }
            boolean instanceMembers = false;
            for (Method m : this.getThisClass().getMethods()) {
                if (!m.isStatic() && m != obj && !isVoidConstructor(getThisClass(), m)) {
                    instanceMembers = true;
                }
            }
            for (Field f : this.getThisClass().getFields()) {
                if (!f.isStatic()) {
                    instanceMembers = true;
                }
            }
            if (!codeDoesSomething(code) && !instanceMembers && "java/lang/Object".equals(getSuperclassName())) {
                priority += 2;
            }
            if (hasBadMethodNames) {
                priority++;
            }
            if (!getXClass().getAnnotations().isEmpty()) {
                priority++;
            }
            if (realVoidConstructor != null) {
                priority = LOW_PRIORITY;
            }

            bugReporter.reportBug(new BugInstance(this, "NM_METHOD_CONSTRUCTOR_CONFUSION", priority).addClassAndMethod(this)
                    .lowerPriorityIfDeprecated());
            return;
        }
    } else if (badMethodName(mName)) {
        bugReporter.reportBug(new BugInstance(this, "NM_METHOD_NAMING_CONVENTION", classIsPublicOrProtected
                && (obj.isPublic() || obj.isProtected()) && !hasBadMethodNames ? NORMAL_PRIORITY : LOW_PRIORITY)
                        .addClassAndMethod(this));
    }

    if (obj.isAbstract()) {
        return;
    }
    if (obj.isPrivate()) {
        return;
    }

    if ("equal".equals(mName) && "(Ljava/lang/Object;)Z".equals(sig)) {
        bugReporter.reportBug(new BugInstance(this, "NM_BAD_EQUAL", HIGH_PRIORITY).addClassAndMethod(this)
                .lowerPriorityIfDeprecated());
        return;
    }
    if ("hashcode".equals(mName) && "()I".equals(sig)) {
        bugReporter.reportBug(new BugInstance(this, "NM_LCASE_HASHCODE", HIGH_PRIORITY).addClassAndMethod(this)
                .lowerPriorityIfDeprecated());
        return;
    }
    if ("tostring".equals(mName) && "()Ljava/lang/String;".equals(sig)) {
        bugReporter.reportBug(new BugInstance(this, "NM_LCASE_TOSTRING", HIGH_PRIORITY).addClassAndMethod(this)
                .lowerPriorityIfDeprecated());
        return;
    }

    if (obj.isPrivate() || obj.isStatic() || Const.CONSTRUCTOR_NAME.equals(mName)) {
        return;
    }

    String sig2 = removePackageNamesFromSignature(sig);
    String allSmall = mName.toLowerCase() + sig2;

    XMethod xm = getXMethod();
    {
        TreeSet<XMethod> s = canonicalToXMethod.computeIfAbsent(allSmall, k -> new TreeSet<>());
        s.add(xm);
    }

}
 
Example 13
Source File: FindNoSideEffectMethods.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void visit(Method method) {
    constructor = method.getName().equals(Const.CONSTRUCTOR_NAME);
    classInit = method.getName().equals(Const.STATIC_INITIALIZER_NAME);
    calledMethods = new ArrayList<>();
    status = SideEffectStatus.NO_SIDE_EFFECT;
    if (hasNoSideEffect(getMethodDescriptor())) {
        handleStatus();
        return;
    }
    if (isObjectOnlyMethod(getMethodDescriptor())) {
        status = SideEffectStatus.OBJECT_ONLY;
    }
    if (method.isNative() || changedArg(getMethodDescriptor()) != -1) {
        status = SideEffectStatus.SIDE_EFFECT;
        handleStatus();
        return;
    }
    boolean sawImplementation = false;
    if (classInit) {
        superClinitCall();
    }
    if (!method.isStatic() && !method.isPrivate() && !method.isFinal() && !constructor && subtypes != null) {
        for (ClassDescriptor subtype : subtypes) {
            try {
                XClass xClass = Global.getAnalysisCache().getClassAnalysis(XClass.class, subtype);
                XMethod matchingMethod = xClass.findMatchingMethod(getMethodDescriptor());
                if (matchingMethod != null) {
                    sawImplementation = true;
                    sawCall(new MethodCall(matchingMethod.getMethodDescriptor(), TARGET_THIS), false);
                }
            } catch (CheckedAnalysisException e) {
            }
        }
    }
    if (method.isAbstract() || method.isInterface()) {
        if (!sawImplementation
                || getClassName().endsWith("Visitor") || getClassName().endsWith("Listener")
                || getClassName().startsWith("java/sql/")
                || (getClassName().equals("java/util/concurrent/Future") && !method.getName().startsWith("is"))
                || (getClassName().equals("java/lang/Process") && method.getName().equals("exitValue"))) {
            status = SideEffectStatus.SIDE_EFFECT;
        } else if (isObjectOnlyMethod(getMethodDescriptor())) {
            status = SideEffectStatus.OBJECT_ONLY;
        } else {
            String[] thrownExceptions = getXMethod().getThrownExceptions();
            if (thrownExceptions != null && thrownExceptions.length > 0) {
                status = SideEffectStatus.SIDE_EFFECT;
            }
        }
    }
    if ((status == SideEffectStatus.SIDE_EFFECT || status == SideEffectStatus.OBJECT_ONLY) || method.isAbstract()
            || method.isInterface() || method.isNative()) {
        handleStatus();
    }
}
 
Example 14
Source File: helloify.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
/**
 * Patch a method.
 */
private static Method helloifyMethod(Method m) {
    final Code code = m.getCode();
    final int flags = m.getAccessFlags();
    final String name = m.getName();

    // Sanity check
    if (m.isNative() || m.isAbstract() || (code == null)) {
        return m;
    }

    // Create instruction list to be inserted at method start.
    final String mesg = "Hello from " + Utility.methodSignatureToString(m.getSignature(),
            name,
            Utility.accessToString(flags));
    final InstructionList patch = new InstructionList();
    patch.append(new GETSTATIC(out));
    patch.append(new PUSH(cp, mesg));
    patch.append(new INVOKEVIRTUAL(println));

    final MethodGen mg = new MethodGen(m, class_name, cp);
    final InstructionList il = mg.getInstructionList();
    final InstructionHandle[] ihs = il.getInstructionHandles();

    if (name.equals("<init>")) { // First let the super or other constructor be called
        for (int j = 1; j < ihs.length; j++) {
            if (ihs[j].getInstruction() instanceof INVOKESPECIAL) {
                il.append(ihs[j], patch); // Should check: method name == "<init>"
                break;
            }
        }
    } else {
        il.insert(ihs[0], patch);
    }

    // Stack size must be at least 2, since the println method takes 2 argument.
    if (code.getMaxStack() < 2) {
        mg.setMaxStack(2);
    }

    m = mg.getMethod();

    il.dispose(); // Reuse instruction handles

    return m;
}