Example usage for org.objectweb.asm Opcodes ACC_SUPER

List of usage examples for org.objectweb.asm Opcodes ACC_SUPER

Introduction

In this page you can find the example usage for org.objectweb.asm Opcodes ACC_SUPER.

Prototype

int ACC_SUPER

To view the source code for org.objectweb.asm Opcodes ACC_SUPER.

Click Source Link

Usage

From source file:org.elasticsearch.painless.PainlessScriptEngine.java

License:Apache License

/**
 * Generates a factory class that will return script instances or stateful factories.
 * Uses the newInstance method from a {@link ScriptContext#factoryClazz} to define the factory method
 * to create new instances of the {@link ScriptContext#instanceClazz} or uses the newFactory method
 * to create new factories of the {@link ScriptContext#statefulFactoryClazz}.
 * @param loader The {@link ClassLoader} that is used to define the factory class and script class.
 * @param context The {@link ScriptContext}'s semantics are used to define the factory class.
 * @param classType The type to be instaniated in the newFactory or newInstance method.  Depends
 *                  on whether a {@link ScriptContext#statefulFactoryClazz} is specified.
 * @param <T> The factory class./*w w w . ja v  a2 s.  c o m*/
 * @return A factory class that will return script instances.
 */
private <T> T generateFactory(Loader loader, ScriptContext<T> context, MainMethodReserved reserved,
        Type classType) {
    int classFrames = ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS;
    int classAccess = Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER | Opcodes.ACC_FINAL;
    String interfaceBase = Type.getType(context.factoryClazz).getInternalName();
    String className = interfaceBase + "$Factory";
    String classInterfaces[] = new String[] { interfaceBase };

    ClassWriter writer = new ClassWriter(classFrames);
    writer.visit(WriterConstants.CLASS_VERSION, classAccess, className, null, OBJECT_TYPE.getInternalName(),
            classInterfaces);

    org.objectweb.asm.commons.Method init = new org.objectweb.asm.commons.Method("<init>",
            MethodType.methodType(void.class).toMethodDescriptorString());

    GeneratorAdapter constructor = new GeneratorAdapter(Opcodes.ASM5, init,
            writer.visitMethod(Opcodes.ACC_PUBLIC, init.getName(), init.getDescriptor(), null, null));
    constructor.visitCode();
    constructor.loadThis();
    constructor.invokeConstructor(OBJECT_TYPE, init);
    constructor.returnValue();
    constructor.endMethod();

    Method reflect = null;

    for (Method method : context.factoryClazz.getMethods()) {
        if ("newInstance".equals(method.getName())) {
            reflect = method;

            break;
        } else if ("newFactory".equals(method.getName())) {
            reflect = method;

            break;
        }
    }

    org.objectweb.asm.commons.Method instance = new org.objectweb.asm.commons.Method(reflect.getName(),
            MethodType.methodType(reflect.getReturnType(), reflect.getParameterTypes())
                    .toMethodDescriptorString());
    org.objectweb.asm.commons.Method constru = new org.objectweb.asm.commons.Method("<init>",
            MethodType.methodType(void.class, reflect.getParameterTypes()).toMethodDescriptorString());

    GeneratorAdapter adapter = new GeneratorAdapter(Opcodes.ASM5, instance, writer.visitMethod(
            Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL, instance.getName(), instance.getDescriptor(), null, null));
    adapter.visitCode();
    adapter.newInstance(classType);
    adapter.dup();
    adapter.loadArgs();
    adapter.invokeConstructor(classType, constru);
    adapter.returnValue();
    adapter.endMethod();

    writeNeedsMethods(context.factoryClazz, writer, reserved);
    writer.visitEnd();

    Class<?> factory = loader.defineFactory(className.replace('/', '.'), writer.toByteArray());

    try {
        return context.factoryClazz.cast(factory.getConstructor().newInstance());
    } catch (Exception exception) { // Catch everything to let the user know this is something caused internally.
        throw new IllegalStateException(
                "An internal error occurred attempting to define the factory class [" + className + "].",
                exception);
    }
}

