Example usage for org.objectweb.asm Opcodes ANEWARRAY

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

Introduction

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

Prototype

int ANEWARRAY

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

Click Source Link

Usage

From source file:jpcsp.Allegrex.compiler.CompilerContext.java

License:Open Source License

private void logSyscallEnd(HLEModuleFunction func, boolean isErrorCode) {
    String loggingLevel = getLoggingLevel(func);
    if (loggingLevel == null) {
        return;//from w  w w.  java 2s . com
    }
    String logCheckFunction = getLogCheckFunction(loggingLevel);

    // if (Modules.getLogger(func.getModuleName()).isDebugEnabled()) {
    //     Modules.getLogger(func.getModuleName()).debug(String.format("<function name> returning 0x%X", new Object[1] { new Integer(returnValue) }));
    // }
    loadModuleLoggger(func);
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Logger.class), logCheckFunction, "()Z");
    Label notDebug = new Label();
    mv.visitJumpInsn(Opcodes.IFEQ, notDebug);

    boolean isReturningVoid = func.getHLEModuleMethod().getReturnType() == void.class;

    mv.visitInsn(Opcodes.DUP);
    mv.visitTypeInsn(Opcodes.NEW, Type.getInternalName(Integer.class));
    mv.visitInsn(Opcodes.DUP_X1);
    mv.visitInsn(Opcodes.SWAP);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Integer.class), "<init>", "(I)V");
    loadImm(1);
    mv.visitTypeInsn(Opcodes.ANEWARRAY, Type.getInternalName(Object.class));
    mv.visitInsn(Opcodes.DUP_X1);
    mv.visitInsn(Opcodes.SWAP);
    loadImm(0);
    mv.visitInsn(Opcodes.SWAP);
    mv.visitInsn(Opcodes.AASTORE);
    String prefix = func.isUnimplemented() && !codeBlock.isHLEFunction() ? "Unimplemented " : "";
    mv.visitLdcInsn(String.format("%s%s returning %s%s", prefix, func.getFunctionName(),
            isErrorCode ? "errorCode " : "", isReturningVoid ? "void" : "0x%X"));
    mv.visitInsn(Opcodes.SWAP);
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(String.class), "format",
            "(" + Type.getDescriptor(String.class) + "[" + Type.getDescriptor(Object.class) + ")"
                    + Type.getDescriptor(String.class));
    loadModuleLoggger(func);
    mv.visitInsn(Opcodes.SWAP);
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Logger.class), loggingLevel,
            "(" + Type.getDescriptor(Object.class) + ")V");

    if (!isErrorCode) {
        ParameterInfo[] parameters = new ClassAnalyzer().getParameters(func.getFunctionName(),
                func.getHLEModuleMethod().getDeclaringClass());
        if (parameters != null) {
            CompilerParameterReader parameterReader;
            if (parametersSavedToLocals) {
                parameterReader = new CompilerLocalVarParameterReader(this, LOCAL_FIRST_SAVED_PARAMETER);
            } else {
                parameterReader = new CompilerParameterReader(this);
            }

            Annotation[][] paramsAnotations = func.getHLEModuleMethod().getParameterAnnotations();
            for (int paramIndex = 0; paramIndex < parameters.length; paramIndex++) {
                ParameterInfo parameter = parameters[paramIndex];
                Class<?> parameterType = parameter.type;

                LengthInfo lengthInfo = BufferInfo.defaultLengthInfo;
                int length = BufferInfo.defaultLength;
                Usage usage = BufferInfo.defaultUsage;
                boolean debugMemory = false;
                for (Annotation parameterAnnotation : paramsAnotations[paramIndex]) {
                    if (parameterAnnotation instanceof BufferInfo) {
                        BufferInfo bufferInfo = (BufferInfo) parameterAnnotation;
                        lengthInfo = bufferInfo.lengthInfo();
                        length = bufferInfo.length();
                        usage = bufferInfo.usage();
                    } else if (parameterAnnotation instanceof DebugMemory) {
                        debugMemory = true;
                    }
                }

                boolean parameterRead = false;
                if ((usage == Usage.out || usage == Usage.inout)
                        && (lengthInfo != LengthInfo.unknown || parameterType == TPointer16.class
                                || parameterType == TPointer32.class || parameterType == TPointer64.class)) {
                    loadModuleLoggger(func);
                    loadImm(1);
                    mv.visitTypeInsn(Opcodes.ANEWARRAY, Type.getInternalName(Object.class));
                    mv.visitInsn(Opcodes.DUP);
                    loadImm(0);

                    Label done = new Label();
                    Label addressNull = new Label();
                    parameterReader.loadNextInt();
                    parameterRead = true;
                    mv.visitInsn(Opcodes.DUP);
                    mv.visitJumpInsn(Opcodes.IFEQ, addressNull);

                    String format = String.format("%s[%s]:%%s", parameter.name, usage);
                    boolean useMemoryDump = true;

                    switch (lengthInfo) {
                    case fixedLength:
                        loadImm(length);
                        break;
                    case nextNextParameter:
                        parameterReader.skipNextInt();
                        paramIndex++;
                        parameterReader.loadNextInt();
                        paramIndex++;
                        break;
                    case nextParameter:
                        parameterReader.loadNextInt();
                        paramIndex++;
                        break;
                    case previousParameter:
                        // Go back to the address parameter
                        parameterReader.rewindPreviousInt();
                        // Go back to the previous parameter
                        parameterReader.rewindPreviousInt();
                        // Load the length from the previous parameter
                        parameterReader.loadNextInt();
                        // Skip again the address parameter
                        // to come back to the above situation
                        parameterReader.skipNextInt();
                        break;
                    case variableLength:
                        mv.visitInsn(Opcodes.DUP);
                        loadMemory();
                        mv.visitInsn(Opcodes.SWAP);
                        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, memoryInternalName, "read32", "(I)I");
                        break;
                    case returnValue:
                        loadRegister(_v0);
                        break;
                    case unknown:
                        useMemoryDump = false;
                        format = String.format("%s[%s]: 0x%%X", parameter.name, usage);
                        loadMemory();
                        mv.visitInsn(Opcodes.SWAP);
                        if (parameterType == TPointer64.class) {
                            if (debugMemory) {
                                mv.visitInsn(Opcodes.DUP);
                                loadImm(8);
                                mv.visitMethodInsn(Opcodes.INVOKESTATIC, runtimeContextInternalName,
                                        "debugMemory", "(II)V");
                            }
                            mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, memoryInternalName, "read64", "(I)J");
                            mv.visitTypeInsn(Opcodes.NEW, Type.getInternalName(Long.class));
                            mv.visitInsn(Opcodes.DUP);
                            mv.visitInsn(Opcodes.DUP2_X2);
                            mv.visitInsn(Opcodes.POP2);
                            mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Long.class),
                                    "<init>", "(J)V");
                        } else if (parameterType == TPointer16.class) {
                            if (debugMemory) {
                                mv.visitInsn(Opcodes.DUP);
                                loadImm(2);
                                mv.visitMethodInsn(Opcodes.INVOKESTATIC, runtimeContextInternalName,
                                        "debugMemory", "(II)V");
                            }
                            mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, memoryInternalName, "read16", "(I)I");
                            mv.visitTypeInsn(Opcodes.NEW, Type.getInternalName(Integer.class));
                            mv.visitInsn(Opcodes.DUP_X1);
                            mv.visitInsn(Opcodes.SWAP);
                            mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Integer.class),
                                    "<init>", "(I)V");
                        } else {
                            if (debugMemory) {
                                mv.visitInsn(Opcodes.DUP);
                                loadImm(4);
                                mv.visitMethodInsn(Opcodes.INVOKESTATIC, runtimeContextInternalName,
                                        "debugMemory", "(II)V");
                            }
                            mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, memoryInternalName, "read32", "(I)I");
                            mv.visitTypeInsn(Opcodes.NEW, Type.getInternalName(Integer.class));
                            mv.visitInsn(Opcodes.DUP_X1);
                            mv.visitInsn(Opcodes.SWAP);
                            mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Integer.class),
                                    "<init>", "(I)V");
                        }
                        break;
                    default:
                        log.error(String.format("Unimplemented lengthInfo=%s", lengthInfo));
                        break;
                    }

                    if (useMemoryDump) {
                        if (debugMemory) {
                            mv.visitInsn(Opcodes.DUP2);
                            mv.visitMethodInsn(Opcodes.INVOKESTATIC, runtimeContextInternalName, "debugMemory",
                                    "(II)V");
                        }
                        mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Utilities.class),
                                "getMemoryDump", "(II)" + Type.getDescriptor(String.class));
                    }
                    mv.visitInsn(Opcodes.AASTORE);

                    mv.visitLdcInsn(format);
                    mv.visitInsn(Opcodes.SWAP);
                    mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(String.class), "format",
                            "(" + Type.getDescriptor(String.class) + "[" + Type.getDescriptor(Object.class)
                                    + ")" + Type.getDescriptor(String.class));
                    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Logger.class), loggingLevel,
                            "(" + Type.getDescriptor(Object.class) + ")V");
                    mv.visitJumpInsn(Opcodes.GOTO, done);

                    mv.visitLabel(addressNull);
                    mv.visitInsn(Opcodes.POP);
                    mv.visitInsn(Opcodes.POP2);
                    mv.visitInsn(Opcodes.POP2);
                    mv.visitLabel(done);
                }

                if (!parameterRead) {
                    if (parameterType == long.class) {
                        parameterReader.skipNextLong();
                    } else if (parameterType == float.class) {
                        parameterReader.skipNextFloat();
                    } else {
                        parameterReader.skipNextInt();
                    }
                }
            }
        }
    }

    mv.visitLabel(notDebug);
}

