Java Code Examples for ghidra.program.disassemble.Disassembler#getDisassembler()

The following examples show how to use ghidra.program.disassemble.Disassembler#getDisassembler() . 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: 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 2
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 3
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 4
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 5
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 6
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 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: 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 9
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 10
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 11
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 12
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 13
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 14
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 15
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);
}