Java Code Examples for docking.widgets.filechooser.GhidraFileChooserMode

The following examples show how to use docking.widgets.filechooser.GhidraFileChooserMode. These examples are extracted from open source projects. 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 Project: ghidra   Source File: PathnameTablePanelTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAddButton() throws Exception {
	File temp = createTempFileForTest();

	Preferences.setProperty(Preferences.LAST_IMPORT_DIRECTORY, temp.getParent());
	panel.setFileChooserProperties("Select Source Files", Preferences.LAST_IMPORT_DIRECTORY,
		GhidraFileChooserMode.FILES_AND_DIRECTORIES, true,
		new ExtensionFileFilter(new String[] { "h" }, "C Header Files"));

	JButton button = findButtonByIcon(panel, ResourceManager.loadImage("images/Plus.png"));
	assertNotNull(button);
	pressButton(button, false);

	waitForPostedSwingRunnables();
	selectFromFileChooser();

	assertEquals(6, table.getRowCount());

	String filename = (String) table.getModel().getValueAt(5, 0);
	assertTrue(filename.endsWith("fred.h"));
}
 
Example 2
Source Project: ghidra   Source File: PathnameTablePanelTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAddToTop() throws Exception {

	panel.setAddToTop(true);
	File temp = createTempFileForTest();
	Preferences.setProperty(Preferences.LAST_IMPORT_DIRECTORY, temp.getParent());
	panel.setFileChooserProperties("Select Source Files", Preferences.LAST_IMPORT_DIRECTORY,
		GhidraFileChooserMode.FILES_AND_DIRECTORIES, true,
		new ExtensionFileFilter(new String[] { "h" }, "C Header Files"));

	JButton button = findButtonByIcon(panel, ResourceManager.loadImage("images/Plus.png"));
	assertNotNull(button);
	pressButton(button, false);

	waitForPostedSwingRunnables();
	selectFromFileChooser();

	assertEquals(6, table.getRowCount());

	String filename = (String) table.getModel().getValueAt(0, 0);
	assertTrue(filename.endsWith("fred.h"));

}
 
Example 3
Source Project: ghidra   Source File: SaveImageAction.java    License: Apache License 2.0 6 votes vote down vote up
private static File getExportFile() {

		GhidraFileChooser chooser = new GhidraFileChooser(null);
		chooser.setTitle("Export Image As...");
		chooser.setApproveButtonText("Save As");
		chooser.setFileSelectionMode(GhidraFileChooserMode.FILES_ONLY);
		chooser.setMultiSelectionEnabled(false);

		File selected = chooser.getSelectedFile(true);

		if (chooser.wasCancelled()) {
			return null;
		}

		return selected;

	}
 
Example 4
Source Project: ghidra   Source File: GraphExporterDialog.java    License: Apache License 2.0 6 votes vote down vote up
private void chooseDestinationFile() {
	GhidraFileChooser chooser = new GhidraFileChooser(getComponent());
	chooser.setSelectedFile(getLastExportDirectory());
	chooser.setTitle("Select Output File");
	chooser.setApproveButtonText("Select Output File");
	chooser.setApproveButtonToolTipText("Select File");
	chooser.setFileSelectionMode(GhidraFileChooserMode.FILES_ONLY);

	chooser.setSelectedFileFilter(GhidraFileFilter.ALL);
	GraphExportFormat exporter = getSelectedExporter();
	if (exporter != null) {
		chooser.setFileFilter(
			new ExtensionFileFilter(exporter.getDefaultFileExtension(), exporter.toString()));
	}
	String filePath = filePathTextField.getText().trim();
	File currentFile = filePath.isEmpty() ? null : new File(filePath);
	if (currentFile != null) {
		chooser.setSelectedFile(currentFile);
	}
	File file = chooser.getSelectedFile();
	if (file != null) {
		setLastExportDirectory(file);
		filePathTextField.setText(file.getAbsolutePath());
	}
}
 
