Example usage for org.objectweb.asm Type getMethodDescriptor

List of usage examples for org.objectweb.asm Type getMethodDescriptor

Introduction

In this page you can find the example usage for org.objectweb.asm Type getMethodDescriptor.

Prototype

public static String getMethodDescriptor(final Method method) 

Source Link

Document

Returns the descriptor corresponding to the given method.

Usage

From source file:ca.weblite.asm.JavaExtendedStubCompiler.java

License:Apache License

public Map<String, byte[]> compile(List<Type> types, File sourceFile) throws IOException {
    final Map<String, byte[]> outMap = new HashMap<>();
    final Set<String> typeNames = (types == null) ? null : new HashSet<String>();
    if (types != null) {
        for (Type type : types) {
            typeNames.add(type.getInternalName());
        }//from   ww w  .ja  v a 2 s .  c o m
    }
    JavaCompiler compiler = JavacTool.create();
    MyFileObject[] fos = new MyFileObject[] { new MyFileObject(sourceFile) };

    JavacTask task = (JavacTask) compiler.getTask(null, null, null, null, null, Arrays.asList(fos));
    Iterable<? extends CompilationUnitTree> asts = task.parse();
    TreePathScanner scanner;

    final LinkedList<ClassFinder> scopeStack = new LinkedList<>();
    scanner = new TreePathScanner() {

        String packageName;
        ClassNode superClass;
        LinkedList<String> stack = new LinkedList<>();
        LinkedList<ClassInfo> classInfoStack = new LinkedList<>();
        LinkedList<ClassWriter> cwStack = new LinkedList<>();
        LinkedList<List<? extends TypeParameterTree>> typeParametersStack = new LinkedList<>();

        @Override
        public Object visitCompilationUnit(CompilationUnitTree cut, Object p) {

            packageName = cut.getPackageName().toString();
            ClassFinder scope = new ClassFinder(context.get(ClassLoader.class), null);
            scopeStack.push(scope);
            scope.addImport(packageName + ".*");
            return super.visitCompilationUnit(cut, p);
        }

        private String getThisInternalName(String simpleName) {
            simpleName = simpleName.replaceAll("\\.", "$");
            StringBuilder sb = new StringBuilder();
            Iterator<String> it = stack.descendingIterator();
            sb.append(packageName.replaceAll("\\.", "/"));
            sb.append("/");

            while (it.hasNext()) {
                sb.append(it.next()).append("$");
            }
            sb.append(simpleName);
            return sb.toString();
        }

        @Override
        public Object visitImport(ImportTree it, Object p) {
            if (!it.isStatic()) {
                String path = it.getQualifiedIdentifier().toString();
                scopeStack.peek().addImport(path);
            }
            return super.visitImport(it, p);
        }

        Object visitConstructor(final MethodTree mt, Object p) {
            ClassWriter classWriter = cwStack.peek();
            List<Type> argTypes = new ArrayList<Type>();
            boolean isVarArgs = false;
            for (VariableTree v : mt.getParameters()) {

                if (v.toString().endsWith("... " + v.getName())) {
                    isVarArgs = true;
                }
                String type = v.getType().toString();
                String fullType = type;
                String signature = null;
                try {
                    signature = TypeUtil.getTypeSignature(type, scopeStack.peek());
                } catch (Throwable t) {
                    System.out.println("Failed to find signature for type");
                }
                if (type.indexOf("<") != -1) {
                    type = type.substring(0, type.indexOf("<"));
                }
                int dim = 0;
                if (TypeUtil.isArrayType(type)) {
                    dim = TypeUtil.getArrayTypeDimension(type);
                    type = TypeUtil.getArrayElementType(type);
                }
                if (TypeUtil.isPrimitiveType(type)) {
                    String descriptor = TypeUtil.getDescriptor(type);
                    argTypes.add(Type.getType(TypeUtil.getArrayDescriptor(descriptor, dim)));
                } else {
                    ClassNode stub = scopeStack.peek().findStub(type);
                    assert stub != null;
                    argTypes.add(Type.getObjectType(stub.name));
                }

            }

            String methodDescriptor = null;
            String methodSignature = null;
            if (argTypes.isEmpty()) {
                methodDescriptor = Type.getMethodDescriptor(Type.getType("V"));
            } else {
                methodDescriptor = Type.getMethodDescriptor(Type.getType("V"), argTypes.toArray(new Type[0]));

            }

            int flags = getFlags(mt.getModifiers().getFlags());
            if (isVarArgs) {
                flags |= Opcodes.ACC_VARARGS;

            }
            classWriter.visitMethod(flags, mt.getName().toString(), methodDescriptor, null, null);
            classInfoStack.peek().numConstructors++;
            return null;
        }

        @Override
        public Object visitMethod(MethodTree mt, Object p) {
            if (mt.getReturnType() == null) {
                // It's a constructor
                return visitConstructor(mt, p);
            } else {
                boolean isVarArgs = false;
                ClassWriter classWriter = cwStack.peek();

                List<Type> argTypes = new ArrayList<>();
                List<String> sigArgTypes = new ArrayList<>();
                for (VariableTree v : mt.getParameters()) {
                    String type = v.getType().toString();
                    if (v.toString().endsWith("... " + v.getName())) {
                        isVarArgs = true;
                    }
                    sigArgTypes.add(type);
                    int dim = 0;
                    if (TypeUtil.isArrayType(type)) {
                        dim = TypeUtil.getArrayTypeDimension(type);
                        type = TypeUtil.getArrayElementType(type);
                    }
                    if (TypeUtil.isPrimitiveType(type)) {
                        String descriptor = TypeUtil.getDescriptor(type);
                        argTypes.add(Type.getType(TypeUtil.getArrayDescriptor(descriptor, dim)));
                    } else {

                        if (isGenericType(type)) {
                            type = "Object";
                        }

                        int arrowPos = type.indexOf("<");
                        if (arrowPos != -1) {
                            type = type.substring(0, arrowPos);
                        }
                        ClassNode stub = scopeStack.peek().findStub(type);
                        if (stub == null) {
                            throw new RuntimeException("Could not find class for " + type);
                        }
                        Type argType = Type.getObjectType(stub.name);
                        argType = Type.getType(TypeUtil.getArrayDescriptor(argType.getInternalName(), dim));
                        argTypes.add(argType);
                    }

                }

                String returnType = mt.getReturnType().toString();
                if (isGenericType(returnType)) {
                    returnType = "Object";
                }

                String methodSignature = null;
                try {
                    methodSignature = TypeUtil.getMethodSignature(scopeStack.peek(), returnType,
                            sigArgTypes.toArray(new String[0]));
                } catch (Exception ex) {
                    System.out.println(
                            "Failed to get signature for method " + mt + " message: " + ex.getMessage());
                }
                int dim = 0;

                Type returnTypeType = null;
                if (TypeUtil.isArrayType(returnType)) {
                    dim = TypeUtil.getArrayTypeDimension(returnType);
                    returnType = TypeUtil.getArrayElementType(returnType);
                    if (isGenericType(returnType)) {
                        returnType = "Object";
                    }

                }
                if (TypeUtil.isPrimitiveType(returnType)) {
                    String descriptor = TypeUtil.getDescriptor(returnType);
                    returnTypeType = Type.getType(TypeUtil.getArrayDescriptor(descriptor, dim));

                } else {
                    int arrowPos = returnType.indexOf("<");
                    if (arrowPos != -1) {
                        returnType = returnType.substring(0, arrowPos);
                    }
                    ClassNode stub = scopeStack.peek().findStub(returnType);
                    if (stub == null) {
                        System.out.println("Type params is " + mt.getTypeParameters());
                        System.out.println("Type kind is " + mt.getReturnType().getKind());
                        throw new RuntimeException("Could not find class for " + returnType);
                    }

                    returnTypeType = Type.getObjectType(stub.name);
                    returnTypeType = Type
                            .getType(TypeUtil.getArrayDescriptor(returnTypeType.getInternalName(), dim));

                }

                String methodDescriptor = null;
                if (argTypes.isEmpty()) {
                    methodDescriptor = Type.getMethodDescriptor(returnTypeType);
                } else {
                    methodDescriptor = Type.getMethodDescriptor(returnTypeType, argTypes.toArray(new Type[0]));
                }

                int flags = getFlags(mt.getModifiers().getFlags());
                if (isVarArgs) {
                    flags |= Opcodes.ACC_VARARGS;
                    //System.out.println("VarArgs "+flags);
                }
                classWriter.visitMethod(flags, mt.getName().toString(), methodDescriptor, methodSignature,
                        null);

            }
            //methodStack.push(mt);
            //Object out= super.visitMethod(mt, p); 
            //methodStack.pop();
            return null;
        }

        //private boolean LinkedList<MethodTree> methodStack  =new LinkedList<>();
        @Override
        public Object visitVariable(VariableTree vt, Object p) {

            ClassWriter classWriter = cwStack.peek();

            String varType = vt.getType().toString();
            if (isGenericType(varType)) {
                varType = "Object";
            }
            String signature = null;
            try {
                signature = TypeUtil.getTypeSignature(varType, scopeStack.peek());
            } catch (Exception ex) {
                System.out.println("Failed to generate signature for type " + varType);
            }
            int dim = 0;

            Type varTypeType = null;
            if (TypeUtil.isArrayType(varType)) {
                dim = TypeUtil.getArrayTypeDimension(varType);
                varType = TypeUtil.getArrayElementType(varType);

            }
            if (TypeUtil.isPrimitiveType(varType)) {
                String descriptor = TypeUtil.getDescriptor(varType);
                varTypeType = Type.getType(TypeUtil.getArrayDescriptor(descriptor, dim));

            } else {
                int arrowPos = varType.indexOf("<");
                if (arrowPos != -1) {
                    varType = varType.substring(0, arrowPos);
                }
                ClassNode stub = scopeStack.peek().findStub(varType);
                if (stub == null) {
                    throw new RuntimeException("Could not find class for " + varType);
                }

                varTypeType = Type.getObjectType(stub.name);
                varTypeType = Type.getType(TypeUtil.getArrayDescriptor(varTypeType.getInternalName(), dim));

            }

            classWriter.visitField(getFlags(vt.getModifiers().getFlags()), vt.getName().toString(),
                    varTypeType.toString(), signature, null);

            return super.visitVariable(vt, p); //To change body of generated methods, choose Tools | Templates.
        }

        boolean isGenericType(String type) {
            for (List<? extends TypeParameterTree> types : typeParametersStack) {
                for (TypeParameterTree tree : types) {
                    if (type.equals(tree.getName().toString())) {
                        return true;
                    }
                }
            }
            return false;
        }

        /**
         * Converts modifier flags from Javac Tree into int flags usable in 
         * TypeMirror
         * @param mods
         * @return 
         */
        int getFlags(Set<Modifier> mods) {
            int flags = 0;
            for (Modifier m : mods) {
                switch (m) {
                case ABSTRACT:
                    flags |= Opcodes.ACC_ABSTRACT;
                    break;
                case FINAL:
                    flags |= Opcodes.ACC_FINAL;
                    break;
                case PRIVATE:
                    flags |= Opcodes.ACC_PRIVATE;
                    break;
                case PROTECTED:
                    flags |= Opcodes.ACC_PROTECTED;
                    break;
                case PUBLIC:

                    flags |= Opcodes.ACC_PUBLIC;
                    break;
                case STATIC:
                    flags |= Opcodes.ACC_STATIC;
                    break;

                }
            }

            return flags;
        }

        @Override
        public Object visitClass(ClassTree ct, Object p) {
            //System.out.println("Visiting class "+ct);
            //System.out.println("Type parameters: "+ct.getTypeParameters());
            typeParametersStack.push(ct.getTypeParameters());
            String simpleName = ct.getSimpleName().toString();
            String internalName = getThisInternalName(simpleName);
            int lastDollar = internalName.lastIndexOf("$");
            String externalName = lastDollar == -1 ? null : internalName.substring(0, lastDollar);
            String supername = "java.lang.Object";
            String[] interfaces = null;
            boolean targetClass = false;
            if (!cwStack.isEmpty()) {
                cwStack.peek().visitInnerClass(internalName, externalName, simpleName,
                        getFlags(ct.getModifiers().getFlags()));
            }

            targetClass = true;
            // This is the one that we'
            //String supername = "java.lang.Object";
            if (ct.getExtendsClause() != null) {
                supername = ct.getExtendsClause().toString().trim();
            }
            String unresolvedSuperName = supername;

            int bracketPos = supername.indexOf("<");
            supername = bracketPos == -1 ? supername : supername.substring(0, bracketPos);
            ClassNode node = scopeStack.peek().findStub(supername);
            if (node == null) {
                throw new RuntimeException("Could not find super stub " + supername);
            }
            supername = node.name;

            String impl = ct.getImplementsClause().toString();
            String[] unresolvedInterfaces = null;
            if (impl != null && !"".equals(impl)) {
                interfaces = impl.split(",");
                unresolvedInterfaces = new String[interfaces.length];
                for (int i = 0; i < interfaces.length; i++) {

                    String iface = interfaces[i];
                    unresolvedInterfaces[i] = interfaces[i];
                    iface = iface.trim();
                    ClassNode inode = scopeStack.peek().findStub(iface);
                    assert inode != null;
                    if (inode == null) {
                        throw new RuntimeException("Could not find stub for interface " + iface);
                    }
                    System.out.println("interface " + iface);
                    interfaces[i] = inode.name;
                }
            }
            String signature = TypeUtil.getClassSignature(scopeStack.peek(), null, unresolvedSuperName,
                    unresolvedInterfaces);
            int flags = getFlags(ct.getModifiers().getFlags());

            switch (ct.getKind()) {
            case INTERFACE:
                flags |= Opcodes.ACC_INTERFACE;
                break;

            case ENUM:
                flags |= Opcodes.ACC_ENUM;
                break;

            }

            ClassWriter classWriter = new ClassWriter(49);
            classWriter.visit(49, flags, internalName, signature, supername, interfaces

            );
            cwStack.push(classWriter);
            classInfoStack.push(new ClassInfo());
            stack.push(simpleName);
            ClassFinder scope = new ClassFinder(context.get(ClassLoader.class), scopeStack.peek());

            scope.addImport(internalName.replaceAll("/", ".").replaceAll("\\$", ".") + ".*"

            );
            scope.addImport(internalName.replaceAll("/", ".").replaceAll("\\$", "."));
            scope.addImport(supername.replaceAll("/", ".").replaceAll("\\$", ".") + ".*"

            );
            scope.addImport(supername.replaceAll("/", ".").replaceAll("\\$", "."));

            if (interfaces != null) {
                for (int i = 0; i < interfaces.length; i++) {
                    scope.addImport(interfaces[i].replaceAll("/", ".").replaceAll("\\$", ".") + ".*"

                    );
                    scope.addImport(interfaces[i].replaceAll("/", ".").replaceAll("\\$", "."));
                }
            }
            for (TypeParameterTree tpTree : ct.getTypeParameters()) {
                //System.out.println("Name: "+tpTree.getName());
                //System.out.println("Kind: "+tpTree.getKind().name());
                //System.out.println("Bounds: "+tpTree.getBounds());
                String bounds = (tpTree.getBounds() != null && !tpTree.getBounds().isEmpty())
                        ? tpTree.getBounds().get(0).toString()
                        : "java.lang.Object";
                scope.addTypeParameter(tpTree.getName().toString(), bounds);
            }
            scopeStack.push(scope);
            Object out = super.visitClass(ct, p);
            stack.pop();
            scopeStack.pop();
            ClassInfo classInfo = classInfoStack.pop();
            if (classInfo.numConstructors == 0) {
                // there are no declared constructors in this class 
                // we need to add a default constructor.
                cwStack.peek().visitMethod(Opcodes.ACC_PUBLIC, "<init>",
                        Type.getMethodDescriptor(Type.getType("V")), null, null);
                classInfo.numConstructors++;
            }

            if (targetClass) {
                byte[] bytes = cwStack.peek().toByteArray();
                outMap.put(internalName, bytes);
                cwStack.pop();
            }

            typeParametersStack.pop();

            return out;
        }

    };
    scanner.scan(asts, null);
    return outMap;
}

