Example usage for org.objectweb.asm Opcodes PUTSTATIC

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

Introduction

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

Prototype

int PUTSTATIC

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

Click Source Link

Usage

From source file:lapin.comp.asm.ASMByteCodeGenerator.java

License:Open Source License

private void generateCall(CallableInfo ci, Env env) {
    /*//from w  ww.j a  v a 2  s.c  o  m
     * local variables
     * <Callable#call>
     * 0: this
     * 1: args (list of arguments)
     * 2: env
     *
     * <Callable0#call0>
     * 0: this
     * 1: env
     *
     * <Callable1#call1>
     * 0: this
     * 1: arg0
     * 2: env
     *
     * <Callable2#call2>
     * 0: this
     * 1: arg0
     * 2: arg1
     * 3: env
     *
     * ...
     *
     */
    MethodVisitor mv = _cw.visitMethod(
            ci.mi.implCallable() ? Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL : Opcodes.ACC_FINAL, ci.mi.name(),
            Type.getMethodDescriptor(ci.retType, ci.paramTypes), null, null);

    // instruction list
    int len = ci.mi.instLen();
    // label
    Label label = null;

    // generate code
    for (int i = 0; i < len; i++) {
        Object inst = ci.mi.getInst(i);
        if (Logger.tracelevelp(env))
            Logger.trace("[asm:gen]" + i + ":\t~S", Lists.list(inst), env);

        // inst is symbol
        // -> convert tag (Symbol) to label (ASMe Label object)
        if (Data.isSymbol(inst)) {
            Symbol tag = Data.symbol(inst);
            Label l = (Label) ci.labelTable.get(tag);
            if (l == null) {
                throw new NotReachedException("label is null: ~S.", Lists.list(tag));
            } else if (l != label) {
                mv.visitLabel(l);
                label = l;
                if (Logger.tracelevelp(env))
                    Logger.trace("[asm:gen]" + i + ":\ttag ~S -> label ~S", Lists.list(tag, l), env);
            } else {
                if (Logger.tracelevelp(env))
                    Logger.trace("[asm:gen]" + i + ":\ttag ~S -> label ~S" + " (dup)", Lists.list(tag, l), env);
            }
            continue;
        }

        // inst must be the form of (id <arg1> <arg2> ....)
        Object id = Lists.car(inst);
        if (id == Insts.CONST) {
            /* push const on the stack. */
            Object obj = Lists.cadr(inst);
            String val = Data.string(constTable.get(obj));
            mv.visitVarInsn(Opcodes.ALOAD, 0);
            mv.visitFieldInsn(Opcodes.GETFIELD, toInternalName(super.classInfo.classname()), val,
                    TYPE_OBJECT.getDescriptor());
        } else if (id == Insts.VAR) {
            /* push var on the stack */
            Object var = Lists.cadr(inst);
            String val = Data.string(varTable.get(var));
            mv.visitVarInsn(Opcodes.ALOAD, 0);
            mv.visitFieldInsn(Opcodes.GETFIELD, toInternalName(super.classInfo.classname()), val,
                    TYPE_SYMBOL.getDescriptor());
        } else if (id == Insts.LAMBDA_LIST) {
            /* push lambdaList on the stack */
            Object var = Lists.cadr(inst);
            /* push _ll_<i> on the stack */
            String val = Data.string(llTable.get(var));
            mv.visitVarInsn(Opcodes.ALOAD, 0);
            mv.visitFieldInsn(Opcodes.GETFIELD, toInternalName(super.classInfo.classname()), val,
                    TYPE_LAMBDA_LIST.getDescriptor());
        } else if (id == Insts.ENV_GET) {
            /* env.get */
            Class type = Data.javaClass(Lists.cadr(inst));
            if (type.equals(int.class)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "getInt",
                        Type.getMethodDescriptor(Type.INT_TYPE, new Type[] { TYPE_SYMBOL }));
            } else if (type.equals(double.class)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "getDouble",
                        Type.getMethodDescriptor(Type.DOUBLE_TYPE, new Type[] { TYPE_SYMBOL }));
            } else if (type.equals(char.class)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "getChar",
                        Type.getMethodDescriptor(Type.CHAR_TYPE, new Type[] { TYPE_SYMBOL }));
            } else if (Object.class.isAssignableFrom(type)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "get",
                        Type.getMethodDescriptor(TYPE_OBJECT, new Type[] { TYPE_SYMBOL }));
            } else {
                throw new NotReachedException("unsupported type: ~S.", Lists.list(type));
            }
        } else if (id == Insts.ENV_SET) {
            /* env.set */
            Class type = Data.javaClass(Lists.cadr(inst));
            if (type.equals(int.class)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "set",
                        Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { TYPE_SYMBOL, Type.INT_TYPE }));
            } else if (type.equals(double.class)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "set",
                        Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { TYPE_SYMBOL, Type.DOUBLE_TYPE }));
            } else if (type.equals(char.class)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "set",
                        Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { TYPE_SYMBOL, Type.CHAR_TYPE }));
            } else if (Object.class.isAssignableFrom(type)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "set",
                        Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { TYPE_SYMBOL, TYPE_OBJECT }));
            } else {
                throw new NotReachedException("unsupported type: ~S.", Lists.list(type));
            }
        } else if (id == Insts.ENV_BIND) {
            /* env.bind */
            Class type = Data.javaClass(Lists.cadr(inst));
            if (type.equals(int.class)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "bind",
                        Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { TYPE_SYMBOL, Type.INT_TYPE }));
            } else if (type.equals(double.class)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "bind",
                        Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { TYPE_SYMBOL, Type.DOUBLE_TYPE }));
            } else if (type.equals(char.class)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "bind",
                        Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { TYPE_SYMBOL, Type.CHAR_TYPE }));
            } else if (Object.class.isAssignableFrom(type)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "bind",
                        Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { TYPE_SYMBOL, TYPE_OBJECT }));
            } else {
                throw new NotReachedException("unsupported type: ~S.", Lists.list(type));
            }
        } else if (id == Insts.ENV_UNBIND) {
            /* env.unbind */
            Class type = Data.javaClass(Lists.cadr(inst));
            if (type.equals(int.class)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "unbindInt",
                        Type.getMethodDescriptor(Type.INT_TYPE, new Type[] { TYPE_SYMBOL }));
            } else if (type.equals(double.class)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "unbindDouble",
                        Type.getMethodDescriptor(Type.DOUBLE_TYPE, new Type[] { TYPE_SYMBOL }));
            } else if (type.equals(char.class)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "unbindChar",
                        Type.getMethodDescriptor(Type.CHAR_TYPE, new Type[] { TYPE_SYMBOL }));
            } else if (Object.class.isAssignableFrom(type)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "unbind",
                        Type.getMethodDescriptor(TYPE_OBJECT, new Type[] { TYPE_SYMBOL }));
            } else {
                throw new NotReachedException("unsupported type: ~S.", Lists.list(type));
            }
        } else if (id == Insts.ENV_CHILD) {
            /* env.child */
            Object oldEnvVar = Lists.cadr(inst);
            Object newEnvVar = Lists.caddr(inst);
            Object oldSlot = Lists.cadr(oldEnvVar);
            Object newSlot = Lists.cadr(newEnvVar);
            int oldLocal = Data.fixnum(ci.localTable.get(oldSlot)).intValue();
            int newLocal = Data.fixnum(ci.localTable.get(newSlot)).intValue();
            if (Logger.tracelevelp(env))
                Logger.trace("[asm:gen]" + i + ":\tenv-child: local ~S -> ~S",
                        Lists.list(Data.toFixnum(oldLocal), Data.toFixnum(newLocal)), env);
            mv.visitVarInsn(Opcodes.ALOAD, oldLocal);
            mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "child",
                    Type.getMethodDescriptor(TYPE_ENV, TYPE_NO_ARGS));
            mv.visitVarInsn(Opcodes.ASTORE, newLocal);
        } else if (id == Insts.CALL) {
            /* funcall */
            int nargs = Data.fixnum(Lists.cadr(inst)).intValue();
            String className = "lapin.eval.Funcall";
            String methodName = nargs < 0 ? "funcall" : "funcall" + nargs;
            Class rType = Object.class;
            Class[] pTypes;
            if (nargs < 0) {
                pTypes = new Class[] { Function.class, Object.class, // list of args
                        Env.class };
            } else {
                pTypes = new Class[nargs + 2];
                pTypes[0] = Function.class;
                for (int j = 0; j < nargs; j++) {
                    pTypes[j + 1] = Object.class;
                }
                pTypes[nargs + 1] = Env.class;
            }

            Type retType = Type.getType(rType);
            Type[] paramTypes = new Type[pTypes.length];
            for (int j = 0; j < pTypes.length; j++)
                paramTypes[j] = Type.getType(pTypes[j]);

            mv.visitMethodInsn(Opcodes.INVOKESTATIC, toInternalName(className), methodName,
                    Type.getMethodDescriptor(retType, paramTypes));
        } else if (id == Insts.CALL_DIRECT) {
            /*
             * public class Foo
             *   extends CompiledExpr implements Callable2 {
             *  public Object call2(Object arg0, Object arg1, Env env) {
             *   ...
             *  }
             * }
             */
            MethodInfo mi = (MethodInfo) Lists.cadr(inst);
            String className = mi.classInfo().classname();
            int nargs = mi.nargs();
            boolean rest = mi.rest();
            String methodName = mi.name();
            Class rType = mi.retType();
            Class[] pTypes = mi.paramTypes();

            Type retType = Type.getType(rType);
            Type[] paramTypes = new Type[pTypes.length];
            for (int j = 0; j < pTypes.length; j++)
                paramTypes[j] = Type.getType(pTypes[j]);

            mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, toInternalName(className), methodName,
                    Type.getMethodDescriptor(retType, paramTypes));
        } else if (id == Insts.COMPILED_EXPR) {
            /*
             * public class Foo extends CompiledExpr {
             *  static public Foo SELF;
             *  ...
             * }
             */
            String className = Data.string(Lists.cadr(inst));
            String fieldName = "SELF";
            String typeName = className;
            mv.visitFieldInsn(Opcodes.GETSTATIC, toInternalName(className), fieldName,
                    toTypeDescriptor(typeName));
        } else if (id == Insts.RETURN) {
            /* return */
            Class type = Data.javaClass(Lists.cadr(inst));
            if (type.equals(int.class) || type.equals(short.class) || type.equals(byte.class)
                    || type.equals(char.class)) {
                mv.visitInsn(Opcodes.IRETURN);
            } else if (type.equals(long.class)) {
                mv.visitInsn(Opcodes.LRETURN);
            } else if (type.equals(float.class)) {
                mv.visitInsn(Opcodes.FRETURN);
            } else if (type.equals(double.class)) {
                mv.visitInsn(Opcodes.DRETURN);
            } else if (type.equals(void.class)) {
                //mv.visitInsn(Opcodes.RETURN);
                throw new NotReachedException("unsupported returnType: ~S.", Lists.list(type));
            } else {
                mv.visitInsn(Opcodes.ARETURN);
            }
        } else if (id == Insts.IFEQ) {
            /* conditional jump */
            Symbol tag = Data.symbol(Lists.cadr(inst));
            Label l = (Label) ci.labelTable.get(tag);
            if (l == null) {
                throw new NotReachedException("label not found: ~S.", Lists.list(tag));
            }
            mv.visitJumpInsn(Opcodes.IFEQ, l);
        } else if (id == Insts.IFNE) {
            /* conditional jump */
            Symbol tag = Data.symbol(Lists.cadr(inst));
            Label l = (Label) ci.labelTable.get(tag);
            if (l == null) {
                throw new NotReachedException("label not found: ~S.", Lists.list(tag));
            }
            mv.visitJumpInsn(Opcodes.IFNE, l);
        } else if (id == Insts.GOTO) {
            /* jump */
            Symbol tag = Data.symbol(Lists.cadr(inst));
            Label l = (Label) ci.labelTable.get(tag);
            if (l == null) {
                throw new NotReachedException("label not found: ~S.", Lists.list(tag));
            }
            mv.visitJumpInsn(Opcodes.GOTO, l);
        } else if (id == Insts.LOAD) {
            /* local -> stack */
            Object localVar = Lists.cadr(inst);
            Object slot = Lists.cadr(localVar);
            Class type = Data.javaClass(Lists.caddr(localVar));
            int local = Data.fixnum(ci.localTable.get(slot)).intValue();
            int op = Type.getType(type).getOpcode(Opcodes.ILOAD);
            if (Logger.tracelevelp(env))
                Logger.trace("[asm:gen]" + i + ":\tload: local=~S type=~S",
                        Lists.list(Data.toFixnum(local), type), env);
            mv.visitVarInsn(op, local);
        } else if (id == Insts.STORE) {
            /* stack -> local */
            Object localVar = Lists.cadr(inst);
            Object slot = Lists.cadr(localVar);
            Class type = Data.javaClass(Lists.caddr(localVar));
            int local = Data.fixnum(ci.localTable.get(slot)).intValue();
            int op = Type.getType(type).getOpcode(Opcodes.ISTORE);
            if (Logger.tracelevelp(env))
                Logger.trace("[asm:gen]" + i + ":\tstore: local=~S type=~S",
                        Lists.list(Data.toFixnum(local), type), env);
            mv.visitVarInsn(op, local);
        } else if (id == Insts.POP) {
            /* pop a value and discard it */
            Class type = Data.javaClass(Lists.cadr(inst));
            int op;
            switch (Classes.sizeOf(type)) {
            case 1:
                op = Opcodes.POP;
                break;
            case 2:
                op = Opcodes.POP2;
                break;
            default:
                throw new NotReachedException("unsupported type: ~S.", Lists.list(type));
            }
            mv.visitInsn(op);
        } else if (id == Insts.DUP) {
            /* peek a value and duplicate it */
            Class type = Data.javaClass(Lists.cadr(inst));
            int op;
            switch (Classes.sizeOf(type)) {
            case 1:
                op = Opcodes.DUP;
                break;
            case 2:
                op = Opcodes.DUP2;
                break;
            default:
                throw new NotReachedException("unsupported type: ~S.", Lists.list(type));
            }
            mv.visitInsn(op);
        } else if (id == Insts.PUSH) {
            /* push a constant */
            Object val = Lists.cadr(inst);
            if (Data.isJavaBoolean(val)) {
                if (Data.javaBoolean(val).booleanValue())
                    mv.visitInsn(Opcodes.ICONST_1);
                else
                    mv.visitInsn(Opcodes.ICONST_0);
            } else if (val instanceof Byte || val instanceof Short || val instanceof Integer) {
                int n = Data.javaNumber(val).intValue();
                if (n == -1)
                    mv.visitInsn(Opcodes.ICONST_M1);
                else if (n == 0)
                    mv.visitInsn(Opcodes.ICONST_0);
                else if (n == 1)
                    mv.visitInsn(Opcodes.ICONST_1);
                else if (n == 2)
                    mv.visitInsn(Opcodes.ICONST_2);
                else if (n == 3)
                    mv.visitInsn(Opcodes.ICONST_3);
                else if (n == 4)
                    mv.visitInsn(Opcodes.ICONST_4);
                else if (n == 5)
                    mv.visitInsn(Opcodes.ICONST_5);
                else if (Byte.MIN_VALUE <= n && n <= Byte.MAX_VALUE)
                    mv.visitIntInsn(Opcodes.BIPUSH, n);
                else if (Short.MIN_VALUE <= n && n <= Short.MAX_VALUE)
                    mv.visitIntInsn(Opcodes.SIPUSH, n);
                else
                    mv.visitLdcInsn(Data.toFixnum(n));
            } else if (val instanceof Long) {
                long n = Data.javaNumber(val).longValue();
                if (n == 0L)
                    mv.visitInsn(Opcodes.LCONST_0);
                else if (n == 1L)
                    mv.visitInsn(Opcodes.LCONST_1);
                else
                    mv.visitLdcInsn(val);
            } else if (val instanceof Float) {
                float n = Data.javaNumber(val).floatValue();
                if (n == 0.0f)
                    mv.visitInsn(Opcodes.FCONST_0);
                else if (n == 1.0f)
                    mv.visitInsn(Opcodes.FCONST_1);
                else if (n == 2.0f)
                    mv.visitInsn(Opcodes.FCONST_2);
                else
                    mv.visitLdcInsn(val);
            } else if (val instanceof Double) {
                double n = Data.javaNumber(val).doubleValue();
                if (n == 0.0)
                    mv.visitInsn(Opcodes.DCONST_0);
                else if (n == 1.0)
                    mv.visitInsn(Opcodes.DCONST_1);
                else
                    mv.visitLdcInsn(val);
            } else if (Data.isCharacter(val)) {
                Character c = Data.character(val);
                int n = (int) c.charValue();
                if (Byte.MIN_VALUE <= n && n <= Byte.MAX_VALUE)
                    mv.visitIntInsn(Opcodes.BIPUSH, n);
                else if (Short.MIN_VALUE <= n && n <= Short.MAX_VALUE)
                    mv.visitIntInsn(Opcodes.SIPUSH, n);
                else
                    mv.visitLdcInsn(Data.toFixnum(n));
            } else if (Data.isString(val)) {
                mv.visitLdcInsn(val);
            } else {
                throw new NotReachedException("cannot push: ~S.", Lists.list(val));
            }
        } else if (id == Insts.GET) {
            Field f = Data.javaField(Lists.cadr(inst));
            String fieldName = f.getName();
            Class c = f.getDeclaringClass();
            String className = c.getName();
            Class t = f.getType();
            String typeName = t.getName();

            boolean isStatic = Classes.isStatic(f);
            int op = isStatic ? Opcodes.GETSTATIC : Opcodes.GETFIELD;

            mv.visitFieldInsn(op, toInternalName(className), fieldName, toTypeDescriptor(typeName));
        } else if (id == Insts.PUT) {
            Field f = Data.javaField(Lists.cadr(inst));
            String fieldName = f.getName();
            Class c = f.getDeclaringClass();
            String className = c.getName();
            Class t = f.getType();
            String typeName = t.getName();

            boolean isStatic = Classes.isStatic(f);
            int op = isStatic ? Opcodes.PUTSTATIC : Opcodes.PUTFIELD;

            mv.visitFieldInsn(op, toInternalName(className), fieldName, toTypeDescriptor(typeName));
        } else if (id == Insts.INVOKE) {
            Method m = Data.javaMethod(Lists.cadr(inst));
            String methodName = m.getName();
            Class c = m.getDeclaringClass();
            String className = c.getName();
            Class rType = m.getReturnType();
            Class[] pTypes = m.getParameterTypes();
            if (rType.equals(void.class)) {
                throw new NotReachedException("unsupported returnType: ~S.", Lists.list(rType));
            }
            Type retType = Type.getType(rType);
            Type[] paramTypes = new Type[pTypes.length];
            for (int j = 0; j < pTypes.length; j++)
                paramTypes[j] = Type.getType(pTypes[j]);

            boolean isStatic = Classes.isStatic(m);
            boolean isInterface = c.isInterface();
            int op = isStatic ? Opcodes.INVOKESTATIC
                    : isInterface ? Opcodes.INVOKEINTERFACE : Opcodes.INVOKEVIRTUAL;

            mv.visitMethodInsn(op, toInternalName(className), methodName,
                    Type.getMethodDescriptor(retType, paramTypes));
        } else if (id == Insts.CHECKCAST) {
            Class c = Data.javaClass(Lists.cadr(inst));
            Type t = Type.getType(c);
            mv.visitTypeInsn(Opcodes.CHECKCAST, t.getInternalName());
        } else if (id == Insts.THROW) {
            mv.visitInsn(Opcodes.ATHROW);
        } else if (id == Insts.CATCH) {
            Symbol tagS = Data.symbol(Lists.cadr(inst));
            Symbol tagE = Data.symbol(Lists.caddr(inst));
            Symbol tagH = Data.symbol(Lists.cadddr(inst));
            String className;
            if (Lists.isEnd(Lists.cddddr(inst))) {
                className = null;
            } else {
                Class c = Data.javaClass(Lists.car(Lists.cddddr(inst)));
                className = toInternalName(c.getName());
            }
            Label labelS = (Label) ci.labelTable.get(tagS);
            if (labelS == null) {
                throw new NotReachedException("label not found: ~S.", Lists.list(tagS));
            }
            Label labelE = (Label) ci.labelTable.get(tagE);
            if (labelE == null) {
                throw new NotReachedException("label not found: ~S.", Lists.list(tagE));
            }
            Label labelH = (Label) ci.labelTable.get(tagH);
            if (labelH == null) {
                throw new NotReachedException("label not found: ~S.", Lists.list(tagH));
            }
            mv.visitTryCatchBlock(labelS, labelE, labelH, className);
        }
        //else if (id == Insts.CATCH_FROM ||
        //         id == Insts.CATCH_TO ||
        //         id == Insts.CATCH_HANDLER) {
        //    /* nothing emitted */
        //    continue;
        //}
        else {
            throw new NotReachedException("unknown inst: ~S.", Lists.list(inst));
        }
    }
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}

