Example usage for org.objectweb.asm Opcodes V1_6

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

Introduction

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

Prototype

int V1_6

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

Click Source Link

Usage

From source file:co.cask.tigon.internal.io.DatumWriterGenerator.java

License:Apache License

/**
 * Generates a {@link DatumWriter} class for encoding data of the given output type with the given schema.
 * @param outputType Type information of the output data type.
 * @param schema Schema of the output data type.
 * @return A {@link co.cask.tigon.internal.asm.ClassDefinition} that contains generated class information.
 *///from  w  w w .  j  a va  2  s  .c o m
ClassDefinition generate(TypeToken<?> outputType, Schema schema) {
    classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES);

    TypeToken<?> interfaceType = getInterfaceType(outputType);

    // Generate the class
    String className = getClassName(interfaceType, schema);
    classType = Type.getObjectType(className);
    classWriter.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, className,
            Signatures.getClassSignature(interfaceType), Type.getInternalName(Object.class),
            new String[] { Type.getInternalName(interfaceType.getRawType()) });

    // Static schema hash field, for verification
    classWriter.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_STATIC + Opcodes.ACC_FINAL, "SCHEMA_HASH",
            Type.getDescriptor(String.class), null, schema.getSchemaHash().toString()).visitEnd();

    // Schema field
    classWriter.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL, "schema", Type.getDescriptor(Schema.class),
            null, null).visitEnd();

    // Encode method
    generateEncode(outputType, schema);

    // Constructor
    generateConstructor();

    ClassDefinition classDefinition = new ClassDefinition(classWriter.toByteArray(), className);
    // DEBUG block. Uncomment for debug
    //    co.cask.tigon.internal.asm.Debugs.debugByteCode(classDefinition, new java.io.PrintWriter(System.out));
    // End DEBUG block
    return classDefinition;
}

From source file:co.cask.tigon.internal.io.FieldAccessorGenerator.java

License:Apache License

ClassDefinition generate(TypeToken<?> classType, Field field, boolean publicOnly) {
    String name = String.format("%s$GeneratedAccessor%s", classType.getRawType().getName(), field.getName());
    if (name.startsWith("java.") || name.startsWith("javax.")) {
        name = "co.cask.tigon." + name;
        publicOnly = true;//from ww  w .  ja  v  a2s  .c o  m
    }
    this.className = name.replace('.', '/');

    if (publicOnly) {
        isPrivate = !Modifier.isPublic(field.getModifiers())
                || !Modifier.isPublic(field.getDeclaringClass().getModifiers());
    } else {
        isPrivate = Modifier.isPrivate(field.getModifiers())
                || Modifier.isPrivate(field.getDeclaringClass().getModifiers());
    }

    // Generate the class
    classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
    classWriter.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, className, null,
            Type.getInternalName(AbstractFieldAccessor.class), new String[0]);

    generateConstructor(field);
    generateGetter(field);
    generateSetter(field);

    classWriter.visitEnd();

    ClassDefinition classDefinition = new ClassDefinition(classWriter.toByteArray(), className);
    // DEBUG block. Uncomment for debug
    //    co.cask.tigon.internal.asm.Debugs.debugByteCode(classDefinition, new java.io.PrintWriter(System.out));
    // End DEBUG block
    return classDefinition;
}

From source file:com.android.build.gradle.integration.packaging.NativeSoPackagingFromJarTest.java

License:Apache License

/**
 * Creates a class and returns the byte[] with the class
 * @return//from w w w  .j  a va2 s. c  o m
 */
private static byte[] getDummyClassByteCode() {
    ClassWriter cw = new ClassWriter(0);
    FieldVisitor fv;
    MethodVisitor mv;
    AnnotationVisitor av0;

    cw.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, "com/foo/Foo", null, "java/lang/Object",
            null);

    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();

    mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "aaa", "()V", null, null);
    mv.visitCode();
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "test/Aaa", "bbb", "()V", false);
    mv.visitInsn(Opcodes.RETURN);
    mv.visitMaxs(1, 1);
    mv.visitEnd();

    mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "bbb", "()V", null, null);
    mv.visitCode();
    mv.visitInsn(Opcodes.RETURN);
    mv.visitMaxs(0, 1);
    mv.visitEnd();

    mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "ccc", "()V", null, null);
    mv.visitCode();
    mv.visitInsn(Opcodes.RETURN);
    mv.visitMaxs(0, 1);
    mv.visitEnd();

    cw.visitEnd();

    return cw.toByteArray();
}

From source file:com.android.build.gradle.internal.transforms.InstantRunTransform.java

