Java Code Examples for ghidra.program.model.listing.Program#endTransaction()

The following examples show how to use ghidra.program.model.listing.Program#endTransaction() . 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: DeleteAction.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(SymbolTreeActionContext context) {
	TreePath[] selectionPaths = context.getSelectedSymbolTreePaths();
	Program program = plugin.getProgram();
	int transactionID = program.startTransaction("Delete Symbol(s)");
	try {
		for (TreePath treePath : selectionPaths) {
			SymbolNode symbolNode = (SymbolNode) treePath.getLastPathComponent();
			Symbol symbol = symbolNode.getSymbol();
			symbol.delete();
			symbolNode.getParent().removeNode(symbolNode);
		}
	}
	finally {
		program.endTransaction(transactionID, true);
	}
}
 
Example 2
Source File: GhidraProject.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Closes the ghidra project, closing (without saving!) any open programs in
 * that project. Also deletes the project if created as a temporary project.
 */
public void close() {
	Iterator<Program> it = openPrograms.keySet().iterator();
	while (it.hasNext()) {
		Program p = it.next();
		int id = (openPrograms.get(p)).intValue();
		if (id >= 0) {
			p.endTransaction(id, true);
		}
		p.release(this);
	}

	openPrograms.clear();
	if (project != null) {
		project.close();
		project = null;
	}

	if (deleteOnClose) {
		ProjectLocator projectLocator = projectData.getProjectLocator();
		if (projectLocator.getMarkerFile().exists()) {
			projectManager.deleteProject(projectLocator);
		}
	}
}
 
Example 3
Source File: ManualStringTranslationService.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method called by Defined String table model to set the value for a single item.
 * <p>
 * This method is here to keep it adjacent to the manual string translation logic.
 *
 * @param program current {@link Program}
 * @param stringLocation {@link ProgramLocation} of the string to set new translation
 * @param newValue String manual translated value
 */
public static void setTranslatedValue(Program program, ProgramLocation stringLocation,
		String newValue) {

	Data data = DataUtilities.getDataAtLocation(stringLocation);
	StringDataInstance sdi = StringDataInstance.getStringDataInstance(data);

	int id = program.startTransaction("Set string translated value");
	try {
		// remove the translation settings if the new value is empty or exactly equal to the
		// actual string data instance value.
		if (newValue.isEmpty() || newValue.equals(sdi.getStringValue())) {
			TRANSLATION.clear(data);
		}
		else {
			TRANSLATION.setTranslatedValue(data, newValue);
			TRANSLATION.setShowTranslated(data, true);
		}
	}
	finally {
		program.endTransaction(id, true);
	}

}
 
Example 4
Source File: DeletePrototypeOverrideAction.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
protected void decompilerActionPerformed(DecompilerActionContext context) {
	Function func = context.getFunction();
	CodeSymbol sym = getSymbol(func, context.getTokenAtCursor());
	Program program = func.getProgram();
	SymbolTable symtab = program.getSymbolTable();
	int transaction = program.startTransaction("Remove Override Signature");
	boolean commit = true;
	if (!symtab.removeSymbolSpecial(sym)) {
		commit = false;
		Msg.showError(getClass(), context.getDecompilerPanel(),
			"Removing Override Signature Failed", "Error removing override signature");
	}
	program.endTransaction(transaction, commit);

}
 
Example 5
Source File: AbstractApplyFunctionSignatureAction.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Attempts to change the signature of a function to that of another
 * function
 * 
 * @param provider the parent component provider 
 * @param destinationFunction the function to change
 * @param sourceFunction the function to copy
 * @return true if the operation was successful
 */