From source file:ca.weblite.netbeans.mirah.lexer.ClassQuery.java

public static List<String> getParameterNames(Class cls, Method constructor, FileObject fo) throws IOException {
    //Class<?> declaringClass = constructor.getDeclaringClass();
    Class declaringClass = cls;/*from  w  w  w .ja  va2 s  . co  m*/
    ClassLoader declaringClassLoader = declaringClass.getClassLoader();
    if (declaringClassLoader == null) {
        cls = findClass(cls.getName(), fo);
        declaringClassLoader = cls.getClassLoader();

    }
    if (declaringClassLoader == null) {
        return null;
    }
    Type declaringType = Type.getType(declaringClass);
    String constructorDescriptor = Type.getMethodDescriptor(constructor);
    String url = declaringType.getInternalName() + ".class";

    InputStream classFileInputStream = declaringClassLoader.getResourceAsStream(url);
    if (classFileInputStream == null) {
        throw new IllegalArgumentException(
                "The constructor's class loader cannot find the bytecode that defined the constructor's class (URL: "
                        + url + ")");
    }

    ClassNode classNode;
    try {
        classNode = new ClassNode();
        ClassReader classReader = new ClassReader(classFileInputStream);
        classReader.accept(classNode, 0);
    } finally {
        classFileInputStream.close();
    }

    @SuppressWarnings("unchecked")
    List<MethodNode> methods = classNode.methods;
    for (MethodNode method : methods) {
        if (method.name.equals(constructor.getName()) && method.desc.equals(constructorDescriptor)) {
            Type[] argumentTypes = Type.getArgumentTypes(method.desc);
            List<String> parameterNames = new ArrayList<String>(argumentTypes.length);
            @SuppressWarnings("unchecked")
            List<LocalVariableNode> localVariables = method.localVariables;
            boolean isStatic = true;
            if (localVariables != null && !localVariables.isEmpty()
                    && localVariables.get(0).name.equals("this")) {
                isStatic = false;
            }
            int offset = isStatic ? 0 : 1;
            for (int i = 0; i < argumentTypes.length; i++) {
                // The first local variable actually represents the "this" object
                try {
                    parameterNames.add(localVariables.get(i + offset).name);
                } catch (NullPointerException npe) {
                    npe.printStackTrace();
                }
            }

            return parameterNames;
        }
    }

    List<String> out = null;
    cls = cls.getSuperclass();
    while (cls != null && out == null) {
        out = getParameterNames(cls, constructor, fo);
        cls = cls.getSuperclass();
    }
    if (out != null) {
        return out;
    }
    return null;
}

