Example usage for org.objectweb.asm.tree ClassNode ClassNode

List of usage examples for org.objectweb.asm.tree ClassNode ClassNode

Introduction

In this page you can find the example usage for org.objectweb.asm.tree ClassNode ClassNode.

Prototype

public ClassNode() 

Source Link

Document

Constructs a new ClassNode .

Usage

From source file:blockphysics.asm.BPTransformer.java

License:Open Source License

private byte[] transformBlockRedstoneLight(byte[] bytes) {
    /*try/*from w w  w.  j  a va 2  s.c o m*/
    {
        FileOutputStream fos = new FileOutputStream("d:/BlockRedstoneLight.orig.class");
        fos.write(bytes);
      fos.close();
    } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
    }*/

    System.out.print("[BlockPhysics] Patching BlockRedstoneLight.class ......");
    boolean ok = false;

    ClassNode classNode = new ClassNode();
    ClassReader classReader = new ClassReader(bytes);
    classReader.accept(classNode, 0);

    MethodNode m;
    Iterator<MethodNode> methods = classNode.methods.iterator();
    while (methods.hasNext()) {
        m = methods.next();

        if (m.name.equals("a") && m.desc.equals("(Labv;IIII)V")) {
            InsnList toInject = new InsnList();
            toInject.add(new VarInsnNode(ALOAD, 1));
            toInject.add(new VarInsnNode(ILOAD, 2));
            toInject.add(new VarInsnNode(ILOAD, 3));
            toInject.add(new VarInsnNode(ILOAD, 4));
            toInject.add(new VarInsnNode(ALOAD, 0));
            toInject.add(new FieldInsnNode(GETFIELD, "aqa", "cF", "I"));
            toInject.add(new MethodInsnNode(INVOKESTATIC, "blockphysics/BlockPhysics", "onNeighborBlockChange",
                    "(Labv;IIII)V"));

            for (int index = m.instructions.size() - 1; index >= 0; index--) {
                if (m.instructions.get(index).getOpcode() == RETURN) {
                    m.instructions.insertBefore(m.instructions.get(index), toInject);
                    ok = true;
                    break;
                }
            }
        }
    }

    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    classNode.accept(cw);

    if (ok)
        System.out.println("OK");
    else
        System.out.println("Failed." + ok);

    /*try
    {
       FileOutputStream fos = new FileOutputStream("d:/BlockRedstoneLight.class");
       fos.write(cw.toByteArray());
     fos.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }*/

    return cw.toByteArray();
}

From source file:blockphysics.asm.BPTransformer.java

License:Open Source License

