Search in sources :

Example 66 with ClassWriter

use of org.objectweb.asm.ClassWriter in project sonar-java by SonarSource.

the class BytecodeListingParser method getCFG.

public static BytecodeCFG getCFG(String bytecodeInstructions) {
    // Define class and method stub for instructions
    ClassWriter cw = new ClassWriter(Opcodes.ASM5);
    cw.visit(V1_8, ACC_PUBLIC, "A", null, "java/lang/Object", null);
    MethodVisitor mv = cw.visitMethod(ACC_PRIVATE, "test", "()V", null, null);
    JavaSymbol.MethodJavaSymbol methodStub = new JavaSymbol.MethodJavaSymbol(0, "test", null);
    Map<Integer, Label> labelIndexes = new HashMap<>();
    String[] lines = bytecodeInstructions.split("\n");
    for (String line : lines) {
        visitLine(line.trim().split(" "), mv, labelIndexes);
    }
    mv.visitEnd();
    cw.visitEnd();
    byte[] bytes = cw.toByteArray();
    return Instructions.getBytecodeCFG(bytes);
}
Also used : JavaSymbol(org.sonar.java.resolve.JavaSymbol) HashMap(java.util.HashMap) Label(org.objectweb.asm.Label) ClassWriter(org.objectweb.asm.ClassWriter) MethodVisitor(org.objectweb.asm.MethodVisitor)

Example 67 with ClassWriter

use of org.objectweb.asm.ClassWriter in project MCPConfig by MinecraftForge.

the class MergeJar method processClass.

public static byte[] processClass(byte[] cIn, byte[] sIn) {
    ClassNode cClassNode = getClassNode(cIn);
    ClassNode sClassNode = getClassNode(sIn);
    processFields(cClassNode, sClassNode);
    processMethods(cClassNode, sClassNode);
    processInners(cClassNode, sClassNode);
    ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    cClassNode.accept(writer);
    return writer.toByteArray();
}
Also used : InnerClassNode(org.objectweb.asm.tree.InnerClassNode) ClassNode(org.objectweb.asm.tree.ClassNode) ClassWriter(org.objectweb.asm.ClassWriter)

Example 68 with ClassWriter

use of org.objectweb.asm.ClassWriter in project cdap by caskdata.

the class AuthEnforceRewriter method rewriteClass.

