use of org.objectweb.asm.util.Printer in project presto by prestodb.
the class CompilerUtils method defineClasses.
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);
}
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 | NegativeArraySizeException 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;
}
Aggregations