ghidra.program.model.mem.MemoryAccessException Java Examples

The following examples show how to use ghidra.program.model.mem.MemoryAccessException. 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: DebugFrameSection.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Analyzes and annotates the debug frame section.
 * @return the region descriptors that compose the debug frame section.
 * @throws MemoryAccessException if memory couldn't be read/written while processing the section.
 * @throws AddressOutOfBoundsException if one or more expected addresses weren't in the program.
 * @throws ExceptionHandlerFrameException if the FDE table can't be decoded.
 */
public List<RegionDescriptor> analyze() throws MemoryAccessException,
		AddressOutOfBoundsException, ExceptionHandlerFrameException, CancelledException {

	List<RegionDescriptor> descriptors = new ArrayList<>();

	MemoryBlock[] blocks = program.getMemory().getBlocks();

	int blockCount = blocks.length;
	monitor.setMaximum(blockCount);

	for (MemoryBlock block : blocks) {
		monitor.checkCanceled();
		monitor.incrementProgress(1);
		if (block.getName().startsWith(DEBUG_FRAME_BLOCK_NAME)) {
			descriptors.addAll(analyzeSection(block));
		}
	}

	return Collections.unmodifiableList(descriptors);

}
 
Example #2
Source File: ValueMapSymbol.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public Constructor resolve(ParserWalker walker, SleighDebugLogger debug)
		throws MemoryAccessException, UnknownInstructionException {
	if (!tableisfilled) {
		long ind = getPatternValue().getValue(walker);
		if ((ind >= valuetable.length) || (ind < 0) || (valuetable[(int) ind] == 0xBADBEEF)) {
			String errmsg =
				"No corresponding entry in valuetable <" + getName() + ">, index=" + ind;
			if (debug != null) {
				debug.append(errmsg + "\n");
			}
			throw new UnknownInstructionException(errmsg);
		}
	}
	return null;
}
 
Example #3
Source File: RELProgramBuilder.java    From Ghidra-GameCube-Loader with Apache License 2.0 6 votes vote down vote up
public RELProgramBuilder(RELHeader rel, ByteProvider provider, Program program,
		TaskMonitor monitor, File originalFile, boolean autoloadMaps, boolean saveRelocations,
		boolean createDefaultMemSections, boolean specifyModuleMemAddrs)
				throws IOException, AddressOverflowException, AddressOutOfBoundsException, MemoryAccessException {
	this.rel = rel;
	this.program = program;
	this.monitor = monitor;
	this.autoloadMaps = autoloadMaps;
	this.saveRelocations = saveRelocations;
	this.specifyModuleMemAddrs = specifyModuleMemAddrs;
	this.binaryName = provider.getName();
	this.symbolInfoList = new ArrayList<Map<Long, SymbolInfo>>();
	
	this.load(provider, originalFile);
	if (createDefaultMemSections) {
		SystemMemorySections.Create(program);
	}
}
 
Example #4
Source File: OperandValue.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public long getValue(ParserWalker walker) throws MemoryAccessException {
	OperandSymbol sym = ct.getOperand(index);
	PatternExpression patexp = sym.getDefiningExpression();
	if (patexp == null) {
		TripleSymbol defSym = sym.getDefiningSymbol();
		if (defSym != null) {
			patexp = defSym.getPatternExpression();
		}
		if (patexp == null) {
			return 0;
		}
	}
	ConstructState tempstate = new ConstructState(null);
	ParserWalker newwalker = new ParserWalker(walker.getParserContext());
	newwalker.setOutOfBandState(ct, index, tempstate, walker);
	long res = patexp.getValue(newwalker);
	return res;
}
 
Example #5
Source File: DisassemblerPlugin.java    From ghidra with Apache License 2.0 6 votes vote down vote up
public void disassembleMipsCallback(ListingActionContext context, boolean mips16) {
	ProgramSelection currentSelection = context.getSelection();
	ProgramLocation currentLocation = context.getLocation();
	Program currentProgram = context.getProgram();
	MipsDisassembleCommand cmd = null;

	if ((currentSelection != null) && (!currentSelection.isEmpty())) {
		cmd = new MipsDisassembleCommand(currentSelection, null, mips16);
	}
	else {
		Address addr = currentLocation.getAddress();
		try {
			currentProgram.getMemory().getByte(addr);
			cmd = new MipsDisassembleCommand(addr, null, mips16);
		}
		catch (MemoryAccessException e) {
			tool.setStatusInfo("Can't disassemble unitialized memory!", true);
		}
	}
	if (cmd != null) {
		tool.executeBackgroundCommand(cmd, currentProgram);
	}
}
 