@Override
@Nullable
public byte[] rewriteClass(String className, InputStream input) throws IOException {
    byte[] classBytes = ByteStreams.toByteArray(input);
    // First pass: Check the class to have a method with AuthEnforce annotation if found store the annotation details
    // and parameters for the method for second pass in which class rewrite will be performed.
    ClassReader cr = new ClassReader(classBytes);
    // SKIP_CODE SKIP_DEBUG and SKIP_FRAMESto make the first pass faster since in the first pass we just want to
    // process annotations to check if the class has any method with AuthEnforce annotation. If such method is found
    // we also store the parameters which has the named annotations as specified in the entities field of the
    // AuthEnforce.
    AuthEnforceAnnotationVisitor classVisitor = new AuthEnforceAnnotationVisitor(className);
    cr.accept(classVisitor, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
    Map<Method, AnnotationDetail> methodAnnotations = classVisitor.getMethodAnnotations();
    if (methodAnnotations.isEmpty()) {
        // if no AuthEnforce annotation was found then return the original class bytes
        return classBytes;
    }
    // We found some method which has AuthEnforce annotation so we need a second pass in to rewrite the class
    // in second pass we COMPUTE_FRAMES and visit classes with EXPAND_FRAMES
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
    cr.accept(new AuthEnforceAnnotationRewriter(className, cw, classVisitor.getFieldDetails(), methodAnnotations), ClassReader.EXPAND_FRAMES);
    return cw.toByteArray();
}
Also used : ClassReader(org.objectweb.asm.ClassReader) Method(org.objectweb.asm.commons.Method) ClassWriter(org.objectweb.asm.ClassWriter) Nullable(javax.annotation.Nullable)

Example 69 with ClassWriter

use of org.objectweb.asm.ClassWriter in project cdap by caskdata.

the class SparkClassRewriter method rewriteSparkNetworkClass.

/**
 * Rewrite Spark classes in the network package for Netty 4.1 compatibility.
 *
 * <ol>
 *   <li>FileRegion interface has a new method, transferred() that replaces the old transfered() method</li>
 *   <li>
 *     FileRegion interface, which implements ReferenceCounted interface, has a new touch(Object hint) method
 *     that is not implemented by the AbstractReferenceCounted based class.
 *   </li>
 * </ol>
 *
 * @param input the source bytecode
 * @return the rewritten class or {@code null} if rewrite is not needed
 */
@Nullable
private byte[] rewriteSparkNetworkClass(InputStream byteCodeStream) throws IOException {
    ClassReader cr = new ClassReader(byteCodeStream);
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    // Scan for class type and methods to see if the rewriting is needed
    final AtomicBoolean rewritten = new AtomicBoolean(false);
    cr.accept(new ClassVisitor(Opcodes.ASM5, cw) {

        private Type classType;

        private boolean isFileRegion;

        private boolean hasTransferredMethod;

        private boolean hasTouchMethod;

        @Override
        public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
            // See if it implements netty FileRegion.
            if (interfaces != null && Arrays.asList(interfaces).contains(NETTY_FILE_REGION_TYPE.getInternalName())) {
                isFileRegion = true;
                classType = Type.getObjectType(name);
            }
            super.visit(version, access, name, signature, superName, interfaces);
        }

        @Override
        public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
            // See if the class has the method `transferred()`.
            if ("transferred".equals(name) && Type.getArgumentTypes(desc).length == 0) {
                hasTransferredMethod = true;
            }
            // See if the class has the method `touch(Object)`.
            if ("touch".equals(name)) {
                Type[] args = Type.getArgumentTypes(desc);
                if (args.length == 1 && Type.getType(Object.class).equals(args[0])) {
                    hasTouchMethod = true;
                }
            }
            return super.visitMethod(access, name, desc, signature, exceptions);
        }

        @Override
        public void visitEnd() {
            if (isFileRegion) {
                if (!hasTransferredMethod) {
                    // Generate the `long transferred()` method by calling `return transfered();` method
                    Method method = new Method("transferred", Type.LONG_TYPE, EMPTY_ARGS);
                    MethodVisitor mv = super.visitMethod(Opcodes.ACC_PUBLIC, method.getName(), method.getDescriptor(), null, null);
                    GeneratorAdapter generator = new GeneratorAdapter(Opcodes.ACC_PUBLIC, method, mv);
                    generator.loadThis();
                    generator.invokeVirtual(classType, new Method("transfered", Type.LONG_TYPE, EMPTY_ARGS));
                    generator.returnValue();
                    generator.endMethod();
                    rewritten.set(true);
                }
                if (!hasTouchMethod) {
                    // that FileRegion overridden to have FileRegion as return type
                    for (Method m : NETTY_FILE_REGION_RC_METHODS) {
                        // Need to generate the actual implementation of the touch methods
                        if (m.getName().equals("touch")) {
                            String desc = Type.getMethodDescriptor(NETTY_FILE_REGION_TYPE, m.getArgumentTypes());
                            MethodVisitor mv = super.visitMethod(Opcodes.ACC_PUBLIC, m.getName(), desc, null, null);
                            GeneratorAdapter generator = new GeneratorAdapter(mv, Opcodes.ACC_PUBLIC, m.getName(), desc);
                            generator.loadThis();
                            generator.returnValue();
                            generator.endMethod();
                        }
                        // Generate the synthetic method by just calling the actual method
                        int syntheticAccess = Opcodes.ACC_PUBLIC | Opcodes.ACC_BRIDGE | Opcodes.ACC_SYNTHETIC;
                        MethodVisitor mv = super.visitMethod(syntheticAccess, m.getName(), m.getDescriptor(), null, null);
                        GeneratorAdapter generator = new GeneratorAdapter(syntheticAccess, m, mv);
                        generator.loadThis();
                        for (int i = 0; i < m.getArgumentTypes().length; i++) {
                            generator.loadArg(i);
                        }
                        generator.invokeVirtual(classType, new Method(m.getName(), NETTY_FILE_REGION_TYPE, m.getArgumentTypes()));
                        generator.returnValue();
                        generator.endMethod();
                    }
                    rewritten.set(true);
                }
            }
            super.visitEnd();
        }
    }, 0);
    return rewritten.get() ? cw.toByteArray() : null;
}
Also used : ClassVisitor(org.objectweb.asm.ClassVisitor) Method(org.objectweb.asm.commons.Method) ClassWriter(org.objectweb.asm.ClassWriter) MethodVisitor(org.objectweb.asm.MethodVisitor) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Type(org.objectweb.asm.Type) ClassReader(org.objectweb.asm.ClassReader) GeneratorAdapter(org.objectweb.asm.commons.GeneratorAdapter) Nullable(javax.annotation.Nullable)

