Java Code Examples for org.objectweb.asm.ClassWriter#visitMethod()

The following examples show how to use org.objectweb.asm.ClassWriter#visitMethod() . 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: WriteStyleablesProcessor.java    From shrinker with Apache License 2.0 6 votes vote down vote up
private void writeClinit(ClassWriter writer) {
    Map<String, int[]> styleables = symbols.getStyleables();
    MethodVisitor clinit = writer.visitMethod(Opcodes.ACC_STATIC, "<clinit>", "()V", null, null);
    clinit.visitCode();

    for (Map.Entry<String, int[]> entry : styleables.entrySet()) {
        final String field = entry.getKey();
        final int[] value = entry.getValue();
        final int length = value.length;
        pushInt(clinit, length);
        clinit.visitIntInsn(Opcodes.NEWARRAY, Opcodes.T_INT);
        for (int i = 0; i < length; i++) {
            clinit.visitInsn(Opcodes.DUP);                  // dup
            pushInt(clinit, i);
            pushInt(clinit, value[i]);
            clinit.visitInsn(Opcodes.IASTORE);              // iastore
        }
        clinit.visitFieldInsn(Opcodes.PUTSTATIC, RSymbols.R_STYLEABLES_CLASS_NAME, field, "[I");
    }
    clinit.visitInsn(Opcodes.RETURN);
    clinit.visitMaxs(0, 0); // auto compute
    clinit.visitEnd();
}
 
Example 2
Source File: AdviceGenerator.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private void addOnThrowMethod(ClassWriter cw) {
    MethodVisitor mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "onThrow",
            "(Ljava/lang/Throwable;Lorg/glowroot/agent/plugin/api/TraceEntry;)V", null, null);
    visitAnnotation(mv, "Lorg/glowroot/agent/plugin/api/weaving/OnThrow;");
    checkNotNull(mv.visitParameterAnnotation(0,
            "Lorg/glowroot/agent/plugin/api/weaving/BindThrowable;", true)).visitEnd();
    checkNotNull(mv.visitParameterAnnotation(1,
            "Lorg/glowroot/agent/plugin/api/weaving/BindTraveler;", true)).visitEnd();
    mv.visitCode();
    if (!config.traceEntryEnabledProperty().isEmpty()) {
        mv.visitVarInsn(ALOAD, 1);
        Label l0 = new Label();
        mv.visitJumpInsn(IFNONNULL, l0);
        mv.visitInsn(RETURN);
        mv.visitLabel(l0);
    }
    mv.visitVarInsn(ALOAD, 1);
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKEINTERFACE, "org/glowroot/agent/plugin/api/TraceEntry",
            "endWithError", "(Ljava/lang/Throwable;)V", true);
    mv.visitInsn(RETURN);
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}
 
Example 3
Source File: MarkerClassGenerator.java    From OpenModsLib with MIT License 6 votes vote down vote up
private <T> Class<? extends T> createMarkerCls(Class<T> superClass, int key) {
	final ClassWriter writer = new ClassWriter(0);

	final String superCls = Type.getInternalName(superClass);
	writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, superCls + "$marker_" + key, null, superCls, interfaces);

	final MethodVisitor mv = writer.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, "getMarkerValue", "()I", null, null);
	mv.visitCode();
	mv.visitLdcInsn(key);
	mv.visitInsn(Opcodes.IRETURN);
	mv.visitMaxs(1, 1);
	mv.visitEnd();

	writer.visitEnd();

	@SuppressWarnings("unchecked")
	final Class<? extends T> cls = (Class<? extends T>)loader.define(writer.toByteArray());
	return cls;
}
 
Example 4
Source File: PeripheralCodeGenerator.java    From OpenPeripheral with MIT License 6 votes vote down vote up
protected void visitConnectivityMethod(String methodName, String clsName, ClassWriter writer, Type targetType, final boolean isAttachable, final boolean isOcAttachable) {
	MethodVisitor onConnect = writer.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, methodName, CONNECTIVITY_METHOD_TYPE.getDescriptor(), null, null);

	onConnect.visitCode();

	if (isAttachable) {
		onConnect.visitVarInsn(Opcodes.ALOAD, 0);
		onConnect.visitInsn(Opcodes.DUP);
		onConnect.visitFieldInsn(Opcodes.GETFIELD, clsName, CommonMethodsBuilder.TARGET_FIELD_NAME, targetType.getDescriptor());
		onConnect.visitVarInsn(Opcodes.ALOAD, 1);
		onConnect.visitMethodInsn(Opcodes.INVOKEVIRTUAL, clsName, methodName, ATTACHABLE_WRAP_TYPE.getDescriptor(), false);
	}

	if (isOcAttachable) {
		onConnect.visitVarInsn(Opcodes.ALOAD, 0);
		onConnect.visitFieldInsn(Opcodes.GETFIELD, clsName, CommonMethodsBuilder.TARGET_FIELD_NAME, targetType.getDescriptor());
		onConnect.visitVarInsn(Opcodes.ALOAD, 1);
		onConnect.visitMethodInsn(Opcodes.INVOKESTATIC, clsName, methodName, OC_ATTACHABLE_WRAP_TYPE.getDescriptor(), false);
	}

	onConnect.visitInsn(Opcodes.RETURN);

	onConnect.visitMaxs(0, 0);
	onConnect.visitEnd();
}
 
