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

The following examples show how to use org.objectweb.asm.MethodVisitor#visitMethodInsn() . These examples are extracted from open source projects. 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 Project: GriefDefender   File: GeneratorUtils.java    License: MIT License 6 votes vote down vote up
/**
 * Insert the necessary methods to box a primitive type (if the given type
 * is a primitive object).
 *
 * @param mv The method visitor
 * @param type The type to unbox
 */
public static void visitBoxingMethod(MethodVisitor mv, Type type) {
    if (type.getSort() == Type.BOOLEAN) {
        mv.visitMethodInsn(INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;", false);
    } else if (type.getSort() == Type.INT) {
        mv.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;", false);
    } else if (type.getSort() == Type.BYTE) {
        mv.visitMethodInsn(INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;", false);
    } else if (type.getSort() == Type.SHORT) {
        mv.visitMethodInsn(INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;", false);
    } else if (type.getSort() == Type.LONG) {
        mv.visitMethodInsn(INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;", false);
    } else if (type.getSort() == Type.FLOAT) {
        mv.visitMethodInsn(INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;", false);
    } else if (type.getSort() == Type.DOUBLE) {
        mv.visitMethodInsn(INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;", false);
    } else if (type.getSort() == Type.CHAR) {
        mv.visitMethodInsn(INVOKESTATIC, "java/lang/Character", "valueOf", "(C)Ljava/lang/Character;", false);
    }
}
 
Example 2
Source Project: slab   File: BytecodeGenerator.java    License: MIT License 6 votes vote down vote up
private void declareConstructor(CheckClassAdapter writer) {
  	MethodVisitor method = writer.visitMethod(ACC_PUBLIC, "<init>", GENERATED_CONSTRUCTOR, null, null);
  	method.visitCode();
method.visitVarInsn(ALOAD, 0);
method.visitVarInsn(ILOAD, 1);
method.visitLdcInsn(inspector.getSizeInBytes());
method.visitVarInsn(ALOAD, 2);
method.visitVarInsn(ALOAD, 3);
method.visitMethodInsn(INVOKESPECIAL,
		classExtended,
		"<init>",
		constructorExtended);
method.visitInsn(RETURN);
method.visitMaxs(5, 5);
method.visitEnd();
  }
 
Example 3
Source Project: glowroot   File: AdviceGenerator.java    License: 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 4
Source Project: Despector   File: StringTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testSimpleStringTemplate() {
    TestMethodBuilder builder = new TestMethodBuilder("main", "()V");
    MethodVisitor mv = builder.getGenerator();
    Label start = new Label();
    mv.visitLabel(start);
    Label end = new Label();
    mv.visitInsn(ICONST_5);
    mv.visitVarInsn(ISTORE, 1);
    mv.visitTypeInsn(NEW, "java/lang/StringBuilder");
    mv.visitInsn(DUP);
    mv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "()V", false);
    mv.visitLdcInsn("a is ");
    mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false);
    mv.visitVarInsn(ILOAD, 1);
    mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(I)Ljava/lang/StringBuilder;", false);
    mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false);
    mv.visitVarInsn(ASTORE, 2);
    mv.visitLabel(end);
    mv.visitInsn(RETURN);
    mv.visitLocalVariable("a", "I", null, start, end, 1);
    mv.visitLocalVariable("s", "Ljava/lang/String;", null, start, end, 2);

    String insn = KotlinTestHelper.getMethodAsString(builder.finish(), "main");
    String good = "fun main() {\n"
            + "    val a: Int = 5\n"
            + "    val s: String = \"a is $a\"\n"
            + "}";
    Assert.assertEquals(good, insn);
}
 
Example 5
Source Project: Despector   File: DoWhileTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testDoWhileBreak() {
    TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(IZ)V");
    MethodVisitor mv = builder.getGenerator();
    Label start = new Label();
    mv.visitLabel(start);
    Label end = new Label();
    Label l1 = new Label();
    Label l2 = new Label();
    mv.visitLabel(l1);
    mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false);
    mv.visitVarInsn(ILOAD, 1);
    mv.visitJumpInsn(IFEQ, l2);
    mv.visitJumpInsn(GOTO, end);
    mv.visitLabel(l2);
    mv.visitVarInsn(ILOAD, 0);
    mv.visitInsn(ICONST_5);
    mv.visitJumpInsn(IF_ICMPLT, l1);
    mv.visitLabel(end);
    mv.visitInsn(RETURN);
    mv.visitLocalVariable("i", "I", null, start, end, 0);
    mv.visitLocalVariable("a", "Z", null, start, end, 1);

    String insn = TestHelper.getAsString(builder.finish(), "test_mth");
    String good = "do {\n"
            + "    org.spongepowered.test.decompile.DoWhileTests.body();\n"
            + "    if (a) {\n"
            + "        break;\n"
            + "    }\n"
            + "} while (i < 5);";
    Assert.assertEquals(good, insn);
}
 
Example 6
Source Project: yql-plus   File: ExpressionHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public BytecodeExpression list(Location loc, final List<BytecodeExpression> args) {
    List<TypeWidget> types = Lists.newArrayList();
    for (BytecodeExpression e : args) {
        types.add(e.getType());
    }
    final TypeWidget unified = unify(types).boxed();
    final ListTypeWidget out = new ListTypeWidget(NotNullableTypeWidget.create(unified));
    return new BaseTypeExpression(out) {
        @Override
        public void generate(CodeEmitter code) {
            MethodVisitor mv = code.getMethodVisitor();
            code.exec(out.construct(constant(args.size())));
            for (BytecodeExpression expr : args) {
                Label skip = new Label();
                mv.visitInsn(Opcodes.DUP);
                code.exec(expr);
                final TypeWidget type = expr.getType();
                boolean nullable = code.cast(unified, type, skip);
                mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(Collection.class), "add", Type.getMethodDescriptor(Type.BOOLEAN_TYPE, Type.getType(Object.class)), true);
                if (nullable) {
                    // we're either going to POP the DUPed List OR the result of add
                    mv.visitLabel(skip);
                }
                mv.visitInsn(Opcodes.POP);
            }
        }
    };
}
 
Example 7
private void writeOperatorCall(final Expression receiver, final Expression arguments, final String operator) {
    prepareSiteAndReceiver(receiver, operator, false, controller.getCompileStack().isLHS());
    controller.getOperandStack().doGroovyCast(Number_TYPE);
    visitBoxedArgument(arguments);
    controller.getOperandStack().doGroovyCast(Number_TYPE);
    MethodVisitor mv = controller.getMethodVisitor();
    mv.visitMethodInsn(INVOKESTATIC, "org/codehaus/groovy/runtime/typehandling/NumberMath", operator, "(Ljava/lang/Number;Ljava/lang/Number;)Ljava/lang/Number;", false);
    controller.getOperandStack().replace(Number_TYPE, 2);
}
 
Example 8
Source Project: Robust   File: RobustAsmUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static void createBooleanObj(MethodVisitor mv, int argsPostion) {
    mv.visitTypeInsn(Opcodes.NEW, "java/lang/Byte");
    mv.visitInsn(Opcodes.DUP);
    mv.visitVarInsn(Opcodes.ILOAD, argsPostion);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Byte", "<init>", "(B)V");
    mv.visitInsn(Opcodes.AASTORE);
}
 
Example 9
Source Project: JQF   File: Utils.java    License: BSD 2-Clause "Simplified" License 4 votes vote down vote up
public static void addSpecialInsn(MethodVisitor mv, int val) {
  addBipushInsn(mv, val);
  mv.visitMethodInsn(INVOKESTATIC, Config.instance.analysisClass, 
    "SPECIAL", "(I)V", false);
}
 
Example 10
Source Project: beautiful_logger   File: LoggerGenerator.java    License: MIT License 4 votes vote down vote up
public static void main(String[] args) throws IOException {
  ClassWriter writer = new ClassWriter(COMPUTE_MAXS|COMPUTE_MAXS);
  
  // reserve slot 1 of the constant pool (see LoggerServiceSPI)
  writer.newClass("com/github/forax/beautifullogger/Logger");
  
  writer.visit(V1_8, ACC_SUPER,
      "com/github/forax/beautifullogger/Logger$Stub", null,
      "java/lang/Object",
      new String[] {"com/github/forax/beautifullogger/Logger"});
  
  // field
  writer.visitField(ACC_PRIVATE|ACC_FINAL, "mh", "Ljava/lang/invoke/MethodHandle;", null, null);
  
  // constructor
  MethodVisitor init = writer.visitMethod(ACC_PRIVATE, "<init>", "(Ljava/lang/invoke/MethodHandle;)V", null, null);
  init.visitCode();
  init.visitVarInsn(ALOAD, 0);
  init.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
  init.visitVarInsn(ALOAD, 0);
  init.visitVarInsn(ALOAD, 1);
  init.visitFieldInsn(PUTFIELD, "com/github/forax/beautifullogger/Logger$Stub", "mh", "Ljava/lang/invoke/MethodHandle;");
  init.visitInsn(RETURN);
  init.visitMaxs(0, 0);
  init.visitEnd();
  
  // static factory method
  MethodVisitor factory = writer.visitMethod(ACC_PUBLIC|ACC_STATIC, "create",
      "(Ljava/lang/invoke/MethodHandle;)Lcom/github/forax/beautifullogger/Logger;", null, null);
  factory.visitCode();
  factory.visitTypeInsn(NEW, "com/github/forax/beautifullogger/Logger$Stub");
  factory.visitInsn(DUP);
  factory.visitVarInsn(ALOAD, 0);
  factory.visitMethodInsn(INVOKESPECIAL, "com/github/forax/beautifullogger/Logger$Stub", "<init>",
      "(Ljava/lang/invoke/MethodHandle;)V", false);
  factory.visitInsn(ARETURN);
  factory.visitMaxs(0, 0);
  factory.visitEnd();
  
  // method
  generateOverride(writer,
      Paths.get("target/main/exploded/com.github.forax.beautifullogger/com/github/forax/beautifullogger/Logger.class"));
  generateOverride(writer,
      Paths.get("target/main/exploded/com.github.forax.beautifullogger/com/github/forax/beautifullogger/LogService.class"));
  
  writer.visitEnd();
  
  byte[] array = writer.toByteArray();
  
  //DEBUG
  //Files.write(Paths.get("Logger$Stub.class"), array);
  
  String data = new String(Base64.getEncoder().encode(array), ISO_8859_1);
  System.out.println(data);
}
 
Example 11
@Override
public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature,
    final String[] exceptions) {
    final MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);

    final String signCode = getBehaviorSignCode(name, desc);
    if (!isMatchedBehavior(signCode)) {
        return mv;
    }


    return new ThirdReWriteMethod(api, mv) {
        @Override
        public void visitInsn(final int opcode) {
            switch (opcode) {
                case RETURN:
                case IRETURN:
                case FRETURN:
                case ARETURN:
                case LRETURN:
                case DRETURN:
                    onExit();
                    break;
                default:
                    break;
            }
            super.visitInsn(opcode);
        }

        private void onExit() {
            Label startTryBlock = new Label();
            Label endTryBlock = new Label();
            Label startCatchBlock = new Label();
            Label endCatchBlock = new Label();
            mv.visitLabel(startTryBlock);
            //静态调用
            Type type = Type.getType(Math.class);
            String owner = type.getInternalName();
            mv.visitMethodInsn(INVOKESTATIC, owner, method.getName(), method.getDescriptor(), false);
            mv.visitInsn(POP2);
            mv.visitLabel(endTryBlock);
            mv.visitJumpInsn(GOTO,endCatchBlock);
            mv.visitLabel(startCatchBlock);
            mv.visitInsn(POP);
            mv.visitLabel(endCatchBlock);
            mv.visitTryCatchBlock(startTryBlock,endTryBlock,startCatchBlock,ASM_TYPE_THROWABLE.getInternalName());
        }
    };
}
 
