Java Code Examples for ghidra.program.model.symbol.SourceType#USER_DEFINED

The following examples show how to use ghidra.program.model.symbol.SourceType#USER_DEFINED . 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: CreateFunctionCmdTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateFunctionFindEntryBodyError() {
	int transactionID = program.startTransaction("Perform the TEST");

	CreateFunctionCmd createCmd = new CreateFunctionCmd("bob", addr(0x1003),
		new AddressSet(addr(0x1003), addr(0x1007)), SourceType.USER_DEFINED, true, true);
	boolean result = createCmd.applyTo(program);

	assertFalse("Create Function", result);

	Function func1000 = func(addr(0x1000));
	Function func1003 = func(addr(0x1003));

	assertNull("No function at 1000", func1000);
	assertNull("No function at 10003", func1003);

	program.endTransaction(transactionID, true);
}
 
Example 2
Source File: RefListFlagsV0.java    From ghidra with Apache License 2.0 6 votes vote down vote up
public RefListFlagsV0(boolean isPrimary, boolean isOffsetRef, boolean hasSymbolID,
		boolean isShiftRef, SourceType source) {
	flags = 0;
	if (source == SourceType.USER_DEFINED || source == SourceType.IMPORTED) {
		flags |= SOURCE_LOBIT;
	}
	if (source == SourceType.ANALYSIS || source == SourceType.IMPORTED) {
		flags |= SOURCE_HIBIT;
	}
	if (isPrimary)
		flags |= IS_PRIMARY;
	if (isOffsetRef)
		flags |= IS_OFFSET;
	if (hasSymbolID)
		flags |= HAS_SYMBOL_ID;
	if (isShiftRef)
		flags |= IS_SHIFT;
}
 
Example 3
Source File: CreateFunctionCmdTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateOverlappingTruncated() {
	int transactionID = program.startTransaction("Perform the TEST");

	CreateFunctionCmd createCmd =
		new CreateFunctionCmd("bob", addr(0x1003), null, SourceType.USER_DEFINED, false, true);
	boolean result = createCmd.applyTo(program);

	assertTrue("Create Function", result);

	Function func1003 = func(addr(0x1003));
	assertEquals("Function body length", 4, func1003.getBody().getNumAddresses());

	createCmd =
		new CreateFunctionCmd(null, addr(0x1000), null, SourceType.USER_DEFINED, true, true);
	result = createCmd.applyTo(program);

	Function func1000 = createCmd.getFunction(); // test result function available from cmd
	assertEquals("Create truncated function", func1000.getEntryPoint(), addr(0x1000));
	assertEquals("Function body length", 3, func1000.getBody().getNumAddresses());

	func1003 = func(addr(0x1003));
	assertEquals("Created function body length", 4, func1003.getBody().getNumAddresses());

	program.endTransaction(transactionID, true);
}
 
Example 4
Source File: FindEmptySpaceScript.java    From ghidra with Apache License 2.0 6 votes vote down vote up
protected void addLabelAndExportSym(Address matchAddr, long len, String stem, String tag,
		String optComment) {
	String label = stem + "_" + matchAddr + "_" + len;
	label = label.replaceAll(":", "_");
	String comment = "{@exportsym " + tag + " " + optComment + "}";
	CodeUnit cd = currentProgram.getListing().getCodeUnitAt(matchAddr);
	if (cd == null) {
		return;
	}
	AddLabelCmd lcmd = new AddLabelCmd(matchAddr, label, false, SourceType.USER_DEFINED);
	lcmd.applyTo(currentProgram);
	String commentThere = cd.getComment(CodeUnit.EOL_COMMENT);
	if (commentThere != null) {
		comment = commentThere + "\n" + comment;
	}
	cd.setComment(CodeUnit.EOL_COMMENT, comment);
}
 
