ghidra.app.cmd.function.CreateFunctionCmd Java Examples

The following examples show how to use ghidra.app.cmd.function.CreateFunctionCmd. 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: SymbolManagerTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveFunctionSymbolBecomesDefault() throws Exception {
	CreateFunctionCmd cmd = new CreateFunctionCmd("MyFunction", addr(0x0200),
		new AddressSet(addr(0x0200), addr(0x0280)), SourceType.USER_DEFINED);
	assertTrue(cmd.applyTo(program));

	Symbol s = st.getPrimarySymbol(addr(0x0200));
	assertEquals(SymbolType.FUNCTION, s.getSymbolType());
	assertEquals(false, s.getSource() == SourceType.DEFAULT);

	st.removeSymbolSpecial(s);

	s = st.getPrimarySymbol(addr(0x0200));
	assertNotNull(s);
	assertEquals("FUN_00000200", s.getName());
	assertEquals(SymbolType.FUNCTION, s.getSymbolType());
	assertEquals(true, s.getSource() == SourceType.DEFAULT);

	boolean removed = st.removeSymbolSpecial(s);
	assertEquals(false, removed);// Should not be able to remove default function symbol.
}
 
Example #2
Source File: SymbolMergeManager3Test.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
protected void createAnalyzedFunction(ProgramDB program, String entryPoint, String name) {
	Address addr = addr(program, entryPoint);
	try {
		CreateFunctionCmd functionCmd =
			new CreateFunctionCmd(name, addr, null, SourceType.ANALYSIS);
		assertTrue("Failed to create function " + name + " @ " + addr,
			functionCmd.applyTo(program));
		Function newFunction = program.getFunctionManager().getFunctionAt(addr);
		assertNotNull(newFunction);
		FunctionStackAnalysisCmd analyzeCmd = new FunctionStackAnalysisCmd(addr, true);
		assertTrue("Failed to analyze stack for " + name + " @ " + addr,
			analyzeCmd.applyTo(program));
	}
	catch (Exception e) {
		e.printStackTrace();
		Assert.fail("Can't create analyzed function @ " + entryPoint + e.getMessage());
	}
}
 
Example #3
Source File: AbstractListingMergeManagerTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
protected void createAnalyzedFunction(ProgramDB program, String entryPoint, String name) {
	Address addr = addr(program, entryPoint);
	try {
		CreateFunctionCmd functionCmd =
			new CreateFunctionCmd(name, addr, null, SourceType.ANALYSIS);
		assertTrue("Failed to create function " + name + " @ " + addr,
			functionCmd.applyTo(program));
		Function newFunction = program.getFunctionManager().getFunctionAt(addr);
		assertNotNull(newFunction);

		if (newFunction.isThunk()) {
			// TODO For thunk functions need to call thunk analyzer here before 
			// stack analysis occurs
		}
		FunctionStackAnalysisCmd analyzeCmd = new FunctionStackAnalysisCmd(addr, true);
		assertTrue("Failed to analyze stack for " + name + " @ " + addr,
			analyzeCmd.applyTo(program));
	}
	catch (Exception e) {
		failWithException("Can't create analyzed function @ " + entryPoint, e);
	}
}
 
Example #4
Source File: AddEditDialoglTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetPrimaryOnOtherLabel() throws Exception {
	Symbol s = getUniqueSymbol(program, "entry", null);
	Function function = program.getFunctionManager().getFunctionAt(s.getAddress());
	if (function == null) {
		tool.execute(new CreateFunctionCmd(s.getAddress()), program);
		program.flushEvents();
		waitForSwing();
		function = program.getFunctionManager().getFunctionAt(s.getAddress());
	}
	// add another label at this address
	AddLabelCmd cmd = new AddLabelCmd(addr(0x01006420), "fred", SourceType.USER_DEFINED);
	tool.execute(cmd, program);

	Symbol fredSymbol = getUniqueSymbol(program, "fred", null);
	assertTrue(!fredSymbol.isPrimary());

	editLabel(fredSymbol);
	setCheckbox(primaryCheckBox, true);
	pressOk();
	program.flushEvents();
	waitForSwing();
	assertEquals("fred", function.getName());
	assertNotNull(getUniqueSymbol(program, "entry", null));
}
 
