ghidra.program.model.listing.Function Java Examples

The following examples show how to use ghidra.program.model.listing.Function. 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: NextFunctionAction.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isEnabledForContext(ActionContext context) {
	if (!(context.getComponentProvider() instanceof MultiFunctionComparisonProvider)) {
		return false;
	}
	MultiFunctionComparisonProvider provider =
		(MultiFunctionComparisonProvider) context.getComponentProvider();

	Component comp = provider.getComponent();
	if (!(comp instanceof MultiFunctionComparisonPanel)) {
		return false;
	}

	MultiFunctionComparisonPanel panel = (MultiFunctionComparisonPanel) comp;
	JComboBox<Function> focusedComponent = panel.getFocusedComponent();
	return focusedComponent.getSelectedIndex() < (focusedComponent.getModel().getSize() - 1);
}
 
Example #2
Source File: MultipleSymbolStringable.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private Namespace getNamespaceForNewLabel(Program program, SymbolInfo symbolInfo,
		Address address) throws DuplicateNameException, InvalidInputException {

	if (symbolInfo.isNamespaceFunctionBased) {
		Function f = program.getFunctionManager().getFunctionContaining(address);
		if (f != null) {
			return f;
		}
	}

	// otherwise create or get the path of namespaces.
	Namespace namespace = program.getGlobalNamespace();
	for (NamespaceInfo info : symbolInfo.namespaceInfos) {
		namespace = getOrCreateNamespace(program, info, namespace);
	}
	return namespace;
}
 
Example #3
Source File: FunctionPluginScreenShots.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testEditStorage() {
	Symbol symbol = getUniqueSymbol(program, "_memcpy");
	Function function = (Function) symbol.getObject();
	Parameter parameter = function.getParameter(0);

	DataTypeManagerService dtService = env.getTool().getService(DataTypeManagerService.class);
	Assert.assertNotNull(dtService);

	final StorageAddressEditorDialog dialog =
		new StorageAddressEditorDialog(program, dtService, parameter, 0);

	runSwing(new Runnable() {
		@Override
		public void run() {
			tool.showDialog(dialog);
		}
	}, false);

	captureDialog(600, 400);
}
 
Example #4
Source File: AbstractSymbolTreePluginExternalsTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
protected ExternalLocation setupExternalLocation(final String library, final String label,
		final Address address, final SourceType sourceType, boolean isFunction)
		throws InvalidInputException, DuplicateNameException {
	boolean success = false;
	int transactionID =
		program.startTransaction("Setting Up External Location " + library + "::" + label);
	try {
		ExternalManager externalManager = program.getExternalManager();
		Namespace libraryScope = getLibraryScope("ADVAPI32.dll");
		ExternalLocation extLocation =
			externalManager.addExtLocation(libraryScope, label, address, sourceType);
		assertNotNull(extLocation);
		if (isFunction) {
			Function function = extLocation.createFunction();
			assertNotNull(function);
		}
		success = true;
		return extLocation;
	}
	finally {
		program.endTransaction(transactionID, success);
	}
}
 
Example #5
Source File: MultipleSymbolStringable.java    From ghidra with Apache License 2.0 6 votes vote down vote up
SymbolInfo(Symbol symbol) {
	this.symbolName = symbol.getName();
	this.sourceType = symbol.getSource();
	this.isDynamic = symbol.isDynamic();
	Namespace namespace = symbol.getParentNamespace();
	while (namespace != null) {
		if (namespace instanceof Function) {
			isNamespaceFunctionBased = true;
			break;
		}
		if (namespace instanceof GlobalNamespace) {
			break;
		}
		namespaceInfos.add(new NamespaceInfo(namespace));
		namespace = namespace.getParentNamespace();
	}
	Collections.reverse(namespaceInfos);
}
 
Example #6
Source File: SpecifyCPrototypeAction.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private FunctionDefinitionDataType buildSignature(HighFunction hf) {
	// try to look up the function that is at the current cursor location
	//   If there isn't one, just use the function we are in.

	Function func = hf.getFunction();
	FunctionDefinitionDataType fsig = new FunctionDefinitionDataType(CategoryPath.ROOT,
		func.getName(), func.getProgram().getDataTypeManager());
	FunctionPrototype functionPrototype = hf.getFunctionPrototype();

	int np = hf.getLocalSymbolMap().getNumParams();
	fsig.setReturnType(functionPrototype.getReturnType());

	ParameterDefinition[] args = new ParameterDefinitionImpl[np];
	for (int i = 0; i < np; i++) {
		HighSymbol parm = hf.getLocalSymbolMap().getParamSymbol(i);
		args[i] = new ParameterDefinitionImpl(parm.getName(), parm.getDataType(), null);
	}
	fsig.setArguments(args);
	fsig.setVarArgs(functionPrototype.isVarArg());
	return fsig;
}
 
