org.apache.bcel.classfile.ClassParser Java Examples

The following examples show how to use org.apache.bcel.classfile.ClassParser. 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: ClassLoader.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
/**
 * Override this method to create you own classes on the fly. The
 * name contains the special token $$BCEL$$. Everything before that
 * token is considered to be a package name. You can encode your own
 * arguments into the subsequent string. You must ensure however not
 * to use any "illegal" characters, i.e., characters that may not
 * appear in a Java class name too
 * <p>
 * The default implementation interprets the string as a encoded compressed
 * Java class, unpacks and decodes it with the Utility.decode() method, and
 * parses the resulting byte array and returns the resulting JavaClass object.
 * </p>
 *
 * @param class_name compressed byte code with "$$BCEL$$" in it
 */
protected JavaClass createClass( final String class_name ) {
    final int index = class_name.indexOf(BCEL_TOKEN);
    final String real_name = class_name.substring(index + BCEL_TOKEN.length());
    JavaClass clazz = null;
    try {
        final byte[] bytes = Utility.decode(real_name, true);
        final ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes), "foo");
        clazz = parser.parse();
    } catch (final IOException e) {
        e.printStackTrace();
        return null;
    }
    // Adapt the class name to the passed value
    final ConstantPool cp = clazz.getConstantPool();
    final ConstantClass cl = (ConstantClass) cp.getConstant(clazz.getClassNameIndex(),
            Const.CONSTANT_Class);
    final ConstantUtf8 name = (ConstantUtf8) cp.getConstant(cl.getNameIndex(),
            Const.CONSTANT_Utf8);
    name.setBytes(class_name.replace('.', '/'));
    return clazz;
}
 
Example #2
Source File: helloify.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] argv) throws Exception {
    for (final String arg : argv) {
        if (arg.endsWith(".class")) {
            final JavaClass java_class = new ClassParser(arg).parse();
            final ConstantPool constants = java_class.getConstantPool();
            final String file_name = arg.substring(0, arg.length() - 6) + "_hello.class";
            cp = new ConstantPoolGen(constants);

            helloifyClassName(java_class);

            out = cp.addFieldref("java.lang.System", "out", "Ljava/io/PrintStream;");
            println = cp.addMethodref("java.io.PrintStream", "println", "(Ljava/lang/String;)V");
            // Patch all methods.
            final Method[] methods = java_class.getMethods();

            for (int j = 0; j < methods.length; j++) {
                methods[j] = helloifyMethod(methods[j]);
            }

            // Finally dump it back to a file.
            java_class.setConstantPool(cp.getFinalConstantPool());
            java_class.dump(file_name);
        }
    }
}
 
Example #3
Source File: Storage.java    From j-j-jvm with Apache License 2.0 6 votes vote down vote up
public void addClass(final InputStream classStream, final boolean doNotify) throws IOException {
  final JavaClass jclazz = new ClassParser(classStream, null).parse();

  String packageName = jclazz.getPackageName();
  if (packageName == null || packageName.length() == 0) {
    packageName = "<default>";
  }

  PackageItem packageItem = getPackageForName(packageName);
  if (packageItem == null) {
    packageItem = addPackage(packageName);
  }

  packageItem.addClass(new ClassItem(packageItem, jclazz));

  if (doNotify) {
    for (final TreeModelListener l : this.treeModelListeners) {
      l.treeStructureChanged(new TreeModelEvent(this, new TreePath(this)));
    }
  }
}
 
Example #4
Source File: RootBuilder.java    From android-classyshark with Apache License 2.0 6 votes vote down vote up
private ClassNode fillFromJar(File file) {

        ClassNode rootNode = new ClassNode(file.getName());
        try {
            JarFile theJar = new JarFile(file);
            Enumeration<? extends JarEntry> en = theJar.entries();

            while (en.hasMoreElements()) {
                JarEntry entry = en.nextElement();
                if (entry.getName().endsWith(".class")) {
                    ClassParser cp = new ClassParser(
                            theJar.getInputStream(entry), entry.getName());
                    JavaClass jc = cp.parse();
                    ClassInfo classInfo = new ClassInfo(jc.getClassName(),
                            jc.getMethods().length);
                    rootNode.add(classInfo);
                }
            }
        } catch (IOException e) {
            System.err.println("Error reading file: " + file + ". " + e.getMessage());
            e.printStackTrace(System.err);
        }

        return rootNode;
    }
 
