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

The following examples show how to use ghidra.program.model.listing.Program#getOptions() . 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: ApplySourceFiles.java    From ghidra with Apache License 2.0 6 votes vote down vote up
static void applyTo(PdbParser pdbParser, XmlPullParser xmlParser, TaskMonitor monitor,
		MessageLog log) {
	Program program = pdbParser.getProgram();
	Options proplist = program.getOptions(Program.PROGRAM_INFO);
	monitor.setMessage("Applying source files...");
	while (xmlParser.hasNext()) {
		if (monitor.isCancelled()) {
			return;
		}
		XmlElement elem = xmlParser.next();
		if (elem.isEnd() && elem.getName().equals("table")) {
			break;
		}

		String name = elem.getAttribute("name");
		int id = XmlUtilities.parseInt(elem.getAttribute("id"));
		proplist.setString("SourceFile" + id, name);

		xmlParser.next();//skip end element
	}
}
 
Example 2
Source File: GhidraProgramUtilities.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the analyzed flag to the specified value.
 * @param program the program to set property
 * @param analyzed the analyzed flag
 */
public static void setAnalyzedFlag(Program program, boolean analyzed) {
	Options options = program.getOptions(Program.PROGRAM_INFO);

	// once the program is analyzed, register the value, so it won't keep writing it to the database.
	if (analyzed && !options.isRegistered(Program.ANALYZED)) {
		options.registerOption(Program.ANALYZED, false, null,
			"Indicates if program has been analyzed");
	}
	int transactionID = program.startTransaction(Program.ANALYZED);
	try {
		options.setBoolean(Program.ANALYZED, analyzed);
	}
	finally {
		program.endTransaction(transactionID, true);
	}
}
 
Example 3
Source File: ImporterUtilities.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Ensure that a {@link Program}'s metadata includes its import origin.
 *
 * @param program imported {@link Program} to modify
 * @param fsrl {@link FSRL} of the import source.
 * @param monitor {@link TaskMonitor} to use when accessing filesystem stuff.
 * @throws CancelledException if user cancels
 * @throws IOException if IO error
 */
public static void setProgramProperties(Program program, FSRL fsrl, TaskMonitor monitor)
		throws CancelledException, IOException {

	Objects.requireNonNull(monitor);

	int id = program.startTransaction("setImportProperties");
	try {
		fsrl = FileSystemService.getInstance().getFullyQualifiedFSRL(fsrl, monitor);

		Options propertyList = program.getOptions(Program.PROGRAM_INFO);
		propertyList.setString(ProgramMappingService.PROGRAM_SOURCE_FSRL, fsrl.toString());
		String md5 = program.getExecutableMD5();
		if ((md5 == null || md5.isEmpty()) && fsrl.getMD5() != null) {
			program.setExecutableMD5(fsrl.getMD5());
		}
	}
	finally {
		program.endTransaction(id, true);
	}
	if (program.canSave()) {
		program.save("Added import properties", monitor);
	}
}
 
Example 4
Source File: ProgramMappingService.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Attempts to create an association between the specified open {@code program} and
 * any {@link FSRL} metadata found in the {@link Program}s properties.
 * <p>
 * Used by event handlers that get notified about a {@link Program} being opened to
 * opportunistically link that program to its source FSRL if the metadata is present.
 * <p>
 * @param program {@link Program} to rummage around in its metadata looking for FSRL info.
 */
public static void createAutoAssocation(Program program) {
	if (program != null) {
		Options propertyList = program.getOptions(Program.PROGRAM_INFO);
		String fsrlStr =
			propertyList.getString(ProgramMappingService.PROGRAM_SOURCE_FSRL, null);
		if (fsrlStr != null) {
			try {
				FSRL fsrl = FSRL.fromString(fsrlStr);
				synchronized (fsrlToProjectPathMap) {
					if (!fsrlToProjectPathMap.containsKey(fsrl)) {
						fsrlToProjectPathMap.put(fsrl, program.getDomainFile().getPathname());
					}
				}
			}
			catch (MalformedURLException e) {
				Msg.error(ProgramMappingService.class, "Bad FSRL found: " + fsrlStr +
					", program: " + program.getDomainFile().getPathname());
			}
		}
	}
}
 
