Search in sources :

Example 71 with JavaClass

use of org.apache.bcel.classfile.JavaClass in project narchy by automenta.

the class MethodCallGraph method addClass.

public MethodCallGraph addClass(String rootClass) throws ClassNotFoundException {
    JavaClass c = Repository.lookupClass(rootClass);
    ClassVisitor visitor = new ClassVisitor(this, c);
    visitor.start();
    return this;
}
Also used : JavaClass(org.apache.bcel.classfile.JavaClass)

Example 72 with JavaClass

use of org.apache.bcel.classfile.JavaClass in project ant by apache.

the class AncestorAnalyzer method determineDependencies.

/**
 * Determine the dependencies of the configured root classes.
 *
 * @param files a vector to be populated with the files which contain
 *      the dependency classes
 * @param classes a vector to be populated with the names of the
 *      dependency classes.
 */
@Override
protected void determineDependencies(Vector<File> files, Vector<String> classes) {
    // we get the root classes and build up a set of
    // classes upon which they depend
    Set<String> dependencies = new HashSet<>();
    Set<File> containers = new HashSet<>();
    Set<String> toAnalyze = new HashSet<>();
    Set<String> nextAnalyze = new HashSet<>();
    for (Enumeration<String> e = getRootClasses(); e.hasMoreElements(); ) {
        toAnalyze.add(e.nextElement());
    }
    int count = 0;
    int maxCount = isClosureRequired() ? MAX_LOOPS : 2;
    while (!toAnalyze.isEmpty() && count++ < maxCount) {
        nextAnalyze.clear();
        for (String classname : toAnalyze) {
            dependencies.add(classname);
            try {
                File container = getClassContainer(classname);
                if (container == null) {
                    continue;
                }
                containers.add(container);
                ClassParser parser;
                if (container.getName().endsWith(".class")) {
                    parser = new ClassParser(container.getPath());
                } else {
                    parser = new ClassParser(container.getPath(), classname.replace('.', '/') + ".class");
                }
                JavaClass javaClass = parser.parse();
                for (String interfaceName : javaClass.getInterfaceNames()) {
                    if (!dependencies.contains(interfaceName)) {
                        nextAnalyze.add(interfaceName);
                    }
                }
                if (javaClass.isClass()) {
                    String superClass = javaClass.getSuperclassName();
                    if (!dependencies.contains(superClass)) {
                        nextAnalyze.add(superClass);
                    }
                }
            } catch (IOException ioe) {
            // ignore
            }
        }
        Set<String> temp = toAnalyze;
        toAnalyze = nextAnalyze;
        nextAnalyze = temp;
    }
    files.clear();
    files.addAll(containers);
    classes.clear();
    classes.addAll(dependencies);
}
Also used : JavaClass(org.apache.bcel.classfile.JavaClass) IOException(java.io.IOException) File(java.io.File) HashSet(java.util.HashSet) ClassParser(org.apache.bcel.classfile.ClassParser)

Example 73 with JavaClass

use of org.apache.bcel.classfile.JavaClass in project ant by apache.

the class FullAnalyzer method determineDependencies.

/**
 * Determine the dependencies of the configured root classes.
 *
 * @param files a vector to be populated with the files which contain
 *      the dependency classes
 * @param classes a vector to be populated with the names of the
 *      dependency classes.
 */
