Example usage for org.objectweb.asm MethodVisitor visitMaxs

List of usage examples for org.objectweb.asm MethodVisitor visitMaxs

Introduction

In this page you can find the example usage for org.objectweb.asm MethodVisitor visitMaxs.

Prototype

public void visitMaxs(final int maxStack, final int maxLocals) 

Source Link

Document

Visits the maximum stack size and the maximum number of local variables of the method.

Usage

From source file:com.gmail.socraticphoenix.occurence.wrappers.BytecodeEventListenerGeneration.java

License:Open Source License

public static List<EventListenerWrapper> of(Object listener, File dir) {
    List<Class> cachedListeners = BytecodeEventListenerGeneration.listenerCache.get(listener.getClass());
    List<EventListenerWrapper> wrappers = new ArrayList<>();

    if (cachedListeners != null) {
        cachedListeners.forEach(c -> {
            try {
                wrappers.add((EventListenerWrapper) c.getConstructor(Object.class).newInstance(listener));
            } catch (InstantiationException | IllegalAccessException | NoSuchMethodException
                    | InvocationTargetException e) {

            }/*w  ww  .j  ava 2  s.c o m*/
        });
    } else {
        try {
            Type listenerType = Type.getType(listener.getClass());
            Map<String, ClassWriter> classes = new LinkedHashMap<>();
            Map<String, String> binaryNames = new LinkedHashMap<>();

            List<Method> methods = new ArrayList<>();
            for (Method method : listener.getClass().getDeclaredMethods()) {
                if (method.isAnnotationPresent(EventListener.class)) {
                    EventListenerWrapper.verify(method, listener);
                    methods.add(method);
                }
            }

            for (Method method : methods) {
                int event = BytecodeEventListenerGeneration.isolateEvent(method);
                int eventVarIndex = event + 1;
                int[] jumpTable = BytecodeEventListenerGeneration.jumpTable(eventVarIndex,
                        method.getParameters());

                Parameter eventParam = method.getParameters()[event];
                Class eventClass = eventParam.getType();
                Type eventType = Type.getType(eventClass);

                String name = BytecodeEventListenerGeneration.name(method);
                ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
                classes.put(name, writer);

                String internalName = BytecodeEventListenerGeneration.listener(
                        method.getAnnotation(EventListener.class), eventClass, listener, method, writer);
                binaryNames.put(name, internalName.replace('/', '.'));

                if (!eventType.equals(BytecodeEventListenerGeneration.eventType)) {
                    MethodVisitor handleDelegateMethod = writer.visitMethod(ACC_PUBLIC | ACC_FINAL, "handle",
                            Type.getMethodDescriptor(Type.VOID_TYPE, BytecodeEventListenerGeneration.eventType),
                            null, null);
                    handleDelegateMethod.visitCode();
                    handleDelegateMethod.visitVarInsn(ALOAD, 0);
                    handleDelegateMethod.visitVarInsn(ALOAD, 1);
                    BytecodeEventListenerGeneration.checkCast(eventType, handleDelegateMethod);
                    handleDelegateMethod.visitMethodInsn(INVOKEVIRTUAL, internalName, "handle",
                            Type.getMethodDescriptor(Type.VOID_TYPE, eventType), false);
                    handleDelegateMethod.visitInsn(RETURN);
                    handleDelegateMethod.visitMaxs(0, 0);
                    handleDelegateMethod.visitEnd();
                }

                MethodVisitor handleMethod = writer.visitMethod(ACC_PUBLIC | ACC_FINAL, "handle",
                        Type.getMethodDescriptor(Type.VOID_TYPE, eventType), null, null);
                handleMethod.visitCode();
                if (method.isAnnotationPresent(Exclude.class)) {
                    BytecodeEventListenerGeneration.exclude(method.getAnnotation(Exclude.class), 1,
                            handleMethod);
                } else if (method.isAnnotationPresent(Include.class)) {
                    BytecodeEventListenerGeneration.include(method.getAnnotation(Include.class), 1,
                            handleMethod);
                }

                if (method.isAnnotationPresent(Cancelled.class)) {
                    BytecodeEventListenerGeneration.cancelled(method.getAnnotation(Cancelled.class), 1,
                            eventClass, handleMethod);
                }

                for (int i = 0; i < method.getParameters().length; i++) {
                    Parameter parameter = method.getParameters()[i];
                    JavaFilledGenerics generics = parameter.getParameterizedType() instanceof ParameterizedType
                            ? JavaFilledGenerics.of((ParameterizedType) parameter.getParameterizedType())
                            : JavaFilledGenerics.empty();
                    int var = i + 1;
                    Annotation annotation = BytecodeEventListenerGeneration.isolateAnnotation(parameter);
                    if (annotation instanceof AllCauses) {
                        AllCauses allCauses = (AllCauses) annotation;
                        Class clazz = generics.getFilled().isEmpty() ? Object.class
                                : generics.getFilled().get(0).type().getRepresented().orElse(Object.class);
                        BytecodeEventListenerGeneration.allCauses(allCauses, clazz, jumpTable[var], 1,
                                handleMethod);
                    } else if (annotation instanceof AllContexts) {
                        AllContexts allContexts = (AllContexts) annotation;

                        JavaNamespace.Filled target = generics.getFilled().isEmpty()
                                ? JavaNamespace.of(Object.class).fill()
                                : generics.getFilled().get(0).type();
                        Class clazz = target.getRepresented().orElse(Object.class);

                        if (!allContexts.value()) {
                            BytecodeEventListenerGeneration.allContexts(allContexts, false, parameter.getType(),
                                    jumpTable[var], 1, handleMethod);
                        } else if (clazz == Pair.class) {
                            Class a = target.getFilledGenerics().getFilled().isEmpty() ? Object.class
                                    : target.getFilledGenerics().getFilled().get(0).type().getRepresented()
                                            .orElse(Object.class);
                            Class b = target.getFilledGenerics().getFilled().size() <= 1 ? Object.class
                                    : target.getFilledGenerics().getFilled().get(1).type().getRepresented()
                                            .orElse(Object.class);
                            if (a == String.class) {
                                BytecodeEventListenerGeneration.allContexts(allContexts, true, b,
                                        jumpTable[var], 1, handleMethod);
                            } else {
                                BytecodeEventListenerGeneration.allContexts(allContexts, false,
                                        parameter.getType(), jumpTable[var], 1, handleMethod);
                            }
                        } else {
                            BytecodeEventListenerGeneration.allContexts(allContexts, false, parameter.getType(),
                                    jumpTable[var], 1, handleMethod);
                        }
                    } else if (annotation instanceof FirstCause) {
                        FirstCause firstCause = (FirstCause) annotation;
                        BytecodeEventListenerGeneration.firstCause(firstCause, parameter.getType(),
                                jumpTable[var], 1, handleMethod);
                    } else if (annotation instanceof FirstContext) {
                        FirstContext firstContext = (FirstContext) annotation;
                        if (!firstContext.value()) {
                            BytecodeEventListenerGeneration.firstContext(firstContext, false,
                                    parameter.getType(), jumpTable[var], 1, handleMethod);
                        } else if (parameter.getType() == Pair.class) {
                            Class a = generics.getFilled().isEmpty() ? Object.class
                                    : generics.getFilled().get(0).type().getRepresented().orElse(Object.class);
                            Class b = generics.getFilled().size() <= 1 ? Object.class
                                    : generics.getFilled().get(1).type().getRepresented().orElse(Object.class);
                            if (a == String.class) {
                                BytecodeEventListenerGeneration.firstContext(firstContext, true, b,
                                        jumpTable[var], 1, handleMethod);
                            } else {
                                BytecodeEventListenerGeneration.firstContext(firstContext, false,
                                        parameter.getType(), jumpTable[var], 1, handleMethod);
                            }
                        } else {
                            BytecodeEventListenerGeneration.firstContext(firstContext, false,
                                    parameter.getType(), jumpTable[var], 1, handleMethod);
                        }
                    } else if (annotation instanceof LastCause) {
                        LastCause lastCause = (LastCause) annotation;
                        BytecodeEventListenerGeneration.lastCause(lastCause, parameter.getType(),
                                jumpTable[var], 1, handleMethod);
                    } else if (annotation instanceof LastContext) {
                        LastContext lastContext = (LastContext) annotation;
                        if (!lastContext.value()) {
                            BytecodeEventListenerGeneration.lastContext(lastContext, false, parameter.getType(),
                                    jumpTable[var], 1, handleMethod);
                        } else if (parameter.getType() == Pair.class) {
                            Class a = generics.getFilled().isEmpty() ? Object.class
                                    : generics.getFilled().get(0).type().getRepresented().orElse(Object.class);
                            Class b = generics.getFilled().size() <= 1 ? Object.class
                                    : generics.getFilled().get(1).type().getRepresented().orElse(Object.class);
                            if (a == String.class) {
                                BytecodeEventListenerGeneration.lastContext(lastContext, true, b,
                                        jumpTable[var], 1, handleMethod);
                            } else {
                                BytecodeEventListenerGeneration.lastContext(lastContext, false,
                                        parameter.getType(), jumpTable[var], 1, handleMethod);
                            }
                        } else {
                            BytecodeEventListenerGeneration.lastContext(lastContext, false, parameter.getType(),
                                    jumpTable[var], 1, handleMethod);
                        }
                    } else if (annotation instanceof GetContext) {
                        GetContext getContext = (GetContext) annotation;
                        BytecodeEventListenerGeneration.getContext(getContext, parameter.getName(),
                                parameter.getType(), jumpTable[var], 1, handleMethod);
                    } else if (annotation instanceof Get) {
                        Get get = (Get) annotation;
                        BytecodeEventListenerGeneration.get(get, parameter, eventClass, jumpTable[var], 1,
                                handleMethod);
                    }
                }

                handleMethod.visitVarInsn(ALOAD, 0);
                handleMethod.visitFieldInsn(GETFIELD, internalName, "listener", listenerType.getDescriptor());
                for (int i = 0; i < method.getParameters().length; i++) {
                    handleMethod.visitVarInsn(ALOAD, jumpTable[i + 1]);
                }
                handleMethod.visitMethodInsn(INVOKEVIRTUAL, listenerType.getInternalName(), method.getName(),
                        Type.getType(method).getDescriptor(), false);
                handleMethod.visitInsn(RETURN);
                handleMethod.visitMaxs(0, 0);
                handleMethod.visitEnd();
            }

            List<Class> cache = BytecodeEventListenerGeneration.listenerCache.get(listener.getClass());
            if (cache == null) {
                cache = new ArrayList<>();
                BytecodeEventListenerGeneration.listenerCache.put(listener.getClass(), cache);
            }

            for (Map.Entry<String, ClassWriter> finished : classes.entrySet()) {
                ClassWriter visitor = finished.getValue();
                visitor.visitEnd();

                byte[] clazz = visitor.toByteArray();
                if (dir != null) {
                    File target = new File(dir, binaryNames.get(finished.getKey()) + ".class");
                    try {
                        target.getAbsoluteFile().getParentFile().mkdirs();
                        target.createNewFile();
                        FileOutputStream stream = new FileOutputStream(target);
                        stream.write(clazz);
                        stream.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
                Class eventListenerClass = EventListenerClassLoader.INSTANCE
                        .defineClass(binaryNames.get(finished.getKey()), clazz);
                cache.add(eventListenerClass);
                EventListenerWrapper instance = (EventListenerWrapper) eventListenerClass
                        .getConstructor(Object.class).newInstance(listener);
                wrappers.add(instance);
            }

        } catch (NoSuchMethodException | InstantiationException | InvocationTargetException
                | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    return wrappers;
}

From source file:com.gmail.socraticphoenix.occurence.wrappers.BytecodeEventListenerGeneration.java

License:Open Source License

public static String listener(EventListener eventListener, Class eventClass, Object listener, Method method,
        ClassVisitor visitor) {//  w  w  w .j av a  2 s.  c  om
    Type listenerType = Type.getType(listener.getClass());
    Type eventType = Type.getType(eventClass);
    String internalImplName = listenerType.getInternalName() + "$listener$" + method.getName() + "$"
            + BytecodeEventListenerGeneration.index++;
    String simpleName = listener.getClass().getName() + "#" + method.getName() + "("
            + Stream.of(method.getParameters()).map(p -> p.getType().getSimpleName())
                    .reduce((a, b) -> a + ", " + b).orElse("")
            + ")";

    visitor.visit(V1_8, ACC_PUBLIC | ACC_SYNTHETIC | ACC_FINAL, internalImplName, null,
            BytecodeEventListenerGeneration.objectType.getInternalName(),
            new String[] { BytecodeEventListenerGeneration.eventWrapperType.getInternalName() });
    visitor.visitField(ACC_PRIVATE | ACC_FINAL, "listener", listenerType.getDescriptor(), null, null)
            .visitEnd();

    MethodVisitor constructor = visitor.visitMethod(ACC_PUBLIC, "<init>",
            Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Object.class)), null, null);
    constructor.visitParameter("listener", ACC_FINAL);
    constructor.visitCode();
    constructor.visitVarInsn(ALOAD, 0);
    constructor.visitMethodInsn(INVOKESPECIAL, BytecodeEventListenerGeneration.objectType.getInternalName(),
            "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false);
    constructor.visitVarInsn(ALOAD, 0);
    constructor.visitVarInsn(ALOAD, 1);
    constructor.visitTypeInsn(CHECKCAST, listenerType.getInternalName());
    constructor.visitFieldInsn(PUTFIELD, internalImplName, "listener", listenerType.getDescriptor());
    constructor.visitInsn(RETURN);
    constructor.visitMaxs(0, 0);
    constructor.visitEnd();

    MethodVisitor name = visitor.visitMethod(ACC_PUBLIC, "name",
            Type.getMethodDescriptor(Type.getType(String.class)), null, null);
    name.visitLdcInsn(simpleName);
    name.visitInsn(ARETURN);
    name.visitMaxs(0, 0);
    name.visitEnd();

    MethodVisitor priority = visitor.visitMethod(ACC_PUBLIC | ACC_FINAL, "priority",
            BytecodeEventListenerGeneration.priorityMethod.getDescriptor(), null, null);
    priority.visitCode();
    priority.visitLdcInsn(eventListener.value());
    priority.visitInsn(IRETURN);
    priority.visitMaxs(0, 0);
    priority.visitEnd();

    MethodVisitor getListener = visitor.visitMethod(ACC_PUBLIC | ACC_FINAL, "listener",
            BytecodeEventListenerGeneration.listenerMethod.getDescriptor(), null, null);
    getListener.visitVarInsn(ALOAD, 0);
    getListener.visitFieldInsn(GETFIELD, internalImplName, "listener", listenerType.getDescriptor());
    getListener.visitInsn(ARETURN);
    getListener.visitMaxs(0, 0);
    getListener.visitEnd();

    MethodVisitor event = visitor.visitMethod(ACC_PUBLIC | ACC_FINAL, "mainEvent",
            BytecodeEventListenerGeneration.mainEventMethod.getDescriptor(), null, null);
    event.visitCode();
    event.visitLdcInsn(eventType);
    event.visitInsn(ARETURN);
    event.visitMaxs(0, 0);
    event.visitEnd();

    return internalImplName;
}

From source file:com.google.code.jconts.instrument.gen.ComputationClassGenerator.java

License:Apache License

private void generateConstructor(ClassVisitor cv) {
    final String name = info.computationClassName;
    final Type outerType = Type.getObjectType(info.owner);

    // Constructor have form either <init>(OuterClass this$0, State state)
    // or <init>(State state)
    String ctorDesc;//from   ww w .  j  ava 2 s.  c  o  m
    if (info.isStatic()) {
        ctorDesc = Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { info.stateType });
    } else {
        cv.visitField(Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL, "this$0", 'L' + info.owner + ';', null, null);

        ctorDesc = Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { outerType, info.stateType });
    }

    // Generate constructor
    MethodVisitor mv = cv.visitMethod(0, CTOR_NAME, ctorDesc, null, null);
    mv.visitCode();
    Label start = new Label();
    Label end = new Label();
    mv.visitLabel(start);

    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, OBJECT_NAME, CTOR_NAME, DEFAULT_CTOR_DESC);

    // Save state field
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitVarInsn(Opcodes.ALOAD, 1 + info.thisOffset);
    mv.visitFieldInsn(Opcodes.PUTFIELD, name, "state", stateDesc);

    // Save outer this
    if (!info.isStatic()) {
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitVarInsn(Opcodes.ALOAD, 1);
        mv.visitFieldInsn(Opcodes.PUTFIELD, name, "this$0", outerType.getDescriptor());
    }
    mv.visitInsn(Opcodes.RETURN);
    mv.visitLabel(end);

    mv.visitLocalVariable("this", 'L' + name + ';', signature, start, end, 0);
    if (!info.isStatic()) {
        mv.visitLocalVariable("this$0", outerType.getDescriptor(), null, start, end, 1);
    }
    mv.visitLocalVariable("state", stateDesc, null, start, end, 1 + info.thisOffset);

    mv.visitMaxs(2, 2 + info.thisOffset);
    mv.visitEnd();
}

