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:naftoreiclag.dontdigleft.transformer.ResizePlayerBoudingBox.java

License:Open Source License

@Override
public byte[] transform(String name, String transformedName, byte[] basicClass) {
    if (name.equals("net.minecraft.entity.player.EntityPlayer") || name.equals("xl")) {
        ClassNode classNode = new ClassNode();
        ClassReader classReader = new ClassReader(basicClass);

        classReader.accept(classNode, 0);

        MethodNode mv = new MethodNode(ASM4, ACC_PROTECTED, "setSize", "(FF)V", null, null);

        mv.visitCode();//from   w  ww .jav  a 2  s. c o  m
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitVarInsn(FLOAD, 1);
        mv.visitLdcInsn(new Float("0.6"));
        mv.visitInsn(FCMPL);
        Label l1 = new Label();
        mv.visitJumpInsn(IFNE, l1);
        mv.visitVarInsn(FLOAD, 2);
        mv.visitLdcInsn(new Float("1.8"));
        mv.visitInsn(FCMPL);
        mv.visitJumpInsn(IFNE, l1);
        Label l2 = new Label();
        mv.visitLabel(l2);
        mv.visitLdcInsn(new Float("0.6"));
        mv.visitVarInsn(FSTORE, 1);
        Label l3 = new Label();
        mv.visitLabel(l3);
        mv.visitLdcInsn(new Float("0.6"));
        mv.visitVarInsn(FSTORE, 2);
        mv.visitLabel(l1);
        mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
        mv.visitVarInsn(ALOAD, 0);
        mv.visitVarInsn(FLOAD, 1);
        mv.visitVarInsn(FLOAD, 2);
        mv.visitMethodInsn(INVOKESPECIAL, "net/minecraft/entity/Entity", "setSize", "(FF)V");
        Label l4 = new Label();
        mv.visitLabel(l4);
        mv.visitInsn(RETURN);
        Label l5 = new Label();
        mv.visitLabel(l5);
        mv.visitLocalVariable("this", "Lnet/minecraft/entity/player/EntityPlayer;", null, l0, l5, 0);
        mv.visitLocalVariable("par1", "F", null, l0, l5, 1);
        mv.visitLocalVariable("par2", "F", null, l0, l5, 2);
        mv.visitMaxs(3, 3);
        mv.visitEnd();

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

        return cw.toByteArray();
    } else {
        return basicClass;
    }
}

From source file:net.enilink.composition.asm.ExtendedClassNode.java

License:Open Source License

@SuppressWarnings("unchecked")
public ExtendedMethod addExtendedMethod(Method method, ClassDefiner definer) throws Exception {
    Object key = getKey(method);/*from   w  ww.ja v a  2s . c o m*/

    ExtendedMethod extendedMethod = extendedMethods.get(key);
    if (extendedMethod == null) {
        extendedMethod = new ExtendedMethod(this, method);

        MethodNode faceNode = AsmUtils.getClassInfo(method.getDeclaringClass().getName(), definer)
                .getMethod(org.objectweb.asm.commons.Method.getMethod(method));
        faceNode.accept(extendedMethod);

        methods.add(extendedMethod);
        extendedMethods.put(key, extendedMethod);

        extendedMethod.access &= ~Opcodes.ACC_ABSTRACT;
    }

    return extendedMethod;
}

From source file:net.malisis.core.asm.AsmUtils.java

License:Open Source License

public static String getMethodNodeAsString(MethodNode methodNode) {
    Printer printer = new Textifier();
    TraceMethodVisitor methodPrinter = new TraceMethodVisitor(printer);

    methodNode.accept(methodPrinter);

    StringWriter sw = new StringWriter();
    printer.print(new PrintWriter(sw));
    printer.getText().clear();//from   w  w  w  .  ja  v a 2  s  .  c  o  m

    return sw.toString();
}

From source file:nova.core.wrapper.mc.forge.v17.asm.lib.ASMHelper.java

