Java Code Examples for org.apache.bcel.classfile.JavaClass

The following examples show how to use org.apache.bcel.classfile.JavaClass. These examples are extracted from open source projects. 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
@Override
public void visitAfter(JavaClass obj) {
    int linesNCSS = 1 + methods + fields;
    if (sawLineNumbers) {
        linesNCSS += lines.cardinality();
    } else {
        linesNCSS += classCodeSize / 10;
    }
    if (stats != null) {
        stats.addClass(getDottedClassName(), obj.getSourceFileName(), obj.isInterface(), linesNCSS);
    }
    totalCodeSize += classCodeSize;
    totalNCSS += linesNCSS;
    totalMethods += methods;
    totalFields += fields;

}
 
Example 2
Source Project: spotbugs   Source File: Hierarchy.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
public static @CheckForNull JavaClassAndMethod findMethod(JavaClass javaClass, String methodName, String methodSig,
        JavaClassAndMethodChooser chooser) {
    if (DEBUG_METHOD_LOOKUP) {
        System.out.println("Check " + javaClass.getClassName());
    }
    Method[] methodList = javaClass.getMethods();
    for (Method method : methodList) {
        if (method.getName().equals(methodName) && method.getSignature().equals(methodSig)) {
            JavaClassAndMethod m = new JavaClassAndMethod(javaClass, method);
            if (chooser.choose(m)) {
                if (DEBUG_METHOD_LOOKUP) {
                    System.out.println("\t==> FOUND: " + method);
                }
                return m;
            }
        }
    }
    if (DEBUG_METHOD_LOOKUP) {
        System.out.println("\t==> NOT FOUND");
    }
    return null;
}
 
Example 3
Source Project: spotbugs   Source File: Subtypes2.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
public static boolean instanceOf(JavaClass subtype, @DottedClassName String dottedSupertype) {
    if (subtype.getClassName().equals(dottedSupertype) || subtype.getSuperclassName().equals(dottedSupertype)) {
        return true;
    }
    if (Values.DOTTED_JAVA_LANG_OBJECT.equals(subtype.getSuperclassName()) && subtype.getInterfaceIndices().length == 0) {
        return false;
    }
    Subtypes2 subtypes2 = AnalysisContext.currentAnalysisContext().getSubtypes2();
    ClassDescriptor subDescriptor = DescriptorFactory.createClassDescriptor(subtype);
    ClassDescriptor superDescriptor = DescriptorFactory.createClassDescriptorFromDottedClassName(dottedSupertype);
    try {
        return subtypes2.isSubtype(subDescriptor, superDescriptor);
    } catch (ClassNotFoundException e) {
        AnalysisContext.reportMissingClass(e);
        return false;
    }
}
 
Example 4
@Override
public void visit(JavaClass obj) {
    extendsObject = Values.DOTTED_JAVA_LANG_OBJECT.equals(getDottedSuperclassName());
    hasFields = false;
    hasHashCode = false;
    hasCompareToObject = false;
    hasCompareToBridgeMethod = false;
    hasCompareToSelf = false;
    hasEqualsObject = false;
    hasEqualsSelf = false;
    hasEqualsOther = false;
    hashCodeIsAbstract = false;
    equalsObjectIsAbstract = false;
    equalsMethodIsInstanceOfEquals = false;
    equalsMethod = null;
    equalsOtherMethod = null;
    compareToMethod = null;
    compareToSelfMethod = null;
    compareToObjectMethod = null;
    hashCodeMethod = null;
    equalsOtherClass = null;
    isApplicationClass = AnalysisContext.currentAnalysisContext().isApplicationClass(obj);
}
 
Example 5
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 6
Source Project: commons-bcel   Source File: FieldAnnotationsTestCase.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Check field AnnotationEntrys (de)serialize ok.
 */