protected boolean updateFunction(ComponentProvider provider, Function destinationFunction,
		Function sourceFunction) {

	Program program = destinationFunction.getProgram();
	int txID = program.startTransaction(ACTION_NAME);
	boolean commit = false;

	try {
		FunctionUtility.updateFunction(destinationFunction, sourceFunction);
		commit = true;
	}
	catch (InvalidInputException | DuplicateNameException e) {
		String message = "Couldn't apply the function signature from " +
			sourceFunction.getName() + " to " + destinationFunction.getName() + " @ " +
			destinationFunction.getEntryPoint().toString() + ". " + e.getMessage();
		Msg.showError(this, provider.getComponent(), ACTION_NAME, message, e);
	}
	finally {
		program.endTransaction(txID, commit);
	}

	return commit;
}
 
Example 6
Source File: LabelMarkupItemTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private Symbol addDefaultLabel(Address address, Program program) {

		SymbolTable symbolTable = program.getSymbolTable();
		int transaction = -1;
		try {
			transaction = program.startTransaction("Test - Add Label");
			ReferenceManager referenceManager = program.getReferenceManager();
			referenceManager.addMemoryReference(address, address, RefType.READ,
				SourceType.USER_DEFINED, 0);
			return symbolTable.getPrimarySymbol(address);
		}
		finally {
			program.endTransaction(transaction, true);
		}
	}
 
Example 7
Source File: AutoTableDisassemblerPlugin.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void run(final TaskMonitor monitor) {
	Program program = currentProgram;
	int transactionID = program.startTransaction("Make Address Table");
	boolean commit = false;
	try {
		collisionCount = makeTables(addresses, monitor);
		commit = true;
	}
	catch (Exception e) {
		if (!(e instanceof DomainObjectException)) {
			Msg.showError(this, null, null, null, e);
		}
	}
	finally {
		program.endTransaction(transactionID, commit);
	}

	SystemUtilities.runSwingLater(() -> {

		AddressTableDialog tempDialog = addressTableDialog;
		if (tempDialog == null) {
			return; // closed/disposed
		}

		tempDialog.makeTablesCompleted();
		if (collisionCount > 0) {
			Msg.showWarn(getClass(), tempDialog.getComponent(),
				"Collisions while Making Tables", collisionMessage);
		}

		refreshModel();
	});
}
 
Example 8
Source File: CommitLocalsAction.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
protected void decompilerActionPerformed(DecompilerActionContext context) {
	Program program = context.getProgram();
	int transaction = program.startTransaction("Commit Local Names");
	try {
		HighFunction hfunc = context.getHighFunction();
		HighFunctionDBUtil.commitLocalNamesToDatabase(hfunc, SourceType.USER_DEFINED);
	}
	finally {
		program.endTransaction(transaction, true);
	}
}
 
Example 9
Source File: ToolBasedColorProvider.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void setVertexColor(FGVertex vertex, Color color) {
	Program program = plugin.getCurrentProgram();
	int id = program.startTransaction("Set Background Color");
	try {
		service.setBackgroundColor(vertex.getAddresses(), color);
	}
	finally {
		program.endTransaction(id, true);
	}

	vertex.setBackgroundColor(color);
}
 
Example 10
Source File: VersionControlSlowScreenShots.java    From ghidra with Apache License 2.0 5 votes vote down vote up
protected void createHistoryEntry(Program p, String symbolName)
		throws InvalidInputException, IOException, CancelledException {
	int transactionID = p.startTransaction("test");
	try {
		SymbolTable symTable = p.getSymbolTable();
		symTable.createLabel(p.getMinAddress().getNewAddress(0x010001000), symbolName,
			SourceType.USER_DEFINED);
	}
	finally {
		p.endTransaction(transactionID, true);
		p.save(null, TaskMonitor.DUMMY);
	}
}
 
Example 11
Source File: MultiTabPluginTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void addComment(Program p) {
	int transactionID = p.startTransaction("test");
	try {
		p.getListing().setComment(p.getAddressFactory().getAddress("01000000"),
			CodeUnit.REPEATABLE_COMMENT, "This is a simple comment change.");
	}
	finally {
		p.endTransaction(transactionID, true);
	}
	p.flushEvents();
	waitForSwing();
}
 
