Java Code Examples for org.objectweb.asm.MethodVisitor#visitTypeInsn()

The following examples show how to use org.objectweb.asm.MethodVisitor#visitTypeInsn() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: jadira   File: InvokeDynamicClassAccess.java    License: Apache License 2.0 6 votes vote down vote up
private static void enhanceForNewInstanceInner(ClassVisitor cw, String classNm, String enclosingClassNm) {
    MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "newInstance", "()LLjava/lang/Object;", null, null);
    mv.visitCode();
    mv.visitTypeInsn(NEW, classNm);
    mv.visitInsn(DUP);
    mv.visitTypeInsn(NEW, enclosingClassNm);
    mv.visitInsn(DUP);
    mv.visitMethodInsn(INVOKESPECIAL, enclosingClassNm, "<init>", "()V");
    mv.visitInsn(DUP);
    mv.visitMethodInsn(INVOKEVIRTUAL, classNm, "getClass", "()Ljava/lang/Class;");
    mv.visitInsn(POP);
    mv.visitMethodInsn(INVOKESPECIAL, classNm, "<init>", "(L" + enclosingClassNm + ";)V");
    mv.visitInsn(ARETURN);
    mv.visitMaxs(4, 1);
    mv.visitEnd();
}
 
Example 2
Source Project: sumk   File: WriterHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static void buildParamArray(MethodVisitor mv, Class<?>[] params) {
	final int len = params == null ? 0 : params.length;
	visitInt(mv, len);

	mv.visitTypeInsn(ANEWARRAY, "java/lang/Object");
	if (len == 0) {
		return;
	}
	int frameIndex = 1;
	for (int i = 0; i < len; i++) {
		mv.visitInsn(DUP);
		visitInt(mv, i);
		Class<?> argType = params[i];
		frameIndex += loadFromLocalVariable(mv, argType, frameIndex, true);
		mv.visitInsn(AASTORE);
	}
}
 
Example 3
Source Project: bistoury   File: CodeFlow.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Produce the correct bytecode to build an array. The opcode to use and the
 * signature to pass along with the opcode can vary depending on the signature
 * of the array type.
 *
 * @param mv        the methodvisitor into which code should be inserted
 * @param size      the size of the array
 * @param arraytype the type of the array
 */
public static void insertNewArrayCode(MethodVisitor mv, int size, String arraytype) {
    insertOptimalLoad(mv, size);
    if (arraytype.length() == 1) {
        mv.visitIntInsn(NEWARRAY, CodeFlow.arrayCodeFor(arraytype));
    } else {
        if (arraytype.charAt(0) == '[') {
            // Handling the nested array case here. If vararg
            // is [[I then we want [I and not [I;
            if (CodeFlow.isReferenceTypeArray(arraytype)) {
                mv.visitTypeInsn(ANEWARRAY, arraytype + ";");
            } else {
                mv.visitTypeInsn(ANEWARRAY, arraytype);
            }
        } else {
            mv.visitTypeInsn(ANEWARRAY, arraytype.substring(1));
        }
    }
}
 
Example 4
Source Project: Stark   File: RedirectionVisitor.java    License: Apache License 2.0 6 votes vote down vote up
private void addInterfaceClassInitializerCode(MethodVisitor mv) {
    mv.visitTypeInsn(Opcodes.NEW, "java/util/concurrent/atomic/AtomicReference");
    mv.visitInsn(Opcodes.DUP);
    mv.visitInsn(Opcodes.ACONST_NULL);
    mv.visitMethodInsn(
            Opcodes.INVOKESPECIAL,
            "java/util/concurrent/atomic/AtomicReference",
            "<init>",
            "(Ljava/lang/Object;)V",
            false);
    mv.visitFieldInsn(
            Opcodes.PUTSTATIC,
            visitedClassName,
            "$starkChange",
            "Ljava/util/concurrent/atomic/AtomicReference;");
}
 
Example 5
Source Project: Mixin   File: ArgsClassGenerator.java    License: MIT License 5 votes vote down vote up
/**
 * Unbox (if necessary, otherwise just <tt>CHECKCAST</tt>) the supplied type
 * 
 * @param method method visitor
 * @param var type to unbox
 */
private static void unbox(MethodVisitor method, Type var) {
    String boxingType = Bytecode.getBoxingType(var);
    if (boxingType != null) {
        String unboxingMethod = Bytecode.getUnboxingMethod(var);
        String desc = "()" + var.getDescriptor();
        method.visitTypeInsn(Opcodes.CHECKCAST, boxingType);
        method.visitMethodInsn(Opcodes.INVOKEVIRTUAL, boxingType, unboxingMethod, desc, false);
    } else {
        method.visitTypeInsn(Opcodes.CHECKCAST, var.getInternalName());
    }
}
 
