org.apache.bcel.classfile.JavaClass Java Examples

The following examples show how to use org.apache.bcel.classfile.JavaClass. 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: ClassDumperTest.java    From cloud-opensource-java with 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 #2
Source File: ParserTest.java    From JQF with 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 #3
Source File: FieldAnnotationsTestCase.java    From commons-bcel with 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 #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: FindHEmismatch.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #6
Source File: PreorderVisitor.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #7
Source File: Subtypes2.java    From spotbugs with 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 #8
Source File: AnalysisContext.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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 #9
Source File: TransitiveHull.java    From commons-bcel with 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 #10
Source File: Hierarchy.java    From spotbugs with 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 #11
Source File: AnonymousLdapDetector.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #12
Source File: AnalysisCache.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #13
Source File: InvalidJUnitTest.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #14
Source File: FindBugsSummaryStats.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #15
Source File: SpringUnvalidatedRedirectDetector.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 #16
Source File: AnonymousClassTestCase.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
public void testAnonymousInnerClassIsAnonymous()
        throws ClassNotFoundException
{
    final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AnonymousClassTest$1");
    assertTrue("anonymous inner classes are anonymous", clazz.isAnonymous());
    assertTrue("anonymous inner classes are anonymous", clazz.isNested());
}
 
Example #17
Source File: UncallableMethodOfAnonymousClass.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
Set<String> definedInClass(JavaClass clazz) {
    HashSet<String> result = new HashSet<>();
    for (Method m : clazz.getMethods()) {
        if (!skip(m)) {
            result.add(m.getName() + m.getSignature());
        }
    }
    return result;
}
 
Example #18
Source File: JavaClassGenerator.java    From JQF with 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 #19
Source File: VerifierAppFrame.java    From commons-bcel with 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 #20
Source File: FindUnreleasedLock.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@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 File: SpringUnvalidatedRedirectDetector.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 #22
Source File: LDAPSSLSocketFactoryGenerator.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the LDAPSocketFactoryImpl class (subclass of {@link AbstractLDAPSSLSocketFactory}.
 * A static method #getDefaulta, a static field _sslContent and no-arg constructor are added
 * to the class.
 *
 * @param className
 *
 * @return byte code
 */
private static byte[] createSubClassByteCode(final String className)
{
    ClassGen classGen = new ClassGen(className,
            AbstractLDAPSSLSocketFactory.class.getName(),
            "<generated>",
            ACC_PUBLIC | ACC_SUPER,
            null);
    ConstantPoolGen constantPoolGen = classGen.getConstantPool();
    InstructionFactory factory = new InstructionFactory(classGen);

    createSslContextStaticField(classGen, constantPoolGen);
    createGetDefaultStaticMethod(classGen, constantPoolGen, factory);

    classGen.addEmptyConstructor(ACC_PROTECTED);

    JavaClass javaClass = classGen.getJavaClass();
    ByteArrayOutputStream out = null;
    try
    {
        out = new ByteArrayOutputStream();
        javaClass.dump(out);
        return out.toByteArray();
    }
    catch (IOException ioex)
    {
        throw new IllegalStateException("Could not write to a ByteArrayOutputStream - should not happen", ioex);
    }
    finally
    {
        closeSafely(out);
    }
}
 
Example #23
Source File: MethodGenTestCase.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
private void testInvalidNullMethodBody(final String className) throws ClassNotFoundException {
    final JavaClass jc = Repository.lookupClass(className);
    final ClassGen classGen = new ClassGen(jc);
    for (final Method method : jc.getMethods()) {
        new MethodGen(method, jc.getClassName(), classGen.getConstantPool());
    }
}
 
Example #24
Source File: ConstantPasswordDetector.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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);
}
 
Example #25
Source File: Encoder.java    From javasdk with 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 #26
Source File: PermissiveCORSDetector.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 INVOKEINTERFACE) {
                INVOKEINTERFACE invoke = (INVOKEINTERFACE) inst;
                String methodName = invoke.getMethodName(cpg);
                String className = invoke.getClassName(cpg);

                if (className.equals("javax.servlet.http.HttpServletResponse") &&
                   (methodName.equals("addHeader") || methodName.equals("setHeader"))) {

                    LDC ldc = ByteCode.getPrevInstruction(location.getHandle().getPrev(), LDC.class);
                    if (ldc != null) {
                        String headerValue = ByteCode.getConstantLDC(location.getHandle().getPrev(), cpg, String.class);
                        if ("Access-Control-Allow-Origin".equalsIgnoreCase((String)ldc.getValue(cpg)) &&
                            (headerValue.contains("*") || "null".equalsIgnoreCase(headerValue))) {

                            JavaClass clz = classContext.getJavaClass();
                            bugReporter.reportBug(new BugInstance(this, PERMISSIVE_CORS, Priorities.HIGH_PRIORITY)
                            .addClass(clz)
                            .addMethod(clz, m)
                            .addSourceLine(classContext, m, location));
                        }
                    }
                }
            }
        }         
        
    }
 
Example #27
Source File: Naming.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 #28
Source File: URLClassPathRepository.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void removeClass(JavaClass javaClass) {
    nameToClassMap.remove(javaClass.getClassName());
    if (DEBUG) {
        System.out.println("Removing class " + javaClass.getClassName() + " from Repository");
        dumpStack();
    }
}
 
Example #29
Source File: InsufficientKeySizeRsaDetector.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void addToReport(Method m, ClassContext classContext, Location locationWeakness, Number n){
    JavaClass clz = classContext.getJavaClass();
    int priority = (n.intValue() < 1024) ? Priorities.NORMAL_PRIORITY : Priorities.LOW_PRIORITY;
    bugReporter.reportBug(new BugInstance(this, RSA_KEY_SIZE_TYPE, priority) //
            .addClass(clz)
            .addMethod(clz, m)
            .addSourceLine(classContext, m, locationWeakness));
}
 
Example #30
Source File: Naming.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visitJavaClass(JavaClass obj) {
    if (BCELUtil.isSynthetic(obj)) {
        return;
    }
    String name = obj.getClassName();
    if (!visited.add(name)) {
        return;
    }

    String superClassName = obj.getSuperclassName();
    if (!Values.DOTTED_JAVA_LANG_OBJECT.equals(name)) {
        if (sameSimpleName(superClassName, name)) {
            bugReporter.reportBug(new BugInstance(this, "NM_SAME_SIMPLE_NAME_AS_SUPERCLASS", HIGH_PRIORITY).addClass(name)
                    .addClass(superClassName));
        }
        for (String interfaceName : obj.getInterfaceNames()) {
            if (sameSimpleName(interfaceName, name)) {
                bugReporter.reportBug(new BugInstance(this, "NM_SAME_SIMPLE_NAME_AS_INTERFACE", NORMAL_PRIORITY).addClass(
                        name).addClass(interfaceName));
            }
        }
    }
    if (obj.isInterface()) {
        return;
    }

    if (Values.DOTTED_JAVA_LANG_OBJECT.equals(superClassName) && !visited.contains(superClassName)) {
        try {
            visitJavaClass(obj.getSuperClass());
        } catch (ClassNotFoundException e) {
            // ignore it
        }
    }
    super.visitJavaClass(obj);
}