@Override
protected void determineDependencies(Vector<File> files, Vector<String> classes) {
    // we get the root classes and build up a set of
    // classes upon which they depend
    Set<String> dependencies = new HashSet<>();
    Set<File> containers = new HashSet<>();
    Set<String> toAnalyze = new HashSet<>(Collections.list(getRootClasses()));
    int count = 0;
    int maxCount = isClosureRequired() ? MAX_LOOPS : 2;
    while (!toAnalyze.isEmpty() && count++ < maxCount) {
        DependencyVisitor dependencyVisitor = new DependencyVisitor();
        for (String classname : toAnalyze) {
            dependencies.add(classname);
            try {
                File container = getClassContainer(classname);
                if (container == null) {
                    continue;
                }
                containers.add(container);
                ClassParser parser;
                if (container.getName().endsWith(".class")) {
                    parser = new ClassParser(container.getPath());
                } else {
                    parser = new ClassParser(container.getPath(), classname.replace('.', '/') + ".class");
                }
                JavaClass javaClass = parser.parse();
                DescendingVisitor traverser = new DescendingVisitor(javaClass, dependencyVisitor);
                traverser.visit();
            } catch (IOException ioe) {
            // ignore
            }
        }
        toAnalyze.clear();
        // now recover all the dependencies collected and add to the list.
        Enumeration<String> depsEnum = dependencyVisitor.getDependencies();
        while (depsEnum.hasMoreElements()) {
            String className = depsEnum.nextElement();
            if (!dependencies.contains(className)) {
                toAnalyze.add(className);
            }
        }
    }
    files.clear();
    files.addAll(containers);
    classes.clear();
    classes.addAll(dependencies);
}
Also used : JavaClass(org.apache.bcel.classfile.JavaClass) IOException(java.io.IOException) File(java.io.File) DescendingVisitor(org.apache.bcel.classfile.DescendingVisitor) HashSet(java.util.HashSet) ClassParser(org.apache.bcel.classfile.ClassParser)

Example 74 with JavaClass

use of org.apache.bcel.classfile.JavaClass in project qpid-broker-j by apache.

the class LDAPSSLSocketFactoryGenerator method createSubClassByteCode.

