Example usage for org.objectweb.asm Opcodes ACC_INTERFACE

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

Introduction

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

Prototype

int ACC_INTERFACE

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

Click Source Link

Usage

From source file:com.microsoft.applicationinsights.agent.internal.agent.ByteCodeUtilsTest.java

License:Open Source License

@Test
public void testIsInterface() throws Exception {
    assertTrue(ByteCodeUtils.isInterface(Opcodes.ACC_INTERFACE));
}

From source file:com.microsoft.applicationinsights.agent.internal.agent.ByteCodeUtilsTest.java

License:Open Source License

@Test
public void testNotIsInterface() throws Exception {
    assertFalse(ByteCodeUtils.isInterface(~Opcodes.ACC_INTERFACE));
}

From source file:com.mogujie.instantrun.IncrementalVisitor.java

License:Apache License

public static boolean instrumentClass(ZipEntry entry, ZipFile zipFile, ZipOutputStream zos,
        VisitorBuilder visitorBuilder, boolean isHotfix) throws IOException {
    byte[] classBytes = FileUtils.toByteArray(zipFile.getInputStream(entry));
    ClassReader classReader = new ClassReader(classBytes);
    // override the getCommonSuperClass to use the thread context class loader instead of
    // the system classloader. This is useful as ASM needs to load classes from the project
    // which the system classloader does not have visibility upon.
    // TODO: investigate if there is not a simpler way than overriding.
    ClassWriter classWriter = new ClassWriter(classReader, ClassWriter.COMPUTE_FRAMES) {
        @Override/*from   w  w w  .j av a 2  s  .co m*/
        protected String getCommonSuperClass(final String type1, final String type2) {
            Class<?> c, d;
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            try {
                c = Class.forName(type1.replace('/', '.'), false, classLoader);
                d = Class.forName(type2.replace('/', '.'), false, classLoader);
            } catch (ClassNotFoundException e) {
                // This may happen if we're processing class files which reference APIs not
                // available on the target device. In this case return a dummy value, since this
                // is ignored during dx compilation.
                return "instant/run/NoCommonSuperClass";
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            if (c.isAssignableFrom(d)) {
                return type1;
            }
            if (d.isAssignableFrom(c)) {
                return type2;
            }
            if (c.isInterface() || d.isInterface()) {
                return "java/lang/Object";
            } else {
                do {
                    c = c.getSuperclass();
                } while (!c.isAssignableFrom(d));
                return c.getName().replace('.', '/');
            }
        }
    };

    ClassNode classNode = new TransformAccessClassNode();
    classReader.accept(classNode, ClassReader.EXPAND_FRAMES);

    // when dealing with interface, we just copy the inputFile over without any changes unless
    // this is a package private interface.
    AccessRight accessRight = AccessRight.fromNodeAccess(classNode.access);
    ZipEntry nowEntry;
    if (isHotfix) {
        String name = entry.getName();
        name = name.substring(0, name.lastIndexOf(".class"));
        nowEntry = new ZipEntry(name + "$override" + ".class");
    } else {
        nowEntry = new ZipEntry(entry.getName());
    }

    if ((classNode.access & Opcodes.ACC_INTERFACE) != 0) {
        if (visitorBuilder.getOutputType() == OutputType.INSTRUMENT) {
            // don't change the name of interfaces.
            zos.putNextEntry(nowEntry);
            if (accessRight == AccessRight.PACKAGE_PRIVATE) {
                classNode.access = classNode.access | Opcodes.ACC_PUBLIC;
                classNode.accept(classWriter);
                zos.write(classWriter.toByteArray());
            } else {
                // just copy the input file over, no change.
                zos.write(classBytes);
            }
            zos.closeEntry();
            return true;
        } else {
            return false;
        }
    }

    List<ClassNode> parentsNodes = parseParents(zipFile, classNode);

    IncrementalVisitor visitor = visitorBuilder.build(classNode, parentsNodes, classWriter);
    classNode.accept(visitor);

    zos.putNextEntry(nowEntry);
    zos.write(classWriter.toByteArray());
    zos.closeEntry();

    if (isHotfix) {
        IncrementalChangeVisitor changeVisitor = (IncrementalChangeVisitor) visitor;
        if (changeVisitor.superMethods.size() > 0) {
            if (parentsNodes.size() <= 0) {
                throw new GradleException("not found " + changeVisitor.visitedClassName + " 's parents.");
            }
            SuperHelperVisitor superHelperVisitor = new SuperHelperVisitor(Opcodes.ASM5, changeVisitor,
                    parentsNodes.get(0));
            superHelperVisitor.start();
            String newName = entry.getName();
            newName = newName.substring(0, newName.lastIndexOf(".class"));
            newName += "$helper.class";
            ZipEntry zipEntry = new ZipEntry(newName);
            zos.putNextEntry(zipEntry);
            zos.write(superHelperVisitor.toByteArray());
            zos.closeEntry();
        }

    }
    return true;
}

From source file:com.mtso.blazer.JavaUtil.java

License:Open Source License

public static ArrayList retrieveSignaturesFromClass(InputStream classFileIS, int signId) throws Exception {

    /*/*  w w  w.  j  av a2  s  . c o  m*/
     * Dynamic array containing multiple signatures arrays
     */
    ArrayList signatures = new ArrayList();

    Object[] signature = new Object[7];
    signature[0] = new Boolean(false); //used for signature selection

    ClassNode classNode = new ClassNode();
    InputStream classFileInputStream = classFileIS;
    try {
        ClassReader classReader = new ClassReader(classFileInputStream);
        classReader.accept((ClassVisitor) classNode, 0);
    } finally {
        classFileInputStream.close();
    }

    Type classType = Type.getObjectType(classNode.name);

    if ((classNode.access & Opcodes.ACC_PUBLIC) != 0) {

        if ((classNode.access & Opcodes.ACC_INTERFACE) != 0) {
            signature[2] = "Interface"; //interface
        } else {
            signature[2] = "Class"; //class
        }

        String name = classType.getClassName();
        name = name.substring(name.lastIndexOf('.') + 1); //packages are not required
        signature[3] = name.substring(0, 1).toLowerCase() + name.substring(1); //convert to javaCase
        @SuppressWarnings("unchecked")
        List<MethodNode> methodNodes = classNode.methods;

        for (MethodNode methodNode : methodNodes) {

            Type[] argumentTypes = Type.getArgumentTypes(methodNode.desc);

            if ((methodNode.access & Opcodes.ACC_PUBLIC) != 0) {

                signature[4] = methodNode.name;

                if (methodNode.visibleAnnotations != null) {

                    Iterator c = methodNode.visibleAnnotations.iterator();
                    while (c.hasNext()) {
                        AnnotationNode anode = (AnnotationNode) c.next();
                        String annotations = anode.desc;
                        annotations = annotations.substring(annotations.lastIndexOf('/') + 1,
                                annotations.lastIndexOf(';'));
                        signature[6] = "@".concat(annotations); //convert to standard format
                    }
                }

                StringBuilder pars = new StringBuilder();

                for (int i = 0; i < argumentTypes.length; i++) {

                    Type argumentType = argumentTypes[i];
                    if (i > 0) {
                        pars.append(", ");
                    }
                    pars.append(argumentType.getClassName());
                }

                signature[5] = pars.toString();

                /* list here all exceptions */
                if (!signature[4].equals("<init>")) {
                    signature[1] = new Integer(signId);
                    signatures.add(signature.clone());
                    signId++;
                }
                signature[5] = "";
            }
            signature[4] = "";
            signature[6] = "";
        }
    }
    return signatures;
}

From source file:com.navercorp.pinpoint.profiler.instrument.ASMClassNodeAdapter.java

License:Apache License

public boolean isInterface() {
    return (classNode.access & Opcodes.ACC_INTERFACE) != 0;
}

From source file:com.navercorp.pinpoint.profiler.instrument.ASMClassWriter.java

License:Apache License

private boolean isInterface(final ClassReader classReader) {
    return (classReader.getAccess() & Opcodes.ACC_INTERFACE) != 0;
}

From source file:com.offbynull.coroutines.instrumenter.asm.FileSystemClassInformationRepository.java

License:Open Source License

private void populateSuperClassMapping(final InputStream is) throws IOException {
    ClassReader classReader = new ClassReader(is);
    String name = classReader.getClassName();

    if (hierarchyMap.containsKey(name)) {
        // duplicate encounter, ignore
        return;//ww  w .  j a v a  2s  .c  o m
    }

    String superName = classReader.getSuperName();
    String[] interfaces = classReader.getInterfaces();
    boolean interfaceMarker = (classReader.getAccess() & Opcodes.ACC_INTERFACE) != 0;

    hierarchyMap.put(name, new ClassInformation(superName, Arrays.asList(interfaces), interfaceMarker));
}

From source file:com.offbynull.coroutines.instrumenter.Instrumenter.java

License:Open Source License

/**
 * Instruments a class./*w w w  .  jav a 2  s .  c o m*/
 * @param input class file contents
 * @return instrumented class
 * @throws IllegalArgumentException if the class could not be instrumented for some reason
 * @throws NullPointerException if any argument is {@code null}
 */
public byte[] instrument(byte[] input) {
    Validate.notNull(input);
    Validate.isTrue(input.length > 0);

    // Read class as tree model -- because we're using SimpleClassNode, JSR blocks get inlined
    ClassReader cr = new ClassReader(input);
    ClassNode classNode = new SimpleClassNode();
    cr.accept(classNode, 0);

    // Is this class an interface? if so, skip it
    if ((classNode.access & Opcodes.ACC_INTERFACE) == Opcodes.ACC_INTERFACE) {
        return input.clone();
    }

    // Has this class already been instrumented? if so, skip it
    if (classNode.interfaces.contains(INSTRUMENTED_CLASS_TYPE.getInternalName())) {
        return input.clone();
    }

    // Find methods that need to be instrumented. If none are found, skip
    List<MethodNode> methodNodesToInstrument = findMethodsWithParameter(classNode.methods,
            CONTINUATION_CLASS_TYPE);
    if (methodNodesToInstrument.isEmpty()) {
        return input.clone();
    }

    // Add the "Instrumented" interface to this class so if we ever come back to it, we can skip it
    classNode.interfaces.add(INSTRUMENTED_CLASS_TYPE.getInternalName());

    // Instrument each method that was returned
    for (MethodNode methodNode : methodNodesToInstrument) {
        // Check if method is constructor -- we cannot instrument constructor
        Validate.isTrue(!"<init>".equals(methodNode.name), "Instrumentation of constructors not allowed");

        // Check for JSR blocks -- Emitted for finally blocks in older versions of the JDK. Should never happen since we already inlined
        // these blocks before coming to this point. This is a sanity check.
        Validate.isTrue(searchForOpcodes(methodNode.instructions, Opcodes.JSR).isEmpty(),
                "JSR instructions not allowed");

        // Find invocations of continuation points
        List<AbstractInsnNode> suspendInvocationInsnNodes = findInvocationsOf(methodNode.instructions,
                CONTINUATION_SUSPEND_METHOD);
        List<AbstractInsnNode> invokeInvocationInsnNodes = findInvocationsWithParameter(methodNode.instructions,
                CONTINUATION_CLASS_TYPE);

        // If there are no continuation points, we don't need to instrument this method. It'll be like any other normal method
        // invocation because it won't have the potential to pause or call in to another method that may potentially pause.
        if (suspendInvocationInsnNodes.isEmpty() && invokeInvocationInsnNodes.isEmpty()) {
            continue;
        }

        // Check for continuation points that use invokedynamic instruction, which are currently only used by lambdas. See comments in
        // validateNoInvokeDynamic to see why we need to do this.
        validateNoInvokeDynamic(suspendInvocationInsnNodes);
        validateNoInvokeDynamic(invokeInvocationInsnNodes);

        // Analyze method
        Frame<BasicValue>[] frames;
        try {
            frames = new Analyzer<>(new SimpleVerifier(classRepo)).analyze(classNode.name, methodNode);
        } catch (AnalyzerException ae) {
            throw new IllegalArgumentException("Analyzer failed to analyze method", ae);
        }

        // Manage arguments and additional local variables that we need for instrumentation
        int contArgIdx = getLocalVariableIndexOfContinuationParameter(methodNode);

        VariableTable varTable = new VariableTable(classNode, methodNode);
        Variable contArg = varTable.getArgument(contArgIdx); // Continuation argument
        Variable methodStateVar = varTable.acquireExtra(MethodState.class); // var shared between monitor and flow instrumentation
        Variable tempObjVar = varTable.acquireExtra(Object.class); // var shared between monitor and flow instrumentation

        // Generate code to deal with suspending around synchronized blocks
        MonitorInstrumentationVariables monitorInstrumentationVariables = new MonitorInstrumentationVariables(
                varTable, methodStateVar, tempObjVar);
        MonitorInstrumentationInstructions monitorInstrumentationLogic = new MonitorInstrumentationGenerator(
                methodNode, monitorInstrumentationVariables).generate();

        // Generate code to deal with flow control (makes use of some of the code generated in monitorInstrumentationLogic)
        FlowInstrumentationVariables flowInstrumentationVariables = new FlowInstrumentationVariables(varTable,
                contArg, methodStateVar, tempObjVar);
        FlowInstrumentationInstructions flowInstrumentationInstructions = new FlowInstrumentationGenerator(
                methodNode, suspendInvocationInsnNodes, invokeInvocationInsnNodes, frames,
                monitorInstrumentationLogic, flowInstrumentationVariables).generate();

        // Apply generated code
        applyInstrumentationLogic(methodNode, flowInstrumentationInstructions, monitorInstrumentationLogic);
    }

    // Write tree model back out as class
    ClassWriter cw = new SimpleClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, classRepo);
    classNode.accept(cw);
    return cw.toByteArray();
}