Example #5
Source File: id.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] argv) throws Exception {
    JavaClass clazz;

    if ((clazz = Repository.lookupClass(argv[0])) == null) {
        clazz = new ClassParser(argv[0]).parse(); // May throw IOException
    }

    final ClassGen cg = new ClassGen(clazz);

    for (final Method method : clazz.getMethods()) {
        final MethodGen mg = new MethodGen(method, cg.getClassName(), cg.getConstantPool());
        cg.replaceMethod(method, mg.getMethod());
    }

    for (final Field field : clazz.getFields()) {
        final FieldGen fg = new FieldGen(field, cg.getConstantPool());
        cg.replaceField(field, fg.getField());
    }

    cg.getJavaClass().dump(clazz.getClassName() + ".clazz");
}
 
Example #6
Source File: patchclass.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] argv) throws Exception {
    final String[] file_name = new String[argv.length];
    int files = 0;

    if (argv.length < 3) {
        System.err.println("Usage: patch <oldstring> <newstring> file1.class ...");
        System.exit(-1);
    }

    for (int i = 2; i < argv.length; i++) {
        file_name[files++] = argv[i];
    }

    for (int i = 0; i < files; i++) {
        final ClassParser parser = new ClassParser(file_name[i]);
        final JavaClass java_class = parser.parse();

        patchIt(argv[0], argv[1], java_class.getConstantPool().getConstantPool());

        // Dump the changed class to a new file
        java_class.dump("_" + file_name[i]);
        System.out.println("Results saved in: _" + file_name[i]);
    }
}
 
Example #7
Source File: TransitiveHull.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] argv) {
    JavaClass java_class;

    try {
        if (argv.length == 0) {
            System.err.println("transitive: No input files specified");
        } else {
            if ((java_class = Repository.lookupClass(argv[0])) == null) {
                java_class = new ClassParser(argv[0]).parse();
            }

            final TransitiveHull hull = new TransitiveHull(java_class);

            hull.start();
            System.out.println(Arrays.asList(hull.getClassNames()));
        }
    } catch (final Exception e) {
        e.printStackTrace();
    }
}
 
Example #8
Source File: ClassLoaderRepository.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
/**
 * Lookup a JavaClass object from the Class Name provided.
 */
@Override
public JavaClass loadClass(final String className) throws ClassNotFoundException {
    final String classFile = className.replace('.', '/');
    JavaClass RC = findClass(className);
    if (RC != null) {
        return RC;
    }
    try (InputStream is = loader.getResourceAsStream(classFile + ".class")) {
        if (is == null) {
            throw new ClassNotFoundException(className + " not found.");
        }
        final ClassParser parser = new ClassParser(is, className);
        RC = parser.parse();
        storeClass(RC);
        return RC;
    } catch (final IOException e) {
        throw new ClassNotFoundException(className + " not found: " + e, e);
    }
}
 
Example #9
Source File: JdkGenericDumpTestCase.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
private void testJar(final File file) throws Exception {
    System.out.println(file);
    try (JarFile jar = new JarFile(file)) {
        final Enumeration<JarEntry> en = jar.entries();
        while (en.hasMoreElements()) {
            final JarEntry jarEntry = en.nextElement();
            final String name = jarEntry.getName();
            if (name.endsWith(".class")) {
                // System.out.println("- " + name);
                try (InputStream inputStream = jar.getInputStream(jarEntry)) {
                    final ClassParser classParser = new ClassParser(inputStream, name);
                    final JavaClass javaClass = classParser.parse();
                    for (final Method method : javaClass.getMethods()) {
                        compare(name, method);
                    }
                }
            }
        }
    }
}
 
Example #10
Source File: RejarClassesForAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private boolean embeddedNameMismatch(ZipFile zipInputFile, ZipEntry ze) throws IOException {
    InputStream zipIn = zipInputFile.getInputStream(ze);
    String name = ze.getName();
    JavaClass j = new ClassParser(zipIn, name).parse();
    zipIn.close();
    String className = j.getClassName();
    String computedFileName = ClassName.toSlashedClassName(className) + ".class";
    if (name.charAt(0) == '1') {
        System.out.println(name);
        System.out.println("  " + className);
    }
    if (computedFileName.equals(name)) {
        return false;
    }
    System.out.println("In " + name + " found " + className);
    return true;
}
 
