org.objectweb.asm.tree.VarInsnNode Java Examples

The following examples show how to use org.objectweb.asm.tree.VarInsnNode. 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: GameDataTransformer.java    From NOVA-Core with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void transformAddPrefix(ClassNode cnode) {
	ObfMapping mapping = new ObfMapping("net/minecraftforge/fml/common/registry/GameData", "addPrefix", "(Ljava/lang/String;)Ljava/lang/String;");
	MethodNode method = ASMHelper.findMethod(mapping, cnode);

	if (method == null) {
		throw new IllegalStateException("[NOVA] Lookup " + mapping + " failed!");
	}

	Game.logger().info("Transforming method {}", method.name);

	@SuppressWarnings("unchecked")
	JumpInsnNode prev = (JumpInsnNode) method.instructions.get(49);

	InsnList list = new InsnList();
	list.add(new VarInsnNode(ALOAD, 4));
	list.add(new MethodInsnNode(INVOKESTATIC, "nova/core/wrapper/mc/forge/v18/asm/StaticForwarder", "isNovaPrefix", "(Ljava/lang/String;)Z", false));
	list.add(new JumpInsnNode(IFNE, prev.label));

	method.instructions.insert(prev, list);

	Game.logger().info("Injected instruction to method: {}", method.name);
}
 
Example #2
Source File: ExceptionObfuscationTX.java    From zelixkiller with GNU General Public License v3.0 6 votes vote down vote up
private void check(ClassNode cn, MethodNode mn, TryCatchBlockNode tcb, LabelNode handler) {
	AbstractInsnNode ain = handler;
	while (ain.getOpcode() == -1) { // skip labels and frames
		ain = ain.getNext();
	}
	if (ain.getOpcode() == ATHROW) {
		removeTCB(mn, tcb);
	} else if (ain instanceof MethodInsnNode && ain.getNext().getOpcode() == ATHROW) {
		MethodInsnNode min = (MethodInsnNode) ain;
		if (min.owner.equals(cn.name)) {
			MethodNode getter = ClassUtils.getMethod(cn, min.name, min.desc);
			AbstractInsnNode getterFirst = getter.instructions.getFirst();
			while (getterFirst.getOpcode() == -1) {
				getterFirst = ain.getNext();
			}
			if (getterFirst instanceof VarInsnNode && getterFirst.getNext().getOpcode() == ARETURN) {
				if (((VarInsnNode) getterFirst).var == 0) {
					removeTCB(mn, tcb);
				}
			}
		}
	}
}
 
Example #3
Source File: InstrumentUtil.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * <p>
 * This method provides instruction to log counter information
 * </p>
 * 
 * @param className
 *            Class which has called the logger
 * @param methodName
 *            Method in which the logger has been called
 * @param logMethod
 *            log method
 * @param logMsgPrefix
 *            log message
 * @param field
 *            field which store the counter
 * @return Instructions
 */
public static InsnList addCounterLoggingOldApi(String className,
		String methodName, String logMethod, String logMsgPrefix,
		String field) {
	String method = "getMapReduceExecutionInfoOldApi";

	InsnList il = new InsnList();
	il.add(new LabelNode());
	il.add(new LdcInsnNode(className));
	il.add(new LdcInsnNode(methodName));
	il.add(new LdcInsnNode(logMethod));
	il.add(new LdcInsnNode(logMsgPrefix));
	il.add(new VarInsnNode(Opcodes.ALOAD, 0));
	il.add(new FieldInsnNode(Opcodes.GETFIELD, ConfigurationUtil
			.convertQualifiedClassNameToInternalName(className), field,
			Type.INT_TYPE.getDescriptor()));
	il.add(new MethodInsnNode(Opcodes.INVOKESTATIC, CLASSNAME_LOGUTIL,
			method, Type.getMethodDescriptor(Type.VOID_TYPE, TYPE_STRING,
					TYPE_STRING, TYPE_STRING, TYPE_STRING, Type.INT_TYPE)));
	return il;
}
 