Example 12
Source Project: groovy   File: AsmClassGenerator.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void visitVariableExpression(final VariableExpression expression) {
    final String variableName = expression.getName();

    if (expression.isThisExpression()) {
        // "this" in static context is Class instance
        if (controller.isStaticMethod() || controller.getCompileStack().isInSpecialConstructorCall()
                || (!controller.getCompileStack().isImplicitThis() && controller.isStaticContext())) {
            ClassNode thisType = controller.getClassNode();
            if (controller.isInGeneratedFunction()) {
                do { thisType = thisType.getOuterClass();
                } while (ClassHelper.isGeneratedFunction(thisType));
            }
            classX(thisType).visit(this);
        } else {
            loadThis(expression);
        }
        return;
    }

    if (expression.isSuperExpression()) {
        // "super" in static context is Class instance
        if (controller.isStaticMethod()) {
            ClassNode superType = controller.getClassNode().getSuperClass();
            classX(superType).visit(this);
        } else {
            loadThis(expression);
        }
        return;
    }

    BytecodeVariable variable = controller.getCompileStack().getVariable(variableName, false);
    if (variable != null) {
        controller.getOperandStack().loadOrStoreVariable(variable, expression.isUseReferenceDirectly());
    } else if (passingParams && controller.isInScriptBody()) {
        MethodVisitor mv = controller.getMethodVisitor();
        mv.visitTypeInsn(NEW, "org/codehaus/groovy/runtime/ScriptReference");
        mv.visitInsn(DUP);
        loadThisOrOwner();
        mv.visitLdcInsn(variableName);
        mv.visitMethodInsn(INVOKESPECIAL, "org/codehaus/groovy/runtime/ScriptReference", "<init>", "(Lgroovy/lang/Script;Ljava/lang/String;)V", false);
    } else {
        PropertyExpression pexp = thisPropX(true, variableName);
        pexp.getObjectExpression().setSourcePosition(expression);
        pexp.getProperty().setSourcePosition(expression);
        pexp.visit(this);
    }

    if (!controller.getCompileStack().isLHS()) {
        controller.getAssertionWriter().record(expression);
    }
}
 
