Java Code Examples for org.objectweb.asm.tree.InsnList#insert()

The following examples show how to use org.objectweb.asm.tree.InsnList#insert() . 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: ClinitCutter.java    From zelixkiller with GNU General Public License v3.0 6 votes vote down vote up
public static InsnList cutClinit(MethodNode mn) {
	InsnList insns = MethodUtils.copy(mn.instructions, null, null);
	ArrayList<LabelNode> handlers = new ArrayList<>();
	for (TryCatchBlockNode tcbn : mn.tryCatchBlocks) {
		handlers.add((LabelNode) insns.get(mn.instructions.indexOf(tcbn.handler)));
	}
	for(LabelNode ln : handlers) {
		findSubroutinesAndDelete(insns, ln);
	}
	AbstractInsnNode endLabel = findEndLabel(insns);
	while (endLabel.getOpcode() == -1) {
		endLabel = endLabel.getNext();
	}
	AbstractInsnNode end = endLabel.getPrevious();
	if (endLabel.getOpcode() != RETURN) {
		findSubroutinesAndDelete(insns, endLabel);
		insns.insert(end, new InsnNode(RETURN));
	}
	return insns;
}
 
Example 2
Source File: GroupClassGenerator.java    From grappa with Apache License 2.0 6 votes vote down vote up
protected static void convertXLoads(final InstructionGroup group)
{
    final String owner = group.getGroupClassType().getInternalName();

    InsnList insnList;

    for (final InstructionGraphNode node : group.getNodes()) {
        if (!node.isXLoad())
            continue;

        final VarInsnNode insn = (VarInsnNode) node.getInstruction();
        final FieldNode field = group.getFields().get(insn.var);
        final FieldInsnNode fieldNode = new FieldInsnNode(GETFIELD, owner,
            field.name, field.desc);

        insnList = group.getInstructions();

        // insert the correct GETFIELD after the xLoad
        insnList.insert(insn, fieldNode);
        // change the load to ALOAD 0
        insnList.set(insn, new VarInsnNode(ALOAD, 0));
    }
}
 
Example 3
Source File: ASMMethodVariables.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
public void initLocalVariables(final InsnList instructions) {
    // find enter & exit instruction.
    final LabelNode variableStartLabelNode = new LabelNode();
    final LabelNode variableEndLabelNode = new LabelNode();
    if(instructions.getFirst() != null) {
        instructions.insertBefore(instructions.getFirst(), variableStartLabelNode);
    } else {
        instructions.insert(variableStartLabelNode);
    }
    instructions.insert(instructions.getLast(), variableEndLabelNode);

    if (!isStatic()) {
        addLocalVariable("this", Type.getObjectType(this.declaringClassInternalName).getDescriptor(), variableStartLabelNode, variableEndLabelNode);
    }

    for (Type type : this.argumentTypes) {
        addLocalVariable(JavaAssistUtils.javaClassNameToVariableName(type.getClassName()), type.getDescriptor(), variableStartLabelNode, variableEndLabelNode);
    }
}
 
Example 4
Source File: StringObfuscationCipherVMT11.java    From zelixkiller with GNU General Public License v3.0 5 votes vote down vote up
private void removeUnwantedCalls(InsnList decryption) {
	// TODO remove unwanted methodinsnnodes
	for (AbstractInsnNode ain : decryption.toArray()) {
		if (ain.getOpcode() == INVOKEDYNAMIC) {
			InvokeDynamicInsnNode idin = (InvokeDynamicInsnNode) ain;
			if (idin.desc.equals("(IJ)Ljava/lang/String;")) {
				decryption.insertBefore(idin, new InsnNode(POP2));
				decryption.insert(idin, new LdcInsnNode("<clinit> decryption invokedynamic string undecrypted"));
				decryption.set(idin, new InsnNode(POP));
			}
		}
	}
}
 
Example 5
Source File: ModifyConstantInjector.java    From Mixin with MIT License 5 votes vote down vote up
private AbstractInsnNode invokeConstantHandler(Type constantType, Target target, Extension extraStack, InsnList before, InsnList after) {
    InjectorData handler = new InjectorData(target, "constant modifier");
    this.validateParams(handler, constantType, constantType);

    if (!this.isStatic) {
        before.insert(new VarInsnNode(Opcodes.ALOAD, 0));
        extraStack.add();
    }
    
    if (handler.captureTargetArgs > 0) {
        this.pushArgs(target.arguments, after, target.getArgIndices(), 0, handler.captureTargetArgs, extraStack);
    }
    
    return this.invokeHandler(after);
}
 