public void testFieldAnnotationEntrysReadWrite() throws ClassNotFoundException,
        IOException
{
    final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AnnotatedFields");
    checkAnnotatedField(clazz, "i", "L"+PACKAGE_BASE_SIG+"/data/SimpleAnnotation;", "id", "1");
    checkAnnotatedField(clazz, "s", "L"+PACKAGE_BASE_SIG+"/data/SimpleAnnotation;", "id", "2");
    // Write it out
    final File tfile = createTestdataFile("AnnotatedFields.class");
    clazz.dump(tfile);
    final SyntheticRepository repos2 = createRepos(".");
    repos2.loadClass("AnnotatedFields");
    checkAnnotatedField(clazz, "i", "L"+PACKAGE_BASE_SIG+"/data/SimpleAnnotation;", "id", "1");
    checkAnnotatedField(clazz, "s", "L"+PACKAGE_BASE_SIG+"/data/SimpleAnnotation;", "id", "2");
    assertTrue(tfile.delete());
}
 
Example 7
public void setupVisitorForClass(JavaClass obj) {
    constantPool = obj.getConstantPool();
    thisClass = obj;
    ConstantClass c = (ConstantClass) constantPool.getConstant(obj.getClassNameIndex());
    className = getStringFromIndex(c.getNameIndex());
    dottedClassName = className.replace('/', '.');
    packageName = obj.getPackageName();
    sourceFile = obj.getSourceFileName();
    dottedSuperclassName = obj.getSuperclassName();
    superclassName = dottedSuperclassName.replace('.', '/');

    ClassDescriptor cDesc = DescriptorFactory.createClassDescriptor(className);
    if (!FindBugs.isNoAnalysis()) {
        try {
            thisClassInfo = (ClassInfo) Global.getAnalysisCache().getClassAnalysis(XClass.class, cDesc);
        } catch (CheckedAnalysisException e) {
            throw new AssertionError("Can't find ClassInfo for " + cDesc);
        }
    }

    super.visitJavaClass(obj);
}
 
Example 8
Source Project: cloud-opensource-java   Source File: ClassDumperTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testListInnerClasses() throws IOException {
  InputStream classFileInputStream = URLClassLoader.getSystemResourceAsStream(
      EXAMPLE_CLASS_FILE);
  ClassParser parser = new ClassParser(classFileInputStream, EXAMPLE_CLASS_FILE);
  JavaClass javaClass = parser.parse();

  Set<String> innerClassNames = ClassDumper.listInnerClassNames(javaClass);
  Truth.assertThat(innerClassNames).containsExactly(
      "com.google.firestore.v1beta1.FirestoreGrpc$FirestoreFutureStub",
      "com.google.firestore.v1beta1.FirestoreGrpc$FirestoreMethodDescriptorSupplier",
      "com.google.firestore.v1beta1.FirestoreGrpc$1",
      "com.google.firestore.v1beta1.FirestoreGrpc$MethodHandlers",
      "com.google.firestore.v1beta1.FirestoreGrpc$FirestoreStub",
      "com.google.firestore.v1beta1.FirestoreGrpc$FirestoreBaseDescriptorSupplier",
      "com.google.firestore.v1beta1.FirestoreGrpc$FirestoreBlockingStub",
      "com.google.firestore.v1beta1.FirestoreGrpc$FirestoreImplBase",
      "com.google.firestore.v1beta1.FirestoreGrpc$FirestoreFileDescriptorSupplier"
  );
}
 
Example 9
Source Project: JQF   Source File: ParserTest.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Fuzz
public void verifyJavaClass(@From(JavaClassGenerator.class) JavaClass javaClass) throws IOException {
    try {
        Repository.addClass(javaClass);
        Verifier verifier = StatelessVerifierFactory.getVerifier(javaClass.getClassName());
        VerificationResult result;
        result = verifier.doPass1();
        assumeThat(result.getMessage(), result.getStatus(), is(VerificationResult.VERIFIED_OK));
        result = verifier.doPass2();
        assumeThat(result.getMessage(), result.getStatus(), is(VerificationResult.VERIFIED_OK));
        for (int i = 0; i < javaClass.getMethods().length; i++) {
            result = verifier.doPass3a(i);
            assumeThat(result.getMessage(), result.getStatus(), is(VerificationResult.VERIFIED_OK));
        }
    } finally {
        Repository.clearCache();
    }
}
 
