Example usage for org.objectweb.asm Opcodes V1_5

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

Introduction

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

Prototype

int V1_5

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

Click Source Link

Usage

From source file:com.sun.fortress.compiler.environments.TopLevelEnvGen.java

License:Open Source License

/**
 * Given one component, generate a Java bytecode compiled environment
 * for that component./*  w ww.j a v  a2s.  co m*/
 */
private static byte[] generateForCompilationUnit(String className, CompilationUnitIndex compUnitIndex) {

    /*
     *  With new ClassWriter(ClassWriter.COMPUTE_FRAMES) everything is
     *  computed automatically. You don't have to call visitFrame, but you
     *  must still call visitMaxs (arguments will be ignored and recomputed).
     *  Using these options is convenient but this has a cost: the COMPUTE_FRAMES option
     *  makes it two times slower.
     *
     *  Currently not a performance bottleneck.
     */
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);

    cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER + Opcodes.ACC_FINAL, className, null,
            Type.getType(BaseEnv.class).getInternalName(), null);

    // Implementing "static reflection" for the interpreter
    EnvSymbolNames symbolNames = new EnvSymbolNames();

    writeFields(cw, compUnitIndex, symbolNames);
    writeMethodInit(cw, className);

    writeMethodGetRaw(cw, className, "getApiNull", EnvironmentClass.ENVIRONMENT, symbolNames);
    writeMethodPutRaw(cw, className, "putApi", EnvironmentClass.ENVIRONMENT, symbolNames);
    writeMethodGetRaw(cw, className, "getValueRaw", EnvironmentClass.FVALUE, symbolNames);
    writeMethodPutRaw(cw, className, "putValueRaw", EnvironmentClass.FVALUE, symbolNames);
    writeMethodGetRaw(cw, className, "getTypeNull", EnvironmentClass.FTYPE, symbolNames);
    writeMethodPutRaw(cw, className, "putTypeRaw", EnvironmentClass.FTYPE, symbolNames);
    writeEmptyMethods(cw, className);
    writeRemoveMethods(cw, className);
    writeDumpMethod(cw, className, symbolNames);
    cw.visitEnd();

    return (cw.toByteArray());
}

From source file:edu.ubc.mirrors.holograms.HologramClassGenerator.java

License:Open Source License

@Override
public void visit(int version, int access, String name, String signature, String superName,
        String[] interfaces) {// w ww.  j ava 2 s.  c om
    this.name = name;
    this.isInterface = (Opcodes.ACC_INTERFACE & access) != 0;
    this.superName = getHologramSuperclassName(isInterface, name, superName);
    interfaces = getHologramInterfaces(name, isInterface, interfaces);

    // Force everything to be public, since HologramClassLoader has to reflectively
    // construct holograms. Again, not a problem because the VM will see the original flags on the ClassMirror instead.
    // Also remove enum flags.
    int hologramAccess = forcePublic(access);
    // Also remove abstract flag. Shouldn't be necessary, but the VM (OpenJDK at least)
    // creates objects that claim to be an instance of VirtualMachineError, which is abstract.
    if (name.equals("hologram/java/lang/VirtualMachineError")) {
        hologramAccess = ~Opcodes.ACC_ABSTRACT & access;
    }

    // We need at least 1.5 to use class literal constants
    // TODO-RS: Work out a better way to interpret 45.X numbers correctly
    if (version == Opcodes.V1_1 || version < Opcodes.V1_5) {
        version = 49;
    }

    super.visit(version, hologramAccess, name, signature, this.superName, interfaces);

    if (this.name.equals(hologramThrowableType.getInternalName())) {
        // Generate aliases for the original superclass' fillInStackTrace and getStackTrace methods,
        // so we can call them in stubs without hitting hologram code.
        MethodVisitor v = super.visitMethod(Opcodes.ACC_PUBLIC, "superFillInStackTrace",
                Type.getMethodDescriptor(Type.VOID_TYPE), null, null);
        v.visitCode();
        v.visitVarInsn(Opcodes.ALOAD, 0);
        v.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Throwable.class), "fillInStackTrace",
                Type.getMethodDescriptor(Type.getType(Throwable.class)));
        v.visitInsn(Opcodes.RETURN);
        v.visitMaxs(1, 1);
        v.visitEnd();

        v = super.visitMethod(Opcodes.ACC_PUBLIC, "superGetStackTrace",
                Type.getMethodDescriptor(Type.getType(StackTraceElement[].class)), null, null);
        v.visitCode();
        v.visitVarInsn(Opcodes.ALOAD, 0);
        v.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Throwable.class), "getStackTrace",
                Type.getMethodDescriptor(Type.getType(StackTraceElement[].class)));
        v.visitInsn(Opcodes.ARETURN);
        v.visitMaxs(1, 1);
        v.visitEnd();
    }
}

