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

The following examples show how to use ghidra.util.task.TaskMonitor#initialize() . 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: RemoveMatchTask.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private boolean removeMatches(TaskMonitor monitor) throws CancelledException {
	monitor.setMessage("Removing matches");
	monitor.initialize(matches.size());
	boolean failed = false;
	for (VTMatch match : matches) {
		monitor.checkCanceled();
		VTMatchSetDB matchSet = (VTMatchSetDB) match.getMatchSet();
		boolean matchRemoved = matchSet.removeMatch(match);
		if (!matchRemoved) {
			failed = true;
		}
		monitor.incrementProgress(1);
	}

	monitor.setProgress(matches.size());
	if (failed) {
		reportError("One or more of your matches could not be removed." +
			"\nNote: You can't remove a match if it is currently accepted.");
	}
	return true;
}
 
Example 2
Source File: OldStackRefDBAdpater.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void moveTable(DBHandle handle, TaskMonitor monitor) throws IOException,
		CancelledException {

	DBHandle tmpHandle = handle.getScratchPad();
	Table newRefTable = tmpHandle.createTable(STACK_REF_TABLE_NAME, STACK_REF_SCHEMA);

	monitor.setMessage("Processing Old Stack References...");
	monitor.initialize(refTable.getRecordCount());
	int count = 0;

	RecordIterator iter = refTable.iterator();
	while (iter.hasNext()) {
		monitor.checkCanceled();
		newRefTable.putRecord(iter.next());
		monitor.setProgress(++count);
	}
	handle.deleteTable(STACK_REF_TABLE_NAME);
	refTable = newRefTable;
}
 
Example 3
Source File: DyldCacheHeader.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void markupImageInfo(Program program, AddressSpace space, TaskMonitor monitor,
		MessageLog log) throws CancelledException {
	monitor.setMessage("Marking up DYLD image info...");
	monitor.initialize(imageInfoList.size());
	try {
		Address addr = fileOffsetToAddr(imagesOffset, program, space);
		for (DyldCacheImageInfo imageInfo : imageInfoList) {
			Data d = DataUtilities.createData(program, addr, imageInfo.toDataType(), -1, false,
				DataUtilities.ClearDataMode.CHECK_FOR_SPACE);
			program.getListing().setComment(addr, CodeUnit.EOL_COMMENT, imageInfo.getPath());
			addr = addr.add(d.getLength());
			monitor.checkCanceled();
			monitor.incrementProgress(1);
		}
	}
	catch (CodeUnitInsertionException | DuplicateNameException | IOException e) {
		log.appendMsg(DyldCacheHeader.class.getSimpleName(),
			"Failed to markup dyld_cache_image_info.");
	}
}
 
Example 4
Source File: VTRelatedMatchTableModel.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
protected void doLoad(Accumulator<VTRelatedMatch> accumulator, TaskMonitor monitor)
		throws CancelledException {
	VTSession session = controller.getSession();
	MatchInfo matchInfo = controller.getMatchInfo();
	if (matchInfo == null) {
		return;
	}

	Collection<VTRelatedMatch> relatedMatches =
		VTRelatedMatchUtil.getRelatedMatches(monitor, session, matchInfo.getMatch());

	monitor.setMessage("Processing markup items");
	monitor.initialize(relatedMatches.size());

	for (VTRelatedMatch vtRelatedMatch : relatedMatches) {
		monitor.checkCanceled();
		accumulator.add(vtRelatedMatch);
		monitor.incrementProgress(1);
	}
}
 
Example 5
Source File: QualifiedSelectionPlugin.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * <code>getDefinedData</code> returns the defined data associated with the selection
 * or with the program if there isn't a selection.
 * 
 * @param taskMonitor The task monitor that will monitor task progress.
 * @return AddressSet the defined data address set.
 */
private AddressSet getDefinedData(ProgramLocationActionContext context,
		AddressSetView startSet, TaskMonitor taskMonitor) {

	Program program = context.getProgram();
	Listing listing = program.getListing();
	AddressSet addressSet = new AddressSet();
	long numDefined = listing.getNumDefinedData(); // Get the total number since we can't easily get the number in the selection.
	taskMonitor.initialize((int) numDefined);
	int counter = 0;
	DataIterator diter = listing.getDefinedData(startSet, true);
	while (diter.hasNext() && !taskMonitor.isCancelled()) {
		counter++;
		taskMonitor.setProgress(counter);
		Data data = diter.next();
		addressSet.addRange(data.getMinAddress(), data.getMaxAddress());
	}
	return addressSet;
}
 
Example 6
Source File: OldFunctionManager.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Actually does the work of upgrading the old program function manager.
 * @param upgradeProgram the program to upgrade
 * @param monitor the task monitor to allow the user to cancel the upgrade
 * @throws CancelledException if the user cancels the upgrade
 * @throws IOException if an i/o error occurs
 */
