ghidra.program.disassemble.Disassembler Java Examples

The following examples show how to use ghidra.program.disassemble.Disassembler. 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: MipsAddressAnalyzer.java    From ghidra with Apache License 2.0 6 votes vote down vote up
Address MipsExtDisassembly(Program program, Instruction instruction, VarnodeContext context,
		Address target, TaskMonitor monitor) {
	if (target == null) {
		return null;
	}

	Address addr = flowISA(program, instruction, context, target);
	if (addr != null) {
		MemoryBlock block = program.getMemory().getBlock(addr);
		if (block == null || !block.isExecute() || !block.isInitialized() ||
			block.getName().equals("EXTERNAL")) {
			return addr;
		}

		Disassembler dis = Disassembler.getDisassembler(program, monitor, null);
		AddressSet disassembleAddrs = dis.disassemble(addr, null);
		AutoAnalysisManager.getAnalysisManager(program).codeDefined(disassembleAddrs);
	}

	return addr;
}
 
Example #2
Source File: ElfDefaultGotPltMarkup.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void disassemble(Address start, Address end, Program prog, TaskMonitor monitor)
		throws CancelledException {
	DisassemblerMessageListener dml = msg -> {
		//don't care...
	};
	// TODO: Should we restrict disassembly or follows flows?
	AddressSet set = new AddressSet(start, end);
	Disassembler disassembler = Disassembler.getDisassembler(prog, monitor, dml);
	while (!set.isEmpty()) {
		monitor.checkCanceled();
		AddressSet disset = disassembler.disassemble(set.getMinAddress(), set, true);
		if (disset.isEmpty()) {
			// Stop on first error but discard error bookmark since
			// some plt sections are partly empty and must rely
			// on normal flow disassembly during analysis
			prog.getBookmarkManager().removeBookmarks(set, BookmarkType.ERROR,
				Disassembler.ERROR_BOOKMARK_CATEGORY, monitor);
			break;//we did not disassemble anything...
		}
		set.delete(disset);
	}
}
 
Example #3
Source File: Emulate.java    From ghidra with Apache License 2.0 6 votes vote down vote up
public Emulate(SleighLanguage lang, MemoryState s, BreakTable b) {
		memstate = s;
		this.language = lang;
		this.addrFactory = lang.getAddressFactory();
		pcReg = lang.getProgramCounter();
		breaktable = b;
		breaktable.setEmulate(this);
		memBuffer =
			new EmulateMemoryStateBuffer(s, addrFactory.getDefaultAddressSpace().getMinAddress());

		uniqueBank =
			new UniqueMemoryBank(lang.getAddressFactory().getUniqueSpace(), lang.isBigEndian());
		memstate.setMemoryBank(uniqueBank);

//		emitterContext = new EmulateDisassemblerContext(lang, s);

		pseudoDisassembler =
			Disassembler.getDisassembler(lang, addrFactory, TaskMonitorAdapter.DUMMY_MONITOR, null);

		initInstuctionStateModifier();
	}
 
Example #4
Source File: MipsR5900AddressAnalyzer.java    From ghidra-emotionengine with Apache License 2.0 6 votes vote down vote up
Address MipsExtDisassembly(Program program, Instruction instruction, VarnodeContext context,
		Address target, TaskMonitor monitor) {
	if (target == null) {
		return null;
	}

	Address addr = instruction.getMinAddress().getNewAddress(target.getOffset() & 0xfffffffe);
	if (addr != null) {
		MemoryBlock block = program.getMemory().getBlock(addr);
		if (block == null || !block.isExecute() || !block.isInitialized() ||
			block.getName().equals("EXTERNAL")) {
			return addr;
		}

		Disassembler dis = Disassembler.getDisassembler(program, monitor, null);
		AddressSet disassembleAddrs = dis.disassemble(addr, null);
		AutoAnalysisManager.getAnalysisManager(program).codeDefined(disassembleAddrs);
	}

	return addr;
}
 
Example #5
Source File: ArmAnalyzer.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Disassemble at the specified target address and optionally create a mnemonic flow reference.
 * @param monitor
 * @param instruction flow from instruction
 * @param target disassembly address
 * @param flowType if not null a reference from the instruction mnemonic will be created to the specified
 * target address using this flowType.
 * @param addRef true if a reference should be added.
 *
 */