Example 6
Source File: MethodByteCodeUtil.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * API to add local variable in method
 * @param mn
 * @param varName
 * @param desc
 * @param signature
 * @param index
 * @return
 */
public static LocalVariableNode addMethodLocalVariable(MethodNode mn, String varName, String desc, String signature, int index) {
	InsnList list = mn.instructions;

	LabelNode begin = new LabelNode();
	LabelNode end = new LabelNode();
	list.insert(list.getFirst(), begin);
	list.insert(list.getLast(), end);

	LocalVariableNode lv = new LocalVariableNode(varName, desc, signature, begin, end, index);

	return lv;

}
 
Example 7
Source File: GroupClassGenerator.java    From grappa with Apache License 2.0 5 votes vote down vote up
protected static void insertSetContextCalls(final InstructionGroup group,
    int localVarIx)
{
    final InsnList instructions = group.getInstructions();
    final CodeBlock block = CodeBlock.newCodeBlock();

    for (final InstructionGraphNode node: group.getNodes()) {
        if (!node.isCallOnContextAware())
            continue;

        final AbstractInsnNode insn = node.getInstruction();

        if (node.getPredecessors().size() > 1) {
            // store the target of the call in a new local variable
            final AbstractInsnNode loadTarget = node.getPredecessors()
                .get(0).getInstruction();

            block.clear().dup().astore(++localVarIx);
            instructions.insert(loadTarget, block.getInstructionList());

            // immediately before the call get the target from the local var
            // and set the context on it
            instructions.insertBefore(insn, new VarInsnNode(ALOAD,
                localVarIx));
        } else {
            // if we have only one predecessor the call does not take any
            // parameters and we can skip the storing and loading of the
            // invocation target
            instructions.insertBefore(insn, new InsnNode(DUP));
        }

        block.clear()
            .aload(1)
            .invokeinterface(CodegenUtils.p(ContextAware.class),
                "setContext", CodegenUtils.sig(void.class, Context.class));

        instructions.insertBefore(insn, block.getInstructionList());
    }
}
 
Example 8
Source File: BlockSplitter.java    From radon with GNU General Public License v3.0 4 votes vote down vote up
private static void doSplit(MethodNode methodNode, AtomicInteger counter, int callStackSize) {
    InsnList insns = methodNode.instructions;

    if (insns.size() > 10 && callStackSize < LIMIT_SIZE) {
        LabelNode p1 = new LabelNode();
        LabelNode p2 = new LabelNode();

        AbstractInsnNode p2Start = insns.get((insns.size() - 1) / 2);
        AbstractInsnNode p2End = insns.getLast();

        AbstractInsnNode p1Start = insns.getFirst();

        // We can't have trap ranges mutilated by block splitting
        if (methodNode.tryCatchBlocks.stream().anyMatch(tcbn ->
                insns.indexOf(tcbn.end) >= insns.indexOf(p2Start)
                        && insns.indexOf(tcbn.start) <= insns.indexOf(p2Start)))
            return;

        ArrayList<AbstractInsnNode> insnNodes = new ArrayList<>();
        AbstractInsnNode currentInsn = p1Start;

        InsnList p1Block = new InsnList();

        while (currentInsn != p2Start) {
            insnNodes.add(currentInsn);

            currentInsn = currentInsn.getNext();
        }

        insnNodes.forEach(insn -> {
            insns.remove(insn);
            p1Block.add(insn);
        });

        p1Block.insert(p1);
        p1Block.add(new JumpInsnNode(GOTO, p2));

        insns.insert(p2End, p1Block);
        insns.insertBefore(p2Start, new JumpInsnNode(GOTO, p1));
        insns.insertBefore(p2Start, p2);

        counter.incrementAndGet();

        // We might have messed up variable ranges when rearranging the block order.
        if (methodNode.localVariables != null)
            new ArrayList<>(methodNode.localVariables).stream().filter(lvn ->
                    insns.indexOf(lvn.end) < insns.indexOf(lvn.start)
            ).forEach(methodNode.localVariables::remove);

        doSplit(methodNode, counter, callStackSize + 1);
    }
}
 
