Ghidra is a software reverse engineering (SRE) framework
GP-426 Add save action to embedded graphic images
dev7473685337b2666f78
diff --git a/Ghidra/Features/Base/certification.manifest b/Ghidra/Features/Base/certification.manifestindex 5ce773a23f..1fa71b205c 100644--- a/Ghidra/Features/Base/certification.manifest+++ b/Ghidra/Features/Base/certification.manifest@@ -19,7 +19,6 @@ data/ExtensionPoint.manifest||GHIDRA||||END|data/MachOFunctionsThatDoNotReturn||GHIDRA||||END|data/PEFunctionsThatDoNotReturn||GHIDRA||||END|data/file_extension_icons.xml||GHIDRA||||END|-data/formats/clamp.properties||GHIDRA||||END|data/functionTags.xml||GHIDRA||||END|data/ms_pe_rich_products.xml||GHIDRA||||END|data/noReturnFunctionConstraints.xml||GHIDRA||||END|@@ -658,6 +657,7 @@ src/main/help/help/topics/Repository/images/label.png||GHIDRA||||END|src/main/help/help/topics/Repository/images/lock.gif||GHIDRA||||END|src/main/help/help/topics/Repository/images/right.png||GHIDRA||||END|src/main/help/help/topics/Repository/images/unlock.gif||GHIDRA||||END|+src/main/help/help/topics/ResourceActionsPlugin/ResourceActions.html||GHIDRA||||END|src/main/help/help/topics/ScalarSearchPlugin/The_Scalar_Table.htm||GHIDRA||||END|src/main/help/help/topics/ScalarSearchPlugin/images/ScalarWindow.png||GHIDRA||||END|src/main/help/help/topics/ScalarSearchPlugin/images/SearchAllScalarsDialog.png||GHIDRA||||END|diff --git a/Ghidra/Features/Base/data/formats/clamp.properties b/Ghidra/Features/Base/data/formats/clamp.propertiesdeleted file mode 100644index fd5d1a59e4..0000000000--- a/Ghidra/Features/Base/data/formats/clamp.properties+++ /dev/null@@ -1,5 +0,0 @@-# feel free to change these values (reasonably) if you run into real-world-# scenarios where these clamp limits are hindering your progress-# (you will need to restart Ghidra after modification)--ghidra.app.util.bin.format.pe.SecurityCertificate.dwLength.max=30000diff --git a/Ghidra/Features/Base/src/main/help/help/TOC_Source.xml b/Ghidra/Features/Base/src/main/help/help/TOC_Source.xmlindex 803c9e2aac..81cdb4c1bd 100644--- a/Ghidra/Features/Base/src/main/help/help/TOC_Source.xml+++ b/Ghidra/Features/Base/src/main/help/help/TOC_Source.xml@@ -236,6 +236,7 @@<tocdef id="Structure Editor" sortgroup="d" text="Structure Editor" target="help/topics/DataTypeEditors/StructureEditor.htm" /><tocdef id="Enum Editor" sortgroup="e" text="Enum Editor" target="help/topics/DataTypeEditors/EnumEditor.htm" /><tocdef id="Translate Strings" sortgroup="e" text="Translate Strings" target="help/topics/TranslateStringsPlugin/TranslateStringsPlugin.htm" />+ <tocdef id="Save Image" sortgroup="e" text="Save Image" target="help/topics/ResourceActionsPlugin/ResourceActions.html" /></tocdef><tocdef id="Labels" sortgroup="d" text="Labels" target="help/topics/LabelMgrPlugin/Labels.htm" >diff --git a/Ghidra/Features/Base/src/main/help/help/topics/ResourceActionsPlugin/ResourceActions.html b/Ghidra/Features/Base/src/main/help/help/topics/ResourceActionsPlugin/ResourceActions.htmlnew file mode 100644index 0000000000..a358b80094--- /dev/null+++ b/Ghidra/Features/Base/src/main/help/help/topics/ResourceActionsPlugin/ResourceActions.html@@ -0,0 +1,57 @@+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">++<HTML>+ <HEAD>+ <META name="generator" content=+ "HTML Tidy for Java (vers. 2009-12-01), see jtidy.sourceforge.net">+ <LINK rel="stylesheet" type="text/css" href="../../shared/Frontpage.css">++ <TITLE>Resource Actions</TITLE>+ </HEAD>++ <BODY>+ <H1>Resource Actions Plugin</H1>++ <BLOCKQUOTE>+ <P>This plugin adds the following actions to images embedded in the Listing. These+ actions are found in the popup menu in the <b>Data</b> → <b>Save Image</b> submenu.</P>+ </BLOCKQUOTE>++ <H2>Actions</H2>++ <BLOCKQUOTE>++ <H3><A name="Save_Image_New_Format"></A>Save Image As New Format</H3>++ <BLOCKQUOTE>+ <P>Given a selected embedded image object, this will write the image to a specified file+ using the format implied by the filename's extension.</P>+ <P>For example, saving a image as "myfile.png" will write the image as PNG format,+ regardless of the original format of the embedded image.</P>+ <P>Known supported formats include:</P>+ <ul>+ <li>PNG+ <li>JPG+ <li>GIF+ <li>BMP+ </ul>+ <P>Attempting to save an image that contains transparency to a format that does not support+ transparency will fail.</P>+ </BLOCKQUOTE>++ <H3><A name="Save_Image_Original_Bytes"></A>Save Image Original Bytes</H3>++ <BLOCKQUOTE>+ <P>Given a selected embedded image object, this will write the embedded+ resource's exact bytes to the specified file.</P>+ </BLOCKQUOTE>+ </BLOCKQUOTE>++ <P class="providedbyplugin">Provided by: <I>Resource Actions Plugin</I></P>+ <P class="relatedtopic">Related Topics:</P>+ <UL>+ <LI><A href="help/topics/CodeBrowserPlugin/CodeBrowser.htm">Listing</A></LI>+ </UL>+ <BR>+ </BODY>+</HTML>diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/resources/ResourceActionsPlugin.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/resources/ResourceActionsPlugin.javanew file mode 100644index 0000000000..9b17c73008--- /dev/null+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/resources/ResourceActionsPlugin.java@@ -0,0 +1,165 @@+/* ###+ * 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.plugin.core.resources;++import java.awt.image.BufferedImage;+import java.io.File;+import java.io.IOException;++import javax.imageio.ImageIO;+import javax.swing.ImageIcon;++import org.apache.commons.io.FilenameUtils;++import docking.action.builder.ActionBuilder;+import docking.widgets.OptionDialog;+import docking.widgets.filechooser.GhidraFileChooser;+import docking.widgets.filechooser.GhidraFileChooserMode;+import generic.util.image.ImageUtils;+import ghidra.app.CorePluginPackage;+import ghidra.app.context.ProgramLocationActionContext;+import ghidra.app.plugin.PluginCategoryNames;+import ghidra.app.util.viewer.field.ResourceFieldLocation;+import ghidra.framework.plugintool.*;+import ghidra.framework.plugintool.util.PluginStatus;+import ghidra.program.model.data.DataImage;+import ghidra.program.model.listing.Data;+import ghidra.program.model.mem.MemoryAccessException;+import ghidra.util.Msg;+import ghidra.util.filechooser.ExtensionFileFilter;+import ghidra.util.filechooser.GhidraFileFilter;+import utilities.util.FileUtilities;++/**+ * A plugin that adds actions to manage data resources in the listing+ */+//@formatter:off+@PluginInfo(+ status = PluginStatus.RELEASED,+ packageName = CorePluginPackage.NAME,+ category = PluginCategoryNames.COMMON,+ shortDescription = "Data resource actions",+ description = "This plugin provides actions related to embedded resources in the Listing."+)+//@formatter:on+public class ResourceActionsPlugin extends Plugin {+ public static final GhidraFileFilter GRAPHIC_FORMATS_FILTER =+ ExtensionFileFilter.forExtensions("Graphic Images", "png", "gif", "bmp", "jpg");++ public ResourceActionsPlugin(PluginTool tool) {+ super(tool);+ }++ @Override+ protected void init() {+ super.init();++ new ActionBuilder("Save Image New Format", getName())+ .withContext(ProgramLocationActionContext.class)+ .validContextWhen(plac -> plac.getLocation() instanceof ResourceFieldLocation &&+ ((ResourceFieldLocation) plac.getLocation()).isDataImageResource())+ .onAction(+ plac -> saveImageAsNewImage((ResourceFieldLocation) plac.getLocation()))+ .popupMenuPath("Data", "Save Image", "As New Format")+ .buildAndInstall(tool);++ new ActionBuilder("Save Image Original Bytes", getName())+ .withContext(ProgramLocationActionContext.class)+ .validContextWhen(plac -> plac.getLocation() instanceof ResourceFieldLocation &&+ ((ResourceFieldLocation) plac.getLocation()).isDataImageResource())+ .onAction(+ plac -> saveImageOriginalBytes((ResourceFieldLocation) plac.getLocation()))+ .popupMenuPath("Data", "Save Image", "Original Bytes")+ .buildAndInstall(tool);++ tool.setMenuGroup(new String[] { "Data", "Save Image" }, "A_save_image");++ }++ private void saveImageAsNewImage(ResourceFieldLocation imageLocation) {+ Data data = imageLocation.getResourceData();+ if (data == null || !(data.getValue() instanceof DataImage)) {+ return;+ }+ DataImage dataImage = (DataImage) data.getValue();+ GhidraFileChooser chooser = new GhidraFileChooser(tool.getActiveWindow());+ chooser.setFileSelectionMode(GhidraFileChooserMode.FILES_ONLY);+ chooser.setTitle("Save Image File As");+ chooser.setApproveButtonText("Save Image As");+ chooser.addFileFilter(GRAPHIC_FORMATS_FILTER);+ File f = chooser.getSelectedFile();+ if (f != null) {+ if (f.exists() && OptionDialog.showYesNoDialog(tool.getActiveWindow(),+ "Overwrite Existing File?",+ "Overwrite " + f.getName() + "?") != OptionDialog.YES_OPTION) {+ return;+ }+ String extension = FilenameUtils.getExtension(f.getName());+ if (extension.isBlank()) {+ Msg.showError(this, null, "Missing File Type",+ "Filename must specify a supported graphics format extension.");+ return;+ }++ try {+ ImageIcon icon = dataImage.getImageIcon();+ BufferedImage buffy = ImageUtils.getBufferedImage(icon.getImage());+ boolean success = ImageIO.write(buffy, extension, f);+ if (!success) {+ Msg.showError(this, null, "Image File Error",+ "Failed to save " + f.getName() ++ ".\n\nEither unsupported image format or " ++ "incompatible image features with selected image format.");+ return;+ }+ tool.setStatusInfo(+ "Image resource at " + data.getAddress() + " saved as: " + f.getName());+ }+ catch (IOException e) {+ Msg.showError(this, null, "Image File Error", "Failed to save " + f.getName(), e);+ }+ }+ }++ private void saveImageOriginalBytes(ResourceFieldLocation imageLocation) {+ Data data = imageLocation.getResourceData();+ if (data == null) {+ return;+ }+ try {+ GhidraFileChooser chooser = new GhidraFileChooser(tool.getActiveWindow());+ chooser.setFileSelectionMode(GhidraFileChooserMode.FILES_ONLY);+ chooser.setTitle("Save Image File As");+ chooser.setApproveButtonText("Save Image As");+ chooser.addFileFilter(GRAPHIC_FORMATS_FILTER);+ File f = chooser.getSelectedFile();+ if (f != null) {+ if (f.exists() && OptionDialog.showYesNoDialog(tool.getActiveWindow(),+ "Overwrite Existing File?",+ "Overwrite " + f.getName() + "?") != OptionDialog.YES_OPTION) {+ return;+ }+ byte[] bytes = data.getBytes();+ FileUtilities.writeBytes(f, bytes);+ tool.setStatusInfo(+ "Image resource at " + data.getAddress() + " saved as: " + f.getName());+ }+ }+ catch (MemoryAccessException | IOException e) {+ Msg.showError(this, null, "Error Saving Image File", "Failed to save image", e);+ }+ }+}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/OperandFieldHelper.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/OperandFieldHelper.javaindex 63851635bb..283cecf8dd 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/OperandFieldHelper.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/OperandFieldHelper.java@@ -205,6 +205,16 @@ abstract class OperandFieldHelper extends FieldFactory {public ProgramLocation getProgramLocation(int row, int col, ListingField lf) {Object obj = lf.getProxy().getObject();+ if (lf instanceof ImageFactoryField) {+ Data data = (Data) obj;+ if (data.getValue() instanceof DataImage) {+ return new ResourceFieldLocation(data.getProgram(), data.getMinAddress(),+ data.getComponentPath(), codeUnitFormat.getDataValueRepresentationString(data),+ 0, col, data);+ }+ // else might be a Playable+ }+if (!(lf instanceof ListingTextField)) {return null;}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/ResourceFieldLocation.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/ResourceFieldLocation.javanew file mode 100644index 0000000000..e2dc237a62--- /dev/null+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/ResourceFieldLocation.java@@ -0,0 +1,86 @@+/* ###+ * 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.viewer.field;++import ghidra.program.model.address.Address;+import ghidra.program.model.data.DataImage;+import ghidra.program.model.data.DataUtilities;+import ghidra.program.model.listing.Data;+import ghidra.program.model.listing.Program;+import ghidra.program.util.OperandFieldLocation;+import ghidra.program.util.ProgramLocation;++/**+ * A {@link ProgramLocation} of an item that is a Resource+ * embedded in a binary (ie. a embedded graphic image)+ */+public class ResourceFieldLocation extends OperandFieldLocation {++ /**+ * Cached here because users will probably need to query its details during+ * action enablement+ */+ private Data data;++ /**+ * Creates an ResourceFieldLocation+ *+ * @param program the program+ * @param address the address of the location+ * @param componentPath the data component path+ * @param displayValue the text being displayed in the text.+ * @param opIndex the index of the operand at this location.+ * @param characterOffset the character position from the beginning of the operand.+ * @param data Data instance at the specified address / component path+ */+ public ResourceFieldLocation(Program program, Address address, int[] componentPath,+ String displayValue, int opIndex, int characterOffset, Data data) {++ super(program, address, componentPath, null, displayValue, opIndex, characterOffset);++ this.data = data;+ }++ /**+ * Default constructor needed for restoring from XML.+ */+ public ResourceFieldLocation() {+ // for restoring from XML+ }++ /**+ * Returns the resource's Data instance.+ *+ * @return the resource's Data instance+ */+ public Data getResourceData() {+ if (data == null) {+ data = DataUtilities.getDataAtLocation(this);+ }+ return data;+ }++ /**+ * Returns true if this resource is a {@link DataImage}.+ *+ * @return true if this resource is a {@link DataImage}+ */+ public boolean isDataImageResource() {+ getResourceData(); // side effect to init data if null after deserialization+ return data != null && data.getValue() instanceof DataImage;+ }++}