Example 6
void generateClinitCode(String clazzname, String constantFieldName, MethodVisitor mv, CodeFlow codeflow, boolean nested) {
    mv.visitTypeInsn(NEW, "java/util/ArrayList");
    mv.visitInsn(DUP);
    mv.visitMethodInsn(INVOKESPECIAL, "java/util/ArrayList", "<init>", "()V", false);
    if (!nested) {
        mv.visitFieldInsn(PUTSTATIC, clazzname, constantFieldName, "Ljava/util/List;");
    }
    int childCount = getChildCount();
    for (int c = 0; c < childCount; c++) {
        if (!nested) {
            mv.visitFieldInsn(GETSTATIC, clazzname, constantFieldName, "Ljava/util/List;");
        } else {
            mv.visitInsn(DUP);
        }
        // The children might be further lists if they are not constants. In this
        // situation do not call back into generateCode() because it will register another clinit adder.
        // Instead, directly build the list here:
        if (children[c] instanceof InlineList) {
            ((InlineList) children[c]).generateClinitCode(clazzname, constantFieldName, mv, codeflow, true);
        } else {
            children[c].generateCode(mv, codeflow);
            if (CodeFlow.isPrimitive(codeflow.lastDescriptor())) {
                CodeFlow.insertBoxIfNecessary(mv, codeflow.lastDescriptor().charAt(0));
            }
        }
        mv.visitMethodInsn(INVOKEINTERFACE, "java/util/List", "add", "(Ljava/lang/Object;)Z", true);
        mv.visitInsn(POP);
    }
}
 
Example 7
Source Project: AVM   File: ArrayWrappingClassGenerator.java    License: MIT License 5 votes vote down vote up
private static void genClone(ClassWriter cw, String wrapper) {
    String cloneMethodName = "avm_clone";
    String cloneMethodDesc = "()Li/IObject;";
    MethodVisitor methodVisitor = cw.visitMethod(ACC_PUBLIC, cloneMethodName, cloneMethodDesc, null, null);

    // energy charge
    methodVisitor.visitLdcInsn(RuntimeMethodFeeSchedule.ObjectArray_avm_clone);
    methodVisitor.visitVarInsn(ALOAD, 0);
    methodVisitor.visitMethodInsn(INVOKEVIRTUAL, wrapper, "length", "()I", false);
    methodVisitor.visitMethodInsn(INVOKESTATIC, SHADOW_ARRAY, "chargeEnergyClone", "(II)V", false);

    // lazyLoad
    methodVisitor.visitVarInsn(ALOAD, 0);
    methodVisitor.visitMethodInsn(INVOKEVIRTUAL, wrapper, "lazyLoad", "()V", false);

    methodVisitor.visitCode();
    methodVisitor.visitTypeInsn(NEW, wrapper);
    methodVisitor.visitInsn(DUP);
    methodVisitor.visitVarInsn(ALOAD, 0);
    methodVisitor.visitFieldInsn(GETFIELD, wrapper, "underlying", "[Ljava/lang/Object;");
    methodVisitor.visitVarInsn(ALOAD, 0);
    methodVisitor.visitFieldInsn(GETFIELD, wrapper, "underlying", "[Ljava/lang/Object;");
    methodVisitor.visitInsn(ARRAYLENGTH);
    methodVisitor.visitMethodInsn(INVOKESTATIC, "java/util/Arrays", "copyOf", "([Ljava/lang/Object;I)[Ljava/lang/Object;", false);
    methodVisitor.visitMethodInsn(INVOKESPECIAL, wrapper, "<init>", "([Ljava/lang/Object;)V", false);
    methodVisitor.visitInsn(ARETURN);
    methodVisitor.visitMaxs(4, 1);
    methodVisitor.visitEnd();
}
 
Example 8
Source Project: groovy   File: StatementWriter.java    License: Apache License 2.0 5 votes vote down vote up
public void writeThrow(final ThrowStatement statement) {
    controller.getAcg().onLineNumber(statement, "visitThrowStatement");
    writeStatementLabel(statement);
    MethodVisitor mv = controller.getMethodVisitor();

    statement.getExpression().visit(controller.getAcg());

    // we should infer the type of the exception from the expression
    mv.visitTypeInsn(CHECKCAST, "java/lang/Throwable");
    mv.visitInsn(ATHROW);

    controller.getOperandStack().remove(1);
}
 