Example 5
Source File: InterfaceFieldClassGeneratorTest.java    From AVM with MIT License 5 votes vote down vote up
public static byte[] getNestedInterfaceCalledFIELDSLevelTwo() {

        ClassWriter classWriter = new ClassWriter(0);
        FieldVisitor fieldVisitor;
        MethodVisitor methodVisitor;

        classWriter.visit(V10, ACC_PUBLIC | ACC_ABSTRACT | ACC_INTERFACE, "NestedInterfaces$FIELDS$FIELDS", null, "java/lang/Object", null);

        classWriter.visitSource("NestedInterfaces.java", null);

        classWriter.visitInnerClass("NestedInterfaces$FIELDS", "NestedInterfaces", "FIELDS", ACC_STATIC | ACC_ABSTRACT | ACC_INTERFACE);

        classWriter.visitInnerClass("NestedInterfaces$FIELDS$FIELDS", "NestedInterfaces$FIELDS", "FIELDS", ACC_PUBLIC | ACC_STATIC | ACC_ABSTRACT | ACC_INTERFACE);

        {
            fieldVisitor = classWriter.visitField(ACC_PUBLIC | ACC_FINAL | ACC_STATIC, "b", "I", null, null);
            fieldVisitor.visitEnd();
        }
        {
            methodVisitor = classWriter.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
            methodVisitor.visitCode();
            Label label0 = new Label();
            methodVisitor.visitLabel(label0);
            methodVisitor.visitLineNumber(7, label0);
            methodVisitor.visitTypeInsn(NEW, "java/lang/Object");
            methodVisitor.visitInsn(DUP);
            methodVisitor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
            methodVisitor.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "hashCode", "()I", false);
            methodVisitor.visitFieldInsn(PUTSTATIC, "NestedInterfaces$FIELDS$FIELDS", "b", "I");
            methodVisitor.visitInsn(RETURN);
            methodVisitor.visitMaxs(2, 0);
            methodVisitor.visitEnd();
        }
        classWriter.visitEnd();

        return classWriter.toByteArray();
    }
 
Example 6
Source File: GenerateHackedConstructorBytecode.java    From glowroot with Apache License 2.0 5 votes vote down vote up
static LazyDefinedClass generateHackedConstructorBytecode() throws Exception {

        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
        MethodVisitor mv;

        cw.visit(V1_7, ACC_PUBLIC + ACC_SUPER, "HackedConstructorBytecode", null,
                Test.class.getName().replace('.', '/'), new String[] {});

        {
            mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
            mv.visitCode();
            mv.visitInsn(ICONST_1);
            mv.visitIntInsn(NEWARRAY, T_BOOLEAN);
            mv.visitVarInsn(ASTORE, 1);

            mv.visitVarInsn(ALOAD, 0);
            mv.visitMethodInsn(INVOKESPECIAL, Test.class.getName().replace('.', '/'), "<init>",
                    "()V", false);

            mv.visitVarInsn(ALOAD, 1);
            mv.visitInsn(ICONST_0);
            mv.visitInsn(ICONST_1);
            mv.visitInsn(BASTORE);

            mv.visitInsn(RETURN);

            mv.visitMaxs(0, 0);
            mv.visitEnd();
        }
        cw.visitEnd();

        return ImmutableLazyDefinedClass.builder()
                .type(Type.getObjectType("HackedConstructorBytecode"))
                .bytes(cw.toByteArray())
                .build();
    }
 
Example 7
Source File: DgmConverter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void createIsValidMethodMethod(CachedMethod method, ClassWriter cw, String className) {
    MethodVisitor mv;
    if (method.getParamsCount() == 2 && method.getParameterTypes()[0].isNumber && method.getParameterTypes()[1].isNumber) {
        // 1 param meta method
        mv = cw.visitMethod(ACC_PUBLIC, "isValidMethod", "([Ljava/lang/Class;)Z", null, null);
        mv.visitCode();
        mv.visitVarInsn(ALOAD, 1);
        Label l0 = new Label();
        mv.visitJumpInsn(IFNULL, l0);
        mv.visitVarInsn(ALOAD, 0);
        mv.visitMethodInsn(INVOKEVIRTUAL, className, "getParameterTypes", "()[Lorg/codehaus/groovy/reflection/CachedClass;", false);
        mv.visitInsn(ICONST_0);
        mv.visitInsn(AALOAD);
        mv.visitVarInsn(ALOAD, 1);
        mv.visitInsn(ICONST_0);
        mv.visitInsn(AALOAD);
        mv.visitMethodInsn(INVOKEVIRTUAL, "org/codehaus/groovy/reflection/CachedClass", "isAssignableFrom", "(Ljava/lang/Class;)Z", false);
        Label l1 = new Label();
        mv.visitJumpInsn(IFEQ, l1);
        mv.visitLabel(l0);
        mv.visitInsn(ICONST_1);
        Label l2 = new Label();
        mv.visitJumpInsn(GOTO, l2);
        mv.visitLabel(l1);
        mv.visitInsn(ICONST_0);
        mv.visitLabel(l2);
        mv.visitInsn(IRETURN);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }
}
 
Example 8
Source File: DefaultApplicationFactory.java    From thorntail with Apache License 2.0 5 votes vote down vote up
static byte[] basicClassBytes() {
    ClassWriter cw = new ClassWriter(0);
    MethodVisitor mv;

    cw.visit(52, ACC_PUBLIC + ACC_SUPER, "org/wildfly/swarm/jaxrs/runtime/DefaultApplication", null, "javax/ws/rs/core/Application", null);

    cw.visitSource("DefaultApplication.java", null);
    {
        mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitLineNumber(23, l0);
        mv.visitVarInsn(ALOAD, 0);
        mv.visitMethodInsn(INVOKESPECIAL, "javax/ws/rs/core/Application", "<init>", "()V", false);
        mv.visitInsn(RETURN);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLocalVariable("this", "Lorg/wildfly/swarm/jaxrs/runtime/DefaultApplication;", null, l0, l1, 0);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }
    cw.visitEnd();

    return cw.toByteArray();

}
 
