Java Code Examples for ghidra.program.model.listing.Program#getReferenceManager()

The following examples show how to use ghidra.program.model.listing.Program#getReferenceManager() . 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: NSArray.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public void markup(Data objectData, Program program, TaskMonitor monitor)
		throws CancelledException {
	ReferenceManager referenceManager = program.getReferenceManager();
	for (int i = 0; i < objectData.getNumComponents(); ++i) {
		monitor.checkCanceled();
		Data component = objectData.getComponent(i);
		if (component.getFieldName().startsWith("value")) {
			long value = getValue(component);
			String name = BinaryPropertyListUtil.generateName(value);
			Symbol symbol = SymbolUtilities.getLabelOrFunctionSymbol(program, name,
				err -> Msg.error(this, err));
			if (symbol != null) {
				referenceManager.addMemoryReference(component.getMinAddress(),
					symbol.getAddress(), RefType.DATA, SourceType.ANALYSIS, 0);
			}
		}
	}
}
 
Example 2
Source File: NSDictionary.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public void markup(Data objectData, Program program, TaskMonitor monitor)
		throws CancelledException {
	ReferenceManager referenceManager = program.getReferenceManager();
	for (int i = 0; i < objectData.getNumComponents(); ++i) {
		monitor.checkCanceled();
		Data component = objectData.getComponent(i);
		if (component.getFieldName().startsWith("key") ||
			component.getFieldName().startsWith("value")) {
			long value = getValue(component);
			String name = BinaryPropertyListUtil.generateName(value);
			Symbol symbol = SymbolUtilities.getLabelOrFunctionSymbol(program, name,
				err -> Msg.error(this, err));
			if (symbol != null) {
				referenceManager.addMemoryReference(component.getMinAddress(),
					symbol.getAddress(), RefType.DATA, SourceType.ANALYSIS, 0);
			}
		}
	}
}
 
Example 3
Source File: NSSet.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public void markup(Data objectData, Program program, TaskMonitor monitor)
		throws CancelledException {
	ReferenceManager referenceManager = program.getReferenceManager();
	for (int i = 0; i < objectData.getNumComponents(); ++i) {
		monitor.checkCanceled();
		Data component = objectData.getComponent(i);
		if (component.getFieldName().startsWith("value")) {
			long value = getValue(component);
			String name = BinaryPropertyListUtil.generateName(value);
			Symbol symbol = SymbolUtilities.getLabelOrFunctionSymbol(program, name,
				err -> Msg.error(this, err));
			if (symbol != null) {
				referenceManager.addMemoryReference(component.getMinAddress(),
					symbol.getAddress(), RefType.DATA, SourceType.ANALYSIS, 0);
			}
		}
	}
}
 
Example 4
Source File: CreateExternalFunctionAction.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private Symbol getExternalCodeSymbol(ListingActionContext listingContext) {

		Program program = listingContext.getProgram();

		ProgramSelection selection = listingContext.getSelection();
		if (selection != null && !selection.isEmpty()) {
			return null;
		}

		ProgramLocation location = listingContext.getLocation();
		if (location instanceof OperandFieldLocation) {
			OperandFieldLocation opLoc = (OperandFieldLocation) location;
			ReferenceManager refMgr = program.getReferenceManager();
			Reference ref =
				refMgr.getPrimaryReferenceFrom(opLoc.getAddress(), opLoc.getOperandIndex());
			if (ref != null && ref.isExternalReference()) {
				Symbol s = program.getSymbolTable().getPrimarySymbol(ref.getToAddress());
				if (s.getSymbolType() == SymbolType.LABEL) {
					return s;
				}
			}
		}
		return null;
	}
 
Example 5
Source File: OffcutReferenceCountToAddressTableColumn.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public Integer getValue(Address address, Settings settings, Program program,
		ServiceProvider serviceProvider) throws IllegalArgumentException {
	int count = 0;
	if (address.isMemoryAddress()) {
		CodeUnit codeUnit = program.getListing().getCodeUnitContaining(address);
		if (codeUnit != null) {
			AddressSet set =
				new AddressSet(codeUnit.getMinAddress(), codeUnit.getMaxAddress());
			set.deleteRange(address, address);
			ReferenceManager referenceManager = program.getReferenceManager();
			AddressIterator it = referenceManager.getReferenceDestinationIterator(set, true);
			while (it.hasNext()) {
				it.next();
				count++;
			}
		}
	}
	return Integer.valueOf(count);
}
 