Example #11
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 #12
Source File: BCELifier.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
static JavaClass getJavaClass(final String name) throws ClassNotFoundException, IOException {
    JavaClass java_class;
    if ((java_class = Repository.lookupClass(name)) == null) {
        java_class = new ClassParser(name).parse(); // May throw IOException
    }
    return java_class;
}
 
Example #13
Source File: ParserTest.java    From JQF with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Fuzz
public void testWithInputStream(InputStream inputStream) throws IOException {
    JavaClass clazz;
    try {
        clazz = new ClassParser(inputStream, "Hello.class").parse();
    } catch (ClassFormatException e) {
        // ClassFormatException thrown by the parser is just invalid input
        Assume.assumeNoException(e);
        return;
    }

    // Any non-IOException thrown here should be marked a failure
    // (including ClassFormatException)
    verifyJavaClass(clazz);
}
 
Example #14
Source File: JdkGenericDumpTestCase.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
private void find(final Path path) throws IOException {
    final Path name = path.getFileName();
    if (name != null && matcher.matches(name)) {
        try (final InputStream inputStream = Files.newInputStream(path)) {
            final ClassParser classParser = new ClassParser(inputStream, name.toAbsolutePath().toString());
            final JavaClass javaClass = classParser.parse();
            Assert.assertNotNull(javaClass);
        }

    }
}
 
Example #15
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 #16
Source File: BCELBenchmark.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
@Benchmark
public void parser(Blackhole bh) throws IOException {
    JarFile jar = getJarFile();

    for (JarEntry entry : getClasses(jar)) {
        byte[] bytes = IOUtils.toByteArray(jar.getInputStream(entry));

        JavaClass clazz = new ClassParser(new ByteArrayInputStream(bytes), entry.getName()).parse();
        bh.consume(clazz);
    }

    jar.close();
}
 
Example #17
Source File: BCELBenchmark.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
@Benchmark
public void generator(Blackhole bh) throws IOException {
    JarFile jar = getJarFile();

    for (JarEntry entry : getClasses(jar)) {
        byte[] bytes = IOUtils.toByteArray(jar.getInputStream(entry));

        JavaClass clazz = new ClassParser(new ByteArrayInputStream(bytes), entry.getName()).parse();

        ClassGen cg = new ClassGen(clazz);

        for (Method m : cg.getMethods()) {
            MethodGen mg = new MethodGen(m, cg.getClassName(), cg.getConstantPool());
            InstructionList il = mg.getInstructionList();

            if (il != null) {
                mg.getInstructionList().setPositions();
                mg.setMaxLocals();
                mg.setMaxStack();
            }
            cg.replaceMethod(m, mg.getMethod());
        }

        bh.consume(cg.getJavaClass().getBytes());
    }

    jar.close();
}
 
Example #18
Source File: Class2HTMLTestCase.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
public void testConvertJavaUtil() throws Exception {
    final File outputDir = new File("target/test-output/html");
    if (!outputDir.mkdirs()) { // either was not created or already existed
        Assert.assertTrue(outputDir.isDirectory()); // fail if missing
    }

    try (FileInputStream file = new FileInputStream("target/test-classes/Java8Example.class")) {

        final ClassParser parser = new ClassParser(file, "Java8Example.class");

        new Class2HTML(parser.parse(), outputDir.getAbsolutePath() + "/");
    }
}
 
Example #19
Source File: JasminVisitor.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] argv) throws Exception {
    JavaClass java_class;

    if (argv.length == 0) {
        System.err.println("disassemble: No input files specified");
        return;
    }

    for (final String arg : argv) {
        if ((java_class = Repository.lookupClass(arg)) == null) {
            java_class = new ClassParser(arg).parse();
        }

        String class_name = java_class.getClassName();
        final int index = class_name.lastIndexOf('.');
        final String path = class_name.substring(0, index + 1).replace('.', File.separatorChar);
        class_name = class_name.substring(index + 1);

        if (!path.equals("")) {
            final File f = new File(path);
            f.mkdirs();
        }

        final String name = path + class_name + ".j";
        final FileOutputStream out = new FileOutputStream(name);
        new JasminVisitor(java_class, out).disassemble();
        System.out.println("File dumped to: " + name);
    }
}
 