From source file:lucee.transformer.bytecode.Page.java

License:Open Source License

/**
 * result byte code as binary array//  w ww.ja  v  a2 s. c o m
 * @param classFile 
 * @return byte code
 * @throws IOException 
 * @throws TemplateException 
 */
public byte[] execute(PageSource source, Resource classFile) throws BytecodeException {
    /*
    // this is done that the Page can be executed more than once
    if(initFunctions==null)
       initFunctions=(ArrayList<IFunction>) functions.clone();
    else
       functions=initFunctions;
    if(initThreads==null)
       initThreads=(ArrayList<TagThread>) threads.clone();
    else
       threads=initThreads;
    methodCount=0;
    off=0;
    staticTextLocation=null;
            
            
    print.e(this.functions);
    print.e(this.threads);*/

    Resource p = classFile.getParentResource().getRealResource(classFile.getName() + ".txt");

    List<LitString> keys = new ArrayList<LitString>();
    ClassWriter cw = ASMUtil.getClassWriter();

    ArrayList<String> imports = new ArrayList<String>();
    getImports(imports, this);

    // parent
    String parent = "lucee/runtime/PagePlus";
    if (isComponent())
        parent = "lucee/runtime/ComponentPage";
    else if (isInterface())
        parent = "lucee/runtime/InterfacePage";

    cw.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, name, null, parent, null);
    cw.visitSource(this.pageSource.getPhyscalFile().getAbsolutePath(),
            "rel:" + this.pageSource.getFullRealpath()); // when adding more use ; as delimiter
    //

    // static constructor
    //GeneratorAdapter statConstrAdapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC,STATIC_CONSTRUCTOR,null,null,cw);
    BytecodeContext statConstr = null;//new BytecodeContext(null,null,this,externalizer,keys,cw,name,statConstrAdapter,STATIC_CONSTRUCTOR,writeLog(),suppressWSbeforeArg);

    // constructor
    GeneratorAdapter constrAdapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC, CONSTRUCTOR_PS, null, null, cw);
    BytecodeContext constr = new BytecodeContext(source, null, null, this, keys, cw, name, constrAdapter,
            CONSTRUCTOR_PS, writeLog(), suppressWSbeforeArg, output);
    constrAdapter.loadThis();
    Type t = Types.PAGE_PLUS;
    if (isComponent())
        t = Types.COMPONENT_PAGE;
    else if (isInterface())
        t = Types.INTERFACE_PAGE;

    constrAdapter.invokeConstructor(t, CONSTRUCTOR);

    // call _init()
    constrAdapter.visitVarInsn(Opcodes.ALOAD, 0);
    constrAdapter.visitMethodInsn(Opcodes.INVOKEVIRTUAL, constr.getClassName(), "initKeys", "()V");

    // private static  ImportDefintion[] test=new ImportDefintion[]{...};
    {
        FieldVisitor fv = cw.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL, "imports",
                "[Llucee/runtime/component/ImportDefintion;", null, null);
        fv.visitEnd();

        constrAdapter.visitVarInsn(Opcodes.ALOAD, 0);
        ArrayVisitor av = new ArrayVisitor();
        av.visitBegin(constrAdapter, Types.IMPORT_DEFINITIONS, imports.size());
        int index = 0;
        Iterator<String> it = imports.iterator();
        while (it.hasNext()) {
            av.visitBeginItem(constrAdapter, index++);
            constrAdapter.push(it.next());
            ASMConstants.NULL(constrAdapter);
            constrAdapter.invokeStatic(Types.IMPORT_DEFINITIONS_IMPL, ID_GET_INSTANCE);
            av.visitEndItem(constrAdapter);
        }
        av.visitEnd();
        constrAdapter.visitFieldInsn(Opcodes.PUTFIELD, name, "imports",
                "[Llucee/runtime/component/ImportDefintion;");

    }

    // getVersion
    GeneratorAdapter adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, VERSION, null, null,
            cw);
    adapter.push(version);
    adapter.returnValue();
    adapter.endMethod();

    // public ImportDefintion[] getImportDefintions()
    if (imports.size() > 0) {
        adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, GET_IMPORT_DEFINITIONS, null,
                null, cw);
        adapter.visitVarInsn(Opcodes.ALOAD, 0);
        adapter.visitFieldInsn(Opcodes.GETFIELD, name, "imports", "[Llucee/runtime/component/ImportDefintion;");
        adapter.returnValue();
        adapter.endMethod();
    } else {
        adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, GET_IMPORT_DEFINITIONS, null,
                null, cw);
        adapter.visitInsn(Opcodes.ICONST_0);
        adapter.visitTypeInsn(Opcodes.ANEWARRAY, "lucee/runtime/component/ImportDefintion");
        adapter.returnValue();
        adapter.endMethod();
    }

    // getSourceLastModified
    adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, LAST_MOD, null, null, cw);
    adapter.push(lastModifed);
    adapter.returnValue();
    adapter.endMethod();

    // getCompileTime
    adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, COMPILE_TIME, null, null, cw);
    adapter.push(System.currentTimeMillis());
    adapter.returnValue();
    adapter.endMethod();

    // newInstance/initComponent/call
    if (isComponent()) {
        Tag component = getComponent();
        writeOutNewComponent(statConstr, constr, keys, cw, component);
        writeOutInitComponent(statConstr, constr, keys, cw, component);
    } else if (isInterface()) {
        Tag interf = getInterface();
        writeOutNewInterface(statConstr, constr, keys, cw, interf);
        writeOutInitInterface(statConstr, constr, keys, cw, interf);
    } else {
        writeOutCall(statConstr, constr, keys, cw);
    }

    // udfCall     
    Function[] functions = getFunctions();
    ConditionVisitor cv;
    DecisionIntVisitor div;
    // less/equal than 10 functions
    if (isInterface()) {
    } else if (functions.length <= 10) {
        adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, UDF_CALL, null,
                new Type[] { Types.THROWABLE }, cw);
        BytecodeContext bc = new BytecodeContext(source, statConstr, constr, this, keys, cw, name, adapter,
                UDF_CALL, writeLog(), suppressWSbeforeArg, output);
        if (functions.length == 0) {
        } else if (functions.length == 1) {
            ExpressionUtil.visitLine(bc, functions[0].getStart());
            functions[0].getBody().writeOut(bc);
            ExpressionUtil.visitLine(bc, functions[0].getEnd());
        } else
            writeOutUdfCallInner(bc, functions, 0, functions.length);
        adapter.visitInsn(Opcodes.ACONST_NULL);
        adapter.returnValue();
        adapter.endMethod();
    }
    // more than 10 functions
    else {
        adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, UDF_CALL, null,
                new Type[] { Types.THROWABLE }, cw);
        BytecodeContext bc = new BytecodeContext(source, statConstr, constr, this, keys, cw, name, adapter,
                UDF_CALL, writeLog(), suppressWSbeforeArg, output);
        cv = new ConditionVisitor();
        cv.visitBefore();
        int count = 0;
        for (int i = 0; i < functions.length; i += 10) {
            cv.visitWhenBeforeExpr();
            div = new DecisionIntVisitor();
            div.visitBegin();
            adapter.loadArg(2);
            div.visitLT();
            adapter.push(i + 10);
            div.visitEnd(bc);
            cv.visitWhenAfterExprBeforeBody(bc);

            adapter.visitVarInsn(Opcodes.ALOAD, 0);
            adapter.visitVarInsn(Opcodes.ALOAD, 1);
            adapter.visitVarInsn(Opcodes.ALOAD, 2);
            adapter.visitVarInsn(Opcodes.ILOAD, 3);
            adapter.visitMethodInsn(Opcodes.INVOKEVIRTUAL, name, createFunctionName(++count),
                    "(Llucee/runtime/PageContext;Llucee/runtime/type/UDF;I)Ljava/lang/Object;");
            adapter.visitInsn(Opcodes.ARETURN);//adapter.returnValue();
            cv.visitWhenAfterBody(bc);
        }
        cv.visitAfter(bc);

        adapter.visitInsn(Opcodes.ACONST_NULL);
        adapter.returnValue();
        adapter.endMethod();

        count = 0;
        Method innerCall;
        for (int i = 0; i < functions.length; i += 10) {
            innerCall = new Method(createFunctionName(++count), Types.OBJECT,
                    new Type[] { Types.PAGE_CONTEXT, USER_DEFINED_FUNCTION, Types.INT_VALUE });

            adapter = new GeneratorAdapter(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL, innerCall, null,
                    new Type[] { Types.THROWABLE }, cw);
            writeOutUdfCallInner(
                    new BytecodeContext(source, statConstr, constr, this, keys, cw, name, adapter, innerCall,
                            writeLog(), suppressWSbeforeArg, output),
                    functions, i, i + 10 > functions.length ? functions.length : i + 10);

            adapter.visitInsn(Opcodes.ACONST_NULL);
            adapter.returnValue();
            adapter.endMethod();
        }
    }

    // threadCall
    TagThread[] threads = getThreads();
    if (true) {
        adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, THREAD_CALL, null,
                new Type[] { Types.THROWABLE }, cw);
        if (threads.length > 0)
            writeOutThreadCallInner(new BytecodeContext(source, statConstr, constr, this, keys, cw, name,
                    adapter, THREAD_CALL, writeLog(), suppressWSbeforeArg, output), threads, 0, threads.length);
        //adapter.visitInsn(Opcodes.ACONST_NULL);
        adapter.returnValue();
        adapter.endMethod();
    }

    // udfDefaultValue
    // less/equal than 10 functions
    if (isInterface()) {
    } else if (functions.length <= 10) {
        adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, UDF_DEFAULT_VALUE, null,
                new Type[] { Types.PAGE_EXCEPTION }, cw);
        if (functions.length > 0)
            writeUdfDefaultValueInner(
                    new BytecodeContext(source, statConstr, constr, this, keys, cw, name, adapter,
                            UDF_DEFAULT_VALUE, writeLog(), suppressWSbeforeArg, output),
                    functions, 0, functions.length);

        adapter.loadArg(DEFAULT_VALUE);
        adapter.returnValue();
        adapter.endMethod();
    } else {
        adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, UDF_DEFAULT_VALUE, null,
                new Type[] { Types.PAGE_EXCEPTION }, cw);
        BytecodeContext bc = new BytecodeContext(source, statConstr, constr, this, keys, cw, name, adapter,
                UDF_DEFAULT_VALUE, writeLog(), suppressWSbeforeArg, output);
        cv = new ConditionVisitor();
        cv.visitBefore();
        int count = 0;
        for (int i = 0; i < functions.length; i += 10) {
            cv.visitWhenBeforeExpr();
            div = new DecisionIntVisitor();
            div.visitBegin();
            adapter.loadArg(1);
            div.visitLT();
            adapter.push(i + 10);
            div.visitEnd(bc);
            cv.visitWhenAfterExprBeforeBody(bc);

            adapter.visitVarInsn(Opcodes.ALOAD, 0);
            adapter.visitVarInsn(Opcodes.ALOAD, 1);
            adapter.visitVarInsn(Opcodes.ILOAD, 2);
            adapter.visitVarInsn(Opcodes.ILOAD, 3);
            adapter.visitVarInsn(Opcodes.ALOAD, 4);

            adapter.visitMethodInsn(Opcodes.INVOKEVIRTUAL, name, "udfDefaultValue" + (++count),
                    "(Llucee/runtime/PageContext;IILjava/lang/Object;)Ljava/lang/Object;");
            adapter.visitInsn(Opcodes.ARETURN);//adapter.returnValue();

            cv.visitWhenAfterBody(bc);
        }
        cv.visitAfter(bc);

        adapter.visitInsn(Opcodes.ACONST_NULL);
        adapter.returnValue();
        adapter.endMethod();

        count = 0;
        Method innerDefaultValue;
        for (int i = 0; i < functions.length; i += 10) {
            innerDefaultValue = new Method("udfDefaultValue" + (++count), Types.OBJECT,
                    new Type[] { Types.PAGE_CONTEXT, Types.INT_VALUE, Types.INT_VALUE, Types.OBJECT });
            adapter = new GeneratorAdapter(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL, innerDefaultValue, null,
                    new Type[] { Types.PAGE_EXCEPTION }, cw);
            writeUdfDefaultValueInner(
                    new BytecodeContext(source, statConstr, constr, this, keys, cw, name, adapter,
                            innerDefaultValue, writeLog(), suppressWSbeforeArg, output),
                    functions, i, i + 10 > functions.length ? functions.length : i + 10);

            adapter.loadArg(DEFAULT_VALUE);
            //adapter.visitInsn(Opcodes.ACONST_NULL);
            adapter.returnValue();
            adapter.endMethod();
        }

    }

    // register fields
    {
        GeneratorAdapter aInit = new GeneratorAdapter(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL, _INIT, null,
                null, cw);
        BytecodeContext bcInit = new BytecodeContext(source, statConstr, constr, this, keys, cw, name, aInit,
                _INIT, writeLog(), suppressWSbeforeArg, output);
        registerFields(bcInit, keys);
        aInit.returnValue();
        aInit.endMethod();
    }

    //setPageSource(pageSource);
    constrAdapter.visitVarInsn(Opcodes.ALOAD, 0);
    constrAdapter.visitVarInsn(Opcodes.ALOAD, 1);
    constrAdapter.invokeVirtual(t, SET_PAGE_SOURCE);

    constrAdapter.returnValue();
    constrAdapter.endMethod();

    return cw.toByteArray();

}

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