Example 5
Source File: ProgramManagerPlugin.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void showProgramOptions(final Program currentProgram) {
	List<String> names = currentProgram.getOptionsNames();
	Options[] options = new Options[names.size()];
	for (int i = 0; i < names.size(); i++) {
		String optionName = names.get(i);
		options[i] = currentProgram.getOptions(optionName);
		if (optionName.equals("Program Information")) {
			setPropertyEditor(options[i], "Executable Location");
			options[i].setOptionsHelpLocation(new HelpLocation(getName(), "Program_Options"));
		}
	}
	OptionsDialog dialog = new OptionsDialog("Properties for " + currentProgram.getName(),
		"Properties", options, new OptionsEditorListener() {
			@Override
			public void beforeChangesApplied() {
				startTransaction(currentProgram);
			}

			@Override
			public void changesApplied() {
				endTransaction(currentProgram);
			}
		});
	dialog.setHelpLocation(new HelpLocation(HelpTopics.PROGRAM, "Program_Options"));
	tool.showDialog(dialog);
}
 
Example 6
Source File: AutoAnalysisWorkerTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public boolean analysisWorkerCallback(Program p, Object workerContext,
		TaskMonitor monitor) {

	// Can't invoke action since we are in background task here

	Options list = p.getOptions("TEST");
	assertTrue("Higher priorty analysis task failed to run first",
		list.getBoolean("p0", false));
	assertTrue("Lower priorty analysis task failed to run last",
		!list.getBoolean("p1", false));

	cb.goToField(addr("0x1001100"), "Operands", 0, 0);
	assertNull(p.getListing().getFunctionAt(addr("0x100110a")));

	DisassembleCommand cmd = new DisassembleCommand(addr("0x1001100"), null, true);
	cmd.applyTo(p, monitor);

	return true;
}
 
Example 7
Source File: AutoAnalysisPlugin.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(ActionContext context) {
	ListingActionContext programContext = getListingContext(context);
	AddressSetView set;
	if (programContext.hasSelection()) {
		set = programContext.getSelection();
	}
	else {
		set = programContext.getProgram().getMemory();
	}

	AutoAnalysisManager analysisMgr =
		AutoAnalysisManager.getAnalysisManager(programContext.getProgram());

	Program program = programContext.getProgram();
	Options options = program.getOptions(Program.ANALYSIS_PROPERTIES);
	options = options.getOptions(analyzer.getName());
	analyzer.optionsChanged(options, program);

	analysisMgr.schedule(
		new OneShotAnalysisCommand(analyzer, set, analysisMgr.getMessageLog()),
		analyzer.getPriority().priority());

	tool.setStatusInfo("Analysis scheduled: " + analyzer.getName());
}
 
Example 8
Source File: GhidraProgramUtilities.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Removes the analyzed flag from the program properties.
 * With this property removed, the user will be prompted to analyze the
 * program the next time it is opened.
 * @param program the program containing the property to be removed
 */
public static void removeAnalyzedFlag(Program program) {
	int transactionID = program.startTransaction(Program.ANALYZED);
	try {
		Options options = program.getOptions(Program.PROGRAM_INFO);
		options.removeOption(Program.ANALYZED);
	}
	finally {
		program.endTransaction(transactionID, true);
	}
}
 
Example 9
Source File: DyldCacheAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public boolean canAnalyze(Program program) {
	Options options = program.getOptions("Program Information");
	String format = options.getString("Executable Format", null);
	if (!BinaryLoader.BINARY_NAME.equals(format)) {
		return false;
	}
	return DyldCacheUtils.isDyldCache(program);
}
 
Example 10
Source File: GhidraProgramUtilities.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if the program contains the analyzed flag.
 * @param program the program to check for the property
 * @return true if the program contains the analyzed flag
 */
public static boolean shouldAskToAnalyze(Program program) {
	try {
		SimpleDateFormat format = new SimpleDateFormat(Program.ANALYSIS_START_DATE_FORMAT);
		Date analysisStartDate = format.parse(Program.ANALYSIS_START_DATE);
		Date creationDate = program.getCreationDate();
		if (creationDate.compareTo(analysisStartDate) < 0) {
			return false;
		}
	}
	catch (ParseException e) {
	}
	Options options = program.getOptions(Program.PROGRAM_INFO);
	return !options.contains(Program.ANALYZED);
}
 