From source file:com.google.code.jconts.instrument.gen.ComputationClassGenerator.java

License:Apache License

private void generateExecute(ClassVisitor cv) {
    final String name = info.computationClassName;
    final Type outerType = Type.getObjectType(info.owner);

    // Generate execute(Continuation<T> cont);
    MethodVisitor mv = cv.visitMethod(Opcodes.ACC_FINAL | Opcodes.ACC_PUBLIC, COMPUTATION_EXECUTE_NAME,
            COMPUTATION_EXECUTE_DESC, executeSignature(), null);
    mv.visitCode();//ww w .  j av a2 s .co m
    Label start = new Label();
    Label end = new Label();
    mv.visitLabel(start);

    // Load outer this
    if (!info.isStatic()) {
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitFieldInsn(Opcodes.GETFIELD, name, "this$0", outerType.getDescriptor());
    }

    // Load state field
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitFieldInsn(Opcodes.GETFIELD, name, "state", stateDesc);

    // state.continuation = continuation
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitFieldInsn(Opcodes.GETFIELD, name, "state", stateDesc);
    mv.visitVarInsn(Opcodes.ALOAD, 1);
    mv.visitFieldInsn(Opcodes.PUTFIELD, info.stateClassName, CONTINUATION_FIELD, CONTINUATION_DESC);

    // Initial state (0)
    mv.visitIntInsn(Opcodes.BIPUSH, 0);
    mv.visitMethodInsn(info.isStatic() ? Opcodes.INVOKESTATIC : Opcodes.INVOKEVIRTUAL, info.owner,
            info.name + "$async",
            Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { info.stateType, Type.INT_TYPE }));

    mv.visitInsn(Opcodes.RETURN);
    mv.visitLabel(end);

    mv.visitLocalVariable("this", 'L' + name + ';', signature, start, end, 0);
    if (!info.isStatic()) {
        mv.visitLocalVariable("this$0", outerType.getDescriptor(), null, start, end, 1);
    }

    SignatureWriter sign = new SignatureWriter();
    contSignature(sign);
    mv.visitLocalVariable("continuation", CONTINUATION_DESC, sign.toString(), start, end, 1 + info.thisOffset);

    mv.visitMaxs(3 + info.thisOffset, 2 + info.thisOffset);
    mv.visitEnd();
}