void doArmThumbDisassembly(Program program, Instruction instruction, VarnodeContext context,
		Address target, FlowType flowType, boolean addRef, TaskMonitor monitor) {
	if (target == null) {
		return;
	}
	
	target = flowArmThumb(program, instruction, context, target, flowType, addRef);
	if (target == null) {
		return;
	}

	// this is here so the reference gets created, but not - disassembled if it is in a bad part of memory.
	// something computed it into the memory
	MemoryBlock block = program.getMemory().getBlock(target);
	if (block == null || !block.isExecute() || !block.isInitialized() ||
		block.getName().equals("EXTERNAL")) {
		return;
	}
	
	Disassembler dis = Disassembler.getDisassembler(program, monitor, null);
	AddressSet disassembleAddrs = dis.disassemble(target, null);
	AutoAnalysisManager.getAnalysisManager(program).codeDefined(disassembleAddrs);
}
 
Example #6
Source File: Pic18Analyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void addSkipReference(Instruction instr) {
	try {
		Instruction nextInstr = instr.getNext();
		if (nextInstr == null) {
			return;
		}

		Address skipAddr = nextInstr.getMaxAddress().add(1);
		instr.addMnemonicReference(skipAddr, RefType.CONDITIONAL_JUMP, SourceType.ANALYSIS);

		disassemblyPoints.addRange(skipAddr, skipAddr);

		if (nextInstr.getLength() != 2) { // skip flow always skips by 2 bytes
			// Remove disassembler error bookmark caused by offcut skip which is OK
			BookmarkManager bookmarkMgr = program.getBookmarkManager();
			Address nextAddr = nextInstr.getMinAddress();
			Bookmark bookmark = bookmarkMgr.getBookmark(nextAddr.add(2), BookmarkType.ERROR,
				Disassembler.ERROR_BOOKMARK_CATEGORY);
			if (bookmark != null) {
				bookmarkMgr.removeBookmark(bookmark);
				bookmarkMgr.setBookmark(nextAddr, BookmarkType.ANALYSIS, "Offcut Skip Detected",
					"");
			}
		}
	}
	catch (AddressOutOfBoundsException e) {
		// ignore
	}

}
 
Example #7
Source File: SleighAssembler.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a SleighAssembler.
 * 
 * @param selector a method of selecting one result from many
 * @param program the program to bind to (must have same language as parser)
 * @param parser the parser for the SLEIGH language
 * @param defaultContext the default context for the language
 * @param ctxGraph the context graph
 */
protected SleighAssembler(AssemblySelector selector, Program program, AssemblyParser parser,
		AssemblyDefaultContext defaultContext, AssemblyContextGraph ctxGraph) {
	this(selector, (SleighLanguage) program.getLanguage(), parser, defaultContext, ctxGraph);
	this.program = program;

	this.listing = program.getListing();
	this.memory = program.getMemory();
	this.dis = Disassembler.getDisassembler(program, TaskMonitor.DUMMY,
		DisassemblerMessageListener.IGNORE);
}
 
Example #8
Source File: MarkCallOtherPcode.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void run() throws Exception {
	if (currentProgram == null) {
		return;
	}
	AddressSetView set = currentSelection;
	if (set == null || set.isEmpty()) {
		set = currentProgram.getMemory().getExecuteSet();
	}

	Disassembler.clearUnimplementedPcodeWarnings(currentProgram, set, monitor);

	int completed = 0;
	monitor.initialize(set.getNumAddresses());

	InstructionIterator instructions = currentProgram.getListing().getInstructions(set, true);
	while (instructions.hasNext()) {
		monitor.checkCanceled();
		Instruction instr = instructions.next();

		PcodeOp[] pcode = instr.getPcode();

		for (int i = 0; i < pcode.length; i++) {
			if (pcode[i].getOpcode() == PcodeOp.CALLOTHER) {
				markCallOtherPcode(instr, pcode[i]);
			}
		}

		completed += instr.getLength();
		if ((completed % 1000) == 0) {
			monitor.setProgress(completed);
		}
	}

}
 