License:Open Source License

public static void replaceMethodCode(MethodNode original, MethodNode replacement) {
    original.instructions.clear();/* ww w. j a v  a 2 s.  c  o m*/
    if (original.localVariables != null) {
        original.localVariables.clear();
    }
    if (original.tryCatchBlocks != null) {
        original.tryCatchBlocks.clear();
    }
    replacement.accept(original);
}

From source file:org.anon.smart.base.stt.asm.ASMSTTWriter.java

License:Open Source License

public Object createMethod(STTVisitor sttvisit, STTDescriptor stt, Object mthd) {
    ASMClazzContext cctx = (ASMClazzContext) sttvisit.clazzContext();
    ClassVisitor visit = cctx.visitor();
    MethodNode nde = (MethodNode) mthd;
    if (!nde.name.equals(CONSTRUCTOR_NAME)) //ignore constructor
    {//from  www  .  j a v a 2 s.c  o m
        String[] exceptions = new String[nde.exceptions.size()];
        nde.exceptions.toArray(exceptions); //TODO check the reference for this
        MethodVisitor mv = visit.visitMethod(nde.access, nde.name, nde.desc, nde.signature, exceptions);
        nde.instructions.resetLabels();
        nde.accept(new RemappingMethodAdapter(nde.access, nde.desc, mv,
                new SimpleRemapper(stt.reader().sttname(), cctx.name())));
        return nde;
    }
    return null;
}

From source file:org.apache.commons.weaver.privilizer.BlueprintingVisitor.java

License:Apache License

private String importMethod(final Pair<Type, Method> key) {
    if (importedMethods.containsKey(key)) {
        return importedMethods.get(key);
    }//from w  w  w  . ja v a 2 s  .c o  m
    final String result = new StringBuilder(key.getLeft().getInternalName().replace('/', '_')).append("$$")
            .append(key.getRight().getName()).toString();
    importedMethods.put(key, result);
    privilizer().env.debug("importing %s#%s as %s", key.getLeft().getClassName(), key.getRight(), result);
    final int access = Opcodes.ACC_PRIVATE + Opcodes.ACC_STATIC + Opcodes.ACC_SYNTHETIC;

    final MethodNode source = typeInfo(key.getLeft()).methods.get(key.getRight());

    final String[] exceptions = source.exceptions.toArray(ArrayUtils.EMPTY_STRING_ARRAY);

    // non-public fields accessed
    final Set<FieldAccess> fieldAccesses = new LinkedHashSet<>();

    source.accept(new MethodVisitor(Privilizer.ASM_VERSION) {
        @Override
        public void visitFieldInsn(final int opcode, final String owner, final String name, final String desc) {
            final FieldAccess fieldAccess = fieldAccess(Type.getObjectType(owner), name);

            super.visitFieldInsn(opcode, owner, name, desc);
            if (!Modifier.isPublic(fieldAccess.access)) {
                fieldAccesses.add(fieldAccess);
            }
        }
    });

    final MethodNode withAccessibleAdvice = new MethodNode(access, result, source.desc, source.signature,
            exceptions);

    // spider own methods:
    MethodVisitor mv = new NestedMethodInvocationHandler(withAccessibleAdvice, key); //NOPMD

    if (!fieldAccesses.isEmpty()) {
        mv = new AccessibleAdvisor(mv, access, result, source.desc, new ArrayList<>(fieldAccesses));
    }
    source.accept(mv);

    // private can only be called by other privileged methods, so no need to mark as privileged
    if (!Modifier.isPrivate(source.access)) {
        withAccessibleAdvice.visitAnnotation(Type.getType(Privileged.class).getDescriptor(), false).visitEnd();
    }
    withAccessibleAdvice.accept(this.cv);

    return result;
}