Example #20
Source File: BCELPerfTest.java    From annotation-tools with MIT License 5 votes vote down vote up
byte[] nullAdaptClass(final InputStream is, final String name)
        throws Exception
{
    JavaClass jc = new ClassParser(is, name + ".class").parse();
    ClassGen cg = new ClassGen(jc);
    ConstantPoolGen cp = cg.getConstantPool();
    Method[] ms = cg.getMethods();
    for (int j = 0; j < ms.length; ++j) {
        MethodGen mg = new MethodGen(ms[j], cg.getClassName(), cp);
        boolean lv = ms[j].getLocalVariableTable() == null;
        boolean ln = ms[j].getLineNumberTable() == null;
        if (lv) {
            mg.removeLocalVariables();
        }
        if (ln) {
            mg.removeLineNumbers();
        }
        mg.stripAttributes(skipDebug);
        InstructionList il = mg.getInstructionList();
        if (il != null) {
            InstructionHandle ih = il.getStart();
            while (ih != null) {
                ih = ih.getNext();
            }
            if (compute) {
                mg.setMaxStack();
                mg.setMaxLocals();
            }
        }
        cg.replaceMethod(ms[j], mg.getMethod());
    }
    return cg.getJavaClass().getBytes();
}
 
Example #21
Source File: BCELPerfTest.java    From annotation-tools with MIT License 5 votes vote down vote up
byte[] nullAdaptClass(final InputStream is, final String name)
        throws Exception
{
    JavaClass jc = new ClassParser(is, name + ".class").parse();
    ClassGen cg = new ClassGen(jc);
    ConstantPoolGen cp = cg.getConstantPool();
    Method[] ms = cg.getMethods();
    for (int j = 0; j < ms.length; ++j) {
        MethodGen mg = new MethodGen(ms[j], cg.getClassName(), cp);
        boolean lv = ms[j].getLocalVariableTable() == null;
        boolean ln = ms[j].getLineNumberTable() == null;
        if (lv) {
            mg.removeLocalVariables();
        }
        if (ln) {
            mg.removeLineNumbers();
        }
        mg.stripAttributes(skipDebug);
        InstructionList il = mg.getInstructionList();
        if (il != null) {
            InstructionHandle ih = il.getStart();
            while (ih != null) {
                ih = ih.getNext();
            }
            if (compute) {
                mg.setMaxStack();
                mg.setMaxLocals();
            }
        }
        cg.replaceMethod(ms[j], mg.getMethod());
    }
    return cg.getJavaClass().getBytes();
}
 
Example #22
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 #23
Source File: URLClassPath.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Look up a class from the classpath.
 *
 * @param className
 *            name of class to look up
 * @return the JavaClass object for the class
 * @throws ClassNotFoundException
 *             if the class couldn't be found
 */
public JavaClass lookupClass(String className) throws ClassNotFoundException {
    if (classesThatCantBeFound.contains(className)) {
        throw new ClassNotFoundException("Error while looking for class " + className + ": class not found");
    }
    String resourceName = className.replace('.', '/') + ".class";
    InputStream in = null;
    boolean parsedClass = false;

    try {

        in = getInputStreamForResource(resourceName);
        if (in == null) {
            classesThatCantBeFound.add(className);
            throw new ClassNotFoundException("Error while looking for class " + className + ": class not found");
        }

        ClassParser classParser = new ClassParser(in, resourceName);
        JavaClass javaClass = classParser.parse();
        parsedClass = true;

        return javaClass;
    } catch (IOException e) {
        classesThatCantBeFound.add(className);
        throw new ClassNotFoundException("IOException while looking for class " + className, e);
    } finally {
        if (in != null && !parsedClass) {
            try {
                in.close();
            } catch (IOException ignore) {
                // Ignore
            }
        }
    }
}
 
Example #24
Source File: PrintClass.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static void printClass(ClassParser parser) throws IOException {
    JavaClass java_class;
    java_class = parser.parse();

    if (superClasses) {
        try {
            while (java_class != null) {
                System.out.print(java_class.getClassName() + "  ");
                java_class = java_class.getSuperClass();
            }
        } catch (ClassNotFoundException e) {
            System.out.println(e.getMessage());

        }
        System.out.println();
        return;
    }
    if (constants || code) {
        System.out.println(java_class); // Dump the contents
    }
    if (constants) {
        System.out.println(java_class.getConstantPool());
    }

    if (code) {
        printCode(java_class.getMethods());
    }
}
 
