Java Code Examples for ghidra.program.model.mem.Memory#contains()

The following examples show how to use ghidra.program.model.mem.Memory#contains() . 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: FollowFlow.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private Address getNextSymbolAddress(Address curAddr, Address curNext) {
	if (curAddr == null) {
		return null;
	}
	// once there is no next function, don't return one.
	if (curNext == Address.NO_ADDRESS) {
		return curNext;
	}

	if (curNext == null || curNext.compareTo(curAddr) < 0) {
		// find the next function symbol from curAddr to end of current space
		SymbolTable symbolTable = program.getSymbolTable();
		Memory memory = program.getMemory();
		SymbolIterator symbols = symbolTable.getSymbolIterator(curAddr, true);
		if (symbols.hasNext()) {
			Symbol symbol = symbols.next();
			Address addr = symbol.getAddress();
			if (addr.getAddressSpace().equals(curAddr.getAddressSpace()) && memory.contains(addr)) {
				return addr;
			}
		}
		return Address.NO_ADDRESS;
	}
	return curNext;
}
 
Example 2
Source File: GetSymbolForDynamicAddress.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void processProgram(Program program) throws Exception {
	if (foundSymbol) {
		return;
	}
	if (!program.getLanguageID().equals(currentProgram.getLanguageID())) {
		return;
	}
	Memory memory = program.getMemory();
	if (memory.contains(addressToLookFor)) {
		programsWithAddress.add(program.getName());
		Listing listing = program.getListing();
		Function function = listing.getFunctionAt(addressToLookFor);
		if (function == null) {
			return;
		}
		String functionName = function.getName();
		demangleAndCreateSymbol(functionName);

		foundSymbol = true;
	}
}
 
Example 3
Source File: DiffGoToService.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public boolean goTo(Navigatable navigatable, Address goToAddress) {
	if (goToAddress == null) {
		return false;
	}
	if (navigatable == null) {
		return diffGoTo(goToAddress);
	}

	Program program = navigatable.getProgram();
	if (program != null) {
		Memory memory = program.getMemory();
		if (!memory.contains(goToAddress)) {
			return false;
		}
	}

	return goTo(goToAddress, program);
}
 
Example 4
Source File: NextPrevAddressPluginTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private List<Symbol> doBulkGoTo() throws Exception {
	List<Symbol> list = new ArrayList<>();
	Memory memory = program.getMemory();
	int count = 0;
	SymbolIterator iter = program.getSymbolTable().getAllSymbols(true);
	while (iter.hasNext() && count < 11) {
		Symbol symbol = iter.next();
		Address addr = symbol.getAddress();
		if ((addr.isMemoryAddress() && !memory.contains(addr)) || addr.isExternalAddress()) {
			continue;
		}
		list.add(symbol);
		goTo(symbol);
		++count;
	}
	return list;
}
 
Example 5
Source File: PEUtil.java    From ghidra with Apache License 2.0 6 votes vote down vote up
static boolean isValidGuidPointer(Program program, Address addr) {
	Memory memory = program.getMemory();
	AddressFactory addressFactory = program.getAddressFactory();
	AddressSpace defaultSpace = addressFactory.getDefaultAddressSpace();
	try {
		int addrAsInt = memory.getInt(addr);
		Address pointedToAddr =
			addressFactory.getAddress(defaultSpace.getBaseSpaceID(), addrAsInt);
		if (memory.contains(pointedToAddr)) {
			GuidInfo guidInfo = GuidUtil.getKnownGuid(program, pointedToAddr);
			if (guidInfo != null) {
				return true;
			}
		}
	}
	catch (MemoryAccessException e) {
	}
	return false;
}
 
Example 6
Source File: GhidraTableCellRenderer.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private boolean isValueOutOfMemoryAddress(TableModel model, Object value) {
	if (!(value instanceof Address)) {
		return false;
	}

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

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

	Address address = (Address) value;
	Memory memory = program.getMemory();
	return !memory.contains(address);
}
 
Example 7
Source File: GoToQuery.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private Address[] validateAddresses(Program program, Address[] addrs) {
	Memory memory = program.getMemory();
	ArrayList<Address> list = new ArrayList<>();
	for (Address element : addrs) {

		boolean isValid = memory.contains(element);
		if (!isValid) {
			continue;
		}

		if (isPreferredAddress(element)) {
			return new Address[] { element };
		}

		list.add(element);
	}

	if (list.size() == addrs.length) {
		return addrs;
	}
	Address[] a = new Address[list.size()];
	return list.toArray(a);
}
 
