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

The following examples show how to use org.objectweb.asm.ClassWriter#visitEnd() . 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: SimpleVersionControl.java    From TabooLib with MIT License 6 votes vote down vote up
public Class<?> translate(Plugin plugin) throws IOException {
    // 防止出现 Class not found 的奇葩问题,使用缓存(目的是兼容热重载)
    InputStream inputStream = useCache ? new ByteArrayInputStream(cacheClasses.computeIfAbsent(target, n -> {
        try {
            return IO.readFully(Files.getResource(plugin, target.replace(".", "/") + ".class"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new byte[0];
    })) : Files.getResource(plugin, target.replace(".", "/") + ".class");
    // 读取
    ClassReader classReader = new ClassReader(inputStream);
    ClassWriter classWriter = new ClassWriter(0);
    ClassVisitor classVisitor = new SimpleClassVisitor(this, classWriter);
    classReader.accept(classVisitor, ClassReader.EXPAND_FRAMES);
    classWriter.visitEnd();
    classVisitor.visitEnd();
    // 打印
    if (mapping || plugin instanceof InternalPlugin) {
        executorService.submit(this::printMapping);
    }
    // 因第三方插件调用该方法时会出现找不到类,所以第三方插件使用 BridgeLoader 加载类
    return plugin instanceof InternalPlugin ? AsmClassLoader.createNewClass(target, classWriter.toByteArray()) : BridgeLoader.createNewClass(target, classWriter.toByteArray());
}
 
Example 2
Source File: FaviconExceptionMapperFactory.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 6 votes vote down vote up
static byte[] create() throws IOException {
    ClassReader reader = new ClassReader(FaviconExceptionMapper.class.getClassLoader().getResourceAsStream(FaviconExceptionMapper.class.getName().replace('.', '/') + ".class"));

    ClassWriter writer = new ClassWriter(0);
    Remapper remapper = new Remapper() {
        @Override
        public String map(String typeName) {
            if (typeName.equals("org/wildfly/swarm/jaxrs/internal/FaviconExceptionMapper")) {
                return "org/wildfly/swarm/generated/FaviconExceptionMapper";
            }
            return super.map(typeName);
        }
    };

    RemappingClassAdapter adapter = new RemappingClassAdapter(writer, remapper);
    reader.accept(adapter, 0);

    writer.visitAnnotation("Ljavax/ws/rs/ext/Provider;", true).visitEnd();
    writer.visitEnd();

    return writer.toByteArray();
}
 
Example 3
Source File: StubGenerator.java    From AVM with MIT License 6 votes vote down vote up
/**
 * Generates and returns the bytecode for an exception class.
 * 
 * @param name The name of the class to generate.
 * @param superName The name of the superclass.
 * @return The bytecode for the new class.
 */
public static byte[] generateExceptionClass(String name, String superName) {
    ClassWriter out = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
    
    // This class only exists to be a type - the superclasses always do everything.
    // (common access for all classes we generate - public and "super", meaning post-1.1 invokestatic).
    int access = Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER;
    // We ignore generics, so null signature.
    String signature = null;
    // We implement no interfaces.
    String[] interfaces = new String[0];
    out.visit(CLASS_VERSION, access, name, signature, superName, interfaces);
    
    // Generate the constructors.
    populateExceptionConstructors(out, superName);
    
    // Finish this and dump the bytes.
    out.visitEnd();
    return out.toByteArray();
}
 
Example 4
Source File: DummyClassGenerator.java    From GriefDefender with MIT License 6 votes vote down vote up
/**
 * Creates a new class prepared to be loaded into the {@link ClassLoader}.
 *
 * @param type The type of class to implement
 * @param name The name of the class
 * @param exceptionType The exception type to throw for all methods
 * @return The generated class
 */
public byte[] createClass(final Class<?> type, final String name, final Class<?> exceptionType) {

    checkNotNull(type, "type");
    checkNotNull(name, "name");
    checkNotNull(exceptionType, "exception");

    checkState(type.isInterface(), String.format("Class %s is not an interface!", type));
    checkState(Throwable.class.isAssignableFrom(exceptionType), String.format("Class %s does not extend Throwable!", exceptionType));

    String internalName = name.replace('.', '/');
    List<Method> methods = this.getInterfaceMethods(type);

    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
    cw.visit(V1_8, ACC_PUBLIC + ACC_SUPER, internalName, null, Type.getInternalName(Object.class), new String[] {Type.getInternalName(type)});

    this.generateConstructor(cw, internalName);
    this.generateMethods(cw, internalName, methods, exceptionType);

    cw.visitEnd();

    return cw.toByteArray();
}
 
Example 5
Source File: SunClassLoader.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void loadMagic() {
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    cw.visit(Opcodes.V1_4, Opcodes.ACC_PUBLIC, "sun/reflect/GroovyMagic", null, "sun/reflect/MagicAccessorImpl", null);
    MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESPECIAL, "sun/reflect/MagicAccessorImpl", "<init>", "()V", false);
    mv.visitInsn(RETURN);
    mv.visitMaxs(0, 0);
    mv.visitEnd();
    cw.visitEnd();

    define(cw.toByteArray(), "sun.reflect.GroovyMagic");
}
 
Example 6
Source File: ClassGenerator.java    From android-perftracking with MIT License 5 votes vote down vote up
/**
 * Creates AppPerformanceConfig.class file with a static boolean field AppPerformanceConfig#enabled in it.
 *
 * @param value Initializes the AppPerformanceConfig#enabled with value.
 * @return byte array of the class.
 */
public static byte[] generateConfigClass(boolean value) {

  ClassWriter cw = new ClassWriter(0);
  cw.visit(V1_6, ACC_FINAL + ACC_SUPER,
      "com/rakuten/tech/mobile/perf/runtime/internal/AppPerformanceConfig", null,
      "java/lang/Object", null);
  cw.visitField(ACC_PUBLIC + ACC_STATIC, "enabled", "Z", null, value);
  cw.visitEnd();
  return cw.toByteArray();
}
 
Example 7
Source File: MetaspaceExhaustionTest.java    From allocation-instrumenter with Apache License 2.0 5 votes vote down vote up
@Test
public void testExhaustion() {
  // 2^16 is a lot of classes.  This should exhaust the metaspace
  // (set on the command line to 32MB, if there is a class leak.
  final int classCount = 65536;

  ClassWriter cw = new ClassWriter(0);
  cw.visit(
      Opcodes.V1_6,
      Opcodes.ACC_PUBLIC,
      "com/google/monitoring/runtime/agentdetection/AgentPresent",
      null,
      "java/lang/Object",
      null);
  cw.visitEnd();
  byte[] classBytes = cw.toByteArray();

  // Uncommenting the lines related to the Class<?> array will cause
  // metaspace exhaustion.  This can be used for testing.
  // Class<?>[] cs = new Class<?>[classCount];
  for (int i = 0; i < classCount; i++) {
    // Load the perfectly legitimate class in its own class loader
    // (so as to prevent the class loader from complaining about
    // name clashes).
    LocalLoader l = new LocalLoader();
    // cs[i] =
    l.findClass("com.google.monitoring.runtime.agentdetection.AgentPresent", classBytes);
  }
}
 
Example 8
Source File: GenZipWithEntries.java    From bazel with Apache License 2.0 5 votes vote down vote up
public static byte[] dump(String name) {
  ClassWriter cw = new ClassWriter(0);
  cw.visit(52, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, name, null, "java/lang/Object", null);
  {
    MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
    mv.visitCode();
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
    mv.visitInsn(Opcodes.RETURN);
    mv.visitMaxs(1, 1);
    mv.visitEnd();
  }
  cw.visitEnd();
  return cw.toByteArray();
}
 
Example 9
Source File: ByteCodeGenTest.java    From paraflow with Apache License 2.0 5 votes vote down vote up
@Test
public void genClass()
{
    ClassWriter classWriter = new ClassWriter(0);
    classWriter.visit(V1_6, ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE,
            "cn/edu/ruc/iir/paraflow/loader/consumer/utils/Comparable",
            null,
            "java/lang/Object",
            null);
    classWriter.visitField(ACC_PUBLIC + ACC_FINAL + ACC_STATIC,
            "LESS", "I", null, -1)
            .visitEnd();
    classWriter.visitField(ACC_PUBLIC + ACC_FINAL + ACC_STATIC,
            "EQUAL", "I", null, 0)
            .visitEnd();
    classWriter.visitField(ACC_PUBLIC + ACC_FINAL + ACC_STATIC,
            "GREATER", "I", null, 1)
            .visitEnd();
    classWriter.visitMethod(ACC_PUBLIC + ACC_ABSTRACT,
            "compareTo", "(Ljava/lang/Object;)I", null, null)
            .visitEnd();
    classWriter.visitEnd();
    byte[] bytes = classWriter.toByteArray();

    MyClassLoader myClassLoader = new MyClassLoader();
    Class clazz = myClassLoader.defineClass("cn.edu.ruc.iir.paraflow.loader.consumer.utils.Comparable", bytes);
    try {
        System.out.println(clazz.getField("LESS").getName());
    }
    catch (NoSuchFieldException e) {
        e.printStackTrace();
    }
}
 
Example 10
Source File: AdviceGenerator.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private LazyDefinedClass generate() {
    LazyDefinedClass methodMetaClass = null;
    if (methodMetaInternalName != null) {
        methodMetaClass = generateMethodMetaClass(config);
    }
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES);
    String[] interfaces = null;
    if (!config.enabledProperty().isEmpty() || !config.traceEntryEnabledProperty().isEmpty()) {
        interfaces = new String[] {"org/glowroot/agent/plugin/api/config/ConfigListener"};
    }
    cw.visit(V1_5, ACC_PUBLIC + ACC_SUPER, adviceInternalName, null, "java/lang/Object",
            interfaces);
    addClassAnnotation(cw);
    addStaticFields(cw);
    addStaticInitializer(cw);
    boolean checkNotInTransaction = config.isTransaction()
            && config.alreadyInTransactionBehavior() == AlreadyInTransactionBehavior.DO_NOTHING;
    boolean checkPropertyNotEnabled = pluginId != null && !config.enabledProperty().isEmpty();
    addIsEnabledMethodIfNeeded(cw, checkNotInTransaction, checkPropertyNotEnabled);
    if (config.isTraceEntryOrGreater()) {
        // methodMetaInternalName is non-null when entry or greater
        checkNotNull(methodMetaInternalName);
        addOnBeforeMethod(cw);
        addOnThrowMethod(cw);
        addOnReturnMethod(cw);
    } else if (config.captureKind() == CaptureKind.TIMER) {
        addOnBeforeMethodTimerOnly(cw);
        addOnAfterMethodTimerOnly(cw);
    } else {
        addOnBeforeMethodOther(cw);
    }
    cw.visitEnd();
    ImmutableLazyDefinedClass.Builder builder = ImmutableLazyDefinedClass.builder()
            .type(Type.getObjectType(adviceInternalName))
            .bytes(cw.toByteArray());
    if (methodMetaClass != null) {
        builder.addDependencies(methodMetaClass);
    }
    return builder.build();
}
 
Example 11
Source File: DynamicClassFactory.java    From caravan with Apache License 2.0 5 votes vote down vote up
private Class<?> createClass(ClassPair classPair) {
  String className = generateClassName(classPair);
  String classStr = className.replaceAll("\\.", "/");

  String keyClassType = Type.getDescriptor(classPair.keyClass);
  String valueClassType = Type.getDescriptor(classPair.valueClass);

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

  AnnotationVisitor anno = cw.visitAnnotation(Type.getDescriptor(JsonPropertyOrder.class), true);
  AnnotationVisitor aa = anno.visitArray("value");
  aa.visit("", "key");
  aa.visit("", "value");
  aa.visitEnd();
  anno.visitEnd();

  FieldVisitor keyField = cw.visitField(ACC_PRIVATE, "key", keyClassType, null, null);
  keyField.visitEnd();

  FieldVisitor valueField = cw.visitField(ACC_PRIVATE, "value", valueClassType, null, null);
  valueField.visitEnd();

  MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
  mv.visitMaxs(2, 1);
  mv.visitVarInsn(ALOAD, 0);
  mv.visitMethodInsn(INVOKESPECIAL, Type.getInternalName(Object.class), "<init>", "()V", false); // call the constructor of super class
  mv.visitInsn(RETURN);
  mv.visitEnd();

  addGetterSetter(classPair, className, classStr, keyClassType, valueClassType, cw);
  addKVPairMethods(classPair, className, classStr, keyClassType, valueClassType, cw);

  cw.visitEnd();

  return defineClass(className, cw.toByteArray());
}
 
Example 12
Source File: ClassWithCredentialsDumper.java    From openpojo with Apache License 2.0 4 votes vote down vote up
static byte[] dump() {

    ClassWriter cw = new ClassWriter(0);
    FieldVisitor fv;
    MethodVisitor mv;
    AnnotationVisitor av0;

    cw.visit(52, ACC_FINAL + ACC_SUPER, CLASS_PACKAGE, null, "java/lang/Object", null);

    {
      fv = cw.visitField(ACC_PRIVATE, "credentials", "L" + SUN_SECURITY_KRB_5_CREDENTIALS + ";", null, null);
      fv.visitEnd();
    }
    {
      mv = cw.visitMethod(0, "<init>", "()V", null, null);
      mv.visitCode();
      mv.visitVarInsn(ALOAD, 0);
      mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
      mv.visitInsn(RETURN);
      mv.visitMaxs(1, 1);
      mv.visitEnd();
    }
    {
      mv = cw.visitMethod(ACC_PUBLIC, "getCredentials", "()L" + SUN_SECURITY_KRB_5_CREDENTIALS + ";", null, null);
      mv.visitCode();
      mv.visitVarInsn(ALOAD, 0);
      mv.visitFieldInsn(GETFIELD, CLASS_PACKAGE, "credentials", "L" + SUN_SECURITY_KRB_5_CREDENTIALS + ";");
      mv.visitInsn(ARETURN);
      mv.visitMaxs(1, 1);
      mv.visitEnd();
    }
    {
      mv = cw.visitMethod(ACC_PUBLIC, "setCredentials", "(L" + SUN_SECURITY_KRB_5_CREDENTIALS + ";)V", null, null);
      mv.visitCode();
      mv.visitVarInsn(ALOAD, 0);
      mv.visitVarInsn(ALOAD, 1);
      mv.visitFieldInsn(PUTFIELD, CLASS_PACKAGE, "credentials", "L" + SUN_SECURITY_KRB_5_CREDENTIALS + ";");
      mv.visitInsn(RETURN);
      mv.visitMaxs(2, 2);
      mv.visitEnd();
    }
    cw.visitEnd();

    return cw.toByteArray();
  }
 
Example 13
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 14
Source File: ASMGen.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static byte[] dump() throws Exception {

		ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
		FieldVisitor fv;
		MethodVisitor mv;
		AnnotationVisitor av0;

		cw.visit(V1_6, ACC_PUBLIC + ACC_SUPER,
				"com/beetl/performance/lab/asm/UserAsmAccessor1", null,
				"java/lang/Object",
				new String[] { "com/beetl/performance/lab/asm/Access" });

		{
			mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
			mv.visitCode();
			mv.visitVarInsn(ALOAD, 0);
			mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>",
					"()V");
			mv.visitInsn(RETURN);
			mv.visitMaxs(1, 1);
			mv.visitEnd();
		}
		{
			mv = cw.visitMethod(
					ACC_PUBLIC,
					"get",
					"(Ljava/lang/Object;I)Ljava/lang/Object;",
					null,
					new String[] { "com/beetl/performance/lab/asm/ASMCastException" });
			mv.visitCode();
			Label l0 = new Label();
			Label l1 = new Label();
			Label l2 = new Label();
			mv.visitTryCatchBlock(l0, l1, l2, "java/lang/Exception");
			mv.visitInsn(ACONST_NULL);
			mv.visitVarInsn(ASTORE, 3);
			mv.visitLabel(l0);
			mv.visitVarInsn(ALOAD, 1);
			mv.visitTypeInsn(CHECKCAST, "com/beetl/performance/lab/User");
			mv.visitVarInsn(ASTORE, 3);
			mv.visitLabel(l1);
			Label l3 = new Label();
			mv.visitJumpInsn(GOTO, l3);
			mv.visitLabel(l2);
			mv.visitFrame(Opcodes.F_FULL, 4, new Object[] {
					"com/beetl/performance/lab/asm/UserAsmAccessor",
					"java/lang/Object", Opcodes.INTEGER,
					"com/beetl/performance/lab/User" }, 1,
					new Object[] { "java/lang/Exception" });
			mv.visitVarInsn(ASTORE, 4);
			mv.visitTypeInsn(NEW,
					"com/beetl/performance/lab/asm/ASMCastException");
			mv.visitInsn(DUP);
			mv.visitMethodInsn(INVOKESPECIAL,
					"com/beetl/performance/lab/asm/ASMCastException", "<init>",
					"()V");
			mv.visitInsn(ATHROW);
			mv.visitLabel(l3);
			mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
			mv.visitVarInsn(ILOAD, 2);
			Label l4 = new Label();
			Label l5 = new Label();
			Label l6 = new Label();
			mv.visitTableSwitchInsn(1, 2, l6, new Label[] { l4, l5 });
			mv.visitLabel(l4);
			mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
			mv.visitVarInsn(ALOAD, 3);
			mv.visitMethodInsn(INVOKEVIRTUAL, "com/beetl/performance/lab/User",
					"getName", "()Ljava/lang/String;");
			mv.visitInsn(ARETURN);
			mv.visitLabel(l5);
			mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
			mv.visitVarInsn(ALOAD, 3);
			mv.visitMethodInsn(INVOKEVIRTUAL, "com/beetl/performance/lab/User",
					"getId", "()I");
			mv.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf",
					"(I)Ljava/lang/Integer;");
			mv.visitInsn(ARETURN);
			mv.visitLabel(l6);
			mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
			mv.visitTypeInsn(NEW, "java/lang/RuntimeException");
			mv.visitInsn(DUP);
			mv.visitMethodInsn(INVOKESPECIAL, "java/lang/RuntimeException",
					"<init>", "()V");
			mv.visitInsn(ATHROW);
			mv.visitMaxs(2, 5);
			mv.visitEnd();
		}
		cw.visitEnd();

		return cw.toByteArray();
	}
 