Example #6
Source File: VTHashedFunctionAddressCorrelation.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public AddressRange getCorrelatedDestinationRange(Address sourceAddress, TaskMonitor monitor)
		throws CancelledException {
	try {
		initializeCorrelation(monitor);
		Address destinationAddress = addressCorrelation.getAddressInSecond(sourceAddress);
		if (destinationAddress == null) {
			return null; // No matching destination.
		}
		return new AddressRangeImpl(destinationAddress, destinationAddress);
	}
	catch (MemoryAccessException e) {
		Msg.error(this, "Could not create HashedFunctionAddressCorrelation", e);
		return null;
	}
}
 
Example #7
Source File: SymbolMerger.java    From ghidra with Apache License 2.0 6 votes vote down vote up
public void merge(int progressMinimum, int progressMaximum, TaskMonitor monitor)
		throws ProgramConflictException, MemoryAccessException, CancelledException {
	monitor.checkCanceled();
	monitor.setProgress(0);
	clearResolveInfo();
	autoMerge(progressMinimum, progressMaximum, monitor);
	monitor.checkCanceled();
	mergeConflicts(monitor);
	monitor.checkCanceled();
	processDeferredRemoves(monitor);
	monitor.checkCanceled();
	infoBuf.append(getDeferredRemovesInfo());
	infoBuf.append(getRenamedConflictsInfo());
	monitor.checkCanceled();
	showResolveInfo();
}
 
Example #8
Source File: HashedFunctionAddressCorrelation.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Finalize a match between two n-grams.  Extend the match is possible, add the matching Instruction pairs to
 * the final map, and remove the Instructions from further match consideration.
 * @param srcEntry is the matching source HashEntry
 * @param srcInstruct is (the starting Instruction of) the source n-gram
 * @param destEntry is the matching destination HashEntry
 * @param destInstruct is (the starting Instruction of) the destination n-gram
 * @throws MemoryAccessException
 */
private void declareMatch(HashEntry srcEntry,InstructHash srcInstruct,HashEntry destEntry,InstructHash destInstruct) throws MemoryAccessException {
	boolean cancelMatch = false;
	int matchSize = srcEntry.hash.size;
	// Its possible that some instructions of the n-gram have already been matched
	if (!srcInstruct.allUnknown(matchSize)) {	// If any source n-gram instructions are already matched
		srcStore.removeHash(srcEntry);			// Remove this HashEntry
		cancelMatch = true;						// Cancel the match
	}
	if (!destInstruct.allUnknown(matchSize)) {	// If any destination n-gram instructions are already matched
		destStore.removeHash(destEntry);		// Remove this HashEntry
		cancelMatch = true;						// Cancel the match
	}
	if (cancelMatch) return;
	ArrayList<Instruction> srcInstructVec = new ArrayList<Instruction>();
	ArrayList<Instruction> destInstructVec = new ArrayList<Instruction>();
	ArrayList<CodeBlock> srcBlockVec = new ArrayList<CodeBlock>();
	ArrayList<CodeBlock> destBlockVec = new ArrayList<CodeBlock>();
	HashStore.NgramMatch srcMatch = new HashStore.NgramMatch();
	HashStore.NgramMatch destMatch = new HashStore.NgramMatch();
	HashStore.extendMatch(matchSize, srcInstruct, srcMatch, destInstruct, destMatch, hashCalc);
	srcStore.matchHash(srcMatch, srcInstructVec, srcBlockVec);
	destStore.matchHash(destMatch, destInstructVec, destBlockVec);
	for(int i=0;i<srcInstructVec.size();++i)
		srcToDest.put(srcInstructVec.get(i).getAddress(), destInstructVec.get(i).getAddress());
}
 
Example #9
Source File: ProgramUtilities.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Get the bytes associated with the specified code unit cu 
 * formatted as a string.  Bytes will be returned as 2-digit hex
 * separated with a space.  Any undefined bytes will be represented by "??".
 * @param cu code unit
 * @return formatted byte string
 */
