ghidra.program.model.symbol.Symbol Java Examples

The following examples show how to use ghidra.program.model.symbol.Symbol. 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: FindReferencesToSymbolAction.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private Symbol getSymbol(DecompilerActionContext context) {

		ProgramLocation location = context.getLocation();
		if (location == null) {
			return null;
		}

		Address address = getDecompilerSymbolAddress(location);
		if (address == null) {
			address = location.getAddress();
		}
		Program program = context.getProgram();
		SymbolTable symbolTable = program.getSymbolTable();
		Symbol symbol = symbolTable.getPrimarySymbol(address);
		return symbol;
	}
 
Example #2
Source File: PCodeTestGroup.java    From ghidra with Apache License 2.0 6 votes vote down vote up
void testFailed(String testName, String errFileName, int errLineNum, boolean callOtherFailure,
		Program program, TestLogger logger) {
	if (callOtherFailure) {
		mainTestControlBlock.getTestResults().addCallOtherResult(testGroupName, testName);
	}
	else {
		mainTestControlBlock.getTestResults().addFailResult(testGroupName, testName);
	}
	String failure = testName;
	if (testName != null) {
		Symbol symbol = SymbolUtilities.getLabelOrFunctionSymbol(program, testName,
			err -> Msg.error(this, err));
		if (symbol != null) {
			failure += " @ " + symbol.getAddress().toString(true);
		}
		failure += " (" + errFileName + ":" + errLineNum + ")";
	}
	testFailures.add(failure);
	logger.log(this,
		"Test Failed: " + failure + (callOtherFailure ? " (callother error)" : ""));
}
 
Example #3
Source File: NamespaceTableColumn.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private Symbol getSymbol(ProgramLocation rowObject, Program program)
		throws IllegalArgumentException {
	ProgramLocation location = rowObject;
	if (rowObject instanceof VariableLocation) {
		Variable var = ((VariableLocation) rowObject).getVariable();
		if (var != null) {
			return var.getSymbol();
		}
	}
	Address address = location.getAddress();
	SymbolTable symbolTable = program.getSymbolTable();
	Symbol symbol = symbolTable.getPrimarySymbol(address);
	if (symbol != null) {
		return symbol;
	}
	return null;
}
 
Example #4
Source File: PreviewTableCellData.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private String getCodeUnitPreview(CodeUnitFormat format) {
	Address addr = location.getAddress();
	if (addr.isExternalAddress()) {
		Symbol s = program.getSymbolTable().getPrimarySymbol(addr);
		if (s != null) {
			ExternalLocation extLoc = program.getExternalManager().getExternalLocation(s);
			DataType dt = extLoc.getDataType();
			if (dt == null) {
				dt = DataType.DEFAULT;
			}
			return dt.getMnemonic(dt.getDefaultSettings());
		}
	}

	CodeUnit cu = program.getListing().getCodeUnitAt(addr);
	return getFormatedCodeUnitPreview(cu);
}
 
Example #5
Source File: LabelCodeUnitFormat.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
protected String getOffcutLabelStringForInstruction(Address offcutAddress,
		Instruction instruction) {
	Program program = instruction.getProgram();
	Symbol offsym = program.getSymbolTable().getPrimarySymbol(offcutAddress);
	Address instructionAddress = instruction.getMinAddress();
	long diff = offcutAddress.subtract(instructionAddress);
	if (!offsym.isDynamic()) {
		return getDefaultOffcutString(offsym, instruction, diff, true);
	}

	Symbol containingSymbol = program.getSymbolTable().getPrimarySymbol(instructionAddress);
	if (containingSymbol != null) {
		return containingSymbol.getName() + PLUS + diff;
	}
	return getDefaultOffcutString(offsym, instruction, diff, true);
}
 
Example #6
Source File: VersionTrackingPluginScreenShots.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private VTMatch getMatch(String sourceLabel, VTAssociationType matchType) {
	List<VTMatchSet> matchSets = session.getMatchSets();
	for (VTMatchSet vtMatchSet : matchSets) {
		Collection<VTMatch> matches = vtMatchSet.getMatches();
		for (VTMatch vtMatch : matches) {
			VTAssociation association = vtMatch.getAssociation();
			VTAssociationType type = association.getType();
			if (type != matchType) {
				continue;
			}
			Address sourceAddr = association.getSourceAddress();
			SymbolTable symbolTable = sourceProgram.getSymbolTable();
			Symbol primarySymbol = symbolTable.getPrimarySymbol(sourceAddr);
			String name = primarySymbol.getName(false);
			if (name.equals(sourceLabel)) {
				return vtMatch;
			}
		}
	}
	return null;
}
 
