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:br.usp.each.saeg.badua.cli.Report.java

License:Open Source License

private void analyze(final MethodNode mn) {
    // do not analyze abstract methods
    if ((mn.access & Opcodes.ACC_ABSTRACT) != 0) {
        return;/*from  w w  w  . ja  v  a2 s.c o  m*/
    }
    // do not analyze static class initialization
    else if (mn.name.equals("<clinit>")) {
        return;
    }

    // we instrument the method to get the probe count
    final CoverageMethodTransformer mt = new CoverageMethodTransformer(className, this);
    final MethodInstrumenter mi = new MethodInstrumenter(mn.access, mn.name, mn.desc, mn.signature,
            toArray(mn.exceptions), NOP, mt);

    mn.accept(mi);

    final long[] dataArray = data.get(classId);
    final BitSet mnData;
    if (dataArray == null) {
        mnData = new BitSet();
    } else {
        mnData = BitSetUtils
                .valueOf(Arrays.copyOfRange(dataArray, classProbeCount - methodProbeCount, classProbeCount));
    }

    if (showClasses) {
        classCoveredDuas = classCoveredDuas + mnData.cardinality();
        classTotalDuas = classTotalDuas + mt.getDefUseChains().length;
    }

    if (showMethods) {
        System.out.println(String.format("%s.%s%s\t(%d/%d)", className, mn.name, mn.desc, mnData.cardinality(),
                mt.getDefUseChains().length));
    }
}

From source file:br.usp.each.saeg.badua.core.internal.instr.MethodInstrumenter.java

License:Open Source License

@Override
public void visitEnd() {
    if (next == null)
        return;/*from   www .  jav  a  2  s . co m*/

    final MethodNode original = new MethodNode(api, access, name, desc, signature, exceptions);
    final CodeSizeEvaluator sizeEval = new CodeSizeEvaluator(null);

    // 1. create a copy of the unmodified MethodNode
    accept(original);
    // 2. transform
    transform();
    // 3. evaluate new size
    accept(sizeEval);

    // size is fine (lower than 65535 bytes)
    if (sizeEval.getMaxSize() < 0xFFFF)
        accept(next);

    // size overflow
    else {
        sizeOverflow();
        original.accept(next);
    }
}

From source file:cl.inria.stiq.db.structure.analysis.Disassembler.java

License:Open Source License

public static DisassembledBehavior disassemble(IBehaviorInfo aBehavior) {
    IClassInfo theClass = aBehavior.getDeclaringType();
    MethodNode theMethodNode = null;
    ClassReader cr = null;//from w  ww .j  av  a 2s .c  om

    byte[] theBytecode = theClass.getBytecode().instrumented;
    if (theBytecode != null) {
        cr = new ClassReader(theBytecode);
        ClassNode cn = new ClassNode();
        cr.accept(cn, 0);

        // Search the requested method
        String theSig = aBehavior.getDescriptor();
        for (Iterator theIterator = cn.methods.iterator(); theIterator.hasNext();) {
            MethodNode theMethod = (MethodNode) theIterator.next();
            if (!theMethod.name.equals(aBehavior.getName()))
                continue;
            if (!theMethod.desc.equals(theSig))
                continue;
            theMethodNode = theMethod;
            break;
        }
    }

    if (theMethodNode == null)
        return null;

    MyTraceMethodVisitor theVisitor = new MyTraceMethodVisitor(cr);
    theMethodNode.accept(theVisitor);

    return new DisassembledBehavior(aBehavior, theVisitor.getInstructions());

}

From source file:co.paralleluniverse.fibers.instrument.InstrumentClass.java

License:Open Source License