License:GNU General Public License

/**
 * Generates:/*  w w w  .j a v  a2  s  . 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 www  .j av  a 2s . c  om*/
 *   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:org.actorsguildframework.internal.codegenerator.ActorProxyCreator.java

License:Apache License

/**
 * Writes a proxy method for messages./*from   w ww .ja  va 2  s .  c o m*/
 * @param classNameInternal the internal class name
 * @param classNameDescriptor the class name descriptor
 * @param cw the ClassWriter
 * @param index the message index
 * @param type the ActorState type to use
 * @param concurrencyModel the concurrency model of the message
 * @param messageDescriptor the message's descriptor
 * @param method the method to override
 * @param simpleDescriptor a simple descriptor of the message
 * @param genericSignature the signature of the message
 */
private static void writeProxyMethod(String classNameInternal, String classNameDescriptor, ClassWriter cw,
        int index, Type actorState, ConcurrencyModel concurrencyModel, MessageImplDescriptor messageDescriptor,
        Method method, String simpleDescriptor, String genericSignature) throws NoSuchMethodException {
    MethodVisitor mv;
    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, method.getName(), simpleDescriptor, genericSignature, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitIntInsn(Opcodes.BIPUSH, method.getParameterTypes().length);
        mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
        for (int j = 0; j < method.getParameterTypes().length; j++) {
            mv.visitInsn(Opcodes.DUP);
            mv.visitIntInsn(Opcodes.BIPUSH, j);
            Class<?> paraType = method.getParameterTypes()[j];
            if (paraType.isPrimitive()) {
                String wrapperClass = GenerationUtils.getWrapperInternalName(paraType);
                Type primType = Type.getType(paraType);
                mv.visitVarInsn(primType.getOpcode(Opcodes.ILOAD), j + 1);
                mv.visitMethodInsn(Opcodes.INVOKESTATIC, wrapperClass, "valueOf",
                        "(" + primType.getDescriptor() + ")" + "L" + wrapperClass + ";");
            } else if (isArgumentFreezingRequired(method, j, paraType)) {
                mv.visitVarInsn(Opcodes.ALOAD, j + 1);
                mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(SerializableFreezer.class),
                        "freeze",
                        Type.getMethodDescriptor(SerializableFreezer.class.getMethod("freeze", Object.class)));
            } else if (paraType.isInterface()) {
                mv.visitVarInsn(Opcodes.ALOAD, j + 1);
                mv.visitInsn(Opcodes.DUP);
                mv.visitTypeInsn(Opcodes.INSTANCEOF, "org/actorsguildframework/Actor");
                Label lEndif = new Label();
                mv.visitJumpInsn(Opcodes.IFNE, lEndif);
                mv.visitTypeInsn(Opcodes.NEW, Type.getInternalName(ActorRuntimeException.class));
                mv.visitInsn(Opcodes.DUP);
                mv.visitLdcInsn(String.format(
                        "Argument %d is an non-Serializable interface, but you did not give an Actor. If a message's argument type is an interface that does not extend Serializable, only Actors are acceptable as argument.",
                        j));
                mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(ActorRuntimeException.class),
                        "<init>", "(Ljava/lang/String;)V");
                mv.visitInsn(Opcodes.ATHROW);
                mv.visitLabel(lEndif);
            } else
                mv.visitVarInsn(Opcodes.ALOAD, j + 1);

            mv.visitInsn(Opcodes.AASTORE);
        }
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitVarInsn(Opcodes.ASTORE, method.getParameterTypes().length + 1); // method.getParameterTypes().length+1 ==> 'args' local variable
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitFieldInsn(Opcodes.GETFIELD, classNameInternal, "actorState__ACTORPROXY",
                actorState.getDescriptor());
        mv.visitFieldInsn(Opcodes.GETSTATIC, classNameInternal,
                String.format(MESSAGE_CALLER_NAME_FORMAT, index),
                "Lorg/actorsguildframework/internal/MessageCaller;");
        mv.visitFieldInsn(Opcodes.GETSTATIC, "org/actorsguildframework/annotations/ThreadUsage",
                messageDescriptor.getThreadUsage().name(),
                "Lorg/actorsguildframework/annotations/ThreadUsage;");
        mv.visitVarInsn(Opcodes.ALOAD, method.getParameterTypes().length + 1);
        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, actorState.getInternalName(), "queueMessage",
                "(Lorg/actorsguildframework/internal/MessageCaller;Lorg/actorsguildframework/annotations/ThreadUsage;[Ljava/lang/Object;)Lorg/actorsguildframework/internal/AsyncResultImpl;");
        mv.visitInsn(Opcodes.ARETURN);
        Label l4 = new Label();
        mv.visitLabel(l4);
        mv.visitLocalVariable("this", classNameDescriptor, null, l0, l4, 0);
        for (int j = 0; j < method.getParameterTypes().length; j++)
            mv.visitLocalVariable("arg" + j, Type.getDescriptor(method.getParameterTypes()[j]),
                    GenericTypeHelper.getSignatureIfGeneric(method.getGenericParameterTypes()[j]), l0, l4,
                    j + 1);
        mv.visitLocalVariable("args", "[Ljava/lang/Object;", null, l1, l4,
                method.getParameterTypes().length + 1);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }
}

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