Example #25
Source File: BCELPerfTest.java    From annotation-tools with MIT License 4 votes vote down vote up
byte[] counterAdaptClass(final InputStream is, final String name)
        throws Exception
{
    JavaClass jc = new ClassParser(is, name + ".class").parse();
    ClassGen cg = new ClassGen(jc);
    ConstantPoolGen cp = cg.getConstantPool();
    if (!cg.isInterface()) {
        FieldGen fg = new FieldGen(ACC_PUBLIC,
                Type.getType("I"),
                "_counter",
                cp);
        cg.addField(fg.getField());
    }
    Method[] ms = cg.getMethods();
    for (int j = 0; j < ms.length; ++j) {
        MethodGen mg = new MethodGen(ms[j], cg.getClassName(), cp);
        if (!mg.getName().equals("<init>") && !mg.isStatic()
                && !mg.isAbstract() && !mg.isNative())
        {
            if (mg.getInstructionList() != null) {
                InstructionList il = new InstructionList();
                il.append(new ALOAD(0));
                il.append(new ALOAD(0));
                il.append(new GETFIELD(cp.addFieldref(name, "_counter", "I")));
                il.append(new ICONST(1));
                il.append(new IADD());
                il.append(new PUTFIELD(cp.addFieldref(name, "_counter", "I")));
                mg.getInstructionList().insert(il);
                mg.setMaxStack(Math.max(mg.getMaxStack(), 2));
                boolean lv = ms[j].getLocalVariableTable() == null;
                boolean ln = ms[j].getLineNumberTable() == null;
                if (lv) {
                    mg.removeLocalVariables();
                }
                if (ln) {
                    mg.removeLineNumbers();
                }
                cg.replaceMethod(ms[j], mg.getMethod());
            }
        }
    }
    return cg.getJavaClass().getBytes();
}
 
Example #26
Source File: BCELPerfTest.java    From annotation-tools with MIT License 4 votes vote down vote up
byte[] counterAdaptClass(final InputStream is, final String name)
        throws Exception
{
    JavaClass jc = new ClassParser(is, name + ".class").parse();
    ClassGen cg = new ClassGen(jc);
    ConstantPoolGen cp = cg.getConstantPool();
    if (!cg.isInterface()) {
        FieldGen fg = new FieldGen(ACC_PUBLIC,
                Type.getType("I"),
                "_counter",
                cp);
        cg.addField(fg.getField());
    }
    Method[] ms = cg.getMethods();
    for (int j = 0; j < ms.length; ++j) {
        MethodGen mg = new MethodGen(ms[j], cg.getClassName(), cp);
        if (!mg.getName().equals("<init>") && !mg.isStatic()
                && !mg.isAbstract() && !mg.isNative())
        {
            if (mg.getInstructionList() != null) {
                InstructionList il = new InstructionList();
                il.append(new ALOAD(0));
                il.append(new ALOAD(0));
                il.append(new GETFIELD(cp.addFieldref(name, "_counter", "I")));
                il.append(new ICONST(1));
                il.append(new IADD());
                il.append(new PUTFIELD(cp.addFieldref(name, "_counter", "I")));
                mg.getInstructionList().insert(il);
                mg.setMaxStack(Math.max(mg.getMaxStack(), 2));
                boolean lv = ms[j].getLocalVariableTable() == null;
                boolean ln = ms[j].getLineNumberTable() == null;
                if (lv) {
                    mg.removeLocalVariables();
                }
                if (ln) {
                    mg.removeLineNumbers();
                }
                cg.replaceMethod(ms[j], mg.getMethod());
            }
        }
    }
    return cg.getJavaClass().getBytes();
}
 
Example #27
Source File: NativeJavahMojo.java    From maven-native with MIT License 4 votes vote down vote up
/**
 * Get applicable class names to be "javahed"
 */