From source file:org.apache.drill.exec.compile.MergeAdapter.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public void visitEnd() {

    // add all the fields of the class we're going to merge.
    for (Iterator<?> it = classToMerge.fields.iterator(); it.hasNext();) {
        ((FieldNode) it.next()).accept(this);
    }/*from  w w w . ja  v  a  2s.c o  m*/

    // add all the methods that we to include.
    for (Iterator<?> it = classToMerge.methods.iterator(); it.hasNext();) {
        MethodNode mn = (MethodNode) it.next();

        if (mn.name.equals("<init>")) {
            continue;
        }

        String[] exceptions = new String[mn.exceptions.size()];
        mn.exceptions.toArray(exceptions);
        MethodVisitor mv = cv.visitMethod(mn.access | Modifier.FINAL, mn.name, mn.desc, mn.signature,
                exceptions);

        mn.instructions.resetLabels();

        // mn.accept(new RemappingMethodAdapter(mn.access, mn.desc, mv, new
        // SimpleRemapper("org.apache.drill.exec.compile.ExampleTemplate", "Bunky")));
        ClassSet top = set;
        while (top.parent != null) {
            top = top.parent;
        }
        mn.accept(new RemappingMethodAdapter(mn.access, mn.desc, mv,
                new SimpleRemapper(top.precompiled.slash, top.generated.slash)));

    }
    super.visitEnd();
}

From source file:org.evosuite.graphs.cfg.CFGMethodAdapter.java

License:Open Source License

/** {@inheritDoc} */
@Override/*from   w  w w  . j ava 2  s. c om*/
public void visitEnd() {
    logger.debug("Creating CFG of " + className + "." + methodName);
    boolean isExcludedMethod = excludeMethod || EXCLUDE.contains(methodName);
    boolean isMainMethod = plain_name.equals("main") && Modifier.isStatic(access);

    List<MethodInstrumentation> instrumentations = new ArrayList<MethodInstrumentation>();
    if (DependencyAnalysis.shouldInstrument(className, methodName)) {
        if (ArrayUtil.contains(Properties.CRITERION, Criterion.DEFUSE)
                || ArrayUtil.contains(Properties.CRITERION, Criterion.ALLDEFS)) {
            instrumentations.add(new BranchInstrumentation());
            instrumentations.add(new DefUseInstrumentation());
        } else if (ArrayUtil.contains(Properties.CRITERION, Criterion.MUTATION)
                || ArrayUtil.contains(Properties.CRITERION, Criterion.WEAKMUTATION)
                || ArrayUtil.contains(Properties.CRITERION, Criterion.ONLYMUTATION)
                || ArrayUtil.contains(Properties.CRITERION, Criterion.STRONGMUTATION)) {
            instrumentations.add(new BranchInstrumentation());
            instrumentations.add(new MutationInstrumentation());
        } else {
            instrumentations.add(new BranchInstrumentation());
        }
    } else {
        //instrumentations.add(new BranchInstrumentation());
    }

    boolean executeOnMain = false;
    boolean executeOnExcluded = false;

    for (MethodInstrumentation instrumentation : instrumentations) {
        executeOnMain = executeOnMain || instrumentation.executeOnMainMethod();
        executeOnExcluded = executeOnExcluded || instrumentation.executeOnExcludedMethods();
    }

    // super.visitEnd();
    // Generate CFG of method
    MethodNode mn = (AnnotatedMethodNode) mv;

    boolean checkForMain = false;
    if (Properties.CONSIDER_MAIN_METHODS) {
        checkForMain = true;
    } else {
        checkForMain = !isMainMethod || executeOnMain;
    }

    // Only instrument if the method is (not main and not excluded) or (the
    // MethodInstrumentation wants it anyway)
    if (checkForMain && (!isExcludedMethod || executeOnExcluded) && (access & Opcodes.ACC_ABSTRACT) == 0
            && (access & Opcodes.ACC_NATIVE) == 0) {

        logger.info("Analyzing method " + methodName + " in class " + className);

        // MethodNode mn = new CFGMethodNode((MethodNode)mv);
        // System.out.println("Generating CFG for "+ className+"."+mn.name +
        // " ("+mn.desc +")");

        BytecodeAnalyzer bytecodeAnalyzer = new BytecodeAnalyzer();
        logger.info("Generating CFG for method " + methodName);

        try {

            bytecodeAnalyzer.analyze(classLoader, className, methodName, mn);
            logger.trace("Method graph for " + className + "." + methodName + " contains "
                    + bytecodeAnalyzer.retrieveCFGGenerator().getRawGraph().vertexSet().size() + " nodes for "
                    + bytecodeAnalyzer.getFrames().length + " instructions");
            // compute Raw and ActualCFG and put both into GraphPool
            bytecodeAnalyzer.retrieveCFGGenerator().registerCFGs();
            logger.info("Created CFG for method " + methodName);

            if (DependencyAnalysis.shouldInstrument(className, methodName)) {
                if (!methods.get(classLoader).containsKey(className))
                    methods.get(classLoader).put(className, new HashSet<String>());

                // add the actual instrumentation
                logger.info("Instrumenting method " + methodName + " in class " + className);
                for (MethodInstrumentation instrumentation : instrumentations)
                    instrumentation.analyze(classLoader, mn, className, methodName, access);

                handleBranchlessMethods();
                String id = className + "." + methodName;
                if (isUsable()) {
                    methods.get(classLoader).get(className).add(id);
                    logger.debug("Counting: " + id);
                }
            }
        } catch (AnalyzerException e) {
            logger.error("Analyzer exception while analyzing " + className + "." + methodName + ": " + e);
            e.printStackTrace();
        }

    } else {
        logger.debug("NOT Creating CFG of " + className + "." + methodName + ": " + checkForMain + ", "
                + ((!isExcludedMethod || executeOnExcluded)) + ", " + ((access & Opcodes.ACC_ABSTRACT) == 0)
                + ", " + ((access & Opcodes.ACC_NATIVE) == 0));
        super.visitEnd();
    }
    mn.accept(next);
}

