Java Code Examples for org.objectweb.asm.MethodVisitor#visitCode()

The following examples show how to use org.objectweb.asm.MethodVisitor#visitCode() . 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: AutomaticGraphVisitor.java    From AVM with MIT License 6 votes vote down vote up
@Override
public void visitEnd() {
    // If this isn't an interface, define the special constructor here.
    if (!this.isInterface) {
        // This logic is similar to StubGenerator.
        MethodVisitor methodVisitor = super.visitMethod(Opcodes.ACC_PUBLIC, INIT_NAME, SPECIAL_CONSTRUCTOR_DESCRIPTOR, null, null);
        methodVisitor.visitCode();
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
        methodVisitor.visitVarInsn(Opcodes.ILOAD, 2);
        methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, this.superClassName, INIT_NAME, SPECIAL_CONSTRUCTOR_DESCRIPTOR, false);
        methodVisitor.visitInsn(Opcodes.RETURN);
        methodVisitor.visitMaxs(4, 4);
        methodVisitor.visitEnd();
    }
    super.visitEnd();
}
 
Example 2
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 3
Source File: DgmConverter.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static void createInvokeMethod(CachedMethod method, ClassWriter cw, Class returnType, String methodDescriptor) {
    MethodVisitor mv;
    mv = cw.visitMethod(ACC_PUBLIC, "invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;", null, null);
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 1);
    BytecodeHelper.doCast(mv, method.getParameterTypes()[0].getTheClass());
    loadParameters(method, 2, mv);
    mv.visitMethodInsn(INVOKESTATIC, BytecodeHelper.getClassInternalName(method.getDeclaringClass().getTheClass()), method.getName(), methodDescriptor, false);
    BytecodeHelper.box(mv, returnType);
    if (method.getReturnType() == void.class) {
        mv.visitInsn(ACONST_NULL);
    }
    mv.visitInsn(ARETURN);
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}
 
Example 4
Source File: CreateTest.java    From AVM with MIT License 6 votes vote down vote up
private byte[] getByteCodeForClassWithoutSuperName() {
    ClassWriter classWriter = new ClassWriter(0);
    MethodVisitor methodVisitor;

    classWriter.visit(V10, ACC_PUBLIC | ACC_SUPER, "b/Main", null, null, null);

    classWriter.visitSource("Main.java", null);
    {
        methodVisitor = classWriter.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
        methodVisitor.visitCode();
        Label label0 = new Label();
        methodVisitor.visitLabel(label0);
        methodVisitor.visitLineNumber(3, label0);
        methodVisitor.visitVarInsn(ALOAD, 0);
        methodVisitor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
        methodVisitor.visitInsn(RETURN);
        methodVisitor.visitMaxs(1, 1);
        methodVisitor.visitEnd();
    }
    classWriter.visitEnd();

    return classWriter.toByteArray();
}
 
Example 5
Source File: ArrayWrappingClassGenerator.java    From AVM with MIT License 6 votes vote down vote up
private static void genSingleDimensionFactory(ClassWriter cw, String wrapper, int d){
    String facDesc = ArrayNameMapper.getFactoryDescriptor(wrapper, d);
    MethodVisitor mv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "initArray", facDesc, null, null);
    mv.visitCode();
    mv.visitTypeInsn(NEW, wrapper);
    mv.visitInsn(DUP);
    mv.visitVarInsn(ILOAD, 0);
    mv.visitMethodInsn(INVOKESPECIAL, wrapper, "<init>", "(I)V", false);

    // Charge energy
    mv.visitVarInsn(ILOAD, 0);
    mv.visitIntInsn(BIPUSH, ArrayElement.REF.getEnergy());
    mv.visitMethodInsn(INVOKESTATIC, SHADOW_ARRAY, "chargeEnergyInitArray", "(II)V", false);

    mv.visitInsn(ARETURN);
    mv.visitMaxs(3, 1);
    mv.visitEnd();
}
 