From source file:edu.ubc.mirrors.holograms.HologramClassGenerator.java

License:Open Source License

public static void generateArray(ClassVisitor visitor, HologramClassLoader loader,
        HologramClassMirror hologramClassMirror) {
    boolean isInterface = !hologramClassMirror.isImplementationClass();
    ClassMirror classMirror = hologramClassMirror.getOriginal();

    Type originalType = Reflection.typeForClassMirror(classMirror);
    Type originalElementType = originalType.getElementType();
    int dims = originalType.getDimensions();

    String internalName = getHologramType(originalType, !isInterface).getInternalName();

    ClassMirror superClassMirror = null;
    String superName = isInterface ? Type.getInternalName(Object.class)
            : Type.getInternalName(ObjectArrayHologram.class);
    Set<String> interfaces = new HashSet<String>();
    int access = Opcodes.ACC_PUBLIC | (isInterface ? Opcodes.ACC_INTERFACE : 0);

    if (originalElementType.getSort() == Type.OBJECT || originalElementType.getSort() == Type.ARRAY) {
        ClassMirror elementClass = loader.loadOriginalClassMirror(originalElementType.getClassName());
        superClassMirror = elementClass.getSuperClassMirror();

        if (isInterface) {
            if (superClassMirror != null) {
                Type superType = Reflection.makeArrayType(dims,
                        Type.getObjectType(superClassMirror.getClassName().replace('.', '/')));
                String superInterfaceName = getHologramType(superType).getInternalName();
                interfaces.add(superInterfaceName);
            }/*from  ww w . j a  va2s. co m*/

            for (ClassMirror interfaceMirror : elementClass.getInterfaceMirrors()) {
                Type superType = Reflection.makeArrayType(dims,
                        Type.getObjectType(interfaceMirror.getClassName().replace('.', '/')));
                String interfaceName = getHologramType(superType).getInternalName();
                interfaces.add(interfaceName);
            }

            interfaces.add(hologramType.getInternalName());

            Type nMinus1Type = Reflection.makeArrayType(dims - 1, Type.getType(Object.class));
            interfaces.add(getHologramType(nMinus1Type).getInternalName());
        }
    }
    if (!isInterface) {
        interfaces.add(getHologramType(originalType, false).getInternalName());
    }

    visitor.visit(Opcodes.V1_5, access, internalName, null, superName, interfaces.toArray(new String[0]));

    if (isInterface) {
        // Generate clone()
        String cloneDesc = Type.getMethodDescriptor(objectType);
        MethodVisitor mv = visitor.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_ABSTRACT, "clone", cloneDesc,
                null, null);
        mv.visitEnd();
    } else {
        // Generate thunk constructors
        String initDesc = Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(ObjectArrayMirror.class));
        MethodVisitor mv = visitor.visitMethod(Opcodes.ACC_PUBLIC, "<init>", initDesc, null, null);
        mv.visitCode();
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitVarInsn(Opcodes.ALOAD, 1);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, superName, "<init>", initDesc);
        mv.visitInsn(Opcodes.RETURN);
        mv.visitMaxs(2, 2);
        mv.visitEnd();

        initDesc = Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE);
        mv = visitor.visitMethod(Opcodes.ACC_PUBLIC, "<init>", initDesc, null, null);
        mv.visitCode();
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitVarInsn(Opcodes.ILOAD, 1);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, superName, "<init>", initDesc);
        mv.visitInsn(Opcodes.RETURN);
        mv.visitMaxs(2, 2);
        mv.visitEnd();
    }

    // Generate the static field used to store the corresponding ClassMirror and the static initializer to set it
    int staticAccess = Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC;
    visitor.visitField(staticAccess, "classMirror", classMirrorType.getDescriptor(), null, null);

    InstructionAdapter mv = new InstructionAdapter(
            visitor.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "<clinit>", "()V", null, null));
    mv.visitCode();
    HologramMethodGenerator.initializeStaticFields(Type.getObjectType(internalName), mv);
    mv.areturn(Type.VOID_TYPE);
    mv.visitMaxs(2, 2);
    mv.visitEnd();

    visitor.visitEnd();
}