License:Apache License

/**
 * Use asm to generate a concrete subclass of the AppPathLoaderImpl class.
 * It only implements one method ://from   w  w  w .j  av a2s .  c  om
 *      String[] getPatchedClasses();
 *
 * 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.
 */
private static void writePatchFileContents(@NonNull ImmutableList<String> patchFileContents,
        @NonNull File outputDir, long buildId) {

    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);

    // Add the build ID to force the patch file to be repackaged.
    cw.visitField(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC + Opcodes.ACC_FINAL, "BUILD_ID", "J", null, buildId);

    {
        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);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.android.build.gradle.shrinker.parser.ProguardFlags.java

License:Apache License

public void target(@NonNull String target) {
    int version;/*from  w  w w .  j  av a  2  s. c om*/
    switch (target) {
    case "8":
    case "1.8":
        version = Opcodes.V1_8;
        break;
    case "7":
    case "1.7":
        version = Opcodes.V1_7;
        break;
    case "6":
    case "1.6":
        version = Opcodes.V1_6;
        break;
    case "5":
    case "1.5":
        version = Opcodes.V1_5;
        break;
    case "1.4":
        version = Opcodes.V1_4;
        break;
    case "1.3":
        version = Opcodes.V1_3;
        break;
    case "1.2":
        version = Opcodes.V1_2;
        break;
    case "1.1":
        version = Opcodes.V1_1;
        break;
    default:
        throw new AssertionError("Unknown target " + target);
    }

    this.bytecodeVersion = new BytecodeVersion(version);
}

From source file:com.devexperts.aprof.transformer.AProfTransformer.java

License:Open Source License

private byte[] transformImpl(ClassLoader loader, String internalClassName, Class<?> classBeingRedefined,
        ProtectionDomain protectionDomain, byte[] classFileBuffer) throws IllegalClassFormatException {
    // measure time spent
    long start = System.currentTimeMillis();

    // init class info map for this classloader (if needed)
    ClassInfoMap classInfoMap = ciCache.getOrInitClassInfoMap(loader);

    // start transformation
    boolean anonymous = internalClassName == null;
    String cname = anonymous ? null : internalClassName.replace('/', '.');
    int classNo = AProfRegistry.incrementCount();
    if (!anonymous && isExcluded(cname)) {
        log(classNo, "Skipping transformation of excluded class", cname, loader, null);
        return null;
    }//  ww w  .  j  a  va2s .  c  o  m
    try {
        ClassReader cr = new ClassReader(classFileBuffer);

        // ---- 1ST PASS: ANALYZE CLASS ----

        // Also build class info if we don't have it yet in cache
        ClassInfo classInfo = anonymous ? null : classInfoMap.get(internalClassName);
        ClassInfoVisitor classInfoVisitor = classInfo == null && !anonymous
                ? new ClassInfoVisitor(classInfoMap.isInitTrackedClasses())
                : null;
        ClassAnalyzer classAnalyzer = new ClassAnalyzer(classNo, loader, classInfoVisitor);
        // set & check name if it was not anonymous
        if (!anonymous)
            classAnalyzer.initNames(internalClassName, cname);
        cr.accept(classAnalyzer, ClassReader.SKIP_DEBUG + ClassReader.SKIP_FRAMES);
        if (classInfoVisitor != null)
            classInfoMap.put(internalClassName, classInfoVisitor.result);
        // get names from analyzer (from inside class file) if it was anonymous
        if (anonymous) {
            internalClassName = classAnalyzer.binaryClassName;
            cname = classAnalyzer.cname;
        }

        // check if transformation is needed
        boolean transformationNeeded = false;
        for (Context methodContext : classAnalyzer.contexts) {
            if (methodContext.isTransformationNeeded()) {
                transformationNeeded = true;
                break;
            }
        }
        if (!transformationNeeded) {
            if (config.isVerbose()) // Note: shall have the same message length as "Transformed"
                log(classNo, "Analyzed   ", cname, loader, null);
            return null; // don't transform classes that don't need transformation
        }

        // ---- 2ND PASS: TRANSFORM CLASS ----

        boolean computeFrames = classAnalyzer.classVersion >= Opcodes.V1_6 && !config.isNoFrames();
        ClassWriter cw = computeFrames ? new FrameClassWriter(cr, loader)
                : new ClassWriter(ClassWriter.COMPUTE_MAXS);
        ClassVisitor classTransformer = new ClassTransformer(cw, classAnalyzer.contexts);
        int transformFlags = (config.isSkipDebug() ? ClassReader.SKIP_DEBUG : 0)
                + (config.isNoFrames() || computeFrames ? ClassReader.SKIP_FRAMES : 0);
        cr.accept(classTransformer, transformFlags);

        // Convert transformed class to byte array, dump (if needed) and return
        byte[] bytes = cw.toByteArray();
        dumpClass(classNo, internalClassName, cname, loader, bytes);
        if (config.isVerbose())
            log(classNo, "Transformed", cname, loader, null);
        return bytes;
    } catch (Throwable t) {
        log(classNo, "Failed to process", cname, loader, t);
        return null;
    } finally {
        AProfRegistry.incrementTime(System.currentTimeMillis() - start);
    }
}

