Skip to content

Ghidra is a software reverse engineering (SRE) framework

isolate script directories, add @imports tag

Jason P. Leasuref864fbdc5009
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 4756c23505..ec79b190a5 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
@@ -19,7 +19,6 @@ import java.io.*;
import java.util.*;
import org.apache.commons.collections4.map.LazyMap;
-import org.apache.commons.lang3.StringUtils;
import generic.jar.ResourceFile;
import generic.util.Path;
@@ -67,9 +66,9 @@ public class GhidraScriptUtil {
private static List<Path> scriptDirectoryPaths = new ArrayList<>();
- static Map<ResourceFile, ScriptInfo> scriptFileToInfoMap = new HashMap<>();
+ private static Map<ResourceFile, ScriptInfo> scriptFileToInfoMap = new HashMap<>();
- static Map<String, List<ResourceFile>> scriptNameToFilesMap =
+ private static Map<String, List<ResourceFile>> scriptNameToFilesMap =
LazyMap.lazyMap(new HashMap<String, List<ResourceFile>>(), () -> new ArrayList<>());
static {
@@ -334,10 +333,8 @@ public class GhidraScriptUtil {
//
ResourceFile preferredFile = null;
for (ResourceFile file : matchingClassFiles) {
- if (file.getParentFile()
- .getAbsolutePath()
- .equals(
- GhidraScriptUtil.USER_SCRIPTS_BIN_DIR)) {
+ if (file.getParentFile().getAbsolutePath().equals(
+ GhidraScriptUtil.USER_SCRIPTS_BIN_DIR)) {
preferredFile = file;
break;
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/script/JavaScriptClassLoader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/script/JavaScriptClassLoader.java
index e46804e828..b45621f10e 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/script/JavaScriptClassLoader.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/script/JavaScriptClassLoader.java
@@ -23,6 +23,7 @@ import generic.jar.ResourceFile;
import ghidra.util.Msg;
import utilities.util.FileUtilities;
+@Deprecated
public class JavaScriptClassLoader extends ClassLoader {
private Map<File, Long> lastModifiedMap = new HashMap<>();
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 e3c8ac917a..351061f887 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
@@ -26,7 +26,6 @@ import javax.tools.*;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject.Kind;
-import org.apache.felix.fileinstall.internal.JarDirUrlHandler;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
@@ -34,19 +33,34 @@ 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.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
+ BundleHost _bundle_host;
+
+ private BundleHost getBundleHost() {
+ if (_bundle_host == null) {
+ _bundle_host = new BundleHost();
+ try {
+ _bundle_host.start_felix();
+ }
+ catch (BundleException | IOException e) {
+ e.printStackTrace();
+ }
- private BundleHost bundle_host = new BundleHost();
- {
- try {
- bundle_host.start_felix();
}
- catch (BundleException | IOException e) {
- e.printStackTrace();
+ return _bundle_host;
+ }
+
+ private SourceBundleInfo getBundleInfoForScript(ResourceFile sourceFile) {
+ ResourceFile sourceDir = getSourceDirectoryForScript(sourceFile);
+ if (sourceDir == null) {
+ return null;
}
+ return getBundleHost().getSourceBundleInfo(sourceDir);
}
@Override
@@ -75,12 +89,12 @@ public class JavaScriptProvider extends GhidraScriptProvider {
writer = new NullPrintWriter();
}
- ScriptBundleInfo bi = getBundleInfoForScript(sourceFile);
- // look for new source files
+ SourceBundleInfo bi = getBundleInfoForScript(sourceFile);
+ // look for new source files
List<ResourceFile> newSource = new ArrayList<>();
List<Path> oldBin = new ArrayList<>();
- BundleHost.visitUpdatedClassFiles(bi.sourceDir, bi.binDir, (sf, bfs) -> {
+ bi.visitUpdatedClassFiles((sf, bfs) -> {
if (sf != null) {
newSource.add(sf);
}
@@ -89,9 +103,27 @@ public class JavaScriptProvider extends GhidraScriptProvider {
}
});
+ 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;
+ }
+ }
+ if (failing > 0 && newSource.isEmpty()) {
+ 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
+
// there's new source, so uninstall any existing bundle, delete old class files, and recompile
if (!newSource.isEmpty()) {
- writer.printf("%s has changed: %d new\n", bi.sourceDir.toString(), newSource.size());
+ writer.printf("%s has changed: %d new/updated\n", bi.getSourceDir().toString(),
+ newSource.size());
Bundle b = bi.getBundle();
if (b != null) {
try {
@@ -116,27 +148,36 @@ public class JavaScriptProvider extends GhidraScriptProvider {
}
BundleCompiler bc = new BundleCompiler(bundle_host);
- Msg.trace(this, "Compiling script " + sourceFile + " to dir " + bi.binDir);
+ Msg.trace(this,
+ "Compiling bundle dir " + bi.getSourceDir() + " to dir " + bi.getBinDir());
+ long startTime = System.nanoTime();
try {
- bc.compileToExplodedBundle(bi.sourceDir, bi.binDir, writer);
+ bc.compileToExplodedBundle(bi, newSource, writer);
}
catch (IOException e) {
e.printStackTrace();
Msg.error(this, "compiling bundle", e);
return null;
}
+ finally {
+ 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 necessary
+ Bundle b = bi.getBundle();
try {
- Bundle b = bundle_host.installExplodedPath(bi.binDir);
- bi.bundleLoc = b.getLocation();
- Msg.out(String.format("new bundle loc is %s\n", bi.bundleLoc));
- b.start();
- if (!bundle_host.waitForBundleStart(bi.bundleLoc)) {
- Msg.error(this, "starting bundle");
+ if (b == null) {
+ b = bi.install();
+ }
+ if (b.getState() != Bundle.ACTIVE) {
+ b.start();
+ }
+ if (!bundle_host.waitForBundleStart(bi.getBundleLoc())) {
+ Msg.error(this, "unable to start bundle");
return null;
}
}
@@ -146,10 +187,10 @@ public class JavaScriptProvider extends GhidraScriptProvider {
return null;
}
- Bundle b = bi.getBundle();
- Class<?> clazz = b.loadClass(bi.classNameForScript(sourceFile));
+ String classname = bi.classNameForScript(sourceFile);
Object object;
try {
+ Class<?> clazz = b.loadClass(classname); // throws ClassNotFoundException
object = clazz.getDeclaredConstructor().newInstance();
}
catch (IllegalArgumentException | InvocationTargetException | NoSuchMethodException
@@ -158,6 +199,12 @@ public class JavaScriptProvider extends GhidraScriptProvider {
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);
@@ -166,8 +213,8 @@ public class JavaScriptProvider extends GhidraScriptProvider {
String message = "Not a valid Ghidra script: " + sourceFile.getName();
writer.println(message);
- Msg.error(this, message); // the writer may not be the same as Msg, so log it too
- return null; // class is not a script
+ Msg.error(this, message);
+ return null; // class is not GhidraScript
}
/**
@@ -186,51 +233,6 @@ public class JavaScriptProvider extends GhidraScriptProvider {
return file;
}
- private class ScriptBundleInfo {
- final ResourceFile sourceDir;
- final String symbolicName;
- final Path binDir;
- String bundleLoc;
-
- public ScriptBundleInfo(ResourceFile sourceDir) {
- this.sourceDir = sourceDir;
- this.symbolicName = getSymbolicNameFromSourceDir(sourceDir);
- this.binDir = bundle_host.getCompiledBundlesDir().resolve(symbolicName);
-
- this.bundleLoc =
- JarDirUrlHandler.PROTOCOL + ":" + binDir.toAbsolutePath().normalize().toString();
- }
-
- public String classNameForScript(ResourceFile sourceFile) {
- String p;
- try {
- p = sourceFile.getCanonicalPath();
- p = p.substring(1 + sourceDir.getCanonicalPath().length(), p.length() - 5);// relative path less ".java"
- return p.replace(File.separatorChar, '.');
- }
- catch (IOException e) {
- e.printStackTrace();
- return null;
- }
- }
-
- Bundle getBundle() {
- return bundle_host.getBundle(bundleLoc);
- }
- }
-
- private ScriptBundleInfo getBundleInfoForScript(ResourceFile sourceFile) {
- ResourceFile bundleDir = getSourceDirectoryForScript(sourceFile);
- if (bundleDir == null) {
- return null;
- }
- return new ScriptBundleInfo(bundleDir);
- }
-
- static public String getSymbolicNameFromSourceDir(ResourceFile sourceDir) {
- return Integer.toHexString(sourceDir.getAbsolutePath().hashCode());
- }
-
public static ResourceFile getSourceDirectoryForScript(ResourceFile sourceFile) {
String sourcePath = sourceFile.getAbsolutePath();
for (ResourceFile sourceDir : GhidraScriptUtil.getScriptSourceDirectories()) {
@@ -281,6 +283,7 @@ public class JavaScriptProvider extends GhidraScriptProvider {
return "//";
}
+ // XXX everything from here down is deprecated but has dependents
@Deprecated
private JavaScriptClassLoader loader = new JavaScriptClassLoader();
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/script/ScriptInfo.java b/Ghidra/Features/Base/src/main/java/ghidra/app/script/ScriptInfo.java
index b4fa44d1d1..51c2032627 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/script/ScriptInfo.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/script/ScriptInfo.java
@@ -51,6 +51,9 @@ public class ScriptInfo {
public static final String AT_MENUPATH = "@menupath";
public static final String AT_TOOLBAR = "@toolbar";
+ // omit from METADATA to avoid pre-populating in new scripts
+ public static final String AT_IMPORTS = "@imports";
+
public static final String[] METADATA =
{ AT_AUTHOR, AT_CATEGORY, AT_KEYBINDING, AT_MENUPATH, AT_TOOLBAR, };
@@ -68,6 +71,7 @@ public class ScriptInfo {
private String[] menupath = new String[0];
private String toolbar;
private ImageIcon toolbarImage;
+ private String imports;
/**
* Constructs a new script.
@@ -92,6 +96,7 @@ public class ScriptInfo {
menupath = new String[0];
toolbar = null;
toolbarImage = null;
+ imports = null;
keybindingErrorMessage = null;
}
@@ -124,6 +129,7 @@ public class ScriptInfo {
* @return the script author information.
*/
public String getAuthor() {
+ parseHeader();
return author;
}
@@ -271,6 +277,9 @@ public class ScriptInfo {
else if (line.startsWith(AT_TOOLBAR)) {
toolbar = getTagValue(AT_TOOLBAR, line);
}
+ else if (line.startsWith(AT_IMPORTS)) {
+ imports = getTagValue(AT_IMPORTS, line);
+ }
}
catch (Exception e) {
Msg.debug(this, "Unexpected exception reading script metadata " + "line: " + line, e);
@@ -404,7 +413,6 @@ public class ScriptInfo {
* @return the script tool bar icon
*/
public ImageIcon getToolBarImage(boolean scaled) {
-
parseHeader();
if (toolbar == null) {
return null;
@@ -428,11 +436,21 @@ public class ScriptInfo {
return toolbarImage;
}
+ /**
+ * Returns the script imports
+ * @return the script imports
+ */
+ public String getImports() {
+ parseHeader();
+ return imports;
+ }
+
/**
* Returns a string designed to be used as a tool tip for describing this script
* @return a string designed to be used as a tool tip
*/
public String getToolTipText() {
+ parseHeader();
String htmlDescription = "No Description";
if (description != null) {
htmlDescription = escapeHTML(description);
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.java
index d9ffbf6ba9..8387665db9 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
@@ -18,8 +18,7 @@ package ghidra.app.script.osgi;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.*;
-import java.util.ArrayList;
-import java.util.List;
+import java.util.*;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import java.util.stream.Collectors;
@@ -28,12 +27,18 @@ 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.phidias.compile.BundleJavaManager;
import aQute.bnd.osgi.*;
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 {
@@ -46,9 +51,73 @@ 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(ResourceFile srcdir, Path bindir, Writer writer)
- throws IOException {
+ public void compileToExplodedBundle(SourceBundleInfo bi, List<ResourceFile> newSource,
+ PrintWriter writer) throws IOException {
+
+ ResourceFile srcdir = bi.getSourceDir();
+ Path bindir = bi.getBinDir();
+
List<String> options = new ArrayList<>();
options.add("-g");
options.add("-d");
@@ -58,30 +127,33 @@ public class BundleCompiler {
options.add("-classpath");
options.add(System.getProperty("java.class.path") + File.pathSeparator + bindir.toString());
options.add("-proc:none");
- final JavaFileManager fm0 =
- new ResourceFileJavaFileManager(GhidraScriptUtil.getScriptSourceDirectories());
- BundleJavaManager fm = new BundleJavaManager(bh.getHostFramework(), fm0, options);
- final List<ResourceFileJavaFileObject> compilationUnits = new ArrayList<>();
+ // final JavaFileManager rfm = new ResourceFileJavaFileManager(Collections.singletonList(bi.getSourceDir()));
+ final JavaFileManager rfm =
+ new ResourceFileJavaFileManager(Collections.singletonList(bi.getSourceDir()));
- BundleHost.visitUpdatedClassFiles(srcdir, bindir, (sf, bf) -> {
- if (sf != null) {
- compilationUnits.add(
- new ResourceFileJavaFileObject(sf.getParentFile(), sf, Kind.SOURCE));
- }
- });
+ // 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);
+
+ wireAdditionalBundles(newSource, bjm, writer);
+
+ final List<ResourceFileJavaFileObject> compilationUnits = newSource.stream().map(
+ sf -> new ResourceFileJavaFileObject(sf.getParentFile(), sf, Kind.SOURCE)).collect(
+ Collectors.toList());
Path dmf = bindir.resolve("META-INF").resolve("MANIFEST.MF");
if (Files.exists(dmf)) {
Files.delete(dmf);
}
- // try to compile, if we fail remove offenders and try again
+ // try to compile, if we fail, avoid offenders and try again
while (!compilationUnits.isEmpty()) {
DiagnosticCollector<JavaFileObject> diagnostics =
new DiagnosticCollector<JavaFileObject>();
JavaCompiler.CompilationTask task =
- compiler.getTask(writer, fm, diagnostics, options, null, compilationUnits);
+ compiler.getTask(writer, bjm, diagnostics, options, null, compilationUnits);
// task.setProcessors // for annotation processing / code generation
Boolean successfulCompilation = task.call();
@@ -89,11 +161,14 @@ public class BundleCompiler {
break;
}
for (Diagnostic<? extends JavaFileObject> d : diagnostics.getDiagnostics()) {
- writer.write(d.getSource().toString() + ": " + d.getMessage(null) + "\n");
+ String err = d.toString() + "\n";
+ writer.write(err);
ResourceFileJavaFileObject sf = (ResourceFileJavaFileObject) d.getSource();
+ ResourceFile rf = sf.getFile();
+ bi.buildError(rf, err); // remember all errors for this file
if (compilationUnits.remove(sf)) {
- writer.write(String.format("skipping %s\n", sf.toString()));
- ResourceFile rf = sf.getFile();
+ writer.printf("skipping %s\n", sf.toString());
+ // if it's a script, mark it for having compile errors
if (GhidraScriptUtil.contains(rf)) {
ScriptInfo info = GhidraScriptUtil.getScriptInfo(rf);
info.setCompileErrors(true);
@@ -101,7 +176,7 @@ public class BundleCompiler {
}
}
}
- // make sure the succeses are marked
+ // mark the successful compilations
for (ResourceFileJavaFileObject sf : compilationUnits) {
ResourceFile rf = sf.getFile();
if (GhidraScriptUtil.contains(rf)) {
@@ -135,9 +210,10 @@ public class BundleCompiler {
analyzer.addClasspath(bjars.collect(Collectors.toUnmodifiableList()));
analyzer.setProperty("Bundle-SymbolicName",
- JavaScriptProvider.getSymbolicNameFromSourceDir(srcdir));
+ BundleHost.getSymbolicNameFromSourceDir(srcdir));
analyzer.setProperty("Bundle-Version", "1.0");
analyzer.setProperty("Import-Package", "*");
+ analyzer.setProperty("Export-Package", "!*.private.*,!*.internal.*,*");
// analyzer.setBundleActivator(s);
try {
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.java
index caadb9ffa6..8fb9480a0d 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
@@ -39,13 +39,116 @@ import ghidra.framework.Application;
import ghidra.util.exception.CancelledException;
import ghidra.util.task.*;
+// XXX this class should be part of a service/plugin
public class BundleHost {
- void dispose() {
+ static public String getSymbolicNameFromSourceDir(ResourceFile sourceDir) {
+ return Integer.toHexString(sourceDir.getAbsolutePath().hashCode());
+ }
+
+ public void dispose() {
if (felix != null) {
stop_felix();
}
}
+ // XXX this should be remembered in savestate
+ HashMap<ResourceFile, SourceBundleInfo> file2sbi = new HashMap<>();
+
+ public SourceBundleInfo getSourceBundleInfo(ResourceFile sourceDir) {
+ return file2sbi.computeIfAbsent(sourceDir, SourceBundleInfo::new);
+ }
+
+ // XXX consumers should clean up after themselves
+ public void removeSourceBundleInfo(ResourceFile sourceDir) {
+ file2sbi.remove(sourceDir);
+ }
+
+ /**
+ * cache of data corresponding to a source directory that is bound to be an exploded bundle
+ */
+ protected static class BuildFailure {
+ long when = -1;
+ StringBuilder message = new StringBuilder();
+ }
+
+ public class SourceBundleInfo {
+ final private ResourceFile sourceDir;
+ final String symbolicName;
+ final private Path binDir;
+ final private String bundleLoc;
+
+ final HashMap<ResourceFile, BuildFailure> buildErrors = new HashMap<>();
+
+ public SourceBundleInfo(ResourceFile sourceDir) {
+ this.sourceDir = sourceDir;
+ this.symbolicName = getSymbolicNameFromSourceDir(sourceDir);
+ this.binDir = BundleHost.this.getCompiledBundlesDir().resolve(symbolicName);
+
+ this.bundleLoc =
+ "reference:file://" + getBinDir().toAbsolutePath().normalize().toString();
+ }
+
+ 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"
+ return p.replace(File.separatorChar, '.');
+ }
+ catch (IOException e) {
+ e.printStackTrace();
+ return null;
+ }
+ }
+
+ public Bundle getBundle() {
+ return BundleHost.this.getBundle(getBundleLoc());
+ }
+
+ public String getBundleLoc() {
+ return bundleLoc;
+ }
+
+ public ResourceFile getSourceDir() {
+ return sourceDir;
+ }
+
+ public Path getBinDir() {
+ 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());
+ }
+
+ public void buildError(ResourceFile rf, String err) {
+ BuildFailure f = buildErrors.computeIfAbsent(rf, x -> new BuildFailure());
+ f.when = rf.lastModified();
+ f.message.append(err);
+ }
+
+ public String getPreviousBuildErrors() {
+ return buildErrors.values().stream().map(e -> e.message.toString()).collect(
+ Collectors.joining());
+ }
+
+ public boolean updatedSinceLastBuild(ResourceFile rf) {
+ BuildFailure f = buildErrors.get(rf);
+ if (f != null) {
+ if (f.when == rf.lastModified()) {
+ return false;
+ }
+ buildErrors.remove(rf);
+ }
+ return true;
+ }
+
+ }
+
String buildExtraPackages() {
Set<String> packages = new HashSet<>();
getPackagesFromClasspath(packages);
@@ -66,11 +169,6 @@ public class BundleHost {
return bc.installBundle(location, new FileInputStream(new File(path_to_jar)));
}
- public Bundle installExplodedPath(Path p) throws BundleException {
- return bc.installBundle("reference:file://" + p.toAbsolutePath().normalize().toString());
-
- }
-
void dumpLoadedBundles() {
System.err.printf("=== Bundles ===\n");
for (Bundle bundle : bc.getBundles()) {
@@ -353,6 +451,9 @@ public class BundleHost {
while (!stack.isEmpty()) {
ResourceFile sd = stack.pop();
String relpath = sd.getAbsolutePath().substring(srcdir.getAbsolutePath().length());
+ if (relpath.startsWith(File.separator)) {
+ relpath=relpath.substring(1);
+ }
Path bd = bindir.resolve(relpath);
// index the class files in the corresponding directory by basename
@@ -386,9 +487,11 @@ public class BundleHost {
}
}
// any remaining .class files are missing .java files
- new_source_cb.found(null,
- binfiles.values().stream().flatMap(l -> l.stream()).collect(
- Collectors.toList()));
+ if (!binfiles.isEmpty()) {
+ new_source_cb.found(null,
+ binfiles.values().stream().flatMap(l -> l.stream()).collect(
+ Collectors.toList()));
+ }
}
}
catch (Throwable t) {