Java Code Examples for ghidra.program.model.listing.Function#getEntryPoint()

The following examples show how to use ghidra.program.model.listing.Function#getEntryPoint() . 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: DecompilerVariable.java    From ghidra with Apache License 2.0 6 votes vote down vote up
public Address getAddress() {
	Address minAddress = variable.getMinAddress();
	if (minAddress != null) {
		return minAddress;
	}

	// Note: some variables do not have an address, such as function parameters.  In that
	//       case, we will walk backwards until we hit the function, using that address.
	ClangNode parent = variable.Parent();
	while (parent != null) {
		if (parent instanceof ClangFunction) {
			HighFunction highFunction = ((ClangFunction) parent).getHighFunction();
			Function function = highFunction.getFunction();
			Address entry = function.getEntryPoint();
			return entry;
		}

		Address parentAddress = parent.getMinAddress();
		if (parentAddress != null) {
			return parentAddress;
		}
		parent = parent.Parent();
	}

	return null;
}
 
Example 2
Source File: FindReferencesToSymbolAction.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private Address getDecompilerSymbolAddress(ProgramLocation location) {

		if (!(location instanceof DecompilerLocation)) {
			return null;
		}

		ClangToken token = ((DecompilerLocation) location).getToken();
		if (!(token instanceof ClangFuncNameToken)) {
			return null;
		}

		Program program = location.getProgram();
		Function function = DecompilerUtils.getFunction(program, (ClangFuncNameToken) token);
		if (function != null) {
			return function.getEntryPoint();
		}

		return null;
	}
 
Example 3
Source File: SubToolContext.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private VTMatch getExistingMatch(Function sourceFunction, Function destinationFunction) {
	if (sourceFunction == null || destinationFunction == null) {
		return null;
	}

	Address sourceAddress = sourceFunction.getEntryPoint();
	Address destinationAddress = destinationFunction.getEntryPoint();
	VTController controller = plugin.getController();
	VTSession session = controller.getSession();
	List<VTMatchSet> matchSets = session.getMatchSets();
	for (VTMatchSet matchSet : matchSets) {
		Collection<VTMatch> matches = matchSet.getMatches(sourceAddress, destinationAddress);
		for (VTMatch nextMatch : matches) {
			return nextMatch;
		}
	}
	return null;
}
 
Example 4
Source File: DecompilerProvider.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public void goToFunction(Function function, boolean newWindow) {

	GoToService service = tool.getService(GoToService.class);
	if (service == null) {
		return;
	}

	Navigatable navigatable = this;
	if (newWindow) {
		DecompilerProvider newProvider = plugin.createNewDisconnectedProvider();
		navigatable = newProvider;
	}

	Symbol symbol = function.getSymbol();
	ExternalManager externalManager = program.getExternalManager();
	ExternalLocation externalLocation = externalManager.getExternalLocation(symbol);
	if (externalLocation != null) {
		service.goToExternalLocation(navigatable, externalLocation, true);
	}
	else {
		Address address = function.getEntryPoint();
		service.goTo(navigatable, new ProgramLocation(program, address), program);
	}
}
 
Example 5
Source File: IterateFunctionsByAddressScript.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void iterateForward() {
	// Use the iterator, there is no easy way to use the function iterator on addresses
	//   If the function begins at address zero, you won't get the function without
	//   a lot of extra more complicated code.
	FunctionIterator fiter = currentProgram.getFunctionManager().getFunctions(true);

	int count = 0;
	while (fiter.hasNext()) {
		Function function = fiter.next();

		if (monitor.isCancelled()) {
			break;
		}

		String string = count + "  :  " + function.getName() + " @ " + function.getEntryPoint();

		monitor.setMessage(string);

		println(string);

		count++;
	}
	println("found " + count + " functions ");
}
 
Example 6
Source File: FunctionTagPluginScreenShots.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Simulates a location change on the listing so the dialog thinks the user has
 * navigated to a function.
 * 
 * @param provider the component provider
 */
private void navigateToFunction(FunctionTagsComponentProvider provider) {
	FunctionIterator iter = program.getFunctionManager().getFunctions(true);
	while (iter.hasNext()) {
		Function func = iter.next();
		Address addr = func.getEntryPoint();
		ProgramLocation loc = new ProgramLocation(program, addr);
		provider.locationChanged(loc);

		// We only need to find one function, so exit after we've got one.
		return;
	}
}
 
Example 7
Source File: FunctionCallingConventionTableColumn.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public ProgramLocation getProgramLocation(Function rowObject, Settings settings,
		Program program, ServiceProvider serviceProvider) {
	if (rowObject == null) {
		return null;
	}

	Address address = rowObject.getEntryPoint();
	String signature = rowObject.getSignature().getPrototypeString();
	return new FunctionCallingConventionFieldLocation(program, address, address, 0, signature);
}
 
Example 8
Source File: FGActionManager.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void goHome() {
	Function function = controller.getGraphedFunction();
	ProgramLocation homeLocation =
		new ProgramLocation(provider.getCurrentProgram(), function.getEntryPoint());
	if (SystemUtilities.isEqual(provider.getCurrentLocation(), homeLocation)) {
		// already at the right location, just make sure we are on the screen and selected
		provider.displayLocation(homeLocation);
	}
	else {
		provider.internalGoTo(homeLocation, provider.getCurrentProgram());
	}
}
 