Example 12
Source File: DataLabelMarkupItemTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private Symbol addLabel(String name, Address address, Program program)
		throws InvalidInputException {

	SymbolTable symbolTable = program.getSymbolTable();
	int transaction = -1;
	try {
		transaction = program.startTransaction("Test - Add Label");
		return symbolTable.createLabel(address, name, SourceType.USER_DEFINED);
	}
	finally {
		program.endTransaction(transaction, true);
	}
}
 
Example 13
Source File: LabelMarkupItemTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private Symbol addLabel(String name, Address address, Program program)
		throws InvalidInputException {

	SymbolTable symbolTable = program.getSymbolTable();
	int transaction = -1;
	try {
		transaction = program.startTransaction("Test - Add Label");
		return symbolTable.createLabel(address, name, SourceType.USER_DEFINED);
	}
	finally {
		program.endTransaction(transaction, true);
	}
}
 
Example 14
Source File: ToyProgramBuilder.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void addInstructionBytes(Address start, byte... instrBytes)
		throws MemoryAccessException {
	Program program = getProgram();
	int txId = program.startTransaction("Add Instruction Bytes");
	try {
		for (int i = 0; i < instrBytes.length; i++) {
			program.getMemory().setByte(start.add(i), instrBytes[i]);
		}
		definedInstrAddresses.add(start);
	}
	finally {
		program.endTransaction(txId, true);
	}
}
 
Example 15
Source File: BreakpointEvent.java    From gdbghidra with MIT License 5 votes vote down vote up
private static void doBreakpointTransaction(String action, BreakpointEvent breakpoint, Program currentProgram, ProgramPlugin plugin, long relocate) {
	var caddress = getBreakpointAddress(breakpoint, currentProgram, relocate);
	var category = "breakpoint";

	var tx = currentProgram.startTransaction(action);
	
	/*==================== Begin Transaction ====================================*/
	var service = plugin.getTool().getService(ColorizingService.class);
	var bm = currentProgram.getBookmarkManager().getBookmark(caddress, category, category);
	
	switch(breakpoint.getAction()) {
		case ENABLE:
			service.setBackgroundColor(caddress, caddress, Color.RED);
			break;
		case DISABLE:
			service.setBackgroundColor(caddress, caddress, Color.LIGHT_GRAY);
			break;
		case DELETE:
			service.setBackgroundColor(caddress, caddress, Color.WHITE);
			break;
	}

	if(bm != null) {
		if(breakpoint.action == BreakpointEventAction.DELETE) {
			currentProgram.getBookmarkManager().removeBookmark(bm);
			service = plugin.getTool().getService(ColorizingService.class);
		}else {
			bm.set(category, action);
		}
	}else {
		currentProgram.getBookmarkManager().setBookmark(caddress, category, category, action);
	}
	/*==================== END Transaction ====================================*/
	currentProgram.endTransaction(tx, true);
	
}
 
Example 16
Source File: ToyProgramBuilder.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Add BAD instruction (consumes 2-bytes).  Location will not be added to
 * defined instruction address list.
 * @param addr bad instruction address
 * @throws MemoryAccessException
 */
public void addBytesBadInstruction(String addr) throws MemoryAccessException {
	// do not add to definedInstrAddresses
	Program program = getProgram();
	int txId = program.startTransaction("Add Instruction Bytes");
	try {
		program.getMemory().setShort(addr(addr), (short) 0xf00f);
	}
	finally {
		program.endTransaction(txId, true);
	}
}
 
