org.objectweb.asm.util.TraceClassVisitor Java Examples

The following examples show how to use org.objectweb.asm.util.TraceClassVisitor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExampleTransformerTests.java    From java-svc with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
void testTransform() throws IOException, IllegalClassFormatException {
	List<TransformDescriptor> probes = ExampleAgent.readProbes(null);
	ExampleTransformer transformer = new ExampleTransformer(probes);
	byte[] originalClass = TestUtils.getByteCode(TestProgram.class);
	byte[] transformedClass = transformer.transform(TestProgram.class.getClassLoader(),
			Type.getInternalName(TestProgram.class), TestProgram.class, null, originalClass);
	assertNotNull(transformedClass);
	assertNotEquals(originalClass, transformedClass);

	
	StringWriter writer = new StringWriter();
	TraceClassVisitor visitor = new TraceClassVisitor(new PrintWriter(writer));
	CheckClassAdapter checkAdapter = new CheckClassAdapter(visitor);
	ClassReader reader = new ClassReader(transformedClass);
	reader.accept(checkAdapter, 0);
	String decompiledTransformedClass = writer.getBuffer().toString();
	// System.out.println(decompiledTransformedClass);
	assertNotNull(decompiledTransformedClass);
}
 
Example #2
Source File: InterfaceTest.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
@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();
	
}
 
Example #3
Source File: ExceptionTest.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
@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();

}
 
Example #4
Source File: AnnotatedAnnotationTest.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
@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();

}
 
Example #5
Source File: ASMBytecodeEmitter.java    From rembulan with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #6
Source File: ASMHelper.java    From CodeChickenLib with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static void dump(Acceptor acceptor, File file, boolean filterImportant, boolean sortLocals, boolean textify) {
    try {
        if(!file.getParentFile().exists())
            file.getParentFile().mkdirs();
        if(!file.exists())
            file.createNewFile();

        PrintWriter pout = new PrintWriter(file);
        ClassVisitor cv = new TraceClassVisitor(null, textify ? new Textifier() : new ASMifier(), 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);
    }
}
 
Example #7
Source File: AsmUtils.java    From turbine with Apache License 2.0 5 votes vote down vote up
public static String textify(byte[] bytes, boolean skipDebug) {
  Printer textifier = new Textifier();
  StringWriter sw = new StringWriter();
  new ClassReader(bytes)
      .accept(
          new TraceClassVisitor(null, textifier, new PrintWriter(sw, true)),
          ClassReader.SKIP_FRAMES
              | ClassReader.SKIP_CODE
              | (skipDebug ? ClassReader.SKIP_DEBUG : 0));
  return sw.toString();
}
 
Example #8
Source File: NullTypesTest.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
@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();
}
 
Example #9
Source File: LineNumbersTest.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
@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();

}
 
Example #10
Source File: CompilerTest.java    From Moxy with MIT License 5 votes vote down vote up
private String getBytecodeString(JavaFileObject file) throws IOException {
	ByteArrayOutputStream out = new ByteArrayOutputStream();
	ClassReader classReader = new ClassReader(file.openInputStream());
	TraceClassVisitor classVisitor = new TraceClassVisitor(new PrintWriter(out));
	classReader.accept(classVisitor, ClassReader.SKIP_DEBUG); // skip debug info (line numbers)
	return out.toString();
}
 
Example #11
Source File: TraceClassGenerator.java    From yql-plus with Apache License 2.0 5 votes vote down vote up
@Override
public ClassVisitor create(String internalName) {
    StringWriter output = new StringWriter();
    TraceClassVisitor tcw = new TraceClassVisitor(new PrintWriter(output));
    writers.add(output);
    return tcw;
}
 
Example #12
Source File: GeneratedClassLoader.java    From yql-plus with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #13
Source File: GeneratedClassLoader.java    From yql-plus with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #14
Source File: InnerClass2Test.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
@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();

}
 
Example #15
Source File: AbstractWorkflowRepository.java    From copper-engine with Apache License 2.0 5 votes vote down vote up
private static void traceBytes(String message, byte[] bytes) {
    if (logger.isTraceEnabled()) {
        StringWriter sw = new StringWriter();
        new ClassReader(bytes).accept(new TraceClassVisitor(new PrintWriter(sw)), 0);
        logger.trace(message + ":\n{}", sw.toString());
    }
}
 
Example #16
Source File: BytecodeTraceUtil.java    From tascalate-async-await with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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();
}
 
Example #17
Source File: Jbfc.java    From cs-summary-reflection with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws IOException {
    if (args.length < 2) {
        System.out.println("Usage: jbfc [-v] <bf program file> <java class name>");
        return;
    }

    boolean verbose = false;
    String fileName = null;
    String className = null;
    for (int i = 0; i < args.length; i++) {
        if ("-v".equals(args[i])) {
            verbose = true;
        } else {
            fileName = args[i];
            className = args[i + 1];
            break;
        }
    }

    FileReader r = new FileReader(fileName);

    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    BFCompiler c = new BFCompiler();
    if (verbose) {
        c.compile(
                r, className, fileName, new TraceClassVisitor(cw, new PrintWriter(System.out)));
    } else {
        c.compile(r, className, fileName, cw);
    }

    r.close();

    FileOutputStream os = new FileOutputStream(className + ".class");
    os.write(cw.toByteArray());
    os.flush();
    os.close();
}
 