private byte[] transformBlockTNT(byte[] bytes) {
    /*try//from   w  ww.  j  a  v  a 2 s.  co m
    {
        FileOutputStream fos = new FileOutputStream("d:/BlockTNT.orig.class");
        fos.write(bytes);
      fos.close();
    } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
    }*/

    System.out.print("[BlockPhysics] Patching BlockTNT.class ................");
    boolean ok = false;
    boolean ok2 = false;

    ClassNode classNode = new ClassNode();
    ClassReader classReader = new ClassReader(bytes);
    classReader.accept(classNode, 0);

    MethodNode m;
    Iterator<MethodNode> methods = classNode.methods.iterator();
    while (methods.hasNext()) {
        m = methods.next();

        if (m.name.equals("a") && m.desc.equals("(Labv;IIII)V")) {
            InsnList toInject = new InsnList();
            toInject.add(new VarInsnNode(ALOAD, 1));
            toInject.add(new VarInsnNode(ILOAD, 2));
            toInject.add(new VarInsnNode(ILOAD, 3));
            toInject.add(new VarInsnNode(ILOAD, 4));
            toInject.add(new VarInsnNode(ALOAD, 0));
            toInject.add(new FieldInsnNode(GETFIELD, "arb", "cF", "I"));
            toInject.add(new MethodInsnNode(INVOKESTATIC, "blockphysics/BlockPhysics", "onNeighborBlockChange",
                    "(Labv;IIII)V"));

            for (int index = m.instructions.size() - 1; index >= 0; index--) {
                if (m.instructions.get(index).getOpcode() == RETURN) {
                    m.instructions.insertBefore(m.instructions.get(index), toInject);
                    ok = true;
                    break;
                }
            }
        } else if (m.name.equals("g") && m.desc.equals("(Labv;IIII)V")) {
            InsnList toInject = new InsnList();
            toInject.add(new VarInsnNode(ALOAD, 1));
            toInject.add(new VarInsnNode(ILOAD, 2));
            toInject.add(new VarInsnNode(ILOAD, 3));
            toInject.add(new VarInsnNode(ILOAD, 4));
            toInject.add(new VarInsnNode(ILOAD, 5));
            toInject.add(new VarInsnNode(ALOAD, 0));
            toInject.add(new FieldInsnNode(GETFIELD, "arb", "cF", "I"));
            toInject.add(new MethodInsnNode(INVOKESTATIC, "blockphysics/BlockPhysics",
                    "onBlockDestroyedByPlayer", "(Labv;IIIII)V"));

            for (int index = m.instructions.size() - 1; index >= 0; index--) {
                if (m.instructions.get(index).getOpcode() == RETURN) {
                    m.instructions.insertBefore(m.instructions.get(index), toInject);
                    ok2 = true;
                    break;
                }
            }
        }
    }

    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    classNode.accept(cw);

    if (ok && ok2)
        System.out.println("OK");
    else
        System.out.println("Failed." + ok + ok2);

    /*try
    {
       FileOutputStream fos = new FileOutputStream("d:/BlockTNT.class");
       fos.write(cw.toByteArray());
     fos.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }*/

    return cw.toByteArray();
}

From source file:blockphysics.asm.BPTransformer.java

License:Open Source License

private byte[] transformBlockFarmland(byte[] bytes) {
    /*try// w w w .j a  v  a  2s.  c  o  m
    {
        FileOutputStream fos = new FileOutputStream("d:/BlockFarmland.orig.class");
        fos.write(bytes);
      fos.close();
    } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
    }*/

    System.out.print("[BlockPhysics] Patching BlockFarmland.class ...........");
    boolean ok = false;

    ClassNode classNode = new ClassNode();
    ClassReader classReader = new ClassReader(bytes);
    classReader.accept(classNode, 0);

    MethodNode m;
    Iterator<MethodNode> methods = classNode.methods.iterator();
    while (methods.hasNext()) {
        m = methods.next();

        if (m.name.equals("a") && m.desc.equals("(Labv;IIILnm;F)V")) {
            InsnList toInject = new InsnList();

            toInject.add(new VarInsnNode(ALOAD, 1));
            toInject.add(new VarInsnNode(ILOAD, 2));
            toInject.add(new VarInsnNode(ILOAD, 3));
            toInject.add(new VarInsnNode(ILOAD, 4));
            toInject.add(new VarInsnNode(ALOAD, 0));
            toInject.add(new FieldInsnNode(GETFIELD, "aoc", "cF", "I"));
            toInject.add(new MethodInsnNode(INVOKESTATIC, "blockphysics/BlockPhysics", "onNeighborBlockChange",
                    "(Labv;IIII)V"));

            for (int index = m.instructions.size() - 1; index >= 0; index--) {
                if (m.instructions.get(index).getOpcode() == RETURN) {
                    m.instructions.insertBefore(m.instructions.get(index), toInject);
                    ok = true;
                    break;
                }
            }
        }
    }

    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    classNode.accept(cw);

    if (ok)
        System.out.println("OK");
    else
        System.out.println("Failed." + ok);

    /*try
    {
       FileOutputStream fos = new FileOutputStream("d:/BlockFarmland.class");
       fos.write(cw.toByteArray());
     fos.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }*/

    return cw.toByteArray();
}

From source file:blockphysics.asm.BPTransformer.java

License:Open Source License

