ghidra.program.model.listing.Program Java Examples

The following examples show how to use ghidra.program.model.listing.Program. 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: ProgramMappingService.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an open {@link Program} instance that matches the specified
 * {@link FSRL}, either from the set of currently open programs, or by
 * requesting the specified {@link ProgramManager} to
 * open a {@link DomainFile} that was found to match this GFile.
 * <p>
 * @param fsrl {@link FSRL} of program original location.
 * @param domainFile optional {@link DomainFile} that corresponds to the FSRL param.
 * @param consumer Object that will be used to pin the matching Program open.  Caller
 * must release the consumer when done.
 * @param programManager {@link ProgramManager} that will be used to open DomainFiles
 * if necessary.
 * @param openState one of {@link ProgramManager#OPEN_VISIBLE}, {@link ProgramManager#OPEN_HIDDEN}, {@link ProgramManager#OPEN_VISIBLE}
 * @return {@link Program} which was imported from the specified FSRL, or null if not found.
 */
public static Program findMatchingProgramOpenIfNeeded(FSRL fsrl, DomainFile domainFile,
		Object consumer, ProgramManager programManager, int openState) {
	Program program = findMatchingOpenProgram(fsrl, consumer);
	if (program != null) {
		programManager.openProgram(program, openState);
		return program;
	}
	DomainFile df = (domainFile == null) ? getCachedDomainFileFor(fsrl) : domainFile;
	if (df == null || programManager == null) {
		return null;
	}

	program = programManager.openProgram(df, DomainFile.DEFAULT_VERSION, openState);
	if (program != null) {
		program.addConsumer(consumer);
	}
	return program;
}
 
Example #2
Source File: RelocLgByImport.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public void apply(ImportStateCache importState, RelocationState relocState, 
		ContainerHeader header, Program program, MessageLog log, TaskMonitor monitor) {

	LoaderInfoHeader loader = header.getLoader();
	ImportedLibrary library = loader.findLibrary(index);
	List<ImportedSymbol> importedSymbols = loader.getImportedSymbols();
	ImportedSymbol importedSymbol = importedSymbols.get(index);

	String name = SymbolUtilities.replaceInvalidChars(importedSymbol.getName(), true);
	Address address = relocState.getRelocationAddress();
	Namespace tvectNamespace = importState.getTVectNamespace();
	AddUniqueLabelCmd cmd = new AddUniqueLabelCmd(address, name, tvectNamespace, SourceType.IMPORTED);
	if (!cmd.applyTo(program)) {
		log.appendMsg(cmd.getStatusMsg());
	}

	Symbol symbol = importState.getSymbol(name, library);
	relocState.fixupMemory(address, symbol.getAddress(), log);

	relocState.incrementRelocationAddress(4);
	relocState.setImportIndex(index + 1);
}
 
Example #3
Source File: SecurityDataDirectory.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public void markup(Program program, boolean isBinary, TaskMonitor monitor, MessageLog log,
		NTHeader ntHeader) throws DuplicateNameException, CodeUnitInsertionException,
		DataTypeConflictException, IOException {

	if (!isBinary) {//certificates are never mapped into running program...
		return;
	}

	monitor.setMessage(program.getName()+": security data...");

	AddressSpace space = program.getAddressFactory().getDefaultAddressSpace();
	Address addr = space.getAddress(virtualAddress);//NOTE: virtualAddress is only a binary offset inside file!!!

	createDirectoryBookmark(program, addr);

	program.getListing().clearCodeUnits(addr, addr, false);

	for (SecurityCertificate cert : certificates) {
		DataType dt = cert.toDataType();
		program.getListing().createData(addr, dt);
		addr = addr.add(dt.getLength());
	}
}
 
Example #4
Source File: SymbolTypeTableColumn.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public String getValue(ProgramLocation rowObject, Settings settings, Program program,
		ServiceProvider serviceProvider) throws IllegalArgumentException {

	if (rowObject instanceof VariableLocation) {
		VariableLocation varLoc = (VariableLocation) rowObject;
		return varLoc.isParameter() ? SymbolType.PARAMETER.toString()
				: SymbolType.LOCAL_VAR.toString();
	}

	SymbolTable symbolTable = program.getSymbolTable();
	Symbol symbol;
	if (rowObject instanceof LabelFieldLocation) {
		LabelFieldLocation labLoc = (LabelFieldLocation) rowObject;
		symbol = labLoc.getSymbol();
	}
	else {
		symbol = symbolTable.getPrimarySymbol(rowObject.getAddress());
	}
	if (symbol == null) {
		return null;
	}

	return SymbolUtilities.getSymbolTypeDisplayName(symbol);
}
 
Example #5
Source File: CliTableMemberRef.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
	public void markup(Program program, boolean isBinary, TaskMonitor monitor, MessageLog log, NTHeader ntHeader) 
			throws DuplicateNameException, CodeUnitInsertionException, IOException {
		for (CliAbstractTableRow row : rows) {
			CliMemberRefRow memberRow = (CliMemberRefRow) row;
			// Handle the signature
			Address sigAddr = CliAbstractStream.getStreamMarkupAddress(program, isBinary, monitor, log,
				ntHeader, metadataStream.getBlobStream(), memberRow.signatureIndex);
			// Create object for correct kind of sig
			CliBlob sigBlob = metadataStream.getBlobStream().getBlob(memberRow.signatureIndex);
			if (CliSigField.isFieldSig(sigBlob)) {
				CliSigField fieldSig = new CliSigField(sigBlob);
				metadataStream.getBlobStream().updateBlob(fieldSig, sigAddr, program);
//				program.getBookmarkManager().setBookmark(sigAddr, BookmarkType.INFO, "Signature!", "FieldSig (Offset "+memberRow.signatureIndex+")");
			}
			else {
				CliSigMethodRef methodSig = new CliSigMethodRef(sigBlob);
				metadataStream.getBlobStream().updateBlob(methodSig, sigAddr, program);
//				program.getBookmarkManager().setBookmark(sigAddr, BookmarkType.INFO, "Signature!", "MethodRefSig (Offset "+memberRow.signatureIndex+")");
			}
		}
	}
 
Example #6
Source File: AutoAnalysisPlugin.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Show the options panel for the auto analysis options. 
 */
private boolean showOptionsDialog(Program program) {
	tool.clearStatusInfo();
	Options options = tool.getOptions(GhidraOptions.CATEGORY_AUTO_ANALYSIS);
	boolean showDialog = options.getBoolean(SHOW_ANALYSIS_OPTIONS, true);
	if (!showDialog) {
		return true;
	}
	int id = program.startTransaction("Analysis Options");
	try {
		AnalysisOptionsDialog dialog = new AnalysisOptionsDialog(program);
		tool.showDialog(dialog);
		return dialog.wasAnalyzeButtonSelected();
	}
	finally {
		program.endTransaction(id, true);
	}
}
 
Example #7
Source File: PcodeInjectLibraryVu.java    From ghidra-emotionengine with Apache License 2.0 6 votes vote down vote up
@Override
/**
* This method is called by DecompileCallback.getPcodeInject.
*/
public InjectPayload getPayload(int type, String name, Program program, String context) {
	if (!VECTOR_INSTRUCTIONS.contains(name)) {
		return super.getPayload(type, name, program, context);
	}

	InjectPayloadVu payload =
		(InjectPayloadVu) super.getPayload(InjectPayload.CALLOTHERFIXUP_TYPE, name, program,
			context);

	synchronized (parser) {
           try {
               OpTpl[] opTemplates = payload.getPcode(parser, program, context);
               adjustUniqueBase(opTemplates);
           } finally {
               //clear the added symbols so that the parser can be used again without
               //duplicate symbol name conflicts.
               parser.clearSymbols();
           }
	}
	return payload;
}
 
Example #8
Source File: RelocationFixupHandler.java    From ghidra with Apache License 2.0 6 votes vote down vote up
protected boolean process32BitRelocation(Program program, Relocation relocation,
		Address oldImageBase, Address newImageBase) throws MemoryAccessException,
		CodeUnitInsertionException {
	long diff = newImageBase.subtract(oldImageBase);

	Address address = relocation.getAddress();
	Memory memory = program.getMemory();
	int value = memory.getInt(address);
	int newValue = (int) (value + diff);

	InstructionStasher instructionStasher = new InstructionStasher(program, address);

	memory.setInt(address, newValue);

	instructionStasher.restore();

	return true;
}
 
Example #9
Source File: AsciiExporter.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public boolean export(File file, DomainObject domainObj, AddressSetView addressSet,
		TaskMonitor monitor) throws IOException {

	log.clear();

	if (!(domainObj instanceof Program)) {
		log.appendMsg("Unsupported type: " + domainObj.getClass().getName());
		return false;
	}
	Program program = (Program) domainObj;

	getOptions(() -> program);
	new ProgramTextWriter(file, program, addressSet, monitor, options, provider);
	return true;
}
 
Example #10
Source File: OffcutReferenceCountToAddressTableColumn.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public Integer getValue(Address address, Settings settings, Program program,
		ServiceProvider serviceProvider) throws IllegalArgumentException {
	int count = 0;
	if (address.isMemoryAddress()) {
		CodeUnit codeUnit = program.getListing().getCodeUnitContaining(address);
		if (codeUnit != null) {
			AddressSet set =
				new AddressSet(codeUnit.getMinAddress(), codeUnit.getMaxAddress());
			set.deleteRange(address, address);
			ReferenceManager referenceManager = program.getReferenceManager();
			AddressIterator it = referenceManager.getReferenceDestinationIterator(set, true);
			while (it.hasNext()) {
				it.next();
				count++;
			}
		}
	}
	return Integer.valueOf(count);
}
 
Example #11
Source File: UIUtil.java    From Ghidra-Switch-Loader with ISC License 6 votes vote down vote up
public static void sortProgramTree(Program program)
{
    ProgramDB db = (ProgramDB)program;
    ProgramModule programTreeModule = db.getTreeManager().getRootModule("Program Tree");
    
    if (programTreeModule == null)
        return;
    
    try 
    {
        sortModule(programTreeModule);
    } 
    catch (NotFoundException e) 
    {
    }
}
 
Example #12
Source File: Rtti2Model.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private DataType getDataType(Program program, DataType rtti1Dt) {

		setIsDataTypeAlreadyBasedOnCount(true);
		DataTypeManager dataTypeManager = program.getDataTypeManager();
		int numElements = getCount();
		// Each entry is a 4 byte value.
		if (numElements == 0) {
			numElements = getNumEntries(program, getAddress());
		}
		if (numElements <= 0) {
			return null; // invalid for rtti 2.
		}
		DataType individualEntryDataType = getIndividualEntryDataType(program, rtti1Dt);
		ArrayDataType array = new ArrayDataType(individualEntryDataType, numElements,
			rtti1Dt.getLength(), dataTypeManager);

		return MSDataTypeUtils.getMatchingDataType(program, array);
	}
 
Example #13
Source File: AnalyzeAllOpenProgramsTaskTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void disableAllAnalyzers() {
	AnalyzeProgramStrategySpy spy = new AnalyzeProgramStrategySpy();
	AnalyzeAllOpenProgramsTask task = new AnalyzeAllOpenProgramsTask(tool, openPrograms.get(0),
		openPrograms.toArray(new Program[openPrograms.size()]), spy);
	runTask(task);

	AnalysisOptionsDialog optionsDialog = waitForDialogComponent(AnalysisOptionsDialog.class);
	AnalysisPanel panel =
		findComponent(optionsDialog.getComponent(), AnalysisPanel.class, false);
	invokeInstanceMethod("deselectAll", panel);
	waitForSwing();
}
 
Example #14
Source File: LocationMemento.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public LocationMemento(SaveState saveState, Program[] programs) {
	String programPath = saveState.getString(PROGRAM_PATH, null);
	long programID = saveState.getLong(PROGRAM_ID, -1);
	program = getProgram(programs, programPath, programID);
	if (program == null) {
		throw new IllegalArgumentException("Unable to find program: " + programPath);
	}

	programLocation = ProgramLocation.getLocation(program, saveState);
	if (programLocation == null) {
		throw new IllegalArgumentException("Unable to create a program location!");
	}
}
 
Example #15
Source File: LibrarySymbolNode.java    From ghidra with Apache License 2.0 5 votes vote down vote up
LibrarySymbolNode(Program program, Symbol symbol) {
	super(program, symbol);

	String name = symbol.getName();
	String externalLibraryPath = program.getExternalManager().getExternalLibraryPath(name);
	tooltip = "External Library Symbol - " + name;
	if (externalLibraryPath != null) {
		tooltip = tooltip + " - " + externalLibraryPath;
	}
}
 
Example #16
Source File: NewExt4Analyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
protected Data createData( Program program, Address address, DataType datatype ) throws Exception {
	if ( program.getMemory( ).contains( address ) ) {
		return super.createData( program, address, datatype );
	}
	if ( program2 != null && program2.getMemory( ).contains( address ) ) {
		return super.createData( program2, address, datatype );
	}
	throw new RuntimeException( "Cannot create data, neither program contains that address." );
}
 
Example #17
Source File: AbstractVersionControlActionTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
protected void createHistoryEntry(Program program, String symbolName)
		throws InvalidInputException, IOException, CancelledException {
	int transactionID = program.startTransaction("test");
	try {
		SymbolTable symTable = program.getSymbolTable();
		symTable.createLabel(program.getMinAddress().getNewAddress(0x010001000), symbolName,
			SourceType.USER_DEFINED);
	}
	finally {
		program.endTransaction(transactionID, true);
		program.save(null, TaskMonitor.DUMMY);
	}
}
 
Example #18
Source File: AutoImporter.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public static Program importByUsingSpecificLoaderClass(File file, DomainFolder programFolder,
		Class<? extends Loader> loaderClass, List<Pair<String, String>> loaderArgs,
		Object consumer, MessageLog messageLog, TaskMonitor monitor) throws IOException,
		CancelledException, DuplicateNameException, InvalidNameException, VersionException {
	SingleLoaderFilter loaderFilter = new SingleLoaderFilter(loaderClass, loaderArgs);
	List<Program> programs = importFresh(file, programFolder, consumer, messageLog, monitor,
		loaderFilter, LoadSpecChooser.CHOOSE_THE_FIRST_PREFERRED, null,
		new LoaderArgsOptionChooser(loaderFilter),
		MultipleProgramsStrategy.ONE_PROGRAM_OR_NULL);
	if (programs != null && programs.size() == 1) {
		return programs.get(0);
	}
	return null;
}
 
Example #19
Source File: TableServicePlugin.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void addProvider(Program program, TableComponentProvider<?> provider) {
	List<TableComponentProvider<?>> list = programMap.get(program);
	if (list == null) {
		list = new ArrayList<>();
		programMap.put(program, list);
	}
	list.add(provider);
}
 
Example #20
Source File: CallTreeProvider.java    From ghidra with Apache License 2.0 5 votes vote down vote up
void initialize(Program program, ProgramLocation location) {
	if (program == null) { // no program open
		setLocation(null);
		return;
	}

	currentProgram = program;
	currentProgram.addListener(this);
	doSetLocation(location);
}
 
Example #21
Source File: ExternalProgramMerger.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Removes the indicated external library from the indicated program version
 * if it is empty.
 * @param program the program
 * @param libName the external library name
 * @throws InvalidInputException if there is no such enterrnal library in the program
 */
private void removeExternalLibrary(Program program, String libName)
		throws InvalidInputException {
	ExternalManager extMgr = program.getExternalManager();
	ExternalLocationIterator iter = extMgr.getExternalLocations(libName);
	if (iter.hasNext()) {
		throw new InvalidInputException(
			"Didn't remove external library " + libName + " since it isn't empty.");
	}
	if (!extMgr.removeExternalLibrary(libName)) {
		throw new InvalidInputException("Didn't remove external library " + libName);
	}
}
 
Example #22
Source File: AbstractGhidraHeadlessIntegrationTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public void goTo(PluginTool tool, Program p, String addrString) {
	AddressFactory factory = p.getAddressFactory();
	Address addr = factory.getAddress(addrString);
	tool.firePluginEvent(
		new ProgramLocationPluginEvent("Test", new ProgramLocation(p, addr), p));
	waitForSwing();
}
 
Example #23
Source File: MultiTabPlugin.java    From ghidra with Apache License 2.0 5 votes vote down vote up
String getStringUsedInList(Program program) {
	DomainFile df = program.getDomainFile();
	String changeIndicator = program.isChanged() ? "*" : "";
	if (!df.isInWritableProject()) {
		return df.toString() + " [Read-Only]" + changeIndicator;
	}
	return df.toString() + changeIndicator;
}
 
Example #24
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 #25
Source File: ProgramManagerPlugin.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void updateSaveAction(Program p) {
	if (p == null) {
		saveAction.getMenuBarData().setMenuItemName("&Save");
		saveAction.setDescription("Save Program");
		saveAction.setEnabled(false);
	}
	else {
		String programName = "'" + p.getDomainFile().getName() + "'";
		saveAction.getMenuBarData().setMenuItemName("&Save " + programName);
		saveAction.setDescription("Save " + programName);
		saveAction.setEnabled(p.isChanged());
	}
}
 
Example #26
Source File: CreateRtti2BackgroundCmd.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
protected Rtti2Model createModel(Program program) {
	if (model == null || program != model.getProgram()) {
		model = new Rtti2Model(program, rtti1Count, getDataAddress(), validationOptions);
	}
	return model;
}
 
Example #27
Source File: PreCommentMarkupType.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
protected ProgramLocation getLocation(VTAssociation association, Address address,
		boolean isSource) {
	if (address == null || address == Address.NO_ADDRESS) {
		return null;
	}

	Program program =
		isSource ? getSourceProgram(association) : getDestinationProgram(association);
	return new CommentFieldLocation(program, address, null, null, CodeUnit.PRE_COMMENT, 0, 0);
}
 
Example #28
Source File: BinaryLoader.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean loadProgramInto(ByteProvider provider, LoadSpec loadSpec,
		List<Option> options, MessageLog log, Program prog, TaskMonitor monitor)
		throws IOException, CancelledException {
	long length = getLength(options);
	//File file = provider.getFile();
	long fileOffset = getFileOffset(options);
	Address baseAddr = getBaseAddr(options);
	String blockName = getBlockName(options);
	boolean isOverlay = isOverlay(options);

	if (length == 0) {
		length = provider.length();
	}

	length = clipToMemorySpace(length, log, prog);

	FileBytes fileBytes =
		MemoryBlockUtils.createFileBytes(prog, provider, fileOffset, length, monitor);
	try {
		AddressSpace space = prog.getAddressFactory().getDefaultAddressSpace();
		if (baseAddr == null) {
			baseAddr = space.getAddress(0);
		}
		if (blockName == null || blockName.length() == 0) {
			blockName = generateBlockName(prog, isOverlay, baseAddr.getAddressSpace());
		}
		createBlock(prog, isOverlay, blockName, baseAddr, fileBytes, length, log);

		return true;
	}
	catch (AddressOverflowException e) {
		throw new IllegalArgumentException("Invalid address range specified: start:" +
			baseAddr + ", length:" + length + " - end address exceeds address space boundary!");
	}
}
 
Example #29
Source File: BinaryPropertyListAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private BinaryPropertyListTrailer markupBinaryPropertyListTrailer(Program program,
		BinaryPropertyListHeader header, Address baseAddress) throws Exception {
	BinaryPropertyListTrailer trailer = header.getTrailer();
	Address trailerAddress = baseAddress.add(trailer.getTrailerIndex());
	DataType trailerDataType = trailer.toDataType();
	clearListing(program, trailerAddress, trailerAddress.add(trailerDataType.getLength()));
	createData(program, trailerAddress, trailerDataType);
	createFragment(program, trailerDataType.getName(), trailerAddress,
		trailerAddress.add(trailerDataType.getLength()));
	setPlateComment(program, trailerAddress, "Binary Property List Trailer");
	return trailer;
}
 
Example #30
Source File: AbstractVTMatchTableModel.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public DisplayableListingAddress getValue(VTMatch rowObject, Settings settings,
		Program program, ServiceProvider serviceProvider) throws IllegalArgumentException {
	if (symbolInspector == null) {
		symbolInspector = new SymbolInspector(serviceProvider, null);
	}
	VTAssociation association = rowObject.getAssociation();
	Address sourceAddress = association.getSourceAddress();
	Program sourceProgram = rowObject.getMatchSet().getSession().getSourceProgram();
	return new DisplayableListingAddress(sourceProgram, sourceAddress);
}