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:org.compass.core.util.reflection.asm.AsmReflectionConstructorGenerator.java

License:Apache License

/**
 * Allows to generate an {@link ReflectionConstructor} implementation based on ASM that does not use
 * reflection./*from w  w  w  . j  a va2 s  . c  o m*/
 */
public static synchronized ReflectionConstructor generateConstructor(Constructor originalCtor)
        throws NoSuchMethodException {
    final Class declaringClass = originalCtor.getDeclaringClass();
    String ownerClassName = declaringClass.getName();

    Constructor[] declaredCtors = declaringClass.getDeclaredConstructors();
    int ctorIndex = 0;
    for (; ctorIndex < declaredCtors.length; ++ctorIndex) {
        if (declaredCtors[ctorIndex].equals(originalCtor))
            break;
    }
    String className = ownerClassName + "ConstReflection" + ctorIndex;

    try {
        Class definedClass;
        try {// checks if was already loaded
            definedClass = declaringClass.getClassLoader().loadClass(className);
        } catch (ClassNotFoundException e) // need to build a new class
        {

            String classInternalName = className.replace('.', '/'); // build internal name for ASM

            ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
            cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, classInternalName, null,
                    OBJECT_INTERNAL_NAME, REFLECTIONCONSTRUCTOR_INTERNAL_NAME);

            createConstructor(cw);
            createNewInstanceMethod(cw, declaringClass);

            cw.visitEnd();

            byte[] b = cw.toByteArray();
            definedClass = defineClass(declaringClass.getClassLoader(), className, b);
        }

        return (ReflectionConstructor) definedClass.newInstance();
    } catch (Exception e) {
        NoSuchMethodException ex = new NoSuchMethodException(
                "Can't create ASM constructor reflection helper for [" + originalCtor + "]");
        ex.initCause(e);
        throw ex;
    }
}

From source file:org.compass.core.util.reflection.asm.AsmReflectionFieldGenerator.java

License:Apache License

/**
 * Allows to generate {@link org.compass.core.util.reflection.ReflectionField} implementation based on
 * ASM that does not use reflection.//from w w  w.j  a  v  a2s.c  om
 */
public static synchronized ReflectionField generateField(Field refField) throws NoSuchFieldException {
    Class declaringClass = refField.getDeclaringClass();
    String ownerClassName = declaringClass.getName();

    Field[] declaredFields = declaringClass.getDeclaredFields();
    int methodIndex = 0;
    for (; methodIndex < declaredFields.length; ++methodIndex) {
        if (declaredFields[methodIndex].equals(refField))
            break;
    }

    String className = ownerClassName + "FieldReflection" + methodIndex;

    try {
        Class definedClass;
        try { // checks if was already loaded
            definedClass = declaringClass.getClassLoader().loadClass(className);
        } catch (ClassNotFoundException e) // need to build a new class
        {
            String classInternalName = className.replace('.', '/'); // build internal name for ASM

            ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
            cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, classInternalName, null,
                    PLAIN_FIELD_INTERNAL_NAME, null);

            createConstructor(cw);
            createGetMethod(cw, declaringClass, refField);
            createSetMethod(cw, declaringClass, refField);
            cw.visitEnd();

            byte[] b = cw.toByteArray();

            definedClass = defineClass(refField.getDeclaringClass().getClassLoader(), className, b);
        }
        Constructor ctor = definedClass.getConstructor(Field.class);
        return (ReflectionField) ctor.newInstance(refField);
    } catch (Exception e) {
        NoSuchFieldException err = new NoSuchFieldException(
                "Can't create ASM field reflection helper for [" + refField + "]");
        err.initCause(e);
        throw err;
    }
}

From source file:org.compass.core.util.reflection.asm.AsmReflectionMethodGenerator.java

License:Apache License

private static synchronized ReflectionMethod generateMethod(Method refMethod, String name, String desc,
        Class interfaceClass, boolean argsParams, boolean returnValue)
        throws SecurityException, NoSuchMethodException {
    final Class declaringClass = refMethod.getDeclaringClass();
    String ownerClassName = declaringClass.getName();

    Method[] declaredMethods = declaringClass.getDeclaredMethods();
    int methodIndex = 0;
    for (; methodIndex < declaredMethods.length; ++methodIndex) {
        if (declaredMethods[methodIndex].equals(refMethod))
            break;
    }//w w  w  .  j  a  va  2s. c  o  m
    String className = ownerClassName + "MethodReflection" + name + methodIndex;

    try {
        Class definedClass;
        try { // checks if was already loaded
            definedClass = declaringClass.getClassLoader().loadClass(className);
        } catch (ClassNotFoundException e) // need to build a new class
        {
            String classInternalName = className.replace('.', '/'); // build internal name for ASM

            ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);

            cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, classInternalName, null, PLAIN_PROCEDURE_INTERNAL_NAME,
                    new String[] { Type.getInternalName(interfaceClass) });

            createCtor(cw);
            createMethod(refMethod.getDeclaringClass(), refMethod.getName(), refMethod, cw, name, desc,
                    argsParams, returnValue, refMethod.getParameterTypes());

            cw.visitEnd();

            byte[] b = cw.toByteArray();
            definedClass = defineClass(declaringClass.getClassLoader(), className, b);
        }

        return (ReflectionMethod) definedClass.getConstructor(Method.class).newInstance(refMethod);
    } catch (Exception e) {
        NoSuchMethodException ex = new NoSuchMethodException(
                "Can't create ASM method reflection helper for [" + refMethod + "]");
        ex.initCause(e);
        throw ex;
    }
}