From source file:com.google.code.jconts.instrument.gen.ContinuationClassGenerator.java

License:Apache License

private void generateConstructor(ClassVisitor cv) {
    final String name = info.continuationClassName;
    final Type outerType = Type.getObjectType(info.owner);

    // Constructor have form either <init>(OuterClass this$0, State state,
    // int index)
    // or <init>(State state, int index)
    String ctorDesc;/* w w w.j a  v a  2s .c o m*/
    if (info.isStatic()) {
        ctorDesc = Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { info.stateType, Type.INT_TYPE });
    } else {
        cv.visitField(Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL, "this$0", 'L' + info.owner + ';', null, null);

        ctorDesc = Type.getMethodDescriptor(Type.VOID_TYPE,
                new Type[] { outerType, info.stateType, Type.INT_TYPE });
    }

    // Generate constructor
    MethodVisitor mv = cv.visitMethod(0, CTOR_NAME, ctorDesc, null, null);
    mv.visitCode();
    Label start = new Label();
    Label end = new Label();
    mv.visitLabel(start);

    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, OBJECT_NAME, CTOR_NAME, DEFAULT_CTOR_DESC);

    // Save state field
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitVarInsn(Opcodes.ALOAD, 1 + info.thisOffset);
    mv.visitFieldInsn(Opcodes.PUTFIELD, name, "state", stateDesc);

    // Save index field
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitVarInsn(Opcodes.ILOAD, 2 + info.thisOffset);
    mv.visitFieldInsn(Opcodes.PUTFIELD, name, "index", "I");

    // Save outer this
    if (!info.isStatic()) {
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitVarInsn(Opcodes.ALOAD, 1);
        mv.visitFieldInsn(Opcodes.PUTFIELD, name, "this$0", outerType.getDescriptor());
    }
    mv.visitInsn(Opcodes.RETURN);
    mv.visitLabel(end);

    mv.visitLocalVariable("this", 'L' + name + ';', signature, start, end, 0);
    if (!info.isStatic()) {
        mv.visitLocalVariable("this$0", outerType.getDescriptor(), null, start, end, 1);
    }
    mv.visitLocalVariable("state", stateDesc, null, start, end, 1 + info.thisOffset);
    mv.visitLocalVariable("index", "I", null, start, end, 2 + info.thisOffset);

    mv.visitMaxs(2, 3 + info.thisOffset);
    mv.visitEnd();
}

