org.objectweb.asm.tree.TableSwitchInsnNode Java Examples

The following examples show how to use org.objectweb.asm.tree.TableSwitchInsnNode. 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: ControlFlowAnalyser.java    From pitest with Apache License 2.0 6 votes vote down vote up
private static Set<LabelNode> findJumpTargets(final InsnList instructions) {
  final Set<LabelNode> jumpTargets = new HashSet<>();
  for (AbstractInsnNode o : instructions) {
    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 #2
Source File: CaseAdapter.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * <p>
 * This method Handled the Switch block of TableSwitchInsnNode type in a
 * method
 * </p>.
 *
 * @param currentTableSwithInsn Type of switch block
 */
private void processTableSwitchBlock(
		TableSwitchInsnNode currentTableSwithInsn) {
	LabelNode currentLabel = currentTableSwithInsn.dflt;

	int switchStartIndex = CollectionUtil.getObjectIndexInArray(insnArr,
			currentTableSwithInsn);
	int switchTargetIndex = CollectionUtil.getObjectIndexInArray(insnArr,
			currentLabel);

	if (switchTargetIndex > switchStartIndex) {
		LOGGER.debug("switch block ended at: " + switchTargetIndex);
		switchCount++;

		AbstractInsnNode[] ainSwitchBlock = new AbstractInsnNode[] {
				currentTableSwithInsn.getPrevious(), currentLabel };
		Integer[] lineNumbers = getLineNumbersForSwitchBlock(ainSwitchBlock);
		InsnList[] il = getInsnForswitchBlock(switchCount, lineNumbers);
		addInsnForswitchBlock(il, ainSwitchBlock);

		scanIndexForswitch = switchTargetIndex;

		handleTableSwitchCases(currentTableSwithInsn);
	}
}
 
Example #3
Source File: CaseAdapter.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * <p>
 * This method finds Switch block in a method and processes it
 * </p>.
 *
 * @param scanStartIndex Start index for the scan
 * @param scanEndIndex End index for the scan
 */
private void instrumentswitchBlock(int scanStartIndex,
		int scanEndIndex) {
	for (scanIndexForswitch = scanStartIndex; scanIndexForswitch <= scanEndIndex; scanIndexForswitch++) {
		AbstractInsnNode currentInsnNode = insnArr[scanIndexForswitch];

		if (currentInsnNode instanceof TableSwitchInsnNode
				&& Opcodes.TABLESWITCH == currentInsnNode.getOpcode()) {
			processTableSwitchBlock((TableSwitchInsnNode) currentInsnNode);
		} else if (currentInsnNode instanceof LookupSwitchInsnNode
				&& Opcodes.LOOKUPSWITCH == currentInsnNode.getOpcode()) {
			processLookupSwitchBlock((LookupSwitchInsnNode) currentInsnNode);
		}

	}
}
 
Example #4
Source File: StackHelper.java    From zelixkiller with GNU General Public License v3.0 6 votes vote down vote up
public InsnValue getSwitchValue(AbstractInsnNode insn, InsnValue value) {
	if (value.getValue() == null) {
		return InsnValue.intValue(-1);
	}
	int i = (int) value.getValue();
	switch (insn.getOpcode()) {
	case Opcodes.TABLESWITCH:
		TableSwitchInsnNode tsin = (TableSwitchInsnNode) insn;
		if (i < tsin.min || i > tsin.max) {
			return InsnValue.intValue(-1);
		}
		return InsnValue.intValue(i);
	case Opcodes.LOOKUPSWITCH:
		LookupSwitchInsnNode lsin = (LookupSwitchInsnNode) insn;
		for (Object o : lsin.keys) {
			if (o.equals(i)) {
				return InsnValue.intValue(i);
			}
		}
		return InsnValue.intValue(-1);
	}

	return null;
}
 
Example #5
Source File: Tableswitch.java    From nuls-v2 with MIT License 6 votes vote down vote up
public static void tableswitch(final Frame frame) {
    TableSwitchInsnNode table = frame.tableSwitchInsnNode();
    LabelNode labelNode = table.dflt;
    int index = frame.operandStack.popInt();
    int min = table.min;
    int max = table.max;
    int size = max - min + 1;
    for (int i = 0; i < size; i++) {
        if (index == (i + min)) {
            labelNode = table.labels.get(i);
            break;
        }
    }
    frame.jump(labelNode);

    //Log.opcode(frame.getCurrentOpCode());
}
 
Example #6
Source File: ControlFlowAnalyser.java    From QuickTheories with Apache License 2.0 6 votes vote down vote up
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 #7
Source File: Tableswitch.java    From nuls with MIT License 6 votes vote down vote up
public static void tableswitch(final Frame frame) {
    TableSwitchInsnNode table = frame.tableSwitchInsnNode();
    LabelNode labelNode = table.dflt;
    int index = frame.operandStack.popInt();
    int min = table.min;
    int max = table.max;
    int size = max - min + 1;
    for (int i = 0; i < size; i++) {
        if (index == (i + min)) {
            labelNode = table.labels.get(i);
            break;
        }
    }
    frame.jump(labelNode);

    //Log.opcode(frame.getCurrentOpCode());
}
 
Example #8
Source File: AsmMethodSource.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
private void convertTableSwitchInsn(TableSwitchInsnNode insn) {
	StackFrame frame = getFrame(insn);
	if (units.containsKey(insn)) {
		frame.mergeIn(pop());
		return;
	}
	Operand key = popImmediate();
	UnitBox dflt = Jimple.v().newStmtBox(null);
	List<UnitBox> targets = new ArrayList<UnitBox>(insn.labels.size());
	labels.put(insn.dflt, dflt);
	for (LabelNode ln : insn.labels) {
		UnitBox box = Jimple.v().newStmtBox(null);
		targets.add(box);
		labels.put(ln, box);
	}
	TableSwitchStmt tss = Jimple.v().newTableSwitchStmt(key.stackOrValue(),
			insn.min, insn.max, targets, dflt);
	key.addBox(tss.getKeyBox());
	frame.in(key);
	frame.boxes(tss.getKeyBox());
	setUnit(insn, tss);
}
 
Example #9
Source File: TableSwitchHandler.java    From native-obfuscator with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void process(MethodContext context, TableSwitchInsnNode node) {
    StringBuilder output = context.output;

    output.append(getStart(context)).append("\n    ");

    for (int i = 0; i < node.labels.size(); ++i) {
        output.append(String.format("    %s\n    ", getPart(context,
                node.min + i,
                node.labels.get(i).getLabel())));
    }
    output.append(String.format("    %s\n    ", getDefault(context, node.dflt.getLabel())));

    instructionName = "TABLESWITCH_END";
}
 
Example #10
Source File: CodeBlock.java    From grappa with Apache License 2.0 5 votes vote down vote up
public CodeBlock tableswitch(final int min, final int max,
    final LabelNode defaultLabel, final LabelNode[] cases)
{
    instructionList.add(new TableSwitchInsnNode(min, max, defaultLabel,
        cases));
    return this;
}
 
Example #11
Source File: CodeBlock.java    From grappa with Apache License 2.0 5 votes vote down vote up
public CodeBlock visitTableSwitchInsn(final int min, final int max,
    final LabelNode defaultHandler, final LabelNode[] handlers)
{
    instructionList.add(new TableSwitchInsnNode(min, max, defaultHandler,
        handlers));
    return this;
}
 
Example #12
Source File: GenericGenerators.java    From coroutines with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Generates instructions for a switch table. This does not automatically generate jumps at the end of each default/case statement. It's
 * your responsibility to either add the relevant jumps, throws, or returns at each default/case statement, otherwise the code will
 * just fall through (which is likely not what you want).
 * @param indexInsnList instructions to calculate the index -- must leave an int on the stack
 * @param defaultInsnList instructions to execute on default statement -- must leave the stack unchanged
 * @param caseStartIdx the number which the case statements start at
 * @param caseInsnLists instructions to execute on each case statement -- must leave the stack unchanged
 * @return instructions for a table switch
 * @throws NullPointerException if any argument is {@code null} or contains {@code null}
 * @throws IllegalArgumentException if any numeric argument is {@code < 0}, or if {@code caseInsnLists} is empty
 */
public static InsnList tableSwitch(InsnList indexInsnList, InsnList defaultInsnList, int caseStartIdx, InsnList... caseInsnLists) {
    Validate.notNull(defaultInsnList);
    Validate.notNull(indexInsnList);
    Validate.isTrue(caseStartIdx >= 0);
    Validate.notNull(caseInsnLists);
    Validate.noNullElements(caseInsnLists);
    Validate.isTrue(caseInsnLists.length > 0);
    InsnList ret = new InsnList();

    LabelNode defaultLabelNode = new LabelNode();
    LabelNode[] caseLabelNodes = new LabelNode[caseInsnLists.length];

    for (int i = 0; i < caseInsnLists.length; i++) {
        caseLabelNodes[i] = new LabelNode();
    }

    ret.add(indexInsnList);
    ret.add(new TableSwitchInsnNode(caseStartIdx, caseStartIdx + caseInsnLists.length - 1, defaultLabelNode, caseLabelNodes));

    for (int i = 0; i < caseInsnLists.length; i++) {
        LabelNode caseLabelNode = caseLabelNodes[i];
        InsnList caseInsnList = caseInsnLists[i];
        if (caseInsnList != null) {
            ret.add(caseLabelNode);
            ret.add(caseInsnList);
        }
    }

    if (defaultInsnList != null) {
        ret.add(defaultLabelNode);
        ret.add(defaultInsnList);
    }
    
    return ret;
}
 
Example #13
Source File: Virtualizer.java    From radon with GNU General Public License v3.0 5 votes vote down vote up
private static boolean canProtect(InsnList insnList) {
    return Stream.of(insnList.toArray()).noneMatch(insn -> insn.getOpcode() == INVOKEDYNAMIC
            || (insn instanceof LdcInsnNode && ((LdcInsnNode) insn).cst instanceof Handle)
            || insn instanceof MultiANewArrayInsnNode
            || insn instanceof LookupSwitchInsnNode
            || insn instanceof TableSwitchInsnNode);
}
 
Example #14
Source File: SwitchInstructionFilter.java    From maple-ir with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean accept(AbstractInsnNode t) {
	if (!(t instanceof LookupSwitchInsnNode || t instanceof TableSwitchInsnNode))
		return false;
	if (!opcodeFilter.accept(t))
		return false;
	for(Filter<Object> filter : filters) {
		if (!filter.accept(t))
			return false;
	}
	return true;
}
 
Example #15
Source File: TableSwitchInsnNodeSerializer.java    From maple-ir with GNU General Public License v3.0 5 votes vote down vote up
@Override
public JsonElement serialize(TableSwitchInsnNode src, Type typeOfSrc, JsonSerializationContext context) {
	JsonObject object = new JsonObject();
    object.add("min", context.serialize(src.min));
    object.add("max", context.serialize(src.max));
    object.add("dflt", context.serialize(src.dflt));
    object.add("labels", context.serialize(src.labels));
    return object;
}
 
Example #16
Source File: TableSwitchInsnNodeSerializer.java    From maple-ir with GNU General Public License v3.0 5 votes vote down vote up
@Override
  public TableSwitchInsnNode deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = (JsonObject) json;
      int min = jsonObject.get("min").getAsInt();
      int max = jsonObject.get("max").getAsInt();
      LabelNode dflt = context.deserialize(jsonObject.get("dflt"), LabelNode.class);
      List<LabelNode> labelList = context.deserialize(jsonObject.get("labels"), List.class);
      LabelNode[] labels = new LabelNode[labelList.size()];
      for(int i=0; i < labels.length; i++){
      	labels[i] = labelList.get(i);
      }
      return new TableSwitchInsnNode(min, max, dflt, labels);
  }
 
Example #17
Source File: InstrUtils.java    From JByteMod-Beta with GNU General Public License v2.0 4 votes vote down vote up
public static String toEasyString(AbstractInsnNode ain) {
	String opc = OpUtils.getOpcodeText(ain.getOpcode()).toLowerCase() + " ";
	switch (ain.getType()) {
	case AbstractInsnNode.LABEL:
		opc = "label " + OpUtils.getLabelIndex((LabelNode) ain);
		break;
	case AbstractInsnNode.LINE:
		opc = "line " + ((LineNumberNode) ain).line;
		break;
	case AbstractInsnNode.FIELD_INSN:
		FieldInsnNode fin = (FieldInsnNode) ain;
		opc += getDisplayType(fin.desc, false) + " " + getDisplayClassEasy(fin.owner) + "." + fin.name;
		break;
	case AbstractInsnNode.METHOD_INSN:
		MethodInsnNode min = (MethodInsnNode) ain;
		opc += getDisplayType(min.desc.split("\\)")[1], false) + " " + getDisplayClassEasy(min.owner) + "." + min.name
				+ "(" + getDisplayArgsEasy(min.desc) + ")";
		break;
	case AbstractInsnNode.VAR_INSN:
		VarInsnNode vin = (VarInsnNode) ain;
		opc += vin.var;
		break;
	case AbstractInsnNode.MULTIANEWARRAY_INSN:
		MultiANewArrayInsnNode mnin = (MultiANewArrayInsnNode) ain;
		opc += mnin.dims + " " + getDisplayType(mnin.desc, false);
		break;
	case AbstractInsnNode.TYPE_INSN:
		TypeInsnNode tin = (TypeInsnNode) ain;
		String esc = tin.desc;
		if (esc.endsWith(";") && esc.startsWith("L")) {
			opc += esc;
		} else {
			opc += getDisplayClassEasy(esc);
		}
		break;
	case AbstractInsnNode.JUMP_INSN:
		JumpInsnNode jin = (JumpInsnNode) ain;
		opc += OpUtils.getLabelIndex(jin.label);
		break;
	case AbstractInsnNode.LDC_INSN:
		LdcInsnNode ldc = (LdcInsnNode) ain;
		opc += ldc.cst.getClass().getSimpleName() + " ";
		if (ldc.cst instanceof String)
			opc += "\"" + ldc.cst.toString() + "\"";
		else {
			opc += ldc.cst.toString();
		}
		break;
	case AbstractInsnNode.INT_INSN:
		opc += OpUtils.getIntValue(ain);
		break;
	case AbstractInsnNode.IINC_INSN:
		IincInsnNode iinc = (IincInsnNode) ain;
		opc += iinc.var + " " + iinc.incr;
		break;
	case AbstractInsnNode.FRAME:
		FrameNode fn = (FrameNode) ain;
		opc = OpUtils.getOpcodeText(fn.type).toLowerCase() + " " + fn.local.size() + " " + fn.stack.size();
		break;
	case AbstractInsnNode.TABLESWITCH_INSN:
		TableSwitchInsnNode tsin = (TableSwitchInsnNode) ain;
		if (tsin.dflt != null) {
			opc += "L" + OpUtils.getLabelIndex(tsin.dflt);
		}
		if (tsin.labels.size() < 20) {
			for (LabelNode l : tsin.labels) {
				opc += " " + "L" + OpUtils.getLabelIndex(l);
			}
		} else {
			opc += " " + tsin.labels.size() + " cases";
		}
		break;
	case AbstractInsnNode.INVOKE_DYNAMIC_INSN:
		InvokeDynamicInsnNode idin = (InvokeDynamicInsnNode) ain;
		opc += idin.name + " " + idin.desc;
		break;
	}
	return opc;
}
 
Example #18
Source File: Block.java    From JByteMod-Beta with GNU General Public License v2.0 4 votes vote down vote up
public boolean endsWithSwitch() {
  return endNode instanceof TableSwitchInsnNode || endNode instanceof LookupSwitchInsnNode;
}
 
Example #19
Source File: InstrUtils.java    From JByteMod-Beta with GNU General Public License v2.0 4 votes vote down vote up
public static String toString(AbstractInsnNode ain) {
	String opc = TextUtils.toBold(OpUtils.getOpcodeText(ain.getOpcode()).toLowerCase()) + " ";
	switch (ain.getType()) {
	case AbstractInsnNode.LABEL:
		opc = TextUtils.toLight("label " + OpUtils.getLabelIndex((LabelNode) ain));
		break;
	case AbstractInsnNode.LINE:
		opc = TextUtils.toLight("line " + ((LineNumberNode) ain).line);
		break;
	case AbstractInsnNode.FIELD_INSN:
		FieldInsnNode fin = (FieldInsnNode) ain;
		opc += getDisplayType(TextUtils.escape(fin.desc), true) + " " + getDisplayClassRed(TextUtils.escape(fin.owner))
				+ "." + fin.name;
		break;
	case AbstractInsnNode.METHOD_INSN:
		MethodInsnNode min = (MethodInsnNode) ain;
		if (min.desc.contains(")")) {
			opc += getDisplayType(min.desc.split("\\)")[1], true);
		} else {
			opc += min.desc;
		}
		opc += " " + getDisplayClassRed(TextUtils.escape(min.owner)) + "." + TextUtils.escape(min.name) + "("
				+ getDisplayArgs(TextUtils.escape(min.desc)) + ")";
		break;
	case AbstractInsnNode.VAR_INSN:
		VarInsnNode vin = (VarInsnNode) ain;
		opc += vin.var;
		break;
	case AbstractInsnNode.TYPE_INSN:
		TypeInsnNode tin = (TypeInsnNode) ain;
		String esc = TextUtils.escape(tin.desc);
		if (esc.endsWith(";") && esc.startsWith("L")) {
			opc += TextUtils.addTag(esc, "font color=" + primColor.getString());
		} else {
			opc += getDisplayClass(esc);
		}
		break;
	case AbstractInsnNode.MULTIANEWARRAY_INSN:
		MultiANewArrayInsnNode mnin = (MultiANewArrayInsnNode) ain;
		opc += mnin.dims + " " + getDisplayType(TextUtils.escape(mnin.desc), true);
		break;
	case AbstractInsnNode.JUMP_INSN:
		JumpInsnNode jin = (JumpInsnNode) ain;
		opc += OpUtils.getLabelIndex(jin.label);
		break;
	case AbstractInsnNode.LDC_INSN:
		LdcInsnNode ldc = (LdcInsnNode) ain;
		opc += TextUtils.addTag(ldc.cst.getClass().getSimpleName(), "font color=" + primColor.getString()) + " ";
		if (ldc.cst instanceof String)
			opc += TextUtils.addTag("\"" + TextUtils.escape(ldc.cst.toString()) + "\"", "font color=#559955");
		else {
			opc += ldc.cst.toString();
		}
		break;
	case AbstractInsnNode.INT_INSN:
		opc += OpUtils.getIntValue(ain);
		break;
	case AbstractInsnNode.IINC_INSN:
		IincInsnNode iinc = (IincInsnNode) ain;
		opc += iinc.var + " " + iinc.incr;
		break;
	case AbstractInsnNode.FRAME:
		FrameNode fn = (FrameNode) ain;
		opc = TextUtils
				.toLight(OpUtils.getFrameType(fn.type).toLowerCase() + " " + fn.local.size() + " " + fn.stack.size());
		break;
	case AbstractInsnNode.TABLESWITCH_INSN:
		TableSwitchInsnNode tsin = (TableSwitchInsnNode) ain;
		if (tsin.dflt != null) {
			opc += TextUtils.addTag("L" + OpUtils.getLabelIndex(tsin.dflt), "font color=" + secColor.getString());
		}
		if (tsin.labels.size() < 20) {
			for (LabelNode l : tsin.labels) {
				opc += " " + TextUtils.addTag("L" + OpUtils.getLabelIndex(l), "font color=" + primColor.getString());
			}
		} else {
			opc += " " + TextUtils.addTag(tsin.labels.size() + " cases", "font color=" + primColor.getString());
		}
		break;
	case AbstractInsnNode.INVOKE_DYNAMIC_INSN:
		InvokeDynamicInsnNode idin = (InvokeDynamicInsnNode) ain;
		Object[] arr = idin.bsmArgs;
		if (arr.length > 1) {
			Object o = arr[1];
			if (o instanceof Handle) {
				Handle h = (Handle) o;
				opc += getDisplayType(h.getDesc().split("\\)")[1], true) + " "
						+ getDisplayClassRed(TextUtils.escape(h.getOwner())) + "." + TextUtils.escape(h.getName()) + "("
						+ getDisplayArgs(TextUtils.escape(h.getDesc())) + ")";

			}
		} else {
			opc += TextUtils.addTag(TextUtils.escape(idin.name), "font color=" + primColor.getString()) + " "
					+ TextUtils.escape(idin.desc);
		}
		break;
	}
	return opc;
}
 
Example #20
Source File: InsnListPrinter.java    From NOVA-Core with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void _visitInsn(AbstractInsnNode insn) {
	switch (insn.getType()) {
		case 0:
			visitInsn(insn.getOpcode());
			break;
		case 1:
			IntInsnNode iinsn = (IntInsnNode) insn;
			visitIntInsn(iinsn.getOpcode(), iinsn.operand);
			break;
		case 2:
			VarInsnNode vinsn = (VarInsnNode) insn;
			visitVarInsn(vinsn.getOpcode(), vinsn.var);
			break;
		case 3:
			TypeInsnNode tinsn = (TypeInsnNode) insn;
			visitTypeInsn(tinsn.getOpcode(), tinsn.desc);
			break;
		case 4:
			FieldInsnNode finsn = (FieldInsnNode) insn;
			visitFieldInsn(finsn.getOpcode(), finsn.owner, finsn.name, finsn.desc);
			break;
		case 5:
			MethodInsnNode minsn = (MethodInsnNode) insn;
			visitMethodInsn(minsn.getOpcode(), minsn.owner, minsn.name, minsn.desc);
			break;
		case 6:
			InvokeDynamicInsnNode idinsn = (InvokeDynamicInsnNode) insn;
			visitInvokeDynamicInsn(idinsn.name, idinsn.desc, idinsn.bsm, idinsn.bsmArgs);
			break;
		case 7:
			JumpInsnNode jinsn = (JumpInsnNode) insn;
			visitJumpInsn(jinsn.getOpcode(), jinsn.label.getLabel());
			break;
		case 8:
			LabelNode linsn = (LabelNode) insn;
			visitLabel(linsn.getLabel());
			break;
		case 9:
			LdcInsnNode ldcinsn = (LdcInsnNode) insn;
			visitLdcInsn(ldcinsn.cst);
			break;
		case 10:
			IincInsnNode iiinsn = (IincInsnNode) insn;
			visitIincInsn(iiinsn.var, iiinsn.incr);
			break;
		case 11:
			TableSwitchInsnNode tsinsn = (TableSwitchInsnNode) insn;
			Label[] tslables = new Label[tsinsn.labels.size()];
			for (int i = 0; i < tslables.length; i++) {
				tslables[i] = tsinsn.labels.get(i).getLabel();
			}
			visitTableSwitchInsn(tsinsn.min, tsinsn.max, tsinsn.dflt.getLabel(), tslables);
			break;
		case 12:
			LookupSwitchInsnNode lsinsn = (LookupSwitchInsnNode) insn;
			Label[] lslables = new Label[lsinsn.labels.size()];
			for (int i = 0; i < lslables.length; i++) {
				lslables[i] = lsinsn.labels.get(i).getLabel();
			}
			int[] lskeys = new int[lsinsn.keys.size()];
			for (int i = 0; i < lskeys.length; i++) {
				lskeys[i] = lsinsn.keys.get(i);
			}
			visitLookupSwitchInsn(lsinsn.dflt.getLabel(), lskeys, lslables);
			break;
		case 13:
			MultiANewArrayInsnNode ainsn = (MultiANewArrayInsnNode) insn;
			visitMultiANewArrayInsn(ainsn.desc, ainsn.dims);
			break;
		case 14:
			FrameNode fnode = (FrameNode) insn;
			switch (fnode.type) {
				case -1:
				case 0:
					visitFrame(fnode.type, fnode.local.size(), fnode.local.toArray(), fnode.stack.size(), fnode.stack.toArray());
					break;
				case 1:
					visitFrame(fnode.type, fnode.local.size(), fnode.local.toArray(), 0, null);
					break;
				case 2:
					visitFrame(fnode.type, fnode.local.size(), null, 0, null);
					break;
				case 3:
					visitFrame(fnode.type, 0, null, 0, null);
					break;
				case 4:
					visitFrame(fnode.type, 0, null, 1, fnode.stack.toArray());
			}
			break;
		case 15:
			LineNumberNode lnode = (LineNumberNode) insn;
			visitLineNumber(lnode.line, lnode.start.getLabel());
			break;
	}
}
 
Example #21
Source File: InsnListPrinter.java    From NOVA-Core with GNU Lesser General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
private void _visitInsn(AbstractInsnNode insn) {
	switch (insn.getType()) {
		case 0:
			visitInsn(insn.getOpcode());
			break;
		case 1:
			IntInsnNode iinsn = (IntInsnNode) insn;
			visitIntInsn(iinsn.getOpcode(), iinsn.operand);
			break;
		case 2:
			VarInsnNode vinsn = (VarInsnNode) insn;
			visitVarInsn(vinsn.getOpcode(), vinsn.var);
			break;
		case 3:
			TypeInsnNode tinsn = (TypeInsnNode) insn;
			visitTypeInsn(tinsn.getOpcode(), tinsn.desc);
			break;
		case 4:
			FieldInsnNode finsn = (FieldInsnNode) insn;
			visitFieldInsn(finsn.getOpcode(), finsn.owner, finsn.name, finsn.desc);
			break;
		case 5:
			MethodInsnNode minsn = (MethodInsnNode) insn;
			visitMethodInsn(minsn.getOpcode(), minsn.owner, minsn.name, minsn.desc);
			break;
		case 6:
			InvokeDynamicInsnNode idinsn = (InvokeDynamicInsnNode) insn;
			visitInvokeDynamicInsn(idinsn.name, idinsn.desc, idinsn.bsm, idinsn.bsmArgs);
			break;
		case 7:
			JumpInsnNode jinsn = (JumpInsnNode) insn;
			visitJumpInsn(jinsn.getOpcode(), jinsn.label.getLabel());
			break;
		case 8:
			LabelNode linsn = (LabelNode) insn;
			visitLabel(linsn.getLabel());
			break;
		case 9:
			LdcInsnNode ldcinsn = (LdcInsnNode) insn;
			visitLdcInsn(ldcinsn.cst);
			break;
		case 10:
			IincInsnNode iiinsn = (IincInsnNode) insn;
			visitIincInsn(iiinsn.var, iiinsn.incr);
			break;
		case 11:
			TableSwitchInsnNode tsinsn = (TableSwitchInsnNode) insn;
			Label[] tslables = new Label[tsinsn.labels.size()];
			for (int i = 0; i < tslables.length; i++) {
				tslables[i] = tsinsn.labels.get(i).getLabel();
			}
			visitTableSwitchInsn(tsinsn.min, tsinsn.max, tsinsn.dflt.getLabel(), tslables);
			break;
		case 12:
			LookupSwitchInsnNode lsinsn = (LookupSwitchInsnNode) insn;
			Label[] lslables = new Label[lsinsn.labels.size()];
			for (int i = 0; i < lslables.length; i++) {
				lslables[i] = lsinsn.labels.get(i).getLabel();
			}
			int[] lskeys = new int[lsinsn.keys.size()];
			for (int i = 0; i < lskeys.length; i++) {
				lskeys[i] = lsinsn.keys.get(i);
			}
			visitLookupSwitchInsn(lsinsn.dflt.getLabel(), lskeys, lslables);
			break;
		case 13:
			MultiANewArrayInsnNode ainsn = (MultiANewArrayInsnNode) insn;
			visitMultiANewArrayInsn(ainsn.desc, ainsn.dims);
			break;
		case 14:
			FrameNode fnode = (FrameNode) insn;
			switch (fnode.type) {
				case -1:
				case 0:
					visitFrame(fnode.type, fnode.local.size(), fnode.local.toArray(), fnode.stack.size(), fnode.stack.toArray());
					break;
				case 1:
					visitFrame(fnode.type, fnode.local.size(), fnode.local.toArray(), 0, null);
					break;
				case 2:
					visitFrame(fnode.type, fnode.local.size(), null, 0, null);
					break;
				case 3:
					visitFrame(fnode.type, 0, null, 0, null);
					break;
				case 4:
					visitFrame(fnode.type, 0, null, 1, fnode.stack.toArray());
			}
			break;
		case 15:
			LineNumberNode lnode = (LineNumberNode) insn;
			visitLineNumber(lnode.line, lnode.start.getLabel());
			break;
	}
}
 
Example #22
Source File: InsnListPrinter.java    From NOVA-Core with GNU Lesser General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
private void _visitInsn(AbstractInsnNode insn) {
	switch (insn.getType()) {
		case 0:
			visitInsn(insn.getOpcode());
			break;
		case 1:
			IntInsnNode iinsn = (IntInsnNode) insn;
			visitIntInsn(iinsn.getOpcode(), iinsn.operand);
			break;
		case 2:
			VarInsnNode vinsn = (VarInsnNode) insn;
			visitVarInsn(vinsn.getOpcode(), vinsn.var);
			break;
		case 3:
			TypeInsnNode tinsn = (TypeInsnNode) insn;
			visitTypeInsn(tinsn.getOpcode(), tinsn.desc);
			break;
		case 4:
			FieldInsnNode finsn = (FieldInsnNode) insn;
			visitFieldInsn(finsn.getOpcode(), finsn.owner, finsn.name, finsn.desc);
			break;
		case 5:
			MethodInsnNode minsn = (MethodInsnNode) insn;
			visitMethodInsn(minsn.getOpcode(), minsn.owner, minsn.name, minsn.desc);
			break;
		case 6:
			InvokeDynamicInsnNode idinsn = (InvokeDynamicInsnNode) insn;
			visitInvokeDynamicInsn(idinsn.name, idinsn.desc, idinsn.bsm, idinsn.bsmArgs);
			break;
		case 7:
			JumpInsnNode jinsn = (JumpInsnNode) insn;
			visitJumpInsn(jinsn.getOpcode(), jinsn.label.getLabel());
			break;
		case 8:
			LabelNode linsn = (LabelNode) insn;
			visitLabel(linsn.getLabel());
			break;
		case 9:
			LdcInsnNode ldcinsn = (LdcInsnNode) insn;
			visitLdcInsn(ldcinsn.cst);
			break;
		case 10:
			IincInsnNode iiinsn = (IincInsnNode) insn;
			visitIincInsn(iiinsn.var, iiinsn.incr);
			break;
		case 11:
			TableSwitchInsnNode tsinsn = (TableSwitchInsnNode) insn;
			Label[] tslables = new Label[tsinsn.labels.size()];
			for (int i = 0; i < tslables.length; i++) {
				tslables[i] = tsinsn.labels.get(i).getLabel();
			}
			visitTableSwitchInsn(tsinsn.min, tsinsn.max, tsinsn.dflt.getLabel(), tslables);
			break;
		case 12:
			LookupSwitchInsnNode lsinsn = (LookupSwitchInsnNode) insn;
			Label[] lslables = new Label[lsinsn.labels.size()];
			for (int i = 0; i < lslables.length; i++) {
				lslables[i] = lsinsn.labels.get(i).getLabel();
			}
			int[] lskeys = new int[lsinsn.keys.size()];
			for (int i = 0; i < lskeys.length; i++) {
				lskeys[i] = lsinsn.keys.get(i);
			}
			visitLookupSwitchInsn(lsinsn.dflt.getLabel(), lskeys, lslables);
			break;
		case 13:
			MultiANewArrayInsnNode ainsn = (MultiANewArrayInsnNode) insn;
			visitMultiANewArrayInsn(ainsn.desc, ainsn.dims);
			break;
		case 14:
			FrameNode fnode = (FrameNode) insn;
			switch (fnode.type) {
				case -1:
				case 0:
					visitFrame(fnode.type, fnode.local.size(), fnode.local.toArray(), fnode.stack.size(), fnode.stack.toArray());
					break;
				case 1:
					visitFrame(fnode.type, fnode.local.size(), fnode.local.toArray(), 0, null);
					break;
				case 2:
					visitFrame(fnode.type, fnode.local.size(), null, 0, null);
					break;
				case 3:
					visitFrame(fnode.type, 0, null, 0, null);
					break;
				case 4:
					visitFrame(fnode.type, 0, null, 1, fnode.stack.toArray());
			}
			break;
		case 15:
			LineNumberNode lnode = (LineNumberNode) insn;
			visitLineNumber(lnode.line, lnode.start.getLabel());
			break;
	}
}
 
Example #23
Source File: BogusSwitchJumpInserter.java    From radon with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void transform() {
    AtomicInteger counter = new AtomicInteger();

    getClassWrappers().stream().filter(classWrapper -> !excluded(classWrapper)).forEach(classWrapper -> {
        AtomicBoolean shouldAdd = new AtomicBoolean();
        FieldNode predicate = new FieldNode(PRED_ACCESS, uniqueRandomString(), "I", null, null);

        classWrapper.getMethods().stream().filter(mw -> !excluded(mw) && mw.hasInstructions()).forEach(mw -> {
            InsnList insns = mw.getInstructions();

            int leeway = mw.getLeewaySize();
            int varIndex = mw.getMaxLocals();
            mw.getMethodNode().maxLocals++; // Prevents breaking of other transformers which rely on this field.

            StackHeightZeroFinder shzf = new StackHeightZeroFinder(mw.getMethodNode(), insns.getLast());
            try {
                shzf.execute(false);
            } catch (StackEmulationException e) {
                e.printStackTrace();
                throw new RadonException(String.format("Error happened while trying to emulate the stack of %s.%s%s",
                        classWrapper.getName(), mw.getName(), mw.getDescription()));
            }

            Set<AbstractInsnNode> check = shzf.getEmptyAt();
            ArrayList<AbstractInsnNode> emptyAt = new ArrayList<>(check);

            if (emptyAt.size() <= 5 || leeway <= 30000)
                return;

            int nTargets = emptyAt.size() / 2;

            ArrayList<LabelNode> targets = new ArrayList<>();
            for (int i = 0; i < nTargets; i++)
                targets.add(new LabelNode());

            LabelNode back = new LabelNode();
            LabelNode dflt = new LabelNode();
            TableSwitchInsnNode tsin = new TableSwitchInsnNode(0, targets.size() - 1, dflt, targets.toArray(new LabelNode[0]));

            InsnList block = new InsnList();
            block.add(new VarInsnNode(ILOAD, varIndex));
            block.add(new JumpInsnNode(IFEQ, dflt));
            block.add(back);
            block.add(new VarInsnNode(ILOAD, varIndex));
            block.add(tsin);
            block.add(dflt);

            AbstractInsnNode switchTarget = emptyAt.get(RandomUtils.getRandomInt(emptyAt.size()));

            insns.insertBefore(switchTarget, block);

            targets.forEach(target -> {
                AbstractInsnNode here = insns.getLast();

                InsnList landing = new InsnList();
                landing.add(target);
                landing.add(ASMUtils.getNumberInsn(RandomUtils.getRandomInt(nTargets)));
                landing.add(new VarInsnNode(ISTORE, varIndex));
                landing.add(new JumpInsnNode(GOTO, targets.get(RandomUtils.getRandomInt(targets.size()))));

                insns.insert(here, landing);
            });

            insns.insert(new VarInsnNode(ISTORE, varIndex));
            insns.insert(new FieldInsnNode(GETSTATIC, classWrapper.getName(), predicate.name, "I"));

            counter.addAndGet(targets.size());
            shouldAdd.set(true);
        });

        if (shouldAdd.get())
            classWrapper.addField(predicate);
    });

    Main.info("Inserted " + counter.get() + " bogus switch jumps");
}
 
Example #24
Source File: MethodInvokationWeaver.java    From Concurnas with MIT License 4 votes vote down vote up
/**
     * After the pausable method call is over, we have four possibilities. The
     * called method yielded, or it returned normally. Orthogonally, we have
     * saved state or not. fiber.up() returns the combined status
     * 
?     * <pre>
     *                     
     * switch (fiber.up()) {
     *    default:
     *    0: goto RESUME; // Not yielding , no State --  resume normal operations
     *    1: goto RESTORE; // Not yielding, has State -- restore state before resuming
     *    2: goto SAVE; // Yielding, no state -- save state before unwinding stack
     *    3: goto UNWIND // Yielding, has state -- nothing to do but unwind.
     * }
     * SAVE:
     *     ...
     *     xRETURN
     * UNWIND:
     *     ...
     *     xRETURN
     * RESTORE:
     *     ...
     *     // fall through to RESUME
     * RESUME:
     *     ... original code
     * </pre>
     * 
     * @param mv
     * 
     */
    void genPostCall(MethodVisitor mv) {
        loadVar(mv, TOBJECT, methodWeaver.getFiberVar());
        //mv.visitLdcInsn(this.bb.flow.name);
        //mv.visitMethodInsn(INVOKEVIRTUAL, FIBER_CLASS, "up", "(Ljava/lang/String;)I", false);
        mv.visitMethodInsn(INVOKEVIRTUAL, FIBER_CLASS, "up", "()I", false);
        LabelNode restoreLabel = new LabelNode();
        LabelNode saveLabel = new LabelNode();
        LabelNode unwindLabel = new LabelNode();
        LabelNode[] labels = new LabelNode[] { resumeLabel, restoreLabel, saveLabel,
                unwindLabel };
        new TableSwitchInsnNode(0, 3, resumeLabel, labels).accept(mv);
        genSave(mv, saveLabel);
        genUnwind(mv, unwindLabel);
        genRestore(mv, restoreLabel);
        resumeLabel.accept(mv);
    }
 
Example #25
Source File: Block.java    From Cafebabe with GNU General Public License v3.0 4 votes vote down vote up
public boolean endsWithSwitch() {
  return endNode instanceof TableSwitchInsnNode || endNode instanceof LookupSwitchInsnNode;
}