Example #7
Source File: FunctionSignatureSourceFieldFactory.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public ListingField getField(ProxyObj<?> proxy, int varWidth) {
	if (!enabled) {
		return null;
	}
	if (proxy instanceof FunctionProxy) {
		FunctionProxy functionProxy = (FunctionProxy) proxy;
		Function function = functionProxy.getObject();
		SourceType source = function.getSignatureSource();
		String sourceStr = "<" + source.toString() + ">";
		AttributedString as = new AttributedString(sourceStr, literalColor, getMetrics());
		return ListingTextField.createSingleLineTextField(this, proxy,
			new TextFieldElement(as, 0, 0), startX + varWidth, width, hlProvider);
	}
	return null;
}
 
Example #8
Source File: RenameLocalAction.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean isEnabledForDecompilerContext(DecompilerActionContext context) {
	Function function = context.getFunction();
	if (function == null || function instanceof UndefinedFunction) {
		return false;
	}

	ClangToken tokenAtCursor = context.getTokenAtCursor();
	if (tokenAtCursor == null) {
		return false;
	}
	if (tokenAtCursor instanceof ClangFieldToken) {
		return false;
	}
	HighSymbol highSymbol = findHighSymbolFromToken(tokenAtCursor, context.getHighFunction());
	if (highSymbol == null) {
		return false;
	}
	return !highSymbol.isGlobal();
}
 
Example #9
Source File: RetypeGlobalAction.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean isEnabledForDecompilerContext(DecompilerActionContext context) {
	Function function = context.getFunction();
	if (function == null || function instanceof UndefinedFunction) {
		return false;
	}

	ClangToken tokenAtCursor = context.getTokenAtCursor();
	if (tokenAtCursor == null) {
		return false;
	}
	if (tokenAtCursor instanceof ClangFieldToken) {
		return false;
	}
	if (tokenAtCursor.Parent() instanceof ClangReturnType) {
		return false;
	}
	if (!tokenAtCursor.isVariableRef()) {
		return false;
	}
	HighSymbol highSymbol = findHighSymbolFromToken(tokenAtCursor, context.getHighFunction());
	if (highSymbol == null) {
		return false;
	}
	return highSymbol.isGlobal();
}
 
Example #10
Source File: SymbolTreePlugin2Test.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testNavigateToFunction() throws Exception {
	// select a node; code browser should go there
	GTreeNode fNode = getFunctionsNode();
	util.expandNode(fNode);

	GTreeNode gNode = fNode.getChild(1);
	util.expandNode(gNode);
	Symbol s = ((SymbolNode) gNode).getSymbol();
	Function f = (Function) s.getObject();

	clickOnNode(gNode);
	ListingTextField tf = (ListingTextField) cbPlugin.getCurrentField();
	assertTrue(tf.getFieldFactory() instanceof FunctionSignatureFieldFactory);
	assertEquals(f.getEntryPoint(), cbPlugin.getCurrentAddress());
}
 
Example #11
Source File: FunctionEditorDialog.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private static String createTitle(Function function) {
	StringBuilder strBuilder = new StringBuilder();
	if (function.isExternal()) {
		strBuilder.append("Edit External Function");
		ExternalLocation extLoc = function.getExternalLocation();
		Address addr = extLoc.getAddress();
		if (addr != null) {
			strBuilder.append(" at ");
			strBuilder.append(addr.toString());
		}
	}
	else {
		Function thunkedFunction = function.getThunkedFunction(false);
		if (thunkedFunction != null) {
			strBuilder.append("Edit Thunk Function at ");
			strBuilder.append(function.getEntryPoint().toString());
		}
		else {
			strBuilder.append("Edit Function at ");
			strBuilder.append(function.getEntryPoint().toString());
		}
	}
	return strBuilder.toString();
}
 
Example #12
Source File: FidProgramSeeker.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
	 * Add the children of the function to the hash family.
	 * @param family the family
	 * @param function the function
	 * @param monitor a task monitor
	 * @throws MemoryAccessException if a function body was inexplicably inaccessible
	 * @throws CancelledException
	 */
	private void addChildren(HashFamily family, Function function, TaskMonitor monitor)
			throws MemoryAccessException, CancelledException {
//		SymbolTable symbolTable = function.getProgram().getSymbolTable();
		ArrayList<Function> children = getChildren(function, true);
		for (Function relation : children) {
			monitor.checkCanceled();
			FidHashQuad hash = cacheFactory.get(relation);
			if (hash != null) {
				family.addChild(hash);
			}
//			else {
//				Symbol[] symbols = symbolTable.getSymbols(relation.getEntryPoint());
//				if (symbols != null && symbols.length != 0) {
//					for (Symbol symbol : symbols) {
//						if (symbol.isPrimary() && symbol.getSource() != SourceType.DEFAULT) {
//							String unresolvedChildName = symbol.getName();
//							family.addUnresolvedChild(unresolvedChildName);
//							break;
//						}
//					}
//				}
//			}
		}
	}
 
