Java Code Examples for ghidra.util.task.TaskMonitor#isCancelled()

The following examples show how to use ghidra.util.task.TaskMonitor#isCancelled() . 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: PdbDataTypeParser.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private DataType findDataTypeInArchives(String datatype, TaskMonitor monitor)
		throws CancelledException {

	DataTypeManager[] managers = service.getDataTypeManagers();
	Arrays.sort(managers, new PdbDataTypeManagerComparator());
	for (DataTypeManager manager : managers) {
		if (monitor.isCancelled()) {
			throw new CancelledException();
		}
		DataType dt = DataTypeUtilities.findNamespaceQualifiedDataType(manager, datatype, null);
		if (dt != null) {
			cacheDataType(datatype, dt);
			return dt;
		}
	}
	return null;
}
 
Example 2
Source File: ArchiveTask.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private boolean writeProjectDirs(JarWriter writer, TaskMonitor monitor) {
	File projectFolder = project.getProjectLocator().getProjectDir();
	String[] names = projectFolder.list();
	for (int i = 0; i < names.length; i++) {
		if (monitor.isCancelled()) {
			return false;
		}
		File file = new File(projectFolder, names[i]);
		monitor.setMessage("Writing " + file.getAbsolutePath());
		if (file.isDirectory()) {
			if (!writer.outputRecursively(file, "", monitor)) {
				return false;
			}
		}
	}
	return true;
}
 
Example 3
Source File: ClearCmd.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void removeRefs(ReferenceManager refMgr, AddressIterator iter,
		Set<SourceType> sourceTypesToClear, TaskMonitor monitor) throws CancelledException {
	while (iter.hasNext()) {

		monitor.checkCanceled();

		Address addr = iter.next();
		Reference[] refs = refMgr.getReferencesFrom(addr);
		for (Reference ref : refs) {
			if (monitor.isCancelled()) {
				break;
			}
			SourceType source = ref.getSource();
			if (sourceTypesToClear.contains(source)) {
				refMgr.delete(ref);
			}
		}
		monitor.incrementProgress(1);
	}
}
 
Example 4
Source File: PropertiesXmlMgr.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void writeVoidMap(VoidPropertyMap map, XmlWriter writer, AddressSetView set,
		TaskMonitor monitor) throws CancelledException {
	AddressIterator iter =
		set != null ? map.getPropertyIterator(set) : map.getPropertyIterator();
	while (iter.hasNext()) {
		if (monitor.isCancelled()) {
			throw new CancelledException();
		}
		Address addr = iter.next();
		XmlAttributes attrs = new XmlAttributes();
		attrs.addAttribute("NAME", map.getName());
		attrs.addAttribute("ADDRESS", XmlProgramUtilities.toString(addr));
		attrs.addAttribute("TYPE", "void");
		writer.startElement("PROPERTY", attrs);
		writer.endElement("PROPERTY");
	}
}
 
Example 5
Source File: FunctionDB.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private Set<Reference> getReferencesFromBody(TaskMonitor monitor) {
	Set<Reference> set = new HashSet<>();
	ReferenceManager referenceManager = program.getReferenceManager();
	AddressSetView addresses = getBody();
	AddressIterator addressIterator = addresses.getAddresses(true);
	while (addressIterator.hasNext()) {
		if (monitor.isCancelled()) {
			return set;
		}
		Address address = addressIterator.next();
		Reference[] referencesFrom = referenceManager.getReferencesFrom(address);
		if (referencesFrom != null) {
			for (Reference reference : referencesFrom) {
				set.add(reference);
			}
		}
	}
	return set;
}
 
Example 6
Source File: SymbolNode.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public List<GTreeNode> generateChildren(TaskMonitor monitor) {
	List<GTreeNode> list = new ArrayList<>();

	if (program.isClosed()) {
		return list;
	}
	SymbolTable symbolTable = program.getSymbolTable();
	SymbolIterator iter = symbolTable.getChildren(symbol);
	while (iter.hasNext()) {
		if (monitor.isCancelled()) {
			return Collections.emptyList();
		}
		list.add(createNode(iter.next(), program));
	}

	sort(list);

	return list;
}
 
