Example usage for org.objectweb.asm Opcodes ACC_SUPER

List of usage examples for org.objectweb.asm Opcodes ACC_SUPER

Introduction

In this page you can find the example usage for org.objectweb.asm Opcodes ACC_SUPER.

Prototype

int ACC_SUPER

To view the source code for org.objectweb.asm Opcodes ACC_SUPER.

Click Source Link

Usage

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

License:Apache License

/**
 * Use asm to generate a concrete subclass of the AppPathLoaderImpl class.
 * It only implements one method :/*  w  ww.  j av  a  2  s  . co  m*/
 * String[] getPatchedClasses();
 * <p>
 * The method is supposed to return the list of classes that were patched in this iteration.
 * This will be used by the InstantRun runtime to load all patched classes and register them
 * as overrides on the original classes.2 class files.
 *
 * @param patchFileContents list of patched class names.
 * @param outputDir         output directory where to generate the .class file in.
 * @return the generated .class files
 */
public static File writePatchFileContents(List<String> patchFileContents, File outputDir) {

    ClassWriter cw = new ClassWriter(0);
    MethodVisitor mv;

    cw.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, IncrementalVisitor.APP_PATCHES_LOADER_IMPL,
            null, IncrementalVisitor.ABSTRACT_PATCHES_LOADER_IMPL, null);

    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, IncrementalVisitor.ABSTRACT_PATCHES_LOADER_IMPL, "<init>",
                "()V", false);
        mv.visitInsn(Opcodes.RETURN);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "getPatchedClasses", "()[Ljava/lang/String;", null, null);
        mv.visitCode();
        mv.visitIntInsn(Opcodes.BIPUSH, patchFileContents.size());
        mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/String");
        for (int index = 0; index < patchFileContents.size(); index++) {
            mv.visitInsn(Opcodes.DUP);
            mv.visitIntInsn(Opcodes.BIPUSH, index);
            mv.visitLdcInsn(patchFileContents.get(index));
            mv.visitInsn(Opcodes.AASTORE);
        }
        mv.visitInsn(Opcodes.ARETURN);
        mv.visitMaxs(4, 1);
        mv.visitEnd();
    }
    cw.visitEnd();

    byte[] classBytes = cw.toByteArray();
    File outputFile = new File(outputDir, IncrementalVisitor.APP_PATCHES_LOADER_IMPL + ".class");
    try {
        Files.createParentDirs(outputFile);
        Files.write(classBytes, outputFile);
        // add the files to the list of files to be processed by subsequent tasks.
        return outputFile;
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

From source file:erjang.ETuple.java

License:Apache License

static byte[] make_tuple_class_data(int num_cells) {
    ClassWriter cww = new ClassWriter(true);

    CheckClassAdapter cw = new CheckClassAdapter(cww);

    String this_class_name = ETUPLE_NAME + num_cells;
    String super_class_name = ETUPLE_NAME;
    cw.visit(Opcodes.V1_4, Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER, this_class_name, null, super_class_name,
            null);/*from   w ww.j  ava  2s. com*/

    // create fields

    for (int i = 1; i <= num_cells; i++) {
        cw.visitField(Opcodes.ACC_PUBLIC, "elem" + i, ETERM_TYPE.getDescriptor(), null, null);
    }

    // create count method
    create_count(cw, num_cells);

    // create cast method
    create_cast(cw, num_cells);
    create_cast2(cw, num_cells);

    // create constructor
    create_constructor(cw, super_class_name);

    // create copy
    create_tuple_copy(num_cells, cw, this_class_name, super_class_name);

    // create nth
    create_tuple_nth(num_cells, cw, this_class_name);

    // create set
    create_tuple_set(num_cells, cw, this_class_name);

    cw.visitEnd();
    byte[] data = cww.toByteArray();

    // dump(this_class_name, data);

    return data;
}

From source file:graph.Modifier.java

License:Apache License

/**
 * Returns an integer bit field for the EnumSet, where the bit values are
 * defined as in the class file format./*from  w w w .  j  a  v  a 2 s  . c  o  m*/
 *
 * @param  set   Set of modifiers to convert to a bit field.
 * @return       Integer bit field.
 */
public static int getBitField(EnumSet<Modifier> set) {
    int access = 0;

    if (set.contains(PUBLIC)) {
        access |= Opcodes.ACC_PUBLIC;
    }

    if (set.contains(PROTECTED)) {
        access |= Opcodes.ACC_PROTECTED;
    }

    if (set.contains(PRIVATE)) {
        access |= Opcodes.ACC_PRIVATE;
    }

    if (set.contains(STATIC)) {
        access |= Opcodes.ACC_STATIC;
    }

    if (set.contains(FINAL)) {
        access |= Opcodes.ACC_FINAL;
    }

    if (set.contains(SUPER)) {
        access |= Opcodes.ACC_SUPER;
    }

    if (set.contains(INTERFACE)) {
        access |= Opcodes.ACC_INTERFACE;
    }

    if (set.contains(ABSTRACT)) {
        access |= Opcodes.ACC_ABSTRACT;
    }

    if (set.contains(SYNTHETIC)) {
        access |= Opcodes.ACC_SYNTHETIC;
    }

    if (set.contains(ANNOTATION)) {
        access |= Opcodes.ACC_ANNOTATION;
    }

    if (set.contains(ENUM)) {
        access |= Opcodes.ACC_ENUM;
    }

    if (set.contains(VOLATILE)) {
        access |= Opcodes.ACC_VOLATILE;
    }

    if (set.contains(TRANSIENT)) {
        access |= Opcodes.ACC_TRANSIENT;
    }

    if (set.contains(SYNCHRONIZED)) {
        access |= Opcodes.ACC_SYNCHRONIZED;
    }

    if (set.contains(BRIDGE)) {
        access |= Opcodes.ACC_BRIDGE;
    }

    if (set.contains(VARARGS)) {
        access |= Opcodes.ACC_VARARGS;
    }

    if (set.contains(NATIVE)) {
        access |= Opcodes.ACC_NATIVE;
    }

    return access;
}

From source file:graph.Modifier.java

License:Apache License

/**
 * Returns an EnumSet of the modifiers, based on the given bit field (where
 * the bit values are defined as in the class file format).
 *
 * @param access Integer bit field giving access modifiers.
 * @return       Set of modifiers./*from www .  j a  v  a  2s  . c om*/
 */
public static EnumSet<Modifier> getSet(int access) {
    EnumSet<Modifier> modifiers = EnumSet.noneOf(Modifier.class);

    if ((access & Opcodes.ACC_PUBLIC) != 0) {
        modifiers.add(Modifier.PUBLIC);
    }

    if ((access & Opcodes.ACC_PROTECTED) != 0) {
        modifiers.add(Modifier.PROTECTED);
    }

    if ((access & Opcodes.ACC_PRIVATE) != 0) {
        modifiers.add(Modifier.PRIVATE);
    }

    if ((access & Opcodes.ACC_STATIC) != 0) {
        modifiers.add(Modifier.STATIC);
    }

    if ((access & Opcodes.ACC_FINAL) != 0) {
        modifiers.add(Modifier.FINAL);
    }

    if ((access & Opcodes.ACC_SUPER) != 0) {
        modifiers.add(Modifier.SUPER);
    }

    if ((access & Opcodes.ACC_INTERFACE) != 0) {
        modifiers.add(Modifier.INTERFACE);
    }

    if ((access & Opcodes.ACC_ABSTRACT) != 0) {
        modifiers.add(Modifier.ABSTRACT);
    }

    if ((access & Opcodes.ACC_SYNTHETIC) != 0) {
        modifiers.add(Modifier.SYNTHETIC);
    }

    if ((access & Opcodes.ACC_ANNOTATION) != 0) {
        modifiers.add(Modifier.ANNOTATION);
    }

    if ((access & Opcodes.ACC_ENUM) != 0) {
        modifiers.add(Modifier.ENUM);
    }

    if ((access & Opcodes.ACC_VOLATILE) != 0) {
        modifiers.add(Modifier.VOLATILE);
    }

    if ((access & Opcodes.ACC_TRANSIENT) != 0) {
        modifiers.add(Modifier.TRANSIENT);
    }

    if ((access & Opcodes.ACC_SYNCHRONIZED) != 0) {
        modifiers.add(Modifier.SYNCHRONIZED);
    }

    if ((access & Opcodes.ACC_BRIDGE) != 0) {
        modifiers.add(Modifier.BRIDGE);
    }

    if ((access & Opcodes.ACC_VARARGS) != 0) {
        modifiers.add(Modifier.VARARGS);
    }

    if ((access & Opcodes.ACC_NATIVE) != 0) {
        modifiers.add(Modifier.NATIVE);
    }

    if ((access & Opcodes.ACC_STRICT) != 0) {
        modifiers.add(Modifier.STRICT);
    }

    return modifiers;
}

From source file:jpcsp.Allegrex.compiler.CodeBlock.java

License:Open Source License

private Class<IExecutable> interpret(CompilerContext context) {
    Class<IExecutable> compiledClass = null;

    context.setCodeBlock(this);
    String className = getInternalClassName();
    if (log.isInfoEnabled()) {
        log.info("Compiling for Interpreter " + className);
    }// ww w  .  j  a v  a 2 s  . c o m

    int computeFlag = ClassWriter.COMPUTE_FRAMES;
    if (context.isAutomaticMaxLocals() || context.isAutomaticMaxStack()) {
        computeFlag |= ClassWriter.COMPUTE_MAXS;
    }
    ClassWriter cw = new ClassWriter(computeFlag);
    ClassVisitor cv = cw;
    if (log.isDebugEnabled()) {
        cv = new CheckClassAdapter(cv);
    }

    StringWriter debugOutput = null;
    if (log.isDebugEnabled()) {
        debugOutput = new StringWriter();
        PrintWriter debugPrintWriter = new PrintWriter(debugOutput);
        cv = new TraceClassVisitor(cv, debugPrintWriter);
    }
    cv.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER, className, null, objectInternalName,
            interfacesForExecutable);
    context.startClass(cv);

    addConstructor(cv);
    addNonStaticMethods(context, cv);

    MethodVisitor mv = cv.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC,
            context.getStaticExecMethodName(), context.getStaticExecMethodDesc(), null, exceptions);
    mv.visitCode();
    context.setMethodVisitor(mv);
    context.startMethod();

    context.compileExecuteInterpreter(getStartAddress());

    mv.visitMaxs(context.getMaxStack(), context.getMaxLocals());
    mv.visitEnd();

    cv.visitEnd();

    if (debugOutput != null) {
        log.debug(debugOutput.toString());
    }

    compiledClass = loadExecutable(context, className, cw.toByteArray());

    return compiledClass;
}