Example 13
Source Project: HttpSessionReplacer   File: ListenerHelpers.java    License: MIT License 4 votes vote down vote up
static void staticInit(String className, MethodVisitor mv) {
  mv.visitMethodInsn(INVOKESTATIC, className,
      "$$isServlet3", "()Z", false);
  mv.visitFieldInsn(PUTSTATIC, className, "$$isServlet3",
      "Z");
}
 
Example 14
Source Project: json-smart-v2   File: ASMUtil.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Append the call of proper extract primitive type of an boxed object. this
 * methode use Number interface to unbox object
 */
protected static void autoUnBoxing2(MethodVisitor mv, Type fieldType) {
	switch (fieldType.getSort()) {
	case Type.BOOLEAN:
		mv.visitTypeInsn(CHECKCAST, "java/lang/Boolean");
		mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Boolean", "booleanValue", "()Z");
		break;
	case Type.BYTE:
		mv.visitTypeInsn(CHECKCAST, "java/lang/Number");
		mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Number", "byteValue", "()B");
		break;
	case Type.CHAR:
		mv.visitTypeInsn(CHECKCAST, "java/lang/Character");
		mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Character", "charValue", "()C");
		break;
	case Type.SHORT:
		mv.visitTypeInsn(CHECKCAST, "java/lang/Number");
		mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Number", "shortValue", "()S");
		break;
	case Type.INT:
		mv.visitTypeInsn(CHECKCAST, "java/lang/Number");
		mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Number", "intValue", "()I");
		break;
	case Type.FLOAT:
		mv.visitTypeInsn(CHECKCAST, "java/lang/Number");
		mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Number", "floatValue", "()F");
		break;
	case Type.LONG:
		mv.visitTypeInsn(CHECKCAST, "java/lang/Number");
		mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Number", "longValue", "()J");
		break;
	case Type.DOUBLE:
		mv.visitTypeInsn(CHECKCAST, "java/lang/Number");
		mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Number", "doubleValue", "()D");
		break;
	case Type.ARRAY:
		mv.visitTypeInsn(CHECKCAST, fieldType.getInternalName());
		break;
	default:
		mv.visitTypeInsn(CHECKCAST, fieldType.getInternalName());
	}
}
 