Example 9
Source File: AdviceGenerator.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private static void addOnAfterMethodTimerOnly(ClassWriter cw) {
    MethodVisitor mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "onAfter",
            "(Lorg/glowroot/agent/plugin/api/Timer;)V", null, null);
    visitAnnotation(mv, "Lorg/glowroot/agent/plugin/api/weaving/OnAfter;");
    checkNotNull(mv.visitParameterAnnotation(0,
            "Lorg/glowroot/agent/plugin/api/weaving/BindTraveler;", true)).visitEnd();
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKEINTERFACE, "org/glowroot/agent/plugin/api/Timer", "stop", "()V",
            true);
    mv.visitInsn(RETURN);
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}
 
Example 10
Source File: AsmTest.java    From java-master with Apache License 2.0 5 votes vote down vote up
@Test
public void ModifyClassTest() throws Exception {
    // 读取的Person类的class文件
    ClassReader classReader = new ClassReader("org.javamaster.b2c.bytecode.model.Person");
    ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    ClassAdapter classAdapter = new ClassAdapter(classWriter);
    classReader.accept(classAdapter, ClassReader.SKIP_DEBUG);

    // 插入新方法
    // Opcodes.ACC_PUBLIC:方法修饰符为public
    // sayHello:方法名为sayHello
    // ()V:没有入参,返回类型为void
    // new String[]{"javax.validation.ValidationException"}:声明抛出ValidationException异常
    MethodVisitor helloVisitor = classWriter
            .visitMethod(Opcodes.ACC_PUBLIC, "sayHello", "()V", null, new String[]{"javax.validation.ValidationException"});
    // 插入方法体内容,以下涉及到了虚拟机字节码指令
    helloVisitor.visitCode();
    // getstatic 指令:取静态字段
    helloVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
    // ldc 指令:取"hello world!"常量到操作数栈
    helloVisitor.visitLdcInsn("hello world!");
    // invokevirtual 指令: 调用实例方法println
    helloVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V");
    // return 指令: 从当前方法返回void
    helloVisitor.visitInsn(Opcodes.RETURN);
    helloVisitor.visitMaxs(1, 1);
    helloVisitor.visitEnd();

    byte[] bytes = classWriter.toByteArray();

    String path = ResourceUtils.getFile("classpath:").getAbsolutePath();
    File file = new File(path, "/org/javamaster/b2c/bytecode/PersonModify.class");
    FileOutputStream fileOutputStream = new FileOutputStream(file);
    fileOutputStream.write(bytes);
    fileOutputStream.close();
}
 
Example 11
Source File: ConstructorAccess.java    From reflectasm with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static void insertNewInstance (ClassWriter cw, String classNameInternal) {
	MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "newInstance", "()Ljava/lang/Object;", null, null);
	mv.visitCode();
	mv.visitTypeInsn(NEW, classNameInternal);
	mv.visitInsn(DUP);
	mv.visitMethodInsn(INVOKESPECIAL, classNameInternal, "<init>", "()V");
	mv.visitInsn(ARETURN);
	mv.visitMaxs(2, 1);
	mv.visitEnd();
}
 
Example 12
Source File: DynamicEntityGenerator.java    From we-cmdb with Apache License 2.0 5 votes vote down vote up
private static void writeGetterForMapperBy(ClassWriter classWriter, FieldNode field, String className, String getter) {
    MethodVisitor methodVisitor;
    AnnotationVisitor annotationVisitor0;
    methodVisitor = classWriter.visitMethod(ACC_PUBLIC, getter, "()Ljava/util/Set;", "()" + getTypeSiganitureForOneToMany(field.getTypeDesc()), null);
    if (DynamicEntityType.MultiReference.equals(field.getEntityType())) {
        annotationVisitor0 = methodVisitor.visitAnnotation("Ljavax/persistence/ManyToMany;", true);
        annotationVisitor0.visit("mappedBy", field.getMappedBy());
        annotationVisitor0.visitEnd();
    } else {
        annotationVisitor0 = methodVisitor.visitAnnotation("Ljavax/persistence/OneToMany;", true);
        annotationVisitor0.visit("mappedBy", field.getMappedBy());
        if (DynamicEntityType.MultiSelection.equals(field.getEntityType())) {
            annotationVisitor0.visitEnum("fetch", "Ljavax/persistence/FetchType;", "EAGER");
            AnnotationVisitor annotationVisitor1 = annotationVisitor0.visitArray("cascade");
            annotationVisitor1.visitEnum(null, "Ljavax/persistence/CascadeType;", CascadeType.ALL.toString());
            annotationVisitor1.visitEnd();
        }
        annotationVisitor0.visitEnd();
    }
    {
        annotationVisitor0 = methodVisitor.visitAnnotation("Lcom/fasterxml/jackson/annotation/JsonIgnore;", true);
        annotationVisitor0.visitEnd();
    }

    // getter method body
    methodVisitor.visitVarInsn(ALOAD, 0);
    methodVisitor.visitFieldInsn(GETFIELD, className, field.getName(), "Ljava/util/Set;");
    methodVisitor.visitInsn(ARETURN);
    methodVisitor.visitMaxs(1, 1);
    methodVisitor.visitEnd();
}
 