private void discoverAdditionalJNIClassName()
    throws MojoExecutionException
{
    if ( !this.javahSearchJNIFromDependencies )
    {
        return;
    }

    // scan the immediate dependency list for jni classes

    List<Artifact> artifacts = this.getJavahArtifacts();

    for ( Iterator<Artifact> iter = artifacts.iterator(); iter.hasNext(); )
    {
        Artifact artifact = iter.next();

        this.getLog().info( "Parsing " + artifact.getFile() + " for native classes." );

        try
        {
            ZipFile zipFile = new ZipFile( artifact.getFile() );
            Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();

            while ( zipEntries.hasMoreElements() )
            {
                ZipEntry zipEntry = zipEntries.nextElement();

                if ( "class".equals( FileUtils.extension( zipEntry.getName() ) ) )
                {
                    ClassParser parser = new ClassParser( artifact.getFile().getPath(), zipEntry.getName() );

                    JavaClass clazz = parser.parse();

                    Method[] methods = clazz.getMethods();

                    for ( int j = 0; j < methods.length; ++j )
                    {
                        if ( methods[j].isNative() )
                        {
                            javahClassNames.add( clazz.getClassName() );

                            this.getLog().info( "Found native class: " + clazz.getClassName() );

                            break;
                        }
                    }
                }
            } // endwhile

            // not full proof
            zipFile.close();
        }
        catch ( IOException ioe )
        {
            throw new MojoExecutionException( "Error searching for native class in " + artifact.getFile(), ioe );
        }
    }

}
 
Example #28
Source File: PrintClass.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static void main(String argv[]) throws IOException {
    String[] file_name = new String[argv.length];
    int files = 0;
    String zip_file = null;

    /*
     * Parse command line arguments.
     */
    for (int i = 0; i < argv.length; i++) {
        if (argv[i].charAt(0) == '-') { // command line switch
            if ("-constants".equals(argv[i])) {
                constants = true;
            } else if ("-code".equals(argv[i])) {
                code = true;
            } else if ("-super".equals(argv[i])) {
                superClasses = true;
            } else if ("-zip".equals(argv[i])) {
                zip_file = argv[++i];
            }
        } else if (argv[i].endsWith(".zip") || argv[i].endsWith(".jar")) {
            zip_file = argv[i];
        } else { // add file name to list
            file_name[files++] = argv[i];
        }
    }

    if (!constants) {
        code = true;
    }
    if (files == 0 && zip_file == null) {
        System.err.println("list: No input files specified");
    } else if (zip_file != null) {
        for (int i = 0; i < files; i++) {
            file_name[i] = file_name[i].replace('.', '/');
        }
        try (ZipFile z = new ZipFile(zip_file)) {
            TreeSet<ZipEntry> zipEntries = new TreeSet<>(new ZipEntryComparator());
            for (Enumeration<? extends ZipEntry> e = z.entries(); e.hasMoreElements();) {
                zipEntries.add(e.nextElement());
            }

            for (ZipEntry ze : zipEntries) {
                String name = ze.getName();
                if (!name.endsWith(".class")) {
                    continue;
                }
                checkMatch: if (files > 0) {
                    for (int i = 0; i < files; i++) {
                        if (name.indexOf(file_name[i]) >= 0) {
                            break checkMatch;
                        }
                    }
                    continue;
                }
                printClass(new ClassParser(z.getInputStream(ze), name));

            }
        }
    } else {
        for (int i = 0; i < files; i++) {
            if (file_name[i].endsWith(".class")) {
                printClass(new ClassParser(file_name[i]));
            }
        }
    }
}
 