private byte[] transformBlockAnvil(byte[] bytes) {
    /*try/*from  ww  w  .  java2s . c  o m*/
    {
        FileOutputStream fos = new FileOutputStream("d:/BlockAnvil.orig.class");
        fos.write(bytes);
      fos.close();
    } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
    }*/

    System.out.print("[BlockPhysics] Patching BlockAnvil.class ..............");
    boolean ok = false, ok2 = false;

    ClassNode classNode = new ClassNode();
    ClassReader classReader = new ClassReader(bytes);
    classReader.accept(classNode, 0);

    MethodNode m;
    Iterator<MethodNode> methods = classNode.methods.iterator();
    while (methods.hasNext()) {
        m = methods.next();

        if (m.name.equals("a") && m.desc.equals("(Lsq;)V")) {
            m.instructions.clear();
            m.localVariables.clear();
            m.instructions.insert(new InsnNode(RETURN));
            ok = true;
        } else if (m.name.equals("a_") && m.desc.equals("(Labv;IIII)V")) {
            m.instructions.clear();
            m.localVariables.clear();
            m.instructions.insert(new InsnNode(RETURN));
            ok2 = true;
        }
    }

    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    classNode.accept(cw);

    if (ok && ok2)
        System.out.println("OK");
    else
        System.out.println("Failed." + ok + ok2);

    /*try
    {
       FileOutputStream fos = new FileOutputStream("d:/BlockAnvil.mod.class");
       fos.write(cw.toByteArray());
     fos.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }*/

    return cw.toByteArray();
}

From source file:blockphysics.asm.BPTransformer.java

License:Open Source License

private byte[] transformBlockDragonEgg(byte[] bytes) {
    /*try/*from   w  ww  .  ja  v  a  2 s.c o  m*/
    {
        FileOutputStream fos = new FileOutputStream("d:/BlockDragonEgg.orig.class");
        fos.write(bytes);
      fos.close();
    } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
    }*/

    System.out.print("[BlockPhysics] Patching BlockDragonEgg.class ..........");
    boolean ok = false, ok2 = false, ok3 = false, ok4 = false;

    ClassNode classNode = new ClassNode();
    ClassReader classReader = new ClassReader(bytes);
    classReader.accept(classNode, 0);

    MethodNode m;
    Iterator<MethodNode> methods = classNode.methods.iterator();
    while (methods.hasNext()) {
        m = methods.next();

        if (m.name.equals("a") && m.desc.equals("(Labv;IIII)V")) {
            InsnList toInject = new InsnList();
            toInject.add(new VarInsnNode(ALOAD, 1));
            toInject.add(new VarInsnNode(ILOAD, 2));
            toInject.add(new VarInsnNode(ILOAD, 3));
            toInject.add(new VarInsnNode(ILOAD, 4));
            toInject.add(new VarInsnNode(ALOAD, 0));
            toInject.add(new FieldInsnNode(GETFIELD, "any", "cF", "I"));
            toInject.add(new MethodInsnNode(INVOKESTATIC, "blockphysics/BlockPhysics", "onNeighborBlockChange",
                    "(Labv;IIII)V"));
            toInject.add(new InsnNode(RETURN));

            m.instructions.clear();
            m.localVariables.clear();
            m.instructions.add(toInject);
            ok = true;

        } else if (m.name.equals("a") && m.desc.equals("(Labv;IIILjava/util/Random;)V")) {
            m.instructions.clear();
            m.localVariables.clear();
            m.instructions.insert(new InsnNode(RETURN));
            ok2 = true;
        } else if (m.name.equals("k") && m.desc.equals("(Labv;III)V")) {
            m.instructions.clear();
            m.localVariables.clear();
            m.instructions.insert(new InsnNode(RETURN));
            ok3 = true;
        } else if (m.name.equals("m") && m.desc.equals("(Labv;III)V")) {
            InsnList toInject = new InsnList();
            toInject.add(new VarInsnNode(ALOAD, 1));
            toInject.add(new VarInsnNode(ILOAD, 6));
            toInject.add(new VarInsnNode(ILOAD, 7));
            toInject.add(new VarInsnNode(ILOAD, 8));
            toInject.add(
                    new MethodInsnNode(INVOKESTATIC, "blockphysics/BlockPhysics", "notifyMove", "(Labv;III)V"));

            for (int index = 0; index < m.instructions.size(); index++) {
                if (m.instructions.get(index).getOpcode() == INVOKEVIRTUAL
                        && m.instructions.get(index).getType() == AbstractInsnNode.METHOD_INSN
                        && ((MethodInsnNode) m.instructions.get(index)).owner.equals("abv")
                        && ((MethodInsnNode) m.instructions.get(index)).name.equals("i")
                        && ((MethodInsnNode) m.instructions.get(index)).desc.equals("(III)Z")) {

                    if (m.instructions.get(index + 1).getOpcode() == POP) {
                        m.instructions.insert(m.instructions.get(index + 1), toInject);
                    } else
                        m.instructions.insert(m.instructions.get(index), toInject);

                    ok4 = true;
                    break;
                }
            }
        }
    }

    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    classNode.accept(cw);

    if (ok && ok2 && ok3 & ok4)
        System.out.println("OK");
    else
        System.out.println("Failed." + ok + ok2 + ok3 + ok4);

    /*try
    {
       FileOutputStream fos = new FileOutputStream("d:/BlockDragonEgg.class");
       fos.write(cw.toByteArray());
     fos.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }*/

    return cw.toByteArray();
}