public void upgrade(ProgramDB upgradeProgram, TaskMonitor monitor)
		throws CancelledException, IOException {

	if (this.program != null) {
		throw new AssertException("Function manager already upgraded");
	}
	this.program = upgradeProgram;
	dataManager = upgradeProgram.getDataTypeManager();

	monitor.setMessage("Upgrading Functions...");
	monitor.initialize(getFunctionCount());
	int cnt = 0;

	OldFunctionIteratorDB iter = getFunctions();
	while (iter.hasNext()) {
		monitor.checkCanceled();
		upgradeFunction(iter.next());
		monitor.setProgress(++cnt);
	}
	dispose();
}
 
Example 7
Source File: ParallelDecompiler.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private static <R> List<R> doDecompileFunctions(QCallback<Function, R> callback,
		Iterator<Function> functions, int count, TaskMonitor monitor)
		throws InterruptedException, Exception {

	DecompilerConcurrentQ<Function, R> queue =
		new DecompilerConcurrentQ<>(callback, THREAD_POOL_NAME, monitor);

	monitor.initialize(count);

	queue.addAll(functions);

	Collection<QResult<Function, R>> qResults = null;
	try {
		qResults = queue.waitForResults();
	}
	finally {
		queue.dispose();
	}

	List<R> results = new ArrayList<>();
	for (QResult<Function, R> qResult : qResults) {
		results.add(qResult.getResult());
	}

	return results;
}
 
Example 8
Source File: OldExtRefAdapter.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void moveTable(DBHandle handle, TaskMonitor monitor) throws IOException,
		CancelledException {

	DBHandle tmpHandle = handle.getScratchPad();
	Table newRefTable = tmpHandle.createTable(EXT_REF_TABLE_NAME, EXT_REF_SCHEMA);

	monitor.setMessage("Processing Old External References...");
	monitor.initialize(refTable.getRecordCount());
	int count = 0;

	RecordIterator iter = refTable.iterator();
	while (iter.hasNext()) {
		monitor.checkCanceled();
		newRefTable.putRecord(iter.next());
		monitor.setProgress(++count);
	}
	handle.deleteTable(EXT_REF_TABLE_NAME);
	refTable = newRefTable;
}
 
Example 9
Source File: DyldCacheAccelerateInfo.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void markupRangeEntry(Program program, Address accelerateInfoAddr, TaskMonitor monitor,
		MessageLog log) throws CancelledException {
	monitor.setMessage("Marking up DYLD range entries...");
	monitor.initialize(rangeEntryList.size());
	try {
		Address addr = accelerateInfoAddr.add(rangeTableOffset);
		for (DyldCacheRangeEntry rangeEntry : rangeEntryList) {
			Data d = DataUtilities.createData(program, addr, rangeEntry.toDataType(), -1, false,
				DataUtilities.ClearDataMode.CHECK_FOR_SPACE);
			addr = addr.add(d.getLength());
			monitor.checkCanceled();
			monitor.incrementProgress(1);
		}
	}
	catch (CodeUnitInsertionException | DuplicateNameException | IOException e) {
		log.appendMsg(DyldCacheAccelerateInfo.class.getSimpleName(),
			"Failed to markup dyld_cache_range_entry.");
	}
}
 
Example 10
Source File: LoadPdbTask.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void analyzeSymbols(TaskMonitor monitor, MessageLog log) {

		MicrosoftDemanglerAnalyzer demanglerAnalyzer = new MicrosoftDemanglerAnalyzer();
		String analyzerName = demanglerAnalyzer.getName();

		Options analysisProperties = program.getOptions(Program.ANALYSIS_PROPERTIES);
		String defaultValueAsString = analysisProperties.getValueAsString(analyzerName);
		boolean doDemangle = true;
		if (defaultValueAsString != null) {
			doDemangle = Boolean.parseBoolean(defaultValueAsString);
		}

		if (doDemangle) {
			AddressSetView addrs = program.getMemory();
			monitor.initialize(addrs.getNumAddresses());
			try {
				demanglerAnalyzer.added(program, addrs, monitor, log);
			}
			catch (CancelledException e) {
				// Don't care about CancelledException
			}

		}
	}
 
Example 11
Source File: DyldCacheHeader.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void parseLocalSymbolsInfo(MessageLog log, TaskMonitor monitor)
		throws CancelledException {
	if (localSymbolsOffset == 0) {
		return;
	}
	monitor.setMessage("Parsing DYLD local symbols info...");
	monitor.initialize(1);
	try {
		reader.setPointerIndex(localSymbolsOffset);
		localSymbolsInfo = new DyldCacheLocalSymbolsInfo(reader, architecture);
		localSymbolsInfo.parse(log, monitor);
		monitor.incrementProgress(1);
	}
	catch (IOException e) {
		log.appendMsg(DyldCacheHeader.class.getSimpleName(),
			"Failed to parse dyld_cache_local_symbols_info.");
	}
}
 