From source file:com.poolik.classfinder.info.ClassInfo.java

License:BSD License

/**
 * Convert an ASM access mask to a reflection Modifier mask.
 *
 * @param asmAccessMask the ASM access mask
 * @return the Modifier mask//ww w .  jav  a2  s  . co  m
 */
private int convertAccessMaskToModifierMask(int asmAccessMask) {
    int modifier = 0;

    // Convert the ASM access info into Reflection API modifiers.

    if ((asmAccessMask & Opcodes.ACC_FINAL) != 0)
        modifier |= Modifier.FINAL;

    if ((asmAccessMask & Opcodes.ACC_NATIVE) != 0)
        modifier |= Modifier.NATIVE;

    if ((asmAccessMask & Opcodes.ACC_INTERFACE) != 0)
        modifier |= Modifier.INTERFACE;

    if ((asmAccessMask & Opcodes.ACC_ABSTRACT) != 0)
        modifier |= Modifier.ABSTRACT;

    if ((asmAccessMask & Opcodes.ACC_PRIVATE) != 0)
        modifier |= Modifier.PRIVATE;

    if ((asmAccessMask & Opcodes.ACC_PROTECTED) != 0)
        modifier |= Modifier.PROTECTED;

    if ((asmAccessMask & Opcodes.ACC_PUBLIC) != 0)
        modifier |= Modifier.PUBLIC;

    if ((asmAccessMask & Opcodes.ACC_STATIC) != 0)
        modifier |= Modifier.STATIC;

    if ((asmAccessMask & Opcodes.ACC_STRICT) != 0)
        modifier |= Modifier.STRICT;

    if ((asmAccessMask & Opcodes.ACC_SYNCHRONIZED) != 0)
        modifier |= Modifier.SYNCHRONIZED;

    if ((asmAccessMask & Opcodes.ACC_TRANSIENT) != 0)
        modifier |= Modifier.TRANSIENT;

    if ((asmAccessMask & Opcodes.ACC_VOLATILE) != 0)
        modifier |= Modifier.VOLATILE;

    return modifier;
}