Example 6
Source File: DgmConverter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void createDoMethodInvokeMethod(CachedMethod method, ClassWriter cw, String className, Class returnType, String methodDescriptor) {
    MethodVisitor mv;
    mv = cw.visitMethod(ACC_PUBLIC + ACC_FINAL, "doMethodInvoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;", null, null);
    mv.visitCode();
    if (method.getParamsCount() == 2 && method.getParameterTypes()[0].isNumber && method.getParameterTypes()[1].isNumber) {
        mv.visitVarInsn(ALOAD, 1);
        BytecodeHelper.doCast(mv, method.getParameterTypes()[0].getTheClass());

        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, 2);
        mv.visitInsn(ICONST_0);
        mv.visitInsn(AALOAD);
        mv.visitMethodInsn(INVOKEVIRTUAL, "org/codehaus/groovy/reflection/CachedClass", "coerceArgument", "(Ljava/lang/Object;)Ljava/lang/Object;", false);

        // cast argument to parameter class, inclusive unboxing
        // for methods with primitive types
        Class type = method.getParameterTypes()[1].getTheClass();
        BytecodeHelper.doCast(mv, type);
    } else {
        mv.visitVarInsn(ALOAD, 0);
        mv.visitVarInsn(ALOAD, 2);
        mv.visitMethodInsn(INVOKEVIRTUAL, className, "coerceArgumentsToClasses", "([Ljava/lang/Object;)[Ljava/lang/Object;", false);
        mv.visitVarInsn(ASTORE, 2);
        mv.visitVarInsn(ALOAD, 1);
        BytecodeHelper.doCast(mv, method.getParameterTypes()[0].getTheClass());
        loadParameters(method, 2, mv);
    }
    mv.visitMethodInsn(INVOKESTATIC, BytecodeHelper.getClassInternalName(method.getDeclaringClass().getTheClass()), method.getName(), methodDescriptor, false);
    BytecodeHelper.box(mv, returnType);
    if (method.getReturnType() == void.class) {
        mv.visitInsn(ACONST_NULL);
    }
    mv.visitInsn(ARETURN);
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}
 
Example 7
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 8
Source File: DgmConverter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void createConstructor(ClassWriter cw) {
    MethodVisitor mv;
    mv = cw.visitMethod(ACC_PUBLIC, "<init>", "(Ljava/lang/String;Lorg/codehaus/groovy/reflection/CachedClass;Ljava/lang/Class;[Ljava/lang/Class;)V", null, null);
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitVarInsn(ALOAD, 1);
    mv.visitVarInsn(ALOAD, 2);
    mv.visitVarInsn(ALOAD, 3);
    mv.visitVarInsn(ALOAD, 4);
    mv.visitMethodInsn(INVOKESPECIAL, "org/codehaus/groovy/reflection/GeneratedMetaMethod", "<init>", "(Ljava/lang/String;Lorg/codehaus/groovy/reflection/CachedClass;Ljava/lang/Class;[Ljava/lang/Class;)V", false);
    mv.visitInsn(RETURN);
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}
 
Example 9
Source File: CommonHelpers.java    From HttpSessionReplacer with MIT License 5 votes vote down vote up
static void addIsServlet3(ClassVisitor cw) {
  FieldVisitor fv = cw.visitField(ACC_PRIVATE + ACC_FINAL + ACC_STATIC, "$$isServlet3", "Z", null, null);
  fv.visitEnd();

  MethodVisitor mv = cw.visitMethod(ACC_PRIVATE + ACC_STATIC, "$$isServlet3", "()Z", null, null);
  mv.visitCode();
  Label l0 = new Label();
  Label l1 = new Label();
  Label l2 = new Label();
  mv.visitTryCatchBlock(l0, l1, l2, "java/lang/NoSuchMethodException");
  mv.visitLabel(l0);
  mv.visitLineNumber(446, l0);
  mv.visitLdcInsn(Type.getType("Ljavax/servlet/ServletRequest;"));
  mv.visitLdcInsn("startAsync");
  mv.visitInsn(ICONST_0);
  mv.visitTypeInsn(ANEWARRAY, "java/lang/Class");
  mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Class", "getMethod",
      "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;", false);
  mv.visitInsn(POP);
  mv.visitLabel(l1);
  mv.visitLineNumber(447, l1);
  mv.visitInsn(ICONST_1);
  mv.visitInsn(IRETURN);
  mv.visitLabel(l2);
  mv.visitLineNumber(448, l2);
  mv.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[] { "java/lang/NoSuchMethodException" });
  mv.visitVarInsn(ASTORE, 0);
  Label l3 = new Label();
  mv.visitLabel(l3);
  mv.visitLineNumber(449, l3);
  mv.visitInsn(ICONST_0);
  mv.visitInsn(IRETURN);
  Label l4 = new Label();
  mv.visitLabel(l4);
  mv.visitLocalVariable("e", "Ljava/lang/NoSuchMethodException;", null, l3, l4, 0);
  mv.visitMaxs(3, 1);
  mv.visitEnd();
}
 
