Java Code Examples for ghidra.app.cmd.function.CreateFunctionCmd#applyTo()

The following examples show how to use ghidra.app.cmd.function.CreateFunctionCmd#applyTo() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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;
}
 
Example 9
Source File: AbstractJavaAnalyzer.java    From ghidra with Apache License 2.0 4 votes vote down vote up
protected Function createFunction(Program program, Address entryPoint) {
	CreateFunctionCmd cmd = new CreateFunctionCmd(entryPoint);
	cmd.applyTo(program);
	return program.getListing().getFunctionAt(entryPoint);
}
 
Example 10
Source File: FileFormatAnalyzer.java    From ghidra with Apache License 2.0 4 votes vote down vote up
protected Function createFunction(Program program, Address entryPoint) {
	CreateFunctionCmd cmd = new CreateFunctionCmd(entryPoint);
	cmd.applyTo(program);
	return program.getListing().getFunctionAt(entryPoint);
}
 
Example 11
Source File: BadInstructionCleanup.java    From ghidra with Apache License 2.0 4 votes vote down vote up
public void cleanup(Address ba) throws Exception {

		Program p = currentProgram;
		BookmarkManager bmgr = p.getBookmarkManager();
		Bookmark bm = bmgr.getBookmark(ba, "Error", "Bad Instruction");
		Listing listing = p.getListing();
		if (bm != null) {
			Register contextReg = p.getProgramContext().getRegister("TMode");
			Address ba_end = ba;
			if (listing.getCodeUnitAt(ba) != null) {
				ba_end = listing.getCodeUnitAt(ba).getMaxAddress();
			}
			while (getDataContaining(ba_end.add(4)) != null) {
				ba_end = getDataContaining(ba_end.add(4)).getMaxAddress();
			}
			while (getDataContaining(ba.subtract(1)) != null) {
				ba = getDataContaining(ba.subtract(1)).getAddress();
			}
			listing.clearCodeUnits(ba, ba_end, false);
			if (contextReg != null) {
				Address paddr = listing.getInstructionBefore(ba).getAddress();
				RegisterValue rv;
				if (paddr != null) {
					rv = p.getProgramContext().getRegisterValue(contextReg,
							paddr);
					p.getProgramContext().setRegisterValue(ba, ba_end, rv);
				}
			}
			DisassembleCommand cmd = new DisassembleCommand(ba, null, true);
			cmd.applyTo(p, monitor);
			Function f = getFunctionBefore(ba);
			if (f != null) {
				CreateFunctionCmd cf = new CreateFunctionCmd(f.getName(), f
						.getEntryPoint(), null, f.getSymbol().getSource(),
						true, true);
				cf.applyTo(p);
			}
			bmgr.removeBookmark(bm);
			bmgr.setBookmark(ba, "Analysis", "Cleanup",
					"Converted invalid pointer to code");
		}
	}
 
Example 12
Source File: ApplyFunctions.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private static Function createFunction(Program program, Address entryPoint) {
	CreateFunctionCmd fCmd = new CreateFunctionCmd(entryPoint);
	fCmd.applyTo(program);
	return program.getListing().getFunctionAt(entryPoint);
}
 
Example 13
Source File: FrameDescriptionEntry.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a Frame Description Entry (FDE) at the address
 * specified.
 * <br>Note: This method must get called before any of the "get..." methods.
 * 
 * @param fdeBaseAddress Address where the FDE should be created.
 * @return a region descriptor which holds information about this FDE. Otherwise, null.
 * @throws MemoryAccessException if memory for the FDE or its associated data can't be accessed
 * @throws ExceptionHandlerFrameException if there is an error creating the FDE information.
 */
