Example usage for org.objectweb.asm.tree MethodNode accept

List of usage examples for org.objectweb.asm.tree MethodNode accept

Introduction

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

Prototype

public void accept(final MethodVisitor methodVisitor) 

Source Link

Document

Makes the given method visitor visit this method.

Usage

From source file:de.tuberlin.uebb.jbop.optimizer.methodsplitter.MethodSplitter.java

License:Open Source License

@Override
public InsnList optimize(final InsnList original, final MethodNode methodNode) throws JBOPClassException {

    LocalVariablesSorter sorter = new LocalVariablesSorter(methodNode.access, methodNode.desc,
            new EmptyMethodVisitor(Opcodes.ASM5));
    methodNode.accept(sorter);

    if (getLength(methodNode) < maxInsns) {
        return clean(original);
    }// www . ja va2 s .  c  o m

    final List<Block> blocks = getBlocks(original, methodNode);

    final String baseName = methodNode.name;
    final String[] exceptions = getExceptions(methodNode);

    final InsnList returnList = new InsnList();
    InsnList list = returnList;

    Block block = blocks.get(0);
    block.renameInsns(block.getVarMap());

    final String name = baseName + "__split__part__";
    final Type endType = Type.getReturnType(methodNode.desc);
    for (int i = 1; i < blocks.size(); ++i) {
        final Map<Integer, Integer> paramRenameMap = block.getVarMap();
        add(list, block.getInstructions(), original);
        block = blocks.get(i);
        block.renameInsns(paramRenameMap);
        final String methodDescriptor = block.getDescriptor();
        final String newMethodName = name + block.getBlockNumber();
        final MethodNode splitMethod = new MethodNode(Opcodes.ASM5, ACCESS, newMethodName, methodDescriptor,
                null, exceptions);
        additionalMethods.add(splitMethod);

        list.add(new VarInsnNode(Opcodes.ALOAD, 0));
        list.add(block.getPushParameters());
        list.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, classNode.name, splitMethod.name, methodDescriptor));
        list.add(new InsnNode(endType.getOpcode(IRETURN)));
        sorter = new LocalVariablesSorter(splitMethod.access, splitMethod.desc,
                new EmptyMethodVisitor(Opcodes.ASM5));
        splitMethod.accept(sorter);
        list = splitMethod.instructions;
    }
    add(list, block.getInstructions(), original);
    return returnList;
}

From source file:de.tuberlin.uebb.jbop.optimizer.methodsplitter.MethodSplitter.java

License:Open Source License

private int getLength(final MethodNode methodNode) {
    final CodeSizeEvaluator codeSizeEvaluator = new CodeSizeEvaluator(null);
    methodNode.accept(codeSizeEvaluator);
    return codeSizeEvaluator.getMaxSize();
}

From source file:de.tuberlin.uebb.jbop.optimizer.utils.NodeHelper.java

License:Open Source License

/**
 * Prints the method.//from w w w  .  j a v a  2  s.c o  m
 * 
 * @param node
 *          the node
 * @param stream
 *          the stream
 */
public static void printMethod(final MethodNode node, final ClassNode classNode, final PrintStream stream,
        final boolean build) {
    final Printer p;
    if (build) {
        p = new ClassNodeBuilderTextifier(node, classNode);
    } else {
        p = new ExtendedTextifier(node, classNode);
    }
    final TraceMethodVisitor traceMethodVisitor = new TraceMethodVisitor(p);
    node.accept(traceMethodVisitor);
    stream.println(StringUtils.join(p.getText(), ""));
}

From source file:de.unisb.cs.st.javalanche.mutation.bytecodeMutations.removeSystemExit.RemoveSystemExitMethodNode.java

License:Open Source License

@SuppressWarnings("unchecked")
// Call to pre-1.5 Code
@Override/*from   w w  w. ja v  a 2  s  .  com*/
public void visitEnd() {
    MethodNode mn = (MethodNode) mv;
    InsnList insns = mn.instructions;
    Iterator i = insns.iterator();
    AbstractInsnNode prev = null;
    InsnList newInstrucionList = new InsnList();
    while (i.hasNext()) {
        boolean addInstruction = true;
        AbstractInsnNode i1 = (AbstractInsnNode) i.next();
        if (i1 instanceof MethodInsnNode) {
            MethodInsnNode methotInsnNode = (MethodInsnNode) i1;
            if (methotInsnNode.name.equals("exit") && methotInsnNode.owner.equals("java/lang/System")) {
                logger.info("Replacing System.exit ");
                newInstrucionList.remove(prev);
                // insns.remove(i1);
                InsnList il = new InsnList();
                Label mutationStartLabel = new Label();
                mutationStartLabel.info = new MutationMarker(true);

                il.add(new LabelNode(mutationStartLabel));
                il.add(new TypeInsnNode(Opcodes.NEW, "java/lang/RuntimeException"));
                il.add(new InsnNode(Opcodes.DUP));
                il.add(new LdcInsnNode("Replaced System.exit()"));
                il.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, "java/lang/RuntimeException", "<init>",
                        "(Ljava/lang/String;)V"));
                il.add(new InsnNode(Opcodes.ATHROW));

                Label mutationEndLabel = new Label();
                mutationEndLabel.info = new MutationMarker(false);
                il.add(new LabelNode(mutationEndLabel));
                newInstrucionList.add(il);
                addInstruction = false;
            }
        }
        if (addInstruction) {
            try {
                insns.remove(i1);
                newInstrucionList.add(i1);
            } catch (Exception e) {
                logger.error(e);
            }

        }
        prev = i1;
    }
    mn.instructions = newInstrucionList;
    mn.accept(next);
}