Example #4
Source File: BlockPatch.java    From ForgeHax with MIT License 6 votes vote down vote up
@Inject(description = "Changes in layer code so that we can change it")
public void inject(MethodNode main) {
  AbstractInsnNode node =
    ASMHelper.findPattern(main.instructions.getFirst(), new int[]{INVOKEVIRTUAL}, "x");
  
  Objects.requireNonNull(node, "Find pattern failed for node");
  
  InsnList insnList = new InsnList();
  
  // starting after INVOKEVIRTUAL on Block.getBlockLayer()
  
  insnList.add(new VarInsnNode(ASTORE, 3)); // store the result from getBlockLayer()
  insnList.add(new VarInsnNode(ALOAD, 0)); // push this
  insnList.add(new VarInsnNode(ALOAD, 1)); // push block state
  insnList.add(new VarInsnNode(ALOAD, 3)); // push this.getBlockLayer() result
  insnList.add(
    new VarInsnNode(ALOAD, 2)); // push the block layer of the block we are comparing to
  insnList.add(
    ASMHelper.call(INVOKESTATIC, TypesHook.Methods.ForgeHaxHooks_onRenderBlockInLayer));
  // now our result is on the stack
  
  main.instructions.insert(node, insnList);
}
 
Example #5
Source File: Instrumentator.java    From instrumentation with Apache License 2.0 6 votes vote down vote up
private int addMethodParametersVariable(InsnList il) {
    il.add(TreeInstructions.getPushInstruction(this.methodArguments.length));
    il.add(new TypeInsnNode(Opcodes.ANEWARRAY, "java/lang/Object"));
    int methodParametersIndex = getFistAvailablePosition();
    il.add(new VarInsnNode(Opcodes.ASTORE, methodParametersIndex));
    this.mn.maxLocals++;
    for (int i = 0; i < this.methodArguments.length; i++) {
        il.add(new VarInsnNode(Opcodes.ALOAD, methodParametersIndex));
        il.add(TreeInstructions.getPushInstruction(i));
        il.add(TreeInstructions.getLoadInst(methodArguments[i],
                getArgumentPosition(i)));
        MethodInsnNode mNode = TreeInstructions
                .getWrapperContructionInst(methodArguments[i]);
        if (mNode != null) {
            il.add(mNode);
        }
        il.add(new InsnNode(Opcodes.AASTORE));
    }
    return methodParametersIndex;
}
 
Example #6
Source File: Instrumentator.java    From instrumentation with Apache License 2.0 6 votes vote down vote up
private void addTraceStart() {
    InsnList il = new InsnList();
    int methodParametersIndex = addMethodParametersVariable(il);
    addGetMethodInvocation(il);
    addStoreMethod(il);
    addGetCallback(il);

    il.add(new VarInsnNode(Opcodes.ALOAD, this.methodVarIndex));
    il.add(new VarInsnNode(Opcodes.ALOAD, methodParametersIndex));
    il.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL,
            "org/brutusin/instrumentation/Callback", "onStart",
            "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/String;", false));

    this.executionIdIndex = getFistAvailablePosition();
    il.add(new VarInsnNode(Opcodes.ASTORE, this.executionIdIndex));
    this.mn.maxLocals++;
    this.startNode = new LabelNode();
    this.mn.instructions.insert(startNode);
    this.mn.instructions.insert(il);
}
 
Example #7
Source File: Instrumentator.java    From instrumentation with Apache License 2.0 6 votes vote down vote up
private InsnList getReturnTraceInstructions() {

        InsnList il = new InsnList();

        int retunedVariablePosition = getFistAvailablePosition();
        il.add(TreeInstructions.getStoreInst(this.methodReturnType, retunedVariablePosition));

        this.variableCreated(this.methodReturnType); // Actualizamos el offset
        addGetCallback(il);
        il.add(new VarInsnNode(Opcodes.ALOAD, this.methodVarIndex));
        il.add(TreeInstructions.getLoadInst(this.methodReturnType, retunedVariablePosition));
        MethodInsnNode mNode = TreeInstructions.getWrapperContructionInst(this.methodReturnType);
        if (mNode != null) {
            il.add(mNode);
        }
        il.add(new VarInsnNode(Opcodes.ALOAD, this.executionIdIndex));
        il.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL,
                "org/brutusin/instrumentation/Callback", "onFinish",
                "(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/String;)V", false));

        il.add(TreeInstructions.getLoadInst(this.methodReturnType, retunedVariablePosition));

        return il;

    }
 