From source file:local.edg.ClassDbVisitor.java

License:Open Source License

@Override
public void visitFieldInsn(int opcode, String owner, String name, String desc) {
    currentMethod.setEmpty(false);/*from  w  w w . j  a v  a 2s.  c om*/
    Class c;
    Field f;
    switch (opcode) {
    case Opcodes.GETFIELD:
    case Opcodes.GETSTATIC:
        c = getClass(owner);
        f = getField(c, name);
        f.setDesc(desc);
        // read after write is not a real read
        // if (!currentMethod.hasWrite(f)){
        currentMethod.addRead(f);
        // }
        break;
    case Opcodes.PUTFIELD:
    case Opcodes.PUTSTATIC:
        c = getClass(owner);
        f = getField(c, name);
        f.setDesc(desc);
        currentMethod.addWrite(f);
        break;
    }
}

From source file:net.sourceforge.cobertura.instrument.pass3.AtomicArrayCodeProvider.java

License:GNU General Public License

public void generateCINITmethod(MethodVisitor mv, String className, int counters_cnt) {
    mv.visitFieldInsn(Opcodes.GETSTATIC, className, COBERTURA_COUNTERS_FIELD_NAME,
            COBERTURA_COUNTERS_FIELD_TYPE);
    Label l1 = new Label();
    mv.visitJumpInsn(Opcodes.IFNONNULL, l1);

    mv.visitTypeInsn(Opcodes.NEW, Type.getInternalName(AtomicIntegerArray.class));
    mv.visitInsn(Opcodes.DUP);/*from   www . java  2  s .c  o m*/
    mv.visitLdcInsn(counters_cnt);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(AtomicIntegerArray.class), "<init>", "(I)V");
    mv.visitFieldInsn(Opcodes.PUTSTATIC, className, COBERTURA_COUNTERS_FIELD_NAME,
            COBERTURA_COUNTERS_FIELD_TYPE);
    generateRegisterClass(mv, className);
    mv.visitLabel(l1);
}

