Example usage for org.objectweb.asm Opcodes NEW

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

Introduction

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

Prototype

int NEW

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

Click Source Link

Usage

From source file:io.syncframework.optimizer.OControllerStaticMethodVisitor.java

License:Apache License

public void visitInsn(int opcode) {
    if (opcode != Opcodes.RETURN) {
        mv.visitInsn(opcode);//from   w  ww . j  a v  a  2  s  .co m
        return;
    }

    Label start = new Label();
    Label l1 = new Label();
    Label l2 = new Label();
    Label interceptorsLabel = new Label();

    mv.visitCode();
    mv.visitTryCatchBlock(start, l1, l2, "java/lang/Throwable");

    /*
     * _asActions = new HashMap<String,Boolean>();
     */
    {
        mv.visitLabel(start);
        mv.visitTypeInsn(Opcodes.NEW, "java/util/HashMap");
        mv.visitInsn(Opcodes.DUP);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/util/HashMap", "<init>", "()V", false);
        mv.visitFieldInsn(Opcodes.PUTSTATIC, reflector.getClazzInternalName(), "_asActions", "Ljava/util/Map;");
    }
    /*
     * _asActions.put("main", true);
     * _asActions.put("action1", true);
     */
    for (String name : reflector.getActions().keySet()) {
        Label l = new Label();
        mv.visitLabel(l);
        mv.visitFieldInsn(Opcodes.GETSTATIC, reflector.getClazzInternalName(), "_asActions", "Ljava/util/Map;");
        mv.visitLdcInsn(name);
        mv.visitInsn(Opcodes.ICONST_1);
        mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;",
                false);
        mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/Map", "put",
                "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", true);
        mv.visitInsn(Opcodes.POP);
    }

    /*
     * _asInterceptors = new HashMap<String,Class<?>[]>()
     */
    {
        Label l = new Label();
        mv.visitLabel(l);
        mv.visitTypeInsn(Opcodes.NEW, "java/util/HashMap");
        mv.visitInsn(Opcodes.DUP);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/util/HashMap", "<init>", "()V", false);
        mv.visitFieldInsn(Opcodes.PUTSTATIC, reflector.getClazzInternalName(), "_asInterceptors",
                "Ljava/util/Map;");
    }

    /*
     * List<Class<?>> l = new ArrayList<Class<?>>();
     */
    mv.visitLabel(interceptorsLabel);
    mv.visitTypeInsn(Opcodes.NEW, "java/util/ArrayList");
    mv.visitInsn(Opcodes.DUP);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/util/ArrayList", "<init>", "()V", false);
    mv.visitVarInsn(Opcodes.ASTORE, 0);

    for (String name : reflector.getActions().keySet()) {
        Class<?> interceptors[] = reflector.getInterceptors().get(name);
        if (interceptors == null || interceptors.length == 0)
            continue;

        /*
         * l.clear();
         */
        Label l01 = new Label();
        mv.visitLabel(l01);
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/List", "clear", "()V", true);

        for (Class<?> interceptor : interceptors) {
            /*
             * l.add(LoginInterceptor.class);
             */
            Label l02 = new Label();
            mv.visitLabel(l02);
            mv.visitVarInsn(Opcodes.ALOAD, 0);
            mv.visitLdcInsn(Type.getType(interceptor));
            mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/List", "add", "(Ljava/lang/Object;)Z", true);
        }

        /*
         * _asInterceptors.put("upload", l.toArray(new Class[0]));
         */
        Label l03 = new Label();
        mv.visitLabel(l03);
        mv.visitFieldInsn(Opcodes.GETSTATIC, reflector.getClazzInternalName(), "_asInterceptors",
                "Ljava/util/Map;");
        mv.visitLdcInsn(name);
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitInsn(Opcodes.ICONST_0);
        mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Class");
        mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/List", "toArray",
                "([Ljava/lang/Object;)[Ljava/lang/Object;", true);
        mv.visitTypeInsn(Opcodes.CHECKCAST, "[Ljava/lang/Class;");
        mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/Map", "put",
                "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", true);
        mv.visitInsn(Opcodes.POP);
    }

    /* 
     * _asParameters = new HashMap<String,Class<?>>() 
     */
    {
        Label l = new Label();
        mv.visitLabel(l);
        mv.visitTypeInsn(Opcodes.NEW, "java/util/HashMap");
        mv.visitInsn(Opcodes.DUP);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/util/HashMap", "<init>", "()V", false);
        mv.visitFieldInsn(Opcodes.PUTSTATIC, reflector.getClazzInternalName(), "_asParameters",
                "Ljava/util/Map;");
    }
    /*
     * _asParameters.put("name", Type.class);
     */
    for (String name : reflector.getParameters().keySet()) {
        Label l = new Label();
        mv.visitLabel(l);
        mv.visitFieldInsn(Opcodes.GETSTATIC, reflector.getClazzInternalName(), "_asParameters",
                "Ljava/util/Map;");
        mv.visitLdcInsn(name);
        mv.visitLdcInsn(Type.getType(reflector.getParameters().get(name)));
        mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/Map", "put",
                "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", true);
        mv.visitInsn(Opcodes.POP);
    }

    /* 
     * _asConverters = new HashMap<String,Class<?>>() 
     */
    {
        Label l = new Label();
        mv.visitLabel(l);
        mv.visitTypeInsn(Opcodes.NEW, "java/util/HashMap");
        mv.visitInsn(Opcodes.DUP);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/util/HashMap", "<init>", "()V", false);
        mv.visitFieldInsn(Opcodes.PUTSTATIC, reflector.getClazzInternalName(), "_asConverters",
                "Ljava/util/Map;");
    }
    /*
     * _asConverters.put("name", Type.class);
     */
    for (String name : reflector.getParameters().keySet()) {
        if (reflector.getConverters().get(name) != null) {
            Class<?> converter = reflector.getConverters().get(name);
            Label l = new Label();
            mv.visitLabel(l);
            mv.visitFieldInsn(Opcodes.GETSTATIC, reflector.getClazzInternalName(), "_asConverters",
                    "Ljava/util/Map;");
            mv.visitLdcInsn(name);
            mv.visitLdcInsn(Type.getType(converter));
            mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/Map", "put",
                    "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", true);
            mv.visitInsn(Opcodes.POP);
        }
    }

    /*
     * }
     * catch(Throwable t) {
     *    throw t;
     * }
     */
    Label throwableStart = new Label();
    Label throwableEnd = new Label();

    mv.visitLabel(l1);
    mv.visitJumpInsn(Opcodes.GOTO, throwableEnd);
    mv.visitLabel(l2);
    mv.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[] { "java/lang/Throwable" });
    mv.visitVarInsn(Opcodes.ASTORE, 0);
    mv.visitLabel(throwableStart);
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitInsn(Opcodes.ATHROW);

    mv.visitLabel(throwableEnd);
    mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
    mv.visitInsn(Opcodes.RETURN);
    mv.visitLocalVariable("l", "Ljava/util/List;", null, interceptorsLabel, l1, 0);
    mv.visitLocalVariable("t", "Ljava/lang/Throwable;", null, throwableStart, throwableEnd, 0);
}