From source file:org.elasticsearch.painless.Writer.java

License:Apache License

private void writeBegin() {
    final int compute = ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS;
    final int version = Opcodes.V1_7;
    final int access = Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER | Opcodes.ACC_FINAL;
    final String base = BASE_CLASS_TYPE.getInternalName();
    final String name = CLASS_TYPE.getInternalName();

    writer = new ClassWriter(compute);
    writer.visit(version, access, name, null, base, null);
    writer.visitSource(source, null);//from   w  w w. ja v  a 2 s  .c o  m
}

From source file:org.elasticsearch.plan.a.Writer.java

License:Apache License

private void writeBegin() {
    final int compute = ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS;
    final int version = Opcodes.V1_7;
    final int access = Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC;
    final String base = BASE_CLASS_TYPE.getInternalName();
    final String name = CLASS_TYPE.getInternalName();

    writer = new ClassWriter(compute);
    writer.visit(version, access, name, null, base, null);
    writer.visitSource(source, null);/*from   www  . j a va2 s.  c  o  m*/
}

From source file:org.evosuite.symbolic.instrument.AccessFlags.java

License:Open Source License

static boolean isSuper(int access) {
    return is(access, Opcodes.ACC_SUPER);
}

From source file:org.freud.analysed.classbytecode.parser.asm.AsmClassByteCode.java

License:Apache License

@Override
public boolean isSuper() {
    return isAccessModifier(Opcodes.ACC_SUPER);
}

From source file:org.gradle.language.base.internal.tasks.apigen.ApiStubGenerator.java

License:Apache License

private boolean isPackagePrivate(int access) {
    return access == 0 || access == Opcodes.ACC_STATIC || access == Opcodes.ACC_SUPER
            || access == (Opcodes.ACC_SUPER | Opcodes.ACC_STATIC);
}

From source file:org.openquark.cal.internal.javamodel.AsmJavaBytecodeGenerator.java

License:Open Source License

/**
 * Accepts a visitor and fills it with information for a given class.
 * @param classRep the representation for the top-level class.
 * @param cv the class visitor to accept.
 * @throws JavaGenerationException//  w  w  w .j a  v  a 2s  .  co m
 */
