Java Code Examples for org.objectweb.asm.tree.InsnList#iterator()
The following examples show how to use
org.objectweb.asm.tree.InsnList#iterator() .
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 File: ClickableViewAccessibilityDetector.java From javaide with GNU General Public License v3.0 | 6 votes |
@SuppressWarnings("unchecked") // ASM API @Nullable private static AbstractInsnNode findMethodCallInstruction( @NonNull InsnList instructions, @NonNull String owner, @NonNull String name, @NonNull String desc) { ListIterator<AbstractInsnNode> iterator = instructions.iterator(); while (iterator.hasNext()) { AbstractInsnNode insnNode = iterator.next(); if (insnNode.getType() == AbstractInsnNode.METHOD_INSN) { MethodInsnNode methodInsnNode = (MethodInsnNode) insnNode; if ((methodInsnNode.owner.equals(owner)) && (methodInsnNode.name.equals(name)) && (methodInsnNode.desc.equals(desc))) { return methodInsnNode; } } } return null; }
Example 2
Source File: Instrumentator.java From instrumentation with Apache License 2.0 | 6 votes |
private void addTraceReturn() { InsnList il = this.mn.instructions; Iterator<AbstractInsnNode> it = il.iterator(); while (it.hasNext()) { AbstractInsnNode abstractInsnNode = it.next(); switch (abstractInsnNode.getOpcode()) { case Opcodes.RETURN: il.insertBefore(abstractInsnNode, getVoidReturnTraceInstructions()); break; case Opcodes.IRETURN: case Opcodes.LRETURN: case Opcodes.FRETURN: case Opcodes.ARETURN: case Opcodes.DRETURN: il.insertBefore(abstractInsnNode, getReturnTraceInstructions()); } } }
Example 3
Source File: Instrumentator.java From instrumentation with Apache License 2.0 | 6 votes |
private void addTraceThrow() { InsnList il = this.mn.instructions; Iterator<AbstractInsnNode> it = il.iterator(); while (it.hasNext()) { AbstractInsnNode abstractInsnNode = it.next(); switch (abstractInsnNode.getOpcode()) { case Opcodes.ATHROW: il.insertBefore(abstractInsnNode, getThrowTraceInstructions()); break; } } }
Example 4
Source File: ControlFlowAnalyser.java From QuickTheories with Apache License 2.0 | 6 votes |
private static Set<AbstractInsnNode> findJumpTargets(final InsnList instructions) { final Set<AbstractInsnNode> jumpTargets = new HashSet<>(); final ListIterator<AbstractInsnNode> it = instructions.iterator(); while (it.hasNext()) { final AbstractInsnNode o = it.next(); if (o instanceof JumpInsnNode) { jumpTargets.add(((JumpInsnNode) o).label); } else if (o instanceof TableSwitchInsnNode) { final TableSwitchInsnNode twn = (TableSwitchInsnNode) o; jumpTargets.add(twn.dflt); jumpTargets.addAll(twn.labels); } else if (o instanceof LookupSwitchInsnNode) { final LookupSwitchInsnNode lsn = (LookupSwitchInsnNode) o; jumpTargets.add(lsn.dflt); jumpTargets.addAll(lsn.labels); } } return jumpTargets; }
Example 5
Source File: SearchUtils.java From coroutines with GNU Lesser General Public License v3.0 | 6 votes |
/** * Find instructions in a certain class that are of a certain set of opcodes. * @param insnList instruction list to search through * @param opcodes opcodes to search for * @return list of instructions that contain the opcodes being searched for * @throws NullPointerException if any argument is {@code null} * @throws IllegalArgumentException if {@code opcodes} is empty */ public static List<AbstractInsnNode> searchForOpcodes(InsnList insnList, int ... opcodes) { Validate.notNull(insnList); Validate.notNull(opcodes); Validate.isTrue(opcodes.length > 0); List<AbstractInsnNode> ret = new LinkedList<>(); Set<Integer> opcodeSet = new HashSet<>(); Arrays.stream(opcodes).forEach((x) -> opcodeSet.add(x)); Iterator<AbstractInsnNode> it = insnList.iterator(); while (it.hasNext()) { AbstractInsnNode insnNode = it.next(); if (opcodeSet.contains(insnNode.getOpcode())) { ret.add(insnNode); } } return ret; }
Example 6
Source File: BeforeFieldAccess.java From Mixin with MIT License | 6 votes |
/** * Searches for an array access instruction in the supplied instruction list * which is within <tt>searchRange</tt> instructions of the supplied field * instruction. Searching halts if the search range is exhausted, if an * {@link Opcodes#ARRAYLENGTH} opcode is encountered immediately after the * specified access, if a matching field access is found, or if the end of * the method is reached. * * @param insns Instruction list to search * @param fieldNode Field instruction to search from * @param opcode array access opcode to search for * @param searchRange search range * @return matching opcode or <tt>null</tt> if not matched */ public static AbstractInsnNode findArrayNode(InsnList insns, FieldInsnNode fieldNode, int opcode, int searchRange) { int pos = 0; for (Iterator<AbstractInsnNode> iter = insns.iterator(insns.indexOf(fieldNode) + 1); iter.hasNext();) { AbstractInsnNode insn = iter.next(); if (insn.getOpcode() == opcode) { return insn; } else if (insn.getOpcode() == Opcodes.ARRAYLENGTH && pos == 0) { return null; } else if (insn instanceof FieldInsnNode) { FieldInsnNode field = (FieldInsnNode) insn; if (field.desc.equals(fieldNode.desc) && field.name.equals(fieldNode.name) && field.owner.equals(fieldNode.owner)) { return null; } } if (pos++ > searchRange) { return null; } } return null; }
Example 7
Source File: SearchUtils.java From coroutines with GNU Lesser General Public License v3.0 | 6 votes |
/** * Find line number associated with an instruction. * @param insnList instruction list for method * @param insnNode instruction within method being searched against * @throws NullPointerException if any argument is {@code null} or contains {@code null} * @throws IllegalArgumentException if arguments aren't all from the same method * @return line number node associated with the instruction, or {@code null} if no line number exists */ public static LineNumberNode findLineNumberForInstruction(InsnList insnList, AbstractInsnNode insnNode) { Validate.notNull(insnList); Validate.notNull(insnNode); int idx = insnList.indexOf(insnNode); Validate.isTrue(idx != -1); // Get index of labels and insnNode within method ListIterator<AbstractInsnNode> insnIt = insnList.iterator(idx); while (insnIt.hasPrevious()) { AbstractInsnNode node = insnIt.previous(); if (node instanceof LineNumberNode) { return (LineNumberNode) node; } } return null; }
Example 8
Source File: JumpInsnPoint.java From Mixin with MIT License | 6 votes |
@Override public boolean find(String desc, InsnList insns, Collection<AbstractInsnNode> nodes) { boolean found = false; int ordinal = 0; ListIterator<AbstractInsnNode> iter = insns.iterator(); while (iter.hasNext()) { AbstractInsnNode insn = iter.next(); if (insn instanceof JumpInsnNode && (this.opCode == -1 || insn.getOpcode() == this.opCode)) { if (this.ordinal == -1 || this.ordinal == ordinal) { nodes.add(insn); found = true; } ordinal++; } } return found; }
Example 9
Source File: BeforeFinalReturn.java From Mixin with MIT License | 6 votes |
@Override public boolean find(String desc, InsnList insns, Collection<AbstractInsnNode> nodes) { AbstractInsnNode ret = null; // RETURN opcode varies based on return type, thus we calculate what opcode we're actually looking for by inspecting the target method int returnOpcode = Type.getReturnType(desc).getOpcode(Opcodes.IRETURN); ListIterator<AbstractInsnNode> iter = insns.iterator(); while (iter.hasNext()) { AbstractInsnNode insn = iter.next(); if (insn instanceof InsnNode && insn.getOpcode() == returnOpcode) { ret = insn; } } // WAT? if (ret == null) { throw new InvalidInjectionException(this.context, "TAIL could not locate a valid RETURN in the target method!"); } nodes.add(ret); return true; }
Example 10
Source File: CallSiteFinder.java From tascalate-javaflow with Apache License 2.0 | 5 votes |
List<Result> findMatchingCallSites(InsnList instructions, List<LocalVariableAnnotationNode> varAnnotations, Map<Integer, List<AnnotationNode>> paramAnnotations) { List<Result> result = new ArrayList<Result>(); for (@SuppressWarnings("unchecked") Iterator<AbstractInsnNode> i = instructions.iterator(); i.hasNext(); ) { AbstractInsnNode ins = i.next(); if (ins instanceof MethodInsnNode) { MethodInsnNode mins = (MethodInsnNode)ins; Result entry = findMatchingCallSite(mins, varAnnotations, paramAnnotations); if (entry != null) { result.add(entry); } } } return result; }
Example 11
Source File: DefaultMethodClassFixer.java From bazel with Apache License 2.0 | 5 votes |
private boolean isClinitAlreadyDesugared( ImmutableList<String> companionsToAccessToTriggerInterfaceClinit) { InsnList instructions = clInitMethodNode.instructions; if (instructions.size() <= companionsToAccessToTriggerInterfaceClinit.size()) { // The <clinit> must end with RETURN, so if the instruction count is less than or equal to // the companion class count, this <clinit> has not been desugared. return false; } Iterator<AbstractInsnNode> iterator = instructions.iterator(); for (String companion : companionsToAccessToTriggerInterfaceClinit) { if (!iterator.hasNext()) { return false; } AbstractInsnNode insn = iterator.next(); if (!(insn instanceof MethodInsnNode)) { return false; } MethodInsnNode methodInsnNode = (MethodInsnNode) insn; if (methodInsnNode.getOpcode() != Opcodes.INVOKESTATIC || !methodInsnNode.owner.equals(companion) || !methodInsnNode.name.equals( InterfaceDesugaring.COMPANION_METHOD_TO_TRIGGER_INTERFACE_CLINIT_NAME)) { return false; } checkState( methodInsnNode.desc.equals( InterfaceDesugaring.COMPANION_METHOD_TO_TRIGGER_INTERFACE_CLINIT_DESC), "Inconsistent method desc: %s vs %s", methodInsnNode.desc, InterfaceDesugaring.COMPANION_METHOD_TO_TRIGGER_INTERFACE_CLINIT_DESC); } return true; }
Example 12
Source File: RegexInsnFinder.java From bytecode-viewer with GNU General Public License v3.0 | 5 votes |
private AbstractInsnNode[] cleanInsn(final InsnList insnList) { final List<AbstractInsnNode> il = new ArrayList<AbstractInsnNode>(); final Iterator<AbstractInsnNode> iIt = insnList.iterator(); while (iIt.hasNext()) { final AbstractInsnNode node = iIt.next(); if (node.getOpcode() >= 0) { il.add(node); } } return il.toArray(new AbstractInsnNode[il.size()]); }
Example 13
Source File: BeforeNew.java From Mixin with MIT License | 5 votes |
protected boolean findCtor(InsnList insns, TypeInsnNode newNode) { int indexOf = insns.indexOf(newNode); for (Iterator<AbstractInsnNode> iter = insns.iterator(indexOf); iter.hasNext();) { AbstractInsnNode insn = iter.next(); if (insn instanceof MethodInsnNode && insn.getOpcode() == Opcodes.INVOKESPECIAL) { MethodInsnNode methodNode = (MethodInsnNode)insn; if (Constants.CTOR.equals(methodNode.name) && methodNode.owner.equals(newNode.desc) && methodNode.desc.equals(this.desc)) { return true; } } } return false; }
Example 14
Source File: BeforeNew.java From Mixin with MIT License | 5 votes |
@SuppressWarnings("unchecked") @Override public boolean find(String desc, InsnList insns, Collection<AbstractInsnNode> nodes) { boolean found = false; int ordinal = 0; Collection<TypeInsnNode> newNodes = new ArrayList<TypeInsnNode>(); Collection<AbstractInsnNode> candidates = (Collection<AbstractInsnNode>) (this.desc != null ? newNodes : nodes); ListIterator<AbstractInsnNode> iter = insns.iterator(); while (iter.hasNext()) { AbstractInsnNode insn = iter.next(); if (insn instanceof TypeInsnNode && insn.getOpcode() == Opcodes.NEW && this.matchesOwner((TypeInsnNode) insn)) { if (this.ordinal == -1 || this.ordinal == ordinal) { candidates.add(insn); found = this.desc == null; } ordinal++; } } if (this.desc != null) { for (TypeInsnNode newNode : newNodes) { if (this.findCtor(insns, newNode)) { nodes.add(newNode); found = true; } } } return found; }
Example 15
Source File: BeforeConstant.java From Mixin with MIT License | 5 votes |
@Override public boolean find(String desc, InsnList insns, Collection<AbstractInsnNode> nodes) { boolean found = false; this.log("BeforeConstant is searching for constants in method with descriptor {}", desc); ListIterator<AbstractInsnNode> iter = insns.iterator(); for (int ordinal = 0, last = 0; iter.hasNext();) { AbstractInsnNode insn = iter.next(); boolean matchesInsn = this.expand ? this.matchesConditionalInsn(last, insn) : this.matchesConstantInsn(insn); if (matchesInsn) { this.log(" BeforeConstant found a matching constant{} at ordinal {}", this.matchByType != null ? " TYPE" : " value", ordinal); if (this.ordinal == -1 || this.ordinal == ordinal) { this.log(" BeforeConstant found {}", Bytecode.describeNode(insn).trim()); nodes.add(insn); found = true; } ordinal++; } if (!(insn instanceof LabelNode) && !(insn instanceof FrameNode)) { last = insn.getOpcode(); } } return found; }
Example 16
Source File: Decoder.java From javasdk with GNU Lesser General Public License v3.0 | 5 votes |
/** * decode hvm payload. * * @param payload in: | class length(4B) | name length(2B) | class | class name | bin | * @return HVMPayload */ public static HVMPayload decodeHVMPayload(String payload) throws IOException { byte[] payloadBytes = ByteUtil.fromHex(payload); int classLen = ByteUtil.bytesToInteger(ByteUtil.copy(payloadBytes, 0, 4)); int nameLen = ByteUtil.bytesToInteger(ByteUtil.copy(payloadBytes, 4, 2)); byte[] classBytes = ByteUtil.copy(payloadBytes, 6, classLen); byte[] name = ByteUtil.copy(payloadBytes, 6 + classLen, nameLen); byte[] bin = ByteUtil.copy(payloadBytes, 6 + classLen + nameLen, payloadBytes.length - 6 - classLen - nameLen); Set<String> methodNames = new HashSet<>(); InputStream is = ByteSource.wrap(classBytes).openStream(); ClassReader reader = new ClassReader(is); ClassNode classNode = new ClassNode(); reader.accept(classNode, 0); for (MethodNode mn : (List<MethodNode>)classNode.methods) { if (mn.name.equalsIgnoreCase("invoke") && Type.getReturnType(mn.desc).toString().indexOf("Object") == -1) { Type[] argumentTypes = Type.getArgumentTypes(mn.desc); InsnList instructions = mn.instructions; for (ListIterator<AbstractInsnNode> lan = instructions.iterator(); lan.hasNext();) { AbstractInsnNode cur = lan.next(); if (cur instanceof MethodInsnNode) { for (Type t : argumentTypes) { if (t.toString().indexOf(((MethodInsnNode) cur).owner) != -1) { methodNames.add(((MethodInsnNode) cur).name); } } } } } } String invokeBeanName = new String(name, "UTF-8"); String invokeArgs = new String(bin, "UTF-8"); return new HVMPayload(invokeBeanName, invokeArgs, methodNames); }
Example 17
Source File: SearchUtils.java From coroutines with GNU Lesser General Public License v3.0 | 5 votes |
/** * Find invocations of a certain method. * @param insnList instruction list to search through * @param expectedMethod type of method being invoked * @return list of invocations (may be nodes of type {@link MethodInsnNode} or {@link InvokeDynamicInsnNode}) * @throws NullPointerException if any argument is {@code null} * @throws NullPointerException if {@code expectedMethodType} isn't of sort {@link Type#METHOD} */ public static List<AbstractInsnNode> findInvocationsOf(InsnList insnList, Method expectedMethod) { Validate.notNull(insnList); Validate.notNull(expectedMethod); List<AbstractInsnNode> ret = new ArrayList<>(); Type expectedMethodDesc = Type.getType(expectedMethod); Type expectedMethodOwner = Type.getType(expectedMethod.getDeclaringClass()); String expectedMethodName = expectedMethod.getName(); Iterator<AbstractInsnNode> it = insnList.iterator(); while (it.hasNext()) { AbstractInsnNode instructionNode = it.next(); Type methodDesc; Type methodOwner; String methodName; if (instructionNode instanceof MethodInsnNode) { MethodInsnNode methodInsnNode = (MethodInsnNode) instructionNode; methodDesc = Type.getType(methodInsnNode.desc); methodOwner = Type.getObjectType(methodInsnNode.owner); methodName = expectedMethod.getName(); } else { continue; } if (methodDesc.equals(expectedMethodDesc) && methodOwner.equals(expectedMethodOwner) && methodName.equals(expectedMethodName)) { ret.add(instructionNode); } } return ret; }
Example 18
Source File: BeforeInvoke.java From Mixin with MIT License | 4 votes |
protected boolean find(String desc, InsnList insns, Collection<AbstractInsnNode> nodes, ITargetSelector selector, SearchType searchType) { if (selector == null) { return false; } ITargetSelector target = searchType == SearchType.PERMISSIVE ? selector.configure("permissive") : selector; int ordinal = 0; int found = 0; ListIterator<AbstractInsnNode> iter = insns.iterator(); while (iter.hasNext()) { AbstractInsnNode insn = iter.next(); if (this.matchesInsn(insn)) { MemberInfo nodeInfo = new MemberInfo(insn); this.log("{} is considering insn {}", this.className, nodeInfo); if (target.match(insn).isExactMatch()) { this.log("{} > found a matching insn, checking preconditions...", this.className); if (this.matchesOrdinal(ordinal)) { this.log("{} > > > found a matching insn at ordinal {}", this.className, ordinal); if (this.addInsn(insns, nodes, insn)) { found++; } if (this.ordinal == ordinal) { break; } } ordinal++; } } this.inspectInsn(desc, insns, insn); } if (searchType == SearchType.PERMISSIVE && found > 1) { this.logger.warn("A permissive match for {} using \"{}\" in {} matched {} instructions, this may cause unexpected behaviour. " + "To inhibit permissive search set mixin.env.allowPermissiveMatch=false", this.className, selector, this.context, found); } return found > 0; }
Example 19
Source File: SearchUtils.java From coroutines with GNU Lesser General Public License v3.0 | 4 votes |
/** * Find trycatch blocks within a method that an instruction is apart of. Only includes the try portion, not the catch (handler) portion. * @param insnList instruction list for method * @param tryCatchBlockNodes trycatch blocks in method * @param insnNode instruction within method being searched against * @throws NullPointerException if any argument is {@code null} or contains {@code null} * @throws IllegalArgumentException if arguments aren't all from the same method * @return items from {@code tryCatchBlockNodes} that {@code insnNode} is a part of */ public static List<TryCatchBlockNode> findTryCatchBlockNodesEncompassingInstruction(InsnList insnList, List<TryCatchBlockNode> tryCatchBlockNodes, AbstractInsnNode insnNode) { Validate.notNull(insnList); Validate.notNull(tryCatchBlockNodes); Validate.notNull(insnNode); Validate.noNullElements(tryCatchBlockNodes); Map<LabelNode, Integer> labelPositions = new HashMap<>(); int insnNodeIdx = -1; // Get index of labels and insnNode within method ListIterator<AbstractInsnNode> insnIt = insnList.iterator(); int insnCounter = 0; while (insnIt.hasNext()) { AbstractInsnNode node = insnIt.next(); // If our instruction, save index if (node == insnNode) { if (insnNodeIdx == -1) { insnNodeIdx = insnCounter; } else { throw new IllegalArgumentException(); // insnNode encountered multiple times in methodNode. Should not happen. } } // If label node, save position if (node instanceof LabelNode) { labelPositions.put((LabelNode) node, insnCounter); } // Increment counter insnCounter++; } Validate.isTrue(insnNodeIdx != -1); //throw exception if node not in method list // Find out which trycatch blocks insnNode is within List<TryCatchBlockNode> ret = new ArrayList<>(); for (TryCatchBlockNode tryCatchBlockNode : tryCatchBlockNodes) { Integer startIdx = labelPositions.get(tryCatchBlockNode.start); Integer endIdx = labelPositions.get(tryCatchBlockNode.end); Validate.isTrue(startIdx != null); Validate.isTrue(endIdx != null); if (insnNodeIdx >= startIdx && insnNodeIdx < endIdx) { ret.add(tryCatchBlockNode); } } return ret; }
Example 20
Source File: WildflyDeploymentFactory.java From netbeans with Apache License 2.0 | 4 votes |
@Override protected Class<?> findClass(String name) throws ClassNotFoundException { // see issue #249135 if (patchXnio && "org.xnio.nio.WorkerThread".equals(name)) { // NOI18N try { LOGGER.log(Level.INFO, "Patching the issue #249135"); String path = name.replace('.', '/').concat(".class"); // NOI18N try (InputStream is = super.getResourceAsStream(path)) { ClassReader cr = new ClassReader(is); ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_FRAMES) { @Override protected String getCommonSuperClass(String string, String string1) { if ("org/xnio/nio/NioHandle".equals(string) // NOI18N || "org/xnio/nio/NioHandle".equals(string1)) { // NOI18N return "java/lang/Object"; // NOI18N } return super.getCommonSuperClass(string, string1); } }; ClassNode node = new ClassNode(Opcodes.ASM7); cr.accept(node, 0); for (MethodNode m : (Collection<MethodNode>) node.methods) { if ("execute".equals(m.name) // NOI18N && "(Ljava/lang/Runnable;)V".equals(m.desc)) { // NOI18N InsnList list = m.instructions; for (ListIterator it = list.iterator(); it.hasNext(); ) { AbstractInsnNode n = (AbstractInsnNode) it.next(); if (n instanceof MethodInsnNode) { MethodInsnNode mn = (MethodInsnNode) n; if ("org/xnio/nio/Log".equals(mn.owner) // NOI18N && "threadExiting".equals(mn.name) // NOI18N && "()Ljava/util/concurrent/RejectedExecutionException;".equals(mn.desc)) { // NOI18N if (it.hasNext()) { AbstractInsnNode possibleThrow = (AbstractInsnNode) it.next(); if (possibleThrow.getOpcode() == Opcodes.ATHROW) { it.set(new InsnNode(Opcodes.POP)); break; } } } } } break; } } node.accept(cw); byte[] newBytecode = cw.toByteArray(); return super.defineClass(name, newBytecode, 0, newBytecode.length); } } catch (Exception ex) { // just fallback to original behavior LOGGER.log(Level.INFO, null, ex); } } return super.findClass(name); }