Example 10
Source File: InterfaceFieldClassGeneratorTest.java    From AVM with MIT License 5 votes vote down vote up
public static byte[] getInnerFILEDSInterfaceBytes() {
    ClassWriter classWriter = new ClassWriter(0);
    MethodVisitor methodVisitor;

    classWriter.visit(V10, ACC_PUBLIC | ACC_SUPER, "NestedInterfaces", 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);

    {
        methodVisitor = classWriter.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
        methodVisitor.visitCode();
        Label label0 = new Label();
        methodVisitor.visitLabel(label0);
        methodVisitor.visitLineNumber(3, label0);
        methodVisitor.visitVarInsn(ALOAD, 0);
        methodVisitor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
        methodVisitor.visitInsn(RETURN);
        methodVisitor.visitMaxs(1, 1);
        methodVisitor.visitEnd();
    }
    classWriter.visitEnd();

    return classWriter.toByteArray();
}
 
Example 11
Source File: FieldAccess.java    From reflectasm with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static private void insertConstructor (ClassWriter cw) {
	MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
	mv.visitCode();
	mv.visitVarInsn(ALOAD, 0);
	mv.visitMethodInsn(INVOKESPECIAL, "com/esotericsoftware/reflectasm/FieldAccess", "<init>", "()V");
	mv.visitInsn(RETURN);
	mv.visitMaxs(1, 1);
	mv.visitEnd();
}
 
Example 12
Source File: DupsTest.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/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();

}
 
Example 13
Source File: ClientServiceFactory.java    From thorntail with Apache License 2.0 4 votes vote down vote up
static byte[] createImpl(String implName, ClassInfo classInfo) {
    ClassWriter cw = new ClassWriter(0);
    MethodVisitor mv;
    AnnotationVisitor av0;

    cw.visit(V1_8, ACC_PUBLIC + ACC_SUPER,
             implName.replace('.', '/'),
             null,
             "java/lang/Object",
             new String[]{classInfo.name().toString().replace('.', '/')}
    );

    int lastDot = implName.lastIndexOf('.');
    String simpleName = implName.substring(lastDot + 1);

    cw.visitSource(simpleName + ".java", null);
    {
        av0 = cw.visitAnnotation("Ljavax/enterprise/context/ApplicationScoped;", true);
        av0.visitEnd();
    }
    cw.visitInnerClass("javax/ws/rs/client/Invocation$Builder", "javax/ws/rs/client/Invocation", "Builder", ACC_PUBLIC + ACC_STATIC + ACC_ABSTRACT + ACC_INTERFACE);

    {
        mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitLineNumber(14, l0);
        mv.visitVarInsn(ALOAD, 0);
        mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLineNumber(15, l1);
        mv.visitInsn(RETURN);
        Label l2 = new Label();
        mv.visitLabel(l2);
        mv.visitLocalVariable("this",
                              buildTypeDef(implName),
                              null,
                              l0,
                              l2,
                              0);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }

    List<AnnotationInstance> annotations = classInfo.annotations().get(DotName.createSimple("org.wildfly.swarm.client.jaxrs.Service"));
    String baseUrl = (String) annotations.get(0).value("baseUrl").value();
    int lineNum = 18;

    classInfo.asClass().methods()
            .stream()
            .forEachOrdered(method -> {
                createMethod(cw, implName, classInfo.name().toString(), method, lineNum, baseUrl);
            });
    cw.visitEnd();

    return cw.toByteArray();
}
 