From source file:net.sourceforge.cobertura.instrument.pass3.FastArrayCodeProvider.java

License:GNU General Public License

public void generateCINITmethod(MethodVisitor mv, String className, int counters_cnt) {
    mv.visitFieldInsn(Opcodes.GETSTATIC, className, COBERTURA_COUNTERS_FIELD_NAME,
            COBERTURA_COUNTERS_FIELD_TYPE);
    Label l1 = new Label();
    mv.visitJumpInsn(Opcodes.IFNONNULL, l1);
    mv.visitLdcInsn(counters_cnt);// w  ww.ja  v a2s  . c o  m
    mv.visitIntInsn(Opcodes.NEWARRAY, Opcodes.T_INT);
    mv.visitFieldInsn(Opcodes.PUTSTATIC, className, COBERTURA_COUNTERS_FIELD_NAME,
            COBERTURA_COUNTERS_FIELD_TYPE);
    generateRegisterClass(mv, className);
    mv.visitLabel(l1);
}

From source file:net.sourceforge.cobertura.instrument.pass3.FastArrayCodeProvider.java

License:GNU General Public License

public void generateCoberturaGetAndResetCountersMethod(ClassVisitor cv, String className) {
    MethodVisitor mv = cv.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC,
            COBERTURA_GET_AND_RESET_COUNTERS_METHOD_NAME, "()[I", null, null);
    mv.visitCode();//from  ww  w  . ja  va  2s  .c o m
    /*cobertura_counters.*/
    mv.visitFieldInsn(Opcodes.GETSTATIC, className, COBERTURA_COUNTERS_FIELD_NAME,
            COBERTURA_COUNTERS_FIELD_TYPE);
    mv.visitVarInsn(Opcodes.ASTORE, 0);
    /*cobertura_counters.*/
    mv.visitFieldInsn(Opcodes.GETSTATIC, className, COBERTURA_COUNTERS_FIELD_NAME,
            COBERTURA_COUNTERS_FIELD_TYPE);
    mv.visitInsn(Opcodes.ARRAYLENGTH);

    mv.visitIntInsn(Opcodes.NEWARRAY, Opcodes.T_INT);
    mv.visitFieldInsn(Opcodes.PUTSTATIC, className, COBERTURA_COUNTERS_FIELD_NAME,
            COBERTURA_COUNTERS_FIELD_TYPE);
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitInsn(Opcodes.ARETURN);
    mv.visitMaxs(0, 0);//will be recalculated by writer
    mv.visitEnd();
}