Example #5
Source File: SymbolManagerTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveFunctionBecomesCodeSymbol() throws Exception {
	CreateFunctionCmd cmd = new CreateFunctionCmd("MyFunction", addr(0x0200),
		new AddressSet(addr(0x0200), addr(0x0280)), SourceType.USER_DEFINED);
	assertTrue(cmd.applyTo(program));

	Symbol s = st.getPrimarySymbol(addr(0x0200));
	assertEquals(SymbolType.FUNCTION, s.getSymbolType());

	program.getFunctionManager().removeFunction(addr(0x0200));

	s = st.getPrimarySymbol(addr(0x0200));
	assertNotNull(s);
	assertEquals("MyFunction", s.getName());
	assertEquals(SymbolType.LABEL, s.getSymbolType());

	boolean removed = st.removeSymbolSpecial(s);
	assertTrue(removed);// Should be able to remove function symbol after function.

	s = st.getPrimarySymbol(addr(0x0200));
	assertNull(s);
}
 
Example #6
Source File: AddEditDialoglTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testRenameFunction() throws Exception {

	Symbol s = getUniqueSymbol(program, "entry", null);
	Function function = program.getFunctionManager().getFunctionAt(s.getAddress());
	if (function == null) {
		tool.execute(new CreateFunctionCmd(s.getAddress()), program);
		program.flushEvents();
		waitForSwing();
		function = program.getFunctionManager().getFunctionAt(s.getAddress());
		s = getUniqueSymbol(program, "entry", null);
	}
	// add another label at this address
	AddLabelCmd cmd = new AddLabelCmd(addr(0x01006420), "fred", SourceType.USER_DEFINED);
	tool.execute(cmd, program);

	// now attempt to rename the entry label
	editLabel(s);
	assertEquals("entry", getText());
	setText("bob");
	pressOk();
	program.flushEvents();
	waitForSwing();
	assertEquals("bob", function.getName());
	assertTrue(function.getSymbol().isPrimary());
}
 
Example #7
Source File: SymbolManagerTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveDefaultFunctionSymbolWithFunction() throws Exception {
	CreateFunctionCmd cmd = new CreateFunctionCmd(addr(0x0200));
	assertTrue(cmd.applyTo(program));
	program.getFunctionManager().removeFunction(addr(0x0200));
	Symbol s = st.getPrimarySymbol(addr(0x0200));
	assertNull(s);
}
 
Example #8
Source File: SymbolManagerTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveDefaultSymbol() throws Exception {
	Address addr = addr(0x0200);
	CreateFunctionCmd cmd = new CreateFunctionCmd(addr);
	assertTrue(cmd.applyTo(program));
	Symbol s = st.getPrimarySymbol(addr(0x0200));
	assertNotNull(s);
	boolean removed = st.removeSymbolSpecial(s);
	assertTrue(!removed);// Shouldn't be able to remove default symbol.
	s = st.getPrimarySymbol(addr(0x0200));
	assertNotNull(s);
	assertEquals("FUN_00000200", s.getName());
}
 
Example #9
Source File: PlateFieldFactoryTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testShowExternalPlates() throws Exception {
	Symbol symbol = getUniqueSymbol(program, "entry");
	Address addr = symbol.getAddress();
	CodeUnit cu = program.getListing().getCodeUnitAt(addr);
	int transactionID = program.startTransaction("test");
	try {
		CreateFunctionCmd cmd = new CreateFunctionCmd(addr);
		cmd.applyTo(program);
		cu.setComment(CodeUnit.PLATE_COMMENT, null);
	}
	finally {
		program.endTransaction(transactionID, true);
	}
	program.flushEvents();
	waitForPostedSwingRunnables();
	cb.updateNow();

	goToService.goTo(addr);

	setBooleanOption(PlateFieldFactory.SHOW_EXT_ENTRY_PLATES_OPTION, true);

	assertTrue(cb.goToField(addr, PlateFieldFactory.FIELD_NAME, 1, 1));
	ListingTextField tf = (ListingTextField) cb.getCurrentField();
	assertEquals(3, tf.getNumRows());
	assertTrue(tf.getText().indexOf(PlateFieldFactory.EXT_ENTRY_PLATE_COMMENT) > 0);
}
 
