jdk.internal.org.objectweb.asm.ClassWriter Java Examples

The following examples show how to use jdk.internal.org.objectweb.asm.ClassWriter. 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: TestInstrumentation.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public byte[] transform(
        ClassLoader classLoader, String className, Class<?> classBeingRedefined,
        ProtectionDomain pd, byte[] bytes) throws IllegalClassFormatException {
    // Check if this class should be instrumented.
    if (!instrClassesTarget.contains(className)) {
        return null;
    }

    boolean isRedefinition = classBeingRedefined != null;
    log("instrument class(" + className + ") " + (isRedefinition ? "redef" : "load"));

    ClassReader reader = new ClassReader(bytes);
    ClassWriter writer = new ClassWriter(
            reader, ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
    CallbackClassVisitor classVisitor = new CallbackClassVisitor(writer);
    reader.accept(classVisitor, 0);
    instrClassesDone.add(className);
    return writer.toByteArray();
}
 
Example #2
Source File: UnsupportedClassFileVersion.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void writeClassFile() throws Exception {
    ClassWriter cw = new ClassWriter(0);
    MethodVisitor mv;

    cw.visit(99, ACC_PUBLIC + ACC_SUPER, "ClassFile", null, "java/lang/Object", 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(1, 1);
    mv.visitEnd();
    cw.visitEnd();

    try (FileOutputStream fos = new FileOutputStream(new File("ClassFile.class"))) {
         fos.write(cw.toByteArray());
    }
}
 
Example #3
Source File: CallSiteDepContextTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
static byte[] getClassFile(String suffix) {
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
    MethodVisitor mv;
    cw.visit(52, ACC_PUBLIC | ACC_SUPER, CLASS_NAME + suffix, null, "java/lang/Object", null);
    {
        mv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, METHOD_NAME, TYPE.toMethodDescriptorString(), null, null);
        mv.visitCode();
        Handle bsm = new Handle(H_INVOKESTATIC,
                CallSiteDepContextTest.class.getName().replace(".", "/"),
                "bootstrap",
                bsmMH.type().toMethodDescriptorString());
        mv.visitInvokeDynamicInsn("methodName", TYPE.toMethodDescriptorString(), bsm);
        mv.visitInsn(IRETURN);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }
    cw.visitEnd();
    return cw.toByteArray();
}
 
Example #4
Source File: Proxy.java    From totallylazy with Apache License 2.0 6 votes vote down vote up
public static byte[] bytes(String name, Class<?> superClass) {
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);

    String superName = Type.getInternalName(superClass);
    cw.visit(V1_8, ACC_PUBLIC + ACC_SUPER, name, null, superName, null);

    handlerField(cw);

    for (Method method : sequence(superClass.getMethods()).
            reject(m -> isFinal(m.getModifiers())).
            reject(m -> isStatic(m.getModifiers())).
            reject(m -> m.getName().equals("toString"))) {
        method(cw, name, method, superName);
    }

    cw.visitEnd();
    return cw.toByteArray();
}
 
Example #5
Source File: CTVMUtilities.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public ClassVisitorForLabels(ClassWriter cw, Map<Label, Integer> lines,
                             Executable target) {
    super(Opcodes.ASM5, cw);
    this.lineNumbers = lines;

    StringBuilder builder = new StringBuilder("(");
    for (Parameter parameter : target.getParameters()) {
        builder.append(Utils.toJVMTypeSignature(parameter.getType()));
    }
    builder.append(")");
    if (target instanceof Constructor) {
        targetName = "<init>";
        builder.append("V");
    } else {
        targetName = target.getName();
        builder.append(Utils.toJVMTypeSignature(
                ((Method) target).getReturnType()));
    }
    targetDesc = builder.toString();
}
 
