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

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

Introduction

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

Prototype

public static void verify(final ClassReader classReader, final ClassLoader loader, final boolean printResults,
        final PrintWriter printWriter) 

Source Link

Document

Checks the given class.

Usage

From source file:com.codename1.tools.ikvm.Parser.java

public static void verify(byte[] clazz, ClassLoader classLoader) throws VerifyException {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    CheckClassAdapter.verify(new ClassReader(clazz), classLoader, false, pw);
    if (sw.toString().length() > 0) {
        throw new VerifyException(sw.toString());
    }//from  ww  w. j a  v a2s .c  om
}

From source file:com.facebook.presto.bytecode.ClassGenerator.java

License:Apache License

public Map<String, Class<?>> defineClasses(List<ClassDefinition> classDefinitions) {
    ClassInfoLoader classInfoLoader = createClassInfoLoader(classDefinitions, classLoader);
    Map<String, byte[]> bytecodes = new LinkedHashMap<>();

    for (ClassDefinition classDefinition : classDefinitions) {
        ClassWriter writer = new SmartClassWriter(classInfoLoader);

        try {/*from   w w  w.j a va  2s  . com*/
            classDefinition.visit(fakeLineNumbers ? new AddFakeLineNumberClassVisitor(writer) : writer);
        } catch (IndexOutOfBoundsException | NegativeArraySizeException e) {
            StringWriter out = new StringWriter();
            classDefinition.visit(new TraceClassVisitor(null, new Textifier(), new PrintWriter(out)));
            throw new IllegalArgumentException("Error processing class definition:\n" + out, e);
        }

        byte[] bytecode;
        try {
            bytecode = writer.toByteArray();
        } catch (RuntimeException e) {
            throw new CompilationException("Error compiling class: " + classDefinition.getName(), e);
        }

        bytecodes.put(classDefinition.getType().getJavaClassName(), bytecode);

        if (runAsmVerifier) {
            ClassReader reader = new ClassReader(bytecode);
            CheckClassAdapter.verify(reader, classLoader, true, new PrintWriter(output));
        }
    }

    dumpClassPath.ifPresent(path -> bytecodes.forEach((className, bytecode) -> {
        String name = typeFromJavaClassName(className).getClassName() + ".class";
        Path file = path.resolve(name).toAbsolutePath();
        try {
            createDirectories(file.getParent());
            Files.write(file, bytecode);
        } catch (IOException e) {
            throw new UncheckedIOException("Failed to write generated class file: " + file, e);
        }
    }));

    if (dumpRawBytecode) {
        for (byte[] bytecode : bytecodes.values()) {
            ClassReader classReader = new ClassReader(bytecode);
            classReader.accept(new TraceClassVisitor(new PrintWriter(output)), ClassReader.EXPAND_FRAMES);
        }
    }

    Map<String, Class<?>> classes = classLoader.defineClasses(bytecodes);

    try {
        for (Class<?> clazz : classes.values()) {
            Reflection.initialize(clazz);
        }
    } catch (VerifyError e) {
        throw new RuntimeException(e);
    }

    return classes;
}

From source file:com.facebook.presto.bytecode.CompilerUtils.java

License:Apache License