Example 10
@Override
public void visit(Code obj) {
    if (!directChildOfTestCase && (getMethodName().equals("setUp") || getMethodName().equals("tearDown"))
            && !getMethod().isPrivate() && getMethodSig().equals("()V")) {
        sawSuperCall = false;
        super.visit(obj);
        if (sawSuperCall) {
            return;
        }
        JavaClass we = Lookup.findSuperImplementor(getThisClass(), getMethodName(), "()V", bugReporter);
        if (we != null && !we.getClassName().equals("junit.framework.TestCase")) {
            // OK, got a bug
            int offset = 0;
            if (getMethodName().equals("tearDown")) {
                offset = obj.getCode().length - 1;
            }
            Method superMethod = Lookup.findImplementation(we, getMethodName(), "()V");
            Code superCode = superMethod.getCode();
            if (superCode != null && superCode.getCode().length > 3) {
                bugReporter.reportBug(new BugInstance(this, getMethodName().equals("setUp") ? "IJU_SETUP_NO_SUPER"
                        : "IJU_TEARDOWN_NO_SUPER", NORMAL_PRIORITY).addClassAndMethod(this).addMethod(we, superMethod)
                                .describe(MethodAnnotation.METHOD_OVERRIDDEN).addSourceLine(this, offset));
            }
        }
    }
}
 
Example 11
private static <DescriptorType> Map<DescriptorType, Object> createMap(
        final Map<Class<?>, ? extends IAnalysisEngine<DescriptorType, ?>> engineMap,
        final Class<?> analysisClass) {
    Map<DescriptorType, Object> descriptorMap;
    // Create a MapCache that allows the analysis engine to
    // decide that analysis results should be retained indefinitely.
    IAnalysisEngine<DescriptorType, ?> engine = engineMap.get(analysisClass);
    if (analysisClass.equals(JavaClass.class)) {
        descriptorMap = new MapCache<>(MAX_JAVACLASS_RESULTS_TO_CACHE);
    } else if (analysisClass.equals(FBClassReader.class)) {
        descriptorMap = new MapCache<>(MAX_FBCLASSREADER_RESULTS_TO_CACHE);
    } else if (analysisClass.equals(ConstantPoolGen.class)) {
        descriptorMap = new MapCache<>(MAX_CONSTANT_POOL_GEN_RESULTS_TO_CACHE);
    } else if (analysisClass.equals(ClassContext.class)) {
        descriptorMap = new MapCache<>(10);
    } else if (engine instanceof IClassAnalysisEngine && ((IClassAnalysisEngine<?>) engine).canRecompute()) {
        descriptorMap = new MapCache<>(MAX_CLASS_RESULTS_TO_CACHE);
    } else {
        descriptorMap = new HashMap<>();
    }
    return descriptorMap;
}
 
Example 12
private void analyzeMethod(Method m, ClassContext classContext) throws CFGBuilderException, DataflowAnalysisException {

        ConstantPoolGen cpg = classContext.getConstantPoolGen();
        CFG cfg = classContext.getCFG(m);
        
        for (Iterator<Location> i = cfg.locationIterator(); i.hasNext(); ) {
            Location location = i.next();

            Instruction inst = location.getHandle().getInstruction();
            
            if (inst instanceof LDC) {
                LDC ldc = (LDC) inst;
                if (ldc != null) {
                    if("java.naming.security.authentication".equals(ldc.getValue(cpg)) &&
                       "none".equals(ByteCode.getConstantLDC(location.getHandle().getNext(), cpg, String.class))){
                        JavaClass clz = classContext.getJavaClass();
                        bugReporter.reportBug(new BugInstance(this, LDAP_ANONYMOUS, Priorities.LOW_PRIORITY) //
                        .addClass(clz)
                        .addMethod(clz, m)
                        .addSourceLine(classContext, m, location));
                        break;
                    }
                }
            }            
        }
    }
 
