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

The following examples show how to use ghidra.util.task.TaskMonitor#setIndeterminate() . 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: ArchiveExtractor.java    From ghidra with Apache License 2.0 6 votes vote down vote up
public static void explode(File baseDir, File archiveFile, TaskMonitor monitor)
		throws ZipException, IOException {

	ZipFile zipFile = new ZipFile(archiveFile);
	monitor.setIndeterminate(true);
	int count = getEntryCount(zipFile);
	monitor.initialize(count);

	Enumeration<? extends ZipEntry> entries = zipFile.entries();
	while (entries.hasMoreElements()) {
		ZipEntry entry = entries.nextElement();
		String path = entry.getName();
		File outputFile = new File(baseDir, path);
		InputStream inputStream = zipFile.getInputStream(entry);
		FileUtilities.copyStreamToFile(inputStream, outputFile, false,
			new CancelOnlyWrappingTaskMonitor(monitor));
		monitor.incrementProgress(1);
		if (monitor.isCancelled()) {
			break;
		}
	}
	zipFile.close();
}
 
Example 2
Source File: NoReturnsFunctionsValidator.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private int checkNumNoReturnFunctions(Program prog, TaskMonitor monitor) {
	FunctionIterator funcIter = prog.getFunctionManager().getFunctions(true);
	int numNoReturnFuncs = 0;

	monitor.setIndeterminate(true);
	while (funcIter.hasNext() && !monitor.isCancelled()) {
		monitor.incrementProgress(1);
		Function func = funcIter.next();
		Address address = func.getEntryPoint();
		Instruction inst = prog.getListing().getInstructionAt(address);

		//This check gets rid of Import Address Table "fake" functions
		if (inst != null) {
			if (func.hasNoReturn()) {
				numNoReturnFuncs++;
			}
		}
	}
	return numNoReturnFuncs;
}
 
Example 3
Source File: JarDecompilerTask.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public void run(TaskMonitor monitor) {

	monitor.setMessage(file.getAbsolutePath());
	monitor.setIndeterminate(true);

	try {
		JadProcessWrapper wrapper = new JadProcessWrapper(file);

		JadProcessController controller = new JadProcessController(wrapper, desc);
		controller.decompile(45, monitor);
	}
	catch (Exception e) {
		Msg.info(this, "Exception in JarDecompileTask", e);
	}
}
 
Example 4
Source File: DecompilerParameterIDValidator.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private static int checkNumberAnalyzed(Program prog, TaskMonitor monitor) {
	FunctionIterator funcIter = prog.getFunctionManager().getFunctions(true);
	int numFuncsWithParameterID = 0;

	monitor.setIndeterminate(false);
	monitor.initialize(prog.getFunctionManager().getFunctionCount());
	while (funcIter.hasNext() && !monitor.isCancelled()) {
		monitor.incrementProgress(1);
		Function func = funcIter.next();
		Address address = func.getEntryPoint();
		Instruction inst = prog.getListing().getInstructionAt(address);

		if (inst != null) {
			final SourceType signatureSource = func.getSignatureSource();
			if (signatureSource == SourceType.ANALYSIS) {
				++numFuncsWithParameterID;
			}
		}
	}

	return numFuncsWithParameterID;
}
 
Example 5
Source File: DecompileRunnable.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Performs the decompile.
 */
@Override
public void monitoredRun(TaskMonitor monitor) {
	monitor.setIndeterminate(true);
	Function function = findFunction(monitor);
	if (function == null) {
		return;
	}
	CodeUnit cu = program.getListing().getCodeUnitAt(function.getEntryPoint());
	if (cu instanceof Data && ((Data) cu).isDefined()) {
		return;
	}
	monitor.setMessage("Decompiling function: " + function.getName() + "...");
	functionToDecompile = function;
	try {
		decompileResults =
			decompilerManager.decompile(program, functionToDecompile, debugFile, monitor);
	}
	catch (DecompileException e) {
		errorMessage = e.getMessage();
	}

}
 
Example 6
Source File: CreateEquateCmd.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public boolean applyTo(DomainObject domain, TaskMonitor monitor) {

	monitor.setIndeterminate(true);
	monitor.setMessage("Creating Equate");

	while (iterator.hasNext() && !monitor.isCancelled()) {
		CodeUnit cu = iterator.next();
		if (cu instanceof Instruction) {
			maybeCreateEquate(domain, (Instruction) cu);
		}
		else if (cu instanceof Data) {
			maybeCreateEquate(domain, (Data) cu);
		}
	}
	return true;
}
 
