Ghidra is a software reverse engineering (SRE) framework
GP-1180 fix LoadPdbDialog handling of missing pdb info, fixes github issue #3289
dev74736876337295d44c
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/plugin/core/analysis/PdbAnalyzerCommon.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/plugin/core/analysis/PdbAnalyzerCommon.javaindex f9149b9984..7c4ead5837 100644--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/plugin/core/analysis/PdbAnalyzerCommon.java+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/plugin/core/analysis/PdbAnalyzerCommon.java@@ -15,9 +15,8 @@*/package ghidra.app.plugin.core.analysis;-import java.util.Set;-import java.io.File;+import java.util.Set;import ghidra.app.services.Analyzer;import ghidra.app.util.opinion.PeLoader;@@ -123,7 +122,7 @@ public class PdbAnalyzerCommon {static File findPdb(Analyzer pdbAnalyzer, Program program, boolean allowRemote,TaskMonitor monitor) {- SymbolFileInfo symbolFileInfo = SymbolFileInfo.fromMetadata(program.getMetadata());+ SymbolFileInfo symbolFileInfo = SymbolFileInfo.fromProgramInfo(program);if (symbolFileInfo == null) {Msg.info(pdbAnalyzer,"Skipping PDB processing: missing PDB information in program metadata");diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/plugin/core/analysis/PdbUniversalAnalyzer.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/plugin/core/analysis/PdbUniversalAnalyzer.javaindex 4ba7249cb5..a02db87386 100644--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/plugin/core/analysis/PdbUniversalAnalyzer.java+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/plugin/core/analysis/PdbUniversalAnalyzer.java@@ -22,11 +22,10 @@ import java.util.Date;import ghidra.app.services.*;import ghidra.app.util.bin.format.pdb2.pdbreader.*;import ghidra.app.util.importer.MessageLog;-import ghidra.app.util.pdb.PdbLocator;import ghidra.app.util.pdb.PdbProgramAttributes;import ghidra.app.util.pdb.pdbapplicator.PdbApplicator;import ghidra.app.util.pdb.pdbapplicator.PdbApplicatorOptions;-import ghidra.framework.Application;+import ghidra.framework.*;import ghidra.framework.options.OptionType;import ghidra.framework.options.Options;import ghidra.program.model.address.AddressSetView;@@ -73,7 +72,14 @@ public class PdbUniversalAnalyzer extends AbstractAnalyzer {private static final String OPTION_NAME_FORCELOAD_FILE = "Force-Load FilePath";private static final String OPTION_DESCRIPTION_FORCELOAD_FILE ="This file is force-loaded if the '" + OPTION_NAME_DO_FORCELOAD + "' option is checked";- private File DEFAULT_FORCE_LOAD_FILE = new File(PdbLocator.DEFAULT_SYMBOLS_DIR, "sample.pdb");++ // Default symbol directory guessing+ private static final File DEFAULT_SYMBOLS_DIR =+ Platform.CURRENT_PLATFORM.getOperatingSystem() == OperatingSystem.WINDOWS+ ? new File("C:\\Symbols")+ : new File(new File(System.getProperty("user.home")), "Symbols");++ private File DEFAULT_FORCE_LOAD_FILE = new File(DEFAULT_SYMBOLS_DIR, "sample.pdb");private File forceLoadFile;private boolean searchRemoteLocations = false;diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/PdbLocator.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/PdbLocator.javadeleted file mode 100644index b3406e48eb..0000000000--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/PdbLocator.java+++ /dev/null@@ -1,700 +0,0 @@-/* ###- * IP: GHIDRA- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-package ghidra.app.util.pdb;--import java.io.File;-import java.io.FileNotFoundException;-import java.util.*;--import docking.widgets.OptionDialog;-import ghidra.app.util.bin.format.pdb.PdbParserConstants;-import ghidra.app.util.bin.format.pdb2.pdbreader.*;-import ghidra.app.util.datatype.microsoft.GUID;-import ghidra.app.util.importer.LibrarySearchPathManager;-import ghidra.app.util.importer.MessageLog;-import ghidra.framework.OperatingSystem;-import ghidra.framework.Platform;-import ghidra.framework.preferences.Preferences;-import ghidra.program.model.listing.Program;-import ghidra.util.Msg;-import ghidra.util.SystemUtilities;-import ghidra.util.exception.CancelledException;-import ghidra.util.task.TaskMonitor;--/**- * Searches for and presents PDB path information in order specified by- * <a href="https://docs.microsoft.com/en-us/windows/desktop/debug/symbol-paths">- * Symbol Paths</a>.- * <P>- * Gist is: TODO.- * <PRE>- * Our design:- * Looking for files with extension .pdb or .PDB using an ordered set of paths and resources.- *- * TODO:- * Option to look exclusively for the above, exclusively for something else, or inclusive of- * other extensions with a preference order. So if we want to inclusively look for .pdb- * and .pdb.xml with a preference of .pdb, and if we have a path search order of path A,- * then path B, the question is whether we would choose a .pdb file in path B before a .pdb.xml- * in path A. Same question for other extensions such as .dbg.- *- * Could do similar to SymSetSearchPath() with semicolon-separated paths.- *- * Could have an configuration list that gives the search order for all resources to be searched.- * For instance: path of the loaded executable, path specified in header of loaded executable,- * local symbol paths, symbol servers at specified URLs.- * -> Could allow any of these to not be active; could require optional user interaction ("are- * you sure") for the path specified in the header of the loaded executable, option of read- * and/or write to local symbol cache.- *- * Depending on whether is or used to be supported by MSFT, allow (with option?) the 2-tier- * symbol server directory structure.- *- * Should we allow different or use different structures for local paths vs. symbol server paths?- * For instance, the extension-tier (if *.dll, search an appropriate set of paths that have a- * "dll" component).- *- * </PRE>- */-public class PdbLocator {-- public static final boolean onWindows =- (Platform.CURRENT_PLATFORM.getOperatingSystem() == OperatingSystem.WINDOWS);-- private static final File USER_HOME = new File(System.getProperty("user.home"));- public static final File DEFAULT_SYMBOLS_DIR =- onWindows ? new File("C:\\Symbols") : new File(USER_HOME, "Symbols");- public final static File WINDOWS_SYMBOLS_DIR =- onWindows ? new File("C:/WINDOWS/Symbols") : null;-- public final static String PDB_SYMBOLS_DIR_PREFERENCE = "PDB Storage Directory";-- private File symbolsRepositoryDir;- /**- * Only holds identifies in PDBs up until a matching one was found--nothing beyond that.- */- private Map<String, PdbIdentifiers> identifiersByFilePath = new HashMap<>();-- public PdbLocator(File symbolsRepositoryDir) {- this.symbolsRepositoryDir = symbolsRepositoryDir;- }-- //==============================================================================================- // TODO: Ideas for future.-// public SymbolPathSearcher(String message) {-// }-- // Search order preference:- // EXTENSION_PREFERENCE_ORDER(pdb, pdb.xml, dbg)--at least one; no duplicates- // e.g., {PDB, PDB_XML, DBG} means *.pdb before *.pdb.xml before *.dbg- // PATH_BEFORE_EXTENSION or EXTENSION_BEFORE_PATH- // e.g.,- // PATH_BEFORE_EXTENSION means: (assuming EXTENION_PREFERENCE_ORDER is {PDB, PDB_XML}),- // at first path in list look for *.pdb, then *.pdb.xml, then if failed to- // find at the first path, try the same tWO ordered searches at the second path in- // the path list, etc.- // EXTENSION_BEFORE_PATH means: (assuming EXTENION_PREFERENCE_ORDER is {PDB, PDB_XML}),- // at first path in list look for *.pdb, then search for *.pdb at the second path, etc.- // If after the last path a *.pdb is not found, then repeat with list of paths, now- // looking for *.pdb.xml-- // Use a list of enums to specify search order?- // queryUser true if can interact with user (non-headless)-- // need paths for symbol server vs. paths for local cache?-- // specify filetype (pdb, pdb.xml, dbg, other?)-- // upper/lower case conversion--// public void find(boolean includePeSpecifiedPdbPath, boolean queryUser) {-// }-- //==============================================================================================- /*- * TODO 20190403: Need to consider documentation at- * <a href="https://docs.microsoft.com/en-us/windows/desktop/debug/symbol-paths">- * Symbol Paths</a>.- * <P>- * Says order:- * <li>C:\MySymbols- * <li>C:\MySymbols\ext, where ext is extension of binary (e.g., dll, exe, sys)- * <li>C:\MySymbols\symbols\ext- * <P>- */- // 20190321 Thoughts for fixing this up:- // Processing logic:- //- // Tenet: Program may or may not specify the following about an associated PDB:- // - filename of PDB- // - version (magic: RSDS)- // - signature- // - age- // - GUID (probably only in later versions)- //- // Tenet: PDB files may or may not specify the following about themselves:- // - version (date field indicating PDB version; also versioning dates of subcomponents)- // - signature- // - age- // - GUID (only in later versions)- //- // Tenet: Can be headed (GUI) or headless processing- //- // Logic Basics:- // - Need at least the filename.- // - No user interaction if headless.- //- // Use cases:- // - Given Program PDB info, search/find matching PDB, and apply all possible; else fail- // - Given Program PDB info, if matching PDB not found, but similar exist, present- // all possibles to user for choice or cancel. Choice would include the filename- // location along with the basic information pieces indicated above. Option to- // apply data types only (to a DataTypeManager) or to additionally apply symbols.- // (Could dig into each PDB for possible compile information, but requires full- // parsing.) Future may allow for a way to bring in symbol information into a- // temporary space that could allow the user to selectively choose symbols to apply- // to Program locations.- // - Given Program PDB info, if headless and exact match not found, option flag to fail- // with no information or to fail with the filenames and associated basic info.- // - Regardless of PDB info, if headless use "force" option with a single filename,- // which will force parsing and application of PDB file. (No option to force- // partially apply any parts of the PDB--think on this more.)- // Additional use cases:- // - Any PDB file can be loaded for general perusing (maybe).- // - Multiple PDB files can be loaded at any given time.- // - Multiple PDB files can have been loaded and had their data type processed and put- // into data type Categories labeled with the PDB information (might need GUID- // and other attributes used to help uniquely identify each (perhaps part of the- // Category name)). Perhaps the symbols for each PDB are available--perhaps just- // have each PDB available for further symbol/data type application.- //- // Today's Logic:- public String findPdb(Program program, PdbProgramAttributes programAttributes,- boolean userInteractive, boolean includePeSpecifiedPdbPath, TaskMonitor monitor,- MessageLog log, String messagePrefix) throws CancelledException {-- List<String> orderedListOfExistingFileNames =- lookForPdb(program, includePeSpecifiedPdbPath, log, messagePrefix);- if (orderedListOfExistingFileNames.isEmpty()) {- String message = "Cannot find candidate PDB files.";- log.appendMsg(messagePrefix, message);- return null;- }-- String pdbFilename = null;- try {- pdbFilename = choosePdb(orderedListOfExistingFileNames, programAttributes, monitor, log,- messagePrefix);- }- catch (PdbException e) {- String message = "Could not find appropriate PDB file. Detailed issues may follow:\n" +- e.toString();- log.appendMsg(messagePrefix, message);- return null;- }-- return pdbFilename;- }-- //==============================================================================================- /**- * @param program Program under analysis.- * @param includePeSpecifiedPdbPath {@code true} if looking for PDB in PE-Header-Specified- * path location, which may be unsafe security-wise.- * @param log MessageLog to report to.- * @param messagePrefix prefix string for any error message written to the log- * @return Ordered List<String> of potential filenames- */- private List<String> lookForPdb(Program program, boolean includePeSpecifiedPdbPath,- MessageLog log, String messagePrefix) {- String message = "";- try {-- List<String> orderedListOfExistingFileNames = findPDB(new PdbProgramAttributes(program),- includePeSpecifiedPdbPath, symbolsRepositoryDir);- if (orderedListOfExistingFileNames.isEmpty()) {-- String pdbName = program.getOptions(Program.PROGRAM_INFO)- .getString(PdbParserConstants.PDB_FILE, (String) null);- if (pdbName == null) {- message = "Program has no associated PDB file.";- }- else {- message = "Unable to locate PDB file \"" + pdbName + "\" with matching GUID.";- }- if (SystemUtilities.isInHeadlessMode()) {- message += "\n Use a script to set the PDB Symbol Location. I.e.,\n" +- " setAnalysisOption(currentProgram, \"PDB.Symbol Repository Path\", " +- "\"/path/to/pdb/folder\");\n" +- " This must be done using a pre-script (prior to analysis).";- }- else {- message +=- "\n You can manually load PDBs using the \"File->Load PDB File...\" action.";- if (pdbName != null) {- message += "\n Alternatively, you may set the PDB Symbol Repository Path" +- "\n using \"Edit->Options for [program]\" prior to analysis.";- }- }- }- return orderedListOfExistingFileNames;- }- catch (PdbException pe) {- message += pe.getMessage();- }- finally {- if (message.length() > 0) {- log.appendMsg(messagePrefix, message);- log.setStatus(message);- }- }-- return null;- }-- //==============================================================================================- private String choosePdb(List<String> orderedListOfExistingFileNames,- PdbProgramAttributes programAttributes, TaskMonitor monitor, MessageLog log,- String messagePrefix) throws PdbException, CancelledException {- String choice = findMatchingPdb(orderedListOfExistingFileNames, programAttributes, monitor);- if (choice == null) {- //choice = userSelectPdb(programAttributes, messagePrefix, log, monitor);- String message = getNoMatchMessage(programAttributes, monitor);- log.appendMsg(message);- }- return choice;- }-- //==============================================================================================- private String findMatchingPdb(List<String> orderedListOfExistingFileNames,- PdbProgramAttributes programAttributes, TaskMonitor monitor)- throws PdbException, CancelledException {-- String message = "";-- for (String filepath : orderedListOfExistingFileNames) {- monitor.checkCanceled();- monitor.setMessage("Attempting to find/process PDB file " + filepath + "...");- try (AbstractPdb tryPdb = PdbParser.parse(filepath, new PdbReaderOptions(), monitor)) {- PdbIdentifiers identifiers = tryPdb.getIdentifiers();- identifiersByFilePath.put(filepath, identifiers);- if (verifyPdbSignature(programAttributes, identifiers)) {- monitor.setMessage("Parsing validated PDB file " + filepath + ".");- return filepath;- }- }- catch (Exception e) {- // Ignore FileNotFoundException.- if (!e.getClass().equals(FileNotFoundException.class)) {- // Noting any exceptions. Will only report if we have not successfully- // found a matching PDB without an exception being thrown for it.- message += "Exception for attempted PDB " + filepath + ": " + e.toString();- }- }- }- if (!message.isEmpty()) {- throw new PdbException(message);- }- return null;- }-- //==============================================================================================- @SuppressWarnings("unused") // for method not being called.- private String userSelectPdb(PdbProgramAttributes programAttributes, String messagePrefix,- MessageLog log, TaskMonitor monitor) throws CancelledException {-- String[] fileNames = new String[identifiersByFilePath.size()];- String[] fileIdents = new String[identifiersByFilePath.size()];- int i = 0;- for (Map.Entry<String, PdbIdentifiers> entry : identifiersByFilePath.entrySet()) {- monitor.checkCanceled();- fileNames[i] = entry.getKey();- fileIdents[i++] = formatPdbIdentifiers(entry.getKey(), entry.getValue()).toString();- }-- String message = "Could not match program with PDB.\n";- if (identifiersByFilePath.size() != 0) {- message += "PDB File Options (Name Signature Age GUID):\n";- for (String fileIdent : fileIdents) {- message += fileIdent + "\n";- }- }-- if (SystemUtilities.isInHeadlessMode()) {- message = "In Headless mode... skipping PDB processing.\n";- log.appendMsg(messagePrefix, message);- log.setStatus(message);- return null;- }- String header =- "Choose PDB or Cancel (for: " + formatPdbIdentifiers(programAttributes) + ")";- String userChoice = OptionDialog.showInputChoiceDialog(null, header, "Choose", fileIdents,- fileIdents[0], OptionDialog.CANCEL_OPTION);- if (userChoice == null) {- return null;- }- for (i = 0; i < fileIdents.length; i++) {- if (userChoice.contentEquals(fileIdents[i])) {- message = "User PDB Choice: " + userChoice;- Msg.info(this, message); // Info for console.- return fileNames[i];- }- }- return null;- }-- //==============================================================================================- private String getNoMatchMessage(PdbProgramAttributes programAttributes, TaskMonitor monitor)- throws CancelledException {- StringBuilder builder = new StringBuilder();- builder.append("ERROR: Could not run PDB Analyzer because a matched PDB was not found.\n");- builder.append("PDB specification from PE header:\n");- builder.append(formatPdbIdentifiers(programAttributes));-- builder.append("Discovered non-matches:\n");- for (Map.Entry<String, PdbIdentifiers> entry : identifiersByFilePath.entrySet()) {- monitor.checkCanceled();- builder.append(formatPdbIdentifiers(entry.getKey(), entry.getValue()));- }- return builder.toString();- }-- public static StringBuilder formatPdbIdentifiers(PdbProgramAttributes attributes) {- Integer signature = (attributes.getPdbSignature() == null) ? null- : Integer.valueOf(attributes.getPdbSignature());- return formatPdbIdentifiers(attributes.getPdbFile(), signature,- Integer.valueOf(attributes.getPdbAge(), 16), attributes.getPdbGuid());- }-- public static StringBuilder formatPdbIdentifiers(String file, PdbIdentifiers identifiers) {- return formatPdbIdentifiers(file, identifiers.getSignature(), identifiers.getAge(),- identifiers.getGuid().toString());- }-- private static StringBuilder formatPdbIdentifiers(String file, Integer signature, int age,- String guidString) {- StringBuilder builder = new StringBuilder();- builder.append(" Location: ").append(file);- if (signature != null) {- builder.append(String.format("; Signature: 0X%08X", signature));- }- builder.append("; Age: 0x");- builder.append(Integer.toHexString(age));- if (guidString != null) {- builder.append("; GUID: ");- builder.append(guidString);- }- builder.append('\n');- return builder;- }-- //==============================================================================================- /**- * Find a matching PDB file using attributes associated with the program. User can specify the- * type of file to search from (.pdb or .pdb.xml).- *- * @param pdbAttributes PDB attributes associated with the program.- * @param includePeSpecifiedPdbPath {@code true} if looking for PDB in PE-Header-Specified- * path location, which may be unsafe security-wise.- * @param symbolsRepositoryDir Location of the local symbols repository (can be null).- * @return matching PDB file (or null, if not found).- * @throws PdbException if there was a problem with the PDB attributes.- */- private static List<String> findPDB(PdbProgramAttributes pdbAttributes,- boolean includePeSpecifiedPdbPath, File symbolsRepositoryDir) throws PdbException {-- // Store potential names of PDB files and potential locations of those files,- // so that all possible combinations can be searched.- // LinkedHashSet is used when we need to preserve order- Set<String> guidSubdirPaths = new HashSet<>();-- String guidAgeString = pdbAttributes.getGuidAgeCombo();- if (guidAgeString == null) {- throw new PdbException(- "Incomplete PDB information (GUID/Signature and/or age) associated with this program.\n" +- "Either the program is not a PE, or it was not compiled with debug information.");- }-- List<String> potentialPdbNames = pdbAttributes.getPotentialPdbFilenames();- for (String potentialName : potentialPdbNames) {- guidSubdirPaths.add(File.separator + potentialName + File.separator + guidAgeString);- }-- return checkPathsForPdb(symbolsRepositoryDir, guidSubdirPaths, potentialPdbNames,- pdbAttributes, includePeSpecifiedPdbPath);- }-- //==============================================================================================- /**- * Check potential paths in a specific order. If the symbolsRepositoryPath parameter is- * supplied and the directory exists, that directory will be searched first for the- * matching PDB file.- *- * If the file type is supplied, then only that file type will be searched for. Otherwise,- * the search process depends on the current operating system that Ghidra is running from:- *- * - Windows: look in the symbolsRepositoryPath for a matching .pdb file. If one does not- * exist, look for a .pdb.xml file in symbolsRepositoryPath. If not found, then- * search for a matching .pdb file, then .pdb.xml file, in other directories.- * - non-Windows: look in the symbolsRepositoryPath for a matching .pdb.xml file. If one does- * not exist, look for a .pdb file. If a .pdb file is found, return an error saying- * that it was found, but could not be processed. If no matches found in- * symbolsRepositoryPath, then look for .pdb.xml file, then .pdb.xml file in other- * directories.- *- * @param symbolsRepositoryDir location of the local symbols repository (can be null)- * @param guidSubdirPaths subdirectory paths (that include the PDB's GUID) that may contain- * a matching PDB- * @param potentialPdbNames all potential filenames for the PDB file(s) that match the program- * @param pdbAttributes PDB attributes associated with the program- * @param includePeSpecifiedPdbPath if true include paths derived from the PDB file path- * determined at time of import. NOTE: This option is considered unsafe and should not be- * enabled unless binary source is trusted and PDB file path is reasonable for this system.- * @return matching PDB file, if found (else null)- */- private static List<String> checkPathsForPdb(File symbolsRepositoryDir,- Set<String> guidSubdirPaths, List<String> potentialPdbNames,- PdbProgramAttributes pdbAttributes, boolean includePeSpecifiedPdbPath) {-- Set<File> symbolsRepoPaths =- getSymbolsRepositoryPaths(symbolsRepositoryDir, guidSubdirPaths);- Set<File> predefinedPaths =- getPredefinedPaths(guidSubdirPaths, pdbAttributes, includePeSpecifiedPdbPath);-- // Start by searching in symbolsRepositoryDir, if available.-- List<String> orderedListOfExistingFileNames = new ArrayList<>();- if (!symbolsRepoPaths.isEmpty()) {- orderedListOfExistingFileNames- .addAll(checkSpecificPathsForPdb(symbolsRepoPaths, potentialPdbNames));- }-- orderedListOfExistingFileNames- .addAll(checkSpecificPathsForPdb(predefinedPaths, potentialPdbNames));-- return orderedListOfExistingFileNames;-- }-- //==============================================================================================- private static List<String> checkSpecificPathsForPdb(Set<File> paths,- List<String> potentialPdbNames) {-- List<String> orderedListOfExistingFileNames = checkForPDBorXML(paths, potentialPdbNames);-- return orderedListOfExistingFileNames;- }-- //==============================================================================================- private static Set<File> getSymbolsRepositoryPaths(File symbolsRepositoryDir,- Set<String> guidSubdirPaths) {-- Set<File> symbolsRepoPaths = new LinkedHashSet<>();-- // Collect sub-directories of the symbol repository that exist- if (symbolsRepositoryDir != null && symbolsRepositoryDir.isDirectory()) {-- for (String guidSubdir : guidSubdirPaths) {- File testDir = new File(symbolsRepositoryDir, guidSubdir);- if (testDir.isDirectory()) {- symbolsRepoPaths.add(testDir);- }- }-- // Check outer folder last- symbolsRepoPaths.add(symbolsRepositoryDir);- }-- return symbolsRepoPaths;- }-- //==============================================================================================- // Get list of "paths we know about" to search for PDBs- private static Set<File> getPredefinedPaths(Set<String> guidSubdirPaths,- PdbProgramAttributes pdbAttributes, boolean includePeSpecifiedPdbPath) {-- Set<File> predefinedPaths = new LinkedHashSet<>();-- getPathsFromAttributes(pdbAttributes, includePeSpecifiedPdbPath, predefinedPaths);- getSymbolPaths(DEFAULT_SYMBOLS_DIR, guidSubdirPaths, predefinedPaths);- getSymbolPaths(WINDOWS_SYMBOLS_DIR, guidSubdirPaths, predefinedPaths);- getLibraryPaths(guidSubdirPaths, predefinedPaths);-- return predefinedPaths;- }-- //==============================================================================================- private static void getLibraryPaths(Set<String> guidSubdirPaths, Set<File> predefinedPaths) {- String[] libraryPaths = LibrarySearchPathManager.getLibraryPaths();-- File libFile, subDir;-- for (String path : libraryPaths) {-- if ((libFile = new File(path)).isDirectory()) {- predefinedPaths.add(libFile);-- // Check alternate locations- for (String guidSubdir : guidSubdirPaths) {- if ((subDir = new File(path, guidSubdir)).isDirectory()) {- predefinedPaths.add(subDir);- }- }- }- }- }-- //==============================================================================================- /**- * TODO 20190403: Need to consider documentation at- * <a href="https://docs.microsoft.com/en-us/windows/desktop/debug/symbol-paths">- * Symbol Paths</a>.- * <P>- * Says order:- * <li>C:\MySymbols- * <li>C:\MySymbols\ext, where ext is extension of binary (e.g., dll, exe, sys)- * <li>C:\MySymbols\symbols\ext- * <P>- */- private static void getSymbolPaths(File symbolsDir, Set<String> guidSubdirPaths,- Set<File> predefinedPaths) {- // TODO: Need to provide better control of symbol directory preference- // instead of only using default- if (symbolsDir == null || !symbolsDir.isDirectory()) {- return;- }- predefinedPaths.add(symbolsDir);-- // Check alternate locations- String specialPdbPath = symbolsDir.getAbsolutePath();-- for (String guidSubdir : guidSubdirPaths) {- File testDir = new File(specialPdbPath + guidSubdir);- if (testDir.isDirectory()) {- predefinedPaths.add(testDir);- }- }- }-- //==============================================================================================- private static void getPathsFromAttributes(PdbProgramAttributes pdbAttributes,- boolean includePeSpecifiedPdbPath, Set<File> predefinedPaths) {- if (pdbAttributes != null) {-- String currentPath = pdbAttributes.getPdbFile();-- if (currentPath != null && includePeSpecifiedPdbPath) {- File parentDir = new File(currentPath).getParentFile();-- if (parentDir != null && parentDir.exists()) {- predefinedPaths.add(parentDir);- }- }-- currentPath = pdbAttributes.getExecutablePath();-- if (currentPath != null && !currentPath.equals("unknown")) {- File parentDir = new File(currentPath).getParentFile();-- if (parentDir != null && parentDir.exists()) {- predefinedPaths.add(parentDir);- }- }- }- }-- //==============================================================================================- /**- * Returns the first PDB-type file found. Assumes list of potentialPdbDirs is in the order- * in which the directories should be searched.- *- * @param potentialPdbDirs List<String> of paths- * @param potentialPdbNames List<String> of file names- * @return Ordered List<String> of potential filenames- */- private static List<String> checkForPDBorXML(Set<File> potentialPdbDirs,- List<String> potentialPdbNames) {-- List<String> orderedListOfExistingFileNames = new ArrayList<>();- File file;-- for (File pdbPath : potentialPdbDirs) {-- for (String filename : potentialPdbNames) {-- file = new File(pdbPath, filename);-- // Note: isFile() also checks for existence- if (file.isFile()) {- orderedListOfExistingFileNames.add(file.getAbsolutePath());- }- }- }-- return orderedListOfExistingFileNames;- }-- //==============================================================================================- public static boolean verifyPdbSignature(PdbProgramAttributes programAttributes,- PdbIdentifiers identifiers) throws PdbException {-- String attributesGuidString = programAttributes.getPdbGuid();- if (attributesGuidString == null) {- // TODO: note that PdbProgramAttributes does not seem to be getting this value from- // the program--getting it as a default value (e.g., from options or elsewhere).- // Should see if it is available in the program somewhere?- String attributesSignatureString = programAttributes.getPdbSignature();- if (attributesSignatureString == null) {- throw new PdbException("No PDB GUID or Signature in file.\n Cannot match.");- }- int attributesSignature = Integer.parseInt(attributesSignatureString);- if (attributesSignature != identifiers.getSignature()) {- return false; // no match- }- }- else {- GUID pdbGuid = identifiers.getGuid();- if (!attributesGuidString.equals(pdbGuid.toString())) {- return false; // no match- }- }-- int attributesAge = Integer.parseInt(programAttributes.getPdbAge(), 16);- if (attributesAge != identifiers.getAge()) {- return false;- }-- return true;- }-- public static File getDefaultPdbSymbolsDir() {- String pdbStorageLocation = Preferences.getProperty(PDB_SYMBOLS_DIR_PREFERENCE, null, true);- File defaultSymbolsDir = DEFAULT_SYMBOLS_DIR;- if (pdbStorageLocation != null) {- File pdbDirectory = new File(pdbStorageLocation);- if (pdbDirectory.isDirectory()) {- defaultSymbolsDir = pdbDirectory;- }- }- return defaultSymbolsDir;- }-- public static void setDefaultPdbSymbolsDir(File symbolsDir) {- Preferences.setProperty(PDB_SYMBOLS_DIR_PREFERENCE, symbolsDir.getAbsolutePath());- Preferences.store();- }--}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/PdbProgramAttributes.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/PdbProgramAttributes.javaindex f8f7502f00..691a9b7133 100644--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/PdbProgramAttributes.java+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/PdbProgramAttributes.java@@ -15,10 +15,6 @@*/package ghidra.app.util.pdb;-import java.util.*;--import org.apache.commons.lang3.StringUtils;-import ghidra.app.util.bin.format.pdb.PdbParserConstants;import ghidra.framework.options.Options;import ghidra.program.model.listing.Program;@@ -32,35 +28,39 @@ public class PdbProgramAttributes {private String pdbGuid;private String pdbSignature;- // A formatted string that combines 'pdbAge' and one of ['pdbGuid' or 'pdbSignature'].- // This string is used to uniquely identify the PDB version and is used here:- // - as part of the URL when retrieving a PDB from the Symbol Server- // - as a directory name when the PDB is stored locally- private String guidAgeCombo;-private String pdbFile;private String pdbVersion;private boolean pdbLoaded;private boolean programAnalyzed;private String executablePath;- private List<String> potentialPdbFilenames = null;-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);- pdbVersion = propList.getString(PdbParserConstants.PDB_VERSION, (String) null);+ pdbGuid = propList.contains(PdbParserConstants.PDB_GUID)+ ? propList.getString(PdbParserConstants.PDB_GUID, null)+ : null;+ pdbAge = propList.contains(PdbParserConstants.PDB_AGE)+ ? propList.getString(PdbParserConstants.PDB_AGE, null)+ : null;+ pdbLoaded = propList.contains(PdbParserConstants.PDB_LOADED)+ ? propList.getBoolean(PdbParserConstants.PDB_LOADED, false)+ : false;+ programAnalyzed = propList.contains(Program.ANALYZED)+ ? propList.getBoolean(Program.ANALYZED, false)+ : false;+ pdbSignature = propList.contains(PdbParserConstants.PDB_SIGNATURE)+ ? propList.getString(PdbParserConstants.PDB_SIGNATURE, null)+ : null;+ pdbFile = propList.contains(PdbParserConstants.PDB_FILE)+ ? propList.getString(PdbParserConstants.PDB_FILE, null)+ : null;+ pdbVersion = propList.contains(PdbParserConstants.PDB_VERSION)+ ? propList.getString(PdbParserConstants.PDB_VERSION, null)+ : null;executablePath = program.getExecutablePath();-- createGuidAgeString();}// Used for testing purposes to make a "dummy" object@@ -75,7 +75,6 @@ public class PdbProgramAttributes {pdbVersion = "RSDS"; // TODO: possibly receive this as argument.executablePath = execPath;- createGuidAgeString();}/**@@ -86,6 +85,20 @@ public class PdbProgramAttributes {return pdbAge;}+ /**+ * Returns the decoded integer value of the age string.+ *+ * @return int value of age string, or 0 if invalid or undefined+ */+ public int getPdbAgeAsInt() {+ try {+ return Integer.parseInt(pdbAge, 16);+ }+ catch (NumberFormatException e) {+ return 0;+ }+ }+public String getPdbGuid() {return pdbGuid;}@@ -94,6 +107,20 @@ public class PdbProgramAttributes {return pdbSignature;}+ /**+ * Returns the decoded integer value of the signature string.+ *+ * @return int value of signature string, or 0 if invalid or undefined+ */+ public int getPdbSignatureAsInt() {+ try {+ return Integer.parseUnsignedInt(pdbSignature, 16);+ }+ catch (NumberFormatException e) {+ return 0;+ }+ }+public String getPdbFile() {return pdbFile;}@@ -114,104 +141,5 @@ public class PdbProgramAttributes {return programAnalyzed;}- /**- * Get a potential list of PDB filenames using the 'pdbFile' and 'executablePath' attributes.- *- * @return list of unique, potential PDB filenames- */- public List<String> getPotentialPdbFilenames() {- if (potentialPdbFilenames == null) {-- // Want to preserve add order while only keeping unique entries- Set<String> set = new LinkedHashSet<>();-- if (!StringUtils.isBlank(pdbFile)) {- set.add(getFilename(pdbFile).toLowerCase());- set.add(getFilename(pdbFile));- }- // getExecutablePath can return "unknown"- if (!executablePath.equals("unknown")) {- String executableFilename = getFilename(executablePath);- set.add(- getBinaryBasename(executableFilename).toLowerCase() + ".pdb");- }-- potentialPdbFilenames = new ArrayList<>(set);- }-- return potentialPdbFilenames;- }-- public String getGuidAgeCombo() {- return guidAgeCombo;- }-- private String getBinaryBasename(String filename) {- String binaryName = filename;- int dotpos = binaryName.lastIndexOf('.');-- // Checking for > 0 because it's not useful if the last '.' is at index 0- if (dotpos > 0) {- binaryName = binaryName.substring(0, dotpos);- }-- return binaryName;- }-- /**- * Reformat GUID or signature and add age to create the guidAgeString. This- * string is used as part of the path that stores the PDB file.- *- * When GUID (preferred) is not available, signature is used in its place.- */- private void createGuidAgeString() {-- if ((StringUtils.isBlank(pdbGuid) && StringUtils.isBlank(pdbSignature)) ||- StringUtils.isBlank(pdbAge)) {- guidAgeCombo = null;- return;- }-- try {- int pdbAgeDecimal = Integer.parseInt(pdbAge, 16);- guidAgeCombo = (pdbGuid == null) ? pdbSignature : pdbGuid;- guidAgeCombo = guidAgeCombo.replaceAll("-", "");- guidAgeCombo = guidAgeCombo.toUpperCase();- guidAgeCombo += pdbAgeDecimal;- }- catch (NumberFormatException e) {- return;- }- }-- /**- * Extracts the actual file name from a full path.- *- * Note that Java methods such as File.getName() and Path.getFileName() won't work here, because- * they are OS-specific. If we are on a Linux machine and calling getName("C:\\Windows\\temp.exe"),- * the Java method will return "C:\\Windows\\temp.exe" and not the expected "temp.exe".- *- * This method also accounts for non-standard paths where both types of slashes are used.- *- * @param fullPath from which to extract the filename- * @return the name of the file specified by the fullPath- */- private String getFilename(String fullPath) {- // Remove any trailing slashes- String editedPath = fullPath;- editedPath = editedPath.replaceAll("[\\/]$", "");-- int lastIndexForwardSlash = editedPath.lastIndexOf('/');- int lastIndexBackSlash = editedPath.lastIndexOf('\\');-- if (lastIndexForwardSlash == -1 && lastIndexBackSlash == -1) {- return editedPath;- }-- int indexToUse = (lastIndexForwardSlash > lastIndexBackSlash) ? lastIndexForwardSlash- : lastIndexBackSlash;-- return editedPath.substring(indexToUse + 1);- }}diff --git a/Ghidra/Features/PDB/src/main/java/pdb/PdbPlugin.java b/Ghidra/Features/PDB/src/main/java/pdb/PdbPlugin.javaindex 4180b875b2..4be44f0c46 100644--- a/Ghidra/Features/PDB/src/main/java/pdb/PdbPlugin.java+++ b/Ghidra/Features/PDB/src/main/java/pdb/PdbPlugin.java@@ -191,7 +191,7 @@ public class PdbPlugin extends Plugin {public static File findPdb(Program program, Set<FindOption> findOptions, TaskMonitor monitor) {try {- SymbolFileInfo symbolFileInfo = SymbolFileInfo.fromMetadata(program.getMetadata());+ SymbolFileInfo symbolFileInfo = SymbolFileInfo.fromProgramInfo(program);if (symbolFileInfo == null) {return null;}diff --git a/Ghidra/Features/PDB/src/main/java/pdb/symbolserver/AbstractSymbolServer.java b/Ghidra/Features/PDB/src/main/java/pdb/symbolserver/AbstractSymbolServer.javaindex bb05641817..5ece95e06d 100644--- a/Ghidra/Features/PDB/src/main/java/pdb/symbolserver/AbstractSymbolServer.java+++ b/Ghidra/Features/PDB/src/main/java/pdb/symbolserver/AbstractSymbolServer.java@@ -15,12 +15,12 @@*/package pdb.symbolserver;+import java.io.IOException;import java.util.List;import java.util.Set;-import java.io.IOException;-import org.apache.commons.io.FilenameUtils;+import org.apache.commons.lang3.StringUtils;import ghidra.util.Msg;import ghidra.util.task.TaskMonitor;@@ -37,6 +37,11 @@ public abstract class AbstractSymbolServer implements SymbolServer {@Overridepublic List<SymbolFileLocation> find(SymbolFileInfo symbolFileInfo, Set<FindOption> options,TaskMonitor monitor) {+ if (StringUtils.isBlank(symbolFileInfo.getName())) {+ Msg.warn(this, "Unable to search for empty filename: " + symbolFileInfo);+ return List.of();+ }+initStorageLevelIfNeeded(monitor);try {diff --git a/Ghidra/Features/PDB/src/main/java/pdb/symbolserver/HttpSymbolServer.java b/Ghidra/Features/PDB/src/main/java/pdb/symbolserver/HttpSymbolServer.javaindex 3f16813217..1dfec9e067 100644--- a/Ghidra/Features/PDB/src/main/java/pdb/symbolserver/HttpSymbolServer.java+++ b/Ghidra/Features/PDB/src/main/java/pdb/symbolserver/HttpSymbolServer.java@@ -41,7 +41,7 @@ public class HttpSymbolServer extends AbstractSymbolServer {private static final String GHIDRA_USER_AGENT = "Ghidra_HttpSymbolServer_client";private static final int HTTP_STATUS_OK = HttpURLConnection.HTTP_OK;private static final int HTTP_REQUEST_TIMEOUT_MS = 10 * 1000; // 10 seconds-+/*** Predicate that tests if the location string is an instance of a HttpSymbolServer location.*@@ -51,7 +51,7 @@ public class HttpSymbolServer extends AbstractSymbolServer {public static boolean isHttpSymbolServerLocation(String locationString) {return locationString.startsWith("http://") || locationString.startsWith("https://");}-+private final URI serverURI;/**@@ -82,9 +82,14 @@ public class HttpSymbolServer extends AbstractSymbolServer {return exists("", monitor) || exists(PINGME_FILENAME, monitor);}- private HttpRequest.Builder request(String str) {- return HttpRequest.newBuilder(serverURI.resolve(str))- .setHeader("User-Agent", GHIDRA_USER_AGENT);+ private HttpRequest.Builder request(String str) throws IOException {+ try {+ return HttpRequest.newBuilder(serverURI.resolve(str))+ .setHeader("User-Agent", GHIDRA_USER_AGENT);+ }+ catch (IllegalArgumentException e) {+ throw new IOException(e);+ }}@Overridediff --git a/Ghidra/Features/PDB/src/main/java/pdb/symbolserver/SymbolFileInfo.java b/Ghidra/Features/PDB/src/main/java/pdb/symbolserver/SymbolFileInfo.javaindex 4f970ebb69..954b1273ea 100644--- a/Ghidra/Features/PDB/src/main/java/pdb/symbolserver/SymbolFileInfo.java+++ b/Ghidra/Features/PDB/src/main/java/pdb/symbolserver/SymbolFileInfo.java@@ -15,16 +15,16 @@*/package pdb.symbolserver;-import java.util.Map;-import java.util.Objects;-import java.io.File;+import java.util.Objects;import org.apache.commons.io.FilenameUtils;+import org.apache.commons.lang3.StringUtils;-import ghidra.app.util.bin.format.pdb.PdbParserConstants;import ghidra.app.util.bin.format.pdb2.pdbreader.PdbIdentifiers;import ghidra.app.util.datatype.microsoft.GUID;+import ghidra.app.util.pdb.PdbProgramAttributes;+import ghidra.program.model.listing.Program;import ghidra.util.task.TaskMonitor;import pdb.PdbUtils;@@ -37,33 +37,32 @@ public class SymbolFileInfo {private static final int MIN_SIG_HEX_STR_LEN = 8;private static final int GUID_HEX_STR_LEN = 32;- /**- * Create a SymbolFileInfo instance that represents an unknown / bad- * file.- *- * @param path path string to use- * @return new SymbolFileInfo with a PdbIdentifier with bogus / default values- */- public static SymbolFileInfo unknown(String path) {- return new SymbolFileInfo(path, new PdbIdentifiers(0, 0, 0, null, null));- }-/*** Create a SymbolFileInfo instance from the metadata found in a program- *- * @param metadata Map of String-to-String values taken from a program+ * @param program where the Pdb metadata is stored* @return new SymbolFileInfo instance, or null if no Pdb info found*/- public static SymbolFileInfo fromMetadata(Map<String, String> metadata) {+ public static SymbolFileInfo fromProgramInfo(Program program) {try {- int sig =- Integer.parseUnsignedInt(- metadata.getOrDefault(PdbParserConstants.PDB_SIGNATURE, "0"), 16);- String guidString = metadata.getOrDefault(PdbParserConstants.PDB_GUID, "");- GUID guid = (guidString != null && !guidString.isBlank()) ? new GUID(guidString) : null;- int age = Integer- .parseUnsignedInt(metadata.getOrDefault(PdbParserConstants.PDB_AGE, "0"), 16);- String path = metadata.getOrDefault(PdbParserConstants.PDB_FILE, "<unknown>");+ PdbProgramAttributes pdbAttrs = new PdbProgramAttributes(program);+ int sig = pdbAttrs.getPdbSignatureAsInt();+ String guidString = pdbAttrs.getPdbGuid();+ GUID guid = null;+ if (!StringUtils.isBlank(guidString)) {+ try {+ guid = new GUID(guidString);+ }+ catch (IllegalArgumentException e) {+ // ignore, fallthru with guid==null+ }+ }+ int age = pdbAttrs.getPdbAgeAsInt();+ String path = pdbAttrs.getPdbFile();+ path = !StringUtils.isBlank(path) ? path : "";++ if (sig == 0 && guid == null && path.isEmpty()) {+ return null;+ }PdbIdentifiers pdbIdentifiers = new PdbIdentifiers(0, sig, age, guid, null);@@ -119,6 +118,9 @@ public class SymbolFileInfo {* or null if bad GUID / signature id string*/public static SymbolFileInfo fromValues(String path, String uid, int age) {+ if (StringUtils.isBlank(path)) {+ return null;+ }try {GUID guid = new GUID(uid);return new SymbolFileInfo(path, new PdbIdentifiers(0, 0, age, guid, null));@@ -139,11 +141,13 @@ public class SymbolFileInfo {/*** Create a new instance using the specified path and {@link PdbIdentifiers}.*- * @param path String pdb path filename+ * @param path String pdb path filename, can not be null* @param pdbIdent {@link PdbIdentifiers}* @return new {@link SymbolFileInfo} instance made of specified path and ident info+ * @throws NullPointerException if path is null*/public static SymbolFileInfo fromPdbIdentifiers(String path, PdbIdentifiers pdbIdent) {+ Objects.requireNonNull(path);return new SymbolFileInfo(path, pdbIdent);}@@ -167,7 +171,7 @@ public class SymbolFileInfo {private final String pdbPath;private SymbolFileInfo(String pdbPath, PdbIdentifiers pdbIdentifiers) {- this.pdbPath = pdbPath;+ this.pdbPath = Objects.requireNonNull(pdbPath);this.pdbIdentifiers = pdbIdentifiers;}@@ -183,7 +187,7 @@ public class SymbolFileInfo {/*** The name of the pdb file, derived from the {@link #getPath() path} value.*- * @return String name of the pdb file+ * @return String name of the pdb file, never null, maybe blank*/public String getName() {return FilenameUtils.getName(pdbPath);@@ -194,7 +198,7 @@ public class SymbolFileInfo {* original binary's debug data. Typically, this is just a plain name string without any* path info.*- * @return original pdb path string recovered from binary's debug data+ * @return original pdb path string recovered from binary's debug data, never null, maybe blank*/public String getPath() {return pdbPath;@@ -213,6 +217,22 @@ public class SymbolFileInfo {}+ /**+ * A string that represents the unique fingerprint of a Pdb file, or empty "" if+ * invalid. Does not include the age.+ *+ * @return either GUID str or signature hexstring or "" if neither+ */+ public String getUniqifierString() {+ if (pdbIdentifiers.getGuid() != null) {+ return pdbIdentifiers.getGuid().toString().replace("-", "").toUpperCase();+ }+ if (pdbIdentifiers.getSignature() != 0) {+ return String.format("%08X", pdbIdentifiers.getSignature());+ }+ return "";+ }+/*** Returns a string that is a combination of the GUID/ID and the age, in a format* used by symbol servers to create subdirectories in their directory structure.diff --git a/Ghidra/Features/PDB/src/main/java/pdb/symbolserver/SymbolServerService.java b/Ghidra/Features/PDB/src/main/java/pdb/symbolserver/SymbolServerService.javaindex 75cbd02c4a..ce91f73c2d 100644--- a/Ghidra/Features/PDB/src/main/java/pdb/symbolserver/SymbolServerService.java+++ b/Ghidra/Features/PDB/src/main/java/pdb/symbolserver/SymbolServerService.java@@ -15,13 +15,13 @@*/package pdb.symbolserver;-import java.util.*;-import java.util.stream.Collectors;-import java.io.File;import java.io.IOException;+import java.util.*;+import java.util.stream.Collectors;import org.apache.commons.io.FilenameUtils;+import org.apache.commons.lang3.StringUtils;import ghidra.util.Msg;import ghidra.util.exception.CancelledException;@@ -137,6 +137,12 @@ public class SymbolServerService {public List<SymbolFileLocation> find(SymbolFileInfo symbolFileInfo,Set<FindOption> findOptions, TaskMonitor monitor) throws CancelledException {+ if (StringUtils.isBlank(symbolFileInfo.getName())) {+ Msg.warn(this,+ logPrefix() + ": Unable to search for empty filename: " + symbolFileInfo);+ return List.of();+ }+List<SymbolFileLocation> allFindResults = new ArrayList<>();Set<String> uniqueSymbolFilePaths = new HashSet<>();diff --git a/Ghidra/Features/PDB/src/main/java/pdb/symbolserver/ui/LoadPdbDialog.java b/Ghidra/Features/PDB/src/main/java/pdb/symbolserver/ui/LoadPdbDialog.javaindex 98e680a1c4..92db3e6e08 100644--- a/Ghidra/Features/PDB/src/main/java/pdb/symbolserver/ui/LoadPdbDialog.java+++ b/Ghidra/Features/PDB/src/main/java/pdb/symbolserver/ui/LoadPdbDialog.java@@ -20,12 +20,13 @@ import java.awt.event.ActionListener;import java.awt.event.MouseEvent;import java.io.File;import java.io.IOException;-import java.util.ArrayList;+import java.util.*;import java.util.List;-import java.util.Set;import java.util.function.Supplier;import javax.swing.*;+import javax.swing.event.DocumentEvent;+import javax.swing.event.DocumentListener;import docking.DialogComponentProvider;import docking.DockingWindowManager;@@ -41,6 +42,7 @@ import docking.widgets.label.GLabel;import docking.widgets.textfield.HexOrDecimalInput;import docking.widgets.textfield.HintTextField;import ghidra.app.util.bin.format.pdb.PdbParser;+import ghidra.app.util.bin.format.pdb2.pdbreader.PdbIdentifiers;import ghidra.app.util.pdb.pdbapplicator.PdbApplicatorControl;import ghidra.framework.preferences.Preferences;import ghidra.program.model.listing.Program;@@ -69,6 +71,8 @@ public class LoadPdbDialog extends DialogComponentProvider {public static final GhidraFileFilter PDB_FILES_FILTER =ExtensionFileFilter.forExtensions("Microsoft Program Databases", "pdb", "pd_", "pdb.xml");+ private static final SymbolFileInfo UNKNOWN_SYMFILE = makeUnknownSymbolFileInstance("");+public static class LoadPdbResults {public File pdbFile;public PdbApplicatorControl control;@@ -103,7 +107,7 @@ public class LoadPdbDialog extends DialogComponentProvider {private SymbolServerService symbolServerService;private SymbolServerInstanceCreatorContext symbolServerInstanceCreatorContext;- private SymbolFileInfo programSymbolFileInfo;+ private SymbolFileInfo programSymbolFileInfo; // never nullprivate List<Supplier<StatusText>> statusTextSuppliers = new ArrayList<>();private Set<FindOption> lastSearchOptions;@@ -151,10 +155,8 @@ public class LoadPdbDialog extends DialogComponentProvider {setRememberSize(false);this.program = program;- this.programSymbolFileInfo = SymbolFileInfo.fromMetadata(program.getMetadata());- if (programSymbolFileInfo == null) {- programSymbolFileInfo = SymbolFileInfo.unknown("missing");- }+ this.programSymbolFileInfo =+ Objects.requireNonNullElse(SymbolFileInfo.fromProgramInfo(program), UNKNOWN_SYMFILE);updateSymbolServerServiceInstanceFromPreferences();build();}@@ -168,13 +170,11 @@ public class LoadPdbDialog extends DialogComponentProvider {@Overrideprotected void dialogShown() {- pdbPathTextField.setText(programSymbolFileInfo.getPath());- pdbUniqueIdTextField.setText(programSymbolFileInfo.getUniqueName());- pdbAgeTextField.setValue(programSymbolFileInfo.getIdentifiers().getAge());- programNameTextField.setText(program.getName());cancelButton.requestFocusInWindow();- searchForPdbs(false);+ if ( getCurrentSymbolFileInfo() != null ) {+ searchForPdbs(false);+ }}@Override@@ -262,10 +262,11 @@ public class LoadPdbDialog extends DialogComponentProvider {private void updateButtonEnablement() {boolean hasLocation = selectedSymbolFile != null;boolean hasGoodService = symbolServerService.isValid();+ boolean isSearchable = getCurrentSymbolFileInfo() != null;loadPdbButton.setEnabled(hasLocation);configButton.setIcon(hasGoodService ? null : MATCH_BAD_ICON);configButton.setToolTipText(hasGoodService ? null : "Missing configuration");- symbolFilePanel.setEnablement(hasGoodService);+ symbolFilePanel.setEnablement(hasGoodService, isSearchable);}private SymbolFileInfo getCurrentSymbolFileInfo() {@@ -284,8 +285,7 @@ public class LoadPdbDialog extends DialogComponentProvider {}SymbolFileInfo symbolFileInfo = getCurrentSymbolFileInfo();if (symbolFileInfo == null) {- Msg.showWarn(this, null, "Bad PDB GUID/ID",- "Invalid PDB GUID / UID value: " + pdbUniqueIdTextField.getText());+ Msg.showWarn(this, null, "Bad PDB Values", "Invalid PDB Path / GUID / UID value");return;}Set<FindOption> findOptions = symbolFilePanel.getFindOptions();@@ -365,11 +365,22 @@ public class LoadPdbDialog extends DialogComponentProvider {private JPanel buildProgramPdbPanel() {+ DocumentListener docListener = new DocumentListener() {+ //@formatter:off+ @Override public void removeUpdate(DocumentEvent e) { updateButtonEnablement(); }+ @Override public void insertUpdate(DocumentEvent e) { updateButtonEnablement(); }+ @Override public void changedUpdate(DocumentEvent e) { updateButtonEnablement(); }+ //@formatter:on+ };+programNameTextField = new BetterNonEditableTextField(20);programNameTextField.setEditable(false);+ programNameTextField.setText(program.getName());- pdbPathTextField = new BetterNonEditableTextField(20);+ pdbPathTextField = new BetterNonEditableTextField(20, "Missing", Color.red);pdbPathTextField.setEditable(false);+ pdbPathTextField.setText(programSymbolFileInfo.getPath());+ pdbPathTextField.getDocument().addDocumentListener(docListener);overridePdbPathCheckBox = new GCheckBox();overridePdbPathCheckBox.setVisible(false);@@ -388,13 +399,15 @@ public class LoadPdbDialog extends DialogComponentProvider {new HelpLocation(PdbPlugin.PDB_PLUGIN_HELP_TOPIC,SymbolFilePanel.SEARCH_OPTIONS_HELP_ANCHOR));- pdbUniqueIdTextField = new BetterNonEditableTextField(36);+ pdbUniqueIdTextField = new BetterNonEditableTextField(36, "Missing", Color.red);pdbUniqueIdTextField.setEditable(false);+ pdbUniqueIdTextField.setText(programSymbolFileInfo.getUniqifierString());pdbUniqueIdTextField.setToolTipText("<html>PDB GUID - 32 hexadecimal characters:<br>" +" <b>'012345678-0123-0123-0123-0123456789ABC'</b> (with or without dashes) or<br>" +"PDB Signature ID - 8 hexadecimal characters:<br>" +" <b>'11223344'</b>");+ pdbUniqueIdTextField.getDocument().addDocumentListener(docListener);overridePdbUniqueIdCheckBox = new GCheckBox();overridePdbUniqueIdCheckBox.setVisible(false);@@ -405,7 +418,7 @@ public class LoadPdbDialog extends DialogComponentProvider {pdbUniqueIdTextField.requestFocusInWindow();}else {- pdbUniqueIdTextField.setText(programSymbolFileInfo.getUniqueName());+ pdbUniqueIdTextField.setText(programSymbolFileInfo.getUniqifierString());}});DockingWindowManager.getHelpService()@@ -416,7 +429,9 @@ public class LoadPdbDialog extends DialogComponentProvider {pdbAgeTextField = new BetterNonEditableHexTextField(8);pdbAgeTextField.setAllowNegative(false);pdbAgeTextField.setHexMode();+ pdbAgeTextField.setValue(programSymbolFileInfo.getIdentifiers().getAge());pdbAgeTextField.setEditable(false);+ pdbAgeTextField.getDocument().addDocumentListener(docListener);overridePdbAgeCheckBox = new GCheckBox();overridePdbAgeCheckBox.setVisible(false);@@ -684,7 +699,7 @@ public class LoadPdbDialog extends DialogComponentProvider {executeMonitoredRunnable("Get PDB Info", true, true, 0, monitor -> {SymbolFileInfo pdbSymbolFileInfo = SymbolFileInfo.fromFile(file, monitor);if (pdbSymbolFileInfo == null) {- pdbSymbolFileInfo = SymbolFileInfo.unknown(file.getName());+ pdbSymbolFileInfo = makeUnknownSymbolFileInstance(file.getName());}SymbolFileLocation symbolFileLocation =SameDirSymbolStore.createManuallySelectedSymbolFileLocation(file,@@ -819,6 +834,10 @@ public class LoadPdbDialog extends DialogComponentProvider {executeProgressTask(task, delay);}+ private static SymbolFileInfo makeUnknownSymbolFileInstance(String path) {+ return SymbolFileInfo.fromPdbIdentifiers(path, new PdbIdentifiers(0, 0, 0, null, null));+ }+//-----------------------------------------------------------------------------------static class StatusText {@@ -852,9 +871,17 @@ public class LoadPdbDialog extends DialogComponentProvider {* text fields to be the same color as the parent container's background.*/static class BetterNonEditableTextField extends JTextField {+ private String hint;+ private Color hintColor;BetterNonEditableTextField(int columns) {+ this(columns, null, null);+ }++ public BetterNonEditableTextField(int columns, String hint, Color hintColor) {super(columns);+ this.hint = hint;+ this.hintColor = hintColor;}@Override@@ -869,6 +896,28 @@ public class LoadPdbDialog extends DialogComponentProvider {}return super.getBackground();}++ /**+ * Overridden to paint the hint text over the field when it's empty+ */+ @Override+ public void paintComponent(Graphics g) {+ super.paintComponent(g);++ if (!getText().isEmpty() || hint == null) {+ return;+ }++ Graphics2D g2 = (Graphics2D) g;+ g2.setColor(hintColor != null ? hintColor : Color.LIGHT_GRAY);+ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);++ Dimension size = getSize();+ Insets insets = getInsets();+ int x = 10; // offset+ int y = size.height - insets.bottom - 1;+ g2.drawString(hint, x, y);+ }}static class BetterNonEditableHexTextField extends HexOrDecimalInput {diff --git a/Ghidra/Features/PDB/src/main/java/pdb/symbolserver/ui/SymbolFilePanel.java b/Ghidra/Features/PDB/src/main/java/pdb/symbolserver/ui/SymbolFilePanel.javaindex dfca92f5d0..c060524041 100644--- a/Ghidra/Features/PDB/src/main/java/pdb/symbolserver/ui/SymbolFilePanel.java+++ b/Ghidra/Features/PDB/src/main/java/pdb/symbolserver/ui/SymbolFilePanel.java@@ -56,7 +56,7 @@ class SymbolFilePanel extends JPanel {super(new BorderLayout());build();- setEnablement(false);+ setEnablement(false, false);searchLocalButton.addActionListener(e -> searchButtonsCallback.searchForPdbs(false));searchAllButton.addActionListener(e -> searchButtonsCallback.searchForPdbs(true));}@@ -85,9 +85,9 @@ class SymbolFilePanel extends JPanel {ignorePdbUid.setSelected(findOptions.contains(FindOption.ANY_ID));}- void setEnablement(boolean hasSymbolServerService) {- searchLocalButton.setEnabled(hasSymbolServerService);- searchAllButton.setEnabled(hasSymbolServerService);+ void setEnablement(boolean hasSymbolServerService, boolean isSearchable) {+ searchLocalButton.setEnabled(hasSymbolServerService && isSearchable);+ searchAllButton.setEnabled(hasSymbolServerService && isSearchable);if (welcomePanel != null && hasSymbolServerService) {remove(welcomePanel);