Example 70 with ClassWriter

use of org.objectweb.asm.ClassWriter in project cdap by caskdata.

the class SparkClassRewriter method rewriteDStreamGraph.

/**
 * Rewrites the DStreamGraph class for calls to parallel array with a call to
 * SparkRuntimeUtils#setTaskSupport(ParArray).
 */
private byte[] rewriteDStreamGraph(InputStream byteCodeStream) throws IOException {
    ClassReader cr = new ClassReader(byteCodeStream);
    ClassWriter cw = new ClassWriter(0);
    cr.accept(new ClassVisitor(Opcodes.ASM5, cw) {

        @Override
        public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
            MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);
            return new MethodVisitor(Opcodes.ASM5, mv) {

                @Override
                public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {
                    super.visitMethodInsn(opcode, owner, name, desc, itf);
                    // If detected call to ArrayBuffer.par(), set the TaskSupport to avoid thread leak.
                    // INVOKEVIRTUAL scala/collection/mutable/ ArrayBuffer.par ()Lscala/collection/parallel/mutable/ParArray;
                    Type returnType = Type.getReturnType(desc);
                    if (opcode == Opcodes.INVOKEVIRTUAL && name.equals("par") && owner.equals("scala/collection/mutable/ArrayBuffer") && returnType.getClassName().equals("scala.collection.parallel.mutable.ParArray")) {
                        super.visitMethodInsn(Opcodes.INVOKESTATIC, SPARK_RUNTIME_UTILS_TYPE.getInternalName(), "setTaskSupport", Type.getMethodDescriptor(returnType, returnType), false);
                    }
                }
            };
        }
    }, ClassReader.EXPAND_FRAMES);
    return cw.toByteArray();
}
Also used : Type(org.objectweb.asm.Type) ClassReader(org.objectweb.asm.ClassReader) ClassVisitor(org.objectweb.asm.ClassVisitor) ClassWriter(org.objectweb.asm.ClassWriter) MethodVisitor(org.objectweb.asm.MethodVisitor)

Aggregations

ClassWriter (org.objectweb.asm.ClassWriter)502 ClassReader (org.objectweb.asm.ClassReader)285 MethodVisitor (org.objectweb.asm.MethodVisitor)127 Test (org.junit.Test)99 ClassVisitor (org.objectweb.asm.ClassVisitor)88 ClassNode (org.objectweb.asm.tree.ClassNode)70 IOException (java.io.IOException)62 Label (org.objectweb.asm.Label)55 SemanticVersioningClassVisitor (org.apache.aries.versioning.utils.SemanticVersioningClassVisitor)52 HashSet (java.util.HashSet)37 Method (java.lang.reflect.Method)36 Type (org.objectweb.asm.Type)33 BinaryCompatibilityStatus (org.apache.aries.versioning.utils.BinaryCompatibilityStatus)32 File (java.io.File)30 InvocationTargetException (java.lang.reflect.InvocationTargetException)28 FieldVisitor (org.objectweb.asm.FieldVisitor)28 FileOutputStream (java.io.FileOutputStream)27 InputStream (java.io.InputStream)26 MethodNode (org.objectweb.asm.tree.MethodNode)25 OuterClass (com.android.tools.layoutlib.create.dataclass.OuterClass)23