Example 7
Source File: LSHMultiHash.java    From ghidra with Apache License 2.0 6 votes vote down vote up
public synchronized void add(List<DominantPair<P, LSHCosineVectorAccum>> coll,
		TaskMonitor monitor) {
	monitor.setIndeterminate(false);
	monitor.initialize(coll.size());

	for (DominantPair<P, LSHCosineVectorAccum> entry : coll) {
		if (monitor.isCancelled()) {
			break;
		}
		monitor.incrementProgress(1);
		if (entry.second == null) {
			continue;
		}
		int[] hashes = hashes(entry.second);
		for (int ii = 0; ii < hashes.length; ++ii) {
			HashSet<DominantPair<P, LSHCosineVectorAccum>> list = maps[ii].get(hashes[ii]);
			if (list == null) {
				list = new HashSet<>();
				maps[ii].put(hashes[ii], list);
			}
			list.add(entry);
		}
	}
}
 
Example 8
Source File: LSHMultiHash.java    From ghidra with Apache License 2.0 6 votes vote down vote up
public synchronized void add(Map<P, LSHCosineVectorAccum> map, TaskMonitor monitor) {
	monitor.setIndeterminate(false);
	monitor.initialize(map.size());

	for (Map.Entry<P, LSHCosineVectorAccum> entry : map.entrySet()) {
		if (monitor.isCancelled()) {
			break;
		}
		monitor.incrementProgress(1);
		if (entry.getValue() == null) {
			continue;
		}
		int[] hashes = hashes(entry.getValue());
		for (int ii = 0; ii < hashes.length; ++ii) {
			HashSet<DominantPair<P, LSHCosineVectorAccum>> list = maps[ii].get(hashes[ii]);
			if (list == null) {
				list = new HashSet<>();
				maps[ii].put(hashes[ii], list);
			}
			list.add(
				new DominantPair<>(entry.getKey(), entry.getValue()));
		}
	}
}
 
Example 9
Source File: GccExceptionAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public boolean added(Program program, AddressSetView addedLocationAddresses,
		TaskMonitor monitor, MessageLog log) throws CancelledException {

	if (visitedPrograms.contains(program)) {
		return true;
	}

	AutoAnalysisManager analysisManager = AutoAnalysisManager.getAnalysisManager(program);
	analysisManager.addListener(analysisListener);

	monitor.setMessage("Analyzing GCC exception-handling artifacts");
	monitor.setIndeterminate(true);
	monitor.setShowProgressValue(false);

	handleStandardSections(program, monitor, log);

	handleDebugFrameSection(program, monitor, log);

	// handleArmSections(program, monitor, log);

	visitedPrograms.add(program);
	monitor.setIndeterminate(false);
	monitor.setShowProgressValue(true);

	return true;
}
 
Example 10
Source File: DIEAMonitoredIterator.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public PagedDIEAMonitoredIterator(DWARFProgram prog, String monitorMessage,
		TaskMonitor monitor) {
	this.prog = prog;
	this.monitor = monitor;
	this.monitorMessage = monitorMessage;
	this.cuCount = prog.getCompilationUnits().size();
	this.aggregateTotalCount = prog.getTotalAggregateCount();
	this.cuIterator = prog.getCompilationUnits().iterator();

	monitor.setIndeterminate(false);
	monitor.setShowProgressValue(true);
	monitor.initialize(aggregateTotalCount);
	monitor.setMessage(monitorMessage);
}
 
Example 11
Source File: DIEAMonitoredIterator.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public SimpleDIEAMonitoredIterator(DWARFProgram prog, String monitorMessage,
		TaskMonitor monitor) {
	this.monitor = monitor;
	this.monitorMessage = monitorMessage;
	this.aggregateTotalCount = prog.getTotalAggregateCount();
	this.aggregateIterator = prog.getAggregates().iterator();

	monitor.setIndeterminate(false);
	monitor.setShowProgressValue(true);
	monitor.initialize(aggregateTotalCount);
	monitor.setMessage(monitorMessage);
}
 
