Example usage for org.objectweb.asm.util CheckClassAdapter CheckClassAdapter

List of usage examples for org.objectweb.asm.util CheckClassAdapter CheckClassAdapter

Introduction

In this page you can find the example usage for org.objectweb.asm.util CheckClassAdapter CheckClassAdapter.

Prototype

public CheckClassAdapter(final ClassVisitor classVisitor, final boolean checkDataFlow) 

Source Link

Document

Constructs a new CheckClassAdapter .

Usage

From source file:com.google.template.soy.jbcsrc.ClassData.java

License:Apache License

/**
 * Runs the {@link CheckClassAdapter} on this class in basic analysis mode.
 *
 * <p>Basic anaylsis mode can flag verification errors that don't depend on knowing complete type
 * information for the classes and methods being called.  This is useful for flagging simple
 * generation mistakes (e.g. stack underflows, method return type mismatches, accessing invalid
 * locals).  Additionally, the error messages are more useful than what the java verifier normally
 * presents.// w ww . j  a v  a2 s  . c  o  m
 */
void checkClass() {
    ClassNode cv = new ClassNode();
    new ClassReader(data).accept(new CheckClassAdapter(cv, true /* check data flow */), 0);
    // double check our fields while we are here.
    checkState(type.internalName().equals(cv.name));
    checkState(numberOfFields == cv.fields.size());
}

From source file:com.google.template.soy.jbcsrc.internal.ClassData.java

License:Apache License

/**
 * Runs the {@link CheckClassAdapter} on this class in basic analysis mode.
 *
 * <p>Basic anaylsis mode can flag verification errors that don't depend on knowing complete type
 * information for the classes and methods being called. This is useful for flagging simple
 * generation mistakes (e.g. stack underflows, method return type mismatches, accessing invalid
 * locals). Additionally, the error messages are more useful than what the java verifier normally
 * presents./* ww  w  .j a  v  a  2s . c om*/
 */
public void checkClass() {
    ClassNode cv = new ClassNode();
    new ClassReader(data).accept(new CheckClassAdapter(cv, true /* check data flow */), 0);
    // double check our fields while we are here.
    checkState(type.internalName().equals(cv.name));
    checkState(numberOfFields == cv.fields.size());
}

From source file:com.google.template.soy.jbcsrc.internal.SoyClassWriter.java

License:Apache License

private SoyClassWriter(Writer writer, Builder builder) {
    super(writer.api(), Flags.DEBUG ? new CheckClassAdapter(writer, false) : writer);
    this.writer = writer;
    this.typeInfo = builder.type;
    super.visit(Opcodes.V1_7, builder.access, builder.type.internalName(), null /* not generic */,
            builder.baseClass.internalName(),
            builder.interfaces.toArray(new String[builder.interfaces.size()]));
    if (builder.fileName != null) {
        super.visitSource(builder.fileName,
                // No JSR-45 style source maps, instead we write the line numbers in the normal locations.
                null);/*  w w w . java 2 s  . c  om*/
    }
}

From source file:com.googlecode.dex2jar.test.TestUtils.java

License:Apache License

@SuppressWarnings("rawtypes")
public static void verify(final ClassReader cr, PrintWriter out)
        throws AnalyzerException, IllegalArgumentException, IllegalAccessException {
    ClassNode cn = new ClassNode();
    cr.accept(new CheckClassAdapter(cn, false), ClassReader.SKIP_DEBUG);

    List methods = cn.methods;// w ww  . j a  va2 s . co m

    for (int i = 0; i < methods.size(); ++i) {
        MethodNode method = (MethodNode) methods.get(i);

        List tryCatchBlocks = method.tryCatchBlocks;
        for (int j = 0; j < tryCatchBlocks.size(); j++) {
            TryCatchBlockNode tcn = (TryCatchBlockNode) tryCatchBlocks.get(j);
            if (tcn.start.equals(tcn.end)) {
                throw new DexException("try/catch block %d in %s has same start(%s) and end(%s)", j,
                        method.name, tcn.start.getLabel(), tcn.end.getLabel());
            }
        }

        BasicVerifier verifier = new BasicVerifier();
        Analyzer a = new Analyzer(verifier);
        try {
            a.analyze(cn.name, method);
        } catch (Exception e) {
            out.println(cr.getClassName() + "." + method.name + method.desc);
            printAnalyzerResult(method, a, out);
            e.printStackTrace(out);
            out.flush();
            throw new DexException("method " + method.name + " " + method.desc, e);
        }
    }
}

From source file:com.googlecode.dex2jar.tools.AsmVerify.java

License:Apache License