From source file:erjang.EFun.java

License:Apache License

static byte[] gen_fun_class_data(int arity) {

    String self_type = EFUN_TYPE.getInternalName() + arity;

    ClassWriter cw = new ClassWriter(true);
    cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC | Opcodes.ACC_ABSTRACT, self_type, null,
            EFUN_TYPE.getInternalName(), null);

    make_invoke_method(cw, self_type, arity);

    CompilerVisitor.make_invoketail_method(cw, self_type, arity, 0);

    MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "arity", "()I", null, null);
    mv.visitCode();//from w ww .j  av  a  2s  .  c  o m
    mv.visitLdcInsn(new Integer(arity));
    mv.visitInsn(Opcodes.IRETURN);
    mv.visitMaxs(2, 2);
    mv.visitEnd();

    mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "invoke", "(" + EPROC_TYPE.getDescriptor()
            + EOBJECT_ARR_TYPE.getDescriptor() + ")" + EOBJECT_TYPE.getDescriptor(), null, PAUSABLE_EX);
    mv.visitCode();
    mv.visitVarInsn(Opcodes.ALOAD, 0); // load this
    mv.visitVarInsn(Opcodes.ALOAD, 1); // load proc
    for (int i = 0; i < arity; i++) {
        mv.visitVarInsn(Opcodes.ALOAD, 2);
        push_int(mv, i);
        mv.visitInsn(Opcodes.AALOAD);
    }

    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, self_type, "invoke", EUtil.getSignature(arity, true));

    mv.visitInsn(Opcodes.ARETURN);
    mv.visitMaxs(arity + 2, arity + 2);
    mv.visitEnd();

    mv = cw.visitMethod(Opcodes.ACC_PROTECTED, "<init>", "()V", null, null);
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, EFUN_TYPE.getInternalName(), "<init>", "()V");
    mv.visitInsn(Opcodes.RETURN);
    mv.visitMaxs(1, 1);
    mv.visitEnd();

    make_cast_method(cw, arity);

    cw.visitEnd();

    byte[] data = cw.toByteArray();
    return data;
}

From source file:erjang.EFun.java

License:Apache License

static byte[] get_exported_fun_class_data(int arity) {
    /* Code template://from   www  . ja  v a  2s.  co  m
     * public abstract class EFun{arity}Exported extends EFun{arity} {
     *   protected final EAtom module_name, function_name;
     *   protected EFun{arity}Exported(String m, String f) {
     *     module_name   = EAtom.intern(m);
     *     function_name = EAtom.intern(f);
     *   }
     * }
     */

    ensure(arity); // Ensure presence of superclass.
    String super_type = EFUN_TYPE.getInternalName() + arity;
    String self_type = super_type + "Exported";

    ClassWriter cw = new ClassWriter(true);
    cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC | Opcodes.ACC_ABSTRACT, self_type, null, super_type, null);

    cw.visitField(ACC_PROTECTED | ACC_FINAL, "module_name", EATOM_TYPE.getDescriptor(), null, null).visitEnd();

    cw.visitField(ACC_PROTECTED | ACC_FINAL, "function_name", EATOM_TYPE.getDescriptor(), null, null)
            .visitEnd();

    MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PROTECTED, "<init>",
            "(Ljava/lang/String;Ljava/lang/String;)V", null, null);

    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, super_type, "<init>", "()V");

    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitVarInsn(Opcodes.ALOAD, 1);
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, EATOM_TYPE.getInternalName(), "intern",
            "(Ljava/lang/String;)Lerjang/EAtom;");
    mv.visitFieldInsn(Opcodes.PUTFIELD, self_type, "module_name", EATOM_DESC);

    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitVarInsn(Opcodes.ALOAD, 2);
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, EATOM_TYPE.getInternalName(), "intern",
            "(Ljava/lang/String;)Lerjang/EAtom;");
    mv.visitFieldInsn(Opcodes.PUTFIELD, self_type, "function_name", EATOM_DESC);

    mv.visitInsn(Opcodes.RETURN);
    mv.visitMaxs(3, 3);
    mv.visitEnd();

    make_encode_method_for_exported(cw, self_type, arity);

    cw.visitEnd();

    byte[] data = cw.toByteArray();
    return data;
}