Example 12
Source File: FunctionReachabilityTableModel.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
protected void doLoad(Accumulator<FunctionReachabilityResult> accumulator, TaskMonitor monitor)
		throws CancelledException {

	if (fromFunction == null || toFunction == null) {
		return;
	}

	monitor.setIndeterminate(true);

	monitor.setMessage("Creating callgraph...");

	Map<Address, FRVertex> instanceMap = new HashMap<>();
	FRVertex v1 = new FRVertex(fromFunction.getEntryPoint());
	FRVertex v2 = new FRVertex(toFunction.getEntryPoint());
	instanceMap.put(fromFunction.getEntryPoint(), v1);
	instanceMap.put(toFunction.getEntryPoint(), v2);

	GDirectedGraph<FRVertex, FREdge> graph = createCallGraph(instanceMap, monitor);

	// debug
	// GraphAlgorithms.printGraph(graph);

	Accumulator<List<FRVertex>> pathAccumulator = new PassThroughAccumulator(accumulator);

	if (v1.equals(v2)) {
		return;
	}

	monitor.setMessage("Finding paths...");
	GraphAlgorithms.findPaths(graph, v1, v2, pathAccumulator, monitor);
}
 
Example 13
Source File: CreateEnumEquateCommand.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public boolean applyTo(DomainObject obj, TaskMonitor monitor) {

	monitor.setIndeterminate(true);
	monitor.setMessage("Installing Equate");

	equateTable = program.getEquateTable();
	try {
		applyEnum(monitor);
	}
	catch (CancelledException e) {
		return false;
	}
	return true;
}
 
Example 14
Source File: CombinedStringSearcher.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Searches the current program for strings based on the user-defined settings in
 * {@link StringTableOptions}.
 * 
 * @param monitor the task monitor
 * @throws CancelledException 
 */
public void search(TaskMonitor monitor) throws CancelledException {
				
	AbstractStringSearcher searcher = createSearcher();
	
	// Save off the set of addresses to search. This will be modified during the
	// search operation depending on whether loaded or unloaded blocks are to be 
	// searched.	
	AddressSetView updatedAddressSet = options.getAddressSet();
	
	updateNextString();
	
	if (options.includeUndefinedStrings() || options.includePartiallyDefinedStrings() ||
		options.includeConflictingStrings()) {
		updatedAddressSet = searcher.search(options.getAddressSet(), new AccumulatorAdapter(), options.useLoadedBlocksOnly(), monitor);
	}

	if (!options.includeDefinedStrings()) {
		return;
	}

	// Add defined strings to the accumulator that haven't been found by the StringSearcher
	monitor.setIndeterminate(true);
	while (nextDefinedString != null) {
		monitor.checkCanceled();
		if (!inRange(updatedAddressSet, nextDefinedString)) {
			updateNextString();
			continue;
		}

		if (!onlyShowWordStrings() ||
			((FoundStringWithWordStatus) nextDefinedString).isHighConfidenceWord()) {
			add(nextDefinedString);
		}

		updateNextString();
	}
}
 
Example 15
Source File: AARCH64PltThunkAnalyzer.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public boolean added(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log)
		throws CancelledException {
	
	Memory memory = program.getMemory();
	MemoryBlock block = memory.getBlock(".plt");
	if (block == null) {
		return true;
	}
	
	set = set.intersectRange(block.getStart(), block.getEnd());
	set = removeFunctionBodies(program, set, monitor);
	if (set.isEmpty()) {
		return true;
	}

	SequenceSearchState sequenceSearchState = SequenceSearchState.buildStateMachine(
			leThunkPatterns);
	
	monitor.setIndeterminate(true);
	monitor.setProgress(0);
	
	ArrayList<Match> matches = new ArrayList<>();
	
	try {
		for (AddressRange range : set.getAddressRanges()) {
			
			byte[] bytes = new byte[(int)range.getLength()];
			if (block.getBytes(range.getMinAddress(), bytes, 0, bytes.length) != bytes.length) {
				log.appendMsg("Expected initialized .plt section block");
				return false;
			}
			
			matches.clear();
			sequenceSearchState.apply(bytes, matches);
			
			for (Match match : matches) {
				Address addr = range.getMinAddress().add(match.getMarkOffset());
				analyzePltThunk(program, addr, match.getSequenceSize(), monitor);
			}
			
		}
	} catch (MemoryAccessException | AddressOutOfBoundsException e) {
		log.appendMsg("Expected initialized .plt section block: " + e.getMessage());
	}
	
	return true;
}
 