Example 7
Source File: PrelinkParser.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private PrelinkMap processElement(Element parentElement, TaskMonitor monitor) {
	PrelinkMap map = new PrelinkMap();
	Iterator<?> iterator = parentElement.getChildren().iterator();
	while (iterator.hasNext()) {
		if (monitor.isCancelled()) {
			break;
		}
		Element element = (Element) iterator.next();
		if (element.getName().equals(TAG_KEY)) {
			Element valueElement = (Element) iterator.next();
			processValue(element, valueElement, map, monitor);
		}
		else {
			//TODO bad parse state...
		}
	}
	return map;
}
 
Example 8
Source File: ClosedSequenceMiner.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * "bide" is short for "BiDirectional Extension", the name of the algorithm
 * in the paper by Wang & Han
 * @param projectedDatabase
 * @param monitor 
 */
private void bide(ProjectedDatabase projectedDatabase, TaskMonitor monitor) {
	TreeSet<FrequentSequenceItem> locallyFrequentItems =
		projectedDatabase.getLocallyFrequentItems(globallyFrequentItems, minSupport);
	Set<FrequentSequenceItem> forwardExtensionItems =
		projectedDatabase.getForwardExtensionItems(locallyFrequentItems);
	if (forwardExtensionItems.size() == 0) {
		frequentClosedSequences.add(new FrequentSequence(projectedDatabase.getPrefix(),
			projectedDatabase.getSupport()));
	}
	for (FrequentSequenceItem fItem : locallyFrequentItems) {
		if (monitor.isCancelled()) {
			return;
		}
		ProjectedDatabase extended = new ProjectedDatabase(projectedDatabase, fItem.getItem());
		Set<FrequentSequenceItem> backwardExtensionItems = extended.getBackwardExtensionItems();
		if (backwardExtensionItems.size() == 0) {
			bide(extended, monitor);
		}
	}
}
 
Example 9
Source File: Pic18Analyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void blockAdded(CodeBlock block, TaskMonitor monitor) throws CancelledException {

		boolean newBlock = true;

		InstructionIterator instIter = listing.getInstructions(block, true);
		while (!monitor.isCancelled() && instIter.hasNext()) {
			Instruction instr = instIter.next();

			if (newBlock) {
				startNewBlock(instr);
				newBlock = false;
			}

			checkRegisterAccess(instr);

			String mnemonic = instr.getMnemonicString();
			if ("MOVFF".equals(mnemonic)) {
				markupFRegInstruction(instr, 0, RefType.READ);
				markupFRegInstruction(instr, 1, RefType.WRITE);
			}
			else if ("MOVSF".equals(mnemonic)) {
				markupFRegInstruction(instr, 1, RefType.WRITE);
			}
			else if (FREG_INSTRUCTIONS.contains(mnemonic)) {
				markupFRegInstruction(instr, 0, null);
			}
			else if (FREG_BIT_INSTRUCTIONS.contains(mnemonic)) {
				markupFRegAndBitInstruction(instr);
			}

			if (SKIP_INSTRUCTIONS.contains(mnemonic)) {
				addSkipReference(instr);
			}

		}
		bsrContext.writeValue(block.getMaxAddress());
		monitor.checkCanceled();
	}
 
Example 10
Source File: AbstractDyldInfoProcessor.java    From ghidra with Apache License 2.0 5 votes vote down vote up
protected String readString( ByteArrayInputStream byteStream, TaskMonitor monitor ) {
	StringBuffer buffer = new StringBuffer();
	while ( !monitor.isCancelled() ) {
		int value = byteStream.read();
		if ( value == -1 ) {
			break;
		}
		byte b = (byte) value;
		if ( b == '\0' ) {
			break;
		}
		buffer.append( (char) ( b & 0xff ) );
	}
	return buffer.toString();
}
 
Example 11
Source File: ApplyEnums.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Perform parsing and applying of enum datatypes
 * @param pdbParser PDB parser object
 * @param xmlParser XML parser position immediately after the enums start element
 * @param monitor task monitor
 * @param log message log
 * @throws CancelledException if task cancelled
 */