Example 5
Source Project: ghidra   Source File: ExporterDialog.java    License: Apache License 2.0 6 votes vote down vote up
private void chooseDestinationFile() {
	GhidraFileChooser chooser = new GhidraFileChooser(getComponent());
	chooser.setSelectedFile(getLastExportDirectory());
	chooser.setTitle("Select Output File");
	chooser.setApproveButtonText("Select Output File");
	chooser.setApproveButtonToolTipText("Select File");
	chooser.setFileSelectionMode(GhidraFileChooserMode.FILES_ONLY);

	chooser.setSelectedFileFilter(GhidraFileFilter.ALL);
	Exporter exporter = getSelectedExporter();
	if (exporter != null && exporter.getDefaultFileExtension() != null) {
		chooser.setFileFilter(
			new ExtensionFileFilter(exporter.getDefaultFileExtension(), exporter.getName()));
	}
	String filePath = filePathTextField.getText().trim();
	File currentFile = filePath.isEmpty() ? null : new File(filePath);
	if (currentFile != null) {
		chooser.setSelectedFile(currentFile);
	}
	File file = chooser.getSelectedFile();
	if (file != null) {
		setLastExportDirectory(file);
		filePathTextField.setText(file.getAbsolutePath());
	}
}
 
Example 6
Source Project: ghidra   Source File: FileSystemBrowserPlugin.java    License: Apache License 2.0 6 votes vote down vote up
private void doOpenFileSystem() {
	Component parent = getTool().getActiveWindow();
	openChooser("Select Filesystem Container To Open", "Open", false);
	chooserOpen.setFileSelectionMode(GhidraFileChooserMode.FILES_AND_DIRECTORIES);
	File file = chooserOpen.getSelectedFile();
	if (file == null) {
		return; // cancelled
	}
	else if (!file.exists()) {
		Msg.showInfo(this, parent, "Open File System Failed",
			"The specified file does not exist: " + file.getPath());
		return;
	}

	if (FileUtilities.isEmpty(file)) {
		Msg.showInfo(this, parent, "Empty file",
			"The selected file is 0 bytes long, skipping.");
		return;
	}

	FSRL containerFSRL = FileSystemService.getInstance().getLocalFSRL(file);
	TaskLauncher.launchModal("Open File System", (monitor) -> {
		doOpenFilesystem(containerFSRL, parent, monitor);
	});
}
 
Example 7
Source Project: dragondance   Source File: DragonHelper.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static String askFile(Component parent, String title, String okButtonText) {
	
	GhidraFileChooser gfc = new GhidraFileChooser(parent);
	
	if (!Globals.LastFileDialogPath.isEmpty()) {
		File def = new File(Globals.LastFileDialogPath);
		gfc.setSelectedFile(def);
	}
	
	gfc.setTitle(title);
	gfc.setApproveButtonText(okButtonText);
	gfc.setFileSelectionMode(GhidraFileChooserMode.FILES_ONLY);
	
	File file = gfc.getSelectedFile();
	
	if (file == null) {
		return null;
	}
	
	if (!file.exists())
		return null;
	
	Globals.LastFileDialogPath =  Util.getDirectoryOfFile(file.getAbsolutePath());
	
	if (Globals.LastFileDialogPath == null)
		Globals.LastFileDialogPath = System.getProperty("user.dir");
	
	return file.getAbsolutePath();
}
 
Example 8
Source Project: ghidra   Source File: PathnameTablePanel.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Set properties on the file chooser that is displayed when the "Add" button is pressed.
 * @param title title of the file chooser
 * @param preferenceForLastSelectedDir Preference to use as the current directory in the
 * file chooser
 * @param selectionMode mode defined in GhidraFileFilter, e.g., GhidraFileFilter.FILES_ONLY
 * @param allowMultiSelection true if multiple files can be selected
 * @param filter filter to use; may be null if no filtering is required
 */
public void setFileChooserProperties(String title, String preferenceForLastSelectedDir,
		GhidraFileChooserMode selectionMode, boolean allowMultiSelection,
		GhidraFileFilter filter) {

	this.title = Objects.requireNonNull(title);
	this.preferenceForLastSelectedDir = preferenceForLastSelectedDir;
	this.fileChooserMode = Objects.requireNonNull(selectionMode);
	this.allowMultiFileSelection = allowMultiSelection;
	this.filter = filter;
}
 