Example 9
static void insertNewInstance (ClassWriter cw, String classNameInternal) {
	MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "newInstance", "()Ljava/lang/Object;", null, null);
	mv.visitCode();
	mv.visitTypeInsn(NEW, classNameInternal);
	mv.visitInsn(DUP);
	mv.visitMethodInsn(INVOKESPECIAL, classNameInternal, "<init>", "()V");
	mv.visitInsn(ARETURN);
	mv.visitMaxs(2, 1);
	mv.visitEnd();
}
 
Example 10
static private void insertGetString (ClassWriter cw, String classNameInternal, ArrayList<Field> fields) {
	int maxStack = 6;
	MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "getString", "(Ljava/lang/Object;I)Ljava/lang/String;", null, null);
	mv.visitCode();
	mv.visitVarInsn(ILOAD, 2);

	if (!fields.isEmpty()) {
		maxStack--;
		Label[] labels = new Label[fields.size()];
		Label labelForInvalidTypes = new Label();
		boolean hasAnyBadTypeLabel = false;
		for (int i = 0, n = labels.length; i < n; i++) {
			if (fields.get(i).getType().equals(String.class))
				labels[i] = new Label();
			else {
				labels[i] = labelForInvalidTypes;
				hasAnyBadTypeLabel = true;
			}
		}
		Label defaultLabel = new Label();
		mv.visitTableSwitchInsn(0, labels.length - 1, defaultLabel, labels);

		for (int i = 0, n = labels.length; i < n; i++) {
			if (!labels[i].equals(labelForInvalidTypes)) {
				Field field = fields.get(i);
				mv.visitLabel(labels[i]);
				mv.visitFrame(F_SAME, 0, null, 0, null);
				mv.visitVarInsn(ALOAD, 1);
				mv.visitTypeInsn(CHECKCAST, classNameInternal);
				mv.visitFieldInsn(GETFIELD, field.getDeclaringClass().getName().replace('.', '/'), field.getName(),
					"Ljava/lang/String;");
				mv.visitInsn(ARETURN);
			}
		}
		// Rest of fields: different type
		if (hasAnyBadTypeLabel) {
			mv.visitLabel(labelForInvalidTypes);
			mv.visitFrame(F_SAME, 0, null, 0, null);
			insertThrowExceptionForFieldType(mv, "String");
		}
		// Default: field not found
		mv.visitLabel(defaultLabel);
		mv.visitFrame(F_SAME, 0, null, 0, null);
	}
	insertThrowExceptionForFieldNotFound(mv);
	mv.visitMaxs(maxStack, 3);
	mv.visitEnd();
}
 
Example 11
private void generateJvmBridge(MethodInfo method) {
    // get a bounds-erased descriptor
    String descriptor = AsmUtil.getDescriptor(method, name -> null);
    // make sure we need a bridge
    if (!userMethods.contains(method.name() + "/" + descriptor)) {
        MethodVisitor mv = super.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC | Opcodes.ACC_BRIDGE,
                method.name(),
                descriptor,
                null,
                null);
        List<org.jboss.jandex.Type> parameters = method.parameters();
        for (int i = 0; i < parameters.size(); i++) {
            mv.visitParameter(method.parameterName(i), 0 /* modifiers */);
        }
        mv.visitCode();
        // this
        mv.visitIntInsn(Opcodes.ALOAD, 0);
        // each param
        for (int i = 0; i < parameters.size(); i++) {
            org.jboss.jandex.Type paramType = parameters.get(i);
            if (paramType.kind() == Kind.PRIMITIVE)
                throw new IllegalStateException("BUG: Don't know how to generate JVM bridge method for " + method
                        + ": has primitive parameters");
            mv.visitIntInsn(Opcodes.ALOAD, i + 1);
            if (paramType.kind() == Kind.TYPE_VARIABLE) {
                String typeParamName = paramType.asTypeVariable().identifier();
                switch (typeParamName) {
                    case "Entity":
                        mv.visitTypeInsn(Opcodes.CHECKCAST, entityBinaryType);
                        break;
                    case "Id":
                        mv.visitTypeInsn(Opcodes.CHECKCAST, idBinaryType);
                        break;
                }
            }
        }

        String targetDescriptor = AsmUtil.getDescriptor(method, name -> typeArguments.get(name));
        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
                daoBinaryName,
                method.name(),
                targetDescriptor, false);
        String targetReturnTypeDescriptor = targetDescriptor.substring(targetDescriptor.indexOf(')') + 1);
        mv.visitInsn(AsmUtil.getReturnInstruction(targetReturnTypeDescriptor));
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }

}
 