From source file:com.google.code.jconts.instrument.gen.ContinuationClassGenerator.java

License:Apache License

private void generateExecute(ClassVisitor cv, boolean execute) {
    final String name = info.continuationClassName;
    final Type outerType = Type.getObjectType(info.owner);

    // Generate invoke(T result);
    String signature = null;//from w  w  w.j a va2s.  c  om
    if (execute) {
        SignatureWriter sign = new SignatureWriter();
        sign.visitParameterType().visitTypeVariable("T");
        sign.visitReturnType().visitBaseType('V'); // void
        signature = sign.toString();
    }
    MethodVisitor mv = cv.visitMethod(Opcodes.ACC_FINAL | Opcodes.ACC_PUBLIC,
            execute ? CONTINUATION_INVOKE_NAME : CONTINUATION_SET_EXCEPTION_NAME,
            execute ? CONTINUATION_INVOKE_DESC : CONTINUATION_SET_EXCEPTION_DESC, signature, null);
    mv.visitCode();
    Label start = new Label();
    Label end = new Label();
    mv.visitLabel(start);

    // Load outer this
    if (!info.isStatic()) {
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitFieldInsn(Opcodes.GETFIELD, name, "this$0", outerType.getDescriptor());
    }

    // state.result = result or state.exception = throwable
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitFieldInsn(Opcodes.GETFIELD, name, "state", stateDesc);
    mv.visitVarInsn(Opcodes.ALOAD, 1);
    mv.visitFieldInsn(Opcodes.PUTFIELD, info.stateClassName, execute ? "result" : "exception",
            execute ? OBJECT_DESC : THROWABLE_DESC);

    // Load state field
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitFieldInsn(Opcodes.GETFIELD, name, "state", stateDesc);

    // Continue from this index or index+1 (for exception)
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitFieldInsn(Opcodes.GETFIELD, name, "index", "I");
    if (!execute) {
        mv.visitInsn(Opcodes.ICONST_1);
        mv.visitInsn(Opcodes.IADD);
    }

    mv.visitMethodInsn(info.isStatic() ? Opcodes.INVOKESTATIC : Opcodes.INVOKEVIRTUAL, info.owner,
            info.name + "$async",
            Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { info.stateType, Type.INT_TYPE }));

    mv.visitInsn(Opcodes.RETURN);
    mv.visitLabel(end);

    mv.visitLocalVariable("this", 'L' + name + ';', signature, start, end, 0);
    if (!info.isStatic()) {
        mv.visitLocalVariable("this$0", outerType.getDescriptor(), null, start, end, 1);
    }
    mv.visitLocalVariable("result", OBJECT_DESC, "TT;", start, end, 1 + info.thisOffset);

    mv.visitMaxs(3 + info.thisOffset + (execute ? 0 : 1), 2 + info.thisOffset);
    mv.visitEnd();
}

