List of usage examples for org.objectweb.asm.tree AbstractInsnNode METHOD_INSN
int METHOD_INSN
To view the source code for org.objectweb.asm.tree AbstractInsnNode METHOD_INSN.
Click Source Link
From source file:ht.misc.injectsocks.InjectSockstTransformerImpl.java
License:Apache License
public byte[] inject(byte[] classfileBuffer) { try {//from w w w .j av a2 s . co m ClassReader cr = new ClassReader(classfileBuffer); ClassNode cn = new ClassNode(); cr.accept(cn, 0); ArrayList<AbstractInsnNode> injectPos = new ArrayList<AbstractInsnNode>(); @SuppressWarnings("unchecked") List<MethodNode> methods = (List<MethodNode>) cn.methods; for (int i = 0; i < methods.size(); ++i) { MethodNode method = methods.get(i); InsnList instructions = method.instructions; if (instructions.size() <= 0) continue; //System.out.println("Method: "+method.name+" "); for (int j = 0; j < instructions.size(); ++j) { AbstractInsnNode insn = (AbstractInsnNode) instructions.get(j); //System.out.println("\tInsn: opc="+OpcodeUtil.getOpcode(insn.getOpcode())+", type="+insn.getType()); if (insn.getType() == AbstractInsnNode.METHOD_INSN) { MethodInsnNode min = (MethodInsnNode) insn; //System.out.printf("\t\towner=%s, name=%s, desc=%s\n", min.owner, min.name, min.desc); if (min.owner.equals("java/net/Socket") && min.name.equals("<init>") && min.desc.equals("()V")) { min.desc = "(Ljava/net/Proxy;)V"; injectPos.add(min); } } } for (int k = 0; k < injectPos.size(); k++) { AbstractInsnNode pos = injectPos.get(k); MethodInsnNode newMin = new MethodInsnNode(Opcodes.INVOKESTATIC, "ht/misc/injectsocks/ProxyManager", "getProxy", "()Ljava/net/Proxy;", false); instructions.insertBefore(pos, newMin); } } ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); cn.accept(cw); byte[] injectedClassfileBuffer = cw.toByteArray(); System.out.printf("INFO: classfileBuffer.legnth=%d, injectedClassfileBuffer.length=%d\n", classfileBuffer.length, injectedClassfileBuffer.length); return injectedClassfileBuffer; } catch (Throwable e) { e.printStackTrace(); return classfileBuffer; } }
From source file:ht.misc.injectsocks.InjectSockstTransformerImpl.java
License:Apache License
public void printClassByteCode(byte code[]) { ClassReader cr = new ClassReader(code); ClassNode cn = new ClassNode(); cr.accept(cn, 0);/*from w w w. j a va 2s . c o m*/ @SuppressWarnings("unchecked") List<MethodNode> methods = (List<MethodNode>) cn.methods; for (int i = 0; i < methods.size(); ++i) { MethodNode method = methods.get(i); InsnList instructions = method.instructions; if (instructions.size() <= 0) continue; System.out.println("Method: " + method.name + " "); for (int j = 0; j < instructions.size(); ++j) { AbstractInsnNode insn = (AbstractInsnNode) instructions.get(j); System.out.println( "\tInsn: opc=" + OpcodeUtil.getOpcode(insn.getOpcode()) + ", type=" + insn.getType()); if (insn.getType() == AbstractInsnNode.METHOD_INSN) { MethodInsnNode min = (MethodInsnNode) insn; System.out.printf("\t\towner=%s, name=%s, desc=%s\n", min.owner, min.name, min.desc); } } } }
From source file:io.moshisho.plugins.MyMojo.java
License:Apache License
private static void betterCompile(String classFile) throws IOException { InputStream is = new FileInputStream(classFile); ClassReader cr = new ClassReader(is); is.close();/*from w ww. jav a 2 s .com*/ ClassNode cn = new ClassNode(); cr.accept(cn, 0); List methods = cn.methods; for (int i = 0; i < methods.size(); ++i) { MethodNode method = (MethodNode) methods.get(i); if (!isStaticllyBound(method)) { continue; } InsnList instructions = method.instructions; AbstractInsnNode last = instructions.getLast(); while (last != null && last.getType() == AbstractInsnNode.LABEL) { last = last.getPrevious(); } if (last == null || !isReturnInstruction(last) || last.getPrevious().getType() != AbstractInsnNode.METHOD_INSN) { continue; } MethodInsnNode methodInv = (MethodInsnNode) last.getPrevious(); if (!isRecursionCall(cn, method, methodInv)) { continue; } System.out.println("TailRec Optimizaing: " + method.name); // get arguments and types String methodDesc = method.desc; String argsDesc = methodDesc.substring(methodDesc.indexOf('(') + 1, methodDesc.indexOf(')')); System.out.println(argsDesc); // work with Type.getArgumentTypes List<AbstractInsnNode> listInstNodes = new LinkedList<AbstractInsnNode>(); for (int j = argsDesc.length() - 1; j >= 0; j--) { char c = argsDesc.charAt(j); switch (c) { case 'I': listInstNodes.add(new VarInsnNode(ISTORE, argsDesc.length() - j)); break; case 'Z': listInstNodes.add(new VarInsnNode(ISTORE, argsDesc.length() - j)); break; case 'C': listInstNodes.add(new VarInsnNode(ISTORE, argsDesc.length() - j)); break; case 'B': listInstNodes.add(new VarInsnNode(ISTORE, argsDesc.length() - j)); break; case 'S': listInstNodes.add(new VarInsnNode(ISTORE, argsDesc.length() - j)); break; case 'F': listInstNodes.add(new VarInsnNode(FSTORE, argsDesc.length() - j)); break; case 'J': listInstNodes.add(new VarInsnNode(LSTORE, argsDesc.length() - j)); break; case 'D': listInstNodes.add(new VarInsnNode(DSTORE, argsDesc.length() - j)); break; case '[': // TODO: case 'L': // TODO: default: System.out.println("NOT TREATING: " + c); } } // remove the last aload_0 of the recursion AbstractInsnNode pnt = last; while (pnt != null && pnt.getOpcode() != 42 && !(pnt.getOpcode() == 25 && ((VarInsnNode) pnt).var == 0)) { pnt = pnt.getPrevious(); } method.instructions.remove(pnt); Collections.reverse(listInstNodes); for (AbstractInsnNode abstractInsnNode : listInstNodes) { method.instructions.insertBefore(last.getPrevious(), abstractInsnNode); } // place instead of return //goto LabelNode startOfMethodLabel = new LabelNode(new Label()); method.instructions.insertBefore(method.instructions.getFirst(), startOfMethodLabel); JumpInsnNode gotoInst = new JumpInsnNode(GOTO, startOfMethodLabel); method.instructions.set(last.getPrevious(), gotoInst); method.instructions.remove(last); ClassWriter cw = new ClassWriter(0); cn.accept(cw); FileOutputStream fos = new FileOutputStream(classFile); fos.write(cw.toByteArray()); fos.close(); } }
From source file:io.moshisho.plugins.OptimizeClasses.java
License:Apache License
private void optimize(File clz) throws Exception { InputStream is = new FileInputStream(clz); ClassReader cr = new ClassReader(is); is.close();// ww w . j a v a 2s . com ClassNode cn = new ClassNode(); cr.accept(cn, 0); List methods = cn.methods; for (int i = 0; i < methods.size(); ++i) { MethodNode method = (MethodNode) methods.get(i); if (!isStaticllyBound(method)) { continue; } InsnList instructions = method.instructions; AbstractInsnNode last = instructions.getLast(); while (last != null && last.getType() == AbstractInsnNode.LABEL) { last = last.getPrevious(); } if (last == null || !isReturnInstruction(last) || last.getPrevious().getType() != AbstractInsnNode.METHOD_INSN) { continue; } MethodInsnNode methodInv = (MethodInsnNode) last.getPrevious(); if (!isRecursionCall(cn, method, methodInv)) { continue; } getLog().info("TailRec Optimizaing: " + method.name); // get arguments and types String methodDesc = method.desc; String argsDesc = methodDesc.substring(methodDesc.indexOf('(') + 1, methodDesc.indexOf(')')); //System.out.println(argsDesc); // work with Type.getArgumentTypes List<AbstractInsnNode> listInstNodes = new LinkedList<AbstractInsnNode>(); for (int j = argsDesc.length() - 1; j >= 0; j--) { char c = argsDesc.charAt(j); switch (c) { case 'I': listInstNodes.add(new VarInsnNode(ISTORE, argsDesc.length() - j)); break; case 'Z': listInstNodes.add(new VarInsnNode(ISTORE, argsDesc.length() - j)); break; case 'C': listInstNodes.add(new VarInsnNode(ISTORE, argsDesc.length() - j)); break; case 'B': listInstNodes.add(new VarInsnNode(ISTORE, argsDesc.length() - j)); break; case 'S': listInstNodes.add(new VarInsnNode(ISTORE, argsDesc.length() - j)); break; case 'F': listInstNodes.add(new VarInsnNode(FSTORE, argsDesc.length() - j)); break; case 'J': listInstNodes.add(new VarInsnNode(LSTORE, argsDesc.length() - j)); break; case 'D': listInstNodes.add(new VarInsnNode(DSTORE, argsDesc.length() - j)); break; case '[': // TODO: case 'L': // TODO: default: System.out.println("NOT TREATING: " + c); } } // remove the last aload_0 of the recursion AbstractInsnNode pnt = last; while (pnt != null && pnt.getOpcode() != 42 && !(pnt.getOpcode() == 25 && ((VarInsnNode) pnt).var == 0)) { pnt = pnt.getPrevious(); } method.instructions.remove(pnt); Collections.reverse(listInstNodes); for (AbstractInsnNode abstractInsnNode : listInstNodes) { method.instructions.insertBefore(last.getPrevious(), abstractInsnNode); } // place instead of return //goto LabelNode startOfMethodLabel = new LabelNode(new Label()); method.instructions.insertBefore(method.instructions.getFirst(), startOfMethodLabel); JumpInsnNode gotoInst = new JumpInsnNode(GOTO, startOfMethodLabel); method.instructions.set(last.getPrevious(), gotoInst); method.instructions.remove(last); ClassWriter cw = new ClassWriter(0); cn.accept(cw); FileOutputStream fos = new FileOutputStream(clz); fos.write(cw.toByteArray()); fos.close(); } }
From source file:jaspex.transactifier.ChangeClinitMethodVisitor.java
License:Open Source License
private static boolean clinitIsSafe(Type t) { try {// www . j av a 2 s. c o m ClassReader cr = new ClassReader(t.commonName()); ClassNode cNode = new ClassNode(); cr.accept(cNode, 0); for (MethodNode method : cNode.methods) { if (!method.name.equals("<clinit>")) continue; // Examinar instruces Iterator<AbstractInsnNode> it = method.instructions.iterator(); while (it.hasNext()) { AbstractInsnNode insn = it.next(); switch (insn.getType()) { case AbstractInsnNode.FRAME: case AbstractInsnNode.INT_INSN: case AbstractInsnNode.JUMP_INSN: case AbstractInsnNode.LABEL: case AbstractInsnNode.LDC_INSN: case AbstractInsnNode.LINE: case AbstractInsnNode.LOOKUPSWITCH_INSN: case AbstractInsnNode.MULTIANEWARRAY_INSN: case AbstractInsnNode.TABLESWITCH_INSN: case AbstractInsnNode.TYPE_INSN: case AbstractInsnNode.VAR_INSN: break; case AbstractInsnNode.FIELD_INSN: FieldInsnNode fieldInsn = (FieldInsnNode) insn; if (fieldInsn.getOpcode() != PUTSTATIC) { // GETSTATIC, GETFIELD, PUTFIELD return false; } break; case AbstractInsnNode.IINC_INSN: return false; case AbstractInsnNode.INSN: if (unsafeInsnBytecodes.contains(insn.getOpcode())) { Log.debug(t.commonName() + ".<clinit>() is unsafe " + "because of bytecode " + insn.getOpcode()); return false; } break; case AbstractInsnNode.METHOD_INSN: MethodInsnNode methodInsn = (MethodInsnNode) insn; if (!ClassFilter.isMethodWhitelisted(Type.fromAsm(methodInsn.owner), methodInsn.name, methodInsn.desc)) { Log.debug(t.commonName() + ".<clinit>() is unsafe " + "because it invokes " + Type.fromAsm(methodInsn.owner).commonName() + "." + methodInsn.name); return false; } break; default: throw new Error("Unexpected bytecode " + insn); } } //Log.debug(t.commonName() + ".<clinit>() for " + t + " is safe"); return true; } return false; } catch (IOException e) { throw new Error(e); } }
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./*from ww w . j av a 2s. 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.mutabilitydetector.checkers.settermethod.AssignmentGuardFinder.java
License:Apache License
private static boolean isEqualsInstruction(final AbstractInsnNode insn) { final boolean result; if (AbstractInsnNode.METHOD_INSN == insn.getType()) { final MethodInsnNode methodInsnNode = (MethodInsnNode) insn; result = methodInsnNode.name.equals("equals"); } else {/*from w w w. j a va 2s . com*/ result = false; } return result; }
From source file:org.mutabilitydetector.checkers.settermethod.EffectiveAssignmentInsnVerifier.java
License:Apache License
private boolean isNotInvokationOfParameterlessInstanceOrClassMethod(final AbstractInsnNode insn) { final boolean result; if (AbstractInsnNode.METHOD_INSN != insn.getType()) { result = true;// ww w . j ava2 s.c o m } else { final MethodInsnNode methodInvokationInstruction = (MethodInsnNode) insn; result = hasInvokedMethodArguments(methodInvokationInstruction) || isInvokedMethodNotInstanceOrClassMethod(methodInvokationInstruction); } return result; }
From source file:org.parboiled.transform.process.ImplicitActionsConverter.java
License:Apache License
private static boolean isObjectArgumentToRuleCreatingMethodCall(final InstructionGraphNode node, final InstructionGraphNode dependent) { // is the single dependent a method call ? final AbstractInsnNode insn = dependent.getInstruction(); if (insn.getType() != AbstractInsnNode.METHOD_INSN) return false; // Does this method call return a Rule ? final MethodInsnNode methodNode = (MethodInsnNode) insn; if (!Type.getType(Rule.class).equals(Type.getReturnType(methodNode.desc))) return false; // Does the result of the Boolean.valueOf(boolean) call correspond to // an Object parameter ? final Type[] argTypes = Type.getArgumentTypes(methodNode.desc); final int argIndex = getArgumentIndex(dependent, node); Preconditions.checkState(argIndex < argTypes.length); final String typeName = argTypes[argIndex].getInternalName(); return CodegenUtils.p(Object.class).equals(typeName); }
From source file:org.spoofax.interpreter.adapter.asm.ASMFactory.java
License:LGPL
public static IStrategoTerm wrap(AbstractInsnNode node) { if (node == null) return None.INSTANCE; switch (node.getType()) { case AbstractInsnNode.FIELD_INSN: return wrap((FieldInsnNode) node); case AbstractInsnNode.FRAME: return wrap((FrameNode) node); case AbstractInsnNode.IINC_INSN: return wrap((IincInsnNode) node); case AbstractInsnNode.INSN: return wrap((InsnNode) node); case AbstractInsnNode.INT_INSN: return wrap((IntInsnNode) node); case AbstractInsnNode.INVOKE_DYNAMIC_INSN: throw new NotImplementedException(); case AbstractInsnNode.JUMP_INSN: return wrap((JumpInsnNode) node); case AbstractInsnNode.LABEL: return wrap((LabelNode) node); case AbstractInsnNode.LDC_INSN: return wrap((LdcInsnNode) node); case AbstractInsnNode.LINE: return wrap((LineNumberNode) node); case AbstractInsnNode.LOOKUPSWITCH_INSN: return wrap((LookupSwitchInsnNode) node); case AbstractInsnNode.METHOD_INSN: return wrap((MethodInsnNode) node); case AbstractInsnNode.MULTIANEWARRAY_INSN: return wrap((MultiANewArrayInsnNode) node); case AbstractInsnNode.TABLESWITCH_INSN: return wrap((TableSwitchInsnNode) node); case AbstractInsnNode.TYPE_INSN: return wrap((TypeInsnNode) node); case AbstractInsnNode.VAR_INSN: return wrap((VarInsnNode) node); case -1:/*from w w w .j a v a 2s. c o m*/ System.err.println("Bogus " + node.getClass().getName()); return None.INSTANCE; default: throw new IllegalArgumentException( "Unknown type " + node.getOpcode() + " for " + node.getClass().getName()); } }