From source file:jpcsp.Allegrex.compiler.CodeBlock.java

License:Open Source License

private Class<IExecutable> compile(CompilerContext context) throws ClassFormatError {
    Class<IExecutable> compiledClass = null;

    context.setCodeBlock(this);
    String className = getInternalClassName();
    if (log.isDebugEnabled()) {
        String functionName = Utilities.getFunctionNameByAddress(getStartAddress());

        if (functionName != null) {
            log.debug(String.format("Compiling %s (%s)", className, functionName));
        } else {//from w w  w . j  ava  2 s . co  m
            log.debug(String.format("Compiling %s", className));
        }
    }

    prepare(context, context.getMethodMaxInstructions());

    currentSequence = null;
    int computeFlag = ClassWriter.COMPUTE_FRAMES;
    if (context.isAutomaticMaxLocals() || context.isAutomaticMaxStack()) {
        computeFlag |= ClassWriter.COMPUTE_MAXS;
    }
    ClassWriter cw = new ClassWriter(computeFlag);
    ClassVisitor cv = cw;
    if (log.isDebugEnabled()) {
        cv = new CheckClassAdapter(cv);
    }
    StringWriter debugOutput = null;
    if (log.isTraceEnabled()) {
        debugOutput = new StringWriter();
        PrintWriter debugPrintWriter = new PrintWriter(debugOutput);
        cv = new TraceClassVisitor(cv, debugPrintWriter);
    }
    cv.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER, className, null, objectInternalName,
            interfacesForExecutable);
    context.startClass(cv);

    addConstructor(cv);
    addNonStaticMethods(context, cv);

    MethodVisitor mv = cv.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC,
            context.getStaticExecMethodName(), context.getStaticExecMethodDesc(), null, exceptions);
    mv.visitCode();
    context.setMethodVisitor(mv);
    context.startMethod();

    // Jump to the block start if other instructions have been inserted in front
    if (!codeInstructions.isEmpty() && codeInstructions.getFirst().getAddress() != getStartAddress()) {
        mv.visitJumpInsn(Opcodes.GOTO, getCodeInstruction(getStartAddress()).getLabel());
    }

    compile(context, mv, codeInstructions);
    mv.visitMaxs(context.getMaxStack(), context.getMaxLocals());
    mv.visitEnd();

    for (SequenceCodeInstruction sequenceCodeInstruction : sequenceCodeInstructions) {
        if (log.isDebugEnabled()) {
            log.debug("Compiling Sequence " + sequenceCodeInstruction.getMethodName(context));
        }
        currentSequence = sequenceCodeInstruction;
        mv = cv.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC,
                sequenceCodeInstruction.getMethodName(context), "()V", null, exceptions);
        mv.visitCode();
        context.setMethodVisitor(mv);
        context.startSequenceMethod();

        compile(context, mv, sequenceCodeInstruction.getCodeSequence().getInstructions());

        context.endSequenceMethod();
        mv.visitMaxs(context.getMaxStack(), context.getMaxLocals());
        mv.visitEnd();
    }
    currentSequence = null;

    cv.visitEnd();

    if (debugOutput != null) {
        log.trace(debugOutput.toString());
    }

    try {
        compiledClass = loadExecutable(context, className, cw.toByteArray());
    } catch (NullPointerException e) {
        log.error("Error while compiling " + className + ": " + e);
    }

    return compiledClass;
}