Example 17
Source File: PrelinkFileSystem.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public Program getProgram(GFile file, LanguageService languageService, TaskMonitor monitor,
		Object consumer) throws Exception {
	Long offset = fileToMachoOffsetMap.get(file);
	if (offset == null) {
		return null;
	}
	MachHeader machHeader =
		MachHeader.createMachHeader(RethrowContinuesFactory.INSTANCE, provider, offset, true);
	LanguageCompilerSpecPair lcs = MacosxLanguageHelper.getLanguageCompilerSpecPair(
		languageService, machHeader.getCpuType(), machHeader.getCpuSubType());
	Program program =
		new ProgramDB(file.getName(), lcs.getLanguage(), lcs.getCompilerSpec(), consumer);
	int id = program.startTransaction(getName());
	boolean success = false;
	try {
		FileBytes fileBytes = MemoryBlockUtils.createFileBytes(program, provider, offset,
			provider.length() - offset, monitor);
		ByteProvider providerWrapper =
			new ByteProviderWrapper(provider, offset, provider.length() - offset);
		MachoProgramBuilder.buildProgram(program, providerWrapper, fileBytes, new MessageLog(),
			monitor);
		program.setExecutableFormat(MachoLoader.MACH_O_NAME);
		program.setExecutablePath(file.getPath());

		if (file.equals(systemKextFile)) {
			processSystemKext(languageService, program, monitor);
		}

		success = true;
	}
	catch (Exception e) {
		throw e;
	}
	finally {
		program.endTransaction(id, success);
		if (!success) {
			program.release(consumer);
		}
	}
	return program;
}
 
Example 18
Source File: PythonPluginExecutionThread.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {

	TaskMonitor interactiveTaskMonitor = plugin.getInteractiveTaskMonitor();
	PythonScript interactiveScript = plugin.getInteractiveScript();
	Program program = plugin.getCurrentProgram();

	// Setup transaction for the execution.
	int transaction_number = -1;
	if (program != null) {
		transaction_number = program.startTransaction("Python command");
	}

	// Setup Ghidra state to be passed into interpreter
	interactiveTaskMonitor.clearCanceled();
	interactiveScript.setSourceFile(new ResourceFile(new File("python")));
	PluginTool tool = plugin.getTool();
	interactiveScript.set(
		new GhidraState(tool, tool.getProject(), program, plugin.getProgramLocation(),
			plugin.getProgramSelection(), plugin.getProgramHighlight()),
		interactiveTaskMonitor, new PrintWriter(plugin.getConsole().getStdOut()));

	// Execute the command
	boolean commit = false;
	moreInputWanted.set(false);
	try {
		moreInputWanted.set(plugin.getInterpreter().push(cmd, plugin.getInteractiveScript()));
		commit = true;
	}
	catch (PyException pye) {
		String exceptionName = PyException.exceptionClassName(pye.type);
		if (exceptionName.equalsIgnoreCase("exceptions.SystemExit")) {
			plugin.reset();
		}
		else {
			plugin.getConsole().getErrWriter().println("Suppressing exception: " +
				PyException.exceptionClassName(pye.type));
		}
	}
	catch (StackOverflowError soe) {
		plugin.getConsole().getErrWriter().println("Stack overflow!");
	}
	finally {
		// Re-get the current program in case the user closed the program while a long running 
		// command was executing.
		program = plugin.getCurrentProgram();
		if (program != null) {
			program.endTransaction(transaction_number, commit);
		}
	}
}
 