Example #10
Source File: SymbolManagerTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddSymbolsToDefaultFunction() throws Exception {
	Address addr = addr(0x200);
	CreateFunctionCmd cmd = new CreateFunctionCmd(addr);
	assertTrue(cmd.applyTo(program));
	Symbol s = st.getPrimarySymbol(addr);
	assertNotNull(s);

	Symbol[] symbols = st.getSymbols(addr);
	assertEquals(1, symbols.length);
	assertEquals("FUN_00000200", symbols[0].getName());
	assertEquals(SymbolType.FUNCTION, symbols[0].getSymbolType());
	assertEquals(true, symbols[0].getSource() == SourceType.DEFAULT);

	st.createLabel(addr, "foo", SourceType.USER_DEFINED);

	symbols = st.getSymbols(addr);
	assertEquals(1, symbols.length);
	assertEquals("foo", symbols[0].getName());
	assertEquals(SymbolType.FUNCTION, symbols[0].getSymbolType());
	assertEquals(false, symbols[0].getSource() == SourceType.DEFAULT);

	st.createLabel(addr, "bar", SourceType.USER_DEFINED);

	symbols = st.getSymbols(addr);
	assertEquals(2, symbols.length);
	assertEquals("foo", symbols[0].getName());
	assertEquals(SymbolType.FUNCTION, symbols[0].getSymbolType());
	assertEquals(false, symbols[0].getSource() == SourceType.DEFAULT);
	assertEquals("bar", symbols[1].getName());
	assertEquals(SymbolType.LABEL, symbols[1].getSymbolType());
	assertEquals(false, symbols[1].getSource() == SourceType.DEFAULT);
}
 
Example #11
Source File: AddEditDialoglTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void createEntryFunction() throws Exception {
	Symbol s = getUniqueSymbol(program, "entry", null);
	Function f = program.getListing().getFunctionAt(s.getAddress());
	if (f == null) {
		Address addr = s.getAddress();
		AddressSet body = new AddressSet(addr, addr.getNewAddress(0x010065cc));
		body.addRange(addr.getNewAddress(0x10065a4), addr.getNewAddress(0x010065cc));
		CreateFunctionCmd cmd =
			new CreateFunctionCmd(null, addr, body, SourceType.USER_DEFINED);
		assertTrue(tool.execute(cmd, program));
	}
}
 
Example #12
Source File: AutoRenameLabelsScriptTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoRenameOnUserDefined() throws Exception {
	SymbolTable symbolTable = program.getSymbolTable();
	Symbol s1 = symbolTable.getPrimarySymbol(addr(0x010046cc));
	assertTrue(s1.getSource() == SourceType.DEFAULT);

	// create a function at 10046d0 so we don't have a default label
	CreateFunctionCmd cmd =
		new CreateFunctionCmd("My_Function1", addr(0x010046d0), null, SourceType.ANALYSIS);
	tool.execute(cmd, program);
	program.flushEvents();
	waitForPostedSwingRunnables();

	Symbol s2 = symbolTable.getPrimarySymbol(addr(0x010046d0));
	assertNotNull(s2);
	assertTrue(s2.getSource() != SourceType.DEFAULT);
	String s2Name = s2.getName();

	ProgramSelection sel = new ProgramSelection(addr(0x010046cc), addr(0x010046d0));
	tool.firePluginEvent(new ProgramSelectionPluginEvent("test", sel, program));
	waitForPostedSwingRunnables();

	ScriptTaskListener scriptID = env.runScript(script);

	JDialog dialog = waitForJDialog(tool.getToolFrame(), "Auto Rename Labels", 2000);
	final JTextField tf = findComponent(dialog, JTextField.class);
	runSwing(() -> tf.setText("My_Label"));
	pressButtonByText(dialog, "OK");
	waitForScriptCompletion(scriptID, 100000);

	program.flushEvents();
	waitForPostedSwingRunnables();
	s1 = symbolTable.getPrimarySymbol(addr(0x010046cc));
	assertEquals("My_Label1", s1.getName());
	// only dynamic label should get renamed
	s2 = symbolTable.getPrimarySymbol(addr(0x010046d0));
	assertTrue(!s2.getName().equals("My_Label2"));
	assertEquals(s2Name, s2.getName());
}
 
Example #13
Source File: ProgramBuilder.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a function by examining the instructions to find the body.
 *
 * @param addressString the address
 * @return the function
 */
public Function createFunction(String addressString) {
	startTransaction();
	Address address = addr(addressString);
	CreateFunctionCmd cmd = new CreateFunctionCmd(address);
	cmd.applyTo(program);
	endTransaction();

	return cmd.getFunction();
}
 
Example #14
Source File: FlatProgramAPI.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a function at entry point with the specified name
 * @param entryPoint the entry point of the function
 * @param name the name of the function or null for a default function
 * @return the new function or null if the function was not created
 */
