Ghidra is a software reverse engineering (SRE) framework
replace +- buttons in bundlestatus gui with toolbar actions
Jason P. Leasure0383926fc368
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleCompiler.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleCompiler.javaindex df90f4b8d0..e4151b1e43 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleCompiler.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleCompiler.java@@ -60,9 +60,6 @@ public class BundleCompiler {throws IOException, OSGiException {sb.compileAttempted();- sb.setSummary(String.format("build %d files, skipping %d%s", sb.getNewSourcesCount(),- sb.getFailingSourcesCount(), sb.newManifestFile() ? ", new manifest" : ""));-ResourceFile srcdir = sb.getSourceDir();Path bindir = sb.getBinDir();Files.createDirectories(bindir);@@ -98,7 +95,7 @@ public class BundleCompiler {}sb.setSummary(- String.format("%d missing @import%s:", reqs.size(), reqs.size() > 1 ? "s" : "",+ String.format("%d missing @import%s:%s", reqs.size(), reqs.size() > 1 ? "s" : "",reqs.stream().flatMap(r -> OSGiUtils.extractPackages(r.toString()).stream()).distinct().collect(Collectors.joining(","))));@@ -106,16 +103,12 @@ public class BundleCompiler {else {sb.setSummary("");}- // XXX add sources that will fail to call attention- List<ResourceFile> newSource = sb.getNewSources();- for (BundleRequirement req : reqs) {- newSource.addAll(sb.req2file.get(req.toString()));- }+ List<ResourceFile> newSources = sb.getNewSources();// send the capabilities to phidiasbundleWirings.forEach(bjm::addBundleWiring);- final List<ResourceFileJavaFileObject> sourceFiles = newSource.stream().map(+ final List<ResourceFileJavaFileObject> sourceFiles = newSources.stream().map(sf -> new ResourceFileJavaFileObject(sf.getParentFile(), sf, Kind.SOURCE)).collect(Collectors.toList());@@ -144,21 +137,13 @@ public class BundleCompiler {sb.buildError(rf, err); // remember all errors for this fileif (sourceFiles.remove(sf)) {writer.printf("skipping %s\n", sf.toString());- // if it's a script, mark it for having compile errors- if (GhidraScriptUtil.containsMetadata(rf)) {- ScriptInfo info = GhidraScriptUtil.getScriptInfo(rf);- info.setCompileErrors(true);- }}}}// mark the successful compilationsfor (ResourceFileJavaFileObject sf : sourceFiles) {ResourceFile rf = sf.getFile();- if (GhidraScriptUtil.containsMetadata(rf)) {- ScriptInfo info = GhidraScriptUtil.getScriptInfo(rf);- info.setCompileErrors(false);- }+ sb.buildSuccess(rf);}// buildErrors is now up to date, set statusif (sb.getFailingSourcesCount() > 0) {diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleHost.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleHost.javaindex dd699d95e1..746873a6eb 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleHost.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleHost.java@@ -15,8 +15,6 @@*/package ghidra.app.plugin.core.osgi;-import static java.util.stream.Collectors.*;-import java.io.*;import java.net.URL;import java.nio.file.*;@@ -111,7 +109,7 @@ public class BundleHost {/*** cache of data corresponding to a source directory that is bound to be an exploded bundle*/- protected static class BuildFailure {+ public static class BuildFailure {long when = -1;StringBuilder message = new StringBuilder();}@@ -452,67 +450,6 @@ public class BundleHost {return felix;}- public interface DiscrepencyCallback {- void found(ResourceFile source_file, Collection<Path> class_files) throws Throwable;- }-- public static void visitDiscrepencies(ResourceFile srcdir, Path bindir,- DiscrepencyCallback new_source_cb) {- try {- // delete class files for which java is either newer, or no longer exists- Deque<ResourceFile> stack = new ArrayDeque<>();- stack.add(srcdir);- while (!stack.isEmpty()) {- ResourceFile sd = stack.pop();- String relpath = sd.getAbsolutePath().substring(srcdir.getAbsolutePath().length());- if (relpath.startsWith(File.separator)) {- relpath = relpath.substring(1);- }- Path bd = bindir.resolve(relpath);-- // index the class files in the corresponding directory by basename- Map<String, List<Path>> binfiles =- Files.exists(bd) ? Files.list(bd).filter(x -> Files.isRegularFile(x) &&- x.getFileName().toString().endsWith(".class")).collect(groupingBy(x -> {- String s = x.getFileName().toString();- int money = s.indexOf('$');- if (money >= 0) {- return s.substring(0, money);- }- return s.substring(0, s.length() - 6);- })) : Collections.emptyMap();-- for (ResourceFile sf : sd.listFiles()) {- if (sf.isDirectory()) {- stack.push(sf);- }- else {- String n = sf.getName();- if (n.endsWith(".java")) {- long sfl = sf.lastModified();- List<Path> bfs = binfiles.remove(n.substring(0, n.length() - 5));- long bfl = (bfs == null || bfs.isEmpty()) ? -1- : bfs.stream().mapToLong(- bf -> bf.toFile().lastModified()).min().getAsLong();- if (sfl > bfl) {- new_source_cb.found(sf, bfs);- }- }- }- }- // any remaining .class files are missing .java files- if (!binfiles.isEmpty()) {- new_source_cb.found(null,- binfiles.values().stream().flatMap(l -> l.stream()).collect(- Collectors.toList()));- }- }- }- catch (Throwable t) {- t.printStackTrace();- }- }-// from https://dzone.com/articles/locate-jar-classpath-givenstatic String findJarForClass(Class<?> c) {final URL location;@@ -583,10 +520,10 @@ public class BundleHost {List<OSGiListener> osgiListeners = new ArrayList<>();- void fireSourceBundleCompiled(GhidraSourceBundle sbi) {+ void fireBundleBuilt(GhidraBundle sbi) {synchronized (osgiListeners) {for (OSGiListener l : osgiListeners) {- l.sourceBundleCompiled(sbi);+ l.bundleBuilt(sbi);}}}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleStatusModel.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleStatusModel.javaindex a0fd5581d5..83353d5deb 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleStatusModel.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleStatusModel.java@@ -169,7 +169,7 @@ public class BundleStatusModel extends AbstractSortedTableModel<BundleStatus> {bundleHost.addListener(bundleListener = new OSGiListener() {@Override- public void sourceBundleCompiled(GhidraSourceBundle sb) {+ public void bundleBuilt(GhidraBundle sb) {BundleStatus bp = getStatus(sb.getBundleLoc());if (bp != null) {bp.setSummary(sb.getSummary());@@ -180,20 +180,23 @@ public class BundleStatusModel extends AbstractSortedTableModel<BundleStatus> {@Overridepublic void bundleActivationChange(Bundle b, boolean newActivation) {- BundleStatus bp = getStatus(b.getLocation());+ BundleStatus status = getStatus(b.getLocation());+ if (status == null) {+ Msg.showError(BundleStatusModel.this, provider.getComponent(),+ "bundle status error", "bundle has no status!");+ }if (newActivation) {- if (bp != null) {- bp.setActive(true);- int row = getRowIndex(bp);- fireTableRowsUpdated(row, row);- }+ GhidraBundle gb = bundleHost.getGhidraBundle(status.getPath());+ status.setActive(true);+ status.setSummary(gb.getSummary());+ int row = getRowIndex(status);+ fireTableRowsUpdated(row, row);}else {- if (bp != null) {- bp.setActive(false);- int row = getRowIndex(bp);- fireTableRowsUpdated(row, row);- }+ status.setActive(false);+ status.setSummary("");+ int row = getRowIndex(status);+ fireTableRowsUpdated(row, row);}}@@ -248,11 +251,13 @@ public class BundleStatusModel extends AbstractSortedTableModel<BundleStatus> {* @param readonly mark them all as readonly*/void addNewPaths(List<File> files, boolean enabled, boolean readonly) {+ int index = statuses.size();for (File f : files) {BundleStatus status = new BundleStatus(new ResourceFile(f), enabled, readonly);addStatus(status);}fireBundlesChanged();+ fireTableRowsInserted(index, files.size() - 1);}void remove(int[] selectedRows) {@@ -493,4 +498,12 @@ public class BundleStatusModel extends AbstractSortedTableModel<BundleStatus> {ss.putBooleans("BundleStatus_ENABLE", enableArr);ss.putBooleans("BundleStatus_READ", readonlyArr);}++ public List<BundleStatus> getRowObjects(int[] rowIndices) {+ List<BundleStatus> rows = new ArrayList<>(rowIndices.length);+ for (int i : rowIndices) {+ rows.add(statuses.get(i));+ }+ return rows;+ }}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleStatusProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleStatusProvider.javaindex b4322718dc..701a1ea816 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleStatusProvider.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleStatusProvider.java@@ -24,6 +24,8 @@ import javax.swing.*;import javax.swing.event.TableModelEvent;import javax.swing.table.TableColumn;+import docking.ActionContext;+import docking.action.*;import docking.widgets.filechooser.GhidraFileChooser;import docking.widgets.filechooser.GhidraFileChooserMode;import docking.widgets.table.*;@@ -37,6 +39,7 @@ import ghidra.util.exception.CancelledException;import ghidra.util.filechooser.GhidraFileChooserModel;import ghidra.util.filechooser.GhidraFileFilter;import ghidra.util.task.*;+import resources.Icons;import resources.ResourceManager;/**@@ -48,8 +51,6 @@ public class BundleStatusProvider extends ComponentProviderAdapter {private JPanel panel;private GTable bundleStatusTable;private final BundleStatusModel bundleStatusModel;- private JButton addButton;- private JButton removeButton;private Color selectionColor;private GhidraFileChooser fileChooser;private GhidraFileFilter filter;@@ -91,7 +92,9 @@ public class BundleStatusProvider extends ComponentProviderAdapter {this.fileChooser = null;build();+ //getTool().addComponentProvider(this, false);addToTool();+ createActions();}public BundleStatusModel getModel() {@@ -103,35 +106,19 @@ public class BundleStatusProvider extends ComponentProviderAdapter {selectionColor = new Color(204, 204, 255);- addButton = new JButton(ResourceManager.loadImage("images/Plus.png"));- addButton.setName("AddBundle");- addButton.setToolTipText("Display file chooser to add bundles to list");- addButton.addActionListener(e -> addButtonAction());- addButton.setFocusable(false);-- removeButton = new JButton(ResourceManager.loadImage("images/edit-delete.png"));- removeButton.setName("RemoveBundle");- removeButton.setToolTipText("Remove selected bundle(s) from list");- removeButton.addActionListener(e -> removeButtonAction());- removeButton.setFocusable(false);-- JPanel buttonPanel = new JPanel(new GridBagLayout());- GridBagConstraints gbc = new GridBagConstraints();- gbc.anchor = GridBagConstraints.CENTER;- gbc.insets = new Insets(0, 0, 0, 0);- gbc.gridx = 0;- gbc.gridy = 0;-- buttonPanel.add(addButton, gbc);- ++gbc.gridy;- buttonPanel.add(removeButton, gbc);-bundleStatusTable = new GTable(bundleStatusModel);bundleStatusTable.setName("BUNDLESTATUS_TABLE");bundleStatusTable.setSelectionBackground(selectionColor);bundleStatusTable.setSelectionForeground(Color.BLACK);bundleStatusTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);+ bundleStatusTable.getSelectionModel().addListSelectionListener(e -> {+ if (e.getValueIsAdjusting()) {+ return;+ }+ tool.contextChanged(BundleStatusProvider.this);+ });+// to allow custom cell renderersbundleStatusTable.setAutoCreateColumnsFromModel(false);@@ -197,29 +184,83 @@ public class BundleStatusProvider extends ComponentProviderAdapter {JScrollPane scrollPane = new JScrollPane(bundleStatusTable);scrollPane.getViewport().setBackground(bundleStatusTable.getBackground());- ListSelectionModel selModel = bundleStatusTable.getSelectionModel();- selModel.addListSelectionListener(e -> {- if (e.getValueIsAdjusting()) {- return;- }- updateButtonsEnabled();- });- updateButtonsEnabled();-- JPanel centerPanel = new JPanel(new BorderLayout());- centerPanel.add(scrollPane, BorderLayout.CENTER);- centerPanel.add(filterPanel, BorderLayout.SOUTH);- panel.add(centerPanel, BorderLayout.CENTER);- panel.add(buttonPanel, BorderLayout.EAST);+ panel.add(filterPanel, BorderLayout.SOUTH);+ panel.add(scrollPane, BorderLayout.CENTER);panel.setPreferredSize(new Dimension(800, 400));}- private void updateButtonsEnabled() {- int[] rows = bundleStatusTable.getSelectedRows();- removeButton.setEnabled(rows.length > 0);+ private void createActions() {+ DockingAction action;+ //++ action = new DockingAction("Clean", this.getName()) {+ @Override+ public void actionPerformed(ActionContext context) {+ int[] selectedRows = bundleStatusTable.getSelectedRows();+ for (BundleStatus o : bundleStatusModel.getRowObjects(selectedRows)) {+ bundleHost.getGhidraBundle(o.getPath()).clean();+ }+ }++ @Override+ public boolean isEnabledForContext(ActionContext context) {+ return bundleStatusTable.getSelectedRows().length > 0;+ }++ };+ action.setPopupMenuData(+ new MenuData(new String[] { "Clean bundle(s)" }, Icons.REFRESH_ICON, null));+ action.setToolBarData(new ToolBarData(Icons.REFRESH_ICON, null));++ action.setDescription("Clean selected bundles");+ action.setEnabled(false);+ getTool().addLocalAction(this, action);++ //+ action = new DockingAction("AddBundle", this.getName()) {+ @Override+ public void actionPerformed(ActionContext context) {+ addBundlesAction();+ }++ @Override+ public boolean isEnabledForContext(ActionContext context) {+ return true;+ }++ };+ action.setPopupMenuData(new MenuData(new String[] { "Add bundle" },+ ResourceManager.loadImage("images/Plus.png"), null));+ action.setToolBarData(new ToolBarData(ResourceManager.loadImage("images/Plus.png"), null));++ action.setDescription("Display file chooser to add bundles to list");+ action.setEnabled(true);+ getTool().addLocalAction(this, action);++ //+ action = new DockingAction("RemoveBundle", this.getName()) {+ @Override+ public void actionPerformed(ActionContext context) {+ removeBundlesAction();+ }++ @Override+ public boolean isEnabledForContext(ActionContext context) {+ return bundleStatusTable.getSelectedRows().length > 0;+ }++ };+ action.setPopupMenuData(new MenuData(new String[] { "Remove bundle(s)" },+ ResourceManager.loadImage("images/edit-delete.png"), null));+ action.setToolBarData(+ new ToolBarData(ResourceManager.loadImage("images/edit-delete.png"), null));++ action.setDescription("Remove selected bundles");+ action.setEnabled(true);+ getTool().addLocalAction(this, action);}- private void removeButtonAction() {+ private void removeBundlesAction() {int[] selectedRows = bundleStatusTable.getSelectedRows();if (selectedRows == null || selectedRows.length == 0) {return;@@ -236,10 +277,9 @@ public class BundleStatusProvider extends ComponentProviderAdapter {if (row >= 0) {bundleStatusTable.setRowSelectionInterval(row, row);}- updateButtonsEnabled();}- private void addButtonAction() {+ private void addBundlesAction() {if (fileChooser == null) {fileChooser = new GhidraFileChooser(panel);fileChooser.setMultiSelectionEnabled(true);@@ -287,6 +327,13 @@ public class BundleStatusProvider extends ComponentProviderAdapter {return panel;}+ /*+ @Override+ public ActionContext getActionContext(MouseEvent event) {+ return new ActionContext(this, bundleStatusTable.getSelectedRows(), bundleStatusTable);+ }+ */+public void dispose() {bundleStatusTable.dispose();}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/GhidraBundle.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/GhidraBundle.javaindex 074bb20700..063beecbe9 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/GhidraBundle.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/GhidraBundle.java@@ -13,6 +13,8 @@ public interface GhidraBundle {BndScript, Jar, SourceDir, INVALID}+ void clean();+/*** attempt to build loadable bundle, if possible*diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/GhidraSourceBundle.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/GhidraSourceBundle.javaindex 5e797ce92a..42aac70ee7 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/GhidraSourceBundle.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/GhidraSourceBundle.java@@ -15,10 +15,15 @@*/package ghidra.app.plugin.core.osgi;+import static java.util.stream.Collectors.*;+import java.io.*;import java.nio.file.Files;import java.nio.file.Path;import java.util.*;+import java.util.Map.Entry;+import java.util.function.Predicate;+import java.util.regex.Pattern;import java.util.stream.Collectors;import org.osgi.framework.Bundle;@@ -30,18 +35,22 @@ import generic.jar.ResourceFile;import ghidra.app.plugin.core.osgi.BundleHost.BuildFailure;import ghidra.app.script.GhidraScriptUtil;import ghidra.app.script.ScriptInfo;+import ghidra.util.Msg;/*** The SourceBundleInfo class is a cache of information for bundles built from source directories.*/public class GhidraSourceBundle implements GhidraBundle {+ public interface DiscrepencyCallback {+ void found(ResourceFile source_file, Collection<Path> class_files) throws Throwable;+ }+final private BundleHost bundleHost;final private ResourceFile sourceDir;final private String symbolicName;final private Path binDir;final private String bundleLoc;- boolean foundNewManifest;final List<ResourceFile> newSources = new ArrayList<>();final List<Path> oldBin = new ArrayList<>();@@ -97,12 +106,26 @@ public class GhidraSourceBundle implements GhidraBundle {return binDir;}- void buildError(ResourceFile rf, String err) {- BuildFailure f = buildErrors.computeIfAbsent(rf, x -> new BundleHost.BuildFailure());- f.when = rf.lastModified();+ void buildSuccess(ResourceFile sourceFile) {+ buildErrors.remove(sourceFile);+ }++ /**+ * append build error+ * @param sourceFile the file w/ errors+ * @param err an error string+ */+ void buildError(ResourceFile sourceFile, String err) {+ BuildFailure f =+ buildErrors.computeIfAbsent(sourceFile, x -> new BundleHost.BuildFailure());+ f.when = sourceFile.lastModified();f.message.append(err);}+ public BuildFailure getErrors(ResourceFile sourceFile) {+ return buildErrors.get(sourceFile);+ }+private String getPreviousBuildErrors() {return buildErrors.values().stream().map(e -> e.message.toString()).collect(Collectors.joining());@@ -112,7 +135,7 @@ public class GhidraSourceBundle implements GhidraBundle {* update buildReqs based on \@imports tag in java files from the default package* @throws GhidraBundleException on failure to parse the \@imports tag*/- private void computeRequirements() throws GhidraBundleException {+ private void updateRequirementsFromMetadata() throws GhidraBundleException {// parse metadata from all Java source in sourceDirbuildReqs.clear();req2file.clear();@@ -156,18 +179,12 @@ public class GhidraSourceBundle implements GhidraBundle {* @throws IOException while accessing manifest file* @throws OSGiException while parsing imports*/- void updateFromFilesystem(PrintWriter writer) throws IOException, OSGiException {+ void updateNewSourceOldBinFromFilesystem(PrintWriter writer) throws IOException, OSGiException {// look for new source filesnewSources.clear();oldBin.clear();- ResourceFile smf =- new ResourceFile(getSourceDir(), "META-INF" + File.separator + "MANIFEST.MF");- Path dmf = getBinDir().resolve("META-INF").resolve("MANIFEST.MF");-- foundNewManifest = smf.exists() && (Files.notExists(dmf) ||- smf.lastModified() > Files.getLastModifiedTime(dmf).toMillis());- BundleHost.visitDiscrepencies(getSourceDir(), getBinDir(), (sf, bfs) -> {+ visitDiscrepencies((sf, bfs) -> {if (sf != null) {newSources.add(sf);}@@ -176,20 +193,15 @@ public class GhidraSourceBundle implements GhidraBundle {}});- computeRequirements();-- // remove source files that failed last time, haven't changed, and don't have new dependencies available+ // don't rebuild source files that failed last time and haven't changedIterator<ResourceFile> it = newSources.iterator();while (it.hasNext()) {ResourceFile sf = it.next();BuildFailure f = buildErrors.get(sf);if (f != null) {if (f.when == sf.lastModified()) {- List<BundleRequirement> r = buildReqs.get(sf);- if (r == null || r.isEmpty() || !bundleHost.canResolveAll(r)) {- it.remove();- continue;- }+ it.remove();+ continue;}// it's either new or worth trying againbuildErrors.remove(sf);@@ -216,10 +228,6 @@ public class GhidraSourceBundle implements GhidraBundle {return newSources;}- boolean newManifestFile() {- return foundNewManifest;- }-long lastCompileAttempt;void compileAttempted() {@@ -255,6 +263,28 @@ public class GhidraSourceBundle implements GhidraBundle {return bundleLoc;}+ boolean hasNewManifest() throws IOException {+ ResourceFile smf =+ new ResourceFile(getSourceDir(), "META-INF" + File.separator + "MANIFEST.MF");+ Path dmf = getBinDir().resolve("META-INF").resolve("MANIFEST.MF");++ return smf.exists() && (Files.notExists(dmf) ||+ smf.lastModified() > Files.getLastModifiedTime(dmf).toMillis());+ }++ static private void wipe(Path path) throws IOException {+ if (Files.exists(path)) {+ for (Path p : (Iterable<Path>) Files.walk(path).sorted(+ Comparator.reverseOrder())::iterator) {+ Files.deleteIfExists(p);+ }+ }+ }++ private void wipeBinDir() throws IOException {+ wipe(binDir);+ }+@Overridepublic boolean build(PrintWriter writer) throws Exception {if (writer == null) {@@ -263,7 +293,41 @@ public class GhidraSourceBundle implements GhidraBundle {boolean needsCompile = false;- updateFromFilesystem(writer);+ // look for a manifest before checking other files+ boolean newManifest = hasNewManifest();+ if (newManifest) {+ wipeBinDir();+ }++ updateNewSourceOldBinFromFilesystem(writer);+ updateRequirementsFromMetadata();++ // if previous failures now resolve, try again+ for (ResourceFile sf : buildErrors.keySet()) {+ List<BundleRequirement> reqs = buildReqs.get(sf);+ if (reqs != null && !reqs.isEmpty() && bundleHost.canResolveAll(reqs)) {+ if (!newSources.contains(sf)) {+ newSources.add(sf);+ }+ for (ResourceFile oldbin : correspondingBinaries(sf)) {+ oldbin.delete();+ }+ }+ }+ // if previous successes no longer resolve, (cleanup) and try again+ for (Entry<ResourceFile, List<BundleRequirement>> e : buildReqs.entrySet()) {+ ResourceFile sf = e.getKey();+ List<BundleRequirement> reqs = e.getValue();+ if (reqs != null && !reqs.isEmpty() && !buildErrors.containsKey(sf) &&+ !bundleHost.canResolveAll(reqs)) {+ if (!newSources.contains(sf)) {+ newSources.add(sf);+ }+ for (ResourceFile oldbin : correspondingBinaries(sf)) {+ oldbin.delete();+ }+ }+ }int failing = getFailingSourcesCount();int newSourcecount = getNewSourcesCount();@@ -279,9 +343,6 @@ public class GhidraSourceBundle implements GhidraBundle {getSourceDir().toString(), failing, failing > 1 ? "s" : "");writer.printf("%s\n", getPreviousBuildErrors());}- if (newManifestFile()) {- needsCompile = true;- }}else {needsCompile = true;@@ -294,7 +355,7 @@ public class GhidraSourceBundle implements GhidraBundle {if (needsCompile) {writer.printf("%d new files, %d skipped, %s\n", newSourcecount, failing,- newManifestFile() ? ", new manifest" : "");+ newManifest ? ", new manifest" : "");// if there a bundle is currently active, uninstall itBundle b = getBundle();@@ -311,7 +372,7 @@ public class GhidraSourceBundle implements GhidraBundle {bundleCompiler.compileToExplodedBundle(this, writer);long endTime = System.nanoTime();writer.printf("%3.2f seconds compile time.\n", (endTime - startTime) / 1e9);- bundleHost.fireSourceBundleCompiled(this);+ bundleHost.fireBundleBuilt(this);return true;}return false;@@ -327,4 +388,114 @@ public class GhidraSourceBundle implements GhidraBundle {return bundleHost.getBundle(getBundleLoc());}+ @Override+ public void clean() {+ try {+ Bundle b = getBundle();+ if (b != null) {+ bundleHost.deactivateSynchronously(b);+ }+ wipeBinDir();+ }+ catch (IOException | GhidraBundleException | InterruptedException e) {+ Msg.showError(this, null, "source bundle clean error",+ "while attempting to delete the compiled directory, an exception was thrown", e);+ }+ }++ private static Predicate<String> bintail =+ Pattern.compile("(\\$.*)?\\.class", Pattern.CASE_INSENSITIVE).asMatchPredicate();++ private ResourceFile[] correspondingBinaries(ResourceFile source) {+ String parentPath = source.getParentFile().getAbsolutePath();+ String relpath = parentPath.substring(sourceDir.getAbsolutePath().length());+ if (relpath.startsWith(File.separator)) {+ relpath = relpath.substring(1);+ }+ String n0 = source.getName();+ final String n = n0.substring(0, n0.length() - 5);// trim .java+ ResourceFile bp = new ResourceFile(binDir.resolve(relpath).toFile());+ return bp.listFiles(f -> {+ String nn = f.getName();+ return nn.startsWith(n) && bintail.test(nn.substring(n.length()));+ });+ }++ /**+ * walk the filesystem to find:+ * - source files that are newer than their corresponding binary+ * reports (source file, list of corresponding binaries)+ * - source files with no corresponding binary+ * reports (source file, <empty list>)+ * - binary files with no corresponding source+ * reports (null, list of binary files)+ *+ * for a source file <source_root>/com/blah/Blah.java+ *+ * all of the following binaries would correspond:+ * <binary_root>/com/blah/Blah.class+ * <binary_root>/com/blah/Blah$Inner.class+ * <binary_root>/com/blah/Blah$12.class+ * <binary_root>/com/blah/Blah$12.class+ * <binary_root>/com/blah/Blah$Inner$Innerer.class+ * ...+ *+ * @param cb callback+ */+ private void visitDiscrepencies(DiscrepencyCallback cb) {+ try {+ // delete class files for which java is either newer, or no longer exists+ Deque<ResourceFile> stack = new ArrayDeque<>();+ stack.add(sourceDir);+ while (!stack.isEmpty()) {+ ResourceFile sd = stack.pop();+ String relpath =+ sd.getAbsolutePath().substring(sourceDir.getAbsolutePath().length());+ if (relpath.startsWith(File.separator)) {+ relpath = relpath.substring(1);+ }+ Path bd = binDir.resolve(relpath);++ // index the class files in the corresponding directory by basename+ Map<String, List<Path>> binfiles =+ Files.exists(bd) ? Files.list(bd).filter(x -> Files.isRegularFile(x) &&+ x.getFileName().toString().endsWith(".class")).collect(groupingBy(x -> {+ String s = x.getFileName().toString();+ int money = s.indexOf('$');+ if (money >= 0) {+ return s.substring(0, money);+ }+ return s.substring(0, s.length() - 6);+ })) : Collections.emptyMap();++ for (ResourceFile sf : sd.listFiles()) {+ if (sf.isDirectory()) {+ stack.push(sf);+ }+ else {+ String n = sf.getName();+ if (n.endsWith(".java")) {+ long source_modtime = sf.lastModified();+ List<Path> bfs = binfiles.remove(n.substring(0, n.length() - 5));+ long bin_modtime = (bfs == null || bfs.isEmpty()) ? -1+ : bfs.stream().mapToLong(+ bf -> bf.toFile().lastModified()).min().getAsLong();+ // if source is newer than the oldest binary, report+ if (source_modtime > bin_modtime) {+ cb.found(sf, bfs);+ }+ }+ }+ }+ // any remaining .class files are missing .java files+ if (!binfiles.isEmpty()) {+ cb.found(null, binfiles.values().stream().flatMap(l -> l.stream()).collect(+ Collectors.toList()));+ }+ }+ }+ catch (Throwable t) {+ t.printStackTrace();+ }+ }}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/OSGiListener.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/OSGiListener.javaindex fdc839f2fa..b0e6783323 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/OSGiListener.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/OSGiListener.java@@ -4,7 +4,11 @@ import org.osgi.framework.Bundle;public interface OSGiListener {- void sourceBundleCompiled(GhidraSourceBundle sb);+ default void bundleBuilt(GhidraBundle gb) {+ //+ }- void bundleActivationChange(Bundle b, boolean newActivation);+ default void bundleActivationChange(Bundle b, boolean newActivation) {+ //+ }}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptComponentProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptComponentProvider.javaindex 177d9f7125..8a1388940f 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptComponentProvider.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptComponentProvider.java@@ -40,6 +40,7 @@ import docking.widgets.tree.GTreeNode;import docking.widgets.tree.support.BreadthFirstIterator;import generic.jar.ResourceFile;import ghidra.app.plugin.core.osgi.*;+import ghidra.app.plugin.core.osgi.BundleHost.BuildFailure;import ghidra.app.script.*;import ghidra.app.services.ConsoleService;import ghidra.framework.options.SaveState;@@ -731,6 +732,7 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {private void build() {bundleStatusProvider = new BundleStatusProvider(plugin.getTool(), plugin.getName());+ // XXX remember listener to remove laterbundleStatusProvider.getModel().addListener(new BundleStatusListener() {@Overridepublic void bundlesChanged() {@@ -746,6 +748,24 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {}});+ BundleHost.getInstance().addListener(new OSGiListener() {++ @Override+ public void bundleBuilt(GhidraBundle sb) {+ if (sb instanceof GhidraSourceBundle) {+ GhidraSourceBundle gsb = (GhidraSourceBundle) sb;+ for (ResourceFile sf : gsb.getNewSources()) {+ if (GhidraScriptUtil.containsMetadata(sf)) {+ ScriptInfo info = GhidraScriptUtil.getScriptInfo(sf);+ BuildFailure e = gsb.getErrors(sf);+ info.setCompileErrors(e != null);+ }+ }+ tableModel.fireTableDataChanged();+ }+ }+ });+scriptRoot = new RootNode();scriptCategoryTree = new GTree(scriptRoot);