Example 16
Source File: ProgramMappingService.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Recursively searches the current active {@link Project} for {@link DomainFile}s that
 * have metadata that matches a {@link FSRL} in the specified list.
 * <p>
 * Warning, this operation is expensive and should only be done in a Task thread.
 * <p>
 * @param fsrls List of {@link FSRL} to match against the metadata of each DomainFile in Project.
 * @param monitor {@link TaskMonitor} to watch for cancel and update with progress.
 * @return Map of FSRLs to {@link DomainFile}s of the found files, never null.
 */
public static Map<FSRL, DomainFile> searchProjectForMatchingFiles(List<FSRL> fsrls,
		TaskMonitor monitor) {
	int fc = AppInfo.getActiveProject().getProjectData().getFileCount();
	if (fc > 0) {
		monitor.setShowProgressValue(true);
		monitor.setMaximum(fc);
		monitor.setProgress(0);
	}
	else {
		monitor.setIndeterminate(true);
	}
	monitor.setMessage("Searching project for matching files");

	Map<String, FSRL> fsrlsToFindByMD5;
	try {
		fsrlsToFindByMD5 = buildFullyQualifiedFSRLMap(fsrls, monitor);
	}
	catch (CancelledException ce) {
		Msg.info(ProgramMappingService.class, "Canceling project search");
		return Collections.emptyMap();
	}

	Map<FSRL, DomainFile> results = new HashMap<>();

	for (DomainFile domainFile : ProjectDataUtils.descendantFiles(
		AppInfo.getActiveProject().getProjectData().getRootFolder())) {
		if (monitor.isCancelled() || fsrlsToFindByMD5.isEmpty()) {
			break;
		}

		monitor.incrementProgress(1);
		Map<String, String> metadata = domainFile.getMetadata();

		FSRL dfFSRL = getFSRLFromMetadata(metadata, domainFile);
		if (dfFSRL != null) {
			// side effect: create association between the FSRL in the DomainFile's props
			// to the DomainFile's path if there is room in the cache.
			// (ie. don't blow out the cache for files that haven't been requested yet)
			createAssociation(dfFSRL, domainFile, true);
		}
		String dfMD5 = (dfFSRL != null) ? dfFSRL.getMD5() : getMD5FromMetadata(metadata);
		if (dfMD5 != null) {
			FSRL matchedFSRL = fsrlsToFindByMD5.get(dfMD5);
			if (matchedFSRL != null) {
				results.put(matchedFSRL, domainFile);
				fsrlsToFindByMD5.remove(dfMD5);
			}
		}
	}

	return results;
}
 
Example 17
Source File: DWARFProgram.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Iterates over all the DWARF DIE records in the program and checks for some
 * pre-known issues, throwing an exception if there is a problem that would
 * prevent a successful run.
 *
 * @param monitor {@link TaskMonitor} to check for cancel and upate with status.
 * @throws DWARFException if DWARF structure error.
 * @throws CancelledException if user cancels.
 * @throws IOException if error reading data.
 */
public void checkPreconditions(TaskMonitor monitor)
		throws DWARFPreconditionException, DWARFException, CancelledException, IOException {
	monitor.setIndeterminate(false);
	monitor.setShowProgressValue(true);

	monitor.setMaximum(getCompilationUnits().size());

	if (getCompilationUnits().size() > 0 &&
		getCompilationUnits().get(0).getCompileUnit().hasDWO()) {
		// probably won't get anything from the file because its all in an external DWO
		Msg.warn(this,
			"Unsupported DWARF DWO (external debug file) detected -- unlikely any debug information will be found");
	}

	// This loop:
	// 1) preloads the DIEs if that option is set
	// 2) checks for cross-cu refs
	// 3) sums up the total number of DIE records found and updates prog with total.
	boolean preLoad = importOptions.isPreloadAllDIEs();
	totalDIECount = 0;
	totalAggregateCount = 0;
	clearDIEIndexes();
	for (DWARFCompilationUnit cu : getCompilationUnits()) {
		monitor.setMessage("DWARF Checking Preconditions - Compilation Unit #" +
			cu.getCompUnitNumber() + "/" + getCompilationUnits().size());
		monitor.setProgress(cu.getCompUnitNumber());

		cu.readDIEs(currentDIEs, monitor);

		if (totalDIECount > importOptions.getImportLimitDIECount() && !preLoad) {
			throw new DWARFPreconditionException(
				String.format(program.getName() + " has more DIE records (%d) than limit of %d",
					totalDIECount, importOptions.getImportLimitDIECount()));
		}

		if (!preLoad) {
			foundCrossCURefs |= checkForCrossCURefs(currentDIEs);
			totalDIECount += currentDIEs.size();
			totalAggregateCount += countAggregates();
			currentDIEs.clear();
			if (foundCrossCURefs) {
				throw new DWARFPreconditionException(
					"Found cross-compilation unit references between DIE records, but 'preload' is not turned on");
			}
		}

	}
	if (preLoad) {
		// build DIE indexes once
		rebuildDIEIndexes();
		this.totalAggregateCount = aggregates.size();
		this.totalDIECount = currentDIEs.size();
	}
}
 
