Example usage for org.objectweb.asm.tree ClassNode ClassNode

List of usage examples for org.objectweb.asm.tree ClassNode ClassNode

Introduction

In this page you can find the example usage for org.objectweb.asm.tree ClassNode ClassNode.

Prototype

public ClassNode() 

Source Link

Document

Constructs a new ClassNode .

Usage

From source file:org.evosuite.runtime.instrumentation.RuntimeInstrumentation.java

License:Open Source License

public boolean isAlreadyInstrumented(ClassReader reader) {
    ClassNode classNode = new ClassNode();

    int readFlags = ClassReader.SKIP_FRAMES | ClassReader.SKIP_CODE;
    reader.accept(classNode, readFlags);
    for (String interfaceName : ((List<String>) classNode.interfaces)) {
        if (InstrumentedClass.class.getName().equals(interfaceName.replace('/', '.')))
            return true;
    }//from   www  .jav  a2  s  .  c om
    return false;
}

From source file:org.evosuite.setup.DependencyAnalysis.java

License:Open Source License

private static ClassNode loadClassNode(String className) throws IOException {

    InputStream classStream = ResourceList
            .getInstance(TestGenerationContext.getInstance().getClassLoaderForSUT())
            .getClassAsStream(className);
    if (classStream == null) {
        // This used to throw an IOException that leads to null being
        // returned, so for now we're just returning null directly
        // TODO: Proper treatment of missing classes (can also be
        //       invalid calls, e.g. [L/java/lang/Object;)
        logger.info("Could not find class file: " + className);
        return null;
    }/*from   w w w . j a v  a2  s.  c o  m*/
    ClassNode cn = new ClassNode();
    try {
        ClassReader reader = new ClassReader(classStream);
        reader.accept(cn, ClassReader.SKIP_FRAMES); // |
        // ClassReader.SKIP_DEBUG);
    } finally {
        classStream.close(); // ASM does not close the stream
    }
    return cn;
}

From source file:org.evosuite.setup.InheritanceTreeGenerator.java

License:Open Source License

private static void analyzeClassStream(InheritanceTree inheritanceTree, InputStream inputStream,
        boolean onlyPublic) {
    try {//from  w w w.j a  v a  2  s .  c  o  m
        ClassReader reader = new ClassReader(inputStream);
        inputStream.close();

        ClassNode cn = new ClassNode();
        reader.accept(cn, ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG | ClassReader.SKIP_CODE);
        analyzeClassNode(inheritanceTree, cn, onlyPublic);

    } catch (IOException e) {
        logger.error("", e);
    } catch (java.lang.ArrayIndexOutOfBoundsException e) {
        logger.error("ASM Error while reading class (" + e.getMessage() + ")");
    }
}

From source file:org.evosuite.testcarver.extraction.CarvingClassLoader.java

License:Open Source License

private Class<?> instrumentClass(String fullyQualifiedTargetClass) throws ClassNotFoundException {
    logger.warn("Instrumenting class '" + fullyQualifiedTargetClass + "'.");

    try {/* w  w w .ja  va  2  s  .  c o  m*/
        String className = fullyQualifiedTargetClass.replace('.', '/');

        InputStream is = ResourceList.getInstance(TestGenerationContext.getInstance().getClassLoaderForSUT())
                .getClassAsStream(className);
        if (is == null) {
            throw new ClassNotFoundException("Class '" + className + ".class"
                    + "' should be in target project, but could not be found!");
        }

        ClassReader reader = new ClassReader(is);
        ClassNode classNode = new ClassNode();
        reader.accept(classNode, ClassReader.SKIP_FRAMES);
        instrumenter.transformClassNode(classNode, className);
        ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
        classNode.accept(new JSRInlinerClassVisitor(writer));
        //classNode.accept(writer);
        byte[] byteBuffer = writer.toByteArray();
        Class<?> result = defineClass(fullyQualifiedTargetClass, byteBuffer, 0, byteBuffer.length);
        if (Modifier.isPrivate(result.getModifiers())) {
            logger.info("REPLACING PRIVATE CLASS " + fullyQualifiedTargetClass);
            result = super.loadClass(fullyQualifiedTargetClass);
        }
        classes.put(fullyQualifiedTargetClass, result);
        logger.info("Keeping class: " + fullyQualifiedTargetClass);
        return result;
    } catch (Throwable t) {
        logger.info("Error: " + t);
        for (StackTraceElement e : t.getStackTrace()) {
            logger.info(e.toString());
        }
        throw new ClassNotFoundException(t.getMessage(), t);
    }
}

From source file:org.evosuite.testcarver.instrument.Instrumenter.java

License:Open Source License