From source file:io.syncframework.optimizer.OInterceptorStaticMethodVisitor.java

License:Apache License

public void visitInsn(int opcode) {
    if (opcode != Opcodes.RETURN) {
        mv.visitInsn(opcode);/*from  w  w w  .java  2 s  . c o m*/
        return;
    }

    Label start = new Label();
    Label l1 = new Label();
    Label l2 = new Label();

    mv.visitCode();
    mv.visitTryCatchBlock(start, l1, l2, "java/lang/Throwable");

    /* 
     * _asParameters = new HashMap<String,Class<?>>() 
     */
    {
        mv.visitLabel(start);
        mv.visitTypeInsn(Opcodes.NEW, "java/util/HashMap");
        mv.visitInsn(Opcodes.DUP);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/util/HashMap", "<init>", "()V", false);
        mv.visitFieldInsn(Opcodes.PUTSTATIC, reflector.getClazzInternalName(), "_asParameters",
                "Ljava/util/Map;");
    }
    /*
     * _asParameters.put("name", Type.class);
     */
    for (String name : reflector.getParameters().keySet()) {
        Label l = new Label();
        mv.visitLabel(l);
        mv.visitFieldInsn(Opcodes.GETSTATIC, reflector.getClazzInternalName(), "_asParameters",
                "Ljava/util/Map;");
        mv.visitLdcInsn(name);
        mv.visitLdcInsn(Type.getType(reflector.getParameters().get(name)));
        mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/Map", "put",
                "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", true);
        mv.visitInsn(Opcodes.POP);
    }

    /* 
     * _asConverters = new HashMap<String,Class<?>>() 
     */
    {
        Label l = new Label();
        mv.visitLabel(l);
        mv.visitTypeInsn(Opcodes.NEW, "java/util/HashMap");
        mv.visitInsn(Opcodes.DUP);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/util/HashMap", "<init>", "()V", false);
        mv.visitFieldInsn(Opcodes.PUTSTATIC, reflector.getClazzInternalName(), "_asConverters",
                "Ljava/util/Map;");
    }
    /*
     * _asConverters.put("name", Type.class);
     */
    for (String name : reflector.getParameters().keySet()) {
        if (reflector.getConverters().get(name) != null) {
            Class<?> converter = reflector.getConverters().get(name);
            Label l = new Label();
            mv.visitLabel(l);
            mv.visitFieldInsn(Opcodes.GETSTATIC, reflector.getClazzInternalName(), "_asConverters",
                    "Ljava/util/Map;");
            mv.visitLdcInsn(name);
            mv.visitLdcInsn(Type.getType(converter));
            mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/Map", "put",
                    "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", true);
            mv.visitInsn(Opcodes.POP);
        }
    }

    /*
     * }
     * catch(Throwable t) {
     *    throw t;
     * }
     */
    Label throwableStart = new Label();
    Label throwableEnd = new Label();

    mv.visitLabel(l1);
    mv.visitJumpInsn(Opcodes.GOTO, throwableEnd);

    mv.visitLabel(l2);
    mv.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[] { "java/lang/Throwable" });
    mv.visitVarInsn(Opcodes.ASTORE, 0);

    mv.visitLabel(throwableStart);
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitInsn(Opcodes.ATHROW);

    mv.visitLabel(throwableEnd);
    mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
    mv.visitInsn(Opcodes.RETURN);
    mv.visitLocalVariable("t", "Ljava/lang/Throwable;", null, throwableStart, throwableEnd, 0);
}

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