Example 5
Source File: CreateFunctionCmdTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateFunctionEntryBodyError() {
	int transactionID = program.startTransaction("Perform the TEST");

	CreateFunctionCmd createCmd = new CreateFunctionCmd("bob", addr(0x1000),
		new AddressSet(addr(0x1003), addr(0x1007)), SourceType.USER_DEFINED, false, true);
	boolean result = createCmd.applyTo(program);

	assertFalse("Create Function", result);

	Function func1000 = func(addr(0x1000));
	Function func1003 = func(addr(0x1003));

	assertNull("No function at 1000", func1000);
	assertNull("No function at 10003", func1003);

	program.endTransaction(transactionID, true);
}
 
Example 6
Source File: CreateMultipleFunctionsCmdTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
   public void testCreateMultipleFunctionsWithSingleRangeSelection() {

	// a selection that covers the functions we are seeking
	AddressSet selection = new AddressSet(addr(0x0), addr(0x20));

	int transactionID = program.startTransaction("Perform the TEST");

	CreateMultipleFunctionsCmd createCmd =
		new CreateMultipleFunctionsCmd(selection, SourceType.USER_DEFINED);
	createCmd.applyTo(program);

	program.endTransaction(transactionID, true);

	// Verify the functions were created.
	assertNotNull(func(addr(0x0)));
	assertNotNull(func(addr(0x5)));
	assertNotNull(func(addr(0xe)));
	assertNotNull(func(addr(0x18)));
	assertNotNull(func(addr(0x1d)));
}
 
Example 7
Source File: FunctionGraphPlugin1Test.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void doTestLabelChangeAtVertexEntryUpdatesTitle() {
	// get the graph contents
	FGData graphData = getFunctionGraphData();
	assertNotNull(graphData);
	assertTrue("Unexpectedly received an empty FunctionGraphData", graphData.hasResults());

	// locate vertex with cursor
	Address vertexAddressWithDefaultLabel = getAddress("01004178");
	FunctionGraph graph = graphData.getFunctionGraph();
	FGVertex vertex = graph.getVertexForAddress(vertexAddressWithDefaultLabel);
	String originalTitle = vertex.getTitle();

	// add a label in the listing
	String labelName = testName.getMethodName();
	AddLabelCmd addCmd =
		new AddLabelCmd(vertexAddressWithDefaultLabel, labelName, SourceType.USER_DEFINED);
	addCmd.applyTo(program);
	program.flushEvents();
	waitForSwing();

	// make sure the label appears in the vertex
	String updatedTitle = vertex.getTitle();
	Assert.assertNotEquals(originalTitle, updatedTitle);
	assertTrue(updatedTitle.indexOf(testName.getMethodName()) != -1);
}
 
Example 8
Source File: CreateMultipleFunctionsCmdTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
   public void testCreateMultipleFunctionsWithMultipleEntryPointSelection() {

	// put each entry point in the selection
	AddressSet selection = new AddressSet();
	selection.add(addr(0x0));
	selection.add(addr(0x5));
	selection.add(addr(0xe));
	selection.add(addr(0x18));
	selection.add(addr(0x1d));

	int transactionID = program.startTransaction("Perform the TEST");

	CreateMultipleFunctionsCmd createCmd =
		new CreateMultipleFunctionsCmd(selection, SourceType.USER_DEFINED);
	createCmd.applyTo(program);

	program.endTransaction(transactionID, true);

	// Verify the functions were created.
	assertNotNull(func(addr(0x0)));
	assertNotNull(func(addr(0x5)));
	assertNotNull(func(addr(0xe)));
	assertNotNull(func(addr(0x18)));
	assertNotNull(func(addr(0x1d)));
}
 
Example 9
Source File: RenameLocalAction.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
protected void decompilerActionPerformed(DecompilerActionContext context) {
	PluginTool tool = context.getTool();
	final ClangToken tokenAtCursor = context.getTokenAtCursor();
	HighSymbol highSymbol = findHighSymbolFromToken(tokenAtCursor, context.getHighFunction());

	RenameVariableTask nameTask = new RenameVariableTask(tool, context.getProgram(),
		context.getDecompilerPanel(),
		tokenAtCursor, highSymbol, SourceType.USER_DEFINED);

	nameTask.runTask(true);
}
 