Example 9
Source Project: ghidra   Source File: PathManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Set properties on the file chooser that is displayed when the "Add" button is pressed.
 * @param title title of the file chooser
 * @param preferenceForLastSelectedDir Preference to use as the current directory in the
 * file chooser
 * @param selectionMode mode defined in GhidraFileChooser, e.g., GhidraFileChooser.FILES_ONLY
 * @param allowMultiSelection true if multiple files can be selected
 * @param filter filter to use; may be null if no filtering is required
 */
public void setFileChooserProperties(String title, String preferenceForLastSelectedDir,
		GhidraFileChooserMode selectionMode, boolean allowMultiSelection,
		GhidraFileFilter filter) {
	this.title = title;
	this.preferenceForLastSelectedDir = preferenceForLastSelectedDir;
	fileChooserMode = selectionMode;
	allowMultiFileSelection = allowMultiSelection;
	this.filter = filter;
	this.fileChooser = null;
}
 
Example 10
Source Project: ghidra   Source File: PathManager.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isValidPath(Path path) {
	if (fileChooserMode == GhidraFileChooserMode.FILES_ONLY && path.getPath().isDirectory()) {
		return false;
	}
	if (fileChooserMode == GhidraFileChooserMode.DIRECTORIES_ONLY && path.getPath().isFile()) {
		return false;
	}
	return path.exists();
}
 
Example 11
Source Project: ghidra   Source File: FidDebugPlugin.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a raw read-only database file from a packed database.  This file is useful
 * for including in a distribution.
 */
protected void createRawFile() {
	FidFile fidFile = askChoice("Choose destination FidDb",
		"Please choose the destination FidDb for population",
		fidFileManager.getUserAddedFiles(), null);
	if (fidFile == null) {
		return;
	}
	GhidraFileChooser chooser = new GhidraFileChooser(tool.getToolFrame());
	chooser.setTitle("Where do you want to create the read-only installable database?");
	chooser.setFileSelectionMode(GhidraFileChooserMode.DIRECTORIES_ONLY);
	File selectedFile = chooser.getSelectedFile();
	if (selectedFile == null) {
		return;
	}
	File outputFile =
		new File(selectedFile, fidFile.getBaseName() + FidFile.FID_RAW_DATABASE_FILE_EXTENSION);

	try (FidDB fidDB = fidFile.getFidDB(false)) {
		fidDB.saveRawDatabaseFile(outputFile, TaskMonitor.DUMMY);
	}
	catch (VersionException | IOException | CancelledException e) {
		// BTW CancelledException can't happen because we used a DUMMY monitor.
		Msg.showError(this, null, "Error saving read-only installable database", e.getMessage(),
			e);
	}
}
 
Example 12
Source Project: ghidra   Source File: EditArchivePathAction.java    License: Apache License 2.0 5 votes vote down vote up
protected PathManagerDialog() {
	super("Edit Data Type Archive Paths");
	pathManager = new PathManager(false, true);
	pathManager.setFileChooserProperties("Select Archive Directory",
		Preferences.LAST_OPENED_ARCHIVE_DIRECTORY, GhidraFileChooserMode.DIRECTORIES_ONLY,
		false, null);
	setHelpLocation(new HelpLocation("DataTypeManagerPlugin", "Edit_Archive_Paths_Dialog"));

	pathManager.restoreFromPreferences(DataTypeManagerHandler.DATA_TYPE_ARCHIVE_PATH_KEY,
		null, DataTypeManagerHandler.DISABLED_DATA_TYPE_ARCHIVE_PATH_KEY);
	addWorkPanel(pathManager.getComponent());
	addOKButton();
	addCancelButton();
}
 