Example #9
Source File: MipsPreAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void redoAllPairs(Program program, AddressSet pairSet, TaskMonitor monitor)
		throws CancelledException {

	final int locationCount = pairSet.getNumAddressRanges();
	int count = 0;
	if (locationCount > NOTIFICATION_INTERVAL) {
		monitor.initialize(locationCount);
	}

	Disassembler dis = Disassembler.getDisassembler(program, monitor, null);
	for (AddressRange addressRange : pairSet) {
		monitor.checkCanceled();
		if (locationCount > NOTIFICATION_INTERVAL) {

			if ((count % NOTIFICATION_INTERVAL) == 0) {
				//monitor.setMaximum(locationCount);
				monitor.setProgress(count);
			}
			count++;
		}

		program.getListing().clearCodeUnits(addressRange.getMinAddress(),
			addressRange.getMaxAddress(), false);

		// Set bits
		try {
			program.getProgramContext().setValue(pairBitRegister, addressRange.getMinAddress(),
				addressRange.getMaxAddress(), BigInteger.valueOf(1));

			// Disassemble all again
			AddressSet rangeSet = new AddressSet(addressRange);
			dis.disassemble(rangeSet, rangeSet, false);
			// don't notify anyone of new code, since this analyzer should run very early on all new code
		}
		catch (ContextChangeException e) {
			Msg.error(this, "Unexpected Exception", e);
		}
	}

}
 
Example #10
Source File: LanguagePostUpgradeInstructionHandler.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Get disassembler for the current program
 * @return disassembler instance
 */
protected Disassembler getDisassembler() {
	if (disassembler == null) {
		disassembler = Disassembler.getDisassembler(program, TaskMonitor.DUMMY, null);
	}
	return disassembler;
}
 
Example #11
Source File: EntryPointAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void doDisassembly(Program program, TaskMonitor monitor, Set<Address> entries) {

		if (entries.isEmpty()) {
			return;
		}

		Iterator<Address> iter = entries.iterator();
		AddressSet disSet = new AddressSet();
		while (iter.hasNext()) {
			Address entry = iter.next();
			disSet.addRange(entry, entry);
		}
		//DisassembleCommand cmd = new DisassembleCommand(disSet, null, true);
		//cmd.applyTo(program, monitor);
		// Disassemble all again
		Disassembler dis = Disassembler.getDisassembler(program, monitor, null);
		AddressSet disassembledSet = dis.disassemble(disSet, null, true);
		AutoAnalysisManager.getAnalysisManager(program).codeDefined(disassembledSet);

		AddressSet functionEntries = new AddressSet();
		Listing listing = program.getListing();
		for (Address addr : entries) {
			if (listing.getInstructionAt(addr) != null) {
				Symbol s = program.getSymbolTable().getPrimarySymbol(addr);
				if (s != null && s.isExternalEntryPoint() &&
					listing.getFunctionContaining(addr) == null) {
					functionEntries.addRange(addr, addr);
				}
			}
		}
		if (!functionEntries.isEmpty()) {
			CreateFunctionCmd createFunctionCmd = new CreateFunctionCmd(functionEntries);
			createFunctionCmd.applyTo(program, monitor);
		}
	}
 
Example #12
Source File: DisassemblerPlugin.java    From ghidra with Apache License 2.0 5 votes vote down vote up
protected void programActivated(Program program) {
	if (program == null) {
		return;
	}
	Options options = program.getOptions(Program.DISASSEMBLER_PROPERTIES);
	options.registerOption(Disassembler.MARK_BAD_INSTRUCTION_PROPERTY, true,
		null, "Place ERROR Bookmark at locations where disassembly could not be perfomed.");
	options.registerOption(
		Disassembler.MARK_UNIMPL_PCODE_PROPERTY,
		true,
		null,
		"Place WARNING Bookmark at locations where a disassembled instruction has unimplemented pcode.");
	options.registerOption(Disassembler.RESTRICT_DISASSEMBLY_TO_EXECUTE_MEMORY_PROPERTY,
		false, null, "Restrict disassembly to executable memory blocks.");
}
 
Example #13
Source File: MarkUnimplementedPcode.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void run() throws Exception {
	if (currentProgram == null) {
		return;
	}
	AddressSetView set = currentSelection;
	if (set == null || set.isEmpty()) {
		set = currentProgram.getMemory().getExecuteSet();
	}

	Disassembler.clearUnimplementedPcodeWarnings(currentProgram, set, monitor);

	int completed = 0;
	monitor.initialize(set.getNumAddresses());

	InstructionIterator instructions = currentProgram.getListing().getInstructions(set, true);
	while (instructions.hasNext()) {
		monitor.checkCanceled();
		Instruction instr = instructions.next();

		PcodeOp[] pcode = instr.getPcode();
		if (pcode != null && pcode.length == 1 &&
			pcode[0].getOpcode() == PcodeOp.UNIMPLEMENTED) {
			markUnimplementedPcode(instr);
		}

		completed += instr.getLength();
		if ((completed % 1000) == 0) {
			monitor.setProgress(completed);
		}
	}

}
 