static void applyTo(XmlPullParser xmlParser, PdbParser pdbParser, TaskMonitor monitor,
		MessageLog log) throws CancelledException {
	monitor.setMessage("Applying enums...");
	while (xmlParser.hasNext()) {
		monitor.checkCanceled();
		XmlElement elem = xmlParser.next();

		if (elem.isEnd() && elem.getName().equals("enums")) {
			break;
		}

		String name = SymbolUtilities.replaceInvalidChars(elem.getAttribute("name"), false);
		int length = XmlUtilities.parseInt(elem.getAttribute("length"));
		EnumDataType enumdt = pdbParser.createEnum(name, length);

		while (xmlParser.hasNext()) {
			if (monitor.isCancelled()) {
				break;
			}
			elem = xmlParser.next();
			if (elem.isEnd() && elem.getName().equals("enum")) {
				break;
			}
			applyEnumMember(enumdt, elem, monitor, log);
			xmlParser.next();//member end element
		}
		pdbParser.cacheDataType(name, enumdt); // cache with namespace-based name
		pdbParser.getProgramDataTypeManager()
				.resolve(enumdt,
					DataTypeConflictHandler.REPLACE_EMPTY_STRUCTS_OR_RENAME_AND_ADD_HANDLER);
	}
}
 
Example 12
Source File: OldJad.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private String readStderrMessagesFromProcess(Process process, TaskMonitor monitor)
		throws IOException {
	StringBuffer buffer = new StringBuffer();
	byte[] bytes = new byte[0x1000];
	InputStream processErrorStream = process.getErrorStream();
	while (!monitor.isCancelled()) {
		int nRead = processErrorStream.read(bytes);
		if (nRead == -1) {
			break;
		}
		buffer.append(new String(bytes, 0, nRead));
	}
	return buffer.toString();
}
 
Example 13
Source File: OpenCloseManager.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void toggleDataRecursivlyUsingSubMonitor(Data data, boolean openState,
		TaskMonitor monitor) {
	if (data == null && !monitor.isCancelled()) {
		return;
	}

	if (isOpen(data) != openState) {
		toggleTopLevelData(data);
	}

	int componentCount = data.getNumComponents();
	for (int i = 0; i < componentCount && !monitor.isCancelled(); i++) {
		toggleDataRecursivlyUsingSubMonitor(data.getComponent(i), openState, monitor);
	}
}
 
Example 14
Source File: ApplyLineNumbers.java    From ghidra with Apache License 2.0 5 votes vote down vote up
void applyTo(TaskMonitor monitor, MessageLog log) {
	while (xmlParser.hasNext()) {
		if (monitor.isCancelled()) {
			return;
		}
		XmlElement elem = xmlParser.peek();
		if (elem.isEnd() && elem.getName().equals("function")) {
			break;
		}
		elem = xmlParser.next();//line number start tag
		String sourcefileName = elem.getAttribute("source_file");

		int start = XmlUtilities.parseInt(elem.getAttribute("start"));
		int addr = XmlUtilities.parseInt(elem.getAttribute("addr"));
		Address address = PdbUtil.reladdr(program, addr);
		// The following line was changed from getCodeUnitAt(address) to
		// getCodeUnitContaining(address) in order to fix an issue where the PDB associates
		// a line number with base part of an instruction instead of the prefix part of an
		// instruction.  In particular, Microsoft emits a "REP RET" (f3 c3) sequence, where
		// the "REP" is an instruction prefix, in order to avoid a branch prediction penalty
		// for AMD processors.  However, Microsoft associates the line number of the
		// instruction with the address of the "RET" (c3) instead of with the address of the
		// "REP" (f3) portion (beginning) of the instruction.
		CodeUnit cu = program.getListing().getCodeUnitContaining(address);
		if (cu == null) {
			log.appendMsg("PDB",
				"Could not apply source code line number (no code unit found at " + address +
					")");
		}
		else {
			cu.setProperty("Source Path", sourcefileName);
			cu.setProperty("Source File", new File(sourcefileName).getName());
			cu.setProperty("Source Line", start);
		}
		//String comment = sourcefile.getName()+":"+start;
		//setComment(CodeUnit.PRE_COMMENT, program.getListing(), address, comment);
		elem = xmlParser.next();//line number end tag
	}
}
 
