Java Code Examples for ghidra.framework.plugintool.PluginTool#getService()

The following examples show how to use ghidra.framework.plugintool.PluginTool#getService() . 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: BlockGraphTask.java    From ghidra with Apache License 2.0 6 votes vote down vote up
public BlockGraphTask(String actionName, boolean graphEntryPointNexus, boolean showCode,
		boolean reuseGraph,
		boolean appendGraph, PluginTool tool, ProgramSelection selection,
		CodeBlockModel blockModel, GraphDisplayProvider graphService) {
	super("Graph Program", true, false, true);
	this.actionName = actionName;

	this.graphEntryPointNexus = graphEntryPointNexus;
	this.showCode = showCode;
	this.reuseGraph = reuseGraph;
	this.appendGraph = appendGraph;
	this.tool = tool;
	this.blockModel = blockModel;
	this.graphService = graphService;
	this.colorizingService = tool.getService(ColorizingService.class);
	this.selection = selection;
	this.program = blockModel.getProgram();
}
 
Example 2
Source File: GhidraScript.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Clears the background of the Listing at the given addresses to the given color.  See the
 * Listing help page in Ghidra help for more information.
 * <p>
 * This method is unavailable in headless mode.
 * <p>
 * Note: you can use the {@link ColorizingService} directly to access more color changing
 * functionality.  See the source code of this method to learn how to access services from
 * a script.
 *
 * @param addresses The address at which to clear the color
 * @see #setBackgroundColor(AddressSetView, Color)
 * @see #clearBackgroundColor(AddressSetView)
 * @see ColorizingService
 * @throws ImproperUseException if this method is run in headless mode
 */
public void clearBackgroundColor(AddressSetView addresses) throws ImproperUseException {

	if (isRunningHeadless()) {
		throw new ImproperUseException(
			"The clearBackgroundColor() method can only be used when running headed Ghidra.");
	}

	PluginTool tool = state.getTool();
	ColorizingService service = tool.getService(ColorizingService.class);
	if (service == null) {
		printerr("Cannot clear background colors without the " +
			ColorizingService.class.getSimpleName() + " installed");
		return;
	}

	service.clearBackgroundColor(addresses);
}
 
Example 3
Source File: GraphASTControlFlowAction.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
protected void decompilerActionPerformed(DecompilerActionContext context) {
	PluginTool tool = context.getTool();
	GraphDisplayBroker service = tool.getService(GraphDisplayBroker.class);
	if (service == null) {
		Msg.showError(this, tool.getToolFrame(), "AST Graph Failed",
			"Graph consumer not found: Please add a graph consumer provider to your tool");
		return;
	}

	// TODO: Options should really be obtained from graph service
	Options options = tool.getOptions("Graph");
	boolean reuseGraph = options.getBoolean("Reuse Graph", false);
	int codeLimitPerBlock = options.getInt("Max Code Lines Displayed", 10);
	HighFunction highFunction = context.getHighFunction();
	Address locationAddr = context.getLocation().getAddress();
	ASTGraphTask task = new ASTGraphTask(service, !reuseGraph, codeLimitPerBlock, locationAddr,
		highFunction, CONTROL_FLOW_GRAPH, tool);
	new TaskLauncher(task, tool.getToolFrame());
}
 
Example 4
Source File: GhidraScript.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the background of the Listing at the given address to the given color.  See the
 * Listing help page in Ghidra help for more information.
 * <p>
 * This method is unavailable in headless mode.
 * <p>
 * Note: you can use the {@link ColorizingService} directly to access more color changing
 * functionality.  See the source code of this method to learn how to access services from
 * a script.
 *
 * @param address The address at which to set the color
 * @param color The color to set
 * @see #setBackgroundColor(AddressSetView, Color)
 * @see #clearBackgroundColor(Address)
 * @see ColorizingService
 * @throws ImproperUseException if this method is run in headless mode
 */
