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

The following examples show how to use ghidra.program.model.listing.Program#getMemory() . 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: RelocationFixupHandler.java    From ghidra with Apache License 2.0 6 votes vote down vote up
protected boolean process32BitRelocation(Program program, Relocation relocation,
		Address oldImageBase, Address newImageBase) throws MemoryAccessException,
		CodeUnitInsertionException {
	long diff = newImageBase.subtract(oldImageBase);

	Address address = relocation.getAddress();
	Memory memory = program.getMemory();
	int value = memory.getInt(address);
	int newValue = (int) (value + diff);

	InstructionStasher instructionStasher = new InstructionStasher(program, address);

	memory.setInt(address, newValue);

	instructionStasher.restore();

	return true;
}
 
Example 2
Source File: TypeDescriptorModel.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Determine if this model's data type has a vf table pointer.
 * @param program the program which will contain this model's data type.
 * @return true if the data type has a vf table pointer. Otherwise, it has a hash value.
 */
private static boolean hasVFPointer(Program program) {
	// Should be true when 64 bit or RTTI.
	if (MSDataTypeUtils.is64Bit(program)) {
		return true;
	}
	Memory memory = program.getMemory();
	try {
		List<MemoryBlock> dataBlocks = ProgramMemoryUtil.getMemoryBlocksStartingWithName(
			program, program.getMemory(), ".data", TaskMonitor.DUMMY);
		for (MemoryBlock memoryBlock : dataBlocks) {
			Address typeInfoAddress =
				memory.findBytes(memoryBlock.getStart(), memoryBlock.getEnd(),
					RttiAnalyzer.TYPE_INFO_STRING.getBytes(), null, true, TaskMonitor.DUMMY);
			if (typeInfoAddress != null) {
				return true; // RTTI has type info string in the data section.
			}
		}
	}
	catch (CancelledException e) {
		// Shouldn't happen since using dummy monitor. Do nothing.
	}
	return false;
}
 
Example 3
Source File: TableEntry.java    From ghidra with Apache License 2.0 6 votes vote down vote up
static long getLongValue(Program program, Address entryAddr, int scaleFactor, int size,
		boolean signExtend) throws MemoryAccessException {
	byte[] bytes = new byte[size];
	Memory mem = program.getMemory();
	if (mem.getBytes(entryAddr, bytes) != size) {
		throw new MemoryAccessException("Failed to read table entry at: " + entryAddr);
	}
	long val = 0;
	if (program.getLanguage().isBigEndian()) {
		if (signExtend && (bytes[0] < 0)) {
			val = -1;
		}
		for (int i = 0; i < size; i++) {
			val = (val << 8) + ((long) bytes[i] & 0x0ff);
		}
	}
	else {
		if (signExtend && (bytes[size - 1] < 0)) {
			val = -1;
		}
		for (int i = size - 1; i >= 0; i--) {
			val = (val << 8) + ((long) bytes[i] & 0x0ff);
		}
	}
	return val * scaleFactor;
}
 
Example 4
Source File: TypeDescriptorModel.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Whether or not the memory at the indicated address appears to be a valid location for the
 * indicated number of TypeDescriptor data types.
 * @throws InvalidDataTypeException if this model's location does not appear to be a valid
 * group of TypeDescriptors. The exception has a message indicating
 * why it does not appear to be a valid location for the data type.
 */
@Override
protected void validateModelSpecificInfo() throws InvalidDataTypeException {

	Program program = getProgram();
	Memory memory = program.getMemory();
	AddressSetView loadedAndInitializedSet = memory.getLoadedAndInitializedAddressSet();
	Address startAddress = getAddress();

	// Do we at least have memory for the first 2 components (the pointers).
	int pointerSize = MSDataTypeUtils.is64Bit(program) ? 8 : 4;

	// Test that we can get the expected number of bytes.
	MSDataTypeUtils.getBytes(memory, startAddress, pointerSize * 2);

	// First component should be reference.
	checkVfTablePointerComponent(loadedAndInitializedSet);

	// Check Spare Data. Should be 0 or a valid address in program.
	checkSpareDataComponent(loadedAndInitializedSet);

	checkTypeNameComponent();
}
 
