Ghidra is a software reverse engineering (SRE) framework
initial commit of OSGI GhidraScripts
Jason P. Leasure34a030173cb8
diff --git a/Ghidra/Features/Base/Module.manifest b/Ghidra/Features/Base/Module.manifestindex 8b13789179..f4e69ef355 100644--- a/Ghidra/Features/Base/Module.manifest+++ b/Ghidra/Features/Base/Module.manifest@@ -1 +1,7 @@-+MODULE FILE LICENSE: lib/biz.aQute.bnd-4.3.0.jar Apache License 2.0+MODULE FILE LICENSE: lib/org.apache.felix.main-6.0.3.jar Apache License 2.0+MODULE FILE LICENSE: lib/org.apache.felix.fileinstall-3.6.4.jar Apache License 2.0+MODULE FILE LICENSE: lib/org.apache.felix.framework-6.0.3.jar Apache License 2.0+MODULE FILE LICENSE: lib/animal-sniffer-annotations-1.9.jar MIT+MODULE FILE LICENSE: lib/org.osgi.core-5.0.0.jar Apache License 2.0+MODULE FILE LICENSE: lib/phidias-0.3.7.jar Apache License 2.0diff --git a/Ghidra/Features/Base/build.gradle b/Ghidra/Features/Base/build.gradleindex da72748bd1..d48e006283 100644--- a/Ghidra/Features/Base/build.gradle+++ b/Ghidra/Features/Base/build.gradle@@ -25,6 +25,12 @@ dependencies {compile project(':SoftwareModeling')compile project(':DB')compile project(':Help')++ compile 'org.apache.felix:org.apache.felix.framework:6.0.3'+ compile 'org.apache.felix:org.apache.felix.main:6.0.3'+ compile 'org.apache.felix:org.apache.felix.fileinstall:3.6.4'+ compile 'com.github.rotty3000:phidias:0.3.7'+ compile 'biz.aQute.bnd:biz.aQute.bnd:4.3.0'compileOnly "junit:junit:4.12"diff --git a/Ghidra/Features/Base/certification.manifest b/Ghidra/Features/Base/certification.manifestindex 219f7fc8ff..366a02322b 100644--- a/Ghidra/Features/Base/certification.manifest+++ b/Ghidra/Features/Base/certification.manifest@@ -1,5 +1,7 @@##VERSION: 2.0##MODULE IP: BSD+##MODULE IP: MIT+##MODULE IP: Apache License 2.0##MODULE IP: Copyright Distribution Permitted##MODULE IP: FAMFAMFAM Icons - CC 2.5##MODULE IP: LGPL 2.1diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptActionManager.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptActionManager.javaindex f509eb1219..6c96879a62 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptActionManager.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptActionManager.java@@ -73,7 +73,7 @@ class GhidraScriptActionManager {}void dispose() {- actionMap.values().forEach(a -> a.dispose());+ actionMap.values().forEach(ScriptAction::dispose);actionMap.clear();}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 257f7443bb..4756c23505 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@@ -51,11 +51,10 @@ public class GhidraScriptUtil {*///@formatter:offpublic static String USER_SCRIPTS_BIN_DIR =- StringUtils.joinWith(File.separator,- Application.getUserSettingsDirectory(),- "dev",- SCRIPTS_SUBDIR_NAME,- BIN_DIR_NAME);+ Application.getUserSettingsDirectory() + File.separator ++ "dev" + File.separator ++ SCRIPTS_SUBDIR_NAME + File.separator ++ BIN_DIR_NAME;//@formatter:onprivate static void createUserScriptsDirs() {@@ -95,7 +94,7 @@ public class GhidraScriptUtil {root = override;}- String sourcePath = StringUtils.joinWith(File.separator, root, SCRIPTS_SUBDIR_NAME);+ String sourcePath = root + File.separator + SCRIPTS_SUBDIR_NAME;return sourcePath;}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 3a634ac844..ff00d5a023 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@@ -16,6 +16,9 @@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;@@ -23,13 +26,29 @@ 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;+import generic.io.NullPrintWriter;import generic.jar.ResourceFile;+import ghidra.app.script.osgi.BundleCompiler;+import ghidra.app.script.osgi.BundleHost;import ghidra.app.util.headless.HeadlessScript;import ghidra.util.Msg;public class JavaScriptProvider extends GhidraScriptProvider {+ private BundleHost bundle_host = new BundleHost();+ {+ try {+ bundle_host.start_felix();+ }+ catch (BundleException | IOException e) {+ e.printStackTrace();+ }+ }+private JavaScriptClassLoader loader = new JavaScriptClassLoader();@Override@@ -58,30 +77,78 @@ public class JavaScriptProvider extends GhidraScriptProvider {writer = new NullPrintWriter();}- // Assuming script is in default java package, so using script's base name as class name.- File clazzFile = getClassFile(sourceFile, GhidraScriptUtil.getBaseName(sourceFile));- if (needsCompile(sourceFile, clazzFile)) {- compile(sourceFile, writer); // may throw an exception- }- else if (scriptCompiledExternally(clazzFile)) {- forceClassReload();- }+ ScriptBundleInfo bi = getBundleInfoForScript(sourceFile);+ // look for new source files- String clazzName = GhidraScriptUtil.getBaseName(sourceFile);+ List<ResourceFile> newSource = new ArrayList<>();+ List<Path> oldBin = new ArrayList<>();+ BundleHost.visitUpdatedClassFiles(bi.sourceDir, bi.binDir, (sf, bf) -> {+ if (sf != null) {+ newSource.add(sf);+ }+ if (bf != null) {+ oldBin.add(bf);+ }+ });++ // there's new source, so uninstall any existing bundle, delete old class files, and recompile+ if (!newSource.isEmpty()) {+ Bundle b = bi.getBundle();+ if (b != null) {+ try {+ bundle_host.synchronousUninstall(b);+ }+ catch (BundleException | InterruptedException e) {+ e.printStackTrace();+ }+ }+ bundle_host.stopBundleWatcher();+ try {+ for (Path bf : oldBin) {+ Files.delete(bf);+ }+ }+ catch (IOException e) {+ e.printStackTrace();+ return null;+ }++ BundleCompiler bc = new BundleCompiler(bundle_host);+ Msg.trace(this, "Compiling script " + sourceFile + " to dir " + bi.binDir);++ try {+ bc.compileToExplodedBundle(bi.sourceDir, bi.binDir, writer);+ }+ catch (IOException e) {+ e.printStackTrace();+ return null;+ }++ bundle_host.startBundleWatcher();+ }- Class<?> clazz = null;+ // wait for bundle to be startedtry {- clazz = Class.forName(clazzName, true, loader);+ if (!bundle_host.waitForBundleStart(bi.bundleLoc)) {+ return null;+ }}- 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 getScriptInstance(sourceFile, writer);+ catch (InterruptedException | BundleException e1) {+ e1.printStackTrace();+ return null;}- Object object = clazz.newInstance();+ Bundle b = bi.getBundle();+ Class<?> clazz = b.loadClass(bi.classNameForScript(sourceFile));+ Object object;+ try {+ object = clazz.getDeclaredConstructor().newInstance();+ }+ catch (IllegalArgumentException | InvocationTargetException | NoSuchMethodException+ | SecurityException e) {+ e.printStackTrace();+ return null;+ }if (object instanceof GhidraScript) {GhidraScript script = (GhidraScript) object;script.setSourceFile(sourceFile);@@ -99,13 +166,12 @@ public class JavaScriptProvider extends GhidraScriptProvider {}/**- * Gets the class file corresponding to the given source file and class name.- * If the class is in a package, the class name should include the full- * package name.+ * Gets the class file corresponding to the given source file and class name. If the class is in a package, the+ * class name should include the full package name.** @param sourceFile The class's source file.- * @param className The class's name (including package if applicable).- * @return The class file corresponding to the given source file and class name.+ * @param className The class's name (including package if applicable).+ * @return The class file corresponding to the given source file and class name.*/protected File getClassFile(ResourceFile sourceFile, String className) {ResourceFile resourceFile =@@ -122,7 +188,8 @@ public class JavaScriptProvider extends GhidraScriptProvider {return true;}- // Need to compile if the script's source file is newer than its corresponding class file.+ // Need to compile if the script's source file is newer than its corresponding+ // class file.if (sourceFile.lastModified() > classFile.lastModified()) {return true;}@@ -177,6 +244,61 @@ public class JavaScriptProvider extends GhidraScriptProvider {return true;}+ private class ScriptBundleInfo {+ final ResourceFile sourceDir;+ final String symbolicName;+ final Path binDir;+ final 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()) {+ if (sourcePath.startsWith(sourceDir.getAbsolutePath())) {+ return sourceDir;+ }+ }+ return null;+ }+protected boolean compile(ResourceFile sourceFile, final PrintWriter writer)throws ClassNotFoundException {@@ -267,7 +389,7 @@ public class JavaScriptProvider extends GhidraScriptProvider {}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.+ // version of Java. So, just delete the class file and try again.ResourceFile classFile = e.getClassFile();classFile.delete();return null; // trigger re-compile@@ -336,17 +458,13 @@ public class JavaScriptProvider extends GhidraScriptProvider {}private String getSourcePath() {- return GhidraScriptUtil.getScriptSourceDirectories()- .stream()- .map(f -> f.getAbsolutePath())- .collect(Collectors.joining(File.pathSeparator));+ return GhidraScriptUtil.getScriptSourceDirectories().stream().map(+ f -> f.getAbsolutePath()).collect(Collectors.joining(File.pathSeparator));}private String getClassPath() {- String scriptBinDirs = GhidraScriptUtil.getScriptBinDirectories()- .stream()- .map(f -> f.getAbsolutePath())- .collect(Collectors.joining(File.pathSeparator));+ String scriptBinDirs = GhidraScriptUtil.getScriptBinDirectories().stream().map(+ f -> f.getAbsolutePath()).collect(Collectors.joining(File.pathSeparator));return System.getProperty("java.class.path") + File.pathSeparator + scriptBinDirs;}@@ -389,4 +507,5 @@ public class JavaScriptProvider extends GhidraScriptProvider {public String getCommentCharacter() {return "//";}+}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.javanew file mode 100644index 0000000000..e475eed794--- /dev/null+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/BundleCompiler.java@@ -0,0 +1,204 @@+/* ###+ * 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.script.osgi;++import java.io.File;+import java.io.IOException;+import java.io.OutputStream;+import java.io.PrintWriter;+import java.io.Writer;+import java.nio.charset.Charset;+import java.nio.file.Files;+import java.nio.file.Path;+import java.nio.file.StandardCopyOption;+import java.util.ArrayList;+import java.util.List;+import java.util.jar.Attributes;+import java.util.jar.Manifest;+import java.util.stream.Collectors;+import java.util.stream.Stream;++import javax.tools.Diagnostic;+import javax.tools.DiagnosticCollector;+import javax.tools.JavaCompiler;+import javax.tools.JavaFileManager;+import javax.tools.JavaFileObject;+import javax.tools.JavaFileObject.Kind;+import javax.tools.StandardJavaFileManager;+import javax.tools.ToolProvider;++import org.phidias.compile.BundleJavaManager;++import aQute.bnd.osgi.Analyzer;+import aQute.bnd.osgi.Clazz;+import aQute.bnd.osgi.Clazz.QUERY;+import aQute.bnd.osgi.Constants;+import aQute.bnd.osgi.Instruction;+import aQute.bnd.osgi.Jar;+import generic.jar.ResourceFile;+import ghidra.app.script.GhidraScriptUtil;+import ghidra.app.script.JavaScriptProvider;+import ghidra.app.script.ResourceFileJavaFileManager;+import ghidra.app.script.ResourceFileJavaFileObject;++public class BundleCompiler {++ private BundleHost bh;++ public BundleCompiler(BundleHost bh) {+ this.bh = bh;+ }++ /** compile a source directory to an exploded bundle */+ public void compileToExplodedBundle(ResourceFile srcdir, Path bindir, Writer output) throws IOException {+ JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();+ List<String> options = new ArrayList<>();+ options.add("-g");+ options.add("-d");+ options.add(bindir.toString());+ options.add("-sourcepath");+ options.add(srcdir.toString());+ 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);+ DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();++ final List<ResourceFileJavaFileObject> compilationUnits = new ArrayList<>();++ BundleHost.visitUpdatedClassFiles(srcdir, bindir, (sf, bf) -> {+ if (sf != null)+ compilationUnits.add(new ResourceFileJavaFileObject(sf.getParentFile(), sf, Kind.SOURCE));+ if (bf != null)+ Files.delete(bf);+ });++ Path dmf = bindir.resolve("META-INF").resolve("MANIFEST.MF");+ if (Files.exists(dmf)) {+ Files.delete(dmf);+ }++ JavaCompiler.CompilationTask task = compiler.getTask(output, fm, diagnostics, options, null, compilationUnits);+ // task.setProcessors // for annotation processing / code generation++ Boolean successfulCompilation = task.call();+ output.flush();+ System.err.printf("%s: %s\n", successfulCompilation ? "Success" : "Fail", output);++ if (successfulCompilation) {+ ResourceFile smf = new ResourceFile(srcdir, "META-INF" + File.separator + "MANIFEST.MF");+ if (smf.exists()) {+ System.err.printf("Found manifest, not generating one\n");+ Files.createFile(dmf);+ Files.copy(smf.getInputStream(), dmf, StandardCopyOption.REPLACE_EXISTING);+ return;+ }++ // no manifest, so create one with bndtools+ Analyzer analyzer = new Analyzer();+ analyzer.setJar(new Jar(bindir.toFile())); // give bnd the contents+ Stream<Object> bjars = Files.list(bh.getCompiledBundlesDir()).filter(f -> f.toString().endsWith(".jar"))+ .map(f -> {+ try {+ return new Jar(f.toFile());+ } catch (IOException e1) {+ e1.printStackTrace();+ return null;+ }+ });++ analyzer.addClasspath(bjars.collect(Collectors.toUnmodifiableList()));+ analyzer.setProperty("Bundle-SymbolicName", JavaScriptProvider.getSymbolicNameFromSourceDir(srcdir));+ analyzer.setProperty("Bundle-Version", "1.0");+ analyzer.setProperty("Import-Package", "*");+ // analyzer.setBundleActivator(s);++ try {+ Manifest manifest = analyzer.calcManifest();+ 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();+ }+ }+ if (activator_classname == null) {+ Path activator_dest = bindir.resolve("GeneratedActivator.java");+ try (PrintWriter writer = 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("}");+ } catch (IOException ex) {+ ex.printStackTrace();+ return;+ }+ activator_classname = "GeneratedActivator";++ options.clear();+ options.add("-g");+ options.add("-d");+ options.add(bindir.toString());+ options.add("-sourcepath");+ options.add(bindir.toString());+ options.add("-classpath");+ options.add(System.getProperty("java.class.path"));+ options.add("-proc:none");++ StandardJavaFileManager fm02 = compiler.getStandardFileManager(null, null, null);+ fm = new BundleJavaManager(bh.getHostFramework(), fm02, options);+ Iterable<? extends JavaFileObject> compilationUnits2 = fm02+ .getJavaFileObjectsFromPaths(List.of(activator_dest));++ JavaCompiler.CompilationTask task2 = compiler.getTask(output, fm, diagnostics, options, null,+ compilationUnits2);+ if (!task2.call())+ return;+ // since we add the activator after bndtools built the imports, we should add its imports too+ String imps = ma.getValue(Constants.IMPORT_PACKAGE);+ ma.putValue(Constants.IMPORT_PACKAGE, imps + ",ghidra.app.script.osgi");+ }+ ma.putValue(Constants.BUNDLE_ACTIVATOR, activator_classname);++ Files.createDirectories(dmf.getParent());+ try (OutputStream out = Files.newOutputStream(dmf)) {+ manifest.write(out);+ }+ } catch (Exception e) {+ e.printStackTrace();+ }+ analyzer.close();+ } else {+ for (Diagnostic<? extends JavaFileObject> dm : diagnostics.getDiagnostics()) {+ System.err.printf("COMPILE ERROR: %s\n", dm);+ }+ }+ }++}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.javanew file mode 100644index 0000000000..b265141e7b--- /dev/null+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/BundleHost.java@@ -0,0 +1,435 @@+/* ###+ * 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.script.osgi;++import java.io.File;+import java.io.FileInputStream;+import java.io.FileNotFoundException;+import java.io.IOException;+import java.net.URL;+import java.nio.file.Files;+import java.nio.file.Path;+import java.nio.file.Paths;+import java.util.ArrayDeque;+import java.util.Collections;+import java.util.Deque;+import java.util.Map;+import java.util.Properties;+import java.util.function.Function;+import java.util.regex.Matcher;+import java.util.regex.Pattern;+import java.util.stream.Collectors;++import org.apache.felix.fileinstall.internal.FileInstall;+import org.apache.felix.framework.FrameworkFactory;+import org.apache.felix.framework.util.FelixConstants;+import org.apache.felix.main.AutoProcessor;+import org.osgi.framework.Bundle;+import org.osgi.framework.BundleContext;+import org.osgi.framework.BundleEvent;+import org.osgi.framework.BundleException;+import org.osgi.framework.BundleListener;+import org.osgi.framework.Constants;+import org.osgi.framework.FrameworkEvent;+import org.osgi.framework.FrameworkListener;+import org.osgi.framework.ServiceEvent;+import org.osgi.framework.ServiceListener;+import org.osgi.framework.ServiceReference;+import org.osgi.framework.launch.Framework;+import org.osgi.service.log.LogEntry;+import org.osgi.service.log.LogListener;+import org.osgi.service.log.LogReaderService;++import com.google.common.reflect.ClassPath;+import com.google.common.reflect.ClassPath.ClassInfo;++import generic.jar.ResourceFile;+import ghidra.framework.Application;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.Task;+import ghidra.util.task.TaskLauncher;+import ghidra.util.task.TaskMonitor;++public class BundleHost {++ void dispose() {+ if (felix != null)+ stop_felix();+ }++ String buildExtraPackages() {+ try {++ //ClassPath.from(BundleHost.class.getClassLoader()).getTopLevelClasses().stream()+ // .map(ClassInfo::getPackageName).sorted().distinct().forEach(x->{+ // System.err.printf("%s\n", x);+ // });+ return ClassPath.from(BundleHost.class.getClassLoader()).getTopLevelClasses().stream()+ .map(ClassInfo::getPackageName).sorted().distinct().collect(Collectors.joining(","));+ } catch (IOException e1) {+ e1.printStackTrace();+ }+ return null;+ }++ BundleContext bc;+ Framework felix;+ Bundle fileinstall_bundle;++ /** install a bundle from disk */+ Bundle installFromPath(String path_to_jar) throws BundleException {+ Path p = Paths.get(path_to_jar);+ return bc.installBundle("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)));+ }++ void dumpLoadedBundles() {+ System.err.printf("=== Bundles ===\n");+ for (Bundle bundle : bc.getBundles()) {+ System.err.printf("%s: %s: %s: %s\n", bundle.getBundleId(), bundle.getSymbolicName(), bundle.getState(),+ bundle.getVersion());+ }+ }++ class FelixLogger extends org.apache.felix.framework.Logger {+ @Override+ protected void doLog(int level, String msg, Throwable throwable) {+ // plugin.printf("felixlogger: %s %s\n", msg, throwable);+ }++ @Override+ protected void doLogOut(int level, String s, Throwable throwable) {+ // plugin.printf("felixlogger: %s %s\n", s, throwable);+ }++ @SuppressWarnings("rawtypes")+ @Override+ protected void doLog(final Bundle bundle, final ServiceReference sr, final int level, final String msg,+ final Throwable throwable) {+ // plugin.printf("felixlogger: %s %s %s\n", bundle, msg, throwable);+ }++ }++ public void start_felix() throws BundleException, IOException {++ Properties config = new Properties();++ config.setProperty(Constants.FRAMEWORK_BSNVERSION, Constants.FRAMEWORK_BSNVERSION_MULTIPLE);+ config.setProperty(Constants.FRAMEWORK_SYSTEMCAPABILITIES, "osgi.ee; osgi.ee=\"JavaSE\";version:List=\"11\"");+ config.setProperty(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, buildExtraPackages());+ // extra packages have lower precedence than imports, so a Bundle-Import will+ // prevent "living off the land"++ config.setProperty("org.osgi.service.http.port", "8080");++ config.setProperty(Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);+ config.setProperty(Constants.FRAMEWORK_STORAGE, makeCacheDir());++ // more properties available at:+ // http://felix.apache.org/documentation/subprojects/apache-felix-service-component-runtime.html+ config.setProperty("ds.showtrace", "true");+ config.setProperty("ds.showerrors", "true");++ config.setProperty("felix.fileinstall.dir", getWatchedBundleDirs());+ // config.setProperty("felix.fileinstall.log.level", "999");+ // config.setProperty("felix.fileinstall.log.default", "jul"); // stdout+ config.setProperty("felix.fileinstall.bundles.new.start", "true"); // autostart bundles+ config.put(FelixConstants.LOG_LEVEL_PROP, "999");// was 4+ config.put(FelixConstants.LOG_LOGGER_PROP, new FelixLogger());++ FrameworkFactory factory = new FrameworkFactory();+ felix = factory.newFramework(config);++ felix.init();+ bc = felix.getBundleContext();+ AutoProcessor.process(config, bc);++ ServiceReference<LogReaderService> ref = bc.getServiceReference(LogReaderService.class);+ if (ref != null) {+ LogReaderService reader = bc.getService(ref);+ reader.addLogListener(new LogListener() {++ @Override+ public void logged(LogEntry entry) {+ // plugin.printf("%s: %s\n", entry.getBundle(), entry.getMessage());+ }+ });+ } else {+ // plugin.printf("no logreaderservice in felix!\n");+ }++ bc.addFrameworkListener(new FrameworkListener() {++ @Override+ public void frameworkEvent(FrameworkEvent event) {+ System.err.printf("%s %s\n", event.getBundle(), event);+ }+ });++ bc.addServiceListener(new ServiceListener() {+ @Override+ public void serviceChanged(ServiceEvent event) {++ String type = "?";+ if (event.getType() == ServiceEvent.REGISTERED) {+ type = "registered";+ } else if (event.getType() == ServiceEvent.UNREGISTERING) {+ type = "unregistering";+ }++ System.err.printf("%s %s from %s\n", event.getSource(), type,+ event.getServiceReference().getBundle().getLocation());++ }+ });+ bc.addBundleListener(new BundleListener() {++ @Override+ public void bundleChanged(BundleEvent event) {+ // System.err.printf("%s %s\n", event.getBundle(), event);+ switch (event.getType()) {+ case BundleEvent.INSTALLED:+ System.err.printf("INSTALLED %s\n", event.getBundle().getSymbolicName());+ break;+ case BundleEvent.UNINSTALLED:+ System.err.printf("UNINSTALLED %s\n", event.getBundle().getSymbolicName());+ break;+ case BundleEvent.STARTED:+ System.err.printf("STARTED %s\n", event.getBundle().getSymbolicName());+ break;+ case BundleEvent.STOPPED:+ System.err.printf("STOPPED %s\n", event.getBundle().getSymbolicName());+ break;+ }+ }+ });++ felix.start();+ fileinstall_bundle = installFromPath(findJarForClass(FileInstall.class));+ fileinstall_bundle.start();+ }++ private Path getOsgiDir() {+ Path usersettings = Application.getUserSettingsDirectory().toPath();+ return usersettings.resolve("osgi");+ }++ private String makeCacheDir() throws IOException {+ Path cache_dir = getOsgiDir().resolve("felixcache");+ Files.createDirectories(cache_dir);+ return cache_dir.toAbsolutePath().toString();+ }++ /** comma separated list of directories watched for bundles by fileinstaller */+ private String getWatchedBundleDirs() {+ return getCompiledBundlesDir().toAbsolutePath().toString();+ }++ public Path getCompiledBundlesDir() {+ return getOsgiDir().resolve("compiled-bundles");+ }++ public Bundle getBundle(String bundleLoc) {+ return bc.getBundle(bundleLoc);+ }++ /**+ * return true if it was running in the first place+ *+ * @throws InterruptedException+ * @throws BundleException+ */+ 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:+ }+ }+ 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);+ }+ }+ return false;+ }++ 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 stop_felix() {+ Task t = new Task("killing felix", false, false, true, true) {+ @Override+ public 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);+ }+ }++ };+ new TaskLauncher(t, null);+ }++ public Framework getHostFramework() {+ return felix;+ }++ public boolean stopBundleWatcher() {+ if (fileinstall_bundle != null) {+ try {+ fileinstall_bundle.stop();+ return true;+ } catch (BundleException e) {+ e.printStackTrace();+ }+ }+ return false;+ }++ public boolean startBundleWatcher() {+ if (fileinstall_bundle != null) {+ try {+ fileinstall_bundle.start();+ return true;+ } catch (BundleException e) {+ e.printStackTrace();+ }+ }+ return false;+ }++ public interface NewSourceCallback {+ void found(ResourceFile source_file, Path class_file) throws Throwable;+ }++ public static void visitUpdatedClassFiles(ResourceFile srcdir, Path bindir, NewSourceCallback new_source_cb) {+ try {+ // delete class files for which java is either newer, or no longer exists+ Deque<ResourceFile> stack = new ArrayDeque<>();+ stack.add(srcdir);+ while (!stack.isEmpty()) {+ ResourceFile sd = stack.pop();+ String relpath = sd.getAbsolutePath().substring(srcdir.getAbsolutePath().length());+ Path bd = bindir.resolve(relpath);++ // index the class files in the corresponding directory by basename+ Map<String, Path> binfiles = Files.exists(bd) ? Files.list(bd)+ .filter(x -> Files.isRegularFile(x) && x.getFileName().toString().endsWith(".class"))+ .collect(Collectors.toMap(x -> {+ String s = x.getFileName().toString();+ return s.substring(0, s.length() - 6);// drop ".class"+ }, Function.identity())) : Collections.emptyMap();++ for (ResourceFile sf : sd.listFiles()) {+ if (sf.isDirectory())+ stack.push(sf);+ else {+ String n = sf.getName();+ if (n.endsWith(".java")) {+ Path bf = binfiles.remove(n.substring(0, n.length() - 5)); // drop ".java"+ long bfl = -1;+ long sfl = sf.lastModified();+ if (bf != null)+ bfl = bf.toFile().lastModified();+ if (sfl > bfl) {+ new_source_cb.found(sf, bf);+ }+ }+ }+ }+ // any remaining .class files are missing .java files+ for (Path bf : binfiles.values()) {+ new_source_cb.found(null, bf);+ }+ }+ } catch (Throwable t) {+ t.printStackTrace();+ }+ }++ // from https://dzone.com/articles/locate-jar-classpath-given+ public static String findJarForClass(Class<?> c) {+ final URL location;+ final String classLocation = c.getName().replace('.', '/') + ".class";+ final ClassLoader loader = c.getClassLoader();+ if (loader == null) {+ location = ClassLoader.getSystemResource(classLocation);+ } else {+ location = loader.getResource(classLocation);+ }+ if (location != null) {+ Pattern p = Pattern.compile("^.*:(.*)!.*$");+ Matcher m = p.matcher(location.toString());+ if (m.find())+ return m.group(1);+ else+ return null; // not loaded from jar?+ } else+ return null;+ }++}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/GhidraBundleActivator.java b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/GhidraBundleActivator.javanew file mode 100644index 0000000000..2f536ad6db--- /dev/null+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/GhidraBundleActivator.java@@ -0,0 +1,37 @@+/* ###+ * 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.script.osgi;++import org.osgi.framework.BundleActivator;+import org.osgi.framework.BundleContext;++public abstract class GhidraBundleActivator implements BundleActivator {+ protected abstract void start(BundleContext bc, Object api);++ protected abstract void stop(BundleContext bc, Object api);++ @Override+ final public void start(BundleContext bc) throws Exception {+ start(bc, null);+ }++ @Override+ final public void stop(BundleContext bc) throws Exception {+ stop(bc, null);+ }++}