From source file:ch.eiafr.cojac.models.DoubleNumbers.java

License:Apache License

/** returns null if such a method does not exist */
public static Method possibleMethod(Object target, String methodName, String desc) {
    if (target == null)
        return null;
    Class<?> clazz = target.getClass();
    //if(methodName.contains("apply")) System.out.println(clazz+" "+methodName+desc);
    Method[] mt = clazz.getMethods();
    for (Method m : mt) {
        if (!m.getName().equals(methodName))
            continue;
        String d = Type.getMethodDescriptor(m);
        if (d.equals(desc)) {
            //System.out.println("-- Found! -- "+methodName+" "+desc+" "+target);
            return m;
        }//ww w.j a  v  a  2  s . c  o  m
    }
    return null;
}

From source file:co.cask.cdap.app.runtime.spark.SparkRunnerClassLoader.java

License:Apache License

/**
 * Define the akka.remote.Remoting by rewriting usages of scala.concurrent.ExecutionContext.Implicits.global
 * to Remoting.system().dispatcher() in the shutdown() method for fixing the Akka thread/permgen leak bug in
 * https://github.com/akka/akka/issues/17729
 *//*  www. j  av  a2  s.  c o  m*/
private Class<?> defineAkkaRemoting(String name, InputStream byteCodeStream)
        throws IOException, ClassNotFoundException {
    final Type dispatcherReturnType = determineAkkaDispatcherReturnType();
    if (dispatcherReturnType == null) {
        LOG.warn("Failed to determine ActorSystem.dispatcher() return type. "
                + "No rewriting of akka.remote.Remoting class. ClassLoader leakage might happen in SDK.");
        return findClass(name);
    }

    ClassReader cr = new ClassReader(byteCodeStream);
    ClassWriter cw = new ClassWriter(0);

    cr.accept(new ClassVisitor(Opcodes.ASM5, cw) {
        @Override
        public MethodVisitor visitMethod(int access, String name, String desc, String signature,
                String[] exceptions) {
            // Call super so that the method signature is registered with the ClassWriter (parent)
            MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);

            // Only rewrite the shutdown() method
            if (!"shutdown".equals(name)) {
                return mv;
            }

            return new MethodVisitor(Opcodes.ASM5, mv) {
                @Override
                public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {
                    // Detect if it is making call "import scala.concurrent.ExecutionContext.Implicits.global",
                    // which translate to Java code as
                    // scala.concurrent.ExecutionContext$Implicits$.MODULE$.global()
                    // hence as bytecode
                    // GETSTATIC scala/concurrent/ExecutionContext$Implicits$.MODULE$ :
                    //           Lscala/concurrent/ExecutionContext$Implicits$;
                    // INVOKEVIRTUAL scala/concurrent/ExecutionContext$Implicits$.global
                    //           ()Lscala/concurrent/ExecutionContextExecutor;
                    if (opcode == Opcodes.INVOKEVIRTUAL && "global".equals(name)
                            && "scala/concurrent/ExecutionContext$Implicits$".equals(owner)
                            && Type.getMethodDescriptor(EXECUTION_CONTEXT_EXECUTOR_TYPE).equals(desc)) {
                        // Discard the GETSTATIC result from the stack by popping it
                        super.visitInsn(Opcodes.POP);
                        // Make the call "import system.dispatch", which translate to Java code as
                        // this.system().dispatcher()
                        // hence as bytecode
                        // ALOAD 0 (load this)
                        // INVOKEVIRTUAL akka/remote/Remoting.system ()Lakka/actor/ExtendedActorSystem;
                        // INVOKEVIRTUAL akka/actor/ExtendedActorSystem.dispatcher ()Lscala/concurrent/ExecutionContextExecutor;
                        Type extendedActorSystemType = Type.getObjectType("akka/actor/ExtendedActorSystem");
                        super.visitVarInsn(Opcodes.ALOAD, 0);
                        super.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "akka/remote/Remoting", "system",
                                Type.getMethodDescriptor(extendedActorSystemType), false);
                        super.visitMethodInsn(Opcodes.INVOKEVIRTUAL, extendedActorSystemType.getInternalName(),
                                "dispatcher", Type.getMethodDescriptor(dispatcherReturnType), false);
                    } else {
                        // For other instructions, just call parent to deal with it
                        super.visitMethodInsn(opcode, owner, name, desc, itf);
                    }
                }
            };
        }
    }, ClassReader.EXPAND_FRAMES);

    byte[] byteCode = cw.toByteArray();
    return defineClass(name, byteCode, 0, byteCode.length);
}