public byte[] instrument(final String className, final byte[] classfileBuffer)
        throws IllegalClassFormatException {
    logger.debug("Start instrumenting class {}", className);

    final ClassReader cr = new ClassReader(classfileBuffer);
    final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    final ClassNode cn = new ClassNode();
    cr.accept(cn, ClassReader.SKIP_DEBUG);

    if (!TransformerUtil.isClassConsideredForInstrumentation(className)) {
        logger.debug("Class {} has not been instrumented because its name is on the blacklist", className);
        return classfileBuffer;
    }/*from w  w w .  j a  v a2  s  . c om*/

    try {
        this.transformClassNode(cn, className);

        cn.accept(cw);

        return cw.toByteArray();

    } catch (final Throwable t) {
        logger.error("An error occurred while instrumenting class {} -> returning unmodified version",
                className, t);
        return classfileBuffer;
    }
}

From source file:org.evosuite.testcarver.instrument.Transformer.java

License:Open Source License

@Override
public byte[] transform(final ClassLoader loader, final String className, final Class<?> classBeingRedefined,
        final ProtectionDomain protectionDomain, final byte[] classFileBuffer)
        throws IllegalClassFormatException {
    logger.debug("transforming {}", className);

    if (!Capturer.isCapturing()) {
        logger.debug("class {} has not been transformed because Capturer is not active", className);
        return classFileBuffer;
    }/*from  w  ww .j ava2  s.  c o m*/

    if (!TransformerUtil.isClassConsideredForInstrumenetation(className)) {
        logger.debug("class {} has not been instrumented because its name is on the blacklist", className);
        return classFileBuffer;
    }

    final ClassReader cr = new ClassReader(classFileBuffer);
    final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    final ClassNode cn = new ClassNode();
    cr.accept(cn, ClassReader.SKIP_DEBUG);

    this.instrumenter.instrument(className, cn);

    cn.accept(cw);

    return cw.toByteArray();
}

From source file:org.f3.tools.bytecodeverifier.Verifier.java

License:Open Source License

private static boolean verify(String name, ClassReader reader, final PrintWriter err, boolean verbose) {
    if (verbose) {
        err.println("Verifying " + name);
    }//from  ww w.  ja va2  s . c  om
    ClassNode classNode = new ClassNode();
    reader.accept(new CheckClassAdapter(classNode), ClassReader.SKIP_DEBUG);

    Type syperType = classNode.superName == null ? null : Type.getObjectType(classNode.superName);
    List<Type> interfaces = new ArrayList<Type>();
    for (Object iface : classNode.interfaces) {
        interfaces.add(Type.getObjectType(iface.toString()));
    }

    List<MethodNode> methods = classNode.methods;
    for (int i = 0; i < methods.size(); i++) {
        MethodNode method = methods.get(i);
        SimpleVerifier verifier = new SimpleVerifier(Type.getObjectType(classNode.name), syperType, interfaces,
                false) {

            @Override
            protected boolean isAssignableFrom(Type t, Type u) {
                // FIXME: Assignment check in the superclass implementation uses
                // Class.forName to check currently loaded classes. We don't want 
                // to use loaded Class objects in the test. We leave the reference 
                // assignment compatibility checks for now.
                return true;
            }
        };

        Analyzer analyzer = new Analyzer(verifier);
        try {
            analyzer.analyze(classNode.name, method);
        } catch (AnalyzerException exp) {
            err.println("Verification failed for " + name);
            exp.printStackTrace(err);
            err.flush();
            return false;
        }
    }
    err.flush();
    return true;
}

From source file:org.fehrman.jcm.find.Find.java

License:CDDL license