From source file:net.sourceforge.cobertura.instrument.pass3.TestUnitCodeProvider.java

License:GNU General Public License

/**
 * Generates://from  ww w  .  ja  v  a2s.  c  o m
 *   public static void __cobertura_init()
 *   {
 *     if (__cobertura_counters == null)
 *       {
 *         __cobertura_counters = new TestUnitInformationHolder[class.length];
 *       }
 *       TouchCollector.registerClass("mypackage/HelloWorld");
 *   }
 */
public void generateCINITmethod(MethodVisitor mv, String className, int counters_cnt) {
    mv.visitFieldInsn(Opcodes.GETSTATIC, className, COBERTURA_COUNTERS_FIELD_NAME,
            COBERTURA_COUNTERS_FIELD_TYPE);
    Label l1 = new Label();
    mv.visitJumpInsn(Opcodes.IFNONNULL, l1);
    mv.visitLdcInsn(counters_cnt);
    mv.visitTypeInsn(Opcodes.ANEWARRAY, Type.getInternalName(TestUnitInformationHolder.class));
    mv.visitFieldInsn(Opcodes.PUTSTATIC, className, COBERTURA_COUNTERS_FIELD_NAME,
            COBERTURA_COUNTERS_FIELD_TYPE);

    mv.visitInsn(ICONST_0);
    mv.visitVarInsn(ISTORE, 1);
    Label l11 = new Label();
    mv.visitLabel(l11);
    Label l2 = new Label();
    mv.visitJumpInsn(GOTO, l2);
    Label l3 = new Label();
    mv.visitLabel(l3);
    mv.visitLineNumber(24, l3);
    mv.visitFrame(Opcodes.F_APPEND, 1, new Object[] { Opcodes.INTEGER }, 0, null);
    mv.visitFieldInsn(GETSTATIC, className, COBERTURA_COUNTERS_FIELD_NAME, COBERTURA_COUNTERS_FIELD_TYPE);
    mv.visitVarInsn(ILOAD, 1);
    mv.visitTypeInsn(NEW, "net/sourceforge/cobertura/coveragedata/TestUnitInformationHolder");
    mv.visitInsn(DUP);
    mv.visitMethodInsn(INVOKESPECIAL, "net/sourceforge/cobertura/coveragedata/TestUnitInformationHolder",
            "<init>", "()V");
    mv.visitInsn(AASTORE);
    Label l4 = new Label();
    mv.visitLabel(l4);
    mv.visitLineNumber(23, l4);
    mv.visitIincInsn(1, 1);
    mv.visitLabel(l2);
    mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
    mv.visitVarInsn(ILOAD, 1);
    mv.visitFieldInsn(GETSTATIC, className, COBERTURA_COUNTERS_FIELD_NAME, COBERTURA_COUNTERS_FIELD_TYPE);
    mv.visitInsn(ARRAYLENGTH);
    mv.visitJumpInsn(IF_ICMPLT, l3);

    mv.visitLabel(l1);

    generateRegisterClass(mv, className);
}