Example 15
Source File: ASMGen.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static byte[] dump() throws Exception {

		ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
		FieldVisitor fv;
		MethodVisitor mv;
		AnnotationVisitor av0;

		cw.visit(V1_6, ACC_PUBLIC + ACC_SUPER,
				"com/beetl/performance/lab/asm/UserAsmAccessor1", null,
				"java/lang/Object",
				new String[] { "com/beetl/performance/lab/asm/Access" });

		{
			mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
			mv.visitCode();
			mv.visitVarInsn(ALOAD, 0);
			mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>",
					"()V");
			mv.visitInsn(RETURN);
			mv.visitMaxs(1, 1);
			mv.visitEnd();
		}
		{
			mv = cw.visitMethod(
					ACC_PUBLIC,
					"get",
					"(Ljava/lang/Object;I)Ljava/lang/Object;",
					null,
					new String[] { "com/beetl/performance/lab/asm/ASMCastException" });
			mv.visitCode();
			Label l0 = new Label();
			Label l1 = new Label();
			Label l2 = new Label();
			mv.visitTryCatchBlock(l0, l1, l2, "java/lang/Exception");
			mv.visitInsn(ACONST_NULL);
			mv.visitVarInsn(ASTORE, 3);
			mv.visitLabel(l0);
			mv.visitVarInsn(ALOAD, 1);
			mv.visitTypeInsn(CHECKCAST, "com/beetl/performance/lab/User");
			mv.visitVarInsn(ASTORE, 3);
			mv.visitLabel(l1);
			Label l3 = new Label();
			mv.visitJumpInsn(GOTO, l3);
			mv.visitLabel(l2);
			mv.visitFrame(Opcodes.F_FULL, 4, new Object[] {
					"com/beetl/performance/lab/asm/UserAsmAccessor",
					"java/lang/Object", Opcodes.INTEGER,
					"com/beetl/performance/lab/User" }, 1,
					new Object[] { "java/lang/Exception" });
			mv.visitVarInsn(ASTORE, 4);
			mv.visitTypeInsn(NEW,
					"com/beetl/performance/lab/asm/ASMCastException");
			mv.visitInsn(DUP);
			mv.visitMethodInsn(INVOKESPECIAL,
					"com/beetl/performance/lab/asm/ASMCastException", "<init>",
					"()V");
			mv.visitInsn(ATHROW);
			mv.visitLabel(l3);
			mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
			mv.visitVarInsn(ILOAD, 2);
			Label l4 = new Label();
			Label l5 = new Label();
			Label l6 = new Label();
			mv.visitTableSwitchInsn(1, 2, l6, new Label[] { l4, l5 });
			mv.visitLabel(l4);
			mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
			mv.visitVarInsn(ALOAD, 3);
			mv.visitMethodInsn(INVOKEVIRTUAL, "com/beetl/performance/lab/User",
					"getName", "()Ljava/lang/String;");
			mv.visitInsn(ARETURN);
			mv.visitLabel(l5);
			mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
			mv.visitVarInsn(ALOAD, 3);
			mv.visitMethodInsn(INVOKEVIRTUAL, "com/beetl/performance/lab/User",
					"getId", "()I");
			mv.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf",
					"(I)Ljava/lang/Integer;");
			mv.visitInsn(ARETURN);
			mv.visitLabel(l6);
			mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
			mv.visitTypeInsn(NEW, "java/lang/RuntimeException");
			mv.visitInsn(DUP);
			mv.visitMethodInsn(INVOKESPECIAL, "java/lang/RuntimeException",
					"<init>", "()V");
			mv.visitInsn(ATHROW);
			mv.visitMaxs(2, 5);
			mv.visitEnd();
		}
		cw.visitEnd();

		return cw.toByteArray();
	}
 