Example #8
Source File: TransformerInjectTracker.java    From Diorite with MIT License 6 votes vote down vote up
public boolean isCompatible(VarInsnNode varInsnNode)
{
    VarCode varCode;
    if (AsmUtils.isLoadCode(varInsnNode.getOpcode()))
    {
        if (AsmUtils.isLoadCode(this.getOpcode()))
        {
            return false;
        }
        return ((StoreCode) this).isCompatible(new LoadCode(varInsnNode));
    }
    else if (AsmUtils.isStoreCode(varInsnNode.getOpcode()))
    {
        if (AsmUtils.isStoreCode(this.getOpcode()))
        {
            return false;
        }
        return ((LoadCode) this).isCompatible(new StoreCode(varInsnNode));
    }
    else
    {
        throw new AnalyzeError("Unexpected VarInsnNode Opcode!");
    }
}
 
Example #9
Source File: Watermarker.java    From radon with GNU General Public License v3.0 6 votes vote down vote up
private static InsnList createInstructions(Deque<Character> watermark, int offset) {
    int xorKey = RandomUtils.getRandomInt();
    int watermarkChar = watermark.pop() ^ xorKey;
    int indexXorKey = RandomUtils.getRandomInt();
    int watermarkIndex = watermark.size() ^ indexXorKey;

    InsnList instructions = new InsnList();
    instructions.add(ASMUtils.getNumberInsn(xorKey));
    instructions.add(ASMUtils.getNumberInsn(watermarkChar));
    instructions.add(ASMUtils.getNumberInsn(indexXorKey));
    instructions.add(ASMUtils.getNumberInsn(watermarkIndex));

    // Local variable x where x is the max locals allowed in method can be the top of a long or double so we add 1
    instructions.add(new VarInsnNode(ISTORE, offset + 1));
    instructions.add(new VarInsnNode(ISTORE, offset + 2));
    instructions.add(new VarInsnNode(ISTORE, offset + 3));
    instructions.add(new VarInsnNode(ISTORE, offset + 4));

    return instructions;
}
 
Example #10
Source File: VariableProvider.java    From obfuscator with MIT License 6 votes vote down vote up
public VariableProvider(MethodNode method) {
    this();

    if (!Modifier.isStatic(method.access)) registerExisting(0, Type.getType("Ljava/lang/Object;"));

    for (Type argumentType : Type.getArgumentTypes(method.desc)) {
        registerExisting(argumentType.getSize() + max - 1, argumentType);
    }

    argumentSize = max;

    for (AbstractInsnNode abstractInsnNode : method.instructions.toArray()) {
        if (abstractInsnNode instanceof VarInsnNode) {
            registerExisting(((VarInsnNode) abstractInsnNode).var, Utils.getType((VarInsnNode) abstractInsnNode));
        }
    }
}
 
Example #11
Source File: EntityRendererPatch.java    From ForgeHax with MIT License 6 votes vote down vote up
@Inject(description = "Add hook that allows the method to be canceled")
public void inject(MethodNode main) {
  AbstractInsnNode preNode = main.instructions.getFirst();
  AbstractInsnNode postNode =
    ASMHelper.findPattern(main.instructions.getFirst(), new int[]{RETURN}, "x");
  
  Objects.requireNonNull(preNode, "Find pattern failed for preNode");
  Objects.requireNonNull(postNode, "Find pattern failed for postNode");
  
  LabelNode endJump = new LabelNode();
  
  InsnList insnPre = new InsnList();
  insnPre.add(new VarInsnNode(FLOAD, 1));
  insnPre.add(ASMHelper.call(INVOKESTATIC, TypesHook.Methods.ForgeHaxHooks_onHurtcamEffect));
  insnPre.add(new JumpInsnNode(IFNE, endJump));
  
  main.instructions.insertBefore(preNode, insnPre);
  main.instructions.insertBefore(postNode, endJump);
}
 