Example 9
Source File: CallTreeProvider.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void updateOutgoingReferences(Function function) {
	GTreeNode rootNode = null;
	if (function == null) {
		rootNode = new EmptyRootNode();
	}
	else {
		rootNode = new OutgoingCallsRootNode(currentProgram, function, function.getEntryPoint(),
			filterDuplicates.isSelected(), recurseDepth);
	}

	outgoingTree.setRootNode(rootNode);
}
 
Example 10
Source File: ExternalCodeBrowserNavigationTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void addThunkToExternalFunction(String libraryName, String label,
		Address thunkAddress) {
	ExternalLocation externalLocation =
		program.getExternalManager().getExternalLocation(libraryName, label);
	Function extFunction = externalLocation.getFunction();

	CreateThunkFunctionCmd cmd = new CreateThunkFunctionCmd(thunkAddress,
		new AddressSet(thunkAddress), extFunction.getEntryPoint());
	int txId = program.startTransaction("Add Thunk");
	cmd.applyTo(program);
	program.endTransaction(txId, true);
}
 
Example 11
Source File: FidProgramSeeker.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public static ArrayList<Function> getParents(Function function,boolean followThunks) {
	Program program = function.getProgram();
	FunctionManager functionManager = program.getFunctionManager();
	ReferenceManager referenceManager = program.getReferenceManager();
	HashSet<Address> alreadyDone = new HashSet<Address>();
	ArrayList<Function> funcList = new ArrayList<Function>();
	int size = 0;
	Address curAddr = function.getEntryPoint();
	Address[] thunkAddresses = null;
	if (followThunks) {
		thunkAddresses = function.getFunctionThunkAddresses();
		if (thunkAddresses != null)
			size = thunkAddresses.length;
	}
	int pos = -1;
	for(;;) {
		ReferenceIterator referenceIterator = referenceManager.getReferencesTo(curAddr);
		for (Reference reference : referenceIterator) {
			// monitor.checkCanceled();
			Address fromAddress = reference.getFromAddress();
			if (reference.getReferenceType().isCall()) {
				Function par = functionManager.getFunctionContaining(fromAddress);
				if (par != null) {
					Address entryPoint = par.getEntryPoint();
					if (!alreadyDone.contains(entryPoint)) {
						funcList.add(par);
						alreadyDone.add(entryPoint);
					}
				}
			}
		}
		pos += 1;
		if (pos >= size) break;
		curAddr = thunkAddresses[pos];
	}

	return funcList;
}
 
Example 12
Source File: FunctionNameTableColumn.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public ProgramLocation getProgramLocation(Address rowObject, Settings settings,
		Program program, ServiceProvider serviceProvider) {
	Function function = getFunctionContaining(rowObject, program);
	if (function != null) {
		return new FunctionNameFieldLocation(program, function.getEntryPoint(), 0,
			function.getPrototypeString(false, false), function.getName());
	}
	return null;
}
 
Example 13
Source File: CreateFunctionDefinitionAction.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Method called when the action is invoked.
 * @param ActionEvent details regarding the invocation of this action
 */
@Override
public void actionPerformed(ListingActionContext context) {
	Function function = funcPlugin.getFunction(context);
	if (function == null) {
		return;
	}
	Address entry = function.getEntryPoint();
	funcPlugin.execute(context.getProgram(), new CreateFunctionDefinitionCmd(entry,
		funcPlugin.getTool()));
}
 
Example 14
Source File: FunctionParameterCountTableColumn.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public ProgramLocation getProgramLocation(Address rowObject, Settings settings,
		Program program, ServiceProvider serviceProvider) {
	Function function = getFunctionContaining(rowObject, program);
	if (function != null) {
		return new FunctionNameFieldLocation(program, function.getEntryPoint(), 0,
			function.getPrototypeString(false, false), function.getName());
	}
	return null;
}
 
Example 15
Source File: FunctionSearchAddressIterator.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public Address next() {
	Function function = functionIterator.next();
	return function.getEntryPoint();
}
 
Example 16
Source File: FunctionToProgramLocationTableRowMapper.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public ProgramLocation map(Function rowObject, Program program, ServiceProvider serviceProvider) {
	return new FunctionSignatureFieldLocation(program, rowObject.getEntryPoint(), null, 0,
		rowObject.getPrototypeString(false, false));
}
 
Example 17
Source File: DecompInterface.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Decompile function
 * @param func function to be decompiled
 * @param timeoutSecs if decompile does not complete in this time a null value
 * will be returned and a timeout error set.
 * @param monitor optional task monitor which may be used to cancel decompile
 * @return decompiled function text
 */