From source file:de.unisb.cs.st.javaslicer.tracer.instrumentation.TracingClassInstrumenter.java

License:Open Source License

protected void transformMethod(final ClassNode classNode, final MethodNode method,
        final ListIterator<MethodNode> methodIt) {
    final ReadMethod readMethod = new ReadMethod(this.readClass, method.access, method.name, method.desc,
            AbstractInstruction.getNextIndex());
    this.readClass.addMethod(readMethod);

    // do not instrument <clinit> methods (break (linear) control flow)
    // because these methods may call other methods, we have to pause tracing when they are entered
    if ("<clinit>".equals(method.name)) {
        new PauseTracingInstrumenter(null, this.tracer).transformMethod(method, methodIt,
                this.readClass.getName());
        return;/*from   ww  w . j  a  v a2s .  c o m*/
    }

    MethodNode oldMethod;
    // only copy the old method if it has more than 2000 instructions
    if (method.instructions.size() > 2000) {
        oldMethod = new MethodNode();
        copyMethod(method, oldMethod);
    } else {
        oldMethod = null;
    }

    new TracingMethodInstrumenter(this.tracer, readMethod, classNode, method).transform(methodIt);

    // test the size of the instrumented method
    final ClassWriter testCW = new ClassWriter(0);
    method.accept(testCW);
    final int byteCodeSize = testCW.toByteArray().length;
    if (byteCodeSize >= 1 << 16) {
        System.err.format(
                "WARNING: instrumented method \"%s.%s%s\" is larger than 64k bytes. undoing instrumentation.%n",
                this.readClass.getName(), readMethod.getName(), readMethod.getDesc());
        if (oldMethod == null) {
            System.err.println(
                    "ERROR: uninstrumented method had less than 2000 instructions, so we cannot roll back the instrumentation...");
        } else {
            System.err.format("#instructions old: %d; #instructions new: %d; size new: %d%n",
                    oldMethod.instructions.size(), method.instructions.size(), byteCodeSize);
            copyMethod(oldMethod, method);
        }
    }

    // reset the labels
    final Iterator<?> insnIt = method.instructions.iterator();
    while (insnIt.hasNext()) {
        final Object insn = insnIt.next();
        if (insn instanceof LabelNode)
            ((LabelNode) insn).resetLabel();
    }

}

From source file:dodola.anole.lib.IncrementalSupportVisitor.java

License:Apache License

/**
 * Insert Constructor specific logic({@link ConstructorArgsRedirection} and
 * {@link ConstructorDelegationDetector}) for constructor redirecting or
 * normal method redirecting ({@link MethodRedirection}) for other methods.
 *///from  ww  w .j ava  2  s  . co m
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {

    access = transformAccessForInstantRun(access);

    MethodVisitor defaultVisitor = super.visitMethod(access, name, desc, signature, exceptions);
    MethodNode method = getMethodByNameInClass(name, desc, classNode);
    // does the method use blacklisted APIs.
    boolean hasIncompatibleChange = InstantRunMethodVerifier
            .verifyMethod(method) != InstantRunVerifierStatus.COMPATIBLE;

    if (hasIncompatibleChange || disableRedirectionForClass || !isAccessCompatibleWithInstantRun(access)
            || name.equals(AsmUtils.CLASS_INITIALIZER)) {
        return defaultVisitor;
    } else {
        ISMethodVisitor mv = new ISMethodVisitor(defaultVisitor, access, name, desc);
        if (name.equals(AsmUtils.CONSTRUCTOR)) {

            ConstructorDelegationDetector.Constructor constructor = ConstructorDelegationDetector
                    .deconstruct(visitedClassName, method);
            LabelNode start = new LabelNode();
            LabelNode after = new LabelNode();
            method.instructions.insert(constructor.loadThis, start);
            if (constructor.lineForLoad != -1) {
                // Record the line number from the start of LOAD_0 for uninitialized 'this'.
                // This allows a breakpoint to be set at the line with this(...) or super(...)
                // call in the constructor.
                method.instructions.insert(constructor.loadThis,
                        new LineNumberNode(constructor.lineForLoad, start));
            }
            method.instructions.insert(constructor.delegation, after);
            mv.addRedirection(new ConstructorArgsRedirection(start, visitedClassName,
                    constructor.args.name + "." + constructor.args.desc, after,
                    Type.getArgumentTypes(constructor.delegation.desc)));

            mv.addRedirection(new MethodRedirection(after, constructor.body.name + "." + constructor.body.desc,
                    Type.getReturnType(desc)));
        } else {
            mv.addRedirection(new MethodRedirection(new LabelNode(mv.getStartLabel()), name + "." + desc,
                    Type.getReturnType(desc)));
        }
        method.accept(mv);
        return null;
    }
}