From source file:net.sf.cglib.proxy.TestEnhancer.java

License:Apache License

public void testBridgeParameterCheckcast() throws Exception {

    // If the compiler used for Z omits the bridge method, and X is compiled with javac,
    // javac will generate an invokespecial bridge in X.

    // public interface I<A, B> {
    //   public A f(B b);
    // }//from  w  w  w.  j av a 2s.c  om
    // public abstract class Z<U extends Number> implements I<U, Long> {
    //   public U f(Long id) {
    //     return null;
    //   }
    // }
    // public class X extends Z<Integer> {}

    final Map<String, byte[]> classes = new HashMap<String, byte[]>();

    {
        ClassWriter cw = new ClassWriter(0);
        cw.visit(49, Opcodes.ACC_PUBLIC | Opcodes.ACC_ABSTRACT | Opcodes.ACC_INTERFACE, "I",
                "<A:Ljava/lang/Object;B:Ljava/lang/Object;>Ljava/lang/Object;", "java/lang/Object", null);
        {
            MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_ABSTRACT, "f",
                    "(Ljava/lang/Object;)Ljava/lang/Object;", "(TB;)TA;", null);
            mv.visitEnd();
        }
        cw.visitEnd();
        classes.put("I.class", cw.toByteArray());
    }
    {
        ClassWriter cw = new ClassWriter(0);
        cw.visit(49, Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER | Opcodes.ACC_ABSTRACT, "Z",
                "<U:Ljava/lang/Number;>Ljava/lang/Object;LI<TU;Ljava/lang/String;>;", "java/lang/Object",
                new String[] { "I" });
        {
            MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
            mv.visitCode();
            mv.visitVarInsn(Opcodes.ALOAD, 0);
            mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
            mv.visitInsn(Opcodes.RETURN);
            mv.visitMaxs(1, 1);
            mv.visitEnd();
        }
        {
            MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "f", "(Ljava/lang/String;)Ljava/lang/Number;",
                    "(Ljava/lang/String;)TU;", null);
            mv.visitCode();
            mv.visitInsn(Opcodes.ACONST_NULL);
            mv.visitInsn(Opcodes.ARETURN);
            mv.visitMaxs(1, 2);
            mv.visitEnd();
        }
        cw.visitEnd();
        classes.put("Z.class", cw.toByteArray());
    }
    {
        ClassWriter cw = new ClassWriter(0);
        cw.visit(49, Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER, "X", "LZ<Ljava/lang/Integer;>;", "Z", null);
        {
            MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
            mv.visitCode();
            mv.visitVarInsn(Opcodes.ALOAD, 0);
            mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "Z", "<init>", "()V", false);
            mv.visitInsn(Opcodes.RETURN);
            mv.visitMaxs(1, 1);
            mv.visitEnd();
        }
        {
            MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_BRIDGE | Opcodes.ACC_SYNTHETIC,
                    "f", "(Ljava/lang/Object;)Ljava/lang/Object;", null, null);
            mv.visitCode();
            mv.visitVarInsn(Opcodes.ALOAD, 0);
            mv.visitVarInsn(Opcodes.ALOAD, 1);
            mv.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/String");
            mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "Z", "f", "(Ljava/lang/String;)Ljava/lang/Number;",
                    false);
            mv.visitInsn(Opcodes.ARETURN);
            mv.visitMaxs(2, 2);
            mv.visitEnd();
        }

        cw.visitEnd();

        classes.put("X.class", cw.toByteArray());
    }

    ClassLoader classLoader = new ClassLoader(getClass().getClassLoader()) {
        @Override
        public InputStream getResourceAsStream(String name) {
            InputStream is = super.getResourceAsStream(name);
            if (is != null) {
                return is;
            }
            if (classes.containsKey(name)) {
                return new ByteArrayInputStream(classes.get(name));
            }
            return null;
        }

        public Class findClass(String name) throws ClassNotFoundException {
            byte[] ba = classes.get(name.replace('.', '/') + ".class");
            if (ba != null) {
                return defineClass(name, ba, 0, ba.length);
            }
            throw new ClassNotFoundException(name);
        }
    };

    List<Class> retTypes = new ArrayList<Class>();
    List<Class> paramTypes = new ArrayList<Class>();
    Interceptor interceptor = new Interceptor(retTypes, paramTypes);

    Enhancer e = new Enhancer();
    e.setClassLoader(classLoader);
    e.setSuperclass(classLoader.loadClass("X"));
    e.setCallback(interceptor);

    Object c = e.create();

    for (Method m : c.getClass().getDeclaredMethods()) {
        if (m.getName().equals("f") && m.getReturnType().equals(Object.class)) {
            m.invoke(c, new Object[] { null });
        }
    }

    // f(Object)Object should bridge to f(Number)String
    assertEquals(Arrays.asList(Object.class, Number.class), retTypes);
    assertEquals(Arrays.asList(Object.class, String.class), paramTypes);
}