License:Open Source License

/**
 * Generate the required Java code to load one parameter for
 * the syscall function from the CPU registers.
 *
 * The following code is generated based on the parameter type:
 * Processor: parameterValue = RuntimeContext.processor
 * int:       parameterValue = cpu.gpr[paramIndex++]
 * float:     parameterValue = cpu.fpr[paramFloatIndex++]
 * long:      parameterValue = (cpu.gpr[paramIndex++] & 0xFFFFFFFFL) + ((long) cpu.gpr[paramIndex++]) << 32)
 * boolean:   parameterValue = cpu.gpr[paramIndex++]
 * TPointer,//from ww w.  ja v  a 2s .  c  o m
 * TPointer8,
 * TPointer16,
 * TPointer32,
 * TPointer64,
 * TErrorPointer32:
 *            if (checkMemoryAccess()) {
 *                if (canBeNullParam && address == 0) {
 *                    goto addressGood;
 *                }
 *                if (RuntimeContext.checkMemoryPointer(address)) {
 *                    goto addressGood;
 *                }
 *                cpu.gpr[_v0] = SceKernelErrors.ERROR_INVALID_POINTER;
 *                pop all the parameters already prepared on the stack;
 *                goto afterSyscall;
 *                addressGood:
 *            }
 *            <parameterType> pointer = new <parameterType>(address);
 *            if (parameterType == TErrorPointer32.class) {
 *                parameterReader.setHasErrorPointer(true);
 *                localVar[LOCAL_ERROR_POINTER] = pointer;
 *            }
 *            parameterValue = pointer
 * HLEUidClass defined in annotation:
 *            <parameterType> uidObject = HLEUidObjectMapping.getObject("<parameterType>", uid);
 *            if (uidObject == null) {
 *                cpu.gpr[_v0] = errorValueOnNotFound;
 *                pop all the parameters already prepared on the stack;
 *                goto afterSyscall;
 *            }
 *            parameterValue = uidObject
 *
 * And then common for all the types:
 *            try {
 *                parameterValue = <module>.<methodToCheck>(parameterValue);
 *            } catch (SceKernelErrorException e) {
 *                goto catchSceKernelErrorException;
 *            }
 *            push parameterValue on stack
 *
 * @param parameterReader               the current parameter state
 * @param func                          the syscall function
 * @param parameterType                 the type of the parameter
 * @param afterSyscallLabel             the Label pointing after the call to the syscall function
 * @param catchSceKernelErrorException  the Label pointing to the SceKernelErrorException catch handler
 */