/**
 * 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);
    }
}
Also used : ConstantPoolGen(org.apache.bcel.generic.ConstantPoolGen) JavaClass(org.apache.bcel.classfile.JavaClass) ClassGen(org.apache.bcel.generic.ClassGen) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) InstructionFactory(org.apache.bcel.generic.InstructionFactory)

Example 75 with JavaClass

use of org.apache.bcel.classfile.JavaClass in project jop by jop-devel.

the class ReplaceNativeAndCPIdx method replace.

private Method replace(Method method) {
    MethodGen mg = new MethodGen(method, clazz.getClassName(), cpoolgen);
    InstructionList il = mg.getInstructionList();
    InstructionFinder f = new InstructionFinder(il);
    String methodId = method.getName() + method.getSignature();
    OldMethodInfo mi = getCli().getMethodInfo(methodId);
    // find invokes first and replace call to Native by
    // JOP native instructions.
    String invokeStr = "InvokeInstruction";
    for (Iterator i = f.search(invokeStr); i.hasNext(); ) {
        InstructionHandle[] match = (InstructionHandle[]) i.next();
        InstructionHandle first = match[0];
        InvokeInstruction ii = (InvokeInstruction) first.getInstruction();
        if (ii.getClassName(cpoolgen).equals(JOPizer.nativeClass)) {
            short opid = (short) JopInstr.getNative(ii.getMethodName(cpoolgen));
            if (opid == -1) {
                System.err.println(method.getName() + ": cannot locate " + ii.getMethodName(cpoolgen) + ". Replacing with NOP.");
                first.setInstruction(new NOP());
            } else {
                first.setInstruction(new NativeInstruction(opid, (short) 1));
                ((JOPizer) ai).outTxt.println("\t" + first.getPosition());
                // then we remove pc+2 and pc+1 from the MGCI info
                if (JOPizer.dumpMgci) {
                    il.setPositions();
                    int pc = first.getPosition();
                    // important: take the high one first
                    GCRTMethodInfo.removePC(pc + 2, mi);
                    GCRTMethodInfo.removePC(pc + 1, mi);
                }
            }
        }
        if (ii instanceof INVOKESPECIAL) {
            // not an initializer
            if (!ii.getMethodName(cpoolgen).equals("<init>")) {
                // check if this is a super invoke
                // TODO this is just a hack, use InvokeSite.isInvokeSuper() when this is ported to the new framework!
                boolean isSuper = false;
                String declaredType = ii.getClassName(cpoolgen);
                JopClassInfo cls = getCli();
                OldClassInfo superClass = cls.superClass;
                while (superClass != null) {
                    if (superClass.clazz.getClassName().equals(declaredType)) {
                        isSuper = true;
                        break;
                    }
                    if ("java.lang.Object".equals(superClass.clazz.getClassName())) {
                        break;
                    }
                    superClass = superClass.superClass;
                }
                if (isSuper) {
                    Integer idx = ii.getIndex();
                    int new_index = getCli().cpoolUsed.indexOf(idx) + 1;
                    first.setInstruction(new JOPSYS_INVOKESUPER((short) new_index));
                // System.err.println("invokesuper "+ii.getClassName(cpoolgen)+"."+ii.getMethodName(cpoolgen));
                }
            }
        }
    }
    if (JOPizer.CACHE_INVAL) {
        f = new InstructionFinder(il);
        // find volatile reads and insert cache invalidation bytecode
        String fieldInstr = "GETFIELD|GETSTATIC|PUTFIELD|PUTSTATIC";
        for (Iterator i = f.search(fieldInstr); i.hasNext(); ) {
            InstructionHandle[] match = (InstructionHandle[]) i.next();
            InstructionHandle ih = match[0];
            FieldInstruction fi = (FieldInstruction) ih.getInstruction();
            JavaClass jc = JOPizer.jz.cliMap.get(fi.getClassName(cpoolgen)).clazz;
            Field field = null;
            while (field == null) {
                Field[] fields = jc.getFields();
                for (int k = 0; k < fields.length; k++) {
                    if (fields[k].getName().equals(fi.getFieldName(cpoolgen))) {
                        field = fields[k];
                        break;
                    }
                }
                if (field == null) {
                    try {
                        jc = jc.getSuperClass();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                        throw new Error();
                    }
                }
            }
            if (field.isVolatile()) {
                if (field.getType().getSize() < 2) {
                    if (fi instanceof GETFIELD || fi instanceof GETSTATIC) {
                        ih.setInstruction(new InvalidateInstruction());
                        ih = il.append(ih, fi);
                    }
                } else {
                    // this only works because we do not throw a
                    // NullPointerException for monitorenter/-exit!
                    ih.setInstruction(new ACONST_NULL());
                    ih = il.append(ih, new MONITORENTER());
                    ih = il.append(ih, fi);
                    ih = il.append(ih, new ACONST_NULL());
                    ih = il.append(ih, new MONITOREXIT());
                }
            }
        }
    }
    f = new InstructionFinder(il);
    // find instructions that access the constant pool
    // and replace the index by the new value from ClassInfo
    String cpInstr = "CPInstruction";
    for (Iterator it = f.search(cpInstr); it.hasNext(); ) {
        InstructionHandle[] match = (InstructionHandle[]) it.next();
        InstructionHandle ih = match[0];
        CPInstruction cpii = (CPInstruction) ih.getInstruction();
        int index = cpii.getIndex();
        // we have to grab the information before we change
        // the CP index.
        FieldInstruction fi = null;
        Type ft = null;
        if (cpii instanceof FieldInstruction) {
            fi = (FieldInstruction) ih.getInstruction();
            ft = fi.getFieldType(cpoolgen);
        }
        Integer idx = new Integer(index);
        // pos is the new position in the reduced constant pool
        // idx is the position in the 'original' unresolved cpool
        int pos = getCli().cpoolUsed.indexOf(idx);
        int new_index = pos + 1;
        // and putfield and by address for getstatic and putstatic
        if (cpii instanceof GETFIELD || cpii instanceof PUTFIELD || cpii instanceof GETSTATIC || cpii instanceof PUTSTATIC) {
            // we use the offset instead of the CP index
            new_index = getFieldOffset(cp, index);
        } else {
            if (pos == -1) {
                System.out.println("Error: constant " + index + " " + cpoolgen.getConstant(index) + " not found");
                System.out.println("new cpool: " + getCli().cpoolUsed);
                System.out.println("original cpool: " + cpoolgen);
                System.exit(-1);
            }
        }
        // set new index, position starts at
        // 1 as cp points to the length of the pool
        cpii.setIndex(new_index);
        if (cpii instanceof FieldInstruction) {
            boolean isRef = ft instanceof ReferenceType;
            boolean isLong = ft == BasicType.LONG || ft == BasicType.DOUBLE;
            if (fi instanceof GETSTATIC) {
                if (isRef) {
                    ih.setInstruction(new GETSTATIC_REF((short) new_index));
                } else if (isLong) {
                    ih.setInstruction(new GETSTATIC_LONG((short) new_index));
                }
            } else if (fi instanceof PUTSTATIC) {
                if (isRef) {
                    if (!com.jopdesign.build.JOPizer.USE_RTTM) {
                        ih.setInstruction(new PUTSTATIC_REF((short) new_index));
                    }
                } else if (isLong) {
                    ih.setInstruction(new PUTSTATIC_LONG((short) new_index));
                }
            } else if (fi instanceof GETFIELD) {
                if (isRef) {
                    ih.setInstruction(new GETFIELD_REF((short) new_index));
                } else if (isLong) {
                    ih.setInstruction(new GETFIELD_LONG((short) new_index));
                }
            } else if (fi instanceof PUTFIELD) {
                if (isRef) {
                    if (!com.jopdesign.build.JOPizer.USE_RTTM) {
                        ih.setInstruction(new PUTFIELD_REF((short) new_index));
                    }
                } else if (isLong) {
                    ih.setInstruction(new PUTFIELD_LONG((short) new_index));
                }
            }
        }
    }
    Method m = mg.getMethod();
    il.dispose();
    return m;
}
Also used : InstructionList(org.apache.bcel.generic.InstructionList) InstructionFinder(org.apache.bcel.util.InstructionFinder) MONITORENTER(org.apache.bcel.generic.MONITORENTER) MethodGen(org.apache.bcel.generic.MethodGen) InstructionHandle(org.apache.bcel.generic.InstructionHandle) ReferenceType(org.apache.bcel.generic.ReferenceType) PUTSTATIC(org.apache.bcel.generic.PUTSTATIC) Field(org.apache.bcel.classfile.Field) CPInstruction(org.apache.bcel.generic.CPInstruction) Iterator(java.util.Iterator) MONITOREXIT(org.apache.bcel.generic.MONITOREXIT) ACONST_NULL(org.apache.bcel.generic.ACONST_NULL) PUTFIELD(org.apache.bcel.generic.PUTFIELD) Method(org.apache.bcel.classfile.Method) INVOKESPECIAL(org.apache.bcel.generic.INVOKESPECIAL) NOP(org.apache.bcel.generic.NOP) InvokeInstruction(org.apache.bcel.generic.InvokeInstruction) GETFIELD(org.apache.bcel.generic.GETFIELD) ReferenceType(org.apache.bcel.generic.ReferenceType) Type(org.apache.bcel.generic.Type) BasicType(org.apache.bcel.generic.BasicType) ConstantNameAndType(org.apache.bcel.classfile.ConstantNameAndType) JavaClass(org.apache.bcel.classfile.JavaClass) FieldInstruction(org.apache.bcel.generic.FieldInstruction) GETSTATIC(org.apache.bcel.generic.GETSTATIC)

Aggregations

JavaClass (org.apache.bcel.classfile.JavaClass)144 OpcodeStack (edu.umd.cs.findbugs.OpcodeStack)45 BugInstance (edu.umd.cs.findbugs.BugInstance)43 Method (org.apache.bcel.classfile.Method)28 ToString (com.mebigfatguy.fbcontrib.utils.ToString)27 Field (org.apache.bcel.classfile.Field)17 HashSet (java.util.HashSet)14 HashMap (java.util.HashMap)11 ClassParser (org.apache.bcel.classfile.ClassParser)10 ArrayList (java.util.ArrayList)9 IOException (java.io.IOException)8 ExceptionTable (org.apache.bcel.classfile.ExceptionTable)8 XField (edu.umd.cs.findbugs.ba.XField)7 Nullable (javax.annotation.Nullable)7 AnnotationEntry (org.apache.bcel.classfile.AnnotationEntry)7 Type (org.apache.bcel.generic.Type)7 Iterator (java.util.Iterator)6 List (java.util.List)6 Map (java.util.Map)6 Set (java.util.Set)6