Ghidra is a software reverse engineering (SRE) framework
add bundlehost tests.. and some fixes
Jason P. Leasureec4cad223722
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.javaindex e26e157425..0f8e66345e 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@@ -55,7 +55,7 @@ public class BundleHost {public void dispose() {if (felix != null) {- forceStopFelix();+ forceStopFramework();}}@@ -301,7 +301,7 @@ public class BundleHost {* @throws OSGiException framework failures* @throws IOException filesystem setup*/- public void startFelix() throws OSGiException, IOException {+ public void startFramework() throws OSGiException, IOException {Properties config = new Properties();@@ -503,20 +503,22 @@ public class BundleHost {}}- void forceStopFelix() {- Task t = new Task("killing felix", false, false, true, true) {+ void forceStopFramework() {+ try {+ felix.stop();+ felix.waitForStop(5000);+ felix = null;+ }+ catch (BundleException | InterruptedException e) {+ e.printStackTrace();+ }+ }++ void forceStopFrameworkTask() {+ Task t = new Task("killing OSGi framework", false, false, true, true) {@Overridepublic void run(TaskMonitor monitor) throws CancelledException {- try {- felix.stop();- System.err.printf("trying to kill felix...\n");- FrameworkEvent x = felix.waitForStop(5000);- System.err.printf("killed felix with %s", x.toString());- felix = null;- }- catch (BundleException | InterruptedException e) {- System.err.printf("failed to kill felix: %s", e);- }+ forceStopFramework();}};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.javaindex 3aec5b08da..cd32d7b561 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@@ -52,11 +52,15 @@ public abstract class GhidraBundle {* @return true if build happened, false if already built* @throws Exception sorry, wasn't possible*/- abstract boolean build(PrintWriter writer) throws Exception;+ public abstract boolean build(PrintWriter writer) throws Exception;- abstract String getSummary();+ public boolean build() throws Exception {+ return build(new PrintWriter(System.err));+ }++ public abstract String getSummary();- abstract String getBundleLoc();+ public abstract String getBundleLoc();abstract List<BundleRequirement> getAllReqs();@@ -108,7 +112,13 @@ public abstract class GhidraBundle {return bundleHost.getBundle(getBundleLoc());}- public Bundle install() throws GhidraBundleException {- return bundleHost.installFromLoc(getBundleLoc());+ public void activate() throws Exception {+ activate(new PrintWriter(System.err));}++ public void activate(PrintWriter writer) throws Exception {+ build(writer);+ bundleHost.activateSynchronously(getBundleLoc());+ }+}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.javaindex f5a4694414..5cc43c936f 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@@ -175,12 +175,12 @@ public class GhidraSourceBundle extends GhidraBundle {}}- private List<BundleRequirement> getComputedReqs() {+ private Map<String, BundleRequirement> getComputedReqs() {Map<String, BundleRequirement> dedupedReqs = new HashMap<>();buildReqs.values().stream().flatMap(List::stream).forEach(r -> dedupedReqs.putIfAbsent(r.toString(), r));- return new ArrayList<>(dedupedReqs.values());+ return dedupedReqs;}@Override@@ -191,7 +191,22 @@ public class GhidraSourceBundle extends GhidraBundle {catch (GhidraBundleException e) {throw new RuntimeException(e);}- return getComputedReqs();+ Map<String, BundleRequirement> reqs = getComputedReqs();+ // insert requirements from a source manifest+ ResourceFile manifest = getSourceManifestPath();+ if (manifest.exists()) {+ try {+ Manifest m = new Manifest(manifest.getInputStream());+ String imports = m.getMainAttributes().getValue("Import-Package");+ for (BundleRequirement r : BundleHost.parseImports(imports)) {+ reqs.putIfAbsent(r.toString(), r);+ }+ }+ catch (IOException | BundleException e) {+ throw new RuntimeException(e);+ }+ }+ return new ArrayList<>(reqs.values());}/**@@ -287,9 +302,12 @@ public class GhidraSourceBundle extends GhidraBundle {return bundleLoc;}+ ResourceFile getSourceManifestPath() {+ return new ResourceFile(getSourceDir(), "META-INF" + File.separator + "MANIFEST.MF");+ }+boolean hasNewManifest() throws IOException {- ResourceFile smf =- new ResourceFile(getSourceDir(), "META-INF" + File.separator + "MANIFEST.MF");+ ResourceFile smf = getSourceManifestPath();Path dmf = getBinDir().resolve("META-INF").resolve("MANIFEST.MF");return smf.exists() && (Files.notExists(dmf) ||@@ -605,7 +623,8 @@ public class GhidraSourceBundle extends GhidraBundle {writer.printf("skipping %s\n", sf.getFile().toString());}else {- throw new IOException("compilation error loop condition for " + sf.getFile().toString());+ throw new IOException(+ "compilation error loop condition for " + sf.getFile().toString());}}@@ -620,10 +639,9 @@ public class GhidraSourceBundle extends GhidraBundle {appendSummary(String.format("%d failing source files", getFailingSourcesCount()));}- ResourceFile smf = new ResourceFile(srcdir, "META-INF" + File.separator + "MANIFEST.MF");+ ResourceFile smf = getSourceManifestPath();if (smf.exists()) {- System.err.printf("Found manifest, not generating one\n");- Files.createFile(dmf);+ Files.createDirectories(dmf.getParent());Files.copy(smf.getInputStream(), dmf, StandardCopyOption.REPLACE_EXISTING);return;}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.javaindex f3797b948a..90eaf1ca53 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@@ -61,7 +61,7 @@ public class GhidraScriptUtil {try {_bundleHost = bundleHost;- _bundleHost.startFelix();+ _bundleHost.startFramework();}catch (OSGiException | IOException e) {e.printStackTrace();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 5ee845bc8d..a6cf13aba0 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@@ -98,12 +98,13 @@ public class JavaScriptProvider extends GhidraScriptProvider {}public Class<?> loadClass(ResourceFile sourceFile, PrintWriter writer) throws Exception {- GhidraSourceBundle bi = getBundleForSource(sourceFile);- bi.build(writer);- Bundle b = bi.install();+ GhidraSourceBundle gb = getBundleForSource(sourceFile);+ gb.build(writer);+ Bundle b = _bundleHost.installFromLoc(gb.getBundleLoc());+_bundleHost.activateSynchronously(b);- String classname = bi.classNameForScript(sourceFile);+ String classname = gb.classNameForScript(sourceFile);Class<?> clazz = b.loadClass(classname); // throws ClassNotFoundExceptionreturn clazz;}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.javanew file mode 100644index 0000000000..cc453e31eb--- /dev/null+++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/script/BundleHostTest.java@@ -0,0 +1,364 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.app.plugin.core.script;++import static org.junit.Assert.*;++import java.io.*;+import java.nio.file.Files;+import java.nio.file.Path;+import java.util.*;+import java.util.regex.Matcher;+import java.util.regex.Pattern;++import org.junit.*;+import org.osgi.framework.Bundle;++import generic.jar.ResourceFile;+import ghidra.app.plugin.core.osgi.*;+import ghidra.test.AbstractGhidraHeadlessIntegrationTest;++public class BundleHostTest extends AbstractGhidraHeadlessIntegrationTest {+ static protected void wipe(Path path) throws IOException {+ if (Files.exists(path)) {+ for (Path p : (Iterable<Path>) Files.walk(path).sorted(+ Comparator.reverseOrder())::iterator) {+ Files.deleteIfExists(p);+ }+ }+ }++ BundleHost bundleHost;++ Set<Path> tmpdirs = new HashSet<>();+ LinkedList<GhidraBundle> gbstack = new LinkedList<>();+ GhidraBundle current_gb;++ protected GhidraBundle pushNewBundle() throws IOException {+ String dir = String.format("sourcebundle%03d", tmpdirs.size());+ Path tmpDir = new File(getTestDirectoryPath(), dir).toPath();+ Files.createDirectories(tmpDir);+ tmpdirs.add(tmpDir);++ ResourceFile rp = new ResourceFile(tmpDir.toFile());+ current_gb = bundleHost.addGhidraBundle(rp, true, false);+ gbstack.push(current_gb);+ return current_gb;+ }++ @Before+ public void setup() throws OSGiException, IOException {+ wipe(BundleHost.getCompiledBundlesDir());++ bundleHost = new BundleHost();+ bundleHost.startFramework();++ pushNewBundle();+ }++ @After+ public void tearDown() throws IOException {+ bundleHost.dispose();+ bundleHost = null;++ for (Path tmpdir : tmpdirs) {+ wipe(tmpdir);+ }+ }++ protected void buildWithExpectations(String expectedCompilerOutput, String expectedSummary)+ throws Exception {+ StringWriter sw = new StringWriter();+ current_gb.build(new PrintWriter(sw));+ sw.flush();++ assertEquals("unexpected output during build", expectedCompilerOutput,+ sw.getBuffer().toString());++ assertEquals("wrong summary", expectedSummary, current_gb.getSummary());+ }++ protected void activate() throws Exception {+ Bundle bundle = bundleHost.installFromLoc(current_gb.getBundleLoc());+ assertNotNull("failed to install bundle", bundle);+ bundle.start();+ }++ protected void buildAndActivate() throws Exception {+ buildWithExpectations("", "");+ activate();+ }++ protected Class<?> loadClass(String classname) throws ClassNotFoundException {+ Class<?> clazz = current_gb.getBundle().loadClass(classname);+ assertNotNull("failed to load class", clazz);+ return clazz;+ }++ protected void addClass(String fullclassname, String body) throws IOException {+ addClass("", fullclassname, body);+ }++ protected void addClass(String imports, String fullclassname, String body) throws IOException {+ addClass("", imports, fullclassname, body);+ }++ protected void addClass(String meta, String imports, String fullclassname, String body)+ throws IOException {+ String simplename;+ Path tmpsource = current_gb.getPath().getFile(false).toPath();++ if (fullclassname.contains(".")) {+ String packagename;++ Pattern classpat = Pattern.compile("^(.*)\\.([^.]*)$");+ Matcher m = classpat.matcher(fullclassname);+ if (!m.matches()) {+ throw new IllegalArgumentException(+ "fullclassname must be of the form \"xxxx.xxxx.Xxxx\"");+ }+ packagename = m.group(1);+ simplename = m.group(2);++ for (String n : packagename.split("\\.")) {+ tmpsource = tmpsource.resolve(n);+ }+ Files.createDirectories(tmpsource);+ tmpsource = tmpsource.resolve(simplename + ".java");++ Files.writeString(tmpsource,+ String.format("%s\npackage %s;\n%s\npublic class %s {\n%s\n}\n", meta, packagename,+ imports, simplename, body));+ }+ else {+ simplename = fullclassname;+ tmpsource = tmpsource.resolve(simplename + ".java");+ Files.writeString(tmpsource, String.format("%s\n%s\npublic class %s {\n%s\n}\n", meta,+ imports, simplename, body));++ }++ }++ protected Object getInstance(String classname) throws Exception {+ Class<?> clazz = loadClass(classname);+ Object o = clazz.getDeclaredConstructor().newInstance();+ assertNotNull("failed to create instance", o);+ return o;+ }++ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */++ @Test+ public void testSimpleBuildAndLoadclass() throws Exception {+ // @formatter:off+ addClass(+ "apackage.AClass",+ "@Override\n" ++ "public String toString() {\n" ++ " return \"yupyup\";\n" ++ "}\n"+ );+ // @formatter:on++ buildAndActivate();++ assertEquals("wrong response from instantiated class", "yupyup",+ getInstance("apackage.AClass").toString());+ }++ @Test+ public void testCompileWhatYouCan() throws Exception {+ // @formatter:off+ addClass(+ "apackage.AClass",+ "@Override\n" ++ "public String toString() {\n" ++ " return \"yupyup\";\n" ++ "}\n"+ );++ addClass(+ "apackage.BClass",+ "@Override\n" ++ "public String toString() {\n" ++ " failing java goes here\n" ++ " return \"yupyup\";\n" ++ "}\n"+ );++ buildWithExpectations(+ "BClass.java:7: error: ';' expected\n" ++ " failing java goes here\n" ++ " ^\n" ++ "BClass.java:7: error: ';' expected\n" ++ " failing java goes here\n" ++ " ^\n" ++ String.format("skipping %s/apackage/BClass.java\n", current_gb.getPath().toString())+ ,+ "1 failing source files"+ );+ // @formatter:on++ activate();++ assertEquals("wrong response from instantiated class", "yupyup",+ getInstance("apackage.AClass").toString());+ }++ @Test+ public void testLibraryInBundle() throws Exception {+ // @formatter:off+ addClass(+ "lib.Library",+ "public static String sup() {\n" ++ " return \"yupyup\";\n" ++ "}\n"+ );+ addClass(+ "import lib.Library;\n",+ "apackage.AClass",+ "@Override\n" ++ "public String toString() {\n" ++ " return \"lib says \" + Library.sup();\n" ++ "}\n"+ );+ // @formatter:on+ buildAndActivate();+ assertEquals("wrong response from instantiated class", "lib says yupyup",+ getInstance("apackage.AClass").toString());+ }++ @Test+ public void testCantLoadLibraryFromOtherBundle() throws Exception {+ // @formatter:off+ addClass(+ "lib.Library",+ "public static String sup() {\n" ++ " return \"yupyup\";\n" ++ "}\n"+ );+ buildAndActivate();+ Class<?> libclass = loadClass("lib.Library");+ assertEquals("wrong response from loaded class", "yupyup",+ libclass.getMethod("sup").invoke(null).toString());+++ pushNewBundle();+ addClass(+ "import lib.Library;\n",+ "apackage.AClass",+ "@Override\n" ++ "public String toString() {\n" ++ " return \"lib says \" + Library.sup();\n" ++ "}\n"+ );++ buildWithExpectations(+ "AClass.java:3: error: package lib does not exist\n" ++ "import lib.Library;\n" ++ " ^\n" ++ "AClass.java:8: error: cannot find symbol\n" ++ " return \"lib says \" + Library.sup();\n" ++ " ^\n" ++ " symbol: variable Library\n" ++ " location: class apackage.AClass\n" ++ String.format("skipping %s/apackage/AClass.java\n", current_gb.getPath().toString())+ ,+ "1 failing source files"+ );+ // @formatter:on+ }++ @Test+ public void testLoadLibraryFromOtherBundleWithImportsTag() throws Exception {+ // @formatter:off+ addClass(+ "lib.Library",+ "public static String sup() {\n" ++ " return \"yupyup\";\n" ++ "}\n"+ );+ buildAndActivate();+ Class<?> libclass = loadClass("lib.Library");+ assertEquals("wrong response from loaded class", "yupyup",+ libclass.getMethod("sup").invoke(null).toString());+++ pushNewBundle();+ // @imports tag is only parsed from classes in default package+ addClass(+ "//@imports lib\n"+ ,+ "import lib.Library;\n"+ ,+ "AClass",+ "@Override\n" ++ "public String toString() {\n" ++ " return \"lib says \" + Library.sup();\n" ++ "}\n"+ );++ buildAndActivate();+ assertEquals("wrong response from instantiated class", "lib says yupyup",+ getInstance("AClass").toString());+ // @formatter:on+ }++ @Test+ public void testLoadLibraryFromOtherBundleWithManifest() throws Exception {+ // @formatter:off+ addClass(+ "lib.Library",+ "public static String sup() {\n" ++ " return \"yupyup\";\n" ++ "}\n"+ );+ buildAndActivate();++ pushNewBundle();+ addClass(+ "import lib.Library;\n",+ "apackage.AClass",+ "@Override\n" ++ "public String toString() {\n" ++ " return \"lib says \" + Library.sup();\n" ++ "}\n"+ );++ Path p = current_gb.getPath().getFile(false).toPath();+ p=p.resolve("META-INF");+ Files.createDirectories(p);+ Path manifest=p.resolve("MANIFEST.MF");++ Files.writeString(manifest,+ "Manifest-Version: 1.0\n" ++ "Bundle-ManifestVersion: 2\n" ++ "Import-Package: lib\n" ++ "Require-Capability: osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=11))\"\n" ++ "Bundle-SymbolicName: ghidratesting.bundleX\n" ++ "Bundle-Version: 1.0\n" ++ "Bundle-Name: bundlex\n"+ );++ buildAndActivate();+ // @formatter:on+ assertEquals("wrong response from instantiated class", "lib says yupyup",+ getInstance("apackage.AClass").toString());++ }++}