public static String getByteCodeString(CodeUnit cu) {
	int length = cu.getLength();
	StringBuffer buffer = new StringBuffer();
	for (int i = 0; i < length; i++) {
		if (i != 0) {
			buffer.append(" ");
		}
		String hex;
		try {
			hex = Integer.toHexString(cu.getByte(i) & 0x0ff);
			if (hex.length() == 1) {
				buffer.append("0");
			}
		}
		catch (MemoryAccessException e) {
			hex = "??";
		}
		buffer.append(hex);
	}
	return buffer.toString();
}
 
Example #10
Source File: DexHeader.java    From ghidra with Apache License 2.0 6 votes vote down vote up
public Address getMethodAddress(Program program, int methodId) {
	if (methodId < 0 || methodId >= methodIdsSize) {
		return Address.NO_ADDRESS;
	}
	Address addr;
	synchronized (methodXref) {
		addr = methodXref.get(methodId);
		if (addr == null) { // First time we've tried to access address
			addr = DexUtil.toLookupAddress(program, methodId);		// Find "__lookup__" address
			int val;
			try {
				val = program.getMemory().getInt(addr);
				if (val != -1) {			// If there is an address here, it is in memory location of function
					addr = program.getAddressFactory().getDefaultAddressSpace().getAddress(
						val & 0xffffffffL);
				}
				// Otherwise, the method is external, and we use the lookup address as placeholder
			}
			catch (MemoryAccessException e) {
				addr = Address.NO_ADDRESS;
			}
			methodXref.put(methodId, addr);
		}
	}
	return addr;
}
 
Example #11
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 #12
Source File: DialogResourceDataType.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private int addItemCreationData(MemBuffer memBuffer, List<DataTypeComponent> comps,
		int tempOffset) throws MemoryAccessException {

	short itemDataLength = memBuffer.getShort(tempOffset);
	if (itemDataLength == 0x0000) {
		tempOffset =
			addComp(createArrayOfShorts(1), 2, "Item Data",
				memBuffer.getAddress().add(tempOffset), comps, tempOffset);
	}
	else {
		tempOffset =
			addComp(new ArrayDataType(ByteDataType.dataType, itemDataLength, 1),
				itemDataLength, "Item Data", memBuffer.getAddress().add(tempOffset), comps,
				tempOffset);
	}
	return tempOffset;
}
 
Example #13
Source File: Constructor.java    From ghidra with Apache License 2.0 6 votes vote down vote up
public String printMnemonic(ParserWalker walker) throws MemoryAccessException {
	String res = "";
	if (flowthruindex != -1) {
		Symbol sym = operands[flowthruindex].getDefiningSymbol();
		if (sym instanceof SubtableSymbol) {
			walker.pushOperand(flowthruindex);
			res = walker.getConstructor().printMnemonic(walker);
			walker.popOperand();
			return res;
		}
	}
	int endind = (firstwhitespace == -1) ? printpiece.length : firstwhitespace;
	for (int i = 0; i < endind; ++i) {
		if (printpiece[i].length() != 0) {
			if (printpiece[i].charAt(0) == '\n') {
				int index = printpiece[i].charAt(1) - 'A';
				res += operands[index].print(walker);
			}
			else {
				res += printpiece[i];
			}
		}
	}
	return res;
}
 
Example #14
Source File: ListingMergeManager.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Performs autoMerge of bytes and code units followed by merge of byte and code unit conflicts.
 * @param monitor the task monitor for canceling the merge
 * @throws ProgramConflictException if programs can't be compared using Diff.
 * @throws MemoryAccessException if bytes can't be merged.
 * @throws CancelledException if the user cancels the merge.
 */
private void mergeCodeUnits(TaskMonitor monitor)
		throws ProgramConflictException, MemoryAccessException, CancelledException {

	displayInitialPhaseMessage(CODE_UNITS_PHASE, "Merge of Byte & Code Unit changes");

	AbstractListingMerger[] mergers = new AbstractListingMerger[] { cuMerge };
	autoMerge(mergers, monitor);

	currentMerger = cuMerge;
	mergeManager.showProgressIcon(false);

	cuMerge.mergeConflicts(this.mergePanel, conflictOption, monitor);

	mergeManager.showProgressIcon(true);
	removeBottomComponent();
	mergeManager.setCompleted(CODE_UNITS_PHASE);
}
 
Example #15
Source File: SleighParserContext.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Get bytes from the instruction stream into an int
 * (packed in big endian format).  Uninitialized or 
 * undefined memory will return zero byte values.
 * @param offset offset relative start of this context
 * @param bytestart pattern byte offset relative to specified context offset 
 * @param size
 * @return requested byte-range value
 * @throws MemoryAccessException if no bytes are available at first byte when (offset+bytestart==0).
 */