private static Map<String, Class<?>> defineClasses(List<ClassDefinition> classDefinitions,
        DynamicClassLoader classLoader) {
    ClassInfoLoader classInfoLoader = ClassInfoLoader.createClassInfoLoader(classDefinitions, classLoader);

    if (DUMP_BYTE_CODE_TREE) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DumpBytecodeVisitor dumpBytecode = new DumpBytecodeVisitor(new PrintStream(out));
        for (ClassDefinition classDefinition : classDefinitions) {
            dumpBytecode.visitClass(classDefinition);
        }//from  ww  w  .ja  v  a  2s.  c  o  m
        System.out.println(new String(out.toByteArray(), StandardCharsets.UTF_8));
    }

    Map<String, byte[]> bytecodes = new LinkedHashMap<>();
    for (ClassDefinition classDefinition : classDefinitions) {
        ClassWriter cw = new SmartClassWriter(classInfoLoader);
        try {
            classDefinition.visit(ADD_FAKE_LINE_NUMBER ? new AddFakeLineNumberClassVisitor(cw) : cw);
        } catch (IndexOutOfBoundsException e) {
            Printer printer = new Textifier();
            StringWriter stringWriter = new StringWriter();
            TraceClassVisitor tcv = new TraceClassVisitor(null, printer, new PrintWriter(stringWriter));
            classDefinition.visit(tcv);
            throw new IllegalArgumentException("An error occurred while processing classDefinition:"
                    + System.lineSeparator() + stringWriter.toString(), e);
        }
        try {
            byte[] bytecode = cw.toByteArray();
            if (RUN_ASM_VERIFIER) {
                ClassReader reader = new ClassReader(bytecode);
                CheckClassAdapter.verify(reader, classLoader, true, new PrintWriter(System.out));
            }
            bytecodes.put(classDefinition.getType().getJavaClassName(), bytecode);
        } catch (RuntimeException e) {
            throw new CompilationException("Error compiling class " + classDefinition.getName(), e);
        }
    }

    String dumpClassPath = DUMP_CLASS_FILES_TO.get();
    if (dumpClassPath != null) {
        for (Map.Entry<String, byte[]> entry : bytecodes.entrySet()) {
            File file = new File(dumpClassPath,
                    ParameterizedType.typeFromJavaClassName(entry.getKey()).getClassName() + ".class");
            try {
                log.debug("ClassFile: " + file.getAbsolutePath());
                Files.createParentDirs(file);
                Files.write(entry.getValue(), file);
            } catch (IOException e) {
                log.error(e, "Failed to write generated class file to: %s" + file.getAbsolutePath());
            }
        }
    }
    if (DUMP_BYTE_CODE_RAW) {
        for (byte[] bytecode : bytecodes.values()) {
            ClassReader classReader = new ClassReader(bytecode);
            classReader.accept(new TraceClassVisitor(new PrintWriter(System.err)), ClassReader.EXPAND_FRAMES);
        }
    }
    Map<String, Class<?>> classes = classLoader.defineClasses(bytecodes);
    try {
        for (Class<?> clazz : classes.values()) {
            Reflection.initialize(clazz);
        }
    } catch (VerifyError e) {
        throw new RuntimeException(e);
    }
    return classes;
}

From source file:com.facebook.presto.sql.gen.CompilerUtils.java

License:Apache License

private static Map<String, Class<?>> defineClasses(List<ClassDefinition> classDefinitions,
        DynamicClassLoader classLoader) {
    ClassInfoLoader classInfoLoader = ClassInfoLoader.createClassInfoLoader(classDefinitions, classLoader);

    if (DUMP_BYTE_CODE_TREE) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DumpByteCodeVisitor dumpByteCode = new DumpByteCodeVisitor(new PrintStream(out));
        for (ClassDefinition classDefinition : classDefinitions) {
            dumpByteCode.visitClass(classDefinition);
        }//from w w w  .ja v a  2  s . c  o m
        System.out.println(new String(out.toByteArray(), StandardCharsets.UTF_8));
    }

    Map<String, byte[]> byteCodes = new LinkedHashMap<>();
    for (ClassDefinition classDefinition : classDefinitions) {
        ClassWriter cw = new SmartClassWriter(classInfoLoader);
        classDefinition.visit(cw);
        byte[] byteCode = cw.toByteArray();
        if (RUN_ASM_VERIFIER) {
            ClassReader reader = new ClassReader(byteCode);
            CheckClassAdapter.verify(reader, classLoader, true, new PrintWriter(System.out));
        }
        byteCodes.put(classDefinition.getType().getJavaClassName(), byteCode);
    }

    String dumpClassPath = DUMP_CLASS_FILES_TO.get();
    if (dumpClassPath != null) {
        for (Map.Entry<String, byte[]> entry : byteCodes.entrySet()) {
            File file = new File(dumpClassPath,
                    ParameterizedType.typeFromJavaClassName(entry.getKey()).getClassName() + ".class");
            try {
                log.debug("ClassFile: " + file.getAbsolutePath());
                Files.createParentDirs(file);
                Files.write(entry.getValue(), file);
            } catch (IOException e) {
                log.error(e, "Failed to write generated class file to: %s" + file.getAbsolutePath());
            }
        }
    }
    if (DUMP_BYTE_CODE_RAW) {
        for (byte[] byteCode : byteCodes.values()) {
            ClassReader classReader = new ClassReader(byteCode);
            classReader.accept(new TraceClassVisitor(new PrintWriter(System.err)), ClassReader.SKIP_FRAMES);
        }
    }
    return classLoader.defineClasses(byteCodes);
}

From source file:com.facebook.presto.sql.gen.ExpressionCompiler.java

License:Apache License