Example #13
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 #14
Source File: SetReturnDataTypeCmd.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @see ghidra.framework.cmd.Command#applyTo(ghidra.framework.model.DomainObject)
 */
@Override
public boolean applyTo(DomainObject obj) {
	Program program = (Program) obj;
	Function function = program.getListing().getFunctionAt(entry);
	try {
		function.setReturnType(dataType, source);
		if (source == SourceType.DEFAULT) {
			function.setSignatureSource(SourceType.DEFAULT);
		}
	}
	catch (InvalidInputException e) {
		status = e.getMessage();
		return false;
	}
	return true;
}
 
Example #15
Source File: FunctionGraphFactory.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private static FunctionGraph createGraph(Function function, FGController controller,
		TaskMonitor monitor) throws CancelledException {

	BidiMap<CodeBlock, FGVertex> vertices = createVertices(function, controller, monitor);

	Collection<FGEdge> edges = createdEdges(vertices, controller, monitor);

	FunctionGraphVertexAttributes settings =
		new FunctionGraphVertexAttributes(controller.getProgram());
	FunctionGraph graph = new FunctionGraph(function, settings, vertices.values(), edges);

	for (FGVertex vertex : vertices.values()) {
		vertex.setVertexType(getVertexType(graph, vertex));
	}

	return graph;
}
 
Example #16
Source File: ReferenceFunctionAlgorithm.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public int score(Function function, TaskMonitor monitor) throws CancelledException {
	Program program = function.getProgram();
	ReferenceManager referenceManager = program.getReferenceManager();
	AddressSetView body = function.getBody();
	long maxIterations = body.getNumAddresses();
	monitor.initialize(maxIterations);

	AddressIterator iterator = referenceManager.getReferenceSourceIterator(body, true);
	int referenceCount = 0;
	while (iterator.hasNext()) {
		monitor.checkCanceled();
		Address address = iterator.next();
		Reference[] referencesFrom = referenceManager.getReferencesFrom(address);
		referenceCount += referencesFrom.length;
		monitor.incrementProgress(1);

		artificialSleepForDemoPurposes();
	}
	return referenceCount;
}
 
Example #17
Source File: FunctionGraphFactory.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private static FunctionGraph cloneGraph(FunctionGraph originalGraph,
		FGController newController) {

	Map<FGVertex, FGVertex> oldToNewCloneMap =
		cloneVertices(originalGraph.getUngroupedVertices(), newController);
	Collection<FGVertex> vertices = oldToNewCloneMap.values();

	Set<FGEdge> originalEdges = originalGraph.getUngroupedEdges();
	Collection<FGEdge> edges =
		cloneEdges(originalGraph, oldToNewCloneMap, originalEdges, newController);

	Program program = newController.getProgram();
	FunctionGraphVertexAttributes newSettings = cloneSettings(originalGraph, program);
	Function function = originalGraph.getFunction();
	FunctionGraph newGraph = new FunctionGraph(function, newSettings, vertices, edges);

	newGraph.setOptions(originalGraph.getOptions());

	FGVertex entry = newGraph.getVertexForAddress(function.getEntryPoint());
	newGraph.setRootVertex(entry);

	return newGraph;
}
 
Example #18
Source File: AddEditDialoglTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetNamespace_NonExistentNamespace_SameNameAsFunction() throws Exception {

	// 
	// Test that we can create a new namespace using the dialog when:
	// 1) that namespace does not exist
	// 2) the namespace matches the existing function name
	// 3) the function name is not default
	//

	String functionName = "Foo";
	Symbol function = createFunction(functionName);

	editLabel(function);
	String nsName = functionName;
	setText(nsName + Namespace.DELIMITER + functionName);
	pressOk();
	assertFalse("Rename unsuccesful", dialog.isShowing());

	Symbol newFunction = getSymbol(functionName);
	Namespace parentNs = newFunction.getParentNamespace();
	assertFalse(parentNs instanceof Function);
	assertEquals(nsName, parentNs.getName());
}
 
Example #19
Source File: RetypeReturnAction.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean isEnabledForDecompilerContext(DecompilerActionContext context) {
	Function function = context.getFunction();
	if (function == null || function instanceof UndefinedFunction) {
		return false;
	}

	ClangToken tokenAtCursor = context.getTokenAtCursor();
	return (tokenAtCursor.Parent() instanceof ClangReturnType);
}
 
Example #20
Source File: FunctionNameTableColumn.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public String getValue(Address rowObject, Settings settings, Program pgm,
		ServiceProvider serviceProvider) throws IllegalArgumentException {
	Function function = getFunctionContaining(rowObject, pgm);
	if (function != null) {
		return function.getName(true);
	}
	return null;
}
 
