Example usage for org.objectweb.asm Opcodes ACC_PUBLIC

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

Introduction

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

Prototype

int ACC_PUBLIC

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

Click Source Link

Usage

From source file:com.google.code.nanorm.internal.introspect.asm.MapperBuilder.java

License:Apache License

/**
 * Generate constructor.// ww w  .ja  va  2 s . c om
 * 
 * @param cw class writer
 * @param owner self type
 * @param baseType
 */
private static void visitConstructor(ClassWriter cw, Type owner, Type baseType) {
    GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC, MAPPER_CTOR, null, null, cw);
    mg.loadThis();
    mg.invokeConstructor(baseType, CTOR);
    mg.loadThis();
    mg.loadArg(0);
    mg.putField(owner, "delegate", QUERY_DELEGATE_TYPE);
    mg.loadThis();
    mg.loadArg(1);
    mg.putField(owner, "configs", STATEMENT_CONFIGS_ARR_TYPE);
    mg.returnValue();
    mg.endMethod();
}

From source file:com.google.code.nanorm.internal.introspect.asm.MapperBuilder.java

License:Apache License

/**
 * Generate mapper method./*from  ww w . j  av  a  2  s.  co  m*/
 * 
 * @param owner self type
 * @param cw class writer
 * @param config method configuration
 */
private static void visitMethod(Type owner, ClassWriter cw, MethodConfig config) {
    java.lang.reflect.Method ifaceMethod = config.getMethod();
    Type returnType = Type.getType(ifaceMethod.getReturnType());
    Type[] args = new Type[ifaceMethod.getParameterTypes().length];
    for (int i = 0; i < args.length; ++i) {
        args[i] = Type.getType(ifaceMethod.getParameterTypes()[i]);
    }

    Method method = new Method(ifaceMethod.getName(), returnType, args);

    GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC, method, null, null, cw);

    // Factory
    mg.loadThis();
    mg.getField(owner, "delegate", QUERY_DELEGATE_TYPE);

    // Statement config
    mg.loadThis();
    mg.getField(owner, "configs", STATEMENT_CONFIGS_ARR_TYPE);
    mg.push(config.getIndex());
    mg.arrayLoad(Type.getType(StatementConfig.class));

    // Arguments
    mg.loadArgArray();

    mg.invokeInterface(QUERY_DELEGATE_TYPE, QUERY_METHOD);
    mg.unbox(returnType);
    mg.returnValue();
    mg.endMethod();

    // Copy the annotations
    copyAnnotations(ifaceMethod, null, mg);
}

From source file:com.google.devtools.build.android.desugar.CoreLibrarySupport.java

License:Open Source License

public void makeDispatchHelpers(GeneratedClassStore store) {
    HashMap<Class<?>, ClassVisitor> dispatchHelpers = new HashMap<>();
    for (Collection<EmulatedMethod> group : emulatedDefaultMethods.asMap().values()) {
        checkState(!group.isEmpty());/*  w w  w  .  j  a v a  2s .co m*/
        Class<?> root = group.stream().map(EmulatedMethod::owner)
                .max(DefaultMethodClassFixer.SubtypeComparator.INSTANCE).get();
        checkState(group.stream().map(m -> m.owner()).allMatch(o -> root.isAssignableFrom(o)),
                "Not a single unique method: %s", group);
        String methodName = group.stream().findAny().get().name();

        ImmutableList<Class<?>> customOverrides = findCustomOverrides(root, methodName);

        for (EmulatedMethod methodDefinition : group) {
            Class<?> owner = methodDefinition.owner();
            ClassVisitor dispatchHelper = dispatchHelpers.computeIfAbsent(owner, clazz -> {
                String className = clazz.getName().replace('.', '/') + "$$Dispatch";
                ClassVisitor result = store.add(className);
                result.visit(Opcodes.V1_7,
                        // Must be public so dispatch methods can be called from anywhere
                        Opcodes.ACC_SYNTHETIC | Opcodes.ACC_PUBLIC, className, /*signature=*/ null,
                        "java/lang/Object", EMPTY_LIST);
                return result;
            });

            // Types to check for before calling methodDefinition's companion, sub- before super-types
            ImmutableList<Class<?>> typechecks = concat(group.stream().map(EmulatedMethod::owner),
                    customOverrides.stream()).filter(o -> o != owner && owner.isAssignableFrom(o)).distinct() // should already be but just in case
                            .sorted(DefaultMethodClassFixer.SubtypeComparator.INSTANCE)
                            .collect(ImmutableList.toImmutableList());
            makeDispatchHelperMethod(dispatchHelper, methodDefinition, typechecks);
        }
    }
}

From source file:com.google.devtools.build.android.desugar.InterfaceDesugaring.java

License:Open Source License