Example #7
Source File: BookmarkPluginTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private boolean checkTable(Bookmark bm, int row) {
	if (!bm.getTypeString().equals(table.getValueAt(row, 0))) {
		return false;
	}
	if (!bm.getCategory().equals(table.getValueAt(row, 1))) {
		return false;
	}
	if (!bm.getComment().equals(table.getValueAt(row, 2))) {
		return false;
	}
	AddressBasedLocation location = (AddressBasedLocation) table.getValueAt(row, 3);
	if (!bm.getAddress().equals(location.getAddress())) {
		return false;
	}

	Symbol[] syms = program.getSymbolTable().getSymbols(bm.getAddress());
	if (syms.length != 0) {
		if (!syms[0].getName().equals(table.getValueAt(row, 4))) {
			return false;
		}
	}
	else {
		return table.getValueAt(row, 4) == null;
	}
	return true;
}
 
Example #8
Source File: LabelCategoryNode.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public SymbolNode symbolAdded(Symbol symbol) {
	if (!isLoaded()) {
		return null;
	}

	// only include global symbols
	if (!symbol.isGlobal()) {
		return null;
	}

	if (!supportsSymbol(symbol)) {
		return null;
	}

	SymbolNode newNode = SymbolNode.createNode(symbol, program);
	doAddNode(this, newNode);
	return newNode;
}
 
Example #9
Source File: GhidraTableCellRenderer.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private boolean isResolvedExternalAddress(TableModel model, Address extAddr) {

		if (!(model instanceof ProgramTableModel)) {
			return false;
		}
		ProgramTableModel programTableModel = (ProgramTableModel) model;

		Program program = programTableModel.getProgram();
		if (program == null) {
			return false; // can happen when program closed
		}

		Symbol s = program.getSymbolTable().getPrimarySymbol(extAddr);
		ExternalLocation extLoc = program.getExternalManager().getExternalLocation(s);
		String path = program.getExternalManager().getExternalLibraryPath(extLoc.getLibraryName());
		return (path != null && path.length() > 0);
	}
 
Example #10
Source File: SleighAssembler.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * A convenience to obtain a map of program labels strings to long values
 * @return the map
 * 
 * {@literal TODO Use a Map<String, Address> instead so that, if possible, symbol values can be checked}
 * lest they be an invalid substitution for a given operand.
 */
protected Map<String, Long> getProgramLabels() {
	Map<String, Long> labels = new HashMap<>();
	for (Register reg : lang.getRegisters()) {
		// TODO/HACK: There ought to be a better mechanism describing suitable symbolic
		// substitutions for a given operand.
		if (!"register".equals(reg.getAddressSpace().getName())) {
			labels.put(reg.getName(), (long) reg.getOffset());
		}
	}
	if (program != null) {
		final SymbolIterator it = program.getSymbolTable().getAllSymbols(false);
		while (it.hasNext()) {
			Symbol sym = it.next();
			labels.put(sym.getName(), sym.getAddress().getOffset());
		}
	}
	return labels;
}
 
Example #11
Source File: LabelCodeUnitFormat.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
protected String getOffcutDataString(Address offcutAddress, Data data) {
	Program program = data.getProgram();
	Symbol offcutSymbol = program.getSymbolTable().getPrimarySymbol(offcutAddress);
	Address dataAddress = data.getMinAddress();
	int diff = (int) offcutAddress.subtract(dataAddress);
	if (!offcutSymbol.isDynamic()) {
		return getDefaultOffcutString(offcutSymbol, data, diff, true);
	}

	DataType dt = data.getBaseDataType();
	String prefix = getPrefixForStringData(data, dataAddress, diff, dt);
	if (prefix != null) {
		String addressString = SymbolUtilities.getAddressString(dataAddress);
		return addOffcutInformation(prefix, addressString, diff, true);
	}

	return getDefaultOffcutString(offcutSymbol, data, diff, true);
}
 