public synchronized DecompileResults decompileFunction(Function func, int timeoutSecs,
		TaskMonitor monitor) {

	decompileMessage = "";
	if (monitor != null && monitor.isCancelled()) {
		return null;
	}

	LimitedByteBuffer res = null;
	if (monitor != null) {
		monitor.addCancelledListener(monitorListener);
	}

	if (program == null) {
		return new DecompileResults(func, pcodelanguage, null, dtmanage, decompileMessage, null,
			DecompileProcess.DisposeState.DISPOSED_ON_CANCEL,
			false /* cancelled--doesn't matter */);
	}

	try {
		Address funcEntry = func.getEntryPoint();
		if (debug != null) {
			debug.setFunction(func);
		}
		decompCallback.setFunction(func, funcEntry, debug);
		String addrstring = Varnode.buildXMLAddress(funcEntry);
		verifyProcess();
		res = decompProcess.sendCommand1ParamTimeout("decompileAt", addrstring.toString(),
			timeoutSecs);
		decompileMessage = decompCallback.getNativeMessage();
	}
	catch (Exception ex) {
		decompileMessage = "Exception while decompiling " + func.getEntryPoint() + ": " +
			ex.getMessage() + '\n';
	}
	finally {
		if (monitor != null) {
			monitor.removeCancelledListener(monitorListener);
		}
	}
	if (debug != null) {
		debug.shutdown(pcodelanguage, xmlOptions.getXML(this));
		debug = null;
	}

	DecompileProcess.DisposeState processState;
	if (decompProcess != null) {
		processState = decompProcess.getDisposeState();
		if (decompProcess.getDisposeState() == DecompileProcess.DisposeState.NOT_DISPOSED) {
			flushCache();
		}
	}
	else {
		processState = DecompileProcess.DisposeState.DISPOSED_ON_CANCEL;
	}

	InputStream stream = null;
	if (res != null) {
		stream = res.getInputStream();
	}
	return new DecompileResults(func, pcodelanguage, compilerSpec, dtmanage, decompileMessage,
		stream, processState, isDisplayNamespace());
}
 
Example 18
Source File: CyclomaticComplexity.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Calculates the cyclomatic complexity of a function by decomposing it into a flow
 * graph using a BasicBlockModel.
 * @param function the function
 * @param monitor a monitor
 * @return the cyclomatic complexity
 * @throws CancelledException
 */
public int calculateCyclomaticComplexity(Function function, TaskMonitor monitor)
		throws CancelledException {
	BasicBlockModel basicBlockModel = new BasicBlockModel(function.getProgram());
	CodeBlockIterator codeBlockIterator =
		basicBlockModel.getCodeBlocksContaining(function.getBody(), monitor);
	Address entryPoint = function.getEntryPoint();
	int nodes = 0;
	int edges = 0;
	int exits = 0;
	while (codeBlockIterator.hasNext()) {
		if (monitor.isCancelled()) {
			break;
		}
		CodeBlock codeBlock = codeBlockIterator.next();
		++nodes;
		if (codeBlock.getFlowType().isTerminal()) {
			++exits;
			// strongly connect the exit to the entry point (*)
			++edges;
		}
		CodeBlockReferenceIterator destinations = codeBlock.getDestinations(monitor);
		while (destinations.hasNext()) {
			if (monitor.isCancelled()) {
				break;
			}
			CodeBlockReference reference = destinations.next();
			FlowType flowType = reference.getFlowType();
			if (flowType.isIndirect() || flowType.isCall()) {
				continue;
			}
			++edges;
			if (codeBlock.getFlowType().isTerminal() &&
				reference.getDestinationAddress().equals(entryPoint)) {
				// remove the edge I created since it already exists and was counted above at (*)
				--edges;
			}
		}
	}
	int complexity = edges - nodes + exits;
	return complexity < 0 ? 0 : complexity;
}
 
Example 19
Source File: FidProgramSeeker.java    From ghidra with Apache License 2.0 3 votes vote down vote up
/**
 * Simply makes a singleton match, since only one function record matched (either outright at
 * the beginning, or through elimination of less likely possibilities).
 * @param function the function
 * @param family is the collection of hashes associated with the function
 * @param hashMatch the match score
 * @return a FidSearchResult describing the new match
 */
private FidSearchResult makeSingletonMatch(Function function, HashFamily family,
		FidMatchScore hashMatch) {
	final LibraryRecord library =
		fidQueryService.getLibraryForFunction(hashMatch.getFunctionRecord());
	FidMatch match = new FidMatchImpl(library, function.getEntryPoint(), hashMatch);
	return new FidSearchResult(function, family.getHash(), Collections.singletonList(match));
}
 
Example 20
Source File: IterateFunctionsByAddressScript.java    From ghidra with Apache License 2.0 3 votes vote down vote up
private void iterateBackward() {
	Address minAddress = currentProgram.getMinAddress();

	Address address = currentProgram.getMaxAddress();

	int count = 0;
	while (address.compareTo(minAddress) >= 0) {

		if (monitor.isCancelled()) {
			break;
		}

		Function function = getFunctionBefore(address);

		if (function == null) {
			break;
		}

		String string = count + "  :  " + function.getName() + " @ " + function.getEntryPoint();

		monitor.setMessage(string);

		println(string);

		address = function.getEntryPoint();

		count++;
	}
	println("found " + count + " functions ");
}