Example 13
Source File: ModClassGenerator.java    From customstuff4 with GNU General Public License v3.0 4 votes vote down vote up
private static byte[] generateClassCode(ModInfo info)
{
    checkArgument(info.isValid(), "Invalid mod id");

    ClassWriter cw = new ClassWriter(0);
    cw.visit(V1_7, ACC_PUBLIC + ACC_SUPER, "cs4mod/" + info.id, null, "java/lang/Object", new String[] {CS4_MOD});

    // Mod annotation
    AnnotationVisitor av = cw.visitAnnotation(String.format("L%s;", MOD), true);
    av.visit("modid", info.id);
    av.visit("name", info.name);
    av.visit("version", info.version);
    av.visit("dependencies", String.format("required-after:%s;%s", CustomStuff4.ID, info.dependencies));
    av.visitEnd();

    // Constructor
    MethodVisitor 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.visitFieldInsn(GETSTATIC, "net/minecraftforge/common/MinecraftForge", "EVENT_BUS", desc(EVENT_BUS));
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKEVIRTUAL, EVENT_BUS, "register", voidMethodDesc("java/lang/Object"), false);
    mv.visitInsn(RETURN);
    mv.visitMaxs(2, 1);
    mv.visitEnd();

    // PreInit
    mv = cw.visitMethod(ACC_PUBLIC, "preInit", voidMethodDesc(PRE_INIT_EVENT), null, null);
    av = mv.visitAnnotation(String.format("L%s;", EVENT_HANDLER), true);
    av.visitEnd();
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESTATIC, MOD_LOADER, "onPreInitMod", voidMethodDesc(CS4_MOD), false);
    mv.visitInsn(RETURN);
    mv.visitMaxs(1, 2);
    mv.visitEnd();

    // Init
    mv = cw.visitMethod(ACC_PUBLIC, "init", voidMethodDesc(INIT_EVENT), null, null);
    av = mv.visitAnnotation(String.format("L%s;", EVENT_HANDLER), true);
    av.visitEnd();
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESTATIC, MOD_LOADER, "onInitMod", voidMethodDesc(CS4_MOD), false);
    mv.visitInsn(RETURN);
    mv.visitMaxs(1, 2);
    mv.visitEnd();

    // PostInit
    mv = cw.visitMethod(ACC_PUBLIC, "postInit", voidMethodDesc(POST_INIT_EVENT), null, null);
    av = mv.visitAnnotation(String.format("L%s;", EVENT_HANDLER), true);
    av.visitEnd();
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESTATIC, MOD_LOADER, "onPostInitMod", voidMethodDesc(CS4_MOD), false);
    mv.visitInsn(RETURN);
    mv.visitMaxs(1, 2);
    mv.visitEnd();

    // RegisterBlocks
    mv = cw.visitMethod(ACC_PUBLIC, "onRegisterBlocks", voidMethodDesc(REGISTER_BLOCKS_EVENT), voidMethodDesc(REGISTER_BLOCKS_SIGNATURE), null);
    av = mv.visitAnnotation(desc(SUBSCRIBE_EVENT), true);
    av.visitEnd();
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESTATIC, MOD_LOADER, "onRegisterBlocks", voidMethodDesc(CS4_MOD), false);
    mv.visitInsn(RETURN);
    mv.visitMaxs(1, 2);
    mv.visitEnd();

    // RegisterItems
    mv = cw.visitMethod(ACC_PUBLIC, "onRegisterItems", voidMethodDesc(REGISTER_ITEMS_EVENT), voidMethodDesc(REGISTER_ITEMS_SIGNATURE), null);
    av = mv.visitAnnotation(desc(SUBSCRIBE_EVENT), true);
    av.visitEnd();
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESTATIC, MOD_LOADER, "onRegisterItems", voidMethodDesc(CS4_MOD), false);
    mv.visitInsn(RETURN);
    mv.visitMaxs(1, 2);
    mv.visitEnd();

    // RegisterModels
    mv = cw.visitMethod(ACC_PUBLIC, "onRegisterModels", voidMethodDesc(REGISTER_MODELS_EVENT), null, null);
    av = mv.visitAnnotation(desc(SUBSCRIBE_EVENT), true);
    av.visitEnd();
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESTATIC, MOD_LOADER, "onRegisterModels", voidMethodDesc(CS4_MOD), false);
    mv.visitInsn(RETURN);
    mv.visitMaxs(1, 2);
    mv.visitEnd();

    return cw.toByteArray();
}
 
Example 14
Source File: SpelCompiler.java    From bistoury with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Generate the class that encapsulates the compiled expression and define it.
 * The  generated class will be a subtype of CompiledExpression.
 *
 * @param expressionToCompile the expression to be compiled
 * @return the expression call, or {@code null} if the decision was to opt out of
 * compilation during code generation
 */
@SuppressWarnings("unchecked")
private Class<? extends CompiledExpression> createExpressionClass(SpelNodeImpl expressionToCompile) {
    // Create class outline 'spel/ExNNN extends org.springframework.expression.spel.CompiledExpression'
    String clazzName = "qunar/tc/bistoury/instrument/client/debugger/Ex" + getNextSuffix();
    ClassWriter cw = new ExpressionClassWriter();
    cw.visit(V1_5, ACC_PUBLIC, clazzName, null, "qunar/tc/bistoury/instrument/client/debugger/CompiledExpression", null);

    // Create default constructor
    MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESPECIAL, "qunar/tc/bistoury/instrument/client/debugger/CompiledExpression",
            "<init>", "()V", false);
    mv.visitInsn(RETURN);
    mv.visitMaxs(1, 1);
    mv.visitEnd();

    // Create getValue() method
    mv = cw.visitMethod(ACC_PUBLIC, "getValue",
            "(Ljava/lang/Object;Lqunar/tc/bistoury/instrument/client/debugger/EvaluationContext;)Ljava/lang/Object;", null,
            new String[]{"qunar/tc/bistoury/instrument/client/debugger/EvaluationException"});
    mv.visitCode();

    CodeFlow cf = new CodeFlow(clazzName, cw);

    // Ask the expression AST to generate the body of the method
    try {
        expressionToCompile.generateCode(mv, cf);
    } catch (IllegalStateException ex) {
        if (logger.isDebugEnabled()) {
            logger.debug(expressionToCompile.getClass().getSimpleName() +
                    ".generateCode opted out of compilation: " + ex.getMessage());
        }
        return null;
    }

    CodeFlow.insertBoxIfNecessary(mv, cf.lastDescriptor());
    if ("V".equals(cf.lastDescriptor())) {
        mv.visitInsn(ACONST_NULL);
    }
    mv.visitInsn(ARETURN);

    mv.visitMaxs(0, 0);  // not supplied due to COMPUTE_MAXS
    mv.visitEnd();
    cw.visitEnd();

    cf.finish();

    byte[] data = cw.toByteArray();
    // TODO need to make this conditionally occur based on a debug flag
    // dump(expressionToCompile.toStringAST(), clazzName, data);
    return (Class<? extends CompiledExpression>) this.ccl.defineClass(clazzName.replaceAll("/", "."), data);
}
 