Example #14
Source File: OperandReferenceAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Check for any jumps to Externals (manufactured labels).
 * Any externals directly jumped to should be looked at as a call.
 *
 * Note: this shouldn't affect jumps in thunks, but beware...
 * @param monitor
 * @throws CancelledException
 */
private boolean checkForExternalJump(Program program, Reference reference, TaskMonitor monitor)
		throws CancelledException {
	// Check any direct jumps into the EXTERNAL memory section
	//   These don't return!
	if (externalBlock == null) {
		return false;
	}

	Address toAddr = reference.getToAddress();
	if (!externalBlock.contains(toAddr)) {
		return false;
	}
	Address fromAddr = reference.getFromAddress();
	Instruction instr = program.getListing().getInstructionAt(fromAddr);

	// override flow
	if (instr != null && instr.getFlowType().isJump()) {
		instr.setFlowOverride(FlowOverride.CALL_RETURN);
		// Get rid of any bad disassembly bookmark
		AddressSet set = new AddressSet(toAddr);
		program.getBookmarkManager()
				.removeBookmarks(set, BookmarkType.ERROR,
					Disassembler.ERROR_BOOKMARK_CATEGORY, monitor);
	}

	// make sure function created at destination
	Function func = program.getFunctionManager().getFunctionAt(toAddr);
	if (func == null) {
		CreateFunctionCmd createFuncCmd = new CreateFunctionCmd(null, toAddr,
			new AddressSet(toAddr, toAddr), SourceType.ANALYSIS);
		createFuncCmd.applyTo(program);
	}
	return true;
}
 
Example #15
Source File: DefaultDataCacheTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultCodeUnitsGetInvalidated() {
	CodeUnit cu = listing.getCodeUnitAt(addr(0x1001));
	assertTrue(cu instanceof Data);
	DataDB data = (DataDB) cu;
	assertTrue(!data.isDefined());
	assertTrue(!data.isInvalid());
	AddressSet restrictedSet = new AddressSet(addr(0x1000), addr(0x1003));
	Disassembler disassembler = Disassembler.getDisassembler(program, TaskMonitor.DUMMY, null);
	AddressSetView disAddrs = disassembler.disassemble(addr(0x1000), restrictedSet);
	assertTrue(!disAddrs.isEmpty());
	assertTrue(!data.checkIsValid());
	assertNull(listing.getCodeUnitAt(addr(0x1001)));
}
 
Example #16
Source File: CodeXmlMgr.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void disassemble(AddressSet set, TaskMonitor monitor) {
	Disassembler disassembler = Disassembler.getDisassembler(program, monitor, this);
	try {
		Listing listing = program.getListing();
		while (!set.isEmpty() && !monitor.isCancelled()) {
			Address start = set.getMinAddress();
			AddressSet disset = disassembler.disassemble(start, set);
			if (disset.isEmpty()) {
				Instruction instr = listing.getInstructionAt(start);
				if (instr == null) {
					AddressRange skipRange = set.iterator().next();
					log.appendMsg("Expected valid Instruction at " + start);
					log.appendMsg("...skipping code range " + skipRange.getMinAddress() +
						" to " + skipRange.getMaxAddress());
					set.delete(skipRange);
				}
				else {
					set.deleteRange(instr.getMinAddress(), instr.getMaxAddress());
				}
			}
			else {
				set.delete(disset);
			}
		}
	}
	catch (Exception e) {
		log.appendMsg("Error during disassembly: " + e.getMessage());
	}
}
 
Example #17
Source File: MarkUnimplementedPcode.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private void markUnimplementedPcode(Instruction instr) {
	currentProgram.getBookmarkManager().setBookmark(instr.getAddress(), BookmarkType.WARNING,
		Disassembler.UNIMPL_BOOKMARK_CATEGORY,
		"Instruction pcode is unimplemented: " + instr.getMnemonicString());
}
 
Example #18
Source File: AbstractListingMergeManagerTest.java    From ghidra with Apache License 2.0 4 votes vote down vote up
protected void disassemble(Program pgm, AddressSetView addrSet) {
	Disassembler disassembler = Disassembler.getDisassembler(pgm, TaskMonitor.DUMMY,
		DisassemblerMessageListener.IGNORE);
	disassembler.disassemble(addrSet.getMinAddress(), addrSet, false);
}
 