@SuppressWarnings("unchecked")
private void processClass(PathIF path, int[] cnt, Properties props, InputStream istream) throws Exception
//----------------------------------------------------------------
{
    boolean match = false;
    boolean verbose = false;
    int lastdot = 0;
    String METHOD = "processClass(InputStream): ";
    String packageName = null;//w  ww.  ja  va  2s  . c  o m
    String className = null;
    String methodName = null;
    String srchValue = null;
    ClassNode classNode = null;
    ClassReader classReader = null;
    Type classType = null;
    List<MethodNode> methodNodes = null;
    OPERATOR oper = null;

    _logger.entering(CLASS, Thread.currentThread().getStackTrace()[1].getMethodName());

    classNode = new ClassNode();

    classReader = new ClassReader(istream);
    classReader.accept(classNode, 0);

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

    if (!StrUtil.isEmpty(className)) {
        lastdot = className.lastIndexOf(".");
        if (lastdot > 0 && lastdot < className.length()) {
            packageName = className.substring(0, lastdot);
            className = className.substring(lastdot + 1);
        } else {
            packageName = className;
        }

        path.push(new PathNode(NodeIF.Type.PACKAGE, packageName));
        path.push(new PathNode(NodeIF.Type.CLASS, className));

        if ((Boolean) props.get(PROP_DISP_DEBUG)) {
            this.out("DEBUG: " + METHOD + "[" + path.getNodes().size() + "] " + this.pathToString(path));
        }

        srchValue = props.getProperty(PROP_SRCH_VALUE);
        verbose = (Boolean) props.get(PROP_DISP_VERBOSE);

        oper = (OPERATOR) props.get(PROP_SRCH_OPERATOR);

        /*
         * PACKAGE NAME
         */

        if ((Boolean) props.get(PROP_SRCH_TYPE_PACKAGE) && !packageName.equals(className)) {
            cnt[CNT_PACKAGE]++;

            match = false;

            switch (oper) {
            case CONTAINS:
                if (packageName.toLowerCase().contains(srchValue)) {
                    match = true;
                }
                break;
            case EQUALS:
                if (packageName.toLowerCase().equals(srchValue)) {
                    match = true;
                }
                break;
            }

            if (match) {
                if (verbose) {
                    this.out(this.pathToStringVerbose(path));
                } else {
                    this.out(this.pathToString(path));
                }
                cnt[CNT_MATCH]++;
            }
        }

        /*
         * CLASS NAME
         */

        if ((Boolean) props.get(PROP_SRCH_TYPE_CLASS)) {
            cnt[CNT_CLASS]++;

            match = false;

            switch (oper) {
            case CONTAINS:
                if (className.toLowerCase().contains(srchValue)) {
                    match = true;
                }
                break;
            case EQUALS:
                if (className.toLowerCase().equals(srchValue)) {
                    match = true;
                }
                break;
            }

            if (match) {
                if (verbose) {
                    this.out(this.pathToStringVerbose(path));
                } else {
                    this.out(this.pathToString(path));
                }
                cnt[CNT_MATCH]++;
            }
        }

        /*
         * METHOD NAME
         */

        if ((Boolean) props.get(PROP_SRCH_TYPE_METHOD)) {
            methodNodes = classNode.methods;

            if (methodNodes != null) {
                for (MethodNode methodNode : methodNodes) {
                    methodName = methodNode.name;
                    if (methodName != null) {
                        cnt[CNT_METHOD]++;

                        match = false;

                        switch (oper) {
                        case CONTAINS:
                            if (methodName.toLowerCase().contains(srchValue)) {
                                match = true;
                            }
                            break;
                        case EQUALS:
                            if (methodName.toLowerCase().equals(srchValue)) {
                                match = true;
                            }
                            break;
                        }

                        if (match) {
                            if (verbose) {
                                path.push(new PathNode(NodeIF.Type.METHOD, this.processMethod(methodNode)));
                                this.out(this.pathToStringVerbose(path));
                                path.pop();
                            } else {
                                path.push(new PathNode(NodeIF.Type.METHOD, methodName));
                                this.out(this.pathToString(path));
                                path.pop();
                            }
                            cnt[CNT_MATCH]++;
                        }
                    }
                }
            }
        }
    }

    path.pop(); // class name
    path.pop(); // package name

    _logger.exiting(CLASS, Thread.currentThread().getStackTrace()[1].getMethodName());

    return;
}

From source file:org.formulacompiler.compiler.internal.build.bytecode.AbstractGenerator.java

License:Open Source License

public AbstractGenerator(Class _template, String _typeName, String _superName) throws IOException {
    super();/*from  w w w .  j  a  v  a2 s . c om*/
    this.cls = _template;
    this.typeName = _typeName;
    this.superName = _superName;
    this.clsNode = new ClassNode();
    new ClassReader(_template.getCanonicalName()).accept(clsNode, ACCEPT_FLAGS);
    this.unaryOperatorDispatchBuilder.indent(4);
    this.binaryOperatorDispatchBuilder.indent(4);
    this.functionDispatchBuilder.indent(3);
}

From source file:org.formulacompiler.compiler.internal.build.bytecode.AbstractGenerator.java

License:Open Source License

protected void genMethods() throws IOException {
    if (this.verbose)
        System.out.println("Processing " + clsNode.name);
    genMethods(clsNode.methods);//w  w  w  .j av a  2 s  .  c  om
    if (!"java/lang/Object".equals(clsNode.superName)) {
        final ClassNode outer = new ClassNode();
        new ClassReader(clsNode.superName).accept(outer, ACCEPT_FLAGS);
        if (this.verbose)
            System.out.println("Processing " + outer.name);
        genMethods(outer.methods);
    }
}