private void loadParameter(CompilerParameterReader parameterReader, HLEModuleFunction func,
        Class<?> parameterType, Annotation[] parameterAnnotations, Label afterSyscallLabel,
        Label catchSceKernelErrorException) {
    if (parameterType == Processor.class) {
        loadProcessor();
        parameterReader.incrementCurrentStackSize();
    } else if (parameterType == CpuState.class) {
        loadCpu();
        parameterReader.incrementCurrentStackSize();
    } else if (parameterType == int.class) {
        parameterReader.loadNextInt();
        parameterReader.incrementCurrentStackSize();
    } else if (parameterType == float.class) {
        parameterReader.loadNextFloat();
        parameterReader.incrementCurrentStackSize();
    } else if (parameterType == long.class) {
        parameterReader.loadNextLong();
        parameterReader.incrementCurrentStackSize(2);
    } else if (parameterType == boolean.class) {
        parameterReader.loadNextInt();
        parameterReader.incrementCurrentStackSize();
    } else if (parameterType == String.class) {
        parameterReader.loadNextInt();

        int maxLength = 16 * 1024;
        for (Annotation parameterAnnotation : parameterAnnotations) {
            if (parameterAnnotation instanceof StringInfo) {
                StringInfo stringInfo = ((StringInfo) parameterAnnotation);
                maxLength = stringInfo.maxLength();
                break;
            }
        }
        loadImm(maxLength);
        mv.visitMethodInsn(Opcodes.INVOKESTATIC, runtimeContextInternalName, "readStringNZ",
                "(II)" + Type.getDescriptor(String.class));
        parameterReader.incrementCurrentStackSize();
    } else if (parameterType == PspString.class) {
        parameterReader.loadNextInt();

        int maxLength = 16 * 1024;
        boolean canBeNull = false;
        for (Annotation parameterAnnotation : parameterAnnotations) {
            if (parameterAnnotation instanceof StringInfo) {
                StringInfo stringInfo = ((StringInfo) parameterAnnotation);
                maxLength = stringInfo.maxLength();
            }
            if (parameterAnnotation instanceof CanBeNull) {
                canBeNull = true;
            }
        }
        loadImm(maxLength);
        loadImm(canBeNull);
        mv.visitMethodInsn(Opcodes.INVOKESTATIC, runtimeContextInternalName, "readPspStringNZ",
                "(IIZ)" + Type.getDescriptor(PspString.class));
        parameterReader.incrementCurrentStackSize();
    } else if (parameterType == TPointer.class || parameterType == TPointer8.class
            || parameterType == TPointer16.class || parameterType == TPointer32.class
            || parameterType == TPointer64.class || parameterType == TErrorPointer32.class) {
        // if (checkMemoryAccess()) {
        //     if (canBeNullParam && address == 0) {
        //         goto addressGood;
        //     }
        //     if (RuntimeContext.checkMemoryPointer(address)) {
        //         goto addressGood;
        //     }
        //     cpu.gpr[_v0] = SceKernelErrors.ERROR_INVALID_POINTER;
        //     pop all the parameters already prepared on the stack;
        //     goto afterSyscall;
        //     addressGood:
        // }
        // <parameterType> pointer = new <parameterType>(address);
        // if (parameterType == TErrorPointer32.class) {
        //     parameterReader.setHasErrorPointer(true);
        //     localVar[LOCAL_ERROR_POINTER] = pointer;
        // }
        mv.visitTypeInsn(Opcodes.NEW, Type.getInternalName(parameterType));
        mv.visitInsn(Opcodes.DUP);
        loadMemory();
        parameterReader.loadNextInt();

        boolean canBeNull = false;
        for (Annotation parameterAnnotation : parameterAnnotations) {
            if (parameterAnnotation instanceof CanBeNull) {
                canBeNull = true;
                break;
            }
        }

        if (checkMemoryAccess() && afterSyscallLabel != null) {
            Label addressGood = new Label();
            if (canBeNull) {
                mv.visitInsn(Opcodes.DUP);
                mv.visitJumpInsn(Opcodes.IFEQ, addressGood);
            }
            mv.visitInsn(Opcodes.DUP);
            mv.visitMethodInsn(Opcodes.INVOKESTATIC, runtimeContextInternalName, "checkMemoryPointer", "(I)Z");
            mv.visitJumpInsn(Opcodes.IFNE, addressGood);
            storeRegister(_v0, SceKernelErrors.ERROR_INVALID_POINTER);
            parameterReader.popAllStack(4);
            mv.visitJumpInsn(Opcodes.GOTO, afterSyscallLabel);
            mv.visitLabel(addressGood);
        }
        if (parameterType == TPointer8.class || parameterType == TPointer16.class
                || parameterType == TPointer32.class || parameterType == TPointer64.class) {
            loadImm(canBeNull);
            mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(parameterType), "<init>",
                    "(" + memoryDescriptor + "IZ)V");
        } else {
            mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(parameterType), "<init>",
                    "(" + memoryDescriptor + "I)V");
        }
        if (parameterType == TErrorPointer32.class) {
            parameterReader.setHasErrorPointer(true);
            mv.visitInsn(Opcodes.DUP);
            mv.visitVarInsn(Opcodes.ASTORE, LOCAL_ERROR_POINTER);
        }
        parameterReader.incrementCurrentStackSize();
    } else if (pspAbstractMemoryMappedStructure.class.isAssignableFrom(parameterType)) {
        parameterReader.loadNextInt();

        boolean canBeNull = false;
        for (Annotation parameterAnnotation : parameterAnnotations) {
            if (parameterAnnotation instanceof CanBeNull) {
                canBeNull = true;
                break;
            }
        }

        if (checkMemoryAccess() && afterSyscallLabel != null) {
            Label addressGood = new Label();
            if (canBeNull) {
                mv.visitInsn(Opcodes.DUP);
                mv.visitJumpInsn(Opcodes.IFEQ, addressGood);
            }
            mv.visitInsn(Opcodes.DUP);
            mv.visitMethodInsn(Opcodes.INVOKESTATIC, runtimeContextInternalName, "checkMemoryPointer", "(I)Z");
            mv.visitJumpInsn(Opcodes.IFNE, addressGood);
            storeRegister(_v0, SceKernelErrors.ERROR_INVALID_POINTER);
            parameterReader.popAllStack(1);
            mv.visitJumpInsn(Opcodes.GOTO, afterSyscallLabel);
            mv.visitLabel(addressGood);
        }

        mv.visitTypeInsn(Opcodes.NEW, Type.getInternalName(parameterType));
        mv.visitInsn(Opcodes.DUP);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(parameterType), "<init>", "()V");
        mv.visitInsn(Opcodes.DUP_X1);
        mv.visitInsn(Opcodes.SWAP);
        loadMemory();
        mv.visitInsn(Opcodes.SWAP);
        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(parameterType), "read",
                "(" + memoryDescriptor + "I)V");
        parameterReader.incrementCurrentStackSize();
    } else {
        HLEUidClass hleUidClass = parameterType.getAnnotation(HLEUidClass.class);
        if (hleUidClass != null) {
            int errorValueOnNotFound = hleUidClass.errorValueOnNotFound();

            // <parameterType> uidObject = HLEUidObjectMapping.getObject("<parameterType>", uid);
            // if (uidObject == null) {
            //     cpu.gpr[_v0] = errorValueOnNotFound;
            //     pop all the parameters already prepared on the stack;
            //     goto afterSyscall;
            // }
            mv.visitLdcInsn(parameterType.getName());
            // Load the UID
            parameterReader.loadNextInt();

            // Load the UID Object
            mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(HLEUidObjectMapping.class),
                    "getObject",
                    "(" + Type.getDescriptor(String.class) + "I)" + Type.getDescriptor(Object.class));
            if (afterSyscallLabel != null) {
                Label foundUid = new Label();
                mv.visitInsn(Opcodes.DUP);
                mv.visitJumpInsn(Opcodes.IFNONNULL, foundUid);
                storeRegister(_v0, errorValueOnNotFound);
                parameterReader.popAllStack(1);
                mv.visitJumpInsn(Opcodes.GOTO, afterSyscallLabel);
                mv.visitLabel(foundUid);
            }
            mv.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(parameterType));
            parameterReader.incrementCurrentStackSize();
        } else {
            log.error(String.format("Unsupported sycall parameter type '%s'", parameterType.getName()));
            Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_UNIMPLEMENTED);
        }
    }

    Method methodToCheck = null;
    if (afterSyscallLabel != null) {
        for (Annotation parameterAnnotation : parameterAnnotations) {
            if (parameterAnnotation instanceof CheckArgument) {
                CheckArgument checkArgument = (CheckArgument) parameterAnnotation;
                try {
                    methodToCheck = func.getHLEModule().getClass().getMethod(checkArgument.value(),
                            parameterType);
                } catch (Exception e) {
                    log.error(String.format("CheckArgument method '%s' not found in %s", checkArgument.value(),
                            func.getModuleName()), e);
                }
                break;
            }
        }
    }

    if (methodToCheck != null) {
        // try {
        //     parameterValue = <module>.<methodToCheck>(parameterValue);
        // } catch (SceKernelErrorException e) {
        //     goto catchSceKernelErrorException;
        // }
        loadModule(func.getModuleName());
        mv.visitInsn(Opcodes.SWAP);

        Label tryStart = new Label();
        Label tryEnd = new Label();
        mv.visitTryCatchBlock(tryStart, tryEnd, catchSceKernelErrorException,
                Type.getInternalName(SceKernelErrorException.class));

        mv.visitLabel(tryStart);
        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(methodToCheck.getDeclaringClass()),
                methodToCheck.getName(),
                "(" + Type.getDescriptor(parameterType) + ")" + Type.getDescriptor(parameterType));
        mv.visitLabel(tryEnd);
    }

    parameterReader.incrementCurrentParameterIndex();
}

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