Example 5
Source File: SearchInfo.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Generate an address set which only includes initialized memory
 * 
 * @param program the program
 * @param startAddress starting point for search or null to start from the top of memory
 * @param selection addresses to be searched or null to search all memory
 * @return searchable address set
 */
protected AddressSetView getSearchableAddressSet(Program program, Address startAddress,
		ProgramSelection selection) {

	if (startAddress == null) {
		return new AddressSet();		// special case if we are at the first address going backwards
		// or the last address going forwards
	}

	Memory memory = program.getMemory();
	AddressSetView set = includeNonLoadedBlocks ? memory.getAllInitializedAddressSet()
			: memory.getLoadedAndInitializedAddressSet();
	if (searchSelection && selection != null && !selection.isEmpty()) {
		set = set.intersect(selection);
	}
	Address start = forwardSearch ? startAddress : memory.getMinAddress();
	Address end = forwardSearch ? memory.getMaxAddress() : startAddress;
	if (start.compareTo(end) > 0) {
		return new AddressSet();
	}
	AddressSet addressSet = program.getAddressFactory().getAddressSet(start, end);
	return set.intersect(addressSet);
}
 
Example 6
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 7
Source File: GccAnalysisUtils.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Reads an signed little endian base 128 integer from memory.
 * @param program the program with memory to be read.
 * @param addr the address in memory to begin reading the signed LEB128.
 * @return the signed LEB128 integer.
 */
public static long readSLEB128(Program program, Address addr) {
	SignedLeb128DataType sleb = SignedLeb128DataType.dataType;

	MemBuffer buf = new DumbMemBufferImpl(program.getMemory(), addr);
	Scalar scalar = (Scalar) sleb.getValue(buf, sleb.getDefaultSettings(), sleb.getLength(buf, -1));
	return scalar.getUnsignedValue();
}
 
Example 8
Source File: BinaryPropertyListAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public boolean analyze(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log)
		throws Exception {
	Memory memory = program.getMemory();
	for (MemoryBlock block : memory.getBlocks()) {
		monitor.checkCanceled();
		if (BinaryPropertyListUtil.isBinaryPropertyList(memory, block.getStart())) {
			ByteProvider provider =
				new ImmutableMemoryRangeByteProvider(memory, block.getStart(), block.getEnd());
			markup(block.getStart(), provider, program, monitor);
		}
	}
	removeEmptyFragments(program);
	return true;
}
 
Example 9
Source File: AbstractScalarOperandHover.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void formatAsAddressVal(Program program, Address addr, Scalar scalar,
		StringBuilder htmlText) {

	// maybe the scalar is an address..
	long scalarLong = scalar.getValue();
	AddressFactory factory = program.getAddressFactory();
	AddressSpace space = factory.getDefaultAddressSpace();
	Address asAddress;
	try {
		asAddress = factory.getAddress(space.getBaseSpaceID(), scalarLong);
	}
	catch (AddressOutOfBoundsException ex) {
		asAddress = null;	// Constant doesn't make sense as an address
	}

	Memory memory = program.getMemory();
	if (asAddress != null && memory.contains(asAddress)) {
		htmlText.append("<hr>");
		htmlText.append("<table>");

		addReprRow(htmlText, "Address", asAddress.toString());

		// .. and maybe it points to some data...
		Data data = program.getListing().getDataContaining(asAddress);
		if (data != null) {
			Symbol primary = data.getPrimarySymbol();
			if (primary != null) {
				addReprRow(htmlText, "Symbol",
					HTMLUtilities.italic(HTMLUtilities.friendlyEncodeHTML(primary.getName())));
			}
		}

		htmlText.append("</table>");
	}
}
 