From source file:blusunrize.immersiveengineering.common.asm.IEClassTransformer.java

@Override
public byte[] transform(String name, String transformedName, byte[] basicClass) {
    if (basicClass != null && transformerMap.containsKey(transformedName)) {
        MethodTransformer[] transformers = transformerMap.get(transformedName);
        ClassReader reader = new ClassReader(basicClass);
        ClassNode node = new ClassNode();
        reader.accept(node, 0);//from w ww . j  a  v a2 s  . c o  m

        for (MethodNode method : node.methods)
            for (MethodTransformer methodTransformer : transformers)
                if ((methodTransformer.functionName.equals(method.name)
                        || methodTransformer.srgName.equals(method.name))
                        && methodTransformer.functionDesc.equals(method.desc))
                    methodTransformer.function.accept(method);

        ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
        node.accept(writer);
        return writer.toByteArray();
    }
    return basicClass;
}

From source file:ca.oson.json.util.ObjectUtil.java

License:Open Source License

/**
 * Returns a list containing one parameter name for each argument accepted
 * by the given constructor. If the class was compiled with debugging
 * symbols, the parameter names will match those provided in the Java source
 * code. Otherwise, a generic "arg" parameter name is generated ("arg0" for
 * the first argument, "arg1" for the second...).
 *
 * This method relies on the constructor's class loader to locate the
 * bytecode resource that defined its class.
 *
 * @param constructor the constructor to get a list of parameter names
 * @return a list of parameter names//from w ww .j  a v a 2  s .co  m
 * @throws IOException io exception to throw
 */