From source file:net.sourceforge.cobertura.instrument.pass3.TestUnitCodeProvider.java

License:GNU General Public License

/**
 * Generates:/*from  ww w. j  av  a  2s.com*/
 *   public static TestUnitInformationHolder[] __cobertura_get_and_reset_counters()
 *   {
 *     TestUnitInformationHolder[] local = __cobertura_counters;
 *     __cobertura_counters = new TestUnitInformationHolder[__cobertura_counters.length];
 *     return local;
 *   }
 */
public void generateCoberturaGetAndResetCountersMethod(ClassVisitor cv, String className) {
    MethodVisitor mv = cv.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC,
            COBERTURA_GET_AND_RESET_COUNTERS_METHOD_NAME, "()" + COBERTURA_COUNTERS_FIELD_TYPE, null, null);
    mv.visitCode();
    /*cobertura_counters.*/
    mv.visitFieldInsn(Opcodes.GETSTATIC, className, COBERTURA_COUNTERS_FIELD_NAME,
            COBERTURA_COUNTERS_FIELD_TYPE);
    mv.visitVarInsn(Opcodes.ASTORE, 0);
    /*cobertura_counters.*/
    mv.visitFieldInsn(Opcodes.GETSTATIC, className, COBERTURA_COUNTERS_FIELD_NAME,
            COBERTURA_COUNTERS_FIELD_TYPE);
    mv.visitInsn(Opcodes.ARRAYLENGTH);

    mv.visitTypeInsn(Opcodes.ANEWARRAY, Type.getInternalName(TestUnitInformationHolder.class));
    mv.visitFieldInsn(Opcodes.PUTSTATIC, className, COBERTURA_COUNTERS_FIELD_NAME,
            COBERTURA_COUNTERS_FIELD_TYPE);
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitInsn(Opcodes.ARETURN);
    mv.visitMaxs(0, 0);//will be recalculated by writer
    mv.visitEnd();
}