Example 15
Source File: DatabaseRangeMapAdapter.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * @see ghidra.program.util.RangeMapAdapter#setLanguage(ghidra.program.util.LanguageTranslator, ghidra.program.model.lang.Register, ghidra.util.task.TaskMonitor)
 */
@Override
public void setLanguage(LanguageTranslator translator, Register mapReg, TaskMonitor monitor)
		throws CancelledException {

	Register newReg = translator.getNewRegister(mapReg);
	if (newReg == null) {
		// register not translated - clear map
		rangeMap.dispose();
		rangeMap = null;
		return;
	}
	Register newBaseReg = newReg.getBaseRegister();

	AddressRangeMapDB tempMap = null;
	if (!newReg.isBaseRegister() || translator.isValueTranslationRequired(mapReg)) {

		// Create temporary map
		String tempName = "TEMP_MAP";
		int retry = 0;
		while (AddressRangeMapDB.exists(dbh, tempName)) {
			tempName = "TEMP_MAP" + (++retry);
		}
		tempMap =
			new AddressRangeMapDB(dbh, addressMap, new Lock("Test"), tempName, errorHandler,
				BinaryField.class, false);

		// Translate range map data into tempMap
		monitor.initialize(rangeMap.getRecordCount());
		monitor.setMessage("Converting " + mapReg.getName() + " values...");
		int cnt = 0;
		AddressRangeIterator rangeIter = rangeMap.getAddressRanges();
		while (rangeIter.hasNext()) {
			if (monitor.isCancelled()) {
				tempMap.dispose();
				throw new CancelledException();
			}
			AddressRange range = rangeIter.next();
			BinaryField value = (BinaryField) rangeMap.getValue(range.getMinAddress());
			byte[] oldBytes = value.getBinaryData();
			RegisterValue regValue = new RegisterValue(mapReg, oldBytes);
			regValue = translator.getNewRegisterValue(regValue);
			if (regValue != null && regValue.hasAnyValue()) {
				byte[] newBytes = regValue.toBytes();
				tempMap.paintRange(range.getMinAddress(), range.getMaxAddress(),
					new BinaryField(newBytes));
			}
			monitor.setProgress(++cnt);
		}
	}

	String newMapName = NAME_PREFIX + newBaseReg.getName();
	if (tempMap == null) {
		if (mapName.equals(newMapName)) {
			// Nothing to change
			return;
		}
	}
	else {
		rangeMap.dispose();
		rangeMap = tempMap;
	}
	if (rangeMap != null) {
		try {
			rangeMap.setName(newMapName);
		}
		catch (DuplicateNameException e) {
			throw new AssertException("Unexpected DuplicateNameException");
		}
	}
	mapName = newMapName;
}
 
Example 16
Source File: BookmarkDBAdapterV0.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Set the old bookmark manager which handles read-only access
 * to bookmarks stored within property maps.
 * The old bookmark manager must be set prior to invoking any other method;
 * @param oldMgr old bookmark manager
 */