Example 9
Source File: MethodByteCodeUtil.java    From jumbune with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * This API reads a method and copies the parameters to temporary variables
 * @param node
 * @param variableIndex
 * @param insnList
 * @param locaVariables
 * @return
 */
public static InstructionsBean readMethodAndCopyParamToTemporaryVariables(AbstractInsnNode node, final int variableIndex, InsnList insnList,
		List<LocalVariableNode> locaVariables) {
	int tempVariableIndex=variableIndex;

	InstructionsBean insBean = new InstructionsBean();
	int indexKeyTempVar = InstrumentConstants.PARAMETER_NULL_INDEX;
	int indexValTempVar = InstrumentConstants.PARAMETER_NULL_INDEX;
	boolean isValueParameterNull = false;
	boolean isKeyParameterNull = false;

	AbstractInsnNode paramValueStart = null;
	try {
		paramValueStart = getParamStartNode(node, locaVariables);
	} catch (IllegalArgumentException pne) {
		paramValueStart = node;
		isValueParameterNull = true;
	}
	try {
		isParameterSetToNull(paramValueStart.getPrevious());
	} catch (IllegalArgumentException pnE) {
		isKeyParameterNull = true;
	}

	// Creating instructions to copy key and insert it just before value
	// parameter
	// starts
	if (!isKeyParameterNull) {
		indexKeyTempVar = tempVariableIndex;
		InsnList copyKeyParamList = createTempVariableAndCopyValue(indexKeyTempVar);
		insnList.insertBefore(paramValueStart, copyKeyParamList);
	}

	tempVariableIndex++;

	// Add copy statement of value if it is not null and so its variable
	// index
	if (!isValueParameterNull) {
		indexValTempVar = tempVariableIndex;
		InsnList copyValParamList = createTempVariableAndCopyValue(indexValTempVar);
		insnList.insert(node, copyValParamList);
	}

	// No matter if value is null or not variable index should be
	// incremented else it
	// will spoil the order of objects created. It is required in case if
	// there are multiple
	// context.write in Map/reduce and one takes null value but others have
	// value, so leaving appropriate
	// space for the value parameter
	tempVariableIndex++;

	// Add the variable index key and value for further use
	insBean.addIndexToTemporaryVariablesList(indexKeyTempVar);
	insBean.addIndexToTemporaryVariablesList(indexValTempVar);

	insBean.setVariableIndex(tempVariableIndex);
	return insBean;
}
 
Example 10
Source File: MethodEntryExitAdapter.java    From jumbune with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
* visit end method for intrumentation	
*/
@Override
public void visitEnd() {
	for (Object o : methods) {
		MethodNode mn = (MethodNode) o;

		// filtering the methods
		if (!(validateMapReduceClinitMethod(mn.name,MAP_METHOD , REDUCE_METHOD,CLINIT_METHOD)
				|| checkMethodNameAndArgumentLength(mn)
				|| (mn.access & Opcodes.ACC_SYNTHETIC) == Opcodes.ACC_SYNTHETIC)) {

			InsnList insnList = mn.instructions;
			AbstractInsnNode[] insnArr = insnList.toArray();

			// adding entry logging
			logger.debug(MessageFormat.format(InstrumentationMessageLoader
					.getMessage(MessageConstants.LOG_METHOD_ENTRY),
					getClassName() + "##" + mn.name + "##" + mn.desc));

			String logMsg = InstrumentationMessageLoader
					.getMessage(MessageConstants.ENTERED_METHOD);
			
			String cSymbol = env.getClassSymbol(getClassName());
			String mSymbol = env.getMethodSymbol(getClassName(),cSymbol, mn.name);
			
			InsnList il = InstrumentUtil.addLogMessage(cSymbol,
					mSymbol, logMsg);
			insnList.insertBefore(insnList.getFirst(), il);

			for (AbstractInsnNode abstractInsnNode : insnArr) {
				if (Opcodes.RETURN >= abstractInsnNode.getOpcode()
						&& Opcodes.IRETURN <= abstractInsnNode.getOpcode()) {
					// adding exit logging
					logger.debug(MessageFormat.format(
							InstrumentationMessageLoader
									.getMessage(MessageConstants.LOG_METHOD_EXIT),
							getClassName() + "##" + mn.name));

					logMsg = InstrumentationMessageLoader
							.getMessage(MessageConstants.EXITING_METHOD);
					cSymbol = env.getClassSymbol(getClassName());
					mSymbol = env.getMethodSymbol(getClassName(),cSymbol,mn.name);
					il = InstrumentUtil.addLogMessage(cSymbol,
							mSymbol, logMsg);

					// inserting the list at the associated label node
					AbstractInsnNode prevNode = abstractInsnNode
							.getPrevious();
					while (!(prevNode instanceof LabelNode)) {
						prevNode = prevNode.getPrevious();
					}
					insnList.insert(prevNode, il);
				}
			}
		}
		mn.visitMaxs(0, 0);
	}
	accept(cv);
}
 