@Override
public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature,
        final String[] exceptions) {
    SuspendableType markedSuspendable = null;
    if (suspendableInterface)
        markedSuspendable = SuspendableType.SUSPENDABLE_SUPER;
    if (markedSuspendable == null)
        markedSuspendable = classifier.isSuspendable(db, className, classEntry.getSuperName(),
                classEntry.getInterfaces(), name, desc, signature, exceptions);
    final SuspendableType setSuspendable = classEntry.check(name, desc);

    if (setSuspendable == null)
        classEntry.set(name, desc,/*from   w w w  .j a  va 2 s  .  c  om*/
                markedSuspendable != null ? markedSuspendable : SuspendableType.NON_SUSPENDABLE);

    final boolean suspendable = markedSuspendable == SuspendableType.SUSPENDABLE
            | setSuspendable == SuspendableType.SUSPENDABLE;

    if (checkAccess(access) && !isYieldMethod(className, name)) {
        if (isSynchronized(access)) {
            if (!db.isAllowMonitors())
                throw new UnableToInstrumentException("synchronization", className, name, desc);
            else
                db.log(LogLevel.WARNING, "Method %s#%s%s is synchronized", className, name, desc);
        }

        if (methods == null)
            methods = new ArrayList<MethodNode>();
        final MethodNode mn = new MethodNode(access, name, desc, signature, exceptions);

        //            if (suspendable) {
        //                if (db.isDebug())
        //                    db.log(LogLevel.INFO, "Method %s#%s suspendable: %s (markedSuspendable: %s setSuspendable: %s)", className, name, suspendable, markedSuspendable, setSuspendable);
        //
        //                methods.add(mn);
        //                return mn; // this causes the mn to be initialized
        //            } else { // look for @Suspendable or @DontInstrument annotation
        return new MethodVisitor(Opcodes.ASM4, mn) {
            private boolean susp = suspendable;
            private boolean commited = false;

            @Override
            public AnnotationVisitor visitAnnotation(String adesc, boolean visible) {
                if (adesc.equals(ANNOTATION_DESC))
                    susp = true;
                else if (adesc.equals(DONT_INSTRUMENT_ANNOTATION_DESC))
                    susp = false;

                return super.visitAnnotation(adesc, visible);
            }

            @Override
            public void visitCode() {
                commit();
                super.visitCode();
            }

            @Override
            public void visitEnd() {
                if (exception != null)
                    return;

                commit();
                try {
                    super.visitEnd();
                } catch (RuntimeException e) {
                    exception = e;
                }
            }

            private void commit() {
                if (commited)
                    return;
                commited = true;

                if (db.isDebug())
                    db.log(LogLevel.INFO,
                            "Method %s#%s suspendable: %s (markedSuspendable: %s setSuspendable: %s)",
                            className, name, susp, susp, setSuspendable);
                classEntry.set(name, desc,
                        susp ? SuspendableType.SUSPENDABLE : SuspendableType.NON_SUSPENDABLE);

                if (susp)
                    methods.add(mn);
                else {
                    MethodVisitor _mv = makeOutMV(mn);
                    _mv = new JSRInlinerAdapter(_mv, access, name, desc, signature, exceptions);
                    mn.accept(new MethodVisitor(Opcodes.ASM4, _mv) {
                        @Override
                        public void visitEnd() {
                            // don't call visitEnd on MV
                        }
                    }); // write method as-is
                    this.mv = _mv;
                }
            }
        };
        //            }
    }
    return super.visitMethod(access, name, desc, signature, exceptions);
}

From source file:co.paralleluniverse.fibers.instrument.InstrumentClass.java

License:Open Source License

