Ghidra is a software reverse engineering (SRE) framework
move more logic out of JavaScriptProvider, always use all @imports
Jason P. Leasure41ee548b039b
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 351061f887..5b6bcad790 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@@ -17,14 +17,6 @@ package ghidra.app.script;import java.io.*;import java.lang.reflect.InvocationTargetException;-import java.nio.file.Files;-import java.nio.file.Path;-import java.util.*;-import java.util.stream.Collectors;--import javax.tools.*;-import javax.tools.JavaCompiler.CompilationTask;-import javax.tools.JavaFileObject.Kind;import org.osgi.framework.Bundle;import org.osgi.framework.BundleException;@@ -34,11 +26,10 @@ import generic.jar.ResourceFile;import ghidra.app.script.osgi.BundleCompiler;import ghidra.app.script.osgi.BundleHost;import ghidra.app.script.osgi.BundleHost.SourceBundleInfo;-import ghidra.app.util.headless.HeadlessScript;import ghidra.util.Msg;public class JavaScriptProvider extends GhidraScriptProvider {- // XXX bundle host should be managed by a plugin+ // XXX embedded OSGi should be a serviceBundleHost _bundle_host;private BundleHost getBundleHost() {@@ -91,39 +82,32 @@ public class JavaScriptProvider extends GhidraScriptProvider {SourceBundleInfo bi = getBundleInfoForScript(sourceFile);- // look for new source files- List<ResourceFile> newSource = new ArrayList<>();- List<Path> oldBin = new ArrayList<>();- bi.visitUpdatedClassFiles((sf, bfs) -> {- if (sf != null) {- newSource.add(sf);- }- if (bfs != null) {- oldBin.addAll(bfs);- }- });-- BundleHost bundle_host = getBundleHost();- Iterator<ResourceFile> it = newSource.iterator();- int failing = 0;- while (it.hasNext()) {- ResourceFile sf = it.next();- if (!bi.updatedSinceLastBuild(sf)) {- it.remove();- ++failing;- }+ try {+ bi.udpateFromFilesystem(writer);}- if (failing > 0 && newSource.isEmpty()) {+ 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());}- // XXX if there is a new or updated manifest file, uninstall bundle, copy manifest, and restart bundle+ if (bi.newManifestFile() && newSourcecount == 0) {+ // XXX if there is a new or updated manifest file, uninstall bundle, copy manifest, and restart bundle+ }+ BundleHost bundle_host = getBundleHost();// there's new source, so uninstall any existing bundle, delete old class files, and recompile- if (!newSource.isEmpty()) {+ if (newSourcecount > 0) {writer.printf("%s has changed: %d new/updated\n", bi.getSourceDir().toString(),- newSource.size());+ newSourcecount);++ // if there a bundle is currently active, uninstall itBundle b = bi.getBundle();if (b != null) {try {@@ -135,15 +119,14 @@ public class JavaScriptProvider extends GhidraScriptProvider {return null;}}- bundle_host.stopBundleWatcher();++ // once we've committed to recompile and regenerate generated classes, delete the old stufftry {- for (Path bf : oldBin) {- Files.delete(bf);- }+ bi.deleteOldBinaries();}catch (IOException e) {- e.printStackTrace();- Msg.error(this, "deleting old binary files", e);+ e.printStackTrace(writer);+ Msg.error(this, "deleting old binaries", e);return null;}@@ -153,10 +136,10 @@ public class JavaScriptProvider extends GhidraScriptProvider {long startTime = System.nanoTime();try {- bc.compileToExplodedBundle(bi, newSource, writer);+ bc.compileToExplodedBundle(bi, writer);}catch (IOException e) {- e.printStackTrace();+ e.printStackTrace(writer);Msg.error(this, "compiling bundle", e);return null;}@@ -164,8 +147,6 @@ public class JavaScriptProvider extends GhidraScriptProvider {long endTime = System.nanoTime();writer.printf("%3.2f seconds compile time.\n", (endTime - startTime) / 1e9);}-- bundle_host.startBundleWatcher();}// as much source as possible built, install bundle and start it if necessaryBundle b = bi.getBundle();@@ -284,239 +265,17 @@ public class JavaScriptProvider extends GhidraScriptProvider {}// XXX everything from here down is deprecated but has dependents- @Deprecated- private JavaScriptClassLoader loader = new JavaScriptClassLoader();-- @Deprecated- private void forceClassReload() {- loader = new JavaScriptClassLoader(); // this forces the script class to be reloaded- }@Deprecatedprotected boolean needsCompile(ResourceFile sourceFile, File classFile) {-- // Need to compile if there is no class file.- if (!classFile.exists()) {- return true;- }-- // Need to compile if the script's source file is newer than its corresponding- // class file.- if (sourceFile.lastModified() > classFile.lastModified()) {- return true;- }-- // Need to compile if parent classes are not up to date.- return !areAllParentClassesUpToDate(sourceFile);- }-- @Deprecated- private boolean areAllParentClassesUpToDate(ResourceFile sourceFile) {-- List<Class<?>> parentClasses = getParentClasses(sourceFile);- if (parentClasses == null) {- // some class is missing!- return false;- }-- if (parentClasses.isEmpty()) {- // nothing to do--no parent class to re-compile- return true;- }-- // check each parent for modification- for (Class<?> clazz : parentClasses) {- ResourceFile parentFile = getSourceFile(clazz);- if (parentFile == null) {- continue; // not sure if this can happen (inner-class, maybe?)- }-- // Parent class might have a non-default java package, so use class's full name.- File clazzFile = getClassFile(parentFile, clazz.getName());-- if (parentFile.lastModified() > clazzFile.lastModified()) {- return false;- }- }-return true;}+ @SuppressWarnings("unused")@Deprecatedprotected boolean compile(ResourceFile sourceFile, final PrintWriter writer)throws ClassNotFoundException {-- ScriptInfo info = GhidraScriptUtil.getScriptInfo(sourceFile);- info.setCompileErrors(true);-- if (!doCompile(sourceFile, writer)) {- writer.flush(); // force any error messages out- throw new ClassNotFoundException("Unable to compile class: " + sourceFile.getName());- }-- compileParentClasses(sourceFile, writer);-- forceClassReload();-- info.setCompileErrors(false);- writer.println("Successfully compiled: " + sourceFile.getName());-- return true;- }-- @Deprecated- private boolean doCompile(ResourceFile sourceFile, final PrintWriter writer) {-- JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();- if (javaCompiler == null) {- String message =- "Compile failed: java compiler provider not found (you must be using a JDK " +- "to compile scripts)!";- writer.println(message);- Msg.error(this, message); // the writer may not be the same as Msg, so log it too- return false;- }-- JavaFileManager fileManager =- new ResourceFileJavaFileManager(GhidraScriptUtil.getScriptSourceDirectories());-- List<ResourceFileJavaFileObject> list = new ArrayList<>();- list.add(- new ResourceFileJavaFileObject(sourceFile.getParentFile(), sourceFile, Kind.SOURCE));-- String outputDirectory =- GhidraScriptUtil.getScriptCompileOutputDirectory(sourceFile).getAbsolutePath();- Msg.trace(this, "Compiling script " + sourceFile + " to dir " + outputDirectory);-- List<String> options = new ArrayList<>();- options.add("-g");- options.add("-d");- options.add(outputDirectory);- options.add("-sourcepath");- options.add(getSourcePath());- options.add("-classpath");- options.add(getClassPath());- options.add("-proc:none"); // Prevents warning when script imports something that will get compiled-- CompilationTask task = javaCompiler.getTask(writer, fileManager, null, options, null, list);- return task.call();- }-- @Deprecated- private List<Class<?>> getParentClasses(ResourceFile scriptSourceFile) {-- Class<?> scriptClass = getScriptClass(scriptSourceFile);- if (scriptClass == null) {- return null; // special signal that there was a problem- }-- List<Class<?>> parentClasses = new ArrayList<>();- Class<?> superClass = scriptClass.getSuperclass();- while (superClass != null) {- if (superClass.equals(GhidraScript.class)) {- break; // not interested in the built-in classes- }- else if (superClass.equals(HeadlessScript.class)) {- break; // not interested in the built-in classes- }- parentClasses.add(superClass);- superClass = superClass.getSuperclass();- }- return parentClasses;- }-- @Deprecated- private Class<?> getScriptClass(ResourceFile scriptSourceFile) {- String clazzName = GhidraScriptUtil.getBaseName(scriptSourceFile);- try {- return Class.forName(clazzName, true, new JavaScriptClassLoader());- }- catch (NoClassDefFoundError | ClassNotFoundException e) {- Msg.error(this, "Unable to find class file for script file: " + scriptSourceFile, e);- }- catch (GhidraScriptUnsupportedClassVersionError e) {- // Unusual Code Alert!: This implies the script was compiled in a newer- // version of Java. So, just delete the class file and try again.- ResourceFile classFile = e.getClassFile();- classFile.delete();- return null; // trigger re-compile- }- return null;- }-- @Deprecated- private void compileParentClasses(ResourceFile sourceFile, PrintWriter writer) {-- List<Class<?>> parentClasses = getParentClasses(sourceFile);- if (parentClasses == null) {- // this shouldn't happen, as this method is called after the child class is- // re-compiled and thus, all parent classes should still be there.- return;- }-- if (parentClasses.isEmpty()) {- // nothing to do--no parent class to re-compile- return;- }-- //- // re-compile each class's source file- //-- // first, reverse the order, so that we compile the highest-level classes first,- // and then on down, all the way to the script class- Collections.reverse(parentClasses);-- // next, add back to the list the script that was just compiled, as it may need- // to be re-compiled after the parent classes are re-compiled- Class<?> scriptClass = getScriptClass(sourceFile);- if (scriptClass == null) {- // shouldn't happen- return;- }- parentClasses.add(scriptClass);-- for (Class<?> parentClass : parentClasses) {- ResourceFile parentFile = getSourceFile(parentClass);- if (parentFile == null) {- continue; // not sure if this can happen (inner-class, maybe?)- }-- if (!doCompile(parentFile, writer)) {- Msg.error(this, "Failed to re-compile parent class: " + parentClass);- return;- }- }- }-- @Deprecated- private ResourceFile getSourceFile(Class<?> c) {- // check all script paths for a dir named- String classname = c.getName();- String filename = classname.replace('.', '/') + ".java";-- List<ResourceFile> scriptDirs = GhidraScriptUtil.getScriptSourceDirectories();- for (ResourceFile dir : scriptDirs) {- ResourceFile possibleFile = new ResourceFile(dir, filename);- if (possibleFile.exists()) {- return possibleFile;- }- }-- return null;- }-- @Deprecated- private String getSourcePath() {- return GhidraScriptUtil.getScriptSourceDirectories().stream().map(- f -> f.getAbsolutePath()).collect(Collectors.joining(File.pathSeparator));- }-- @Deprecated- private String getClassPath() {- String scriptBinDirs = GhidraScriptUtil.getScriptBinDirectories().stream().map(- f -> f.getAbsolutePath()).collect(Collectors.joining(File.pathSeparator));- return System.getProperty("java.class.path") + File.pathSeparator + scriptBinDirs;+ return false;}}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 8387665db9..307802349b 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@@ -27,11 +27,9 @@ import java.util.stream.Stream;import javax.tools.*;import javax.tools.JavaFileObject.Kind;-import org.apache.felix.framework.util.manifestparser.ManifestParser;-import org.osgi.framework.Bundle;-import org.osgi.framework.BundleException;import org.osgi.framework.Constants;-import org.osgi.framework.wiring.*;+import org.osgi.framework.wiring.BundleRequirement;+import org.osgi.framework.wiring.BundleWiring;import org.phidias.compile.BundleJavaManager;import aQute.bnd.osgi.*;@@ -43,6 +41,7 @@ import ghidra.util.Msg;public class BundleCompiler {+ public static final String GENERATED_ACTIVATOR_CLASSNAME = "GeneratedActivator";private BundleHost bh;public BundleCompiler(BundleHost bh) {@@ -51,72 +50,15 @@ public class BundleCompiler {JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();- void wireAdditionalBundles(List<ResourceFile> newSource, BundleJavaManager bjm,- PrintWriter writer) throws IOException {- // parse metadata for the scripts we're compiling- List<ScriptInfo> infos = newSource.stream().filter(GhidraScriptUtil::contains).map(- GhidraScriptUtil::getScriptInfo).collect(Collectors.toList());-- // concatenate all imports into a single "Import-Package" string- String package_imports = infos.stream().map(ScriptInfo::getImports).filter(- s -> s != null && !s.isEmpty()).collect(Collectors.joining(","));-- if (package_imports == null || package_imports.isEmpty()) {- return;- }-- // parse it with Felix's ManifestParser to a list of BundleRequirement objects- Map<String, Object> headerMap = new HashMap<>();- headerMap.put(Constants.IMPORT_PACKAGE, package_imports);- ManifestParser mp;- try {- mp = new ManifestParser(null, null, null, headerMap);- }- catch (BundleException e) {- throw new IOException("failed to parse imports metadata", e);- }- List<BundleRequirement> reqs = mp.getRequirements();-- // enumerate active bundles, looking for capabilities meeting our requirements- List<BundleWiring> bundleWirings = new ArrayList<>();- for (Bundle b : bh.bc.getBundles()) {- if (b.getState() == Bundle.ACTIVE) {- BundleWiring bw = b.adapt(BundleWiring.class);- boolean keeper = false;- for (BundleCapability cap : bw.getCapabilities(null)) {- Iterator<BundleRequirement> it = reqs.iterator();- while (it.hasNext()) {- BundleRequirement req = it.next();- if (req.matches(cap)) {- it.remove();- keeper = true;- }- }- }- if (keeper) {- bundleWirings.add(bw);- }- }- }-- if (!reqs.isEmpty()) {- writer.printf("%d import requirement%s remain%s:\n", reqs.size(),- reqs.size() > 1 ? "s" : "", reqs.size() > 1 ? "" : "s");- for (BundleRequirement req : reqs) {- writer.printf(" %s\n", req.toString());- }- }-- // finally, add all the wirings we found to bjm- bundleWirings.forEach(bw -> bjm.addBundleWiring(bw));- }-// compile a source directory to an exploded bundle- public void compileToExplodedBundle(SourceBundleInfo bi, List<ResourceFile> newSource,- PrintWriter writer) throws IOException {+ public void compileToExplodedBundle(SourceBundleInfo bi, PrintWriter writer)+ throws IOException {ResourceFile srcdir = bi.getSourceDir();Path bindir = bi.getBinDir();+ Files.createDirectories(bindir);++ List<ResourceFile> newSource = bi.getNewSources();List<String> options = new ArrayList<>();options.add("-g");@@ -132,12 +74,24 @@ public class BundleCompiler {final JavaFileManager rfm =new ResourceFileJavaFileManager(Collections.singletonList(bi.getSourceDir()));- // phidias provides a JavaFileManager for compiling from within a bundle -- making all of the- // bundles dependencies available to the compilation. Here, we are compiling for an as-yet- // non-existant bundle, so we forge the wiring based on metadata.BundleJavaManager bjm = new BundleJavaManager(bh.getHostFramework(), rfm, options);+ // The phidias BundleJavaManager is for compiling from within a bundle -- it makes the+ // bundle dependencies available to the compiler classpath. Here, we are compiling in an as-yet+ // non-existing bundle, so we forge the wiring based on @imports metadata.++ List<BundleRequirement> reqs = bi.getRequirements();+ List<BundleWiring> bundleWirings = bh.resolve(reqs);++ if (!reqs.isEmpty()) {+ writer.printf("%d import requirement%s remain%s after resolution:\n", reqs.size(),+ reqs.size() > 1 ? "s" : "", reqs.size() > 1 ? "" : "s");+ for (BundleRequirement req : reqs) {+ writer.printf(" %s\n", req.toString());+ }+ }- wireAdditionalBundles(newSource, bjm, writer);+ // send the capabilities to phidias+ bundleWirings.forEach(bw -> bjm.addBundleWiring(bw));final List<ResourceFileJavaFileObject> compilationUnits = newSource.stream().map(sf -> new ResourceFileJavaFileObject(sf.getParentFile(), sf, Kind.SOURCE)).collect(@@ -203,7 +157,7 @@ public class BundleCompiler {return new Jar(f.toFile());}catch (IOException e1) {- e1.printStackTrace();+ e1.printStackTrace(writer);return null;}});@@ -229,14 +183,19 @@ public class BundleCompiler {}}if (activator_classname == null) {- activator_classname = "GeneratedActivator";+ activator_classname = GENERATED_ACTIVATOR_CLASSNAME;if (!createActivator(bindir, activator_classname, writer)) {Msg.error(this, "failed to create activator");return;}// since we add the activator after bndtools built the imports, we should add its imports tooString imps = ma.getValue(Constants.IMPORT_PACKAGE);- ma.putValue(Constants.IMPORT_PACKAGE, imps + ",ghidra.app.script.osgi");+ if (imps == null) {+ ma.putValue(Constants.IMPORT_PACKAGE, "ghidra.app.script.osgi");+ }+ else {+ ma.putValue(Constants.IMPORT_PACKAGE, imps + ",ghidra.app.script.osgi");+ }}ma.putValue(Constants.BUNDLE_ACTIVATOR, activator_classname);@@ -247,31 +206,32 @@ public class BundleCompiler {}}catch (Exception e) {- e.printStackTrace();+ e.printStackTrace(writer);}finally {analyzer.close();}}- private boolean createActivator(Path bindir, String activator_classname, Writer output)+ private boolean createActivator(Path bindir, String activator_classname, Writer writer)throws IOException {Path activator_dest = bindir.resolve(activator_classname + ".java");- try (PrintWriter writer =+ try (PrintWriter out =new PrintWriter(Files.newBufferedWriter(activator_dest, Charset.forName("UTF-8")))) {- writer.println("import ghidra.app.script.osgi.GhidraBundleActivator;");- writer.println("import org.osgi.framework.BundleActivator;");- writer.println("import org.osgi.framework.BundleContext;");- writer.println("public class GeneratedActivator extends GhidraBundleActivator {");- writer.println(" protected void start(BundleContext bc, Object api) {");- writer.println(" // TODO: stuff to do on bundle start");- writer.println(" }");- writer.println(" protected void stop(BundleContext bc, Object api) {");- writer.println(" // TODO: stuff to do on bundle stop");- writer.println(" }");- writer.println();- writer.println("}");+ out.println("import ghidra.app.script.osgi.GhidraBundleActivator;");+ out.println("import org.osgi.framework.BundleActivator;");+ out.println("import org.osgi.framework.BundleContext;");+ out.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("}");}catch (IOException ex) {ex.printStackTrace();@@ -288,16 +248,16 @@ public class BundleCompiler {options.add(System.getProperty("java.class.path"));options.add("-proc:none");- StandardJavaFileManager fm0 = compiler.getStandardFileManager(null, null, null);- BundleJavaManager fm = new BundleJavaManager(bh.getHostFramework(), fm0, options);+ StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);+ BundleJavaManager bjm = new BundleJavaManager(bh.getHostFramework(), fm, options);Iterable<? extends JavaFileObject> compilationUnits2 =- fm0.getJavaFileObjectsFromPaths(List.of(activator_dest));+ fm.getJavaFileObjectsFromPaths(List.of(activator_dest));DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();JavaCompiler.CompilationTask task2 =- compiler.getTask(output, fm, diagnostics, options, null, compilationUnits2);+ compiler.getTask(writer, bjm, diagnostics, options, null, compilationUnits2);if (!task2.call()) {for (Diagnostic<? extends JavaFileObject> d : diagnostics.getDiagnostics()) {- output.write(d.getSource().toString() + ": " + d.getMessage(null) + "\n");+ writer.write(d.getSource().toString() + ": " + d.getMessage(null) + "\n");}return false;}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 8fb9480a0d..cf5ed36ce7 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@@ -29,13 +29,18 @@ import java.util.stream.Stream;import org.apache.felix.framework.FrameworkFactory;import org.apache.felix.framework.util.FelixConstants;+import org.apache.felix.framework.util.manifestparser.ManifestParser;import org.apache.felix.main.AutoProcessor;import org.osgi.framework.*;import org.osgi.framework.launch.Framework;+import org.osgi.framework.wiring.*;import org.osgi.service.log.*;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.*;@@ -63,6 +68,23 @@ public class BundleHost {file2sbi.remove(sourceDir);}+ /**+ * 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 failed parse+ */+ 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();+ }+/*** cache of data corresponding to a source directory that is bound to be an exploded bundle*/@@ -77,8 +99,13 @@ public class BundleHost {final private Path binDir;final private String bundleLoc;+ //// information indexed by source file++ // XXX add separate missing requirements trackingfinal HashMap<ResourceFile, BuildFailure> buildErrors = new HashMap<>();+ // cached values parsed form @imports tags on default-package source files+public SourceBundleInfo(ResourceFile sourceDir) {this.sourceDir = sourceDir;this.symbolicName = getSymbolicNameFromSourceDir(sourceDir);@@ -86,6 +113,7 @@ public class BundleHost {this.bundleLoc ="reference:file://" + getBinDir().toAbsolutePath().normalize().toString();+}public String classNameForScript(ResourceFile sourceFile) {@@ -117,10 +145,6 @@ public class BundleHost {return binDir;}- public void visitUpdatedClassFiles(NewSourceCallback new_source_cb) {- BundleHost.visitUpdatedClassFiles(getSourceDir(), getBinDir(), new_source_cb);- }-public Bundle install() throws BundleException {return BundleHost.this.bc.installBundle(getBundleLoc());}@@ -136,15 +160,118 @@ public class BundleHost {Collectors.joining());}- public boolean updatedSinceLastBuild(ResourceFile rf) {+ /**+ * check for build errors from last time+ * @param rf file to test+ * @return true if this file had errors and hasn't changed+ */+ private boolean syncBuildErrors(ResourceFile rf) {BuildFailure f = buildErrors.get(rf);if (f != null) {if (f.when == rf.lastModified()) {- return false;+ return true;}buildErrors.remove(rf);}- return true;+ return false;+ }++ public List<BundleRequirement> getRequirements() {+ return foundRequirements;+ }++ final List<ResourceFile> newSources = new ArrayList<>();+ List<Path> oldBin = new ArrayList<>();++ boolean foundNewManifest;+ private List<BundleRequirement> foundRequirements;++ private void computeRequirements() throws BundleException {+ foundRequirements = null;+ Map<String, BundleRequirement> dedupedreqs = new HashMap<>();+ // parse metadata from all Java source in sourceDir+ for (ResourceFile rf : sourceDir.listFiles()) {+ if (rf.getName().endsWith(".java")) {+ // NB: ScriptInfo will update field values if lastModified has changed since last time they were computed+ ScriptInfo si = GhidraScriptUtil.getScriptInfo(rf);+ String imps = si.getImports();+ if (imps != null && !imps.isEmpty()) {+ for (BundleRequirement req : BundleHost.parseImports(imps)) {+ dedupedreqs.put(req.toString(), req);+ }+ }+ }+ }+ foundRequirements = new ArrayList<>(dedupedreqs.values());+ }++ /**+ * look for new sources, metadata, manifest file.+ *+ * @param writer for reporting status to user+ * @throws IOException when there are unexpected issues w/ the filesystem+ */+ public void udpateFromFilesystem(PrintWriter writer) throws IOException {++ // look for new source files+ newSources.clear();+ oldBin.clear();+ ResourceFile smf =+ new ResourceFile(getSourceDir(), "META-INF" + File.separator + "MANIFEST.MF");+ Path dmf = getBinDir().resolve("META-INF").resolve("MANIFEST.MF");++ foundNewManifest = smf.exists() && (Files.notExists(dmf) ||+ smf.lastModified() > Files.getLastModifiedTime(dmf).toMillis());++ BundleHost.visitDiscrepencies(getSourceDir(), getBinDir(), (sf, bfs) -> {+ if (sf != null) {+ newSources.add(sf);+ }+ if (bfs != null) {+ oldBin.addAll(bfs);+ }+ });++ try {+ computeRequirements();+ }+ catch (BundleException e) {+ Msg.error(this, "computing requirements", e);+ e.printStackTrace(writer);+ return;+ }++ // remove source files that failed last time and haven't changed+ Iterator<ResourceFile> it = newSources.iterator();+ while (it.hasNext()) {+ ResourceFile sf = it.next();+ if (syncBuildErrors(sf)) {+ it.remove();+ }+ }+ }++ public void deleteOldBinaries() throws IOException {+ for (Path bf : oldBin) {+ Files.delete(bf);+ }+ // oldBin.clear();+ }++ public int getFailingSourcesCount() {+ return buildErrors.size();+ }++ public int getNewSourcesCount() {+ return newSources.size();+ }++ public List<ResourceFile> getNewSources() {+ return newSources;+ }++ public boolean newManifestFile() {+ return foundNewManifest;}}@@ -177,6 +304,37 @@ public class BundleHost {}}+ /**+ * Attempt to resolve a list of BundleRequirements with active Bundle capabilities.+ *+ * @param reqs list of requirements -- satisfied requirements are removed as capabiliites are found+ * @return the list of BundeWiring objects correpsonding to matching capabilities+ */+ 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);+ boolean keeper = false;+ for (BundleCapability cap : bw.getCapabilities(null)) {+ Iterator<BundleRequirement> it = reqs.iterator();+ while (it.hasNext()) {+ BundleRequirement req = it.next();+ if (req.matches(cap)) {+ it.remove();+ keeper = true;+ }+ }+ }+ if (keeper) {+ bundleWirings.add(bw);+ }+ }+ }+ return bundleWirings;+ }+class FelixLogger extends org.apache.felix.framework.Logger {@Overrideprotected void doLog(int level, String msg, Throwable throwable) {@@ -442,7 +600,7 @@ public class BundleHost {void found(ResourceFile source_file, Collection<Path> class_files) throws Throwable;}- public static void visitUpdatedClassFiles(ResourceFile srcdir, Path bindir,+ public static void visitDiscrepencies(ResourceFile srcdir, Path bindir,NewSourceCallback new_source_cb) {try {// delete class files for which java is either newer, or no longer exists@@ -452,7 +610,7 @@ public class BundleHost {ResourceFile sd = stack.pop();String relpath = sd.getAbsolutePath().substring(srcdir.getAbsolutePath().length());if (relpath.startsWith(File.separator)) {- relpath=relpath.substring(1);+ relpath = relpath.substring(1);}Path bd = bindir.resolve(relpath);