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:net.minecrell.quartz.plugin.QuartzPluginManager.java

License:MIT License

@Nullable
private String findPlugin(InputStream in) throws IOException {
    ClassReader reader = new ClassReader(in);
    ClassNode classNode = new ClassNode();
    reader.accept(classNode, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);

    if (classNode.visibleAnnotations != null) {
        for (AnnotationNode node : classNode.visibleAnnotations) {
            if (node.desc.equals(PLUGIN_DESCRIPTOR)) {
                return classNode.name.replace('/', '.');
            }/*from   w w w  . j  a v  a 2 s. c om*/
        }
    }

    return null;
}

From source file:net.orfjackal.retrolambda.Transformers.java

License:Open Source License

public List<byte[]> backportInterface(ClassReader reader) {
    // The lambdas must be backported only once, because bad things will happen if a lambda
    // is called by different class name in the interface and its companion class, and then
    // the wrong one of them is written to disk last.
    ClassNode lambdasBackported = new ClassNode();
    ClassVisitor next = lambdasBackported;
    next = new BackportLambdaInvocations(next, analyzer);
    reader.accept(next, 0);//from  w  ww.  j  av a2  s . c o m

    List<byte[]> results = new ArrayList<>();
    results.add(backportInterface2(lambdasBackported));
    results.addAll(extractInterfaceCompanion(lambdasBackported));
    return results;
}

From source file:net.petercashel.jmsDd.util.ASMTransformer.java

License:Apache License