Example 11
Source File: TimerAdapter.java    From jumbune with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * visit end method for intrumentation	
 */
@SuppressWarnings("unchecked")
@Override
public void visitEnd() {
	if (isMapperClass() || isReducerClass()) {
		for (Object o : methods) {
			MethodNode mn = (MethodNode) o;
			if (InstrumentUtil.validateMapReduceMethod(mn)) {
				logger.debug("instrumenting " + getClassName() + "##"
						+ mn.name);
				InsnList list = mn.instructions;
				AbstractInsnNode[] insnArr = list.toArray();
				int variable = mn.maxLocals;

				// adding variable declaration
				InsnList il = new InsnList();
				LabelNode newLabel = new LabelNode();
				il.add(newLabel);
				il.add(new MethodInsnNode(Opcodes.INVOKESTATIC,
						"java/lang/System", "currentTimeMillis", Type
								.getMethodDescriptor(Type.LONG_TYPE)));
				il.add(new VarInsnNode(Opcodes.LSTORE, variable));
				list.insertBefore(list.getFirst(), il);

				// adding local variable
				LabelNode begin = new LabelNode();
				LabelNode end = new LabelNode();
				list.insertBefore(list.getFirst(), begin);
				list.insert(list.getLast(), end);
				Type type = Type.LONG_TYPE;
				LocalVariableNode lv = new LocalVariableNode("startMethod",
						type.getDescriptor(), null, begin, end, variable);
				mn.localVariables.add(lv);

				// finding the return statement
				for (AbstractInsnNode abstractInsnNode : insnArr) {
					if (abstractInsnNode.getOpcode() >= Opcodes.IRETURN
							&& abstractInsnNode.getOpcode() <= Opcodes.RETURN) {
						// adding logging statement
						String msg = new StringBuilder(
								"[Method executed] [time] ").toString();
						String cSymbol = env.getClassSymbol(getClassName());
						String mSymbol = env.getMethodSymbol(getClassName(), cSymbol, mn.name);
						InsnList il1 = InstrumentUtil.addTimerLogging(
								cSymbol,mSymbol, variable, msg);

						list.insertBefore(abstractInsnNode, il1);
					}
				}
			}
			mn.visitMaxs(0, 0);
		}
	}
	accept(cv);
}
 
Example 12
Source File: MREntryExitAdapter.java    From jumbune with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * visit end for instrumentation of map-reduce methods
 */