private static void encodeClassAcceptingVisitor(JavaClassRep classRep, ClassVisitor cv)
        throws JavaGenerationException {

    // Get the fully-qualified internal class and superclass names.    
    final JavaTypeName classRepTypeName = classRep.getClassName();
    final String className = classRepTypeName.getJVMInternalName();
    final String superclassName = classRep.getSuperclassName().getJVMInternalName();

    // Determine if the class or any inner class contains assert statements.
    int assertPresence = classRep.getAssertionContainment();
    if ((assertPresence & JavaClassRep.ASSERTS_UNKNOWN) > 0) {
        assertPresence = AsmJavaBytecodeGenerator.containsAsserts(classRep);
    }

    // Create the interfaces[] array.
    final int nInterfaces = classRep.getNInterfaces();
    final String[] interfaces = new String[nInterfaces];
    for (int i = 0; i < nInterfaces; i++) {
        interfaces[i] = classRep.getInterface(i).getJVMInternalName();
    }

    //ACC_SUPER flag should always be set for the flags defining a class file.
    //(see the Java language specification under ACC_SUPER in the index. The flag is not set only
    //by older Java compilers and exists for backwards compatibility reasons).
    int classModifiers = classRep.getModifiers() | Opcodes.ACC_SUPER;
    //static inner classes are marked with the static modifier, but this is not a valid access flag for a class.
    classModifiers &= ~Modifier.STATIC;

    // We aren't generating or using generics, so the signature can be null
    String classSignature = null;
    cv.visit(Opcodes.V1_5, classModifiers, className, classSignature, superclassName, interfaces);

    //sourcefileName = null, since this class was not compiled from a Java source file.
    //However, if we are debugging byte codes, use a "fake" source file name as if this class were generated from a Java source file.
    //This eliminates a trivial difference between the byte code generated by ASM and that of javac and makes inspecting the
    //differences in a differencing tool easier.
    String sourceFileName = null;
    //        if (AsmJavaBytecodeGenerator.DEBUG_GENERATED_BYTECODE) {               
    String unqualifiedName = classRepTypeName.getUnqualifiedJavaSourceName();
    int dotPosition = unqualifiedName.indexOf('.');
    if (dotPosition != -1) {
        //get the top level class name.
        unqualifiedName = unqualifiedName.substring(0, dotPosition);
    }
    sourceFileName = unqualifiedName + ".java";
    //        }

    cv.visitSource(sourceFileName, null);

    //add the fields        
    for (int i = 0, nFields = classRep.getNFieldDeclarations(); i < nFields; ++i) {

        JavaFieldDeclaration fieldDeclaration = classRep.getFieldDeclaration(i);

        //todoBI it may be more efficient to handle initializers for static-fields here in the cases where it is possible
        //(int, long, float, double, String).
        cv.visitField(fieldDeclaration.getModifiers(), fieldDeclaration.getFieldName(),
                fieldDeclaration.getFieldType().getJVMDescriptor(), null, null);
    }

    /*
     * When dealing with assert statements there is possibly an additional field that needs to be
     * added.
     * If a class contains an assert statement a static final synthetic boolean field called '$assertionsDisabled' is
     * added.  This field is initialized in the class static initializer and is used to determine whether to
     * check or skip assertions.
     */
    if (assertPresence != JavaClassRep.ASSERTS_NONE) {

        if ((assertPresence & JavaClassRep.ASSERTS_IN_CLASS) > 0) {
            // We need to add a static final synthetic boolean field to indicate the enabled/disabled state of assertions.
            cv.visitField(Opcodes.ACC_FINAL + Opcodes.ACC_STATIC + Opcodes.ACC_SYNTHETIC, "$assertionsDisabled",
                    "Z", null, null);
        }
    }

    //add the constructors
    final int nConstructors = classRep.getNConstructors();
    if (nConstructors == 0) {
        //if empty, add the default constructor.             

        JavaConstructor defaultConstructor = new JavaConstructor(Modifier.PUBLIC,
                ((JavaTypeName.Reference.Object) classRepTypeName).getBaseName());
        defaultConstructor.addStatement(new JavaStatement.ReturnStatement());
        encodeConstructor(classRep, defaultConstructor, cv);

    } else {

        for (int i = 0; i < nConstructors; ++i) {
            encodeConstructor(classRep, classRep.getConstructor(i), cv);
        }
    }

    //add the methods
    for (int i = 0, nMethods = classRep.getNMethods(); i < nMethods; ++i) {

        encodeMethod(classRep, classRep.getMethod(i), cv);
    }

    //add the initializers for the static fields
    encodeClassInitializer(classRep, cv, (assertPresence & JavaClassRep.ASSERTS_IN_CLASS) > 0);

    //add the inner classes (these are basically just references to the inner classes)

    //if classRep itself is an inner class, call visitInnerClass on itself. This is what the eclipse java compiler does.
    //javac annotates for every inner class reference occurring within the class file e.g. a field declared of inner class type,
    //an instance of expression of inner class type, a throws declaration on a method where an inner class is thrown.
    if (classRepTypeName.isInnerClass()) {

        JavaTypeName.Reference.Object classTypeName = (JavaTypeName.Reference.Object) classRepTypeName;
        String internalImportName = classTypeName.getImportName().replace('.', '/');

        cv.visitInnerClass(classTypeName.getJVMInternalName(), internalImportName, classTypeName.getBaseName(),
                classRep.getModifiers());
    }

    /*
     * Previously we would call visitInnerClass for any inner classes associated with this class.  However,
     * we are no longer doing this.  
     * Bytecode is generated in different scenarios (i.e. static generation, dynamic generation, etc).  In some
     * scenarios inner classes are generated separately from the containing class.  In order to keep the generated
     * bytecode consistent between the dynamic and static scenarios wer are not adding the attributes for contained 
     * inner classes to the bytecode.
     * 
     for (int i = 0, nInnerClasses = classRep.getNInnerClasses(); i < nInnerClasses; ++i) {
            
    JavaClassRep innerClass = classRep.getInnerClass(i);
    JavaTypeName.Reference.Object innerClassTypeName = (JavaTypeName.Reference.Object)innerClass.getClassName();            
            
    cw.visitInnerClass(innerClassTypeName.getJVMInternalName(), className, innerClassTypeName.getBaseName(), innerClass.getModifiers());
    }               
            
    */

    cv.visitEnd();
}