Example 10
Source File: DisplayableEolTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testReferenceToStringData() throws Exception {

	Command cmd = new AddMemRefCmd(addr("0x1001000"), addr("0x1001234"),
		SourceType.USER_DEFINED, 0, true);
	applyCmd(cmd);

	Listing listing = program.getListing();
	CodeUnit cu = listing.getCodeUnitAt(addr("0x1001000"));
	DisplayableEol displayableEol = new DisplayableEol(cu, true, true, true, false, 5, true);

	String[] comments = displayableEol.getAutomaticComment();
	assertEquals(1, comments.length);
	assertEquals("= \"one.two\"", comments[0]);
}
 
Example 11
Source File: HighSymbolTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void isolateVariable(HighSymbol highSymbol, ClangToken tokenAtCursor, String newName) {
	IsolateVariableTask isolate = new IsolateVariableTask(provider.getTool(), program,
		provider.getDecompilerPanel(), tokenAtCursor, highSymbol, SourceType.USER_DEFINED);
	assertTrue(isolate.isValid(newName));
	modifyProgram(p -> {
		isolate.commit();
	});
	waitForDecompiler();
}
 
Example 12
Source File: IsolateVariableAction.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
protected void decompilerActionPerformed(DecompilerActionContext context) {
	final ClangToken tokenAtCursor = context.getTokenAtCursor();
	HighSymbol highSymbol = tokenAtCursor.getHighVariable().getSymbol();
	IsolateVariableTask newVariableTask =
		new IsolateVariableTask(context.getTool(), context.getProgram(),
			context.getDecompilerPanel(), tokenAtCursor, highSymbol, SourceType.USER_DEFINED);

	newVariableTask.runTask(false);
}
 
Example 13
Source File: LabelFieldFactoryTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void createLabel(String addr, String name) {

		int transaction = program.startTransaction("Add Label");
		try {
			AddLabelCmd cmd = new AddLabelCmd(addr(addr), name, SourceType.USER_DEFINED);
			cmd.applyTo(program);
			program.flushEvents();
			waitForPostedSwingRunnables();
		}
		finally {
			program.endTransaction(transaction, true);
		}
	}
 
Example 14
Source File: OperandFieldFactoryTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
	 * Tests that offcut references into arrays are painted as offsets into the array and not
	 * as simply an offset from the min address.
	 */
	@Test
	public void testOffcutReferenceIntoArray() throws Exception {
//		openEmptyNotepad();

		StructureDataType structure = new StructureDataType("structure", 0);
		structure.add(IntegerDataType.dataType, "field1", "Comment 1");
		structure.add(IntegerDataType.dataType, "field2", "Comment 2");
		structure.add(IntegerDataType.dataType, "field3", "Comment 3");

		Address arrayAddr = addr("01001888");
		Command cmd = new CreateArrayCmd(arrayAddr, 3, structure, 12);
		applyCmd(program, cmd);

		String arrayName = "ArrayOfStructures";
		cmd = new AddLabelCmd(arrayAddr, arrayName, SourceType.USER_DEFINED);
		applyCmd(program, cmd);

		String operandAddressString = "1006440";
		Address operandAddr = addr(operandAddressString);
		cmd = new AddMemRefCmd(addr(operandAddressString), addr("010018a0"),
			SourceType.USER_DEFINED, 0, true);
		applyCmd(program, cmd);

		//
		// We should expect the operand field to use the dynamic label of the array, which is
		// generated by the reference.  It should look something like:
		//     ArrayOfStructures[2].field1
		//
		assertTrue(cb.goToField(operandAddr, OperandFieldFactory.FIELD_NAME, 0, 1));
		ListingTextField tf = (ListingTextField) cb.getCurrentField();
		assertEquals(arrayName + "[2].field1", tf.getText());
	}
 