Example 13
Source Project: ghidra   Source File: LibraryPathsDialog.java    License: Apache License 2.0 5 votes vote down vote up
private JComponent buildWorkPanel() {
	String[] libraryPaths = LibrarySearchPathManager.getLibraryPaths();
	tablePanel = new PathnameTablePanel(libraryPaths, false, true, () -> reset());
	// false=> not editable, true=> add new paths to top of the table

	tablePanel.setFileChooserProperties("Select Directory", "LibrarySearchDirectory",
		GhidraFileChooserMode.DIRECTORIES_ONLY, false, null);

	return tablePanel;
}
 
Example 14
Source Project: ghidra   Source File: PathManagerTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testAddButton() throws Exception {

	PathManagerListener listener = new PathManagerListener() {
		@Override
		public void pathsChanged() {
			wasListenerNotified = true;
		}

		@Override
		public void pathMessage(String message) {
			// don't care
		}
	};

	pathManager.addListener(listener);

	File temp = createTempFileForTest();

	Preferences.setProperty(Preferences.LAST_IMPORT_DIRECTORY, temp.getParent());
	pathManager.setFileChooserProperties("Select Source Files",
		Preferences.LAST_IMPORT_DIRECTORY, GhidraFileChooserMode.FILES_AND_DIRECTORIES, true,
		new ExtensionFileFilter(new String[] { "h" }, "C Header Files"));

	JButton button = findButtonByIcon(pathManager.getComponent(),
		ResourceManager.loadImage("images/Plus.png"));
	assertNotNull(button);
	pressButton(button, false);

	waitForSwing();
	GhidraFileChooser fileChooser = waitForDialogComponent(GhidraFileChooser.class);
	assertNotNull(fileChooser);

	JButton chooseButton = findButtonByText(fileChooser, "OK");
	assertNotNull(chooseButton);

	runSwing(() -> fileChooser.setSelectedFile(new File(temp.getParent(), "fred.h")));
	waitForUpdateOnChooser(fileChooser);

	pressButton(chooseButton);
	assertTrue("The file chooser did not close as expected", !fileChooser.isVisible());
	waitForSwing();

	assertEquals(5, table.getRowCount());

	Path filename = (Path) table.getModel().getValueAt(0, 1);
	assertTrue(filename.getPathAsString().endsWith("fred.h"));

	assertTrue(wasListenerNotified);
	pathManager.removeListener(listener);
}
 
Example 15
Source Project: ghidra   Source File: ExtensionTableProvider.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Creates an action to allow users to manually add new extensions.
 * 
 * @param panel The extensions table panel.
 */
private void createAddAction(ExtensionTablePanel panel) {
	Icon addIcon = ResourceManager.loadImage("images/Plus.png");
	DockingAction addAction = new DockingAction("ExtensionTools", "AddExtension") {

		@Override
		public void actionPerformed(ActionContext context) {

			// Don't let the user attempt to install anything if they don't have write
			// permissions on the installation dir.
			ResourceFile installDir =
				Application.getApplicationLayout().getExtensionInstallationDir();
			if (!installDir.canWrite()) {
				Msg.showError(this, null, "Permissions Error",
					"Cannot install/uninstall extensions: Invalid write permissions on installation directory.\n" +
						"See the \"Ghidra Extension Notes\" section of the Ghidra Installation Guide for more information.");
				return;
			}

			GhidraFileChooser chooser = new GhidraFileChooser(getComponent());
			chooser.setFileSelectionMode(GhidraFileChooserMode.FILES_AND_DIRECTORIES);
			chooser.setTitle("Select extension");
			chooser.addFileFilter(new ExtensionFileFilter());

			List<File> files = chooser.getSelectedFiles();
			for (File file : files) {
				try {
					if (!ExtensionUtils.isExtension(new ResourceFile(file))) {
						Msg.showError(this, null, "Installation Error", "Selected file: [" +
							file.getName() + "] is not a valid Ghidra Extension");
						continue;
					}
				}
				catch (ExtensionException e1) {
					Msg.showError(this, null, "Installation Error", "Error determining if [" +
						file.getName() + "] is a valid Ghidra Extension", e1);
					continue;
				}

				if (!hasCorrectVersion(file)) {
					Msg.showError(this, null, "Installation Error", "Extension version for [" +
						file.getName() + "] is incompatible with Ghidra.");
					continue;
				}

				try {
					if (ExtensionUtils.install(new ResourceFile(file))) {
						panel.refreshTable();
						requireRestart = true;
					}
				}
				catch (Exception e) {
					Msg.error(null, "Problem installing extension [" + file.getName() + "]", e);
				}
			}
		}
	};

	String group = "extensionTools";
	addAction.setMenuBarData(new MenuData(new String[] { "Add Extension" }, addIcon, group));
	addAction.setToolBarData(new ToolBarData(addIcon, group));
	addAction.setHelpLocation(new HelpLocation(GenericHelpTopics.FRONT_END, "ExtensionTools"));
	addAction.setDescription(
		SystemUtilities.isInDevelopmentMode() ? "Add Extension (disabled in development mode)"
				: "Add extension");
	addAction.setEnabled(
		!SystemUtilities.isInDevelopmentMode() && !Application.inSingleJarMode());
	addAction(addAction);
}
 