Example #12
Source File: Instrumentator.java    From instrumentation with Apache License 2.0 6 votes vote down vote up
private InsnList getThrowTraceInstructions() {
    InsnList il = new InsnList();

    int exceptionVariablePosition = getFistAvailablePosition();
    il.add(new VarInsnNode(Opcodes.ASTORE, exceptionVariablePosition));

    this.methodOffset++; // Actualizamos el offset
    addGetCallback(il);
    il.add(new VarInsnNode(Opcodes.ALOAD, this.methodVarIndex));
    il.add(new VarInsnNode(Opcodes.ALOAD, exceptionVariablePosition));
    il.add(new VarInsnNode(Opcodes.ALOAD, this.executionIdIndex));
    il.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL,
            "org/brutusin/instrumentation/Callback", "onThrowableThrown",
            "(Ljava/lang/Object;Ljava/lang/Throwable;Ljava/lang/String;)V", false));

    il.add(new VarInsnNode(Opcodes.ALOAD, exceptionVariablePosition));

    return il;
}
 
Example #13
Source File: ASMClassNodeAdapter.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
public void addGetterMethod(final String methodName, final ASMFieldNodeAdapter fieldNode) {
    Assert.requireNonNull(methodName, "methodName");
    Assert.requireNonNull(fieldNode, "fieldNode");


    // no argument is ().
    final String desc = "()" + fieldNode.getDesc();
    final MethodNode methodNode = new MethodNode(Opcodes.ACC_PUBLIC, methodName, desc, null, null);
    final InsnList instructions = getInsnList(methodNode);
    // load this.
    instructions.add(new VarInsnNode(Opcodes.ALOAD, 0));
    // get fieldNode.
    instructions.add(new FieldInsnNode(Opcodes.GETFIELD, classNode.name, fieldNode.getName(), fieldNode.getDesc()));
    // return of type.
    final Type type = Type.getType(fieldNode.getDesc());
    instructions.add(new InsnNode(type.getOpcode(Opcodes.IRETURN)));

    addMethodNode0(methodNode);
}
 
Example #14
Source File: IForgeRegistryEntryTransformer.java    From NOVA-Core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void transform(ClassNode cnode) {
	Game.logger().info("Transforming IForgeRegistryEntry class for correct NOVA mod id mapping.");

	ObfMapping mapping = new ObfMapping("net/minecraftforge/fml/common/registry/IForgeRegistryEntry$Impl", "setRegistryName", "(Ljava/lang/String;)Lnet/minecraftforge/fml/common/registry/IForgeRegistryEntry;");
	MethodNode method = ASMHelper.findMethod(mapping, cnode);

	if (method == null) {
		throw new IllegalStateException("[NOVA] Lookup " + mapping + " failed!");
	}

	Game.logger().info("Transforming method {}", method.name);

	InsnList list = new InsnList();
	list.add(new VarInsnNode(ALOAD, 5));
	list.add(new MethodInsnNode(INVOKESTATIC, "nova/core/wrapper/mc/forge/v1_11_2/asm/StaticForwarder", "isNovaPrefix", "(Ljava/lang/String;)Z", false));
	list.add(new JumpInsnNode(IFNE, (LabelNode) method.instructions.get(120)));

	method.instructions.insert(method.instructions.get(101), list);

	Game.logger().info("Injected instruction to method: {}", method.name);
}
 
Example #15
Source File: WorldPatch.java    From ForgeHax with MIT License 6 votes vote down vote up
@Inject(description = "Add hook before everything")
public void inject(MethodNode method) {
  AbstractInsnNode node = method.instructions.getFirst();
  
  Objects.requireNonNull(node, "Failed to find node.");
  
  LabelNode label = new LabelNode();
  
  InsnList list = new InsnList();
  list.add(new VarInsnNode(ALOAD, 1)); // enum
  list.add(new VarInsnNode(ALOAD, 2)); // blockpos
  list.add(ASMHelper.call(INVOKESTATIC, TypesHook.Methods.ForgeHaxHooks_onWorldCheckLightFor));
  list.add(new JumpInsnNode(IFEQ, label));
  list.add(new InsnNode(ICONST_0));
  list.add(new InsnNode(IRETURN));
  list.add(label);
  
  method.instructions.insertBefore(node, list);
}
 
Example #16
Source File: JobAdapter.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Handle submit case.
 *
 * @param jobVariableIndex the job variable index
 * @param type the type
 * @return the insn list
 */