Example 15
@Override
public void visitEnd() {
    // generate the class only if interface has declared fields
    if (isInterface && fields.size() > 0) {
        /* AKI-329: Previously generated classes using InterfaceFieldMappingVisitor had the FIELDS suffix. To deserialize classes correctly and in
         the same order, this suffix is kept for re-transformation. However, this name can collide with any interface inner class called FIELDS.
         So all the inner class names starting with FIELDS are collected so that the generated class name will not collide with any preexisting user classes.
        */
        if (generatedClassName == null) {
            generatedClassName = getNextAvailableFieldsClassName();
        }

        interfaceFieldClassNames.put(className, generatedClassName);
        String genSuperName = javaLangObject;
        int genAccess = access & ~ACC_INTERFACE;

        ClassWriter cw = new ClassWriter(0);

        // class declaration
        cw.visit(V1_6, genAccess, generatedClassName, null, genSuperName, null);

        // default constructor
        {
            MethodVisitor mv = cw.visitMethod(ACC_PRIVATE, "<init>", "()V", null, null);
            mv.visitCode();
            mv.visitVarInsn(ALOAD, 0); //load the first local variable: this
            mv.visitMethodInsn(INVOKESPECIAL, javaLangObject, "<init>", "()V", false);
            mv.visitInsn(RETURN);
            mv.visitMaxs(1, 1);
            mv.visitEnd();
        }

        // fields
        for (FieldNode field : fields) {
            field.accept(cw);
        }

        // clinit
        if (clinit != null) {
            clinit.accept(cw);
        }

        consumer.accept(genSuperName, generatedClassName, cw.toByteArray());
    }
}
 