From source file:fi.jumi.test.BuildTest.java

License:Open Source License

@Parameters(name = "{0}")
public static Collection<Object[]> data() {
    return asList(new Object[][] {
            { "jumi-actors", asList(Opcodes.V1_6), asList(),
                    asList(MANIFEST, POM_FILES, BASE_PACKAGE + "actors/"), new Deprecations() },

            { "thread-safety-agent", asList(Opcodes.V1_5, Opcodes.V1_6), asList(),
                    asList(MANIFEST, POM_FILES, BASE_PACKAGE + "threadsafetyagent/"), new Deprecations() }, });
}

From source file:jaspex.transactifier.Transactifier.java

License:Open Source License

private byte[] transactify() throws IOException {
    final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);

    // Copiar mtodos originais inalterados
    cr.accept(new ClassVisitor(Opcodes.ASM4) {
        @Override/*from  w w w.  java 2s .c  o  m*/
        public void visit(int version, int access, String name, String signature, String superName,
                String[] interfaces) {
            cw.visit(version, access, name, signature, superName, interfaces);
        }

        @Override
        public MethodVisitor visitMethod(int access, String name, String desc, String signature,
                String[] exceptions) {
            if (name.equals("<clinit>"))
                return new EmptyMethodVisitor();
            return cw.visitMethod(access, name, desc, signature, exceptions);
        }

        @Override
        public void visitEnd() {
            cw.visitEnd();
        }
    }, 0);

    // Varivel que contm o ltimo ClassVisitor da "chain" de classvisitors que servem de filtros ao
    // ficheiro original
    ClassVisitor cv = cw;

    // Mtodos alterados so marcados com $transactional no nome
    // Este marcador  temporrio, e ir ser substituido por $speculative mais  frente
    // Nota: Apenas os mtodos so renomeados, os seus INVOKE* ainda no apontam para os
    // $transactional; essa alterao  feita no SpeculativeTransformer
    cv = new ClassVisitor(Opcodes.ASM4, cv) {
        @Override
        public MethodVisitor visitMethod(int access, String name, String desc, String signature,
                String[] exceptions) {
            if (name.equals("<init>")) {
                desc = desc.replace(")", "Ljaspex/MARKER/Transactional;)");
            } else if (!name.equals("<clinit>")) {
                name += "$transactional";
            }
            return cv.visitMethod(access, name, desc, signature, exceptions);
        }
    };

    // Remover ACC_SYNCHRONIZED dos mtodos
    if (Options.REMOVESYNC || _JDKClass)
        cv = new RemoveSyncClassVisitor(cv);

    // Remover MONITORENTER/MONITOREXIT dos mtodos
    if (Options.REMOVEMONITORS)
        cv = new GenericMethodVisitorAdapter(cv, RemoveMonitorsClassVisitor.class);

    // Verificar se existem mtodos com ACC_SYNCHRONIZED ou opcodes MONITORENTER/MONITOREXIT
    if (!_JDKClass)
        cv = new CheckMonitorUsage(cv);

    // Corrigir chamadas a alguns mtodos de java.lang.Object
    cv = new GenericMethodVisitorAdapter(cv, ChangeObjectMethodsMethodVisitor.class, currentClass);

    // Adicionar overrides a alguns mtodos de java.lang.Object
    cv = new AddObjectMethodsClassVisitor(cv, currentClass);

    // Suporte para Arrays
    cv = new GenericMethodVisitorAdapter(cv, ChangeArrayAccessMethodVisitor.class, currentClass, _JDKClass);

    // Adicionar inicializao de offsets usados pela unsafetrans ao clinit da classe
    // Nota: Visitor tem que estar *depois* do FieldTransactifierClassVisitor
    if (!_JDKClass)
        cv = new GenericMethodVisitorAdapter(cv, ChangeClinitMethodVisitor.class, currentClass);

    // Visitor que cria os fields offset e o staticfieldbase
    if (!_JDKClass)
        cv = new FieldTransactifierClassVisitor(cv);

    // Alterar acessos a fields para passarem pela STM
    cv = new GenericMethodVisitorAdapter(cv, ChangeFieldAccessMethodVisitor.class, currentClass, _JDKClass);

    // Modificar string com filename da classe que aparece em excepes
    if (!_JDKClass)
        cv = new MarkAsTransactifiedClassVisitor(cv);

    // Verificar e fazer upgrade da verso da classe, se necessrio
    if (!_JDKClass)
        cv = new ClassVisitor(Opcodes.ASM4, cv) {
            @Override
            public void visit(int version, int access, String name, String signature, String superName,
                    String[] interfaces) {
                // Transactificao precisa de version >= 49, porque usa o MethodVisitor.visitLdcInsn(Type)
                // MethodVisitor.visitLdcInsn(Type), que s funciona a partir dessa verso dos classfiles.
                // http://asm.ow2.org/asm40/javadoc/user/org/objectweb/asm/MethodVisitor.html#visitLdcInsn(java.lang.Object)
                // http://stackoverflow.com/questions/2784791/
                // Caso especial: V1_1  196653, por alguma razo...
                if (version < Opcodes.V1_5 || version == Opcodes.V1_1) {
                    //Log.debug("Class " + name + " has version " + version + ", upgrading it to Java 5");
                    version = Opcodes.V1_5;
                }

                if (version > Opcodes.V1_6 && !name.startsWith("java/")) {
                    Log.warn("Class " + name + " is compiled for Java 7 or newer");
                }

                super.visit(version, access, name, signature, superName, interfaces);
            }
        };

    cr.accept(cv, ClassReader.EXPAND_FRAMES);

    return cw.toByteArray();
}

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