void setOldBookmarkManager(OldBookmarkManager oldMgr, AddressMap addrMap, TaskMonitor monitor)
		throws IOException {

	// Convert old bookmarks to new schema using temporary database
	// This is the easiest way to index into the old bookmarks
	tmpHandle = new DBHandle();
	try {
		conversionAdapter =
			BookmarkDBAdapter.getAdapter(tmpHandle, DBConstants.CREATE, new int[0], addrMap,
				monitor);
	}
	catch (VersionException e) {
		throw new AssertException();
	}
	Record[] oldTypes = oldMgr.getTypeRecords();
	if (oldTypes.length == 0) {
		return;
	}

	monitor.setMessage("Translating Old Bookmarks...");
	int max = 0;
	for (int i = 0; i < oldTypes.length; i++) {
		max +=
			oldMgr.getBookmarkCount(oldTypes[i].getString(BookmarkTypeDBAdapter.TYPE_NAME_COL));
	}
	monitor.initialize(max);
	int cnt = 0;

	for (int i = 0; i < oldTypes.length; i++) {
		String type = oldTypes[i].getString(BookmarkTypeDBAdapter.TYPE_NAME_COL);
		int typeId = (int) oldTypes[i].getKey();
		conversionAdapter.addType(typeId);
		AddressIterator iter = oldMgr.getBookmarkAddresses(type);
		while (iter.hasNext()) {
			if (monitor.isCancelled()) {
				throw new IOException("Upgrade Cancelled");
			}
			Address addr = iter.next();
			OldBookmark bm = oldMgr.getBookmark(addr, type);
			conversionAdapter.createBookmark(typeId, bm.getCategory(),
				addrMap.getKey(addr, true), bm.getComment());
			monitor.setProgress(++cnt);
		}
	}
}
 
Example 17
Source File: NeLoader.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public void load(ByteProvider provider, LoadSpec loadSpec, List<Option> options, Program prog,
		TaskMonitor monitor, MessageLog log) throws IOException, CancelledException {

	if (monitor.isCancelled()) {
		return;
	}
	monitor.setMessage("Processing new executable...");

	initVars();

	ContinuesFactory factory = MessageLogContinuesFactory.create(log);

	// We don't use the file bytes to create block because the bytes are manipulated before
	// forming the block.  Creating the FileBytes anyway in case later we want access to all
	// the original bytes.
	MemoryBlockUtils.createFileBytes(prog, provider, monitor);

	SegmentedAddressSpace space =
		(SegmentedAddressSpace) prog.getAddressFactory().getDefaultAddressSpace();
	NewExecutable ne = new NewExecutable(factory, provider, space.getAddress(SEGMENT_START, 0));
	WindowsHeader wh = ne.getWindowsHeader();
	InformationBlock ib = wh.getInformationBlock();
	SegmentTable st = wh.getSegmentTable();
	ResourceTable rt = wh.getResourceTable();
	EntryTable et = wh.getEntryTable();
	ResidentNameTable rnt = wh.getResidentNameTable();
	NonResidentNameTable nrnt = wh.getNonResidentNameTable();
	ImportedNameTable imp = wh.getImportedNameTable();
	ModuleReferenceTable mrt = wh.getModuleReferenceTable();

	Listing listing = prog.getListing();
	SymbolTable symbolTable = prog.getSymbolTable();
	Memory memory = prog.getMemory();
	ProgramContext context = prog.getProgramContext();
	RelocationTable relocTable = prog.getRelocationTable();

	if (monitor.isCancelled()) {
		return;
	}
	monitor.setMessage("Processing segment table...");
	processSegmentTable(log, ib, st, space, prog, context, monitor);
	if (prog.getMemory().isEmpty()) {
		Msg.error(this, "Empty memory for " + prog);
		return;
	}

	if (monitor.isCancelled()) {
		return;
	}
	monitor.setMessage("Processing resource table...");
	processResourceTable(log, prog, rt, space, monitor);

	if (monitor.isCancelled()) {
		return;
	}
	monitor.setMessage("Processing module reference table...");
	processModuleReferenceTable(mrt, st, imp, prog, space, log, monitor);

	if (monitor.isCancelled()) {
		return;
	}
	monitor.setMessage("Processing entry table...");
	processEntryTable(st, ib, et, symbolTable, space);

	if (monitor.isCancelled()) {
		return;
	}
	monitor.setMessage("Processing non-resident name table...");
	processNonResidentNameTable(nrnt, symbolTable);

	if (monitor.isCancelled()) {
		return;
	}
	monitor.setMessage("Processing resident name table...");
	processResidentNameTable(rnt, symbolTable);

	if (monitor.isCancelled()) {
		return;
	}
	monitor.setMessage("Processing segment relocations...");
	processRelocations(st, imp, mrt, relocTable, prog, memory, space, log, monitor);

	if (monitor.isCancelled()) {
		return;
	}
	monitor.setMessage("Processing information block...");
	processInformationBlock(ib, nrnt, memory, listing);

	processProperties(ib, prog, monitor);

}
 
