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

The following examples show how to use ghidra.program.model.mem.Memory#getBytes() . 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: MemSearchPlugin.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private byte[] getInitialSearchBytes(NavigatableActionContext context) {
	if (!prepopulateSearch) {
		return null;
	}

	ProgramSelection selection = context.getSelection();
	if (selection == null || selection.isEmpty() || hasBigSelection(context)) {
		return null;
	}
	// safe cast as size has already been checked.
	int numAddresses = (int) selection.getNumAddresses();
	Address address = selection.getMinAddress();
	Memory memory = context.getProgram().getMemory();
	byte[] bytes = new byte[numAddresses];
	try {
		int count = memory.getBytes(address, bytes);
		if (count == numAddresses) {
			return bytes;
		}
	}
	catch (MemoryAccessException e) {
		// fall through and return null
	}
	return null;
}
 
Example 2
Source File: ElfBinaryAnalysisCommand.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public boolean canApply(Program program) {
	try {
		Options options = program.getOptions("Program Information");
		String format = options.getString("Executable Format", null);
		if (!BinaryLoader.BINARY_NAME.equals(format)) {
			return false;
		}
		Memory memory = program.getMemory();
		byte[] magicBytes = new byte[ElfConstants.MAGIC_BYTES.length];
		memory.getBytes(program.getAddressFactory().getDefaultAddressSpace().getAddress(0),
			magicBytes);
		return Arrays.equals(magicBytes, ElfConstants.MAGIC_BYTES);
	}
	catch (Exception e) {
		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: SampleLocationGenerator.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public ProgramLocation[] getBytesLocations() {
	Memory mem = program.getMemory();
	ProgramLocation[] locs = new ProgramLocation[3];
	try {
		Address a = addr(0x1006420);
		byte[] bytes = new byte[1];
		mem.getBytes(a, bytes);
		locs[0] = new BytesFieldLocation(program, a);

		a = addr(0x100643d);
		bytes = new byte[3];
		mem.getBytes(a, bytes);
		locs[1] = new BytesFieldLocation(program, a.add(2), a.add(2), null, 4);

		a = addr(0x10064f1);
		bytes = new byte[5];
		mem.getBytes(a, bytes);
		locs[2] = new BytesFieldLocation(program, a.add(1));

	}
	catch (MemoryAccessException e) {
		throw new RuntimeException("Unexpected exception reading bytes!", e);
	}
	return locs;
}
 
Example 5
Source File: PPC64CallStubAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private Match matchKnownCallStubs(Address addr, Memory memory,
		SequenceSearchState sequenceSearchState) {
	byte[] bytes = new byte[maxPatternLength];
	ArrayList<Match> matches = new ArrayList<>();
	int cnt = 0;
	try {
		cnt = memory.getBytes(addr, bytes);
	}
	catch (MemoryAccessException e) {
		// ignore
	}
	if (cnt == 0) {
		return null;
	}

	byte[] searchBytes = bytes;
	if (cnt != bytes.length) {
		// although rare, shorten searchBytes if unable to fill
		searchBytes = new byte[cnt];
		System.arraycopy(bytes, 0, searchBytes, 0, cnt);
	}

	matches.clear();
	sequenceSearchState.apply(searchBytes, matches);
	if (matches.size() == 0) {
		return null;
	}

	return matches.get(0);
}
 
Example 6
Source File: BinaryPropertyListUtil.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public static boolean isBinaryPropertyList( Memory memory, Address address ) {
	byte [] bytes = new byte [ BinaryPropertyListConstants.BINARY_PLIST_MAGIC.length( ) ];
	try {
		memory.getBytes( address, bytes );
	}
	catch ( Exception e ) {
		// ignore
	}
	String magic = new String( bytes );
	return BinaryPropertyListConstants.BINARY_PLIST_MAGIC.equals( magic );
}
 
Example 7
Source File: CondenseFillerBytesAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private boolean getBytes(Memory memory, Address fillerAddress, byte[] programBytes) {
	try {
		memory.getBytes(fillerAddress, programBytes);
		return true;
	}
	catch (MemoryAccessException e) {
		return false;
	}
}
 
Example 8
Source File: PefDebug.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public PefDebug(Memory memory, Address address) throws MemoryAccessException {
	unknown = memory.getInt(address);
	type = memory.getInt(address.add(0x4));
	flags = memory.getInt(address.add(0x8));
	distance = memory.getInt(address.add(0xc));
	nameLength = memory.getShort(address.add(0x10)) & 0xffff;
	byte [] stringBytes = new byte[nameLength];
	memory.getBytes(address.add(0x12), stringBytes);
	name = new String(stringBytes);
}
 
Example 9
Source File: CoffArchiveBinaryAnalysisCommand.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public boolean canApply(Program program) {
	try {
		Memory memory = program.getMemory();
		byte[] magicBytes = new byte[CoffArchiveConstants.MAGIC_LEN];
		memory.getBytes(program.getAddressFactory().getDefaultAddressSpace().getAddress(0),
			magicBytes);
		String magic = new String(magicBytes);
		return CoffArchiveConstants.MAGIC.equals(magic);
	}
	catch (Exception e) {
		// expected, ignore
	}
	return false;
}
 
Example 10
Source File: CreateStringScript.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private boolean createLabelForString(Address addr, int length) throws Exception {
	Listing listing = currentProgram.getListing();
	Memory memory = currentProgram.getMemory();
	Data data = listing.getDataAt(addr);
	String value = (String) data.getValue();
	if (value == null) {
		return false;
	}

	boolean needsUnderscore = true;
	StringBuffer buf = new StringBuffer();
	buf.append("s");
	byte[] bytes = new byte[length];
	try {
		memory.getBytes(addr, bytes);
	}
	catch (MemoryAccessException e) {
	}
	for (int i = 0; i < length; i++) {
		char c = (char) bytes[i];
		if (c > 0x20 && c <= 0x7f) {
			if (needsUnderscore) {
				buf.append('_');
				needsUnderscore = false;
			}
			buf.append(c);
		}
		else if (c != 0) {
			needsUnderscore = true;
		}
	}
	String newLabel = buf.toString();

	createLabel(addr, newLabel, true);
	return true;
}
 
Example 11
Source File: PeLoader.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private void processRelocations(OptionalHeader optionalHeader, Program prog,
		TaskMonitor monitor, MessageLog log) {

	if (monitor.isCancelled()) {
		return;
	}
	monitor.setMessage("[" + prog.getName() + "]: processing relocation tables...");

	DataDirectory[] dataDirectories = optionalHeader.getDataDirectories();
	if (dataDirectories.length <= OptionalHeader.IMAGE_DIRECTORY_ENTRY_BASERELOC) {
		return;
	}
	BaseRelocationDataDirectory brdd =
		(BaseRelocationDataDirectory) dataDirectories[OptionalHeader.IMAGE_DIRECTORY_ENTRY_BASERELOC];
	if (brdd == null) {
		return;
	}

	AddressSpace space = prog.getAddressFactory().getDefaultAddressSpace();
	RelocationTable relocTable = prog.getRelocationTable();

	Memory memory = prog.getMemory();

	BaseRelocation[] relocs = brdd.getBaseRelocations();
	long originalImageBase = optionalHeader.getOriginalImageBase();
	AddressRange brddRange =
		new AddressRangeImpl(space.getAddress(originalImageBase + brdd.getVirtualAddress()),
			space.getAddress(originalImageBase + brdd.getVirtualAddress() + brdd.getSize()));
	AddressRange headerRange = new AddressRangeImpl(space.getAddress(originalImageBase),
		space.getAddress(originalImageBase + optionalHeader.getSizeOfHeaders()));
	DataConverter conv = LittleEndianDataConverter.INSTANCE;

	for (BaseRelocation reloc : relocs) {
		if (monitor.isCancelled()) {
			return;
		}
		int baseAddr = reloc.getVirtualAddress();
		int count = reloc.getCount();
		for (int j = 0; j < count; ++j) {
			int type = reloc.getType(j);
			if (type == BaseRelocation.IMAGE_REL_BASED_ABSOLUTE) {
				continue;
			}
			int offset = reloc.getOffset(j);
			long addr = Conv.intToLong(baseAddr + offset) + optionalHeader.getImageBase();
			Address relocAddr = space.getAddress(addr);

			try {
				byte[] bytes = optionalHeader.is64bit() ? new byte[8] : new byte[4];
				memory.getBytes(relocAddr, bytes);
				if (optionalHeader.wasRebased()) {
					long val = optionalHeader.is64bit() ? conv.getLong(bytes)
							: conv.getInt(bytes) & 0xFFFFFFFFL;
					val =
						val - (originalImageBase & 0xFFFFFFFFL) + optionalHeader.getImageBase();
					byte[] newbytes = optionalHeader.is64bit() ? conv.getBytes(val)
							: conv.getBytes((int) val);
					if (type == BaseRelocation.IMAGE_REL_BASED_HIGHLOW) {
						memory.setBytes(relocAddr, newbytes);
					}
					else if (type == BaseRelocation.IMAGE_REL_BASED_DIR64) {
						memory.setBytes(relocAddr, newbytes);
					}
					else {
						Msg.error(this, "Non-standard relocation type " + type);
					}
				}

				relocTable.add(relocAddr, type, null, bytes, null);

			}
			catch (MemoryAccessException e) {
				log.appendMsg("Relocation does not exist in memory: " + relocAddr);
			}
			if (brddRange.contains(relocAddr)) {
				Msg.error(this, "Self-modifying relocation table at " + relocAddr);
				return;
			}
			if (headerRange.contains(relocAddr)) {
				Msg.error(this, "Header modified at " + relocAddr);
				return;
			}
		}
	}
}
 
Example 12
Source File: ByteTrie.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Search memory using the Aho-Corasick multiple string
 * trie search algorithm.
 * @param memory the program memory manager
 * @param view the address set view to search
 * @param monitor a task monitor
 * @return a list of search results
 * @throws MemoryAccessException if bytes are not available
 * @throws CancelledException if the user cancels
 */
@Override
public List<SearchResult<Address, T>> search(Memory memory, AddressSetView view,
		TaskMonitor monitor) throws MemoryAccessException, CancelledException {
	AddressSetView initView = memory.getLoadedAndInitializedAddressSet().intersect(view);
	monitor.initialize(numberOfNodes() + initView.getNumAddresses());

	fixupSuffixPointers(monitor);
	ArrayList<SearchResult<Address, T>> results = new ArrayList<SearchResult<Address, T>>();
	byte[] buffer = new byte[BUFFER_SIZE];

	AddressRangeIterator addressRanges = initView.getAddressRanges(true);
	while (addressRanges.hasNext()) {
		AddressRange range = addressRanges.next();
		BigInteger rangeLength = range.getBigLength();
		int fetchSize = BUFFER_SIZE;
		if (rangeLength.compareTo(BigInteger.valueOf(BUFFER_SIZE)) < 0) {
			fetchSize = rangeLength.intValue();
		}
		ByteTrieNode<T> ptr = root;
		Address address = range.getMinAddress();
		while (range.contains(address)) {
			monitor.checkCanceled();
			final int bytesRead = memory.getBytes(address, buffer, 0, fetchSize);
			monitor.incrementProgress(bytesRead);

			int index = 0;
			while (index < bytesRead) {
				ByteTrieNode<T> trans = null;
				while (trans == null) {
					trans = getTransition(ptr, buffer[index]);
					if (ptr == root) {
						break;
					}
					if (trans == null) {
						ptr = ptr.suffix;
					}
				}
				if (trans != null) {
					ptr = trans;
				}
				ByteTrieNode<T> tmp = ptr;
				while (tmp != root) {
					if (tmp.isTerminal()) {
						int offset = index - tmp.length() + 1;
						Address position = address.add(offset);
						results.add(new SearchResult<Address, T>(tmp, position, tmp.getItem()));
					}
					tmp = tmp.suffix;
				}
				++index;
			}

			try {
				address = address.add(bytesRead);
			}
			catch (AddressOutOfBoundsException e) {
				break; // hit end of address space
			}
		}
	}

	return results;
}
 
Example 13
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());
}
  }