From source file:net.yrom.tools.RSymbols.java

License:Apache License

private void drainSymbols(Path file) {
    final String filename = file.getFileName().toString();
    String typeName = filename.substring(0, filename.length() - ".class".length());
    byte[] bytes;
    try {//from w ww  .  ja v a 2  s.c  o m
        bytes = Files.readAllBytes(file);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
    ClassVisitor visitor = new ClassVisitor(Opcodes.ASM5) {
        @Override
        public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
            // read constant value
            if (value instanceof Integer) {
                String key = typeName + '.' + name;
                Integer old = symbols.get(key);
                if (old != null && !old.equals(value)) {
                    throw new IllegalStateException("Value of " + key + " mismatched! " + "Excepted 0x"
                            + Integer.toHexString(old) + " but was 0x" + Integer.toHexString((Integer) value));
                } else {
                    symbols.put(key, (Integer) value);
                }
            }
            return null;
        }

        @Override
        public MethodVisitor visitMethod(int access, String name, String desc, String signature,
                String[] exceptions) {
            if (access == Opcodes.ACC_STATIC && "<clinit>".equals(name)) {

                return new MethodVisitor(Opcodes.ASM5) {
                    int[] current = null;
                    LinkedList<Integer> intStack = new LinkedList<>();

                    @Override
                    public void visitIntInsn(int opcode, int operand) {
                        if (opcode == Opcodes.NEWARRAY && operand == Opcodes.T_INT) {
                            current = new int[intStack.pop()];
                        } else if (opcode == Opcodes.BIPUSH) {
                            intStack.push(operand);
                        }
                    }

                    @Override
                    public void visitLdcInsn(Object cst) {
                        if (cst instanceof Integer) {
                            intStack.push((Integer) cst);
                        }
                    }

                    @Override
                    public void visitInsn(int opcode) {
                        if (opcode >= Opcodes.ICONST_0 && opcode <= Opcodes.ICONST_5) {
                            intStack.push(opcode - Opcodes.ICONST_0);
                        } else if (opcode == Opcodes.IASTORE) {
                            int value = intStack.pop();
                            int index = intStack.pop();
                            current[index] = value;
                        }
                    }

                    @Override
                    public void visitFieldInsn(int opcode, String owner, String name, String desc) {
                        if (opcode == Opcodes.PUTSTATIC) {
                            int[] old = styleables.get(name);
                            if (old != null && old.length != current.length && !Arrays.equals(old, current)) {
                                throw new IllegalStateException("Value of styleable." + name + " mismatched! "
                                        + "Excepted " + Arrays.toString(old) + " but was "
                                        + Arrays.toString(current));
                            } else {
                                styleables.put(name, current);
                            }
                            current = null;
                            intStack.clear();
                        }
                    }
                };
            }
            return null;
        }
    };

    new ClassReader(bytes).accept(visitor, SKIP_DEBUG | SKIP_FRAMES);
}