License:Apache License

/**
 * Writes the bean constructor to the given ClassWriter.
 * @param beanClass the original bean class to extend
 * @param bcd the descriptor of the bean
 * @param classNameInternal the internal name of the new class
 * @param cw the ClassWriter to write to
 * @param snippetWriter if not null, this will be invoked to add a snippet
 *                      after the invocation of the super constructor
 *//*from  ww w.  j  a  v  a 2 s  . co  m*/
public static void writeConstructor(Class<?> beanClass, BeanClassDescriptor bcd, String classNameInternal,
        ClassWriter cw, SnippetWriter snippetWriter) {
    String classNameDescriptor = "L" + classNameInternal + ";";

    int localPropertySize = 0;
    ArrayList<PropertyDescriptor> localVarProperties = new ArrayList<PropertyDescriptor>();
    for (int i = 0; i < bcd.getPropertyCount(); i++) {
        PropertyDescriptor pd = bcd.getProperty(i);
        if (pd.getPropertySource().isGenerating() || (pd.getDefaultValue() != null)) {
            localVarProperties.add(pd);
            localPropertySize += Type.getType(pd.getPropertyClass()).getSize();
        }
    }

    final int locVarThis = 0;
    final int locVarController = 1;
    final int locVarProps = 2;
    final int locVarPropertiesOffset = 3;
    final int locVarP = 3 + localPropertySize;
    final int locVarK = 4 + localPropertySize;
    final int locVarV = 5 + localPropertySize;

    MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>",
            "(Lorg/actorsguildframework/internal/Controller;Lorg/actorsguildframework/Props;)V", null, null);
    mv.visitCode();
    Label lTry = new Label();
    Label lCatch = new Label();
    mv.visitTryCatchBlock(lTry, lCatch, lCatch, "java/lang/ClassCastException");

    Label lBegin = new Label();
    mv.visitLabel(lBegin);
    mv.visitVarInsn(Opcodes.ALOAD, locVarThis);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(beanClass), "<init>", "()V");

    if (snippetWriter != null)
        snippetWriter.write(mv);

    Label lPropertyInit = new Label();
    mv.visitLabel(lPropertyInit);
    // load default values into the local variables for each property that must be set
    int varCount = 0;
    for (PropertyDescriptor pd : localVarProperties) {
        Type pt = Type.getType(pd.getPropertyClass());
        if (pd.getDefaultValue() != null)
            mv.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(pd.getDefaultValue().getDeclaringClass()),
                    pd.getDefaultValue().getName(), Type.getDescriptor(pd.getDefaultValue().getType()));
        else
            GenerationUtils.generateLoadDefault(mv, pd.getPropertyClass());
        mv.visitVarInsn(pt.getOpcode(Opcodes.ISTORE), locVarPropertiesOffset + varCount);
        varCount += pt.getSize();
    }

    // loop through the props argument's list
    mv.visitVarInsn(Opcodes.ALOAD, locVarProps);
    mv.visitVarInsn(Opcodes.ASTORE, locVarP);
    Label lWhile = new Label();
    Label lEndWhile = new Label();
    Label lWhileBody = new Label();
    mv.visitLabel(lWhile);
    mv.visitJumpInsn(Opcodes.GOTO, lEndWhile);
    mv.visitLabel(lWhileBody);

    mv.visitVarInsn(Opcodes.ALOAD, locVarP);
    mv.visitInsn(Opcodes.DUP);
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "org/actorsguildframework/Props", "getKey",
            "()Ljava/lang/String;");
    mv.visitVarInsn(Opcodes.ASTORE, locVarK);
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "org/actorsguildframework/Props", "getValue",
            "()Ljava/lang/Object;");
    mv.visitVarInsn(Opcodes.ASTORE, locVarV);

    mv.visitLabel(lTry);
    // write an if for each property
    Label lEndIf = new Label();
    varCount = 0;
    int ifCount = 0;
    for (int i = 0; i < bcd.getPropertyCount(); i++) {
        PropertyDescriptor pd = bcd.getProperty(i);
        boolean usesLocal = pd.getPropertySource().isGenerating() || (pd.getDefaultValue() != null);
        Class<?> propClass = pd.getPropertyClass();
        Type pt = Type.getType(propClass);
        mv.visitVarInsn(Opcodes.ALOAD, locVarK);
        mv.visitLdcInsn(pd.getName());
        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/String", "equals", "(Ljava/lang/Object;)Z");
        Label lElse = new Label();
        mv.visitJumpInsn(Opcodes.IFEQ, lElse);

        if (!usesLocal)
            mv.visitVarInsn(Opcodes.ALOAD, locVarThis); // for setter invocation, load 'this'

        if (propClass.isPrimitive()) {
            mv.visitLdcInsn(pd.getName());
            mv.visitVarInsn(Opcodes.ALOAD, locVarV);
            mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(BeanHelper.class),
                    String.format("get%s%sFromPropValue",
                            propClass.getName().substring(0, 1).toUpperCase(Locale.US),
                            propClass.getName().substring(1)),
                    "(Ljava/lang/String;Ljava/lang/Object;)" + pt.getDescriptor());
        } else if (!propClass.equals(Object.class)) {
            mv.visitVarInsn(Opcodes.ALOAD, locVarV);
            mv.visitTypeInsn(Opcodes.CHECKCAST, pt.getInternalName());
        } else
            mv.visitVarInsn(Opcodes.ALOAD, locVarV);

        if (!usesLocal)
            mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, classNameInternal, pd.getSetter().getName(),
                    Type.getMethodDescriptor(pd.getSetter()));
        else
            mv.visitVarInsn(pt.getOpcode(Opcodes.ISTORE), varCount + locVarPropertiesOffset);

        mv.visitJumpInsn(Opcodes.GOTO, lEndIf);
        mv.visitLabel(lElse);

        ifCount++;
        if (usesLocal)
            varCount += pt.getSize();
    }

    // else (==> if not prop matched) throw IllegalArgumentException
    mv.visitTypeInsn(Opcodes.NEW, Type.getInternalName(IllegalArgumentException.class));
    mv.visitInsn(Opcodes.DUP);
    mv.visitLdcInsn("Unknown property \"%s\".");
    mv.visitInsn(Opcodes.ICONST_1);
    mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
    mv.visitInsn(Opcodes.DUP);
    mv.visitInsn(Opcodes.ICONST_0);
    mv.visitVarInsn(Opcodes.ALOAD, locVarK);
    mv.visitInsn(Opcodes.AASTORE);
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/String", "format",
            "(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;");
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(IllegalArgumentException.class), "<init>",
            "(Ljava/lang/String;)V");
    mv.visitInsn(Opcodes.ATHROW);

    mv.visitLabel(lCatch);
    mv.visitInsn(Opcodes.POP); // pop the exception object (not needed)
    mv.visitTypeInsn(Opcodes.NEW, Type.getInternalName(IllegalArgumentException.class));
    mv.visitInsn(Opcodes.DUP);
    mv.visitLdcInsn("Incompatible type for property \"%s\". Got %s.");
    mv.visitInsn(Opcodes.ICONST_2);
    mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
    mv.visitInsn(Opcodes.DUP);
    mv.visitInsn(Opcodes.ICONST_0);
    mv.visitVarInsn(Opcodes.ALOAD, locVarK);
    mv.visitInsn(Opcodes.AASTORE);
    mv.visitInsn(Opcodes.DUP);
    mv.visitInsn(Opcodes.ICONST_1);
    mv.visitVarInsn(Opcodes.ALOAD, locVarV);
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Object", "getClass", "()Ljava/lang/Class;");
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "getName", "()Ljava/lang/String;");
    mv.visitInsn(Opcodes.AASTORE);
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/String", "format",
            "(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;");
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(IllegalArgumentException.class), "<init>",
            "(Ljava/lang/String;)V");
    mv.visitInsn(Opcodes.ATHROW);

    mv.visitLabel(lEndIf);
    mv.visitVarInsn(Opcodes.ALOAD, locVarP);
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "org/actorsguildframework/Props", "tail",
            "()Lorg/actorsguildframework/Props;");
    mv.visitVarInsn(Opcodes.ASTORE, locVarP);

    mv.visitLabel(lEndWhile);
    mv.visitVarInsn(Opcodes.ALOAD, locVarP);
    mv.visitJumpInsn(Opcodes.IFNONNULL, lWhileBody);

    // write local variables back into properties 
    varCount = 0;
    for (PropertyDescriptor pd : localVarProperties) {
        Type pt = Type.getType(pd.getPropertyClass());
        mv.visitVarInsn(Opcodes.ALOAD, locVarThis);
        if (pd.getPropertySource() == PropertySource.ABSTRACT_METHOD) {
            mv.visitVarInsn(pt.getOpcode(Opcodes.ILOAD), locVarPropertiesOffset + varCount);
            mv.visitFieldInsn(Opcodes.PUTFIELD, classNameInternal,
                    String.format(PROP_FIELD_NAME_TEMPLATE, pd.getName()), pt.getDescriptor());
        } else if (pd.getPropertySource() == PropertySource.USER_WRITTEN) {
            mv.visitVarInsn(pt.getOpcode(Opcodes.ILOAD), locVarPropertiesOffset + varCount);
            mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, classNameInternal, pd.getSetter().getName(),
                    Type.getMethodDescriptor(pd.getSetter()));
        } else
            throw new RuntimeException("Internal error");
        varCount += pt.getSize();
    }

    // if bean is thread-safe, publish all writes now
    if (bcd.isThreadSafe()) {
        mv.visitVarInsn(Opcodes.ALOAD, locVarThis);
        mv.visitInsn(Opcodes.DUP);
        mv.visitInsn(Opcodes.MONITORENTER);
        mv.visitInsn(Opcodes.MONITOREXIT);
    }

    mv.visitInsn(Opcodes.RETURN);
    Label lEnd = new Label();
    mv.visitLabel(lEnd);

    mv.visitLocalVariable("this", classNameDescriptor, null, lBegin, lEnd, locVarThis);
    mv.visitLocalVariable("controller", "Lorg/actorsguildframework/internal/Controller;", null, lBegin, lEnd,
            locVarController);
    mv.visitLocalVariable("props", "Lorg/actorsguildframework/Props;", null, lBegin, lEnd, locVarProps);
    varCount = 0;
    for (PropertyDescriptor pd : localVarProperties) {
        Type pt = Type.getType(pd.getPropertyClass());
        mv.visitLocalVariable("__" + pd.getName(), pt.getDescriptor(),
                GenericTypeHelper.getSignature(pd.getPropertyType()), lPropertyInit, lEnd,
                locVarPropertiesOffset + varCount);
        varCount += pt.getSize();
    }
    mv.visitLocalVariable("p", "Lorg/actorsguildframework/Props;", null, lPropertyInit, lEnd, locVarP);
    mv.visitLocalVariable("k", "Ljava/lang/String;", null, lWhile, lEndWhile, locVarK);
    mv.visitLocalVariable("v", "Ljava/lang/Object;", null, lWhile, lEndWhile, locVarV);
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}