private Map<String, Class<?>> defineClasses(List<ClassDefinition> classDefinitions,
        DynamicClassLoader classLoader) {
    ClassInfoLoader classInfoLoader = ClassInfoLoader.createClassInfoLoader(classDefinitions, classLoader);

    if (DUMP_BYTE_CODE_TREE) {
        DumpByteCodeVisitor dumpByteCode = new DumpByteCodeVisitor(System.out);
        for (ClassDefinition classDefinition : classDefinitions) {
            dumpByteCode.visitClass(classDefinition);
        }//www  .j  a v a 2 s. c o m
    }

    Map<String, byte[]> byteCodes = new LinkedHashMap<>();
    for (ClassDefinition classDefinition : classDefinitions) {
        ClassWriter cw = new SmartClassWriter(classInfoLoader);
        classDefinition.visit(cw);
        byte[] byteCode = cw.toByteArray();
        if (RUN_ASM_VERIFIER) {
            ClassReader reader = new ClassReader(byteCode);
            CheckClassAdapter.verify(reader, classLoader, true, new PrintWriter(System.out));
        }
        byteCodes.put(classDefinition.getType().getJavaClassName(), byteCode);
    }

    String dumpClassPath = DUMP_CLASS_FILES_TO.get();
    if (dumpClassPath != null) {
        for (Entry<String, byte[]> entry : byteCodes.entrySet()) {
            File file = new File(dumpClassPath,
                    ParameterizedType.typeFromJavaClassName(entry.getKey()).getClassName() + ".class");
            try {
                log.debug("ClassFile: " + file.getAbsolutePath());
                Files.createParentDirs(file);
                Files.write(entry.getValue(), file);
            } catch (IOException e) {
                log.error(e, "Failed to write generated class file to: %s" + file.getAbsolutePath());
            }
        }
    }
    if (DUMP_BYTE_CODE_RAW) {
        for (byte[] byteCode : byteCodes.values()) {
            ClassReader classReader = new ClassReader(byteCode);
            classReader.accept(new TraceClassVisitor(new PrintWriter(System.err)), ClassReader.SKIP_FRAMES);
        }
    }
    Map<String, Class<?>> classes = classLoader.defineClasses(byteCodes);
    generatedClasses.addAndGet(classes.size());
    return classes;
}

From source file:com.facebook.presto.sql.gen.JoinCompiler.java

License:Apache License

private static Map<String, Class<?>> defineClasses(List<ClassDefinition> classDefinitions,
        DynamicClassLoader classLoader) {
    ClassInfoLoader classInfoLoader = ClassInfoLoader.createClassInfoLoader(classDefinitions, classLoader);

    if (DUMP_BYTE_CODE_TREE) {
        DumpByteCodeVisitor dumpByteCode = new DumpByteCodeVisitor(System.out);
        for (ClassDefinition classDefinition : classDefinitions) {
            dumpByteCode.visitClass(classDefinition);
        }/*from w  ww  .j  av a 2s  .  co  m*/
    }

    Map<String, byte[]> byteCodes = new LinkedHashMap<>();
    for (ClassDefinition classDefinition : classDefinitions) {
        ClassWriter cw = new SmartClassWriter(classInfoLoader);
        classDefinition.visit(cw);
        byte[] byteCode = cw.toByteArray();
        if (RUN_ASM_VERIFIER) {
            ClassReader reader = new ClassReader(byteCode);
            CheckClassAdapter.verify(reader, classLoader, true, new PrintWriter(System.out));
        }
        byteCodes.put(classDefinition.getType().getJavaClassName(), byteCode);
    }

    String dumpClassPath = DUMP_CLASS_FILES_TO.get();
    if (dumpClassPath != null) {
        for (Entry<String, byte[]> entry : byteCodes.entrySet()) {
            File file = new File(dumpClassPath,
                    ParameterizedType.typeFromJavaClassName(entry.getKey()).getClassName() + ".class");
            try {
                log.debug("ClassFile: " + file.getAbsolutePath());
                Files.createParentDirs(file);
                Files.write(entry.getValue(), file);
            } catch (IOException e) {
                log.error(e, "Failed to write generated class file to: %s" + file.getAbsolutePath());
            }
        }
    }
    if (DUMP_BYTE_CODE_RAW) {
        for (byte[] byteCode : byteCodes.values()) {
            ClassReader classReader = new ClassReader(byteCode);
            classReader.accept(new TraceClassVisitor(new PrintWriter(System.err)), ClassReader.SKIP_FRAMES);
        }
    }
    return classLoader.defineClasses(byteCodes);
}