From source file:org.evosuite.instrumentation.error.ErrorConditionMethodAdapter.java

License:Open Source License

/** {@inheritDoc} */
@Override
public void visitEnd() {
    MethodNode mn = (MethodNode) mv;
    mn.accept(next);
}

From source file:org.glowroot.agent.weaving.WeavingClassVisitor.java

License:Apache License

@RequiresNonNull("type")
private void addMixin(MixinType mixinType) {
    ClassReader cr = new ClassReader(mixinType.implementationBytes());
    ClassNode cn = new ClassNode();
    cr.accept(cn, ClassReader.EXPAND_FRAMES);
    // SuppressWarnings because generics are explicitly removed from asm binaries
    // see http://forge.ow2.org/tracker/?group_id=23&atid=100023&func=detail&aid=316377
    @SuppressWarnings("unchecked")
    List<FieldNode> fieldNodes = cn.fields;
    for (FieldNode fieldNode : fieldNodes) {
        fieldNode.accept(this);
    }//from w  w w .  ja  v a 2s .co  m
    // SuppressWarnings because generics are explicitly removed from asm binaries
    @SuppressWarnings("unchecked")
    List<MethodNode> methodNodes = cn.methods;
    for (MethodNode mn : methodNodes) {
        if (mn.name.equals("<init>")) {
            continue;
        }
        // SuppressWarnings because generics are explicitly removed from asm binaries
        @SuppressWarnings("unchecked")
        String[] exceptions = Iterables.toArray(mn.exceptions, String.class);
        MethodVisitor mv = cw.visitMethod(mn.access, mn.name, mn.desc, mn.signature, exceptions);
        mn.accept(new RemappingMethodAdapter(mn.access, mn.desc, mv,
                new SimpleRemapper(cn.name, type.getInternalName())));
    }
}