Example #12
Source File: AddressEvaluator.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private static Object getValueObject(SymbolTable st, AddressFactory af, String tok) {

		try {
			return new Long(NumericUtilities.parseHexLong(tok));
		}
		catch (NumberFormatException e) {
			// ignore
		}
		Address address = af.getAddress(tok);
		if (address != null) {
			return address;
		}

		List<Symbol> globalSymbols = st.getLabelOrFunctionSymbols(tok, null);
		if (globalSymbols.size() == 1) {
			return globalSymbols.get(0).getAddress();
		}
		return null;
	}
 
Example #13
Source File: SymbolGTree.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean isSelected,
		boolean expanded, boolean leaf, int row, boolean isFocused) {

	JLabel label = (JLabel) super.getTreeCellRendererComponent(tree, value, isSelected,
		expanded, leaf, row, isFocused);

	if (label.getIcon() == null) {
		label.setIcon(expanded ? OPEN_FOLDER_GROUP_ICON : CLOSED_FOLDER_GROUP_ICON);
	}

	if (!isSelected && (value instanceof SymbolNode)) {
		SymbolNode node = (SymbolNode) value;
		Symbol symbol = node.getSymbol();
		Color color = symbolInspector.getColor(symbol);
		label.setForeground(color);
	}

	return label;
}
 
Example #14
Source File: StringTableSearchTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testMakeStringWhileFilteredForSCR_5689() throws Exception {

	StringTableProvider provider = performSearch();
	StringTableModel model = (StringTableModel) getInstanceField("stringModel", provider);
	GhidraTable table = (GhidraTable) getInstanceField("table", provider);
	toggleDefinedStateButtons(provider, false, true, false, false);
	waitForTableModel(model);
	setAutoLabelCheckbox(provider, true);

	filter("SING", provider);
	waitForTableModel(model);

	selectRow(table, 0);

	// make string
	DockingAction makeStringAction =
		(DockingAction) getInstanceField("makeStringAction", provider);
	performAction(makeStringAction, model);

	Symbol sym = program.getSymbolTable().getPrimarySymbol(addr(0x4040c0));
	assertEquals("s_SING_error", sym.getName());
}
 
Example #15
Source File: SymbolGTreeDragNDropHandler.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void dropNodeList(Namespace namespace, Object transferData) {
	@SuppressWarnings("unchecked")
	List<GTreeNode> nodeList = (List<GTreeNode>) transferData;
	List<Symbol> symbolsToMoveList = new ArrayList<Symbol>();
	for (GTreeNode node : nodeList) {
		// we only allow dragging of SymbolNodes
		SymbolNode symbolNode = (SymbolNode) node;
		Symbol symbol = symbolNode.getSymbol();
		symbolsToMoveList.add(symbol);
	}

	SymbolTreeProvider provider = plugin.getProvider();
	if (provider.reparentSymbols(namespace, symbolsToMoveList) != symbolsToMoveList.size()) {
		plugin.getTool().setStatusInfo("Failed to move one more specified symbols");
	}
}
 
Example #16
Source File: EditLabelAction.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean isEnabledForContext(ListingActionContext context) {
	Symbol symbol = plugin.getSymbol(context);
	if (symbol != null) {
		if (symbol.isExternal()) {
			return false;
		}
		getPopupMenuData().setMenuItemName(EDIT_LABEL);
		return true;
	}
	if (LabelMgrPlugin.getComponent(context) != null) {
		getPopupMenuData().setMenuItemName(EDIT_FIELDNAME);
		return true;
	}
	return false;
}
 
Example #17
Source File: StackEditorProvider.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private boolean inCurrentFunction(DomainObjectChangeRecord record) {
	if (!(record instanceof ProgramChangeRecord)) {
		return false;
	}

	if (function == null) {
		return false; // not sure if this can happen
	}

	ProgramChangeRecord programChangeRecord = (ProgramChangeRecord) record;
	Object affectedValue = programChangeRecord.getObject();
	if (affectedValue instanceof Symbol) {
		Address address = ((Symbol) affectedValue).getAddress();
		if (address.isVariableAddress()) {
			Symbol s = (Symbol) affectedValue;
			return s.getParentNamespace() == function;
		}
	}
	else if (affectedValue instanceof Function) {
		Address changedEntry = ((Function) affectedValue).getEntryPoint();
		if (changedEntry.equals(function.getEntryPoint())) {
			return true;
		}
	}

	return false;
}
 