Example #29
Source File: PerformanceTest.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
private static void test(final File lib) throws IOException {
    final NanoTimer total = new NanoTimer();
    final NanoTimer parseTime = new NanoTimer();
    final NanoTimer cgenTime = new NanoTimer();
    final NanoTimer mgenTime = new NanoTimer();
    final NanoTimer mserTime = new NanoTimer();
    final NanoTimer serTime = new NanoTimer();

    System.out.println("parsing " + lib);

    total.start();
    try (JarFile jar = new JarFile(lib)) {
        final Enumeration<?> en = jar.entries();

        while (en.hasMoreElements()) {
            final JarEntry e = (JarEntry) en.nextElement();
            if (e.getName().endsWith(".class")) {
                byte[] bytes;
                try (InputStream in = jar.getInputStream(e)) {
                    bytes = read(in);
                }

                parseTime.start();
                final JavaClass clazz = new ClassParser(new ByteArrayInputStream(bytes), e.getName()).parse();
                parseTime.stop();

                cgenTime.start();
                final ClassGen cg = new ClassGen(clazz);
                cgenTime.stop();

                final Method[] methods = cg.getMethods();
                for (final Method m : methods) {
                    mgenTime.start();
                    final MethodGen mg = new MethodGen(m, cg.getClassName(), cg.getConstantPool());
                    final InstructionList il = mg.getInstructionList();
                    mgenTime.stop();

                    mserTime.start();
                    if (il != null) {
                        mg.getInstructionList().setPositions();
                        mg.setMaxLocals();
                        mg.setMaxStack();
                    }
                    cg.replaceMethod(m, mg.getMethod());
                    mserTime.stop();
                }

                serTime.start();
                cg.getJavaClass().getBytes();
                serTime.stop();
            }
        }
    }
    total.stop();
    if (REPORT) {
        System.out.println("ClassParser.parse: " + parseTime);
        System.out.println("ClassGen.init: " + cgenTime);
        System.out.println("MethodGen.init: " + mgenTime);
        System.out.println("MethodGen.getMethod: " + mserTime);
        System.out.println("ClassGen.getJavaClass.getBytes: " + serTime);
        System.out.println("Total: " + total);
        System.out.println();
    }
}
 
Example #30
Source File: ClassFilePreDecompilationScan.java    From windup with Eclipse Public License 1.0 4 votes vote down vote up
private void addClassFileMetadata(GraphRewrite event, EvaluationContext context, JavaClassFileModel javaClassFileModel)
{
    try (FileInputStream fis = new FileInputStream(javaClassFileModel.getFilePath()))
    {
        final ClassParser parser = new ClassParser(fis, javaClassFileModel.getFilePath());
        final JavaClass bcelJavaClass = parser.parse();
        final String packageName = bcelJavaClass.getPackageName();

        final String qualifiedName = bcelJavaClass.getClassName();

        final JavaClassService javaClassService = new JavaClassService(event.getGraphContext());
        final JavaClassModel javaClassModel = javaClassService.create(qualifiedName);
        int majorVersion = bcelJavaClass.getMajor();
        int minorVersion = bcelJavaClass.getMinor();

        String simpleName = qualifiedName;
        if (packageName != null && !packageName.isEmpty() && simpleName != null)
        {
            simpleName = StringUtils.substringAfterLast(simpleName, ".");
        }

        javaClassFileModel.setMajorVersion(majorVersion);
        javaClassFileModel.setMinorVersion(minorVersion);
        javaClassFileModel.setPackageName(packageName);

        javaClassModel.setSimpleName(simpleName);
        javaClassModel.setPackageName(packageName);
        javaClassModel.setQualifiedName(qualifiedName);
        javaClassModel.setClassFile(javaClassFileModel);
        javaClassModel.setPublic(bcelJavaClass.isPublic());
        javaClassModel.setInterface(bcelJavaClass.isInterface());

        final String[] interfaceNames = bcelJavaClass.getInterfaceNames();
        if (interfaceNames != null)
        {
            for (final String interfaceName : interfaceNames)
            {
                JavaClassModel interfaceModel = javaClassService.getOrCreatePhantom(interfaceName);
                javaClassService.addInterface(javaClassModel, interfaceModel);
            }
        }

        String superclassName = bcelJavaClass.getSuperclassName();
        if (!bcelJavaClass.isInterface() && !StringUtils.isBlank(superclassName))
            javaClassModel.setExtends(javaClassService.getOrCreatePhantom(superclassName));

        javaClassFileModel.setJavaClass(javaClassModel);
    }
    catch (Exception ex)
    {
        String nl = ex.getMessage() != null ? Util.NL + "\t" : " ";
        final String message = "BCEL was unable to parse class file '" + javaClassFileModel.getFilePath() + "':" + nl + ex.toString();
        LOG.log(Level.WARNING, message);
        ClassificationService classificationService = new ClassificationService(event.getGraphContext());
        classificationService.attachClassification(event, context, javaClassFileModel, UNPARSEABLE_CLASS_CLASSIFICATION, UNPARSEABLE_CLASS_DESCRIPTION);
        javaClassFileModel.setParseError(message);
        javaClassFileModel.setSkipDecompilation(true);
    }
}