Example 18
Source File: iOS_KextStubFixupAnalyzer.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 {

	//attempt to get the program manager service
	//we can keep working without it, but the analysis will run much slower
	ProgramManager programManager = null;
	AutoAnalysisManager autoAnalysisManager = AutoAnalysisManager.getAnalysisManager(program);
	if (autoAnalysisManager != null) {
		PluginTool tool = autoAnalysisManager.getAnalysisTool();
		if (tool != null) {
			programManager = tool.getService(ProgramManager.class);
		}
	}

	Listing listing = program.getListing();
	SymbolTable symbolTable = program.getSymbolTable();
	Memory memory = program.getMemory();
	ReferenceManager referenceManager = program.getReferenceManager();
	ExternalManager externalManager = program.getExternalManager();

	MemoryBlock stubBlock = memory.getBlock("__stub");
	if (stubBlock == null) {
		stubBlock = memory.getBlock("__stubs");
	}
	if (stubBlock == null) {
		return true;
	}
	disassembleStubSection(program, stubBlock, monitor);
	Namespace stubNameSpace = getOrCreateNameSpace(program, stubBlock);

	MemoryBlock destinationBlock = memory.getBlock("__nl_symbol_ptr");
	if (destinationBlock == null) {
		destinationBlock = memory.getBlock("__got");
	}
	if (destinationBlock == null) {
		return true;
	}
	markupNonLazySymbolPointerSection(program, destinationBlock, monitor);
	Namespace nlSymbolPtrNameSpace = getOrCreateNameSpace(program, destinationBlock);

	DataIterator dataIterator =
		program.getListing().getData(toAddressSet(destinationBlock), true);
	while (dataIterator.hasNext()) {

		if (monitor.isCancelled()) {
			break;
		}

		Data data = dataIterator.next();

		if (data.getMinAddress().compareTo(destinationBlock.getEnd()) > 0) {
			break;
		}

		monitor.setMessage("Fixing STUB section at " + data.getMinAddress());

		Object value = data.getValue();

		if (!(value instanceof Address)) {
			continue;
		}

		Address destinationAddress = (Address) value;

		if (memory.contains(destinationAddress)) {
			continue;
		}

		if ((destinationAddress.getOffset() % 2) != 0) {
			destinationAddress =
				destinationAddress.getNewAddress(destinationAddress.getOffset() - 1);
		}

		DestinationProgramInfo destinationProgramInfo =
			findDestinationProgram(program, programManager, destinationAddress, monitor);

		if (destinationProgramInfo == null) {
			continue;
		}

		createSymbolInNonLazySymbolPointerSection(symbolTable, nlSymbolPtrNameSpace, data,
			destinationProgramInfo);

		createExternalReferenceInNonLazySymbolPointerSection(referenceManager, externalManager,
			data, destinationAddress, destinationProgramInfo);

		createSymbolInStubSection(listing, symbolTable, referenceManager, stubNameSpace, data,
			destinationProgramInfo, monitor);
	}

	return true;
}
 