License:Open Source License

/**
 * Creates an {@link ExtendedClassNode}.
 * //from  w  w  w.java 2s  . c  o m
 * @param type
 *            Java type that gets defined by this class node.
 * @param parentClass
 *            The direct super class or the primary interface for this class
 *            node.
 * @param parentClassInfo
 *            Optional meta information for <code>parentClass</code>.
 */
public ExtendedClassNode(Type type, Class<?> parentClass, ClassInfo parentClassInfo) {
    super(Opcodes.ASM5);
    String[] interfaces = new String[parentClass.getInterfaces().length];
    int i = 0;
    for (Class<?> face : parentClass.getInterfaces()) {
        interfaces[i++] = Type.getInternalName(face);
    }

    Class<?> superClass = parentClass.isInterface() ? Object.class : parentClass;
    visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, type.getInternalName(), null, Type.getInternalName(superClass),
            interfaces);

    if (parentClassInfo != null) {
        parentClassInfo.copyAnnotations(this);
    }

    this.type = type;
    this.parentClass = parentClass;
    parentType = Type.getType(parentClass);
}

From source file:net.orfjackal.retrolambda.LowerBytecodeVersion.java

License:Open Source License

@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
    MethodVisitor next = super.visitMethod(access, name, desc, signature, exceptions);
    if (targetVersion <= Opcodes.V1_5) {
        return new RemoveMethodFrames(next);
    } else {/*  w  w w  . j  av  a  2  s  .co  m*/
        return next;
    }
}

From source file:net.sf.sveditor.core.db.persistence.JITPersistenceDelegateFactory.java

License:Open Source License

private void build_boilerplate(ClassWriter cw) {
    String classname = "SVDBPersistenceDelegate";
    String full_classname = transform_cls(fTargetPkg) + "/" + classname;

    cw.visit(Opcodes.V1_5, ACC_PROTECTED + ACC_PUBLIC + ACC_SUPER, full_classname, null, fBaseClass, null);
    cw.visitSource(classname + ".java", null);

    MethodVisitor mv;/*from w ww .  j av a  2  s  . c  o  m*/

    // Constructor
    mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESPECIAL, fBaseClass, "<init>", "()V");
    mv.visitInsn(RETURN);
    mv.visitMaxs(1, 1);
    mv.visitEnd();

    buildItemDispatchMethods(cw);
    buildObjectDispatchMethods(cw);
}