public int getInstructionBytes(int offset, int bytestart, int size)
		throws MemoryAccessException {
	offset += bytestart;
	byte[] bytes = new byte[size]; // leave any unavailable bytes as 0 in result
	int readSize = memBuffer.getBytes(bytes, offset);
	if (offset == 0 && readSize == 0) {
		throw new MemoryAccessException("invalid memory");
	}
	int result = 0;
	for (int i = 0; i < size; i++) {
		result <<= 8;
		result |= bytes[i] & 0xff;
	}
	return result;
}
 
Example #16
Source File: ReferenceMerger.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public void mergeConflicts(ListingMergePanel listingPanel, Address addr,
		int chosenConflictOption, TaskMonitor monitor) throws CancelledException,
		MemoryAccessException {
	if (!hasConflict(addr)) {
		return;
	}
	monitor.setMessage("Merging conflicting References.");
	// Manually merge each operand as necessary.
	CodeUnit resultCU = resultPgm.getListing().getCodeUnitAt(addr);
	int numOps = resultCU.getNumOperands();
	// Check each operand for ref conflicts.
	for (int opIndex = -1; opIndex < numOps; opIndex++) {
		mergeConflicts(listingPanel, addr, opIndex, chosenConflictOption, monitor);
	}
}
 
Example #17
Source File: Rtti3Model.java    From ghidra with Apache License 2.0 6 votes vote down vote up
public static int getRtti1Count(Program program, Address rtti3Address) {

		Memory memory = program.getMemory();

		Address rtti1CountAddress = rtti3Address.add(NUM_BASES_OFFSET);
		int rtti1Count = 0;
		try {
			rtti1Count =
				(int) new Scalar(32, memory.getInt(rtti1CountAddress, memory.isBigEndian()))
					.getValue();
			return rtti1Count;
		}
		catch (MemoryAccessException e) {
			Msg.error(Rtti3Model.class, "Unexpected Exception: " + e.getMessage(), e);
			return 0;
		}
	}
 
Example #18
Source File: ControlFlowGuard.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Performs markup on the ControlFlowGuard dispatch function, if it exists.
 * 
 * @param lcd The PE LoadConfigDirectory.
 * @param is64bit True if the PE is 64-bit; false if it's 32-bit.
 * @param space The program's address space.
 * @param mem The program's memory.
 * @param symbolTable The program's symbol table.
 */
private static void markupCfgDispatchFunction(LoadConfigDirectory lcd, boolean is64bit,
		AddressSpace space, Memory mem, SymbolTable symbolTable) {

	if (lcd.getCfgDispatchFunctionPointer() == 0) {
		return;
	}

	try {
		Address functionPointerAddr = space.getAddress(lcd.getCfgDispatchFunctionPointer());
		Address functionAddr = space.getAddress(
			is64bit ? mem.getLong(functionPointerAddr) : mem.getInt(functionPointerAddr));
		symbolTable.createLabel(functionAddr, "_guard_dispatch_icall", SourceType.IMPORTED);
	}
	catch (MemoryAccessException | AddressOutOfBoundsException | InvalidInputException e) {
		Msg.warn(ControlFlowGuard.class, "Unable to label ControlFlowGuard dispatch function.",
			e);
	}
}
 
Example #19
Source File: ListingMergeManager.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Performs autoMerge of each remaining address based program item followed by merge of
 * their conflicts in address order.
 * @param monitor the task monitor for canceling the merge
 * @throws ProgramConflictException if programs can't be compared using Diff.
 * @throws MemoryAccessException if bytes can't be merged.
 * @throws CancelledException if the user cancels the merge.
 */
private void mergeAddressBasedProgramItems(TaskMonitor monitor)
		throws ProgramConflictException, MemoryAccessException, CancelledException {

	// Now that the final code units are established,
	// merge the remaining listing at the address level in address order.
	// Each of the following mergers are address based listing mergers.
	displayInitialPhaseMessage(ADDRESS_BASED_PHASE,
		"Merge of Equate, User Defined Property, Reference,Function Tags, Bookmark & Comment changes");

	AbstractListingMerger[] mergers = new AbstractListingMerger[] { equateMerger,
		userPropertyMerger, referenceMerger, bookmarkMerger, commentMerger, functionTagMerger };
	autoMerge(mergers, monitor);

	mergeManager.showProgressIcon(false);

	mergeConflicts(mergers, monitor);

	mergeManager.showProgressIcon(true);
	removeBottomComponent();
	mergeManager.setCompleted(ADDRESS_BASED_PHASE);
}
 