Example 6
Source File: CallNode.java    From ghidra with Apache License 2.0 6 votes vote down vote up
protected Set<Reference> getReferencesFrom(Program program, AddressSetView addresses,
		TaskMonitor monitor) throws CancelledException {
	Set<Reference> set = new HashSet<Reference>();
	ReferenceManager referenceManager = program.getReferenceManager();
	AddressIterator addressIterator = addresses.getAddresses(true);
	while (addressIterator.hasNext()) {
		monitor.checkCanceled();
		Address address = addressIterator.next();
		Reference[] referencesFrom = referenceManager.getReferencesFrom(address);
		if (referencesFrom != null) {
			for (Reference reference : referencesFrom) {
				set.add(reference);
			}
		}
	}
	return set;
}
 
Example 7
Source File: EditExternalLabelAction.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private Symbol getExternalSymbol(ListingActionContext context) {
	Symbol s = null;
	ProgramLocation location = context.getLocation();
	if (location instanceof OperandFieldLocation) {
		OperandFieldLocation opLoc = (OperandFieldLocation) location;
		Address address = opLoc.getAddress();
		int opIndex = opLoc.getOperandIndex();
		Program program = context.getProgram();
		ReferenceManager refMgr = program.getReferenceManager();
		Reference ref = refMgr.getPrimaryReferenceFrom(address, opIndex);
		if (ref != null) {
			s = program.getSymbolTable().getSymbol(ref);
		}
	}
	if (s == null || !s.isExternal()) {
		return null;
	}
	if (s.getSymbolType() == SymbolType.LABEL || s.getSymbolType() == SymbolType.FUNCTION) {
		return s;
	}
	return null;
}
 
Example 8
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 9
Source File: RemoveAllReferencesCmd.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
* 
* @see ghidra.framework.cmd.Command#applyTo(ghidra.framework.model.DomainObject)
*/
  public boolean applyTo(DomainObject obj) {
  	Program program = (Program)obj;
  	ReferenceManager refMgr = program.getReferenceManager();

  	if (!useOpIndex) {
  		refMgr.removeAllReferencesFrom(fromAddr);
  		return true;
  	}
  	
  	Reference[] refs = refMgr.getReferencesFrom(fromAddr, opIndex);
for (int i = 0; i < refs.length; i++) {
	refMgr.delete(refs[i]);
	RemoveReferenceCmd.fixupReferencedVariable(program, refs[i]);
}
	return true;
  }
 
Example 10
Source File: LabelMarkupItemTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private Symbol addDefaultLabel(Address address, Program program) {

		SymbolTable symbolTable = program.getSymbolTable();
		int transaction = -1;
		try {
			transaction = program.startTransaction("Test - Add Label");
			ReferenceManager referenceManager = program.getReferenceManager();
			referenceManager.addMemoryReference(address, address, RefType.READ,
				SourceType.USER_DEFINED, 0);
			return symbolTable.getPrimarySymbol(address);
		}
		finally {
			program.endTransaction(transaction, true);
		}
	}
 
Example 11
Source File: PseudoCodeUnit.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a pseudo code unit within a program
 * @param program the program this code unit is in.
 * @param addr the minimum address of this code unit.
 * @param length the length  of this code unit.
 * @param cacheLength the number of memBuffer bytes to be available within this CodeUnit MemBuffer
 * @param memBuffer the memory buffer where bytes can be obtained for this code unit.
 * @throws AddressOverflowException if code unit length causes wrap within space
 */
PseudoCodeUnit(Program program, Address addr, int length, int cacheLength, MemBuffer memBuffer)
		throws AddressOverflowException {
	this(addr, length, cacheLength, memBuffer);

	this.program = program;
	if (program != null) {
		refMgr = program.getReferenceManager();
	}
}
 
Example 12
Source File: ResolveExternalReferences.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
protected void run() throws Exception {
	Program program = getState().getCurrentProgram();
	ReferenceManager referenceManager = program.getReferenceManager();
	ExternalManager externalManager = program.getExternalManager();
	ReferenceIterator externalReferences = referenceManager.getExternalReferences();
	while (externalReferences.hasNext()) {
		Reference reference = externalReferences.next();
		if (reference instanceof ExternalReference) {
			ExternalReference externalReference = (ExternalReference) reference;
			ExternalLocation externalLocation = externalReference.getExternalLocation();
			String externalLibraryPath =
				externalManager.getExternalLibraryPath(externalLocation.getLibraryName());
			println(beanify(externalLocation).toString());
			println("externalLibraryPath = " + externalLibraryPath);
		}
		else {
			printerr("Asked for external references, but got: " + reference);
		}
		println("");
	}

	SymbolTable symbolTable = program.getSymbolTable();
	SymbolIterator allSymbols = symbolTable.getAllSymbols(false);
	while (allSymbols.hasNext()) {
		Symbol symbol = allSymbols.next();

		if (symbol.isExternalEntryPoint()) {
			println("external entry point: " + beanify(symbol));
		}
	}
}
 