Example #19
Source File: CompareSleighExternal.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private void markErrorBad(Address addr, String type, String error) {
	currentProgram.getBookmarkManager().setBookmark(addr, BookmarkType.ERROR,
		Disassembler.ERROR_BOOKMARK_CATEGORY,
		error);
}
 
Example #20
Source File: ClearFlowAndRepairCmd.java    From ghidra with Apache License 2.0 4 votes vote down vote up
public static void clearBadBookmarks(Program program, AddressSetView set, TaskMonitor monitor)
		throws CancelledException {

	BookmarkManager bookmarkMgr = program.getBookmarkManager();

	// Check data fall-through locations for bookmarks
	Listing listing = program.getListing();
	for (AddressRange range : set.getAddressRanges()) {
		monitor.checkCanceled();
		Address maxAddr = range.getMaxAddress();
		Instruction lastInstr = listing.getInstructionContaining(maxAddr);
		if (lastInstr == null) {
			continue;
		}
		Address nextAddr = lastInstr.getFallThrough();
		if (nextAddr == null) {
			continue;
		}
		if (listing.getDataContaining(nextAddr) != null) {
			Bookmark bookmark = bookmarkMgr.getBookmark(nextAddr, BookmarkType.ERROR,
				Disassembler.ERROR_BOOKMARK_CATEGORY);
			if (bookmark != null) {
				bookmarkMgr.removeBookmark(bookmark);
			}
		}
	}

	// Check any offcut flows that are not part of the cleared set
	//    This assumes that any bookmark at then end of a to reference from the
	//      cleared set is not a good bookmark.  Could test that there are no other refs to it
	ReferenceManager referenceManager = program.getReferenceManager();
	AddressIterator refIter = referenceManager.getReferenceSourceIterator(set, true);
	for (Address address : refIter) {
		Reference[] referencesFrom = referenceManager.getReferencesFrom(address);
		for (Reference reference : referencesFrom) {
			Address toAddr = reference.getToAddress();
			if (set.contains(toAddr)) {
				continue;
			}
			// if we aren't offcut, continue
			if (listing.getInstructionAt(toAddr) != null) {
				continue;
			}
			// no bookmark there, continue;
			if (program.getBookmarkManager().getBookmarks(toAddr).length == 0) {
				continue;
			}
			// not the right references
			int referenceCountTo = referenceManager.getReferenceCountTo(toAddr);
			if (referenceCountTo > 1) {
				// if more than one ref, must make sure all others are not data refs
				ReferenceIterator referencesTo = referenceManager.getReferencesTo(toAddr);
				int flowCount = 0;
				for (Reference referenceTo : referencesTo) {
					if (referenceTo.getReferenceType().isFlow()) {
						flowCount++;
					}
				}
				if (flowCount != 1) {
					continue;
				}
			}
			clearBadBookmarks(program, toAddr, toAddr, monitor);
		}

	}

	bookmarkMgr.removeBookmarks(set, BookmarkType.ERROR, Disassembler.ERROR_BOOKMARK_CATEGORY,
		monitor);
}
 
Example #21
Source File: ClearFlowAndRepairCmd.java    From ghidra with Apache License 2.0 4 votes vote down vote up
public static void clearBadBookmarks(Program program, Address start, Address end,
		TaskMonitor monitor) throws CancelledException {
	AddressSet set = new AddressSet(start, end);
	program.getBookmarkManager().removeBookmarks(set, BookmarkType.ERROR,
		Disassembler.ERROR_BOOKMARK_CATEGORY, monitor);
}
 