Example 15
Source File: UnbalancedMonitorsTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private static void visitWrongOrder(ClassWriter cw) {
    MethodVisitor mv;
    mv = cw.visitMethod(ACC_PUBLIC, "wrongOrder", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", null, null);
    mv.visitCode();
    Label l0 = new Label();
    Label l1 = new Label();
    Label l2 = new Label();
    mv.visitTryCatchBlock(l0, l1, l2, null);
    Label l3 = new Label();
    mv.visitTryCatchBlock(l2, l3, l2, null);
    Label l4 = new Label();
    Label l5 = new Label();
    Label l6 = new Label();
    mv.visitTryCatchBlock(l4, l5, l6, null);
    Label l7 = new Label();
    mv.visitTryCatchBlock(l2, l7, l6, null);
    Label l8 = new Label();
    mv.visitLabel(l8);
    mv.visitVarInsn(ALOAD, 1);
    mv.visitInsn(DUP);
    mv.visitVarInsn(ASTORE, 3);
    mv.visitInsn(MONITORENTER);
    mv.visitLabel(l4);
    mv.visitVarInsn(ALOAD, 2);
    mv.visitInsn(DUP);
    mv.visitVarInsn(ASTORE, 4);
    mv.visitInsn(MONITORENTER);
    mv.visitLabel(l0);
    mv.visitVarInsn(ALOAD, 2);
    mv.visitVarInsn(ALOAD, 3);
    mv.visitInsn(MONITOREXIT);
    mv.visitLabel(l1);
    // Swapped exit order with exit above
    mv.visitVarInsn(ALOAD, 4);
    mv.visitInsn(MONITOREXIT);
    mv.visitLabel(l5);
    mv.visitInsn(ARETURN);
    mv.visitLabel(l2);
    mv.visitFrame(Opcodes.F_FULL, 5, new Object[]{INNER_CLASS_NAME_INTERNAL, "java/lang/Object", "java/lang/Object", "java/lang/Object",
                    "java/lang/Object"}, 1, new Object[]{"java/lang/Throwable"});
    mv.visitVarInsn(ALOAD, 4);
    mv.visitInsn(MONITOREXIT);
    mv.visitLabel(l3);
    mv.visitInsn(ATHROW);
    mv.visitLabel(l6);
    mv.visitFrame(Opcodes.F_FULL, 4, new Object[]{INNER_CLASS_NAME_INTERNAL, "java/lang/Object", "java/lang/Object", "java/lang/Object"}, 1,
                    new Object[]{"java/lang/Throwable"});
    mv.visitVarInsn(ALOAD, 3);
    mv.visitInsn(MONITOREXIT);
    mv.visitLabel(l7);
    mv.visitInsn(ATHROW);
    Label l9 = new Label();
    mv.visitLabel(l9);
    mv.visitMaxs(2, 5);
    mv.visitEnd();
}
 
Example 16
Source File: AdviceGenerator.java    From glowroot with Apache License 2.0 4 votes vote down vote up
private void addStaticInitializer(ClassWriter cw) {
    MethodVisitor mv = cw.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
    mv.visitCode();
    if (pluginId != null) {
        mv.visitLdcInsn(pluginId);
        mv.visitMethodInsn(INVOKESTATIC, "org/glowroot/agent/plugin/api/Agent",
                "getConfigService",
                "(Ljava/lang/String;)Lorg/glowroot/agent/plugin/api/config/ConfigService;",
                false);
        mv.visitFieldInsn(PUTSTATIC, adviceInternalName, "configService",
                "Lorg/glowroot/agent/plugin/api/config/ConfigService;");
    }
    if (config.isTimerOrGreater()) {
        mv.visitLdcInsn(Type.getObjectType(adviceInternalName));
        mv.visitMethodInsn(INVOKESTATIC, "org/glowroot/agent/plugin/api/Agent", "getTimerName",
                "(Ljava/lang/Class;)Lorg/glowroot/agent/plugin/api/TimerName;", false);
        mv.visitFieldInsn(PUTSTATIC, adviceInternalName, "timerName",
                "Lorg/glowroot/agent/plugin/api/TimerName;");
    }
    if (!config.enabledProperty().isEmpty() && pluginId != null) {
        mv.visitFieldInsn(GETSTATIC, adviceInternalName, "configService",
                "Lorg/glowroot/agent/plugin/api/config/ConfigService;");
        mv.visitLdcInsn(config.enabledProperty());
        mv.visitMethodInsn(INVOKEINTERFACE,
                "org/glowroot/agent/plugin/api/config/ConfigService", "getBooleanProperty",
                "(Ljava/lang/String;)Lorg/glowroot/agent/plugin/api/config/BooleanProperty;",
                true);
        mv.visitFieldInsn(PUTSTATIC, adviceInternalName, "enabled",
                "Lorg/glowroot/agent/plugin/api/config/BooleanProperty;");
    }
    if (!config.traceEntryEnabledProperty().isEmpty() && pluginId != null) {
        mv.visitFieldInsn(GETSTATIC, adviceInternalName, "configService",
                "Lorg/glowroot/agent/plugin/api/config/ConfigService;");
        mv.visitLdcInsn(config.traceEntryEnabledProperty());
        mv.visitMethodInsn(INVOKEINTERFACE,
                "org/glowroot/agent/plugin/api/config/ConfigService", "getBooleanProperty",
                "(Ljava/lang/String;)Lorg/glowroot/agent/plugin/api/config/BooleanProperty;",
                true);
        mv.visitFieldInsn(PUTSTATIC, adviceInternalName, "entryEnabled",
                "Lorg/glowroot/agent/plugin/api/config/BooleanProperty;");
    }
    mv.visitInsn(RETURN);
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}
 
Example 17
Source File: FieldAccess.java    From reflectasm with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
static private void insertGetString (ClassWriter cw, String classNameInternal, ArrayList<Field> fields) {
	int maxStack = 6;
	MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "getString", "(Ljava/lang/Object;I)Ljava/lang/String;", null, null);
	mv.visitCode();
	mv.visitVarInsn(ILOAD, 2);

	if (!fields.isEmpty()) {
		maxStack--;
		Label[] labels = new Label[fields.size()];
		Label labelForInvalidTypes = new Label();
		boolean hasAnyBadTypeLabel = false;
		for (int i = 0, n = labels.length; i < n; i++) {
			if (fields.get(i).getType().equals(String.class))
				labels[i] = new Label();
			else {
				labels[i] = labelForInvalidTypes;
				hasAnyBadTypeLabel = true;
			}
		}
		Label defaultLabel = new Label();
		mv.visitTableSwitchInsn(0, labels.length - 1, defaultLabel, labels);

		for (int i = 0, n = labels.length; i < n; i++) {
			if (!labels[i].equals(labelForInvalidTypes)) {
				Field field = fields.get(i);
				mv.visitLabel(labels[i]);
				mv.visitFrame(F_SAME, 0, null, 0, null);
				mv.visitVarInsn(ALOAD, 1);
				mv.visitTypeInsn(CHECKCAST, classNameInternal);
				mv.visitFieldInsn(GETFIELD, field.getDeclaringClass().getName().replace('.', '/'), field.getName(),
					"Ljava/lang/String;");
				mv.visitInsn(ARETURN);
			}
		}
		// Rest of fields: different type
		if (hasAnyBadTypeLabel) {
			mv.visitLabel(labelForInvalidTypes);
			mv.visitFrame(F_SAME, 0, null, 0, null);
			insertThrowExceptionForFieldType(mv, "String");
		}
		// Default: field not found
		mv.visitLabel(defaultLabel);
		mv.visitFrame(F_SAME, 0, null, 0, null);
	}
	insertThrowExceptionForFieldNotFound(mv);
	mv.visitMaxs(maxStack, 3);
	mv.visitEnd();
}
 