@Override
protected void doCommandLine() throws Exception {
    if (remainingArgs.length < 1) {
        usage();//w w w  .  ja v a2  s  . c  o m
        return;
    }

    List<Path> files = new ArrayList<>();
    for (String fn : remainingArgs) {
        Path file = new File(fn).toPath();
        if (!Files.exists(file)) {
            System.err.println(fn + " is not exists");
            usage();
            return;
        }
        files.add(file);
    }

    for (Path file : files) {
        System.out.println("verify " + file);
        walkJarOrDir(file, new FileVisitorX() {
            @Override
            public void visitFile(Path file, Path relative) throws IOException {
                if (file.getFileName().toString().endsWith(".class")) {
                    ClassReader cr = new ClassReader(Files.readAllBytes(file));
                    ClassNode cn = new ClassNode();
                    cr.accept(new CheckClassAdapter(cn, false), ClassReader.SKIP_DEBUG);
                    for (MethodNode method : cn.methods) {
                        BasicVerifier verifier = new BasicVerifier();
                        Analyzer<BasicValue> a = new Analyzer<>(verifier);
                        try {
                            a.analyze(cn.name, method);
                        } catch (Exception ex) {
                            System.err.println("Error verify method " + cr.getClassName() + "." + method.name
                                    + " " + method.desc);
                            if (detail) {
                                ex.printStackTrace(System.err);
                                printAnalyzerResult(method, a, new PrintWriter(
                                        new OutputStreamWriter(System.err, StandardCharsets.UTF_8)));
                            }
                        }
                    }
                }
            }
        });
    }
}

From source file:com.yahoo.yqlplus.engine.internal.bytecode.ASMClassSource.java

public void build() throws IOException, ClassNotFoundException {
    Preconditions.checkState(!built, "ASMClassSource may only be built once");
    DynamicBootstrapUnit bootstrapper = new DynamicBootstrapUnit(this);
    bootstrapper.init();/*from   w  w w .j a v  a  2  s.  c  om*/
    built = true;

    List<UnitPrep> unitPreps = Lists.newArrayList();
    List<UnitGenerator> reversed = Lists.newArrayList(units);
    Collections.reverse(reversed);
    for (UnitGenerator unit : reversed) {
        UnitPrep unitPrep = new UnitPrep(unit);
        unitPreps.add(unitPrep);
        ByteClassGenerator classes = new ByteClassGenerator();
        try {
            unit.generate(classes);
        } catch (NullPointerException | ArrayIndexOutOfBoundsException | NegativeArraySizeException e) {
            // this is almost inevitably an error from visitMaxes
            // so let's dump some data
            unit.trace(System.err);
            throw e;
        }
        for (Map.Entry<String, byte[]> e : classes) {
            generatedClassLoader.put(e.getKey(), e.getValue());
            unitPrep.names.add(e.getKey());
        }
    }
    Collections.reverse(unitPreps);
    for (UnitPrep unit : unitPreps) {
        for (String name : unit.names) {
            try {
                generatedClassLoader.loadClass(name);
            } catch (ClassNotFoundException | ClassFormatError | VerifyError e) {
                byte[] data = generatedClassLoader.getBytes(name);
                ClassReader reader = new ClassReader(data);
                TraceClassVisitor tcv = new TraceClassVisitor(new PrintWriter(System.err));
                reader.accept(tcv, 0);
                ClassVisitor cc = new CheckClassAdapter(new ClassWriter(0), true);
                new ClassReader(data).accept(cc, 0);
                throw e;
            }
        }
    }

    for (UnitPrep unit : unitPreps) {
        for (String name : unit.names) {
            try {
                Class<?> clazz = generatedClassLoader.getClass(name.replace('/', '.'));
                unit.unit.prepare(clazz);
            } catch (ClassFormatError | VerifyError e) {
                byte[] data = generatedClassLoader.getBytes(name);
                ClassReader reader = new ClassReader(data);
                TraceClassVisitor tcv = new TraceClassVisitor(new PrintWriter(System.err));
                reader.accept(tcv, 0);
                ClassVisitor cc = new CheckClassAdapter(new ClassWriter(0), true);
                new ClassReader(data).accept(cc, 0);
                throw e;
            }
        }
    }
}

From source file:de.chimos.property.compiler.passtwo.javafx.PassTwoJFXFileVisitor.java

License:Open Source License

@Override
public FileVisitResult visitFile(Path t, BasicFileAttributes bfa) throws IOException {

    if (t.getFileName().toString().endsWith(".class")) {
        ClassWriter cw = new ClassWriter(0);
        CheckClassAdapter cca = new CheckClassAdapter(cw, true);
        ClassReader cr = new ClassReader(new FileInputStream(t.toFile()));
        cr.accept(new PassTwoJFXClassVisitor(properties, cca, config), 0);

        t.toFile().delete();/*from   www.  j  ava2 s. c  o  m*/

        try (FileOutputStream o = new FileOutputStream(t.toFile())) {
            o.write(cw.toByteArray());
        }
    }

    return FileVisitResult.CONTINUE;
}

From source file:de.unisb.cs.st.javaslicer.tracer.instrumentation.Transformer.java

License:Open Source License