Example #6
Source File: StripDebugPlugin.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public ResourcePool transform(ResourcePool in, ResourcePoolBuilder out) {
    //remove *.diz files as well as debug attributes.
    in.transformAndCopy((resource) -> {
        ResourcePoolEntry res = resource;
        if (resource.type().equals(ResourcePoolEntry.Type.CLASS_OR_RESOURCE)) {
            String path = resource.path();
            if (path.endsWith(".class")) {
                if (path.endsWith("module-info.class")) {
                    // XXX. Do we have debug info? Is Asm ready for module-info?
                } else {
                    ClassReader reader = new ClassReader(resource.contentBytes());
                    ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
                    reader.accept(writer, ClassReader.SKIP_DEBUG);
                    byte[] content = writer.toByteArray();
                    res = resource.copyWithContent(content);
                }
            }
        } else if (predicate.test(res.path())) {
            res = null;
        }
        return res;
    }, out);

    return out.build();
}
 
Example #7
Source File: ClassFileAttributes.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected ByteVector write(ClassWriter cw,
                           byte[] code,
                           int len,
                           int maxStack,
                           int maxLocals)
{
    ByteVector attr = new ByteVector();

    int target_platform_index = 0;
    if (targetPlatform != null && targetPlatform.length() > 0)
        target_platform_index = cw.newUTF8(targetPlatform);
    attr.putShort(target_platform_index);

    return attr;
}
 
Example #8
Source File: TestConcreteClassWithAbstractMethod.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public static byte[] dumpT2() {
    ClassWriter cw = new ClassWriter(0);
    MethodVisitor mv;

    cw.visit(52, ACC_PUBLIC | ACC_SUPER, "p1/T2", null, "p1/T1", null);
    {
        mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        mv.visitVarInsn(ALOAD, 0);
        mv.visitMethodInsn(INVOKESPECIAL, "p1/T1", "<init>", "()V", false);
        mv.visitInsn(RETURN);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, "m", "()I", null, null);
        mv.visitEnd();
    }
    cw.visitEnd();

    return cw.toByteArray();
}
 
Example #9
Source File: LambdaAsm.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
static void verifyASM() throws Exception {
    ClassWriter cw = new ClassWriter(0);
    cw.visit(V1_8, ACC_PUBLIC, "X", null, "java/lang/Object", null);
    MethodVisitor mv = cw.visitMethod(ACC_STATIC, "foo",
            "()V", null, null);
    mv.visitMaxs(2, 1);
    mv.visitMethodInsn(INVOKESTATIC,
            "java/util/function/Function.class",
            "identity", "()Ljava/util/function/Function;", true);
    mv.visitInsn(RETURN);
    cw.visitEnd();
    byte[] carray = cw.toByteArray();
    // for debugging
    // write((new File("X.class")).toPath(), carray, CREATE, TRUNCATE_EXISTING);

    // verify using javap/classfile reader
    ClassFile cf = ClassFile.read(new ByteArrayInputStream(carray));
    int mcount = checkMethod(cf, "foo");
    if (mcount < 1) {
        throw new RuntimeException("unexpected method count, expected 1" +
                "but got " + mcount);
    }
}
 
Example #10
Source File: TestOSRWithNonEmptyStack.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private static void generateTestMethod(ClassWriter classWriter) {
    MethodVisitor mv = classWriter.visitMethod(ACC_PUBLIC,
            TestOSRWithNonEmptyStack.METHOD_NAME, "()V", null, null);
    Label osrEntryPoint = new Label();

    mv.visitCode();
    // Push 'this' into stack before OSR entry point to bail out compilation
    mv.visitVarInsn(ALOAD, 0);
    // Setup loop counter
    mv.visitInsn(ICONST_0);
    mv.visitVarInsn(ISTORE, 1);
    // Begin loop
    mv.visitLabel(osrEntryPoint);
    // Increment loop counter
    mv.visitVarInsn(ILOAD, 1);
    mv.visitInsn(ICONST_1);
    mv.visitInsn(IADD);
    // Duplicate it for loop condition check
    mv.visitInsn(DUP);
    mv.visitVarInsn(ISTORE, 1);
    // Check loop condition
    mv.visitLdcInsn(TestOSRWithNonEmptyStack.ITERATIONS);
    mv.visitJumpInsn(IF_ICMPLT, osrEntryPoint);
    // Pop 'this'.
    mv.visitInsn(POP);
    mv.visitInsn(RETURN);

    mv.visitMaxs(0, 0);
    mv.visitEnd();
}
 