Example #18
Source File: AbstractVTMatchTableModel.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public Component getTableCellRendererComponent(GTableCellRenderingData data) {

	Object value = data.getValue();

	DisplayableListingAddress displayableAddress =
		(DisplayableListingAddress) value;
	String addressString = displayableAddress.getDisplayString();

	GTableCellRenderingData renderData = data.copyWithNewValue(addressString);

	JLabel renderer = (JLabel) super.getTableCellRendererComponent(renderData);

	Program program = displayableAddress.getProgram();
	Address address = displayableAddress.getAddress();
	if (!address.isMemoryAddress() && symbolInspector != null) {
		Symbol s = program.getSymbolTable().getPrimarySymbol(address);
		symbolInspector.setProgram(program);
		Color c = (s != null) ? symbolInspector.getColor(s) : Color.RED;
		setForeground(c);
	}
	else if (!program.getMemory().contains(address)) {
		setForeground(Color.RED);
	}

	renderer.setOpaque(true);

	return renderer;
}
 
Example #19
Source File: ExportsCategoryNode.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private List<Symbol> getExportSymbols() {
	List<Symbol> symbols = new ArrayList<Symbol>();
	AddressIterator iterator = symbolTable.getExternalEntryPointIterator();
	while (iterator.hasNext()) {
		Symbol symbol = symbolTable.getPrimarySymbol(iterator.next());
		if (symbol != null) {
			symbols.add(symbol);
		}
	}
	return symbols;
}
 
Example #20
Source File: AutoRenamePlugin.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Perform Fragment Auto-Rename on selected Fragments.
 * Rename is performed on all selected Fragments within Program Tree.
 */
void autoRenameCallback(ActionContext context) {

    Object obj = context.getContextObject();
    if (obj instanceof ProgramNode) {
        ProgramNode node = (ProgramNode) obj;

        CompoundCmd cmd = new CompoundCmd("Auto Rename Fragment(s)");
        SymbolTable symTable = currentProgram.getSymbolTable();

        // Find selected Fragments
        TreePath[] selectedPaths = node.getTree().getSelectionPaths();
        boolean ignoreDuplicateNames = (selectedPaths.length > 1);
        for (int i = 0; i < selectedPaths.length; i++) {
            ProgramNode n = (ProgramNode) selectedPaths[i].getLastPathComponent();
            if (!n.isFragment())
                continue;

            // Rename Fragment using minimum address label	
            ProgramFragment f = n.getFragment();
            Address a = f.getMinAddress();
            if (a == null)
                continue; // empty Fragment
            Symbol s = symTable.getPrimarySymbol(a);
            if (s != null) {
                cmd.add(new RenameCmd(f.getTreeName(), false, f.getName(), s.getName(), 
                	ignoreDuplicateNames));
            }
        }

        if (cmd.size() > 0 && !tool.execute(cmd, currentProgram)) {
            tool.setStatusInfo("Error renaming fragment: " + cmd.getStatusMsg());
        }
    }
}
 
Example #21
Source File: StringTableSearchTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoMakeLabelOnExistingString() throws Exception {

	StringTableProvider provider = performSearch();
	StringTableModel model = (StringTableModel) getInstanceField("stringModel", provider);
	GhidraTable table = (GhidraTable) getInstanceField("table", provider);
	toggleDefinedStateButtons(provider, false, true, false, false);
	waitForTableModel(model);

	// *************************************************************************
	// make sure that no label is made when auto label is disabled but that the string is
	// *******************************************************************************
	setAutoLabelCheckbox(provider, false);

	// select row Address 404fde: \n\rString6\n\r)
	selectRows(table, addr(0x404fde));
	assertEquals("00404fde",
		getModelValue(model, table.getSelectedRow(), addressColumnIndex).toString());

	// make string with auto label selected
	DockingAction makeStringAction =
		(DockingAction) getInstanceField("makeStringAction", provider);
	performAction(makeStringAction, model);

	// make sure label not created but the string is
	Symbol sym = program.getSymbolTable().getPrimarySymbol(addr(0x404fde));
	assertEquals(null, sym);

	Data d = listing.getDataAt(addr(0x404fde));
	DataType dt = d.getBaseDataType();
	assertTrue(dt instanceof StringDataType);
	assertEquals("\n\rString6\n\r", d.getValue());

}
 