public void setBackgroundColor(Address address, Color color) throws ImproperUseException {

	if (isRunningHeadless()) {
		throw new ImproperUseException(
			"The setBackgroundColor() method can only be used when running headed Ghidra.");
	}

	PluginTool tool = state.getTool();
	ColorizingService service = tool.getService(ColorizingService.class);
	if (service == null) {
		printerr("Cannot set background colors without the " +
			ColorizingService.class.getSimpleName() + " installed");
		return;
	}

	service.setBackgroundColor(address, address, color);
}
 
Example 5
Source File: AbstractGhidraHeadlessIntegrationTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Replaces the given implementations of the provided service class with the given class.
 * 
 * @param tool the tool whose services to update (optional)
 * @param service the service to override
 * @param replacement the new version of the service
 * @param <T> the service type
 */
@SuppressWarnings("unchecked")
public static <T> void replaceService(PluginTool tool, Class<? extends T> service,
		T replacement) {

	ServiceManager serviceManager = (ServiceManager) getInstanceField("serviceMgr", tool);

	List<Class<?>> extentions =
		(List<Class<?>>) getInstanceField("extensionPoints", ClassSearcher.class);
	Set<Class<?>> set = new HashSet<>(extentions);
	Iterator<Class<?>> iterator = set.iterator();
	while (iterator.hasNext()) {
		Class<?> c = iterator.next();
		if (service.isAssignableFrom(c)) {
			iterator.remove();
			T instance = tool.getService(service);
			serviceManager.removeService(service, instance);
		}
	}

	set.add(replacement.getClass());
	serviceManager.addService(service, replacement);

	List<Class<?>> newExtensionPoints = new ArrayList<>(set);
	setInstanceField("extensionPoints", ClassSearcher.class, newExtensionPoints);
}
 
Example 6
Source File: StringParameterPropagator.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private DecompInterface setUpDecompiler(Program program) {
	DecompInterface decompInterface = new DecompInterface();

	DecompileOptions options;
	options = new DecompileOptions();
	PluginTool tool = state.getTool();
	if (tool != null) {
		OptionsService service = tool.getService(OptionsService.class);
		if (service != null) {
			ToolOptions opt = service.getOptions("Decompiler");
			options.grabFromToolAndProgram(null, opt, program);
		}
	}
	decompInterface.setOptions(options);

	decompInterface.toggleCCode(true);
	decompInterface.toggleSyntaxTree(true);
	decompInterface.setSimplificationStyle("decompile");

	return decompInterface;
}
 
Example 7
Source File: FSBUtils.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private static PluginTool selectPMTool(PluginTool tool) {
	ProgramManager pm = tool.getService(ProgramManager.class);
	if (pm != null) {
		return tool;
	}

	List<PluginTool> pluginTools = FSBUtils.getRunningProgramManagerTools(tool);

	if (pluginTools.size() == 1) {
		return pluginTools.get(0);
	}

	if (pluginTools.isEmpty()) {
		Msg.showWarn(tool, tool.getActiveWindow(), "No open tools",
			"There are no open tools to use to open a program with");
		return null;
	}

	PluginTool pt = SelectFromListDialog.selectFromList(pluginTools, "Select tool",
		"Select a tool to use to open programs", pluginTool -> pluginTool.getName());
	return pt;
}
 
Example 8
Source File: FSBUtils.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the {@link ProgramManager} associated with this fs browser plugin.
 * <p>
 * When this FS Browser plugin is part of the front-end tool, this will search
 * for an open CodeBrowser tool that can be used to handle programs.
 * <p>
 * When this FS Browser plugin is part of a CodeBrowser tool, this will just return
 * the local ProgramManager / CodeBrowser.
 *
 * @param tool The plugin tool.
 * @param allowUserPrompt boolean flag to allow this method to query the user to select
 * a CodeBrowser.
 * @return null if front-end and no open CodeBrowser, otherwise returns the local
 * CodeBrowser ProgramManager service.
 */