Example 12
Source File: ClearCmd.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void clearProperties(Program program, AddressSetView clearView, TaskMonitor monitor)
		throws CancelledException {

	monitor.initialize(clearView.getNumAddresses());
	monitor.setMessage("Starting to clear properties...");

	Listing listing = program.getListing();
	AddressRangeIterator iter = clearView.getAddressRanges();
	int progress = 0;
	while (iter.hasNext()) {
		AddressRange range = iter.next();
		listing.clearProperties(range.getMinAddress(), range.getMaxAddress(), monitor);
		progress += range.getLength();
		monitor.setProgress(progress);
	}
}
 
Example 13
Source File: FunctionStackAnalysisCmd.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @see ghidra.framework.cmd.BackgroundCommand#applyTo(ghidra.framework.model.DomainObject, ghidra.util.task.TaskMonitor)
 */
@Override
public boolean applyTo(DomainObject obj, TaskMonitor monitor) {
	program = (Program) obj;

	int count = 0;
	monitor.initialize(entryPoints.getNumAddresses());
	AddressIterator iter = entryPoints.getAddresses(true);
	while (iter.hasNext()) {
		if (monitor.isCancelled()) {
			break;
		}

		Address origEntry = iter.next();
		monitor.setProgress(++count);

		Symbol funName = program.getSymbolTable().getPrimarySymbol(origEntry);
		String msg = (funName == null ? "" + origEntry : funName.getName());
		monitor.setMessage("Stack " + msg);

		try {
			if (!analyzeFunction(origEntry, monitor)) {
				setStatusMsg("Function overlaps an existing function body");
			}
		}
		catch (CancelledException e) {
			//
		}
	}
	if (monitor.isCancelled()) {
		setStatusMsg("Function Stack analysis cancelled");
		return false;
	}
	return true;
}
 
Example 14
Source File: BookmarkDeleteBackgroundCmd.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * @see ghidra.framework.cmd.BackgroundCommand#applyTo(ghidra.framework.model.DomainObject, ghidra.util.task.TaskMonitor)
 */
@Override
public boolean applyTo(DomainObject obj, TaskMonitor monitor) {
	BookmarkManager mgr = ((Program) obj).getBookmarkManager();
	monitor.initialize(bookmarks.length);
	for (int i = 0; i < bookmarks.length; i++) {
		if (monitor.isCancelled()) {
			return true;
		}
		Bookmark bm = bookmarks[i];
		mgr.removeBookmark(bm);
		monitor.setProgress(i);
	}
	return true;
}
 
Example 15
Source File: ByteTrie.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Search an array of bytes using the Aho-Corasick multiple string
 * trie search algorithm.
 * @param text the bytes to search
 * @param monitor a task monitor
 * @return a list of search results
 * @throws CancelledException
 */
@Override
public List<SearchResult<Integer, T>> search(byte[] text, TaskMonitor monitor)
		throws CancelledException {
	monitor.initialize(numberOfNodes() + text.length);
	fixupSuffixPointers(monitor);
	ArrayList<SearchResult<Integer, T>> results = new ArrayList<SearchResult<Integer, T>>();
	ByteTrieNode<T> ptr = root;
	int index = 0;
	while (index < text.length) {
		monitor.checkCanceled();
		monitor.incrementProgress(1);
		ByteTrieNode<T> trans = null;
		while (trans == null) {
			trans = getTransition(ptr, text[index]);
			if (ptr == root) {
				break;
			}
			if (trans == null) {
				ptr = ptr.suffix;
			}
		}
		if (trans != null) {
			ptr = trans;
		}
		ByteTrieNode<T> tmp = ptr;
		while (tmp != root) {
			if (tmp.isTerminal()) {
				results.add(new SearchResult<Integer, T>(tmp, index - tmp.length() + 1,
					tmp.getItem()));
			}
			tmp = tmp.suffix;
		}
		++index;
	}
	return results;
}
 
Example 16
Source File: DataTypeArchiveGTree.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void expandedStateRestored(TaskMonitor monitor) {
	// walk all of our nodes and reclaim any that aren't expanded
	GTreeNode rootNode = getViewRoot();
	if (rootNode == null) {
		return; // in a state of flux; been disposed
	}

	monitor.setMessage("Recycling unused tree nodes");
	monitor.initialize(rootNode.getLeafCount());
	reclaimClosedNodes(rootNode, monitor);
}
 