Example 18
Source File: PPC64CallStubAnalyzer.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public boolean added(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log)
		throws CancelledException {
	
	Memory memory = program.getMemory();
	Listing listing = program.getListing();
	ProgramContext programContext = program.getProgramContext();
	
	SequenceSearchState sequenceSearchState = SequenceSearchState.buildStateMachine(
			program.getMemory().isBigEndian() ? beCallStubPatterns : leCallStubPatterns);
	
	monitor.setIndeterminate(false);
	monitor.setMaximum(set.getNumAddresses());
	monitor.setProgress(0);
	int functionCount = 0;
	
	// each address should correspond to a function
	for (Function function : listing.getFunctions(set, true)) {
		
		monitor.checkCanceled();
		monitor.setProgress(functionCount++);
		
		Address entryAddr = function.getEntryPoint();
		boolean isThunk = function.isThunk();
		
		Match stubMatch = null;
		if (!isThunk) {
			stubMatch = matchKnownCallStubs(entryAddr, memory, sequenceSearchState);
			if (stubMatch == null) {
				continue; // non-stub
			}
		}
		else if (!thunksUnknownFunction(function)) {
			continue; // previously resolved thunk
		}
		
		RegisterValue r2Value = programContext.getRegisterValue(r2Reg, entryAddr);
		if (r2Value == null || !r2Value.hasValue()) {
			if (!isThunk) { // stubMatch is known
				// Thunk unknown function for future processing once r2 is propagated
				createThunk(program, entryAddr, stubMatch.getSequenceSize(), getUnknownFunction(
					program).getEntryPoint());
			}
			continue;
		}
		
		int stubLength = stubMatch != null ? stubMatch.getSequenceSize()
				: (int) function.getBody().getNumAddresses();
		
		analyzeCallStub(program, function, stubLength, monitor);
	}
	
	return true;
}
 
Example 19
Source File: SingleEntSubIterator.java    From ghidra with Apache License 2.0 3 votes vote down vote up
/**
 * Creates a new iterator that will iterate over the
 * program within a given address range set. All blocks which 
 * overlap the address set will be returned.
 * <P>
 * @param model  the BlockModel the iterator will use in its operations.
 * @param set    the address range set which the iterator is to be
 *               restricted to.
 * @param monitor task monitor which allows user to cancel operation.
 * @throws CancelledException if the monitor cancels the operation.
 */
public SingleEntSubIterator(OverlapCodeSubModel model, AddressSetView set, TaskMonitor monitor)
		throws CancelledException {
	this.model = model;
	this.monitor = monitor;
	monitor.setIndeterminate(true);
	addrSet = set;
	nextSub = null;
	modelMIter = model.getModelM().getCodeBlocksContaining(set, monitor);
}
 
Example 20
Source File: MultEntSubIterator.java    From ghidra with Apache License 2.0 3 votes vote down vote up
/**
 * Creates a new iterator that will iterate over the
 * program within a given address range set. All blocks which 
 * overlap the address set will be returned.
 * <P>
 *
 * @param model  the SubroutineModel the iterator will use in its operations.
 * @param set    the address range set which the iterator is to be
 *               restricted to.
 * @param monitor task monitor which allows user to cancel operation.
 */
MultEntSubIterator(MultEntSubModel model, AddressSetView set, TaskMonitor monitor) {
	this.model = model;
	this.monitor = monitor;
	monitor.setIndeterminate(true);
	listing = model.getProgram().getListing();
	addrSet = new AddressSet(set);
	nextSub = null;
}