Example 16
/**
 * 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 17
@Override
protected void generate(TraceClassVisitor visitor) {
	MethodVisitor mv;
	FieldVisitor fv;

	visitor.visit(V1_1, ACC_SUPER, "soot/asm/backend/targets/InnerClass$Inner", null,
			"java/lang/Object", null);
	
	visitor.visitSource("InnerClass.java", null);

	visitor.visitInnerClass("soot/asm/backend/targets/InnerClass$Inner", "soot/asm/backend/targets/InnerClass",
			"Inner", ACC_PRIVATE);

	{
		fv = visitor.visitField(ACC_FINAL + ACC_STATIC, "a", "I", null,
				new Integer(3));
		fv.visitEnd();
	}
	{
		fv = visitor.visitField(ACC_FINAL + ACC_SYNTHETIC, "this$0",
				"Lsoot/asm/backend/targets/InnerClass;", null, null);
		fv.visitEnd();
	}
	{
		mv = visitor.visitMethod(ACC_PRIVATE, "<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$Inner", "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();
	}
	visitor.visitEnd();

}
 
Example 18
private static void tryBlockForPlatform(MethodVisitor methodVisitor, String platformType) {
  methodVisitor.visitCode();

  // Generate the enveloping try/catch block:
  //
  //   try {
  //     ...
  //   } catch (NoClassDefFoundError | IllegalAccessException | InstantiationException
  //       | InvocationTargetException | NoSuchMethodException e) {
  //     ...
  //   }
  //
  // Note that the exception types need to be listed explicitly (rather than using
  // java.lang.ReflectiveOperationException) because that parent exception type isn't available
  // on Android until API level 19.
  Label startLabel = new Label();
  Label endLabel = new Label();
  Label handlerLabel = new Label();
  methodVisitor.visitTryCatchBlock(
      startLabel, endLabel, handlerLabel, "java/lang/NoClassDefFoundError");
  methodVisitor.visitTryCatchBlock(
      startLabel, endLabel, handlerLabel, "java/lang/IllegalAccessException");
  methodVisitor.visitTryCatchBlock(
      startLabel, endLabel, handlerLabel, "java/lang/InstantiationException");
  methodVisitor.visitTryCatchBlock(
      startLabel, endLabel, handlerLabel, "java/lang/reflect/InvocationTargetException");
  methodVisitor.visitTryCatchBlock(
      startLabel, endLabel, handlerLabel, "java/lang/NoSuchMethodException");
  methodVisitor.visitLabel(startLabel);

  // Generate the actual reflective constructor call inside the try block:
  //
  //   return (Platform) PlatformClass.class.getDeclaredConstructor().newInstance();
  //
  // Note that the constructor call happens reflectively to make sure that the platform class
  // isn't loaded until actually executing this instruction. That is important because an
  // earlier class load could happen outside of the try/catch block where we are explicitly
  // handling the case of the class not being present.
  methodVisitor.visitLdcInsn(Type.getType(platformType));
  methodVisitor.visitInsn(ICONST_0);
  methodVisitor.visitTypeInsn(ANEWARRAY, "java/lang/Class");
  methodVisitor.visitMethodInsn(
      INVOKEVIRTUAL,
      "java/lang/Class",
      "getDeclaredConstructor",
      "([Ljava/lang/Class;)Ljava/lang/reflect/Constructor;",
      false);
  methodVisitor.visitInsn(ICONST_0);
  methodVisitor.visitTypeInsn(ANEWARRAY, "java/lang/Object");
  methodVisitor.visitMethodInsn(
      INVOKEVIRTUAL,
      "java/lang/reflect/Constructor",
      "newInstance",
      "([Ljava/lang/Object;)Ljava/lang/Object;",
      false);
  methodVisitor.visitTypeInsn(CHECKCAST, "com/google/common/flogger/backend/Platform");
  methodVisitor.visitLabel(endLabel);
  methodVisitor.visitInsn(ARETURN);

  // Generate the catch block of the overall try/catch. The catch block is actually just empty,
  // but Java does require the catch handler to have at least a frame in it to declare the
  // exception variable that is available within the catch block scope:
  // https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-3.html#jvms-3.12
  methodVisitor.visitLabel(handlerLabel);
  methodVisitor.visitFrame(F_SAME1, 0, null, 1, new Object[] {"java/lang/Throwable"});
  methodVisitor.visitVarInsn(ASTORE, 0);
}
 
Example 19
Source Project: AVM   File: TestEnumForJavacDump.java    License: 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, "$VALUES", "[L" + PACKAGE_NAME_INTERNAL + "/TestEnumForValues;", null, null);
        fieldVisitor.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", "$VALUES", "[L" + PACKAGE_NAME_INTERNAL + "/TestEnumForValues;");
        methodVisitor.visitMethodInsn(INVOKEVIRTUAL, "[L" + PACKAGE_NAME_INTERNAL + "/TestEnumForValues;", "clone", "()Ljava/lang/Object;", false);
        methodVisitor.visitTypeInsn(CHECKCAST, "[L" + PACKAGE_NAME_INTERNAL + "/TestEnumForValues;");
        methodVisitor.visitInsn(ARETURN);
        methodVisitor.visitMaxs(1, 0);
        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();
    }
    {
        methodVisitor = classWriter.visitMethod(ACC_PRIVATE, "<init>", "(Ljava/lang/String;I)V", "()V", 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_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", "$VALUES", "[L" + PACKAGE_NAME_INTERNAL + "/TestEnumForValues;");
        methodVisitor.visitInsn(RETURN);
        methodVisitor.visitMaxs(4, 0);
        methodVisitor.visitEnd();
    }
    classWriter.visitEnd();

    return classWriter.toByteArray();
}
 
Example 20
Source Project: quarkus   File: AsmUtil.java    License: Apache License 2.0 4 votes vote down vote up
private static void unbox(MethodVisitor mv, String owner, String methodName, String returnTypeSignature) {
    mv.visitTypeInsn(Opcodes.CHECKCAST, owner);
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, owner, methodName, "()" + returnTypeSignature, false);
}