Example 8
Source File: FlowArrowPlugin.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private FlowArrow getFlowArrow(Reference ref) {
	Address start = toLayoutAddress(ref.getFromAddress());
	Address end = toLayoutAddress(ref.getToAddress());
	if (start == null || end == null) {
		return null;
	}

	if (!start.hasSameAddressSpace(end)) {
		return null;		// is this right??
	}

	Memory memory = program.getMemory();
	if (!memory.contains(end)) {
		return null; // bad disassembly
	}

	RefType refType = ref.getReferenceType();
	if (refType.isFallthrough()) {
		return new FallthroughFlowArrow(this, flowArrowPanel, start, end, refType);
	}
	else if (refType.isConditional()) {
		return new ConditionalFlowArrow(this, flowArrowPanel, start, end, refType);
	}

	return new DefaultFlowArrow(this, flowArrowPanel, start, end, refType);
}
 
Example 9
Source File: AnnotationTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public boolean goTo(Program p, ProgramLocation location) {

	Address address = location.getAddress();
	Memory memory = p.getMemory();
	if (!memory.contains(address)) {
		// this lets us change flow in the annotation by passing an address not in memory
		return false;
	}

	lastLocation = location;
	return true;
}
 
Example 10
Source File: GoToPluginTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testSaveRestoreState() throws Exception {
	int maxEntries = plugin.getMaximumGotoEntries();

	loadProgram("x86.exe");
	Memory memory = program.getMemory();

	int count = 0;
	SymbolIterator iter = program.getSymbolTable().getAllSymbols(true);
	while (iter.hasNext() && count < 30) {
		Symbol symbol = iter.next();
		Address addr = symbol.getAddress();
		if ((addr.isMemoryAddress() && !memory.contains(addr)) || addr.isExternalAddress()) {
			continue;
		}
		setText(symbol.getName());
		performOkCallback();
		++count;
	}

	SaveState saveState = new SaveState("test");
	plugin.writeDataState(saveState);

	plugin.readDataState(saveState);

	GhidraComboBox<?> combo = findComponent(dialog, GhidraComboBox.class);
	assertNotNull(combo);
	assertEquals(maxEntries, combo.getModel().getSize());
}
 
Example 11
Source File: RTTI4DataType.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the total length of the data created when this data type is placed at the indicated 
 * address in memory.
 * @param memory the program memory for this data.
 * @param address the start address of the data.
 * @param bytes the bytes for this data.
 * @return the length of the data. zero is returned if valid data can't be created at the 
 * indicated address using this data type.
 */
public int getLength(Memory memory, Address address, byte[] bytes) {
	Program program = memory.getProgram();
	// RTTI4 should start on a 4 byte boundary.
	if (address.getOffset() % 4 != 0) {
		return 0;
	}
	// check RTTI4 length in bytes.
	if (bytes.length < LENGTH) {
		return 0;
	}

	// First 12 bytes is 3 dword numeric values.
	// Next there may be bytes to align the rtti0 pointer.

	// Next component should refer to RTTI0.
	Address rtti0CompAddress = address.add(RTTI_0_OFFSET);
	Address rtti0Address = getReferencedAddress(program, rtti0CompAddress);
	if (rtti0Address == null || !memory.contains(rtti0Address)) {
		return 0;
	}

	// Last component should refer to RTTI3.
	Address rtti3CompAddress = address.add(RTTI_3_OFFSET);
	Address rtti3Address = getReferencedAddress(program, rtti3CompAddress);
	if (rtti3Address == null || !memory.contains(rtti3Address)) {
		return 0;
	}

	return LENGTH;
}
 
Example 12
Source File: Rtti3Model.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private static Address getRtti2Address(Program program, Address rtti3Address) {

		Memory memory = program.getMemory();

		Address rtti2CompAddress = rtti3Address.add(BASE_ARRAY_PTR_OFFSET);
		Address pointedToAddress = getReferencedAddress(program, rtti2CompAddress);
		if (pointedToAddress == null || !memory.contains(pointedToAddress)) {
			return null;
		}
		return pointedToAddress;
	}
 
Example 13
Source File: PEUtil.java    From ghidra with Apache License 2.0 5 votes vote down vote up
static boolean isValidPointer(Program program, Address addr) {
	Memory memory = program.getMemory();
	AddressFactory addressFactory = program.getAddressFactory();
	AddressSpace defaultSpace = addressFactory.getDefaultAddressSpace();
	try {
		int addrAsInt = memory.getInt(addr);
		Address pointedToAddr =
			addressFactory.getAddress(defaultSpace.getBaseSpaceID(), addrAsInt);
		return memory.contains(pointedToAddr);
	}
	catch (MemoryAccessException e) {
	}
	return false;
}
 