License:Open Source License

private void logSyscall(HLEModuleFunction func, String logPrefix, String logCheckFunction, String logFunction) {
    // Modules.getLogger(func.getModuleName()).warn("Unimplemented...");
    loadModuleLoggger(func);/*from  w  w w .  ja v a  2 s.c  om*/
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Logger.class), logCheckFunction, "()Z");
    Label loggingDisabled = new Label();
    mv.visitJumpInsn(Opcodes.IFEQ, loggingDisabled);

    loadModuleLoggger(func);

    StringBuilder formatString = new StringBuilder();
    if (logPrefix != null) {
        formatString.append(logPrefix);
    }
    formatString.append(func.getFunctionName());
    ParameterInfo[] parameters = new ClassAnalyzer().getParameters(func.getFunctionName(),
            func.getHLEModuleMethod().getDeclaringClass());
    if (parameters != null) {
        // Log message:
        //    String.format(
        //       "Unimplemented <function name>
        //                 <parameterIntegerName>=0x%X,
        //                 <parameterBooleanName>=%b,
        //                 <parameterLongName>=0x%X,
        //                 <parameterFloatName>=%f,
        //                 <parameterOtherTypeName>=%s",
        //       new Object[] {
        //                 new Integer(parameterValueInteger),
        //                 new Boolean(parameterValueBoolean),
        //                 new Long(parameterValueLong),
        //                 new Float(parameterValueFloat),
        //                 parameterValueOtherTypes
        //       })
        loadImm(parameters.length);
        mv.visitTypeInsn(Opcodes.ANEWARRAY, Type.getInternalName(Object.class));
        CompilerParameterReader parameterReader = new CompilerParameterReader(this);
        Annotation[][] paramsAnotations = func.getHLEModuleMethod().getParameterAnnotations();
        int objectArrayIndex = 0;
        for (int paramIndex = 0; paramIndex < parameters.length; paramIndex++) {
            ParameterInfo parameter = parameters[paramIndex];
            Class<?> parameterType = parameter.type;
            CompilerTypeInformation typeInformation = compilerTypeManager
                    .getCompilerTypeInformation(parameterType);

            mv.visitInsn(Opcodes.DUP);
            loadImm(objectArrayIndex);

            formatString.append(paramIndex > 0 ? ", " : " ");
            formatString.append(parameter.name);
            formatString.append("=");
            formatString.append(typeInformation.formatString);

            if (typeInformation.boxingTypeInternalName != null) {
                mv.visitTypeInsn(Opcodes.NEW, typeInformation.boxingTypeInternalName);
                mv.visitInsn(Opcodes.DUP);
            }

            loadParameter(parameterReader, func, parameterType, paramsAnotations[paramIndex], null, null);

            if (typeInformation.boxingTypeInternalName != null) {
                mv.visitMethodInsn(Opcodes.INVOKESPECIAL, typeInformation.boxingTypeInternalName, "<init>",
                        typeInformation.boxingMethodDescriptor);
            }
            mv.visitInsn(Opcodes.AASTORE);

            objectArrayIndex++;
        }
        mv.visitLdcInsn(formatString.toString());
        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), logFunction,
                "(" + Type.getDescriptor(Object.class) + ")V");

        parameterReader = new CompilerParameterReader(this);
        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;
            for (Annotation parameterAnnotation : paramsAnotations[paramIndex]) {
                if (parameterAnnotation instanceof BufferInfo) {
                    BufferInfo bufferInfo = (BufferInfo) parameterAnnotation;
                    lengthInfo = bufferInfo.lengthInfo();
                    length = bufferInfo.length();
                    usage = bufferInfo.usage();
                }
            }

            boolean parameterRead = false;
            if ((usage == Usage.in || 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 unknown:
                    useMemoryDump = false;
                    format = String.format("%s[%s]: 0x%%X", parameter.name, usage);
                    loadMemory();
                    mv.visitInsn(Opcodes.SWAP);
                    if (parameterType == TPointer64.class) {
                        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) {
                        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 {
                        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) {
                    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), logFunction,
                        "(" + 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();
                }
            }
        }
    } else {
        mv.visitLdcInsn(formatString.toString());
        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Logger.class), logFunction,
                "(" + Type.getDescriptor(Object.class) + ")V");
    }

    mv.visitLabel(loggingDisabled);
}

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  ww w  .  ja  v  a2s .  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:me.rojo8399.placeholderapi.impl.placeholder.gen.ClassPlaceholderFactory.java