From source file:org.adjective.stout.operation.CreateArrayExpression.java

License:Apache License

public void getInstructions(ExecutionStack stack, InstructionCollector collector) {
    addInstruction(collector, ConstantIntegerExpression.getInstruction(_elements.length));

    Instruction store;/*from  w  w w.ja  va2  s .c  o m*/
    Class<?> componentClass = _componentType.getRawClass();
    if (componentClass.isPrimitive()) {
        addInstruction(collector, new IntInstruction(Opcodes.NEWARRAY, getTypeCode(componentClass)));
        store = new GenericInstruction(Type.getType(componentClass).getOpcode(Opcodes.IASTORE));
    } else {
        addInstruction(collector, new TypeInstruction(Opcodes.ANEWARRAY, _componentType.getInternalName()));
        store = new GenericInstruction(Opcodes.AASTORE);
    }

    for (int i = 0; i < _elements.length; i++) {
        addInstruction(collector, DUPLICATE);
        addInstruction(collector, ConstantIntegerExpression.getInstruction(i));
        _elements[i].getInstructions(stack, collector);
        addInstruction(collector, store);
    }

}

From source file:org.adjective.stout.tools.StackVisualiserMethodVisitor.java

License:Apache License

public void visitTypeInsn(int opcode, String type) {
    String description = type.replace('/', '.');
    Type objectType = Type.getObjectType(type);
    switch (opcode) {
    case Opcodes.NEW:
        push(simpleName(type), objectType);
        break;/*from w w w.ja  va 2s  .  c  o m*/
    case Opcodes.ANEWARRAY:
        StackValue size = pop(Type.INT_TYPE);
        push(simpleName(type) + "[" + size.description + "]", arrayOf(objectType));
        break;
    case Opcodes.CHECKCAST:
        StackValue pop = pop();
        push("(" + type + ") " + pop.description, objectType);
        break;
    default:
        throw new IllegalArgumentException("Unsupported opcode " + OPCODES[opcode]);
    }
    print(opcode, description);
}