Example 10
Source File: ProgramMappedMemory.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public ProgramMappedMemory(Program program, MemoryFaultHandler faultHandler) {
	this.program = program;
	Memory memory = program.getMemory();

	initializedAddressSet = memory.getLoadedAndInitializedAddressSet();
	for (MemoryBlock block : memory.getBlocks()) {
		if (!block.isInitialized() && block.isMapped()) {
			initializedAddressSet = addMappedInitializedMemory(block);
		}
	}

	program.addConsumer(this);
	this.faultHandler = faultHandler;
}
 
Example 11
Source File: MemorySectionProgramLocationBasedTableColumn.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 {
	Memory memory = program.getMemory();
	MemoryBlock block = memory.getBlock(rowObject.getAddress());
	if (block == null) {
		return "";
	}
	return block.getName();
}
 
Example 12
Source File: Apple8900Analyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public boolean analyze(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log)
		throws Exception {
	monitor.setMessage("Processing Apple 8900 header...");

	ByteProvider provider =
		new MemoryByteProvider(program.getMemory(),
			program.getAddressFactory().getDefaultAddressSpace());
	BinaryReader reader = new BinaryReader(provider, true);

	Apple8900Header header = new Apple8900Header(reader);

	if (!header.getMagic().equals(Apple8900Constants.MAGIC)) {
		log.appendMsg("Invalid 8900 file!");
		return false;
	}

	DataType headerDataType = header.toDataType();
	Data headerData = createData(program, toAddr(program, 0), headerDataType);
	createFragment(program, headerDataType.getName(), headerData.getMinAddress(),
		headerData.getMaxAddress().add(1));

	Address dataStart = toAddr(program, 0x800);
	Address dataEnd = toAddr(program, 0x800 + header.getSizeOfData());
	createFragment(program, "Data", dataStart, dataEnd);

	Address footerSigStart = toAddr(program, 0x800 + header.getFooterSignatureOffset());
	Address footerSigEnd = toAddr(program, 0x800 + header.getFooterCertificateOffset());
	createFragment(program, "FooterSig", footerSigStart, footerSigEnd);

	Address footerCertStart = toAddr(program, 0x800 + header.getFooterCertificateOffset());
	Address footerCertEnd =
		toAddr(program,
			0x800 + header.getFooterCertificateOffset() + header.getFooterCertificateLength());
	createFragment(program, "FooterCert", footerCertStart, footerCertEnd);

	removeEmptyFragments(program);

	return true;
}
 
Example 13
Source File: RttiUtil.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Determines the number of vf addresses in the vf table that begins at the specified base 
 * address.
 * @param program the program whose memory is providing their addresses
 * @param vfTableBaseAddress the base address in the program for the vf table
 * @return the number of virtual function addresses in the vf table
 */
static int getVfTableCount(Program program, Address vfTableBaseAddress) {

	Memory memory = program.getMemory();
	MemoryBlock textBlock = memory.getBlock(".text");
	AddressSetView initializedAddresses = memory.getLoadedAndInitializedAddressSet();
	PseudoDisassembler pseudoDisassembler = new PseudoDisassembler(program);

	// Create pointers starting at the address until reaching a 0 pointer.
	// Terminate the possible table at any entry containing a cross reference that 
	// is beyond the first table entry and don't include it.
	int tableSize = 0;
	Address currentVfPointerAddress = vfTableBaseAddress;
	int defaultPointerSize = program.getDefaultPointerSize();
	while (true) {
		Address referencedAddress = getAbsoluteAddress(program, currentVfPointerAddress);
		if (referencedAddress == null) {
			break; // Cannot get a virtual function address.
		}
		if (referencedAddress.getOffset() == 0) {
			break; // Encountered 0 entry.
		}
		if (!initializedAddresses.contains(referencedAddress)) {
			break; // Not pointing to initialized memory.
		}
		if ((textBlock != null) ? !textBlock.equals(memory.getBlock(referencedAddress))
				: false) {
			break; // Not pointing to text section.
		}
		if (!pseudoDisassembler.isValidSubroutine(referencedAddress, true)) {
			break; // Not pointing to possible function.
		}

		tableSize++; // Count this entry in the table.

		// Advance to the next table entry address.
		currentVfPointerAddress = currentVfPointerAddress.add(defaultPointerSize);
	}
	return tableSize;
}
 