Example 14
Source File: GoToHelper.java    From ghidra with Apache License 2.0 4 votes vote down vote up
public boolean goTo(final Navigatable navigatable, ProgramLocation loc, Program program) {
		if (loc == null || loc.getAddress() == null) {
			return false;
		}
		if (program == null) {
			program = findGoToProgram(navigatable.getProgram(), loc.getAddress());
		}
		if (program == null) {
			return false;
		}

		Address addr = loc.getAddress();
		if (addr.isExternalAddress()) {
			Symbol externalSym = program.getSymbolTable().getPrimarySymbol(addr);
			if (externalSym == null) {
				return false;
			}
			ExternalLocation externalLoc =
				program.getExternalManager().getExternalLocation(externalSym);

			// TODO - this seems like a mistake to always pass 'false' here; please doc why we
			//        wish to ignore the user options for when to navigate to external programs
			return goToExternalLinkage(navigatable, externalLoc, false);
		}

		Memory memory = program.getMemory();
		if (!memory.contains(addr)) {
			tool.setStatusInfo("Address not found in program memory: " + addr);
			return false;
		}

		saveLocation(navigatable);

		if (!navigatable.goTo(program, loc)) {
			return false;
		}

// If we want the goto to request focus then we will need to add a new parameter - you don't always
//       	want to request focus.
//       	// sometimes this gets call directly after creating a new provider window.  Need to
//       	// request focus in an invokeLater to give WindowManager a chance to create the component
//       	// hierarchy tree.
//       	SwingUtilities.invokeLater(new Runnable() {
//			public void run() {
//		       	navigatable.requestFocus();
//			}
//		});

		saveLocation(navigatable);

		return true;
	}
 
Example 15
Source File: ApplyEnumsAsLabelsAction.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private CreateLabelResult createLabels(Enum enumDt) {
	long[] values = enumDt.getValues();
	SymbolTable symbolTable = program.getSymbolTable();
	CreateLabelResult result = new CreateLabelResult();
	for (long value : values) {
		// Check to see if value is an address that exists in the program.
		// If so then create a label there with the enum value's name.
		String labelName = enumDt.getName(value);
		labelName = SymbolUtilities.replaceInvalidChars(labelName, true);
		AddressFactory addressFactory = program.getAddressFactory();
		String addressString = Long.toHexString(value);
		Address address = addressFactory.getAddress(addressString);
		if (address == null) {
			continue;
		}

		Memory memory = program.getMemory();
		if (!memory.contains(address)) {
			Msg.warn(this, "Couldn't create label for \"" + labelName + "\" at " +
				addressString + ".");
			result.failedToCreateSomeLabels = true;
			continue;
		}

		try {
			Symbol symbol = symbolTable.getGlobalSymbol(labelName, address);
			if (symbol == null) {
				symbolTable.createLabel(address, labelName, SourceType.USER_DEFINED);
				result.numberCreated++;
			}
			else {
				result.someAlreadyExisted = true;
			}
		}
		catch (InvalidInputException e) {
			Msg.warn(this, "Couldn't create label for \"" + labelName + "\" at " +
				addressString + "." + "\n" + e.getMessage());
			result.failedToCreateSomeLabels = true;
		}
	}

	return result;
}
 
Example 16
Source File: EditReferencesProvider.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public Component getTableCellRendererComponent(GTableCellRenderingData data) {

	super.getTableCellRendererComponent(data);

	JTable table = data.getTable();
	int row = data.getRowViewIndex();
	boolean isSelected = data.isSelected();

	Reference ref = tableModel.getReference(row);

	Address addr = ref.getToAddress();
	Memory memory = tableModel.getProgram().getMemory();
	boolean bad = addr.isMemoryAddress() ? !memory.contains(addr) : false;

	setOpaque(false); // disable table striping
	setFont(table.getFont());

	if (isSelected) {
		if (bad) {
			setForeground(Color.pink);
			setFont(boldFont);
		}
		else {
			setFont(defaultFont);
		}

		setOpaque(true);
	}
	else {
		// set color to red if address does not exist in memory

		if (bad) {
			setForeground(Color.red);
			setFont(boldFont);
		}
		else {
			setFont(defaultFont);
		}
		if (ref.getOperandIndex() == instrPanel.getSelectedOpIndex()) {
			setBackground(HIGHLIGHT_COLOR);
			setOpaque(true);
		}
	}

	return this;
}
 
