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

The following examples show how to use org.objectweb.asm.tree.InsnList#insertBefore() . 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: 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 2
Source File: Instrumentator.java    From instrumentation with Apache License 2.0 6 votes vote down vote up
private void addTraceReturn() {

        InsnList il = this.mn.instructions;

        Iterator<AbstractInsnNode> it = il.iterator();
        while (it.hasNext()) {
            AbstractInsnNode abstractInsnNode = it.next();

            switch (abstractInsnNode.getOpcode()) {
                case Opcodes.RETURN:
                    il.insertBefore(abstractInsnNode, getVoidReturnTraceInstructions());
                    break;
                case Opcodes.IRETURN:
                case Opcodes.LRETURN:
                case Opcodes.FRETURN:
                case Opcodes.ARETURN:
                case Opcodes.DRETURN:
                    il.insertBefore(abstractInsnNode, getReturnTraceInstructions());
            }
        }
    }
 
Example 3
Source File: Instrumentator.java    From instrumentation with Apache License 2.0 6 votes vote down vote up
private void addTraceThrow() {

        InsnList il = this.mn.instructions;

        Iterator<AbstractInsnNode> it = il.iterator();
        while (it.hasNext()) {
            AbstractInsnNode abstractInsnNode = it.next();

            switch (abstractInsnNode.getOpcode()) {
                case Opcodes.ATHROW:
                    il.insertBefore(abstractInsnNode, getThrowTraceInstructions());
                    break;
            }
        }

    }
 
Example 4
Source File: RuleMethodRewriter.java    From grappa with Apache License 2.0 6 votes vote down vote up
private void createNewGroupClassInstance(final InstructionGroup group)
{
    final String internalName
        = group.getGroupClassType().getInternalName();
    final InstructionGraphNode root = group.getRoot();
    final AbstractInsnNode rootInsn = root.getInstruction();
    final InsnList insnList = method.instructions;
    final String constant = method.name + (root.isActionRoot() ? "_Action"
        + ++actionNr : "_VarInit" + ++varInitNr);

    final CodeBlock block = CodeBlock.newCodeBlock();

    block.newobj(internalName)
        .dup()
        .ldc(constant)
        .invokespecial(internalName, "<init>",
            CodegenUtils.sig(void.class, String.class));

    if (root.isActionRoot()
        && method.hasSkipActionsInPredicatesAnnotation())
        block.dup().invokevirtual(internalName, "setSkipInPredicates",
            CodegenUtils.sig(void.class));

    insnList.insertBefore(rootInsn, block.getInstructionList());
}
 
Example 5
Source File: ConfigureMapReduceAdapter.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * It modifies existing setup/configure , cleanup/close methods by adding
 * jumbune logging related instructions.
 *
 * @param mn - current method node
 * @param isSetup - true if its setup method, false if its cleanup method
 */
private void modifyConfigureMethods(MethodNode mn, boolean isSetup) {
	if (isSetup) {
		LOGGER.debug(MessageFormat.format(InstrumentationMessageLoader
				.getMessage(MessageConstants.LOG_MODIFY_SETUP_METHOD),
				getClassName()));
	} else {
		LOGGER.debug(MessageFormat.format(InstrumentationMessageLoader
				.getMessage(MessageConstants.LOG_MODIFY_CLEANUP_METHODD),
				getClassName()));
	}
	InsnList insnList = mn.instructions;
	AbstractInsnNode[] insnArr = insnList.toArray();

	for (AbstractInsnNode abstractInsnNode : insnArr) {
		if (Opcodes.RETURN >= abstractInsnNode.getOpcode()
				&& Opcodes.IRETURN <= abstractInsnNode.getOpcode()) {
			InsnList il = new InsnList();

			il.add(prepareMapReduceForJumbuneInstructions(isSetup, mn));

			insnList.insertBefore(abstractInsnNode, il);
			break;
		}
	}
}
 
Example 6
Source File: ReturnAdapter.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * visit end method for intrumentation	
 */
@Override
public void visitEnd() {
	for (Object o : methods) {
		MethodNode mn = (MethodNode) o;

		if (validateMethods(mn)
				&& InstrumentUtil.validateMethodName(mn.name, "<clinit>")
				&& mn.name.indexOf("access$") < 0) {

			logger.debug("instrumenting " + getClassName() + "##" + mn.name);

			InsnList insnList = mn.instructions;
			AbstractInsnNode[] insnArr = insnList.toArray();
			for (AbstractInsnNode abstractInsnNode : insnArr) {
				if (Opcodes.RETURN >= abstractInsnNode.getOpcode()
						&& Opcodes.IRETURN <= abstractInsnNode.getOpcode()) {
					String msg = new StringBuilder("[Return] [method] [] ")
							.toString();

					String cSymbol = env.getClassSymbol(getClassName());
					String mSymbol = env.getMethodSymbol(getClassName(), cSymbol, mn.name);

					InsnList il = InstrumentUtil.addReturnLogging(
							cSymbol, mSymbol, msg);
					insnList.insertBefore(abstractInsnNode, il);
				}
			}
		}
		mn.visitMaxs(0, 0);
	}
	accept(cv);
}
 