Example 19
Source File: DyldCacheAnalyzer.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 headerAddress = program.getMinAddress();

	ByteProvider provider = new MemoryByteProvider(program.getMemory(), headerAddress);

	DyldArchitecture architecture = DyldArchitecture.getArchitecture(provider);
	if (architecture == null) {
		log.appendMsg("Invalid DYLD cache file.");
		return false;
	}

	BinaryReader reader =
		new BinaryReader(provider, architecture.getEndianness() == Endian.LITTLE);

	DyldCacheHeader header = new DyldCacheHeader(reader);

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

	reader.setPointerIndex(header.getImagesOffset());
	Address address = toAddr(program, header.getImagesOffset());

	for (int i = 0; i < header.getImagesCount(); ++i) {

		if (monitor.isCancelled()) {
			break;
		}

		DyldCacheImageInfo data = new DyldCacheImageInfo(reader);
		DataType dataDataType = data.toDataType();
		Data dataData = createData(program, address, dataDataType);
		createFragment(program, dataDataType.getName(), dataData.getMinAddress(),
			dataData.getMaxAddress().add(1));

		Address fileOffset = toAddr(program, data.getAddress());
		Data fileData = createData(program, fileOffset, new StringDataType());
		createFragment(program, "LibraryNames", fileData.getMinAddress(),
			fileData.getMaxAddress().add(1));

		String filePath = (String) fileData.getValue();

		Address libraryOffsetAddress =
			toAddr(program, data.getAddress() - header.getBaseAddress());

		MachoBinaryAnalysisCommand command = new MachoBinaryAnalysisCommand(
			libraryOffsetAddress, false, program.getListing().getDefaultRootModule());
		command.applyTo(program, monitor);

		setPlateComment(program, address, filePath);
		setPlateComment(program, libraryOffsetAddress, filePath);

		address = address.add(dataDataType.getLength());
	}

	updateImageBase(program, header);

	return false;
}
 
Example 20
Source File: DisassemblerQueue.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Return next block to disassemble for the current InstructionSet.
 * @param fallThruAddr specifies the next instruction to be disassembled if the 
 * previous instruction had a fall-through.  If specified, the previous block 
 * will be return.  If null, the next block to be disassembled will be returned. 
 * @param memory needed for normalization of SegementedAddresses (may be null).
 * @param monitor cancellable task monitor 
 * @return next block to be disassembled or null if no more queued flows to process
 * for current InstructionSet, or remaining flows fall outside restricted address set,
 * monitor has cancelled disassembly.
 */
InstructionBlock getNextBlockToBeDisassembled(Address fallThruAddr, Memory memory,
		TaskMonitor monitor) {

	if (monitor != null && monitor.isCancelled()) {
		lastBlock = null;
		return null;
	}

	if (fallThruAddr != null) {
		if (lastBlock == null) {
			throw new IllegalStateException();
		}
		// no state change fallThruAddr is 
		if (fallThruAddr.equals(lastBlockAddr)) {
			return lastBlock;
		}
		// fallthrough within block - continue disassembly of last block
		lastFlowFrom = lastBlockAddr;
		lastBlockAddr = fallThruAddr;

		if (checkMemoryRestriction(fallThruAddr)) {
			lastFlowFrom = lastBlockAddr;
			lastBlockAddr = fallThruAddr;
			return lastBlock;
		}
	}

	lastBlock = null;
	lastBlockAddr = null;
	lastFlowFrom = null;

	while ((monitor == null || !monitor.isCancelled()) &&
		(fallThruAddr != null || !priorityQueue.isEmpty() || !currentBranchQueue.isEmpty())) {

		// Prepare new block using next queued flow
		boolean forcedStartOfFlow = false;
		InstructionBlockFlow branchFlow = null;
		if (!priorityQueue.isEmpty()) {
			branchFlow = priorityQueue.first();
			priorityQueue.remove(branchFlow);
			// must force start of flow within InstructionSet so that this flow
			// is not dependent upon a flow-from block within the InstructionSet
			forcedStartOfFlow = true;
		}
		else if (!currentBranchQueue.isEmpty()) {
			branchFlow = currentBranchQueue.first();
			currentBranchQueue.remove(branchFlow);
		}
		processedBranchFlows.add(branchFlow);

		Address blockAddr = branchFlow.getDestinationAddress();
		if (blockAddr instanceof SegmentedAddress) {
			blockAddr = normalize((SegmentedAddress) blockAddr, memory);
		}

		if (checkMemoryRestriction(blockAddr)) {
			lastBlockAddr = blockAddr;
			lastFlowFrom = branchFlow.getFlowFromAddress();
			lastBlock = new InstructionBlock(lastBlockAddr);
			lastBlock.setFlowFromAddress(lastFlowFrom);
			lastBlock.setStartOfFlow(forcedStartOfFlow);
			break;
		}
	}
	return lastBlock;
}