Example #22
Source File: ClearFlowAndRepairCmd.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
	 * Repair fall-through flows which fall into the cleared area.
	 */
	private AddressSetView repairFallThroughsInto(Program program, AddressSetView clearSet,
			Address ignoreStart, TaskMonitor monitor) throws CancelledException {

		AddressSet disassemblePoints = new AddressSet();
		//AddressSet alreadyCleared = new AddressSet(program.getAddressFactory());

		Listing listing = program.getListing();

		ProgramContext programContext = program.getProgramContext();
		Register contextReg = programContext.getBaseContextRegister();
		DisassemblerContextImpl seedContext = null;

		AddressRangeIterator rangeIter = clearSet.getAddressRanges();
		while (rangeIter.hasNext()) {
			monitor.checkCanceled();
			AddressRange range = rangeIter.next();
			Address addr = range.getMinAddress();
			int searchCnt = 0;

			// Search backward for incomplete fallthrough
			// A fallthrough to ignoreStart is ignored
			while (searchCnt < FALLTHROUGH_SEARCH_LIMIT && (addr = addr.previous()) != null) {
				CodeUnit cu = listing.getCodeUnitAt(addr);
				if (cu == null) {
					if (!program.getMemory().contains(addr)) {
						break;
					}
					continue; // in middle of code unit
				}
				if (cu instanceof Instruction) {
					Instruction instr = (Instruction) cu;
					if (instr.isInDelaySlot()) {
						continue;
					}
					Address ftAddr = instr.getFallThrough();
					if (ftAddr != null && (ignoreStart == null || !ftAddr.equals(ignoreStart))) {
//                        alreadyCleared.addRange(ftAddr, addr);
						disassemblePoints.addRange(ftAddr, ftAddr);
						if (contextReg != null) {
							if (seedContext == null) {
								seedContext = new DisassemblerContextImpl(programContext);
							}
							repairFallThroughContextFrom(program, instr.getMinAddress(),
								seedContext);
						}
					}
					break;
				}
				Data d = (Data) cu;
				if (d.isDefined()) {
					break;
				}
				++searchCnt;
			}
		}
//         clearSet.add(alreadyCleared);

		// Get rid of any bad bookmarks at seed points, will be put back if they are still bad.
		program.getBookmarkManager().removeBookmarks(disassemblePoints, BookmarkType.ERROR,
			Disassembler.ERROR_BOOKMARK_CATEGORY, monitor);

		// Disassemble fallthrough reference points
		DisassembleCommand cmd = new DisassembleCommand(disassemblePoints, null);
		cmd.setSeedContext(seedContext);
		cmd.applyTo(program, monitor);

		return cmd.getDisassembledAddressSet();
	}
 
Example #23
Source File: iOS_Analyzer.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public boolean analyze(Program program, AddressSetView set, TaskMonitor monitor,
		final MessageLog log) throws Exception {

	DisassemblerMessageListener listener = new DisassemblerMessageListener() {
		@Override
		public void disassembleMessageReported(String msg) {
			log.appendMsg(msg);
		}
	};

	Address imageBase = program.getImageBase();

	AutoAnalysisManager manager = AutoAnalysisManager.getAnalysisManager(program);

	Disassembler disassembler = Disassembler.getDisassembler(program, monitor, listener);

	disassembler.disassemble(imageBase.add(0x00000000L), null, false);
	manager.disassemble(imageBase.add(0x00000000L));

	disassembler.disassemble(imageBase.add(0x00000004L), null, false);
	disassembler.disassemble(imageBase.add(0x00000008L), null, false);
	disassembler.disassemble(imageBase.add(0x0000000cL), null, false);
	disassembler.disassemble(imageBase.add(0x00000010L), null, false);
	disassembler.disassemble(imageBase.add(0x00000014L), null, false);
	disassembler.disassemble(imageBase.add(0x00000018L), null, false);
	disassembler.disassemble(imageBase.add(0x0000001cL), null, false);

	disassembler.disassemble(imageBase.add(0x00000020L),
		new AddressSet(imageBase.add(0x00000020L)), false);

	disassembler.disassemble(imageBase.add(0x00000040L), null, false);
	disassembler.disassemble(imageBase.add(0x00000074L), null, false);

	createData(program, imageBase.add(0x00000200L), new StringDataType());
	createData(program, imageBase.add(0x00000240L), new StringDataType());
	createData(program, imageBase.add(0x00000280L), new StringDataType());

	long offset = 0x0000032cL;
	while (!monitor.isCancelled()) {
		if (offset > 0x000005e8) {//end of ARM code...
			break;
		}
		disassembler.disassemble(imageBase.add(offset), null);
		Function function = createFunction(program, imageBase.add(offset));
		if (function == null) {
			break;
		}
		offset = function.getBody().getMaxAddress().getOffset() + 1 - imageBase.getOffset();
	}

	log.appendMsg("You should now run the iOS_ThumbFunctionFinder script!");

	return true;
}
 