From source file:co.paralleluniverse.common.util.ExtendedStackTrace.java

License:Open Source License

protected static final String getDescriptor(Member m) {
    if (m instanceof Constructor)
        return Type.getConstructorDescriptor((Constructor) m);
    return Type.getMethodDescriptor((Method) m);
}

From source file:co.paralleluniverse.data.record.DynamicGeneratedRecord.java

License:Open Source License

private static byte[] generateMethodAccessor(Class<?> type, Field<?, ?> field, Method getter, Method setter) {
    final String typeName = Type.getInternalName(type);
    final String fieldTypeName = Type.getInternalName(field.typeClass());
    final String fieldTypeDesc = Type.getDescriptor(field.typeClass());
    final String accName = accessorName(field) + "Accessor";

    ClassWriter cw = generateClass(type, field, accName);
    MethodVisitor mv;//from www.j  a v a2 s. c om

    mv = cw.visitMethod(ACC_PUBLIC, "get", "(Ljava/lang/Object;)" + methodSigTypeDesc(field), null, null);
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 1);
    mv.visitTypeInsn(CHECKCAST, typeName);
    mv.visitMethodInsn(INVOKEVIRTUAL, typeName, getter.getName(), Type.getMethodDescriptor(getter));
    mv.visitInsn(returnOpcode(field));
    mv.visitEnd();

    mv = cw.visitMethod(ACC_PUBLIC, "set", "(Ljava/lang/Object;" + methodSigTypeDesc(field) + ")V", null, null);
    mv.visitCode();

    if (setter != null) {
        mv.visitVarInsn(ALOAD, 1);
        mv.visitTypeInsn(CHECKCAST, typeName);
        mv.visitVarInsn(loadOpcode(field), 2);
        if (field instanceof Field.ObjectField)
            mv.visitTypeInsn(CHECKCAST, fieldTypeName);
        mv.visitMethodInsn(INVOKEVIRTUAL, typeName, setter.getName(), Type.getMethodDescriptor(setter));
        mv.visitInsn(RETURN);
    } else {
        mv.visitTypeInsn(NEW, Type.getInternalName(ReadOnlyFieldException.class));
        mv.visitInsn(DUP);
        mv.visitLdcInsn(field.name);
        mv.visitVarInsn(ALOAD, 1);
        mv.visitMethodInsn(INVOKESPECIAL, Type.getInternalName(ReadOnlyFieldException.class), "<init>",
                "(Ljava/lang/String;Ljava/lang/Object;)V");
        mv.visitInsn(ATHROW);
    }
    mv.visitEnd();

    cw.visitEnd();

    return cw.toByteArray();
}