Example 14
Source File: AbstractDwarfEHDecoder.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Reads a signed LEB128-encoded value from <code>program</code> at <code>addr</code>
 * @param program Program to read from
 * @param addr Address to read from
 * @throws MemoryAccessException if the data can't be read
 */
protected long read_sleb128(Program program, Address addr) throws MemoryAccessException {

	SignedLeb128DataType sleb = SignedLeb128DataType.dataType;

	MemBuffer buf = new DumbMemBufferImpl(program.getMemory(), addr);
	Scalar scalar =
		(Scalar) sleb.getValue(buf, sleb.getDefaultSettings(), sleb.getLength(buf, -1));
	return scalar.getSignedValue();
}
 
Example 15
Source File: SearchAllSearchInfo.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
protected AddressSetView getSearchableAddressSet(Program program, Address address,
		ProgramSelection selection) {

	// in the search all case, we don't care about the starting address.

	Memory memory = program.getMemory();
	AddressSetView set =
		this.includeNonLoadedBlocks ? memory.getAllInitializedAddressSet()
				: memory.getLoadedAndInitializedAddressSet();
	if (searchSelection && selection != null && !selection.isEmpty()) {
		set = set.intersect(selection);
	}
	return set;
}
 
Example 16
Source File: RTTI2DataType.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();
	Listing listing = program.getListing();

	if (!memory.contains(startAddress)) {
		return false;
	}

	// Each entry is a 4 byte value.
	long numEntries = (rtti1Count != 0) ? rtti1Count
			: getNumEntries(program, startAddress, validationOptions);
	if (numEntries == 0) {
		return false;
	}
	long length = numEntries * ENTRY_SIZE;
	Address endAddress = startAddress.add(length - 1);
	if (!validRefData(memory, startAddress)) {
		return false;
	}

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

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

	boolean validateReferredToData = validationOptions.shouldValidateReferredToData();

	Address addr = startAddress;
	for (int ordinal = 0; ordinal < numEntries && addr != null &&
		validRefData(memory, addr); ordinal++) {

		// Each component is either a direct reference or an image base offset.
		Address rtti1Address = getReferencedAddress(program, addr);
		if (rtti1Address == null || (validateReferredToData &&
			!rtti1.isValid(program, rtti1Address, validationOptions))) {
			return false;
		}

		try {
			addr = addr.add(ENTRY_SIZE); // Add the data type size.
		}
		catch (AddressOutOfBoundsException e) {
			if (ordinal < (rtti1Count - 1)) {
				return false; // Didn't get all the entries.
			}
			break;
		}
	}

	return true;
}
 
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: OdexHeaderFormatAnalyzer.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 {

	Address address = toAddr( program, 0x0 );

	if ( getDataAt( program, address ) != null ) {
		log.appendMsg( "data already exists." );
		return true;
	}

	Memory memory = program.getMemory( );
	MemoryBlock block = memory.getBlock( "ram" );
	block.setRead( true );
	block.setWrite( false );
	block.setExecute( false );

	ByteProvider provider = new MemoryByteProvider( program.getMemory( ), program.getMinAddress( ) );
	BinaryReader reader = new BinaryReader( provider, true );

	OdexHeader header = new OdexHeader( reader );

	DataType headerDataType = header.toDataType();
	createData( program, address, headerDataType);

	createFragment(program, "header", address, address.add(headerDataType.getLength()));

	Address dexAddress = toAddr(program, header.getDexOffset());
	createFragment(program, "dex", dexAddress, dexAddress.add(header.getDexLength()));

	Address depsAddress = toAddr(program, header.getDepsOffset());
	createFragment(program, "deps", depsAddress, depsAddress.add(header.getDepsLength()));
	processDeps( program, header, monitor, log );

	Address auxAddress = toAddr(program, header.getAuxOffset());
	createFragment(program, "aux", auxAddress, auxAddress.add(header.getAuxLength()));

	monitor.setMessage( "ODEX: cleaning up tree" );
	removeEmptyFragments( program );

	return true;
}
 