Example 16
Source Project: ghidra   Source File: PdbSymbolServerPlugin.java    License: Apache License 2.0 4 votes vote down vote up
private File askForLocalStorageLocation() throws CancelledException {

		final GhidraFileChooser fileChooser = new GhidraFileChooser(tool.getActiveWindow());

		// Need to store the variable in an array to allow the final variable to be reassigned.
		// Using an array prevents the compiler from warning about "The final local variable
		// cannot be assigned, since it is defined in an enclosing type."
		final File[] chosenDir = new File[1];

		File testDirectory = null;

		// localDir is not null if we already parsed the _NT_SYMBOL_PATH environment var
		if (localDir != null) {
			testDirectory = localDir;
		}
		else {
			String userHome = System.getProperty("user.home");

			String storedLocalDir =
				Preferences.getProperty(PdbParser.PDB_STORAGE_PROPERTY, userHome, true);

			testDirectory = new File(storedLocalDir);

			if (!testDirectory.exists()) {
				testDirectory = new File(userHome);
			}
		}

		final File storedDirectory = testDirectory;

		Runnable r = () -> {
			while (chosenDir[0] == null && !fileChooser.wasCancelled()) {
				fileChooser.setSelectedFile(storedDirectory);

				fileChooser.setTitle("Select Location to Save Retrieved File");
				fileChooser.setApproveButtonText("OK");
				fileChooser.setFileSelectionMode(GhidraFileChooserMode.DIRECTORIES_ONLY);
				chosenDir[0] = fileChooser.getSelectedFile();

				if (chosenDir[0] != null) {
					if (!chosenDir[0].exists()) {
						Msg.showInfo(getClass(), null, "Directory does not exist",
							"The directory '" + chosenDir[0].getAbsolutePath() +
								"' does not exist. Please create it or choose a valid directory.");
						chosenDir[0] = null;
					}
					else if (chosenDir[0].isFile()) {
						Msg.showInfo(getClass(), null, "Invalid Directory",
							"The location '" + chosenDir[0].getAbsolutePath() +
								"' represents a file, not a directory. Please choose a directory.");
						chosenDir[0] = null;
					}
				}
			}
		};
		SystemUtilities.runSwingNow(r);

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

		Preferences.setProperty(PdbParser.PDB_STORAGE_PROPERTY, chosenDir[0].getAbsolutePath());

		return chosenDir[0];
	}
 