Example 12
Source Project: jadira   File: AsmClassAccess.java    License: Apache License 2.0 4 votes vote down vote up
private static void enhanceForGetValueObject(ClassVisitor cw, String accessClassNm, String clazzNm, Field[] fields) {

		MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "getValue", "(Ljava/lang/Object;Ljava/lang/String;)Ljava/lang/Object;", null, null);

		mv.visitCode();
		mv.visitVarInsn(ALOAD, 0);
		mv.visitFieldInsn(GETFIELD, accessClassNm, "fieldNames", "[Ljava/lang/String;");
		mv.visitVarInsn(ALOAD, 2);
		mv.visitMethodInsn(INVOKESTATIC, "java/util/Arrays", "binarySearch", "([Ljava/lang/Object;Ljava/lang/Object;)I");
		mv.visitVarInsn(ISTORE, 3);
		mv.visitVarInsn(ILOAD, 3);

		final int maxStack;

		if (fields.length > 0) {
			maxStack = 5;
			Label[] labels = constructLabels(fields);

			Label defaultLabel = new Label();
			mv.visitTableSwitchInsn(0, labels.length - 1, defaultLabel, labels);

			for (int i = 0, n = labels.length; i < n; i++) {
				Field field = fields[i];
				mv.visitLabel(labels[i]);
				mv.visitFrame(F_SAME, 0, null, 0, null);
				mv.visitVarInsn(ALOAD, 1);
				mv.visitTypeInsn(CHECKCAST, clazzNm);
				mv.visitFieldInsn(GETFIELD, clazzNm, field.getName(), Type.getDescriptor(field.getType()));

				Type fieldType = Type.getType(field.getType());
				switch (fieldType.getSort()) {
				case Type.BOOLEAN:
					mv.visitMethodInsn(INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;");
					break;
				case Type.BYTE:
					mv.visitMethodInsn(INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;");
					break;
				case Type.CHAR:
					mv.visitMethodInsn(INVOKESTATIC, "java/lang/Character", "valueOf", "(C)Ljava/lang/Character;");
					break;
				case Type.SHORT:
					mv.visitMethodInsn(INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;");
					break;
				case Type.INT:
					mv.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;");
					break;
				case Type.FLOAT:
					mv.visitMethodInsn(INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;");
					break;
				case Type.LONG:
					mv.visitMethodInsn(INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;");
					break;
				case Type.DOUBLE:
					mv.visitMethodInsn(INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;");
					break;
				}

				mv.visitInsn(ARETURN);
			}

			mv.visitLabel(defaultLabel);
			mv.visitFrame(F_SAME, 0, null, 0, null);
		} else {
			maxStack = 6;
		}
		enhanceForThrowingException(mv, IllegalArgumentException.class, "Field was not found", "Ljava/lang/Object;", ALOAD, 2);
		mv.visitMaxs(maxStack, 4);
		mv.visitEnd();
	}
 
Example 13
Source Project: groovy   File: ProxyGeneratorAdapter.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) {
    Object key = Arrays.asList(name, desc);
    if (visitedMethods.contains(key)) return null;
    if (Modifier.isPrivate(access) || Modifier.isNative(access) || ((access & ACC_SYNTHETIC) != 0)) {
        // do not generate bytecode for private methods
        return null;
    }
    int accessFlags = access;
    visitedMethods.add(key);
    if ((objectDelegateMethods.contains(name + desc) || delegatedClosures.containsKey(name) || (!"<init>".equals(name) && hasWildcard)) && !Modifier.isStatic(access) && !Modifier.isFinal(access)) {
        if (!GROOVYOBJECT_METHOD_NAMESS.contains(name)) {
            if (Modifier.isAbstract(access)) {
                // prevents the proxy from being abstract
                accessFlags -= ACC_ABSTRACT;
            }
            if (delegatedClosures.containsKey(name) || (!"<init>".equals(name) && hasWildcard)) {
                delegatedClosures.put(name, Boolean.TRUE);
                return makeDelegateToClosureCall(name, desc, signature, exceptions, accessFlags);
            }
            if (generateDelegateField && objectDelegateMethods.contains(name + desc)) {
                return makeDelegateCall(name, desc, signature, exceptions, accessFlags);
            }
            delegatedClosures.put(name, Boolean.TRUE);
            return makeDelegateToClosureCall(name, desc, signature, exceptions, accessFlags);
        }
    } else if ("getProxyTarget".equals(name) && "()Ljava/lang/Object;".equals(desc)) {
        return createGetProxyTargetMethod(access, name, desc, signature, exceptions);
    } else if ("<init>".equals(name) && (Modifier.isPublic(access) || Modifier.isProtected(access))) {
        return createConstructor(access, name, desc, signature, exceptions);
    } else if (Modifier.isAbstract(access) && !GROOVYOBJECT_METHOD_NAMESS.contains(name)) {
        if (isImplemented(superClass, name, desc)) {
            return null;
        }
        accessFlags -= ACC_ABSTRACT;
        MethodVisitor mv = super.visitMethod(accessFlags, name, desc, signature, exceptions);
        mv.visitCode();
        Type[] args = Type.getArgumentTypes(desc);
        if (emptyBody) {
            Type returnType = Type.getReturnType(desc);
            if (returnType == Type.VOID_TYPE) {
                mv.visitInsn(RETURN);
            } else {
                int loadIns = getLoadInsn(returnType);
                switch (loadIns) {
                    case ILOAD:
                        mv.visitInsn(ICONST_0);
                        break;
                    case LLOAD:
                        mv.visitInsn(LCONST_0);
                        break;
                    case FLOAD:
                        mv.visitInsn(FCONST_0);
                        break;
                    case DLOAD:
                        mv.visitInsn(DCONST_0);
                        break;
                    default:
                        mv.visitInsn(ACONST_NULL);
                }
                mv.visitInsn(getReturnInsn(returnType));
                mv.visitMaxs(2, registerLen(args) + 1);
            }
        } else {
            // for compatibility with the legacy proxy generator, we should throw an UnsupportedOperationException
            // instead of an AbtractMethodException
            mv.visitTypeInsn(NEW, "java/lang/UnsupportedOperationException");
            mv.visitInsn(DUP);
            mv.visitMethodInsn(INVOKESPECIAL, "java/lang/UnsupportedOperationException", "<init>", "()V", false);
            mv.visitInsn(ATHROW);
            mv.visitMaxs(2, registerLen(args) + 1);
        }
        mv.visitEnd();
    }
    return null;
}
 
Example 14
public static void assembleMethodHandleField(final ClassWriter cw, final Method targetMethod, final String invokerName) {
    final String desc = Type.getDescriptor(MethodHandle.class);
    cw.visitField(ACC_PRIVATE | ACC_FINAL + ACC_STATIC, "HANDLE", desc, null, null);
    cw.visitEnd();

    final MethodVisitor ctor = cw.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
    final Label cs = createLabel();
    final Label ce = createLabel();

    ctor.visitCode();
    ctor.visitLabel(cs);

    final String clName = targetMethod.getDeclaringClass().getCanonicalName();
    final String targetMethodName = targetMethod.getName();
    ctor.visitLdcInsn(clName);
    ctor.visitLdcInsn(targetMethodName);

    final Parameter[] parameters = targetMethod.getParameters();
    ctor.visitLdcInsn(parameters.length);

    final Type classType = Type.getType(Class.class);
    final String descriptor = classType.getInternalName();
    ctor.visitTypeInsn(ANEWARRAY, descriptor);

    for (int i = 0; i < parameters.length; i++) {
        ctor.visitInsn(DUP);
        ctor.visitLdcInsn(i);

        final Class<?> paramClass = parameters[i].getType();
        if (paramClass.isPrimitive()) {
            final Class<?> wrapper = Primitives.wrap(paramClass);
            final String holderName = Type.getType(wrapper).getInternalName();

            ctor.visitFieldInsn(GETSTATIC, holderName, "TYPE", CL_DESCRIPTOR);
        } else {
            final Type parameterType = Type.getType(paramClass);
            ctor.visitLdcInsn(parameterType);
        }

        ctor.visitInsn(AASTORE);
    }

    ctor.visitMethodInsn(INVOKESTATIC, MHC_INTERNAL_NAME, "createUniversal",
            '(' + STR_DESCRIPTOR + STR_DESCRIPTOR + CLA_DESCRIPTOR + ')' + MH_DESCRIPTOR, false);
    ctor.visitFieldInsn(PUTSTATIC, invokerName, "HANDLE", MH_DESCRIPTOR);
    ctor.visitInsn(RETURN);

    ctor.visitLabel(ce);
    ctor.visitEnd();

    ctor.visitMaxs(0, 0);
}
 
Example 15
private void generateModelBridge(MethodInfo method, AnnotationValue targetReturnTypeErased) {
    String descriptor = AsmUtil.getDescriptor(method, name -> typeArguments.get(name));
    // JpaOperations erases the Id type to Object
    String descriptorForJpaOperations = AsmUtil.getDescriptor(method,
            name -> name.equals("Entity") ? entitySignature : null);
    String signature = AsmUtil.getSignature(method, name -> typeArguments.get(name));
    List<org.jboss.jandex.Type> parameters = method.parameters();

    String castTo = null;
    if (targetReturnTypeErased != null && targetReturnTypeErased.asBoolean()) {
        org.jboss.jandex.Type type = method.returnType();
        if (type.kind() == Kind.TYPE_VARIABLE &&
                type.asTypeVariable().identifier().equals("Entity")) {
            castTo = entityBinaryType;
        }
        if (castTo == null)
            castTo = type.name().toString('/');
    }

    // Note: we can't use SYNTHETIC here because otherwise Mockito will never mock these methods
    MethodVisitor mv = super.visitMethod(Opcodes.ACC_PUBLIC,
            method.name(),
            descriptor,
            signature,
            null);
    for (int i = 0; i < parameters.size(); i++) {
        mv.visitParameter(method.parameterName(i), 0 /* modifiers */);
    }
    mv.visitCode();
    injectModel(mv);
    for (int i = 0; i < parameters.size(); i++) {
        mv.visitIntInsn(Opcodes.ALOAD, i + 1);
    }
    // inject Class
    String forwardingDescriptor = "(" + getModelDescriptor() + descriptorForJpaOperations.substring(1);
    if (castTo != null) {
        // return type is erased to Object
        int lastParen = forwardingDescriptor.lastIndexOf(')');
        forwardingDescriptor = forwardingDescriptor.substring(0, lastParen + 1) + "Ljava/lang/Object;";
    }
    mv.visitMethodInsn(Opcodes.INVOKESTATIC,
            getPanacheOperationsBinaryName(),
            method.name(),
            forwardingDescriptor, false);
    if (castTo != null)
        mv.visitTypeInsn(Opcodes.CHECKCAST, castTo);
    String returnTypeDescriptor = descriptor.substring(descriptor.lastIndexOf(")") + 1);
    mv.visitInsn(AsmUtil.getReturnInstruction(returnTypeDescriptor));
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}
 
Example 16
Source Project: groovy   File: AssertionWriter.java    License: Apache License 2.0 4 votes vote down vote up
private void writeSourcelessAssertText(AssertStatement statement) {
    MethodVisitor mv = controller.getMethodVisitor();
    OperandStack operandStack = controller.getOperandStack();
    
    BooleanExpression booleanExpression = statement.getBooleanExpression();
    // push expression string onto stack
    String expressionText = booleanExpression.getText();
    List<String> list = new ArrayList<String>();
    addVariableNames(booleanExpression, list);
    if (list.isEmpty()) {
        mv.visitLdcInsn(expressionText);
    } else {
        boolean first = true;

        // let's create a new expression
        mv.visitTypeInsn(NEW, "java/lang/StringBuffer");
        mv.visitInsn(DUP);
        mv.visitLdcInsn(expressionText + ". Values: ");
        mv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuffer", "<init>", "(Ljava/lang/String;)V", false);
        //TODO: maybe use more special type StringBuffer here
        operandStack.push(ClassHelper.OBJECT_TYPE);
        int tempIndex = controller.getCompileStack().defineTemporaryVariable("assert", true);

        for (String name : list) {
            String text = name + " = ";
            if (first) {
                first = false;
            } else {
                text = ", " + text;
            }

            mv.visitVarInsn(ALOAD, tempIndex);
            mv.visitLdcInsn(text);
            mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuffer", "append", "(Ljava/lang/Object;)Ljava/lang/StringBuffer;", false);
            mv.visitInsn(POP);

            mv.visitVarInsn(ALOAD, tempIndex);
            new VariableExpression(name).visit(controller.getAcg());
            operandStack.box();
            mv.visitMethodInsn(INVOKESTATIC, "org/codehaus/groovy/runtime/InvokerHelper", "toString", "(Ljava/lang/Object;)Ljava/lang/String;", false);
            mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuffer", "append", "(Ljava/lang/String;)Ljava/lang/StringBuffer;", false);
            mv.visitInsn(POP);
            operandStack.remove(1);
        }
        mv.visitVarInsn(ALOAD, tempIndex);
        controller.getCompileStack().removeVar(tempIndex);
    }
}
 
Example 17
Source Project: Despector   File: BytecodeCastEmitter.java    License: MIT License 4 votes vote down vote up
@Override
public void emit(BytecodeEmitterContext ctx, Cast arg, TypeSignature type) {
    MethodVisitor mv = ctx.getMethodVisitor();
    ctx.emitInstruction(arg.getValue(), null);
    TypeSignature to = arg.getType();
    TypeSignature from = arg.getValue().inferType();
    if (to == ClassTypeSignature.INT) {
        if (from == ClassTypeSignature.LONG) {
            mv.visitInsn(Opcodes.L2I);
        } else if (from == ClassTypeSignature.FLOAT) {
            mv.visitInsn(Opcodes.F2I);
        } else if (from == ClassTypeSignature.DOUBLE) {
            mv.visitInsn(Opcodes.D2I);
        }
    } else if (to == ClassTypeSignature.LONG) {
        if (from == ClassTypeSignature.INT) {
            mv.visitInsn(Opcodes.I2L);
        } else if (from == ClassTypeSignature.FLOAT) {
            mv.visitInsn(Opcodes.F2L);
        } else if (from == ClassTypeSignature.DOUBLE) {
            mv.visitInsn(Opcodes.D2L);
        }
    } else if (to == ClassTypeSignature.FLOAT) {
        if (from == ClassTypeSignature.LONG) {
            mv.visitInsn(Opcodes.L2F);
        } else if (from == ClassTypeSignature.INT) {
            mv.visitInsn(Opcodes.I2F);
        } else if (from == ClassTypeSignature.DOUBLE) {
            mv.visitInsn(Opcodes.D2F);
        }
    } else if (to == ClassTypeSignature.DOUBLE) {
        if (from == ClassTypeSignature.LONG) {
            mv.visitInsn(Opcodes.L2D);
        } else if (from == ClassTypeSignature.FLOAT) {
            mv.visitInsn(Opcodes.F2D);
        } else if (from == ClassTypeSignature.INT) {
            mv.visitInsn(Opcodes.I2D);
        }
    }
    mv.visitTypeInsn(Opcodes.CHECKCAST, to.getDescriptor());
}
 
Example 18
@Override
protected void generate(TraceClassVisitor cw) {
	MethodVisitor mv;

	cw.visit(V1_1, ACC_PUBLIC + ACC_SUPER, "soot/asm/backend/targets/InstanceOfCasts",
			null, "java/lang/Object", null);
	cw.visitSource("InstanceOfCasts.java", null);
	
	{
		mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
		mv.visitCode();
		mv.visitVarInsn(ALOAD, 0);
		mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
		mv.visitInsn(RETURN);
		mv.visitMaxs(0, 0);
		mv.visitEnd();
		}
	{
	mv = cw.visitMethod(ACC_PUBLIC, "convertMeasurableArray", "([Ljava/lang/Object;)[Lsoot/asm/backend/targets/Measurable;", null, null);
	mv.visitCode();
	mv.visitVarInsn(ALOAD, 1);
	mv.visitTypeInsn(INSTANCEOF, "[Lsoot/asm/backend/targets/Measurable;");
	Label l0 = new Label();
	mv.visitJumpInsn(IFEQ, l0);
	mv.visitVarInsn(ALOAD, 1);
	mv.visitTypeInsn(CHECKCAST, "[Lsoot/asm/backend/targets/Measurable;");
	if (targetCompiler != TargetCompiler.eclipse)
		mv.visitTypeInsn(CHECKCAST, "[Lsoot/asm/backend/targets/Measurable;");
	mv.visitInsn(ARETURN);
	mv.visitLabel(l0);
	mv.visitInsn(ACONST_NULL);
	mv.visitInsn(ARETURN);
	mv.visitMaxs(0, 0);
	mv.visitEnd();
	}
		{
		mv = cw.visitMethod(ACC_PUBLIC, "isMeasurable", "(Ljava/lang/Object;)Z", null, null);
		mv.visitCode();
		mv.visitVarInsn(ALOAD, 1);
		mv.visitTypeInsn(INSTANCEOF, "soot/asm/backend/targets/Measurable");
		mv.visitInsn(IRETURN);
		mv.visitMaxs(0, 0);
		mv.visitEnd();
		}
		cw.visitEnd();

	
}
 
Example 19
Source Project: groovy   File: ProxyGeneratorAdapter.java    License: Apache License 2.0 4 votes vote down vote up
protected MethodVisitor makeDelegateToClosureCall(final String name, final String desc, final String signature, final String[] exceptions, final int accessFlags) {
        MethodVisitor mv = super.visitMethod(accessFlags, name, desc, signature, exceptions);
//        TraceMethodVisitor tmv = new TraceMethodVisitor(mv);
//        mv = tmv;
        mv.visitCode();
        int stackSize = 0;
        // method body should be:
        //  this.$delegate$closure$methodName.call(new Object[] { method arguments })
        Type[] args = Type.getArgumentTypes(desc);
        int arrayStore = args.length + 1;
        BytecodeHelper.pushConstant(mv, args.length);
        mv.visitTypeInsn(ANEWARRAY, "java/lang/Object"); // stack size = 1
        stackSize = 1;
        int idx = 1;
        for (int i = 0; i < args.length; i++) {
            Type arg = args[i];
            mv.visitInsn(DUP); // stack size = 2
            BytecodeHelper.pushConstant(mv, i); // array index, stack size = 3
            // primitive types must be boxed
            boxPrimitiveType(mv, idx, arg);
            idx += registerLen(arg);
            stackSize = Math.max(4, 3 + registerLen(arg));
            mv.visitInsn(AASTORE); // store value into array
        }
        mv.visitVarInsn(ASTORE, arrayStore); // store array
        int arrayIndex = arrayStore;
        mv.visitVarInsn(ALOAD, 0); // load this
        mv.visitFieldInsn(GETFIELD, proxyName, CLOSURES_MAP_FIELD, "Ljava/util/Map;"); // load closure map
        mv.visitLdcInsn(name); // load method name
        mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Map", "get", "(Ljava/lang/Object;)Ljava/lang/Object;", true);
        arrayStore++;
        mv.visitVarInsn(ASTORE, arrayStore);
        // if null, test if wildcard exists
        Label notNull = new Label();
        mv.visitIntInsn(ALOAD, arrayStore);
        mv.visitJumpInsn(IFNONNULL, notNull);
        mv.visitVarInsn(ALOAD, 0); // load this
        mv.visitFieldInsn(GETFIELD, proxyName, CLOSURES_MAP_FIELD, "Ljava/util/Map;"); // load closure map
        mv.visitLdcInsn("*"); // load wildcard
        mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Map", "get", "(Ljava/lang/Object;)Ljava/lang/Object;", true);
        mv.visitVarInsn(ASTORE, arrayStore);
        mv.visitLabel(notNull);
        mv.visitVarInsn(ALOAD, arrayStore);
        mv.visitMethodInsn(INVOKESTATIC, BytecodeHelper.getClassInternalName(this.getClass()), "ensureClosure", "(Ljava/lang/Object;)Lgroovy/lang/Closure;", false);
        mv.visitVarInsn(ALOAD, arrayIndex); // load argument array
        stackSize++;
        mv.visitMethodInsn(INVOKEVIRTUAL, "groovy/lang/Closure", "call", "([Ljava/lang/Object;)Ljava/lang/Object;", false); // call closure
        unwrapResult(mv, desc);
        mv.visitMaxs(stackSize, arrayStore + 1);
        mv.visitEnd();
//        System.out.println("tmv.getText() = " + tmv.getText());
        return null;
    }
 
Example 20
Source Project: OpenModsLib   File: BlockSpaceTransform.java    License: MIT License 4 votes vote down vote up
private static void createTransformMethod(MethodVisitor mv, boolean invert) {
	// 0 - this (unused)
	// 1 - orientation
	// 2,3 - x
	// 4,5 - y
	// 6,7 - z
	mv.visitCode();

	mv.visitVarInsn(Opcodes.ALOAD, 1);

	final String enumType = Type.getInternalName(Enum.class);
	mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, enumType, "ordinal", Type.getMethodDescriptor(Type.INT_TYPE), false);

	final Orientation[] orientations = Orientation.values();

	final Label defaultLabel = new Label();
	final Label[] targets = new Label[orientations.length];
	for (int i = 0; i < orientations.length; i++)
		targets[i] = new Label();

	mv.visitTableSwitchInsn(0, orientations.length - 1, defaultLabel, targets);

	{
		mv.visitLabel(defaultLabel);
		final String excType = Type.getInternalName(IllegalArgumentException.class);
		final Type stringType = Type.getType(String.class);

		mv.visitTypeInsn(Opcodes.NEW, excType);
		mv.visitInsn(Opcodes.DUP);
		mv.visitVarInsn(Opcodes.ALOAD, 1);
		mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Object.class), "toString", Type.getMethodDescriptor(stringType), false);
		mv.visitMethodInsn(Opcodes.INVOKESPECIAL, excType, "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, stringType), false);
		mv.visitInsn(Opcodes.ATHROW);
	}

	{
		final String createVectorDesc = Type.getMethodDescriptor(Type.getType(Vec3d.class), Type.DOUBLE_TYPE, Type.DOUBLE_TYPE, Type.DOUBLE_TYPE);
		final String selfType = Type.getInternalName(BlockSpaceTransform.class);
		for (int i = 0; i < orientations.length; i++) {
			mv.visitLabel(targets[i]);
			final Orientation orientation = orientations[i];
			final Matrix3f mat = orientation.getLocalToWorldMatrix();
			if (invert) mat.invert();

			createRowVectorMultiplication(mv, mat.m00, mat.m01, mat.m02);
			createRowVectorMultiplication(mv, mat.m10, mat.m11, mat.m12);
			createRowVectorMultiplication(mv, mat.m20, mat.m21, mat.m22);

			mv.visitMethodInsn(Opcodes.INVOKESTATIC, selfType, "createVector", createVectorDesc, false);
			mv.visitInsn(Opcodes.ARETURN);
		}
	}

	mv.visitMaxs(0, 0);
	mv.visitEnd();
}