Example 7
Source File: VarFramingGenerator.java    From grappa with Apache License 2.0 5 votes vote down vote up
@Override
public void process(@Nonnull final ParserClassNode classNode,
    @Nonnull final RuleMethod method)
    throws Exception
{
    Objects.requireNonNull(classNode, "classNode");
    Objects.requireNonNull(method, "method");
    final InsnList instructions = method.instructions;

    AbstractInsnNode ret = instructions.getLast();
    while (ret.getOpcode() != ARETURN)
        ret = ret.getPrevious();

    final CodeBlock block = CodeBlock.newCodeBlock();

    block.newobj(CodegenUtils.p(VarFramingMatcher.class))
        .dup_x1()
        .swap();

    createVarFieldArray(block, method);

    block.invokespecial(CodegenUtils.p(VarFramingMatcher.class), "<init>",
        CodegenUtils.sig(void.class, Rule.class, Var[].class));

    instructions.insertBefore(ret, block.getInstructionList());

    method.setBodyRewritten();
}
 
Example 8
Source File: LabellingGenerator.java    From grappa with Apache License 2.0 5 votes vote down vote up
@Override
public void process(@Nonnull final ParserClassNode classNode,
    @Nonnull final RuleMethod method)
    throws Exception
{
    Objects.requireNonNull(classNode, "classNode");
    Objects.requireNonNull(method, "method");
    // super methods have flag moved to the overriding method
    Preconditions.checkState(!method.isSuperMethod());

    final InsnList instructions = method.instructions;

    AbstractInsnNode retInsn = instructions.getLast();
    while (retInsn.getOpcode() != ARETURN)
        retInsn = retInsn.getPrevious();

    final LabelNode label = new LabelNode();
    final CodeBlock block = CodeBlock.newCodeBlock()
        .dup()
        .ifnull(label)
        .ldc(getLabelText(method))
        .invokeinterface(CodegenUtils.p(Rule.class), "label",
            CodegenUtils.sig(Rule.class, String.class))
        .label(label);

    instructions.insertBefore(retInsn, block.getInstructionList());
}
 
Example 9
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 10
Source File: MainAdapter.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @see org.jumbune.debugger.instrumentation.adapter.BaseAdapter#visitEnd()
 */
@Override
public void visitEnd() {
	for (Object o : methods) {
		MethodNode mn = (MethodNode) o;

		// finding main method
		if (InstrumentUtil.validateMethodName(mn.name, MAIN_METHOD)
				&& Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC == mn.access
				&& Type.getMethodDescriptor(Type.VOID_TYPE,
						TYPE_STRING_ARRAY).equals(mn.desc)) {
			LOGGER.debug(MessageFormat.format(InstrumentationMessageLoader
					.getMessage(MessageConstants.MAIN_METHOD_FOUND),
					getClassName()));

			InsnList insnList = mn.instructions;

			InsnList il = new InsnList();
			il.add(loadClasses());

			// insert as first instruction
			insnList.insertBefore(insnList.getFirst(), il);
			break;
		}
		mn.visitMaxs(0, 0);
	}
	accept(cv);
}
 
Example 11
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 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: 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 14
Source File: JobAdapter.java    From jumbune with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Visit end.
 *
 * @see org.jumbune.debugger.instrumentation.adapter.BaseAdapter#visitEnd()
 */