@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
    MethodVisitor result;//  w w  w .  ja  va  2s . c o m
    if (BitFlags.isSet(accessFlags, Opcodes.ACC_INTERFACE)
            && BitFlags.noneSet(access, Opcodes.ACC_ABSTRACT | Opcodes.ACC_BRIDGE)
            && !"<clinit>".equals(name)) {
        checkArgument(BitFlags.noneSet(access, Opcodes.ACC_NATIVE), "Forbidden per JLS ch 9.4");

        boolean isLambdaBody = name.startsWith("lambda$") && BitFlags.isSet(access, Opcodes.ACC_SYNTHETIC);
        if (isLambdaBody) {
            access &= ~Opcodes.ACC_PUBLIC; // undo visibility change from LambdaDesugaring
            // Rename lambda method to reflect the new owner.  Not doing so confuses LambdaDesugaring
            // if it's run over this class again.
            name += COMPANION_SUFFIX;
        }
        if (BitFlags.isSet(access, Opcodes.ACC_STATIC)) {
            // Completely move static interface methods, which requires rewriting call sites
            result = companion().visitMethod(access & ~Opcodes.ACC_PRIVATE, name, desc, signature, exceptions);
        } else {
            MethodVisitor abstractDest;
            if (isLambdaBody) {
                // Completely move lambda bodies, which requires rewriting call sites
                access &= ~Opcodes.ACC_PRIVATE;
                abstractDest = null;
            } else {
                // Make default methods abstract but move their implementation into a static method with
                // corresponding signature.  Doesn't require callsite rewriting but implementing classes
                // may need to implement default methods explicitly.
                checkArgument(BitFlags.noneSet(access, Opcodes.ACC_PRIVATE),
                        "Unexpected private interface method %s.%s : %s", name, internalName, desc);
                abstractDest = super.visitMethod(access | Opcodes.ACC_ABSTRACT, name, desc, signature,
                        exceptions);
            }

            // TODO(b/37110951): adjust signature with explicit receiver type, which may be generic
            MethodVisitor codeDest = companion().visitMethod(access | Opcodes.ACC_STATIC, name,
                    companionDefaultMethodDescriptor(internalName, desc), (String) null, // drop signature, since given one doesn't include the new param
                    exceptions);

            result = abstractDest != null ? new MultiplexAnnotations(codeDest, abstractDest) : codeDest;
        }
    } else {
        result = super.visitMethod(access, name, desc, signature, exceptions);
    }
    return result != null ? new InterfaceInvocationRewriter(result) : null;
}

From source file:com.google.devtools.build.android.desugar.InterfaceDesugaring.java

License:Open Source License

private ClassVisitor companion() {
    if (companion == null) {
        checkState(BitFlags.isSet(accessFlags, Opcodes.ACC_INTERFACE));
        String companionName = internalName + COMPANION_SUFFIX;

        companion = store.add(companionName);
        companion.visit(bytecodeVersion,
                // Companion class must be public so moved methods can be called from anywhere
                (accessFlags | Opcodes.ACC_SYNTHETIC | Opcodes.ACC_PUBLIC) & ~Opcodes.ACC_INTERFACE,
                companionName, (String) null, // signature
                "java/lang/Object", new String[0]);
    }/*  w  ww.ja  v  a 2 s  .c  o  m*/
    return companion;
}

From source file:com.google.devtools.build.android.desugar.LambdaDesugaring.java

License:Open Source License

@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
    if (name.equals("$deserializeLambda$") && BitFlags.isSet(access, Opcodes.ACC_SYNTHETIC)) {
        // Android doesn't do anything special for lambda serialization so drop the special
        // deserialization hook that javac generates.  This also makes sure we don't reference
        // java/lang/invoke/SerializedLambda, which doesn't exist on Android.
        return null;
    }//from  w  ww .  j a v  a 2s. c om
    if (name.startsWith("lambda$") && BitFlags.isSet(access, Opcodes.ACC_SYNTHETIC)) {
        if (!allowDefaultMethods && isInterface && BitFlags.isSet(access, Opcodes.ACC_STATIC)) {
            // There must be a lambda in the interface (which in the absence of hand-written default or
            // static interface methods must mean it's in the <clinit> method or inside another lambda).
            // We'll move this method out of this class, so just record and drop it here.
            // (Note lambda body methods have unique names, so we don't need to remember desc here.)
            aggregateInterfaceLambdaMethods.add(internalName + '#' + name);
            return null;
        }
        if (BitFlags.isSet(access, Opcodes.ACC_PRIVATE)) {
            // Make lambda body method accessible from lambda class
            access &= ~Opcodes.ACC_PRIVATE;
            if (allowDefaultMethods && isInterface) {
                // java 8 requires interface methods to have exactly one of ACC_PUBLIC and ACC_PRIVATE
                access |= Opcodes.ACC_PUBLIC;
            } else {
                // Method was private so it can be final, which should help VMs perform dispatch.
                access |= Opcodes.ACC_FINAL;
            }
        }
        // Guarantee unique lambda body method name to avoid accidental overriding. This wouldn't be
        // be necessary for static methods but in visitOuterClass we don't know whether a potential
        // outer lambda$ method is static or not, so we just always do it.
        name = uniqueInPackage(internalName, name);
    }
    MethodVisitor dest = super.visitMethod(access, name, desc, signature, exceptions);
    return dest != null ? new InvokedynamicRewriter(dest, access, name, desc, signature, exceptions) : null;
}