@Override
public void visitEnd() {
	if (isMapperClass() || isReducerClass()) {
		for (Object o : methods) {
			MethodNode mn = (MethodNode) o;
			/**
			 * Valid map/reduce method
			 */
			if (InstrumentUtil.validateMapReduceMethod(mn)) {
				InsnList insnList = mn.instructions;
				AbstractInsnNode[] insnArr = insnList.toArray();

				// adding entry logging
				LOGGER.debug(MessageFormat.format(
						InstrumentationMessageLoader
								.getMessage(MessageConstants.LOG_MAPREDUCE_METHOD_ENTRY),
						getClassName() + "##" + mn.name + "##" + mn.desc));
				String logMsg = new StringBuilder(
						MessageFormat.format(
								InstrumentationMessageLoader
										.getMessage(MessageConstants.ENTERED_MAPREDUCE),
								mn.name)).toString();

				// setting the logger number in ThreadLocal
				InsnList il1 = new InsnList();
				il1.add(new LabelNode());
				il1.add(new VarInsnNode(Opcodes.ALOAD, 0));
				il1.add(new FieldInsnNode(
						Opcodes.GETFIELD,
						ConfigurationUtil.convertQualifiedClassNameToInternalName(getClassName()),
						InstrumentConstants.FIELD_LOGGERNUMBER, "I"));
				il1.add(new MethodInsnNode(Opcodes.INVOKESTATIC,
						CLASSNAME_MAPREDUCEEXECUTIL, "setLoggerNumber",
						Type.getMethodDescriptor(Type.VOID_TYPE,
								Type.INT_TYPE)));
				
				String symbol = env.getClassSymbol(getClassName());
				il1.add(InstrumentUtil.addLogMessage(symbol,
						mn.name, logMsg));

				il1.add(addMapCounter(mn));
				insnList.insertBefore(insnList.getFirst(), il1);

				// traversing the instructions for exit logging
				for (AbstractInsnNode abstractInsnNode : insnArr) {
					// return statement
					if (abstractInsnNode.getOpcode() >= Opcodes.IRETURN
							&& abstractInsnNode.getOpcode() <= Opcodes.RETURN) {
						LOGGER.debug(MessageFormat.format(
								InstrumentationMessageLoader
										.getMessage(MessageConstants.LOG_MAPREDUCE_METHOD_EXIT),
								getClassName() + "##" + mn.name));
						String logMsg2 = new StringBuilder(
								MessageFormat.format(
										InstrumentationMessageLoader
												.getMessage(MessageConstants.EXITING_MAPREDUCE),
										mn.name)).toString();
						
						symbol = getLogClazzName(); 
						InsnList il = InstrumentUtil.addLogMessage(
								symbol, mn.name, logMsg2);
						insnList.insert(abstractInsnNode.getPrevious(), il);
					}
				}
			}
			mn.visitMaxs(0, 0);
		}
	}
	accept(cv);
}
 
Example 13
Source File: SubmitCaseAdapter.java    From jumbune with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void visitEnd() {
	for (Object o : methods) {
		MethodNode mn = (MethodNode) o;
		InsnList insnList = mn.instructions;
		AbstractInsnNode[] insnArr = insnList.toArray();

		/**
		 * Finding the method instruction nodes whose owner is mapreduce.Job
		 * and it submits the job
		 */
		for (AbstractInsnNode abstractInsnNode : insnArr) {
			if (abstractInsnNode instanceof MethodInsnNode) {
				MethodInsnNode min = (MethodInsnNode) abstractInsnNode;

				// finding job submission
				if (min.name.equals(EnumJobSubmitMethods.JOB_SUBMIT
						.toString())) {

					LOGGER.debug(MessageFormat.format(
							InstrumentationMessageLoader
									.getMessage(MessageConstants.JOB_SUBMISSION_FOUND),
							getClassName() + "##" + mn.name));

					// validating that the owner of the method call is

					if (min.owner.equals(EnumJobSubmitMethods.JOB_SUBMIT
							.getOwner().getInternalName())) {
						LOGGER.debug(MessageFormat.format(
								InstrumentationMessageLoader
										.getMessage(MessageConstants.LOG_OWNER_IS_JOB),
								getClassName() + "##" + mn.name));
						AbstractInsnNode ain = min.getPrevious();
						while (!(ain instanceof VarInsnNode)) {
							ain = ain.getPrevious();
						}
						VarInsnNode vin = (VarInsnNode) ain;
						int jobVariableIndex = vin.var;
						InsnList il = null;
						il = handleJobSubmitcase(mn, jobVariableIndex);
						insnList.insert(min, il);
					}
				}
			}
		}
		mn.visitMaxs(0, 0);
	}
	accept(cv);
}
 
Example 14
Source File: ContextWriteValidationAdapter.java    From jumbune with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * This method first copies the key/value to new temporary variables and
 * pass these variables to either PatternMatcher class or the class
 * specified by user. The call to these classes is embedded in Log method so
 * the result returned will be printed. To summarize this method will modify
 * context.write method for copying parameters to local variables and it
 * will then add a call for Log class which prints the result of
 * validation/matching by taking in message a call to these
 * PatternMatcher/User defined validation class. Sample output:
 * 
 * context.write(tempKey = key, tempVal = value); Log.info("result " +
 * PatternMatcher.match(tempVal, regEx)); Log.info("validation result " +
 * UserSpecifiedClass.method(tempVal));
 */