From source file:com.google.code.jconts.instrument.gen.StateClassGenerator.java

License:Apache License

public void accept(TransformationContext context) {
    ClassVisitor cv = context.writer();//from   www.  j a  v  a  2s  .  c  om

    final String name = info.stateClassName;

    cv.visit(Opcodes.V1_6, Opcodes.ACC_FINAL /*| Opcodes.ACC_SYNTHETIC*/, name, null, OBJECT_NAME, null);

    cv.visitSource(info.ownerSource, null);
    cv.visitOuterClass(info.owner, null, null);

    cv.visitField(0/*Opcodes.ACC_SYNTHETIC*/, CONTINUATION_FIELD, CONTINUATION_DESC,
            'L' + CONTINUATION_NAME + '<' + info.valueSignature + ">;", null);

    // Local variables state
    List<String> names = info.tracker.getFieldNames();
    List<Type> types = info.tracker.getFieldTypes();
    for (int i = 0; i < names.size(); ++i) {
        cv.visitField(0/*Opcodes.ACC_SYNTHETIC*/, names.get(i), types.get(i).getDescriptor(), null, null);
    }

    // Return value variable
    cv.visitField(0/*Opcodes.ACC_SYNTHETIC*/, "result", OBJECT_DESC, null, null);
    cv.visitField(0/*Opcodes.ACC_SYNTHETIC*/, "exception", THROWABLE_DESC, null, null);

    // Generate constructor
    MethodVisitor mv = cv.visitMethod(0, CTOR_NAME, DEFAULT_CTOR_DESC, null, null);
    mv.visitCode();
    Label start = new Label();
    Label end = new Label();
    mv.visitLabel(start);
    mv.visitLineNumber(0, start);

    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, OBJECT_NAME, CTOR_NAME, DEFAULT_CTOR_DESC);
    mv.visitInsn(Opcodes.RETURN);
    mv.visitLabel(end);

    mv.visitLocalVariable("this", 'L' + name + ';', null, start, end, 0);

    mv.visitMaxs(1, 1);
    mv.visitEnd();

    cv.visitEnd();
}