Example 17
Source File: RTTI4DataType.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isValid(Program program, Address startAddress,
		DataValidationOptions validationOptions) {

	Memory memory = program.getMemory();
	if (!memory.contains(startAddress)) {
		return false;
	}

	// RTTI4 should start on a 4 byte boundary.
	if (startAddress.getOffset() % 4 != 0) {
		return false;
	}

	Listing listing = program.getListing();
	Address endAddress = startAddress.add(LENGTH - 1);
	try {
		MSDataTypeUtils.getBytes(memory, startAddress, LENGTH);
	}
	catch (InvalidDataTypeException e) {
		return false; // Couldn't get enough bytes from memory for an RTTI4.
	}

	if (!validationOptions.shouldIgnoreInstructions() &&
		containsInstruction(listing, startAddress, endAddress)) {
		return false;
	}

	if (!validationOptions.shouldIgnoreDefinedData() &&
		containsDefinedData(listing, startAddress, endAddress)) {
		return false;
	}

	// First 12 bytes is 3 dword numeric values.

	boolean validateReferredToData = validationOptions.shouldValidateReferredToData();

	// Fourth component should refer to RTTI0.
	Address rtti0CompAddress = startAddress.add(RTTI_0_OFFSET);
	Address rtti0Address = getReferencedAddress(program, rtti0CompAddress);
	if (rtti0Address == null ||
		(validateReferredToData && !rtti0.isValid(program, rtti0Address, validationOptions))) {
		return false;
	}

	// Last component should refer to RTTI3.
	Address rtti3CompAddress = startAddress.add(RTTI_3_OFFSET);
	Address rtti3Address = getReferencedAddress(program, rtti3CompAddress);
	if (rtti3Address == null ||
		(validateReferredToData && !rtti3.isValid(program, rtti3Address, validationOptions))) {
		return false;
	}

	return true;
}
 
Example 18
Source File: EmbeddedFinderScript.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
  public void run() throws Exception {
byte[] MAGIC_DOS_HEADER = new byte[] { 0x4d, 0x5a };				// M Z
byte[] MAGIC_NT_HEADER  = new byte[] { 0x50, 0x45, 0x00, 0x00 };	// P E 0x00 0x00

List<Address> allFound = new ArrayList<Address>();

Memory memory = currentProgram.getMemory();
Address baseAddr = memory.getMinAddress();
Address currAddr = baseAddr;

while (currAddr != null) {
	// The purpose of breaking each check into small segments (where they could be combined)
	// is to make way for future file type support, keep code clean, and to encourage readability.
	boolean DOSExists = false;
	boolean NTExists = false;
	boolean DOSAgreesWithNT = false;

	Address DOS = memory.findBytes(currAddr, MAGIC_DOS_HEADER, null, true, getMonitor());
	if (DOS != null) {
		// IMAGE_DOS_HEADER is 128 bytes in length, so let's check if that much memory is available
		if (memory.contains(DOS.add(128)))
			DOSExists = true;
	}

	Address NT = memory.findBytes(DOS, MAGIC_NT_HEADER, null, true, getMonitor());
	if (NT != null) {
		// IMAGE_NT_HEADERS32 is 80 bytes in length, so let's check if that much memory is available
		if (memory.contains(NT.add(80)))
			NTExists = true;
	}

	if (DOSExists && NTExists) {
		// It would be better to import the proper structs rather than hard coding offsets.
		// However I'm unsure of what the best way of doing this would be. It's possible to include WINNT.h
		// but this requires the non-development environment to have access to it which makes things
		// less flexible and renders it brittle for future embedded target-type searches.
		// IMAGE_DOS_HEADER + 0x3c is the IMAGE_NT_HEADERS32 offset
		long impliedOffset = memory.getShort(DOS.add(0x3c));
		long actualOffset = NT.getAddressableWordOffset() - DOS.getAddressableWordOffset();
		if (impliedOffset == actualOffset)
			DOSAgreesWithNT = true;
	}

	if (DOSAgreesWithNT) {
		byte[] MAGIC_NT_HEADER_TEST = new byte[4];	// [TODO] Get this to dynamically pull correct size, not hardcoded
		memory.getBytes(NT, MAGIC_NT_HEADER_TEST);

		if (Arrays.equals(MAGIC_NT_HEADER, MAGIC_NT_HEADER_TEST)) {
			if (DOS != baseAddr)
				allFound.add(DOS);		// We only care about targets that are not also the parent file
		}
	}

	if (DOS != null)
		currAddr = DOS.add(1);	// Ensure next search doesn't overlap with current target
	else
		currAddr = null;
}

// Present user with target discovery(s)

if (allFound.isEmpty())
	println("No embedded targets identified");
else {
	println("Embedded targets identified");
	for (Address found : allFound)
		println("\t" + found.toString());
}
  }
 
