List of usage examples for org.objectweb.asm Opcodes INVOKEINTERFACE
int INVOKEINTERFACE
To view the source code for org.objectweb.asm Opcodes INVOKEINTERFACE.
Click Source Link
From source file:org.jetbrains.jet.codegen.JetTypeMapper.java
License:Apache License
public CallableMethod mapToCallableMethod(FunctionDescriptor functionDescriptor, boolean superCall, OwnerKind kind) {/*w w w.ja va2 s .co m*/ if (functionDescriptor == null) return null; final DeclarationDescriptor functionParent = functionDescriptor.getOriginal().getContainingDeclaration(); JvmMethodSignature descriptor = mapSignature(functionDescriptor.getOriginal(), true, kind); String owner; String ownerForDefaultImpl; String ownerForDefaultParam; int invokeOpcode; ClassDescriptor thisClass; if (functionParent instanceof NamespaceDescriptor) { assert !superCall; boolean namespace = true; if (functionParent instanceof JavaNamespaceDescriptor) { namespace = ((JavaNamespaceDescriptor) functionParent).isNamespace(); } owner = NamespaceCodegen.getJVMClassName(DescriptorUtils.getFQName(functionParent), namespace); ownerForDefaultImpl = ownerForDefaultParam = owner; invokeOpcode = INVOKESTATIC; thisClass = null; } else if (functionDescriptor instanceof ConstructorDescriptor) { assert !superCall; ClassDescriptor containingClass = (ClassDescriptor) functionParent; owner = mapType(containingClass.getDefaultType(), OwnerKind.IMPLEMENTATION).getInternalName(); ownerForDefaultImpl = ownerForDefaultParam = owner; invokeOpcode = INVOKESPECIAL; thisClass = null; } else if (functionParent instanceof ClassDescriptor) { FunctionDescriptor declarationFunctionDescriptor = findAnyDeclaration(functionDescriptor); ClassDescriptor currentOwner = (ClassDescriptor) functionParent; ClassDescriptor declarationOwner = (ClassDescriptor) declarationFunctionDescriptor .getContainingDeclaration(); boolean originalIsInterface = CodegenUtil.isInterface(declarationOwner); boolean currentIsInterface = CodegenUtil.isInterface(currentOwner); ClassDescriptor receiver; if (currentIsInterface && !originalIsInterface) { receiver = declarationOwner; } else { receiver = currentOwner; } ClassDescriptor containingClass = (ClassDescriptor) functionParent; boolean isInterface = originalIsInterface && currentIsInterface; OwnerKind kind1 = isInterface && superCall ? OwnerKind.TRAIT_IMPL : OwnerKind.IMPLEMENTATION; Type type = mapType(receiver.getDefaultType(), OwnerKind.IMPLEMENTATION); owner = type.getInternalName(); ownerForDefaultParam = mapType(((ClassDescriptor) declarationOwner).getDefaultType(), OwnerKind.IMPLEMENTATION).getInternalName(); ownerForDefaultImpl = ownerForDefaultParam + (originalIsInterface ? JvmAbi.TRAIT_IMPL_SUFFIX : ""); invokeOpcode = isInterface ? (superCall ? Opcodes.INVOKESTATIC : Opcodes.INVOKEINTERFACE) : (superCall ? Opcodes.INVOKESPECIAL : Opcodes.INVOKEVIRTUAL); if (isInterface && superCall) { descriptor = mapSignature(functionDescriptor, false, OwnerKind.TRAIT_IMPL); owner += JvmAbi.TRAIT_IMPL_SUFFIX; } thisClass = receiver; } else { throw new UnsupportedOperationException("unknown function parent"); } final CallableMethod result = new CallableMethod(owner, ownerForDefaultImpl, ownerForDefaultParam, descriptor, invokeOpcode); result.setNeedsThis(thisClass); if (functionDescriptor.getReceiverParameter().exists()) { result.setNeedsReceiver(functionDescriptor); } return result; }
From source file:org.lambdamatic.analyzer.ast.LambdaExpressionReader.java
License:Open Source License
/** * Reads the bytecode from the given {@link InsnCursor}'s <strong>current position</strong>, until * there is no further instruction to proceed. It is the responsability of the caller to set the * cursor position.// ww w .j a va2 s . c o m * * @param insnCursor the instruction cursor used to read the bytecode. * @param expressionStack the expression stack to put on or pop from. * @param localVariables the local variables * @return a {@link List} of {@link Statement} containing the {@link Statement} */ private List<Statement> readStatements(final InsnCursor insnCursor, final Stack<Expression> expressionStack, final List<CapturedArgument> capturedArguments, final LocalVariables localVariables) { final List<Statement> statements = new ArrayList<>(); while (insnCursor.hasCurrent()) { final AbstractInsnNode currentInstruction = insnCursor.getCurrent(); switch (currentInstruction.getType()) { case AbstractInsnNode.VAR_INSN: final VarInsnNode varInstruction = (VarInsnNode) currentInstruction; switch (currentInstruction.getOpcode()) { // load a reference onto the stack from a local variable case Opcodes.ALOAD: case Opcodes.ILOAD: // load an int value from a local variable // Note: The 'var' operand is the index of a local variable // all captured arguments come before the local variable in the method signature, // which means that the local variables table is empty on the first slots which are // "allocated" // for the captured arguments. if (varInstruction.var < capturedArguments.size()) { // if the variable index matches a captured argument // note: not using actual captured argument but rather, use a _reference_ to it. final Object capturedArgumentValue = capturedArguments.get(varInstruction.var).getValue(); final Class<?> capturedArgumentValueType = capturedArgumentValue != null ? capturedArgumentValue.getClass() : Object.class; final CapturedArgumentRef capturedArgumentRef = new CapturedArgumentRef(varInstruction.var, capturedArgumentValueType); expressionStack.add(capturedArgumentRef); } else { // the variable index matches a local variable final LocalVariableNode var = localVariables.load(varInstruction.var); expressionStack.add(new LocalVariable(var.index, var.name, readSignature(var.desc))); } break; case Opcodes.ASTORE: // store a reference into a local variable localVariables.store(varInstruction.var); break; default: throw new AnalyzeException( "Unexpected Variable instruction code: " + varInstruction.getOpcode()); } break; case AbstractInsnNode.LDC_INSN: // let's move this instruction on top of the stack until it // is used as an argument during a method call final LdcInsnNode ldcInsnNode = (LdcInsnNode) currentInstruction; final Expression constant = ExpressionFactory.getExpression(ldcInsnNode.cst); LOGGER.trace("Stacking constant {}", constant); expressionStack.add(constant); break; case AbstractInsnNode.FIELD_INSN: final FieldInsnNode fieldInsnNode = (FieldInsnNode) currentInstruction; switch (fieldInsnNode.getOpcode()) { case Opcodes.GETSTATIC: final Type ownerType = Type.getType(fieldInsnNode.desc); final FieldAccess staticFieldAccess = new FieldAccess(new ClassLiteral(getType(ownerType)), fieldInsnNode.name); expressionStack.add(staticFieldAccess); break; case Opcodes.GETFIELD: final Expression fieldAccessParent = expressionStack.pop(); final FieldAccess fieldAccess = new FieldAccess(fieldAccessParent, fieldInsnNode.name); expressionStack.add(fieldAccess); break; case Opcodes.PUTFIELD: final Expression fieldAssignationValue = expressionStack.pop(); final Expression parentSource = expressionStack.pop(); final FieldAccess source = new FieldAccess(parentSource, fieldInsnNode.name); final Assignment assignmentExpression = new Assignment(source, fieldAssignationValue); statements.add(new ExpressionStatement(assignmentExpression)); break; default: throw new AnalyzeException("Unexpected field instruction type: " + fieldInsnNode.getOpcode()); } break; case AbstractInsnNode.METHOD_INSN: final MethodInsnNode methodInsnNode = (MethodInsnNode) currentInstruction; final Type[] argumentTypes = Type.getArgumentTypes(methodInsnNode.desc); final List<Expression> args = new ArrayList<>(); final List<Class<?>> parameterTypes = new ArrayList<>(); Stream.of(argumentTypes).forEach(argumentType -> { final Expression arg = expressionStack.pop(); final String argumentClassName = argumentType.getClassName(); args.add(castOperand(arg, argumentClassName)); try { parameterTypes.add(ClassUtils.getClass(argumentClassName)); } catch (Exception e) { throw new AnalyzeException("Failed to find class '" + argumentClassName + "'", e); } }); // arguments appear in reverse order in the bytecode Collections.reverse(args); switch (methodInsnNode.getOpcode()) { case Opcodes.INVOKEINTERFACE: case Opcodes.INVOKEVIRTUAL: case Opcodes.INVOKESPECIAL: // object instantiation if (methodInsnNode.name.equals("<init>")) { final ObjectInstanciation objectVariable = (ObjectInstanciation) expressionStack.pop(); objectVariable.setInitArguments(args); } else { final Expression sourceExpression = expressionStack.pop(); final Method javaMethod = ReflectionUtils.findJavaMethod(sourceExpression.getJavaType(), methodInsnNode.name, parameterTypes); final Class<?> returnType = findReturnType(insnCursor, javaMethod); final MethodInvocation invokedMethod = new MethodInvocation(sourceExpression, javaMethod, returnType, args); expressionStack.add(invokedMethod); } break; case Opcodes.INVOKESTATIC: final Type type = Type.getObjectType(methodInsnNode.owner); try { final Class<?> sourceClass = Class.forName(type.getClassName()); final Method javaMethod = ReflectionUtils.findJavaMethod(sourceClass, methodInsnNode.name, parameterTypes); final Class<?> returnType = findReturnType(insnCursor, javaMethod); final MethodInvocation invokedStaticMethod = new MethodInvocation( new ClassLiteral(sourceClass), javaMethod, returnType, args); expressionStack.add(invokedStaticMethod); } catch (ClassNotFoundException e) { throw new AnalyzeException("Failed to retrieve class for " + methodInsnNode.owner, e); } break; default: throw new AnalyzeException("Unexpected method invocation type: " + methodInsnNode.getOpcode()); } break; case AbstractInsnNode.INVOKE_DYNAMIC_INSN: final InvokeDynamicInsnNode invokeDynamicInsnNode = (InvokeDynamicInsnNode) currentInstruction; final Handle handle = (Handle) invokeDynamicInsnNode.bsmArgs[1]; final int argNumber = Type.getArgumentTypes(invokeDynamicInsnNode.desc).length; final List<CapturedArgumentRef> lambdaArgs = new ArrayList<>(); for (int i = 0; i < argNumber; i++) { final Expression expr = expressionStack.pop(); if (expr.getExpressionType() != ExpressionType.CAPTURED_ARGUMENT_REF) { throw new AnalyzeException("Unexpected argument type when following InvokeDynamic call: " + expr.getExpressionType()); } lambdaArgs.add((CapturedArgumentRef) expr); // , expr.getValue() } Collections.reverse(lambdaArgs); final EmbeddedSerializedLambdaInfo lambdaInfo = new EmbeddedSerializedLambdaInfo(handle.getOwner(), handle.getName(), handle.getDesc(), lambdaArgs, capturedArguments); final LambdaExpression lambdaExpression = LambdaExpressionAnalyzer.getInstance() .analyzeExpression(lambdaInfo); expressionStack.add(lambdaExpression); break; case AbstractInsnNode.JUMP_INSN: statements.addAll( readJumpInstruction(insnCursor, expressionStack, capturedArguments, localVariables)); return statements; case AbstractInsnNode.INT_INSN: readIntInstruction((IntInsnNode) currentInstruction, expressionStack, localVariables); break; case AbstractInsnNode.INSN: final List<Statement> instructionStatement = readInstruction(insnCursor, expressionStack, capturedArguments, localVariables); statements.addAll(instructionStatement); break; case AbstractInsnNode.TYPE_INSN: readTypeInstruction((TypeInsnNode) currentInstruction, expressionStack, localVariables); break; default: throw new AnalyzeException( "This is embarrassing... We've reached an unexpected instruction operator: " + currentInstruction.getType()); } insnCursor.next(); } return statements; }
From source file:org.mbte.groovypp.compiler.StaticCompiler.java
License:Apache License
private void visitForLoopWithIntRange(ForStatement forLoop) { compileStack.pushLoop(forLoop.getVariableScope(), forLoop.getStatementLabel()); forLoop.getVariable().setType(ClassHelper.int_TYPE); Label breakLabel = compileStack.getBreakLabel(); Label continueLabel = compileStack.getContinueLabel(); mv.visitInsn(DUP);//ww w .j a v a2 s . c o m int collIdx = compileStack.defineTemporaryVariable("$coll$", ClassHelper.OBJECT_TYPE, true); mv.visitTypeInsn(INSTANCEOF, BytecodeHelper.getClassInternalName(EmptyRange.class)); mv.visitJumpInsn(IFNE, breakLabel); mv.visitVarInsn(ALOAD, collIdx); mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "groovy/lang/Range", "getFrom", "()Ljava/lang/Comparable;"); BytecodeExpr.unbox(ClassHelper.int_TYPE, mv); mv.visitVarInsn(ALOAD, collIdx); mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "groovy/lang/Range", "getTo", "()Ljava/lang/Comparable;"); BytecodeExpr.unbox(ClassHelper.int_TYPE, mv); mv.visitVarInsn(ALOAD, collIdx); mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "groovy/lang/Range", "isReverse", "()Z"); mv.visitInsn(DUP); int isReverse = compileStack.defineTemporaryVariable("$isReverse$", ClassHelper.boolean_TYPE, true); Label lElse1 = new Label(); mv.visitJumpInsn(IFEQ, lElse1); mv.visitInsn(SWAP); mv.visitLabel(lElse1); int otherEnd = compileStack.defineTemporaryVariable("$otherEnd$", ClassHelper.int_TYPE, true); int thisEnd = compileStack.defineTemporaryVariable("$thisEnd$", ClassHelper.int_TYPE, true); Register it = compileStack.defineVariable(forLoop.getVariable(), false); mv.startLoopVisitLabel(continueLabel); mv.visitVarInsn(ILOAD, otherEnd); mv.visitVarInsn(ILOAD, thisEnd); Label lElse2 = new Label(), lDone2 = new Label(); mv.visitVarInsn(ILOAD, isReverse); mv.visitJumpInsn(IFNE, lElse2); mv.visitJumpInsn(IF_ICMPLT, breakLabel); mv.visitJumpInsn(GOTO, lDone2); mv.visitLabel(lElse2); mv.visitJumpInsn(IF_ICMPGT, breakLabel); mv.visitLabel(lDone2); mv.visitVarInsn(ILOAD, thisEnd); mv.visitInsn(DUP); mv.visitVarInsn(ISTORE, it.getIndex()); mv.visitInsn(ICONST_1); mv.visitVarInsn(ILOAD, isReverse); Label lElse3 = new Label(), lDone3 = new Label(); mv.visitJumpInsn(IFNE, lElse3); mv.visitInsn(IADD); mv.visitJumpInsn(GOTO, lDone3); mv.visitLabel(lElse3); mv.visitInsn(ISUB); mv.visitLabel(lDone3); mv.visitVarInsn(ISTORE, thisEnd); forLoop.getLoopBlock().visit(this); mv.visitJumpInsn(GOTO, continueLabel); mv.visitLabel(breakLabel); compileStack.pop(); }
From source file:org.openquark.cal.internal.javamodel.AsmJavaBytecodeGenerator.java
License:Open Source License
/** * Create the Java code for a given method invocation. * The expression result to be pushed onto the stack. * @param mi the method invocation /* w ww. j a va2 s . co m*/ * @param context * @return JavaTypeName the type of the result on the operand stack. * @throws JavaGenerationException */ private static JavaTypeName encodeMethodInvocationExpr(JavaExpression.MethodInvocation mi, GenerationContext context) throws JavaGenerationException { MethodInvocation.InvocationType invocationType = mi.getInvocationType(); int invocationCode; JavaTypeName invocationClassType; if (invocationType != MethodInvocation.InvocationType.STATIC) { JavaExpression invocationTarget = ((MethodInvocation.Instance) mi).getInvocationTarget(); if (invocationTarget == null) { //push a reference to 'this' onto the stack. invocationClassType = encodeThis(context); } else { //push a reference to the invoking expression onto the stack invocationClassType = encodeExpr(invocationTarget, context); } // The MethodInvocation may contain an explicit invoking class type. If it does // use it in preference to the type of the invocation target. if (mi instanceof MethodInvocation.Instance && ((MethodInvocation.Instance) mi).getDeclaringClass() != null) { invocationClassType = ((MethodInvocation.Instance) mi).getDeclaringClass(); } if (invocationType == MethodInvocation.InvocationType.VIRTUAL) { invocationCode = Opcodes.INVOKEVIRTUAL; } else if (invocationType == MethodInvocation.InvocationType.INTERFACE) { if (invocationClassType.isInterface()) { invocationCode = Opcodes.INVOKEINTERFACE; } else { //if we invoke an interface method on a reference that is known to be a Class, then we must use invoke virtual //to avoid getting a IncompatibleClassChangeError. invocationCode = Opcodes.INVOKEVIRTUAL; } } else if (invocationType == MethodInvocation.InvocationType.SPECIAL) { invocationCode = Opcodes.INVOKESPECIAL; } else { throw new JavaGenerationException("Unknown invocation type: " + invocationType); } } else { //static invocation. No object reference needs to be pushed. invocationCode = Opcodes.INVOKESTATIC; invocationClassType = ((MethodInvocation.Static) mi).getInvocationClass(); } //push the arguments onto the stack for (int i = 0, nArgs = mi.getNArgs(); i < nArgs; ++i) { encodeExpr(mi.getArg(i), context); } //invoke the method context.getMethodVisitor().visitMethodInsn(invocationCode, invocationClassType.getJVMInternalName(), mi.getMethodName(), mi.getJVMMethodDescriptor()); return mi.getReturnType(); }
From source file:org.pitest.mutationtest.mocksupport.JavassistInputStreamInterceptorAdapater.java
License:Apache License
@Override public void visitMethodInsn(final int opcode, final String owner, final String name, final String desc, boolean itf) { if ((opcode == Opcodes.INVOKEINTERFACE) && owner.equals("javassist/ClassPath") && name.equals("openClassfile")) { this.mv.visitMethodInsn(Opcodes.INVOKESTATIC, INTERCEPTOR_CLASS, name, "(Ljava/lang/Object;Ljava/lang/String;)Ljava/io/InputStream;", false); } else {/* w ww . ja v a2s . c o m*/ this.mv.visitMethodInsn(opcode, owner, name, desc, itf); } }
From source file:org.sonar.java.bytecode.se.BytecodeEGWalkerExecuteTest.java
License:Open Source License
@Test public void test_invoke_instance_method() throws Exception { int[] opcodes = new int[] { Opcodes.INVOKESPECIAL, Opcodes.INVOKEVIRTUAL, Opcodes.INVOKEINTERFACE }; for (int opcode : opcodes) { SymbolicValue thisSv = new SymbolicValue(); ProgramState stateWithThis = ProgramState.EMPTY_STATE.stackValue(thisSv); ProgramState programState = execute(invokeMethod(opcode, "methodWithoutArgument", "()V"), stateWithThis);/* w ww .jav a 2 s .c om*/ assertEmptyStack(programState); assertThat(programState.getConstraints(thisSv).get(ObjectConstraint.class)) .isEqualTo(ObjectConstraint.NOT_NULL); programState = execute(invokeMethod(opcode, "finalVoid", "()V"), stateWithThis); assertEmptyStack(programState); assertThat(programState.getConstraints(thisSv).get(ObjectConstraint.class)) .isEqualTo(ObjectConstraint.NOT_NULL); programState = execute(invokeMethod(opcode, "booleanMethod", "()Z"), stateWithThis); assertStack(programState, new Constraint[] { null }); assertThat(isDoubleOrLong(programState, programState.peekValue())).isFalse(); SymbolicValue arg = new SymbolicValue(); programState = execute(invokeMethod(opcode, "intMethodWithIntArgument", "(I)I"), stateWithThis.stackValue(arg)); assertStack(programState, new Constraint[] { null }); assertThat(programState.peekValue()).isNotEqualTo(arg); programState = execute(invokeMethod(opcode, "methodWithIntIntArgument", "(II)V"), stateWithThis.stackValue(arg).stackValue(arg)); assertEmptyStack(programState); assertThatThrownBy( () -> execute(invokeMethod(opcode, "methodWithIntIntArgument", "(II)V"), stateWithThis)) .isInstanceOf(IllegalStateException.class); programState = execute(invokeMethod(opcode, "returningLong", "()J"), stateWithThis); assertThat(isDoubleOrLong(programState, programState.peekValue())).isTrue(); programState = execute(invokeMethod(opcode, "returningDouble", "()D"), stateWithThis); assertThat(isDoubleOrLong(programState, programState.peekValue())).isTrue(); } }
From source file:org.spongepowered.despector.emitter.bytecode.instruction.BytecodeInstanceMethodInvokeEmitter.java
License:Open Source License
public int getOpcode(InstanceMethodInvoke.Type type) { switch (type) { case INTERFACE: return Opcodes.INVOKEINTERFACE; case SPECIAL: return Opcodes.INVOKESPECIAL; case VIRTUAL: default://from w w w . j a v a2 s .c om return Opcodes.INVOKEVIRTUAL; } }
From source file:org.springsource.loaded.test.infra.MethodPrinter.java
License:Apache License
public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { if (opcode == Opcodes.INVOKESTATIC) { to.println(" INVOKESTATIC " + owner + "." + name + desc); } else if (opcode == Opcodes.INVOKESPECIAL) { to.println(" INVOKESPECIAL " + owner + "." + name + desc); } else if (opcode == Opcodes.INVOKEVIRTUAL) { to.println(" INVOKEVIRTUAL " + owner + "." + name + desc); } else if (opcode == Opcodes.INVOKEINTERFACE) { to.println(" INVOKEINTERFACE " + owner + "." + name + desc); } else {/*from www. j ava 2s . c om*/ throw new IllegalStateException(":" + opcode); } }
From source file:org.zoeey.ztpl.compiler.ByteCodeHelper.java
License:LGPL
/** * template//from ww w . j a v a 2s. c om */ public void callClass(String className) { className = ZtplConstant.CLASS_URI + className; mv.visitTypeInsn(Opcodes.NEW, className); mv.visitInsn(Opcodes.DUP); mv.visitMethodInsn(Opcodes.INVOKESPECIAL, className, "<init>", "()V"); // mv.visitVarInsn(Opcodes.ALOAD, VAR_INDEX_WRITER); mv.visitVarInsn(Opcodes.ALOAD, VAR_INDEX_PARAMSMAP); mv.visitVarInsn(Opcodes.ALOAD, VAR_INDEX_ZTPL); mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, ZtplConstant.TEMPLATE_INTERFACE// , "publish", "(Ljava/io/Writer;Ljava/util/Map;Lorg/zoeey/ztpl/Ztpl;)V"); }
From source file:org.zoeey.ztpl.compiler.ByteCodeHelper.java
License:LGPL
/** * ????/*w w w.j ava 2 s. c o m*/ * @param key */ public void getContext(String key) { mv.visitVarInsn(Opcodes.ALOAD, VAR_INDEX_PARAMSMAP); mv.visitLdcInsn(key); mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/Map", "get", "(Ljava/lang/Object;)Ljava/lang/Object;"); }