Example #11
Source File: ClassGenerator.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
static ClassWriter makeClassWriter() {
    return new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS) {
        @Override
        protected String getCommonSuperClass(final String type1, final String type2) {
            try {
                return super.getCommonSuperClass(type1, type2);
            } catch (final RuntimeException | LinkageError e) {
                return StringConstants.OBJECT_TYPE;
            }
        }
    };
}
 
Example #12
Source File: JIClassInstrumentation.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private byte[] makeBytecode() throws IOException, ClassNotFoundException {

        // Find the methods to instrument and inline

        final List<Method> instrumentationMethods = new ArrayList<>();
        for (final Method m : instrumentor.getDeclaredMethods()) {
            JIInstrumentationMethod im = m.getAnnotation(JIInstrumentationMethod.class);
            if (im != null) {
                instrumentationMethods.add(m);
            }
        }

        // We begin by inlining the target's methods into the instrumentor

        ClassNode temporary = new ClassNode();
        ClassVisitor inliner = new JIInliner(
                Opcodes.ASM5,
                temporary,
                targetName,
                instrumentorName,
                targetClassReader,
                instrumentationMethods);
        instrClassReader.accept(inliner, ClassReader.EXPAND_FRAMES);

        // Now we have the target's methods inlined into the instrumentation code (in 'temporary').
        // We now need to replace the target's method with the code in the
        // instrumentation method.

        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
        JIMethodMergeAdapter ma = new JIMethodMergeAdapter(
                cw,
                temporary,
                instrumentationMethods,
                instrumentor.getAnnotationsByType(JITypeMapping.class));
        targetClassReader.accept(ma, ClassReader.EXPAND_FRAMES);

       return cw.toByteArray();
    }
 
Example #13
Source File: LambdaStackTrace.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static byte[] generateStringMaker() {
    // interface StringMaker extends Maker {
    //   String make();
    // }
    ClassWriter cw = new ClassWriter(0);
    cw.visit(V1_7, ACC_INTERFACE | ACC_ABSTRACT, "StringMaker", null, "java/lang/Object", new String[]{"Maker"});
    cw.visitMethod(ACC_PUBLIC | ACC_ABSTRACT, "make",
            "()Ljava/lang/String;", null, null);
    cw.visitEnd();
    return cw.toByteArray();
}
 
Example #14
Source File: RedefineAnnotations.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public byte[] asm(ClassLoader loader, String className,
        Class<?> classBeingRedefined,
        ProtectionDomain protectionDomain, byte[] classfileBuffer)
    throws IllegalClassFormatException {

    ClassWriter cw = new ClassWriter(0);
    ClassVisitor cv = new ReAddDummyFieldsClassVisitor(ASM5, cw) { };
    ClassReader cr = new ClassReader(classfileBuffer);
    cr.accept(cv, 0);
    return cw.toByteArray();
}
 
Example #15
Source File: RedefineRunningMethodsWithResolutionErrors.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static byte[] loadC(boolean redefine) {
    ClassWriter cw = new ClassWriter(0);

    cw.visit(52, ACC_SUPER | ACC_PUBLIC, "C", null, "java/lang/Object", null);
    {
        MethodVisitor mv;

        mv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "m", "()V", null, null);
        mv.visitCode();

        // First time we run we will:
        // 1) Cache resolution errors
        // 2) Redefine the class / method
        // 3) Try to read the resolution errors that were cached
        //
        // The redefined method will never run, throw error to be sure
        if (redefine) {
            createThrowRuntimeExceptionCode(mv, "The redefined method was called");
        } else {
            createMethodBody(mv);
        }
        mv.visitMaxs(3, 0);
        mv.visitEnd();
    }
    cw.visitEnd();
    return cw.toByteArray();
}
 