Example 18
Source File: UnbalancedMonitorsTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private static void visitBlockStructured(ClassWriter cw, boolean normalReturnError, boolean tooMany) {
    String name = (tooMany ? "tooMany" : "tooFew") + "Exits" + (normalReturnError ? "" : "Exceptional");
    // Generate too many or too few exits down the either the normal or exceptional return paths
    int exceptionalExitCount = normalReturnError ? 1 : (tooMany ? 2 : 0);
    int normalExitCount = normalReturnError ? (tooMany ? 2 : 0) : 1;
    MethodVisitor mv;
    mv = cw.visitMethod(ACC_PUBLIC, name, "(Ljava/lang/Object;Ljava/lang/Object;)Z", null, null);
    mv.visitCode();
    Label l0 = new Label();
    Label l1 = new Label();
    Label l2 = new Label();
    mv.visitTryCatchBlock(l0, l1, l2, null);
    Label l3 = new Label();
    mv.visitTryCatchBlock(l2, l3, l2, null);
    Label l4 = new Label();
    Label l5 = new Label();
    Label l6 = new Label();
    mv.visitTryCatchBlock(l4, l5, l6, null);
    Label l7 = new Label();
    mv.visitTryCatchBlock(l2, l7, l6, null);
    Label l8 = new Label();
    mv.visitLabel(l8);
    mv.visitVarInsn(ALOAD, 1);
    mv.visitInsn(DUP);
    mv.visitVarInsn(ASTORE, 3);
    mv.visitInsn(MONITORENTER);
    mv.visitLabel(l4);
    mv.visitVarInsn(ALOAD, 2);
    mv.visitInsn(DUP);
    mv.visitVarInsn(ASTORE, 4);
    mv.visitInsn(MONITORENTER);
    mv.visitLabel(l0);
    mv.visitVarInsn(ALOAD, 2);
    mv.visitVarInsn(ALOAD, 1);
    mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "equals", "(Ljava/lang/Object;)Z", false);
    mv.visitVarInsn(ALOAD, 4);
    mv.visitInsn(MONITOREXIT);
    mv.visitLabel(l1);
    for (int i = 0; i < normalExitCount; i++) {
        mv.visitVarInsn(ALOAD, 3);
        mv.visitInsn(MONITOREXIT);
    }
    mv.visitLabel(l5);
    mv.visitInsn(IRETURN);
    mv.visitLabel(l2);
    mv.visitFrame(Opcodes.F_FULL, 5, new Object[]{INNER_CLASS_NAME_INTERNAL, "java/lang/Object", "java/lang/Object", "java/lang/Object",
                    "java/lang/Object"}, 1, new Object[]{"java/lang/Throwable"});
    mv.visitVarInsn(ALOAD, 4);
    mv.visitInsn(MONITOREXIT);
    mv.visitLabel(l3);
    mv.visitInsn(ATHROW);
    mv.visitLabel(l6);
    mv.visitFrame(Opcodes.F_FULL, 4, new Object[]{INNER_CLASS_NAME_INTERNAL, "java/lang/Object", "java/lang/Object", "java/lang/Object"}, 1,
                    new Object[]{"java/lang/Throwable"});
    for (int i = 0; i < exceptionalExitCount; i++) {
        mv.visitVarInsn(ALOAD, 3);
        mv.visitInsn(MONITOREXIT);
    }
    mv.visitLabel(l7);
    mv.visitInsn(ATHROW);
    Label l9 = new Label();
    mv.visitLabel(l9);
    mv.visitMaxs(2, 5);
    mv.visitEnd();
}
 