From source file:org.spongepowered.mod.asm.util.ASMEventListenerFactory.java

License:MIT License

@SuppressWarnings("unchecked")
private static <T> Class<T> createClass(Class<T> interf, Method input, Method output) {

    String className = getClassName(interf, input, output);

    ClassWriter cwBase = new ClassWriter(0);
    CheckClassAdapter cw = new CheckClassAdapter(cwBase);

    MethodVisitor mv;/*from  w  w w .j  a va2  s  .c  o  m*/

    String classNameDesc = className.replace('.', '/');

    String interfaceInternalName = Type.getInternalName(interf);

    String inputName = input.getName();
    String inputMethodDescriptor = Type.getMethodDescriptor(input);

    String outputParameterTypeIntName = Type.getInternalName(output.getParameterTypes()[0]);
    String outputTargetTypeIntName = Type.getInternalName(output.getDeclaringClass());
    String outputMethodDescriptor = Type.getMethodDescriptor(output);
    String outputName = output.getName();

    boolean isOutputInterface = output.getDeclaringClass().isInterface();

    // A new class of the following form is created, with a unique name
    //
    // package org.spongepowered.mod.asm;
    // public class <className> extends java.lang.Object implements <interf>
    //
    //     private final Object target
    //
    //     public <className> (java.lang.Object target) {
    //         super();
    //         this.target = target;
    //         return;
    //     }
    //
    //     public void <inputMethod> (<inputMethodType event) {
    //         ((outputTargetType) this.target).outputMethod((outputParameteType) event);
    //         return
    //     }
    // }

    // package org.spongepowered.mod.asm;
    // public class <className> extends java.lang.Object implements <interf>
    cw.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER, classNameDesc, null, "java/lang/Object",
            new String[] { interfaceInternalName });

    // private final Object target
    cw.visitField(Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL, "target", "Ljava/lang/Object;", null, null);

    // Constructor

    // public UniqueClass (java.lang.Object target) {
    mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "(Ljava/lang/Object;)V", null, null);
    mv.visitCode();

    // super();
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);

    // this.target = target;
    mv.visitVarInsn(Opcodes.ALOAD, 0); // Loads this
    mv.visitVarInsn(Opcodes.ALOAD, 1); // Loads target (from input)
    mv.visitFieldInsn(Opcodes.PUTFIELD, classNameDesc, "target", "Ljava/lang/Object;");

    // return;
    mv.visitInsn(Opcodes.RETURN);

    // }
    // 2 localvars due to inputs: this, target
    // 2 items on stack after double ALOAD
    mv.visitMaxs(2, 2);
    mv.visitEnd();

    // Callback method

    // public void <inputMethod> (<inputMethodType event) {
    mv = cw.visitMethod(Opcodes.ACC_PUBLIC, inputName, inputMethodDescriptor, null, null);
    mv.visitCode();

    // push((casted) this.target)
    mv.visitVarInsn(Opcodes.ALOAD, 0); // Loads this
    mv.visitFieldInsn(Opcodes.GETFIELD, classNameDesc, "target", "Ljava/lang/Object;");
    mv.visitTypeInsn(Opcodes.CHECKCAST, outputTargetTypeIntName);

    // push((casted) event)
    mv.visitVarInsn(Opcodes.ALOAD, 1); // Loads method parameter 0
    mv.visitTypeInsn(Opcodes.CHECKCAST, outputParameterTypeIntName);

    // ((outputTargetType) this.target).outputMethod((outputParameteType) event);
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, outputTargetTypeIntName, outputName, outputMethodDescriptor,
            isOutputInterface);

    // return
    mv.visitInsn(Opcodes.RETURN);

    // }
    mv.visitMaxs(2, 2);
    mv.visitEnd();

    cw.visitEnd();

    byte[] bytes = cwBase.toByteArray();

    return (Class<T>) loader.defineClass(className, bytes);
}