Example #16
Source File: ClassGenerator.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
static ClassWriter makeClassWriter() {
    return new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS) {
        @Override
        protected String getCommonSuperClass(final String type1, final String type2) {
            try {
                return super.getCommonSuperClass(type1, type2);
            } catch (final RuntimeException | LinkageError e) {
                return StringConstants.OBJECT_TYPE;
            }
        }
    };
}
 
Example #17
Source File: TestConcreteClassWithAbstractMethod.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static byte[] dumpT1() {
    ClassWriter cw = new ClassWriter(0);
    MethodVisitor mv;

    cw.visit(52, ACC_PUBLIC | ACC_SUPER, "p1/T1", null, "java/lang/Object", 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(1, 1);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(ACC_PUBLIC, "m", "()I", null, null);
        mv.visitCode();
        mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
        mv.visitLdcInsn("p1/T1.m()");
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "print", "(Ljava/lang/String;)V", false);
        mv.visitIntInsn(BIPUSH, 3);
        mv.visitInsn(IRETURN);
        mv.visitMaxs(2, 1);
        mv.visitEnd();
    }
    cw.visitEnd();

    return cw.toByteArray();
}
 
Example #18
Source File: TestPrivateInterfaceMethodReflect.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private byte[] loadClassData(String name) throws Exception {
    ClassWriter cw = new ClassWriter(0);
    MethodVisitor mv;
    switch (name) {
        case INTERFACE_NAME:
            cw.visit(V1_8, ACC_ABSTRACT | ACC_INTERFACE | ACC_PUBLIC, INTERFACE_NAME, null, "java/lang/Object", null);
            {
                mv = cw.visitMethod(ACC_PRIVATE, "privInstance", "()I", null, null);
                mv.visitCode();
                mv.visitLdcInsn(EXPECTED);
                mv.visitInsn(IRETURN);
                mv.visitMaxs(1, 1);
                mv.visitEnd();
            }
            break;
        case CLASS_NAME:
            cw.visit(52, ACC_SUPER | ACC_PUBLIC, CLASS_NAME, null, "java/lang/Object", new String[]{INTERFACE_NAME});
            {
                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();
            }
            break;
        default:
            break;
    }
    cw.visitEnd();

    return cw.toByteArray();
}
 
Example #19
Source File: TestOSRWithNonEmptyStack.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static void generateConstructor(ClassWriter classWriter) {
    MethodVisitor mv = classWriter.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();
}
 
Example #20
Source File: ConstructorTracerWriter.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
static byte[] generateBytes(Class<?> clz, byte[] oldBytes) throws IOException {
    InputStream in = new ByteArrayInputStream(oldBytes);
    ClassReader cr = new ClassReader(in);
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    ConstructorTracerWriter ctw = new ConstructorTracerWriter(cw, clz);
    cr.accept(ctw, 0);
    return cw.toByteArray();
}
 
Example #21
Source File: ModuleTargetAttribute.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
@Override
protected ByteVector write(
        final ClassWriter classWriter,
        final byte[] code,
        final int codeLength,
        final int maxStack,
        final int maxLocals) {
    ByteVector byteVector = new ByteVector();
    byteVector.putShort(platform == null ? 0 : classWriter.newUTF8(platform));
    return byteVector;
}
 
Example #22
Source File: ClassEmitter.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructor - only used internally in this class as it breaks
 * abstraction towards ASM or other code generator below
 *
 * @param env script environment
 * @param cw  ASM classwriter
 */
private ClassEmitter(final ScriptEnvironment env, final ClassWriter cw) {
    assert env != null;

    this.env            = env;
    this.cw             = cw;
    this.methodsStarted = new HashSet<>();
}
 
Example #23
Source File: ScriptClassInstrumentor.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * External entry point for ScriptClassInfoCollector if run from the command line
 *
 * @param args arguments - one argument is needed, the name of the class to collect info from
 *
 * @throws IOException if there are problems reading class
 */