Example 16
Source File: ArrayWrappingClassGenerator.java    From AVM with MIT License 4 votes vote down vote up
private static byte[] generateInterfaceBytecode(String wrapperInterfaceSlashName, String[] superInterfaces) {
    ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    classWriter.visit(V10, ACC_PUBLIC | ACC_ABSTRACT | ACC_INTERFACE , wrapperInterfaceSlashName, null, "java/lang/Object", superInterfaces);
    classWriter.visitEnd();
    return classWriter.toByteArray();
}
 
Example 17
Source File: ComplexIndyGenerator.java    From bumblebench with Apache License 2.0 4 votes vote down vote up
public static byte[] makeExample() throws Throwable {
	      ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
	      cw.visit(V1_7, ACC_PUBLIC | ACC_SUPER, "ComplexIndy", null, "java/lang/Object", null);
	      		      
	      MethodVisitor mv;
	      {
	         mv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "gwtTest", "(Ljava/lang/Object;)Ljava/lang/String;", null, null);
	         mv.visitCode();
		 mv.visitVarInsn(ALOAD, 0);
	         mv.visitInvokeDynamicInsn("gwtBootstrap", "(Ljava/lang/Object;)Ljava/lang/String;",
	               new Handle(
	            		   H_INVOKESTATIC, 
	            		   "BootstrapMethods", 
	            		   "fibBootstrap",
	            		   Type.getType(
	            				 "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;"
	            		   ).getDescriptor())
	         );
	         mv.visitInsn(ARETURN);
	         mv.visitMaxs(0, 0);
	         mv.visitEnd();
	      }

	{
		mv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "fibIndy", "(I)I", null, null);
		mv.visitCode();
		mv.visitVarInsn(ILOAD, 0);
		mv.visitInvokeDynamicInsn("fibBootstrap", "(I)I",
			new Handle(
				H_INVOKESTATIC, 
				"BootstrapMethods", 
				"fibBootstrap",
				Type.getType(
					"(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;"
				).getDescriptor())
			);
		mv.visitInsn(IRETURN);
		mv.visitMaxs(0, 0);
		mv.visitEnd();
	}