From source file:com.electriccloud.maven.javac2.Javac2MojoSupport.java

License:Open Source License

/**
 * @param   version//from   ww w . ja  v  a  2s  .  com
 *
 * @return  the flags for class writer
 */
private static int getAsmClassWriterFlags(int version) {
    return version >= Opcodes.V1_6 && version != Opcodes.V1_1 ? ClassWriter.COMPUTE_FRAMES
            : ClassWriter.COMPUTE_MAXS;
}

From source file:com.facebook.buck.jvm.java.abi.ClassVisitorDriverFromElement.java

License:Apache License

/** Gets the class file version corresponding to the given source version constant. */
private static int sourceVersionToClassFileVersion(SourceVersion version) {
    switch (version) {
    case RELEASE_0:
        return Opcodes.V1_1; // JVMS8 4.1: 1.0 and 1.1 both support version 45.3 (Opcodes.V1_1)
    case RELEASE_1:
        return Opcodes.V1_1;
    case RELEASE_2:
        return Opcodes.V1_2;
    case RELEASE_3:
        return Opcodes.V1_3;
    case RELEASE_4:
        return Opcodes.V1_4;
    case RELEASE_5:
        return Opcodes.V1_5;
    case RELEASE_6:
        return Opcodes.V1_6;
    case RELEASE_7:
        return Opcodes.V1_7;
    case RELEASE_8:
        return Opcodes.V1_8;
    default://w  ww  . j  a v  a  2 s  . c  om
        throw new IllegalArgumentException(String.format("Unexpected source version: %s", version));
    }
}

From source file:com.facebook.buck.jvm.java.abi.SourceVersionUtils.java

License:Apache License

/** Gets the class file version corresponding to the given source version constant. */
public static int sourceVersionToClassFileVersion(SourceVersion version) {
    switch (version) {
    case RELEASE_0:
        return Opcodes.V1_1; // JVMS8 4.1: 1.0 and 1.1 both support version 45.3 (Opcodes.V1_1)
    case RELEASE_1:
        return Opcodes.V1_1;
    case RELEASE_2:
        return Opcodes.V1_2;
    case RELEASE_3:
        return Opcodes.V1_3;
    case RELEASE_4:
        return Opcodes.V1_4;
    case RELEASE_5:
        return Opcodes.V1_5;
    case RELEASE_6:
        return Opcodes.V1_6;
    case RELEASE_7:
        return Opcodes.V1_7;
    case RELEASE_8:
        return Opcodes.V1_8;
    default:/*from www  .ja  v a  2 s.  c  om*/
        throw new IllegalArgumentException(String.format("Unexpected source version: %s", version));
    }
}

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

License:Apache License

public void accept(TransformationContext context) {
    ClassVisitor cv = context.writer();//from w  ww . j  a  v a2s .c om

    // extends Object implements Computation<ValueType>
    SignatureWriter sign = new SignatureWriter();
    SignatureVisitor supsign = sign.visitSuperclass();
    supsign.visitClassType(OBJECT_NAME);
    supsign.visitEnd();
    SignatureVisitor iface = sign.visitInterface();
    iface.visitClassType(COMPUTATION_NAME);
    SignatureVisitor argsign = iface.visitTypeArgument('=');
    new SignatureReader(info.valueSignature).acceptType(argsign);
    argsign.visitEnd();

    cv.visit(Opcodes.V1_6, Opcodes.ACC_FINAL, info.computationClassName, sign.toString(), OBJECT_NAME,
            new String[] { COMPUTATION_NAME });

    cv.visitSource(info.ownerSource, null);
    cv.visitInnerClass(info.stateClassName, info.owner, info.stateSimpleName, 0);
    cv.visitInnerClass(info.computationClassName, info.owner, info.computationSimpleName, 0);

    cv.visitField(Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL, "state", stateDesc, null, null);

    generateConstructor(cv);
    generateExecute(cv);

    cv.visitEnd();
}