From source file:org.eclipselabs.nullness.NullnessCompiler.java

License:Open Source License

private void addRuntimeChecks(IFile javaFile, NullAnnotationFinder finder, FieldCache fieldCache)
        throws JavaModelException {
    IRegion region = JavaCore.newRegion();
    ICompilationUnit cu = (ICompilationUnit) JavaCore.create(javaFile);
    region.add(cu);/* ww w.j a va2 s. c  o m*/
    IResource[] resources = JavaCore.getGeneratedResources(region, false);
    ASTParser parser = ASTParser.newParser(AST.JLS4);
    parser.setProject(cu.getJavaProject());
    parser.setIgnoreMethodBodies(false);
    IType[] allTypes = getAllTypes(cu);
    IBinding[] bindings = parser.createBindings(allTypes, null);
    for (IResource resource : resources) {
        if (resource instanceof IFile) {
            IFile file = (IFile) resource;
            if ("class".equals(file.getFileExtension())) {
                try {
                    final InputStream inputStream = file.getContents();
                    try {
                        ClassReader reader = new ClassReader(inputStream);
                        int version = getClassFileVersion(reader);
                        if (version >= Opcodes.V1_5) {
                            ClassWriter writer = new ClassWriter(getClassWriterFlags(version));
                            String binaryName = file.getFullPath().removeFileExtension().lastSegment();
                            ITypeBinding typeBinding = findTypeBinding(binaryName, bindings);
                            if (typeBinding != null) {
                                final NullnessAssertionInserter nullChecker = new NullnessAssertionInserter(
                                        writer, typeBinding, finder, fieldCache);
                                reader.accept(nullChecker, 0);
                                if (nullChecker.isCheckInserted()) {
                                    ByteArrayInputStream newContent = new ByteArrayInputStream(
                                            writer.toByteArray());
                                    file.setContents(newContent, IResource.NONE, null);
                                }
                            }
                        }
                    } finally {
                        inputStream.close();
                    }
                } catch (CoreException e) {
                    // TODO reasonable exception handling
                    throw new RuntimeException(e);
                } catch (IOException e) {
                    // TODO reasonable exception handling
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

From source file:org.fabric3.binding.rs.runtime.bytecode.ProviderGeneratorImpl.java

License:Open Source License

private byte[] writeClass(ClassWriter cw, Class<?> baseClass, Class<?> delegateClass, int number) {
    String internalName = Type.getInternalName(baseClass);
    String generatedInternalName = internalName + SUFFIX + "_" + number;
    String descriptor = Type.getDescriptor(baseClass);

    cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, generatedInternalName, null, internalName, null);
    writeAnnotations(cw, delegateClass);
    writeConstructor(internalName, descriptor, cw);
    cw.visitEnd();//from   w  ww.j  a  v  a 2 s . co  m
    return cw.toByteArray();
}

From source file:org.graalvm.compiler.replacements.test.DeoptimizeOnExceptionTest.java

License:Open Source License

private static byte[] makeClazz() {
    // Code generated the class below using asm.
    String clazzName = DeoptimizeOnExceptionTest.class.getName().replace('.', '/');
    final ClassWriter w = new ClassWriter(0);
    w.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, "t/TestJSR", null, "java/lang/Object",
            new String[] { "java/lang/Runnable" });
    MethodVisitor mv = w.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, new String[] {});
    mv.visitCode();//from w ww.j  av a  2  s.c  o  m
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
    mv.visitInsn(Opcodes.RETURN);
    mv.visitMaxs(10, 10);
    mv.visitEnd();

    mv = w.visitMethod(Opcodes.ACC_PUBLIC, "run", "()V", null, null);
    mv.visitCode();
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, clazzName, "getM", "()Ljava/lang/Object;", false);
    Label l1 = new Label();
    mv.visitJumpInsn(Opcodes.JSR, l1);
    mv.visitInsn(Opcodes.RETURN);

    mv.visitLabel(l1);
    mv.visitVarInsn(Opcodes.ASTORE, 1);

    Label lElse = new Label();
    Label lEnd = new Label();
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/System", "currentTimeMillis", "()J", false);
    mv.visitInsn(Opcodes.POP2);
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, clazzName, "getM", "()Ljava/lang/Object;", false);
    mv.visitInsn(Opcodes.DUP);
    mv.visitJumpInsn(Opcodes.IFNULL, lElse);
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, clazzName, "methodA", "()V", false);
    mv.visitJumpInsn(Opcodes.GOTO, lEnd);
    mv.visitLabel(lElse);
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, clazzName, "methodB", "()V", false);
    mv.visitLabel(lEnd);

    mv.visitVarInsn(Opcodes.RET, 1);
    mv.visitMaxs(10, 10);
    mv.visitEnd();
    return w.toByteArray();
}