Example 15
Source File: BookmarkPluginTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void initProgram() {
	addrFactory = program.getAddressFactory();

	// Remove all existing bookmarks
	BookmarkDeleteCmd delCmd = new BookmarkDeleteCmd(addrFactory.getAddressSet(), null, null);
	applyCmd(program, delCmd);

	// Add specific bookmarks
	CompoundCmd addCmd = new CompoundCmd("Add Bookmarks");
	addCmd.add(new BookmarkEditCmd(addr("01001010"), "Type1", "Cat1a", "Cmt1A"));
	addCmd.add(new BookmarkEditCmd(addr("01001020"), "Type1", "Cat1a", "Cmt1B"));
	addCmd.add(new BookmarkEditCmd(addr("01001020"), "Type1", "Cat1b", "Cmt1C"));
	addCmd.add(new BookmarkEditCmd(addr("01001030"), "Type1", "Cat1b", "Cmt1D"));
	addCmd.add(new BookmarkEditCmd(addr("01001030"), "Type2", "Cat2a", "Cmt2E"));
	addCmd.add(new BookmarkEditCmd(addr("01001040"), "Type2", "Cat2b", "Cmt2F"));
	addCmd.add(new BookmarkEditCmd(addr("01001040"), "Type3", "Cat3a", "Cmt2G"));
	addCmd.add(new BookmarkEditCmd(addr("01001050"), "Type3", "Cat3a", "Cmt2H"));
	addCmd.add(new BookmarkEditCmd(addr("01001060"), "Type3", "Cat3b", "Cmt2I"));
	applyCmd(program, addCmd);

	AddLabelCmd labelCmd =
		new AddLabelCmd(addr("01001020"), "Test20", false, SourceType.USER_DEFINED);
	applyCmd(program, labelCmd);

	labelCmd = new AddLabelCmd(addr("01001050"), "Test50", false, SourceType.USER_DEFINED);
	applyCmd(program, labelCmd);

	List<Bookmark> list = getBookmarks(program.getBookmarkManager());
	assertEquals(9, list.size());
	bookmarks = new Bookmark[9];
	list.toArray(bookmarks);
	Arrays.sort(bookmarks);
}
 
Example 16
Source File: LabelFieldFactoryTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void renameFunction(Function function, String name) {
	SetFunctionNameCmd cmd =
		new SetFunctionNameCmd(function.getEntryPoint(), name, SourceType.USER_DEFINED);

	int ID = program.startTransaction("Test - Create Reference");
	try {
		cmd.applyTo(program);
	}
	finally {
		program.endTransaction(ID, true);
	}

	program.flushEvents();
	waitForPostedSwingRunnables();
}
 
Example 17
Source File: CreateMultipleFunctionsCmdTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
   public void testCreateMultipleFunctionsWithMultipleOffsetRangeSelection() {

	// create a selection that starts inside functions and ends inside a follow-up function
	AddressSet selection = new AddressSet();
	selection.addRange(addr(0x2), addr(0x7));
	selection.addRange(addr(0xf), addr(0x1a));

	int transactionID = program.startTransaction("Perform the TEST");

	CreateMultipleFunctionsCmd createCmd =
		new CreateMultipleFunctionsCmd(selection, SourceType.USER_DEFINED);
	createCmd.applyTo(program);

	program.endTransaction(transactionID, true);

	// Verify where the functions were created.
	assertNotNull(func(addr(0x2)));// manually created
	assertNotNull(func(addr(0x5)));// next function
	assertNotNull(func(addr(0xf)));// manually created
	assertNotNull(func(addr(0x18)));// next function

	// Verify where the functions were not created.
	assertNull(func(addr(0x0)));
	assertNull(func(addr(0xe)));
	assertNull(func(addr(0x1d)));
}
 