private static List<String> getParameterNamesBytecode(Constructor<?> constructor) throws IOException {
    Class<?> declaringClass = constructor.getDeclaringClass();
    ClassLoader declaringClassLoader = declaringClass.getClassLoader();

    if (declaringClassLoader == null) {
        return null;
    }

    org.objectweb.asm.Type declaringType = org.objectweb.asm.Type.getType(declaringClass);
    String constructorDescriptor = org.objectweb.asm.Type.getConstructorDescriptor(constructor);
    String url = declaringType.getInternalName() + ".class";

    InputStream classFileInputStream = declaringClassLoader.getResourceAsStream(url);
    if (classFileInputStream == null) {
        // throw new IllegalArgumentException("The constructor's class loader cannot find the bytecode that defined the constructor's class (URL: " + url + ")");
        return null;
    }

    ClassNode classNode;
    try {
        classNode = new ClassNode();
        ClassReader classReader = new ClassReader(classFileInputStream);
        classReader.accept(classNode, 0);
    } finally {
        classFileInputStream.close();
    }

    @SuppressWarnings("unchecked")
    List<MethodNode> methods = classNode.methods;
    for (MethodNode method : methods) {
        if (method.name.equals("<init>") && method.desc.equals(constructorDescriptor)) {
            org.objectweb.asm.Type[] argumentTypes = org.objectweb.asm.Type.getArgumentTypes(method.desc);
            List<String> parameterNames = new ArrayList<String>(argumentTypes.length);

            @SuppressWarnings("unchecked")
            List<LocalVariableNode> localVariables = method.localVariables;
            for (int i = 0; i < argumentTypes.length && i < localVariables.size() - 1; i++) {
                // The first local variable actually represents the "this" object
                parameterNames.add(localVariables.get(i + 1).name);
            }

            return parameterNames;
        }
    }

    return null;
}

From source file:ca.weblite.asm.ASMClassLoader.java