public final Function createFunction(Address entryPoint, String name) {
	CreateFunctionCmd cmd = new CreateFunctionCmd(name, entryPoint, null,
		name != null ? SourceType.USER_DEFINED : SourceType.DEFAULT);
	if (cmd.applyTo(currentProgram, monitor)) {
		return currentProgram.getListing().getFunctionAt(entryPoint);
	}
	return null;
}
 
Example #15
Source File: OperandReferenceAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Check for any jumps to Externals (manufactured labels).
 * Any externals directly jumped to should be looked at as a call.
 *
 * Note: this shouldn't affect jumps in thunks, but beware...
 * @param monitor
 * @throws CancelledException
 */
private boolean checkForExternalJump(Program program, Reference reference, TaskMonitor monitor)
		throws CancelledException {
	// Check any direct jumps into the EXTERNAL memory section
	//   These don't return!
	if (externalBlock == null) {
		return false;
	}

	Address toAddr = reference.getToAddress();
	if (!externalBlock.contains(toAddr)) {
		return false;
	}
	Address fromAddr = reference.getFromAddress();
	Instruction instr = program.getListing().getInstructionAt(fromAddr);

	// override flow
	if (instr != null && instr.getFlowType().isJump()) {
		instr.setFlowOverride(FlowOverride.CALL_RETURN);
		// Get rid of any bad disassembly bookmark
		AddressSet set = new AddressSet(toAddr);
		program.getBookmarkManager()
				.removeBookmarks(set, BookmarkType.ERROR,
					Disassembler.ERROR_BOOKMARK_CATEGORY, monitor);
	}

	// make sure function created at destination
	Function func = program.getFunctionManager().getFunctionAt(toAddr);
	if (func == null) {
		CreateFunctionCmd createFuncCmd = new CreateFunctionCmd(null, toAddr,
			new AddressSet(toAddr, toAddr), SourceType.ANALYSIS);
		createFuncCmd.applyTo(program);
	}
	return true;
}
 
Example #16
Source File: SymbolManagerTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveSymbolWhereFunctionIs() throws Exception {
	Address addr = addr(0x0200);
	CreateFunctionCmd cmd =
		new CreateFunctionCmd("MyFunction", addr, null, SourceType.USER_DEFINED);
	assertTrue(cmd.applyTo(program));
	st.createLabel(addr, "lamp", SourceType.USER_DEFINED);
	st.createLabel(addr, "shade", SourceType.USER_DEFINED);

	Symbol[] symbols = st.getSymbols(addr);
	assertEquals(3, symbols.length);
	assertEquals("MyFunction", symbols[0].getName());
	assertEquals(SymbolType.FUNCTION, symbols[0].getSymbolType());
	assertEquals(false, symbols[0].getSource() == SourceType.DEFAULT);
	assertEquals("lamp", symbols[1].getName());
	assertEquals(SymbolType.LABEL, symbols[1].getSymbolType());
	assertEquals(false, symbols[1].getSource() == SourceType.DEFAULT);
	assertEquals("shade", symbols[2].getName());
	assertEquals(SymbolType.LABEL, symbols[2].getSymbolType());
	assertEquals(false, symbols[2].getSource() == SourceType.DEFAULT);

	Function f = program.getFunctionManager().getFunctionAt(addr);
	assertEquals("MyFunction", f.getSymbol().getName());

	st.removeSymbolSpecial(symbols[1]);

	symbols = st.getSymbols(addr);
	assertEquals(2, symbols.length);
	assertEquals("MyFunction", symbols[0].getName());
	assertEquals(SymbolType.FUNCTION, symbols[0].getSymbolType());
	assertEquals(false, symbols[0].getSource() == SourceType.DEFAULT);
	assertEquals("shade", symbols[1].getName());
	assertEquals(SymbolType.LABEL, symbols[1].getSymbolType());
	assertEquals(false, symbols[1].getSource() == SourceType.DEFAULT);

	f = program.getFunctionManager().getFunctionAt(addr);
	assertEquals("MyFunction", f.getSymbol().getName());
}
 
Example #17
Source File: SymbolManagerTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveDefaultFunctionSymbolBeforeFunction() throws Exception {
	CreateFunctionCmd cmd = new CreateFunctionCmd(addr(0x0200));
	assertTrue(cmd.applyTo(program));
	Symbol s = st.getPrimarySymbol(addr(0x0200));
	assertNotNull(s);
	boolean removed = st.removeSymbolSpecial(s);
	assertTrue(!removed);// Shouldn't be able to remove function symbol before function.
	s = st.getPrimarySymbol(addr(0x0200));
	assertNotNull(s);
	assertEquals("FUN_00000200", s.getName());
}
 