Example #21
Source File: VariableCommentAction.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(ListingActionContext context) {
	Function function = funcPlugin.getFunction(context);
	Variable var = getVariable(function, context.getLocation());
	if (var == null) {
		return;
	}
	VariableCommentDialog dialog = funcPlugin.getVariableCommentDialog();
	if (dialog == null) {
		dialog = new VariableCommentDialog(funcPlugin);
	}
	dialog.showDialog(function.getProgram(), var);
}
 
Example #22
Source File: SpecifyCPrototypeAction.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean isEnabledForDecompilerContext(DecompilerActionContext context) {
	Function function = context.getFunction();
	if (function instanceof UndefinedFunction) {
		return false;
	}

	return getFunction(function, context.getTokenAtCursor()) != null;
}
 
Example #23
Source File: FunctionRowObjectToAddressTableRowMapper.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public Address map(FunctionRowObject rowObject, Program program,
		ServiceProvider serviceProvider) {
	Function function = rowObject.getFunction();
	if (function == null) {
		return null;
	}
	return function.getEntryPoint();
}
 
Example #24
Source File: RenameFieldAction.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean isEnabledForDecompilerContext(DecompilerActionContext context) {
	Function function = context.getFunction();
	if (function == null || function instanceof UndefinedFunction) {
		return false;
	}

	ClangToken tokenAtCursor = context.getTokenAtCursor();
	return (tokenAtCursor instanceof ClangFieldToken);
}
 
Example #25
Source File: VTFunctionAssociationProvider.java    From ghidra with Apache License 2.0 5 votes vote down vote up
protected void goToSelectedDestinationFunction() {
	Function destinationFunction = getSelectedDestinationFunction();
	if (destinationFunction != null) {
		controller.gotoDestinationLocation(new ProgramLocation(destinationFunction.getProgram(),
			destinationFunction.getEntryPoint()));
	}
}
 
Example #26
Source File: FunctionCategoryNode.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private boolean isChildNamespaceOfFunction(Symbol symbol) {
	if (symbol instanceof Function) {
		return false;
	}

	Namespace parentNamespace = symbol.getParentNamespace();
	while (parentNamespace != null && parentNamespace != globalNamespace) {
		if (parentNamespace instanceof Function) {
			return true;
		}
		parentNamespace = parentNamespace.getParentNamespace();
	}
	return false;
}
 
Example #27
Source File: FunctionCallGraph.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
protected void verticesRemoved(Collection<FcgVertex> removed) {
	for (FcgVertex v : removed) {
		Function f = v.getFunction();
		verticesByFunction.remove(f);
		verticesByLevel.get(v.getLevel()).remove(v);
	}
	super.verticesRemoved(removed);
}
 
Example #28
Source File: TokenHighlights.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private Function getFunction(ClangToken t) {
	ClangFunction cFunction = t.getClangFunction();
	if (cFunction == null) {
		return null;
	}

	HighFunction highFunction = cFunction.getHighFunction();
	if (highFunction == null) {
		return null;
	}
	return highFunction.getFunction();
}
 
Example #29
Source File: AbstractProgramLoader.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void createSymbol(Program program, AddressLabelInfo info, boolean anchorSymbols) {
	SymbolTable symTable = program.getSymbolTable();
	Address addr = info.getAddress();
	Symbol s = symTable.getPrimarySymbol(addr);
	try {
		if (s == null || s.getSource() == SourceType.IMPORTED) {
			Namespace namespace = program.getGlobalNamespace();
			if (info.getScope() != null) {
				namespace = info.getScope();
			}
			s = symTable.createLabel(addr, info.getLabel(), namespace,
				info.getSource());
			if (info.isEntry()) {
				symTable.addExternalEntryPoint(addr);
			}
			if (info.isPrimary()) {
				s.setPrimary();
			}
			if (anchorSymbols) {
				s.setPinned(true);
			}
		}
		else if (s.getSource() == SourceType.DEFAULT) {
			String labelName = info.getLabel();
			if (s.getSymbolType() == SymbolType.FUNCTION) {
				Function f = (Function) s.getObject();
				f.setName(labelName, SourceType.IMPORTED);
			}
			else {
				s.setName(labelName, SourceType.IMPORTED);
			}
			if (anchorSymbols) {
				s.setPinned(true);
			}
		}
	}
	catch (DuplicateNameException | InvalidInputException e) {
		// Nothing to do
	}
}
 
Example #30
Source File: FunctionCallGraph.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
protected void verticesAdded(Collection<FcgVertex> added) {
	for (FcgVertex v : added) {
		Function f = v.getFunction();
		verticesByFunction.put(f, v);
		verticesByLevel.get(v.getLevel()).add(v);
	}
	super.verticesAdded(added);
}