public static void main(final String[] args) throws IOException {
    if (args.length != 1) {
        System.err.println("Usage: " + ScriptClassInstrumentor.class.getName() + " <class>");
        System.exit(1);
    }

    final String fileName = args[0].replace('.', '/') + ".class";
    final ScriptClassInfo sci = ClassGenerator.getScriptClassInfo(fileName);
    if (sci == null) {
        System.err.println("No @ScriptClass in " + fileName);
        System.exit(2);
        throw new AssertionError(); //guard against warning that sci is null below
    }

    try {
        sci.verify();
    } catch (final Exception e) {
        System.err.println(e.getMessage());
        System.exit(3);
    }

    final ClassWriter writer = ClassGenerator.makeClassWriter();
    try (final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileName))) {
        final ClassReader reader = new ClassReader(bis);
        final CheckClassAdapter checker = new CheckClassAdapter(writer);
        final ScriptClassInstrumentor instr = new ScriptClassInstrumentor(checker, sci);
        reader.accept(instr, 0);
    }

    try (FileOutputStream fos = new FileOutputStream(fileName)) {
        fos.write(writer.toByteArray());
    }
}
 
Example #24
Source File: ClassEmitter.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructor from the compiler.
 *
 * @param env           Script environment
 * @param sourceName    Source name
 * @param unitClassName Compile unit class name.
 * @param strictMode    Should we generate this method in strict mode
 */
ClassEmitter(final Context context, final String sourceName, final String unitClassName, final boolean strictMode) {
    this(context,
         new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS) {
            private static final String OBJECT_CLASS  = "java/lang/Object";

            @Override
            protected String getCommonSuperClass(final String type1, final String type2) {
                try {
                    return super.getCommonSuperClass(type1, type2);
                } catch (final RuntimeException e) {
                    if (isScriptObject(Compiler.SCRIPTS_PACKAGE, type1) && isScriptObject(Compiler.SCRIPTS_PACKAGE, type2)) {
                        return className(ScriptObject.class);
                    }
                    return OBJECT_CLASS;
                }
            }
        });

    this.unitClassName        = unitClassName;
    this.constantMethodNeeded = new HashSet<>();

    cw.visit(V1_7, ACC_PUBLIC | ACC_SUPER, unitClassName, null, pathName(jdk.nashorn.internal.scripts.JS.class.getName()), null);
    cw.visitSource(sourceName, null);

    defineCommonStatics(strictMode);
}
 
Example #25
Source File: TestPrivateInterfaceMethodReflect.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private byte[] loadClassData(String name) throws Exception {
    ClassWriter cw = new ClassWriter(0);
    MethodVisitor mv;
    switch (name) {
        case INTERFACE_NAME:
            cw.visit(V1_8, ACC_ABSTRACT | ACC_INTERFACE | ACC_PUBLIC, INTERFACE_NAME, null, "java/lang/Object", null);
            {
                mv = cw.visitMethod(ACC_PRIVATE, "privInstance", "()I", null, null);
                mv.visitCode();
                mv.visitLdcInsn(EXPECTED);
                mv.visitInsn(IRETURN);
                mv.visitMaxs(1, 1);
                mv.visitEnd();
            }
            break;
        case CLASS_NAME:
            cw.visit(52, ACC_SUPER | ACC_PUBLIC, CLASS_NAME, null, "java/lang/Object", new String[]{INTERFACE_NAME});
            {
                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();
            }
            break;
        default:
            break;
    }
    cw.visitEnd();

    return cw.toByteArray();
}
 
Example #26
Source File: OverriderMsg.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void dump_Overrider () throws Exception {

        ClassWriter cw = new ClassWriter(0);
        MethodVisitor mv;
        cw.visit(V1_7, ACC_PUBLIC + ACC_SUPER, "Overrider", null, "HasFinal", null);

        {
            mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
            mv.visitCode();
            mv.visitVarInsn(ALOAD, 0);
            mv.visitMethodInsn(INVOKESPECIAL, "HasFinal", "<init>", "()V");
            mv.visitInsn(RETURN);
            mv.visitMaxs(1, 1);
            mv.visitEnd();
        }
        {
            mv = cw.visitMethod(ACC_PUBLIC, "m", "(Ljava/lang/String;)V", null, null);
            mv.visitCode();
            mv.visitInsn(RETURN);
            mv.visitMaxs(0, 2);
            mv.visitEnd();
        }
        {
            mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null);
            mv.visitCode();
            mv.visitInsn(RETURN);
            mv.visitMaxs(0, 1);
            mv.visitEnd();
        }
        cw.visitEnd();

        try (FileOutputStream fos = new FileOutputStream(new File("Overrider.class"))) {
             fos.write(cw.toByteArray());
        }
    }
 