Example 11
Source File: AnalyzeAllOpenProgramsTaskTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void verifyDefaultOptions(Collection<Program> programs) {
	for (Program program : programs) {
		Options options = program.getOptions(Program.ANALYSIS_PROPERTIES);
		for (String name : options.getOptionNames()) {
			assertTrue("Program options are unexpectedly changed: " + program,
				options.isDefaultValue(name));
		}
	}
}
 
Example 12
Source File: ResourceDataDirectory.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void processVersionInfo(Address addr, ResourceInfo info, Program program,
		MessageLog log, TaskMonitor monitor) throws IOException {
	Options infoList = program.getOptions(Program.PROGRAM_INFO);
	VS_VERSION_INFO versionInfo = null;
	try {
		int ptr = ntHeader.rvaToPointer(info.getAddress());
		if (ptr < 0) {
			Msg.error(this, "Invalid RVA " + Integer.toHexString(info.getAddress()));
			return;
		}
		versionInfo = new VS_VERSION_INFO(reader, ptr);
		PeUtils.createData(program, addr, versionInfo.toDataType(), log);
	}
	catch (DuplicateNameException e) {
		Msg.error(this, "Unexpected Exception: VS_VERSION_INFO structure previously defined",
			e);
	}
	VS_VERSION_CHILD[] children = versionInfo.getChildren();
	for (VS_VERSION_CHILD child : children) {
		if (monitor.isCancelled()) {
			return;
		}
		markupChild(child, addr, program, log, monitor);
	}

	String[] keys = versionInfo.getKeys();
	for (String key : keys) {
		if (monitor.isCancelled()) {
			return;
		}
		String value = versionInfo.getValue(key);
		infoList.setString(key, value);
	}
}
 
Example 13
Source File: AutoAnalysisPlugin.java    From ghidra with Apache License 2.0 5 votes vote down vote up
protected void programOpened(final Program program) {
	final AutoAnalysisManager analysisMgr = AutoAnalysisManager.getAnalysisManager(program);
	analysisMgr.addTool(tool);
	analysisMgr.addListener(this);

	Options options = program.getOptions(Program.ANALYSIS_PROPERTIES);
	options.registerOptionsEditor(new AnalysisOptionsEditor(program));
	options.setOptionsHelpLocation(
		new HelpLocation("AutoAnalysisPlugin", "Auto_Analysis_Option"));
}
 
Example 14
Source File: DataTypeArchiveUtility.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * get a list of known applicable .GDT archives for the given program.
 * 
 * @param program - program to lookup archives for
 * @return list of archives that could apply to this program
 */
public static List<String> getArchiveList(Program program) {
	List<String> list = new ArrayList<String>();

	Options props = program.getOptions(Program.PROGRAM_INFO);
	String format = props.getString("Executable Format", "");

	int size = program.getAddressFactory().getDefaultAddressSpace().getSize();

	if (format.equals(PeLoader.PE_NAME) ||
		(format.equals(CoffLoader.COFF_NAME) && isVisualStudio(program))) {
		// TODO: add in win7/win10
		if (size == 64) {
			list.add("windows_vs12_64");
		}
		else {
			list.add("windows_vs12_32");
		}
	}
	else if (format.equals(MachoLoader.MACH_O_NAME)) {
		// list.add("Cocoa");  // no more cocoa puffs for you
		// TODO: should we have a 64/32 version?
		// TODO: multiple OSX versions
		list.add("mac_osx");
	}
	else if (size == 64) {
		list.add("generic_clib_64");
	}
	// everyone else gets generic clib that was parsed as 32 bit wordsize
	else {
		list.add("generic_clib");
	}
	return list;
}
 