From source file:co.paralleluniverse.data.record.DynamicGeneratedRecord.java

License:Open Source License

private static byte[] generateIndexedAccessor(Class<?> type, Field<?, ?> field, Method getter, Method setter) {
    final String typeName = Type.getInternalName(type);
    final String fieldComponentTypeName = Type.getInternalName(field.typeClass().getComponentType());
    final String fieldTypeDesc = Type.getDescriptor(field.typeClass());
    final String accName = accessorName(field) + "IndexedAccessor";

    ClassWriter cw = generateClass(type, field, accName);
    MethodVisitor mv;//from   w ww.  j ava 2s .co  m

    mv = cw.visitMethod(ACC_PUBLIC, "get", "(Ljava/lang/Object;I)" + methodSigComponentTypeDesc(field), null,
            null);
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 1);
    mv.visitTypeInsn(CHECKCAST, typeName);
    mv.visitVarInsn(ILOAD, 2);
    mv.visitMethodInsn(INVOKEVIRTUAL, typeName, getter.getName(), Type.getMethodDescriptor(getter));
    mv.visitInsn(returnOpcode(field));
    mv.visitEnd();

    mv = cw.visitMethod(ACC_PUBLIC, "set", "(Ljava/lang/Object;I" + methodSigComponentTypeDesc(field) + ")V",
            null, null);
    mv.visitCode();
    if (setter != null) {
        mv.visitVarInsn(ALOAD, 1);
        mv.visitTypeInsn(CHECKCAST, typeName);
        mv.visitVarInsn(ILOAD, 2);
        mv.visitVarInsn(loadOpcode(field), 3);
        if (field instanceof Field.ObjectArrayField)
            mv.visitTypeInsn(CHECKCAST, fieldComponentTypeName);
        mv.visitMethodInsn(INVOKEVIRTUAL, typeName, setter.getName(), Type.getMethodDescriptor(setter));
        mv.visitInsn(RETURN);
    } else {
        mv.visitTypeInsn(NEW, Type.getInternalName(ReadOnlyFieldException.class));
        mv.visitInsn(DUP);
        mv.visitLdcInsn(field.name);
        mv.visitVarInsn(ALOAD, 1);
        mv.visitMethodInsn(INVOKESPECIAL, Type.getInternalName(ReadOnlyFieldException.class), "<init>",
                "(Ljava/lang/String;Ljava/lang/Object;)V");
        mv.visitInsn(ATHROW);
    }
    mv.visitEnd();

    cw.visitEnd();

    return cw.toByteArray();
}