Example 13
Source File: AddOffsetMemRefCmd.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
* 
* @see ghidra.framework.cmd.Command#applyTo(ghidra.framework.model.DomainObject)
*/
  public boolean applyTo(DomainObject obj) {
  	Program p = (Program)obj;
  	ReferenceManager refMgr = p.getReferenceManager();
refMgr.addOffsetMemReference(fromAddr, toAddr, offset, refType, source, opIndex);
return true;
  }
 
Example 14
Source File: AddShiftedMemRefCmd.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
* 
* @see ghidra.framework.cmd.Command#applyTo(ghidra.framework.model.DomainObject)
*/
  public boolean applyTo(DomainObject obj) {
  	Program p = (Program)obj;
  	ReferenceManager refMgr = p.getReferenceManager();
refMgr.addShiftedMemReference(fromAddr, toAddr, shift, refType, source, opIndex);
return true;
  }
 
Example 15
Source File: VariableXRefHeaderFieldFactory.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a field with "XREF[m,n]:"
 * <br>
 * Where:<br>
 *      m is the number of cross references <br>
 *      n is the number of off-cut cross references <br><br>
 */
private String getXRefHeaderString(Object obj) {
	if (obj == null || !(obj instanceof Variable)) {
		return null;
	}
	Variable var = (Variable) obj;

	int xrefCount = 0;
	int offcutCount = 0;
	Varnode varnode = var.getFirstStorageVarnode();
	if (varnode == null) {
		return null;
	}
	Address varAddr = varnode.getAddress();
	Program program = var.getFunction().getProgram();
	ReferenceManager refMgr = program.getReferenceManager();
	Reference[] vrefs = refMgr.getReferencesTo(var);
	for (Reference vref : vrefs) {
		if (vref.getToAddress().equals(varAddr)) {
			xrefCount++;
		}
		else {
			offcutCount++;
		}
	}

	if (xrefCount > 0 || offcutCount > 0) {
		if (offcutCount > 0) {
			return "XREF[" + xrefCount + "," + offcutCount + "]:";
		}
		return "XREF[" + xrefCount + "]:";
	}
	return null;
}
 
Example 16
Source File: OperandLabelDialog.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * This method gets called when the user clicks on the Ok Button.  The base
 * class calls this method.
 */
@Override
protected void okCallback() {
	Program program = programActionContext.getProgram();
	ProgramLocation loc = programActionContext.getLocation();
	OperandFieldLocation location = (OperandFieldLocation) loc;
	Symbol sym = getSymbol(programActionContext);
	String currentLabel = myChoice.getText();
	if (currentLabel.equals(sym.getName(true))) {
		close();
		return;
	}

	ReferenceManager refMgr = program.getReferenceManager();
	SymbolTable symTable = program.getSymbolTable();
	int opIndex = location.getOperandIndex();
	Address addr = location.getAddress();
	Address symAddr = sym.getAddress();
	Reference ref = refMgr.getReference(addr, symAddr, opIndex);

	CompoundCmd cmd = new CompoundCmd("Set Label");
	Namespace scope = null;

	Symbol newSym = findSymbol(symTable, currentLabel, symAddr);
	if (newSym == null) {
		cmd.add(new AddLabelCmd(symAddr, currentLabel, SourceType.USER_DEFINED));
	}
	else {
		scope = newSym.getParentNamespace();
		currentLabel = newSym.getName();
	}
	cmd.add(new AssociateSymbolCmd(ref, currentLabel, scope));

	if (!plugin.getTool().execute(cmd, program)) {
		setStatusText(cmd.getStatusMsg());
		return;
	}
	close();

}
 
Example 17
Source File: NextPreviousLabelAction.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private Address getNextReferenceToAddress(Program program, Address address, boolean forward) {
	ReferenceManager referenceManager = program.getReferenceManager();
	AddressIterator it = referenceManager.getReferenceDestinationIterator(address, forward);
	if (it.hasNext()) {
		return it.next();
	}
	return null;
}
 
Example 18
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 19
Source File: DataLabelMarkupItemTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private Symbol addDefaultLabel(Address address, Program program) {

		SymbolTable symbolTable = program.getSymbolTable();
		int transaction = -1;
		try {
			transaction = program.startTransaction("Test - Add Label");
			ReferenceManager referenceManager = program.getReferenceManager();
			referenceManager.addMemoryReference(address, address, RefType.READ,
				SourceType.USER_DEFINED, 0);
			return symbolTable.getPrimarySymbol(address);
		}
		finally {
			program.endTransaction(transaction, true);
		}
	}
 
Example 20
Source File: AbstractProgramDiffTest.java    From ghidra with Apache License 2.0 4 votes vote down vote up
protected void createDataReference(Program pgm, Address fromAddr, Address toAddr) {
	ReferenceManager refMgr = pgm.getReferenceManager();
	refMgr.addMemoryReference(fromAddr, toAddr, RefType.DATA, SourceType.USER_DEFINED, 0);
}