Example 14
Source File: AsmBackedEmptyScriptGenerator.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private <T extends Script> Class<? extends T> generateEmptyScriptClass(Class<T> type) {
    ClassWriter visitor = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    String typeName = type.getName() + "_Decorated";
    Type generatedType = Type.getType("L" + typeName.replaceAll("\\.", "/") + ";");
    Type superclassType = Type.getType(type);
    visitor.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, generatedType.getInternalName(), null,
            superclassType.getInternalName(), new String[0]);

    // Constructor

    String constructorDescriptor = Type.getMethodDescriptor(Type.VOID_TYPE, new Type[0]);
    MethodVisitor methodVisitor = visitor.visitMethod(Opcodes.ACC_PUBLIC, "<init>", constructorDescriptor, null,
            new String[0]);
    methodVisitor.visitCode();

    // super()
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superclassType.getInternalName(), "<init>",
            constructorDescriptor);

    methodVisitor.visitInsn(Opcodes.RETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    // run() method

    String runDesciptor = Type.getMethodDescriptor(Type.getType(Object.class), new Type[0]);
    methodVisitor = visitor.visitMethod(Opcodes.ACC_PUBLIC, "run", runDesciptor, null, new String[0]);
    methodVisitor.visitCode();

    // return null
    methodVisitor.visitInsn(Opcodes.ACONST_NULL);

    methodVisitor.visitInsn(Opcodes.ARETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    visitor.visitEnd();

    byte[] bytecode = visitor.toByteArray();
    JavaMethod<ClassLoader, Class> method = JavaReflectionUtil.method(ClassLoader.class, Class.class, "defineClass", String.class, byte[].class, int.class, int.class);
    @SuppressWarnings("unchecked")
    Class<T> clazz = method.invoke(type.getClassLoader(), typeName, bytecode, 0, bytecode.length);
    return clazz;
}
 
Example 15
Source File: WMRouterTransform.java    From WMRouter with Apache License 2.0 4 votes vote down vote up
/**
 * 生成格式如下的代码,其中ServiceInit_xxx由注解生成器生成。
 * <pre>
 * package com.sankuai.waimai.router.generated;
 *
 * public class ServiceLoaderInit {
 *
 *     public static void init() {
 *         ServiceInit_xxx1.init();
 *         ServiceInit_xxx2.init();
 *     }
 * }
 * </pre>
 */
private void generateServiceInitClass(String directory, Set<String> classes) {

    if (classes.isEmpty()) {
        WMRouterLogger.info(GENERATE_INIT + "skipped, no service found");
        return;
    }

    try {
        WMRouterLogger.info(GENERATE_INIT + "start...");
        long ms = System.currentTimeMillis();

        ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
        ClassVisitor cv = new ClassVisitor(Opcodes.ASM5, writer) {
        };
        String className = Const.SERVICE_LOADER_INIT.replace('.', '/');
        cv.visit(50, Opcodes.ACC_PUBLIC, className, null, "java/lang/Object", null);

        MethodVisitor mv = cv.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC,
                Const.INIT_METHOD, "()V", null, null);

        mv.visitCode();

        for (String clazz : classes) {
            mv.visitMethodInsn(Opcodes.INVOKESTATIC, clazz.replace('.', '/'),
                    "init",
                    "()V",
                    false);
        }
        mv.visitMaxs(0, 0);
        mv.visitInsn(Opcodes.RETURN);
        mv.visitEnd();
        cv.visitEnd();

        File dest = new File(directory, className + SdkConstants.DOT_CLASS);
        dest.getParentFile().mkdirs();
        new FileOutputStream(dest).write(writer.toByteArray());

        WMRouterLogger.info(GENERATE_INIT + "cost %s ms", System.currentTimeMillis() - ms);

    } catch (IOException e) {
        WMRouterLogger.fatal(e);
    }
}
 