Example #22
Source File: CreateLabelsFromEnumsTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void checkLabelExists(boolean shouldExist, String labelString, String addressString) {
	SymbolTable symbolTable = program.getSymbolTable();
	Symbol symbol;
	if (addressString != null) {
		symbol = symbolTable.getGlobalSymbol(labelString, addr(addressString));
	}
	else {
		symbol = getUniqueSymbol(program, labelString);
	}
	assertEquals(shouldExist, (symbol != null));
}
 
Example #23
Source File: LabelTableColumn.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public String getValue(ProgramLocation rowObject, Settings settings, Program program,
		ServiceProvider serviceProvider) throws IllegalArgumentException {
	if (rowObject instanceof LabelFieldLocation) {
		LabelFieldLocation labelFieldLocation = (LabelFieldLocation) rowObject;
		return labelFieldLocation.getSymbolPath().getName();
	}
	Symbol symbol = getSymbol(rowObject, program);
	if (symbol != null) {
		return symbol.getName();
	}
	return null;
}
 
Example #24
Source File: SymbolTreeRootNode.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private GTreeNode findVariableSymbolNode(SymbolNode key, boolean loadChildren,
		TaskMonitor monitor) {

	Symbol searchSymbol = key.getSymbol();
	Symbol functionSymbol = searchSymbol.getParentSymbol();
	SymbolNode parentKey = SymbolNode.createNode(functionSymbol, program);
	GTreeNode functionNode = findFunctionSymbolNode(parentKey, loadChildren, monitor);
	return ((SymbolTreeNode) functionNode).findSymbolTreeNode(key, loadChildren, monitor);
}
 
Example #25
Source File: SymbolEditor.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,
		int row, int column) {

	Symbol symbol = (Symbol) value;
	if (symbol != null) {
		symbolField.setText(symbol.getName());
	}
	else {
		symbolField.setText("");
	}
	return symbolField;
}
 
Example #26
Source File: LabelMarkupUtils.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public static void removeDefaultLabels( Program destinationProgram, Address address ) {
    SymbolTable symbolTable = destinationProgram.getSymbolTable();
    Symbol[] symbols = symbolTable.getSymbols( address );
    for ( Symbol symbol : symbols ) {
        if ( symbol instanceof FunctionSymbol ) {
            continue;
        }
        
        if ( !symbol.isDynamic() ) {
            continue;
        }
        
        symbolTable.removeSymbolSpecial( symbol );
    }
}
 
Example #27
Source File: DisplayableLabel.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public int compareTo(DisplayableLabel otherDisplayableLabel) {
	if (otherDisplayableLabel == null) {
		return 1;
	}
	Symbol otherSymbol = otherDisplayableLabel.getSymbol();
	if (symbol == null) {
		return (otherSymbol == null) ? 0 : -1;
	}
	if (otherSymbol == null) {
		return 1;
	}
	return symbol.getName().compareToIgnoreCase(otherSymbol.getName());
}
 
Example #28
Source File: AddressLocationDescriptor.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private String getLabelForAddress(CodeUnitLocation location) {
	Address address = getAddressForLocation(location);
	SymbolTable symbolTable = program.getSymbolTable();
	Symbol symbol = symbolTable.getPrimarySymbol(address);
	if (symbol != null) {
		return symbol.getName();
	}

	if (location instanceof AddressFieldLocation) {
		return ((AddressFieldLocation) location).getAddressRepresentation();
	}

	return location.getAddress().toString();
}
 
Example #29
Source File: ExportsCategoryNode.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public List<GTreeNode> generateChildren(TaskMonitor monitor) {
	List<GTreeNode> list = new ArrayList<GTreeNode>();

	List<Symbol> functionSymbolList = getExportSymbols();
	for (Symbol symbol : functionSymbolList) {
		list.add(SymbolNode.createNode(symbol, program));
	}

	Collections.sort(list, getChildrenComparator());

	return list;
}
 
Example #30
Source File: PinSymbolCmd.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public boolean applyTo(DomainObject obj) {
	SymbolTable symbolTable = ((Program) obj).getSymbolTable();
	Symbol symbol = symbolTable.getGlobalSymbol(name, addr);
	if (symbol == null) {
		message = "Could not find symbol named " + name + " at address " + addr;
		return false;
	}
	symbol.setPinned(pin);
	return true;
}