From source file:net.yrom.tools.WriteStyleablesProcessor.java

License:Apache License

@Override
public void proceed() {
    ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC | Opcodes.ACC_SUPER,
            RSymbols.R_STYLEABLES_CLASS_NAME, null, "java/lang/Object", null);
    for (String name : symbols.getStyleables().keySet()) {
        writer.visitField(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL, name, "[I", null, null);
    }//from   w  w  w  . j  a  v a2s.  com

    writeClinit(writer);
    writer.visitEnd();
    byte[] bytes = writer.toByteArray();
    try {
        if (!dir.isDirectory() && !dir.mkdirs()) {
            throw new RuntimeException("Cannot mkdir " + dir);
        }
        Files.write(dir.toPath().resolve(RSymbols.R_STYLEABLES_CLASS_NAME + ".class"), bytes);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:org.actorsguildframework.internal.codegenerator.ActorProxyCreator.java

License:Apache License

/**
 * Create or get a MessageCaller implementation for the given method.
 * @param ownerClass the class that owns the message
 * @param method the method to invoke//from  w  w w  . ja v a 2  s  . com
 * @return the message caller
 * @throws NoSuchMethodException 
 * @throws SecurityException 
 */
@SuppressWarnings("unchecked")
public static Class<MessageCaller<?>> createMessageCaller(Class<?> ownerClass, Method method)
        throws SecurityException, NoSuchMethodException {

    String className = String.format("%s_%s_%d__MESSAGECALLER", ownerClass.getName(), method.getName(),
            getMethodNumber(method));
    String classNameInternal = className.replace('.', '/');
    java.lang.reflect.Type fullReturnType = method.getGenericReturnType();
    if ((!(fullReturnType instanceof ParameterizedType))
            && AsyncResult.class.isAssignableFrom(((Class) ((ParameterizedType) fullReturnType).getRawType())))
        throw new RuntimeException("Something's wrong here: should not be called for such a method");
    String returnSignature = GenericTypeHelper
            .getSignature(((ParameterizedType) fullReturnType).getActualTypeArguments()[0]);

    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
    MethodVisitor mv;

    cw.visit(codeVersion, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER + Opcodes.ACC_SYNTHETIC,
            classNameInternal, "L" + classNameInternal + "<" + returnSignature + ">;",
            "org/actorsguildframework/internal/MessageCaller", null);
    cw.visitSource(null, null);

    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "org/actorsguildframework/internal/MessageCaller", "<init>",
                "()V");
        mv.visitInsn(Opcodes.RETURN);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLocalVariable("this", "L" + classNameInternal + ";", null, l0, l1, 0);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "invoke",
                "(Lorg/actorsguildframework/Actor;[Ljava/lang/Object;)Lorg/actorsguildframework/AsyncResult;",
                "(Lorg/actorsguildframework/Actor;[Ljava/lang/Object;)Lorg/actorsguildframework/AsyncResult<"
                        + returnSignature + ">;",
                null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);

        mv.visitVarInsn(Opcodes.ALOAD, 1);
        mv.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(method.getDeclaringClass()) + "__ACTORPROXY");

        int idx = 0;
        for (Class<?> t : method.getParameterTypes()) {
            mv.visitVarInsn(Opcodes.ALOAD, 2);
            mv.visitIntInsn(Opcodes.BIPUSH, idx);
            mv.visitInsn(Opcodes.AALOAD);
            if (t.isPrimitive()) {
                String wrapperDescr = GenerationUtils.getWrapperInternalName(t);
                mv.visitTypeInsn(Opcodes.CHECKCAST, wrapperDescr);
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, wrapperDescr, t.getName() + "Value",
                        "()" + Type.getDescriptor(t));
            } else {
                if (isArgumentFreezingRequired(method, idx, t)) {
                    mv.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(SerializableFreezer.class));
                    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(SerializableFreezer.class),
                            "get", Type.getMethodDescriptor(SerializableFreezer.class.getMethod("get")));
                }
                if (!t.equals(Object.class))
                    mv.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(t));
            }
            idx++;
        }
        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
                Type.getInternalName(method.getDeclaringClass()) + "__ACTORPROXY",
                String.format(SUPER_CALLER_NAME_FORMAT, method.getName()), Type.getMethodDescriptor(method));

        mv.visitInsn(Opcodes.ARETURN);

        Label l2 = new Label();
        mv.visitLabel(l2);
        mv.visitLocalVariable("this", "L" + classNameInternal + ";", null, l0, l2, 0);
        mv.visitLocalVariable("instance", "Lorg/actorsguildframework/Actor;", null, l0, l2, 1);
        mv.visitLocalVariable("arguments", "[Ljava/lang/Object;", null, l0, l2, 2);

        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "getMessageName", "()Ljava/lang/String;", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitLdcInsn(method.getName());
        mv.visitInsn(Opcodes.ARETURN);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLocalVariable("this", "L" + classNameInternal + ";", null, l0, l1, 0);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }
    cw.visitEnd();

    return (Class<MessageCaller<?>>) GenerationUtils.loadClass(className, cw.toByteArray());
}