Example 19
Source File: AddressBasedLocation.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private static String buildStringRepresentation(Program program, Address address,
		Reference reference, ShowBlockName showBlockName) {
	if (address == null) {
		return "<NULL>";
	}
	if (address.getAddressSpace().getType() == AddressSpace.TYPE_NONE) {
		return ""; // NO_ADDRESS or EXT_FROM_ADDRESS not rendered
	}
	if (address.isExternalAddress()) {
		return getExternalAddressRepresentation(program, address);
	}
	if (address.isVariableAddress()) {
		return getVariableAddressRepresentation();
	}
	if (address.isStackAddress()) {
		return getStackAddressRepresentation(address);
	}
	if (address.isConstantAddress()) {
		return getConstantAddressRepresentation(address);
	}
	if (address.isRegisterAddress()) {
		return getRegisterAddressRepresentation(program, address);
	}

	// Handle all other spaces (e.g., memory, other, overlays, hash, etc.)
	String addrStr;
	if (reference != null && reference.isOffsetReference()) {
		OffsetReference offsetRef = (OffsetReference) reference;
		long offset = offsetRef.getOffset();
		boolean neg = (offset < 0);
		Address baseAddr = offsetRef.getBaseAddress();
		addrStr = baseAddr.toString() + (neg ? "-" : "+") + "0x" +
			Long.toHexString(neg ? -offset : offset);
	}
	else if (reference != null && reference.isShiftedReference()) {
		// TODO: unsure of rendering which has never really been addressed
		// TODO: shifted references have never addressed concerns related to
		// addressable unit size
		ShiftedReference shiftedRef = (ShiftedReference) reference;
		StringBuilder buf = new StringBuilder();
		buf.append(address.toString());
		buf.append("(0x");
		buf.append(Long.toHexString(shiftedRef.getValue()));
		buf.append("<<");
		buf.append(Long.toString(shiftedRef.getShift()));
		buf.append(")");
		addrStr = buf.toString();
	}
	else {
		addrStr = address.toString();
	}

	if (showBlockName != ShowBlockName.NEVER) {
		Memory mem = program.getMemory();
		MemoryBlock toBlock = mem.getBlock(address);
		if (toBlock != null && showBlockName == ShowBlockName.NON_LOCAL && reference != null &&
			toBlock.equals(mem.getBlock(reference.getFromAddress()))) {
			toBlock = null;
		}
		if (toBlock != null) {
			addrStr = toBlock.getName() + "::" + addrStr;
		}
	}

	return addrStr;
}
 
Example 20
Source File: ProgramMemoryUtil.java    From ghidra with Apache License 2.0 3 votes vote down vote up
/**
 * Copies the bytes to one program from another for the specified address 
 * range.
 * @param toProgram program that the bytes are copied to.
 * @param fromProgram program the bytes are copied from.
 * @param minAddr the minimum address of the range to be copied.
 * This address should be derived from the toProgram.
 * @param maxAddr the maximum address of the range to be copied.
 * This address should be derived from the toProgram.
 * 
 * @throws MemoryAccessException if bytes can't be copied.
 */
public static void copyBytesInRanges(Program toProgram, Program fromProgram, Address minAddr,
		Address maxAddr) throws MemoryAccessException {
	Memory toMem = toProgram.getMemory();
	Memory fromMem = fromProgram.getMemory();
	AddressRange range = new AddressRangeImpl(minAddr, maxAddr);
	copyByteRange(toMem, fromMem, range);
}