From source file:com.facebook.swift.codec.internal.compiler.ThriftCodecByteCodeGenerator.java

License:Apache License

@SuppressWarnings("unchecked")
@SuppressFBWarnings("DM_DEFAULT_ENCODING")
public ThriftCodecByteCodeGenerator(ThriftCodecManager codecManager, ThriftStructMetadata metadata,
        DynamicClassLoader classLoader, boolean debug) {
    this.codecManager = codecManager;
    this.metadata = metadata;

    structType = type(metadata.getStructClass());
    codecType = toCodecType(metadata);//from ww  w.  j a  v  a  2 s .c  o  m

    classDefinition = new ClassDefinition(a(PUBLIC, SUPER), codecType.getClassName(), type(Object.class),
            type(ThriftCodec.class, structType));

    // declare the class fields
    typeField = declareTypeField();
    codecFields = declareCodecFields();

    // declare methods
    defineConstructor();
    defineGetTypeMethod();

    switch (metadata.getMetadataType()) {
    case STRUCT:
        defineReadStructMethod();
        defineWriteStructMethod();
        break;
    case UNION:
        defineReadUnionMethod();
        defineWriteUnionMethod();
        break;
    default:
        throw new IllegalStateException(format("encountered type %s", metadata.getMetadataType()));
    }

    // add the non-generic bridge read and write methods
    defineReadBridgeMethod();
    defineWriteBridgeMethod();

    // generate the byte code
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
    classDefinition.getClassNode().accept(cw);
    byte[] byteCode = cw.toByteArray();

    // Run the asm verifier only in debug mode (prints a ton of info)
    if (debug) {
        ClassReader reader = new ClassReader(byteCode);
        CheckClassAdapter.verify(reader, classLoader, true, new PrintWriter(System.out));
    }

    // load the class
    Class<?> codecClass = classLoader.defineClass(codecType.getClassName().replace('/', '.'), byteCode);
    try {
        Class<?>[] types = parameters.getTypes();
        Constructor<?> constructor = codecClass.getConstructor(types);
        thriftCodec = (ThriftCodec<T>) constructor.newInstance(parameters.getValues());
    } catch (Exception e) {
        throw new IllegalStateException("Generated class is invalid", e);
    }
}

From source file:com.gargoylesoftware.js.nashorn.internal.runtime.Context.java

License:Open Source License

/**
 * Verify generated bytecode before emission. This is called back from the
 * {@link ObjectClassGenerator} or the {@link Compiler}. If the "--verify-code" parameter
 * hasn't been given, this is a nop/*from   ww w  . ja  v a  2  s  .co  m*/
 *
 * Note that verification may load classes -- we don't want to do that unless
 * user specified verify option. We check it here even though caller
 * may have already checked that flag
 *
 * @param bytecode bytecode to verify
 */
public void verify(final byte[] bytecode) {
    if (env._verify_code) {
        // No verification when security manager is around as verifier
        // may load further classes - which should be avoided.
        if (System.getSecurityManager() == null) {
            CheckClassAdapter.verify(new ClassReader(bytecode), sharedLoader, false,
                    new PrintWriter(System.err, true));
        }
    }
}

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

License:Apache License

/**
 * Utility to run the {@link CheckClassAdapter} on the class and print it to a string. for 
 * debugging.//from w w  w .j ava  2s  .c  om
 */
private static void checkClassData(ClassData clazz) {
    StringWriter sw = new StringWriter();
    CheckClassAdapter.verify(new ClassReader(clazz.data()), ExpressionTester.class.getClassLoader(), false,
            new PrintWriter(sw));
    String result = sw.toString();
    if (!result.isEmpty()) {
        throw new IllegalStateException(result);
    }
}

From source file:com.google.template.soy.jbcsrc.restricted.testing.ExpressionEvaluator.java

License:Apache License

/**
 * Utility to run the {@link CheckClassAdapter} on the class and print it to a string. for
 * debugging.// w w w.j av  a  2 s  .c o m
 */
private static void checkClassData(ClassData clazz) {
    StringWriter sw = new StringWriter();
    CheckClassAdapter.verify(new ClassReader(clazz.data()), ExpressionEvaluator.class.getClassLoader(), false,
            new PrintWriter(sw));
    String result = sw.toString();
    if (!result.isEmpty()) {
        throw new IllegalStateException(result);
    }
}