Example 16
Source File: InstanceOfCastsTest.java    From JAADAS with GNU General Public License v3.0 4 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/InstanceOfCasts",
			null, "java/lang/Object", null);
	cw.visitSource("InstanceOfCasts.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, "convertMeasurableArray", "([Ljava/lang/Object;)[Lsoot/asm/backend/targets/Measurable;", null, null);
	mv.visitCode();
	mv.visitVarInsn(ALOAD, 1);
	mv.visitTypeInsn(INSTANCEOF, "[Lsoot/asm/backend/targets/Measurable;");
	Label l0 = new Label();
	mv.visitJumpInsn(IFEQ, l0);
	mv.visitVarInsn(ALOAD, 1);
	mv.visitTypeInsn(CHECKCAST, "[Lsoot/asm/backend/targets/Measurable;");
	if (targetCompiler != TargetCompiler.eclipse)
		mv.visitTypeInsn(CHECKCAST, "[Lsoot/asm/backend/targets/Measurable;");
	mv.visitInsn(ARETURN);
	mv.visitLabel(l0);
	mv.visitInsn(ACONST_NULL);
	mv.visitInsn(ARETURN);
	mv.visitMaxs(0, 0);
	mv.visitEnd();
	}
		{
		mv = cw.visitMethod(ACC_PUBLIC, "isMeasurable", "(Ljava/lang/Object;)Z", null, null);
		mv.visitCode();
		mv.visitVarInsn(ALOAD, 1);
		mv.visitTypeInsn(INSTANCEOF, "soot/asm/backend/targets/Measurable");
		mv.visitInsn(IRETURN);
		mv.visitMaxs(0, 0);
		mv.visitEnd();
		}
		cw.visitEnd();

	
}
 
Example 17
Source File: DummyClassGenerator.java    From GriefDefender with MIT License 4 votes vote down vote up
private void generateMethods(ClassWriter cw, String internalName, List<Method> methods, Class<?> exceptionType) {
    for (Method method: methods) {
        MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, method.getName(), Type.getMethodDescriptor(method), null, null);
        mv.visitCode();

        String internalException = Type.getInternalName(exceptionType);

        mv.visitTypeInsn(NEW, internalException);
        mv.visitInsn(DUP);

        // Load first argument to String.format
        mv.visitLdcInsn("A method was invoked on a dummy class, due to the static field %s not being initialized "
                + "(most likely in a CatalogType-related class).\n"
                + "Method: " + method);

        // Create new array
        mv.visitLdcInsn(1);
        mv.visitTypeInsn(ANEWARRAY, "java/lang/String");

        // Store in local var 2
        mv.visitVarInsn(Opcodes.ASTORE, 2);

        // AASTORE part 1 - array reference
        mv.visitVarInsn(Opcodes.ALOAD, 2);

        // AASTORE part 2 - array index
        mv.visitLdcInsn(0);

        // AASTORE part 3 = the actual value
        // Load formatter argument (the field FIELD_NAME)
        mv.visitVarInsn(ALOAD, 0);
        mv.visitFieldInsn(GETFIELD, internalName, FIELD_NAME, Type.getDescriptor(String.class));

        // Store in array
        mv.visitInsn(AASTORE);

        // Load array reference
        mv.visitVarInsn(ALOAD, 2);

        // Call String.format
        mv.visitMethodInsn(INVOKESTATIC, Type.getInternalName(String.class), "format",
            "(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;", false);

        // Invoke throwable constructor
        mv.visitMethodInsn(INVOKESPECIAL, internalException, "<init>", "(Ljava/lang/String;)V", false);
        mv.visitInsn(ATHROW);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }
}
 