Example #18
Source File: FindNoReturnFunctionsAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
protected void fixCallingFunctionBody(Program cp, Address entry) throws CancelledException {
	if (createBookmarksEnabled) {
		cp.getBookmarkManager().setBookmark(entry, BookmarkType.ANALYSIS,
			"Non-Returning Function", "Non-Returning Function Found");
	}
	AddressSet fixedSet = new AddressSet();

	ReferenceIterator refIter = cp.getReferenceManager().getReferencesTo(entry);
	while (refIter.hasNext()) {
		Reference ref = refIter.next();
		if (!ref.getReferenceType().isCall()) {
			continue;
		}
		Address fromAddr = ref.getFromAddress();

		// don't fixup already fixed locations
		if (fixedSet.contains(fromAddr)) {
			continue;
		}
		Function fixFunc = cp.getFunctionManager().getFunctionContaining(fromAddr);
		if (fixFunc == null) {
			continue;
		}
		AddressSetView oldBody = fixFunc.getBody();

		AddressSetView newBody = CreateFunctionCmd.getFunctionBody(cp, fixFunc.getEntryPoint());
		if (oldBody.equals(newBody)) {
			fixedSet.add(newBody);
			continue;
		}
		CreateFunctionCmd.fixupFunctionBody(cp, fixFunc, monitor);
		Function newFunc = cp.getFunctionManager().getFunctionContaining(fromAddr);

		if (newFunc != null) {
			newBody = newFunc.getBody();
			fixedSet.add(newBody);
		}
	}
}
 
Example #19
Source File: FindNoReturnFunctionsAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Set function to non-returning
 * 
 * @param cp program
 * @param entry function entry to change to non-returning
 */
private void setFunctionNonReturning(Program cp, Address entry) {
	Function func = cp.getFunctionManager().getFunctionAt(entry);
	if (func == null) {
		CreateFunctionCmd createFunctionCmd = new CreateFunctionCmd(entry);
		createFunctionCmd.applyTo(cp);
		func = cp.getFunctionManager().getFunctionAt(entry);
		if (func == null) {
			return;
		}
	}
	// if func is null, create one at entry
	func.setNoReturn(true);
}
 
Example #20
Source File: CallFixupAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Fix the bodies of all functions that called the non-returning function.
 * 
 * @param program containing the functions
 * @param callLocations that need the bodies of the functions containing them fixed
 * @param monitor to allow canceling
 * 
 * @return the set of all repaired function entry points
 * 
 * @throws CancelledException
 */
protected AddressSet fixCallingFunctionBody(Program program, AddressSet callLocations,
		TaskMonitor monitor) throws CancelledException {

	AddressSet fixedSet = new AddressSet();
	AddressSet repairedFunctions = new AddressSet();

	AddressIterator addrIter = callLocations.getAddresses(true);
	while (addrIter.hasNext()) {
		Address fromAddr = addrIter.next();

		// don't fixup already fixed locations
		if (fixedSet.contains(fromAddr)) {
			continue;
		}
		Function fixFunc = program.getFunctionManager().getFunctionContaining(fromAddr);
		if (fixFunc == null) {
			continue;
		}

		// should always add fixed functions. any function could have an internal call to a non-returning function
		// the internal flows would have changed requiring other analysis to know about the changed body
		repairedFunctions.add(fixFunc.getEntryPoint());

		CreateFunctionCmd.fixupFunctionBody(program, fixFunc, monitor);

		fixedSet.add(fixFunc.getBody()); // new body
	}

	return repairedFunctions;
}
 