Example #24
Source File: Emulator.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Disassemble from the current execute address
 * @param count number of contiguous instructions to disassemble
 * @return list of instructions
 */
public List<String> disassemble(Integer count) {
	if (!emuHalt || isExecuting) {
		throw new IllegalStateException("disassembly not allowed while emulator is executing");
	}

	// TODO: This can provide bad disassembly if reliant on future context state (e.g., end of loop)

	List<String> disassembly = new ArrayList<>();

	EmulateDisassemblerContext disassemblerContext = emulator.getNewDisassemblerContext();
	Address addr = getExecuteAddress();
	EmulateMemoryStateBuffer memBuffer = new EmulateMemoryStateBuffer(memState, addr);

	Disassembler disassembler = Disassembler.getDisassembler(language, addrFactory,
		TaskMonitor.DUMMY, null);

	boolean stopOnError = false;

	while (count > 0 && !stopOnError) {
		memBuffer.setAddress(addr);
		disassemblerContext.setCurrentAddress(addr);

		InstructionBlock block = disassembler.pseudoDisassembleBlock(memBuffer,
			disassemblerContext.getCurrentContextRegisterValue(), count);

		if (block.hasInstructionError() && count > block.getInstructionCount()) {
			InstructionError instructionError = block.getInstructionConflict();
			Msg.error(this,
				"Target disassembler error at " + instructionError.getConflictAddress() + ": " +
					instructionError.getConflictMessage());
			stopOnError = true;
		}

		Instruction lastInstr = null;
		Iterator<Instruction> iterator = block.iterator();
		while (iterator.hasNext() && count != 0) {
			Instruction instr = iterator.next();
			disassembly.add(instr.getAddressString(false, true) + " " + instr.toString());
			lastInstr = instr;
			--count;
		}

		try {
			addr = lastInstr.getAddress().addNoWrap(lastInstr.getLength());
		}
		catch (Exception e) {
			count = 0;
		}
	}

	return disassembly;
}
 
Example #25
Source File: PowerPC_ElfExtension.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Identify presence of blrl instruction within .got section with execute permission.
 * The instruction will be disassembled and transformed into a get_pc_thunk_lr function
 * with an applied call-fixup.
 * @param elfLoadHelper
 * @param monitor
 * @throws CancelledException
 */
private void markupGotBLRL(ElfLoadHelper elfLoadHelper, TaskMonitor monitor)
		throws CancelledException {

	Program program = elfLoadHelper.getProgram();
	Memory memory = program.getMemory();
	Listing listing = program.getListing();

	boolean applyCallFixup = gotThunkCallFixupExists(program);

	Disassembler disassembler = Disassembler.getDisassembler(program, monitor, null);

	MemoryBlock[] blocks = memory.getBlocks();

	for (MemoryBlock block : blocks) {
		monitor.checkCanceled();

		MemoryBlock gotBlock = block;

		if (!gotBlock.getName().startsWith(ElfSectionHeaderConstants.dot_got) ||
			!gotBlock.isExecute()) {
			continue;
		}

		Address blrlAddr = findBLRL(gotBlock, memory.isBigEndian());
		if (blrlAddr == null) {
			continue;
		}

		listing.clearCodeUnits(blrlAddr, gotBlock.getEnd(), false);

		Address blrlEndAddr = blrlAddr.add(3);
		AddressSet range = new AddressSet(blrlAddr, blrlEndAddr);

		disassembler.disassemble(blrlAddr, range);

		try {
			Instruction blrlInstr = listing.getInstructionAt(blrlAddr);
			if (blrlInstr == null) {
				elfLoadHelper.log(
					"Failed to generate blrl instruction within " + gotBlock.getName());
				continue;
			}

			blrlInstr.setFlowOverride(FlowOverride.RETURN);

			Function f = listing.createFunction(GOT_THUNK_NAME + gotBlock.getName(), blrlAddr,
				range, SourceType.IMPORTED);
			if (applyCallFixup) {
				f.setCallFixup(GOT_THUNK_NAME);
			}

		}
		catch (InvalidInputException | OverlappingFunctionException e) {
			// should not happen
		}

	}
}
 
Example #26
Source File: DisassemblerPlugin.java    From ghidra with Apache License 2.0 2 votes vote down vote up
/**
 * @see ghidra.app.plugin.contrib.disassembler.DisassemblyTaskListener#disassemblyDone(DisassemblyTask)
 */
public void disassemblyDone(Disassembler task) {
}