public static ProgramManager getProgramManager(PluginTool tool, boolean allowUserPrompt) {
	PluginTool pmTool = null;
	ProgramManager pm = tool.getService(ProgramManager.class);
	if (pm != null) {
		pmTool = tool;
	}
	else {
		List<PluginTool> runningPMTools = FSBUtils.getRunningProgramManagerTools(tool);
		if (runningPMTools.size() == 1) {
			pmTool = runningPMTools.get(0);
		}
		else {
			pmTool = allowUserPrompt ? selectPMTool(tool) : null;
		}
	}
	return (pmTool != null) ? pmTool.getService(ProgramManager.class) : null;
}
 
Example 9
Source File: GoToQuery.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void loadingFinished(boolean wasCancelled) {
	int rowCount = model.getRowCount();
	boolean hasData = rowCount > 0;
	if (!hasData) {
		notifyListener(false);
		return;
	}

	if (rowCount == 1) {
		goTo(null, model.getProgramLocation(0, 0));
		notifyListener(true);
		return;
	}

	PluginTool tool = plugin.getTool();
	if (tool == null) {
		return; // this can happen if a search is taking place when the tool is closed
	}

	TableService service = tool.getService(TableService.class);
	TableComponentProvider<?> provider = service.showTable(
		"Goto " + queryData.getQueryString(), "Goto", model, "Go To", navigatable);
	if (model.getRowCount() >= maxHits) {
		showMaxSearchWarning(provider.getComponent(), model.getRowCount());
	}

	notifyListener(true);
}
 
Example 10
Source File: VTMatchApplySettingsAction.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
	public void actionPerformed(ActionContext context) {
		PluginTool tool = controller.getTool();
		OptionsService service = tool.getService(OptionsService.class);
		service.showOptionsDialog(VERSION_TRACKING_OPTIONS_NAME + "." +
//				VERSION_TRACKING_APPLY_MARKUP_OPTIONS, "Version Tracking");
			VERSION_TRACKING_APPLY_MARKUP_OPTIONS, "Apply");
	}
 
Example 11
Source File: GhidraScript.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Closes the specified program in the current tool.
 *
 * @param program the program to close
 */
public void closeProgram(Program program) {
	PluginTool tool = state.getTool();
	if (tool == null) {
		return;
	}
	ProgramManager pm = tool.getService(ProgramManager.class);
	pm.closeProgram(program, false);
}
 
Example 12
Source File: VTAddToSessionTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void setSelectionInTool(PluginTool subTool, AddressSet sourceSelection) {
	CodeViewerService service = subTool.getService(CodeViewerService.class);
	if (service == null) {
		Assert.fail("Couldn't get listing for tool: " + subTool.getName());
	}
	service.getListingPanel().setSelection(new ProgramSelection(sourceSelection));
}
 
Example 13
Source File: GhidraScript.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Opens the specified program in the current tool.
 *
 * @param program the program to open
 */
public void openProgram(Program program) {
	PluginTool tool = state.getTool();
	if (tool == null) {
		return;
	}
	ProgramManager pm = tool.getService(ProgramManager.class);
	pm.openProgram(program);
	end(true);
	GhidraState newState = new GhidraState(tool, tool.getProject(), program, null, null, null);
	set(newState, monitor, writer);
	start();
}
 
Example 14
Source File: WindowsResourceReferenceAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private PrintWriter getOutputMsgStream(PluginTool tool) {
	if (tool != null) {
		ConsoleService console = tool.getService(ConsoleService.class);
		if (console != null) {
			return console.getStdOut();
		}
	}
	return new PrintWriter(System.out);
}
 
Example 15
Source File: GhidraScript.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Sends a 'goto' event that navigates the listing to the specified
 * address.
 *
 * @param address the address to 'goto'
 * @return true if the address is valid
 */
public boolean goTo(Address address) {
	PluginTool tool = state.getTool();
	if (tool == null) {
		return false;
	}

	GoToService gotoService = tool.getService(GoToService.class);
	if (gotoService != null) {
		return gotoService.goTo(address);
	}
	return false;
}
 