From source file:com.google.code.jconts.instrument.gen.TramplineMethodGenerator.java

License:Apache License

public void accept(ClassVisitor cv) {
    MethodVisitor mv = cv.visitMethod(info.access, info.name, info.desc, info.signature, info.exceptions);
    mv.visitCode();//from ww  w  .j av  a2  s.  c om
    mv.visitTypeInsn(Opcodes.NEW, info.computationClassName);
    mv.visitInsn(Opcodes.DUP);

    // "this' for new Computation(this, state)
    if (!info.isStatic()) {
        mv.visitVarInsn(Opcodes.ALOAD, 0);
    }

    // new State()
    mv.visitTypeInsn(Opcodes.NEW, info.stateClassName);
    mv.visitInsn(Opcodes.DUP);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, info.stateClassName, CTOR_NAME, DEFAULT_CTOR_DESC);

    // state.varX = argX
    String[] names = info.entryLocalsVars;
    for (int i = 0; i < info.entryLocals.length; ++i) {
        mv.visitInsn(Opcodes.DUP);
        mv.visitVarInsn(info.entryLocals[i].getOpcode(Opcodes.ILOAD), i + info.thisOffset);
        mv.visitFieldInsn(Opcodes.PUTFIELD, info.stateClassName, names[i], info.entryLocals[i].getDescriptor());
    }

    // new Computation(this, state);
    String ctorDesc;
    if (info.isStatic()) {
        ctorDesc = Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { info.stateType });
    } else {
        ctorDesc = Type.getMethodDescriptor(Type.VOID_TYPE,
                new Type[] { Type.getObjectType(info.owner), info.stateType });
    }
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, info.computationClassName, CTOR_NAME, ctorDesc);

    mv.visitInsn(Opcodes.ARETURN);
    mv.visitMaxs(info.isStatic() ? 5 : 6,
            info.isStatic() ? info.entryLocals.length : info.entryLocals.length + 1);
    mv.visitEnd();
}

