Ghidra is a software reverse engineering (SRE) framework
GP-5036 added new 'copy special' options. One to copy just data and one to copy de-referenced pointer data
ghidragonb7cf578cd517
diff --git a/Ghidra/Features/Base/src/main/help/help/topics/ClipboardPlugin/Clipboard.htm b/Ghidra/Features/Base/src/main/help/help/topics/ClipboardPlugin/Clipboard.htmindex df8fcc01a6..d23b41ecf7 100644--- a/Ghidra/Features/Base/src/main/help/help/topics/ClipboardPlugin/Clipboard.htm+++ b/Ghidra/Features/Base/src/main/help/help/topics/ClipboardPlugin/Clipboard.htm@@ -167,6 +167,15 @@<LI><B>Byte String (No Spaces)</B> <A name="ByteString_NoSpaces"></A> - This is the same asthe Byte String format, except there are no delimiting spaces between bytes.</LI>+ <LI><B>Data</B> - Copies a the values of all the selected data objects to the clipboard as+ text. This option ignores any compound data objects such as structures, unions, or arrays.+ You can copy data from structures, but you must first open them and select the elements you+ want to copy as a string.</LI>++ <LI><B>Dereferenced Data</B> - Copies the values of all data pointed to by the selected+ pointers. The contents will be copied to the clipboard as text. If the pointed to data is a+ compound data object such as a structure or array, it is ignored.</LI>+<LI><B>Python Byte String</B> - Copies the bytes into the Python byte string format, forexample: <CODE>b'\x41\xec\x49\x89'</CODE>.</LI>diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/clipboard/ClipboardPlugin.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/clipboard/ClipboardPlugin.javaindex 619685eaea..bceb56c422 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/clipboard/ClipboardPlugin.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/clipboard/ClipboardPlugin.java@@ -4,9 +4,9 @@* 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.@@ -65,7 +65,7 @@ public class ClipboardPlugin extends ProgramPluginpublic static final String GROUP_NAME = "Clipboard";public static final String TOOLBAR_GROUP_NAME = "ZClipboard";- private static final String REMOVE_QUOTES_OPTION = "Copy Strings Without Quotes";+ static final String REMOVE_QUOTES_OPTION = "Copy Strings Without Quotes";//The provider that owns the clipboard contentprivate ClipboardContentProviderService clipboardOwnerProvider;diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/clipboard/CodeBrowserClipboardProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/clipboard/CodeBrowserClipboardProvider.javaindex bccaf952be..c39bd541fb 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/clipboard/CodeBrowserClipboardProvider.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/clipboard/CodeBrowserClipboardProvider.java@@ -31,6 +31,7 @@ import docking.ActionContext;import docking.ComponentProvider;import docking.dnd.GenericDataFlavor;import docking.dnd.StringTransferable;+import docking.tool.ToolConstants;import docking.widgets.fieldpanel.Layout;import docking.widgets.fieldpanel.internal.*;import generic.text.TextLayoutGraphics;@@ -43,6 +44,8 @@ import ghidra.app.services.ClipboardContentProviderService;import ghidra.app.util.*;import ghidra.app.util.viewer.listingpanel.ListingModel;import ghidra.framework.model.DomainFile;+import ghidra.framework.options.OptionsChangeListener;+import ghidra.framework.options.ToolOptions;import ghidra.framework.plugintool.PluginTool;import ghidra.program.database.mem.AddressSourceInfo;import ghidra.program.database.symbol.CodeSymbol;@@ -54,12 +57,13 @@ import ghidra.program.model.mem.MemoryBlock;import ghidra.program.model.symbol.*;import ghidra.program.util.*;import ghidra.util.Msg;+import ghidra.util.bean.opteditor.OptionsVetoException;import ghidra.util.task.CancellableIterator;import ghidra.util.task.TaskMonitor;import util.CollectionUtils;public class CodeBrowserClipboardProvider extends ByteCopier- implements ClipboardContentProviderService {+ implements ClipboardContentProviderService, OptionsChangeListener {protected static final PaintContext PAINT_CONTEXT = new PaintContext();private static int[] COMMENT_TYPES = CommentTypes.getTypes();@@ -89,6 +93,11 @@ public class CodeBrowserClipboardProvider extends ByteCopierpublic static final ClipboardType GHIDRA_SHARED_URL_TYPE =new ClipboardType(DataFlavor.stringFlavor, "Shared GhidraURL");+ public static final ClipboardType GHIDRA_DATA_TEXT_TYPE =+ new ClipboardType(DataFlavor.stringFlavor, "Data");+ public static final ClipboardType GHIDRA_DEREFERENCED_DATA_TEXT_TYPE =+ new ClipboardType(DataFlavor.stringFlavor, "Dereferenced Data");+private static final List<ClipboardType> COPY_TYPES = createCopyTypesList();private static List<ClipboardType> createCopyTypesList() {@@ -100,6 +109,8 @@ public class CodeBrowserClipboardProvider extends ByteCopierlist.add(COMMENTS_TYPE);list.add(BYTE_STRING_TYPE);list.add(BYTE_STRING_NO_SPACE_TYPE);+ list.add(GHIDRA_DATA_TEXT_TYPE);+ list.add(GHIDRA_DEREFERENCED_DATA_TEXT_TYPE);list.add(PYTHON_BYTE_STRING_TYPE);list.add(PYTHON_LIST_TYPE);list.add(CPP_BYTE_ARRAY_TYPE);@@ -119,12 +130,19 @@ public class CodeBrowserClipboardProvider extends ByteCopierprivate Set<ChangeListener> listeners = new CopyOnWriteArraySet<>();private String stringContent;+ private boolean includeQuotesForStringData;public CodeBrowserClipboardProvider(PluginTool tool, ComponentProvider codeViewerProvider) {this.tool = tool;this.componentProvider = codeViewerProvider;PAINT_CONTEXT.setTextCopying(true);++ ToolOptions options = tool.getOptions(ToolConstants.TOOL_OPTIONS);+ includeQuotesForStringData =+ !options.getBoolean(ClipboardPlugin.REMOVE_QUOTES_OPTION, false);+ options.addOptionsChangeListener(this);+}@Override@@ -266,6 +284,12 @@ public class CodeBrowserClipboardProvider extends ByteCopierelse if (copyType == GHIDRA_SHARED_URL_TYPE) {return copySharedGhidraURL();}+ else if (copyType == GHIDRA_DATA_TEXT_TYPE) {+ return copyDataText();+ }+ else if (copyType == GHIDRA_DEREFERENCED_DATA_TEXT_TYPE) {+ return copyReferencedDataText();+ }return copyBytes(copyType, monitor);}@@ -534,6 +558,111 @@ public class CodeBrowserClipboardProvider extends ByteCopierreturn createStringTransferable(url.toString());}+ private Transferable copyDataText() {+ return copyDataText(false);+ }++ private Transferable copyReferencedDataText() {+ return copyDataText(true);+ }++ private Transferable copyDataText(boolean followPointers) {+ AddressSetView addrs = getSelectedAddresses();+ List<String> strings = new ArrayList<>();+ Listing listing = currentProgram.getListing();+ if (addrs instanceof ProgramSelection programSelection &&+ programSelection.getInteriorSelection() != null) {+ InteriorSelection interiorSelection = programSelection.getInteriorSelection();+ copyInteriorDataText(strings, listing, interiorSelection, followPointers);+ }+ else {+ for (Data data : listing.getData(addrs, true)) {+ String string = getString(data, followPointers);+ if (string != null) {+ strings.add(string);+ }+ }+ }+ return createStringTransferable(String.join("\n", strings));+ }++ private void copyInteriorDataText(List<String> strings, Listing listing,+ InteriorSelection interior, boolean followPointers) {++ Data outer = listing.getDataContaining(interior.getStartAddress());+ ProgramLocation from = interior.getFrom();+ ProgramLocation to = interior.getTo();+ Data first = outer.getComponent(from.getComponentPath());+ Data last = outer.getComponent(to.getComponentPath());+ if (first == null || last == null) {+ return;+ }++ // We have a selection inside a data that has child elements. This may be several levels+ // deep. The first and last data retrieved above are children in the same parent. So+ // get the index of the first and last data in that parent and add string data for each+ // selected element in that parent.+ Data parent = first.getParent();+ int startIndex = first.getComponentIndex();+ int endIndex = last.getComponentIndex();+ for (int i = startIndex; i <= endIndex; i++) {+ Data child = parent.getComponent(i);+ String string = getString(child, followPointers);+ if (string != null) {+ strings.add(string);+ }+ }+ }++ private Data getReferencedData(Data data, Set<Address> visited) {+ Object value = data.getValue();+ if (!(value instanceof Address address)) {+ return null;+ }+ if (visited.contains(address)) {+ return null;+ }+ visited.add(address);+ Data referenced = currentProgram.getListing().getDataAt(address);+ if (referenced == null) {+ return null;+ }+ if (referenced.isPointer()) {+ return getReferencedData(referenced, visited);+ }+ return referenced;+ }++ private String getString(Data data, boolean followPointers) {+ if (!followPointers) {+ return getString(data);+ }+ // if following pointers and data is not a pointer, then nothing to do+ if (!data.isPointer()) {+ return null;+ }++ // otherwise follow pointers to non-pointer data and return its string+ Set<Address> visited = new HashSet<>();+ Data referenced = getReferencedData(data, visited);+ return getString(referenced);+ }++ private String getString(Data data) {+ // For now, don't get string data for compound object such as structures, unions, or arrays+ if (data == null || data.getNumComponents() > 0) {+ return null;+ }+ Object value = data.getValue();+ if (value instanceof String s) {+ if (includeQuotesForStringData) {+ return "\"" + s + "\"";+ }+ return s;+ }+ return data.getDefaultValueRepresentation();+ }+private boolean pasteLabelsComments(Transferable pasteData, boolean pasteLabels,boolean pasteComments) {try {@@ -897,4 +1026,13 @@ public class CodeBrowserClipboardProvider extends ByteCopierreturn flavorList.contains(flavor);}}++ @Override+ public void optionsChanged(ToolOptions options, String optionName, Object oldValue,+ Object newValue) throws OptionsVetoException {+ if (optionName.equals(ClipboardPlugin.REMOVE_QUOTES_OPTION)) {+ includeQuotesForStringData =+ !options.getBoolean(ClipboardPlugin.REMOVE_QUOTES_OPTION, false);+ }+ }}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/program/database/ProgramBuilder.java b/Ghidra/Features/Base/src/main/java/ghidra/program/database/ProgramBuilder.javaindex ae3eafa37f..6f723e9e09 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/program/database/ProgramBuilder.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/program/database/ProgramBuilder.java@@ -4,9 +4,9 @@* 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.@@ -15,6 +15,7 @@*/package ghidra.program.database;+import java.io.ByteArrayInputStream;import java.math.BigInteger;import java.nio.charset.Charset;import java.nio.charset.StandardCharsets;@@ -36,6 +37,7 @@ import ghidra.framework.options.Options;import ghidra.framework.plugintool.PluginTool;import ghidra.program.database.data.ProgramDataTypeManager;import ghidra.program.database.function.OverlappingFunctionException;+import ghidra.program.database.mem.FileBytes;import ghidra.program.model.address.*;import ghidra.program.model.data.*;import ghidra.program.model.data.DataUtilities.ClearDataMode;@@ -293,6 +295,14 @@ public class ProgramBuilder {return createMemory(name, address, size, comment, (byte) 0);}+ public MemoryBlock createMemory(String name, String address, FileBytes fileBytes, int size) {+ return tx(() -> {+ Address startAddress = addr(address);+ Memory memory = program.getMemory();+ return memory.createInitializedBlock(name, startAddress, fileBytes, 0, size, false);+ });+ }+public MemoryBlock createMemory(String name, String address, int size, String comment,byte initialValue) {@@ -1087,6 +1097,22 @@ public class ProgramBuilder {program.setChanged(changed);}+ public FileBytes createFileBytes(int size) throws Exception {+ byte[] bytes = new byte[size];+ for (int i = 0; i < size; i++) {+ bytes[i] = (byte) i;+ }++ return tx(() -> {+ FileBytes fileBytes =+ program.getMemory()+ .createFileBytes("test", 0, size, new ByteArrayInputStream(bytes),+ TaskMonitor.DUMMY);++ return fileBytes;+ });+ }+private <E extends Exception> void tx(ExceptionalCallback<E> c) {startTransaction();boolean commit = true;diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/clipboard/CodeBrowserClipboardProviderTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/clipboard/CodeBrowserClipboardProviderTest.javaindex a97abfb40f..6b1977b444 100644--- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/clipboard/CodeBrowserClipboardProviderTest.java+++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/clipboard/CodeBrowserClipboardProviderTest.java@@ -4,9 +4,9 @@* 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.@@ -31,17 +31,18 @@ import ghidra.app.util.ByteCopier.ProgrammingByteStringTransferable;import ghidra.app.util.ClipboardType;import ghidra.framework.cmd.Command;import ghidra.framework.model.DomainObject;+import ghidra.framework.options.ToolOptions;import ghidra.framework.plugintool.PluginTool;import ghidra.program.database.ProgramBuilder;+import ghidra.program.database.mem.FileBytes;import ghidra.program.model.address.*;-import ghidra.program.model.data.DataType;+import ghidra.program.model.data.*;import ghidra.program.model.listing.*;import ghidra.program.model.mem.Memory;import ghidra.program.model.mem.MemoryAccessException;import ghidra.program.model.symbol.RefType;import ghidra.program.model.symbol.SourceType;-import ghidra.program.util.ProgramLocation;-import ghidra.program.util.ProgramSelection;+import ghidra.program.util.*;import ghidra.test.AbstractGhidraHeadedIntegrationTest;import ghidra.test.DummyTool;import ghidra.util.NumericUtilities;@@ -59,17 +60,22 @@ public class CodeBrowserClipboardProviderTest extends AbstractGhidraHeadedIntegrprogram = createProgram();PluginTool tool = new DummyTool() {@Override- public boolean execute(Command command, DomainObject obj) {+ public <T extends DomainObject> boolean execute(Command<T> command, T obj) {boolean result = command.applyTo(obj);if (!result) {throw new AssertException("Failed to write bytes");}return true;}- };+ @Override+ public ToolOptions getOptions(String categoryName) {+ return new ToolOptions("Test");+ }+ };clipboardProvider = new CodeBrowserClipboardProvider(tool, null);clipboardProvider.setProgram(program);+}private Program createProgram() throws Exception {@@ -109,7 +115,119 @@ public class CodeBrowserClipboardProviderTest extends AbstractGhidraHeadedIntegrbuilder.setBytes("0x0100418c", "ff 15 08 10 00 01");builder.disassemble("0x0100418c", 6);- return builder.getProgram();+ // create some data with numbers, strings to test copy special for "data"+ builder.createMemory("test", "0x02000000", 400);++ // create some pointers to numbers and strings to test copy special for "referenced data"+ builder.setBytes("0x02000000", "00, 01, 02, 03, 04, 05, 61, 62, 63, 0");++ // create some data with numbers and strings that will go inside a structure+ builder.setBytes("0x02000000", "00, 01, 02, 03, 04, 05, 61, 62, 63, 0");++ builder.setBytes("0x02000100", "02, 00, 00, 04, 02, 00, 00, 06");+ builder.setBytes("0x02000200", "00, 01, 02, 61, 62, 63, 0");+ builder.applyDataType("0x02000000", new ByteDataType());+ builder.applyDataType("0x02000001", new ByteDataType());+ builder.applyDataType("0x02000002", new ByteDataType());+ builder.applyDataType("0x02000003", new ByteDataType());+ builder.applyDataType("0x02000004", new ByteDataType());+ builder.applyDataType("0x02000005", new ByteDataType());+ builder.applyDataType("0x02000006", new StringDataType());+ builder.applyDataType("0x02000100", new PointerDataType(new ByteDataType()));+ builder.applyDataType("0x02000104", new PointerDataType(new StringDataType()));++ // create a structure to test interior data selection+ StructureDataType struct = new StructureDataType("struct_for_data", 0);+ struct.add(new ByteDataType());+ struct.add(new ByteDataType());+ struct.add(new ByteDataType());+ struct.add(new StringDataType(), 4);+ builder.applyDataType("0x02000200", struct);++ // We would like to test copying of source byte offset values. To do so, we need to create+ // a memory block that has source byte offset information.+ FileBytes fileBytes = builder.createFileBytes(100);+ builder.createMemory("filebytes", "0x03000100", fileBytes, 100);+ program = builder.getProgram();+ return program;+ }++ @Test+ public void testCopySpecialFileOffsets() throws Exception {+ clipboardProvider.setLocation(location("0x03000113"));+ ClipboardType type = CodeBrowserClipboardProvider.BYTE_SOURCE_OFFSET_TYPE;+ Transferable transferable = clipboardProvider.copySpecial(type, TaskMonitor.DUMMY);+ assertThat(transferable, instanceOf(StringTransferable.class));+ String data = (String) transferable.getTransferData(DataFlavor.stringFlavor);+ assertEquals("13", data);+ }+ @Test+ public void testCopySpecialBlockOffsets() throws Exception {+ clipboardProvider.setLocation(location("0x02000012"));+ ClipboardType type = CodeBrowserClipboardProvider.BLOCK_OFFSET_TYPE;+ Transferable transferable = clipboardProvider.copySpecial(type, TaskMonitor.DUMMY);+ assertThat(transferable, instanceOf(StringTransferable.class));+ String data = (String) transferable.getTransferData(DataFlavor.stringFlavor);+ assertEquals("12", data);+ }+ @Test+ public void testCopySpecialFunctionOffsets() throws Exception {+ // function address = "0x010023f5";+ clipboardProvider.setLocation(location("0x010023f9"));+ ClipboardType type = CodeBrowserClipboardProvider.FUNCTION_OFFSET_TYPE;+ Transferable transferable = clipboardProvider.copySpecial(type, TaskMonitor.DUMMY);+ assertThat(transferable, instanceOf(StringTransferable.class));+ String data = (String) transferable.getTransferData(DataFlavor.stringFlavor);+ assertEquals("4", data);+ }+ @Test+ public void testCopySpecialImageBaseOffsets() throws Exception {+ clipboardProvider.setLocation(location("0x0100"));+ ClipboardType type = CodeBrowserClipboardProvider.IMAGEBASE_OFFSET_TYPE;+ Transferable transferable = clipboardProvider.copySpecial(type, TaskMonitor.DUMMY);+ assertThat(transferable, instanceOf(StringTransferable.class));+ String data = (String) transferable.getTransferData(DataFlavor.stringFlavor);+ assertEquals("100", data);+ }++ @Test+ public void testCopySpecialData() throws Exception {+ clipboardProvider.setSelection(selection("0x02000000", 10));++ ClipboardType type = CodeBrowserClipboardProvider.GHIDRA_DATA_TEXT_TYPE;+ Transferable transferable = clipboardProvider.copySpecial(type, TaskMonitor.DUMMY);+ assertThat(transferable, instanceOf(StringTransferable.class));+ StringTransferable st = (StringTransferable) transferable;+ String data = (String) st.getTransferData(DataFlavor.stringFlavor);+ assertEquals("0h\n1h\n2h\n3h\n4h\n5h\n\"abc\"", data);+ }++ @Test+ public void testCopySpecialDataInterior() throws Exception {+ //builder.setBytes("0x02000200", "00, 01, 02, 61, 62, 63, 0");++ ProgramSelection interiorSelection =+ makeInteriorSelection("0x02000201", "0x02000203", 1, 3);+ clipboardProvider.setSelection(interiorSelection);++ ClipboardType type = CodeBrowserClipboardProvider.GHIDRA_DATA_TEXT_TYPE;+ Transferable transferable = clipboardProvider.copySpecial(type, TaskMonitor.DUMMY);+ assertThat(transferable, instanceOf(StringTransferable.class));+ StringTransferable st = (StringTransferable) transferable;+ String data = (String) st.getTransferData(DataFlavor.stringFlavor);+ assertEquals("1h\n2h\n\"abc\"", data);+ }++ @Test+ public void testCopySpecialReferencedData() throws Exception {+ clipboardProvider.setSelection(selection("0x02000100", 8));++ ClipboardType type = CodeBrowserClipboardProvider.GHIDRA_DEREFERENCED_DATA_TEXT_TYPE;+ Transferable transferable = clipboardProvider.copySpecial(type, TaskMonitor.DUMMY);+ assertThat(transferable, instanceOf(StringTransferable.class));+ StringTransferable st = (StringTransferable) transferable;+ String data = (String) st.getTransferData(DataFlavor.stringFlavor);+ assertEquals("4h\n\"abc\"", data);}@Test@@ -273,4 +391,19 @@ public class CodeBrowserClipboardProviderTest extends AbstractGhidraHeadedIntegrprivate ProgramLocation location(String addressString) {return new ProgramLocation(program, addr(addressString));}++ private ProgramSelection makeInteriorSelection(String startAddr, String endAddr, int index1,+ int index2) {+ Address start = addr(startAddr);+ Address end = addr(endAddr);+ AddressFieldLocation startLocation =+ new AddressFieldLocation(program, start, new int[] { index1 }, start.toString(), 0);+ AddressFieldLocation endLocation =+ new AddressFieldLocation(program, end, new int[] { index2 }, end.toString(), 0);+ InteriorSelection interiorSelection =+ new InteriorSelection(startLocation, endLocation, start, end);+ return new ProgramSelection(interiorSelection);++ }+}