public static InsnList handleSubmitCase(int jobVariableIndex, Type type) {
	InsnList il = new InsnList();
	il.add(new LabelNode());
	il.add(new VarInsnNode(Opcodes.ALOAD, jobVariableIndex));
	il.add(new MethodInsnNode(Opcodes.INVOKESTATIC, CLASSNAME_JOB_UTIL,
			"handleSubmitCase", Type.getMethodDescriptor(Type.VOID_TYPE,
					type)));

	return il;
}
 
Example #17
Source File: PlayerControllerMCPatch.java    From ForgeHax with MIT License 5 votes vote down vote up
@Inject(description = "Add callback at top of method")
public void inject(MethodNode node) {
  InsnList list = new InsnList();
  list.add(new VarInsnNode(ALOAD, 0));
  list.add(new VarInsnNode(ALOAD, 1));
  list.add(new VarInsnNode(ALOAD, 2));
  list.add(ASMHelper.call(INVOKESTATIC, TypesHook.Methods.ForgeHaxHooks_onPlayerAttackEntity));
  
  node.instructions.insert(list);
}
 
Example #18
Source File: OpUtils.java    From JByteMod-Beta with GNU General Public License v2.0 5 votes vote down vote up
public static String toString(AbstractInsnNode ain) {
  String s = getOpcodeText(ain.getOpcode());
  switch (ain.getType()) {
  case AbstractInsnNode.FIELD_INSN:
    FieldInsnNode fin = (FieldInsnNode) ain;
    return s + " " + fin.owner + "#" + fin.name + " " + fin.desc;
  case AbstractInsnNode.METHOD_INSN:
    MethodInsnNode min = (MethodInsnNode) ain;
    return s + " " + min.owner + "#" + min.name + min.desc;
  case AbstractInsnNode.VAR_INSN:
    VarInsnNode vin = (VarInsnNode) ain;
    return s + " " + vin.var;
  case AbstractInsnNode.TYPE_INSN:
    TypeInsnNode tin = (TypeInsnNode) ain;
    return s + " " + tin.desc;
  case AbstractInsnNode.MULTIANEWARRAY_INSN:
    MultiANewArrayInsnNode mnin = (MultiANewArrayInsnNode) ain;
    return s + " " + mnin.dims + " " + mnin.desc;
  case AbstractInsnNode.JUMP_INSN:
    JumpInsnNode jin = (JumpInsnNode) ain;
    return s + " " + getIndex(jin.label);
  case AbstractInsnNode.LDC_INSN:
    LdcInsnNode ldc = (LdcInsnNode) ain;
    return s + " " + ldc.cst.toString();
  case AbstractInsnNode.INT_INSN:
    return s + " " + getIntValue(ain);
  case AbstractInsnNode.IINC_INSN:
    IincInsnNode iinc = (IincInsnNode) ain;
    return s + " " + iinc.var + " +" + iinc.incr;
  case AbstractInsnNode.FRAME:
    FrameNode fn = (FrameNode) ain;
    return s + " " + getOpcodeText(fn.type) + " " + fn.local.size() + " " + fn.stack.size();
  case AbstractInsnNode.LABEL:
    LabelNode ln = (LabelNode) ain;
    return s + " " + getIndex(ln);
  }
  return s;
}
 
Example #19
Source File: ConstructorDelegationDetector.java    From AnoleFix with MIT License 5 votes vote down vote up
Constructor(VarInsnNode loadThis, int lineForLoad, MethodNode args, MethodInsnNode delegation, MethodNode body) {
    this.loadThis = loadThis;
    this.lineForLoad = lineForLoad;
    this.args = args;
    this.delegation = delegation;
    this.body = body;
}
 
Example #20
Source File: TreeInstructions.java    From instrumentation with Apache License 2.0 5 votes vote down vote up
public static VarInsnNode getStoreInst(Type type, int position) {
    int opCode = -1;
    switch (type.getDescriptor().charAt(0)) {
        case 'B':
            opCode = Opcodes.ISTORE;
            break;
        case 'C':
            opCode = Opcodes.ISTORE;
            break;
        case 'D':
            opCode = Opcodes.DSTORE;
            break;
        case 'F':
            opCode = Opcodes.FSTORE;
            break;
        case 'I':
            opCode = Opcodes.ISTORE;
            break;
        case 'J':
            opCode = Opcodes.LSTORE;
            break;
        case 'L':
            opCode = Opcodes.ASTORE;
            break;
        case '[':
            opCode = Opcodes.ASTORE;
            break;
        case 'Z':
            opCode = Opcodes.ISTORE;
            break;
        case 'S':
            opCode = Opcodes.ISTORE;
            break;
        default:
            throw new ClassFormatError("Invalid method signature: "
                    + type.getDescriptor());
    }
    return new VarInsnNode(opCode, position);
}
 