Example 17
Source Project: ghidra   Source File: GatherParamPanel.java    License: Apache License 2.0 4 votes vote down vote up
public void addParameterRegardless(String key, String label, int type, Object defaultValue) {
	Component displayComponent = null;
	if (type == FILE || type == DIRECTORY) {
		String titleString = null;
		if (type == DIRECTORY) {
			titleString = "SELECT DIRECTORY";
		}
		else {
			titleString = "SELECT FILE";
		}
		GhidraFileChooserPanel panel = new GhidraFileChooserPanel(titleString,
			"Recipe.fileChooser", "", true, GhidraFileChooserPanel.INPUT_MODE);
		if (type == DIRECTORY) {
			panel.setFileSelectionMode(GhidraFileChooserMode.DIRECTORIES_ONLY);
		}
		panel.setFileName(defaultValue.toString());
		parameters.put(key, new ParamComponent(panel, type));
		displayComponent = panel;
	}
	else if (type == ADDRESS) {
		AddressInput addressInput = new AddressInput();
		if (state.getCurrentProgram() != null) {
			addressInput.setAddressFactory(state.getCurrentProgram().getAddressFactory());
		}
		addressInput.selectDefaultAddressSpace();
		addressInput.select();
		if (defaultValue != null) {
			addressInput.setValue(defaultValue.toString());
		}
		displayComponent = addressInput;
		parameters.put(key, new ParamComponent(displayComponent, type));
	}
	else {
		JTextField textField = new JTextField();
		if (defaultValue != null) {
			textField.setText(defaultValue.toString());
		}
		displayComponent = textField;
		parameters.put(key, new ParamComponent(displayComponent, type));
	}
	add(new GLabel(label));
	add(displayComponent);
	shown = false;
}
 
Example 18
Source Project: ghidra   Source File: ParseDialog.java    License: Apache License 2.0 4 votes vote down vote up
protected JPanel buildMainPanel() {
	mainPanel = new JPanel(new BorderLayout(10, 5));

	comboModel = new DefaultComboBoxModel<>();
	populateComboBox();

	comboBox = new GhidraComboBox<>(comboModel);
	comboItemListener = e -> selectionChanged(e);
	comboBox.addItemListener(comboItemListener);

	JPanel cPanel = new JPanel(new BorderLayout());
	cPanel.setBorder(BorderFactory.createTitledBorder("Parse Configuration"));
	cPanel.add(comboBox);
	JPanel comboPanel = new JPanel(new BorderLayout());
	comboPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
	comboPanel.add(cPanel);

	pathPanel = new PathnameTablePanel(null, true, false);
	pathPanel.setBorder(BorderFactory.createTitledBorder("Source files to parse"));
	String importDir = Preferences.getProperty(LAST_IMPORT_C_DIRECTORY);
	if (importDir == null) {
		importDir = Preferences.getProperty(Preferences.LAST_IMPORT_DIRECTORY);
		if (importDir != null) {
			Preferences.setProperty(LAST_IMPORT_C_DIRECTORY, importDir);
		}
	}
	pathPanel.setFileChooserProperties("Choose Source Files", LAST_IMPORT_C_DIRECTORY,
		GhidraFileChooserMode.FILES_AND_DIRECTORIES, true,
		new ExtensionFileFilter(new String[] { "h" }, "C Header Files"));

	tableListener = e -> {
		ComboBoxItem item = (ComboBoxItem) comboBox.getSelectedItem();
		item.isChanged = true;
		setActionsEnabled();
	};
	tableModel = pathPanel.getTable().getModel();
	tableModel.addTableModelListener(tableListener);

	JPanel optionsPanel = new JPanel(new BorderLayout());
	optionsPanel.setBorder(BorderFactory.createTitledBorder("Parse Options"));

	// create options field
	// initialize it with windows options
	parseOptionsField = new JTextArea(5, 70);
	JScrollPane pane = new JScrollPane(parseOptionsField);
	pane.getViewport().setPreferredSize(new Dimension(300, 200));
	optionsPanel.add(pane, BorderLayout.CENTER);

	// create Parse Button

	parseButton = new JButton("Parse to Program");
	parseButton.addActionListener(ev -> doParse(false));
	parseButton.setToolTipText("Parse files and add data types to current program");
	addButton(parseButton);

	parseToFileButton = new JButton("Parse to File...");
	parseToFileButton.addActionListener(ev -> doParse(true));
	parseToFileButton.setToolTipText("Parse files and output to archive file");
	addButton(parseToFileButton);

	pathPanel.setPreferredSize(new Dimension(pathPanel.getPreferredSize().width, 200));
	JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, pathPanel, optionsPanel);
	splitPane.setResizeWeight(0.50);
	mainPanel.add(comboPanel, BorderLayout.NORTH);
	mainPanel.add(splitPane, BorderLayout.CENTER);

	setHelpLocation(new HelpLocation(plugin.getName(), "Parse_C_Source"));

	loadProfile();

	return mainPanel;
}
 