Example 19
Source File: AdviceGenerator.java    From glowroot with Apache License 2.0 4 votes vote down vote up
private void addOnReturnMethod(ClassWriter cw) {
    boolean entryOrTimer = !config.traceEntryEnabledProperty().isEmpty();
    String travelerType =
            entryOrTimer ? "Ljava/lang/Object;" : "Lorg/glowroot/agent/plugin/api/TraceEntry;";
    MethodVisitor mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "onReturn",
            "(Lorg/glowroot/agent/plugin/api/weaving/OptionalReturn;" + travelerType + ")V",
            null, null);
    checkNotNull(mv.visitParameterAnnotation(0,
            "Lorg/glowroot/agent/plugin/api/weaving/BindOptionalReturn;", true)).visitEnd();
    checkNotNull(mv.visitParameterAnnotation(1,
            "Lorg/glowroot/agent/plugin/api/weaving/BindTraveler;", true)).visitEnd();
    int travelerParamIndex = 1;
    visitAnnotation(mv, "Lorg/glowroot/agent/plugin/api/weaving/OnReturn;");
    mv.visitCode();
    if (!config.traceEntryEnabledProperty().isEmpty()) {
        mv.visitVarInsn(ALOAD, travelerParamIndex);
        // TraceEntryImpl implements both TraceEntry and Timer so cannot check instanceof Timer
        // to differentiate here (but can check isntanceof TraceEntry)
        mv.visitTypeInsn(INSTANCEOF, "org/glowroot/agent/plugin/api/TraceEntry");
        Label label = new Label();
        mv.visitJumpInsn(IFNE, label);
        mv.visitVarInsn(ALOAD, travelerParamIndex);
        mv.visitTypeInsn(CHECKCAST, "org/glowroot/agent/plugin/api/Timer");
        mv.visitMethodInsn(INVOKEINTERFACE, "org/glowroot/agent/plugin/api/Timer", "stop",
                "()V", true);
        mv.visitInsn(RETURN);
        mv.visitLabel(label);
    }
    mv.visitVarInsn(ALOAD, 1);
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKEINTERFACE, "org/glowroot/agent/plugin/api/weaving/OptionalReturn",
            "isVoid", "()Z", true);
    Label notVoidLabel = new Label();
    Label endIfLabel = new Label();
    mv.visitJumpInsn(IFEQ, notVoidLabel);
    mv.visitLdcInsn("void");
    mv.visitJumpInsn(GOTO, endIfLabel);
    mv.visitLabel(notVoidLabel);
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKEINTERFACE, "org/glowroot/agent/plugin/api/weaving/OptionalReturn",
            "getValue", "()Ljava/lang/Object;", true);
    mv.visitLabel(endIfLabel);
    mv.visitMethodInsn(INVOKESTATIC, "org/glowroot/agent/bytecode/api/Bytecode",
            "updateWithReturnValue",
            "(Lorg/glowroot/agent/plugin/api/TraceEntry;Ljava/lang/Object;)V", false);
    mv.visitVarInsn(ALOAD, travelerParamIndex);
    Integer stackTraceThresholdMillis = config.traceEntryStackThresholdMillis();
    if (stackTraceThresholdMillis == null) {
        mv.visitMethodInsn(INVOKEINTERFACE, "org/glowroot/agent/plugin/api/TraceEntry", "end",
                "()V", true);
    } else {
        mv.visitLdcInsn(stackTraceThresholdMillis.longValue());
        mv.visitFieldInsn(GETSTATIC, "java/util/concurrent/TimeUnit", "MILLISECONDS",
                "Ljava/util/concurrent/TimeUnit;");
        mv.visitMethodInsn(INVOKEINTERFACE, "org/glowroot/agent/plugin/api/TraceEntry",
                "endWithLocationStackTrace", "(JLjava/util/concurrent/TimeUnit;)V", true);
    }
    mv.visitInsn(RETURN);
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}
 