From source file:org.actorsguildframework.internal.codegenerator.ActorProxyCreator.java

License:Apache License

/**
 * Creates and loads the actor's proxy class.
 * @param actorClass the Actor class/*w  ww. j  a  v a  2 s .  c om*/
 * @param acd the actor's class descriptor
 * @throws ConfigurationException if the agent is not configured correctly
 */
@SuppressWarnings("unchecked")
private static Class<?> generateProxyClass(Class<?> actorClass, final ActorClassDescriptor acd)
        throws NoSuchMethodException {
    BeanClassDescriptor bcd = acd.getBeanClassDescriptor();

    String className = String.format("%s__ACTORPROXY", actorClass.getName());
    final String classNameInternal = className.replace('.', '/');
    String classNameDescriptor = "L" + classNameInternal + ";";

    final Type actorState = Type
            .getType(acd.getConcurrencyModel().isMultiThreadingCapable() ? MultiThreadedActorState.class
                    : SingleThreadedActorState.class);

    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
    MethodVisitor mv;
    cw.visit(codeVersion, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER + Opcodes.ACC_SYNTHETIC,
            classNameInternal, null, Type.getInternalName(actorClass),
            new String[] { "org/actorsguildframework/internal/ActorProxy" });

    cw.visitSource(null, null);

    {
        for (int i = 0; i < acd.getMessageCount(); i++)
            cw.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL + Opcodes.ACC_STATIC,
                    String.format(MESSAGE_CALLER_NAME_FORMAT, i),
                    "Lorg/actorsguildframework/internal/MessageCaller;",
                    "Lorg/actorsguildframework/internal/MessageCaller<*>;", null).visitEnd();

        cw.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL, "actorState__ACTORPROXY",
                actorState.getDescriptor(), null, null).visitEnd();
    }

    BeanCreator.writePropFields(bcd, cw);

    {
        mv = cw.visitMethod(Opcodes.ACC_STATIC, "<clinit>", "()V", null, null);
        mv.visitCode();

        for (int i = 0; i < acd.getMessageCount(); i++) {
            Class<?> caller = createMessageCaller(acd.getMessage(i).getOwnerClass(),
                    acd.getMessage(i).getMethod());
            String mcName = Type.getInternalName(caller);
            mv.visitTypeInsn(Opcodes.NEW, mcName);
            mv.visitInsn(Opcodes.DUP);
            mv.visitMethodInsn(Opcodes.INVOKESPECIAL, mcName, "<init>", "()V");
            mv.visitFieldInsn(Opcodes.PUTSTATIC, classNameInternal,
                    String.format(MESSAGE_CALLER_NAME_FORMAT, i),
                    "Lorg/actorsguildframework/internal/MessageCaller;");
        }
        mv.visitInsn(Opcodes.RETURN);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }

    BeanCreator.writeConstructor(actorClass, bcd, classNameInternal, cw, new BeanCreator.SnippetWriter() {
        @Override
        public void write(MethodVisitor mv) {
            mv.visitVarInsn(Opcodes.ALOAD, 0);
            mv.visitTypeInsn(Opcodes.NEW, actorState.getInternalName());
            mv.visitInsn(Opcodes.DUP);
            mv.visitVarInsn(Opcodes.ALOAD, 1);
            mv.visitVarInsn(Opcodes.ALOAD, 0);
            mv.visitMethodInsn(Opcodes.INVOKESPECIAL, actorState.getInternalName(), "<init>",
                    "(Lorg/actorsguildframework/internal/Controller;Lorg/actorsguildframework/Actor;)V");
            mv.visitFieldInsn(Opcodes.PUTFIELD, classNameInternal, "actorState__ACTORPROXY",
                    actorState.getDescriptor());
        }
    });

    BeanCreator.writePropAccessors(bcd, classNameInternal, cw);

    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "getState__ACTORPROXYMETHOD",
                "()Lorg/actorsguildframework/internal/ActorState;", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitFieldInsn(Opcodes.GETFIELD, classNameInternal, "actorState__ACTORPROXY",
                actorState.getDescriptor());
        mv.visitInsn(Opcodes.ARETURN);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLocalVariable("this", classNameDescriptor, null, l0, l1, 0);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }

    for (int i = 0; i < acd.getMessageCount(); i++) {
        MessageImplDescriptor mid = acd.getMessage(i);
        Method method = mid.getMethod();
        String simpleDescriptor = Type.getMethodDescriptor(method);
        String genericSignature = GenericTypeHelper.getSignature(method);

        writeProxyMethod(classNameInternal, classNameDescriptor, cw, i, actorState, acd.getConcurrencyModel(),
                mid, method, simpleDescriptor, genericSignature);

        writeSuperProxyMethod(actorClass, classNameDescriptor, cw, method, simpleDescriptor, genericSignature,
                !acd.getConcurrencyModel().isMultiThreadingCapable());
    }

    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_SYNCHRONIZED, "toString", "()Ljava/lang/String;",
                null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "toString", "()Ljava/lang/String;");
        mv.visitInsn(Opcodes.ARETURN);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLocalVariable("this", classNameDescriptor, null, l0, l1, 0);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }
    cw.visitEnd();

    try {
        return (Class<? extends ActorProxy>) GenerationUtils.loadClass(className, cw.toByteArray());
    } catch (Exception e) {
        throw new ConfigurationException("Failure loading ActorProxy", e);
    }
}