public ClassNode findClass(Type type) {
    if (nodeCache.containsKey(type.getInternalName())) {
        return nodeCache.get(type.getInternalName());
    }/*w  ww .j  a v a2  s.co  m*/
    String classFile = type.getInternalName() + ".class";
    while (true) {
        InputStream bytecode = loader.getResourceAsStream(classFile);
        if (bytecode != null) {
            try {
                ClassNode node = new ClassNode();
                ClassReader reader = new ClassReader(bytecode);
                reader.accept(node, ClassReader.SKIP_CODE);
                if ((node.name + ".class").equals(classFile)) {
                    nodeCache.put(type.getInternalName(), node);
                    return node;
                }
            } catch (IOException ex) {
                Logger.getLogger(ASMClassLoader.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        int lastSlash = classFile.lastIndexOf("/");
        if (lastSlash == -1) {
            break;
        }
        classFile = classFile.substring(0, lastSlash) + "$" + classFile.substring(lastSlash + 1);
    }

    return super.findClass(type);
}

From source file:ca.weblite.asm.JavaSourceClassLoader.java

@Override
public ClassNode findClass(Type type) {
    String classFile = type.getInternalName() + ".class";
    ClassNode cached = cacheClassLoader.findClass(type);
    long cacheMtime = cacheClassLoader.getLastModified();

    String javaFile = type.getInternalName() + ".java";
    while (true) {
        File file = loader.getResource(javaFile);
        if (file != null) {
            try (FileInputStream bytecode = new FileInputStream(file)) {
                if (cached != null && cacheMtime >= lastModified) {
                    // The cached version is up to date
                    // no need to load the class
                    return cached;
                }/*from   w ww  . java 2s.c om*/

                ClassNode node = new ClassNode();
                ClassReader reader = new ClassReader(bytecode);
                reader.accept(node, ClassReader.SKIP_CODE);
                if ((node.name + ".java").equals(javaFile)) {
                    return node;
                }
            } catch (IOException ex) {
                Logger.getLogger(JavaSourceClassLoader.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        int lastSlash = javaFile.lastIndexOf("/");
        if (lastSlash == -1) {
            break;
        }
        javaFile = javaFile.substring(0, lastSlash) + ".java";
    }

    return super.findClass(type);
}

From source file:ca.weblite.asm.MirahClassLoader.java

License:Apache License

private ClassNode findClassImpl(final Type type) {
    lastFoundClass = null;//from  ww w .j  a v  a2s  .co  m
    SourceFile sourceFile = index.findSourceFile(type);
    if (sourceFile != null) {
        if (!sourceFile.dirty) {
            ClassNode cached = bytecodeLoader.findClass(type);
            if (cached != null && bytecodeLoader.getLastModified() > sourceFile.file.lastModified()) {
                lastFoundClass = cached;
                return cached;
            }
        }

        try (FileInputStream fis = new FileInputStream(sourceFile.file)) {
            MirahParser parser = new MirahParser();
            StreamCodeSource source = new StreamCodeSource(sourceFile.file.getPath(), fis);

            final LinkedList<ClassFinder> scopeStack = new LinkedList<>();
            Object ast = parser.parse(source);

            if (ast instanceof Node) {
                Node node = (Node) ast;
                node.accept(new NodeScanner() {

                    String packageName = null;

                    @Override
                    public boolean enterPackage(mirah.lang.ast.Package node, Object arg) {
                        if (lastFoundClass != null) {
                            return true;
                        }
                        packageName = node.name().identifier();
                        ClassFinder scope = new ClassFinder(context.get(ClassLoader.class), null);
                        scope.addImport(packageName + ".*");
                        if (!scopeStack.isEmpty()) {
                            scopeStack.pop();
                        }
                        scopeStack.push(scope);
                        return super.enterPackage(node, arg);
                    }

                    @Override
                    public boolean enterInterfaceDeclaration(InterfaceDeclaration node, Object arg) {
                        return enterClassDefinition(node, arg);
                    }

                    @Override
                    public boolean enterClassDefinition(ClassDefinition node, Object arg) {
                        if (lastFoundClass != null) {
                            return true;
                        }
                        String className = packageName.replaceAll("\\.", "/") + "/" + node.name().identifier();
                        if (type.getInternalName().equals(className)) {
                            ClassWriter writer = new ClassWriter(1);

                            String superName = "java/lang/Object";
                            if (node.superclass() != null) {
                                superName = node.superclass().typeref().name();
                                ClassNode superClass = scopeStack.peek().findStub(superName);
                                assert superClass != null;
                                superName = superClass.name;
                            }

                            List<String> interfaces = new ArrayList<>();
                            if (node.interfaces() != null) {
                                int len = node.interfaces_size();
                                for (int i = 0; i < len; i++) {
                                    String iname = node.interfaces(i).typeref().name();
                                    ClassNode iClass = scopeStack.peek().findStub(iname);
                                    if (iClass == null) {
                                        throw new RuntimeException("Failed to find interface " + iname
                                                + " in class definition of " + className);
                                    }
                                    interfaces.add(iClass.name);
                                }
                            }

                            lastFoundClass = new ClassNode();
                            lastFoundClass.version = 1;
                            lastFoundClass.access = Opcodes.ACC_PUBLIC;
                            lastFoundClass.name = type.getInternalName();
                            lastFoundClass.superName = superName;
                            lastFoundClass.interfaces = interfaces;

                            writer.visit(1, Opcodes.ACC_PUBLIC, type.getInternalName(), null, superName,
                                    interfaces.toArray(new String[0]));

                            byte[] classBytes = writer.toByteArray();

                            File classFilePath = new File(getCachePath(), type.getInternalName() + ".class");
                            classFilePath.getParentFile().mkdirs();
                            try (FileOutputStream fos = new FileOutputStream(classFilePath)) {
                                fos.write(classBytes);
                            } catch (IOException ex) {
                                Logger.getLogger(MirahClassLoader.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }

                        return super.enterClassDefinition(node, arg);
                    }

                    @Override
                    public Object exitClassDefinition(ClassDefinition node, Object arg) {
                        return super.exitClassDefinition(node, arg);
                    }

                    @Override
                    public boolean enterImport(Import node, Object arg) {

                        if (scopeStack.isEmpty()) {
                            ClassFinder scope = new ClassFinder(context.get(ClassLoader.class), null);
                            scopeStack.push(scope);
                        }
                        scopeStack.peek().addImport(node.fullName().identifier());
                        //System.out.println("Entering import: "+node.fullName().identifier());
                        return super.enterImport(node, arg);
                    }

                }, null);

            }
        } catch (IOException ex) {
            Logger.getLogger(MirahClassLoader.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (lastFoundClass != null) {
            return lastFoundClass;
        }

    }
    return null;
}