From source file:org.boretti.drools.integration.drools5.DroolsAbstractMethodVisitor.java

License:Open Source License

private void addCondition(boolean preCondition, String type, String resourceName, Type error) {
    droolsGoalExecutionLog.getLogs()/*from   w  w w. j a v  a 2 s  .  c o  m*/
            .add(new DroolsGoalExecutionLog(droolsGoalExecutionLog.getFileName(),
                    droolsGoalExecutionLog.getAction(), "Method instrumentalization for "
                            + ((preCondition) ? "pre" : "post") + "-condition " + name + "/" + desc));
    visitor.setMethodChange(true);
    Type types[] = Type.getArgumentTypes(super.methodDesc);
    //runPreCondition
    this.visitVarInsn(Opcodes.ALOAD, 0);
    this.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getObjectType(parent).getInternalName(), "getClass",
            "()Ljava/lang/Class;");
    if (type == null)
        type = "COMPILED";
    this.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(DroolsServiceType.class), type,
            Type.getDescriptor(DroolsServiceType.class));
    this.visitLdcInsn(resourceName);
    this.visitLdcInsn(error);
    this.visitVarInsn(Opcodes.ALOAD, 0);
    this.visitIntInsn(Opcodes.BIPUSH, types.length);
    this.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
    int position = 1;
    for (int i = 0; i < types.length; i++) {
        this.visitInsn(Opcodes.DUP);
        this.visitIntInsn(Opcodes.BIPUSH, i);
        if (types[i].equals(Type.BOOLEAN_TYPE)) {
            this.visitVarInsn(Opcodes.ILOAD, position);
            this.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Boolean.class), "valueOf",
                    "(Z)Ljava/lang/Boolean;");
            position += 1;
        } else if (types[i].equals(Type.BYTE_TYPE)) {
            this.visitTypeInsn(Opcodes.NEW, "java/lang/Byte");
            this.visitInsn(Opcodes.DUP);
            this.visitVarInsn(Opcodes.ILOAD, position);
            this.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Byte.class), "<init>", "(B)V");
            position += 1;
        } else if (types[i].equals(Type.CHAR_TYPE)) {
            this.visitTypeInsn(Opcodes.NEW, "java/lang/Character");
            this.visitInsn(Opcodes.DUP);
            this.visitVarInsn(Opcodes.ILOAD, position);
            this.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Character.class), "<init>",
                    "(C)V");
            position += 1;
        } else if (types[i].equals(Type.DOUBLE_TYPE)) {
            this.visitTypeInsn(Opcodes.NEW, "java/lang/Double");
            this.visitInsn(Opcodes.DUP);
            this.visitVarInsn(Opcodes.DLOAD, position);
            this.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Double.class), "<init>", "(D)V");
            position += 2;
        } else if (types[i].equals(Type.FLOAT_TYPE)) {
            this.visitTypeInsn(Opcodes.NEW, "java/lang/Float");
            this.visitInsn(Opcodes.DUP);
            this.visitVarInsn(Opcodes.FLOAD, position);
            this.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Float.class), "<init>", "(F)V");
            position += 1;
        } else if (types[i].equals(Type.INT_TYPE)) {
            this.visitTypeInsn(Opcodes.NEW, "java/lang/Integer");
            this.visitInsn(Opcodes.DUP);
            this.visitVarInsn(Opcodes.ILOAD, position);
            this.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Integer.class), "<init>", "(I)V");
            position += 1;
        } else if (types[i].equals(Type.LONG_TYPE)) {
            this.visitTypeInsn(Opcodes.NEW, "java/lang/Long");
            this.visitInsn(Opcodes.DUP);
            this.visitVarInsn(Opcodes.LLOAD, position);
            this.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Long.class), "<init>", "(J)V");
            position += 2;
        } else if (types[i].equals(Type.SHORT_TYPE)) {
            this.visitTypeInsn(Opcodes.NEW, "java/lang/Short");
            this.visitInsn(Opcodes.DUP);
            this.visitVarInsn(Opcodes.ILOAD, position);
            this.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Short.class), "<init>", "(S)V");
            position += 1;
        } else {
            this.visitVarInsn(Opcodes.ALOAD, position);
            position += 1;
        }
        this.visitInsn(Opcodes.AASTORE);
    }
    if (preCondition)
        this.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(DroolsProvider.class),
                "runPreCondition",
                "(Ljava/lang/Class;Lorg/boretti/drools/integration/drools5/DroolsServiceType;Ljava/lang/String;Ljava/lang/Class;Ljava/lang/Object;[Ljava/lang/Object;)V");
    else
        this.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(DroolsProvider.class),
                "runPostCondition",
                "(Ljava/lang/Class;Lorg/boretti/drools/integration/drools5/DroolsServiceType;Ljava/lang/String;Ljava/lang/Class;Ljava/lang/Object;[Ljava/lang/Object;)V");
}

From source file:org.brutusin.instrumentation.Instrumentator.java

License:Apache License

private int addMethodParametersVariable(InsnList il) {
    il.add(TreeInstructions.getPushInstruction(this.methodArguments.length));
    il.add(new TypeInsnNode(Opcodes.ANEWARRAY, "java/lang/Object"));
    int methodParametersIndex = getFistAvailablePosition();
    il.add(new VarInsnNode(Opcodes.ASTORE, methodParametersIndex));
    this.mn.maxLocals++;
    for (int i = 0; i < this.methodArguments.length; i++) {
        il.add(new VarInsnNode(Opcodes.ALOAD, methodParametersIndex));
        il.add(TreeInstructions.getPushInstruction(i));
        il.add(TreeInstructions.getLoadInst(methodArguments[i], getArgumentPosition(i)));
        MethodInsnNode mNode = TreeInstructions.getWrapperContructionInst(methodArguments[i]);
        if (mNode != null) {
            il.add(mNode);/*from  w  w  w . j a va 2  s  . c o  m*/
        }
        il.add(new InsnNode(Opcodes.AASTORE));
    }
    return methodParametersIndex;
}