Ghidra is a software reverse engineering (SRE) framework
GP-440 Refactored graph exporters to be more extensible and easy to use in scripts
ghidravore6dc9b3387df6
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/graph/GraphDisplayBrokerPlugin.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/graph/GraphDisplayBrokerPlugin.javaindex c64b0b909d..c6ed1c08c2 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/graph/GraphDisplayBrokerPlugin.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/graph/GraphDisplayBrokerPlugin.java@@ -26,8 +26,7 @@ import ghidra.app.services.GraphDisplayBroker;import ghidra.framework.options.*;import ghidra.framework.plugintool.*;import ghidra.framework.plugintool.util.PluginStatus;-import ghidra.service.graph.GraphDisplay;-import ghidra.service.graph.GraphDisplayProvider;+import ghidra.service.graph.*;import ghidra.util.classfinder.ClassSearcher;import ghidra.util.exception.GraphException;import ghidra.util.task.TaskMonitor;@@ -50,6 +49,7 @@ public class GraphDisplayBrokerPlugin extends Pluginprivate GraphDisplayProvider defaultGraphDisplayProvider;private List<GraphDisplayBrokerListener> listeners = new ArrayList<>();private List<GraphSelectionAction> actions = new ArrayList<>();+ private List<AttributedGraphExporter> exporters;public GraphDisplayBrokerPlugin(PluginTool tool) {super(tool);@@ -206,4 +206,23 @@ public class GraphDisplayBrokerPlugin extends Pluginreturn null;}+ @Override+ public List<AttributedGraphExporter> getGraphExporters() {+ if (exporters == null) {+ exporters = ClassSearcher.getInstances(AttributedGraphExporter.class);+ }+ return Collections.unmodifiableList(exporters);+ }++ @Override+ public AttributedGraphExporter getGraphExporters(String exporterName) {+ List<AttributedGraphExporter> graphExporters = getGraphExporters();+ for (AttributedGraphExporter exporter : graphExporters) {+ if (exporter.getName().equals(exporterName)) {+ return exporter;+ }+ }+ return null;+ }+}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/services/GraphDisplayBroker.java b/Ghidra/Features/Base/src/main/java/ghidra/app/services/GraphDisplayBroker.javaindex 57112667a0..47e41e8cad 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/services/GraphDisplayBroker.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/services/GraphDisplayBroker.java@@ -15,11 +15,12 @@*/package ghidra.app.services;+import java.util.List;+import ghidra.app.plugin.core.graph.GraphDisplayBrokerListener;import ghidra.app.plugin.core.graph.GraphDisplayBrokerPlugin;import ghidra.framework.plugintool.ServiceInfo;-import ghidra.service.graph.GraphDisplay;-import ghidra.service.graph.GraphDisplayProvider;+import ghidra.service.graph.*;import ghidra.util.exception.GraphException;import ghidra.util.task.TaskMonitor;@@ -74,4 +75,21 @@ public interface GraphDisplayBroker {* @return the GraphDisplayProvider with the given name or null if none with that name exists.*/public GraphDisplayProvider getGraphDisplayProvider(String name);++ /**+ * Returns a list of all discovered {@link AttributedGraphExporter}.+ * @return a list of all discovered {@link AttributedGraphExporter}.+ */+ public List<AttributedGraphExporter> getGraphExporters();++ /**+ * Returns the {@link AttributedGraphExporter} with the given name or null in no exporter with+ * that name is known+ *+ * @param name the name of the exporter to retrieve+ * @return the {@link AttributedGraphExporter} with the given name or null if no exporter with+ * that name is known+ */+ public AttributedGraphExporter getGraphExporters(String name);+}diff --git a/Ghidra/Features/GraphServices/certification.manifest b/Ghidra/Features/GraphServices/certification.manifestindex 37be0115f7..3800380e4f 100644--- a/Ghidra/Features/GraphServices/certification.manifest+++ b/Ghidra/Features/GraphServices/certification.manifest@@ -8,6 +8,7 @@##MODULE IP: Tango Icons - Public DomainModule.manifest||GHIDRA||||END|build.gradle||GHIDRA||||END|+data/ExtensionPoint.manifest||GHIDRA||||END|src/main/help/help/TOC_Source.xml||GHIDRA||||END|src/main/help/help/shared/arrow.gif||GHIDRA||||END|src/main/help/help/shared/note.png||Oxygen Icons - LGPL 3.0|||Oxygen icon theme (dual license; LGPL or CC-SA-3.0)|END|diff --git a/Ghidra/Features/GraphServices/data/ExtensionPoint.manifest b/Ghidra/Features/GraphServices/data/ExtensionPoint.manifestnew file mode 100644index 0000000000..0435287364--- /dev/null+++ b/Ghidra/Features/GraphServices/data/ExtensionPoint.manifest@@ -0,0 +1 @@+GraphExporterdiff --git a/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/export/AbstractGraphExporterFactory.java b/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/export/AbstractGraphExporterFactory.javadeleted file mode 100644index bd65e9db6c..0000000000--- a/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/export/AbstractGraphExporterFactory.java+++ /dev/null@@ -1,159 +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.graph.export;--import java.util.Collections;-import java.util.Map;-import java.util.function.Function;-import java.util.function.Supplier;--import org.jgrapht.nio.*;-import org.jgrapht.nio.csv.*;-import org.jgrapht.nio.dimacs.DIMACSExporter;-import org.jgrapht.nio.dimacs.DIMACSFormat;-import org.jgrapht.nio.dot.DOTExporter;-import org.jgrapht.nio.gml.GmlExporter;-import org.jgrapht.nio.graphml.GraphMLExporter;-import org.jgrapht.nio.json.JSONExporter;-import org.jgrapht.nio.lemon.LemonExporter;-import org.jgrapht.nio.matrix.MatrixExporter;--/**- * Base factory class for using the JGrapht export library. Clients should subclass this- * for specific graph types and provide better providers than the defaults defined here.- *- * @param <V> the graph vertex type- * @param <E> the graph edge type- */-public abstract class AbstractGraphExporterFactory<V, E> {- protected char csvDelimiter = ',';- protected CSVFormat csvFormat = CSVFormat.EDGE_LIST;- protected DIMACSFormat dimacsFormat = DIMACSExporter.DEFAULT_DIMACS_FORMAT;- protected MatrixExporter.Format matrixFormat = MatrixExporter.Format.SPARSE_ADJACENCY_MATRIX;-- protected Function<V, String> defaultVertexIdProvider = new IntegerIdProvider<>();- protected Function<E, String> defaultEdgeIdProvider = new IntegerIdProvider<>();-- protected Supplier<String> graphIdProvider = () -> "Ghidra";- protected Function<V, String> vertexLabelProvider = Object::toString;- protected Function<E, String> edgeLabelProvider = Object::toString;- protected Function<E, String> edgeIdProvider = defaultEdgeIdProvider;- protected Function<V, String> vertexIdProvider = defaultVertexIdProvider;-- protected Function<E, Map<String, Attribute>> edgeAttributeProvider =- e -> Collections.emptyMap();- protected Function<V, Map<String, Attribute>> vertexAttributeProvider =- v -> Collections.emptyMap();-- /**- * Creates an exporter of the specified type- *- * @param format the file output type- * @return a {@link GraphExporter} configured to output in the specified format- */- public GraphExporter<V, E> createExporter(GraphExportFormat format) {- switch (format) {- case CSV:- return createCsvExporter();- case DIMACS:- return createDimacsExporter();- case DOT:- return createDotExporter();- case GML:- return createGmlExporter();- case JSON:- return createJsonExporter();- case LEMON:- return createLemonExporter();- case MATRIX:- return createMatrixExporter();- case VISIO:- return createVisioExporter();- case GRAPHML:- default:- return createGraphMlExporter();-- }- }-- private GraphExporter<V, E> createGraphMlExporter() {- GraphMLExporter<V, E> exporter = new GraphMLExporter<>(vertexIdProvider);- setupExporter(exporter);- return exporter;- }-- private GraphExporter<V, E> createVisioExporter() {- VisioExporter<V, E> exporter = new VisioExporter<>(vertexIdProvider);- setupExporter(exporter);- return exporter;- }-- private GraphExporter<V, E> createMatrixExporter() {- MatrixExporter<V, E> exporter = new MatrixExporter<>(matrixFormat, vertexIdProvider);- setupExporter(exporter);- return exporter;- }-- private GraphExporter<V, E> createLemonExporter() {- LemonExporter<V, E> exporter = new LemonExporter<>(vertexIdProvider);- setupExporter(exporter);- return exporter;- }-- private GraphExporter<V, E> createJsonExporter() {- JSONExporter<V, E> exporter = new JSONExporter<>(vertexIdProvider);- setupExporter(exporter);- return exporter;- }-- private GraphExporter<V, E> createGmlExporter() {- GmlExporter<V, E> exporter = new GmlExporter<>(vertexIdProvider);- setupExporter(exporter);- return exporter;- }-- String getQuotedId(V vertex) {- String id = vertexIdProvider.apply(vertex);- return "\"" + id + "\"";- }-- private GraphExporter<V, E> createDotExporter() {- // DOT format is picky about its identifiers, so pass in a vertex id supplier- // that wraps the vertex ids in quotes- DOTExporter<V, E> exporter = new DOTExporter<>(this::getQuotedId);- setupExporter(exporter);- return exporter;- }-- private GraphExporter<V, E> createDimacsExporter() {- DIMACSExporter<V, E> exporter = new DIMACSExporter<>(vertexIdProvider, dimacsFormat);- setupExporter(exporter);- return exporter;- }-- private GraphExporter<V, E> createCsvExporter() {- CSVExporter<V, E> exporter = new CSVExporter<>(vertexIdProvider, csvFormat, csvDelimiter);- setupExporter(exporter);- return exporter;- }-- private void setupExporter(BaseExporter<V, E> exporter) {- exporter.setEdgeIdProvider(defaultEdgeIdProvider);- exporter.setVertexAttributeProvider(vertexAttributeProvider);- exporter.setEdgeAttributeProvider(edgeAttributeProvider);- exporter.setGraphIdProvider(graphIdProvider);- }-}diff --git a/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/export/AttributedGraphExporterFactory.java b/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/export/AttributedGraphExporterFactory.javadeleted file mode 100644index 7884705eaf..0000000000--- a/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/export/AttributedGraphExporterFactory.java+++ /dev/null@@ -1,60 +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.graph.export;--import java.util.AbstractMap;-import java.util.Map;-import java.util.stream.Collectors;--import org.jgrapht.nio.*;--import ghidra.service.graph.*;--/**- * Specific implementation of {@link AbstractGraphExporterFactory} for exporting graphs with- * {@link AttributedVertex} vertices and {@link AttributedEdge} edges.- */-public class AttributedGraphExporterFactory- extends AbstractGraphExporterFactory<AttributedVertex, AttributedEdge> {-- AttributedGraphExporterFactory() {- vertexLabelProvider = AttributedVertex::getName;- edgeLabelProvider = Object::toString;- edgeIdProvider = AttributedEdge::getId;- edgeAttributeProvider = AttributedGraphExporterFactory::getComponentAttributes;- vertexAttributeProvider = AttributedGraphExporterFactory::getComponentAttributes;- vertexIdProvider = AttributedVertex::getId;- }-- /**- * Gets {@link GraphExporter} configured to output a graph in the specified format.- * @param format the output file format.- * @return {@link GraphExporter} configured to output a graph in the specified format.- */- public static GraphExporter<AttributedVertex, AttributedEdge> getExporter(- GraphExportFormat format) {- return new AttributedGraphExporterFactory().createExporter(format);- }-- private static Map<String, Attribute> getComponentAttributes(Attributed v) {- return v.getAttributeMap()- .entrySet()- .stream()- .map(entry -> new AbstractMap.SimpleEntry<String, Attribute>(entry.getKey(),- new DefaultAttribute<>(entry.getValue(), AttributeType.STRING)))- .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));- }-}diff --git a/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/export/ExportAttributedGraphDisplay.java b/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/export/ExportAttributedGraphDisplay.javaindex c75c8caa67..b01fe8e654 100644--- a/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/export/ExportAttributedGraphDisplay.java+++ b/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/export/ExportAttributedGraphDisplay.java@@ -15,16 +15,15 @@*/package ghidra.graph.export;-import java.util.Collections;-import java.util.Set;+import java.util.*;import org.jgrapht.Graph;import docking.action.DockingAction;import docking.widgets.EventTrigger;+import ghidra.app.services.GraphDisplayBroker;import ghidra.framework.plugintool.PluginTool;import ghidra.service.graph.*;-import ghidra.util.Swing;import ghidra.util.task.TaskMonitor;/**@@ -37,7 +36,7 @@ import ghidra.util.task.TaskMonitor;*/class ExportAttributedGraphDisplay implements GraphDisplay {- private final PluginTool pluginTool;+ private final PluginTool tool;private String title;private AttributedGraph graph;@@ -46,7 +45,7 @@ class ExportAttributedGraphDisplay implements GraphDisplay {* @param programGraphDisplayProvider provides a {@link PluginTool} for Docking features*/ExportAttributedGraphDisplay(ExportAttributedGraphDisplayProvider programGraphDisplayProvider) {- this.pluginTool = programGraphDisplayProvider.getPluginTool();+ this.tool = programGraphDisplayProvider.getPluginTool();}@Override@@ -67,8 +66,17 @@ class ExportAttributedGraphDisplay implements GraphDisplay {* @param attributedGraph the {@link AttributedGraph} to visualize*/private void doSetGraphData(AttributedGraph attributedGraph) {- GraphExporterDialog dialog = new GraphExporterDialog(attributedGraph);- Swing.runLater(() -> pluginTool.showDialog(dialog));+ List<AttributedGraphExporter> exporters = findGraphExporters();+ GraphExporterDialog dialog = new GraphExporterDialog(attributedGraph, exporters);+ tool.showDialog(dialog);+ }++ private List<AttributedGraphExporter> findGraphExporters() {+ GraphDisplayBroker service = tool.getService(GraphDisplayBroker.class);+ if (service != null) {+ return service.getGraphExporters();+ }+ return Collections.emptyList();}@Overridediff --git a/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/export/GraphExportFormat.java b/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/export/GraphExportFormat.javadeleted file mode 100644index 4f14e6de17..0000000000--- a/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/export/GraphExportFormat.java+++ /dev/null@@ -1,38 +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.graph.export;--enum GraphExportFormat {- CSV("csv"),- DIMACS("col"),- DOT("gv"),- GML("gml"),- GRAPHML("graphml"),- JSON("json"),- LEMON("lgf"),- MATRIX("g"),- VISIO("vsd");-- private final String fileExtension;-- GraphExportFormat(String fileExtension) {- this.fileExtension = fileExtension;- }-- public String getDefaultFileExtension() {- return fileExtension;- }-}diff --git a/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/export/GraphExporterDialog.java b/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/export/GraphExporterDialog.javaindex 6bc87c1035..4e29276969 100644--- a/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/export/GraphExporterDialog.java+++ b/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/export/GraphExporterDialog.java@@ -17,8 +17,7 @@ package ghidra.graph.export;import java.awt.BorderLayout;import java.awt.Component;-import java.io.*;-import java.util.Arrays;+import java.io.File;import java.util.List;import java.util.concurrent.atomic.AtomicBoolean;@@ -26,9 +25,6 @@ import javax.swing.*;import javax.swing.event.DocumentEvent;import javax.swing.event.DocumentListener;-import org.jgrapht.Graph;-import org.jgrapht.nio.GraphExporter;-import docking.DialogComponentProvider;import docking.options.editor.ButtonPanelFactory;import docking.widgets.OptionDialog;@@ -37,8 +33,8 @@ import docking.widgets.filechooser.GhidraFileChooser;import docking.widgets.filechooser.GhidraFileChooserMode;import docking.widgets.label.GLabel;import ghidra.framework.preferences.Preferences;-import ghidra.service.graph.AttributedEdge;-import ghidra.service.graph.AttributedVertex;+import ghidra.service.graph.AttributedGraph;+import ghidra.service.graph.AttributedGraphExporter;import ghidra.util.*;import ghidra.util.filechooser.ExtensionFileFilter;import ghidra.util.filechooser.GhidraFileFilter;@@ -54,22 +50,26 @@ import ghidra.util.task.TaskMonitor;public class GraphExporterDialog extends DialogComponentProvider {- private static GraphExportFormat lastUsedExporterFormat = GraphExportFormat.GRAPHML; // default to GZF first time+ private static String lastUsedExporterName = "JSON"; // default to JSON first timeprivate JTextField filePathTextField;private JButton fileChooserButton;- private GhidraComboBox<GraphExportFormat> comboBox;- private final Graph<AttributedVertex, AttributedEdge> graph;+ private GhidraComboBox<AttributedGraphExporter> comboBox;+ private final AttributedGraph graph;++ private List<AttributedGraphExporter> exporters;/*** Construct a new ExporterDialog for exporting a program, optionally only exported a* selected region.** @param graph the graph to save+ * @param exporters the list of known exporters*/- public GraphExporterDialog(Graph<AttributedVertex, AttributedEdge> graph) {+ public GraphExporterDialog(AttributedGraph graph, List<AttributedGraphExporter> exporters) {super("Export Graph");this.graph = graph;+ this.exporters = exporters;addWorkPanel(buildWorkPanel());addOKButton();@@ -152,10 +152,10 @@ public class GraphExporterDialog extends DialogComponentProvider {chooser.setFileSelectionMode(GhidraFileChooserMode.FILES_ONLY);chooser.setSelectedFileFilter(GhidraFileFilter.ALL);- GraphExportFormat exporter = getSelectedExporter();+ AttributedGraphExporter exporter = getSelectedExporter();if (exporter != null) {chooser.setFileFilter(- new ExtensionFileFilter(exporter.getDefaultFileExtension(), exporter.toString()));+ new ExtensionFileFilter(exporter.getFileExtension(), exporter.toString()));}String filePath = filePathTextField.getText().trim();File currentFile = filePath.isEmpty() ? null : new File(filePath);@@ -182,30 +182,26 @@ public class GraphExporterDialog extends DialogComponentProvider {private Component buildFormatChooser() {- List<GraphExportFormat> exporters = getApplicableExporters();- comboBox = new GhidraComboBox<>(exporters.toArray(new GraphExportFormat[0]));+ comboBox =+ new GhidraComboBox<>(exporters.toArray(new AttributedGraphExporter[exporters.size()]));- GraphExportFormat defaultExporter = getDefaultExporter(exporters);+ AttributedGraphExporter defaultExporter = getDefaultExporter();if (defaultExporter != null) {comboBox.setSelectedItem(defaultExporter);}return comboBox;}- private List<GraphExportFormat> getApplicableExporters() {- return Arrays.asList(GraphExportFormat.values());- }-- private GraphExportFormat getDefaultExporter(List<GraphExportFormat> list) {+ private AttributedGraphExporter getDefaultExporter() {// first try the last one used- for (GraphExportFormat exporter : list) {- if (lastUsedExporterFormat.equals(exporter)) {+ for (AttributedGraphExporter exporter : exporters) {+ if (lastUsedExporterName.equals(exporter.getName())) {return exporter;}}- return list.isEmpty() ? null : list.get(0);+ return exporters.isEmpty() ? null : exporters.get(0);}private void validate() {@@ -232,8 +228,8 @@ public class GraphExporterDialog extends DialogComponentProvider {setOkEnabled(true);}- private GraphExportFormat getSelectedExporter() {- return (GraphExportFormat) comboBox.getSelectedItem();+ private AttributedGraphExporter getSelectedExporter() {+ return (AttributedGraphExporter) comboBox.getSelectedItem();}private File getSelectedOutputFile() {@@ -247,8 +243,8 @@ public class GraphExporterDialog extends DialogComponentProvider {}private String appendExporterFileExtension(String filename) {- GraphExportFormat exporterFormat = getSelectedExporter();- String extension = "." + exporterFormat.getDefaultFileExtension();+ AttributedGraphExporter exporter = getSelectedExporter();+ String extension = "." + exporter.getFileExtension();if (!filename.toLowerCase().endsWith(extension.toLowerCase())) {return filename + extension;}@@ -257,7 +253,7 @@ public class GraphExporterDialog extends DialogComponentProvider {@Overrideprotected void okCallback() {- lastUsedExporterFormat = getSelectedExporter();+ AttributedGraphExporter exporter = getSelectedExporter();setLastExportDirectory(getSelectedOutputFile());if (doExport()) {close();@@ -273,7 +269,7 @@ public class GraphExporterDialog extends DialogComponentProvider {}private boolean tryExport(TaskMonitor monitor) {- GraphExportFormat exporterFormat = getSelectedExporter();+ AttributedGraphExporter exporter = getSelectedExporter();File outputFile = getSelectedOutputFile();if (outputFile.exists() &&@@ -283,14 +279,8 @@ public class GraphExporterDialog extends DialogComponentProvider {return false;}- try (Writer writer = new FileWriter(outputFile)) {-- GraphExporter<AttributedVertex, AttributedEdge> exporter =- AttributedGraphExporterFactory.getExporter(exporterFormat);-- exporter.exportGraph(graph, writer);-- displaySummaryResults(exporterFormat);+ try {+ exporter.exportGraph(graph, outputFile);return true;}catch (Exception e) {@@ -301,33 +291,14 @@ public class GraphExporterDialog extends DialogComponentProvider {return false;}- /**- * TODO: this does nothing useful- * @param exporter the export format- */- private void displaySummaryResults(GraphExportFormat exporter) {- File outputFile = getSelectedOutputFile();- String results =- "Destination file: " +- "Destination file Size: " +- outputFile.length() + "\n" +- "Format: " +- exporter.toString() + "\n\n";-- String log = exporter.toString();- if (log != null) {- results += log;- }- }-// for testingpublic void setOutputFile(String outputFilePath) {filePathTextField.setText(outputFilePath);}// for testing- public void setExportFormat(GraphExportFormat format) {- comboBox.setSelectedItem(format);+ public void setExporter(AttributedGraphExporter exporter) {+ comboBox.setSelectedItem(exporter);}}diff --git a/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/AbstractAttributedGraphExporter.java b/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/AbstractAttributedGraphExporter.javanew file mode 100644index 0000000000..d84d2fef97--- /dev/null+++ b/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/AbstractAttributedGraphExporter.java@@ -0,0 +1,79 @@+/* ###+ * 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.graph.exporter;++import java.util.HashMap;+import java.util.Map;+import java.util.Map.Entry;+import java.util.function.Function;+import java.util.function.Supplier;++import org.jgrapht.nio.*;++import ghidra.service.graph.*;++/**+ * Abstract base class that graph exporters can extend to get some common functionality+ */+public abstract class AbstractAttributedGraphExporter implements AttributedGraphExporter {+ protected Function<AttributedEdge, String> edgeIdProvider = AttributedEdge::getId;+ protected Function<AttributedVertex, String> vertexIdProvider = AttributedVertex::getId;+ protected Supplier<String> graphIdProvider = () -> "Ghidra";++ /**+ * Converts the attributes of an Attributed object from map of <String, String> to a+ * map of <String, Attribute>+ * @param attributed the {@link Attributed} object+ * @return a map of <String, Attributes> that represent the attributes of the given Attributed+ * object+ */+ protected Map<String, Attribute> getAttributes(Attributed attributed) {+ Map<String, Attribute> attributeMap = new HashMap<>();++ for (Entry<String, String> entry : attributed.entrySet()) {+ String key = entry.getKey();+ String value = entry.getValue();+ attributeMap.put(key, new DefaultAttribute<>(value, AttributeType.STRING));+ }+ return attributeMap;+ }++ @Override+ public String toString() {+ return getName();+ }++ @Override+ public int hashCode() {+ return getName().hashCode();+ }++ @Override+ public boolean equals(Object obj) {+ if (this == obj) {+ return true;+ }+ if (obj == null) {+ return false;+ }+ if (getClass() != obj.getClass()) {+ return false;+ }+ AbstractAttributedGraphExporter other = (AbstractAttributedGraphExporter) obj;+ return getName().equals(other.getName());+ }++}diff --git a/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/CsvAdjacencyListGraphExporter.java b/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/CsvAdjacencyListGraphExporter.javanew file mode 100644index 0000000000..58a662afc0--- /dev/null+++ b/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/CsvAdjacencyListGraphExporter.java@@ -0,0 +1,58 @@+/* ###+ * 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.graph.exporter;++import java.io.File;+import java.io.IOException;++import org.jgrapht.nio.csv.CSVExporter;+import org.jgrapht.nio.csv.CSVFormat;++import ghidra.service.graph.*;++public class CsvAdjacencyListGraphExporter extends AbstractAttributedGraphExporter {++ private static final char CVS_DELIMITER = ',';++ @Override+ public void exportGraph(AttributedGraph graph, File file) throws IOException {+ CSVExporter<AttributedVertex, AttributedEdge> exporter =+ new CSVExporter<>(vertexIdProvider, CSVFormat.ADJACENCY_LIST, CVS_DELIMITER);++ try {+ exporter.exportGraph(graph, file);+ }+ catch (Exception e) {+ throw new IOException(e);+ }+ }++ @Override+ public String getFileExtension() {+ return "csv";+ }++ @Override+ public String getName() {+ return "CSV";+ }++ @Override+ public String getDesciption() {+ return "JGraphT library export of a graph to a adjacency list CSV file";+ }++}diff --git a/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/CsvEdgeListGraphExporter.java b/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/CsvEdgeListGraphExporter.javanew file mode 100644index 0000000000..2bceb7949c--- /dev/null+++ b/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/CsvEdgeListGraphExporter.java@@ -0,0 +1,58 @@+/* ###+ * 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.graph.exporter;++import java.io.File;+import java.io.IOException;++import org.jgrapht.nio.csv.CSVExporter;+import org.jgrapht.nio.csv.CSVFormat;++import ghidra.service.graph.*;++public class CsvEdgeListGraphExporter extends AbstractAttributedGraphExporter {++ private static final char CVS_DELIMITER = ',';++ @Override+ public void exportGraph(AttributedGraph graph, File file) throws IOException {+ CSVExporter<AttributedVertex, AttributedEdge> exporter =+ new CSVExporter<>(vertexIdProvider, CSVFormat.EDGE_LIST, CVS_DELIMITER);++ try {+ exporter.exportGraph(graph, file);+ }+ catch (Exception e) {+ throw new IOException(e);+ }+ }++ @Override+ public String getFileExtension() {+ return "csv";+ }++ @Override+ public String getName() {+ return "CSV";+ }++ @Override+ public String getDesciption() {+ return "JGraphT library export of a graph to a edge list CSV file";+ }++}diff --git a/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/DimacsGraphExporter.java b/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/DimacsGraphExporter.javanew file mode 100644index 0000000000..d272359fcb--- /dev/null+++ b/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/DimacsGraphExporter.java@@ -0,0 +1,59 @@+/* ###+ * 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.graph.exporter;++import java.io.File;+import java.io.IOException;++import org.jgrapht.nio.dimacs.DIMACSExporter;+import org.jgrapht.nio.dimacs.DIMACSFormat;++import ghidra.service.graph.*;++public class DimacsGraphExporter extends AbstractAttributedGraphExporter {++ protected DIMACSFormat dimacsFormat = DIMACSExporter.DEFAULT_DIMACS_FORMAT;+++ @Override+ public void exportGraph(AttributedGraph graph, File file) throws IOException {+ DIMACSExporter<AttributedVertex, AttributedEdge> exporter =+ new DIMACSExporter<>(vertexIdProvider, dimacsFormat);++ try {+ exporter.exportGraph(graph, file);+ }+ catch (Exception e) {+ throw new IOException(e);+ }+ }++ @Override+ public String getFileExtension() {+ return "col";+ }++ @Override+ public String getName() {+ return "DIMACS";+ }++ @Override+ public String getDesciption() {+ return "JGraphT library export of a graph to a DIMACS file";+ }++}diff --git a/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/DotGraphExporter.java b/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/DotGraphExporter.javanew file mode 100644index 0000000000..53e8a0583b--- /dev/null+++ b/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/DotGraphExporter.java@@ -0,0 +1,68 @@+/* ###+ * 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.graph.exporter;++import java.io.File;+import java.io.IOException;++import org.jgrapht.nio.dimacs.DIMACSExporter;+import org.jgrapht.nio.dimacs.DIMACSFormat;+import org.jgrapht.nio.dot.DOTExporter;++import ghidra.service.graph.*;++public class DotGraphExporter extends AbstractAttributedGraphExporter {++ protected DIMACSFormat dimacsFormat = DIMACSExporter.DEFAULT_DIMACS_FORMAT;+++ @Override+ public void exportGraph(AttributedGraph graph, File file) throws IOException {+ DOTExporter<AttributedVertex, AttributedEdge> exporter =+ new DOTExporter<>(this::getQuotedId);++ exporter.setVertexAttributeProvider(this::getAttributes);+ exporter.setEdgeAttributeProvider(this::getAttributes);+ exporter.setGraphIdProvider(graphIdProvider);++ try {+ exporter.exportGraph(graph, file);+ }+ catch (Exception e) {+ throw new IOException(e);+ }+ }++ @Override+ public String getFileExtension() {+ return "gf";+ }++ @Override+ public String getName() {+ return "DOT";+ }++ @Override+ public String getDesciption() {+ return "JGraphT library export of a graph to a DOT file";+ }++ String getQuotedId(AttributedVertex vertex) {+ String id = vertexIdProvider.apply(vertex);+ return "\"" + id + "\"";+ }+}diff --git a/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/GmlGraphExporter.java b/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/GmlGraphExporter.javanew file mode 100644index 0000000000..a276d9a42e--- /dev/null+++ b/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/GmlGraphExporter.java@@ -0,0 +1,57 @@+/* ###+ * 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.graph.exporter;++import java.io.File;+import java.io.IOException;++import org.jgrapht.nio.gml.GmlExporter;++import ghidra.service.graph.*;++public class GmlGraphExporter extends AbstractAttributedGraphExporter {++ @Override+ public void exportGraph(AttributedGraph graph, File file) throws IOException {+ GmlExporter<AttributedVertex, AttributedEdge> exporter =+ new GmlExporter<>(vertexIdProvider);++ exporter.setEdgeIdProvider(edgeIdProvider);++ try {+ exporter.exportGraph(graph, file);+ }+ catch (Exception e) {+ throw new IOException(e);+ }+ }++ @Override+ public String getFileExtension() {+ return "gml";+ }++ @Override+ public String getName() {+ return "GML";+ }++ @Override+ public String getDesciption() {+ return "JGraphT library export of a graph to a GML file";+ }++}diff --git a/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/GraphMlGraphExporter.java b/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/GraphMlGraphExporter.javanew file mode 100644index 0000000000..e8fa94375e--- /dev/null+++ b/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/GraphMlGraphExporter.java@@ -0,0 +1,56 @@+/* ###+ * 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.graph.exporter;++import java.io.File;+import java.io.IOException;++import org.jgrapht.nio.graphml.GraphMLExporter;++import ghidra.service.graph.*;++public class GraphMlGraphExporter extends AbstractAttributedGraphExporter {++ @Override+ public void exportGraph(AttributedGraph graph, File file) throws IOException {+ GraphMLExporter<AttributedVertex, AttributedEdge> exporter =+ new GraphMLExporter<>(vertexIdProvider);++ exporter.setEdgeIdProvider(edgeIdProvider);+ try {+ exporter.exportGraph(graph, file);+ }+ catch (Exception e) {+ throw new IOException(e);+ }+ }++ @Override+ public String getFileExtension() {+ return "graphml";+ }++ @Override+ public String getName() {+ return "GRAPHML";+ }++ @Override+ public String getDesciption() {+ return "JGraphT library export of a graph to a GRAPHML file";+ }++}diff --git a/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/JsonGraphExporter.java b/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/JsonGraphExporter.javanew file mode 100644index 0000000000..5c49a9ce34--- /dev/null+++ b/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/JsonGraphExporter.java@@ -0,0 +1,58 @@+/* ###+ * 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.graph.exporter;++import java.io.File;+import java.io.IOException;++import org.jgrapht.nio.json.JSONExporter;++import ghidra.service.graph.*;++public class JsonGraphExporter extends AbstractAttributedGraphExporter {++ @Override+ public void exportGraph(AttributedGraph graph, File file) throws IOException {+ JSONExporter<AttributedVertex, AttributedEdge> exporter =+ new JSONExporter<>(vertexIdProvider);++ exporter.setVertexAttributeProvider(this::getAttributes);+ exporter.setEdgeAttributeProvider(this::getAttributes);+ exporter.setEdgeIdProvider(edgeIdProvider);+ try {+ exporter.exportGraph(graph, file);+ }+ catch (Exception e) {+ throw new IOException(e);+ }+ }++ @Override+ public String getFileExtension() {+ return "json";+ }++ @Override+ public String getName() {+ return "JSON";+ }++ @Override+ public String getDesciption() {+ return "JGraphT library export of a graph to a JSON file";+ }++}diff --git a/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/MatrixGraphExporter.java b/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/MatrixGraphExporter.javanew file mode 100644index 0000000000..1d07abb22e--- /dev/null+++ b/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/MatrixGraphExporter.java@@ -0,0 +1,57 @@+/* ###+ * 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.graph.exporter;++import java.io.File;+import java.io.IOException;++import org.jgrapht.nio.matrix.MatrixExporter;++import ghidra.service.graph.*;++public class MatrixGraphExporter extends AbstractAttributedGraphExporter {+ private static final MatrixExporter.Format MATRIX_FORMAT =+ MatrixExporter.Format.SPARSE_ADJACENCY_MATRIX;++ @Override+ public void exportGraph(AttributedGraph graph, File file) throws IOException {+ MatrixExporter<AttributedVertex, AttributedEdge> exporter =+ new MatrixExporter<>(MATRIX_FORMAT, vertexIdProvider);++ try {+ exporter.exportGraph(graph, file);+ }+ catch (Exception e) {+ throw new IOException(e);+ }+ }++ @Override+ public String getFileExtension() {+ return "g";+ }++ @Override+ public String getName() {+ return "MATRIX";+ }++ @Override+ public String getDesciption() {+ return "JGraphT library export of a graph to a MATRIX file";+ }++}diff --git a/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/VisioGraphExporter.java b/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/VisioGraphExporter.javanew file mode 100644index 0000000000..accc2442f2--- /dev/null+++ b/Ghidra/Features/GraphServices/src/main/java/ghidra/graph/exporter/VisioGraphExporter.java@@ -0,0 +1,55 @@+/* ###+ * 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.graph.exporter;++import java.io.File;+import java.io.IOException;++import org.jgrapht.nio.csv.VisioExporter;++import ghidra.service.graph.*;++public class VisioGraphExporter extends AbstractAttributedGraphExporter {++ @Override+ public void exportGraph(AttributedGraph graph, File file) throws IOException {+ VisioExporter<AttributedVertex, AttributedEdge> exporter =+ new VisioExporter<>(vertexIdProvider);++ try {+ exporter.exportGraph(graph, file);+ }+ catch (Exception e) {+ throw new IOException(e);+ }+ }++ @Override+ public String getFileExtension() {+ return "vsd";+ }++ @Override+ public String getName() {+ return "VISIO";+ }++ @Override+ public String getDesciption() {+ return "JGraphT library export of a graph to a VISIO file";+ }++}diff --git a/Ghidra/Features/GraphServices/src/test/java/ghidra/graph/export/AttributedGraphExportersTest.java b/Ghidra/Features/GraphServices/src/test/java/ghidra/graph/export/AttributedGraphExportersTest.javanew file mode 100644index 0000000000..289d2285d0--- /dev/null+++ b/Ghidra/Features/GraphServices/src/test/java/ghidra/graph/export/AttributedGraphExportersTest.java@@ -0,0 +1,327 @@+/* ###+ * 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.graph.export;++import static org.junit.Assert.*;++import java.io.File;+import java.io.IOException;+import java.util.List;++import org.junit.*;++import generic.test.AbstractGenericTest;+import ghidra.graph.exporter.*;+import ghidra.service.graph.*;+import ghidra.util.Msg;+import utilities.util.FileUtilities;++public class AttributedGraphExportersTest extends AbstractGenericTest {++ private AttributedGraph graph;++ @Before+ public void setUp() throws Exception {++ graph = createGraph();+ }++ @After+ public void tearDown() {+ }++ @Test+ public void testCsvEdgeList() throws Exception {+ CsvEdgeListGraphExporter exporter = new CsvEdgeListGraphExporter();+ List<String> lines = doExport(exporter, graph);++ assertOutput(lines,+ "A,B",+ "B,C",+ "B,D",+ "C,E",+ "D,E");+ }++ @Test+ public void testCsvAdjacencyList() throws Exception {+ CsvAdjacencyListGraphExporter exporter = new CsvAdjacencyListGraphExporter();+ List<String> lines = doExport(exporter, graph);++ assertOutput(lines,+ "A,B",+ "B,C,D",+ "C,E",+ "D,E",+ "E",+ "F");+ }++ @Test+ public void testDIMACS() throws Exception {+ DimacsGraphExporter exporter = new DimacsGraphExporter();+ List<String> lines = doExport(exporter, graph);+ assertOutput(lines,+ "c",+ "c SOURCE: Generated using the JGraphT library",+ "c",+ "p edge 6 5",+ "e A B",+ "e B C",+ "e B D",+ "e C E",+ "e D E");+ }++ @Test+ public void testDOT() throws Exception {+ DotGraphExporter exporter = new DotGraphExporter();+ List<String> lines = doExport(exporter, graph);++ assertOutput(lines,+ "digraph Ghidra {",+ " \"A\" [ Type=\"X\" Inverted=\"true\" Name=\"A\" ];",+ " \"B\" [ Type=\"Y\" Name=\"B\" ];",+ " \"C\" [ Type=\"Y\" Name=\"C\" ];",+ " \"D\" [ Type=\"Y\" Name=\"D\" ];",+ " \"E\" [ Type=\"Z\" Name=\"E\" ];",+ " \"F\" [ Type=\"T\" Name=\"F\" ];",+ " \"A\" -> \"B\" [ EType=\"Fall\" ];",+ " \"B\" -> \"C\" [ EType=\"JMP\" ];",+ " \"B\" -> \"D\" [ EType=\"Fall\" ];",+ " \"C\" -> \"E\" [ EType=\"Fall\" ];",+ " \"D\" -> \"E\" [ EType=\"Call\" ];",+ "}");++ }++ @Test+ public void testGraphML() throws Exception {+ GmlGraphExporter exporter = new GmlGraphExporter();+ List<String> lines = doExport(exporter, graph);+ assertOutput(lines,+ "Creator \"JGraphT GML Exporter\"",+ "Version 1",+ "graph",+ "[",+ " label \"\"",+ " directed 1",+ " node",+ " [",+ " id A",+ " ]",+ " node",+ " [",+ " id B",+ " ]",+ " node",+ " [",+ " id C",+ " ]",+ " node",+ " [",+ " id D",+ " ]",+ " node",+ " [",+ " id E",+ " ]",+ " node",+ " [",+ " id F",+ " ]",+ " edge",+ " [",+ " id 1",+ " source A",+ " target B",+ " ]",+ " edge",+ " [",+ " id 2",+ " source B",+ " target C",+ " ]",+ " edge",+ " [",+ " id 3",+ " source B",+ " target D",+ " ]",+ " edge",+ " [",+ " id 4",+ " source C",+ " target E",+ " ]",+ " edge",+ " [",+ " id 5",+ " source D",+ " target E",+ " ]",+ "]");+ }++ @Test+ public void testGRAPHML() throws Exception {+ GraphMlGraphExporter exporter = new GraphMlGraphExporter();+ List<String> lines = doExport(exporter, graph);+ assertOutput(lines,+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?><graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\" xsi:schemaLocation=\"http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">",+ " <graph edgedefault=\"directed\">",+ " <node id=\"A\"/>",+ " <node id=\"B\"/>",+ " <node id=\"C\"/>",+ " <node id=\"D\"/>",+ " <node id=\"E\"/>",+ " <node id=\"F\"/>",+ " <edge id=\"1\" source=\"A\" target=\"B\"/>",+ " <edge id=\"2\" source=\"B\" target=\"C\"/>",+ " <edge id=\"3\" source=\"B\" target=\"D\"/>",+ " <edge id=\"4\" source=\"C\" target=\"E\"/>",+ " <edge id=\"5\" source=\"D\" target=\"E\"/>",+ " </graph>",+ "</graphml>");++ }++ @Test+ public void testJSON() throws Exception {+ JsonGraphExporter exporter = new JsonGraphExporter();+ List<String> lines = doExport(exporter, graph);+ assertOutput(lines,+ "{\"creator\":\"JGraphT JSON Exporter\",\"version\":\"1\",\"nodes\":" ++ "[{\"id\":\"A\",\"Type\":\"X\",\"Inverted\":\"true\",\"Name\":\"A\"}," ++ "{\"id\":\"B\",\"Type\":\"Y\",\"Name\":\"B\"}," ++ "{\"id\":\"C\",\"Type\":\"Y\",\"Name\":\"C\"}," ++ "{\"id\":\"D\",\"Type\":\"Y\",\"Name\":\"D\"}," ++ "{\"id\":\"E\",\"Type\":\"Z\",\"Name\":\"E\"}," ++ "{\"id\":\"F\",\"Type\":\"T\",\"Name\":\"F\"}]," ++ "\"edges\":[{\"id\":\"1\",\"source\":\"A\",\"target\":\"B\",\"EType\":\"Fall\"}," ++ "{\"id\":\"2\",\"source\":\"B\",\"target\":\"C\",\"EType\":\"JMP\"}," ++ "{\"id\":\"3\",\"source\":\"B\",\"target\":\"D\",\"EType\":\"Fall\"}," ++ "{\"id\":\"4\",\"source\":\"C\",\"target\":\"E\",\"EType\":\"Fall\"}," ++ "{\"id\":\"5\",\"source\":\"D\",\"target\":\"E\",\"EType\":\"Call\"}]}");++ }++ @Test+ public void testMATRIX() throws Exception {+ MatrixGraphExporter exporter = new MatrixGraphExporter();+ List<String> lines = doExport(exporter, graph);+ assertOutput(lines,+ "A B 1",+ "B C 1",+ "B D 1",+ "C E 1",+ "D E 1");+ }++ @Test+ public void testVISIO() throws Exception {+ VisioGraphExporter exporter = new VisioGraphExporter();+ List<String> lines = doExport(exporter, graph);+ assertOutput(lines,+ "Shape,A,,A",+ "Shape,B,,B",+ "Shape,C,,C",+ "Shape,D,,D",+ "Shape,E,,E",+ "Shape,F,,F",+ "Link,A-->B,,,A,B",+ "Link,B-->C,,,B,C",+ "Link,B-->D,,,B,D",+ "Link,C-->E,,,C,E",+ "Link,D-->E,,,D,E");+ }++ private AttributedGraph createGraph() {+ AttributedGraph g = new AttributedGraph();+ AttributedVertex vA = g.addVertex("A");+ AttributedVertex vB = g.addVertex("B");+ AttributedVertex vC = g.addVertex("C");+ AttributedVertex vD = g.addVertex("D");+ AttributedVertex vE = g.addVertex("E");+ AttributedVertex vF = g.addVertex("F");++ // A+ // |+ // B+ // / \+ // C D F+ // \ /+ // E++ AttributedEdge e1 = g.addEdge(vA, vB);+ AttributedEdge e2 = g.addEdge(vB, vC);+ AttributedEdge e3 = g.addEdge(vB, vD);+ AttributedEdge e4 = g.addEdge(vC, vE);+ AttributedEdge e5 = g.addEdge(vD, vE);++ vA.setAttribute("Type", "X");+ vB.setAttribute("Type", "Y");+ vC.setAttribute("Type", "Y");+ vD.setAttribute("Type", "Y");+ vE.setAttribute("Type", "Z");+ vF.setAttribute("Type", "T");++ e1.setAttribute("EType", "Fall");+ e2.setAttribute("EType", "JMP");+ e3.setAttribute("EType", "Fall");+ e4.setAttribute("EType", "Fall");+ e5.setAttribute("EType", "Call");++ vA.setAttribute("Inverted", "true");+ return g;+ }++ private void printLines(List<String> lines) {+ Msg.debug(this, "\n" + testName.getMethodName());+ for (String line : lines) {+ Msg.debug(this, "\"" + line + "\",");+ }+ }++ private void assertOutput(List<String> actual, String... expected) {+ assertEquals(expected.length, actual.size());+ try {+ for (int i = 0; i < expected.length; i++) {+ if (i >= actual.size()) {+ fail(testName.getMethodName() + ": output line " + (i + 1) + ": expected :\"" ++ expected[i] ++ "\", got: EOF");+ }+ assertEquals(testName.getMethodName() + ": output line " + (i + 1) + ": ",+ expected[i],+ actual.get(i));+ }+ }+ catch (Throwable e) {+ printLines(actual);+ throw e;+ }+ }++ private List<String> doExport(AttributedGraphExporter exporter, AttributedGraph graph2)+ throws IOException {+ File file = createTempFile("GraphTest", "." + exporter.getFileExtension());+ exporter.exportGraph(graph, file);+ List<String> lines = FileUtilities.getLines(file);+ return lines;+ }++}diff --git a/Ghidra/Framework/Graph/src/main/java/ghidra/service/graph/AttributedGraph.java b/Ghidra/Framework/Graph/src/main/java/ghidra/service/graph/AttributedGraph.javaindex 8e59e08090..3b9bb49887 100644--- a/Ghidra/Framework/Graph/src/main/java/ghidra/service/graph/AttributedGraph.java+++ b/Ghidra/Framework/Graph/src/main/java/ghidra/service/graph/AttributedGraph.java@@ -222,21 +222,27 @@ public class AttributedGraph extends AbstractBaseGraph<AttributedVertex, Attribureturn Integer.toString(weight);}+ /**+ * Default VertexSupplier that uses a simple one up number for default vertex ids+ */private static class VertexSupplier implements Supplier<AttributedVertex> {- long id = 0;+ long nextId = 1;@Overridepublic AttributedVertex get() {- return new AttributedVertex(Long.toString(id++));+ return new AttributedVertex(Long.toString(nextId++));}}+ /**+ * Default EdgeSupplier that uses a simple one up number for default edge ids+ */private static class EdgeSupplier implements Supplier<AttributedEdge> {- long id = 0;+ long nextId = 1;@Overridepublic AttributedEdge get() {- return new AttributedEdge(Long.toString(id++));+ return new AttributedEdge(Long.toString(nextId++));}}}diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/service/graph/AttributedGraphExporter.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/service/graph/AttributedGraphExporter.javanew file mode 100644index 0000000000..ed0866897b--- /dev/null+++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/service/graph/AttributedGraphExporter.java@@ -0,0 +1,53 @@+/* ###+ * 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.service.graph;++import java.io.File;+import java.io.IOException;++import ghidra.util.classfinder.ExtensionPoint;++/**+ * Interface for exporting AttributedGraphs+ */+public interface AttributedGraphExporter extends ExtensionPoint {+ /**+ * Exports the given graph to the given writer+ * @param graph the {@link AttributedGraph} to export+ * @param file the file to export to+ * @throws IOException if there is an error exporting the graph+ */+ public void exportGraph(AttributedGraph graph, File file) throws IOException;++ /**+ * Returns the suggested file extension to use for this exporter+ * @return the suggested file extension to use for this exporter+ */+ public String getFileExtension();++ /**+ * Returns the name of this exporter+ * @return the name of this exporter+ */+ public String getName();++ /**+ * Returns a description of the exporter+ * @return a description of the exporter+ */+ public String getDesciption();++}diff --git a/Ghidra/Features/GraphServices/src/test/java/ghidra/graph/export/GraphExportTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/graph/export/GraphExportTest.javasimilarity index 83%rename from Ghidra/Features/GraphServices/src/test/java/ghidra/graph/export/GraphExportTest.javarename to Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/graph/export/GraphExportTest.javaindex 28bd9f4369..88493f86c4 100644--- a/Ghidra/Features/GraphServices/src/test/java/ghidra/graph/export/GraphExportTest.java+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/graph/export/GraphExportTest.java@@ -30,11 +30,13 @@ import ghidra.app.services.BlockModelService;import ghidra.app.services.GraphDisplayBroker;import ghidra.framework.plugintool.PluginTool;import ghidra.framework.plugintool.util.PluginException;+import ghidra.graph.exporter.*;import ghidra.program.database.ProgramDB;import ghidra.service.graph.*;import ghidra.test.AbstractGhidraHeadedIntegrationTest;import ghidra.test.TestEnv;import ghidra.util.Msg;+import ghidra.util.exception.CancelledException;import ghidra.util.task.TaskMonitor;import utilities.util.FileUtilities;@@ -60,10 +62,20 @@ public class GraphExportTest extends AbstractGhidraHeadedIntegrationTest {AttributedGraph graph = createGraph();GraphDisplay exporter = exportProvider.getGraphDisplay(false, TaskMonitor.DUMMY);- exporter.setGraph(graph, "Test", false, TaskMonitor.DUMMY);+ // run in swing so the test is not blocked when we mess with the dialog.+ runSwing(() -> setGraph(graph, exporter), false);waitForSwing();}+ private void setGraph(AttributedGraph graph, GraphDisplay exporter) {+ try {+ exporter.setGraph(graph, "Test", false, TaskMonitor.DUMMY);+ }+ catch (CancelledException e) {+ // can't happen with dummy+ }+ }+@Afterpublic void tearDown() {env.dispose();@@ -71,7 +83,7 @@ public class GraphExportTest extends AbstractGhidraHeadedIntegrationTest {@Testpublic void testCSV() throws Exception {- List<String> lines = processDialog(GraphExportFormat.CSV);+ List<String> lines = processDialog(new CsvEdgeListGraphExporter());assertOutput(lines,"A,B",@@ -83,7 +95,7 @@ public class GraphExportTest extends AbstractGhidraHeadedIntegrationTest {@Testpublic void testDIMACS() throws Exception {- List<String> lines = processDialog(GraphExportFormat.DIMACS);+ List<String> lines = processDialog(new DimacsGraphExporter());assertOutput(lines,"c","c SOURCE: Generated using the JGraphT library",@@ -98,26 +110,27 @@ public class GraphExportTest extends AbstractGhidraHeadedIntegrationTest {@Testpublic void testDOT() throws Exception {- List<String> lines = processDialog(GraphExportFormat.DOT);+ List<String> lines = processDialog(new DotGraphExporter());assertOutput(lines,+"digraph Ghidra {",- " A [ Type=\"X\" Inverted=\"true\" Name=\"A\" ];",- " B [ Type=\"Y\" Name=\"B\" ];",- " C [ Type=\"Y\" Name=\"C\" ];",- " D [ Type=\"Y\" Name=\"D\" ];",- " E [ Type=\"Z\" Name=\"E\" ];",- " A -> B [ EType=\"Fall\" ];",- " B -> C [ EType=\"JMP\" ];",- " B -> D [ EType=\"Fall\" ];",- " C -> E [ EType=\"Fall\" ];",- " D -> E [ EType=\"Call\" ];",+ " \"A\" [ Type=\"X\" Inverted=\"true\" Name=\"A\" ];",+ " \"B\" [ Type=\"Y\" Name=\"B\" ];",+ " \"C\" [ Type=\"Y\" Name=\"C\" ];",+ " \"D\" [ Type=\"Y\" Name=\"D\" ];",+ " \"E\" [ Type=\"Z\" Name=\"E\" ];",+ " \"A\" -> \"B\" [ EType=\"Fall\" ];",+ " \"B\" -> \"C\" [ EType=\"JMP\" ];",+ " \"B\" -> \"D\" [ EType=\"Fall\" ];",+ " \"C\" -> \"E\" [ EType=\"Fall\" ];",+ " \"D\" -> \"E\" [ EType=\"Call\" ];","}");}@Testpublic void testGML() throws Exception {- List<String> lines = processDialog(GraphExportFormat.GML);+ List<String> lines = processDialog(new GmlGraphExporter());assertOutput(lines,"Creator \"JGraphT GML Exporter\"","Version 1",@@ -180,7 +193,7 @@ public class GraphExportTest extends AbstractGhidraHeadedIntegrationTest {@Testpublic void testGRAPHML() throws Exception {- List<String> lines = processDialog(GraphExportFormat.GRAPHML);+ List<String> lines = processDialog(new GraphMlGraphExporter());assertOutput(lines,"<?xml version=\"1.0\" encoding=\"UTF-8\"?><graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\" xsi:schemaLocation=\"http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"," <graph edgedefault=\"directed\">",@@ -201,7 +214,7 @@ public class GraphExportTest extends AbstractGhidraHeadedIntegrationTest {@Testpublic void testJSON() throws Exception {- List<String> lines = processDialog(GraphExportFormat.JSON);+ List<String> lines = processDialog(new JsonGraphExporter());assertOutput(lines,"{\"creator\":\"JGraphT JSON Exporter\",\"version\":\"1\",\"nodes\":" +"[{\"id\":\"A\",\"Type\":\"X\",\"Inverted\":\"true\",\"Name\":\"A\"}," +@@ -217,35 +230,10 @@ public class GraphExportTest extends AbstractGhidraHeadedIntegrationTest {}- @Test- public void testLEMON() throws Exception {- List<String> lines = processDialog(GraphExportFormat.LEMON);-- assertOutput(lines,- "#Creator: JGraphT Lemon (LGF) Exporter",- "#Version: 1",- "",- "@nodes",- "label",- "A",- "B",- "C",- "D",- "E",- "",- "@arcs",- " -",- "A B",- "B C",- "B D",- "C E",- "D E",- "");- }@Testpublic void testMATRIX() throws Exception {- List<String> lines = processDialog(GraphExportFormat.MATRIX);+ List<String> lines = processDialog(new MatrixGraphExporter());assertOutput(lines,"A B 1","B C 1",@@ -256,7 +244,7 @@ public class GraphExportTest extends AbstractGhidraHeadedIntegrationTest {@Testpublic void testVISIO() throws Exception {- List<String> lines = processDialog(GraphExportFormat.VISIO);+ List<String> lines = processDialog(new VisioGraphExporter());assertOutput(lines,"Shape,A,,A","Shape,B,,B",@@ -281,12 +269,12 @@ public class GraphExportTest extends AbstractGhidraHeadedIntegrationTest {tool.addPlugin(GraphDisplayBrokerPlugin.class.getName());}- private List<String> processDialog(GraphExportFormat format) throws IOException {+ private List<String> processDialog(AttributedGraphExporter exporter) throws IOException {dialog = getDialogComponent(GraphExporterDialog.class);String filePath =- createTempFilePath("GraphExportTest", "." + format.getDefaultFileExtension());+ createTempFilePath("GraphExportTest", "." + exporter.getFileExtension());runSwing(() -> dialog.setOutputFile(filePath));- dialog.setExportFormat(format);+ dialog.setExporter(exporter);pressButtonByText(dialog, "OK");List<String> lines = FileUtilities.getLines(new File(filePath));return lines;