From source file:org.gradle.groovy.scripts.AsmBackedEmptyScriptGenerator.java

License:Apache License

private <T extends Script> Class<? extends T> generateEmptyScriptClass(Class<T> type) {
    ClassWriter visitor = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    String typeName = type.getName() + "_Decorated";
    Type generatedType = Type.getType("L" + typeName.replaceAll("\\.", "/") + ";");
    Type superclassType = Type.getType(type);
    visitor.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, generatedType.getInternalName(), null,
            superclassType.getInternalName(), new String[0]);

    // Constructor

    String constructorDescriptor = Type.getMethodDescriptor(Type.VOID_TYPE, new Type[0]);
    MethodVisitor methodVisitor = visitor.visitMethod(Opcodes.ACC_PUBLIC, "<init>", constructorDescriptor, null,
            new String[0]);
    methodVisitor.visitCode();/* ww w.j a v  a 2  s  . c o m*/

    // super()
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superclassType.getInternalName(), "<init>",
            constructorDescriptor);

    methodVisitor.visitInsn(Opcodes.RETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    // run() method

    String runDesciptor = Type.getMethodDescriptor(Type.getType(Object.class), new Type[0]);
    methodVisitor = visitor.visitMethod(Opcodes.ACC_PUBLIC, "run", runDesciptor, null, new String[0]);
    methodVisitor.visitCode();

    // return null
    methodVisitor.visitInsn(Opcodes.ACONST_NULL);

    methodVisitor.visitInsn(Opcodes.ARETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    visitor.visitEnd();

    byte[] bytecode = visitor.toByteArray();
    return (Class<T>) ReflectionUtil.invoke(type.getClassLoader(), "defineClass",
            new Object[] { typeName, bytecode, 0, bytecode.length });
}

From source file:org.gradle.initialization.ExceptionDecoratingClassGenerator.java

License:Apache License

private <T> Class<? extends T> doGenerate(Class<T> type) {
    ClassWriter visitor = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    String typeName = StringUtils.substringBeforeLast(type.getName(), ".") + ".LocationAware"
            + type.getSimpleName();//from   ww w.  j a  v a2s . c  om
    Type generatedType = Type.getType("L" + typeName.replaceAll("\\.", "/") + ";");
    Type superclassType = Type.getType(type);

    visitor.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, generatedType.getInternalName(), null,
            superclassType.getInternalName(),
            new String[] { Type.getType(LocationAwareException.class).getInternalName() });

    Type helperType = Type.getType(ExceptionHelper.class);
    Type throwableType = Type.getType(Throwable.class);
    Type scriptSourceType = Type.getType(ScriptSource.class);
    Type integerType = Type.getType(Integer.class);

    // GENERATE private ExceptionHelper helper;
    visitor.visitField(Opcodes.ACC_PRIVATE, "helper", helperType.getDescriptor(), null, null);

    // GENERATE <init>(<type> target, ScriptSource source, Integer lineNumber)

    String methodDescriptor = Type.getMethodDescriptor(Type.VOID_TYPE,
            new Type[] { superclassType, scriptSourceType, integerType });
    MethodVisitor methodVisitor = visitor.visitMethod(Opcodes.ACC_PUBLIC, "<init>", methodDescriptor, null,
            new String[0]);
    methodVisitor.visitCode();

    boolean noArgsConstructor;
    try {
        type.getConstructor(type);
        noArgsConstructor = false;
    } catch (NoSuchMethodException e) {
        try {
            type.getConstructor();
            noArgsConstructor = true;
        } catch (NoSuchMethodException e1) {
            throw new IllegalArgumentException(String.format(
                    "Cannot create subtype for exception '%s'. It needs a zero-args or copy constructor.",
                    type.getName()));
        }
    }

    if (noArgsConstructor) {
        // GENERATE super()
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superclassType.getInternalName(), "<init>",
                Type.getMethodDescriptor(Type.VOID_TYPE, new Type[0]));
        // END super()
    } else {
        // GENERATE super(target)
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
        methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superclassType.getInternalName(), "<init>",
                Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { superclassType }));
        // END super(target)
    }

    // GENERATE helper = new ExceptionHelper(this, target, source, lineNumber)
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);

    methodVisitor.visitTypeInsn(Opcodes.NEW, helperType.getInternalName());
    methodVisitor.visitInsn(Opcodes.DUP);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
    methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, helperType.getInternalName(), "<init>",
            Type.getMethodDescriptor(Type.VOID_TYPE,
                    new Type[] { throwableType, throwableType, scriptSourceType, integerType }));

    methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, generatedType.getInternalName(), "helper",
            helperType.getDescriptor());

    // END helper = new ExceptionHelper(target)

    methodVisitor.visitInsn(Opcodes.RETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    // END <init>(<type> target, ScriptSource source, Integer lineNumber)

    for (Method method : ExceptionHelper.class.getDeclaredMethods()) {
        // GENERATE public <type> <method>() { return helper.<method>(); }
        methodDescriptor = Type.getMethodDescriptor(Type.getType(method.getReturnType()), new Type[0]);
        methodVisitor = visitor.visitMethod(Opcodes.ACC_PUBLIC, method.getName(), methodDescriptor, null,
                new String[0]);
        methodVisitor.visitCode();

        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitFieldInsn(Opcodes.GETFIELD, generatedType.getInternalName(), "helper",
                helperType.getDescriptor());
        methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, helperType.getInternalName(), method.getName(),
                methodDescriptor);

        methodVisitor.visitInsn(Opcodes.ARETURN);
        methodVisitor.visitMaxs(0, 0);
        methodVisitor.visitEnd();
        // END public <type> <method>() { return helper.<method>(); }
    }

    visitor.visitEnd();

    byte[] bytecode = visitor.toByteArray();
    return (Class<T>) ReflectionUtil.invoke(type.getClassLoader(), "defineClass",
            new Object[] { typeName, bytecode, 0, bytecode.length });
}