From source file:dodola.anole.lib.InstantRunMethodVerifier.java

License:Apache License

/**
 * Verifies a method implementation against the blacklisted list of APIs.
 *
 * @param method the method to verify/* w w  w  .  j a v a2 s  .  c  o m*/
 * @return a {@link InstantRunVerifierStatus} instance or null if the method is not making any
 * blacklisted calls.
 */
public static InstantRunVerifierStatus verifyMethod(MethodNode method) {

    VerifierMethodVisitor mv = new VerifierMethodVisitor(method);
    method.accept(mv);
    return mv.incompatibleChange.or(InstantRunVerifierStatus.COMPATIBLE);
}

From source file:forgefix.ForgeFixTransformer.java

License:LGPL

@Override
public byte[] transform(String name, String transformedName, byte[] bytes) {
    if (bytes == null)
        return bytes;

    if (transformedName.equals("com.xcompwiz.mystcraft.world.gen.structure.ComponentVillageArchivistHouse")
            || (transformedName.equals(// www.  j a v  a 2 s .  c  o  m
                    "com.xcompwiz.mystcraft.world.gen.structure.ComponentScatteredFeatureSmallLibrary"))) {
        ClassNode classNode = new ClassNode();
        ClassReader classReader = new ClassReader(bytes);

        classReader.accept(classNode, 0);

        MethodNode vanillaMethod = null;
        for (MethodNode method : classNode.methods) {
            if (method.name.equals("generateStructureLectern")) {
                vanillaMethod = method;
            }
        }

        MethodNode moddedMethod = new MethodNode(ASM4, ACC_PROTECTED, "generateStructureLectern",
                getMethodDescriptor(BOOLEAN_TYPE), null, null);
        moddedMethod.desc = "(Lnet/minecraft/world/World;Lnet/minecraft/world/gen/structure/StructureBoundingBox;Ljava/util/Random;IIIIILnet/minecraftforge/common/ChestGenHooks;)Z";
        moddedMethod.instructions.add(new InsnNode(ICONST_0));
        moddedMethod.instructions.add(new InsnNode(IRETURN));

        if (moddedMethod != null) {
            classNode.methods.remove(vanillaMethod);
            moddedMethod.accept(classNode);

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

    return bytes;
}

From source file:fr.insalyon.telecom.jooflux.InvokeMethodAdapter.java

License:Mozilla Public License

@Override
public void visitEnd() {
    MethodNode methodNode = (MethodNode) this.mv;
    InvokeMethodTransformer invokeMethodTransformer = new InvokeMethodTransformer(null);
    invokeMethodTransformer.transform(methodNode);
    methodNode.accept(this.methodVisitor);
}

From source file:jaspex.speculation.newspec.FlowFrame.java

License:Open Source License

static void printCode(MethodNode mn, List<? extends Frame<?>> frames, Collection<FlowFrame> highlight,
        FlowFrame specialHighlight) {/*from  www. j ava2  s  .co  m*/
    if (!Log.isTraceEnabled())
        return;

    Textifier textifier = new Textifier();
    TraceMethodVisitor tmv = new TraceMethodVisitor(textifier);
    mn.accept(tmv);

    highlight = highlight != null ? highlight : new ArrayList<FlowFrame>();

    List<String> instructions = listGenericCast(textifier.getText());
    InsnList il = mn.instructions;

    int offset = mn.tryCatchBlocks.size();
    for (int i = 0; i < instructions.size(); i++) {
        int pos = i - offset;
        Frame<?> f = pos >= 0 && pos < frames.size() ? frames.get(pos) : null;
        String insn = pos < il.size() && pos >= 0
                ? il.get(pos).toString().replace("org.objectweb.asm.tree.", "")
                : null;
        String highlightColor = specialHighlight != null && specialHighlight.equals(f) ? "45"
                : highlight.contains(f) ? "41" : "32";
        Log.trace(pos + instructions.get(i).replace("\n", "") + " "
                + (f != null ? color(f.toString(), highlightColor) : "") + " (" + insn + ")");
    }
}