Example 19
Source File: iOS_KextStubFixupAnalyzer.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public boolean analyze(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log)
		throws Exception {

	//attempt to get the program manager service
	//we can keep working without it, but the analysis will run much slower
	ProgramManager programManager = null;
	AutoAnalysisManager autoAnalysisManager = AutoAnalysisManager.getAnalysisManager(program);
	if (autoAnalysisManager != null) {
		PluginTool tool = autoAnalysisManager.getAnalysisTool();
		if (tool != null) {
			programManager = tool.getService(ProgramManager.class);
		}
	}

	Listing listing = program.getListing();
	SymbolTable symbolTable = program.getSymbolTable();
	Memory memory = program.getMemory();
	ReferenceManager referenceManager = program.getReferenceManager();
	ExternalManager externalManager = program.getExternalManager();

	MemoryBlock stubBlock = memory.getBlock("__stub");
	if (stubBlock == null) {
		stubBlock = memory.getBlock("__stubs");
	}
	if (stubBlock == null) {
		return true;
	}
	disassembleStubSection(program, stubBlock, monitor);
	Namespace stubNameSpace = getOrCreateNameSpace(program, stubBlock);

	MemoryBlock destinationBlock = memory.getBlock("__nl_symbol_ptr");
	if (destinationBlock == null) {
		destinationBlock = memory.getBlock("__got");
	}
	if (destinationBlock == null) {
		return true;
	}
	markupNonLazySymbolPointerSection(program, destinationBlock, monitor);
	Namespace nlSymbolPtrNameSpace = getOrCreateNameSpace(program, destinationBlock);

	DataIterator dataIterator =
		program.getListing().getData(toAddressSet(destinationBlock), true);
	while (dataIterator.hasNext()) {

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

		Data data = dataIterator.next();

		if (data.getMinAddress().compareTo(destinationBlock.getEnd()) > 0) {
			break;
		}

		monitor.setMessage("Fixing STUB section at " + data.getMinAddress());

		Object value = data.getValue();

		if (!(value instanceof Address)) {
			continue;
		}

		Address destinationAddress = (Address) value;

		if (memory.contains(destinationAddress)) {
			continue;
		}

		if ((destinationAddress.getOffset() % 2) != 0) {
			destinationAddress =
				destinationAddress.getNewAddress(destinationAddress.getOffset() - 1);
		}

		DestinationProgramInfo destinationProgramInfo =
			findDestinationProgram(program, programManager, destinationAddress, monitor);

		if (destinationProgramInfo == null) {
			continue;
		}

		createSymbolInNonLazySymbolPointerSection(symbolTable, nlSymbolPtrNameSpace, data,
			destinationProgramInfo);

		createExternalReferenceInNonLazySymbolPointerSection(referenceManager, externalManager,
			data, destinationAddress, destinationProgramInfo);

		createSymbolInStubSection(listing, symbolTable, referenceManager, stubNameSpace, data,
			destinationProgramInfo, monitor);
	}

	return true;
}
 
Example 20
Source File: DataDB.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private void computeLength() {
	length = dataType.getLength();
	if (length < 1) {
		length = codeMgr.getLength(address);
	}
	if (length < 1) {
		if (baseDataType instanceof Pointer) {
			length = address.getPointerSize();
		}
		else {
			length = 1;
		}
	}

	// FIXME Trying to get Data to display for External.
	if (address.isExternalAddress()) { // FIXME
		return; // FIXME
	} // FIXME

	Memory mem = program.getMemory();
	Address endAddress = null;
	boolean noEndAddr = false;
	try {
		endAddress = address.addNoWrap(length - 1);
	}
	catch (AddressOverflowException ex) {
		noEndAddr = true;
	}

	if (noEndAddr || (!mem.contains(address, endAddress))) {
		MemoryBlock block = mem.getBlock(address);
		if (block != null) {
			endAddress = block.getEnd();
			length = (int) endAddress.subtract(address) + 1;
		}
		else {
			length = 1; // ?? what should this be?
		}
	}

	Address nextAddr = codeMgr.getDefinedAddressAfter(address);
	if ((nextAddr != null) && nextAddr.compareTo(endAddress) <= 0) {
		length = (int) nextAddr.subtract(address);
	}
	bytes = null;
}