From source file:org.hua.ast.visitors.BytecodeGeneratorASTVisitor.java

@Override
public void visit(ClassDefinition node) throws ASTVisitorException {
    ClassNode classNode = new ClassNode();
    cn = classNode;// www .java  2 s .c  om

    cn.version = Opcodes.V1_5;
    cn.superName = "java/lang/Object";
    cn.name = node.getIdentifier();
    cn.access = Opcodes.ACC_PUBLIC;

    // create constructor
    mn = new MethodNode(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
    mn.instructions.add(new VarInsnNode(Opcodes.ALOAD, 0));
    mn.instructions.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false));
    mn.instructions.add(new InsnNode(Opcodes.RETURN));

    mn.maxLocals = 1;
    mn.maxStack = 1;
    classNode.methods.add(mn);

    node.getFfDefinitions().accept(this);

    // IMPORTANT: this should be dynamically calculated
    // use COMPUTE_MAXS when computing the ClassWriter,
    // e.g. new ClassWriter(ClassWriter.COMPUTE_MAXS)
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    //         ClassVisitor ca = new CheckClassAdapter(cw);
    //         cn.accept(new CheckClassAdapter(ca));
    TraceClassVisitor cv = new TraceClassVisitor(cw, new PrintWriter(System.out));

    cn.accept(cv);
    //get code
    byte code[] = cw.toByteArray();

    Logger.getLogger(BytecodeGeneratorASTVisitor.class.getName())
            .info("Writing " + node.getIdentifier() + " class to .class file");
    // update to file
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(node.getIdentifier() + ".class");
        fos.write(code);
        fos.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(BytecodeGeneratorASTVisitor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(BytecodeGeneratorASTVisitor.class.getName()).log(Level.SEVERE, null, ex);
    }

    cn = null;
    System.out.println("##### finished writing to file");

}

From source file:org.jacoco.core.analysis.AnalyzerTest.java

License:Open Source License

@Test
public void should_ignore_synthetic_classes() throws Exception {
    final ClassWriter cw = new ClassWriter(0);
    cw.visit(Opcodes.V1_5, Opcodes.ACC_SYNTHETIC, "Foo", null, "java/lang/Object", null);
    cw.visitEnd();/*  w w  w  . ja  va 2 s. c  o  m*/
    final byte[] bytes = cw.toByteArray();

    analyzer.analyzeClass(bytes, "");

    assertTrue(classes.isEmpty());
}