Example 19
Source File: DataTypePreviewPluginTest.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Test
public void testPreview() throws Exception {

	DTPPTableModel model = plugin.getTableModel();
	GoToService gotoService = plugin.getGoToService();

	assertEquals(9, model.getRowCount());

	model.add(new ByteDataType());
	model.add(new CharDataType());
	model.add(new DoubleDataType());
	model.add(new QWordDataType());
	model.add(new TerminatedUnicodeDataType());

	assertEquals(9, model.getRowCount());

	Program program = buildProgram();

	env.open(program);

	gotoService.goTo(addr(program, 0x100df26));

	assertEquals("54h", model.getValueAt(0, DTPPTableModel.PREVIEW_COL));
	assertEquals("\"T\"", model.getValueAt(6, DTPPTableModel.PREVIEW_COL));
	assertEquals("20006500680054h", model.getValueAt(5, DTPPTableModel.PREVIEW_COL));
	assertEquals(
		"u\"The Margin values are not correct. Either they are not numeric characters " +
			"or they don't fit the dimensions of the page. Try either entering a number " +
			"or decreasing the margins.\",02h,00h,\"&f\\aPage &p\"",
		model.getValueAt(7, DTPPTableModel.PREVIEW_COL));

	gotoService.goTo(addr(program, 0x100e08c));

	assertEquals("50h", model.getValueAt(0, DTPPTableModel.PREVIEW_COL));
	assertEquals("'P'", model.getValueAt(1, DTPPTableModel.PREVIEW_COL));
	assertEquals("9.346009625593543E-307", model.getValueAt(2, DTPPTableModel.PREVIEW_COL));
	assertEquals("65006700610050h", model.getValueAt(5, DTPPTableModel.PREVIEW_COL));
	assertEquals("u\"Page &p\"", model.getValueAt(7, DTPPTableModel.PREVIEW_COL));

	Structure struct = new StructureDataType("TestStruct", 0);
	struct.add(new FloatDataType(), 4, "FLOAT", null);
	struct.add(new DoubleDataType(), 5, "DOUBLE", null);
	struct.add(new WordDataType(), 2, "WORD", null);
	struct.add(new DWordDataType(), 4, "DWORD", null);
	struct.add(new StringDataType(), 10, "STRING", null);

	int id = program.startTransaction("add");
	try {
		struct = (Structure) program.getDataTypeManager().addDataType(struct,
			DataTypeConflictHandler.REPLACE_HANDLER);
	}
	finally {
		program.endTransaction(id, true);
	}
	model.add(struct);

	assertEquals("8.908155E-39", model.getValueAt(4, DTPPTableModel.PREVIEW_COL));
	assertEquals("6.119088925166103E-308", model.getValueAt(9, DTPPTableModel.PREVIEW_COL));
	assertEquals("2600h", model.getValueAt(10, DTPPTableModel.PREVIEW_COL));
	assertEquals("7000h", model.getValueAt(11, DTPPTableModel.PREVIEW_COL));
	assertEquals("\"\\0\\0\\0\\0\\0\\0\\0\",0Eh,\"\\0f\"",
		model.getValueAt(12, DTPPTableModel.PREVIEW_COL));

	assertEquals(14, model.getRowCount());
}
 
Example 20
Source File: GhidraProject.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Saves the given program to the project with the given name.
 *
 * @param program
 *            the program to be saved
 * @param folderPath
 *            the path where to save the program.
 * @param name
 *            the name to save the program as.
 * @param overWrite
 *            if true, any existing program with that name will be
 *            over-written.
 * @throws DuplicateFileException
 *             if a file exists with that name and overwrite is false or overwrite failed
 * @throws InvalidNameException
 *             the name is null or has invalid characters.
 * @throws IOException
 *             if there was a problem accessing the program
 */
public void saveAs(Program program, String folderPath, String name, boolean overWrite)
		throws InvalidNameException, IOException {

	if (program == null) {
		throw new IllegalArgumentException("Program is null!");
	}
	int id = -1;
	Integer intID = openPrograms.get(program);
	if (intID != null) {
		id = intID.intValue();
	}
	if (id >= 0) {
		program.endTransaction(id, true);
	}
	boolean success = false;
	try {
		DomainFolder folder = projectData.getFolder(folderPath);
		try {
			if (folder == null) {
				throw new IOException("folder not found: " + folderPath);
			}
			if (overWrite) {
				DomainFile df = folder.getFile(name);
				if (df != null) {
					df.delete();
				}
			}
			folder.createFile(name, program, MONITOR);
			success = true;
		}
		catch (DuplicateFileException e) {
			if (overWrite) {
				throw new IOException("Failed to overwrite existing project file: " + name);
			}
			throw e;
		}
	}
	catch (CancelledException e1) {
		throw new IOException("Cancelled");
	}
	finally {
		if (success || id >= 0) {
			openPrograms.put(program, new Integer(program.startTransaction("")));
		}
	}

}