@Override
public void visitEnd() {
	for (Object o : methods) {
		MethodNode mn = (MethodNode) o;

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

		LOGGER.debug(MessageFormat.format(InstrumentationMessageLoader
				.getMessage(MessageConstants.LOG_INSTRUMENTING_METHOD),
				getClassName() + "##" + mn.name));
		// traversing in reverse order as job submission comes at the end of
		// the method
		for (AbstractInsnNode abstractInsnNode : insnArr) {
			if (abstractInsnNode instanceof MethodInsnNode) {
				MethodInsnNode min = (MethodInsnNode) abstractInsnNode;

				// finding job submission
				if (InstrumentUtil.isJobSubmissionMethod(min)) {

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

					// validating if the owner is mapreduce.Job or JobClient
					if (InstrumentUtil.isOwnerJob(min)) {

						LOGGER.debug(MessageFormat.format(
								InstrumentationMessageLoader
										.getMessage(MessageConstants.LOG_OWNER_IS_JOB),
								getClassName()));
						// finding index of job variable
						AbstractInsnNode ain = min.getPrevious();
						while (!(ain instanceof VarInsnNode)) {
							ain = ain.getPrevious();
						}
						VarInsnNode vin = (VarInsnNode) ain;
						int jobVariableIndex = vin.var;

						InsnList il = new InsnList();

						// classpath is to be passed as libjars
						il.add(addClasspath(jobVariableIndex,
								getOwnerType(min)));
						// // output path modification
						il.add(modifyOutputPath(jobVariableIndex,
								getOwnerType(min)));
						insnList.insertBefore(vin, il);

						// Disabling the profiling for the pure jar - old
						// api
						if (getOwnerType(min).getInternalName().equals(
								CLASSNAME_JOB_CONF)) {

							il.add(new LabelNode());
							il.add(new VarInsnNode(Opcodes.ALOAD,
									jobVariableIndex));
							il.add(new LdcInsnNode(false));
							il.add(new MethodInsnNode(
									Opcodes.INVOKEVIRTUAL,
									CLASSNAME_JOB_CONF,
									"setProfileEnabled", Type
											.getMethodDescriptor(
													Type.VOID_TYPE,
													Type.BOOLEAN_TYPE)));
						} else {
							il.add(new LabelNode());
							il.add(new VarInsnNode(Opcodes.ALOAD,
									jobVariableIndex));
							il.add(new MethodInsnNode(
									Opcodes.INVOKEVIRTUAL,
									CLASSNAME_MR_JOB, "getConfiguration",
									Type.getMethodDescriptor(Type
											.getType(Configuration.class))));

							il.add(new LdcInsnNode(PROFILE_TASK));
							il.add(new LdcInsnNode(Boolean.toString(false)));
							il.add(new MethodInsnNode(
									Opcodes.INVOKEVIRTUAL,
									CLASSNAME_HADOOP_CONFIGURATION, "set",
									Type.getMethodDescriptor(
											Type.VOID_TYPE, TYPE_STRING,
											TYPE_STRING)));
						}

						insnList.insertBefore(vin, il);
					}
				}
			}
		}
		mn.visitMaxs(0, 0);
	}
	accept(cv);
}
 
Example 15
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 16
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 17
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 18
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 19
Source File: BogusJumpInserter.java    From radon with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Generates a generic "escape" pattern to avoid inserting multiple copies of the same bytecode instructions.
 *
 * @param methodNode the {@link MethodNode} we are inserting into.
 * @return a {@link LabelNode} which "escapes" all other flow.
 */
private static LabelNode exitLabel(MethodNode methodNode) {
    LabelNode lb = new LabelNode();
    LabelNode escapeNode = new LabelNode();

    InsnList insns = methodNode.instructions;
    AbstractInsnNode target = insns.getFirst();

    insns.insertBefore(target, new JumpInsnNode(GOTO, escapeNode));
    insns.insertBefore(target, lb);

    switch (Type.getReturnType(methodNode.desc).getSort()) {
        case Type.VOID:
            insns.insertBefore(target, new InsnNode(RETURN));
            break;
        case Type.BOOLEAN:
            insns.insertBefore(target, ASMUtils.getNumberInsn(RandomUtils.getRandomInt(2)));
            insns.insertBefore(target, new InsnNode(IRETURN));
            break;
        case Type.CHAR:
            insns.insertBefore(target, ASMUtils.getNumberInsn(RandomUtils
                    .getRandomInt(Character.MAX_VALUE + 1)));
            insns.insertBefore(target, new InsnNode(IRETURN));
            break;
        case Type.BYTE:
            insns.insertBefore(target, ASMUtils.getNumberInsn(RandomUtils.getRandomInt(Byte.MAX_VALUE + 1)));
            insns.insertBefore(target, new InsnNode(IRETURN));
            break;
        case Type.SHORT:
            insns.insertBefore(target, ASMUtils.getNumberInsn(RandomUtils.getRandomInt(Short.MAX_VALUE + 1)));
            insns.insertBefore(target, new InsnNode(IRETURN));
            break;
        case Type.INT:
            insns.insertBefore(target, ASMUtils.getNumberInsn(RandomUtils.getRandomInt()));
            insns.insertBefore(target, new InsnNode(IRETURN));
            break;
        case Type.LONG:
            insns.insertBefore(target, ASMUtils.getNumberInsn(RandomUtils.getRandomLong()));
            insns.insertBefore(target, new InsnNode(LRETURN));
            break;
        case Type.FLOAT:
            insns.insertBefore(target, ASMUtils.getNumberInsn(RandomUtils.getRandomFloat()));
            insns.insertBefore(target, new InsnNode(FRETURN));
            break;
        case Type.DOUBLE:
            insns.insertBefore(target, ASMUtils.getNumberInsn(RandomUtils.getRandomDouble()));
            insns.insertBefore(target, new InsnNode(DRETURN));
            break;
        default:
            insns.insertBefore(target, new InsnNode(ACONST_NULL));
            insns.insertBefore(target, new InsnNode(ARETURN));
            break;
    }
    insns.insertBefore(target, escapeNode);

    return lb;
}