Example #21
Source File: ASMHelper.java    From jaop with Apache License 2.0 5 votes vote down vote up
public static void storeNode(ListIterator<AbstractInsnNode> iterator, Object paramType, int index) {
    //(Ljava/lang/String;IDCBSJZF)V
    if (Opcodes.INTEGER.equals(paramType)) {
        iterator.add(new VarInsnNode(Opcodes.ISTORE, index));
    } else if (Opcodes.LONG.equals(paramType)) {
        iterator.add(new VarInsnNode(Opcodes.LSTORE, index));
    } else if (Opcodes.FLOAT.equals(paramType)) {
        iterator.add(new VarInsnNode(Opcodes.FSTORE, index));
    } else if (Opcodes.DOUBLE.equals(paramType)) {
        iterator.add(new VarInsnNode(Opcodes.DSTORE, index));
    } else {
        iterator.add(new VarInsnNode(Opcodes.ASTORE, index));
    }
}
 
Example #22
Source File: SynchronizationGenerators.java    From coroutines with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Generates instruction to exit a monitor (top item on the stack) and remove it from the {@link LockState} object sitting in the
 * lockstate variable.
 * @param markerType debug marker type
 * @param lockVars variables for lock/synchpoint functionality
 * @return instructions to exit a monitor and remove it from the {@link LockState} object
 * @throws NullPointerException if any argument is {@code null}
 * @throws IllegalArgumentException if lock variables aren't set (the method doesn't contain any monitorenter/monitorexit instructions)
 */
public static InsnList exitMonitorAndDelete(MarkerType markerType, LockVariables lockVars) {
    Validate.notNull(markerType);
    Validate.notNull(lockVars);

    Variable lockStateVar = lockVars.getLockStateVar();
    Validate.isTrue(lockStateVar != null);

    Type clsType = Type.getType(LOCKSTATE_EXIT_METHOD.getDeclaringClass());
    Type methodType = Type.getType(LOCKSTATE_EXIT_METHOD);
    String clsInternalName = clsType.getInternalName();
    String methodDesc = methodType.getDescriptor();
    String methodName = LOCKSTATE_EXIT_METHOD.getName();
    
    // NOTE: This removes the lock AFTER unlocking.
    return merge(
            debugMarker(markerType, "Exiting monitor and unstoring"),
                                                                     // [obj]
            new InsnNode(Opcodes.DUP),                               // [obj, obj]
            new InsnNode(Opcodes.MONITOREXIT),                       // [obj]
            new VarInsnNode(Opcodes.ALOAD, lockStateVar.getIndex()), // [obj, lockState]
            new InsnNode(Opcodes.SWAP),                              // [lockState, obj]
            new MethodInsnNode(Opcodes.INVOKEVIRTUAL,                // []
                    clsInternalName,
                    methodName,
                    methodDesc,
                    false)
    );
}
 
Example #23
Source File: ConfigureMapReduceAdapter.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * <p>
 * This method provides instructions to add Pattern.compile() call for regex
 * values
 * </p>
 *
 * @return Instructions
 */
private InsnList addPatternCompiler() {
	JobConfig jobConfig = (JobConfig)getConfig();
	String keyRegex = jobConfig.getMapReduceKeyRegex(getClassName());
	String valueRegex = jobConfig.getMapReduceValueRegex(getClassName());

	InsnList il = new InsnList();

	LOGGER.debug(MessageFormat.format(InstrumentationMessageLoader
			.getMessage(MessageConstants.LOG_ADD_PATTERN_COMPILE),
			getClassName()));

	// regex values
	String[] regexes = new String[] { keyRegex, valueRegex };

	// class fields
	String[] filedNames = new String[] { KEY_PATTERN, VALUE_PATTERN };

	for (int i = 0; i < regexes.length; i++) {
		il.add(new LabelNode());
		il.add(new VarInsnNode(Opcodes.ALOAD, 0));
		// if regex is not null
		if (regexes[i] != null) {
			il.add(new LdcInsnNode(regexes[i]));
			il.add(new MethodInsnNode(Opcodes.INVOKESTATIC,
					CLASSNAME_PATTERN, "compile", Type.getMethodDescriptor(
							Type.getType(Pattern.class), TYPE_STRING)));
			il.add(new FieldInsnNode(
					Opcodes.PUTFIELD,
					ConfigurationUtil.convertQualifiedClassNameToInternalName(getClassName()),
					filedNames[i], DESCRIPTOR_PATTERN));
		}
	}

	return il;
}
 