From source file:com.sun.fortress.runtimeSystem.Instantiater.java

License:Open Source License

@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
    // necessary?
    name = oprs.getMethodName(name);/*from  ww w  .java  2 s  .  co  m*/
    //System.out.println("old desc=" + desc);
    //desc = types.getMethodDesc(desc);
    //System.out.println("new desc=" + desc);
    String newDesc = types.getMethodDesc(desc);
    MethodVisitor mv = cv.visitMethod(access, name, newDesc, signature, exceptions);

    if (!desc.equals(newDesc)) { // catch flattened tuples
        String params = desc.substring(desc.indexOf("(") + 1, //TODO: wrong if nested parens
                desc.indexOf(")"));
        String newParams = newDesc.substring(newDesc.indexOf("(") + 1, newDesc.indexOf(")"));
        if (params.split(";").length == 1 && //single generic parameter 
                newParams.startsWith("LTuple")) { //tuple substituted in
            //System.out.println(access + " " + name + " " + signature + " " +this.instanceName);
            if ((this.access_flags & Opcodes.ACC_INTERFACE) == 0 && //not in an interface
                    (access & Opcodes.ACC_STATIC) == 0) { //and not a static method, so generate a body  

                //extract the parameters and create strings for the types 
                List<String> paramList = InstantiationMap.extractStringParameters(newParams,
                        newParams.indexOf(Naming.LEFT_OXFORD),
                        InstantiationMap.templateClosingRightOxford(newParams), new ArrayList<String>());
                String rawParams = "";
                for (String p : paramList)
                    rawParams = rawParams + Naming.internalToDesc(p);
                final String altDesc = newDesc.substring(0, newDesc.indexOf("(") + 1) + rawParams
                        + newDesc.substring(newDesc.indexOf(")"), newDesc.length());
                String tuple_params = InstantiatingClassloader.stringListToTuple(paramList);
                String make_sig = InstantiatingClassloader.toJvmSig(paramList,
                        Naming.javaDescForTaggedFortressType(tuple_params));

                MethodVisitor altMv = cv.visitMethod(access, name, altDesc, signature, exceptions);

                altMv.visitVarInsn(Opcodes.ALOAD, 0); //load this

                final int n = paramList.size(); //load the parameters
                for (int i = 1; i <= n; i++) {
                    altMv.visitVarInsn(Opcodes.ALOAD, i);
                }
                altMv.visitMethodInsn(Opcodes.INVOKESTATIC, InstantiatingClassloader.CONCRETE_ + tuple_params,
                        "make", make_sig); //create a tuple from the parameters

                if (name.equals("<init>")) {
                    altMv.visitMethodInsn(Opcodes.INVOKESPECIAL, this.instanceName, name, newDesc); //call original method
                    altMv.visitInsn(Opcodes.RETURN); //return
                } else {
                    altMv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, this.instanceName, name, newDesc); //call original method
                    altMv.visitInsn(Opcodes.ARETURN); //return
                }
                altMv.visitMaxs(Naming.ignoredMaxsParameter, Naming.ignoredMaxsParameter);
                altMv.visitEnd();
            }
        }
    }
    return new MethodInstantiater(mv, types, icl);
}