Ghidra is a software reverse engineering (SRE) framework
improve OSGi error messages
Jason P. Leasure7873bb32fa74
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 cc9793795d..b72fa11db2 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@@ -737,6 +737,7 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {void startActivateDeactiveTask(BundlePath path, boolean activate) {path.setBusy(true);bundleStatusProvider.notifyTableChanged();+ ConsoleService console = plugin.getTool().getService(ConsoleService.class);new TaskLauncher(new Task((activate ? "Activating" : "Deactivating ") + " bundle...") {@Override@@ -745,16 +746,11 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {if (activate) {if (path.getType() == BundlePath.Type.SourceDir) {SourceBundleInfo sbi = bundleHost.getSourceBundleInfo(path.getPath());- ConsoleService console =- plugin.getTool().getService(ConsoleService.class);bundleHost.compileSourceBundle(sbi, console.getStdErr());}String loc = bundleStatusProvider.getModel().getBundleLoc(path);if (loc != null) {- Bundle bundle = bundleHost.getBundle(loc);- if (bundle != null) {- bundle.start();- }+ bundleHost.activateSynchronously(loc);}}else { // deactivate@@ -762,14 +758,17 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {if (loc != null) {Bundle bundle = bundleHost.getBundle(loc);if (bundle != null) {- bundle.uninstall();+ bundleHost.deactivateSynchronously(bundle);}}}}catch (Exception e) {+ e.printStackTrace(console.getStdErr());+ path.setActive(!activate);+Msg.showError(this, GhidraScriptComponentProvider.this.getComponent(),- "activation failed", e);+ "bundle activation failed", e.getMessage());}finally {path.setBusy(false);@@ -784,7 +783,7 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {bundleStatusProvider =new BundleStatusProvider(plugin.getTool(), plugin.getName(), bundleHost);- bundleStatusProvider.addListener(new BundlePathManagerListener() {+ bundleStatusProvider.getModel().addListener(new BundleStatusListener() {@Overridepublic void bundlesChanged() {plugin.getTool().setConfigChanged(true);@@ -1073,7 +1072,7 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {}public void readConfigState(SaveState saveState) {- bundleStatusProvider.restoreState(saveState);+ bundleStatusProvider.getModel().restoreState(saveState);// pull in the just-loaded pathsList<ResourceFile> paths = bundleStatusProvider.getModel().getPaths();@@ -1100,7 +1099,7 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {}public void writeConfigState(SaveState saveState) {- bundleStatusProvider.saveState(saveState);+ bundleStatusProvider.getModel().saveState(saveState);actionManager.saveUserDefinedKeybindings(saveState);actionManager.saveScriptsThatAreInTool(saveState);diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/osgi/BundlePath.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/osgi/BundlePath.javaindex e9893a0342..6ecd38508d 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/osgi/BundlePath.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/osgi/BundlePath.java@@ -28,6 +28,7 @@ public class BundlePath extends Path {boolean active = false;boolean busy = false;+ String summary;public static enum Type {BndScript, Jar, SourceDir, INVALID@@ -100,4 +101,12 @@ public class BundlePath extends Path {return busy;}+ public void setSummary(String summary) {+ this.summary = summary;+ }++ public String getSummary() {+ return summary;+ }+}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/osgi/BundlePathManagerListener.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/osgi/BundleStatusListener.javasimilarity index 95%rename from Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/osgi/BundlePathManagerListener.javarename to Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/osgi/BundleStatusListener.javaindex 0db13a0d46..f84e96181d 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/osgi/BundlePathManagerListener.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/osgi/BundleStatusListener.java@@ -16,7 +16,7 @@*/package ghidra.app.plugin.core.script.osgi;-public interface BundlePathManagerListener {+public interface BundleStatusListener {/*** Called when the list of bundle paths changesdiff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/osgi/BundleStatusModel.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/osgi/BundleStatusModel.javaindex 7b3bfcc217..4628374ffa 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/osgi/BundleStatusModel.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/osgi/BundleStatusModel.java@@ -16,16 +16,17 @@*/package ghidra.app.plugin.core.script.osgi;+import java.io.File;import java.util.*;import java.util.stream.Collectors;-import org.osgi.framework.*;+import org.osgi.framework.Bundle;import docking.widgets.table.AbstractSortedTableModel;import generic.jar.ResourceFile;import ghidra.app.script.GhidraScriptUtil;-import ghidra.app.script.osgi.BundleHost;-import ghidra.app.script.osgi.SourceBundleInfo;+import ghidra.app.script.osgi.*;+import ghidra.framework.options.SaveState;import ghidra.framework.preferences.Preferences;import ghidra.util.Msg;@@ -72,7 +73,7 @@ public class BundleStatusModel extends AbstractSortedTableModel<BundlePath> {@Overridevoid setValue(BundlePath path, Object newValue) {path.setEnabled((Boolean) newValue);- provider.fireBundleEnablementChanged(path, (Boolean) newValue);+ fireBundleEnablementChanged(path, (Boolean) newValue);}};Column activeColumn = new Column("Active", Boolean.class) {@@ -89,15 +90,10 @@ public class BundleStatusModel extends AbstractSortedTableModel<BundlePath> {@Overridevoid setValue(BundlePath path, Object newValue) {path.setActive((Boolean) newValue);- provider.fireBundleActivationChanged(path, (Boolean) newValue);+ fireBundleActivationChanged(path, (Boolean) newValue);}};Column typeColumn = new Column("Type", String.class) {- @Override- boolean editable(BundlePath path) {- return false;- }-@OverrideObject getValue(BundlePath path) {return path.getType().toString();@@ -106,15 +102,17 @@ public class BundleStatusModel extends AbstractSortedTableModel<BundlePath> {Column pathColumn = new Column("Path", BundlePath.class) {@Override- boolean editable(BundlePath path) {- return false;+ Object getValue(BundlePath path) {+ return path;}-+ };+ Column summaryColumn = new Column("Summary", BundlePath.class) {@OverrideObject getValue(BundlePath path) {- return path;+ return path.getSummary();}};+Column badColumn = new Column("INVALID", Object.class);{columns.remove(columns.size() - 1); // pop badColumn@@ -131,7 +129,7 @@ public class BundleStatusModel extends AbstractSortedTableModel<BundlePath> {private BundleStatusProvider provider;private List<BundlePath> paths;private BundleHost bundleHost;- BundleListener bundleListener;+ OSGiListener bundleListener;private Map<String, BundlePath> loc2bp = new HashMap<>();@@ -180,42 +178,36 @@ public class BundleStatusModel extends AbstractSortedTableModel<BundlePath> {this.paths.add(0, new BundlePath(GhidraScriptUtil.getUserScriptDirectory(), true, false));computeCache();- bundleHost.addListener(bundleListener = new BundleListener() {+ bundleHost.addListener(bundleListener = new OSGiListener() {@Override- public void bundleChanged(BundleEvent event) {- Bundle b = event.getBundle();- BundlePath bp;- switch (event.getType()) {- case BundleEvent.INSTALLED:- case BundleEvent.LAZY_ACTIVATION:- case BundleEvent.RESOLVED:- case BundleEvent.STARTING:- case BundleEvent.STOPPED:- case BundleEvent.STOPPING:- case BundleEvent.UNRESOLVED:- case BundleEvent.UPDATED:- break;- case BundleEvent.STARTED:- bp = getPath(b.getLocation());- if (bp != null) {- bp.setActive(true);- int row = getRowIndex(bp);- fireTableRowsUpdated(row, row);- }- break;- case BundleEvent.UNINSTALLED:- bp = getPath(b.getLocation());- if (bp != null) {- bp.setActive(false);- int row = getRowIndex(bp);- fireTableRowsUpdated(row, row);- }- break;- default:- System.err.printf("What is a %d event??", event.getType());- break;+ public void sourceBundleCompiled(SourceBundleInfo sbi) {+ BundlePath bp = getPath(sbi.getBundleLoc());+ if (bp != null) {+ bp.setSummary(sbi.getSummary());+ int row = getRowIndex(bp);+ fireTableRowsUpdated(row, row);}}++ @Override+ public void bundleActivationChange(Bundle b, boolean newActivation) {+ BundlePath bp = getPath(b.getLocation());+ if (newActivation) {+ if (bp != null) {+ bp.setActive(true);+ int row = getRowIndex(bp);+ fireTableRowsUpdated(row, row);+ }+ }+ else {+ if (bp != null) {+ bp.setActive(false);+ int row = getRowIndex(bp);+ fireTableRowsUpdated(row, row);+ }+ }++ }});fireTableDataChanged();@@ -259,18 +251,26 @@ public class BundleStatusModel extends AbstractSortedTableModel<BundlePath> {fireTableRowsInserted(index, index);}- BundlePath addNewPath(ResourceFile path, boolean enabled, boolean readonly) {+ private BundlePath addNewPath(ResourceFile path, boolean enabled, boolean readonly) {BundlePath p = new BundlePath(path, enabled, readonly);addPath(p);return p;}- BundlePath addNewPath(String path, boolean enabled, boolean readonly) {+ private BundlePath addNewPath(String path, boolean enabled, boolean readonly) {BundlePath p = new BundlePath(path, enabled, readonly);addPath(p);return p;}+ void addNewPaths(List<File> files, boolean enabled, boolean readonly) {+ for (File f : files) {+ BundlePath p = new BundlePath(new ResourceFile(f), enabled, readonly);+ addPath(p);+ }+ fireBundlesChanged();+ }+void remove(int[] selectedRows) {List<BundlePath> list = new ArrayList<>();for (int selectedRow : selectedRows) {@@ -287,6 +287,7 @@ public class BundleStatusModel extends AbstractSortedTableModel<BundlePath> {}}fireTableDataChanged();+ fireBundlesChanged();}/***************************************************/@@ -321,6 +322,8 @@ public class BundleStatusModel extends AbstractSortedTableModel<BundlePath> {public void setValueAt(Object aValue, int rowIndex, int columnIndex) {BundlePath path = paths.get(rowIndex);getColumn(columnIndex).setValue(path, aValue);+ // XXX: preclude RowObjectSelectionManager.repairSelection+ provider.selectRow(rowIndex);}@Override@@ -355,7 +358,7 @@ public class BundleStatusModel extends AbstractSortedTableModel<BundlePath> {if (!path.isEnabled()) {path.setEnabled(true);fireTableDataChanged();- provider.fireBundlesChanged();+ fireBundlesChanged();return true;}return false;@@ -364,7 +367,7 @@ public class BundleStatusModel extends AbstractSortedTableModel<BundlePath> {addNewPath(dir, true, false);Preferences.setProperty(BundleStatusProvider.preferenceForLastSelectedBundle,dir.getAbsolutePath());- provider.fireBundlesChanged();+ fireBundlesChanged();return true;}@@ -403,4 +406,108 @@ public class BundleStatusModel extends AbstractSortedTableModel<BundlePath> {addNewPath(path, true, false);}+ private ArrayList<BundleStatusListener> listeners = new ArrayList<>();++ public void addListener(BundleStatusListener listener) {+ synchronized (listeners) {+ if (!listeners.contains(listener)) {+ listeners.add(listener);+ }+ }+ }++ public void removeListener(BundleStatusListener listener) {+ synchronized (listeners) {+ listeners.remove(listener);+ }+ }++ private void fireBundlesChanged() {+ synchronized (listeners) {+ for (BundleStatusListener listener : listeners) {+ listener.bundlesChanged();+ }+ }+ }++ void fireBundleEnablementChanged(BundlePath path, boolean newValue) {+ synchronized (listeners) {+ for (BundleStatusListener listener : listeners) {+ listener.bundleEnablementChanged(path, newValue);+ }+ }+ }++ void fireBundleActivationChanged(BundlePath path, boolean newValue) {+ synchronized (listeners) {+ for (BundleStatusListener listener : listeners) {+ listener.bundleActivationChanged(path, newValue);+ }+ }+ }++ /**+ * Restores the paths from the specified SaveState object.+ * @param ss the SaveState object+ */+ public void restoreState(SaveState ss) {+ String[] pathArr = ss.getStrings("BundleStatus_PATH", new String[0]);++ if (pathArr.length == 0) {+ return;+ }++ boolean[] enableArr = ss.getBooleans("BundleStatus_ENABLE", new boolean[pathArr.length]);+ boolean[] readonlyArr = ss.getBooleans("BundleStatus_READ", new boolean[pathArr.length]);++ List<BundlePath> currentPaths = getAllPaths();+ clear();++ for (int i = 0; i < pathArr.length; i++) {+ BundlePath currentPath = getPath(pathArr[i], currentPaths);+ if (currentPath != null) {+ currentPaths.remove(currentPath);+ addNewPath(pathArr[i], enableArr[i], readonlyArr[i]);+ }+ else if (!readonlyArr[i]) {+ // skip read-only paths which are not present in the current config+ // This is needed to thin-out old default entries+ addNewPath(pathArr[i], enableArr[i], readonlyArr[i]);+ }+ }+ fireBundlesChanged();+ }++ private static BundlePath getPath(String filepath, List<BundlePath> paths) {+ for (BundlePath path : paths) {+ if (filepath.equals(path.getPathAsString())) {+ return path;+ }+ }+ return null;+ }++ /**+ * Saves the paths to the specified SaveState object.+ * @param ss the SaveState object+ */+ public void saveState(SaveState ss) {+ List<BundlePath> currentPaths = getAllPaths();++ String[] pathArr = new String[currentPaths.size()];+ boolean[] enableArr = new boolean[currentPaths.size()];+ boolean[] readonlyArr = new boolean[currentPaths.size()];++ int index = 0;+ for (BundlePath path : currentPaths) {+ pathArr[index] = path.getPathAsString();+ enableArr[index] = path.isEnabled();+ readonlyArr[index] = path.isReadOnly();+ ++index;+ }++ ss.putStrings("BundleStatus_PATH", pathArr);+ ss.putBooleans("BundleStatus_ENABLE", enableArr);+ ss.putBooleans("BundleStatus_READ", readonlyArr);+ }}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/osgi/BundleStatusProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/osgi/BundleStatusProvider.javaindex ee90627ed3..3288c9fd96 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/osgi/BundleStatusProvider.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/osgi/BundleStatusProvider.java@@ -17,7 +17,6 @@ package ghidra.app.plugin.core.script.osgi;import java.awt.*;import java.io.File;-import java.util.ArrayList;import java.util.Arrays;import java.util.List;@@ -28,9 +27,7 @@ import javax.swing.table.TableColumn;import docking.widgets.filechooser.GhidraFileChooser;import docking.widgets.filechooser.GhidraFileChooserMode;import docking.widgets.table.*;-import generic.jar.ResourceFile;import ghidra.app.script.osgi.BundleHost;-import ghidra.framework.options.SaveState;import ghidra.framework.plugintool.ComponentProviderAdapter;import ghidra.framework.plugintool.PluginTool;import ghidra.framework.preferences.Preferences;@@ -45,35 +42,16 @@ public class BundleStatusProvider extends ComponentProviderAdapter {static String preferenceForLastSelectedBundle = "LastGhidraScriptBundle";private JPanel panel;- private GTable bundlePathTable;+ private GTable bundleStatusTable;private final BundleStatusModel bundleStatusModel;private JButton addButton;private JButton removeButton;private Color selectionColor;private GhidraFileChooser fileChooser;private GhidraFileFilter filter;- private ArrayList<BundlePathManagerListener> listeners = new ArrayList<>();public void notifyTableChanged() {- bundlePathTable.notifyTableChanged(new TableModelEvent(bundleStatusModel));- }-- void fireBundlesChanged() {- for (BundlePathManagerListener listener : listeners) {- listener.bundlesChanged();- }- }-- void fireBundleEnablementChanged(BundlePath path, boolean newValue) {- for (BundlePathManagerListener listener : listeners) {- listener.bundleEnablementChanged(path, newValue);- }- }-- void fireBundleActivationChanged(BundlePath path, boolean newValue) {- for (BundlePathManagerListener listener : listeners) {- listener.bundleActivationChanged(path, newValue);- }+ bundleStatusTable.notifyTableChanged(new TableModelEvent(bundleStatusModel));}public BundleStatusProvider(PluginTool tool, String owner, BundleHost bundleHost) {@@ -101,16 +79,6 @@ public class BundleStatusProvider extends ComponentProviderAdapter {return bundleStatusModel;}- public void addListener(BundlePathManagerListener listener) {- if (!listeners.contains(listener)) {- listeners.add(listener);- }- }-- public void removeListener(BundlePathManagerListener listener) {- listeners.remove(listener);- }-private void build() {panel = new JPanel(new BorderLayout(5, 5));@@ -139,25 +107,25 @@ public class BundleStatusProvider extends ComponentProviderAdapter {++gbc.gridy;buttonPanel.add(removeButton, gbc);- bundlePathTable = new GTable(bundleStatusModel);- bundlePathTable.setName("BUNDLEPATH_TABLE");- bundlePathTable.setSelectionBackground(selectionColor);- bundlePathTable.setSelectionForeground(Color.BLACK);- bundlePathTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);+ bundleStatusTable = new GTable(bundleStatusModel);+ bundleStatusTable.setName("BUNDLEPATH_TABLE");+ bundleStatusTable.setSelectionBackground(selectionColor);+ bundleStatusTable.setSelectionForeground(Color.BLACK);+ bundleStatusTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);// to allow custom cell renderers- bundlePathTable.setAutoCreateColumnsFromModel(false);+ bundleStatusTable.setAutoCreateColumnsFromModel(false);int skinnyWidth = 50;TableColumn column =- bundlePathTable.getColumnModel().getColumn(bundleStatusModel.enabledColumn.index);+ bundleStatusTable.getColumnModel().getColumn(bundleStatusModel.enabledColumn.index);column.setPreferredWidth(skinnyWidth);column.setMinWidth(skinnyWidth);column.setMaxWidth(skinnyWidth);column.setWidth(skinnyWidth);- column = bundlePathTable.getColumnModel().getColumn(bundleStatusModel.activeColumn.index);+ column = bundleStatusTable.getColumnModel().getColumn(bundleStatusModel.activeColumn.index);column.setPreferredWidth(skinnyWidth);column.setMinWidth(skinnyWidth);column.setMaxWidth(skinnyWidth);@@ -184,13 +152,13 @@ public class BundleStatusProvider extends ComponentProviderAdapter {});- column = bundlePathTable.getColumnModel().getColumn(bundleStatusModel.typeColumn.index);+ column = bundleStatusTable.getColumnModel().getColumn(bundleStatusModel.typeColumn.index);FontMetrics fontmetrics = panel.getFontMetrics(panel.getFont());column.setMaxWidth(10 +SwingUtilities.computeStringWidth(fontmetrics, BundlePath.Type.SourceDir.toString()));- column = bundlePathTable.getColumnModel().getColumn(bundleStatusModel.pathColumn.index);+ column = bundleStatusTable.getColumnModel().getColumn(bundleStatusModel.pathColumn.index);column.setCellRenderer(new GTableCellRenderer() {@Overridepublic Component getTableCellRendererComponent(GTableCellRenderingData data) {@@ -205,12 +173,12 @@ public class BundleStatusProvider extends ComponentProviderAdapter {});GTableFilterPanel<BundlePath> filterPanel =- new GTableFilterPanel<>(bundlePathTable, bundleStatusModel);+ new GTableFilterPanel<>(bundleStatusTable, bundleStatusModel);- JScrollPane scrollPane = new JScrollPane(bundlePathTable);- scrollPane.getViewport().setBackground(bundlePathTable.getBackground());+ JScrollPane scrollPane = new JScrollPane(bundleStatusTable);+ scrollPane.getViewport().setBackground(bundleStatusTable.getBackground());- ListSelectionModel selModel = bundlePathTable.getSelectionModel();+ ListSelectionModel selModel = bundleStatusTable.getSelectionModel();selModel.addListSelectionListener(e -> {if (e.getValueIsAdjusting()) {return;@@ -228,12 +196,12 @@ public class BundleStatusProvider extends ComponentProviderAdapter {}private void updateButtonsEnabled() {- int[] rows = bundlePathTable.getSelectedRows();+ int[] rows = bundleStatusTable.getSelectedRows();removeButton.setEnabled(rows.length > 0);}private void removeButtonAction() {- int[] selectedRows = bundlePathTable.getSelectedRows();+ int[] selectedRows = bundleStatusTable.getSelectedRows();if (selectedRows == null || selectedRows.length == 0) {return;}@@ -247,10 +215,9 @@ public class BundleStatusProvider extends ComponentProviderAdapter {row = count - 1;}if (row >= 0) {- bundlePathTable.setRowSelectionInterval(row, row);+ bundleStatusTable.setRowSelectionInterval(row, row);}updateButtonsEnabled();- fireBundlesChanged();}private void addButtonAction() {@@ -292,10 +259,7 @@ public class BundleStatusProvider extends ComponentProviderAdapter {if (!files.isEmpty()) {Preferences.setProperty(preferenceForLastSelectedBundle,files.get(0).getAbsolutePath());- for (File element : files) {- bundleStatusModel.addNewPath(new ResourceFile(element), true, false);- }- fireBundlesChanged();+ bundleStatusModel.addNewPaths(files, true, false);}}@@ -304,73 +268,12 @@ public class BundleStatusProvider extends ComponentProviderAdapter {return panel;}- /**- * Saves the paths to the specified SaveState object.- * @param ss the SaveState object- */- public void saveState(SaveState ss) {- List<BundlePath> paths = bundleStatusModel.getAllPaths();-- String[] pathArr = new String[paths.size()];- boolean[] enableArr = new boolean[paths.size()];- boolean[] readonlyArr = new boolean[paths.size()];-- int index = 0;- for (BundlePath path : paths) {- pathArr[index] = path.getPathAsString();- enableArr[index] = path.isEnabled();- readonlyArr[index] = path.isReadOnly();- ++index;- }-- ss.putStrings("BundleStatus_PATH", pathArr);- ss.putBooleans("BundleStatus_ENABLE", enableArr);- ss.putBooleans("BundleStatus_READ", readonlyArr);- }-- /**- * Restores the paths from the specified SaveState object.- * @param ss the SaveState object- */- public void restoreState(SaveState ss) {- String[] pathArr = ss.getStrings("BundleStatus_PATH", new String[0]);-- if (pathArr.length == 0) {- return;- }-- boolean[] enableArr = ss.getBooleans("BundleStatus_ENABLE", new boolean[pathArr.length]);- boolean[] readonlyArr = ss.getBooleans("BundleStatus_READ", new boolean[pathArr.length]);-- List<BundlePath> currentPaths = bundleStatusModel.getAllPaths();- bundleStatusModel.clear();-- for (int i = 0; i < pathArr.length; i++) {- BundlePath currentPath = getPath(pathArr[i], currentPaths);- if (currentPath != null) {- currentPaths.remove(currentPath);- bundleStatusModel.addNewPath(pathArr[i],enableArr[i],readonlyArr[i]);- }- else if (!readonlyArr[i]) {- // skip read-only paths which are not present in the current config- // This is needed to thin-out old default entries- bundleStatusModel.addNewPath(pathArr[i],enableArr[i],readonlyArr[i]);- }- }- fireBundlesChanged();- }-- private static BundlePath getPath(String filepath, List<BundlePath> paths) {- for (BundlePath path : paths) {- if (filepath.equals(path.getPathAsString())) {- return path;- }- }- return null;+ public void dispose() {+ bundleStatusTable.dispose();}- public void dispose() {- bundlePathTable.dispose();+ void selectRow(int rowIndex) {+ bundleStatusTable.selectRow(rowIndex);}}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/script/JavaScriptProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/script/JavaScriptProvider.javaindex 61773ec458..c75cf049b1 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/script/JavaScriptProvider.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/script/JavaScriptProvider.java@@ -48,7 +48,7 @@ public class JavaScriptProvider extends GhidraScriptProvider {Bundle b = getBundleInfoForSource(sourceFile).getBundle();if (b != null) {try {- BundleHost.getInstance().synchronousUninstall(b);+ BundleHost.getInstance().deactivateSynchronously(b);}catch (GhidraBundleException | InterruptedException e) {e.printStackTrace();@@ -89,8 +89,18 @@ public class JavaScriptProvider extends GhidraScriptProvider {static public Class<?> loadClass(ResourceFile sourceFile, PrintWriter writer)throws IOException, OSGiException, ClassNotFoundException, InterruptedException {+ BundleHost bundleHost = BundleHost.getInstance();+SourceBundleInfo bi = getBundleInfoForSource(sourceFile);- Bundle b = BundleHost.getInstance().compileSourceBundle(bi, writer);+ bundleHost.compileSourceBundle(bi, writer);++ // as much source as possible built, install bundle and start it if necessary+ Bundle b = bi.getBundle();+ if (b == null) {+ b = bi.install();+ }+ bundleHost.activateSynchronously(b);+String classname = bi.classNameForScript(sourceFile);Class<?> clazz = b.loadClass(classname); // throws ClassNotFoundExceptionreturn clazz;@@ -99,7 +109,7 @@ public class JavaScriptProvider extends GhidraScriptProvider {public static ResourceFile getSourceDirectoryContaining(ResourceFile sourceFile) {String sourcePath = sourceFile.getAbsolutePath();for (ResourceFile sourceDir : GhidraScriptUtil.getScriptSourceDirectories()) {- if (sourcePath.startsWith(sourceDir.getAbsolutePath()+File.separatorChar)) {+ if (sourcePath.startsWith(sourceDir.getAbsolutePath() + File.separatorChar)) {return sourceDir;}}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/BundleCompiler.java b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/BundleCompiler.javaindex a53ad0e88d..195e3ded45 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/BundleCompiler.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/BundleCompiler.java@@ -51,22 +51,22 @@ public class BundleCompiler {/*** compile a source directory to an exploded bundle*- * @param bi the bundle info to build+ * @param sbi the bundle info to build* @param writer for updating the user during compilation* @throws IOException for source/manifest file reading/generation and binary deletion/creation* @throws OSGiException if generation of bundle metadata fails*/- public void compileToExplodedBundle(SourceBundleInfo bi, PrintWriter writer)+ public void compileToExplodedBundle(SourceBundleInfo sbi, PrintWriter writer)throws IOException, OSGiException {- bi.compileAttempted();+ sbi.compileAttempted();+ sbi.setSummary(String.format("build %d files, skipping %d%s", sbi.getNewSourcesCount(),+ sbi.getFailingSourcesCount(), sbi.newManifestFile() ? ", new manifest" : ""));- ResourceFile srcdir = bi.getSourceDir();- Path bindir = bi.getBinDir();+ ResourceFile srcdir = sbi.getSourceDir();+ Path bindir = sbi.getBinDir();Files.createDirectories(bindir);- List<ResourceFile> newSource = bi.getNewSources();-List<String> options = new ArrayList<>();options.add("-g");options.add("-d");@@ -79,28 +79,44 @@ public class BundleCompiler {// final JavaFileManager rfm = new ResourceFileJavaFileManager(Collections.singletonList(bi.getSourceDir()));final JavaFileManager rfm =- new ResourceFileJavaFileManager(Collections.singletonList(bi.getSourceDir()));+ new ResourceFileJavaFileManager(Collections.singletonList(sbi.getSourceDir()));BundleJavaManager bjm = new BundleJavaManager(bh.getHostFramework(), rfm, options);// The phidias BundleJavaManager is for compiling from within a bundle -- it makes the// bundle dependencies available to the compiler classpath. Here, we are compiling in an as-yet// non-existing bundle, so we forge the wiring based on @imports metadata.- List<BundleRequirement> reqs = bi.getRequirements();+ // XXX skip this if there's a source manifest, emit warnings about @imports+ // get wires for currently active bundles to satisfy all requirements+ List<BundleRequirement> reqs = sbi.getAllReqs();List<BundleWiring> bundleWirings = bh.resolve(reqs);if (!reqs.isEmpty()) {- writer.printf("%d import requirement%s remain%s after resolution:\n", reqs.size(),+ writer.printf("%d import requirement%s remain%s unresolved:\n", reqs.size(),reqs.size() > 1 ? "s" : "", reqs.size() > 1 ? "" : "s");for (BundleRequirement req : reqs) {writer.printf(" %s\n", req.toString());}++ sbi.setSummary(+ String.format("%d missing @import%s:", reqs.size(), reqs.size() > 1 ? "s" : "",+ reqs.stream().flatMap(+ r -> OSGiUtils.extractPackages(r.toString()).stream()).distinct().collect(+ Collectors.joining(","))));+ }+ else {+ sbi.setSummary("");+ }+ // XXX add sources that will fail to call attention+ List<ResourceFile> newSource = sbi.getNewSources();+ for (BundleRequirement req : reqs) {+ newSource.addAll(sbi.req2file.get(req.toString()));}// send the capabilities to phidias- bundleWirings.forEach(bw -> bjm.addBundleWiring(bw));+ bundleWirings.forEach(bjm::addBundleWiring);- final List<ResourceFileJavaFileObject> compilationUnits = newSource.stream().map(+ final List<ResourceFileJavaFileObject> sourceFiles = newSource.stream().map(sf -> new ResourceFileJavaFileObject(sf.getParentFile(), sf, Kind.SOURCE)).collect(Collectors.toList());@@ -110,11 +126,11 @@ public class BundleCompiler {}// try to compile, if we fail, avoid offenders and try again- while (!compilationUnits.isEmpty()) {+ while (!sourceFiles.isEmpty()) {DiagnosticCollector<JavaFileObject> diagnostics =new DiagnosticCollector<JavaFileObject>();JavaCompiler.CompilationTask task =- compiler.getTask(writer, bjm, diagnostics, options, null, compilationUnits);+ compiler.getTask(writer, bjm, diagnostics, options, null, sourceFiles);// task.setProcessors // for annotation processing / code generationBoolean successfulCompilation = task.call();@@ -126,8 +142,8 @@ public class BundleCompiler {writer.write(err);ResourceFileJavaFileObject sf = (ResourceFileJavaFileObject) d.getSource();ResourceFile rf = sf.getFile();- bi.buildError(rf, err); // remember all errors for this file- if (compilationUnits.remove(sf)) {+ sbi.buildError(rf, err); // remember all errors for this file+ if (sourceFiles.remove(sf)) {writer.printf("skipping %s\n", sf.toString());// if it's a script, mark it for having compile errorsif (GhidraScriptUtil.containsMetadata(rf)) {@@ -138,13 +154,18 @@ public class BundleCompiler {}}// mark the successful compilations- for (ResourceFileJavaFileObject sf : compilationUnits) {+ for (ResourceFileJavaFileObject sf : sourceFiles) {ResourceFile rf = sf.getFile();if (GhidraScriptUtil.containsMetadata(rf)) {ScriptInfo info = GhidraScriptUtil.getScriptInfo(rf);info.setCompileErrors(false);}}+ // buildErrors is now up to date, set status+ if (sbi.getFailingSourcesCount() > 0) {+ sbi.appendSummary(+ String.format("%d failing source files", sbi.getFailingSourcesCount()));+ }ResourceFile smf = new ResourceFile(srcdir, "META-INF" + File.separator + "MANIFEST.MF");if (smf.exists()) {@@ -157,17 +178,16 @@ public class BundleCompiler {// no manifest, so create one with bndtoolsAnalyzer analyzer = new Analyzer();analyzer.setJar(new Jar(bindir.toFile())); // give bnd the contents- Stream<Object> bjars =- Files.list(GhidraScriptUtil.getCompiledBundlesDir()).filter(f -> f.toString().endsWith(".jar")).map(- f -> {- try {- return new Jar(f.toFile());- }- catch (IOException e1) {- e1.printStackTrace(writer);- return null;- }- });+ Stream<Object> bjars = Files.list(GhidraScriptUtil.getCompiledBundlesDir()).filter(+ f -> f.toString().endsWith(".jar")).map(f -> {+ try {+ return new Jar(f.toFile());+ }+ catch (IOException e1) {+ e1.printStackTrace(writer);+ return null;+ }+ });analyzer.addClasspath(bjars.collect(Collectors.toUnmodifiableList()));analyzer.setProperty("Bundle-SymbolicName",@@ -183,6 +203,7 @@ public class BundleCompiler {manifest = analyzer.calcManifest();}catch (Exception e) {+ sbi.appendSummary("bad manifest");throw new OSGiException("failed to calculate manifest by analyzing code", e);}Attributes ma = manifest.getMainAttributes();@@ -198,11 +219,13 @@ public class BundleCompiler {}}catch (Exception e) {+ sbi.appendSummary("failed bnd analysis");throw new OSGiException("failed to query classes while searching for activator", e);}if (activator_classname == null) {activator_classname = GENERATED_ACTIVATOR_CLASSNAME;if (!buildDefaultActivator(bindir, activator_classname, writer)) {+ sbi.appendSummary("failed to build generated activator");return;}// since we add the activator after bndtools built the imports, we should add its imports too@@ -236,8 +259,7 @@ public class BundleCompiler {* @return true if compilation succeeded* @throws IOException for failed write of source/binary activator*/- private boolean buildDefaultActivator(Path bindir, String activator_classname,- Writer writer)+ private boolean buildDefaultActivator(Path bindir, String activator_classname, Writer writer)throws IOException {Path activator_dest = bindir.resolve(activator_classname + ".java");@@ -270,12 +292,12 @@ public class BundleCompiler {StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);BundleJavaManager bjm = new BundleJavaManager(bh.getHostFramework(), fm, options);- Iterable<? extends JavaFileObject> compilationUnits2 =+ Iterable<? extends JavaFileObject> sourceFiles =fm.getJavaFileObjectsFromPaths(List.of(activator_dest));DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();- JavaCompiler.CompilationTask task2 =- compiler.getTask(writer, bjm, diagnostics, options, null, compilationUnits2);- if (!task2.call()) {+ JavaCompiler.CompilationTask task =+ compiler.getTask(writer, bjm, diagnostics, options, null, sourceFiles);+ if (!task.call()) {for (Diagnostic<? extends JavaFileObject> d : diagnostics.getDiagnostics()) {writer.write(d.getSource().toString() + ": " + d.getMessage(null) + "\n");}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/BundleHost.java b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/BundleHost.javaindex d87aa91457..24e926970c 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/BundleHost.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/BundleHost.java@@ -125,7 +125,7 @@ public class BundleHost {return installFromLoc("file://" + p.toAbsolutePath().normalize().toString());}- Bundle installFromLoc(String bundle_loc) throws GhidraBundleException {+ public Bundle installFromLoc(String bundle_loc) throws GhidraBundleException {try {return bc.installBundle(bundle_loc);}@@ -182,6 +182,12 @@ public class BundleHost {return bundleWirings;}+ public boolean canResolveAll(Collection<BundleRequirement> reqs) {+ LinkedList<BundleRequirement> tmp = new LinkedList<>(reqs);+ resolve(tmp);+ return tmp.isEmpty();+ }+class FelixLogger extends org.apache.felix.framework.Logger {@Overrideprotected void doLog(int level, String msg, Throwable throwable) {@@ -203,6 +209,33 @@ public class BundleHost {}+ static String getEventTypeString(BundleEvent e) {+ switch (e.getType()) {+ case BundleEvent.INSTALLED:+ return "INSTALLED";+ case BundleEvent.RESOLVED:+ return "RESOLVED";+ case BundleEvent.LAZY_ACTIVATION:+ return "LAZY_ACTIVATION";+ case BundleEvent.STARTING:+ return "STARTING";+ case BundleEvent.STARTED:+ return "STARTED";+ case BundleEvent.STOPPING:+ return "STOPPING";+ case BundleEvent.STOPPED:+ return "STOPPED";+ case BundleEvent.UPDATED:+ return "UPDATED";+ case BundleEvent.UNRESOLVED:+ return "UNRESOLVED";+ case BundleEvent.UNINSTALLED:+ return "UNINSTALLED";+ default:+ return "???";+ }+ }+/*** start the framework*@@ -287,22 +320,20 @@ public class BundleHost {}});bc.addBundleListener(new BundleListener() {-@Overridepublic void bundleChanged(BundleEvent event) {- // System.err.printf("%s %s\n", event.getBundle(), event);+ Bundle b = event.getBundle();+ String n = b.getSymbolicName();+ String l = b.getLocation();+ System.err.printf("%s %s from %s\n", getEventTypeString(event), n, l);switch (event.getType()) {- case BundleEvent.INSTALLED:- System.err.printf("INSTALLED %s\n", event.getBundle().getSymbolicName());+ case BundleEvent.STARTED:+ fireBundleActivationChange(b, true);break;case BundleEvent.UNINSTALLED:- System.err.printf("UNINSTALLED %s\n", event.getBundle().getSymbolicName());- break;- case BundleEvent.STARTED:- System.err.printf("STARTED %s\n", event.getBundle().getSymbolicName());+ fireBundleActivationChange(b, false);break;- case BundleEvent.STOPPED:- System.err.printf("STOPPED %s\n", event.getBundle().getSymbolicName());+ default:break;}}@@ -340,7 +371,7 @@ public class BundleHost {}}- public void synchronousStart(Bundle b) throws InterruptedException, GhidraBundleException {+ public void activateSynchronously(Bundle b) throws InterruptedException, GhidraBundleException {if (b.getState() == Bundle.ACTIVE) {return;}@@ -353,31 +384,35 @@ public class BundleHost {waitFor(b, Bundle.ACTIVE);}- public void synchronousStop(Bundle b) throws InterruptedException, GhidraBundleException {- if (oneOf(b, Bundle.RESOLVED, Bundle.INSTALLED, Bundle.UNINSTALLED)) {- return;- }- try {- b.stop();+ public void activateSynchronously(String bundleLoc)+ throws GhidraBundleException, InterruptedException {+ Bundle bundle = getBundle(bundleLoc);+ if (bundle == null) {+ bundle = installFromLoc(bundleLoc);}- catch (BundleException e) {- throw new GhidraBundleException(b, "stopping bundle", e);- }- waitFor(b, Bundle.RESOLVED, Bundle.INSTALLED, Bundle.UNINSTALLED);+ activateSynchronously(bundle);}- public void synchronousUninstall(Bundle b) throws InterruptedException, GhidraBundleException {+ public void deactivateSynchronously(Bundle b)+ throws InterruptedException, GhidraBundleException {if (b.getState() == Bundle.UNINSTALLED) {return;}- try {- // stop first??- b.uninstall();- }- catch (BundleException e) {- throw new GhidraBundleException(b, "unisntalling bundle", e);+ FrameworkWiring fw = felix.adapt(FrameworkWiring.class);+ LinkedList<Bundle> dependents =+ new LinkedList<Bundle>(fw.getDependencyClosure(Collections.singleton(b)));+ System.err.printf("%s has %d dependendts\n", b.getSymbolicName(), dependents.size());+ while (!dependents.isEmpty()) {+ b = dependents.pop();+ try {+ b.uninstall();+ fw.refreshBundles(dependents);+ }+ catch (BundleException e) {+ throw new GhidraBundleException(b, "uninstalling bundle", e);+ }+ waitFor(b, Bundle.UNINSTALLED);}- waitFor(b, Bundle.UNINSTALLED);}void forceStopFelix() {@@ -534,42 +569,40 @@ public class BundleHost {}/**- * compile a source bundle if it's binary is out of sync+ * compile a source bundle if it's out of sync*- * @param bi the bundle info+ * @param sbi the bundle info* @param writer where to write issues* @throws OSGiException if bundle operations fail* @throws IOException if there are issues with the contents of the bundle* @return the activated bundle* @throws InterruptedException if interrupted while waiting for bundle state change*/- public Bundle compileSourceBundle(SourceBundleInfo bi, PrintWriter writer)+ public boolean compileSourceBundle(SourceBundleInfo sbi, PrintWriter writer)throws OSGiException, IOException, InterruptedException {if (writer == null) {writer = new NullPrintWriter();}- bi.updateFromFilesystem(writer);-- // needsCompile => needsBundleActivateboolean needsCompile = false;- boolean needsBundleActivate = false;- int failing = bi.getFailingSourcesCount();- int newSourcecount = bi.getNewSourcesCount();+ sbi.updateFromFilesystem(writer);++ int failing = sbi.getFailingSourcesCount();+ int newSourcecount = sbi.getNewSourcesCount();long lastBundleActivation = 0; // XXX record last bundle activation in bundlestatusmodel- if (failing > 0 && (lastBundleActivation > bi.getLastCompileAttempt())) {+ if (failing > 0 && (lastBundleActivation > sbi.getLastCompileAttempt())) {needsCompile = true;}if (newSourcecount == 0) {if (failing > 0) {writer.printf("%s hasn't changed, with %d file%s failing in previous build(s):\n",- bi.getSourceDir().toString(), failing, failing > 1 ? "s" : "");- writer.printf("%s\n", bi.getPreviousBuildErrors());+ sbi.getSourceDir().toString(), failing, failing > 1 ? "s" : "");+ writer.printf("%s\n", sbi.getPreviousBuildErrors());}- if (bi.newManifestFile()) {+ if (sbi.newManifestFile()) {needsCompile = true;}}@@ -577,50 +610,59 @@ public class BundleHost {needsCompile = true;}- needsBundleActivate |= needsCompile;-- if (needsBundleActivate) {- writer.printf("%s has %d new/updated %d failed in previous build(s)%s\n",- bi.getSourceDir().toString(), newSourcecount, failing,- bi.newManifestFile() ? " and the manifest is new" : "");+ if (needsCompile) {+ writer.printf("%d new files, %d skipped, %s\n", newSourcecount, failing,+ sbi.newManifestFile() ? ", new manifest" : "");// if there a bundle is currently active, uninstall it- Bundle b = bi.getBundle();+ Bundle b = sbi.getBundle();if (b != null) {- synchronousUninstall(b);+ deactivateSynchronously(b);}// once we've committed to recompile and regenerate generated classes, delete the old stuff- if (needsCompile) {- bi.deleteOldBinaries();+ sbi.deleteOldBinaries();- BundleCompiler bundleCompiler = new BundleCompiler(this);+ BundleCompiler bundleCompiler = new BundleCompiler(this);- long startTime = System.nanoTime();- bundleCompiler.compileToExplodedBundle(bi, writer);- long endTime = System.nanoTime();- writer.printf("%3.2f seconds compile time.\n", (endTime - startTime) / 1e9);- }+ long startTime = System.nanoTime();+ bundleCompiler.compileToExplodedBundle(sbi, writer);+ long endTime = System.nanoTime();+ writer.printf("%3.2f seconds compile time.\n", (endTime - startTime) / 1e9);+ fireSourceBundleCompiled(sbi);+ return true;}- // as much source as possible built, install bundle and start it if necessary- Bundle b = bi.getBundle();- if (b == null) {- b = bi.install();- needsBundleActivate = true;+ return false;+ }++ List<OSGiListener> osgiListeners = new ArrayList<>();++ void fireSourceBundleCompiled(SourceBundleInfo sbi) {+ synchronized (osgiListeners) {+ for (OSGiListener l : osgiListeners) {+ l.sourceBundleCompiled(sbi);+ }}+ }- if (needsBundleActivate) {- synchronousStart(b);+ void fireBundleActivationChange(Bundle b, boolean newActivation) {+ synchronized (osgiListeners) {+ for (OSGiListener l : osgiListeners) {+ l.bundleActivationChange(b, newActivation);+ }}- return b;}- public void addListener(BundleListener bundleListener) {- bc.addBundleListener(bundleListener);+ public void addListener(OSGiListener osgiListener) {+ synchronized (osgiListeners) {+ osgiListeners.add(osgiListener);+ }}- public void removeListener(BundleListener bundleListener) {- bc.removeBundleListener(bundleListener);+ public void removeListener(OSGiListener osgiListener) {+ synchronized (osgiListeners) {+ osgiListeners.remove(osgiListener);+ }}}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/GhidraBundleException.java b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/GhidraBundleException.javaindex 05bcba3bd1..4d1d3bf650 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/GhidraBundleException.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/GhidraBundleException.java@@ -16,6 +16,8 @@package ghidra.app.script.osgi;+import java.util.stream.Collectors;+import org.osgi.framework.Bundle;import org.osgi.framework.BundleException;@@ -23,18 +25,13 @@ public class GhidraBundleException extends OSGiException {private Bundle bundle;private String bundle_loc;- public GhidraBundleException(Bundle bundle, String msg, Throwable cause) {- super(msg, cause);- this.bundle = bundle;- }-- public GhidraBundleException(Bundle bundle, String msg) {- super(msg);+ public GhidraBundleException(Bundle bundle, String msg, BundleException cause) {+ super(msg + ": " + parsedCause(cause), cause);this.bundle = bundle;}public GhidraBundleException(String bundle_loc, String msg, BundleException cause) {- super(msg, cause);+ super(msg + ": " + parsedCause(cause), cause);this.bundle_loc = bundle_loc;}@@ -46,4 +43,111 @@ public class GhidraBundleException extends OSGiException {return bundle_loc;}+ static private String parsedCause(Throwable e) {+ if (e == null) {+ return "";+ }+ if (e instanceof BundleException) {+ BundleException be = (BundleException) e;+ switch (be.getType()) {+ default:+ case BundleException.UNSPECIFIED:+ return "No exception type";++ /**+ * The operation was unsupported. This type can be used anywhere a+ * BundleException can be thrown.+ */+ case BundleException.UNSUPPORTED_OPERATION:+ return "UNSUPPORTED_OPERATION";++ /**+ * The operation was invalid.+ */+ case BundleException.INVALID_OPERATION:+ return "INVALID_OPERATION";++ /**+ * The bundle manifest was in error.+ */+ case BundleException.MANIFEST_ERROR:+ return "MANIFEST_ERROR";++ /**+ * The bundle was not resolved.+ */+ case BundleException.RESOLVE_ERROR: {+ String message = be.getMessage();+ if (message.startsWith("Unable to acquire global lock")) {+ return message;+ }+ // parse the package constraints from filters in the BundleRequirement string+ String packages =+ OSGiUtils.extractPackages(be.getMessage()).stream().distinct().collect(+ Collectors.joining("\n"));+ return "RESOLVE_ERROR with reference to packages:\n" + packages;+ }++ /**+ * The bundle activator was in error.+ */+ case BundleException.ACTIVATOR_ERROR:+ return "ACTIVATOR_ERROR";++ /**+ * The operation failed due to insufficient permissions.+ */+ case BundleException.SECURITY_ERROR:+ return "SECURITY_ERROR";++ /**+ * The operation failed to complete the requested lifecycle state change.+ */+ case BundleException.STATECHANGE_ERROR:+ return "STATECHANGE_ERROR";++ /**+ * The bundle could not be resolved due to an error with the+ * Bundle-NativeCode header.+ */+ case BundleException.NATIVECODE_ERROR:+ return "NATIVECODE_ERROR";++ /**+ * The install or update operation failed because another already installed+ * bundle has the same symbolic name and version. This exception type will+ * only occur if the framework is configured to only allow a single bundle+ * to be installed for a given symbolic name and version.+ *+ * @see Constants#FRAMEWORK_BSNVERSION+ */+ case BundleException.DUPLICATE_BUNDLE_ERROR:+ return "DUPLICATE_BUNDLE_ERROR";++ /**+ * The start transient operation failed because the start level of the+ * bundle is greater than the current framework start level+ */+ case BundleException.START_TRANSIENT_ERROR:+ return "START_TRANSIENT_ERROR";++ /**+ * The framework received an error while reading the input stream for a+ * bundle.+ */+ case BundleException.READ_ERROR:+ return "READ_ERROR";++ /**+ * A framework hook rejected the operation.+ *+ * @since 1.6+ */+ case BundleException.REJECTED_BY_HOOK:+ return "REJECTED_BY_HOOK";+ }+ }+ return e.getCause().getMessage();+ }+}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/OSGiListener.java b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/OSGiListener.javanew file mode 100644index 0000000000..378730b7e2--- /dev/null+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/OSGiListener.java@@ -0,0 +1,10 @@+package ghidra.app.script.osgi;++import org.osgi.framework.Bundle;++public interface OSGiListener {++ void sourceBundleCompiled(SourceBundleInfo sbi);++ void bundleActivationChange(Bundle b, boolean newActivation);+}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/OSGiUtils.java b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/OSGiUtils.javanew file mode 100644index 0000000000..788f7965a1--- /dev/null+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/OSGiUtils.java@@ -0,0 +1,34 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package ghidra.app.script.osgi;++import java.util.List;+import java.util.Scanner;+import java.util.regex.Pattern;+import java.util.stream.Collectors;++public class OSGiUtils {++ public static List<String> extractPackages(String str) {+ try (Scanner s = new Scanner(str)) {+ return s.findAll(Pattern.compile("\\(osgi\\.wiring\\.package=([^)]*)\\)")).map(m -> {+ return m.group(1);+ }).collect(Collectors.toList());+ }+ }++}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/SourceBundleInfo.java b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/SourceBundleInfo.javaindex 5a37ee2136..24371c3a71 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/SourceBundleInfo.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/SourceBundleInfo.java@@ -30,24 +30,29 @@ import ghidra.app.script.ScriptInfo;import ghidra.app.script.osgi.BundleHost.BuildFailure;/**- * The SourceBundleInfo class is a cache of information about source directory bundles.+ * The SourceBundleInfo class is a cache of information for bundles built from source directories.*/public class SourceBundleInfo {- private final BundleHost bundle_host;+ private final BundleHost bundleHost;final private ResourceFile sourceDir;final String symbolicName;final private Path binDir;final private String bundleLoc;+ boolean foundNewManifest;++ final List<ResourceFile> newSources = new ArrayList<>();+ final List<Path> oldBin = new ArrayList<>();//// information indexed by source file- // XXX add separate missing requirements trackingfinal HashMap<ResourceFile, BuildFailure> buildErrors = new HashMap<>();+ final HashMap<ResourceFile, List<BundleRequirement>> buildReqs = new HashMap<>();+ final HashMap<String, List<ResourceFile>> req2file = new HashMap<>();// cached values parsed form @imports tags on default-package source filespublic SourceBundleInfo(BundleHost bundleHost, ResourceFile sourceDir) {- bundle_host = bundleHost;+ this.bundleHost = bundleHost;this.sourceDir = sourceDir;this.symbolicName = BundleHost.getSymbolicNameFromSourceDir(sourceDir);this.binDir = GhidraScriptUtil.getCompiledBundlesDir().resolve(symbolicName);@@ -75,14 +80,6 @@ public class SourceBundleInfo {}}- public Bundle getBundle() {- return bundle_host.getBundle(getBundleLoc());- }-- public String getBundleLoc() {- return bundleLoc;- }-public ResourceFile getSourceDir() {return sourceDir;}@@ -92,7 +89,7 @@ public class SourceBundleInfo {}public Bundle install() throws GhidraBundleException {- return bundle_host.installFromLoc(getBundleLoc());+ return bundleHost.installFromLoc(getBundleLoc());}public void buildError(ResourceFile rf, String err) {@@ -107,59 +104,49 @@ public class SourceBundleInfo {}/**- * check for build errors from last time- * @param rf file to test- * @return true if this file had errors and hasn't changed+ * update buildReqs based on \@imports tag in java files from the default package+ *+ * @throws OSGiException on failure to parse the \@imports tag*/- private boolean syncBuildErrors(ResourceFile rf) {- BuildFailure f = buildErrors.get(rf);- if (f != null) {- if (f.when == rf.lastModified()) {- return true;- }- buildErrors.remove(rf);- }- return false;- }-- public List<BundleRequirement> getRequirements() {- return foundRequirements;- }-- final List<ResourceFile> newSources = new ArrayList<>();- List<Path> oldBin = new ArrayList<>();-- boolean foundNewManifest;- private List<BundleRequirement> foundRequirements;-private void computeRequirements() throws OSGiException {- foundRequirements = null;- Map<String, BundleRequirement> dedupedreqs = new HashMap<>();// parse metadata from all Java source in sourceDir+ buildReqs.clear();+ req2file.clear();+for (ResourceFile rf : sourceDir.listFiles()) {if (rf.getName().endsWith(".java")) {// NB: ScriptInfo will update field values if lastModified has changed since last time they were computedScriptInfo si = GhidraScriptUtil.getScriptInfo(rf);String imps = si.getImports();if (imps != null && !imps.isEmpty()) {- for (BundleRequirement req : BundleHost.parseImports(imps)) {- dedupedreqs.put(req.toString(), req);+ List<BundleRequirement> reqs = BundleHost.parseImports(imps);+ buildReqs.put(rf, reqs);+ for (BundleRequirement req : reqs) {+ req2file.computeIfAbsent(req.toString(), x -> new ArrayList<>()).add(rf);}}}}- foundRequirements = new ArrayList<>(dedupedreqs.values());+ }++ public List<BundleRequirement> getAllReqs() {+ Map<String, BundleRequirement> dedupedReqs = new HashMap<>();+ buildReqs.values().stream().flatMap(List::stream).forEach(+ r -> dedupedReqs.putIfAbsent(r.toString(), r));++ return new ArrayList<>(dedupedReqs.values());}/*** look for new sources, metadata, manifest file.*+ * if files had errors last time, haven't changed, and no new requirements are available, remove them.+ ** @param writer for reporting status to user* @throws IOException while accessing manifest file* @throws OSGiException while parsing imports*/public void updateFromFilesystem(PrintWriter writer) throws IOException, OSGiException {-// look for new source filesnewSources.clear();oldBin.clear();@@ -181,12 +168,21 @@ public class SourceBundleInfo {computeRequirements();- // remove source files that failed last time and haven't changed+ // remove source files that failed last time, haven't changed, and don't have new dependencies availableIterator<ResourceFile> it = newSources.iterator();while (it.hasNext()) {ResourceFile sf = it.next();- if (syncBuildErrors(sf)) {- it.remove();+ 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's either new or worth trying again+ buildErrors.remove(sf);}}}@@ -223,4 +219,32 @@ public class SourceBundleInfo {public long getLastCompileAttempt() {return lastCompileAttempt;}++ String summary = "";++ public void setSummary(String summary) {+ this.summary = summary;+ }++ public void appendSummary(String s) {+ if (!summary.isEmpty()) {+ summary += ", " + s;+ }+ else {+ summary = s;+ }+ }++ public String getSummary() {+ return summary;+ }++ public Bundle getBundle() {+ return bundleHost.getBundle(getBundleLoc());+ }++ public String getBundleLoc() {+ return bundleLoc;+ }+}