Example 15
Source File: ProgramMappingService.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a currently open Ghidra {@link Program} that has metadata that links it
 * to the specified {@code file} parameter.
 * <p>
 * (ie. an open program has a MD5 or FSRL metadata value that matches the file)
 * <p>
 * See also {@link #isFileOpen(FSRL)}.
 * <p>
 * @param fsrl {@link FSRL} to use when inspecting each open Program's metadata.
 * @param consumer Object that will be used to pin the matching Program open.  Caller
 * must release the consumer when done.
 * @return Already open {@link Program} that has matching metadata, or null if not found.
 */
public static Program findMatchingOpenProgram(FSRL fsrl, Object consumer) {
	String expectedMD5 = fsrl.getMD5();

	// use a temp consumer to hold the domainObject open because the caller-supplied
	// consumer might already have been used to open one of the files we are querying.
	Object tmpConsumer = new Object();
	List<DomainFile> openDomainFiles = AppInfo.getActiveProject().getOpenData();
	for (DomainFile df : openDomainFiles) {
		DomainObject openedDomainObject = df.getOpenedDomainObject(tmpConsumer);
		try {
			if (openedDomainObject instanceof Program) {
				Program program = (Program) openedDomainObject;
				Options propertyList = program.getOptions(Program.PROGRAM_INFO);
				String fsrlStr =
					propertyList.getString(ProgramMappingService.PROGRAM_SOURCE_FSRL, null);
				String md5 =
					propertyList.getString(ProgramMappingService.PROGRAM_METADATA_MD5, null);

				if ((expectedMD5 != null && expectedMD5.equals(md5)) ||
					fsrl.isEquivalent(fsrlStr)) {
					// lock the domain file with the caller-supplied consumer now that
					// we've found it.
					df.getOpenedDomainObject(consumer);
					return program;
				}
			}
		}
		finally {
			if (openedDomainObject != null) {
				openedDomainObject.release(tmpConsumer);
			}
		}
	}
	return null;
}
 
Example 16
Source File: ProgramMappingService.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if there is a current open Ghidra {@link Program} that has metadata
 * that links it to the specified {@link FSRL}.
 * <p>
 * (ie. an open program has a MD5 or FSRL metadata value that matches the fsrl param.)
 *
 * @param fsrl {@link FSRL} to search for in open program info.
 * @return boolean true if found.
 */
public static boolean isFileOpen(FSRL fsrl) {
	String expectedMD5 = fsrl.getMD5();

	List<DomainFile> openDomainFiles = new ArrayList<>();
	AppInfo.getActiveProject().getProjectData().findOpenFiles(openDomainFiles);

	Object consumer = new Object();
	for (DomainFile df : openDomainFiles) {
		DomainObject openedDomainObject = df.getOpenedDomainObject(consumer);
		try {
			if (openedDomainObject instanceof Program) {
				Program program = (Program) openedDomainObject;
				Options propertyList = program.getOptions(Program.PROGRAM_INFO);
				String fsrlStr =
					propertyList.getString(ProgramMappingService.PROGRAM_SOURCE_FSRL, null);
				String md5 =
					propertyList.getString(ProgramMappingService.PROGRAM_METADATA_MD5, null);

				if ((expectedMD5 != null && expectedMD5.equals(md5)) ||
					fsrl.isEquivalent(fsrlStr)) {
					createAssociation(fsrl, program);
					return true;
				}
			}
		}
		finally {
			if (openedDomainObject != null && openedDomainObject.isUsedBy(consumer)) {
				openedDomainObject.release(consumer);
			}
		}
	}
	return false;
}
 
Example 17
Source File: PdbParserTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private Program buildProgram(String exeLocation) throws Exception {

		Program currentTestProgram;

		builder = new ProgramBuilder(programBasename + ".exe", ProgramBuilder._TOY);

		builder.createMemory("test", "0x100", 0x500);
		builder.setBytes("0x110",
			"21 00 01 66 8c 25 28 21 00 01 66 8c 2d 24 21 00 01 9c 8f 05 58 21 00 01 8b 45 00 a3 " +
				"4c 21 00 01 8b 45 04 a3 50 21 00 01 8d 45 08 a3 5c 21 00 01 8b 85 e0 fc ff ff " +
				"c7 05 98 20 00 01 01 00 01 00 a1 50 21 00 01 a3 54 20 00 01 c7 05 48 20 00 01 " +
				"09 04 00 c0 c7 05 4c 20 00 01 01 00 00 00 a1 0c 20 00 01 89 85 d8 fc ff ff a1 " +
				"10 20 00 01 89 85 dc fc ff ff 6a 00 ff 15 28 10 00 01 68 d4 11 00 01 ff 15 38 " +
				"10 00 01 68 09 04 00 c0 ff 15 08 10 00 01 50 ff 15 0c 10 00 01 c3 cc cc cc cc cc");

		currentTestProgram = builder.getProgram();
		currentTestProgram.startTransaction("TEST_" + programBasename + ".exe");

		Options optionsList = currentTestProgram.getOptions(Program.PROGRAM_INFO);
		optionsList.setString(PdbParserConstants.PDB_GUID, notepadGUID);
		optionsList.setString(PdbParserConstants.PDB_AGE, notepadAge);
		optionsList.setString(PdbParserConstants.PDB_FILE, programBasename + ".pdb");
		optionsList.setString("Executable Location",
			exeLocation + File.separator + builder.getProgram().getName());

		return currentTestProgram;
	}
 
Example 18
Source File: PdbProgramAttributes.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public PdbProgramAttributes(Program program) {

		Options propList = program.getOptions(Program.PROGRAM_INFO);

		pdbGuid = propList.getString(PdbParserConstants.PDB_GUID, (String) null);
		pdbAge = propList.getString(PdbParserConstants.PDB_AGE, (String) null);
		pdbLoaded = propList.getBoolean(PdbParserConstants.PDB_LOADED, false);
		programAnalyzed = propList.getBoolean(Program.ANALYZED, false);
		pdbSignature = propList.getString(PdbParserConstants.PDB_SIGNATURE, (String) null);
		pdbFile = propList.getString(PdbParserConstants.PDB_FILE, (String) null);

		executablePath = program.getExecutablePath();

		createGuidAgeString();
	}
 
Example 19
Source File: LibraryLookupTable.java    From ghidra with Apache License 2.0 4 votes vote down vote up
public synchronized static ResourceFile createFile(Program program, boolean overwrite,
		boolean inSystem, TaskMonitor monitor) throws IOException, CancelledException {
	ResourceFile file = null;
	int size = program.getLanguage().getLanguageDescription().getSize();

	if (inSystem) {
		file = getNewSystemExportsFile(new File(program.getExecutablePath()).getName(), size);
	}
	else {
		file = getNewExportsFile(program.getName(), size);
	}
	if (file.exists() && !overwrite) {
		return file;
	}

	monitor.setMessage("[" + program.getName() + "]: creating symbol file...");
	LibrarySymbolTable symTab = new LibrarySymbolTable(program, monitor);
	cacheMap.put(symTab.getCacheKey(), symTab);

	Options props = program.getOptions(Program.PROGRAM_INFO);
	String company = props.getString("CompanyName", "");
	String version = props.getString("FileVersion", "");

	boolean save = company != null && company.toLowerCase().indexOf("microsoft") >= 0;
	if (!save) {
		filesToDeleteList.add(file);
	}
	else {
		symTab.setVersion(version);
	}

	// apply any name definition files
	ResourceFile existingDefFile = getExistingOrdinalFile(program.getName(), size);
	if (existingDefFile != null) {
		symTab.applyOrdinalFile(existingDefFile, false);
	}

	monitor.checkCanceled();

	File f = file.getFile(true);
	if (f == null) {
		Msg.warn(LibraryLookupTable.class, "Can't write to installation directory");
	}
	else {
		symTab.write(f, new File(program.getExecutablePath()), version);
	}

	return file;
}
 
Example 20
Source File: AnalyzeAllOpenProgramsTaskTest.java    From ghidra with Apache License 2.0 2 votes vote down vote up
/**
 * Returns true if the given analyzer is enabled.
 * 
 * @param name the name of the analyzer
 * @param program the program to check
 * @return true if the analyzer is enabled; false otherwise
 */
private boolean isAnalyzerEnabled(String name, Program program) {
	Options options = program.getOptions(Program.ANALYSIS_PROPERTIES);
	return options.getBoolean(name, true);
}