Example #21
Source File: EntryPointAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void doDisassembly(Program program, TaskMonitor monitor, Set<Address> entries) {

		if (entries.isEmpty()) {
			return;
		}

		Iterator<Address> iter = entries.iterator();
		AddressSet disSet = new AddressSet();
		while (iter.hasNext()) {
			Address entry = iter.next();
			disSet.addRange(entry, entry);
		}
		//DisassembleCommand cmd = new DisassembleCommand(disSet, null, true);
		//cmd.applyTo(program, monitor);
		// Disassemble all again
		Disassembler dis = Disassembler.getDisassembler(program, monitor, null);
		AddressSet disassembledSet = dis.disassemble(disSet, null, true);
		AutoAnalysisManager.getAnalysisManager(program).codeDefined(disassembledSet);

		AddressSet functionEntries = new AddressSet();
		Listing listing = program.getListing();
		for (Address addr : entries) {
			if (listing.getInstructionAt(addr) != null) {
				Symbol s = program.getSymbolTable().getPrimarySymbol(addr);
				if (s != null && s.isExternalEntryPoint() &&
					listing.getFunctionContaining(addr) == null) {
					functionEntries.addRange(addr, addr);
				}
			}
		}
		if (!functionEntries.isEmpty()) {
			CreateFunctionCmd createFunctionCmd = new CreateFunctionCmd(functionEntries);
			createFunctionCmd.applyTo(program, monitor);
		}
	}
 
Example #22
Source File: SymbolManagerTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveFunctionSymbolAfterFunction() throws Exception {
	CreateFunctionCmd cmd = new CreateFunctionCmd("MyFunction", addr(0x0200),
		new AddressSet(addr(0x0200), addr(0x0280)), SourceType.USER_DEFINED);
	assertTrue(cmd.applyTo(program));
	program.getFunctionManager().removeFunction(addr(0x0200));
	Symbol s = st.getPrimarySymbol(addr(0x0200));
	assertNotNull(s);
	boolean removed = st.removeSymbolSpecial(s);
	assertTrue(removed);// Should be able to remove function symbol after function.
	s = st.getPrimarySymbol(addr(0x0200));
	assertNull(s);
}
 
Example #23
Source File: SymbolManagerTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveFunctionSymbolBecomesExistingCodeSymbol() throws Exception {
	Address entryPt = addr(0x0200);
	CreateFunctionCmd cmd = new CreateFunctionCmd("MyFunction", entryPt,
		new AddressSet(addr(0x0200), addr(0x0280)), SourceType.USER_DEFINED);
	assertTrue(cmd.applyTo(program));

	st.createLabel(entryPt, "Bob", SourceType.USER_DEFINED);

	Symbol s = st.getPrimarySymbol(entryPt);
	assertEquals(SymbolType.FUNCTION, s.getSymbolType());
	assertEquals(false, s.getSource() == SourceType.DEFAULT);

	Symbol[] symbols = st.getSymbols(entryPt);
	assertEquals(2, symbols.length);
	assertEquals("MyFunction", symbols[0].getName());
	assertEquals(SymbolType.FUNCTION, symbols[0].getSymbolType());
	assertEquals(false, symbols[0].getSource() == SourceType.DEFAULT);
	assertEquals("Bob", symbols[1].getName());
	assertEquals(SymbolType.LABEL, symbols[1].getSymbolType());
	assertEquals(false, symbols[1].getSource() == SourceType.DEFAULT);

	st.removeSymbolSpecial(s);

	symbols = st.getSymbols(entryPt);
	assertEquals(1, symbols.length);
	assertEquals("Bob", symbols[0].getName());
	assertEquals(SymbolType.FUNCTION, symbols[0].getSymbolType());
	assertEquals(false, symbols[0].getSource() == SourceType.DEFAULT);

	assertEquals("Bob", program.getFunctionManager().getFunctionAt(entryPt).getName());
}
 
Example #24
Source File: SwitchOverride.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void run() throws Exception {
	ArrayList<Address> destlist = new ArrayList<Address>();
	Address branchind = null;
	
	if (currentSelection != null && !currentSelection.isEmpty()) {
		branchind = collectSelectedJumpData(currentProgram.getListing(),currentSelection,destlist);
	} else {
		branchind = collectPointJumpData(currentProgram.getListing(),currentLocation.getAddress(),destlist);
	}
	
	if (branchind==null) {
		println("Please highlight or place the cursor on the instruction performing the computed jump");
		return;
	}
	if (destlist.size()==0) {
		println("Please highlight destination instructions in addition to instruction performing switch");
		println(" Or put CONDITIONAL_JUMP destination references at the branching instruction");
		return;
	}
	Function function = this.getFunctionContaining(branchind);
	if (function==null) {
		println("Computed jump instruction must be in a Function body.");
		return;
	}
	
	Instruction instr = currentProgram.getListing().getInstructionAt(branchind);
	for (Address address : destlist) {
		instr.addOperandReference(0, address, RefType.COMPUTED_JUMP, SourceType.USER_DEFINED);
	}

	// Allocate an override jumptable
	JumpTable jumpTab = new JumpTable(branchind,destlist,true);
	jumpTab.writeOverride(function);
	
	// fixup the body now that there are jump references
	CreateFunctionCmd.fixupFunctionBody(currentProgram, function, monitor);
}
 