Example 13
/**
 * This is equivalent to Repository.lookupClass() or this.lookupClass(),
 * except it uses the original Repository instead of the current one.
 *
 * This can be important because URLClassPathRepository objects are closed
 * after an analysis, so JavaClass objects obtained from them are no good on
 * subsequent runs.
 *
 * @param className
 *            the name of the class
 * @return the JavaClass representing the class
 * @throws ClassNotFoundException
 */
public static JavaClass lookupSystemClass(@Nonnull String className) throws ClassNotFoundException {
    // TODO: eventually we should move to our own thread-safe repository
    // implementation
    requireNonNull(className, "className is null");
    if (originalRepository == null) {
        throw new IllegalStateException("originalRepository is null");
    }

    JavaClass clazz = originalRepository.findClass(className);
    if (clazz != null) {
        return clazz;
    }
    // XXX workaround for system classes missing on Java 9
    // Not sure if we BCEL update, but this seem to work in simple cases
    return AnalysisContext.currentAnalysisContext().lookupClass(className);
}
 
Example 14
Source Project: commons-bcel   Source File: TransitiveHull.java    License: Apache License 2.0 6 votes vote down vote up
private void add(String class_name) {
    class_name = class_name.replace('/', '.');

    for (final String anIgnored : ignored) {
        if (Pattern.matches(anIgnored, class_name)) {
            return;
        }
    }

    try {
        final JavaClass clazz = Repository.lookupClass(class_name);

        if (set.add(clazz)) {
            queue.enqueue(clazz);
        }
    } catch (final ClassNotFoundException e) {
        throw new IllegalStateException("Missing class: " + e.toString());
    }
}
 
Example 15
Source Project: javasdk   Source File: Encoder.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * get hvm invoke payload.
 *
 * @param bean invoke bean
 * @return payload
 */