Example 18
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 19
Source File: ProxyGeneratorAdapter.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) {
    Object key = Arrays.asList(name, desc);
    if (visitedMethods.contains(key)) return null;
    if (Modifier.isPrivate(access) || Modifier.isNative(access) || ((access & ACC_SYNTHETIC) != 0)) {
        // do not generate bytecode for private methods
        return null;
    }
    int accessFlags = access;
    visitedMethods.add(key);
    if ((objectDelegateMethods.contains(name + desc) || delegatedClosures.containsKey(name) || (!"<init>".equals(name) && hasWildcard)) && !Modifier.isStatic(access) && !Modifier.isFinal(access)) {
        if (!GROOVYOBJECT_METHOD_NAMESS.contains(name)) {
            if (Modifier.isAbstract(access)) {
                // prevents the proxy from being abstract
                accessFlags -= ACC_ABSTRACT;
            }
            if (delegatedClosures.containsKey(name) || (!"<init>".equals(name) && hasWildcard)) {
                delegatedClosures.put(name, Boolean.TRUE);
                return makeDelegateToClosureCall(name, desc, signature, exceptions, accessFlags);
            }
            if (generateDelegateField && objectDelegateMethods.contains(name + desc)) {
                return makeDelegateCall(name, desc, signature, exceptions, accessFlags);
            }
            delegatedClosures.put(name, Boolean.TRUE);
            return makeDelegateToClosureCall(name, desc, signature, exceptions, accessFlags);
        }
    } else if ("getProxyTarget".equals(name) && "()Ljava/lang/Object;".equals(desc)) {
        return createGetProxyTargetMethod(access, name, desc, signature, exceptions);
    } else if ("<init>".equals(name) && (Modifier.isPublic(access) || Modifier.isProtected(access))) {
        return createConstructor(access, name, desc, signature, exceptions);
    } else if (Modifier.isAbstract(access) && !GROOVYOBJECT_METHOD_NAMESS.contains(name)) {
        if (isImplemented(superClass, name, desc)) {
            return null;
        }
        accessFlags -= ACC_ABSTRACT;
        MethodVisitor mv = super.visitMethod(accessFlags, name, desc, signature, exceptions);
        mv.visitCode();
        Type[] args = Type.getArgumentTypes(desc);
        if (emptyBody) {
            Type returnType = Type.getReturnType(desc);
            if (returnType == Type.VOID_TYPE) {
                mv.visitInsn(RETURN);
            } else {
                int loadIns = getLoadInsn(returnType);
                switch (loadIns) {
                    case ILOAD:
                        mv.visitInsn(ICONST_0);
                        break;
                    case LLOAD:
                        mv.visitInsn(LCONST_0);
                        break;
                    case FLOAD:
                        mv.visitInsn(FCONST_0);
                        break;
                    case DLOAD:
                        mv.visitInsn(DCONST_0);
                        break;
                    default:
                        mv.visitInsn(ACONST_NULL);
                }
                mv.visitInsn(getReturnInsn(returnType));
                mv.visitMaxs(2, registerLen(args) + 1);
            }
        } else {
            // for compatibility with the legacy proxy generator, we should throw an UnsupportedOperationException
            // instead of an AbtractMethodException
            mv.visitTypeInsn(NEW, "java/lang/UnsupportedOperationException");
            mv.visitInsn(DUP);
            mv.visitMethodInsn(INVOKESPECIAL, "java/lang/UnsupportedOperationException", "<init>", "()V", false);
            mv.visitInsn(ATHROW);
            mv.visitMaxs(2, registerLen(args) + 1);
        }
        mv.visitEnd();
    }
    return null;
}
 
Example 20
Source File: FieldAccess.java    From reflectasm with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
static private void insertGetObject (ClassWriter cw, String classNameInternal, ArrayList<Field> fields) {
	int maxStack = 6;
	MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "get", "(Ljava/lang/Object;I)Ljava/lang/Object;", null, null);
	mv.visitCode();
	mv.visitVarInsn(ILOAD, 2);

	if (!fields.isEmpty()) {
		maxStack--;
		Label[] labels = new Label[fields.size()];
		for (int i = 0, n = labels.length; i < n; i++)
			labels[i] = new Label();
		Label defaultLabel = new Label();
		mv.visitTableSwitchInsn(0, labels.length - 1, defaultLabel, labels);

		for (int i = 0, n = labels.length; i < n; i++) {
			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(),
				Type.getDescriptor(field.getType()));

			Type fieldType = Type.getType(field.getType());
			switch (fieldType.getSort()) {
			case Type.BOOLEAN:
				mv.visitMethodInsn(INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;");
				break;
			case Type.BYTE:
				mv.visitMethodInsn(INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;");
				break;
			case Type.CHAR:
				mv.visitMethodInsn(INVOKESTATIC, "java/lang/Character", "valueOf", "(C)Ljava/lang/Character;");
				break;
			case Type.SHORT:
				mv.visitMethodInsn(INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;");
				break;
			case Type.INT:
				mv.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;");
				break;
			case Type.FLOAT:
				mv.visitMethodInsn(INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;");
				break;
			case Type.LONG:
				mv.visitMethodInsn(INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;");
				break;
			case Type.DOUBLE:
				mv.visitMethodInsn(INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;");
				break;
			}

			mv.visitInsn(ARETURN);
		}

		mv.visitLabel(defaultLabel);
		mv.visitFrame(F_SAME, 0, null, 0, null);
	}
	insertThrowExceptionForFieldNotFound(mv);
	mv.visitMaxs(maxStack, 3);
	mv.visitEnd();
}