Example 18
Source File: FunctionPlugin.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * This method is the same as {@link #createData(DataType, ProgramLocation)}, except that this
 * method will use the given value of <tt>convertPointers</tt> to determine if the new
 * DataType should be made into a pointer if the existing DataType is a pointer.
 * @param dataType The DataType to create.
 * @param location The location at which to create the DataType.
 * @param convertPointers True signals to convert the given DataType to a pointer if there is
 *        an existing pointer at the specified location.
 * @param promptForConflictRemoval if true and specified dataType results in a storage conflict,
 * user may be prompted for removal of conflicting variables (not applicable for return type)
 * @return True if the DataType could be created at the given location.
 */
public boolean createData(DataType dataType, ListingActionContext context,
		boolean convertPointers, boolean promptForConflictRemoval) {
	ProgramLocation location = context.getLocation();
	Program program = context.getProgram();
	if (!(location instanceof FunctionLocation)) {
		tool.setStatusInfo("Unsupported function location for data-type");
		return false;
	}

	if (dataType != DataType.DEFAULT && dataType != DataType.VOID) {
		dtmService.setRecentlyUsed(dataType);
	}

	Function function = getFunction(context);
	if (function == null) {
		tool.setStatusInfo("Unsupported function location for data-type");
		return false;
	}

	// TODO: this will not allow setting a return value as a function pointer
	if ((location instanceof FunctionSignatureFieldLocation) &&
		(dataType instanceof FunctionSignature)) {
		return tool.execute(new ApplyFunctionSignatureCmd(function.getEntryPoint(),
			(FunctionSignature) dataType, SourceType.USER_DEFINED), program);
	}

	DataType existingDT = getCurrentDataType(context);
	dataType = DataUtilities.reconcileAppliedDataType(existingDT, dataType, convertPointers);

	if (dataType.getLength() < 0) {
		tool.setStatusInfo("Only fixed-length data-type permitted");
		return false;
	}

	// this check must come before the signature check, since this is a FunctionSignatureFieldLocation
	if (location instanceof FunctionParameterFieldLocation) {
		FunctionParameterFieldLocation parameterLocation =
			(FunctionParameterFieldLocation) location;
		Parameter parameter = parameterLocation.getParameter();

		return setVariableDataType(parameter, dataType, promptForConflictRemoval);
	}
	else if (location instanceof FunctionSignatureFieldLocation) {
		SourceType source =
			(dataType == DataType.DEFAULT) ? SourceType.DEFAULT : SourceType.USER_DEFINED;
		return tool.execute(
			new SetReturnDataTypeCmd(function.getEntryPoint(), dataType, source), program);
	}
	else if (location instanceof VariableLocation) {
		Variable variable = ((VariableLocation) location).getVariable();
		return setVariableDataType(variable, dataType, promptForConflictRemoval);
	}
	tool.setStatusInfo("Unsupported function location for data-type");
	return false;
}
 
Example 19
Source File: AbstractLocationReferencesTest.java    From ghidra with Apache License 2.0 4 votes vote down vote up
protected void createReference(Address from, Address to) {
	AddMemRefCmd addRefCommand =
		new AddMemRefCmd(from, to, RefType.READ, SourceType.USER_DEFINED, 0);
	boolean referenceAdded = applyCmd(program, addRefCommand);
	assertTrue("Unable to add reference to: " + to, referenceAdded);
}
 
Example 20
Source File: CreateFunctionCmdTest.java    From ghidra with Apache License 2.0 3 votes vote down vote up
@Test
public void testCreateThunkFunction() {

	int transactionID = program.startTransaction("Perform the TEST");

	CreateFunctionCmd createCmd = new CreateFunctionCmd(addr(0x1000));
	createCmd.applyTo(program);

	createCmd = new CreateFunctionCmd("thunky", addr(0x1007),
		new AddressSet(addr(0x1007), addr(0x1008)), SourceType.USER_DEFINED);
	createCmd.applyTo(program);

	Function func1007 = func(addr(0x1007));
	assertNotNull("Thunk function created", func1007);

	assertEquals("Function is a thunk", true, func1007.isThunk());

	assertEquals("Thunk function body size", 2, func1007.getBody().getNumAddresses());

	createCmd =
		new CreateFunctionCmd(null, addr(0x1007), null, SourceType.USER_DEFINED, true, true);
	boolean result = createCmd.applyTo(program);

	assertTrue("Recreate Thunk figure out body", result);

	func1007 = func(addr(0x1007));
	assertNotNull("Recreated thunk function", func1007);

	assertEquals("Recreated thunk function body length", 5,
		func1007.getBody().getNumAddresses());

	program.endTransaction(transactionID, true);
}