Skip to content

Ghidra is a software reverse engineering (SRE) framework

style fixes for ghidra.app.plugin.core.osgi

Jason P. Leasure6bc33bdf6567
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.java
index f1c4151dbb..582daa83c0 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
@@ -16,23 +16,19 @@
package ghidra.app.plugin.core.osgi;
import java.io.*;
-import java.net.URL;
-import java.nio.file.*;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.*;
-import java.util.Map.Entry;
import java.util.function.Function;
-import java.util.jar.JarFile;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.stream.*;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
import org.apache.felix.framework.FrameworkFactory;
+import org.apache.felix.framework.Logger;
import org.apache.felix.framework.util.FelixConstants;
-import org.apache.felix.framework.util.manifestparser.ManifestParser;
import org.osgi.framework.*;
import org.osgi.framework.launch.Framework;
import org.osgi.framework.wiring.*;
-import org.osgi.service.log.*;
import generic.io.NullPrintWriter;
import generic.jar.ResourceFile;
@@ -43,186 +39,278 @@ import ghidra.util.Msg;
import ghidra.util.exception.CancelledException;
import ghidra.util.task.*;
+/**
+ * Hosts the embedded OSGi framework and manages {@link GhidraBundle}s.
+ *
+ * <br/><br/>
+ * note: {@link GhidraBundle}, its implementations, and this class constitute
+ * a bridge between OSGi's {@link Bundle} and Ghidra.
+ * - unqualified, "bundle" will mean {@link GhidraBundle}
+ * - use of OSGi types, including {@link Bundle} and {@link Framework}, should be package scoped (not public)
+ * - OSGi bundle lifecycle is simplified to "active" and "inactive" (OSGi's "uninstalled" state)
+ */
public class BundleHost {
- protected static final boolean DUMP_TO_STDERR = false;
+ protected static final boolean STDERR_DEBUGGING = false;
+ private static final String saveStateTagPath = "BundleHost_PATH";
+ private static final String saveStateTagEnabled = "BundleHost_ENABLE";
+ private static final String saveStateTagActive = "BundleHost_ACTIVE";
+ private static final String saveStateTagSystem = "BundleHost_SYSTEM";
- static public String getSymbolicNameFromSourceDir(ResourceFile sourceDir) {
- return Integer.toHexString(sourceDir.getAbsolutePath().hashCode());
- }
+ HashMap<ResourceFile, GhidraBundle> bundlePathToBundleMap = new HashMap<>();
+ HashMap<String, GhidraBundle> bundleLocationToBundleMap = new HashMap<>();
+
+ BundleContext frameworkBundleContext;
+ Framework felixFramework;
+
+ List<BundleHostListener> listeners = new ArrayList<>();
+ /** constructor */
public BundleHost() {
//
}
- public void dispose() {
- disposeFramework();
+ private static GhidraBundle newGhidraBundle(BundleHost bundleHost, ResourceFile bundlePath,
+ boolean enabled, boolean systemBundle) {
+ switch (GhidraBundle.getType(bundlePath)) {
+ case SourceDir:
+ return new GhidraSourceBundle(bundleHost, bundlePath, enabled, systemBundle);
+ case Jar:
+ return new GhidraJarBundle(bundleHost, bundlePath, enabled, systemBundle);
+ case BndScript:
+ default:
+ break;
+ }
+ return new GhidraPlaceholderBundle(bundleHost, bundlePath, enabled, systemBundle);
}
- HashMap<ResourceFile, GhidraBundle> bp2gb = new HashMap<>();
- HashMap<String, GhidraBundle> bl2gb = new HashMap<>();
+ /**
+ * stop the framework.
+ */
+ public void dispose() {
+ stopFramework();
+ }
+ /**
+ * If there is currently a bundle managed with path {@code bundlePath}, return its {@link GhidraBundle},
+ * otherwise return {@code null}.
+ *
+ * @param bundlePath the bundlePath of the sought bundle
+ * @return a {@link GhidraBundle} or {@code null}
+ */
public GhidraBundle getExistingGhidraBundle(ResourceFile bundlePath) {
- GhidraBundle r = bp2gb.get(bundlePath);
- if (r == null) {
+ GhidraBundle bundle = bundlePathToBundleMap.get(bundlePath);
+ if (bundle == null) {
Msg.showError(this, null, "ghidra bundle cache",
- "getExistingGhidraBundle before GhidraBundle created: " + bundlePath);
+ "getExistingGhidraBundle expected a GhidraBundle created at " + bundlePath +
+ " but none was found");
}
- return r;
+ return bundle;
}
+ /**
+ * If a {@link GhidraBundle} hasn't already been added for {@bundlePath}, add it now as a
+ * non-system bundle.
+ *
+ * Enable the bundle.
+ *
+ * @param bundlePath the path to the bundle to (add and) enable
+ * @return false if the bundle was already enabled
+ */
public boolean enablePath(ResourceFile bundlePath) {
- GhidraBundle gb = bp2gb.get(bundlePath);
- if (gb == null) {
- gb = addGhidraBundle(bundlePath, true, false);
+ GhidraBundle bundle = bundlePathToBundleMap.get(bundlePath);
+ if (bundle == null) {
+ bundle = add(bundlePath, true, false);
return true;
}
- return enable(gb);
+ return enable(bundle);
}
- public boolean enable(GhidraBundle gbundle) {
- if (!gbundle.isEnabled()) {
- gbundle.setEnabled(true);
- fireBundleEnablementChange(gbundle, true);
+ /**
+ * Enable a bundle and notify listeners.
+ *
+ * @param bundle the bundle to enable
+ * @return false if the bundle was already enabled
+ */
+ public boolean enable(GhidraBundle bundle) {
+ if (!bundle.isEnabled()) {
+ bundle.setEnabled(true);
+ fireBundleEnablementChange(bundle, true);
return true;
}
return false;
}
- public boolean disable(GhidraBundle gbundle) {
- if (gbundle.isEnabled()) {
- gbundle.setEnabled(false);
- fireBundleEnablementChange(gbundle, false);
+ /**
+ * Disable a bundle and notify listeners.
+ *
+ * @param bundle the bundle to disable
+ * @return true if the bundle was enabled
+ */
+ public boolean disable(GhidraBundle bundle) {
+ if (bundle.isEnabled()) {
+ bundle.setEnabled(false);
+ fireBundleEnablementChange(bundle, false);
return true;
}
return false;
}
- public GhidraBundle addGhidraBundle(ResourceFile path, boolean enabled, boolean systemBundle) {
- GhidraBundle gb = newGhidraBundle(this, path, enabled, systemBundle);
- bp2gb.put(path, gb);
- bl2gb.put(gb.getBundleLoc(), gb);
- fireBundleAdded(gb);
- return gb;
- }
-
- public void addGhidraBundles(List<ResourceFile> paths, boolean enabled, boolean systemBundle) {
- Map<ResourceFile, GhidraBundle> newmap =
- paths.stream().collect(Collectors.toUnmodifiableMap(Function.identity(),
- path -> newGhidraBundle(BundleHost.this, path, enabled, systemBundle)));
- bp2gb.putAll(newmap);
- bl2gb.putAll(newmap.values().stream().collect(
- Collectors.toUnmodifiableMap(GhidraBundle::getBundleLoc, Function.identity())));
- fireBundlesAdded(newmap.values());
+ /**
+ * Create a new GhidraBundle and add to the list of managed bundles
+ *
+ * @param bundlePath the bundle's path
+ * @param enabled if the new bundle should be enabled
+ * @param systemBundle if the new bundle is a system bundle
+ * @return a new GhidraBundle
+ */
+ public GhidraBundle add(ResourceFile bundlePath, boolean enabled, boolean systemBundle) {
+ GhidraBundle bundle = newGhidraBundle(this, bundlePath, enabled, systemBundle);
+ bundlePathToBundleMap.put(bundlePath, bundle);
+ bundleLocationToBundleMap.put(bundle.getBundleLocation(), bundle);
+ fireBundleAdded(bundle);
+ return bundle;
}
- public void add(List<GhidraBundle> gbundles) {
- for (GhidraBundle gb : gbundles) {
- bp2gb.put(gb.getPath(), gb);
- bl2gb.put(gb.getBundleLoc(), gb);
- }
- fireBundlesAdded(gbundles);
+ /**
+ * Create new GhidraBundles and add to the list of managed bundles. All GhidraBundles created
+ * with the same {@code enabled} and {@code systemBundle} values.
+ *
+ * @param bundlePaths a list of bundle paths
+ * @param enabled if the new bundle should be enabled
+ * @param systemBundle if the new bundle is a system bundle
+ */
+ public void add(List<ResourceFile> bundlePaths, boolean enabled, boolean systemBundle) {
+ Map<ResourceFile, GhidraBundle> newBundleMap = bundlePaths.stream()
+ .collect(Collectors.toUnmodifiableMap(Function.identity(),
+ bundlePath -> newGhidraBundle(BundleHost.this, bundlePath, enabled, systemBundle)));
+ bundlePathToBundleMap.putAll(newBundleMap);
+ bundleLocationToBundleMap.putAll(newBundleMap.values()
+ .stream()
+ .collect(
+ Collectors.toUnmodifiableMap(GhidraBundle::getBundleLocation, Function.identity())));
+ fireBundlesAdded(newBundleMap.values());
}
- static private GhidraBundle newGhidraBundle(BundleHost bh, ResourceFile path, boolean enabled,
- boolean systemBundle) {
- switch (GhidraBundle.getType(path)) {
- case SourceDir:
- return new GhidraSourceBundle(bh, path, enabled, systemBundle);
- case Jar:
- return new GhidraJarBundle(bh, path, enabled, systemBundle);
- case BndScript:
- default:
- break;
+ /**
+ * Add bundles to the list of managed bundles.
+ *
+ * @param bundles the bundles to add
+ */
+ public void add(List<GhidraBundle> bundles) {
+ for (GhidraBundle bundle : bundles) {
+ bundlePathToBundleMap.put(bundle.getPath(), bundle);
+ bundleLocationToBundleMap.put(bundle.getBundleLocation(), bundle);
}
- return new GhidraPlaceholderBundle(bh, path, enabled, systemBundle);
+ fireBundlesAdded(bundles);
}
- // XXX consumers must clean up after themselves
+ /**
+ * Remove a bundle from the list of managed bundles.
+ *
+ * @param bundlePath the path of the bundle to remove
+ */
public void removeBundlePath(ResourceFile bundlePath) {
- GhidraBundle gb = bp2gb.remove(bundlePath);
- bl2gb.remove(gb.getBundleLoc());
- fireBundleRemoved(gb);
- }
-
- public void removeBundleLoc(String bundleLoc) {
- GhidraBundle gb = bl2gb.remove(bundleLoc);
- bp2gb.remove(gb.getPath());
- fireBundleRemoved(gb);
- }
-
- public void remove(GhidraBundle gb) {
- bp2gb.remove(gb.getPath());
- bl2gb.remove(gb.getBundleLoc());
- fireBundleRemoved(gb);
- }
-
- public void remove(Collection<GhidraBundle> gbundles) {
- for (GhidraBundle gb : gbundles) {
- bp2gb.remove(gb.getPath());
- bl2gb.remove(gb.getBundleLoc());
- }
- fireBundlesRemoved(gbundles);
+ GhidraBundle bundle = bundlePathToBundleMap.remove(bundlePath);
+ bundleLocationToBundleMap.remove(bundle.getBundleLocation());
+ fireBundleRemoved(bundle);
}
/**
- * parse Import-Package string from a bundle manifest
+ * Remove a bundle from the list of managed bundles.
*
- * @param imports Import-Package value
- * @return deduced requirements or null if there was an error
- * @throws BundleException on parse failure
+ * @param bundleLocation the location id of the bundle to remove
*/
- static List<BundleRequirement> parseImports(String imports) throws BundleException {
- // parse it with Felix's ManifestParser to a list of BundleRequirement objects
- Map<String, Object> headerMap = new HashMap<>();
- headerMap.put(Constants.IMPORT_PACKAGE, imports);
- ManifestParser mp;
- mp = new ManifestParser(null, null, null, headerMap);
- return mp.getRequirements();
+ public void removeBundleLoc(String bundleLocation) {
+ GhidraBundle bundle = bundleLocationToBundleMap.remove(bundleLocation);
+ bundlePathToBundleMap.remove(bundle.getPath());
+ fireBundleRemoved(bundle);
}
/**
- * cache of data corresponding to a source directory that is bound to be an exploded bundle
+ * Remove a bundle from the list of managed bundles.
+ *
+ * @param bundle the bundle to remove
*/
- public static class BuildFailure {
- long when = -1;
- StringBuilder message = new StringBuilder();
+ public void remove(GhidraBundle bundle) {
+ bundlePathToBundleMap.remove(bundle.getPath());
+ bundleLocationToBundleMap.remove(bundle.getBundleLocation());
+ fireBundleRemoved(bundle);
}
- String buildExtraPackages() {
- Set<String> packages = new HashSet<>();
- getPackagesFromClasspath(packages);
- return packages.stream().collect(Collectors.joining(","));
+ /**
+ * Remove bundles from the list of managed bundles.
+ *
+ * @param bundles the bundles to remove
+ */
+ public void remove(Collection<GhidraBundle> bundles) {
+ for (GhidraBundle bundle : bundles) {
+ bundlePathToBundleMap.remove(bundle.getPath());
+ bundleLocationToBundleMap.remove(bundle.getBundleLocation());
+ }
+ fireBundlesRemoved(bundles);
}
- BundleContext bc;
- Framework felix;
- Bundle fileinstall_bundle;
-
Bundle installFromPath(Path p) throws GhidraBundleException {
return installFromLoc("file://" + p.toAbsolutePath().normalize().toString());
}
- public Bundle installFromLoc(String bundle_loc) throws GhidraBundleException {
+ /**
+ * Try to install a bundle.
+ *
+ *
+ * @param bundle the bundle to install
+ * @return the OSGi bundle returned by the framework
+ * @throws GhidraBundleException when install fails
+ */
+ public Bundle install(GhidraBundle bundle) throws GhidraBundleException {
+ try {
+ return frameworkBundleContext.installBundle(bundle.getBundleLocation());
+ }
+ catch (BundleException e) {
+ throw new GhidraBundleException(bundle.getBundleLocation(),
+ "installing from bundle location", e);
+ }
+ }
+
+ Bundle installFromLoc(String bundleLocation) throws GhidraBundleException {
try {
- return bc.installBundle(bundle_loc);
+ return frameworkBundleContext.installBundle(bundleLocation);
}
catch (BundleException e) {
- throw new GhidraBundleException(bundle_loc, "installing from bundle location", e);
+ throw new GhidraBundleException(bundleLocation, "installing from bundle location", e);
}
}
- Bundle installAsLoc(String bundle_loc, InputStream contents) throws GhidraBundleException {
+ Bundle installAsLoc(String bundleLocation, InputStream contents) throws GhidraBundleException {
try {
- return bc.installBundle(bundle_loc, contents);
+ return frameworkBundleContext.installBundle(bundleLocation, contents);
}
catch (BundleException e) {
- throw new GhidraBundleException(bundle_loc, "installing as bundle location", e);
+ throw new GhidraBundleException(bundleLocation, "installing as bundle location", e);
}
}
+ /**
+ * return all of the currently managed bundles
+ *
+ * @return all the bundles
+ */
+ public Collection<GhidraBundle> getGhidraBundles() {
+ return bundlePathToBundleMap.values();
+ }
+
+ /**
+ * return paths of currently managed bundles
+ *
+ * @return all the bundle paths
+ */
+ public Collection<ResourceFile> getBundlePaths() {
+ return bundlePathToBundleMap.keySet();
+ }
+
void dumpLoadedBundles() {
System.err.printf("=== Bundles ===\n");
- for (Bundle bundle : bc.getBundles()) {
+ for (Bundle bundle : frameworkBundleContext.getBundles()) {
System.err.printf("%s: %s: %s: %s\n", bundle.getBundleId(), bundle.getSymbolicName(),
bundle.getState(), bundle.getVersion());
}
@@ -237,9 +325,9 @@ public class BundleHost {
public List<BundleWiring> resolve(List<BundleRequirement> reqs) {
// enumerate active bundles, looking for capabilities meeting our requirements
List<BundleWiring> bundleWirings = new ArrayList<>();
- for (Bundle b : bc.getBundles()) {
- if (b.getState() == Bundle.ACTIVE) {
- BundleWiring bw = b.adapt(BundleWiring.class);
+ for (Bundle bundle : frameworkBundleContext.getBundles()) {
+ if (bundle.getState() == Bundle.ACTIVE) {
+ BundleWiring bw = bundle.adapt(BundleWiring.class);
boolean keeper = false;
for (BundleCapability cap : bw.getCapabilities(null)) {
Iterator<BundleRequirement> it = reqs.iterator();
@@ -259,68 +347,70 @@ public class BundleHost {
return bundleWirings;
}
- public boolean canResolveAll(Collection<BundleRequirement> reqs) {
- LinkedList<BundleRequirement> tmp = new LinkedList<>(reqs);
- resolve(tmp);
- return tmp.isEmpty();
+ /**
+ * Attempt to resolve {@code requirements} against the currently active bundles.
+ *
+ * @param requirements a list of {@link BundleRequirement} objects
+ * @return true if all of the requiremetns can be resolved
+ */
+ public boolean canResolveAll(Collection<BundleRequirement> requirements) {
+ LinkedList<BundleRequirement> tmpRequirements = new LinkedList<>(requirements);
+ resolve(tmpRequirements);
+ return tmpRequirements.isEmpty();
}
- class FelixStderrLogger extends org.apache.felix.framework.Logger {
+ private class FelixStderrLogger extends Logger {
@Override
- protected void doLog(int level, String msg, Throwable throwable) {
- System.err.printf("felixlogger: %s %s\n", msg, throwable);
+ protected void doLog(int level, String message, Throwable throwable) {
+ System.err.printf("felixlogger: %s %s\n", message, throwable);
}
@Override
- protected void doLogOut(int level, String msg, Throwable throwable) {
- System.err.printf("felixlogger: %s %s\n", msg, throwable);
+ protected void doLogOut(int level, String message, Throwable throwable) {
+ System.err.printf("felixlogger: %s %s\n", message, throwable);
}
@SuppressWarnings("rawtypes")
@Override
protected void doLog(final Bundle bundle, final ServiceReference sr, final int level,
- final String msg, final Throwable throwable) {
- System.err.printf("felixlogger: %s %s %s\n", bundle, msg, throwable);
- }
-
- }
-
- 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 "???";
+ final String message, final Throwable throwable) {
+ System.err.printf("felixlogger: %s %s %s\n", bundle, message, throwable);
}
+
+ }
+
+ protected String buildExtraSystemPackages() {
+ Set<String> packages = new HashSet<>();
+ OSGiUtils.getPackagesFromClasspath(packages);
+ return packages.stream().collect(Collectors.joining(","));
}
/**
- * start the framework
+ * A subdirectory of the user settings directory for storing OSGi artifacts.
*
- * @throws OSGiException framework failures
- * @throws IOException filesystem setup
+ * @return the path
*/
- public void startFramework() throws OSGiException, IOException {
+ public static Path getOsgiDir() {
+ Path usersettings = Application.getUserSettingsDirectory().toPath();
+ return usersettings.resolve("osgi");
+ }
+
+ /**
+ * A directory for use by Felix as a cache
+ * @return the directory
+ */
+ protected static Path getCacheDir() {
+ return BundleHost.getOsgiDir().resolve("felixcache");
+ }
+
+ private static String makeCacheDir() throws IOException {
+ Path cacheDir = getCacheDir();
+ Files.createDirectories(cacheDir);
+ return cacheDir.toAbsolutePath().toString();
+ }
+ protected void createAndConfigureFramework() throws IOException {
Properties config = new Properties();
// allow multiple bundles w/ the same symbolic name -- location can distinguish
@@ -330,7 +420,7 @@ public class BundleHost {
// compute and add everything in the class path. extra packages have lower precedence than imports,
// so an Import-Package / @importpackage will override the "living off the land" default
- config.setProperty(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, buildExtraPackages());
+ config.setProperty(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, buildExtraSystemPackages());
// only clean on first startup, o/w keep our storage around
config.setProperty(Constants.FRAMEWORK_STORAGE_CLEAN,
@@ -340,97 +430,80 @@ public class BundleHost {
config.setProperty(Constants.FRAMEWORK_STORAGE, makeCacheDir());
config.put(FelixConstants.LOG_LEVEL_PROP, "1");
- if (DUMP_TO_STDERR) {
+ if (STDERR_DEBUGGING) {
config.put(FelixConstants.LOG_LEVEL_PROP, "999");
config.put(FelixConstants.LOG_LOGGER_PROP, new FelixStderrLogger());
}
FrameworkFactory factory = new FrameworkFactory();
- felix = factory.newFramework(config);
-
- try {
- felix.init();
- }
- catch (BundleException e) {
- throw new OSGiException("initializing felix OSGi framework", e);
- }
- bc = felix.getBundleContext();
+ felixFramework = factory.newFramework(config);
+ }
- ServiceReference<LogReaderService> ref = bc.getServiceReference(LogReaderService.class);
- if (ref != null) {
- LogReaderService reader = bc.getService(ref);
- reader.addLogListener(new LogListener() {
+ protected void addDebuggingListeners() {
+ frameworkBundleContext.addFrameworkListener(new FrameworkListener() {
+ @Override
+ public void frameworkEvent(FrameworkEvent event) {
+ System.err.printf("%s %s\n", event.getBundle(), event);
+ }
+ });
+ frameworkBundleContext.addServiceListener(new ServiceListener() {
+ @Override
+ public void serviceChanged(ServiceEvent event) {
- @Override
- public void logged(LogEntry entry) {
- // plugin.printf("%s: %s\n", entry.getBundle(), entry.getMessage());
+ String type = "?";
+ if (event.getType() == ServiceEvent.REGISTERED) {
+ type = "registered";
}
- });
- }
- else {
- // plugin.printf("no logreaderservice in felix!\n");
- }
-
- if (DUMP_TO_STDERR) {
- bc.addFrameworkListener(new FrameworkListener() {
- @Override
- public void frameworkEvent(FrameworkEvent event) {
- System.err.printf("%s %s\n", event.getBundle(), event);
+ else if (event.getType() == ServiceEvent.UNREGISTERING) {
+ type = "unregistering";
}
- });
- bc.addServiceListener(new ServiceListener() {
- @Override
- public void serviceChanged(ServiceEvent event) {
- String type = "?";
- if (event.getType() == ServiceEvent.REGISTERED) {
- type = "registered";
- }
- else if (event.getType() == ServiceEvent.UNREGISTERING) {
- type = "unregistering";
- }
-
- System.err.printf("%s %s from %s\n", event.getSource(), type,
- event.getServiceReference().getBundle().getLocation());
+ System.err.printf("%s %s from %s\n", event.getSource(), type,
+ event.getServiceReference().getBundle().getLocation());
- }
- });
- }
+ }
+ });
+ }
- final Bundle systemBundle = bc.getBundle();
- bc.addBundleListener(new BundleListener() {
+ /**
+ * add the {@code BundleListener} that notifies listeners of bundle activation changes
+ */
+ protected void addBundleListener() {
+ final Bundle systemBundle = frameworkBundleContext.getBundle();
+ frameworkBundleContext.addBundleListener(new BundleListener() {
@Override
public void bundleChanged(BundleEvent event) {
- Bundle b = event.getBundle();
+ Bundle osgiBundle = event.getBundle();
- if (b == systemBundle) {
+ // ignore events on the system bundle
+ if (osgiBundle == systemBundle) {
return;
}
- if (DUMP_TO_STDERR) {
- String n = b.getSymbolicName();
- String l = b.getLocation();
- System.err.printf("%s %s from %s\n", getEventTypeString(event), n, l);
+ if (STDERR_DEBUGGING) {
+ String n = osgiBundle.getSymbolicName();
+ String l = osgiBundle.getLocation();
+ System.err.printf("%s %s from %s\n", OSGiUtils.getEventTypeString(event), n, l);
}
- GhidraBundle gb;
+ GhidraBundle bundle;
switch (event.getType()) {
case BundleEvent.STARTED:
- gb = bl2gb.get(b.getLocation());
- if (gb != null) {
- fireBundleActivationChange(gb, true);
+ bundle = bundleLocationToBundleMap.get(osgiBundle.getLocation());
+ if (bundle != null) {
+ fireBundleActivationChange(bundle, true);
}
else {
- Msg.error(this,
- String.format("not a GhidraBundle: %s\n", b.getLocation()));
+ Msg.error(this, String.format("not a GhidraBundle: %s\n",
+ osgiBundle.getLocation()));
}
break;
case BundleEvent.UNINSTALLED:
- gb = bl2gb.get(b.getLocation());
- if (gb != null) {
- fireBundleActivationChange(gb, false);
+ bundle = bundleLocationToBundleMap.get(osgiBundle.getLocation());
+ if (bundle != null) {
+ fireBundleActivationChange(bundle, false);
}
else {
- Msg.error(this,
- String.format("not a GhidraBundle: %s\n", b.getLocation()));
+ Msg.error(this, String.format("not a GhidraBundle: %s\n",
+ osgiBundle.getLocation()));
}
break;
default:
@@ -438,242 +511,262 @@ public class BundleHost {
}
}
});
+ }
+
+ /**
+ * start the framework
+ *
+ * @throws OSGiException framework failures
+ * @throws IOException filesystem setup
+ */
+ public void startFramework() throws OSGiException, IOException {
+ createAndConfigureFramework();
try {
- felix.start();
+ felixFramework.init();
}
catch (BundleException e) {
- throw new OSGiException("starting felix OSGi framework", e);
+ throw new OSGiException("initializing felix OSGi framework", e);
}
- }
+ frameworkBundleContext = felixFramework.getBundleContext();
- public static Path getCompiledBundlesDir() {
- return getOsgiDir().resolve("compiled-bundles");
- }
+ if (STDERR_DEBUGGING) {
+ addDebuggingListeners();
+ }
- public static Path getOsgiDir() {
- Path usersettings = Application.getUserSettingsDirectory().toPath();
- return usersettings.resolve("osgi");
+ addBundleListener();
+
+ try {
+ felixFramework.start();
+ }
+ catch (BundleException e) {
+ throw new OSGiException("starting felix OSGi framework", e);
+ }
}
- static public Path getCacheDir() {
- return BundleHost.getOsgiDir().resolve("felixcache");
+ /**
+ * stop the OSGi framework synchronously
+ */
+ protected void stopFramework() {
+ if (felixFramework != null) {
+ try {
+ felixFramework.stop();
+ felixFramework.waitForStop(5000);
+ felixFramework = null;
+ }
+ catch (BundleException | InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
}
- private String makeCacheDir() throws IOException {
- Path cache_dir = getCacheDir();
- Files.createDirectories(cache_dir);
- return cache_dir.toAbsolutePath().toString();
+ /**
+ * @return the OSGi framework
+ */
+ Framework getHostFramework() {
+ return felixFramework;
}
- public Bundle getBundle(String bundleLoc) {
- return bc.getBundle(bundleLoc);
+ /**
+ * Get the OSGi bundle with the given bundle location identifier.
+ *
+ * @param bundleLocation the bundle location identifier
+ * @return the OSGi bundle or null
+ */
+ Bundle getOSGiBundle(String bundleLocation) {
+ return frameworkBundleContext.getBundle(bundleLocation);
}
- static private boolean oneOf(Bundle b, int... bundle_states) {
- Integer s = b.getState();
- return IntStream.of(bundle_states).anyMatch(s::equals);
+ private static boolean anyMatch(Bundle bundle, int... bundleStates) {
+ Integer s = bundle.getState();
+ return IntStream.of(bundleStates).anyMatch(s::equals);
}
- static private void waitFor(Bundle b, int... bundle_states) throws InterruptedException {
+ private static void waitFor(Bundle bundle, int... bundleStates) throws InterruptedException {
while (true) {
- if (oneOf(b, bundle_states)) {
+ if (anyMatch(bundle, bundleStates)) {
return;
}
Thread.sleep(500);
}
}
- public void activateSynchronously(Bundle b) throws InterruptedException, GhidraBundleException {
- if (b.getState() == Bundle.ACTIVE) {
+ /**
+ * Activate a bundle, returning only after the bundle is active.
+ *
+ * @param bundle the bundle
+ * @throws InterruptedException if the wait is interrupted
+ * @throws GhidraBundleException if there's a problem activating
+ */
+ public void activateSynchronously(Bundle bundle)
+ throws InterruptedException, GhidraBundleException {
+ if (bundle.getState() == Bundle.ACTIVE) {
return;
}
try {
- b.start();
+ bundle.start();
}
catch (BundleException e) {
- GhidraBundleException gbe = new GhidraBundleException(b, "activating bundle", e);
+ GhidraBundleException gbe = new GhidraBundleException(bundle, "activating bundle", e);
fireBundleException(gbe);
throw gbe;
}
- waitFor(b, Bundle.ACTIVE);
+ waitFor(bundle, Bundle.ACTIVE);
}
- public void activateSynchronously(String bundleLoc)
+ /**
+ * Activate a bundle, returning only after the bundle is active.
+ *
+ * @param bundleLocation the bundle location identifier
+ * @throws InterruptedException if the wait is interrupted
+ * @throws GhidraBundleException if there's a problem activating
+ */
+ public void activateSynchronously(String bundleLocation)
throws GhidraBundleException, InterruptedException {
- Bundle bundle = getBundle(bundleLoc);
+ Bundle bundle = getOSGiBundle(bundleLocation);
if (bundle == null) {
- bundle = installFromLoc(bundleLoc);
+ bundle = installFromLoc(bundleLocation);
}
activateSynchronously(bundle);
}
- public void deactivateSynchronously(Bundle b)
+ /**
+ * Deactivate a bundle, returning only after the bundle is inactive.
+ *
+ * @param bundle the bundle
+ * @throws InterruptedException if the wait is interrupted
+ * @throws GhidraBundleException if there's a problem activating
+ */
+ public void deactivateSynchronously(Bundle bundle)
throws InterruptedException, GhidraBundleException {
- if (b.getState() == Bundle.UNINSTALLED) {
+ if (bundle.getState() == Bundle.UNINSTALLED) {
return;
}
- FrameworkWiring fw = felix.adapt(FrameworkWiring.class);
- LinkedList<Bundle> dependents =
- new LinkedList<Bundle>(fw.getDependencyClosure(Collections.singleton(b)));
- while (!dependents.isEmpty()) {
- b = dependents.pop();
+ FrameworkWiring frameworkWiring = felixFramework.adapt(FrameworkWiring.class);
+ LinkedList<Bundle> dependentBundles = new LinkedList<Bundle>(
+ frameworkWiring.getDependencyClosure(Collections.singleton(bundle)));
+ while (!dependentBundles.isEmpty()) {
+ Bundle dependentBundle = dependentBundles.pop();
try {
- b.uninstall();
- fw.refreshBundles(dependents);
+ dependentBundle.uninstall();
+ frameworkWiring.refreshBundles(dependentBundles);
}
catch (BundleException e) {
- GhidraBundleException gbe = new GhidraBundleException(b, "deactivating bundle", e);
- fireBundleException(gbe);
- throw gbe;
+ GhidraBundleException exception =
+ new GhidraBundleException(dependentBundle, "deactivating bundle", e);
+ fireBundleException(exception);
+ throw exception;
}
- waitFor(b, Bundle.UNINSTALLED);
+ waitFor(dependentBundle, Bundle.UNINSTALLED);
}
}
- public void deactivateSynchronously(String bundleLoc)
+ /**
+ * Deactivate a bundle, returning only after the bundle is inactive.
+ *
+ * @param bundleLocation the bundle location identifier
+ * @throws InterruptedException if the wait is interrupted
+ * @throws GhidraBundleException if there's a problem activating
+ */
+ public void deactivateSynchronously(String bundleLocation)
throws GhidraBundleException, InterruptedException {
- Bundle b = getBundle(bundleLoc);
- if (b != null) {
- deactivateSynchronously(b);
+ Bundle bundle = getOSGiBundle(bundleLocation);
+ if (bundle != null) {
+ deactivateSynchronously(bundle);
}
}
- void disposeFramework() {
- if (felix != null) {
- try {
- felix.stop();
- felix.waitForStop(5000);
- felix = null;
- }
- catch (BundleException | InterruptedException e) {
- e.printStackTrace();
- }
+ /**
+ * Remove a listener for OSGi framework events.
+ *
+ * @param bundleHostListener the listener
+ */
+ public void removeListener(BundleHostListener bundleHostListener) {
+ synchronized (listeners) {
+ listeners.remove(bundleHostListener);
}
}
- void forceStopFrameworkTask() {
- Task t = new Task("killing OSGi framework", false, false, true, true) {
- @Override
- public void run(TaskMonitor monitor) throws CancelledException {
- disposeFramework();
+ protected void activateAll(Collection<GhidraBundle> bundles, TaskMonitor monitor,
+ PrintWriter console) {
+ List<GhidraBundle> bundlesRemaining = new ArrayList<>(bundles);
+
+ monitor.setMaximum(bundlesRemaining.size());
+ while (!bundlesRemaining.isEmpty() && !monitor.isCancelled()) {
+ List<GhidraBundle> resolvableBundles = bundlesRemaining.stream()
+ .filter(bundle -> canResolveAll(bundle.getAllRequirements()))
+ .collect(Collectors.toList());
+ if (resolvableBundles.isEmpty()) {
+ // final round, try everything we couldn't resolve to generate errors
+ resolvableBundles = bundlesRemaining;
+ bundlesRemaining = Collections.emptyList();
}
-
- };
- new TaskLauncher(t, null);
- }
-
- public Framework getHostFramework() {
- return felix;
- }
-
- // from https://dzone.com/articles/locate-jar-classpath-given
- static String findJarForClass(Class<?> c) {
- final URL location;
- final String classLocation = c.getName().replace('.', '/') + ".class";
- final ClassLoader loader = c.getClassLoader();
- if (loader == null) {
- location = ClassLoader.getSystemResource(classLocation);
- }
- else {
- location = loader.getResource(classLocation);
- }
- if (location != null) {
- Pattern p = Pattern.compile("^.*:(.*)!.*$");
- Matcher m = p.matcher(location.toString());
- if (m.find()) {
- return m.group(1);
- }
- return null; // not loaded from jar?
- }
- return null;
- }
-
- static void getPackagesFromClasspath(Set<String> s) {
- getClasspathElements().forEach(p -> {
- if (Files.isDirectory(p)) {
- collectPackagesFromDirectory(p, s);
+ else {
+ bundlesRemaining.removeAll(resolvableBundles);
}
- else if (p.toString().endsWith(".jar")) {
- collectPackagesFromJar(p, s);
+
+ for (GhidraBundle bundle : resolvableBundles) {
+ if (monitor.isCancelled()) {
+ break;
+ }
+ try {
+ bundle.build(console);
+ activateSynchronously(bundle.getBundleLocation());
+ }
+ catch (Exception e) {
+ e.printStackTrace(console);
+ }
+ monitor.incrementProgress(1);
}
- });
- }
-
- static Stream<Path> getClasspathElements() {
- String classpathStr = System.getProperty("java.class.path");
- return Collections.list(new StringTokenizer(classpathStr, File.pathSeparator)).stream().map(
- String.class::cast).map(Paths::get).map(Path::normalize);
- }
-
- static void collectPackagesFromDirectory(Path dirPath, Set<String> s) {
- try {
- Files.walk(dirPath).filter(p -> p.toString().endsWith(".class")).forEach(p -> {
- String n = dirPath.relativize(p).toString();
- int lastSlash = n.lastIndexOf(File.separatorChar);
- s.add(lastSlash > 0 ? n.substring(0, lastSlash).replace(File.separatorChar, '.')
- : "");
- });
-
- }
- catch (IOException e) {
- e.printStackTrace();
}
}
- static void collectPackagesFromJar(Path jarPath, Set<String> s) {
- try {
- try (JarFile j = new JarFile(jarPath.toFile())) {
- j.stream().filter(je -> je.getName().endsWith(".class")).forEach(je -> {
- String n = je.getName();
- int lastSlash = n.lastIndexOf('/');
- s.add(lastSlash > 0 ? n.substring(0, lastSlash).replace('/', '.') : "");
- });
- }
- }
- catch (IOException e) {
- e.printStackTrace();
- }
+ /**
+ * Used by {@link GhidraBundle}s to notify the host that a bundle has been built.
+ *
+ * @param bundle the bundle that was built
+ * @param summary a summary of anything notable (errors or warnings) during the build
+ */
+ void notifyBundleBuilt(GhidraBundle bundle, String summary) {
+ fireBundleBuilt(bundle, summary);
}
- List<BundleHostListener> listeners = new ArrayList<>();
-
- void fireBundleBuilt(GhidraBundle gb, String summary) {
+ private void fireBundleBuilt(GhidraBundle bundle, String summary) {
synchronized (listeners) {
for (BundleHostListener l : listeners) {
- l.bundleBuilt(gb, summary);
+ l.bundleBuilt(bundle, summary);
}
}
}
- void fireBundleEnablementChange(GhidraBundle gb, boolean newEnablement) {
+ private void fireBundleEnablementChange(GhidraBundle bundle, boolean newEnablement) {
synchronized (listeners) {
for (BundleHostListener l : listeners) {
- l.bundleEnablementChange(gb, newEnablement);
+ l.bundleEnablementChange(bundle, newEnablement);
}
}
}
- void fireBundleActivationChange(GhidraBundle gb, boolean newEnablement) {
+ private void fireBundleActivationChange(GhidraBundle bundle, boolean newEnablement) {
synchronized (listeners) {
for (BundleHostListener l : listeners) {
- l.bundleActivationChange(gb, newEnablement);
+ l.bundleActivationChange(bundle, newEnablement);
}
}
}
- private void fireBundleAdded(GhidraBundle gb) {
+ private void fireBundleAdded(GhidraBundle bundle) {
synchronized (listeners) {
for (BundleHostListener l : listeners) {
- l.bundleAdded(gb);
+ l.bundleAdded(bundle);
}
}
}
- private void fireBundleRemoved(GhidraBundle gb) {
+ private void fireBundleRemoved(GhidraBundle bundle) {
synchronized (listeners) {
for (BundleHostListener l : listeners) {
- l.bundleRemoved(gb);
+ l.bundleRemoved(bundle);
}
}
}
@@ -702,140 +795,106 @@ public class BundleHost {
}
}
+ /**
+ * Add a listener for OSGi framework events.
+ *
+ * @param bundleHostListener the listener
+ */
public void addListener(BundleHostListener bundleHostListener) {
synchronized (listeners) {
listeners.add(bundleHostListener);
}
}
- public void removeListener(BundleHostListener bundleHostListener) {
- synchronized (listeners) {
- listeners.remove(bundleHostListener);
- }
- }
-
- public void removeAllListeners() {
- synchronized (listeners) {
- listeners.clear();
+ private void startActivateAllTask(Collection<GhidraBundle> bundlesToActivate) {
+ if (!bundlesToActivate.isEmpty()) {
+ new TaskLauncher(new Task("restoring bundle state", true, true, false) {
+ @Override
+ public void run(TaskMonitor monitor) throws CancelledException {
+ activateAll(bundlesToActivate, monitor, new NullPrintWriter());
+ }
+ });
}
}
- public Collection<GhidraBundle> getGhidraBundles() {
- return bp2gb.values();
- }
-
- public Collection<ResourceFile> getBundlePaths() {
- return bp2gb.keySet();
- }
-
- /*
- * this is done at most once, and it's done AFTER system bundles have been added.
+ /**
+ * Restore the list of managed bundles from {@code saveState} and each bundle's state.
+ *
+ * Bundles that had been active are reactivated.
+ *
+ * note: This is done once on startup, AFTER system bundles have been added.
+ *
+ * @param saveState the state object
+ * @param tool the tool
*/
- public void restoreStateAndActivate(SaveState ss, PluginTool tool) {
- // XXX lock bundlehost operations
- String[] pathArr = ss.getStrings("BundleHost_PATH", new String[0]);
-
- if (pathArr.length == 0) {
- return;
- }
-
- boolean[] enableArr = ss.getBooleans("BundleHost_ENABLE", new boolean[pathArr.length]);
- boolean[] activeArr = ss.getBooleans("BundleHost_ACTIVE", new boolean[pathArr.length]);
- boolean[] systemArr = ss.getBooleans("BundleHost_SYSTEM", new boolean[pathArr.length]);
-
- List<GhidraBundle> added = new ArrayList<>();
- List<GhidraBundle> need_activation = new ArrayList<>();
- for (int i = 0; i < pathArr.length; i++) {
-
- ResourceFile bp = generic.util.Path.fromPathString(pathArr[i]);
- boolean en = enableArr[i];
- boolean act = activeArr[i];
- boolean sys = systemArr[i];
- GhidraBundle gb = bp2gb.get(bp);
- if (gb != null) {
- if (en != gb.isEnabled()) {
- gb.setEnabled(en);
- fireBundleEnablementChange(gb, en);
+ public void restoreManagedBundleState(SaveState saveState, PluginTool tool) {
+ String[] bundlePaths = saveState.getStrings(saveStateTagPath, new String[0]);
+
+ boolean[] bundleIsEnabled =
+ saveState.getBooleans(saveStateTagEnabled, new boolean[bundlePaths.length]);
+ boolean[] bundleIsActive =
+ saveState.getBooleans(saveStateTagActive, new boolean[bundlePaths.length]);
+ boolean[] bundleIsSystem =
+ saveState.getBooleans(saveStateTagSystem, new boolean[bundlePaths.length]);
+
+ List<GhidraBundle> newBundles = new ArrayList<>();
+ List<GhidraBundle> bundlesToActivate = new ArrayList<>();
+ for (int i = 0; i < bundlePaths.length; i++) {
+ ResourceFile bundlePath = generic.util.Path.fromPathString(bundlePaths[i]);
+ boolean isEnabled = bundleIsEnabled[i];
+ boolean isActive = bundleIsActive[i];
+ boolean isSystem = bundleIsSystem[i];
+ GhidraBundle bundle = bundlePathToBundleMap.get(bundlePath);
+ if (bundle != null) {
+ if (isEnabled != bundle.isEnabled()) {
+ bundle.setEnabled(isEnabled);
+ fireBundleEnablementChange(bundle, isEnabled);
}
- if (sys != gb.isSystemBundle()) {
- gb.systemBundle = sys;
- Msg.error(this, String.format("%s went from %system to %system", bp,
- sys ? "not " : "", sys ? "" : "not "));
+ if (isSystem != bundle.isSystemBundle()) {
+ bundle.systemBundle = isSystem;
+ Msg.error(this, String.format("%s went from %system to %system", bundlePath,
+ isSystem ? "not " : "", isSystem ? "" : "not "));
}
}
- else if (sys) {
+ else if (isSystem) {
// stored system bundles that weren't already initialized must be old, drop 'm.
}
else {
- added.add(gb = newGhidraBundle(this, bp, en, sys));
+ newBundles.add(bundle = newGhidraBundle(this, bundlePath, isEnabled, isSystem));
}
- if (gb != null && act) {
- need_activation.add(gb);
+ if (bundle != null && isActive) {
+ bundlesToActivate.add(bundle);
}
}
- add(added);
-
- new TaskLauncher(new Task("restoring bundle state", true, true, false) {
- @Override
- public void run(TaskMonitor monitor) throws CancelledException {
- activateAll(need_activation, monitor, new NullPrintWriter());
- }
- });
+ add(newBundles);
+ startActivateAllTask(bundlesToActivate);
}
- public void saveState(SaveState ss) {
- int n = bp2gb.size();
- String[] pathArr = new String[n];
- boolean[] enableArr = new boolean[n];
- boolean[] activeArr = new boolean[n];
- boolean[] systemArr = new boolean[n];
+ /**
+ * Save the list of managed bundles and each bundle's state.
+ *
+ * @param saveState the state object
+ */
+ public void saveManagedBundleState(SaveState saveState) {
+ int numBundles = bundlePathToBundleMap.size();
+ String[] bundlePaths = new String[numBundles];
+ boolean[] bundleIsEnabled = new boolean[numBundles];
+ boolean[] bundleIsActive = new boolean[numBundles];
+ boolean[] bundleIsSystem = new boolean[numBundles];
int index = 0;
- for (Entry<ResourceFile, GhidraBundle> e : bp2gb.entrySet()) {
- GhidraBundle gb = e.getValue();
- pathArr[index] = generic.util.Path.toPathString(gb.getPath());
- enableArr[index] = gb.isEnabled();
- activeArr[index] = gb.isActive();
- systemArr[index] = gb.isSystemBundle();
+ for (GhidraBundle bundle : bundlePathToBundleMap.values()) {
+ bundlePaths[index] = generic.util.Path.toPathString(bundle.getPath());
+ bundleIsEnabled[index] = bundle.isEnabled();
+ bundleIsActive[index] = bundle.isActive();
+ bundleIsSystem[index] = bundle.isSystemBundle();
++index;
}
- ss.putStrings("BundleHost_PATH", pathArr);
- ss.putBooleans("BundleHost_ENABLE", enableArr);
- ss.putBooleans("BundleHost_ACTIVE", activeArr);
- ss.putBooleans("BundleHost_SYSTEM", systemArr);
- }
-
- protected void activateAll(List<GhidraBundle> gbs, TaskMonitor monitor, PrintWriter console) {
-
- monitor.setMaximum(gbs.size());
- while (!gbs.isEmpty() && !monitor.isCancelled()) {
- List<GhidraBundle> l =
- gbs.stream().filter(gb -> canResolveAll(gb.getAllReqs())).collect(
- Collectors.toList());
- if (l.isEmpty()) {
- // final round
- l = gbs;
- gbs = Collections.emptyList();
- }
- else {
- gbs.removeAll(l);
- }
-
- for (GhidraBundle gb : l) {
- if (monitor.isCancelled()) {
- break;
- }
- try {
- gb.build(console);
- activateSynchronously(gb.getBundleLoc());
- }
- catch (Exception e) {
- e.printStackTrace(console);
- }
- monitor.incrementProgress(1);
- }
- }
+ saveState.putStrings(saveStateTagPath, bundlePaths);
+ saveState.putBooleans(saveStateTagEnabled, bundleIsEnabled);
+ saveState.putBooleans(saveStateTagActive, bundleIsActive);
+ saveState.putBooleans(saveStateTagSystem, bundleIsSystem);
}
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleHostListener.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleHostListener.java
index e6ef58041d..6c07d356bb 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleHostListener.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleHostListener.java
@@ -22,39 +22,84 @@ import java.util.Collection;
*/
public interface BundleHostListener {
- default void bundleBuilt(GhidraBundle gbundle, String summary) {
+ /**
+ * Invoked when a bundle is built.
+ *
+ * @param bundle the bundle
+ * @param summary a summary of the build
+ */
+ default void bundleBuilt(GhidraBundle bundle, String summary) {
//
}
- default void bundleEnablementChange(GhidraBundle gbundle, boolean newEnablement) {
+ /**
+ * Invoked when a bundle is enabled or disabled.
+ *
+ * @param bundle the bundle
+ * @param newEnablement true if enabled, false if disabled
+ */
+ default void bundleEnablementChange(GhidraBundle bundle, boolean newEnablement) {
//
}
- default void bundleActivationChange(GhidraBundle gbundle, boolean newActivation) {
+ /**
+ * Invoked when a bundle is activated or deactivated.
+ *
+ * @param bundle the bundle
+ * @param newActivation true if activated, false if deactivated
+ */
+ default void bundleActivationChange(GhidraBundle bundle, boolean newActivation) {
//
}
- default void bundleAdded(GhidraBundle gbundle) {
+ /**
+ * Invoked when a bundle is added to {@link BundleHost}
+ *
+ * @param bundle the bundle
+ */
+ default void bundleAdded(GhidraBundle bundle) {
//
}
- default void bundlesAdded(Collection<GhidraBundle> gbundles) {
- for (GhidraBundle gbundle : gbundles) {
- bundleAdded(gbundle);
+ /**
+ * Invoked when a number of bundles is added at once. A listener should implement this method
+ * to avoid repeated invocation of {@link #bundleAdded} in quick succession.
+ *
+ * @param bundles the bundles
+ */
+ default void bundlesAdded(Collection<GhidraBundle> bundles) {
+ for (GhidraBundle bundle : bundles) {
+ bundleAdded(bundle);
}
}
- default void bundleRemoved(GhidraBundle gbundle) {
+ /**
+ * Invoked when a bundle is removed from {@link BundleHost}
+ *
+ * @param bundle the bundle
+ */
+ default void bundleRemoved(GhidraBundle bundle) {
//
}
- default void bundlesRemoved(Collection<GhidraBundle> gbundles) {
- for (GhidraBundle gbundle : gbundles) {
- bundleRemoved(gbundle);
+ /**
+ * Invoked when a number of bundles is removed at once. A listener should implement this method
+ * to avoid repeated invocation of {@link #bundleRemoved} in quick succession.
+ *
+ * @param bundles the bundles
+ */
+ default void bundlesRemoved(Collection<GhidraBundle> bundles) {
+ for (GhidraBundle bundle : bundles) {
+ bundleRemoved(bundle);
}
}
- default void bundleException(GhidraBundleException gbe) {
+ /**
+ * Invoked when {@link BundleHost} excepts during bundle activation/deactivation.
+ *
+ * @param exception the exception thrown
+ */
+ default void bundleException(GhidraBundleException exception) {
//
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleStatus.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleStatus.java
index 3b417c49ea..d2e46d988d 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleStatus.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleStatus.java
@@ -20,88 +20,125 @@ import generic.util.Path;
/**
* The BundleStatus class represents the runtime state and user preferences for OSGi bundles in Ghidra.
- *
- * XXX: this class relies on generic.util.Path solely for the parsing and formatting of USER_HOME and GHIDRA_HOME
*/
public class BundleStatus implements Comparable<BundleStatus> {
final Path path;
final GhidraBundle.Type type;
- final String bundleLoc;
+ final String bundleLocation;
boolean active = false;
boolean busy = false;
+ String summary;
+
+ BundleStatus(ResourceFile path, boolean enabled, boolean readonly, String bundleLoc) {
+ this.path = new Path(path, enabled, false, readonly);
+ type = GhidraBundle.getType(getPath());
+ this.bundleLocation = bundleLoc;
+ }
+
+ @Override
+ public int compareTo(BundleStatus o) {
+ return path.compareTo(o != null ? o.path : null);
+ }
+
+ /**
+ * @return true if the bundle is enabled
+ */
public boolean isEnabled() {
return path.isEnabled();
}
+ /**
+ * Set the bundle's status to enabled or disabled.
+ *
+ * @param isEnabled true to set status to enabled
+ */
public void setEnabled(boolean isEnabled) {
path.setEnabled(isEnabled);
}
+ /**
+ * @return true if the bundle is read only
+ */
public boolean isReadOnly() {
return path.isReadOnly();
}
- String summary;
-
+ /**
+ * @return the bundle type
+ *
+ * @see GhidraBundle.Type
+ */
public GhidraBundle.Type getType() {
return type;
}
- BundleStatus(ResourceFile path, boolean enabled, boolean readonly, String bundleLoc) {
- this.path = new Path(path, enabled, false, readonly);
- type = GhidraBundle.getType(getPath());
- this.bundleLoc = bundleLoc;
- }
-
- public boolean isDirectory() {
- return getPath().isDirectory();
- }
-
+ /**
+ * @return true if the bundle is active
+ */
public boolean isActive() {
return active;
}
- public void setActive(boolean b) {
- active = b;
- }
-
- public void setBusy(boolean b) {
- busy = b;
- }
-
- public boolean isBusy() {
- return busy;
+ /**
+ * Set the bundle's status to active or inactive.
+ *
+ * @param isActive true for active, false for inactive
+ */
+ public void setActive(boolean isActive) {
+ active = isActive;
}
+ /**
+ * Set the bundle's build summary.
+ *
+ * @param summary the build summary
+ */
public void setSummary(String summary) {
this.summary = summary;
}
+ /**
+ * @return the bundle's build summary
+ */
public String getSummary() {
return summary != null ? summary : "";
}
+ /**
+ * @return the bundle's path
+ */
public ResourceFile getPath() {
return path.getPath();
}
+ /**
+ * @return true if the bundle's path exists
+ */
public boolean pathExists() {
return path.exists();
}
- @Override
- public int compareTo(BundleStatus o) {
- return path.compareTo(o != null ? o.path : null);
- }
-
+ /**
+ * @return the bundle's path as a string, using $USER and $GHIDRA_HOME when appropriate
+ */
public String getPathAsString() {
return path.getPathAsString();
}
- public String getBundleLoc() {
- return bundleLoc;
+ /**
+ * @return the bundle's location identifier
+ */
+ public String getBundleLocation() {
+ return bundleLocation;
}
+ void setBusy(boolean isBusy) {
+ busy = isBusy;
+ }
+
+ boolean isBusy() {
+ return busy;
+ }
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleStatusChangeRequestListener.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleStatusChangeRequestListener.java
index 64f5136e32..4591602361 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleStatusChangeRequestListener.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleStatusChangeRequestListener.java
@@ -20,11 +20,23 @@ package ghidra.app.plugin.core.osgi;
*/
public interface BundleStatusChangeRequestListener {
- default public void bundleEnablementChangeRequest(BundleStatus status, boolean newValue) {
+ /**
+ * Invoked when the user requests that a bundle is enabled/disabled.
+ *
+ * @param status the current status
+ * @param newValue true if enabled, false if disabled
+ */
+ default void bundleEnablementChangeRequest(BundleStatus status, boolean newValue) {
//
}
- default public void bundleActivationChangeRequest(BundleStatus status, boolean newValue) {
+ /**
+ * Invoked when the user requests that a bundle is activated/deactivated.
+ *
+ * @param status the current status
+ * @param newValue true if activated, false if deactivated
+ */
+ default void bundleActivationChangeRequest(BundleStatus status, boolean newValue) {
//
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleStatusComponentProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleStatusComponentProvider.java
index b4615e4cef..9691c3fc7e 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleStatusComponentProvider.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleStatusComponentProvider.java
@@ -49,7 +49,10 @@ import resources.ResourceManager;
* component for managing OSGi bundle status
*/
public class BundleStatusComponentProvider extends ComponentProviderAdapter {
- static String preferenceForLastSelectedBundle = "LastGhidraBundle";
+ static final String BUNDLE_GROUP = "0bundle group";
+ static final String BUNDLE_LIST_GROUP = "1bundle list group";
+
+ static final String PREFENCE_LAST_SELECTED_BUNDLE = "LastGhidraBundle";
private JPanel panel;
private LessFreneticGTable bundleStatusTable;
@@ -60,9 +63,14 @@ public class BundleStatusComponentProvider extends ComponentProviderAdapter {
private GhidraFileFilter filter;
private final BundleHost bundleHost;
- static final String BUNDLE_GROUP = "0bundle group";
- static final String BUNDLE_LIST_GROUP = "1bundle list group";
-
+ /**
+ * {@link BundleStatusComponentProvider} visualizes bundle status and exposes actions for
+ * adding, removing, enabling, disabling, activating, and deactivating bundles.
+ *
+ * @param tool the tool
+ * @param owner the owner name
+ * @param bundleHost the bundle host
+ */
public BundleStatusComponentProvider(PluginTool tool, String owner, BundleHost bundleHost) {
super(tool, "BundleManager", owner);
setHelpLocation(new HelpLocation("BundleManager", "BundleManager"));
@@ -136,12 +144,24 @@ public class BundleStatusComponentProvider extends ComponentProviderAdapter {
// to allow custom cell renderers
bundleStatusTable.setAutoCreateColumnsFromModel(false);
+ configureTableColumns();
+ filterPanel = new GTableFilterPanel<>(bundleStatusTable, bundleStatusTableModel);
+
+ JScrollPane scrollPane = new JScrollPane(bundleStatusTable);
+ scrollPane.getViewport().setBackground(bundleStatusTable.getBackground());
+
+ panel.add(filterPanel, BorderLayout.SOUTH);
+ panel.add(scrollPane, BorderLayout.CENTER);
+ panel.setPreferredSize(new Dimension(800, 400));
+ }
+
+ private void configureTableColumns() {
TableColumn column;
int skinnyWidth = 60;
//
- column = bundleStatusTable.getColumnModel().getColumn(
- bundleStatusTableModel.enabledColumn.index);
+ column = bundleStatusTable.getColumnModel()
+ .getColumn(bundleStatusTableModel.enabledColumn.index);
column.setPreferredWidth(skinnyWidth);
column.setMinWidth(skinnyWidth);
column.setMaxWidth(skinnyWidth);
@@ -171,9 +191,7 @@ public class BundleStatusComponentProvider extends ComponentProviderAdapter {
setText("");
}
return x;
-
}
-
});
//
@@ -197,25 +215,14 @@ public class BundleStatusComponentProvider extends ComponentProviderAdapter {
return c;
}
});
-
- filterPanel = new GTableFilterPanel<>(bundleStatusTable, bundleStatusTableModel);
-
- JScrollPane scrollPane = new JScrollPane(bundleStatusTable);
- scrollPane.getViewport().setBackground(bundleStatusTable.getBackground());
-
- panel.add(filterPanel, BorderLayout.SOUTH);
- panel.add(scrollPane, BorderLayout.CENTER);
- panel.setPreferredSize(new Dimension(800, 400));
}
- private void createActions() {
- DockingAction action;
-
- //
- action = new DockingAction("ActivateBundles", this.getName()) {
+ private void addBundlesAction(String actionName, String description, Icon icon,
+ Runnable runnable) {
+ DockingAction action = new DockingAction(actionName, this.getName()) {
@Override
public void actionPerformed(ActionContext context) {
- doActivateBundles();
+ runnable.run();
}
@Override
@@ -223,56 +230,48 @@ public class BundleStatusComponentProvider extends ComponentProviderAdapter {
return bundleStatusTable.getSelectedRows().length > 0;
}
};
- action.setPopupMenuData(new MenuData(new String[] { "Activate bundle(s)" },
- ResourceManager.loadImage("images/media-playback-start.png"), BUNDLE_GROUP));
- action.setToolBarData(new ToolBarData(
- ResourceManager.loadImage("images/media-playback-start.png"), BUNDLE_GROUP));
- action.setDescription("Activate bundle(s)");
+ action.setPopupMenuData(new MenuData(new String[] { description }, icon, BUNDLE_GROUP));
+ action.setToolBarData(new ToolBarData(icon, BUNDLE_GROUP));
+ action.setDescription(description);
action.setEnabled(false);
getTool().addLocalAction(this, action);
- //
- action = new DockingAction("DeactivateBundles", this.getName()) {
+ }
+
+ private void addBundleListAction(String actionName, String name, String description, Icon icon,
+ Runnable runnable) {
+ DockingAction action = new DockingAction(actionName, this.getName()) {
@Override
public void actionPerformed(ActionContext context) {
- doDeactivateBundles();
+ runnable.run();
}
@Override
public boolean isEnabledForContext(ActionContext context) {
- return bundleStatusTable.getSelectedRows().length > 0;
+ return true;
}
};
- action.setPopupMenuData(new MenuData(new String[] { "Deactivate bundle(s)" },
- ResourceManager.loadImage("images/media-playback-stop.png"), BUNDLE_GROUP));
- action.setToolBarData(new ToolBarData(
- ResourceManager.loadImage("images/media-playback-stop.png"), BUNDLE_GROUP));
- action.setDescription("Deactivate bundle(s)");
- action.setEnabled(false);
+ action.setPopupMenuData(new MenuData(new String[] { name }, icon, BUNDLE_LIST_GROUP));
+ action.setToolBarData(new ToolBarData(icon, BUNDLE_LIST_GROUP));
+ action.setDescription(description);
+ action.setEnabled(true);
getTool().addLocalAction(this, action);
- //
- action = new DockingAction("CleanBundles", this.getName()) {
- @Override
- public void actionPerformed(ActionContext context) {
- doClean();
- }
+ }
- @Override
- public boolean isEnabledForContext(ActionContext context) {
- return bundleStatusTable.getSelectedRows().length > 0;
- }
- };
- // cache is a lightning bolt
- action.setPopupMenuData(new MenuData(new String[] { "Clean bundle(s)" },
- ResourceManager.loadImage("images/erase16.png"), BUNDLE_GROUP));
- action.setToolBarData(
- new ToolBarData(ResourceManager.loadImage("images/erase16.png"), BUNDLE_GROUP));
- action.setDescription("Clean build artifacts for bundle(s)");
- action.setEnabled(false);
- getTool().addLocalAction(this, action);
+ private void createActions() {
+ DockingAction action;
- //
+ addBundlesAction("ActivateBundles", "Activate bundle(s)",
+ ResourceManager.loadImage("images/media-playback-start.png"), this::doActivateBundles);
+
+ addBundlesAction("DeactivateBundles", "Deactivate bundle(s)",
+ ResourceManager.loadImage("images/media-playback-stop.png"), this::doDeactivateBundles);
+
+ addBundlesAction("CleanBundles", "Clean bundle(s)",
+ ResourceManager.loadImage("images/erase16.png"), this::doClean);
+
+ //
action = new DockingAction("AddBundles", this.getName()) {
@Override
public void actionPerformed(ActionContext context) {
@@ -285,16 +284,16 @@ public class BundleStatusComponentProvider extends ComponentProviderAdapter {
}
};
- action.setPopupMenuData(new MenuData(new String[] { "Add bundle(s)" },
- ResourceManager.loadImage("images/Plus.png"), BUNDLE_LIST_GROUP));
- action.setToolBarData(
- new ToolBarData(ResourceManager.loadImage("images/Plus.png"), BUNDLE_LIST_GROUP));
-
+ Icon icon = ResourceManager.loadImage("images/Plus.png");
+ action.setPopupMenuData(
+ new MenuData(new String[] { "Add bundle(s)" }, icon, BUNDLE_LIST_GROUP));
+ action.setToolBarData(new ToolBarData(icon, BUNDLE_LIST_GROUP));
action.setDescription("Display file chooser to add bundles to list");
action.setEnabled(true);
getTool().addLocalAction(this, action);
- //
+ //
+ icon = ResourceManager.loadImage("images/edit-delete.png");
action = new DockingAction("RemoveBundles", this.getName()) {
@Override
public void actionPerformed(ActionContext context) {
@@ -307,11 +306,9 @@ public class BundleStatusComponentProvider extends ComponentProviderAdapter {
}
};
- action.setPopupMenuData(new MenuData(new String[] { "Remove bundle(s)" },
- ResourceManager.loadImage("images/edit-delete.png"), BUNDLE_LIST_GROUP));
- action.setToolBarData(new ToolBarData(ResourceManager.loadImage("images/edit-delete.png"),
- BUNDLE_LIST_GROUP));
-
+ action.setPopupMenuData(
+ new MenuData(new String[] { "Remove bundle(s)" }, icon, BUNDLE_LIST_GROUP));
+ action.setToolBarData(new ToolBarData(icon, BUNDLE_LIST_GROUP));
action.setDescription("Remove selected bundle(s) from the list");
action.setEnabled(true);
getTool().addLocalAction(this, action);
@@ -341,7 +338,7 @@ public class BundleStatusComponentProvider extends ComponentProviderAdapter {
}
}
if (anythingCleaned) {
- getModel().fireTableDataChanged();
+ bundleStatusTableModel.fireTableDataChanged();
AnimationUtils.shakeComponent(getComponent());
}
}
@@ -354,9 +351,10 @@ public class BundleStatusComponentProvider extends ComponentProviderAdapter {
doDeactivateBundles();
Map<Boolean, List<GhidraBundle>> bundles =
- bundleStatusTableModel.getRowObjects(selectedModelRows).stream().map(
- bs -> bundleHost.getExistingGhidraBundle(bs.getPath())).collect(
- Collectors.partitioningBy(gb -> gb.isSystemBundle()));
+ bundleStatusTableModel.getRowObjects(selectedModelRows)
+ .stream()
+ .map(bs -> bundleHost.getExistingGhidraBundle(bs.getPath()))
+ .collect(Collectors.partitioningBy(gb -> gb.isSystemBundle()));
List<GhidraBundle> systemBundles = bundles.get(true);
if (!systemBundles.isEmpty()) {
StringBuilder sb = new StringBuilder();
@@ -388,19 +386,19 @@ public class BundleStatusComponentProvider extends ComponentProviderAdapter {
}
@Override
- public boolean accept(File f, GhidraFileChooserModel l_model) {
- return filter.accept(f, l_model);
+ public boolean accept(File f, GhidraFileChooserModel model) {
+ return filter.accept(f, model);
}
});
}
- String lastSelected = Preferences.getProperty(preferenceForLastSelectedBundle);
+ String lastSelected = Preferences.getProperty(PREFENCE_LAST_SELECTED_BUNDLE);
if (lastSelected != null) {
File f = new File(lastSelected);
fileChooser.setSelectedFile(f);
}
}
else {
- String lastSelected = Preferences.getProperty(preferenceForLastSelectedBundle);
+ String lastSelected = Preferences.getProperty(PREFENCE_LAST_SELECTED_BUNDLE);
if (lastSelected != null) {
File f = new File(lastSelected);
fileChooser.setSelectedFile(f);
@@ -410,10 +408,9 @@ public class BundleStatusComponentProvider extends ComponentProviderAdapter {
List<File> files = fileChooser.getSelectedFiles();
if (!files.isEmpty()) {
- Preferences.setProperty(preferenceForLastSelectedBundle,
- files.get(0).getAbsolutePath());
+ Preferences.setProperty(PREFENCE_LAST_SELECTED_BUNDLE, files.get(0).getAbsolutePath());
- bundleHost.addGhidraBundles(
+ bundleHost.add(
files.stream().map(ResourceFile::new).collect(Collectors.toUnmodifiableList()),
true, false);
}
@@ -429,8 +426,10 @@ public class BundleStatusComponentProvider extends ComponentProviderAdapter {
bundleStatusTable.chill();
List<BundleStatus> statuses =
- bundleStatusTableModel.getRowObjects(selectedModelRows).stream().filter(
- bs -> !bs.isActive()).collect(Collectors.toUnmodifiableList());
+ bundleStatusTableModel.getRowObjects(selectedModelRows)
+ .stream()
+ .filter(bs -> !bs.isActive())
+ .collect(Collectors.toUnmodifiableList());
List<GhidraBundle> gbs = new ArrayList<>();
for (BundleStatus bs : statuses) {
@@ -469,16 +468,16 @@ public class BundleStatusComponentProvider extends ComponentProviderAdapter {
new TaskLauncher(new Task("deactivating", true, true, false) {
@Override
public void run(TaskMonitor monitor) throws CancelledException {
- List<GhidraBundle> gbs =
- bundleStatusTableModel.getRowObjects(selectedModelRows).stream().filter(
- bs -> bs.isActive()).map(
- bs -> bundleHost.getExistingGhidraBundle(bs.getPath())).collect(
- Collectors.toList());
+ List<GhidraBundle> gbs = bundleStatusTableModel.getRowObjects(selectedModelRows)
+ .stream()
+ .filter(bs -> bs.isActive())
+ .map(bs -> bundleHost.getExistingGhidraBundle(bs.getPath()))
+ .collect(Collectors.toList());
monitor.setMaximum(gbs.size());
for (GhidraBundle gb : gbs) {
try {
- bundleHost.deactivateSynchronously(gb.getBundleLoc());
+ bundleHost.deactivateSynchronously(gb.getBundleLocation());
}
catch (GhidraBundleException | InterruptedException e) {
e.printStackTrace(console.getStdErr());
@@ -501,10 +500,10 @@ public class BundleStatusComponentProvider extends ComponentProviderAdapter {
GhidraBundle gb = bundleHost.getExistingGhidraBundle(status.getPath());
if (activate) {
gb.build(console.getStdErr());
- bundleHost.activateSynchronously(gb.getBundleLoc());
+ bundleHost.activateSynchronously(gb.getBundleLocation());
}
else { // deactivate
- bundleHost.deactivateSynchronously(gb.getBundleLoc());
+ bundleHost.deactivateSynchronously(gb.getBundleLocation());
}
}
catch (Exception e) {
@@ -518,18 +517,14 @@ public class BundleStatusComponentProvider extends ComponentProviderAdapter {
}, null, 1000);
}
- public BundleStatusTableModel getModel() {
- return bundleStatusTableModel;
- }
-
- public void notifyTableRowChanged(BundleStatus status) {
+ private void notifyTableRowChanged(BundleStatus status) {
int modelRowIndex = bundleStatusTableModel.getRowIndex(status);
int viewRowIndex = filterPanel.getViewRow(modelRowIndex);
- bundleStatusTable.notifyTableChanged(
- new TableModelEvent(bundleStatusTableModel, viewRowIndex));
+ bundleStatusTable
+ .notifyTableChanged(new TableModelEvent(bundleStatusTableModel, viewRowIndex));
}
- public void notifyTableDataChanged() {
+ private void notifyTableDataChanged() {
bundleStatusTable.notifyTableChanged(new TableModelEvent(bundleStatusTableModel));
}
@@ -545,6 +540,9 @@ public class BundleStatusComponentProvider extends ComponentProviderAdapter {
}
*/
+ /**
+ * cleanup this component
+ */
public void dispose() {
bundleStatusTable.dispose();
}
@@ -553,4 +551,17 @@ public class BundleStatusComponentProvider extends ComponentProviderAdapter {
bundleStatusTable.selectRow(filterPanel.getViewRow(modelRowIndex));
}
+ /**
+ * This is for testing only! during normal execution, statuses are only added through BundleHostListener bundle(s) added events.
+ *
+ * each path is marked editable and non-readonly
+ *
+ * @param bundlePaths the paths to use
+ */
+ public void setPathsForTesting(List<ResourceFile> bundlePaths) {
+ bundleStatusTableModel.setModelData(bundlePaths.stream()
+ .map(f -> new BundleStatus(f, true, false, null))
+ .collect(Collectors.toList()));
+ }
+
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleStatusTableModel.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleStatusTableModel.java
index 051e2d752c..da06e93306 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleStatusTableModel.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/BundleStatusTableModel.java
@@ -71,7 +71,7 @@ public class BundleStatusTableModel extends AbstractSortedTableModel<BundleStatu
Column activeColumn = new Column("Active", Boolean.class) {
@Override
boolean editable(BundleStatus status) {
- return status.pathExists(); // XXX maybe only if it's already enabled
+ return status.pathExists() && status.isEnabled();
}
@Override
@@ -110,31 +110,80 @@ public class BundleStatusTableModel extends AbstractSortedTableModel<BundleStatu
}
- Column getColumn(int i) {
- if (i >= 0 && i < columns.size()) {
- return columns.get(i);
- }
- return badColumn;
- }
-
+ private BundleHost bundleHost;
private BundleStatusComponentProvider provider;
+ private Map<String, BundleStatus> bundleLocToStatusMap = new HashMap<>();
+ private BundleHostListener bundleHostListener;
+
+ private ArrayList<BundleStatusChangeRequestListener> bundleStatusListeners = new ArrayList<>();
private List<BundleStatus> statuses;
- private BundleHost bundleHost;
- BundleHostListener bundleListener;
- private Map<String, BundleStatus> loc2status = new HashMap<>();
+ protected class MyBundleHostListener implements BundleHostListener {
+ @Override
+ public void bundleBuilt(GhidraBundle bundle, String summary) {
+ BundleStatus status = getStatus(bundle);
+ status.setSummary(summary);
+ int row = getRowIndex(status);
+ fireTableRowsUpdated(row, row);
+ }
- BundleStatus getStatus(GhidraBundle gb) {
- return getStatusFromLoc(gb.getBundleLoc());
- }
+ @Override
+ public void bundleActivationChange(GhidraBundle bundle, boolean newActivation) {
+ BundleStatus status = getStatus(bundle);
+ int row = getRowIndex(status);
+ status.setBusy(false);
+ if (newActivation) {
+ status.setActive(true);
+ }
+ else {
+ status.setActive(false);
+ }
+ fireTableRowsUpdated(row, row);
+ }
- BundleStatus getStatusFromLoc(String bundleLoc) {
- BundleStatus status = loc2status.get(bundleLoc);
- if (status == null) {
- Msg.showError(BundleStatusTableModel.this, provider.getComponent(),
- "bundle status error", "bundle has no status!");
+ @Override
+ public void bundleAdded(GhidraBundle bundle) {
+ addNewStatus(bundle);
+ }
+
+ @Override
+ public void bundlesAdded(Collection<GhidraBundle> bundles) {
+ int index = statuses.size();
+ for (GhidraBundle bundle : bundles) {
+ addNewStatusNoFire(bundle);
+ }
+ fireTableRowsInserted(index, bundles.size() - 1);
+ }
+
+ @Override
+ public void bundleRemoved(GhidraBundle bundle) {
+ BundleStatus status = getStatus(bundle);
+ removeStatus(status);
+ }
+
+ @Override
+ public void bundlesRemoved(Collection<GhidraBundle> bundles) {
+ List<BundleStatus> toRemove = bundles.stream()
+ .map(BundleStatusTableModel.this::getStatus)
+ .collect(Collectors.toUnmodifiableList());
+ removeStatuses(toRemove);
+ }
+
+ @Override
+ public void bundleEnablementChange(GhidraBundle bundle, boolean newEnablement) {
+ BundleStatus status = getStatus(bundle);
+ status.setEnabled(newEnablement);
+ int row = getRowIndex(status);
+ fireTableRowsUpdated(row, row);
+ }
+
+ @Override
+ public void bundleException(GhidraBundleException exception) {
+ BundleStatus status = getStatusFromLoc(exception.getBundleLocation());
+ status.setSummary(exception.getMessage());
+ int row = getRowIndex(status);
+ fireTableRowsUpdated(row, row);
}
- return status;
}
BundleStatusTableModel(BundleStatusComponentProvider provider, BundleHost bundleHost) {
@@ -142,114 +191,57 @@ public class BundleStatusTableModel extends AbstractSortedTableModel<BundleStatu
this.provider = provider;
this.bundleHost = bundleHost;
statuses = new ArrayList<>();
- for (GhidraBundle gb : bundleHost.getGhidraBundles()) {
- addNewStatus(gb);
+ for (GhidraBundle bundle : bundleHost.getGhidraBundles()) {
+ addNewStatus(bundle);
}
- bundleHost.addListener(bundleListener = new BundleHostListener() {
- @Override
- public void bundleBuilt(GhidraBundle gb, String summary) {
- BundleStatus status = getStatus(gb);
- status.setSummary(summary);
- int row = getRowIndex(status);
- fireTableRowsUpdated(row, row);
- }
-
- @Override
- public void bundleActivationChange(GhidraBundle gb, boolean newActivation) {
- BundleStatus status = getStatus(gb);
- int row = getRowIndex(status);
- status.setBusy(false);
- if (newActivation) {
- status.setActive(true);
- }
- else {
- status.setActive(false);
- }
- fireTableRowsUpdated(row, row);
- }
-
- @Override
- public void bundleAdded(GhidraBundle gb) {
- addNewStatus(gb);
- }
-
- @Override
- public void bundlesAdded(Collection<GhidraBundle> gbundles) {
- int index = statuses.size();
- for (GhidraBundle gb : gbundles) {
- addNewStatusNoFire(gb);
- }
- fireTableRowsInserted(index, gbundles.size() - 1);
- }
-
- @Override
- public void bundleRemoved(GhidraBundle gbundle) {
- BundleStatus status = getStatus(gbundle);
- removeStatus(status);
- }
-
- @Override
- public void bundlesRemoved(Collection<GhidraBundle> gbundles) {
- List<BundleStatus> toRemove =
- gbundles.stream().map(BundleStatusTableModel.this::getStatus).collect(
- Collectors.toUnmodifiableList());
- removeStatuses(toRemove);
- }
+ bundleHost.addListener(bundleHostListener = new MyBundleHostListener());
+ }
- @Override
- public void bundleEnablementChange(GhidraBundle gbundle, boolean newEnablement) {
- BundleStatus status = getStatus(gbundle);
- status.setEnabled(newEnablement);
- int row = getRowIndex(status);
- fireTableRowsUpdated(row, row);
- }
+ Column getColumn(int i) {
+ if (i >= 0 && i < columns.size()) {
+ return columns.get(i);
+ }
+ return badColumn;
+ }
- @Override
- public void bundleException(GhidraBundleException gbe) {
- BundleStatus status = getStatusFromLoc(gbe.getBundleLocation());
- status.setSummary(gbe.getMessage());
- int row = getRowIndex(status);
- fireTableRowsUpdated(row, row);
- }
+ BundleStatus getStatus(GhidraBundle bundle) {
+ return getStatusFromLoc(bundle.getBundleLocation());
+ }
- });
+ BundleStatus getStatusFromLoc(String bundleLoc) {
+ BundleStatus status = bundleLocToStatusMap.get(bundleLoc);
+ if (status == null) {
+ Msg.showError(BundleStatusTableModel.this, provider.getComponent(),
+ "bundle status error", "bundle has no status!");
+ }
+ return status;
}
@Override
public void dispose() {
super.dispose();
- bundleHost.removeListener(bundleListener);
- }
-
- public List<ResourceFile> getEnabledPaths() {
- List<ResourceFile> list = new ArrayList<>();
- for (BundleStatus status : statuses) {
- if (status.isEnabled()) {
- list.add(status.getPath());
- }
- }
- return list;
+ bundleHost.removeListener(bundleHostListener);
}
- private void addNewStatusNoFire(GhidraBundle gb) {
- BundleStatus status =
- new BundleStatus(gb.getPath(), gb.isEnabled(), gb.isSystemBundle(), gb.getBundleLoc());
+ private void addNewStatusNoFire(GhidraBundle bundle) {
+ BundleStatus status = new BundleStatus(bundle.getPath(), bundle.isEnabled(),
+ bundle.isSystemBundle(), bundle.getBundleLocation());
if (statuses.contains(status)) {
throw new RuntimeException(
- "Bundle status manager already contains " + gb.getPath().toString());
+ "Bundle status manager already contains " + bundle.getPath().toString());
}
- status.setActive(gb.isActive());
- loc2status.put(status.getBundleLoc(), status);
+ status.setActive(bundle.isActive());
+ bundleLocToStatusMap.put(status.getBundleLocation(), status);
statuses.add(status);
}
/**
* add new status and fire a table update
*/
- private void addNewStatus(GhidraBundle gb) {
+ private void addNewStatus(GhidraBundle bundle) {
int index = statuses.size();
- addNewStatusNoFire(gb);
+ addNewStatusNoFire(bundle);
fireTableRowsInserted(index, index);
}
@@ -257,7 +249,7 @@ public class BundleStatusTableModel extends AbstractSortedTableModel<BundleStatu
if (!status.isReadOnly()) {
int i = statuses.indexOf(status);
statuses.remove(i);
- loc2status.remove(status.getBundleLoc());
+ bundleLocToStatusMap.remove(status.getBundleLocation());
return i;
}
return -1;
@@ -271,8 +263,9 @@ public class BundleStatusTableModel extends AbstractSortedTableModel<BundleStatu
}
void remove(int[] modelRows) {
- List<BundleStatus> toRemove = Arrays.stream(modelRows).mapToObj(statuses::get).collect(
- Collectors.toUnmodifiableList());
+ List<BundleStatus> toRemove = Arrays.stream(modelRows)
+ .mapToObj(statuses::get)
+ .collect(Collectors.toUnmodifiableList());
removeStatuses(toRemove);
}
@@ -315,7 +308,7 @@ public class BundleStatusTableModel extends AbstractSortedTableModel<BundleStatu
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
BundleStatus status = statuses.get(rowIndex);
getColumn(columnIndex).setValue(status, aValue);
- // XXX I don't know why it's unselected, but it's maddening
+ // anything that's clicked on should become selected!
provider.selectModelRow(rowIndex);
}
@@ -339,8 +332,19 @@ public class BundleStatusTableModel extends AbstractSortedTableModel<BundleStatu
return statuses;
}
- private ArrayList<BundleStatusChangeRequestListener> bundleStatusListeners = new ArrayList<>();
+ void setModelData(List<BundleStatus> statuses) {
+ this.statuses = statuses;
+ computeCache();
+ fireTableDataChanged();
+ }
+ /**
+ * Add a change request listener.
+ *
+ * When the user requests a change to the status of a bundle, each listener is called.
+ *
+ * @param listener the listener to add
+ */
public void addListener(BundleStatusChangeRequestListener listener) {
synchronized (bundleStatusListeners) {
if (!bundleStatusListeners.contains(listener)) {
@@ -349,6 +353,11 @@ public class BundleStatusTableModel extends AbstractSortedTableModel<BundleStatu
}
}
+ /**
+ * Remove change request listener.
+ *
+ * @param listener the listener to remove
+ */
public void removeListener(BundleStatusChangeRequestListener listener) {
synchronized (bundleStatusListeners) {
bundleStatusListeners.remove(listener);
@@ -371,6 +380,12 @@ public class BundleStatusTableModel extends AbstractSortedTableModel<BundleStatu
}
}
+ /**
+ * return the row objects corresponding an array of model row indices.
+ *
+ * @param modelRowIndices row indices
+ * @return status objects
+ */
public List<BundleStatus> getRowObjects(int[] modelRowIndices) {
List<BundleStatus> rows = new ArrayList<>(modelRowIndices.length);
for (int i : modelRowIndices) {
@@ -418,24 +433,10 @@ public class BundleStatusTableModel extends AbstractSortedTableModel<BundleStatu
* (re)compute cached mapping from bundleloc to bundlepath
*/
private void computeCache() {
- loc2status.clear();
+ bundleLocToStatusMap.clear();
for (BundleStatus status : statuses) {
- loc2status.put(status.getBundleLoc(), status);
+ bundleLocToStatusMap.put(status.getBundleLocation(), status);
}
}
- /**
- * This is for testing only! during normal execution, statuses are only added through BundleHostListener bundle(s) added events.
- *
- * each path is marked editable and non-readonly
- *
- * @param paths the statuses to use
- */
- public void setPathsForTesting(List<ResourceFile> paths) {
- this.statuses = paths.stream().map(f -> new BundleStatus(f, true, false, null)).collect(
- Collectors.toList());
- computeCache();
- fireTableDataChanged();
- }
-
}
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.java
index f77bcfb37a..496bb71717 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
@@ -24,6 +24,9 @@ import org.osgi.framework.wiring.BundleRequirement;
import generic.jar.ResourceFile;
+/**
+ * Proxy for an OSGi bundle that may require being built.
+ */
public abstract class GhidraBundle {
protected final ResourceFile path;
@@ -31,9 +34,10 @@ public abstract class GhidraBundle {
protected boolean enabled;
protected boolean systemBundle;
- GhidraBundle(BundleHost bundleHost, ResourceFile path, boolean enabled, boolean systemBundle) {
+ GhidraBundle(BundleHost bundleHost, ResourceFile bundlePath, boolean enabled,
+ boolean systemBundle) {
this.bundleHost = bundleHost;
- this.path = path;
+ this.path = bundlePath;
this.enabled = enabled;
this.systemBundle = systemBundle;
}
@@ -48,45 +52,97 @@ public abstract class GhidraBundle {
/**
* build OSGi bundle if possible
*
- * @param writer console for user messages
+ * @param writer console for build messages to user
* @return true if build happened, false if already built
- * @throws Exception sorry, wasn't possible
+ * @throws Exception if the build cannot complete
*/
public abstract boolean build(PrintWriter writer) throws Exception;
+ /**
+ * same as {@link #build(PrintWriter)} with writer = {@link System.err}.
+ */
+ @SuppressWarnings("javadoc")
public boolean build() throws Exception {
return build(new PrintWriter(System.err));
}
- public abstract String getBundleLoc();
+ /**
+ * Return the location identifier of the bundle that this GhidraBundle represents.
+ * The location identifier is passed to {@link org.osgi.framework.BundleContext#installBundle} when this
+ * bundle is installed.
+ *
+ * @return location identifier of this bundle
+ */
+ public abstract String getBundleLocation();
- abstract List<BundleRequirement> getAllReqs();
+ abstract List<BundleRequirement> getAllRequirements();
+ /**
+ * @return this bundle's path
+ */
public ResourceFile getPath() {
return path;
}
+ /**
+ * @return true if this bundle is enabled
+ */
public boolean isEnabled() {
return enabled;
}
- public void setEnabled(boolean enabled) {
+ /**
+ * set the enablement flag for this bundle.
+ *
+ * If a bundle is enabled its contents will be scanned, e.g. for scripts.
+ *
+ * @param enabled new state
+ */
+ void setEnabled(boolean enabled) {
this.enabled = enabled;
}
+ /**
+ * If a bundle is a "system bundle" it cannot be removed and its contends cannot be edited.
+ *
+ * @return true if this is a system bundle
+ */
public boolean isSystemBundle() {
return systemBundle;
}
+ /**
+ * A GhidraBundle can be
+ * <ul>
+ * <li>a Bndtools .bnd script</li>
+ * <li>an OSGi bundle .jar file</li>
+ * <li>a directory of Java source</li>
+ * </u>
+ *
+ */
enum Type {
BndScript, Jar, SourceDir, INVALID
}
- static GhidraBundle.Type getType(ResourceFile rf) {
- if (rf.isDirectory()) {
+ /**
+ * a string error with a time stamp
+ */
+ public static class BuildFailure {
+ long when = -1;
+ StringBuilder message = new StringBuilder();
+ }
+
+ /**
+ * Get the type of a GhidraBundle from its path.
+ *
+ * @param path a resource path
+ * @return the type
+ */
+ static GhidraBundle.Type getType(ResourceFile path) {
+ if (path.isDirectory()) {
return GhidraBundle.Type.SourceDir;
}
- String n = rf.getName().toLowerCase();
+ String n = path.getName().toLowerCase();
if (n.endsWith(".bnd")) {
return GhidraBundle.Type.BndScript;
}
@@ -96,11 +152,17 @@ public abstract class GhidraBundle {
return GhidraBundle.Type.INVALID;
}
- static public GhidraBundle.Type getType(File f) {
- if (f.isDirectory()) {
+ /**
+ * Get the type of a GhidraBundle from its path.
+ *
+ * @param path a file system path
+ * @return the type
+ */
+ public static GhidraBundle.Type getType(File path) {
+ if (path.isDirectory()) {
return GhidraBundle.Type.SourceDir;
}
- String n = f.getName().toLowerCase();
+ String n = path.getName().toLowerCase();
if (n.endsWith(".bnd")) {
return GhidraBundle.Type.BndScript;
}
@@ -110,21 +172,20 @@ public abstract class GhidraBundle {
return GhidraBundle.Type.INVALID;
}
- public Bundle getBundle() {
- return bundleHost.getBundle(getBundleLoc());
- }
-
- public void activate() throws Exception {
- activate(new PrintWriter(System.err));
- }
-
- public void activate(PrintWriter writer) throws Exception {
- build(writer);
- bundleHost.activateSynchronously(getBundleLoc());
+ /**
+ * Get the OSGi bundle respresented by this GhidraBundle or null
+ *
+ * @return a Bundle or null
+ */
+ public Bundle getOSGiBundle() {
+ return bundleHost.getOSGiBundle(getBundleLocation());
}
+ /**
+ * @return true if this bundle is active
+ */
public boolean isActive() {
- Bundle b = getBundle();
+ Bundle b = getOSGiBundle();
return (b != null) && b.getState() == Bundle.ACTIVE;
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/GhidraBundleActivator.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/GhidraBundleActivator.java
index 19174d7110..90e5e57385 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/GhidraBundleActivator.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/GhidraBundleActivator.java
@@ -19,18 +19,18 @@ import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public abstract class GhidraBundleActivator implements BundleActivator {
- protected abstract void start(BundleContext bc, Object api);
+ protected abstract void start(BundleContext bundleContext, Object api);
- protected abstract void stop(BundleContext bc, Object api);
+ protected abstract void stop(BundleContext bundleContext, Object api);
@Override
- final public void start(BundleContext bc) throws Exception {
- start(bc, null);
+ public final void start(BundleContext bundleContext) throws Exception {
+ start(bundleContext, null);
}
@Override
- final public void stop(BundleContext bc) throws Exception {
- stop(bc, null);
+ public final void stop(BundleContext bundleContext) throws Exception {
+ stop(bundleContext, null);
}
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/GhidraBundleException.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/GhidraBundleException.java
index d697ce6fbe..141547252d 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/GhidraBundleException.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/GhidraBundleException.java
@@ -21,28 +21,52 @@ import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
public class GhidraBundleException extends OSGiException {
- private Bundle bundle;
- private String bundle_loc;
-
+ private final Bundle bundle;
+ private final String bundleLocation;
+
+ /**
+ * {@link GhidraBundleException}s store the context associated with exceptions thrown during bundle operations.
+ *
+ * @param bundle the bundle (if available)
+ * @param msg a contextual message
+ * @param cause the original exception
+ */
public GhidraBundleException(Bundle bundle, String msg, BundleException cause) {
super(msg + ": " + parsedCause(cause), cause);
this.bundle = bundle;
+ this.bundleLocation = bundle.getLocation();
}
- public GhidraBundleException(String bundle_loc, String msg, BundleException cause) {
+ /**
+ * {@link GhidraBundleException}s store the context associated with exceptions thrown during bundle operations.
+ *
+ * @param bundleLocation the bundle location identifier (since no bundle is available)
+ * @param msg a contextual message
+ * @param cause the original exception
+ */
+ public GhidraBundleException(String bundleLocation, String msg, BundleException cause) {
super(msg + ": " + parsedCause(cause), cause);
- this.bundle_loc = bundle_loc;
+ this.bundle = null;
+ this.bundleLocation = bundleLocation;
}
+ /**
+ * @return the associated bundle, or null. If null, the bundle location identifier will be non-null
+ */
public Bundle getBundle() {
return bundle;
}
+ /**
+ * When no {@link Bundle} is available, {@link #getBundle()} will return {@code null}.
+ *
+ * @return the bundle location identifier of the offending bundle.
+ */
public String getBundleLocation() {
- return bundle_loc != null ? bundle_loc : bundle.getLocation();
+ return bundleLocation != null ? bundleLocation : bundle.getLocation();
}
- static private String parsedCause(Throwable e) {
+ private static String parsedCause(Throwable e) {
if (e == null) {
return "";
}
@@ -81,9 +105,10 @@ public class GhidraBundleException extends OSGiException {
return message;
}
// parse the package constraints from filters in the BundleRequirement string
- String packages =
- OSGiUtils.extractPackages(be.getMessage()).stream().distinct().collect(
- Collectors.joining("\n"));
+ String packages = OSGiUtils.extractPackageNamesFromFailedResolution(be.getMessage())
+ .stream()
+ .distinct()
+ .collect(Collectors.joining("\n"));
return "RESOLVE_ERROR with reference to packages:\n" + packages;
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/GhidraJarBundle.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/GhidraJarBundle.java
index 461c4265b7..eec75b2251 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/GhidraJarBundle.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/GhidraJarBundle.java
@@ -26,13 +26,24 @@ import aQute.bnd.osgi.Constants;
import aQute.bnd.osgi.Jar;
import generic.jar.ResourceFile;
+/**
+ * Proxy to an ordinary OSGi Jar bundle. {@link GhidraJarBundle#build(PrintWriter)} does nothing.
+ */
public class GhidraJarBundle extends GhidraBundle {
- final String bundleLoc;
+ final String bundleLocation;
+ /**
+ * {@link GhidraJarBundle} wraps an ordinary OSGi bundle .jar.
+ *
+ * @param bundleHost the {@link BundleHost} instance this bundle will belong to
+ * @param path the jar file's path
+ * @param enabled true to start enabled
+ * @param systemBundle true if this is a Ghidra system bundle
+ */
public GhidraJarBundle(BundleHost bundleHost, ResourceFile path, boolean enabled,
boolean systemBundle) {
super(bundleHost, path, enabled, systemBundle);
- this.bundleLoc = "file://" + path.getAbsolutePath().toString();
+ this.bundleLocation = "file://" + path.getAbsolutePath().toString();
}
@Override
@@ -46,19 +57,19 @@ public class GhidraJarBundle extends GhidraBundle {
}
@Override
- public String getBundleLoc() {
- return bundleLoc;
+ public String getBundleLocation() {
+ return bundleLocation;
}
@Override
- public List<BundleRequirement> getAllReqs() {
+ public List<BundleRequirement> getAllRequirements() {
Jar jar;
try {
jar = new Jar(path.getFile(true));
Manifest m = jar.getManifest();
String imps = m.getMainAttributes().getValue(Constants.IMPORT_PACKAGE);
if (imps != null) {
- return BundleHost.parseImports(imps);
+ return OSGiUtils.parseImports(imps);
}
return Collections.emptyList();
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/GhidraPlaceholderBundle.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/GhidraPlaceholderBundle.java
index f61095b205..28b027c0e7 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/GhidraPlaceholderBundle.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/GhidraPlaceholderBundle.java
@@ -23,11 +23,14 @@ import org.osgi.framework.wiring.BundleRequirement;
import generic.jar.ResourceFile;
+/**
+ * {@link GhidraPlaceholderBundle} represents invalid bundle paths in the GUI.
+ */
public class GhidraPlaceholderBundle extends GhidraBundle {
- GhidraPlaceholderBundle(BundleHost bundleHost, ResourceFile path, boolean enabled,
- boolean systemBundle) {
- super(bundleHost, path, enabled, systemBundle);
+ GhidraPlaceholderBundle(BundleHost bundleHost, ResourceFile bundlePath, boolean isEnabled,
+ boolean isSystemBundle) {
+ super(bundleHost, bundlePath, isEnabled, isSystemBundle);
}
@Override
@@ -41,12 +44,12 @@ public class GhidraPlaceholderBundle extends GhidraBundle {
}
@Override
- public String getBundleLoc() {
+ public String getBundleLocation() {
return "invalid://" + getPath();
}
@Override
- List<BundleRequirement> getAllReqs() {
+ List<BundleRequirement> getAllRequirements() {
return Collections.emptyList();
}
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.java
index 65cadc6e32..d3277b0ff0 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
@@ -42,44 +42,93 @@ import aQute.bnd.osgi.*;
import aQute.bnd.osgi.Clazz.QUERY;
import generic.io.NullPrintWriter;
import generic.jar.ResourceFile;
-import ghidra.app.plugin.core.osgi.BundleHost.BuildFailure;
import ghidra.app.script.*;
import ghidra.util.Msg;
/**
- * The SourceBundleInfo class is a cache of information for bundles built from source directories.
+ * {@link GhidraSourceBundle} represents a Java source directory that is compiled on build to an OSGi bundle.
+ *
+ * A manifest and BundleActivator are generated if not already present.
*/
public class GhidraSourceBundle extends GhidraBundle {
- public interface DiscrepencyCallback {
- void found(ResourceFile source_file, Collection<Path> class_files) throws Throwable;
+ private static final String GENERATED_ACTIVATOR_CLASSNAME = "GeneratedActivator";
+ private static final Predicate<String> isClassFile =
+ Pattern.compile("(\\$.*)?\\.class", Pattern.CASE_INSENSITIVE).asMatchPredicate();
+
+ protected interface DiscrepencyCallback {
+ /**
+ * Invoked when there is a discrepancy between {@code sourceFile} and its
+ * corresponding class file(s), {@code classFiles}
+ *
+ * @param sourceFile the source file or null to indicate the class files have no corresponding source
+ * @param classFiles corresponding class files(s)
+ * @throws Throwable an exception
+ */
+ void found(ResourceFile sourceFile, Collection<Path> classFiles) throws Throwable;
}
- final private String symbolicName;
- final private Path binDir;
- final private String bundleLoc;
+ private final String symbolicName;
+ private final Path binDir;
+ private final String bundleLoc;
- final List<ResourceFile> newSources = new ArrayList<>();
- final List<Path> oldBin = new ArrayList<>();
+ private final List<ResourceFile> newSources = new ArrayList<>();
+ private final List<Path> oldBin = new ArrayList<>();
- static final String GENERATED_ACTIVATOR_CLASSNAME = "GeneratedActivator";
private JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
//// information indexed by source file
- final HashMap<ResourceFile, BuildFailure> buildErrors = new HashMap<>();
- final HashMap<ResourceFile, List<BundleRequirement>> buildReqs = new HashMap<>();
- final HashMap<String, List<ResourceFile>> req2file = new HashMap<>();
+ private final HashMap<ResourceFile, GhidraBundle.BuildFailure> buildErrors = new HashMap<>();
+ private final HashMap<ResourceFile, List<BundleRequirement>> sourceFileToRequirements =
+ new HashMap<>();
+ private final HashMap<String, List<ResourceFile>> requirementToSourceFileMap = new HashMap<>();
- // cached values parsed form @imports tags on default-package source files
+ private long lastCompileAttempt;
+ /**
+ * Create a new GhidraSourceBundle.
+ *
+ * @param bundleHost the {@link BundleHost} instance this bundle will belong to
+ * @param sourceDirectory the source bundle directory
+ * @param enabled true to start enabled
+ * @param systemBundle true if this is a Ghidra system bundle
+ */
public GhidraSourceBundle(BundleHost bundleHost, ResourceFile sourceDirectory, boolean enabled,
boolean systemBundle) {
super(bundleHost, sourceDirectory, enabled, systemBundle);
- this.symbolicName = BundleHost.getSymbolicNameFromSourceDir(path);
- this.binDir = BundleHost.getCompiledBundlesDir().resolve(symbolicName);
+ this.symbolicName = GhidraSourceBundle.sourceDirHash(path);
+ this.binDir = GhidraSourceBundle.getCompiledBundlesDir().resolve(symbolicName);
+
+ this.bundleLoc = "reference:file://" + binDir.toAbsolutePath().normalize().toString();
+ }
+
+ /**
+ * Source bundles are compiled to a path relative to the user's home:
+ * &nbsp;{@code $USERHOME/.ghidra/.ghidra_<ghidra version>/osgi/compiled-bundles/<sourceDirHash> }
+ *
+ * @return the destination for compiled source bundles
+ *
+ * @see BundleHost#getOsgiDir
+ */
+ public static Path getCompiledBundlesDir() {
+ return BundleHost.getOsgiDir().resolve("compiled-bundles");
+ }
- this.bundleLoc = "reference:file://" + getBinDir().toAbsolutePath().normalize().toString();
+ /**
+ * When a source bundle doesn't have a manifest, Ghidra computes the bundle's
+ * symbolic name as a hash of the source directory path.
+ *
+ * The hash is is also used as the final path component of the compile destination:<br/>
+ * &nbsp;{@code $USERHOME/.ghidra/.ghidra_<ghidra version>/osgi/compiled-bundles/<sourceDirHash> }
+ *
+ * @param sourceDir the source directory
+ * @return a string hash of the source directory path
+ *
+ * @see #getCompiledBundlesDir
+ */
+ public static String sourceDirHash(ResourceFile sourceDir) {
+ return Integer.toHexString(sourceDir.getAbsolutePath().hashCode());
}
/**
@@ -88,17 +137,23 @@ public class GhidraSourceBundle extends GhidraBundle {
* @param sourceFile a ghidra script file
* @return the directory its class is compiled to
*/
- static public Path getBindirFromScriptFile(ResourceFile sourceFile) {
+ public static Path getBindirFromScriptFile(ResourceFile sourceFile) {
ResourceFile tmpSourceDir = sourceFile.getParentFile();
- String tmpSymbolicName = BundleHost.getSymbolicNameFromSourceDir(tmpSourceDir);
- return BundleHost.getCompiledBundlesDir().resolve(tmpSymbolicName);
+ String tmpSymbolicName = GhidraSourceBundle.sourceDirHash(tmpSourceDir);
+ return GhidraSourceBundle.getCompiledBundlesDir().resolve(tmpSymbolicName);
}
+ /**
+ * Returen the class name corresponding to a script in this source bundle.
+ *
+ * @param sourceFile a source file from this bundle
+ * @return the class name
+ */
public String classNameForScript(ResourceFile sourceFile) {
String p;
try {
p = sourceFile.getCanonicalPath();
- p = p.substring(1 + getSourceDir().getCanonicalPath().length(), p.length() - 5);// relative path less ".java"
+ p = p.substring(1 + path.getCanonicalPath().length(), p.length() - 5);// relative path less ".java"
return p.replace(File.separatorChar, '.');
}
catch (IOException e) {
@@ -107,14 +162,6 @@ public class GhidraSourceBundle extends GhidraBundle {
}
}
- ResourceFile getSourceDir() {
- return path;
- }
-
- Path getBinDir() {
- return binDir;
- }
-
void buildSuccess(ResourceFile sourceFile) {
buildErrors.remove(sourceFile);
}
@@ -125,53 +172,62 @@ public class GhidraSourceBundle extends GhidraBundle {
* @param err an error string
*/
void buildError(ResourceFile sourceFile, String err) {
- BuildFailure f =
- buildErrors.computeIfAbsent(sourceFile, x -> new BundleHost.BuildFailure());
+ GhidraBundle.BuildFailure f =
+ buildErrors.computeIfAbsent(sourceFile, x -> new GhidraBundle.BuildFailure());
f.when = sourceFile.lastModified();
f.message.append(err);
}
- public BuildFailure getErrors(ResourceFile sourceFile) {
+ /**
+ * get any errors associated with building the given source file.
+ *
+ * @param sourceFile the source file
+ * @return a {@link GhidraBundle.BuildFailure} object
+ */
+ public GhidraBundle.BuildFailure getErrors(ResourceFile sourceFile) {
return buildErrors.get(sourceFile);
}
private String getPreviousBuildErrors() {
- return buildErrors.values().stream().map(e -> e.message.toString()).collect(
- Collectors.joining());
+ return buildErrors.values()
+ .stream()
+ .map(e -> e.message.toString())
+ .collect(Collectors.joining());
}
- private String parseImps(ResourceFile javaSource) {
- // XXX don't use @imports, use an annotation
+ private String parseImports(ResourceFile javaSource) {
return GhidraScriptUtil.newScriptInfo(javaSource).getImportPackage();
}
/**
- * update buildReqs based on \@imports tag in java files from the default package
+ * update buildReqs based on \@importpackages tag in java files in the default(unnamed) package
*
- * @throws GhidraBundleException on failure to parse the \@imports tag
+ * @throws GhidraBundleException on failure to parse the \@importpackages tag
*/
private void updateRequirementsFromMetadata() throws GhidraBundleException {
- buildReqs.clear();
- req2file.clear();
+ sourceFileToRequirements.clear();
+ requirementToSourceFileMap.clear();
- for (ResourceFile rf : path.listFiles()) {
- if (rf.getName().endsWith(".java")) {
+ for (ResourceFile file : path.listFiles()) {
+ if (file.getName().endsWith(".java")) {
// without GhidraScriptComponentProvider.updateAvailableScriptFilesForDirectory, or GhidraScriptComponentProvider.newScript
// this might be the earliest need for ScriptInfo, so allow construction.
// NB: ScriptInfo will update field values if lastModified has changed since last time they were computed
- String imps = parseImps(rf);
+ String imps = parseImports(file);
if (imps != null && !imps.isEmpty()) {
- List<BundleRequirement> reqs;
+ List<BundleRequirement> requirements;
try {
- reqs = BundleHost.parseImports(imps);
+ requirements = OSGiUtils.parseImports(imps);
}
catch (BundleException e) {
- throw new GhidraBundleException(getBundleLoc(), "parsing manifest", e);
+ throw new GhidraBundleException(getBundleLocation(), "parsing manifest", e);
}
- buildReqs.put(rf, reqs);
- for (BundleRequirement req : reqs) {
- req2file.computeIfAbsent(req.toString(), x -> new ArrayList<>()).add(rf);
+ sourceFileToRequirements.put(file, requirements);
+ for (BundleRequirement requirement : requirements) {
+ requirementToSourceFileMap
+ .computeIfAbsent(requirement.toString(), x -> new ArrayList<>())
+ .add(file);
}
}
}
@@ -180,14 +236,16 @@ public class GhidraSourceBundle extends GhidraBundle {
private Map<String, BundleRequirement> getComputedReqs() {
Map<String, BundleRequirement> dedupedReqs = new HashMap<>();
- buildReqs.values().stream().flatMap(List::stream).forEach(
- r -> dedupedReqs.putIfAbsent(r.toString(), r));
+ sourceFileToRequirements.values()
+ .stream()
+ .flatMap(List::stream)
+ .forEach(r -> dedupedReqs.putIfAbsent(r.toString(), r));
return dedupedReqs;
}
@Override
- public List<BundleRequirement> getAllReqs() {
+ public List<BundleRequirement> getAllRequirements() {
try {
updateRequirementsFromMetadata();
}
@@ -201,7 +259,7 @@ public class GhidraSourceBundle extends GhidraBundle {
try {
Manifest m = new Manifest(manifest.getInputStream());
String imports = m.getMainAttributes().getValue("Import-Package");
- for (BundleRequirement r : BundleHost.parseImports(imports)) {
+ for (BundleRequirement r : OSGiUtils.parseImports(imports)) {
reqs.putIfAbsent(r.toString(), r);
}
}
@@ -239,7 +297,7 @@ public class GhidraSourceBundle extends GhidraBundle {
Iterator<ResourceFile> it = newSources.iterator();
while (it.hasNext()) {
ResourceFile sf = it.next();
- BuildFailure f = buildErrors.get(sf);
+ GhidraBundle.BuildFailure f = buildErrors.get(sf);
if (f != null) {
if (f.when == sf.lastModified()) {
it.remove();
@@ -270,12 +328,14 @@ public class GhidraSourceBundle extends GhidraBundle {
return newSources.size();
}
+ /**
+ * used just after {@link #build} to get the newly compiled source files
+ * @return new source files
+ */
public List<ResourceFile> getNewSources() {
return newSources;
}
- long lastCompileAttempt;
-
void compileAttempted() {
lastCompileAttempt = System.currentTimeMillis();
}
@@ -285,27 +345,27 @@ public class GhidraSourceBundle extends GhidraBundle {
}
@Override
- public String getBundleLoc() {
+ public String getBundleLocation() {
return bundleLoc;
}
ResourceFile getSourceManifestPath() {
- return new ResourceFile(getSourceDir(), "META-INF" + File.separator + "MANIFEST.MF");
+ return new ResourceFile(path, "META-INF" + File.separator + "MANIFEST.MF");
}
boolean hasNewManifest() throws IOException {
ResourceFile smf = getSourceManifestPath();
- Path dmf = getBinDir().resolve("META-INF").resolve("MANIFEST.MF");
+ Path dmf = binDir.resolve("META-INF").resolve("MANIFEST.MF");
return smf.exists() && (Files.notExists(dmf) ||
smf.lastModified() > Files.getLastModifiedTime(dmf).toMillis());
}
- static protected boolean wipeContents(Path path) throws IOException {
+ protected static boolean wipeContents(Path path) throws IOException {
if (Files.exists(path)) {
boolean anythingDeleted = false;
- for (Path p : (Iterable<Path>) Files.walk(path).sorted(
- Comparator.reverseOrder())::iterator) {
+ for (Path p : (Iterable<Path>) Files.walk(path)
+ .sorted(Comparator.reverseOrder())::iterator) {
anythingDeleted |= Files.deleteIfExists(p);
}
return anythingDeleted;
@@ -336,7 +396,7 @@ public class GhidraSourceBundle extends GhidraBundle {
// if previous failures now resolve, try again
for (ResourceFile sf : buildErrors.keySet()) {
- List<BundleRequirement> reqs = buildReqs.get(sf);
+ List<BundleRequirement> reqs = sourceFileToRequirements.get(sf);
if (reqs != null && !reqs.isEmpty() && bundleHost.canResolveAll(reqs)) {
if (!newSources.contains(sf)) {
newSources.add(sf);
@@ -347,7 +407,7 @@ public class GhidraSourceBundle extends GhidraBundle {
}
}
// if previous successes no longer resolve, (cleanup) and try again
- for (Entry<ResourceFile, List<BundleRequirement>> e : buildReqs.entrySet()) {
+ for (Entry<ResourceFile, List<BundleRequirement>> e : sourceFileToRequirements.entrySet()) {
ResourceFile sf = e.getKey();
List<BundleRequirement> reqs = e.getValue();
if (reqs != null && !reqs.isEmpty() && !buildErrors.containsKey(sf) &&
@@ -356,23 +416,19 @@ public class GhidraSourceBundle extends GhidraBundle {
newSources.add(sf);
}
- Arrays.stream(correspondingBinaries(sf)).map(
- rf -> rf.getFile(false).toPath()).forEach(oldBin::add);
+ Arrays.stream(correspondingBinaries(sf))
+ .map(rf -> rf.getFile(false).toPath())
+ .forEach(oldBin::add);
}
}
- int failing = getFailingSourcesCount();
- int newSourcecount = getNewSourcesCount();
-
- long lastBundleActivation = 0; // XXX record last bundle activation in bundlehost
- if (failing > 0 && (lastBundleActivation > getLastCompileAttempt())) {
- needsCompile = true;
- }
+ int failuresLastTime = getFailingSourcesCount();
+ int newSourceCount = getNewSourcesCount();
- if (newSourcecount == 0) {
- if (failing > 0) {
+ if (newSourceCount == 0) {
+ if (failuresLastTime > 0) {
writer.printf("%s hasn't changed, with %d file%s failing in previous build(s):\n",
- getSourceDir().toString(), failing, failing > 1 ? "s" : "");
+ path.toString(), failuresLastTime, failuresLastTime > 1 ? "s" : "");
writer.printf("%s\n", getPreviousBuildErrors());
}
}
@@ -386,11 +442,8 @@ public class GhidraSourceBundle extends GhidraBundle {
}
if (needsCompile) {
- // XXX update status?
- // writer.printf("%d new files, %d skipped, %s\n", newSourcecount, failing, newManifest ? ", new manifest" : "");
-
- // if there a bundle is currently active, uninstall it
- Bundle b = getBundle();
+ // if there is a bundle at our locations, uninstall it
+ Bundle b = bundleHost.getOSGiBundle(getBundleLocation());
if (b != null) {
bundleHost.deactivateSynchronously(b);
}
@@ -399,7 +452,7 @@ public class GhidraSourceBundle extends GhidraBundle {
deleteOldBinaries();
String summary = compileToExplodedBundle(writer);
- bundleHost.fireBundleBuilt(this, summary);
+ bundleHost.notifyBundleBuilt(this, summary);
return true;
}
return false;
@@ -414,7 +467,7 @@ public class GhidraSourceBundle extends GhidraBundle {
}
try {
- Bundle b = getBundle();
+ Bundle b = getOSGiBundle();
if (b != null) {
bundleHost.deactivateSynchronously(b);
}
@@ -427,9 +480,6 @@ public class GhidraSourceBundle extends GhidraBundle {
return anythingChanged;
}
- 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(path.getAbsolutePath().length());
@@ -444,12 +494,13 @@ public class GhidraSourceBundle extends GhidraBundle {
}
return bp.listFiles(f -> {
String nn = f.getName();
- return nn.startsWith(n) && bintail.test(nn.substring(n.length()));
+ return nn.startsWith(n) && isClassFile.test(nn.substring(n.length()));
});
}
/**
- * walk the filesystem to find:
+ * <pre>
+ * walk resources to find:
* - source files that are newer than their corresponding binary
* reports (source file, list of corresponding binaries)
* - source files with no corresponding binary
@@ -457,21 +508,20 @@ public class GhidraSourceBundle extends GhidraBundle {
* - binary files with no corresponding source
* reports (null, list of binary files)
*
- * for a source file <source_root>/com/blah/Blah.java
+ * 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
+ * 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
* ...
- *
+ * </pre>
* @param cb callback
*/
- private void visitDiscrepencies(DiscrepencyCallback cb) {
+ protected 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(path);
while (!stack.isEmpty()) {
@@ -483,16 +533,17 @@ public class GhidraSourceBundle extends GhidraBundle {
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();
+ 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()) {
@@ -501,13 +552,15 @@ public class GhidraSourceBundle extends GhidraBundle {
else {
String n = sf.getName();
if (n.endsWith(".java")) {
- long source_modtime = sf.lastModified();
+ long sourceLastModified = 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();
+ long binaryLastModified = (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) {
+ if (sourceLastModified > binaryLastModified) {
cb.found(sf, bfs);
}
}
@@ -515,8 +568,11 @@ public class GhidraSourceBundle extends GhidraBundle {
}
// any remaining .class files are missing .java files
if (!binfiles.isEmpty()) {
- cb.found(null, binfiles.values().stream().flatMap(l -> l.stream()).collect(
- Collectors.toList()));
+ cb.found(null,
+ binfiles.values()
+ .stream()
+ .flatMap(l -> l.stream())
+ .collect(Collectors.toList()));
}
}
}
@@ -525,7 +581,7 @@ public class GhidraSourceBundle extends GhidraBundle {
}
}
- static private class Summary {
+ private static class Summary {
static String SEP = ", ";
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw, true);
@@ -556,35 +612,34 @@ public class GhidraSourceBundle extends GhidraBundle {
* @throws OSGiException if generation of bundle metadata fails
*/
private String compileToExplodedBundle(PrintWriter writer) throws IOException, OSGiException {
-
compileAttempted();
- ResourceFile srcdir = getSourceDir();
- Path bindir = getBinDir();
- Files.createDirectories(bindir);
+
+ Files.createDirectories(binDir);
Summary summary = new Summary();
List<String> options = new ArrayList<>();
options.add("-g");
options.add("-d");
- options.add(bindir.toString());
+ options.add(binDir.toString());
options.add("-sourcepath");
- options.add(srcdir.toString());
+ options.add(path.toString());
options.add("-classpath");
- options.add(System.getProperty("java.class.path") + File.pathSeparator + bindir.toString());
+ options.add(System.getProperty("java.class.path") + File.pathSeparator + binDir.toString());
options.add("-proc:none");
- final ResourceFileJavaFileManager rfm = new ResourceFileJavaFileManager(
- Collections.singletonList(getSourceDir()), buildErrors.keySet());
+ final ResourceFileJavaFileManager resourceFileJavaManager =
+ new ResourceFileJavaFileManager(Collections.singletonList(path), buildErrors.keySet());
- BundleJavaManager bjm = new BundleJavaManager(bundleHost.getHostFramework(), rfm, options);
+ BundleJavaManager bundleJavaManager =
+ new BundleJavaManager(bundleHost.getHostFramework(), resourceFileJavaManager, 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.
+ // non-existing bundle, so we forge the wiring based on @importpackages metadata.
- // XXX skip this if there's a source manifest, emit warnings about @imports
+ // XXX skip this if there's a source manifest, emit warnings about @importpackages
// get wires for currently active bundles to satisfy all requirements
- List<BundleRequirement> reqs = getAllReqs();
+ List<BundleRequirement> reqs = getAllRequirements();
List<BundleWiring> bundleWirings = bundleHost.resolve(reqs);
if (!reqs.isEmpty()) {
@@ -595,18 +650,19 @@ public class GhidraSourceBundle extends GhidraBundle {
}
summary.printf("%d missing @import%s:%s", reqs.size(), reqs.size() > 1 ? "s" : "",
- reqs.stream().flatMap(
- r -> OSGiUtils.extractPackages(r.toString()).stream()).distinct().collect(
- Collectors.joining(",")));
+ reqs.stream()
+ .flatMap(r -> OSGiUtils.extractPackageNamesFromFailedResolution(r.toString()).stream())
+ .distinct()
+ .collect(Collectors.joining(",")));
}
// send the capabilities to phidias
- bundleWirings.forEach(bjm::addBundleWiring);
+ bundleWirings.forEach(bundleJavaManager::addBundleWiring);
- final List<ResourceFileJavaFileObject> sourceFiles = newSources.stream().map(
- sf -> new ResourceFileJavaFileObject(sf.getParentFile(), sf, Kind.SOURCE)).collect(
- Collectors.toList());
+ final List<ResourceFileJavaFileObject> sourceFiles = newSources.stream()
+ .map(sf -> new ResourceFileJavaFileObject(sf.getParentFile(), sf, Kind.SOURCE))
+ .collect(Collectors.toList());
- Path dmf = bindir.resolve("META-INF").resolve("MANIFEST.MF");
+ Path dmf = binDir.resolve("META-INF").resolve("MANIFEST.MF");
if (Files.exists(dmf)) {
Files.delete(dmf);
}
@@ -615,8 +671,8 @@ public class GhidraSourceBundle extends GhidraBundle {
while (!sourceFiles.isEmpty()) {
DiagnosticCollector<JavaFileObject> diagnostics =
new DiagnosticCollector<JavaFileObject>();
- JavaCompiler.CompilationTask task =
- compiler.getTask(writer, bjm, diagnostics, options, null, sourceFiles);
+ JavaCompiler.CompilationTask task = compiler.getTask(writer, bundleJavaManager,
+ diagnostics, options, null, sourceFiles);
// task.setProcessors // for annotation processing / code generation
Boolean successfulCompilation = task.call();
@@ -662,11 +718,10 @@ public class GhidraSourceBundle extends GhidraBundle {
// no manifest, so create one with bndtools
Analyzer analyzer = new Analyzer();
- analyzer.setJar(new Jar(bindir.toFile())); // give bnd the contents
- analyzer.setProperty("Bundle-SymbolicName",
- BundleHost.getSymbolicNameFromSourceDir(srcdir));
+ analyzer.setJar(new Jar(binDir.toFile())); // give bnd the contents
+ analyzer.setProperty("Bundle-SymbolicName", GhidraSourceBundle.sourceDirHash(path));
analyzer.setProperty("Bundle-Version", "1.0");
- // XXX we must constrain analyzed imports according to constraints declared in @imports tags
+ // XXX we must constrain analyzed imports according to constraints declared in @importpackages tags
analyzer.setProperty("Import-Package", "*");
analyzer.setProperty("Export-Package", "!*.private.*,!*.internal.*,*");
// analyzer.setBundleActivator(s);
@@ -682,13 +737,13 @@ public class GhidraSourceBundle extends GhidraBundle {
}
Attributes ma = manifest.getMainAttributes();
- String activator_classname = null;
+ String activatorClassName = null;
try {
for (Clazz clazz : analyzer.getClassspace().values()) {
if (clazz.is(QUERY.IMPLEMENTS,
new Instruction("org.osgi.framework.BundleActivator"), analyzer)) {
System.err.printf("found BundleActivator class %s\n", clazz);
- activator_classname = clazz.toString();
+ activatorClassName = clazz.toString();
}
}
}
@@ -696,9 +751,9 @@ public class GhidraSourceBundle extends GhidraBundle {
summary.print("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)) {
+ if (activatorClassName == null) {
+ activatorClassName = GENERATED_ACTIVATOR_CLASSNAME;
+ if (!buildDefaultActivator(binDir, activatorClassName, writer)) {
summary.print("failed to build generated activator");
return summary.getValue();
}
@@ -713,7 +768,7 @@ public class GhidraSourceBundle extends GhidraBundle {
imps + "," + GhidraBundleActivator.class.getPackageName());
}
}
- ma.putValue(Constants.BUNDLE_ACTIVATOR, activator_classname);
+ ma.putValue(Constants.BUNDLE_ACTIVATOR, activatorClassName);
// write the manifest
Files.createDirectories(dmf.getParent());
@@ -731,30 +786,30 @@ public class GhidraSourceBundle extends GhidraBundle {
* create and compile a default bundle activator
*
* @param bindir destination for class file
- * @param activator_classname the name to use for the genearted activator class
+ * @param activatorClassName the name to use for the genearted activator class
* @param writer for writing compile errors
* @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 activatorClassName, Writer writer)
throws IOException {
- Path activator_dest = bindir.resolve(activator_classname + ".java");
-
- try (PrintWriter out =
- new PrintWriter(Files.newBufferedWriter(activator_dest, Charset.forName("UTF-8")))) {
- out.println("import " + GhidraBundleActivator.class.getName() + ";");
- out.println("import org.osgi.framework.BundleActivator;");
- out.println("import org.osgi.framework.BundleContext;");
- out.println("public class " + GENERATED_ACTIVATOR_CLASSNAME +
+ Path activatorSourceFileName = bindir.resolve(activatorClassName + ".java");
+
+ try (PrintWriter activatorWriter = new PrintWriter(
+ Files.newBufferedWriter(activatorSourceFileName, Charset.forName("UTF-8")))) {
+ activatorWriter.println("import " + GhidraBundleActivator.class.getName() + ";");
+ activatorWriter.println("import org.osgi.framework.BundleActivator;");
+ activatorWriter.println("import org.osgi.framework.BundleContext;");
+ activatorWriter.println("public class " + GENERATED_ACTIVATOR_CLASSNAME +
" extends GhidraBundleActivator {");
- out.println(" protected void start(BundleContext bc, Object api) {");
- out.println(" // TODO: stuff to do on bundle start");
- out.println(" }");
- out.println(" protected void stop(BundleContext bc, Object api) {");
- out.println(" // TODO: stuff to do on bundle stop");
- out.println(" }");
- out.println();
- out.println("}");
+ activatorWriter.println(" protected void start(BundleContext bc, Object api) {");
+ activatorWriter.println(" // TODO: stuff to do on bundle start");
+ activatorWriter.println(" }");
+ activatorWriter.println(" protected void stop(BundleContext bc, Object api) {");
+ activatorWriter.println(" // TODO: stuff to do on bundle stop");
+ activatorWriter.println(" }");
+ activatorWriter.println();
+ activatorWriter.println("}");
}
List<String> options = new ArrayList<>();
@@ -767,16 +822,18 @@ public class GhidraSourceBundle extends GhidraBundle {
options.add(System.getProperty("java.class.path"));
options.add("-proc:none");
- StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
- BundleJavaManager bjm = new BundleJavaManager(bundleHost.getHostFramework(), fm, options);
+ StandardJavaFileManager javaFileManager = compiler.getStandardFileManager(null, null, null);
+ BundleJavaManager bundleJavaManager =
+ new BundleJavaManager(bundleHost.getHostFramework(), javaFileManager, options);
Iterable<? extends JavaFileObject> sourceFiles =
- fm.getJavaFileObjectsFromPaths(List.of(activator_dest));
+ javaFileManager.getJavaFileObjectsFromPaths(List.of(activatorSourceFileName));
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
JavaCompiler.CompilationTask task =
- compiler.getTask(writer, bjm, diagnostics, options, null, sourceFiles);
+ compiler.getTask(writer, bundleJavaManager, diagnostics, options, null, sourceFiles);
if (!task.call()) {
- for (Diagnostic<? extends JavaFileObject> d : diagnostics.getDiagnostics()) {
- writer.write(d.getSource().toString() + ": " + d.getMessage(null) + "\n");
+ for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
+ writer.write(
+ diagnostic.getSource().toString() + ": " + diagnostic.getMessage(null) + "\n");
}
return false;
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/LessFreneticGTable.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/LessFreneticGTable.java
index 580d009913..f0e66aa25a 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/LessFreneticGTable.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/LessFreneticGTable.java
@@ -23,7 +23,7 @@ import docking.widgets.table.*;
/**
* RowObjectSelectionManager attempts to repair selections in a filtered table
- * before and after filter events. The additiona selection events, however, cause focus changes we don't want.
+ * before and after filter events. The additional selection events, however, cause focus changes we don't want.
*/
class LessFreneticGTable extends GTable {
boolean chilled = false;
@@ -35,27 +35,29 @@ class LessFreneticGTable extends GTable {
}
@Override
- public void tableChanged(TableModelEvent e) {
+ public void tableChanged(TableModelEvent event) {
if (!chilled) {
- super.tableChanged(e);
+ super.tableChanged(event);
}
}
}
+ LessFreneticGTable(TableModel model) {
+ super(model);
+ }
+
+ /** suppress issuing table change events */
public void chill() {
chilled = true;
}
+ /** resume issuing table change events */
public void thaw() {
chilled = false;
notifyTableChanged(new TableModelEvent(getModel()));
}
- LessFreneticGTable(TableModel dm) {
- super(dm);
- }
-
@SuppressWarnings("unchecked")
@Override
protected <T> SelectionManager createSelectionManager(TableModel model) {
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/OSGiException.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/OSGiException.java
index ef8b129093..cba3ae1d74 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/OSGiException.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/OSGiException.java
@@ -14,15 +14,26 @@
* limitations under the License.
*/
package ghidra.app.plugin.core.osgi;
-import ghidra.util.exception.UsrException;
+import ghidra.util.exception.UsrException;
public class OSGiException extends UsrException {
- public OSGiException(String msg, Throwable cause) {
- super(msg, cause);
+ /**
+ * Wrapper for exceptions originating with an OSGi operation.
+ *
+ * @param message a contextual message
+ * @param cause the original exception
+ */
+ public OSGiException(String message, Throwable cause) {
+ super(message, cause);
}
- public OSGiException(String msg) {
- super(msg);
+ /**
+ * Wrapper for exceptions originating with an OSGi operation.
+ *
+ * @param message a contextual message
+ */
+ public OSGiException(String message) {
+ super(message);
}
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/OSGiUtils.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/OSGiUtils.java
index 93c24c7cf8..08e09d3e2e 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/OSGiUtils.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/osgi/OSGiUtils.java
@@ -15,19 +15,151 @@
*/
package ghidra.app.plugin.core.osgi;
-import java.util.List;
-import java.util.Scanner;
+import java.io.File;
+import java.io.IOException;
+import java.net.URL;
+import java.nio.file.*;
+import java.util.*;
+import java.util.jar.JarFile;
+import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import org.apache.felix.framework.util.manifestparser.ManifestParser;
+import org.osgi.framework.*;
+import org.osgi.framework.wiring.BundleRequirement;
public class OSGiUtils {
- public static List<String> extractPackages(String str) {
- try (Scanner s = new Scanner(str)) {
+ /**
+ * The syntax of the error generated when OSGi requirements cannot be resolved is
+ * difficult to parse, so we try to extract package names.
+ *
+ * @param osgiExceptionMessage the exception message
+ * @return a list of package names
+ */
+ static List<String> extractPackageNamesFromFailedResolution(String osgiExceptionMessage) {
+ try (Scanner s = new Scanner(osgiExceptionMessage)) {
return s.findAll(Pattern.compile("\\(osgi\\.wiring\\.package=([^)]*)\\)")).map(m -> {
return m.group(1);
}).collect(Collectors.toList());
}
}
+ 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 "???";
+ }
+ }
+
+ /**
+ * parse Import-Package string from a bundle manifest
+ *
+ * @param imports Import-Package value
+ * @return deduced requirements or null if there was an error
+ * @throws BundleException on parse failure
+ */
+ static List<BundleRequirement> parseImports(String imports) throws BundleException {
+ // parse it with Felix's ManifestParser to a list of BundleRequirement objects
+ Map<String, Object> headerMap = new HashMap<>();
+ headerMap.put(Constants.IMPORT_PACKAGE, imports);
+ ManifestParser mp;
+ mp = new ManifestParser(null, null, null, headerMap);
+ return mp.getRequirements();
+ }
+
+ // from https://dzone.com/articles/locate-jar-classpath-given
+ static String findJarForClass(Class<?> c) {
+ final URL location;
+ final String classLocation = c.getName().replace('.', '/') + ".class";
+ final ClassLoader loader = c.getClassLoader();
+ if (loader == null) {
+ location = ClassLoader.getSystemResource(classLocation);
+ }
+ else {
+ location = loader.getResource(classLocation);
+ }
+ if (location != null) {
+ Pattern p = Pattern.compile("^.*:(.*)!.*$");
+ Matcher m = p.matcher(location.toString());
+ if (m.find()) {
+ return m.group(1);
+ }
+ return null; // not loaded from jar?
+ }
+ return null;
+ }
+
+ static void getPackagesFromClasspath(Set<String> s) {
+ getClasspathElements().forEach(p -> {
+ if (Files.isDirectory(p)) {
+ collectPackagesFromDirectory(p, s);
+ }
+ else if (p.toString().endsWith(".jar")) {
+ collectPackagesFromJar(p, s);
+ }
+ });
+ }
+
+ static Stream<Path> getClasspathElements() {
+ String classpathStr = System.getProperty("java.class.path");
+ return Collections.list(new StringTokenizer(classpathStr, File.pathSeparator))
+ .stream()
+ .map(String.class::cast)
+ .map(Paths::get)
+ .map(Path::normalize);
+ }
+
+ static void collectPackagesFromDirectory(Path dirPath, Set<String> s) {
+ try {
+ Files.walk(dirPath).filter(p -> p.toString().endsWith(".class")).forEach(p -> {
+ String n = dirPath.relativize(p).toString();
+ int lastSlash = n.lastIndexOf(File.separatorChar);
+ s.add(lastSlash > 0 ? n.substring(0, lastSlash).replace(File.separatorChar, '.')
+ : "");
+ });
+
+ }
+ catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ static void collectPackagesFromJar(Path jarPath, Set<String> s) {
+ try {
+ try (JarFile j = new JarFile(jarPath.toFile())) {
+ j.stream().filter(je -> je.getName().endsWith(".class")).forEach(je -> {
+ String n = je.getName();
+ int lastSlash = n.lastIndexOf('/');
+ s.add(lastSlash > 0 ? n.substring(0, lastSlash).replace('/', '.') : "");
+ });
+ }
+ }
+ catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptActionManager.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptActionManager.java
index 5db19973c8..c9c9ad02e7 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptActionManager.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptActionManager.java
@@ -578,10 +578,10 @@ class GhidraScriptActionManager {
}
private void launchJavadoc() {
- URI URI = entryFile.toURI();
- URL URL = null;
+ URI uri = entryFile.toURI();
+ URL url = null;
try {
- URL = URI.toURL();
+ url = uri.toURL();
}
catch (MalformedURLException e) {
// shouldn't happen
@@ -591,7 +591,7 @@ class GhidraScriptActionManager {
return;
}
- BrowserLoader.display(URL, URL, plugin.getTool());
+ BrowserLoader.display(url, url, plugin.getTool());
}
private void writeZipEntry(File unzipDirectory, ZipEntry entry, InputStream inputStream)
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.java
index 38a57f42ce..00eb6a9ff5 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
@@ -41,7 +41,6 @@ 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;
@@ -66,12 +65,12 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {
static final String WINDOW_GROUP = "Script Group";
private Map<ResourceFile, GhidraScriptEditorComponentProvider> editorMap = new HashMap<>();
- final private GhidraScriptMgrPlugin plugin;
+ private final GhidraScriptMgrPlugin plugin;
private JPanel component;
private RootNode scriptRoot;
private GTree scriptCategoryTree;
private DraggableScriptTable scriptTable;
- final private GhidraScriptInfoManager infoManager;
+ private final GhidraScriptInfoManager infoManager;
private GhidraScriptTableModel tableModel;
private BundleStatusComponentProvider bundleStatusComponentProvider;
private TaskListener taskListener = new ScriptTaskListener();
@@ -99,8 +98,8 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {
}
};
- final private BundleHost bundleHost;
- final private RefreshingBundleHostListener refreshingBundleHostListener =
+ private final BundleHost bundleHost;
+ private final RefreshingBundleHostListener refreshingBundleHostListener =
new RefreshingBundleHostListener();
GhidraScriptComponentProvider(GhidraScriptMgrPlugin plugin, BundleHost bundleHost) {
@@ -158,8 +157,8 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {
}
});
- scriptCategoryTree.getSelectionModel().setSelectionMode(
- TreeSelectionModel.SINGLE_TREE_SELECTION);
+ scriptCategoryTree.getSelectionModel()
+ .setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tableModel = new GhidraScriptTableModel(this, infoManager);
@@ -237,7 +236,7 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {
//==================================================================================================
public void readConfigState(SaveState saveState) {
- bundleHost.restoreStateAndActivate(saveState, getTool());
+ bundleHost.restoreManagedBundleState(saveState, getTool());
actionManager.restoreUserDefinedKeybindings(saveState);
actionManager.restoreScriptsThatAreInTool(saveState);
@@ -261,7 +260,7 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {
}
public void writeConfigState(SaveState saveState) {
- bundleHost.saveState(saveState);
+ bundleHost.saveManagedBundleState(saveState);
actionManager.saveUserDefinedKeybindings(saveState);
actionManager.saveScriptsThatAreInTool(saveState);
@@ -408,8 +407,8 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {
action.setKeyBindingData(new KeyBindingData(ks));
}
- assert !infoManager.containsMetadata(
- renameFile) : "renamed script already has metadata";
+ assert !infoManager
+ .containsMetadata(renameFile) : "renamed script already has metadata";
infoManager.getScriptInfo(renameFile);
tableModel.switchScript(script, renameFile);
@@ -452,15 +451,20 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {
}
public List<ResourceFile> getScriptDirectories() {
- return bundleHost.getGhidraBundles().stream().filter(
- gb -> gb.isEnabled() && gb instanceof GhidraSourceBundle).map(
- GhidraBundle::getPath).collect(Collectors.toList());
+ return bundleHost.getGhidraBundles()
+ .stream()
+ .filter(bundle -> bundle.isEnabled() && bundle instanceof GhidraSourceBundle)
+ .map(GhidraBundle::getPath)
+ .collect(Collectors.toList());
}
public List<ResourceFile> getWritableScriptDirectories() {
- return bundleHost.getGhidraBundles().stream().filter(
- GhidraSourceBundle.class::isInstance).filter(gb -> !gb.isSystemBundle()).map(
- GhidraBundle::getPath).collect(Collectors.toList());
+ return bundleHost.getGhidraBundles()
+ .stream()
+ .filter(GhidraSourceBundle.class::isInstance)
+ .filter(bundle -> !bundle.isSystemBundle())
+ .map(GhidraBundle::getPath)
+ .collect(Collectors.toList());
}
boolean isEditorOpen(ResourceFile script) {
@@ -698,14 +702,14 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {
class RefreshingBundleHostListener implements BundleHostListener {
@Override
- public void bundleBuilt(GhidraBundle sb, String summary) {
- if (sb instanceof GhidraSourceBundle) {
- GhidraSourceBundle gsb = (GhidraSourceBundle) sb;
- for (ResourceFile sf : gsb.getNewSources()) {
- if (infoManager.containsMetadata(sf)) {
- ScriptInfo info = infoManager.getExistingScriptInfo(sf);
- BuildFailure e = gsb.getErrors(sf);
- info.setCompileErrors(e != null);
+ public void bundleBuilt(GhidraBundle bundle, String summary) {
+ if (bundle instanceof GhidraSourceBundle) {
+ GhidraSourceBundle sourceBundle = (GhidraSourceBundle) bundle;
+ for (ResourceFile sourceFile : sourceBundle.getNewSources()) {
+ if (infoManager.containsMetadata(sourceFile)) {
+ ScriptInfo scriptInfo = infoManager.getExistingScriptInfo(sourceFile);
+ GhidraBundle.BuildFailure e = sourceBundle.getErrors(sourceFile);
+ scriptInfo.setCompileErrors(e != null);
}
}
tableModel.fireTableDataChanged();
@@ -713,32 +717,32 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {
}
@Override
- public void bundleEnablementChange(GhidraBundle gbundle, boolean newEnablment) {
- if (gbundle instanceof GhidraSourceBundle) {
+ public void bundleEnablementChange(GhidraBundle bundle, boolean newEnablment) {
+ if (bundle instanceof GhidraSourceBundle) {
refresh();
}
}
@Override
- public void bundleAdded(GhidraBundle gbundle) {
+ public void bundleAdded(GhidraBundle bundle) {
plugin.getTool().setConfigChanged(true);
refresh();
}
@Override
- public void bundlesAdded(Collection<GhidraBundle> gbundles) {
+ public void bundlesAdded(Collection<GhidraBundle> bundles) {
plugin.getTool().setConfigChanged(true);
refresh();
}
@Override
- public void bundleRemoved(GhidraBundle gbundle) {
+ public void bundleRemoved(GhidraBundle bundle) {
plugin.getTool().setConfigChanged(true);
refresh();
}
@Override
- public void bundlesRemoved(Collection<GhidraBundle> gbundles) {
+ public void bundlesRemoved(Collection<GhidraBundle> bundles) {
plugin.getTool().setConfigChanged(true);
refresh();
}
@@ -1030,10 +1034,10 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {
}
private JComponent buildDescriptionComponent() {
- JPanel descriptionPanel = new JPanel(new BorderLayout());
descriptionTextPane = new JTextPane();
descriptionTextPane.setEditable(false);
descriptionTextPane.setEditorKit(new HTMLEditorKit());
+ JPanel descriptionPanel = new JPanel(new BorderLayout());
descriptionPanel.add(descriptionTextPane);
JScrollPane scrollPane = new JScrollPane(descriptionPanel);
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptMgrPlugin.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptMgrPlugin.java
index 38b91d9eca..309bd455f2 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptMgrPlugin.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptMgrPlugin.java
@@ -50,10 +50,10 @@ import ghidra.util.task.TaskListener;
//@formatter:on
public class GhidraScriptMgrPlugin extends ProgramPlugin implements GhidraScriptService {
- final private GhidraScriptComponentProvider provider;
+ private final GhidraScriptComponentProvider provider;
- static private int loaded = 0;
- final private BundleHost bundleHost;
+ private static int loaded = 0;
+ private final BundleHost bundleHost;
public GhidraScriptMgrPlugin(PluginTool tool) {
super(tool, true, true, true);
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptTableModel.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptTableModel.java
index 6eabde2ced..72f9718b3d 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptTableModel.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptTableModel.java
@@ -39,12 +39,12 @@ class GhidraScriptTableModel extends GDynamicColumnTableModel<ResourceFile, Obje
private static final String EMPTY_STRING = "";
private static final ImageIcon ERROR_IMG = Icons.ERROR_ICON;
- final static String SCRIPT_ACTION_COLUMN_NAME = "In Tool";
- final static String SCRIPT_STATUS_COLUMN_NAME = "Status";
+ static final String SCRIPT_ACTION_COLUMN_NAME = "In Tool";
+ static final String SCRIPT_STATUS_COLUMN_NAME = "Status";
private GhidraScriptComponentProvider provider;
private List<ResourceFile> scriptList = new ArrayList<>();
- final private GhidraScriptInfoManager infoManager;
+ private final GhidraScriptInfoManager infoManager;
GhidraScriptTableModel(GhidraScriptComponentProvider provider,
GhidraScriptInfoManager infoManager) {
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/script/GhidraScriptUtil.java b/Ghidra/Features/Base/src/main/java/ghidra/app/script/GhidraScriptUtil.java
index 5bbb20f5ee..0478bb1509 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/script/GhidraScriptUtil.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/script/GhidraScriptUtil.java
@@ -74,12 +74,12 @@ public class GhidraScriptUtil {
setBundleHost(bundleHost);
if (extraSystemPaths != null) {
for (String path : extraSystemPaths) {
- bundleHost.addGhidraBundle(new ResourceFile(path), true, true);
+ bundleHost.add(new ResourceFile(path), true, true);
}
}
- bundleHost.addGhidraBundle(GhidraScriptUtil.getUserScriptDirectory(), true, false);
- bundleHost.addGhidraBundles(GhidraScriptUtil.getSystemScriptPaths(), true, true);
+ bundleHost.add(GhidraScriptUtil.getUserScriptDirectory(), true, false);
+ bundleHost.add(GhidraScriptUtil.getSystemScriptPaths(), true, true);
}
public static void dispose() {
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.java
index dd0e5f1ddd..b2ca70d44f 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
@@ -51,9 +51,9 @@ public class JavaScriptProvider extends GhidraScriptProvider {
@Override
public boolean deleteScript(ResourceFile sourceFile) {
try {
- Bundle b = getBundleForSource(sourceFile).getBundle();
- if (b != null) {
- _bundleHost.deactivateSynchronously(b);
+ Bundle osgiBundle = getBundleForSource(sourceFile).getOSGiBundle();
+ if (osgiBundle != null) {
+ _bundleHost.deactivateSynchronously(osgiBundle);
}
}
catch (GhidraBundleException | InterruptedException e) {
@@ -95,7 +95,8 @@ public class JavaScriptProvider extends GhidraScriptProvider {
public Class<?> loadClass(ResourceFile sourceFile, PrintWriter writer) throws Exception {
GhidraSourceBundle gb = getBundleForSource(sourceFile);
gb.build(writer);
- Bundle b = _bundleHost.installFromLoc(gb.getBundleLoc());
+
+ Bundle b = _bundleHost.install(gb);
_bundleHost.activateSynchronously(b);
diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/script/AbstractGhidraScriptMgrPluginTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/script/AbstractGhidraScriptMgrPluginTest.java
index 2ad984aaec..724d9afcae 100644
--- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/script/AbstractGhidraScriptMgrPluginTest.java
+++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/script/AbstractGhidraScriptMgrPluginTest.java
@@ -26,6 +26,7 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
import javax.swing.*;
import javax.swing.table.TableModel;
@@ -44,11 +45,9 @@ import docking.widgets.table.RowObjectTableModel;
import docking.widgets.tree.GTree;
import docking.widgets.tree.GTreeNode;
import generic.jar.ResourceFile;
-import generic.test.TestUtils;
import ghidra.app.plugin.core.codebrowser.CodeBrowserPlugin;
import ghidra.app.plugin.core.console.ConsoleComponentProvider;
-import ghidra.app.plugin.core.osgi.BundleHost;
-import ghidra.app.plugin.core.osgi.BundleStatusComponentProvider;
+import ghidra.app.plugin.core.osgi.GhidraSourceBundle;
import ghidra.app.script.*;
import ghidra.app.services.ConsoleService;
import ghidra.framework.Application;
@@ -181,8 +180,8 @@ public abstract class AbstractGhidraScriptMgrPluginTest
static protected void wipe(Path path) throws IOException {
if (Files.exists(path)) {
- for (Path p : (Iterable<Path>) Files.walk(path).sorted(
- Comparator.reverseOrder())::iterator) {
+ for (Path p : (Iterable<Path>) Files.walk(path)
+ .sorted(Comparator.reverseOrder())::iterator) {
Files.deleteIfExists(p);
}
}
@@ -687,8 +686,8 @@ public abstract class AbstractGhidraScriptMgrPluginTest
"Contents of file on disk do not match that of the editor after performing " +
"a save operation: " + file);
printChars(expectedContents, fileText);
- Assert.fail(
- "Contents of file on disk do not match that of the editor after performing " +
+ Assert
+ .fail("Contents of file on disk do not match that of the editor after performing " +
"a save operation: " + file);
}
//
@@ -980,15 +979,16 @@ public abstract class AbstractGhidraScriptMgrPluginTest
protected void cleanupOldTestFiles() throws IOException {
// remove the compiled bundles directory so that any scripts we use will be recompiled
- wipe(BundleHost.getCompiledBundlesDir());
+ wipe(GhidraSourceBundle.getCompiledBundlesDir());
String myTestName = super.testName.getMethodName();
// destroy any NewScriptxxx files...and Temp ones too
- BundleStatusComponentProvider bundleStatusComponentProvider =
- (BundleStatusComponentProvider) TestUtils.getInstanceField(
- "bundleStatusComponentProvider", provider);
- List<ResourceFile> paths = bundleStatusComponentProvider.getModel().getEnabledPaths();
+ List<ResourceFile> paths = provider.getBundleHost()
+ .getBundlePaths()
+ .stream()
+ .filter(ResourceFile::isDirectory)
+ .collect(Collectors.toList());
for (ResourceFile path : paths) {
File file = path.getFile(false);
diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/script/BundleHostTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/script/BundleHostTest.java
index f3676e4c81..4e7e47112b 100644
--- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/script/BundleHostTest.java
+++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/script/BundleHostTest.java
@@ -55,7 +55,7 @@ public class BundleHostTest extends AbstractGhidraHeadlessIntegrationTest {
tmpdirs.add(tmpDir);
ResourceFile rp = new ResourceFile(tmpDir.toFile());
- current_gb = bundleHost.addGhidraBundle(rp, true, false);
+ current_gb = bundleHost.add(rp, true, false);
gbstack.push(current_gb);
return current_gb;
}
@@ -71,7 +71,7 @@ public class BundleHostTest extends AbstractGhidraHeadlessIntegrationTest {
@Before
public void setup() throws OSGiException, IOException {
- wipe(BundleHost.getCompiledBundlesDir());
+ wipe(GhidraSourceBundle.getCompiledBundlesDir());
bundleHost = new BundleHost();
bundleHost.startFramework();
@@ -106,7 +106,7 @@ public class BundleHostTest extends AbstractGhidraHeadlessIntegrationTest {
}
protected void activate() throws Exception {
- Bundle bundle = bundleHost.installFromLoc(current_gb.getBundleLoc());
+ Bundle bundle = bundleHost.install(current_gb);
assertNotNull("failed to install bundle", bundle);
bundle.start();
}
@@ -117,7 +117,7 @@ public class BundleHostTest extends AbstractGhidraHeadlessIntegrationTest {
}
protected Class<?> loadClass(String classname) throws ClassNotFoundException {
- Class<?> clazz = current_gb.getBundle().loadClass(classname);
+ Class<?> clazz = current_gb.getOSGiBundle().loadClass(classname);
assertNotNull("failed to load class", clazz);
return clazz;
}
@@ -313,7 +313,7 @@ public class BundleHostTest extends AbstractGhidraHeadlessIntegrationTest {
pushNewBundle();
- // @imports tag is only parsed from classes in default package
+ // @importpackages tag is only parsed from classes in default package
addClass(
"//@importpackage lib\n"
,