@Override
@SuppressWarnings("CallToThreadDumpStack")
public void visitEnd() {
    if (exception != null)
        throw exception;

    classEntry.setRequiresInstrumentation(false);
    db.recordSuspendableMethods(className, classEntry);

    if (methods != null && !methods.isEmpty()) {
        if (alreadyInstrumented && !forceInstrumentation) {
            for (MethodNode mn : methods)
                mn.accept(makeOutMV(mn));
        } else {/* w  w w .ja  v  a 2 s  .c o m*/
            if (!alreadyInstrumented) {
                super.visitAnnotation(ALREADY_INSTRUMENTED_DESC, true);
                classEntry.setInstrumented(true);
            }

            for (MethodNode mn : methods) {
                final MethodVisitor outMV = makeOutMV(mn);
                try {
                    InstrumentMethod im = new InstrumentMethod(db, className, mn);
                    if (db.isDebug())
                        db.log(LogLevel.INFO, "About to instrument method %s#%s%s", className, mn.name,
                                mn.desc);

                    if (im.collectCodeBlocks()) {
                        if (mn.name.charAt(0) == '<')
                            throw new UnableToInstrumentException("special method", className, mn.name,
                                    mn.desc);
                        im.accept(outMV, hasAnnotation(mn));
                    } else {
                        db.log(LogLevel.INFO, "Nothing to instrument in method %s#%s%s", className, mn.name,
                                mn.desc);
                        mn.accept(outMV);
                    }

                } catch (AnalyzerException ex) {
                    ex.printStackTrace();
                    throw new InternalError(ex.getMessage());
                }
            }
        }
    } else {
        // if we don't have any suspendable methods, but our superclass is instrumented, we mark this class as instrumented, too.
        if (!alreadyInstrumented && classEntry.getSuperName() != null) {
            ClassEntry superClass = db.getClassEntry(classEntry.getSuperName());
            if (superClass != null && superClass.isInstrumented()) {
                super.visitAnnotation(ALREADY_INSTRUMENTED_DESC, true);
                classEntry.setInstrumented(true);
            }
        }
    }
    super.visitEnd();
}

From source file:com.alibaba.hotswap.processor.constructor.ConstructorVisitor.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public void visitEnd() {
    if (!isInterface) {
        ClassMeta classMeta = HotswapRuntime.getClassMeta(className);
        if (!HotswapRuntime.getClassInitialized(className)) {
            // The first time
            for (String mk : initKeys) {
                MethodNode node = initNodes.get(mk);
                node.accept(cv);

                classMeta.primaryInitNodes.put(mk, node);
                classMeta.primaryInitKeyList.add(mk);

                MethodMeta mm = new MethodMeta(node.access, node.name, node.desc, node.signature,
                        (String[]) (node.exceptions == null ? null : node.exceptions.toArray(new String[] {})));
                classMeta.refreshInitMeta(mm, false);
            }/*from  ww  w  . ja  v a 2s  .c om*/
            addEmptyUniformConstructor();
        } else {
            // Reload
            for (String mk : classMeta.primaryInitKeyList) {
                MethodNode node = initNodes.remove(mk);
                if (node != null) {
                    MethodMeta mm = new MethodMeta(node.access, node.name, node.desc, node.signature,
                            (String[]) (node.exceptions == null ? null
                                    : node.exceptions.toArray(new String[] {})));
                    classMeta.refreshInitMeta(mm, false);
                }

                node = classMeta.primaryInitNodes.get(mk);
                node.accept(cv);
            }

            addUniformConstructor(classMeta);
        }

        Iterator<Entry<String, MethodMeta>> iter = classMeta.initMetas.entrySet().iterator();
        while (iter.hasNext()) {
            Entry<String, MethodMeta> entry = iter.next();
            MethodMeta mm = entry.getValue();
            if (classMeta.loadedIndex > mm.loadedIndex && !classMeta.primaryInitKeyList.contains(mm.getKey())) {
                iter.remove();
            }
        }
    }
    super.visitEnd();
}

From source file:com.alibaba.hotswap.processor.v.VClassGenerateVisitor.java

License:Open Source License