Example 19
/**
 * Method to select which known FID databases are currently active
 * during search.
 * @throws IOException 
 */
private void exportToFile() throws IOException {
    var fileChooser = new GhidraFileChooser(null);
    fileChooser.addFileFilter(new ExtensionFileFilter("map", "Symbol Map Files"));
    fileChooser.setTitle("Select an output file");
    fileChooser.setFileSelectionMode(GhidraFileChooserMode.FILES_ONLY);
    var selectedFile = fileChooser.getSelectedFile(true);
    if (selectedFile != null) {
        var writer = new PrintWriter(new FileWriter(selectedFile));
        var symTable = this.currentProgram.getSymbolTable();
        for (var sym : symTable.getAllSymbols(true)) {
            var addr = sym.getAddress().getUnsignedOffset();
            if (addr < 0x80000000L || addr >= 0x81800000L)
                continue; // Ignore out of range addresses
            
            var symName = sym.getName();
            if (symName.startsWith("LAB_") || symName.startsWith("DAT_") || symName.startsWith("PTR_") || symName.startsWith("caseD_") || symName.equals("switchD"))
                continue; // Don't save Ghidra generated symbols.
            var alignment = 8;
            var size = 1L;
            var func = this.currentProgram.getFunctionManager().getFunctionAt(sym.getAddress());
            if (func != null) {
                size = func.getBody().getMaxAddress().getUnsignedOffset() - func.getBody().getMinAddress().getUnsignedOffset() + 1;
                alignment = 4;
            }
            else {
                var memBlock = this.currentProgram.getMemory().getBlock(sym.getAddress());
                if (memBlock != null && memBlock.isExecute() == false) {
                    var cm = ((ProgramDB)this.currentProgram).getCodeManager();
                    var data = cm.getDataAt(sym.getAddress());
                    if (data != null) {
                        size = data.getDataType().getLength();
                        alignment = data.getDataType().getAlignment();
                        if (size < 1) {
                            size = 1;
                        }
                    }
                }
            }
            writer.println(String.format("  %08x %06x %08x %2s %s \t%s", addr, size, addr, Integer.toString(alignment), symName, sym.getParentNamespace().getName()));
        }
        writer.close();
    }
    else {
        Msg.info(this, "A valid map file path must be selected!");
    }
}
 
Example 20
Source Project: ghidra   Source File: GhidraScript.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Returns a File object, using the String parameters for guidance.  The actual behavior of the
 * method depends on your environment, which can be GUI or headless.
 * <p>
 * Regardless of environment -- if script arguments have been set, this method will use the
 * next argument in the array and advance the array index so the next call to an ask method
 * will get the next argument.  If there are no script arguments and a .properties file
 * sharing the same base name as the Ghidra Script exists (i.e., Script1.properties for
 * Script1.java), then this method will then look there for the String value to return.
 * The method will look in the .properties file by searching for a property name that is a
 * space-separated concatenation of the input String parameters (title + " " + approveButtonText).
 * If that property name exists and its value represents a valid <b>absolute path</b> of a valid
 * File, then the .properties value will be used in the following way:
 * <ol>
 * 		<li>In the GUI environment, this method displays a file chooser dialog that allows the
 * 			user to select a file. If the file chooser dialog has been run before in the same
 * 			session, the File selection will be pre-populated with the last-selected file. If
 * 			not, the File selection will be pre-populated with the .properties value (if it
 * 			exists).
 * 		</li>
 *		<li>In the headless environment, this method returns a File object representing	the
 *			.properties	String value (if it exists), or throws an Exception if there is an
 *			invalid or missing .properties value.
 *		</li>
 * </ol>
 *
 * @param title the title of the dialog (in GUI mode) or the first part of the variable name
 * 			(in headless mode or when using using .properties file)
 * @param approveButtonText the approve button text (in GUI mode - typically, this would
 * 		  	be "Open" or "Save") or the second part of the variable name (in headless mode
 * 			or when using .properties file)
 * @return the selected file or null if no tool was available
 * @throws CancelledException if the user hit the 'cancel' button in GUI mode
 * @throws IllegalArgumentException if in headless mode, there was a missing or invalid file
 * 			name specified in the .properties file
 */