From source file:co.paralleluniverse.pulsar.ClojureHelper.java

License:Open Source License

public static Object retransform(Object thing) throws UnmodifiableClassException {
    final Class clazz;
    if (thing instanceof IFn)
        clazz = thing.getClass();//from ww w  . j a  va  2  s. c om
    else if (thing instanceof Class)
        clazz = (Class) thing;
    else
        throw new IllegalArgumentException(
                "Not a class or an IFn: " + thing + " (type: " + thing.getClass() + ")");
    if (!(IFn.class.isAssignableFrom(clazz)))
        throw new IllegalArgumentException("Class " + clazz + " does not implement IFn");

    if (clazz.isAnnotationPresent(Instrumented.class))
        return thing;

    try {
        // Clojure might break up a single function into several classes. We must instrument them all.
        for (Map.Entry<String, ClassEntry> entry : Retransform.getMethodDB()
                .getInnerClassesEntries(Type.getInternalName(clazz)).entrySet()) {
            final String className = entry.getKey();
            final ClassEntry ce = entry.getValue();
            final Class cls = Class.forName(className.replaceAll("/", "."), false, clazz.getClassLoader());
            //System.out.println("---- " + cls + " " + IFn.class.isAssignableFrom(cls));
            ce.setRequiresInstrumentation(true);
            Method[] methods = cls.getMethods();
            for (Method method : methods) {
                if (method.getName().equals("invoke") || method.getName().equals("doInvoke"))
                    ce.set(method.getName(), Type.getMethodDescriptor(method), true);
            }
            Retransform.retransform(cls);
        }
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
    return thing;
}

From source file:com.asakusafw.dag.compiler.builtin.BranchOperatorGenerator.java

License:Apache License

static void branch(MethodVisitor method, Context context, UserOperator operator, LocalVarRef input,
        Map<OperatorProperty, FieldRef> dependencies) {
    OperatorOutput[] outputs = outputs(context, operator);
    Label[] caseLabels = Stream.of(outputs).map(o -> new Label()).toArray(Label[]::new);
    Label defaultLabel = new Label();
    Label endLabel = new Label();

    method.visitMethodInsn(Opcodes.INVOKEVIRTUAL, typeOf(Enum.class).getInternalName(), "ordinal",
            Type.getMethodDescriptor(Type.INT_TYPE), false);
    method.visitTableSwitchInsn(0, caseLabels.length - 1, defaultLabel, caseLabels);

    for (int i = 0; i < outputs.length; i++) {
        method.visitLabel(caseLabels[i]);
        FieldRef ref = Invariants.requireNonNull(dependencies.get(outputs[i]));
        ref.load(method);//from w  ww .ja v  a 2 s  .co m
        input.load(method);
        invokeResultAdd(method);
        method.visitJumpInsn(Opcodes.GOTO, endLabel);
    }
    method.visitLabel(defaultLabel);
    getNew(method, Descriptions.typeOf(AssertionError.class));
    method.visitInsn(Opcodes.ATHROW);

    method.visitLabel(endLabel);
}

From source file:com.asakusafw.dag.compiler.builtin.FoldOperatorGenerator.java

License:Apache License

private ClassData generateSimpleClass(Context context, UserOperator operator, ClassDescription target) {
    TypeDescription dataType = operator.getInput(Fold.ID_INPUT).getDataType();

    ClassWriter writer = newWriter(target, SimpleCombineResult.class);
    FieldRef impl = defineOperatorField(writer, operator, target);
    FieldRef acc = defineField(writer, target, "acc", typeOf(dataType)); //$NON-NLS-1$
    Map<OperatorProperty, FieldRef> map = defineConstructor(context, operator, target, writer, method -> {
        method.visitVarInsn(Opcodes.ALOAD, 0);
        method.visitMethodInsn(Opcodes.INVOKESPECIAL,
                AsmUtil.typeOf(SimpleCombineResult.class).getInternalName(), CONSTRUCTOR_NAME,
                Type.getMethodDescriptor(Type.VOID_TYPE), false);

        setOperatorField(method, operator, impl);

        method.visitVarInsn(Opcodes.ALOAD, 0);
        getNew(method, dataType);/*w  ww  . j a  va2s  .c  o  m*/
        putField(method, acc);
    }, method -> Lang.pass());
    defineSimpleStart(operator, writer, acc);
    defineSimpleCombine(context, operator, writer, impl, acc, map);
    defineSimpleFinish(writer, acc, map.get(operator.getOutput(Fold.ID_OUTPUT)));
    return new ClassData(target, writer::toByteArray);
}