Example #24
Source File: AccessorGeneratorFieldGetter.java    From Mixin with MIT License 5 votes vote down vote up
@Override
public MethodNode generate() {
    MethodNode method = this.createMethod(this.targetType.getSize(), this.targetType.getSize());
    if (!this.targetIsStatic) {
        method.instructions.add(new VarInsnNode(Opcodes.ALOAD, 0));
    }
    int opcode = this.targetIsStatic ? Opcodes.GETSTATIC : Opcodes.GETFIELD;
    method.instructions.add(new FieldInsnNode(opcode, this.info.getClassNode().name, this.targetField.name, this.targetField.desc));
    method.instructions.add(new InsnNode(this.targetType.getOpcode(Opcodes.IRETURN)));
    return method;
}
 
Example #25
Source File: InstrumentUtil.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * This method inserts a LogUtil method call in class. This LogUtil method
 * calls PatternMatcher.match(Writable) method. The match method takes only
 * writable object since the regEx given by user is null. So it doesn't
 * requires Pattern object.
 * 
 * @param logBean
 *            LogInfoBean object that contains information related to
 *            logging
 * @param variableIndex
 *            index of writable object to be matched against null
 * @param methodNode
 *            - method which holds context.write either map/reduce
 *  @param logKeyValues
 *  			check if user wants to log unmatched key/values
 * @return InstructionList containing instructions for inserting statement
 *         LogUtil.getRegexInfo("msg" + PatternMatcher.match(writableVal));
 */
public static InsnList addRegExMatcherClassCall(LogInfoBean logBean,
		int variableIndex, MethodNode methodNode, boolean logKeyValues) {
	// If using context use this else not
	String logMethodDesc;
	
	if (logKeyValues) {
		logMethodDesc = Type.getMethodDescriptor(Type.VOID_TYPE,
				TYPE_STRING, TYPE_STRING, TYPE_STRING, TYPE_STRING,
				Type.BOOLEAN_TYPE, TYPE_OBJECT, TYPE_OBJECT);
	} else {
		logMethodDesc = Type.getMethodDescriptor(Type.VOID_TYPE,
				TYPE_STRING, TYPE_STRING, TYPE_STRING, TYPE_STRING,
				Type.BOOLEAN_TYPE);
	}

	InsnList il = createBasicLoggerInsns(logBean);
	il.add(new VarInsnNode(Opcodes.ALOAD, variableIndex));

	// Calling the method PatternMatcher.match
	il.add(new MethodInsnNode(Opcodes.INVOKESTATIC,
			InstrumentConstants.CLASSNAME_PATTERNMATCHER,
			InstrumentConstants.REGEX_METHOD_NAME,
			InstrumentConstants.REGEX_NULL_METHOD_DESC));
	
	if (logKeyValues) {
		il.add(new VarInsnNode(Opcodes.ALOAD, variableIndex));
		methodNode.visitVarInsn(Opcodes.ASTORE, 1);
		il.add(new VarInsnNode(Opcodes.ALOAD, 1));
	}
	
	il.add(new MethodInsnNode(Opcodes.INVOKESTATIC,
			InstrumentConstants.CLASSNAME_LOGUTIL,
			InstrumentConstants.REGEX_LOG_METHOD, logMethodDesc));

	return il;
}
 
Example #26
Source File: PlayerTabOverlayPatch.java    From ForgeHax with MIT License 5 votes vote down vote up
private void replaceConstant(MethodNode method, AbstractInsnNode node, int eventVar) {
  InsnList list = new InsnList();
  list.add(new VarInsnNode(ALOAD, eventVar));
  list.add(
    new MethodInsnNode(
      INVOKEVIRTUAL, Type.getInternalName(RenderTabNameEvent.class), "getColor", "()I"));
  
  method.instructions.insert(node, list); // insert at constant
  method.instructions.remove(node); // remove constant
}
 