private void processInitMethods() {
    ClassMeta classMeta = HotswapRuntime.getClassMeta(className);
    if (!HotswapRuntime.getClassInitialized(className)) {
        // The first time
        for (String mk : initKeys) {
            initNodes.get(mk).accept(cv);
        }//from  w  w w.j av a2 s  .  c  o m
    } else {
        // Reload
        for (String mk : classMeta.primaryInitKeyList) {
            MethodNode node = initNodes.remove(mk);
            if (node == null) {
                node = classMeta.primaryInitNodes.get(mk);
            }
            node.accept(cv);
        }

        for (MethodNode node : initNodes.values()) {
            node.accept(cv);
        }
    }
}

From source file:com.android.build.gradle.internal.incremental.ByteCodeUtils.java

License:Apache License

/**
 * Converts the given method to a String.
 *//*from  www. j a va  2  s .  c o  m*/
public static String textify(@NonNull MethodNode method) {
    Textifier textifier = new Textifier();
    TraceMethodVisitor trace = new TraceMethodVisitor(textifier);
    method.accept(trace);
    String ret = "";
    for (Object line : textifier.getText()) {
        ret += line;
    }
    return ret;
}

From source file:com.android.build.gradle.internal.incremental.IncrementalSupportVisitor.java

License:Apache License

/**
 * Insert Constructor specific logic({@link ConstructorRedirection} and
 * {@link ConstructorBuilder}) for constructor redirecting or
 * normal method redirecting ({@link MethodRedirection}) for other methods.
 *///from   ww w.  ja v a  2s. c  o 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 = checkNotNull(getMethodByNameInClass(name, desc, classNode),
            "Method found by visitor but not in the pre-parsed class node.");

    // does the method use blacklisted APIs.
    boolean hasIncompatibleChange = InstantRunMethodVerifier
            .verifyMethod(method) != InstantRunVerifierStatus.COMPATIBLE;

    if (hasIncompatibleChange || disableRedirectionForClass || !isAccessCompatibleWithInstantRun(access)
            || name.equals(ByteCodeUtils.CLASS_INITIALIZER)) {
        return defaultVisitor;
    } else {
        ArrayList<Type> args = new ArrayList<>(Arrays.asList(Type.getArgumentTypes(desc)));
        boolean isStatic = (access & Opcodes.ACC_STATIC) != 0;
        if (!isStatic) {
            args.add(0, Type.getType(Object.class));
        }

        // Install the Jsr/Ret inliner adapter, we have had reports of code still using the
        // Jsr/Ret deprecated byte codes.
        // see https://code.google.com/p/android/issues/detail?id=220019
        JSRInlinerAdapter jsrInlinerAdapter = new JSRInlinerAdapter(defaultVisitor, access, name, desc,
                signature, exceptions);

        ISMethodVisitor mv = new ISMethodVisitor(jsrInlinerAdapter, access, name, desc);
        if (name.equals(ByteCodeUtils.CONSTRUCTOR)) {
            Constructor constructor = ConstructorBuilder.build(visitedClassName, method);
            LabelNode start = 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));
            }
            mv.addRedirection(new ConstructorRedirection(start, constructor, args));
        } else {
            mv.addRedirection(new MethodRedirection(new LabelNode(mv.getStartLabel()), name + "." + desc, args,
                    Type.getReturnType(desc)));
        }
        method.accept(mv);
        return null;
    }
}

From source file:com.android.build.gradle.internal.incremental.IncrementalSupportVisitorTest.java

License:Apache License

@Nullable
public static String findOwnerForMethodDispatch(@NonNull MethodNode methodNode,
        @NonNull String dispatchedMethod, @Nullable String dispatchedDesc) {
    AtomicReference<String> ownerRef = new AtomicReference<>(null);
    MethodVisitor methodVisitor = new MethodVisitor(Opcodes.ASM5) {
        @Override//  w w  w.  jav  a 2  s. co  m
        public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {
            super.visitMethodInsn(opcode, owner, name, desc, itf);
            if (name.equals(dispatchedMethod) && (dispatchedDesc == null || dispatchedDesc.equals(desc))) {
                ownerRef.set(owner);
            }
        }
    };
    methodNode.accept(methodVisitor);
    return ownerRef.get();
}