Example 20
Source File: TestEnumForEclipseCompilerDump.java    From AVM with MIT License 4 votes vote down vote up
public static byte[] generateBytecode() {
    ClassWriter classWriter = new ClassWriter(0);
    FieldVisitor fieldVisitor;
    MethodVisitor methodVisitor;

    classWriter.visit(V10, ACC_PUBLIC | ACC_FINAL | ACC_SUPER | ACC_ENUM, PACKAGE_NAME_INTERNAL + "/TestEnumForValues", "Ljava/lang/Enum<L" + PACKAGE_NAME_INTERNAL + "/TestEnumForValues;>;", "java/lang/Enum", null);

    {
        fieldVisitor = classWriter.visitField(ACC_PUBLIC | ACC_FINAL | ACC_STATIC | ACC_ENUM, "TEST", "L" + PACKAGE_NAME_INTERNAL + "/TestEnumForValues;", null, null);
        fieldVisitor.visitEnd();
    }
    {
        fieldVisitor = classWriter.visitField(ACC_PRIVATE | ACC_FINAL | ACC_STATIC | ACC_SYNTHETIC, "ENUM$VALUES", "[L" + PACKAGE_NAME_INTERNAL + "/TestEnumForValues;", null, null);
        fieldVisitor.visitEnd();
    }
    {
        methodVisitor = classWriter.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
        methodVisitor.visitCode();
        methodVisitor.visitTypeInsn(NEW, PACKAGE_NAME_INTERNAL + "/TestEnumForValues");
        methodVisitor.visitInsn(DUP);
        methodVisitor.visitLdcInsn("TEST");
        methodVisitor.visitInsn(ICONST_0);
        methodVisitor.visitMethodInsn(INVOKESPECIAL, PACKAGE_NAME_INTERNAL + "/TestEnumForValues", "<init>", "(Ljava/lang/String;I)V", false);
        methodVisitor.visitFieldInsn(PUTSTATIC, PACKAGE_NAME_INTERNAL + "/TestEnumForValues", "TEST", "L" + PACKAGE_NAME_INTERNAL + "/TestEnumForValues;");
        methodVisitor.visitInsn(ICONST_1);
        methodVisitor.visitTypeInsn(ANEWARRAY, PACKAGE_NAME_INTERNAL + "/TestEnumForValues");
        methodVisitor.visitInsn(DUP);
        methodVisitor.visitInsn(ICONST_0);
        methodVisitor.visitFieldInsn(GETSTATIC, PACKAGE_NAME_INTERNAL + "/TestEnumForValues", "TEST", "L" + PACKAGE_NAME_INTERNAL + "/TestEnumForValues;");
        methodVisitor.visitInsn(AASTORE);
        methodVisitor.visitFieldInsn(PUTSTATIC, PACKAGE_NAME_INTERNAL + "/TestEnumForValues", "ENUM$VALUES", "[L" + PACKAGE_NAME_INTERNAL + "/TestEnumForValues;");
        methodVisitor.visitInsn(RETURN);
        methodVisitor.visitMaxs(4, 0);
        methodVisitor.visitEnd();
    }
    {
        methodVisitor = classWriter.visitMethod(ACC_PRIVATE, "<init>", "(Ljava/lang/String;I)V", null, null);
        methodVisitor.visitCode();
        methodVisitor.visitVarInsn(ALOAD, 0);
        methodVisitor.visitVarInsn(ALOAD, 1);
        methodVisitor.visitVarInsn(ILOAD, 2);
        methodVisitor.visitMethodInsn(INVOKESPECIAL, "java/lang/Enum", "<init>", "(Ljava/lang/String;I)V", false);
        methodVisitor.visitInsn(RETURN);
        methodVisitor.visitMaxs(3, 3);
        methodVisitor.visitEnd();
    }
    {
        methodVisitor = classWriter.visitMethod(ACC_PUBLIC | ACC_STATIC, "values", "()[L" + PACKAGE_NAME_INTERNAL + "/TestEnumForValues;", null, null);
        methodVisitor.visitCode();
        methodVisitor.visitFieldInsn(GETSTATIC, PACKAGE_NAME_INTERNAL + "/TestEnumForValues", "ENUM$VALUES", "[L" + PACKAGE_NAME_INTERNAL + "/TestEnumForValues;");
        methodVisitor.visitInsn(DUP);
        methodVisitor.visitVarInsn(ASTORE, 0);
        methodVisitor.visitInsn(ICONST_0);
        methodVisitor.visitVarInsn(ALOAD, 0);
        methodVisitor.visitInsn(ARRAYLENGTH);
        methodVisitor.visitInsn(DUP);
        methodVisitor.visitVarInsn(ISTORE, 1);
        methodVisitor.visitTypeInsn(ANEWARRAY, PACKAGE_NAME_INTERNAL + "/TestEnumForValues");
        methodVisitor.visitInsn(DUP);
        methodVisitor.visitVarInsn(ASTORE, 2);
        methodVisitor.visitInsn(ICONST_0);
        methodVisitor.visitVarInsn(ILOAD, 1);
        methodVisitor.visitMethodInsn(INVOKESTATIC, "java/lang/System", "arraycopy", "(Ljava/lang/Object;ILjava/lang/Object;II)V", false);
        methodVisitor.visitVarInsn(ALOAD, 2);
        methodVisitor.visitInsn(ARETURN);
        methodVisitor.visitMaxs(5, 3);
        methodVisitor.visitEnd();
    }
    {
        methodVisitor = classWriter.visitMethod(ACC_PUBLIC | ACC_STATIC, "valueOf", "(Ljava/lang/String;)L" + PACKAGE_NAME_INTERNAL + "/TestEnumForValues;", null, null);
        methodVisitor.visitCode();
        methodVisitor.visitLdcInsn(Type.getType("L" + PACKAGE_NAME_INTERNAL + "/TestEnumForValues;"));
        methodVisitor.visitVarInsn(ALOAD, 0);
        methodVisitor.visitMethodInsn(INVOKESTATIC, "java/lang/Enum", "valueOf", "(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;", false);
        methodVisitor.visitTypeInsn(CHECKCAST, PACKAGE_NAME_INTERNAL + "/TestEnumForValues");
        methodVisitor.visitInsn(ARETURN);
        methodVisitor.visitMaxs(2, 1);
        methodVisitor.visitEnd();
    }
    classWriter.visitEnd();

    return classWriter.toByteArray();
}