From source file:org.springframework.xd.fluent.internal.CustomizedModuleGenerator.java

License:Apache License

/**
 * @param inDescriptor input descriptor of the form Lfoo/Bar;
 * @param outDescriptor output descriptor of the form Lfoo/Boo;
 *///from ww w  . j av a  2s. c o  m
private static void writeCustomCode(ZipOutputStream zos, String inDescriptor, String outDescriptor) {
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
    cw.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER, "org/springframework/xd/code/Code", null,
            "org/springframework/xd/code/CodeDrivenProcessor", null);

    MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESPECIAL, "org/springframework/xd/code/CodeDrivenProcessor", "<init>", "()V",
            false);
    mv.visitInsn(RETURN);
    mv.visitMaxs(1, 1);
    mv.visitEnd();

    // An example transform method that picks even number chars from the input payload and makes that into the output
    mv = cw.visitMethod(ACC_PUBLIC, "transform", "(" + inDescriptor + ")" + outDescriptor, null, null);
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitFieldInsn(Opcodes.GETFIELD, "org/springframework/xd/code/Code", "fn",
            "Ljava/util/function/Function;");
    mv.visitVarInsn(ALOAD, 1);
    mv.visitMethodInsn(INVOKEINTERFACE, "java/util/function/Function", "apply",
            "(Ljava/lang/Object;)Ljava/lang/Object;", true);
    mv.visitTypeInsn(CHECKCAST, outDescriptor.substring(1, outDescriptor.length() - 1));//"java/lang/Integer");
    mv.visitInsn(ARETURN);
    mv.visitMaxs(2, 2);
    mv.visitEnd();
    cw.visitEnd();
    try {
        zos.write(cw.toByteArray());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.springsource.loaded.ri.ReflectiveInterceptor.java

License:Apache License

/**
 * Performs access checks and returns a (potential) copy of the method with accessibility flag set if this necessary for the
 * invoke to succeed./*  ww  w. j a  v a 2s . c  o m*/
 * <p>
 * Also checks for deleted methods.
 * <p>
 * If any checks fail, an appropriate exception is raised.
 */
private static Method asAccessibleMethod(ReloadableType methodDeclaringTypeReloadableType, Method method,
        Object target, boolean makeAccessibleCopy) throws IllegalAccessException {
    if (methodDeclaringTypeReloadableType != null && isDeleted(methodDeclaringTypeReloadableType, method)) {
        throw Exceptions.noSuchMethodError(method);
    }

    if (method.isAccessible()) {
        //More expensive check not required / copy not required
    } else {
        Class<?> clazz = method.getDeclaringClass();
        int mods = method.getModifiers();
        int classmods;

        //      ReloadableType rtype = getReloadableTypeIfHasBeenReloaded(clazz);
        if (methodDeclaringTypeReloadableType == null || !methodDeclaringTypeReloadableType.hasBeenReloaded()) {
            classmods = clazz.getModifiers();
        } else {
            //Note: the "super bit" may be set in class modifiers but we should block it out, it
            //shouldn't be shown to users of the reflection API.
            classmods = methodDeclaringTypeReloadableType.getLatestTypeDescriptor().getModifiers()
                    & ~Opcodes.ACC_SUPER;
        }
        if (Modifier.isPublic(mods & classmods/*jlClassGetModifiers(clazz)*/)) {
            //More expensive check not required / copy not required
        } else {
            //More expensive check required
            Class<?> callerClass = getCallerClass();
            JVM.ensureMemberAccess(callerClass, clazz, target, mods);
            if (makeAccessibleCopy) {
                method = JVM.copyMethod(method); // copy: we must not change accessible flag on original method!
                method.setAccessible(true);
            }
        }
    }
    return makeAccessibleCopy ? method : null;
}