Example #27
Source File: GenerateJLIClassesHelper.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static void addMethod(String className, String methodName, LambdaForm form,
        MethodType type, ClassWriter cw) {
    InvokerBytecodeGenerator g
            = new InvokerBytecodeGenerator(className, methodName, form, type);
    g.setClassWriter(cw);
    g.addMethod();
}
 
Example #28
Source File: ClassEmitter.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructor from the compiler.
 *
 * @param env           Script environment
 * @param sourceName    Source name
 * @param unitClassName Compile unit class name.
 * @param strictMode    Should we generate this method in strict mode
 */
ClassEmitter(final Context context, final String sourceName, final String unitClassName, final boolean strictMode) {
    this(context,
         new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS) {
            private static final String OBJECT_CLASS  = "java/lang/Object";

            @Override
            protected String getCommonSuperClass(final String type1, final String type2) {
                try {
                    return super.getCommonSuperClass(type1, type2);
                } catch (final RuntimeException e) {
                    if (isScriptObject(Compiler.SCRIPTS_PACKAGE, type1) && isScriptObject(Compiler.SCRIPTS_PACKAGE, type2)) {
                        return className(ScriptObject.class);
                    }
                    return OBJECT_CLASS;
                }
            }
        });

    this.unitClassName        = unitClassName;
    this.constantMethodNeeded = new HashSet<>();

    cw.visit(V1_7, ACC_PUBLIC | ACC_SUPER, unitClassName, null, pathName(jdk.nashorn.internal.scripts.JS.class.getName()), null);
    cw.visitSource(sourceName, null);

    defineCommonStatics(strictMode);
}
 
Example #29
Source File: LambdaStackTrace.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static byte[] generateMaker() {
    // interface Maker {
    //   Object make();
    // }
    ClassWriter cw = new ClassWriter(0);
    cw.visit(V1_7, ACC_INTERFACE | ACC_ABSTRACT, "Maker", null, "java/lang/Object", null);
    cw.visitMethod(ACC_PUBLIC | ACC_ABSTRACT, "make",
            "()Ljava/lang/Object;", null, null);
    cw.visitEnd();
    return cw.toByteArray();
}
 
Example #30
Source File: ClassEmitter.java    From nashorn with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructor from the compiler
 *
 * @param env           Script environment
 * @param sourceName    Source name
 * @param unitClassName Compile unit class name.
 * @param strictMode    Should we generate this method in strict mode
 */
ClassEmitter(final ScriptEnvironment env, final String sourceName, final String unitClassName, final boolean strictMode) {
    this(env,
         new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS) {
            private static final String OBJECT_CLASS  = "java/lang/Object";

            @Override
            protected String getCommonSuperClass(final String type1, final String type2) {
                try {
                    return super.getCommonSuperClass(type1, type2);
                } catch (final RuntimeException e) {
                    if (isScriptObject(Compiler.SCRIPTS_PACKAGE, type1) && isScriptObject(Compiler.SCRIPTS_PACKAGE, type2)) {
                        return className(ScriptObject.class);
                    }
                    return OBJECT_CLASS;
                }
            }
        });

    this.unitClassName        = unitClassName;
    this.constantMethodNeeded = new HashSet<>();

    cw.visit(V1_7, ACC_PUBLIC | ACC_SUPER, unitClassName, null, pathName(jdk.nashorn.internal.scripts.JS.class.getName()), null);
    cw.visitSource(sourceName, null);

    defineCommonStatics(strictMode);
}