Example #20
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 #21
Source File: AbstractFunctionGraphTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Added this method for cache testing.  No blocks were needed, just needed another
 * function to have enough to test a function being removed from the cache.
 */
private void buildFoo(ToyProgramBuilder builder) throws MemoryAccessException {
	builder.addBytesReturn("0x01002339");

	builder.disassemble("0x01002339", 1, true);
	builder.createFunction("0x01002339");
	builder.createLabel("0x01002339", "foo");// function label
}
 
Example #22
Source File: WEVTResourceDataType.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private boolean checkMagic(byte[] sigBytes, MemBuffer memBuffer, int tempOffset) {
	try {
		for (int i = 0; i < sigBytes.length; i++) {
			if (sigBytes[i] != (memBuffer.getByte(tempOffset + i))) {
				return false;
			}
		}
	}
	catch (MemoryAccessException e) {
		Msg.debug(this, "Incorrect signature for a WEVT resource");
	}
	return true;
}
 
Example #23
Source File: Undefined8DataType.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @see ghidra.program.model.data.DataType#getValue(ghidra.program.model.mem.MemBuffer, ghidra.docking.settings.Settings, int)
 */
public Object getValue(MemBuffer buf, Settings settings, int length) {
	try {
		return new Scalar(64, getValue(buf));
	}
	catch (MemoryAccessException e) {
		return null;
	}
}
 
Example #24
Source File: TokenField.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public long getValue(ParserWalker walker) throws MemoryAccessException {
	long res = getInstructionBytes(walker);

	res >>= shift;
	if (signbit)
		res = signExtend(res, bitend - bitstart);
	else
		res = zeroExtend(res, bitend - bitstart);
	return res;
}
 
Example #25
Source File: FidProgramSeeker.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Search for matches to a single function. Only returns null, if the function can't be hashed.
 * @param function is the function to search for
 * @param monitor is a monitor to check for cancels
 * @return the FidSearchResult object describing any matches (or if there are none)
 * @throws MemoryAccessException
 * @throws CancelledException
 */
public FidSearchResult searchFunction(Function function, TaskMonitor monitor)
		throws MemoryAccessException, CancelledException {
	HashFamily family = getFamily(function, monitor);
	FidSearchResult fidResult = null;
	if (family != null) {
		fidResult = processMatches(function, family, monitor);
		if (fidResult == null) {
			fidResult = new FidSearchResult(function, family.getHash(), null);
		}
	}
	return fidResult;
}
 
Example #26
Source File: GhidraBigEndianDataConverter.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public final int getInt(MemBuffer buf, int offset) throws MemoryAccessException {
	byte[] bytes = new byte[4];
	if (buf.getBytes(bytes, offset) != 4) {
		throw new MemoryAccessException();
	}
	return getInt(bytes, 0);
}
 
Example #27
Source File: EhFrameHeaderSection.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private int getFdeTableCount(Address countAddress, MemoryBlock curMemBlock,
		DwarfEHDecoder fdeDecoder) throws MemoryAccessException {

	DwarfDecodeContext context = new DwarfDecodeContext(program, countAddress, curMemBlock);
	int fdeTableCnt = (int) fdeDecoder.decode(context);
	return fdeTableCnt;
}
 
Example #28
Source File: Undefined7DataType.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @see ghidra.program.model.data.DataType#getValue(ghidra.program.model.mem.MemBuffer, ghidra.docking.settings.Settings, int)
 */
public Object getValue(MemBuffer buf, Settings settings, int length) {
	try {
		return new Scalar(56, getValue(buf));
	}
	catch (MemoryAccessException e) {
		return null;
	}
}
 
Example #29
Source File: PngResource.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private int readInt() throws MemoryAccessException {
	int val = 0;
	for (int i = 0; i < 4; i++) {
		val = val << 8;
		val |= buf.getByte(bufOffset++) & 0xff;
	}
	return val;
}
 
Example #30
Source File: WAVEDataType.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private boolean checkMagic(MemBuffer buf) throws MemoryAccessException {
	for (int i = 0; i < MAGIC.length; i++) {
		if (MAGIC[i] != (buf.getByte(i) & MAGIC_MASK[i])) {
			return false;
		}
	}
	return true;
}