License:Open Source License

private static void nullCheck(MethodVisitor mv, boolean nullable, Consumer<MethodVisitor> success,
        boolean throwError) {
    if (nullable) {
        return;/*from   w  ww .  j  a v a 2  s .c  o  m*/
    }
    // assume null check obj already loaded to stack
    Label no = new Label();
    mv.visitJumpInsn(IFNONNULL, no);
    if (throwError) {
        mv.visitTypeInsn(Opcodes.NEW, Type.getInternalName(NoValueException.class));
        mv.visitVarInsn(ASTORE, 7);
        mv.visitVarInsn(ALOAD, 7);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(NoValueException.class), "<init>", "()V",
                false);
        mv.visitVarInsn(ALOAD, 7);
        mv.visitInsn(Opcodes.ATHROW);
    } else {
        mv.visitInsn(ACONST_NULL);
        mv.visitInsn(ARETURN);
    }
    mv.visitLabel(no);
    success.accept(mv);
}

From source file:me.themallard.bitmmo.impl.plugin.SimplePlugin.java

License:Open Source License

private void createInstances(ClassNode cn) {
    for (MethodNode mn : cn.methods) {
        if (!new PatternBuilder().add(new LdcElement(new LdcInsnNode("PulpCore-Destroyer"))).build()
                .contains(mn.instructions))
            continue;

        for (String clazz : instancesCreate) {
            InsnList inject = new InsnList();

            inject.add(new TypeInsnNode(Opcodes.NEW, clazz));
            inject.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, clazz, "<init>", "()V", false));

            mn.instructions.insertBefore(mn.instructions.get(0), inject);
        }/*from  w  w w.  j a v a 2 s .  co m*/
    }
}

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   w ww.  ja v  a 2s. 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:org.actorsguildframework.internal.codegenerator.ActorProxyCreator.java

License:Apache License

/**
 * Creates and loads the actor's proxy class.
 * @param actorClass the Actor class/* w ww . ja v  a2 s .c o  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);
    }
}

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

License:Apache License

/**
 * Writes a proxy method for messages./*from   w  ww.j av  a 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();
    }
}