Example #25
Source File: DecompilerNavigationTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void createThunkToExternal(String addressString) throws Exception {

		int txId = program.startTransaction("Set External Location");
		try {

			program.getExternalManager().setExternalPath("ADVAPI32.dll", "/FILE1", true);

			Address address = addr(addressString);
			CreateFunctionCmd cmd = new CreateFunctionCmd(address);
			cmd.applyTo(program);

			String extAddress = "0x1001000";
			ExternalManager em = program.getExternalManager();

			// "ADVAPI32.dll", "externalFunctionXyz", "_Zxyz"
			ExternalLocation externalLocation =
				em.addExtFunction(Library.UNKNOWN, "_Zxyz", addr(extAddress), SourceType.IMPORTED);
			Library lib = em.addExternalLibraryName("ADVAPI32.dll", SourceType.IMPORTED);
			externalLocation.setName(lib, "externalFunctionXyz", SourceType.IMPORTED);

			Function function = program.getFunctionManager().getFunctionAt(addr(addressString));
			function.setThunkedFunction(externalLocation.getFunction());
		}
		finally {
			program.endTransaction(txId, true);
		}

		program.flushEvents();
		waitForSwing();
	}
 
Example #26
Source File: HighSymbolTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void createFunction(String address) {
	modifyProgram(p -> {
		Address addr = p.getAddressFactory().getAddress(address);
		CreateFunctionCmd createCmd = new CreateFunctionCmd(addr);
		createCmd.applyTo(p);
	});
}
 
Example #27
Source File: AddLabelCmdTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private Function getTestFunction() {
	FunctionManager fm = notepad.getFunctionManager();
	Function function = fm.getFunctionAt(addr(0x0));
	if (function == null) {
		execute(new CreateFunctionCmd(addr(0x0)));
		function = fm.getFunctionAt(addr(0x0));
	}
	return function;
}
 
Example #28
Source File: FixupNoReturnFunctionsScript.java    From ghidra with Apache License 2.0 4 votes vote down vote up
protected void fixCallingFunctionBody(Program cp, Address entry) throws CancelledException {
	println("** NoReturn func " + cp.getFunctionManager().getFunctionAt(entry).getName());

	AddressSet fixedSet = new AddressSet();

	ReferenceIterator refIter = cp.getReferenceManager().getReferencesTo(entry);
	while (refIter.hasNext()) {
		Reference ref = refIter.next();
		if (!ref.getReferenceType().isCall()) {
			continue;
		}
		Address fromAddr = ref.getFromAddress();

		// don't fixup already fixed locations
		if (fixedSet.contains(fromAddr)) {
			continue;
		}
		Function fixFunc = cp.getFunctionManager().getFunctionContaining(fromAddr);
		if (fixFunc == null) {
			continue;
		}
		AddressSetView oldBody = fixFunc.getBody();

		AddressSetView newBody = CreateFunctionCmd.getFunctionBody(cp, fixFunc.getEntryPoint());
		if (oldBody.equals(newBody)) {
			fixedSet.add(newBody);
			continue;
		}
		CreateFunctionCmd.fixupFunctionBody(cp, fixFunc, monitor);
		Function newFunc = cp.getFunctionManager().getFunctionContaining(fromAddr);

		if (newFunc != null) {
			newBody = newFunc.getBody();
			fixedSet.add(newBody);

			if (!oldBody.equals(newBody)) {
				println("Fixed func at " + oldBody.getMinAddress() + " to " +
					newBody.getMinAddress());
			}
		}
	}
}
 