public RegionDescriptor create(Address fdeBaseAddress)
		throws MemoryAccessException, ExceptionHandlerFrameException {

	if (fdeBaseAddress == null || monitor.isCancelled()) {
		return null;
	}

	Address addr = fdeBaseAddress;
	baseAddress = fdeBaseAddress;
	MemoryBlock ehblock = program.getMemory().getBlock(addr);
	RegionDescriptor region = new RegionDescriptor(ehblock);

	// See if processing should stop due to the current length field == 0
	if (program.getMemory().getInt(addr) == 0) {
		markEndOfFrame(addr);
		endOfFrame = true;
		return null;
	}

	// Begin creating the fields that compose the FDE.
	addr = createFdeLength(addr);
	addr = createExtendedLength(addr);
	addr = createCiePointer(addr);
	addr = createPcBegin(addr, region);
	addr = createPcRange(addr); // This can return null.

	AddressRange addrRange = new AddressRangeImpl(pcBeginAddr, pcEndAddr);

	region.setIPRange(addrRange);

	try {
		/* Create a function at the pcBegin Addr address */
		CreateFunctionCmd createFuncCmd = new CreateFunctionCmd(pcBeginAddr);
		createFuncCmd.applyTo(program);
	}
	catch (AddressOutOfBoundsException e) {
		throw new ExceptionHandlerFrameException(
			e.getMessage() + ": " + pcBeginAddr.toString() + " + " + intPcRange);
	}

	// If some FDE data remains, then it is the augmentation fields or call frame instructions.
	if (curSize < intLength) {

		// Get the Augmentation String from the CIE
		cieAugmentationString = cie.getAugmentationString();

		addr = createAugmentationFields(addr); // If addr is originally null, it remains null.

		/*
		 * Add call frame instructions and possible padding
		 */
		if (!hasExtLength) {
			if (addr != null && curSize < intLength) {
				// Create the call frame instructions w/ the remaining bytes.
				addr = createCallFrameInstructions(addr);
			}
		}
		else {
			throw new ExceptionHandlerFrameException(
				"ExtLength is not completely implemented.");
		}
	}

	createFdeLabel(fdeBaseAddress);

	region.setFrameDescriptorEntry(this);

	createAugmentationInfo(ehblock, region);

	nextAddress = addr; // This could be null.
	return region;
}
 
Example 14
Source File: CopyPasteCommentsTest.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private void setupProgramTwo() throws Exception {
	Address min = addr(programTwo, 0x31b);
	Address max = addr(programTwo, 0x0343);
	Listing listing = programTwo.getListing();

	// create a function over the range 0x31b through 0x0343.
	int transactionID = programTwo.startTransaction("test");

	CreateFunctionCmd fnCmd =
		new CreateFunctionCmd(null, min, new AddressSet(min, max), SourceType.ANALYSIS);
	fnCmd.applyTo(programTwo);

	Function function = programTwo.getListing().getFunctionAt(min);

	// add a function comment.
	function.setComment("my function comment");
	// add some Plate, Pre, and Post comments within this function.
	CodeUnit cu = listing.getCodeUnitAt(addr(programTwo, 0x0320));
	cu.setComment(CodeUnit.PLATE_COMMENT, "My Plate Comment");
	cu.setComment(CodeUnit.POST_COMMENT, "My Post comment");

	cu = listing.getCodeUnitAt(addr(programTwo, 0x326));
	cu.setComment(CodeUnit.PLATE_COMMENT, "More Plate Comments (1)");
	cu.setComment(CodeUnit.POST_COMMENT, "More Post comments (1)");
	cu.setComment(CodeUnit.EOL_COMMENT, "More EOL comments (1)");

	cu = listing.getCodeUnitAt(addr(programTwo, 0x32a));
	cu.setComment(CodeUnit.PLATE_COMMENT, "More Plate Comments (2)");
	cu.setComment(CodeUnit.POST_COMMENT, "More Post comments (2)");
	cu.setComment(CodeUnit.EOL_COMMENT, "More EOL comments (2)");

	// Edit the label at 0x32d (RSR05) and make it part of a scope
	Symbol symbol = getUniqueSymbol(programTwo, "RSR05", null);

	assertNotNull(symbol);
	SymbolTable st2 = programTwo.getSymbolTable();
	Namespace ns = st2.createNameSpace(null, "MyNamespace", SourceType.USER_DEFINED);
	symbol.setNamespace(ns);

	programTwo.endTransaction(transactionID, true);
}