public File askFile(final String title, final String approveButtonText)
		throws CancelledException {

	String key = join(title, approveButtonText);
	File existingValue = loadAskValue(this::parseFile, key);
	if (isRunningHeadless()) {
		return existingValue;
	}

	File choice = doAsk(File.class, title, approveButtonText, existingValue, lastValue -> {

		GhidraFileChooser chooser = new GhidraFileChooser(null);
		AtomicReference<File> ref = new AtomicReference<>();

		Runnable r = () -> {
			chooser.setSelectedFile(lastValue);
			chooser.setTitle(title);
			chooser.setApproveButtonText(approveButtonText);
			chooser.setFileSelectionMode(GhidraFileChooserMode.FILES_ONLY);
			ref.set(chooser.getSelectedFile());
		};
		Swing.runNow(r);

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

		return ref.get();
	});

	return choice;
}
 
Example 21
Source Project: ghidra   Source File: GhidraScript.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Returns a directory File object, using the String parameters for guidance. The actual
 * behavior of the method depends on your environment, which can be GUI or headless.
 * <p>
 * Regardless of environment -- if script arguments have been set, this method will use the
 * next argument in the array and advance the array index so the next call to an ask method
 * will get the next argument.  If there are no script arguments and a .properties file
 * sharing the same base name as the Ghidra Script exists (i.e., Script1.properties for
 * Script1.java), then this method will then look there for the String value to return.
 * The method will look in the .properties file by searching for a property name that is a
 * space-separated concatenation of the input String parameters (title + " " + approveButtonText).
 * If that property name exists and its value represents a valid <b>absolute path</b> of a valid
 * directory File, then the .properties value will be used in the following way:
 * <ol>
 * 		<li>In the GUI environment, this method displays a file chooser dialog that allows the
 * 			user to select a directory. If the file chooser dialog has been run before in the
 * 			same session, the directory selection will be pre-populated with the last-selected
 * 			directory. If not, the directory selection will be pre-populated with the
 * 			.properties	value (if it exists).</li>
 *		<li>In the headless environment, this method returns a directory File representing
 *			the .properties value (if it exists), or throws an Exception if there is an invalid
 *			or missing .properties value.</li>
 * </ol>
 *
 * @param title the title of the dialog (in GUI mode) or the first part of the variable name
 * 			(in headless mode or when using .properties file)
 * @param approveButtonText the approve button text (in GUI mode - typically, this would be
 * 			"Open" or "Save") or the second part of the variable name (in headless mode or
 * 			when using .properties file)
 * @return the selected directory or null if no tool was available
 * @throws CancelledException if the user hit the 'cancel' button in GUI mode
 * @throws IllegalArgumentException if in headless mode, there was a missing or invalid
 * 				directory name specified in the .properties file
 */
public File askDirectory(final String title, final String approveButtonText)
		throws CancelledException {

	String key = join(title, approveButtonText);
	File existingValue = loadAskValue(this::parseDirectory, key);
	if (isRunningHeadless()) {
		return existingValue;
	}

	File choice = doAsk(DIRECTORY.class, title, approveButtonText, existingValue, lastValue -> {

		GhidraFileChooser chooser = new GhidraFileChooser(null);
		AtomicReference<File> ref = new AtomicReference<>();

		Runnable r = () -> {
			chooser.setSelectedFile(lastValue);
			chooser.setTitle(title);
			chooser.setApproveButtonText(approveButtonText);
			chooser.setFileSelectionMode(GhidraFileChooserMode.DIRECTORIES_ONLY);
			ref.set(chooser.getSelectedFile());
		};
		Swing.runNow(r);

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

		return ref.get();
	});

	return choice;
}