From source file:com.google.devtools.build.android.resources.RClassGenerator.java

License:Open Source License

/**
 * Builds the bytecode and writes out the R.class file, and R$inner.class files.
 *///from   w w w.  j a va 2s.c  o  m
public void write() throws IOException {
    Iterable<String> folders = PACKAGE_SPLITTER.split(packageName);
    Path packageDir = outFolder;
    for (String folder : folders) {
        packageDir = packageDir.resolve(folder);
    }
    // At least create the outFolder that was requested. However, if there are no symbols, don't
    // create the R.class and inner class files (no need to have an empty class).
    Files.createDirectories(packageDir);
    if (initializers.isEmpty()) {
        return;
    }
    Path rClassFile = packageDir.resolve(SdkConstants.FN_COMPILED_RESOURCE_CLASS);

    String packageWithSlashes = packageName.replaceAll("\\.", "/");
    String rClassName = packageWithSlashes + "/R";
    ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    classWriter.visit(JAVA_VERSION, Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_SUPER, rClassName,
            null, /* signature */
            SUPER_CLASS, null /* interfaces */);
    classWriter.visitSource(SdkConstants.FN_RESOURCE_CLASS, null);
    writeConstructor(classWriter);

    // Build the R.class w/ the inner classes, then later build the individual R$inner.class.
    for (ResourceType resourceType : initializers.keySet()) {
        String innerClassName = rClassName + "$" + resourceType;
        classWriter.visitInnerClass(innerClassName, rClassName, resourceType.toString(),
                Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC);
    }
    classWriter.visitEnd();
    Files.write(rClassFile, classWriter.toByteArray());

    // Now generate the R$inner.class files.
    for (Map.Entry<ResourceType, List<FieldInitializer>> entry : initializers.entrySet()) {
        writeInnerClass(entry.getValue(), packageDir, rClassName, entry.getKey().toString());
    }
}

From source file:com.google.devtools.build.android.resources.RClassGenerator.java

License:Open Source License

private void writeInnerClass(List<FieldInitializer> initializers, Path packageDir,
        String fullyQualifiedOuterClass, String innerClass) throws IOException {
    ClassWriter innerClassWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    String fullyQualifiedInnerClass = writeInnerClassHeader(fullyQualifiedOuterClass, innerClass,
            innerClassWriter);//from   ww w . ja  v  a2 s . c om

    List<FieldInitializer> deferredInitializers = new ArrayList<>();
    int fieldAccessLevel = Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC;
    if (finalFields) {
        fieldAccessLevel |= Opcodes.ACC_FINAL;
    }
    for (FieldInitializer init : initializers) {
        if (init.writeFieldDefinition(innerClassWriter, fieldAccessLevel, finalFields)) {
            deferredInitializers.add(init);
        }
    }
    if (!deferredInitializers.isEmpty()) {
        writeStaticClassInit(innerClassWriter, fullyQualifiedInnerClass, deferredInitializers);
    }

    innerClassWriter.visitEnd();
    Path innerFile = packageDir.resolve("R$" + innerClass + ".class");
    Files.write(innerFile, innerClassWriter.toByteArray());
}

From source file:com.google.devtools.build.android.resources.RClassGenerator.java

License:Open Source License

private String writeInnerClassHeader(String fullyQualifiedOuterClass, String innerClass,
        ClassWriter innerClassWriter) {//from  w ww.ja v a2s  .c  o  m
    String fullyQualifiedInnerClass = fullyQualifiedOuterClass + "$" + innerClass;
    innerClassWriter.visit(JAVA_VERSION, Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_SUPER,
            fullyQualifiedInnerClass, null, /* signature */
            SUPER_CLASS, null /* interfaces */);
    innerClassWriter.visitSource(SdkConstants.FN_RESOURCE_CLASS, null);
    writeConstructor(innerClassWriter);
    innerClassWriter.visitInnerClass(fullyQualifiedInnerClass, fullyQualifiedOuterClass, innerClass,
            Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC);
    return fullyQualifiedInnerClass;
}

From source file:com.google.devtools.build.android.resources.RClassGenerator.java

License:Open Source License

private static void writeConstructor(ClassWriter classWriter) {
    MethodVisitor constructor = classWriter.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V",
            null, /* signature */
            null /* exceptions */);
    constructor.visitCode();//w ww.j  ava2 s. com
    constructor.visitVarInsn(Opcodes.ALOAD, 0);
    constructor.visitMethodInsn(Opcodes.INVOKESPECIAL, SUPER_CLASS, "<init>", "()V", false);
    constructor.visitInsn(Opcodes.RETURN);
    constructor.visitMaxs(1, 1);
    constructor.visitEnd();
}