From source file:net.yrom.tools.WriteStyleablesProcessor.java

License:Apache License

private void writeClinit(ClassWriter writer) {
    Map<String, int[]> styleables = symbols.getStyleables();
    MethodVisitor clinit = writer.visitMethod(Opcodes.ACC_STATIC, "<clinit>", "()V", null, null);
    clinit.visitCode();//from  w  w w  .ja  v  a 2  s  .  c  o  m

    for (Map.Entry<String, int[]> entry : styleables.entrySet()) {
        final String field = entry.getKey();
        final int[] value = entry.getValue();
        final int length = value.length;
        pushInt(clinit, length);
        clinit.visitIntInsn(Opcodes.NEWARRAY, Opcodes.T_INT);
        for (int i = 0; i < length; i++) {
            clinit.visitInsn(Opcodes.DUP); // dup
            pushInt(clinit, i);
            pushInt(clinit, value[i]);
            clinit.visitInsn(Opcodes.IASTORE); // iastore
        }
        clinit.visitFieldInsn(Opcodes.PUTSTATIC, RSymbols.R_STYLEABLES_CLASS_NAME, field, "[I");
    }
    clinit.visitInsn(Opcodes.RETURN);
    clinit.visitMaxs(0, 0); // auto compute
    clinit.visitEnd();
}

From source file:org.actorsguildframework.internal.codegenerator.ActorProxyCreator.java

License:Apache License

/**
 * Creates and loads the actor's proxy class.
 * @param actorClass the Actor class//from   ww w. ja  va2  s . co  m
 * @param acd the actor's class descriptor
 * @throws ConfigurationException if the agent is not configured correctly
 */