Example 17
Source File: ClearCmd.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void clearRegisters(Program program, AddressSetView clearView, TaskMonitor monitor)
		throws CancelledException {

	monitor.initialize(clearView.getNumAddresses());
	monitor.setMessage("Starting to clear registers...");
	ProgramContext pc = program.getProgramContext();
	AddressRangeIterator iter = clearView.getAddressRanges();
	while (iter.hasNext()) {
		AddressRange range = iter.next();
		removeRegisters(pc, range, monitor);
	}
}
 
Example 18
Source File: FidProgramSeeker.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Searches the database for function names.
 * @param monitor a task monitor
 * @return the results of all the searching
 * @throws CancelledException if the user cancels
 */
public List<FidSearchResult> search(TaskMonitor monitor) throws CancelledException {
	List<FidSearchResult> result = new LinkedList<FidSearchResult>();

	FunctionManager functionManager = program.getFunctionManager();
	monitor.initialize(functionManager.getFunctionCount());
	FunctionIterator functions = functionManager.getFunctions(true);
	for (Function function : functions) {
		monitor.checkCanceled();
		monitor.incrementProgress(1);
		try {
			HashFamily family = getFamily(function, monitor);
			if (family != null) {
				FidSearchResult searchResult = processMatches(function, family, monitor);
				if (searchResult != null) {
					result.add(searchResult);
				}
			}
		}
		catch (MemoryAccessException e) {
			Msg.showError(this, null, "Memory Access Exception",
				"Internal error, degenerate unhashable function");
		}
	}

	return result;
}
 
Example 19
Source File: ReferenceUtils.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Returns all references (locations) that use the given datatype.
 * <br>
 * <b>Note: </b> This method call may take a long time, as it must search all of the
 * data within the program and may also perform long running tasks, like decompiling every
 * function in the program.
 * <br>
 * @param accumulator the results storage
 * @param dataType The datatype for which to find references.
 * @param fieldName optional field name for which to search; the <tt>dataType</tt> must be
 *                  a {@link Composite} to search for a field
 * @param program The program from within which to find references.
 * @param discoverTypes if true, the {@link DataTypeReferenceFinder} service 
 *                will be used to search for data types that are not applied in memory.  
 *                Using the service will be slower, but will recover type usage that could
 *                not be found by examining the Listing.
 * @param monitor A task monitor to be updated as data is searched; if this is null, then a
 *        dummy monitor will be used.
 * @throws CancelledException if the monitor is cancelled
 */
public static void findDataTypeReferences(Accumulator<LocationReference> accumulator,
		DataType dataType, String fieldName, Program program, boolean discoverTypes,
		TaskMonitor monitor) throws CancelledException {

	// Note: none of the params can be null, but this one gets used much later, so check now
	Objects.requireNonNull(dataType, () -> "Data Type cannot be null");

	// sanity check
	if (fieldName != null && !(dataType instanceof Composite)) {
		throw new IllegalArgumentException("Can only search for a field with a Composite type");
	}

	if (monitor == null) {
		monitor = TaskMonitor.DUMMY;
	}

	Listing listing = program.getListing();

	long dataCount = listing.getNumDefinedData();
	int functionCount = program.getFunctionManager().getFunctionCount();
	int totalCount = (int) dataCount + functionCount;

	monitor.initialize(totalCount);

	// Mimic a set in case the client passes in an accumulator that allows duplicates.  This
	// seems a bit cleaner than adding checks for 'accumulator.contains(ref)' throughout
	// the code.
	Accumulator<LocationReference> asSet = asSet(accumulator);

	if (fieldName == null) {
		// It only makes sense to search here when we do not have a field

		boolean localsOnly = discoverTypes;
		FunctionIterator iterator = listing.getFunctions(false);
		findDataTypeMatchesInFunctionHeaders(asSet, iterator, dataType, localsOnly, monitor);

		// external functions don't get searched by type discovery  
		localsOnly = false;
		iterator = listing.getExternalFunctions();
		findDataTypeMatchesInFunctionHeaders(asSet, iterator, dataType, localsOnly, monitor);
	}

	Predicate<Data> dataMatcher = data -> {
		DataType baseType = getBaseDataType(data.getDataType());
		boolean matches = dataTypesMatch(dataType, baseType);
		return matches;
	};
	findDataTypeMatchesInDefinedData(asSet, program, dataMatcher, fieldName, monitor);

	if (discoverTypes) {
		findDataTypeMatchesOutsideOfListing(asSet, program, dataType, fieldName, monitor);
	}

	monitor.checkCanceled();
}
 
Example 20
Source File: DeleteProjectFilesTask.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private void initializeMonitor(TaskMonitor monitor) {
	monitor.setMessage("Deleting Files...");
	monitor.initialize(statistics.getFileCount());
}