Skip to content

Ghidra is a software reverse engineering (SRE) framework

fix NPE when adding jar with no manifest, improve error handling

Jason P. Leasure636a20c8e262
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 8b30a4bdf1..5e1b57d316 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
@@ -691,15 +691,9 @@ public class BundleHost {
public void activateAll(Collection<GhidraBundle> bundles, TaskMonitor monitor,
PrintWriter console) {
- List<GhidraBundle> availableBundles = getGhidraBundles().stream()
- .filter(GhidraBundle::isEnabled)
- .collect(Collectors.toList());
-
- BundleDependencyGraph dependencyGraph =
- new BundleDependencyGraph(availableBundles, bundles, monitor);
+ BundleDependencyGraph dependencyGraph = new BundleDependencyGraph(bundles, monitor);
monitor.setMaximum(dependencyGraph.vertexSet().size());
-
for (GhidraBundle bundle : dependencyGraph.inTopologicalOrder()) {
if (monitor.isCancelled()) {
break;
@@ -728,21 +722,25 @@ public class BundleHost {
*/
public void activateInStages(Collection<GhidraBundle> bundles, TaskMonitor monitor,
PrintWriter console) {
- List<GhidraBundle> bundlesRemaining = new ArrayList<>(bundles);
+ Map<GhidraBundle, List<BundleRequirement>> requirementMap = new HashMap<>();
+ for (GhidraBundle bundle : bundles) {
+ try {
+ requirementMap.put(bundle, bundle.getAllRequirements());
+ }
+ catch (GhidraBundleException e) {
+ fireBundleException(e);
+ }
+ }
+ List<GhidraBundle> bundlesRemaining = new ArrayList<>(requirementMap.keySet());
monitor.setMaximum(bundlesRemaining.size());
while (!bundlesRemaining.isEmpty() && !monitor.isCancelled()) {
- List<GhidraBundle> resolvableBundles = bundlesRemaining.stream().filter(bundle -> {
- try {
- return canResolveAll(bundle.getAllRequirements());
- }
- catch (GhidraBundleException e) {
- // failure in last round will set fireBundleException
- }
- return false;
- }).collect(Collectors.toList());
+ List<GhidraBundle> resolvableBundles = bundlesRemaining.stream()
+ .filter(bundle -> canResolveAll(requirementMap.get(bundle)))
+ .collect(Collectors.toList());
if (resolvableBundles.isEmpty()) {
- // final round, try everything we couldn't resolve to generate errors
+ // final round, try everything that hasn't already been eliminated.
+ // this can generate helpful error messages
resolvableBundles = bundlesRemaining;
bundlesRemaining = Collections.emptyList();
}
@@ -927,18 +925,29 @@ public class BundleHost {
// exists only to be distinguished by id
}
- private static class BundleDependencyGraph
- extends DirectedMultigraph<GhidraBundle, Dependency> {
+ /**
+ * Utility class to build a dependency graph from bundles where capabilities map to requirements.
+ */
+ private class BundleDependencyGraph extends DirectedMultigraph<GhidraBundle, Dependency> {
final Map<GhidraBundle, List<BundleCapability>> capabilityMap = new HashMap<>();
final List<GhidraBundle> availableBundles;
final TaskMonitor monitor;
- BundleDependencyGraph(List<GhidraBundle> availableBundles,
- Collection<GhidraBundle> startingBundles, TaskMonitor monitor) {
+ BundleDependencyGraph(Collection<GhidraBundle> startingBundles, TaskMonitor monitor) {
super(null, null, false);
- this.availableBundles = availableBundles;
this.monitor = monitor;
+ // maintain a list of bundles available for resolution, starting with all of the enabled bundles
+ this.availableBundles = new ArrayList<>();
+ for (GhidraBundle bundle : getGhidraBundles()) {
+ if (bundle.isEnabled()) {
+ addToAvailable(bundle);
+ }
+ }
+ // An edge A->B indicates that the capabilities of A resolve some requirement(s) of B
+
+ // "front" accumulates bundles and links to bundles already in the graph that they provide capabilities for.
+ // e.g. if front[A]=[B,...] then A->B, B is already in the graph, and we will add A next iteration.
Map<GhidraBundle, Set<GhidraBundle>> front = new HashMap<>();
for (GhidraBundle bundle : startingBundles) {
front.put(bundle, null);
@@ -951,6 +960,7 @@ public class BundleHost {
for (GhidraBundle bundle : front.keySet()) {
resolve(bundle, newFront);
}
+
handleBackEdges(newFront);
front = newFront;
}
@@ -969,7 +979,9 @@ public class BundleHost {
GhidraBundle source = entry.getKey();
if (containsVertex(source)) {
for (GhidraBundle destination : entry.getValue()) {
- addEdge(source, destination, new Dependency());
+ if (source != destination) {
+ addEdge(source, destination, new Dependency());
+ }
}
newFrontIter.remove();
}
@@ -979,31 +991,48 @@ public class BundleHost {
void addFront(Map<GhidraBundle, Set<GhidraBundle>> front) {
for (Entry<GhidraBundle, Set<GhidraBundle>> e : front.entrySet()) {
GhidraBundle source = e.getKey();
- availableBundles.add(source);
- addVertex(source);
- Set<GhidraBundle> destinations = e.getValue();
- if (destinations != null) {
- for (GhidraBundle destination : destinations) {
- addEdge(source, destination, new Dependency());
+ if (addToAvailable(source)) {
+ addVertex(source);
+ Set<GhidraBundle> destinations = e.getValue();
+ if (destinations != null) {
+ for (GhidraBundle destination : destinations) {
+ addEdge(source, destination, new Dependency());
+ }
}
}
}
}
+ boolean addToAvailable(GhidraBundle bundle) {
+ try {
+ capabilityMap.put(bundle, bundle.getAllCapabilities());
+ availableBundles.add(bundle);
+ return true;
+ }
+ catch (GhidraBundleException ex) {
+ fireBundleException(ex);
+ return false;
+ }
+ }
+
+ // populate newFront with edges depBundle -> bundle,
+ // where depBundle has a capability that resolves a requirement of bundle
void resolve(GhidraBundle bundle, Map<GhidraBundle, Set<GhidraBundle>> newFront) {
List<BundleRequirement> requirements;
try {
requirements = new ArrayList<>(bundle.getAllRequirements());
+ if (requirements.isEmpty()) {
+ return;
+ }
}
catch (GhidraBundleException e) {
- throw new RuntimeException(e);
- }
- if (requirements.isEmpty()) {
+ fireBundleException(e);
+ removeVertex(bundle);
return;
}
for (GhidraBundle depBundle : availableBundles) {
- for (BundleCapability capability : getCapabilities(depBundle)) {
+ for (BundleCapability capability : capabilityMap.get(depBundle)) {
if (monitor.isCancelled()) {
return;
}
@@ -1020,18 +1049,8 @@ public class BundleHost {
}
}
}
- }
-
- List<BundleCapability> getCapabilities(GhidraBundle bundle) {
- return capabilityMap.computeIfAbsent(bundle, b -> {
- try {
- return b.getAllCapabilities();
- }
- catch (GhidraBundleException e) {
- Msg.error(this, "getting capabilities", e);
- return null;
- }
- });
+ // if requirements remain, some will be resolved by system
+ // and others will generate helpful errors for the user during activation
}
}
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 95fe3c29c5..3125ae9df7 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
@@ -36,8 +36,7 @@ import ghidra.app.services.ConsoleService;
import ghidra.framework.plugintool.ComponentProviderAdapter;
import ghidra.framework.plugintool.PluginTool;
import ghidra.framework.preferences.Preferences;
-import ghidra.util.HelpLocation;
-import ghidra.util.Msg;
+import ghidra.util.*;
import ghidra.util.exception.CancelledException;
import ghidra.util.filechooser.GhidraFileChooserModel;
import ghidra.util.filechooser.GhidraFileFilter;
@@ -321,14 +320,18 @@ public class BundleStatusComponentProvider extends ComponentProviderAdapter {
}
private void notifyTableRowChanged(BundleStatus status) {
- int modelRowIndex = bundleStatusTableModel.getRowIndex(status);
- int viewRowIndex = filterPanel.getViewRow(modelRowIndex);
- bundleStatusTable
- .notifyTableChanged(new TableModelEvent(bundleStatusTableModel, viewRowIndex));
+ Swing.runIfSwingOrRunLater(() -> {
+ int modelRowIndex = bundleStatusTableModel.getRowIndex(status);
+ int viewRowIndex = filterPanel.getViewRow(modelRowIndex);
+ bundleStatusTable
+ .notifyTableChanged(new TableModelEvent(bundleStatusTableModel, viewRowIndex));
+ });
}
private void notifyTableDataChanged() {
- bundleStatusTable.notifyTableChanged(new TableModelEvent(bundleStatusTableModel));
+ Swing.runIfSwingOrRunLater(() -> {
+ bundleStatusTable.notifyTableChanged(new TableModelEvent(bundleStatusTableModel));
+ });
}
@Override
@@ -374,24 +377,22 @@ public class BundleStatusComponentProvider extends ComponentProviderAdapter {
@Override
public void run(TaskMonitor monitor) throws CancelledException {
deactivateBundlesTask.run(monitor);
- if (!monitor.isCancelled()) {
- // partition bundles into system (bundles.get(true)) and non-system (bundles.get(false)).
- Map<Boolean, List<GhidraBundle>> bundles = statuses.stream()
- .map(bs -> bundleHost.getExistingGhidraBundle(bs.getFile()))
- .collect(Collectors.partitioningBy(GhidraBundle::isSystemBundle));
-
- List<GhidraBundle> systemBundles = bundles.get(true);
- if (!systemBundles.isEmpty()) {
- StringBuilder stringBuilder = new StringBuilder();
- for (GhidraBundle bundle : systemBundles) {
- stringBuilder.append(Path.toPathString(bundle.getFile()) + "\n");
- }
- Msg.showWarn(this, BundleStatusComponentProvider.this.getComponent(),
- "Unabled to remove",
- "System bundles cannot be removed:\n" + stringBuilder.toString());
+ monitor.checkCanceled();
+ // partition bundles into system (bundles.get(true)) and non-system (bundles.get(false)).
+ Map<Boolean, List<GhidraBundle>> bundles = statuses.stream()
+ .map(bs -> bundleHost.getExistingGhidraBundle(bs.getFile()))
+ .collect(Collectors.partitioningBy(GhidraBundle::isSystemBundle));
+
+ List<GhidraBundle> systemBundles = bundles.get(true);
+ if (!systemBundles.isEmpty()) {
+ StringBuilder buff = new StringBuilder();
+ for (GhidraBundle bundle : systemBundles) {
+ buff.append(Path.toPathString(bundle.getFile()) + "\n");
}
- bundleHost.remove(bundles.get(false));
+ Msg.showWarn(this, BundleStatusComponentProvider.this.getComponent(),
+ "Unabled to remove", "System bundles cannot be removed:\n" + buff.toString());
}
+ bundleHost.remove(bundles.get(false));
}
}
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 36681948a3..1f9ec1cf1a 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
@@ -53,6 +53,18 @@ public class GhidraBundleException extends OSGiException {
this.bundleLocation = bundleLocation;
}
+ /**
+ * Construct a new exception originating with the bundle having location identifier {@code bundleLocation}.
+ *
+ * @param bundleLocation the bundle location identifier (since no bundle is available)
+ * @param msg a contextual message
+ */
+ public GhidraBundleException(String bundleLocation, String msg) {
+ super(msg);
+ this.bundle = null;
+ this.bundleLocation = bundleLocation;
+ }
+
/**
* @return the associated bundle, or null. If null, the bundle location identifier will be non-null
*/
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 6076abde3e..918ee8836a 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
@@ -23,11 +23,13 @@ import java.util.jar.Manifest;
import java.util.stream.Collectors;
import org.apache.felix.framework.util.manifestparser.ManifestParser;
+import org.osgi.framework.BundleException;
import org.osgi.framework.wiring.BundleCapability;
import org.osgi.framework.wiring.BundleRequirement;
import aQute.bnd.osgi.Jar;
import generic.jar.ResourceFile;
+import ghidra.util.exception.AssertException;
/**
* Proxy to an ordinary OSGi Jar bundle. {@link GhidraJarBundle#build(PrintWriter)} does nothing.
@@ -64,9 +66,12 @@ public class GhidraJarBundle extends GhidraBundle {
return bundleLocation;
}
- protected ManifestParser createManifestParser() {
+ protected ManifestParser createManifestParser() throws GhidraBundleException {
try (Jar jar = new Jar(file.getFile(true))) {
Manifest manifest = jar.getManifest();
+ if (manifest == null) {
+ throw new GhidraBundleException(bundleLocation, "jar bundle with no manifest");
+ }
Attributes mainAttributes = manifest.getMainAttributes();
Map<String, Object> headerMap = mainAttributes.entrySet()
.stream()
@@ -74,8 +79,14 @@ public class GhidraJarBundle extends GhidraBundle {
Collectors.toMap(e -> e.getKey().toString(), e -> e.getValue().toString()));
return new ManifestParser(null, null, null, headerMap);
}
+ catch (BundleException e) {
+ throw new GhidraBundleException(bundleLocation, "parsing manifest", e);
+ }
+ catch (GhidraBundleException e) {
+ throw e;
+ }
catch (Exception e) {
- throw new RuntimeException(e);
+ throw new AssertException("Unexpected exception while parsing manifest", e);
}
}
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 693cce573b..241135958a 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
@@ -713,11 +713,31 @@ public class GhidraSourceBundle extends GhidraBundle {
}
}
catch (Throwable e) {
- Msg.error(this, "Exception searching ", e);
- e.printStackTrace();
+ Msg.error(this, "Exception while searching for file system discrepancies ", e);
}
}
+ /* requirements that resolve internally are never "missing", but will only resolve _after_ build/install */
+ private boolean resolveInternally(List<BundleRequirement> requirements)
+ throws GhidraBundleException {
+ if (requirements.isEmpty()) {
+ return true;
+ }
+ List<BundleCapability> capabilities = getAllCapabilities();
+ Iterator<BundleRequirement> requirementIterator = requirements.iterator();
+ boolean anyMissing = false;
+ while (requirementIterator.hasNext()) {
+ BundleRequirement requirement = requirementIterator.next();
+ if (capabilities.stream().anyMatch(requirement::matches)) {
+ requirementIterator.remove();
+ }
+ else {
+ anyMissing = true;
+ }
+ }
+ return !anyMissing;
+ }
+
/*
* when calling the java compiler programmatically, we map import requests to files with
* a custom {@link JavaFileManager}. We wrap the system JavaFileManager with one that
@@ -740,7 +760,7 @@ public class GhidraSourceBundle extends GhidraBundle {
List<BundleRequirement> requirements = getAllRequirements();
List<BundleWiring> bundleWirings = bundleHost.resolve(requirements);
- if (!requirements.isEmpty()) {
+ if (!resolveInternally(requirements)) {
writer.printf("%d import requirement%s remain%s unresolved:\n", requirements.size(),
requirements.size() > 1 ? "s" : "", requirements.size() > 1 ? "" : "s");
for (BundleRequirement requirement : requirements) {
@@ -1097,8 +1117,7 @@ public class GhidraSourceBundle extends GhidraBundle {
}
try (Stream<Path> paths = Files.list(directory)) {
- classToClassFilesMap = paths
- .filter(p -> Files.isRegularFile(p))
+ classToClassFilesMap = paths.filter(p -> Files.isRegularFile(p))
.filter(p -> p.getFileName().toString().endsWith(".class"))
.collect(groupingBy(this::getClassName));
}