cw.visitEnd();
return cw.toByteArray();
}
 
Example 18
Source File: LoggerGenerator.java    From beautiful_logger with 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 19
Source File: AsmBackedEmptyScriptGenerator.java    From Pushjet-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 20
Source File: MethodHandleFieldAssembler.java    From spring-boot-netty with MIT License 4 votes vote down vote up
public static void assembleMethodHandleField(final ClassWriter cw, final Method targetMethod, final String invokerName) {
    final String desc = Type.getDescriptor(MethodHandle.class);
    cw.visitField(ACC_PRIVATE | ACC_FINAL + ACC_STATIC, "HANDLE", desc, null, null);
    cw.visitEnd();

    final MethodVisitor ctor = cw.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
    final Label cs = createLabel();
    final Label ce = createLabel();

    ctor.visitCode();
    ctor.visitLabel(cs);

    final String clName = targetMethod.getDeclaringClass().getCanonicalName();
    final String targetMethodName = targetMethod.getName();
    ctor.visitLdcInsn(clName);
    ctor.visitLdcInsn(targetMethodName);

    final Parameter[] parameters = targetMethod.getParameters();
    ctor.visitLdcInsn(parameters.length);

    final Type classType = Type.getType(Class.class);
    final String descriptor = classType.getInternalName();
    ctor.visitTypeInsn(ANEWARRAY, descriptor);

    for (int i = 0; i < parameters.length; i++) {
        ctor.visitInsn(DUP);
        ctor.visitLdcInsn(i);

        final Class<?> paramClass = parameters[i].getType();
        if (paramClass.isPrimitive()) {
            final Class<?> wrapper = Primitives.wrap(paramClass);
            final String holderName = Type.getType(wrapper).getInternalName();

            ctor.visitFieldInsn(GETSTATIC, holderName, "TYPE", CL_DESCRIPTOR);
        } else {
            final Type parameterType = Type.getType(paramClass);
            ctor.visitLdcInsn(parameterType);
        }

        ctor.visitInsn(AASTORE);
    }

    ctor.visitMethodInsn(INVOKESTATIC, MHC_INTERNAL_NAME, "createUniversal",
            '(' + STR_DESCRIPTOR + STR_DESCRIPTOR + CLA_DESCRIPTOR + ')' + MH_DESCRIPTOR, false);
    ctor.visitFieldInsn(PUTSTATIC, invokerName, "HANDLE", MH_DESCRIPTOR);
    ctor.visitInsn(RETURN);

    ctor.visitLabel(ce);
    ctor.visitEnd();

    ctor.visitMaxs(0, 0);
}