Example #18
Source File: BytecodeTraceUtil.java    From tascalate-async-await with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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();
}
 
Example #19
Source File: GenNerdClass.java    From cs652 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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();
}
 
Example #20
Source File: BytecodeDumper.java    From groovy with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #21
Source File: ASMTest.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@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 );
}
 
Example #22
Source File: Bytecode.java    From Mixin with MIT License 5 votes vote down vote up
/**
 * Runs textifier on the specified method node and dumps the output to the
 * specified output stream
 * 
 * @param methodNode method to textify
 * @param out output stream
 */
public static void textify(MethodNode methodNode, OutputStream out) {
    TraceClassVisitor trace = new TraceClassVisitor(new PrintWriter(out));
    MethodVisitor mv = trace.visitMethod(methodNode.access, methodNode.name, methodNode.desc, methodNode.signature,
            methodNode.exceptions.toArray(new String[0]));
    methodNode.accept(mv);
    trace.visitEnd();
}
 
Example #23
Source File: GenNerdClass.java    From cs652 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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();
}
 
Example #24
Source File: MutantExportInterceptor.java    From pitest with Apache License 2.0 5 votes vote down vote up
private void writeBytecodeToDisk(final byte[] clazz, Path folder) throws IOException {
    final ClassReader reader = new ClassReader(clazz);
    final CharArrayWriter buffer = new CharArrayWriter();
    reader.accept(new TraceClassVisitor(null, new Textifier(), new PrintWriter(
        buffer)), ClassReader.EXPAND_FRAMES);
    final Path outFile = folder.resolve(this.currentClass.asJavaName() + ".txt");
    Files.write(outFile, Collections.singleton(buffer.toString()), StandardCharsets.UTF_8, StandardOpenOption.CREATE);
}
 
Example #25
Source File: ClassTree.java    From pitest with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
  final StringWriter writer = new StringWriter();
  this.rawNode.accept(new TraceClassVisitor(null, new Textifier(), new PrintWriter(
      writer)));
  return writer.toString();

}
 
Example #26
Source File: ASMBytecodeDisassembler.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private void accept(byte[] bytecode, Printer printer, PrintWriter writer) {

        final ClassReader cr = new ClassReader(bytecode);
        final ClassWriter cw = new ClassWriter(this.cwFlag);
        final TraceClassVisitor tcv = new TraceClassVisitor(cw, printer, writer);
        cr.accept(tcv, this.crFlag);
    }
 
Example #27
Source File: ASMClassWriterTest.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void accept() throws Exception {
    final String className = "com.navercorp.pinpoint.profiler.instrument.mock.SampleClass";
    ClassNode classNode = ASMClassNodeLoader.get(JavaAssistUtils.javaNameToJvmName(className));

    ASMClassWriter cw = new ASMClassWriter(pluginContext, 0, null);
    TraceClassVisitor tcv = new TraceClassVisitor(cw, null);
    classNode.accept(tcv);
}
 
Example #28
Source File: DebuggingWrapper.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
public ClassVisitor wrap(TypeDescription instrumentedType,
                         ClassVisitor classVisitor,
                         Implementation.Context implementationContext,
                         TypePool typePool,
                         FieldList<FieldDescription.InDefinedShape> fields,
                         MethodList<?> methods,
                         int writerFlags,
                         int readerFlags) {
    return check
            ? new CheckClassAdapter(new TraceClassVisitor(classVisitor, printer, printWriter))
            : new TraceClassVisitor(classVisitor, printer, printWriter);
}
 
Example #29
Source File: ViewBytecodeUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenUsingASM_thenReadBytecode() throws IOException {
    ClassReader reader = new ClassReader("java.lang.Object");
    StringWriter sw = new StringWriter();
    TraceClassVisitor tcv = new TraceClassVisitor(new PrintWriter(sw));
    reader.accept(tcv, 0); 
    
    assertTrue(sw.toString().contains("public class java/lang/Object")); 
}
 
Example #30
Source File: JarDumper.java    From buck with Apache License 2.0 5 votes vote down vote up
private Stream<String> dumpClassFile(InputStream stream) throws IOException {
  byte[] textifiedClass;
  try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
      PrintWriter pw = new PrintWriter(bos)) { // NOPMD required by API
    ClassReader reader = new ClassReader(stream);
    TraceClassVisitor traceVisitor = new TraceClassVisitor(null, new Textifier(), pw);
    reader.accept(traceVisitor, asmFlags);
    textifiedClass = bos.toByteArray();
  }

  try (InputStreamReader streamReader =
      new InputStreamReader(new ByteArrayInputStream(textifiedClass))) {
    return CharStreams.readLines(streamReader).stream();
  }
}