public static String encodeInvokeBeanJava(BaseInvoke bean) {
    try {
        //1. get the bean class bytes
        ClassLoaderRepository repository = new ClassLoaderRepository(Thread.currentThread().getContextClassLoader());
        JavaClass beanClass = repository.loadClass(bean.getClass());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        beanClass.dump(baos);
        byte[] clazz = baos.toByteArray();
        if (clazz.length > 0xffff) {
            throw new IOException("the bean class is too large"); // 64k
        }
        //2. get the bean class name
        byte[] clzName = bean.getClass().getCanonicalName().getBytes(Utils.DEFAULT_CHARSET);
        if (clzName.length > 0xffff) {
            throw new IOException("the bean class name is too large"); // 64k
        }
        //3. get the bin of bean
        Gson gson = new Gson();
        byte[] beanBin = gson.toJson(bean).getBytes(Utils.DEFAULT_CHARSET);
        //4. accumulate: | class length(4B) | name length(2B) | class | class name | bin |
        //               | len(txHash)      | len("__txHash__")| txHash | "__txHash__" | bin |
        StringBuilder sb = new StringBuilder();
        sb.append(ByteUtil.toHex(ByteUtil.intToByteArray(clazz.length)));
        sb.append(ByteUtil.toHex(ByteUtil.shortToBytes((short) clzName.length)));

        sb.append(ByteUtil.toHex(clazz));
        sb.append(ByteUtil.toHex(clzName));
        sb.append(ByteUtil.toHex(beanBin));
        return sb.toString();
    } catch (ClassNotFoundException | IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 16
@Override
public void visitAfter(JavaClass obj) {
    for (String i : obj.getInterfaceNames()) {
        if ("java.lang.annotation.Annotation".equals(i)) {
            AnalysisContext.currentAnalysisContext().getAnnotationRetentionDatabase()
                    .setRuntimeRetention(getDottedClassName(), runtimeRetention);
        }
    }

}
 
Example 17
Source Project: spotbugs   Source File: SelfCalls.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Is the given instruction a self-call?
 */
private Method isSelfCall(InvokeInstruction inv) {
    ConstantPoolGen cpg = classContext.getConstantPoolGen();
    JavaClass jclass = classContext.getJavaClass();

    String calledClassName = inv.getClassName(cpg);

    // FIXME: is it possible we would see a superclass name here?
    // Not a big deal for now, as we are mostly just interested in calls
    // to private methods, for which we will definitely see the right
    // called class name.
    if (!calledClassName.equals(jclass.getClassName())) {
        return null;
    }

    String calledMethodName = inv.getMethodName(cpg);
    String calledMethodSignature = inv.getSignature(cpg);
    boolean isStaticCall = (inv instanceof INVOKESTATIC);

    // Scan methods for one that matches.
    Method[] methods = jclass.getMethods();
    for (Method method : methods) {
        String methodName = method.getName();
        String signature = method.getSignature();
        boolean isStatic = method.isStatic();

        if (methodName.equals(calledMethodName) && signature.equals(calledMethodSignature) && isStatic == isStaticCall) {
            // This method looks like a match.
            return wantCallsFor(method) ? method : null;
        }
    }

    // Hmm...no matching method found.
    // This is almost certainly because the named method
    // was inherited from a superclass.
    LOG.debug("No method found for {}.{} : {}", calledClassName, calledMethodName, calledMethodSignature);
    return null;
}
 
Example 18
Source Project: ApkToolPlus   Source File: TransitiveHull.java    License: Apache License 2.0 5 votes vote down vote up
public void update(String classname){

		System.gc(); // avoid swapping if possible.

		for (int i=0; i<indent; i++){
			System.out.print(" ");
		}
		System.out.println(classname);
		indent += 1;

		Verifier v = VerifierFactory.getVerifier(classname);
	
		VerificationResult vr;
		vr = v.doPass1();
		if (vr != VerificationResult.VR_OK) //System.exit(1);
			System.out.println("Pass 1:\n"+vr);

		vr = v.doPass2();
      if (vr != VerificationResult.VR_OK) //System.exit(1);
			System.out.println("Pass 2:\n"+vr);

		if (vr == VerificationResult.VR_OK){
			JavaClass jc = Repository.lookupClass(v.getClassName());
			for (int i=0; i<jc.getMethods().length; i++){
				vr = v.doPass3a(i);
				if (vr != VerificationResult.VR_OK) //System.exit(1);
					System.out.println(v.getClassName()+", Pass 3a, method "+i+" ['"+jc.getMethods()[i]+"']:\n"+vr);

				vr = v.doPass3b(i);
				if (vr != VerificationResult.VR_OK) //System.exit(1);
					System.out.println(v.getClassName()+", Pass 3b, method "+i+" ['"+jc.getMethods()[i]+"']:\n"+vr);
			}
		}

		indent -= 1;
	}
 
Example 19
private boolean classDefinesMethod(JavaClass c, XMethod m) {
    for (Method definedMethod : c.getMethods()) {
        if (definedMethod.getName().equals(m.getName()) && definedMethod.getSignature().equals(m.getSignature())
                && definedMethod.isStatic() == m.isStatic()) {
            return true;
        }
    }
    return false;
}
 
Example 20
@Override
public void inspectResult(ClassContext classContext, MethodGen methodGen, CFG cfg,
        Dataflow<ResourceValueFrame, ResourceValueAnalysis<Lock>> dataflow, Lock resource) {

    JavaClass javaClass = classContext.getJavaClass();

    ResourceValueFrame exitFrame = dataflow.getResultFact(cfg.getExit());
    if (DEBUG) {
        System.out.println("Resource value at exit: " + exitFrame);
    }
    int exitStatus = exitFrame.getStatus();

    if (exitStatus == ResourceValueFrame.OPEN || exitStatus == ResourceValueFrame.OPEN_ON_EXCEPTION_PATH) {
        String bugType;
        int priority;
        if (exitStatus == ResourceValueFrame.OPEN) {
            bugType = "UL_UNRELEASED_LOCK";
            priority = HIGH_PRIORITY;
        } else {
            bugType = "UL_UNRELEASED_LOCK_EXCEPTION_PATH";
            priority = NORMAL_PRIORITY;
        }

        String sourceFile = javaClass.getSourceFileName();
        Location location = resource.getLocation();
        InstructionHandle handle = location.getHandle();
        InstructionHandle nextInstruction = handle.getNext();
        if (nextInstruction.getInstruction() instanceof RETURN) {
            return; // don't report as error; intentional
        }
        bugAccumulator.accumulateBug(new BugInstance(this, bugType, priority).addClassAndMethod(methodGen, sourceFile),
                SourceLineAnnotation.fromVisitedInstruction(classContext, methodGen, sourceFile, handle));
    }
}
 
Example 21
Source Project: commons-bcel   Source File: VerifierAppFrame.java    License: Apache License 2.0 5 votes vote down vote up
synchronized void pass3bJList_valueChanged( final ListSelectionEvent e ) {
    if (e.getValueIsAdjusting()) {
        return;
    }
    final Verifier v = VerifierFactory.getVerifier(current_class);
    final StringBuilder all3bmsg = new StringBuilder();
    boolean all3bok = true;
    boolean rejected = false;
    for (int i = 0; i < pass3bJList.getModel().getSize(); i++) {
        if (pass3bJList.isSelectedIndex(i)) {
            final VerificationResult vr = v.doPass3b(i);
            if (vr.getStatus() == VerificationResult.VERIFIED_REJECTED) {
                all3bok = false;
                rejected = true;
            }
            JavaClass jc = null;
            try {
                jc = Repository.lookupClass(v.getClassName());
                all3bmsg.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();
            }
        }
    }
    pass3bTextPane.setText(all3bmsg.toString());
    pass3bTextPane.setBackground(all3bok ? Color.green : (rejected ? Color.red : Color.yellow));
}
 
Example 22
@Override
public void storeClass(JavaClass javaClass) {
  String className = javaClass.getClassName();
  loadedClass.put(className, javaClass);
  javaClass.setRepository(this);

  String fileName = javaClass.getFileName();
  if (!className.equals(fileName)) {
    // When class file has special location not matching class name, remember it to load the class
    // file by class name.
    classFileNames.put(className, fileName);
  }
}
 
Example 23
@Override
public JavaClass loadClass(String className) throws ClassNotFoundException {
  // Check special location for the class. If it's not found, lookup by className instead.
  // Usually classFileName == className. But sometimes classFileName has a framework-specific
  // prefix. Example: "BOOT-INF.classes.com.google.Foo"
  String fileName = getFileName(className);
  return super.loadClass(fileName);
}
 
Example 24
Source Project: gemfirexd-oss   Source File: ClassPathLoaderJUnitTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
  ClassGen cg = new ClassGen(name, "java.lang.Object", "<generated>", Constants.ACC_PUBLIC | Constants.ACC_SUPER, null);
  cg.addEmptyConstructor(Constants.ACC_PUBLIC);
  JavaClass jClazz = cg.getJavaClass();
  byte[] bytes = jClazz.getBytes();
  return defineClass(jClazz.getClassName(), bytes, 0, bytes.length);
}
 
Example 25
Source Project: commons-bcel   Source File: MethodGenTestCase.java    License: Apache License 2.0 5 votes vote down vote up
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 26
Source Project: commons-bcel   Source File: BCELifier.java    License: Apache License 2.0 5 votes vote down vote up
/** Default main method
 */
public static void main( final String[] argv ) throws Exception {
    if (argv.length != 1) {
        System.out.println("Usage: BCELifier classname");
        System.out.println("\tThe class must exist on the classpath");
        return;
    }
    final JavaClass java_class = getJavaClass(argv[0]);
    final BCELifier bcelifier = new BCELifier(java_class, System.out);
    bcelifier.start();
}
 
Example 27
Source Project: JQF   Source File: JavaClassGenerator.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public JavaClass generate(SourceOfRandomness r, GenerationStatus s) {
    constants = new ConstantPoolGen();

    // Generate a class with its meta-data
    String className = "example.A";
    String superName = r.nextBoolean() ? "example.B" : "java.lang.Object";
    String fileName = "A.class";
    int flags = r.nextInt(0, Short.MAX_VALUE);
    int numInterfaces = r.nextBoolean() ? 0 : geom.sampleWithMean(MEAN_INTERFACE_COUNT, r);
    String[] interfaces = new String[numInterfaces];
    for (int i = 0; i < numInterfaces; i++) {
        interfaces[i] = "example.I"+i;
    }
    ClassGen classGen = new ClassGen(className, superName, fileName, flags, interfaces, constants);

    // Validate flags
    Assume.assumeFalse(classGen.isFinal() && (classGen.isAbstract() | classGen.isInterface()));

    int numFields = geom.sampleWithMean(MEAN_FIELDS_COUNT, r);
    for (int i = 0; i < numFields; i++) {
        classGen.addField(generateField(r));
    }

    int numMethods = geom.sampleWithMean(MEAN_METHODS_COUNT, r);
    for (int i = 0; i < numMethods; i++) {
        classGen.addMethod(generateMethod(className, r));
    }

    return classGen.getJavaClass();

}
 
Example 28
@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 29
private void analyzeMethod(Method m, ClassContext classContext) throws CFGBuilderException{
    JavaClass clazz = classContext.getJavaClass();
    ConstantPoolGen cpg = classContext.getConstantPoolGen();
    CFG cfg = classContext.getCFG(m);

    for (Iterator<Location> i = cfg.locationIterator(); i.hasNext(); ) {
        Location loc = i.next();
        Instruction inst = loc.getHandle().getInstruction();

        if (inst instanceof INVOKEVIRTUAL) {
            INVOKEVIRTUAL invoke = (INVOKEVIRTUAL)inst;
            if( "java.lang.StringBuilder".equals(invoke.getClassName(cpg)) && "append".equals(invoke.getMethodName(cpg))) {
                Instruction prev = loc.getHandle().getPrev().getInstruction();

                if (prev instanceof LDC) {
                    LDC ldc = (LDC)prev;
                    Object value = ldc.getValue(cpg);

                    if (value instanceof String) {
                        String v = (String)value;

                        if ("redirect:".equals(v)) {
                            BugInstance bug = new BugInstance(this, SPRING_UNVALIDATED_REDIRECT_TYPE, Priorities.NORMAL_PRIORITY);
                            bug.addClass(clazz).addMethod(clazz,m).addSourceLine(classContext,m,loc);
                            reporter.reportBug(bug);
                        }
                    }
                }
            }
        }
    }
}
 
Example 30
@Override
public void visitAfter(JavaClass obj) {
    Collection<String> fieldsToReport = new ArrayList<String>();
    for (String field : hardCodedFields) {
        if (isSuspiciousName(field, obj) && !reportedFields.contains(field)) {
            fieldsToReport.add(field);
        }
    }
    reportBugSource(fieldsToReport, Priorities.NORMAL_PRIORITY);
    // TODO global analysis
    hardCodedFields.clear();
    reportedFields.clear();
    super.visitAfter(obj);
}