@Override
public void visitEnd() {
	JobConfig jobConfig = (JobConfig)getConfig();
	if (validateUserValidationClass(jobConfig.getUserValidations(),
			getClassName())
			|| validateRegexValidationClass(jobConfig.getRegex(),
					getClassName())) {
		for (int i = 0; i < methods.size(); i++) {
			MethodNode mn = (MethodNode) methods.get(i);
			int variableIndex = mn.maxLocals;
			/**
			 * context.write/output.collect has been written in the
			 * map/reduce methods and other user defined functions. Applying
			 * filter to skip synthetic methods.
			 */
			if (!InstrumentUtil.isSysntheticAccess(mn.access)) {
				InsnList insnList = mn.instructions;
				AbstractInsnNode[] insnArr = insnList.toArray();
				int writeCount = 0;
				for (int j = 0; j < insnArr.length; j++) {
					AbstractInsnNode abstractInsnNode = insnArr[j];

					if (abstractInsnNode instanceof MethodInsnNode) {
						MethodInsnNode min = (MethodInsnNode) abstractInsnNode;

						// write method
						if (InstrumentUtil.isOutputMethod(min)) {

							LOG.debug(MessageFormat.format(
									InstrumentationMessageLoader
											.getMessage(MessageConstants.LOG_ADDING_REGEX_VALIDATION_CALL),
									getClassName() + "##" + mn.name,
									writeCount++));

							InstructionsBean insBean = MethodByteCodeUtil
									.readMethodAndCopyParamToTemporaryVariables(
											min.getPrevious(),
											variableIndex, insnList,
											mn.localVariables);

							// Add the instance of temporary key/value index
							// to ContextWriteParams
							ContextWriteParams
									.getInstance()
									.setTempKeyVariableIndex(
											insBean.getTemporaryVariablesIndexList()
													.get(KEY_INDEX));
							ContextWriteParams
									.getInstance()
									.setTempValueVariableIndex(
											insBean.getTemporaryVariablesIndexList()
													.get(VALUE_INDEX));

							InsnList patternValidationInsnList = new InsnList();
							LOG.debug("***** Just going to add validations  keyIndex "
									+ insBean
											.getTemporaryVariablesIndexList()
											.get(KEY_INDEX)
									+ " Value Index "
									+ insBean
											.getTemporaryVariablesIndexList()
											.get(VALUE_INDEX));

							LOG.debug("ContextWriteParams.getInstance() KEY --  "
									+ ContextWriteParams.getInstance()
											.getTempKeyVariableIndex());
							addValidations(patternValidationInsnList, 
									insBean, mn);

							if (patternValidationInsnList != null
									&& patternValidationInsnList.size() > 0) {
								insnList.insert(abstractInsnNode,
										patternValidationInsnList);
							}
						}
					}
				}
			}
			mn.visitMaxs(0, 0);
		}
	}
	accept(cv);
}
 