public static byte[] transform(String name, byte[] bytes) {
    if (debug)// w w w . ja va 2 s  .c  o m
        System.out.println(bytes.length);
    ClassNode classNode = new ClassNode();
    String classNameASM = name.replace('.', '/');
    ClassReader classReader = new ClassReader(bytes);
    classReader.accept(classNode, 0);
    boolean DoModInit = false;
    boolean HasInit = false;
    String initDesc = "()V";
    boolean lockDesc = false;

    try {
        try {
            for (int i = 0; i < classNode.visibleAnnotations.size(); i++) {
                AnnotationNode ann = (AnnotationNode) classNode.visibleAnnotations.get(i);
                if (ann.desc.equalsIgnoreCase("Lnet/petercashel/jmsDd/module/Module;")) {
                    try {
                        if (debug)
                            System.out.println("ANNOTE!");
                        DoModInit = true;
                        Map<String, Object> values = asmList2Map(ann.values);
                        ModuleSystem.modulesToLoad.put(
                                values.get("ModuleName").toString().replace("[", "").replace("]", ""),
                                classNode.name.replace("/", "."));
                    } catch (Exception e) {
                        e.printStackTrace();

                    }
                }
            }
        } catch (Exception e) {
        }

        try {
            if (DoModInit) {

                for (int i = 0; i < classNode.methods.size(); i++) {
                    MethodNode m = (MethodNode) classNode.methods.get(i);
                    if (m.name.contentEquals("<init>")) {
                        initDesc = m.desc;
                        if (m.desc.contentEquals("()V")) {
                            HasInit = true;
                            if (debug)
                                System.out.println("Found <init>");
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (debug)
        System.out.println("Still alive?");
    try {

        //          L0
        //             LINENUMBER 43 L0
        //             ALOAD 0
        //             INVOKESPECIAL // CLASSNAME FOR ASM  // ()V    ////// This is effectically a super() call but to the discovered constructor
        //            L1
        //             LINENUMBER 44 L1
        //             INVOKESTATIC net/petercashel/jmsDd/API/API$Impl.getAPI ()Lnet/petercashel/jmsDd/API/API;
        //             ALOAD 0
        //             INVOKEINTERFACE net/petercashel/jmsDd/API/API.registerEventBus (Ljava/lang/Object;)V
        //            L2
        //             LINENUMBER 46 L2
        //             RETURN
        //            L3
        //             LOCALVARIABLE this // "L" + CLASSNAME FOR ASM + ";" // L0 L3 0
        //             LOCALVARIABLE e Lnet/petercashel/jmsDd/event/module/DummyEvent; L0 L3 1
        //             MAXSTACK = 2
        //             MAXLOCALS = 2
        if (DoModInit) {
            if (HasInit) {
                if (debug)
                    System.out.println("Adding Extra Constructor to " + name);
                MethodNode constructor = new MethodNode(Opcodes.ACC_PUBLIC, "<init>",
                        "(Lnet/petercashel/jmsDd/event/module/DummyEvent;)V", null, null);

                Label L0 = new Label();
                constructor.visitLabel(L0);
                constructor.visitVarInsn(Opcodes.ALOAD, 0);
                constructor.visitMethodInsn(Opcodes.INVOKESPECIAL, classNameASM, "<init>", initDesc);

                Label L1 = new Label();
                constructor.visitLabel(L1);
                constructor.visitMethodInsn(Opcodes.INVOKESTATIC, "net/petercashel/jmsDd/API/API$Impl",
                        "getAPI", "()Lnet/petercashel/jmsDd/API/API;");
                constructor.visitVarInsn(Opcodes.ALOAD, 0);
                constructor.visitMethodInsn(Opcodes.INVOKEINTERFACE, "net/petercashel/jmsDd/API/API",
                        "registerEventBus", "(Ljava/lang/Object;)V");

                Label L2 = new Label();
                constructor.visitLabel(L2);
                constructor.visitInsn(Opcodes.RETURN);

                Label L3 = new Label();
                constructor.visitLabel(L3);
                constructor.visitLocalVariable("this", "L" + classNameASM + ";", null, L0, L3, 0);
                constructor.visitLocalVariable("e", "Lnet/petercashel/jmsDd/event/module/DummyEvent;", null, L0,
                        L3, 1);
                constructor.visitMaxs(2, 2);
                constructor.visitEnd();
                classNode.methods.add(constructor);

            } else {
                System.err.println("WARNING! " + name
                        + " Doesn't have a default no-args constructor.  Module loader cannot chain load the constructor. \n If you are recieving this error and your module has no constructors defined, or a no-args constructor defined, \n please report the bug to the author of JMSDd.");
                MethodNode constructor = new MethodNode(Opcodes.ACC_PUBLIC, "<init>",
                        "(Lnet/petercashel/jmsDd/event/module/DummyEvent;)V", null, null);

                Label L0 = new Label();
                constructor.visitLabel(L0);
                constructor.visitVarInsn(Opcodes.ALOAD, 0);
                //INVOKESPECIAL java/lang/Object.<init> ()V ////// There is no other constructor, call super() to Object.
                constructor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V");

                Label L1 = new Label();
                constructor.visitLabel(L1);
                constructor.visitMethodInsn(Opcodes.INVOKESTATIC, "net/petercashel/jmsDd/API/API$Impl",
                        "getAPI", "()Lnet/petercashel/jmsDd/API/API;");
                constructor.visitVarInsn(Opcodes.ALOAD, 0);
                constructor.visitMethodInsn(Opcodes.INVOKEINTERFACE, "net/petercashel/jmsDd/API/API",
                        "registerEventBus", "(Ljava/lang/Object;)V");

                Label L2 = new Label();
                constructor.visitLabel(L2);
                constructor.visitInsn(Opcodes.RETURN);

                Label L3 = new Label();
                constructor.visitLabel(L3);
                constructor.visitLocalVariable("this", "L" + classNameASM + ";", null, L0, L3, 0);
                constructor.visitLocalVariable("e", "Lnet/petercashel/jmsDd/event/module/DummyEvent;", null, L0,
                        L3, 1);
                constructor.visitMaxs(2, 2);
                constructor.visitEnd();
                classNode.methods.add(constructor);
            }
            classNode.visitEnd();
            ClassWriter wr = new ClassWriter(0);
            classNode.accept(wr);

            bytes = wr.toByteArray();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (debug)
        System.out.println("Still alive.");
    if (debug)
        System.out.println(bytes.length);
    if (plugins.size() > 0) {
        for (ASMPlugin p : plugins) {
            try {
                bytes = p.transform(name, bytes);
            } catch (Exception e) {

            }
        }
    }

    return bytes;
}

From source file:net.rim.ejde.internal.launching.MDSCSChecker.java

License:Open Source License

private static String getMDSCSVersion(InputStream inputStream) {
    _currentVersion = null; // reset the value
    try {/*  ww w  .j a v a 2 s .co  m*/
        ClassReader classReader = new ClassReader(inputStream);
        ClassNode myVisitor = new ClassNode() {
            public FieldVisitor visitField(int access, String name, String desc, String signature,
                    Object value) {
                if (value instanceof String) {
                    String[] parts = ((String) value).split("\\.");
                    if (parts.length > 2) {
                        _currentVersion = (String) value;
                    }
                }
                return super.visitField(access, name, desc, signature, value);
            }
        };
        classReader.accept(myVisitor, ClassReader.SKIP_FRAMES);
    } catch (Throwable ex) {
        _logger.error("", ex);
    }
    return _currentVersion;
}

From source file:net.roryclaasen.asm.rorysmodcore.transformer.EntityPlayerTransformer.java

License:Apache License

public byte[] patchOnUpdate(String name, byte[] bytes, boolean obfuscated) {
    RMLog.info("[EntityPlayer] [onUpdate] Patching", true);
    String targetMethodName = "";

    if (obfuscated == true)
        targetMethodName = "h";
    else/*from  w  w  w .  j  av  a2 s .  c  om*/
        targetMethodName = "onUpdate";
    ClassNode classNode = new ClassNode();
    ClassReader classReader = new ClassReader(bytes);
    classReader.accept(classNode, 0);

    Iterator<MethodNode> methods = classNode.methods.iterator();
    while (methods.hasNext()) {
        MethodNode method = methods.next();
        int invok_index = -1;
        if ((method.name.equals(targetMethodName) && method.desc.equals("()V"))) {
            AbstractInsnNode currentNode = null;
            AbstractInsnNode targetNode = null;

            Iterator<AbstractInsnNode> iter = method.instructions.iterator();

            int index = -1;

            int GETFIELD_COUNT = 0;
            while (iter.hasNext()) {
                index++;
                currentNode = iter.next();
                if (currentNode.getOpcode() == Opcodes.GETFIELD) {
                    GETFIELD_COUNT++;
                    if (GETFIELD_COUNT == 13) {
                        targetNode = currentNode;
                        invok_index = index;
                        break;
                    }
                }
            }
            if (targetNode == null || invok_index == -1) {
                RMLog.info("[EntityPlayer] Did not find all necessary target nodes! ABANDON CLASS!", true);
                return bytes;
            }
            /*
             * mv.visitLineNumber(305, l19);
             * mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
             * mv.visitVarInsn(ALOAD, 0);
             * -- mv.visitFieldInsn(GETFIELD, "net/minecraft/entity/player/EntityPlayer", "worldObj", "Lnet/minecraft/world/World;");
             * mv.visitFieldInsn(GETFIELD, "net/minecraft/world/World", "isRemote", "Z");
             * Label l21 = new Label();
             * mv.visitJumpInsn(IFNE, l21);
             */
            @SuppressWarnings("unused")
            AbstractInsnNode p1, p2, p3;
            p1 = method.instructions.get(invok_index - 1); // mv.visitVarInsn(ALOAD, 0);
            p2 = method.instructions.get(invok_index); // mv.visitFieldInsn(GETFIELD, "net/minecraft/entity/player/EntityPlayer", "worldObj", "Lnet/minecraft/world/World;");
            p3 = method.instructions.get(invok_index + 1); // mv.visitFieldInsn(GETFIELD, "net/minecraft/world/World", "isRemote", "Z");

            //method.instructions.remove(p1);
            //method.instructions.remove(p2);
            //method.instructions.remove(p3);

            MethodInsnNode m1 = new MethodInsnNode(Opcodes.INVOKESTATIC,
                    "net/roryclaasen/asm/rorysmodcore/transformer/StaticClass", "shouldWakeUp",
                    "(Lnet/minecraft/entity/player/EntityPlayer;)Z", false);

            method.instructions.set(p2, m1);
            method.instructions.remove(p3);
            break;
        }
    }
    ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    classNode.accept(writer);
    return writer.toByteArray();
}

From source file:net.roryclaasen.asm.rorysmodcore.transformer.WorldServerTransformer.java

License:Apache License

public byte[] patchTick(String name, byte[] bytes, boolean obfuscated) {
    RMLog.info("[WorldServer] [tick] Patching", true);
    String targetMethodName = "";

    if (obfuscated == true)
        targetMethodName = "b";
    else//www. j a  va 2s.  c  o m
        targetMethodName = "tick";
    ClassNode classNode = new ClassNode();
    ClassReader classReader = new ClassReader(bytes);
    classReader.accept(classNode, 0);

    Iterator<MethodNode> methods = classNode.methods.iterator();
    while (methods.hasNext()) {
        MethodNode method = methods.next();
        int invok_index = -1;
        if ((method.name.equals(targetMethodName) && method.desc.equals("()V"))) {
            AbstractInsnNode currentNode = null;
            AbstractInsnNode targetNode = null;

            Iterator<AbstractInsnNode> iter = method.instructions.iterator();

            int index = -1;

            int INVOKEVIRTUAL_COUNT = 0;
            while (iter.hasNext()) {
                index++;
                currentNode = iter.next();
                if (currentNode.getOpcode() == Opcodes.INVOKEVIRTUAL) {
                    INVOKEVIRTUAL_COUNT++;
                    if (INVOKEVIRTUAL_COUNT == 9) {
                        targetNode = currentNode;
                        invok_index = index;
                        break;
                    }
                }
            }
            if (targetNode == null || invok_index == -1) {
                RMLog.info("[WorldServer] Did not find all necessary target nodes! ABANDON CLASS!", true);
                return bytes;
            }
            AbstractInsnNode p1 = method.instructions.get(invok_index);
            MethodInsnNode a1 = new MethodInsnNode(Opcodes.INVOKESPECIAL, "net/minecraft/world/WorldServer",
                    "resetRainAndThunder", "()V", false);

            method.instructions.set(p1, a1);
            break;
        }
    }
    ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    classNode.accept(writer);
    return writer.toByteArray();
}

From source file:net.roryclaasen.asm.rorysmodcore.transformer.WorldServerTransformer.java

License:Apache License

public byte[] patchWakeAllPlayers(String name, byte[] bytes, boolean obfuscated) {
    RMLog.info("[WorldServer] [wakeAllPlayers] Patching", true);
    String targetMethodName = "";

    if (obfuscated == true)
        targetMethodName = "d";
    else//from w ww . jav a 2 s. c  o m
        targetMethodName = "wakeAllPlayers";

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

    Iterator<MethodNode> methods = classNode.methods.iterator();
    while (methods.hasNext()) {
        MethodNode method = methods.next();
        int invok_index = -1;
        if ((method.name.equals(targetMethodName) && method.desc.equals("()V"))) {
            AbstractInsnNode currentNode = null;
            AbstractInsnNode targetNode = null;

            Iterator<AbstractInsnNode> iter = method.instructions.iterator();
            int index = -1;
            while (iter.hasNext()) {
                index++;
                currentNode = iter.next();
                if (currentNode.getOpcode() == Opcodes.INVOKEVIRTUAL) {
                    invok_index = index;
                    targetNode = currentNode;
                    break;
                }
            }
            if (targetNode == null || invok_index == -1) {
                RMLog.info("[WorldServer] Did not find all necessary target nodes! ABANDON CLASS!", true);
                return bytes;
            }
            AbstractInsnNode p1 = method.instructions.get(invok_index);
            MethodInsnNode p2 = new MethodInsnNode(Opcodes.INVOKESTATIC,
                    "net/roryclaasen/asm/rorysmodcore/transformer/StaticClass", "shouldWakeUp", "()Z", false);

            method.instructions.set(p1, p2);
            method.instructions.remove(method.instructions.get(invok_index - 1));
            break;
        }
    }
    ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    classNode.accept(writer);
    return writer.toByteArray();
}

From source file:net.sandius.rembulan.compiler.gen.asm.ASMBytecodeEmitter.java

License:Apache License

public ASMBytecodeEmitter(IRFunc fn, SlotAllocInfo slots, TypeInfo types, DependencyInfo deps,
        CompilerSettings compilerSettings, ClassNameTranslator classNameTranslator, String sourceFile) {

    this.fn = Objects.requireNonNull(fn);
    this.slots = Objects.requireNonNull(slots);
    this.types = Objects.requireNonNull(types);
    this.deps = Objects.requireNonNull(deps);

    this.compilerSettings = Objects.requireNonNull(compilerSettings);
    this.classNameTranslator = Objects.requireNonNull(classNameTranslator);
    this.sourceFile = Objects.requireNonNull(sourceFile);

    classNode = new ClassNode();

    this.fields = new ArrayList<>();

    upvalueFieldNames = new HashMap<>();

    String s = System.getProperty("net.sandius.rembulan.compiler.VerifyAndPrint");
    verifyAndPrint = s != null && "true".equals(s.trim().toLowerCase());
}

From source file:net.signbit.tools.atomizer.ClassRef.java

License:Apache License

private ClassRef(InputStream stream, String jarName) throws IOException {
    this.jarName = jarName;
    fullDependencySet = new HashSet<>();

    ClassReader reader = new ClassReader(stream);
    ClassNode classNode = new ClassNode();
    reader.accept(classNode, 0);//from   w w w .j  a  v  a 2  s.co  m

    String[] packageElements = classNode.name.split("/");
    if (packageElements.length > 1) {
        String[] packageOnly = Arrays.copyOfRange(packageElements, 0, packageElements.length - 1);
        packageName = String.join(".", packageOnly);
    } else {
        packageName = "";
    }
    className = packageElements[packageElements.length - 1];

    fullDependencySet.add(classNode.superName.replace('/', '.'));

    for (Object itf : classNode.interfaces) {
        fullDependencySet.add(((String) itf).replace('/', '.'));
    }

    for (Object mn : classNode.methods) {
        MethodNode methodNode = (MethodNode) mn;

        Type type = Type.getType(methodNode.desc);
        fullDependencySet.add(type.getReturnType().getClassName());
        for (Type argType : type.getArgumentTypes()) {
            fullDependencySet.add(argType.getClassName());
        }

        for (Object oo : methodNode.exceptions) {
            String excClass = (String) oo;
            fullDependencySet.add(excClass.replace('/', '.'));
        }

        if (null != methodNode.localVariables) {
            for (Object lon : methodNode.localVariables) {
                LocalVariableNode localVariableNode = (LocalVariableNode) lon;
                fullDependencySet.add(Type.getType(localVariableNode.desc).getClassName());
            }
        }
    }

    fullDependencySet.remove("void");
    fullDependencySet.remove("long");
    fullDependencySet.remove("int");
    fullDependencySet.remove("boolean");

    // the constructor adds it
    fullDependencySet.remove(packageName + '.' + className);
}

From source file:net.signbit.tools.atomizer.DumpClassReferences.java

License:Apache License

private static void processClass(InputStream stream) throws IOException {
    ClassReader reader = new ClassReader(stream);
    ClassNode classNode = new ClassNode();
    reader.accept(classNode, 0);/*  w ww .j a  va  2 s  . c om*/

    System.out.println("Class: " + classNode.name);
    System.out.println("   Extends: " + classNode.superName);

    for (Object itf : classNode.interfaces) {
        System.out.println("   Implements: " + itf);
    }

    for (Object mn : classNode.methods) {
        MethodNode methodNode = (MethodNode) mn;
        System.out.println("   Method: " + methodNode.name);

        Type type = Type.getType(methodNode.desc);
        System.out.println("      Return: " + type.getReturnType().getClassName());
        for (Type argType : type.getArgumentTypes()) {
            System.out.println("      Param: " + argType.getClassName());
        }

        for (Object oo : methodNode.exceptions) {
            System.out.println("      Throws: " + oo);
        }

        for (Object lon : methodNode.localVariables) {
            LocalVariableNode localVariableNode = (LocalVariableNode) lon;
            System.out.println("      Var: " + Type.getType(localVariableNode.desc).getClassName());
        }
    }

}