Ghidra is a software reverse engineering (SRE) framework
add exceptions and handlers for osgi + scripting
Jason P. Leasure44aea2a48a0f
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/script/JavaScriptProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/script/JavaScriptProvider.javaindex 5b6bcad790..52d60e2bed 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@@ -19,12 +19,10 @@ import java.io.*;import java.lang.reflect.InvocationTargetException;import org.osgi.framework.Bundle;-import org.osgi.framework.BundleException;import generic.io.NullPrintWriter;import generic.jar.ResourceFile;-import ghidra.app.script.osgi.BundleCompiler;-import ghidra.app.script.osgi.BundleHost;+import ghidra.app.script.osgi.*;import ghidra.app.script.osgi.BundleHost.SourceBundleInfo;import ghidra.util.Msg;@@ -38,10 +36,9 @@ public class JavaScriptProvider extends GhidraScriptProvider {try {_bundle_host.start_felix();}- catch (BundleException | IOException e) {- e.printStackTrace();+ catch (OSGiException | IOException e) {+ throw new RuntimeException(e);}-}return _bundle_host;}@@ -80,122 +77,96 @@ public class JavaScriptProvider extends GhidraScriptProvider {writer = new NullPrintWriter();}- SourceBundleInfo bi = getBundleInfoForScript(sourceFile);-try {- bi.udpateFromFilesystem(writer);- }- catch (IOException e) {- e.printStackTrace(writer);- return null;- }- int failing = bi.getFailingSourcesCount();- int newSourcecount = bi.getNewSourcesCount();- if (failing > 0 && newSourcecount == 0) {- writer.printf("%s hasn't changed, with %d file%s failing in previous build(s):\n",- bi.getSourceDir().toString(), failing, failing > 1 ? "s" : "");- writer.printf("%s\n", bi.getPreviousBuildErrors());- }- if (bi.newManifestFile() && newSourcecount == 0) {- // XXX if there is a new or updated manifest file, uninstall bundle, copy manifest, and restart bundle- }+ SourceBundleInfo bi = getBundleInfoForScript(sourceFile);- BundleHost bundle_host = getBundleHost();- // there's new source, so uninstall any existing bundle, delete old class files, and recompile- if (newSourcecount > 0) {- writer.printf("%s has changed: %d new/updated\n", bi.getSourceDir().toString(),- newSourcecount);+ bi.updateFromFilesystem(writer);- // if there a bundle is currently active, uninstall it- Bundle b = bi.getBundle();- if (b != null) {- try {- bundle_host.synchronousUninstall(b);- }- catch (BundleException | InterruptedException e) {- e.printStackTrace();- Msg.error(this, "uninstalling bundle", e);- return null;- }+ // needsCompile => needsBundleActivate+ boolean needsCompile = false;+ boolean needsBundleActivate = false;++ int failing = bi.getFailingSourcesCount();+ int newSourcecount = bi.getNewSourcesCount();++ long lastBundleActivation = 0; // XXX record last bundle activation in pathmanager+ if (failing > 0 && (lastBundleActivation > bi.getLastCompileAttempt())) {+ needsCompile = true;}- // once we've committed to recompile and regenerate generated classes, delete the old stuff- try {- bi.deleteOldBinaries();+ if (newSourcecount == 0) {+ if (failing > 0) {+ writer.printf(+ "%s hasn't changed, with %d file%s failing in previous build(s):\n",+ bi.getSourceDir().toString(), failing, failing > 1 ? "s" : "");+ writer.printf("%s\n", bi.getPreviousBuildErrors());+ }+ if (bi.newManifestFile()) {+ needsCompile = true;+ }}- catch (IOException e) {- e.printStackTrace(writer);- Msg.error(this, "deleting old binaries", e);- return null;+ else {+ needsCompile = true;}- BundleCompiler bc = new BundleCompiler(bundle_host);- Msg.trace(this,- "Compiling bundle dir " + bi.getSourceDir() + " to dir " + bi.getBinDir());+ needsBundleActivate |= needsCompile;- long startTime = System.nanoTime();- try {- bc.compileToExplodedBundle(bi, writer);- }- catch (IOException e) {- e.printStackTrace(writer);- Msg.error(this, "compiling bundle", e);- return null;- }- finally {- long endTime = System.nanoTime();- writer.printf("%3.2f seconds compile time.\n", (endTime - startTime) / 1e9);- }- }- // as much source as possible built, install bundle and start it if necessary- Bundle b = bi.getBundle();- try {- if (b == null) {- b = bi.install();- }- if (b.getState() != Bundle.ACTIVE) {- b.start();+ BundleHost bundle_host = getBundleHost();+ if (needsBundleActivate) {+ writer.printf("%s has %d new/updated %d failed in previous build(s)%s\n",+ bi.getSourceDir().toString(), newSourcecount, failing,+ bi.newManifestFile() ? " and the manifest is new" : "");++ // if there a bundle is currently active, uninstall it+ Bundle b = bi.getBundle();+ if (b != null) {+ bundle_host.synchronousUninstall(b);+ }++ // once we've committed to recompile and regenerate generated classes, delete the old stuff+ if (needsCompile) {+ bi.deleteOldBinaries();++ BundleCompiler bc = new BundleCompiler(bundle_host);++ long startTime = System.nanoTime();+ bc.compileToExplodedBundle(bi, writer);+ long endTime = System.nanoTime();+ writer.printf("%3.2f seconds compile time.\n", (endTime - startTime) / 1e9);+ }}- if (!bundle_host.waitForBundleStart(bi.getBundleLoc())) {- Msg.error(this, "unable to start bundle");- return null;+ // as much source as possible built, install bundle and start it if necessary+ Bundle b = bi.getBundle();+ if (needsBundleActivate) {+ if (b == null) {+ b = bi.install();+ }+ bundle_host.synchronousStart(b);}- }- catch (InterruptedException | BundleException e) {- e.printStackTrace();- Msg.error(this, "starting bundle", e);- return null;- }- String classname = bi.classNameForScript(sourceFile);- Object object;- try {+ String classname = bi.classNameForScript(sourceFile);+ Object object;Class<?> clazz = b.loadClass(classname); // throws ClassNotFoundExceptionobject = clazz.getDeclaredConstructor().newInstance();- }- catch (IllegalArgumentException | InvocationTargetException | NoSuchMethodException- | SecurityException e) {- e.printStackTrace();- Msg.error(this, "instantiatiating script", e);- return null;- }- catch (ClassNotFoundException e) {- throw new ClassNotFoundException(- String.format("%s not found in bundle %s", classname, bi.getBinDir().toString()),- e.getException());- }- if (object instanceof GhidraScript) {- GhidraScript script = (GhidraScript) object;- script.setSourceFile(sourceFile);- return script;- }+ if (object instanceof GhidraScript) {+ GhidraScript script = (GhidraScript) object;+ script.setSourceFile(sourceFile);+ return script;+ }- String message = "Not a valid Ghidra script: " + sourceFile.getName();- writer.println(message);- Msg.error(this, message);- return null; // class is not GhidraScript+ String message = "Not a valid Ghidra script: " + sourceFile.getName();+ writer.println(message);+ Msg.error(this, message);+ return null; // class is not GhidraScript+ }+ catch (NoSuchMethodException | IOException | IllegalArgumentException+ | InvocationTargetException | SecurityException | InterruptedException+ | OSGiException e) {+ // XXX getScriptInstance only distinguishes exception to print one of three messages.+ throw new ClassNotFoundException("", e);+ }}/**@@ -264,8 +235,6 @@ public class JavaScriptProvider extends GhidraScriptProvider {return "//";}- // XXX everything from here down is deprecated but has dependents-@Deprecatedprotected boolean needsCompile(ResourceFile sourceFile, File classFile) {return true;diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/BundleCompiler.java b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/BundleCompiler.javaindex 307802349b..4d6fe062fc 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/BundleCompiler.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/BundleCompiler.java@@ -37,7 +37,6 @@ import aQute.bnd.osgi.Clazz.QUERY;import generic.jar.ResourceFile;import ghidra.app.script.*;import ghidra.app.script.osgi.BundleHost.SourceBundleInfo;-import ghidra.util.Msg;public class BundleCompiler {@@ -50,9 +49,18 @@ public class BundleCompiler {JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();- // compile a source directory to an exploded bundle+ /**+ * compile a source directory to an exploded bundle+ *+ * @param bi the bundle info to build+ * @param writer for updating the user during compilation+ * @throws IOException for source/manifest file reading/generation and binary deletion/creation+ * @throws OSGiException if generation of bundle metadata fails+ */public void compileToExplodedBundle(SourceBundleInfo bi, PrintWriter writer)- throws IOException {+ throws IOException, OSGiException {++ bi.compileAttempted();ResourceFile srcdir = bi.getSourceDir();Path bindir = bi.getBinDir();@@ -171,21 +179,31 @@ public class BundleCompiler {// analyzer.setBundleActivator(s);try {- Manifest manifest = analyzer.calcManifest();+ Manifest manifest;+ try {+ manifest = analyzer.calcManifest();+ }+ catch (Exception e) {+ throw new OSGiException("failed to calculate manifest by analyzing code", e);+ }Attributes ma = manifest.getMainAttributes();String activator_classname = null;- 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();+ 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();+ }}}+ catch (Exception e) {+ throw new OSGiException("failed to query classes while searching for activator", e);+ }if (activator_classname == null) {activator_classname = GENERATED_ACTIVATOR_CLASSNAME;- if (!createActivator(bindir, activator_classname, writer)) {- Msg.error(this, "failed to create activator");+ if (!buildDefaultActivator(bindir, activator_classname, writer)) {return;}// since we add the activator after bndtools built the imports, we should add its imports too@@ -205,15 +223,22 @@ public class BundleCompiler {manifest.write(out);}}- catch (Exception e) {- e.printStackTrace(writer);- }finally {analyzer.close();}}- private boolean createActivator(Path bindir, String activator_classname, Writer writer)+ /**+ * 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 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)throws IOException {Path activator_dest = bindir.resolve(activator_classname + ".java");@@ -233,10 +258,6 @@ public class BundleCompiler {out.println();out.println("}");}- catch (IOException ex) {- ex.printStackTrace();- return false;- }List<String> options = new ArrayList<>();options.add("-g");diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/BundleHost.java b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/BundleHost.javaindex cf5ed36ce7..6667dfeafb 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/BundleHost.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/BundleHost.java@@ -24,8 +24,7 @@ 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 java.util.stream.*;import org.apache.felix.framework.FrameworkFactory;import org.apache.felix.framework.util.FelixConstants;@@ -40,7 +39,6 @@ import generic.jar.ResourceFile;import ghidra.app.script.GhidraScriptUtil;import ghidra.app.script.ScriptInfo;import ghidra.framework.Application;-import ghidra.util.Msg;import ghidra.util.exception.CancelledException;import ghidra.util.task.*;@@ -52,7 +50,7 @@ public class BundleHost {public void dispose() {if (felix != null) {- stop_felix();+ forceStopFelix();}}@@ -73,16 +71,21 @@ public class BundleHost {** @param imports Import-Package value* @return deduced requirements or null if there was an error- * @throws BundleException on failed parse+ * @throws OSGiException on parse failure*/- static List<BundleRequirement> parseImports(String imports) throws BundleException {+ static List<BundleRequirement> parseImports(String imports) throws OSGiException {// parse it with Felix's ManifestParser to a list of BundleRequirement objectsMap<String, Object> headerMap = new HashMap<>();headerMap.put(Constants.IMPORT_PACKAGE, imports);ManifestParser mp;- mp = new ManifestParser(null, null, null, headerMap);- return mp.getRequirements();+ try {+ mp = new ManifestParser(null, null, null, headerMap);+ return mp.getRequirements();+ }+ catch (org.osgi.framework.BundleException e) {+ throw new OSGiException("parsing Import-Package: " + imports, e);+ }}/**@@ -145,8 +148,8 @@ public class BundleHost {return binDir;}- public Bundle install() throws BundleException {- return BundleHost.this.bc.installBundle(getBundleLoc());+ public Bundle install() throws GhidraBundleException {+ return BundleHost.this.installFromLoc(getBundleLoc());}public void buildError(ResourceFile rf, String err) {@@ -186,7 +189,7 @@ public class BundleHost {boolean foundNewManifest;private List<BundleRequirement> foundRequirements;- private void computeRequirements() throws BundleException {+ private void computeRequirements() throws OSGiException {foundRequirements = null;Map<String, BundleRequirement> dedupedreqs = new HashMap<>();// parse metadata from all Java source in sourceDir@@ -209,9 +212,10 @@ public class BundleHost {* look for new sources, metadata, manifest file.** @param writer for reporting status to user- * @throws IOException when there are unexpected issues w/ the filesystem+ * @throws IOException while accessing manifest file+ * @throws OSGiException while parsing imports*/- public void udpateFromFilesystem(PrintWriter writer) throws IOException {+ public void updateFromFilesystem(PrintWriter writer) throws IOException, OSGiException {// look for new source filesnewSources.clear();@@ -232,14 +236,7 @@ public class BundleHost {}});- try {- computeRequirements();- }- catch (BundleException e) {- Msg.error(this, "computing requirements", e);- e.printStackTrace(writer);- return;- }+ computeRequirements();// remove source files that failed last time and haven't changedIterator<ResourceFile> it = newSources.iterator();@@ -274,6 +271,16 @@ public class BundleHost {return foundNewManifest;}+ long lastCompileAttempt;++ public void compileAttempted() {+ lastCompileAttempt = System.currentTimeMillis();+ }++ public long getLastCompileAttempt() {+ return lastCompileAttempt;+ }+}String buildExtraPackages() {@@ -286,14 +293,26 @@ public class BundleHost {Framework felix;Bundle fileinstall_bundle;- Bundle installFromPath(String path_to_jar) throws BundleException {- Path p = Paths.get(path_to_jar);- return bc.installBundle("file://" + p.toAbsolutePath().normalize().toString());+ Bundle installFromPath(Path p) throws GhidraBundleException {+ return installFromLoc("file://" + p.toAbsolutePath().normalize().toString());}- Bundle installFromPathAs(String path_to_jar, String location)- throws FileNotFoundException, IOException, BundleException {- return bc.installBundle(location, new FileInputStream(new File(path_to_jar)));+ Bundle installFromLoc(String bundle_loc) throws GhidraBundleException {+ try {+ return bc.installBundle(bundle_loc);+ }+ catch (BundleException e) {+ throw new GhidraBundleException(bundle_loc, "installing from bundle location", e);+ }+ }++ Bundle installAsLoc(String bundle_loc, InputStream contents) throws GhidraBundleException {+ try {+ return bc.installBundle(bundle_loc, contents);+ }+ catch (BundleException e) {+ throw new GhidraBundleException(bundle_loc, "installing as bundle location", e);+ }}void dumpLoadedBundles() {@@ -356,7 +375,13 @@ public class BundleHost {}- public void start_felix() throws BundleException, IOException {+ /**+ * start the framework+ *+ * @throws OSGiException framework failures+ * @throws IOException filesystem setup+ */+ public void start_felix() throws OSGiException, IOException {Properties config = new Properties();@@ -388,7 +413,12 @@ public class BundleHost {FrameworkFactory factory = new FrameworkFactory();felix = factory.newFramework(config);- felix.init();+ try {+ felix.init();+ }+ catch (BundleException e) {+ throw new OSGiException("initializing felix OSGi framework", e);+ }bc = felix.getBundleContext();AutoProcessor.process(config, bc);@@ -454,7 +484,12 @@ public class BundleHost {}});- felix.start();+ try {+ felix.start();+ }+ catch (BundleException e) {+ throw new OSGiException("starting felix OSGi framework", e);+ }// fileinstall_bundle = installFromPath(findJarForClass(FileInstall.class));// fileinstall_bundle.start();@@ -484,69 +519,61 @@ public class BundleHost {return bc.getBundle(bundleLoc);}- // return true if it was running in the first place- public boolean synchronousStop(Bundle b) throws InterruptedException, BundleException {- if (b != null) {- switch (b.getState()) {- case Bundle.STARTING:- case Bundle.ACTIVE:- b.stop();- case Bundle.STOPPING:- while (true) {- switch (b.getState()) {- case Bundle.ACTIVE:- case Bundle.STOPPING:- Thread.sleep(500);- default:- return true;- }- }- case Bundle.INSTALLED:- case Bundle.RESOLVED:- case Bundle.UNINSTALLED:+ static private boolean oneOf(Bundle b, int... bundle_states) {+ Integer s = b.getState();+ return IntStream.of(bundle_states).anyMatch(s::equals);+ }++ static private void waitFor(Bundle b, int... bundle_states) throws InterruptedException {+ while (true) {+ if (oneOf(b, bundle_states)) {+ return;}+ Thread.sleep(500);}- return false;}- public boolean synchronousUninstall(Bundle b) throws InterruptedException, BundleException {- if (b != null) {- if (b.getState() != Bundle.UNINSTALLED) {- b.uninstall();- while (true) {- if (b.getState() == Bundle.UNINSTALLED) {- return true;- }- Thread.sleep(500);- }- }+ public void synchronousStart(Bundle b) throws InterruptedException, GhidraBundleException {+ if (b.getState() == Bundle.ACTIVE) {+ return;}- return false;+ try {+ b.start();+ }+ catch (BundleException e) {+ throw new GhidraBundleException(b, "starting bundle", e);+ }+ waitFor(b, Bundle.ACTIVE);}- public boolean waitForBundleStart(String location)- throws InterruptedException, BundleException {- while (true) {- Bundle b = bc.getBundle(location);- if (b != null) {- switch (b.getState()) {- case Bundle.ACTIVE:- return true;- case Bundle.UNINSTALLED:- case Bundle.STOPPING:- return false;- case Bundle.INSTALLED:- case Bundle.RESOLVED:- b.start();- continue;- case Bundle.STARTING:- }- }- Thread.sleep(500);+ public void synchronousStop(Bundle b) throws InterruptedException, GhidraBundleException {+ if (oneOf(b, Bundle.RESOLVED, Bundle.INSTALLED, Bundle.UNINSTALLED)) {+ return;+ }+ try {+ b.stop();+ }+ catch (BundleException e) {+ throw new GhidraBundleException(b, "stopping bundle", e);+ }+ waitFor(b, Bundle.RESOLVED, Bundle.INSTALLED, Bundle.UNINSTALLED);+ }++ public void synchronousUninstall(Bundle b) throws InterruptedException, GhidraBundleException {+ if (b.getState() == Bundle.UNINSTALLED) {+ return;+ }+ try {+ // stop first??+ b.uninstall();+ }+ catch (BundleException e) {+ throw new GhidraBundleException(b, "unisntalling bundle", e);}+ waitFor(b, Bundle.UNINSTALLED);}- public void stop_felix() {+ void forceStopFelix() {Task t = new Task("killing felix", false, false, true, true) {@Overridepublic void run(TaskMonitor monitor) throws CancelledException {diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/GhidraBundleException.java b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/GhidraBundleException.javanew file mode 100644index 0000000000..3d6b557a9f--- /dev/null+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/GhidraBundleException.java@@ -0,0 +1,33 @@+package ghidra.app.script.osgi;++import org.osgi.framework.Bundle;+import org.osgi.framework.BundleException;++public class GhidraBundleException extends OSGiException {+ private Bundle bundle;+ private String bundle_loc;++ public GhidraBundleException(Bundle bundle, String msg, Throwable cause) {+ super(msg, cause);+ this.bundle = bundle;+ }++ public GhidraBundleException(Bundle bundle, String msg) {+ super(msg);+ this.bundle = bundle;+ }++ public GhidraBundleException(String bundle_loc, String msg, BundleException cause) {+ super(msg, cause);+ this.bundle_loc = bundle_loc;+ }++ public Bundle getBundle() {+ return bundle;+ }++ public String getBundleLocation() {+ return bundle_loc;+ }++}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/OSGiException.java b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/OSGiException.javanew file mode 100644index 0000000000..b1a73d9b8b--- /dev/null+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/OSGiException.java@@ -0,0 +1,13 @@+package ghidra.app.script.osgi;++import ghidra.util.exception.UsrException;++public class OSGiException extends UsrException {+ public OSGiException(String msg, Throwable cause) {+ super(msg, cause);+ }++ public OSGiException(String msg) {+ super(msg);+ }+}