Example #27
Source File: InstrumentUtil.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * <p>
 * This method provides instructions to log header row
 * </p>
 * 
 * @param className
 *            Class which has called the logger
 * @return InsnList Instructions
 */
private static InsnList addLogHeader(String className, Type contextType) {
	String method = "addLogHeader";

	InsnList il = new InsnList();
	il.add(new LabelNode());
	il.add(new VarInsnNode(Opcodes.ALOAD, CONTEXT_VARIABLE_IN_CLEANUP_SETUP));
	il.add(new LdcInsnNode(className));
	il.add(new MethodInsnNode(Opcodes.INVOKESTATIC, CLASSNAME_LOGUTIL,
			method, Type.getMethodDescriptor(Type.VOID_TYPE, contextType,
					TYPE_STRING)));
	return il;
}
 
Example #28
Source File: NetHandlerPlayClientPatch.java    From seppuku with GNU General Public License v3.0 5 votes vote down vote up
@MethodPatch(
        mcpName = "handleChunkData",
        notchName = "a",
        mcpDesc = "(Lnet/minecraft/network/play/server/SPacketChunkData;)V",
        notchDesc = "(Lje;)V")
public void handleChunkData(MethodNode methodNode, PatchManager.Environment env) {
    final InsnList insnList = new InsnList();
    insnList.add(new VarInsnNode(ALOAD, 1));
    insnList.add(new MethodInsnNode(INVOKESTATIC, Type.getInternalName(this.getClass()), "handleChunkDataHook", env == PatchManager.Environment.IDE ? "(Lnet/minecraft/network/play/server/SPacketChunkData;)V" : "(Lje;)V", false));
    methodNode.instructions.insertBefore(ASMUtil.bottom(methodNode), insnList);
}
 
Example #29
Source File: NetManagerPatch.java    From ForgeHax with MIT License 5 votes vote down vote up
@Inject(description = "Add pre and post hook that allows the method to be disabled")
public void inject(MethodNode main) {
  AbstractInsnNode preNode =
    ASMHelper.findPattern(
      main.instructions.getFirst(),
      new int[]{ALOAD, ALOAD, GETFIELD, INVOKEINTERFACE},
      "xxxx");
  AbstractInsnNode postNode =
    ASMHelper.findPattern(
      main.instructions.getFirst(),
      new int[]{
        INVOKEINTERFACE, 0x00, 0x00, GOTO,
      },
      "x??x");
  
  Objects.requireNonNull(preNode, "Find pattern failed for preNode");
  Objects.requireNonNull(postNode, "Find pattern failed for postNode");
  
  LabelNode endJump = new LabelNode();
  
  InsnList insnPre = new InsnList();
  insnPre.add(new VarInsnNode(ALOAD, 2));
  insnPre.add(ASMHelper.call(INVOKESTATIC, TypesHook.Methods.ForgeHaxHooks_onPreReceived));
  insnPre.add(new JumpInsnNode(IFNE, endJump));
  
  InsnList insnPost = new InsnList();
  insnPost.add(new VarInsnNode(ALOAD, 2));
  insnPost.add(ASMHelper.call(INVOKESTATIC, TypesHook.Methods.ForgeHaxHooks_onPostReceived));
  insnPost.add(endJump);
  
  main.instructions.insertBefore(preNode, insnPre);
  main.instructions.insert(postNode, insnPost);
}
 
Example #30
Source File: AfterInvoke.java    From Mixin with MIT License 5 votes vote down vote up
@Override
protected boolean addInsn(InsnList insns, Collection<AbstractInsnNode> nodes, AbstractInsnNode insn) {
    MethodInsnNode methodNode = (MethodInsnNode)insn;
    if (Type.getReturnType(methodNode.desc) == Type.VOID_TYPE) {
        return false;
    }
    
    insn = InjectionPoint.nextNode(insns, insn);
    if (insn instanceof VarInsnNode && insn.getOpcode() >= Opcodes.ISTORE) {
        insn = InjectionPoint.nextNode(insns, insn);
    }
    
    nodes.add(insn);
    return true;
}