@SuppressWarnings("unchecked")
private static Class<?> generateProxyClass(Class<?> actorClass, final ActorClassDescriptor acd)
        throws NoSuchMethodException {
    BeanClassDescriptor bcd = acd.getBeanClassDescriptor();

    String className = String.format("%s__ACTORPROXY", actorClass.getName());
    final String classNameInternal = className.replace('.', '/');
    String classNameDescriptor = "L" + classNameInternal + ";";

    final Type actorState = Type
            .getType(acd.getConcurrencyModel().isMultiThreadingCapable() ? MultiThreadedActorState.class
                    : SingleThreadedActorState.class);

    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
    MethodVisitor mv;
    cw.visit(codeVersion, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER + Opcodes.ACC_SYNTHETIC,
            classNameInternal, null, Type.getInternalName(actorClass),
            new String[] { "org/actorsguildframework/internal/ActorProxy" });

    cw.visitSource(null, null);

    {
        for (int i = 0; i < acd.getMessageCount(); i++)
            cw.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL + Opcodes.ACC_STATIC,
                    String.format(MESSAGE_CALLER_NAME_FORMAT, i),
                    "Lorg/actorsguildframework/internal/MessageCaller;",
                    "Lorg/actorsguildframework/internal/MessageCaller<*>;", null).visitEnd();

        cw.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL, "actorState__ACTORPROXY",
                actorState.getDescriptor(), null, null).visitEnd();
    }

    BeanCreator.writePropFields(bcd, cw);

    {
        mv = cw.visitMethod(Opcodes.ACC_STATIC, "<clinit>", "()V", null, null);
        mv.visitCode();

        for (int i = 0; i < acd.getMessageCount(); i++) {
            Class<?> caller = createMessageCaller(acd.getMessage(i).getOwnerClass(),
                    acd.getMessage(i).getMethod());
            String mcName = Type.getInternalName(caller);
            mv.visitTypeInsn(Opcodes.NEW, mcName);
            mv.visitInsn(Opcodes.DUP);
            mv.visitMethodInsn(Opcodes.INVOKESPECIAL, mcName, "<init>", "()V");
            mv.visitFieldInsn(Opcodes.PUTSTATIC, classNameInternal,
                    String.format(MESSAGE_CALLER_NAME_FORMAT, i),
                    "Lorg/actorsguildframework/internal/MessageCaller;");
        }
        mv.visitInsn(Opcodes.RETURN);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }

    BeanCreator.writeConstructor(actorClass, bcd, classNameInternal, cw, new BeanCreator.SnippetWriter() {
        @Override
        public void write(MethodVisitor mv) {
            mv.visitVarInsn(Opcodes.ALOAD, 0);
            mv.visitTypeInsn(Opcodes.NEW, actorState.getInternalName());
            mv.visitInsn(Opcodes.DUP);
            mv.visitVarInsn(Opcodes.ALOAD, 1);
            mv.visitVarInsn(Opcodes.ALOAD, 0);
            mv.visitMethodInsn(Opcodes.INVOKESPECIAL, actorState.getInternalName(), "<init>",
                    "(Lorg/actorsguildframework/internal/Controller;Lorg/actorsguildframework/Actor;)V");
            mv.visitFieldInsn(Opcodes.PUTFIELD, classNameInternal, "actorState__ACTORPROXY",
                    actorState.getDescriptor());
        }
    });

    BeanCreator.writePropAccessors(bcd, classNameInternal, cw);

    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "getState__ACTORPROXYMETHOD",
                "()Lorg/actorsguildframework/internal/ActorState;", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitFieldInsn(Opcodes.GETFIELD, classNameInternal, "actorState__ACTORPROXY",
                actorState.getDescriptor());
        mv.visitInsn(Opcodes.ARETURN);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLocalVariable("this", classNameDescriptor, null, l0, l1, 0);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }

    for (int i = 0; i < acd.getMessageCount(); i++) {
        MessageImplDescriptor mid = acd.getMessage(i);
        Method method = mid.getMethod();
        String simpleDescriptor = Type.getMethodDescriptor(method);
        String genericSignature = GenericTypeHelper.getSignature(method);

        writeProxyMethod(classNameInternal, classNameDescriptor, cw, i, actorState, acd.getConcurrencyModel(),
                mid, method, simpleDescriptor, genericSignature);

        writeSuperProxyMethod(actorClass, classNameDescriptor, cw, method, simpleDescriptor, genericSignature,
                !acd.getConcurrencyModel().isMultiThreadingCapable());
    }

    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_SYNCHRONIZED, "toString", "()Ljava/lang/String;",
                null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "toString", "()Ljava/lang/String;");
        mv.visitInsn(Opcodes.ARETURN);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLocalVariable("this", classNameDescriptor, null, l0, l1, 0);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }
    cw.visitEnd();

    try {
        return (Class<? extends ActorProxy>) GenerationUtils.loadClass(className, cw.toByteArray());
    } catch (Exception e) {
        throw new ConfigurationException("Failure loading ActorProxy", e);
    }
}