Example #29
Source File: SymbolManagerTest.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Test
public void testRemoveFunctionSymbolBecomesExistingCodeSymbolWithNamespace() throws Exception {
	Namespace oldNamespace = st.createNameSpace(null, "OldNameSpace", SourceType.USER_DEFINED);
	Namespace newNamespace = st.createNameSpace(null, "NewNameSpace", SourceType.USER_DEFINED);
	Address entryPt = addr(0x0200);
	CreateFunctionCmd cmd = new CreateFunctionCmd("MyFunction", entryPt,
		new AddressSet(addr(0x0200), addr(0x0280)), SourceType.USER_DEFINED);
	assertTrue(cmd.applyTo(program));
	Symbol functionSym = program.getFunctionManager().getFunctionAt(entryPt).getSymbol();
	Symbol conflictSym = st.createLabel(addr(0x0230), "Bob", SourceType.USER_DEFINED);// put a conflict symbol in.
	conflictSym.setNamespace(oldNamespace);

	Symbol otherSym = st.createLabel(entryPt, "Bob", SourceType.USER_DEFINED);
	functionSym.setNamespace(oldNamespace);
	otherSym.setNamespace(newNamespace);

	Symbol s = st.getPrimarySymbol(entryPt);
	assertEquals(SymbolType.FUNCTION, s.getSymbolType());
	assertEquals(false, s.getSource() == SourceType.DEFAULT);

	Symbol[] symbols = st.getSymbols(entryPt);
	assertEquals(2, symbols.length);
	assertEquals("MyFunction", symbols[0].getName());
	assertEquals(SymbolType.FUNCTION, symbols[0].getSymbolType());
	assertEquals(oldNamespace, symbols[0].getParentNamespace());
	assertEquals(false, symbols[0].getSource() == SourceType.DEFAULT);
	assertEquals("Bob", symbols[1].getName());
	assertEquals(SymbolType.LABEL, symbols[1].getSymbolType());
	assertEquals(newNamespace, symbols[1].getParentNamespace());
	assertEquals(false, symbols[1].getSource() == SourceType.DEFAULT);

	st.removeSymbolSpecial(s);

	symbols = st.getSymbols(entryPt);
	assertEquals(1, symbols.length);
	assertEquals("Bob", symbols[0].getName());
	assertEquals(SymbolType.FUNCTION, symbols[0].getSymbolType());
	assertEquals(newNamespace, symbols[0].getParentNamespace());
	assertEquals(false, symbols[0].getSource() == SourceType.DEFAULT);

	assertEquals("Bob", program.getFunctionManager().getFunctionAt(entryPt).getName());
}
 
Example #30
Source File: ARMPreAnalyzer.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public boolean added(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log) {

	String switch_fn = "\\x01\\xc0\\x5e\\xe5" + // ldrb ip,[lr,#-0x1]
		"\\x0c\\x00\\x53\\xe1" + // cmp r3,ip
		"(" + "\\x03\\x30\\xde\\x37" + // ldrbcc r3,[lr,r3]
		"\\x0c\\x30\\xde\\x27" + // ldrbcs r3,[lr,ip]
		"|" +                    // OR
		"\\x0c\\x30\\xde\\x27" + // ldrbcs r3,[lr,ip]
		"\\x03\\x30\\xde\\x37" + // ldrbcc r3,[lr,r3]
		")" + "(" + "\\x83\\xc0\\x8e\\xe0" + // add ip,lr,r3, lsl #0x1
		"\\x1c\\xff\\x2f\\xe1" + // bx ip
		"|" +                    // OR
		"\\x83\\xe0\\x8e\\xe0" + // add lr,lr,r3, lsl #0x1
		"\\x1e\\xff\\x2f\\xe1" + // bx lr
		")";

	RegExSearchData searchData = RegExSearchData.createRegExSearchData(switch_fn);

	SearchInfo searchInfo = new SearchInfo(searchData, 30, false, true, 4, false, null);

	AddressSet intersection =
		program.getMemory().getLoadedAndInitializedAddressSet().intersect(set);
	RegExMemSearcherAlgorithm searcher =
		new RegExMemSearcherAlgorithm(searchInfo, intersection, program, true);

	ListAccumulator<MemSearchResult> accumulator = new ListAccumulator<>();
	searcher.search(accumulator, monitor);
	List<MemSearchResult> results = accumulator.asList();

	// create a function here with the correct call fixup
	for (MemSearchResult result : results) {

		Address addr = result.getAddress();

		// disassemble ARM
		DisassembleCommand disassembleCommand = new DisassembleCommand(addr, null, true);
		disassembleCommand.applyTo(program);

		// create function
		CreateFunctionCmd createFunctionCmd = new CreateFunctionCmd(addr, false);
		createFunctionCmd.applyTo(program);

		// set call fixup
		Function func = program.getFunctionManager().getFunctionAt(addr);
		if (func != null) {
			func.setCallFixup("switch8_r3");
		}

		BookmarkManager bookmarkManager = program.getBookmarkManager();
		bookmarkManager.setBookmark(addr, BookmarkType.ANALYSIS, getName(),
			"Found Switch8_r3 Function");
	}

	return true;
}