From source file:com.google.code.jtracert.instrument.impl.asm.JTracertClassAdapter.java

License:Open Source License

/**
 *
 *///from   w  w w  .  j  a va 2s  . c om
@Override
public void visitEnd() {

    if (!isInterface) {
        // Apply class transformations
    }

    if ("java.lang.System".equals(getClassName()) || "java/lang/System".equals(getClassName())) {
        MethodVisitor mv = cv.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC + Opcodes.ACC_SYNCHRONIZED,
                "constructor", "(Ljava/lang/Object;)V", null, null);
        mv.visitCode();
        mv.visitInsn(Opcodes.RETURN);
        mv.visitMaxs(0, 1);
        mv.visitEnd();
    }

    super.visitEnd();
}

From source file:com.google.devtools.build.android.desugar.CoreLibrarySupport.java

License:Open Source License

private void makeDispatchHelperMethod(ClassVisitor helper, EmulatedMethod method,
        ImmutableList<Class<?>> typechecks) {
    checkArgument(method.owner().isInterface());
    String owner = method.owner().getName().replace('.', '/');
    Type methodType = Type.getMethodType(method.descriptor());
    String companionDesc = InterfaceDesugaring.companionDefaultMethodDescriptor(owner, method.descriptor());
    MethodVisitor dispatchMethod = helper.visitMethod(method.access() | Opcodes.ACC_STATIC, method.name(),
            companionDesc, /*signature=*/ null, // signature is invalid due to extra "receiver" argument
            method.exceptions().toArray(EMPTY_LIST));

    dispatchMethod.visitCode();//w  ww  . j a  v  a  2 s  .c o m
    {
        // See if the receiver might come with its own implementation of the method, and call it.
        // We do this by testing for the interface type created by EmulatedInterfaceRewriter
        Label fallthrough = new Label();
        String emulationInterface = renameCoreLibrary(owner);
        dispatchMethod.visitVarInsn(Opcodes.ALOAD, 0); // load "receiver"
        dispatchMethod.visitTypeInsn(Opcodes.INSTANCEOF, emulationInterface);
        dispatchMethod.visitJumpInsn(Opcodes.IFEQ, fallthrough);
        dispatchMethod.visitVarInsn(Opcodes.ALOAD, 0); // load "receiver"
        dispatchMethod.visitTypeInsn(Opcodes.CHECKCAST, emulationInterface);

        visitLoadArgs(dispatchMethod, methodType, 1 /* receiver already loaded above */);
        dispatchMethod.visitMethodInsn(Opcodes.INVOKEINTERFACE, emulationInterface, method.name(),
                method.descriptor(), /*itf=*/ true);
        dispatchMethod.visitInsn(methodType.getReturnType().getOpcode(Opcodes.IRETURN));

        dispatchMethod.visitLabel(fallthrough);
        // Trivial frame for the branch target: same empty stack as before
        dispatchMethod.visitFrame(Opcodes.F_SAME, 0, EMPTY_FRAME, 0, EMPTY_FRAME);
    }

    // Next, check for subtypes with specialized implementations and call them
    for (Class<?> tested : typechecks) {
        Label fallthrough = new Label();
        String testedName = tested.getName().replace('.', '/');
        // In case of a class this must be a member move; for interfaces use the companion.
        String target = tested.isInterface() ? InterfaceDesugaring.getCompanionClassName(testedName)
                : checkNotNull(memberMoves.get(rewriter.unprefix(testedName) + '#' + method.name()));
        dispatchMethod.visitVarInsn(Opcodes.ALOAD, 0); // load "receiver"
        dispatchMethod.visitTypeInsn(Opcodes.INSTANCEOF, testedName);
        dispatchMethod.visitJumpInsn(Opcodes.IFEQ, fallthrough);
        dispatchMethod.visitVarInsn(Opcodes.ALOAD, 0); // load "receiver"
        dispatchMethod.visitTypeInsn(Opcodes.CHECKCAST, testedName); // make verifier happy

        visitLoadArgs(dispatchMethod, methodType, 1 /* receiver already loaded above */);
        dispatchMethod.visitMethodInsn(Opcodes.INVOKESTATIC, target, method.name(),
                InterfaceDesugaring.companionDefaultMethodDescriptor(testedName, method.descriptor()),
                /*itf=*/ false);
        dispatchMethod.visitInsn(methodType.getReturnType().getOpcode(Opcodes.IRETURN));

        dispatchMethod.visitLabel(fallthrough);
        // Trivial frame for the branch target: same empty stack as before
        dispatchMethod.visitFrame(Opcodes.F_SAME, 0, EMPTY_FRAME, 0, EMPTY_FRAME);
    }

    // Call static type's default implementation in companion class
    dispatchMethod.visitVarInsn(Opcodes.ALOAD, 0); // load "receiver"
    visitLoadArgs(dispatchMethod, methodType, 1 /* receiver already loaded above */);
    dispatchMethod.visitMethodInsn(Opcodes.INVOKESTATIC, InterfaceDesugaring.getCompanionClassName(owner),
            method.name(), companionDesc, /*itf=*/ false);
    dispatchMethod.visitInsn(methodType.getReturnType().getOpcode(Opcodes.IRETURN));

    dispatchMethod.visitMaxs(0, 0);
    dispatchMethod.visitEnd();
}