Example 16
Source File: CompositeEditorPanel.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void stopEdit(PluginTool tool) {
	DataTypeManagerService service = tool.getService(DataTypeManagerService.class);
	DataType dataType = service.getDataType((String) null);
	if (dataType != null) {
		editor.setCellEditorValue(dataType);
		editor.stopCellEditing();
	}
	else {
		editor.cancelCellEditing();
	}
}
 
Example 17
Source File: JavaFileListHandler.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(PluginTool tool, DataTree dataTree, GTreeNode destinationNode,
		Object transferData, int dropAction) {

	FileImporterService importer = tool.getService(FileImporterService.class);
	if (importer == null) {
		Msg.showError(this, dataTree, "Could Not Import", "Could not find Importer Service");
		return;
	}

	DomainFolder folder = getDomainFolder(destinationNode);
	doImport(importer, folder, transferData);
}
 
Example 18
Source File: GhidraScript.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a Program, using the title parameter for guidance. The actual behavior of the
 * method depends on your environment, which can be GUI or headless.
 * <br>
 * Regardless of environment -- if script arguments have been set, this method will use the
 * next argument in the array and advance the array index so the next call to an ask method
 * will get the next argument.  If there are no script arguments and a .properties file
 * sharing the same base name as the Ghidra Script exists (i.e., Script1.properties for
 * Script1.java), then this method will then look there for the String value to return.
 * The method will look in the .properties file by searching for a property name that is the
 * title String parameter.  If that property name exists and its value represents a valid
 * program, then the .properties value will be used in the following way:
 * <ol>
 * 		<li>In the GUI environment, this method displays a popup dialog that prompts the user
 * 			to select a program.</li>
 *		<li>In the headless environment, if a .properties file sharing the same base name as the
 *			Ghidra Script exists (i.e., Script1.properties for Script1.java), then this method
 *			looks there for the name of the program to return. The method will look in the
 *			.properties file by searching for a property name equal to the 'title' parameter. If
 *			that property name exists and its value represents a valid Program in the project,
 *			then that value	is returned. Otherwise, an Exception is thrown if there is an
 *			invalid or missing .properties value.</li>
 * </ol>
 * 
 *
 * @param title the title of the pop-up dialog (in GUI mode) or the variable name (in
 * 			headless mode)
 * @return the user-specified Program
 * @throws VersionException if the Program is out-of-date from the version of GHIDRA
 * @throws IOException if there is an error accessing the Program's DomainObject
 * @throws CancelledException if the operation is cancelled
 * @throws IllegalArgumentException if in headless mode, there was a missing or invalid	program
 * 			specified in the .properties file
 */
public Program askProgram(String title)
		throws VersionException, IOException, CancelledException {

	DomainFile existingValue = loadAskValue(this::parseDomainFile, title);
	if (isRunningHeadless()) {
		return (Program) existingValue.getDomainObject(this, false, false, monitor);
	}

	DomainFile choice = doAsk(Program.class, title, "", existingValue, lastValue -> {

		DataTreeDialog dtd = new DataTreeDialog(null, title, DataTreeDialog.OPEN);
		AtomicReference<DomainFile> ref = new AtomicReference<>();

		dtd.addOkActionListener(e -> {
			ref.set(dtd.getDomainFile());
			dtd.close();
		});

		Runnable r = () -> dtd.showComponent();
		Swing.runNow(r);

		if (dtd.wasCancelled()) {
			throw new CancelledException();
		}

		return ref.get();
	});

	if (choice == null) {
		return null;
	}

	PluginTool tool = state.getTool();
	if (tool == null) {
		return (Program) choice.getDomainObject(this, false, false, monitor);
	}

	ProgramManager pm = tool.getService(ProgramManager.class);
	return pm.openProgram(choice);
}
 
Example 19
Source File: EditDataTypeAction.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private boolean hasCustomEditorForBaseDataType(PluginTool tool, DataType dataType) {
	DataType baseDataType = DataTypeUtils.getBaseDataType(dataType);
	final DataTypeManagerService service = tool.getService(DataTypeManagerService.class);
	return baseDataType != null && service.isEditable(baseDataType);
}
 
Example 20
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;
}