private byte[] classNodeToBytes(ClassNode classNode) { ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); classNode.accept(writer); 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; }
public static void main(String[] args) throws Exception { final String k2 = "org/apache/drill/Pickle.class"; final URL url = Resources.getResource(k2); final byte[] clazz = Resources.toByteArray(url); final ClassReader cr = new ClassReader(clazz); final ClassWriter cw = writer(); final TraceClassVisitor visitor = new TraceClassVisitor(cw, new Textifier(), new PrintWriter(System.out)); final ValueHolderReplacementVisitor v2 = new ValueHolderReplacementVisitor(visitor, true); cr.accept(v2, ClassReader.EXPAND_FRAMES );//| ClassReader.SKIP_DEBUG); final byte[] output = cw.toByteArray(); Files.write(output, new File("/src/scratch/bytes/S.class")); check(output); final DrillConfig c = DrillConfig.forClient(); final SystemOptionManager m = new SystemOptionManager(c, new LocalPStoreProvider(c)); m.init(); try (QueryClassLoader ql = new QueryClassLoader(DrillConfig.create(), m)) { ql.injectByteCode("org.apache.drill.Pickle$OutgoingBatch", output); Class<?> clz = ql.loadClass("org.apache.drill.Pickle$OutgoingBatch"); clz.getMethod("x").invoke(null); } }
public static void dump(Acceptor acceptor, File file, boolean filterImportant, boolean sortLocals) { try { if(!file.getParentFile().exists()) file.getParentFile().mkdirs(); if(!file.exists()) file.createNewFile(); PrintWriter pout = new PrintWriter(file); ClassVisitor cv = new TraceClassVisitor(pout); if(filterImportant) cv = new ImportantInsnVisitor(cv); if(sortLocals) cv = new LocalVariablesSorterVisitor(cv); acceptor.accept(cv); pout.close(); } catch (IOException e) { throw new RuntimeException(e); } }
@Override protected void generate(TraceClassVisitor visitor) { visitor.visit(Opcodes.V1_1, Opcodes.ACC_PUBLIC + Opcodes.ACC_ABSTRACT + Opcodes.ACC_INTERFACE, "soot/asm/backend/targets/Comparable", null, "java/lang/Object", new String[] { "soot/asm/backend/targets/Measurable" }); visitor.visitSource("Comparable.java", null); visitor.visitField(Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_STATIC, "LESS", "I", null, new Integer(-1)).visitEnd(); visitor.visitField(Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_STATIC, "EQUAL", "I", null, new Integer(0)).visitEnd(); visitor.visitField(Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_STATIC, "GREATER", "I", null, new Integer(1)).visitEnd(); visitor.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_ABSTRACT, "compareTo", "(Ljava/lang/Object;)I", null, null).visitEnd(); visitor.visitEnd(); }
@Override protected void generate(TraceClassVisitor cw) { MethodVisitor mv; cw.visit(V1_4, ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE, "soot/asm/backend/targets/ExceptionMethods", null, "java/lang/Object", null); cw.visitSource("ExceptionMethods.java", null); { mv = cw.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, "foo", "()V", null, new String[] { "java/lang/NullPointerException" }); mv.visitEnd(); } cw.visitEnd(); }
@Override protected void generate(TraceClassVisitor cw) { MethodVisitor mv; cw.visit(V1_5, ACC_PUBLIC + ACC_ANNOTATION + ACC_ABSTRACT + ACC_INTERFACE, "soot/asm/backend/targets/MyAnnotatedAnnotation", null, "java/lang/Object", new String[] { "java/lang/annotation/Annotation" }); //TODO V1_1 seems wrong here cw.visitSource("MyAnnotatedAnnotation.java", null); { mv = cw.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, "value", "()Lsoot/asm/backend/targets/MyTestAnnotation;", null, null); mv.visitEnd(); } cw.visitEnd(); }
static void dumpASM(byte[] basicClass) { ClassReader cr = new ClassReader(basicClass); ClassNode cn = new ClassNode(); cr.accept(cn, 0); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); cn.accept(cw); File f = new File("/tmp/ASM/" + cn.name.replace("/", "_")); try { FileOutputStream os = new FileOutputStream(f); cr.accept(new TraceClassVisitor(new PrintWriter(os)), 0); os.close(); } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public static void main(String[] args) throws Exception { final String k2 = "org/apache/drill/Pickle.class"; final URL url = Resources.getResource(k2); final byte[] clazz = Resources.toByteArray(url); final ClassReader cr = new ClassReader(clazz); final ClassWriter cw = writer(); final TraceClassVisitor visitor = new TraceClassVisitor(cw, new Textifier(), new PrintWriter(System.out)); final ValueHolderReplacementVisitor v2 = new ValueHolderReplacementVisitor(visitor, true); cr.accept(v2, ClassReader.EXPAND_FRAMES );//| ClassReader.SKIP_DEBUG); final byte[] output = cw.toByteArray(); Files.write(output, new File("/src/scratch/bytes/S.class")); check(output); final DrillConfig c = DrillConfig.forClient(); final SystemOptionManager m = new SystemOptionManager(PhysicalPlanReaderTestFactory.defaultLogicalPlanPersistence(c), new LocalPersistentStoreProvider(c), c); m.init(); try (QueryClassLoader ql = new QueryClassLoader(DrillConfig.create(), m)) { ql.injectByteCode("org.apache.drill.Pickle$OutgoingBatch", output); Class<?> clz = ql.loadClass("org.apache.drill.Pickle$OutgoingBatch"); clz.getMethod("x").invoke(null); } }
private ClassBlock disassembleClass(ClassReader classReader, Block parent) throws UnsupportedVersionException { Writer bytecodeStringWriter = new StringWriter(); ClassVisitor classVisitor = new TraceClassVisitor(new PrintWriter(bytecodeStringWriter)); classReader.accept(classVisitor, ClassReader.EXPAND_FRAMES); ClassNode classNode = new ClassNode(); classReader.accept(classNode, ClassReader. EXPAND_FRAMES); if (classNode.version < 51 || classNode.version > 52) { throw new UnsupportedVersionException("Class files of version " + classNode.version + " are not supported"); } ClassBlock classBlock = new ClassBlock(classNode, parent); classBlock.setBytecode(bytecodeStringWriter.toString()); classBlock.disassemble(); return classBlock; }
public void test() throws Exception { Attribute[] attributes = new Attribute[] { new ASMStackMapTableAttribute() }; ClassWriter cw = new ClassWriter(false); ClassReader cr1 = new ClassReader(is); cr1.accept(cw, attributes, true); ClassReader cr2 = new ClassReader(cw.toByteArray()); if (!Arrays.equals(cr1.b, cr2.b)) { StringWriter sw1 = new StringWriter(); StringWriter sw2 = new StringWriter(); ClassVisitor cv1 = new TraceClassVisitor(new PrintWriter(sw1)); ClassVisitor cv2 = new TraceClassVisitor(new PrintWriter(sw2)); cr1.accept(cv1, attributes, true); cr2.accept(cv2, attributes, true); assertEquals("different data", sw1.toString(), sw2.toString()); } }
public byte[] toBytes() { ClassNode classNode = new ClassNode(Opcodes.ASM5); populate(classNode); classNode.accept(new TraceClassVisitor(new PrintWriter(Debug.getPrintStream(Debug.LEVEL_HIGH)))); ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); classNode.accept(classWriter); boolean hasASMMethodNodes = classDom.getMethods().stream().map(x -> new StatementDomVisitor.Return<MethodNode>() { @Override public void visitASM(MethodNode methodNode) { setResult(methodNode); } }.returnFrom(x.getBody())).anyMatch(x -> x != null); try { org.objectweb.asm.util.CheckClassAdapter.verify(new ClassReader(classWriter.toByteArray()), true, new PrintWriter(Debug.getPrintStream(Debug.LEVEL_HIGH))); } catch(Exception e) { if(!hasASMMethodNodes) throw e; } return classWriter.toByteArray(); }
public void validateClass(ClassReader reader) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); Exception error = null; try { CheckClassAdapter.verify(reader, this, false, printWriter); } catch (Exception e) { error = e; } String contents = writer.toString(); if (error != null || contents.length() > 0) { reader.accept(new TraceClassVisitor(printWriter), 0); throw new RuntimeException("Generation error\nDump for " + reader.getClassName() + "\n" + writer.toString(), error); } }
private byte[] handleCarving(String className, ClassWriter writer) { ClassReader cr = new ClassReader(writer.toByteArray()); ClassNode cn2 = new ClassNode(); cr.accept(cn2, ClassReader.EXPAND_FRAMES); this.testCarvingInstrumenter.transformClassNode(cn2, className); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); cn2.accept(cw); if (logger.isDebugEnabled()) { final StringWriter sw = new StringWriter(); cn2.accept(new TraceClassVisitor(new PrintWriter(sw))); logger.debug("test carving instrumentation result:\n{}", sw); } return cw.toByteArray(); }
private Class<?> instrumentClass(String fullyQualifiedTargetClass) throws ClassNotFoundException { try { String className = fullyQualifiedTargetClass.replace('.', '/'); InputStream is = ClassLoader.getSystemResourceAsStream(className + ".class"); if (is == null) { throw new ClassNotFoundException("Class '" + className + ".class" + "' should be in target project, but could not be found!"); } ClassReader reader = new ClassReader(is); ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES); TraceClassVisitor tc = new TraceClassVisitor(writer, new PrintWriter(System.err)); // CheckClassAdapter ca = new CheckClassAdapter(tc); StubClassVisitor visitor = new StubClassVisitor(tc, fullyQualifiedTargetClass); reader.accept(visitor, ClassReader.SKIP_FRAMES); byte[] byteBuffer = writer.toByteArray(); Class<?> result = defineClass(fullyQualifiedTargetClass, byteBuffer, 0, byteBuffer.length); classes.put(fullyQualifiedTargetClass, result); return result; } catch (Throwable t) { throw new ClassNotFoundException(t.getMessage(), t); } }
public static void debugSaveTrace(String name, final byte[] bytes) { try { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); new ClassReader(bytes).accept(new TraceClassVisitor(pw), 0); pw.flush(); Path path = Paths.get("target/classes2/" + name + ".asmtrace"); Files.createDirectories(path.getParent()); Files.write(path, sw.toString().getBytes(Charset.forName("UTF-8"))); System.out.println("Writing file to " + path.toUri()); } catch (IOException e) { e.printStackTrace(); } }
public static void debugSaveTrace(String name, ClassNode node) { try { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); node.accept(new TraceClassVisitor(pw)); pw.flush(); Path path = Paths.get("target/classes2/" + name + ".asmtrace"); Files.createDirectories(path.getParent()); Files.write(path, sw.toString().getBytes(Charset.forName("UTF-8"))); System.out.println("Writing file to " + path.toUri()); } catch (IOException e) { e.printStackTrace(); } }
public void assertEquals(final ClassReader cr1, final ClassReader cr2, final ClassFilter filter1, final ClassFilter filter2) throws Exception { if (!Arrays.equals(cr1.b, cr2.b)) { StringWriter sw1 = new StringWriter(); StringWriter sw2 = new StringWriter(); ClassVisitor cv1 = new TraceClassVisitor(new PrintWriter(sw1)); ClassVisitor cv2 = new TraceClassVisitor(new PrintWriter(sw2)); if (filter1 != null) { filter1.setNext(cv1); } if (filter2 != null) { filter2.setNext(cv2); } cr1.accept(filter1 == null ? cv1 : filter1, 0); cr2.accept(filter2 == null ? cv2 : filter2, 0); String s1 = sw1.toString(); String s2 = sw2.toString(); assertEquals("different data", s1, s2); } }
private ClassNode loadClass(String name) { return Try.apply(() -> { String cname = name.replace("/", "."); ClassNode node = cache.get(cname); if (node == null) { String rname = cname.replace(".", "/") + ".class"; try (InputStream in = loader.getResourceAsStream(rname)) { if (in == null) { throw new FileNotFoundException(rname + " using " + loader); } ClassReader reader = new ClassReader(ByteStreams.toByteArray(in)); node = new ClassNode(); reader.accept(node, 0); cache.put(cname, node); if (log.isDebugEnabled()) { log.info("Source: {}; Class: {}", node.sourceFile, node.name); reader.accept( new TraceClassVisitor(null, new ASMifier(), new PrintWriter(writer(log, name))), 0); } } } return node; }).get(); }
public void assertEquals( final ClassReader cr1, final ClassReader cr2, final ClassFilter filter1, final ClassFilter filter2) throws Exception { if (!Arrays.equals(cr1.b, cr2.b)) { StringWriter sw1 = new StringWriter(); StringWriter sw2 = new StringWriter(); ClassVisitor cv1 = new TraceClassVisitor(new PrintWriter(sw1)); ClassVisitor cv2 = new TraceClassVisitor(new PrintWriter(sw2)); if (filter1 != null) { filter1.setNext(cv1); } if (filter2 != null) { filter2.setNext(cv2); } cr1.accept(filter1 == null ? cv1 : filter1, 0); cr2.accept(filter2 == null ? cv2 : filter2, 0); String s1 = sw1.toString(); String s2 = sw2.toString(); assertEquals("different data", s1, s2); } }
private void update(ClassInstance cls) { if (cls == null) { text.setText(""); } else { StringWriter writer = new StringWriter(); try (PrintWriter pw = new PrintWriter(writer)) { synchronized (Util.asmNodeSync) { cls.getMergedAsmNode().accept(new TraceClassVisitor(pw)); } } text.setText(writer.toString()); } }
private void writeBytecodeToDisk(final byte[] clazz, Path folder) throws IOException { final ClassReader reader = new ClassReader(clazz); CharArrayWriter buffer = new CharArrayWriter(); reader.accept(new TraceClassVisitor(null, new Textifier(), new PrintWriter( buffer)), ClassReader.EXPAND_FRAMES); Path outFile = folder.resolve(currentClass.asJavaName() + ".txt"); Files.write(outFile, Collections.singleton(buffer.toString()), StandardCharsets.UTF_8, StandardOpenOption.CREATE); }
public static String textify(byte[] bytes) { Printer textifier = new Textifier(); StringWriter sw = new StringWriter(); new ClassReader(bytes) .accept( new TraceClassVisitor(null, textifier, new PrintWriter(sw, true)), ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES | ClassReader.SKIP_CODE); return sw.toString(); }
@Override protected void generate(TraceClassVisitor cw) { MethodVisitor mv; cw.visit(V1_1, ACC_PUBLIC + ACC_SUPER, "soot/asm/backend/targets/LineNumbers", null, "java/lang/Object", null); cw.visitSource("LineNumbers.java", null); { mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv.visitCode(); Label l1 = new Label(); mv.visitLabel(l1); mv.visitLineNumber(3, l1); mv.visitVarInsn(ALOAD, 0); Label l2 = new Label(); mv.visitLabel(l2); mv.visitLineNumber(3, l2); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); Label l3 = new Label(); mv.visitLabel(l3); mv.visitLineNumber(3, l3); mv.visitInsn(RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } { mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null); mv.visitCode(); Label l0 = new Label(); mv.visitLabel(l0); mv.visitLineNumber(6, l0); mv.visitInsn(RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } cw.visitEnd(); }
@Override protected void generate(TraceClassVisitor cw) { MethodVisitor mv; cw.visit(V1_1, ACC_PUBLIC + ACC_SUPER, "soot/asm/backend/targets/Dups", null, "java/lang/Object", null); cw.visitSource("Dups.java", null); { mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); mv.visitInsn(RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } { mv = cw.visitMethod(ACC_PUBLIC, "dubl", "()J", null, null); mv.visitCode(); mv.visitLdcInsn(new Long(1234L)); mv.visitInsn(DUP2); mv.visitInsn(LADD); mv.visitInsn(LRETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } { mv = cw.visitMethod(ACC_PUBLIC, "dup", "()Ljava/lang/Object;", null, null); mv.visitCode(); mv.visitTypeInsn(NEW, "java/lang/Object"); mv.visitInsn(DUP); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); mv.visitInsn(ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } cw.visitEnd(); }
@Override protected void generate(TraceClassVisitor cw) { MethodVisitor mv; FieldVisitor fv; cw.visit(V1_1, ACC_SUPER, "soot/asm/backend/targets/InnerClass$1", null, "java/lang/Object", new String[] { "soot/asm/backend/targets/Measurable" }); cw.visitSource("InnerClass.java", null); cw.visitOuterClass("soot/asm/backend/targets/InnerClass", "doInner", "()V"); cw.visitInnerClass("soot/asm/backend/targets/InnerClass$1", null, null, 0); { fv = cw.visitField(ACC_FINAL + ACC_SYNTHETIC, "this$0", "Lsoot/asm/backend/targets/InnerClass;", null, null); fv.visitEnd(); } { mv = cw.visitMethod(0, "<init>", "(Lsoot/asm/backend/targets/InnerClass;)V", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitFieldInsn(PUTFIELD, "soot/asm/backend/targets/InnerClass$1", "this$0", "Lsoot/asm/backend/targets/InnerClass;"); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); mv.visitInsn(RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } cw.visitEnd(); }
@Override protected void generate(TraceClassVisitor cw) { MethodVisitor mv; cw.visit(V1_1, ACC_PUBLIC + ACC_SUPER, "soot/asm/backend/targets/nullTypes", null, "java/lang/Object", null); cw.visitSource("nullTypes.java", null); { mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); mv.visitInsn(RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } { mv = cw.visitMethod(0, "doStuff", "(Ljava/lang/Integer;)Ljava/lang/Integer;", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 1); Label l0 = new Label(); mv.visitJumpInsn(IFNONNULL, l0); mv.visitInsn(ACONST_NULL); mv.visitInsn(ARETURN); mv.visitLabel(l0); //mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null); mv.visitInsn(ICONST_1); mv.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;", false); mv.visitInsn(ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } cw.visitEnd(); }
@Override public ClassVisitor create(String internalName) { StringWriter output = new StringWriter(); TraceClassVisitor tcw = new TraceClassVisitor(new PrintWriter(output)); writers.add(output); return tcw; }
public void dump(PrintStream out) { for (Map.Entry<String, byte[]> e : classBytes.entrySet()) { ClassReader reader = new ClassReader(e.getValue()); TraceClassVisitor visitor = new TraceClassVisitor(new PrintWriter(out, true)); reader.accept(visitor, 0); } }
public void analyze(OutputStream out) { for (Map.Entry<String, byte[]> e : classBytes.entrySet()) { ClassReader reader = new ClassReader(e.getValue()); ClassVisitor visitor = new CheckClassAdapter(new TraceClassVisitor(new PrintWriter(out, true))); reader.accept(visitor, 0); } }
public static String toString(Class<?> type) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); AsmUtil.classReader(type).accept( new TraceClassVisitor(pw), ClassReader.EXPAND_FRAMES); return sw.toString(); }
public static String toString(byte[] bytes) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); AsmUtil.classReader(bytes).accept( new TraceClassVisitor(pw), ClassReader.EXPAND_FRAMES); return sw.toString(); }
@Test @Ignore( "Convenience to look at what code is generated in the Fragment Classloader, and is not really a test case." ) public void fragmentClassLoaderGenerateClassTest() throws Exception { FragmentClassLoader classLoader = new FragmentClassLoader( getClass().getClassLoader() ); byte[] asm = generateClass(); byte[] cl = classLoader.generateClass( QI256Test.TestTransient.TestTransientMixin.class.getName() + "_Stub", QI256Test.TestTransient.TestTransientMixin.class ); new ClassReader( cl ).accept( new TraceClassVisitor( new PrintWriter( System.out, true ) ), 0 ); Assert.assertArrayEquals( asm, cl ); }
public static String toString(byte[] clazz) { StringWriter strOut = new StringWriter(); PrintWriter out = new PrintWriter(strOut); ClassVisitor cv = new TraceClassVisitor(out); ClassReader cr = new ClassReader(clazz); cr.accept(cv, Opcodes.ASM5); strOut.flush(); return strOut.toString(); }
public static String toString(ClassNode cn) { StringWriter strOut = new StringWriter(); PrintWriter out = new PrintWriter(strOut); cn.accept(new TraceClassVisitor(out)); strOut.flush(); return strOut.toString(); }
public Class<?> loadClass(ClassCompilationContext ctx) { // generate bytecode ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); ctx.getClazz().accept(cw); // load class Class<?> cls; byte[] bb = cw.toByteArray(); String className = Type.getObjectType(ctx.getClazz().name).getClassName(); // try { // Files.write(bb, new File("target/compiledRecipes/" + ctx.clazz.name // + ".class")); // } catch (IOException e2) { // throw new SaltaException("Error while writing generated class", e2); // } try { cls = getLoader().defineClass(className, bb); ctx.initFields(cls); } catch (Throwable e) { System.out.println("Error while loading compiled recipe class"); ClassReader cr = new ClassReader(bb); cr.accept(new TraceClassVisitor(null, new ASMifier(), new PrintWriter(System.out)), 0); CheckClassAdapter.verify(cr, false, new PrintWriter(System.err)); throw new SaltaException("Error while loading compiled recipe", e); } // return result return cls; }
public NaiveCompilerVisitor(String packageName, String className) { if(StringUtils.isBlank(packageName)){ throw new IllegalArgumentException("packageName"); } if(StringUtils.isBlank(className)){ throw new IllegalArgumentException("className"); } this.packageName = packageName; this.className = className; this.classWriter = new ClassWriter(0); traceClassVisitor = new TraceClassVisitor(classWriter, new PrintWriter(System.out)); }
public static void main(String[] args) throws Exception { ClassWriter cw = new ClassWriter(0); TraceClassVisitor tracer = new TraceClassVisitor(cw, new PrintWriter(System.out)); ClassVisitor cv = tracer; String name = "Nerd"; String generics = null; String superName = "java/lang/Object"; String[] interfaces = null; int access = ACC_PUBLIC + ACC_INTERFACE; int version = V1_5; cv.visit(version, access, name, generics, superName, interfaces); int fieldAccess = ACC_PUBLIC + ACC_FINAL + ACC_STATIC; String shortDescriptor = Type.SHORT_TYPE.getDescriptor(); FieldVisitor hair = cv.visitField(fieldAccess, "hair", shortDescriptor, null, new Integer(0)); hair.visitEnd(); MethodVisitor playVideoGame = cv.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, "playVideoGame", "()V", null, null); // no code to define, just finish it up playVideoGame.visitEnd(); cv.visitEnd(); // prints if using tracer byte[] b = cw.toByteArray(); // can define or write to file: // defineClass(name, b, 0, b.length) // from findClass() in subclass of ClassLoader FileOutputStream fos = new FileOutputStream("Nerd.class"); fos.write(b); fos.close(); }
@Override public byte[] processBytecode(final String name, final byte[] original) { PrintWriter pw = out instanceof PrintWriter ? (PrintWriter) out : new PrintWriter(out); TraceClassVisitor visitor = new TraceClassVisitor(pw); ClassReader reader = new ClassReader(original); reader.accept(visitor, 0); return original; }