private byte[] transform0(final String className, final String javaClassName, final byte[] classfileBuffer) {

    long startNanos = System.nanoTime();

    final ClassReader reader = new ClassReader(classfileBuffer);

    final ClassNode classNode = new ClassNode();
    reader.accept(classNode, 0);/*  ww  w.  java2 s. c om*/
    final ClassWriter writer;

    this.totalBytecodeParsingTime.addAndGet(System.nanoTime() - startNanos);

    if (this.tracer.check) {
        checkClass(classfileBuffer, className, classfileBuffer);
    }

    // we have to synchronize on System.out first.
    // otherwise it may lead to a deadlock if a thread calls removeStale() on ConcurrentReferenceHashMap
    // while he holds the lock for System.out, but another thread is inside the transformation step and
    // waits for the lock of System.out
    synchronized (System.out) {
        synchronized (this.transformationLock) {

            // register that class for later reconstruction of the trace
            List<Field> fields = classNode.fields.isEmpty() ? Collections.<Field>emptyList()
                    : new ArrayList<Field>(classNode.fields.size());

            final String javaSuperName = Type.getObjectType(classNode.superName).getClassName();
            final ReadClass readClass = new ReadClass(className, AbstractInstruction.getNextIndex(),
                    classNode.access, classNode.sourceFile, fields, javaSuperName);
            for (final Object fieldObj : classNode.fields) {
                final FieldNode f = (FieldNode) fieldObj;
                fields.add(new Field(f.name, f.desc, f.access, readClass));
            }

            long nanosBeforeTransformation = System.nanoTime();

            if (Arrays.asList(this.pauseTracingClasses).contains(javaClassName)
                    || className.startsWith("java/security/")) {
                new PauseTracingInstrumenter(readClass, this.tracer).transform(classNode);
            } else {
                if ("java/lang/Thread".equals(className))
                    new ThreadInstrumenter(readClass, this.tracer).transform(classNode);
                else
                    new TracingClassInstrumenter(readClass, this.tracer).transform(classNode);
            }

            new IdentifiableInstrumenter(readClass, this.tracer).transform(classNode);

            long nanosAfterTransformation = System.nanoTime();
            this.totalRawTransformationTime.addAndGet(nanosAfterTransformation - nanosBeforeTransformation);

            writer = new FixedClassWriter(
                    COMPUTE_FRAMES ? ClassWriter.COMPUTE_FRAMES : ClassWriter.COMPUTE_MAXS);
            ClassVisitor output = this.tracer.check ? new CheckClassAdapter(writer, false) : writer;

            classNode.accept(COMPUTE_FRAMES ? new JSRInliner(output) : output);

            this.totalBytecodeWritingTime.addAndGet(System.nanoTime() - nanosAfterTransformation);

            readClass.setInstructionNumberEnd(AbstractInstruction.getNextIndex());

            // now we can write the class out
            // NOTE: we do not write it out immediately, because this sometimes leads
            // to circular dependencies!
            //readClass.writeOut(this.readClassesOutputStream, this.readClassesStringCache);
            this.readClasses.add(readClass);

        }
    }

    final byte[] newClassfileBuffer = writer.toByteArray();

    if (this.tracer.check) {
        checkClass(newClassfileBuffer, className, classfileBuffer);
    }

    //printClass(newClassfileBuffer, Type.getObjectType(className).getClassName());
    /*
    if (className.endsWith("line/Main"))
    printClass(newClassfileBuffer, Type.getObjectType(className).getClassName());
    */

    return newClassfileBuffer;
}

From source file:net.sandius.rembulan.compiler.gen.asm.ASMBytecodeEmitter.java

License:Apache License

private byte[] classNodeToBytes(ClassNode classNode) {
    ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    classNode.accept(writer);/*from   w w  w .j a v a 2  s .c  o  m*/
    byte[] bytes = writer.toByteArray();

    // verify bytecode

    if (verifyAndPrint) {
        ClassReader reader = new ClassReader(bytes);
        ClassVisitor tracer = new TraceClassVisitor(new PrintWriter(System.out));
        ClassVisitor checker = new CheckClassAdapter(tracer, true);
        reader.accept(checker, 0);
    }

    return bytes;
}

From source file:net.sourceforge.cobertura.instrument.AbstractFindTouchPointsClassInstrumenter.java

License:GNU General Public License

/**
 * @param cv                 - a listener for code-instrumentation events
 * @param ignoreRegexp       - list of patters of method calls that should be ignored from line-coverage-measurement
 * @param duplicatedLinesMap - map of found duplicates in the class. You should use {@link DetectDuplicatedCodeClassVisitor} to find the duplicated lines.
 *//*from w ww  .ja  v  a 2s . c o  m*/
public AbstractFindTouchPointsClassInstrumenter(ClassVisitor cv, Collection<Pattern> ignoreRegexp,
        Map<Integer, Map<Integer, Integer>> duplicatedLinesMap) {
    super(Opcodes.ASM4, new CheckClassAdapter(cv, false));
    this.ignoreRegexp = ignoreRegexp;
    this.duplicatedLinesMap = duplicatedLinesMap;
}