Example 15
Source File: ContextWriteLogAdapter.java    From jumbune with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void visitEnd() {
	if (isMapperClass() || isReducerClass()) {
		for (Object o : methods) {
			MethodNode mn = (MethodNode) o;
			InsnList insnList = mn.instructions;
			AbstractInsnNode[] insnArr = insnList.toArray();
			int writeCount = 0;

			// traversing the instructions
			for (AbstractInsnNode abstractInsnNode : insnArr) {
				if (abstractInsnNode instanceof MethodInsnNode) {
					MethodInsnNode min = (MethodInsnNode) abstractInsnNode;

					// write method
					if (InstrumentUtil.isOutputMethod(min)) {
						writeCount++;
						LOGGER.debug(MessageFormat.format(
								InstrumentationMessageLoader
										.getMessage(MessageConstants.LOG_MAPREDUCE_CTXWRITE_CALL),
								getClassName() + "##" + mn.name, writeCount));
						String logMsg = null;

						// mapper
						if (isMapperClass()) {
							logMsg = InstrumentationMessageLoader
									.getMessage(MessageConstants.MAPPER_CONTEXT_WRITE);
						}
						// combiner or reducer
						else if (isReducerClass()) {
							logMsg = InstrumentationMessageLoader
									.getMessage(MessageConstants.REDUCER_CONTEXT_WRITE);
						}

						InsnList il = InstrumentUtil
								.addMapReduceContextWriteLogging(
										getLogClazzName(), mn.name, logMsg);

						insnList.insertBefore(abstractInsnNode, il);

						// setting loggernumber to ThreadLocal
						InsnList lll = new InsnList();
						lll.add(new LabelNode());
						lll.add(new VarInsnNode(Opcodes.ALOAD, 0));
						lll.add(new FieldInsnNode(
								Opcodes.GETFIELD,
								ConfigurationUtil.convertQualifiedClassNameToInternalName(getClassName()),
								InstrumentConstants.FIELD_LOGGERNUMBER, "I"));
						lll.add(new MethodInsnNode(Opcodes.INVOKESTATIC,
								CLASSNAME_MAPREDUCEEXECUTIL,
								"setLoggerNumber", Type
										.getMethodDescriptor(
												Type.VOID_TYPE,
												Type.INT_TYPE)));

						insnList.insert(abstractInsnNode, lll);
					}
				}
			}
			mn.visitMaxs(0, 0);
		}
	}
	accept(cv);
}
 
Example 16
Source File: PartitionerAdapter.java    From jumbune with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * method for instrumenting jar for debugging partitioner
 */
@Override
public void visitEnd() {
	if (isMapperClass()) {
		LOG.debug("Instrumenting jar for debugging partitioner !!");
		for (int i = 0; i < methods.size(); i++) {
			MethodNode mn = (MethodNode) methods.get(i);
			final int variableIndex = mn.maxLocals;

			if (InstrumentUtil.validateMapMethod(mn)) {
				InsnList insnList = mn.instructions;
				AbstractInsnNode[] insnArr = insnList.toArray();

				// Get the index of temporary variables of key and value
				int keyVariableIndex = ContextWriteParams.getInstance()
						.getTempKeyVariableIndex();
				int valueVariableIndex = ContextWriteParams.getInstance()
						.getTempValueVariableIndex();

				LOG.debug("Index set in ContextWriteParams  "
						+ keyVariableIndex + " Index of Value  "
						+ valueVariableIndex + " for class "
						+ getClassName());

				for (AbstractInsnNode abstractInsnNode : insnArr) {
					if (abstractInsnNode instanceof MethodInsnNode) {
						MethodInsnNode min = (MethodInsnNode) abstractInsnNode;

						if (InstrumentUtil.isOutputMethod(min)) {
							// If both the key and value index are 0 that
							// means its yet not copied to temporary
							// variables just copy these params to temporary
							// variables
							if (keyVariableIndex == 0
									&& valueVariableIndex == 0) {
								LOG.debug("Since params are not copied to temporary variables do it now !!!!! "
										+ " \n previous to context.write  "
										+ min.getPrevious()
										+ " variableIndex "
										+ variableIndex
										+ " insnList " + insnList.size());
								InstructionsBean insBean = MethodByteCodeUtil
										.readMethodAndCopyParamToTemporaryVariables(
												min.getPrevious(),
												variableIndex, insnList,
												mn.localVariables);
								LOG.debug("After the instructions were added size of insnList :: "
										+ insnList.size());
								// Add the instance of temporary key/value
								// index to ContextWriteParams
								keyVariableIndex = insBean
										.getTemporaryVariablesIndexList()
										.get(KEY_INDEX);
								valueVariableIndex = insBean
										.getTemporaryVariablesIndexList()
										.get(VALUE_INDEX);

								ContextWriteParams.getInstance()
										.setTempKeyVariableIndex(
												keyVariableIndex);
								ContextWriteParams.getInstance()
										.setTempValueVariableIndex(
												valueVariableIndex);
							}
							// Add instructions for detecting the time taken
							// in partitioning
							insnList.insert(
									abstractInsnNode,
									getInsnListForCalculatePartitioningTime(
											keyVariableIndex,
											valueVariableIndex));
						}
					}
				}
			}
			mn.visitMaxs(0, 0);
		}
	}
	accept(cv);
}