@eyeauras/insight-cli 0.7.0 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.cli-package-build.json +1 -1
- package/SKILL.md +1 -1
- package/dist/src/activity-audit.d.ts +7 -0
- package/dist/src/activity-audit.js +14 -4
- package/dist/src/analysis-storage.d.ts +5 -1
- package/dist/src/analysis-storage.js +9 -2
- package/dist/src/audit-retention.d.ts +8 -2
- package/dist/src/audit-retention.js +68 -7
- package/dist/src/cli.js +21 -5
- package/dist/src/context-diagnostics.d.ts +1 -1
- package/dist/src/context-diagnostics.js +10 -2
- package/dist/src/contexts.d.ts +118 -10
- package/dist/src/contexts.js +851 -199
- package/dist/src/debugger.js +2 -1
- package/dist/src/diagnostic-error.js +1 -1
- package/dist/src/inline-script.js +3 -4
- package/dist/src/lifecycle.d.ts +11 -0
- package/dist/src/lifecycle.js +34 -6
- package/dist/src/native-inputs.d.ts +6 -0
- package/dist/src/native-inputs.js +30 -6
- package/dist/src/native-queries.js +1 -6
- package/dist/src/native-service.d.ts +40 -0
- package/dist/src/native-service.js +406 -0
- package/dist/src/research.d.ts +29 -1
- package/dist/src/research.js +106 -27
- package/dist/src/server.d.ts +38 -1
- package/dist/src/server.js +160 -12
- package/dist/src/storage-gc.js +1 -1
- package/dist/src/sync-policy.js +2 -1
- package/dist/src/timed-backend.js +8 -0
- package/dist/src/timing-report.d.ts +32 -0
- package/dist/src/timing-report.js +74 -0
- package/dist/src/tool-runtime/identity.js +86 -1
- package/dist/src/tool-runtime/supervisor.js +6 -5
- package/dist/src/transport.d.ts +35 -0
- package/dist/src/transport.js +77 -7
- package/dist/src/unresolved-guidance.d.ts +46 -0
- package/dist/src/unresolved-guidance.js +55 -0
- package/dist/src/windbg.d.ts +1 -1
- package/dist/src/work/backup.d.ts +66 -0
- package/dist/src/work/backup.js +434 -0
- package/dist/src/work/commands.d.ts +5 -0
- package/dist/src/work/commands.js +277 -0
- package/dist/src/work/dashboard.d.ts +12 -0
- package/dist/src/work/dashboard.js +103 -0
- package/dist/src/work/model.d.ts +131 -0
- package/dist/src/work/model.js +124 -0
- package/dist/src/work/store.d.ts +368 -0
- package/dist/src/work/store.js +1050 -0
- package/dist/src/work/timing.d.ts +26 -0
- package/dist/src/work/timing.js +80 -0
- package/dist/src/worker-lease.d.ts +17 -0
- package/dist/src/worker-lease.js +50 -0
- package/dist/src/workspace.d.ts +5 -9
- package/dist/src/workspace.js +20 -41
- package/package.json +1 -1
- package/references/native/InsightHeadlessMain.java +9 -2
- package/references/native/InsightNativeCheckout.java +113 -43
- package/references/native/InsightNativeFingerprint.java +28 -1
- package/references/native/InsightNativeRead.java +32 -9
- package/references/native/InsightNativeService.java +43 -0
- package/references/native/InsightNativeView.java +17 -6
- package/references/native/InsightOwnedScripts.java +170 -0
- package/references/native/InsightWorkerLease.java +132 -0
- package/references/recovery.md +68 -3
- package/references/research.md +38 -4
- package/references/setup.md +5 -1
- package/references/work-tracking.md +203 -0
- package/runtime/toolbox.json +1 -0
- package/skill-bundle/insight-artifacts/SKILL.md +1 -1
- package/skill-bundle/insight-artifacts/references/recovery.md +68 -3
- package/skill-bundle/insight-binary/SKILL.md +1 -1
- package/skill-bundle/insight-capture/SKILL.md +1 -1
- package/skill-bundle/insight-cli/SKILL.md +1 -1
- package/skill-bundle/insight-cli/references/recovery.md +68 -3
- package/skill-bundle/insight-cli/references/setup.md +5 -1
- package/skill-bundle/insight-die/SKILL.md +1 -1
- package/skill-bundle/insight-dnspy/SKILL.md +1 -1
- package/skill-bundle/insight-dotnet-dump/SKILL.md +1 -1
- package/skill-bundle/insight-dotnet-stack/SKILL.md +1 -1
- package/skill-bundle/insight-dotnet-trace/SKILL.md +1 -1
- package/skill-bundle/insight-frida/SKILL.md +1 -1
- package/skill-bundle/insight-ghidra/SKILL.md +1 -1
- package/skill-bundle/insight-ghidra/references/recovery.md +68 -3
- package/skill-bundle/insight-ghidra/references/research.md +38 -4
- package/skill-bundle/insight-ghidra/references/setup.md +5 -1
- package/skill-bundle/insight-ilspy/SKILL.md +1 -1
- package/skill-bundle/insight-interop/SKILL.md +1 -1
- package/skill-bundle/insight-lldb/SKILL.md +1 -1
- package/skill-bundle/insight-llvm/SKILL.md +1 -1
- package/skill-bundle/insight-managed-heap/SKILL.md +1 -1
- package/skill-bundle/insight-managed-metadata/SKILL.md +1 -1
- package/skill-bundle/insight-mitmproxy/SKILL.md +1 -1
- package/skill-bundle/insight-overview/SKILL.md +1 -1
- package/skill-bundle/insight-procmon/SKILL.md +1 -1
- package/skill-bundle/insight-re/SKILL.md +5 -1
- package/skill-bundle/insight-re/references/recovery.md +68 -3
- package/skill-bundle/insight-re/references/work-tracking.md +203 -0
- package/skill-bundle/insight-sevenzip/SKILL.md +1 -1
- package/skill-bundle/insight-strace/SKILL.md +1 -1
- package/skill-bundle/insight-tshark/SKILL.md +1 -1
- package/skill-bundle/insight-windbg/SKILL.md +1 -1
- package/skill-bundle/manifest.json +1 -1
- package/skills/insight-artifacts/SKILL.md +1 -1
- package/skills/insight-artifacts/references/recovery.md +68 -3
- package/skills/insight-binary/SKILL.md +1 -1
- package/skills/insight-capture/SKILL.md +1 -1
- package/skills/insight-die/SKILL.md +1 -1
- package/skills/insight-dnspy/SKILL.md +1 -1
- package/skills/insight-dotnet-dump/SKILL.md +1 -1
- package/skills/insight-dotnet-stack/SKILL.md +1 -1
- package/skills/insight-dotnet-trace/SKILL.md +1 -1
- package/skills/insight-frida/SKILL.md +1 -1
- package/skills/insight-ghidra/SKILL.md +1 -1
- package/skills/insight-ghidra/references/recovery.md +68 -3
- package/skills/insight-ghidra/references/research.md +38 -4
- package/skills/insight-ghidra/references/setup.md +5 -1
- package/skills/insight-ilspy/SKILL.md +1 -1
- package/skills/insight-interop/SKILL.md +1 -1
- package/skills/insight-lldb/SKILL.md +1 -1
- package/skills/insight-llvm/SKILL.md +1 -1
- package/skills/insight-managed-heap/SKILL.md +1 -1
- package/skills/insight-managed-metadata/SKILL.md +1 -1
- package/skills/insight-mitmproxy/SKILL.md +1 -1
- package/skills/insight-overview/SKILL.md +1 -1
- package/skills/insight-procmon/SKILL.md +1 -1
- package/skills/insight-re/SKILL.md +5 -1
- package/skills/insight-re/references/recovery.md +68 -3
- package/skills/insight-re/references/work-tracking.md +203 -0
- package/skills/insight-sevenzip/SKILL.md +1 -1
- package/skills/insight-strace/SKILL.md +1 -1
- package/skills/insight-tshark/SKILL.md +1 -1
- package/skills/insight-windbg/SKILL.md +1 -1
|
@@ -22,6 +22,8 @@ public final class InsightNativeCheckout {
|
|
|
22
22
|
static final TaskMonitor MONITOR=TaskMonitor.DUMMY;
|
|
23
23
|
static final Object CONSUMER=new Object();
|
|
24
24
|
static boolean permitMerge=true;
|
|
25
|
+
/** Set when a request leaves this JVM in a doubtful state (an Error or a failed cleanup): a service then exits. */
|
|
26
|
+
static volatile boolean poisoned;
|
|
25
27
|
static class Projects extends DefaultProjectManager {Projects(){super();}}
|
|
26
28
|
static final class HeadChanged extends RuntimeException {HeadChanged(){super("Shared head changed before native check-in");}}
|
|
27
29
|
static class Factory extends ghidra.program.database.GhidraProgramMultiUserMergeManagerFactory {
|
|
@@ -48,9 +50,15 @@ public final class InsightNativeCheckout {
|
|
|
48
50
|
require(p.getExecutableSHA256().equals(text(owner,"sourceSha")),"Native source identity changed");
|
|
49
51
|
if(!p.getOptions("Insight").getString("Publication Engine","").equals("native-checkout-v1"))throw new InsightNativeMigration.Required();
|
|
50
52
|
}
|
|
53
|
+
/** The program is this target's native model; no bytes are read. */
|
|
54
|
+
static void identified(DomainFile file,JsonObject owner)throws Exception {
|
|
55
|
+
Program p=(Program)file.getDomainObject(CONSUMER,false,false,MONITOR);
|
|
56
|
+
try{source(p,owner);}finally{p.release(CONSUMER);}
|
|
57
|
+
}
|
|
58
|
+
/** The saved state of a local file as Ghidra identifies it; the database is not read. */
|
|
51
59
|
static Map<String,Object> saved(DomainFile file,JsonObject owner)throws Exception {
|
|
52
60
|
Program p=(Program)file.getDomainObject(CONSUMER,false,false,MONITOR);
|
|
53
|
-
try{source(p,owner);return Map.of("fingerprint",InsightNativeFingerprint.
|
|
61
|
+
try{source(p,owner);return Map.of("fingerprint",InsightNativeFingerprint.saved(p),"modified",file.isCheckedOut()&&file.modifiedSinceCheckout(),"version",file.getVersion(),"fileId",file.getFileID(),
|
|
54
62
|
"language",p.getLanguageID().toString(),"compiler",p.getCompilerSpec().getCompilerSpecID().toString(),"imageBase",p.getImageBase().toString());}
|
|
55
63
|
finally{p.release(CONSUMER);}
|
|
56
64
|
}
|
|
@@ -59,18 +67,23 @@ public final class InsightNativeCheckout {
|
|
|
59
67
|
for(DomainFile f:folder.getFiles())if(!f.isVersioned()||f.isCheckedOut()||f.isHijacked()||f.canRecover())names.add(f.getPathname().substring(1));
|
|
60
68
|
for(DomainFolder child:folder.getFolders())if(child.isLinked())names.add(child.getPathname().substring(1)+"/");else local(child,names);
|
|
61
69
|
}
|
|
62
|
-
|
|
70
|
+
/** Ghidra's save counter of the local file: a later save of a file that survived its release is seen without reading it. */
|
|
71
|
+
static long localVersion(DomainFile file)throws Exception {
|
|
72
|
+
Program p=(Program)file.getDomainObject(CONSUMER,false,false,MONITOR);
|
|
73
|
+
try{return InsightNativeFingerprint.localVersion(p);}finally{p.release(CONSUMER);}
|
|
74
|
+
}
|
|
63
75
|
static boolean sameRelease(JsonObject receipt,JsonObject q){
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
return Objects.equals(receipt.get("fileId"),q.get("fileId"))&&Objects.equals(receipt.get("savedFingerprint"),new JsonPrimitive(authorized(q)));
|
|
76
|
+
// The checkout, its base version and its file identify a release. Receipts of earlier builds also recorded
|
|
77
|
+
// fingerprints, which name nothing comparable any more and are not consulted.
|
|
78
|
+
if(!Objects.equals(receipt.get("checkoutId"),q.get("checkoutId"))||!Objects.equals(receipt.get("version"),q.get("verifiedVersion")))return false;
|
|
79
|
+
return !receipt.has("fileId")||Objects.equals(receipt.get("fileId"),q.get("fileId"));
|
|
69
80
|
}
|
|
70
81
|
/** A new intent can prove the local file left between server termination and native undo's local deletion. */
|
|
71
|
-
static boolean survivingRelease(JsonObject receipt,JsonObject q,
|
|
72
|
-
|
|
73
|
-
|
|
82
|
+
static boolean survivingRelease(JsonObject receipt,JsonObject q,String fileId,long localVersion){
|
|
83
|
+
// The intent was recorded only after Ghidra reported this checkout unmodified and without recovery data. The
|
|
84
|
+
// file left behind is that one only while it was not saved again.
|
|
85
|
+
return receipt.has("fileId")&&receipt.has("localVersion")&&Objects.equals(receipt.get("state"),new JsonPrimitive("release_intent"))&&sameRelease(receipt,q)&&
|
|
86
|
+
fileId.equals(text(receipt,"fileId"))&&localVersion>=0&&receipt.get("localVersion").getAsLong()==localVersion;
|
|
74
87
|
}
|
|
75
88
|
static boolean backupName(String program,String name){
|
|
76
89
|
String keep=program+".keep";
|
|
@@ -102,13 +115,13 @@ public final class InsightNativeCheckout {
|
|
|
102
115
|
JsonObject created=proof.getAsJsonObject();
|
|
103
116
|
if(!saved.get("fileId").equals(text(created,"fileId"))||!saved.get("fingerprint").equals(text(created,"fingerprint"))||
|
|
104
117
|
!journal.get("backupExpected").getAsBoolean())return false;
|
|
105
|
-
if(created.get("schema").getAsInt()==2){
|
|
118
|
+
if(created.get("schema").getAsInt()==2||created.get("schema").getAsInt()==3){
|
|
106
119
|
String program=text(journal.getAsJsonObject("request").getAsJsonObject("owner"),"path").substring(1);
|
|
107
120
|
return text(journal.getAsJsonObject("request"),"operation").equals("discard")&&
|
|
108
121
|
name.equals(createdBackup(program,journal.getAsJsonObject("backupFilesBefore"),journal.getAsJsonObject("backupFilesAfter")))&&
|
|
109
122
|
journal.getAsJsonObject("backupFilesAfter").get(name).equals(created.get("fileId"))&&
|
|
110
123
|
name.equals(text(journal.getAsJsonObject("result"),"retainedKeepFile"))&&
|
|
111
|
-
created.get("fingerprint").equals(journal.getAsJsonObject("before").get("fingerprint"));
|
|
124
|
+
(created.get("schema").getAsInt()==3||created.get("fingerprint").equals(journal.getAsJsonObject("before").get("fingerprint")));
|
|
112
125
|
}
|
|
113
126
|
boolean newFile=journal.has("backupAbsent")&&(journal.get("backupAbsent").getAsBoolean()||journal.has("backupBeforeFileId")&&!journal.get("backupBeforeFileId").isJsonNull()&&
|
|
114
127
|
!journal.get("backupBeforeFileId").equals(created.get("fileId")));
|
|
@@ -227,33 +240,50 @@ public final class InsightNativeCheckout {
|
|
|
227
240
|
for(var checkout:repository.getCheckouts("/",name))require(checkout.getCheckoutId()!=id,"Owned checkout remains");
|
|
228
241
|
return Map.of("state","abandoned","terminated",present);
|
|
229
242
|
}
|
|
243
|
+
/** One-shot helper: one request file, one JSON result line, then exit. */
|
|
230
244
|
public static void main(String[] args){
|
|
231
|
-
var output=System.out;System.setOut(System.err);
|
|
245
|
+
var output=System.out;System.setOut(System.err);Map<String,Object> result;
|
|
246
|
+
try{require(args.length==1,"Owned request required");initialize();result=handle(Path.of(args[0]));}
|
|
247
|
+
catch(Throwable failure){failure.printStackTrace(System.err);result=unknown(failure);}
|
|
248
|
+
output.println(GSON.toJson(result));System.exit(0);
|
|
249
|
+
}
|
|
250
|
+
private static boolean registered;
|
|
251
|
+
/** Ghidra and the stock multi-user merge factory are initialized once per JVM (helper or long-lived service). */
|
|
252
|
+
static synchronized void initialize()throws Exception {
|
|
253
|
+
if(!Application.isInitialized())Application.initializeApplication(new GhidraApplicationLayout(),new HeadlessGhidraApplicationConfiguration());
|
|
254
|
+
if(!registered){
|
|
255
|
+
Class.forName("ghidra.program.database.ProgramMultiUserMergeManagerFactory");
|
|
256
|
+
PluggableServiceRegistry.registerPluggableService(ghidra.program.database.ProgramMultiUserMergeManagerFactory.class,new Factory());registered=true;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
static Map<String,Object> unknown(Throwable failure){
|
|
260
|
+
return Map.of("state","unknown","diagnostic",failure.getClass().getSimpleName(),"reason",Objects.toString(failure.getMessage(),failure.toString()),"code",failure instanceof InsightNativeMigration.Required?"migration":"unknown");
|
|
261
|
+
}
|
|
262
|
+
/** One native checkout operation. Per-request state is reset, so a long-lived service handles requests independently. */
|
|
263
|
+
static Map<String,Object> handle(Path requestFile){
|
|
264
|
+
Project project=null;GhidraServerManager server=null;
|
|
232
265
|
Map<String,Object> out=new LinkedHashMap<>();
|
|
266
|
+
permitMerge=true;HeadlessProgramMergeManager.invocations=0;HeadlessProgramMergeManager.phases.clear();
|
|
233
267
|
try {
|
|
234
|
-
|
|
235
|
-
JsonObject q=JsonParser.parseString(Files.readString(Path.of(args[0]))).getAsJsonObject();
|
|
268
|
+
JsonObject q=JsonParser.parseString(Files.readString(requestFile)).getAsJsonObject();
|
|
236
269
|
boolean abandoning=text(q,"operation").equals("abandon");
|
|
237
270
|
Path root=abandoning?Path.of(text(q,"root")):Path.of(text(q,"root")).toRealPath();
|
|
238
271
|
JsonObject owner=abandoning?q.getAsJsonObject("owner"):JsonParser.parseString(Files.readString(root.resolve("native-owner.json"))).getAsJsonObject();
|
|
239
272
|
require(owner.equals(q.getAsJsonObject("owner")),"Native owner receipt changed");
|
|
240
273
|
require(text(owner,"protocol").equals("native-checkout-v1")&&text(owner,"path").equals("/"+text(owner,"target")+".bin"),"Malformed native binding");
|
|
241
274
|
String operation=text(q,"operation"),path=text(owner,"path"),name=path.substring(1);
|
|
242
|
-
Application.initializeApplication(new GhidraApplicationLayout(),new HeadlessGhidraApplicationConfiguration());
|
|
243
|
-
Class.forName("ghidra.program.database.ProgramMultiUserMergeManagerFactory");
|
|
244
|
-
PluggableServiceRegistry.registerPluggableService(ghidra.program.database.ProgramMultiUserMergeManagerFactory.class,new Factory());
|
|
245
275
|
server=new GhidraServerManager();server.connect();require(server.isConnected(),"Native repository disconnected");
|
|
246
276
|
RepositoryAdapter repository=server.server().getRepository(text(owner,"repository"));repository.connect();
|
|
247
277
|
require(repository.getUser().hasWritePermission()&&repository.getUser().getName().equals(System.getenv("GHIDRA_SERVER_USER")),"Publisher authority required");
|
|
248
278
|
if(abandoning){
|
|
249
|
-
out.putAll(abandon(repository,q,owner));repository.disconnect();server.disconnect();
|
|
279
|
+
out.putAll(abandon(repository,q,owner));repository.disconnect();server.disconnect();server=null;return out;
|
|
250
280
|
}
|
|
251
281
|
ProjectLocator locator=new ProjectLocator(root.toString(),"view");Projects manager=new Projects();
|
|
252
282
|
// After a proved release the project is never reopened: an interrupted deletion can leave it unreadable.
|
|
253
283
|
if((operation.equals("release")||operation.equals("drop"))&&released(root,q)){
|
|
254
284
|
require(Arrays.stream(repository.getCheckouts("/",name)).noneMatch(c->c.getCheckoutId()==q.get("checkoutId").getAsLong()),"Owned checkout remains");
|
|
255
285
|
if(operation.equals("drop"))deleteReleased(root,locator);
|
|
256
|
-
repository.disconnect();server.disconnect();
|
|
286
|
+
repository.disconnect();server.disconnect();server=null;return new LinkedHashMap<>(Map.of("state",operation.equals("drop")?"dropped":"released"));
|
|
257
287
|
}
|
|
258
288
|
if(operation.equals("create")&&!locator.getMarkerFile().exists())project=manager.createProject(locator,repository,false);
|
|
259
289
|
else project=manager.openProject(locator,false,false);
|
|
@@ -264,12 +294,39 @@ public final class InsightNativeCheckout {
|
|
|
264
294
|
if(operation.equals("create")&&!file.isCheckedOut()){
|
|
265
295
|
String projectPath=ghidra.framework.store.ItemCheckoutStatus.getProjectPath(locator.toString(),false);
|
|
266
296
|
require(Arrays.stream(repository.getCheckouts("/",name)).noneMatch(c->projectPath.equals(c.getProjectPath())),"Uncertain checkout creation must be reconciled");
|
|
267
|
-
|
|
297
|
+
identified(file,owner);require(file.checkout(false,MONITOR),"Native checkout denied");
|
|
268
298
|
}
|
|
269
299
|
require(!file.isCheckedOutExclusive(),"Ordinary native checkout required");
|
|
270
300
|
if(q.has("fileId"))require(file.getFileID().equals(text(q,"fileId")),"Native file ID changed");
|
|
271
301
|
if(q.has("checkoutId")&&file.isCheckedOut())require(file.getCheckoutStatus().getCheckoutId()==q.get("checkoutId").getAsLong(),"Native checkout owner changed");
|
|
272
302
|
Path operations=root.resolve("operations");Files.createDirectories(operations);
|
|
303
|
+
// Opening a file for writing discards Ghidra's recovery snapshot of unsaved changes. A file that has one is
|
|
304
|
+
// reported as it is and never opened: that work is kept for its owner to recover.
|
|
305
|
+
if(operation.equals("unsaved")){
|
|
306
|
+
// Ghidra's own open applies the recovery data or deletes it; this helper reads and writes none of it.
|
|
307
|
+
// Everything is checked before the only effect.
|
|
308
|
+
require(file.isCheckedOut()&&file.getCheckoutStatus().getCheckoutVersion()==q.get("baseVersion").getAsInt(),"Native checkout differs from its receipt");
|
|
309
|
+
boolean keep=q.get("keep").getAsBoolean(),present=file.canRecover();
|
|
310
|
+
if(present){
|
|
311
|
+
ProgramDB p=(ProgramDB)file.getDomainObject(CONSUMER,false,keep,MONITOR);
|
|
312
|
+
if(keep)try{p.save("insight recovered unsaved changes",MONITOR);}
|
|
313
|
+
catch(Throwable failure){
|
|
314
|
+
// Closing a restored program that was not saved makes Ghidra delete its recovery data. The process
|
|
315
|
+
// ends as an interrupted session does instead: the data stays and the command can be repeated.
|
|
316
|
+
failure.printStackTrace(System.err);System.err.flush();Runtime.getRuntime().halt(70);
|
|
317
|
+
}
|
|
318
|
+
p.release(CONSUMER);
|
|
319
|
+
require(!file.canRecover(),"Ghidra kept the recovery data");
|
|
320
|
+
}
|
|
321
|
+
out.put("state",!present?"absent":keep?"recovered":"discarded");
|
|
322
|
+
}
|
|
323
|
+
if(file.canRecover()){
|
|
324
|
+
require(operation.equals("status"),"Unsaved changes of an interrupted session can be recovered; keep them with `ghidra changes recover-unsaved` or drop them with `ghidra changes discard-unsaved` before this operation");
|
|
325
|
+
out.put("recoverable",true);out.put("modified",file.isCheckedOut()&&file.modifiedSinceCheckout());out.put("fileId",file.getFileID());out.put("checkedOut",file.isCheckedOut());
|
|
326
|
+
var local=new TreeSet<String>();local(project.getProjectData().getRootFolder(),local);out.put("projectFiles",local);
|
|
327
|
+
if(file.isCheckedOut()){out.put("checkoutId",file.getCheckoutStatus().getCheckoutId());out.put("baseVersion",file.getCheckoutStatus().getCheckoutVersion());}
|
|
328
|
+
history(repository,path,out);out.put("state","ready");project.close();project=null;repository.disconnect();server.disconnect();server=null;return out;
|
|
329
|
+
}
|
|
273
330
|
if(operation.equals("update")||operation.equals("checkin")||operation.equals("discard")){
|
|
274
331
|
String request=text(q,"request");require(request.matches("q_[a-f0-9-]{36}"),"Native request identity required");
|
|
275
332
|
Path journal=operations.resolve(request+"-"+operation+".json");
|
|
@@ -297,8 +354,9 @@ public final class InsightNativeCheckout {
|
|
|
297
354
|
DomainFile created=project.getProjectData().getFile("/"+keep);
|
|
298
355
|
require(created!=null&&!created.isVersioned()&&!created.canRecover()&&!created.isCheckedOut()&&!created.isHijacked(),"Native discard backup is not private");
|
|
299
356
|
var actual=saved(created,owner);
|
|
300
|
-
|
|
301
|
-
|
|
357
|
+
// Ghidra's undoCheckout made this copy; it is identified as it stands now, so a later edit of it is noticed.
|
|
358
|
+
require(Objects.equals(actual.get("fileId"),backupsAfter.get(keep)),"Native discard backup differs from the created file");
|
|
359
|
+
out.put("retainedKeepFile",keep);out.put("disposableBackups",Map.of(keep,Map.of("schema",3,"fileId",actual.get("fileId"),"fingerprint",actual.get("fingerprint"))));
|
|
302
360
|
}
|
|
303
361
|
file=project.getProjectData().getFile(path);require(file.checkout(false,MONITOR),"Native checkout after discard was refused");
|
|
304
362
|
}else if(operation.equals("update")){
|
|
@@ -306,7 +364,7 @@ public final class InsightNativeCheckout {
|
|
|
306
364
|
// Only dirty incoming Update can replace .keep. A refusal is a completed pre-call outcome,
|
|
307
365
|
// carried by the existing conflict/recovery path; incomplete/legacy intents remain unknown.
|
|
308
366
|
if(backupExpected&&!keepAbsent&&!replaceableBackup(project,operations,q,owner,base,intent)){
|
|
309
|
-
require(
|
|
367
|
+
require(file.getCheckoutStatus().getCheckoutId()==checkout&&file.getCheckoutStatus().getCheckoutVersion()==base,"Backup refusal did not preserve local state");
|
|
310
368
|
out.put("state","conflict");out.put("conflict","Existing native backup is not proved disposable; retain and inspect this project before Update");
|
|
311
369
|
var refusal=new LinkedHashMap<String,Object>(Map.of("schema",1,"operation","update","invoked",false,"reason","protected_existing_backup"));
|
|
312
370
|
refusal.put("fileId",priorKeepId);out.put("preCallRefusal",refusal);
|
|
@@ -316,12 +374,11 @@ public final class InsightNativeCheckout {
|
|
|
316
374
|
require(file.getCheckoutStatus().getCheckoutId()==checkout&&file.getCheckoutStatus().getCheckoutVersion()>=head,"Native Update did not establish the requested ancestry");
|
|
317
375
|
out.put("state","updated");}
|
|
318
376
|
catch(HeadlessProgramMergeManager.UnresolvedNativeConflict conflict){
|
|
319
|
-
require(
|
|
377
|
+
require(file.getCheckoutStatus().getCheckoutId()==checkout&&file.getCheckoutStatus().getCheckoutVersion()==base,"Native conflict did not preserve local state");
|
|
320
378
|
out.put("state","conflict");out.put("conflict",conflict.getMessage());
|
|
321
379
|
}
|
|
322
380
|
}
|
|
323
381
|
}else{
|
|
324
|
-
require(before.get("fingerprint").equals(text(q,"fingerprint")),"Prepared native publication changed");
|
|
325
382
|
if(head!=base||head!=q.get("expectedVersion").getAsInt()){
|
|
326
383
|
// A known pre-call head race is not an unknown check-in: none was issued.
|
|
327
384
|
out.put("state","conflict");out.put("conflict","Shared head changed before native check-in");
|
|
@@ -333,7 +390,7 @@ public final class InsightNativeCheckout {
|
|
|
333
390
|
permitMerge=false;
|
|
334
391
|
try{file.checkin(new DefaultCheckinHandler("insight native "+request,true,false),MONITOR);out.put("state","checked_in");}
|
|
335
392
|
catch(HeadChanged changed){
|
|
336
|
-
require(
|
|
393
|
+
require(file.getCheckoutStatus().getCheckoutId()==checkout&&file.getCheckoutStatus().getCheckoutVersion()==base&&Arrays.stream(repository.getVersions("/",name)).noneMatch(v->("insight native "+request).equals(v.getComment())),"Check-in outcome is unknown");
|
|
337
394
|
out.put("state","conflict");out.put("conflict",changed.getMessage());
|
|
338
395
|
}finally{permitMerge=true;}
|
|
339
396
|
}
|
|
@@ -352,41 +409,50 @@ public final class InsightNativeCheckout {
|
|
|
352
409
|
}
|
|
353
410
|
}else if(operation.equals("release")){
|
|
354
411
|
Path releaseFile=root.resolve("released.json");
|
|
355
|
-
Map<String,Object> release=new LinkedHashMap<>(Map.of("checkoutId",q.get("checkoutId").getAsLong(),"version",q.get("verifiedVersion").getAsInt(),
|
|
356
|
-
"fileId",text(q,"fileId")
|
|
412
|
+
Map<String,Object> release=new LinkedHashMap<>(Map.of("checkoutId",q.get("checkoutId").getAsLong(),"version",q.get("verifiedVersion").getAsInt(),
|
|
413
|
+
"fileId",text(q,"fileId")));
|
|
357
414
|
if(file.isCheckedOut()){
|
|
358
|
-
|
|
359
|
-
require(file.getCheckoutStatus().getCheckoutVersion()==q.get("verifiedVersion").getAsInt()&&!file.canRecover(),"Unpublished native work must be retained");
|
|
360
|
-
|
|
361
|
-
// Ghidra's own rewrite on open marks a checkout modified; only bytes the coordinator proved to hold no work may carry it.
|
|
362
|
-
require(local.equals(authorized(q)),"Verified native buffers changed");
|
|
363
|
-
require(q.has("opened")||!file.modifiedSinceCheckout(),"Unpublished native work must be retained");
|
|
364
|
-
release.put("disposableBackups",releaseFiles(project,operations,q,owner,true));
|
|
415
|
+
// Ghidra's own answer decides: a checkout it reports modified, or with recoverable changes, holds work.
|
|
416
|
+
require(file.getCheckoutStatus().getCheckoutVersion()==q.get("verifiedVersion").getAsInt()&&!file.canRecover()&&!file.modifiedSinceCheckout(),"Unpublished native work must be retained");
|
|
417
|
+
release.put("disposableBackups",releaseFiles(project,operations,q,owner,true));release.put("localVersion",localVersion(file));
|
|
365
418
|
release.put("state","release_intent");write(releaseFile,release);file.undoCheckout(false);
|
|
366
419
|
}else{
|
|
367
420
|
var prior=JsonParser.parseString(Files.readString(releaseFile)).getAsJsonObject();
|
|
368
421
|
require(text(prior,"state").equals("release_intent")&&sameRelease(prior,q),"Release intent changed");
|
|
369
422
|
boolean surviving=file.isHijacked();
|
|
370
|
-
if(surviving)require(!file.canRecover()&&survivingRelease(prior,q,
|
|
423
|
+
if(surviving)require(!file.canRecover()&&survivingRelease(prior,q,file.getFileID(),localVersion(file)),"Unproved surviving native file must be retained");
|
|
371
424
|
release.put("disposableBackups",releaseFiles(project,operations,q,owner,surviving));
|
|
372
425
|
}
|
|
373
426
|
require(Arrays.stream(repository.getCheckouts("/",name)).noneMatch(c->c.getCheckoutId()==q.get("checkoutId").getAsLong()),"Owned checkout remains");
|
|
374
427
|
release.put("state","released");write(releaseFile,release);out.put("state","released");
|
|
428
|
+
project.close();project=null;repository.disconnect();server.disconnect();server=null;return out;
|
|
375
429
|
}else if(operation.equals("drop")){
|
|
376
430
|
require(false,"Verified release receipt differs");
|
|
431
|
+
}else if(operation.equals("prune-backups")){
|
|
432
|
+
// A checkout kept after its verified publication: Update/discard backups proved by this checkout's own
|
|
433
|
+
// journals hold no unpublished work. Anything else, including the program, is retained.
|
|
434
|
+
require(file.isCheckedOut()&&file.getCheckoutStatus().getCheckoutVersion()==q.get("verifiedVersion").getAsInt()&&!file.modifiedSinceCheckout()&&!file.canRecover(),
|
|
435
|
+
"Backup pruning requires the verified unchanged checkout");
|
|
436
|
+
List<String> pruned=new ArrayList<>();
|
|
437
|
+
for(var entry:backups(project,operations,q,owner).entrySet()){
|
|
438
|
+
DomainFile backup=project.getProjectData().getFile("/"+entry.getKey());
|
|
439
|
+
if(backup!=null&&!backup.isVersioned()&&!backup.isCheckedOut()&&saved(backup,owner).get("fingerprint").equals(entry.getValue())){backup.delete();pruned.add(entry.getKey());}
|
|
440
|
+
}
|
|
441
|
+
out.put("state","pruned");out.put("pruned",pruned);
|
|
377
442
|
}else if(operation.equals("inspect")||operation.equals("fields")||operation.equals("export")){
|
|
378
443
|
require(saved(file,owner).get("fingerprint").equals(text(q,"fingerprint")),"Saved native view changed");
|
|
379
444
|
ProgramDB p=(ProgramDB)file.getDomainObject(CONSUMER,false,false,MONITOR);
|
|
380
445
|
try{
|
|
381
446
|
if(operation.equals("export")){
|
|
382
447
|
Path target=Path.of(text(q,"output"));require(target.getParent().toRealPath().startsWith(root)&&!Files.exists(target),"Native export escaped owned storage");
|
|
383
|
-
p.saveToPackedFile(target.toFile(),MONITOR);
|
|
448
|
+
p.saveToPackedFile(target.toFile(),MONITOR);
|
|
384
449
|
}else out.put("value",operation.equals("fields")?InsightSnapshotFields.inspect(p,q.getAsJsonArray("selectors")):InsightSnapshotInspect.inspect(p,q.getAsJsonObject("parameters")));
|
|
385
450
|
}
|
|
386
451
|
finally{p.release(CONSUMER);}
|
|
387
|
-
}else require(operation.equals("create")||operation.equals("status"),"Unknown native operation");
|
|
452
|
+
}else require(operation.equals("create")||operation.equals("status")||operation.equals("unsaved"),"Unknown native operation");
|
|
388
453
|
if(project!=null){
|
|
389
|
-
out.
|
|
454
|
+
if(!out.containsKey("saved"))out.put("saved",saved(file,owner));
|
|
455
|
+
out.put("modified",file.modifiedSinceCheckout());out.put("fileId",file.getFileID());out.put("checkedOut",file.isCheckedOut());
|
|
390
456
|
out.put("recoverable",file.canRecover());
|
|
391
457
|
var local=new TreeSet<String>();local(project.getProjectData().getRootFolder(),local);out.put("projectFiles",local);
|
|
392
458
|
if(file.isCheckedOut()){out.put("checkoutId",file.getCheckoutStatus().getCheckoutId());out.put("baseVersion",file.getCheckoutStatus().getCheckoutVersion());}
|
|
@@ -394,8 +460,12 @@ public final class InsightNativeCheckout {
|
|
|
394
460
|
history(repository,path,out);out.putIfAbsent("state","ready");out.put("guiWindows",java.awt.Window.getWindows().length);
|
|
395
461
|
require(java.awt.Window.getWindows().length==0,"Unexpected GUI window");
|
|
396
462
|
if(project!=null){project.close();project=null;}repository.disconnect();server.disconnect();server=null;
|
|
397
|
-
|
|
398
|
-
}catch(Throwable failure){failure.printStackTrace(System.err);
|
|
399
|
-
|
|
463
|
+
return out;
|
|
464
|
+
}catch(Throwable failure){failure.printStackTrace(System.err);
|
|
465
|
+
if(failure instanceof Error)poisoned=true;
|
|
466
|
+
try{if(project!=null)project.close();}catch(Throwable cleanup){poisoned=true;}
|
|
467
|
+
try{if(server!=null)server.disconnect();}catch(Throwable cleanup){poisoned=true;}
|
|
468
|
+
if(java.awt.Window.getWindows().length>0)poisoned=true;
|
|
469
|
+
return unknown(failure);}
|
|
400
470
|
}
|
|
401
471
|
}
|
|
@@ -4,12 +4,39 @@ import db.buffers.InsightBlockTransfer;
|
|
|
4
4
|
import ghidra.program.database.ProgramDB;
|
|
5
5
|
import ghidra.program.model.listing.Program;
|
|
6
6
|
|
|
7
|
-
/**
|
|
7
|
+
/**
|
|
8
|
+
* `of` and `content` read a whole database and are for the two places where the coordinator itself copies or
|
|
9
|
+
* converts one (initial publication, legacy migration). Native checkouts are identified by `saved` and `version`.
|
|
10
|
+
*/
|
|
8
11
|
public final class InsightNativeFingerprint {
|
|
9
12
|
public static String of(Program p)throws Exception {
|
|
10
13
|
if(p.isChanged())throw new IllegalStateException("Program has unsaved changes");
|
|
11
14
|
return InsightBlockTransfer.fingerprint(((ProgramDB)p).getDBHandle().getBufferMgr().getSourceFile());
|
|
12
15
|
}
|
|
16
|
+
/**
|
|
17
|
+
* Identity of one saved state of a local file, from what Ghidra itself keeps: the file, its base version and
|
|
18
|
+
* the version of its local buffer file, which Ghidra advances on every save. No bytes are read.
|
|
19
|
+
* It names a saved state so that a later request can tell whether it still looks at the same one; it says
|
|
20
|
+
* nothing about content, and whether a checkout holds work is Ghidra's own `modifiedSinceCheckout()`.
|
|
21
|
+
*/
|
|
22
|
+
public static String saved(Program p)throws Exception {
|
|
23
|
+
if(p.isChanged())throw new IllegalStateException("Program has unsaved changes");
|
|
24
|
+
var file=p.getDomainFile();Object source=((ProgramDB)p).getDBHandle().getBufferMgr().getSourceFile();
|
|
25
|
+
// A repository item (no local file) is one immutable version; the database is never read to name a state.
|
|
26
|
+
if(!(source instanceof db.buffers.LocalManagedBufferFile local))return version(file.getFileID(),file.getVersion());
|
|
27
|
+
// Only what the local project knows: a worker's project is not connected to the repository server.
|
|
28
|
+
return identity("local|"+file.getFileID()+"|"+(file.isCheckedOut()?"base "+file.getVersion():"private")+"|"+local.getVersion());
|
|
29
|
+
}
|
|
30
|
+
/** The version of a program's local buffer file, which Ghidra advances on every save; -1 without a local file. */
|
|
31
|
+
public static long localVersion(Program p){
|
|
32
|
+
Object source=((ProgramDB)p).getDBHandle().getBufferMgr().getSourceFile();
|
|
33
|
+
return source instanceof db.buffers.LocalManagedBufferFile local?local.getVersion():-1;
|
|
34
|
+
}
|
|
35
|
+
/** Identity of one immutable version of a repository item. */
|
|
36
|
+
public static String version(String fileId,int version)throws Exception {return identity("server|"+fileId+"|"+version);}
|
|
37
|
+
private static String identity(String value)throws Exception {
|
|
38
|
+
return java.util.HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(("insight-saved-state-v1|"+value).getBytes(java.nio.charset.StandardCharsets.UTF_8)));
|
|
39
|
+
}
|
|
13
40
|
/**
|
|
14
41
|
* Every saved record except what opening a program writes by itself: the derived Metadata table, rebuilt
|
|
15
42
|
* from options on save, and the GUI's "Should Ask To Analyze" flag. Stored file bytes are included; memory
|
|
@@ -13,17 +13,29 @@ import java.util.*;
|
|
|
13
13
|
|
|
14
14
|
/** Independent read authority, immutable exact-version native database; never checks out. */
|
|
15
15
|
public final class InsightNativeRead {
|
|
16
|
+
static final Gson GSON=new GsonBuilder().serializeNulls().create();
|
|
17
|
+
static volatile boolean poisoned;
|
|
18
|
+
/** One-shot helper: one request file, one JSON result line, then exit. */
|
|
16
19
|
public static void main(String[] args){
|
|
17
|
-
var output=System.out;System.setOut(System.err);
|
|
20
|
+
var output=System.out;System.setOut(System.err);Map<String,Object> result;
|
|
21
|
+
try{if(!Application.isInitialized())Application.initializeApplication(new GhidraApplicationLayout(),new HeadlessGhidraApplicationConfiguration());result=handle(Path.of(args[0]));}
|
|
22
|
+
catch(Throwable failure){failure.printStackTrace(System.err);result=unknown(failure);}
|
|
23
|
+
output.println(GSON.toJson(result));System.exit(0);
|
|
24
|
+
}
|
|
25
|
+
static Map<String,Object> unknown(Throwable failure){
|
|
26
|
+
return Map.of("state","unknown","diagnostic",failure.getClass().getSimpleName(),"reason",Objects.toString(failure.getMessage(),failure.toString()),"code",failure instanceof InsightNativeMigration.Required?"migration":"unknown");
|
|
27
|
+
}
|
|
28
|
+
/** One independent read. The server connection is closed after every request, also on failure. */
|
|
29
|
+
static Map<String,Object> handle(Path requestFile){
|
|
30
|
+
GhidraServerManager server=null;
|
|
18
31
|
try {
|
|
19
|
-
JsonObject q=JsonParser.parseString(Files.readString(
|
|
32
|
+
JsonObject q=JsonParser.parseString(Files.readString(requestFile)).getAsJsonObject();
|
|
20
33
|
String repo=q.get("repository").getAsString(),path=q.get("path").getAsString(),sha=q.get("sourceSha").getAsString(),op=q.get("operation").getAsString();
|
|
21
34
|
if(!path.startsWith("/")||path.indexOf('/',1)>=0)throw new SecurityException();String name=path.substring(1);
|
|
22
|
-
|
|
23
|
-
var server=new GhidraServerManager();server.connect();var repository=server.server().getRepository(repo);repository.connect();
|
|
35
|
+
server=new GhidraServerManager();server.connect();var repository=server.server().getRepository(repo);repository.connect();
|
|
24
36
|
if(!repository.getUser().isReadOnly()||!repository.getUser().getName().equals(System.getenv("GHIDRA_SERVER_USER")))throw new SecurityException();
|
|
25
37
|
var item=repository.getItem("/",name);
|
|
26
|
-
if(item==null&&op.equals("migration-probe")){repository.disconnect();server.disconnect();
|
|
38
|
+
if(item==null&&op.equals("migration-probe")){repository.disconnect();server.disconnect();server=null;return new LinkedHashMap<>(Map.of("state","absent"));}
|
|
27
39
|
if(item==null||repository.isCheckinActive("/",name))throw new IllegalStateException("Native item is absent or busy");
|
|
28
40
|
int version=q.has("version")?q.get("version").getAsInt():item.getVersion();
|
|
29
41
|
if(q.has("fileId")&&!item.getFileID().equals(q.get("fileId").getAsString()))throw new SecurityException("Native item ID changed");
|
|
@@ -31,14 +43,22 @@ public final class InsightNativeRead {
|
|
|
31
43
|
var matches=Arrays.stream(repository.getVersions("/",name)).filter(v->q.get("marker").getAsString().equals(v.getComment())).toList();
|
|
32
44
|
if(matches.size()!=1||matches.getFirst().getVersion()!=version)throw new IllegalStateException("Native history marker is unresolved");
|
|
33
45
|
}
|
|
46
|
+
// The unique request marker at the expected version is the publication. Nothing more is opened to settle a
|
|
47
|
+
// lost check-in reply; only a migration asks for the bytes.
|
|
48
|
+
if(op.equals("verify")&&!(q.has("bytes")&&q.get("bytes").getAsBoolean())){
|
|
49
|
+
Map<String,Object> settled=new LinkedHashMap<>(Map.of("state","verified","version",version,"fileId",item.getFileID(),"fingerprint",InsightNativeFingerprint.version(item.getFileID(),version)));
|
|
50
|
+
repository.disconnect();server.disconnect();server=null;return settled;
|
|
51
|
+
}
|
|
34
52
|
DBHandle db=new DBHandle(repository.openDatabase("/",name,version,-1));Object consumer=new Object();ProgramDB program=null;
|
|
35
53
|
Map<String,Object> result=new LinkedHashMap<>();
|
|
36
54
|
try {
|
|
37
|
-
|
|
55
|
+
// An immutable version is identified by its item and number. Only a migration compares whole databases.
|
|
56
|
+
String fingerprint=op.equals("migration-probe")||q.has("bytes")&&q.get("bytes").getAsBoolean()?InsightNativeFingerprint.of(db):InsightNativeFingerprint.version(item.getFileID(),version);
|
|
38
57
|
program=new ProgramDB(db,OpenMode.IMMUTABLE,TaskMonitor.DUMMY,consumer);
|
|
39
58
|
if(!sha.equals(program.getExecutableSHA256()))throw new SecurityException("Native source changed");
|
|
40
59
|
if(!op.equals("migration-probe")&&!program.getOptions("Insight").getString("Publication Engine","").equals("native-checkout-v1"))throw new InsightNativeMigration.Required();
|
|
41
|
-
|
|
60
|
+
// Only a migration compares bytes; a version is otherwise the one that was asked for by item and number.
|
|
61
|
+
if(q.has("bytes")&&q.get("bytes").getAsBoolean()&&q.has("fingerprint")&&!fingerprint.equals(q.get("fingerprint").getAsString()))throw new SecurityException("Exact native buffers differ");
|
|
42
62
|
result.put("state","verified");result.put("version",version);result.put("fileId",item.getFileID());result.put("fingerprint",fingerprint);
|
|
43
63
|
if(op.equals("migration-probe")){result.put("content",InsightNativeFingerprint.content(program));result.put("engine",program.getOptions("Insight").getString("Publication Engine",""));result.put("programIdentity",InsightNativeMigration.programIdentity(program));var functions=program.getFunctionManager().getFunctions(true);int samples=0;String sample=null;
|
|
44
64
|
while(functions.hasNext()&&samples++<1000){var f=functions.next();var block=program.getMemory().getBlock(f.getEntryPoint());if(!f.isThunk()&&block!=null&&block.isInitialized()&&block.isExecute()){if(sample==null)sample=f.getEntryPoint().toString();if(program.getReferenceManager().getReferencesTo(f.getEntryPoint()).hasNext()){sample=f.getEntryPoint().toString();break;}}}result.put("sampleFunction",sample);
|
|
@@ -51,7 +71,10 @@ public final class InsightNativeRead {
|
|
|
51
71
|
}finally{if(program!=null)program.release(consumer);else db.close();}
|
|
52
72
|
var after=repository.getItem("/",name);
|
|
53
73
|
if(after==null||!after.getFileID().equals(item.getFileID())||after.getVersion()<version)throw new SecurityException("Native item changed while reading its exact version");
|
|
54
|
-
repository.disconnect();server.disconnect();
|
|
55
|
-
}catch(Throwable failure){failure.printStackTrace(System.err);
|
|
74
|
+
repository.disconnect();server.disconnect();server=null;return result;
|
|
75
|
+
}catch(Throwable failure){failure.printStackTrace(System.err);
|
|
76
|
+
if(failure instanceof Error)poisoned=true;
|
|
77
|
+
try{if(server!=null)server.disconnect();}catch(Throwable cleanup){poisoned=true;}
|
|
78
|
+
return unknown(failure);}
|
|
56
79
|
}
|
|
57
80
|
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import com.google.gson.*;
|
|
2
|
+
import ghidra.GhidraApplicationLayout;
|
|
3
|
+
import ghidra.framework.*;
|
|
4
|
+
import java.io.*;
|
|
5
|
+
import java.nio.charset.StandardCharsets;
|
|
6
|
+
import java.nio.file.Path;
|
|
7
|
+
import java.util.*;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Long-lived trusted native service owned by one coordinator process. Ghidra is initialized once; then each
|
|
11
|
+
* stdin line names one owned request file and receives one stdout line with its result, strictly in order.
|
|
12
|
+
* The publisher role runs native checkout operations with publisher credentials, the reader role runs
|
|
13
|
+
* independent reads with reader credentials; agent code never runs here. Each request keeps the one-shot
|
|
14
|
+
* helper's semantics (its own server connection, journals and result shape). End of input stops the service.
|
|
15
|
+
*/
|
|
16
|
+
public final class InsightNativeService {
|
|
17
|
+
public static void main(String[] args){
|
|
18
|
+
var output=new PrintStream(new FileOutputStream(FileDescriptor.out),true,StandardCharsets.UTF_8);System.setOut(System.err);
|
|
19
|
+
String role=args.length==1?args[0]:"";
|
|
20
|
+
try{
|
|
21
|
+
if(!role.equals("publisher")&&!role.equals("reader"))throw new IllegalArgumentException("Native service role required");
|
|
22
|
+
if(role.equals("publisher"))InsightNativeCheckout.initialize();
|
|
23
|
+
else if(!Application.isInitialized())Application.initializeApplication(new GhidraApplicationLayout(),new HeadlessGhidraApplicationConfiguration());
|
|
24
|
+
}catch(Throwable failure){failure.printStackTrace(System.err);output.println("{\"state\":\"failed\"}");System.exit(1);}
|
|
25
|
+
output.println("{\"state\":\"ready\",\"role\":\""+role+"\",\"pid\":"+ProcessHandle.current().pid()+"}");
|
|
26
|
+
try(var input=new BufferedReader(new InputStreamReader(System.in,StandardCharsets.UTF_8))){
|
|
27
|
+
for(String line;(line=input.readLine())!=null;){
|
|
28
|
+
String id=null;Path request;
|
|
29
|
+
try{JsonObject q=JsonParser.parseString(line).getAsJsonObject();id=q.get("id").getAsString();request=Path.of(q.get("request").getAsString());}
|
|
30
|
+
catch(RuntimeException malformed){
|
|
31
|
+
// Answer with the id when one was readable, so the caller reports this request instead of waiting.
|
|
32
|
+
output.println(id==null?"{\"error\":\"malformed\"}":InsightNativeCheckout.GSON.toJson(Map.of("id",id,"result",Map.of("state","unknown","diagnostic","Malformed","reason","Malformed native service request","code","unknown"))));continue;}
|
|
33
|
+
Map<String,Object> result=role.equals("publisher")?InsightNativeCheckout.handle(request):InsightNativeRead.handle(request);
|
|
34
|
+
// A doubtful JVM state never serves another request: the reply announces the exit, so the caller
|
|
35
|
+
// never sends a queued request here, and the next one starts a fresh service.
|
|
36
|
+
boolean closing=InsightNativeCheckout.poisoned||InsightNativeRead.poisoned;
|
|
37
|
+
output.println(InsightNativeCheckout.GSON.toJson(closing?Map.of("id",id,"result",result,"closing",true):Map.of("id",id,"result",result)));
|
|
38
|
+
if(closing)break;
|
|
39
|
+
}
|
|
40
|
+
}catch(Throwable failure){failure.printStackTrace(System.err);}
|
|
41
|
+
System.exit(0);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -11,19 +11,30 @@ public class InsightNativeView extends GhidraScript {
|
|
|
11
11
|
public void run()throws Exception {
|
|
12
12
|
JsonObject q=JsonParser.parseString(new String(Base64.getDecoder().decode(getScriptArgs()[0]),java.nio.charset.StandardCharsets.UTF_8)).getAsJsonObject();
|
|
13
13
|
if(currentProgram==null||currentProgram.isChanged())throw new IllegalStateException("Saved program required");
|
|
14
|
-
String fingerprint=
|
|
14
|
+
String fingerprint=saved();
|
|
15
15
|
if(q.has("expected")&&!fingerprint.equals(q.get("expected").getAsString()))throw new IllegalStateException("Saved native view changed");
|
|
16
16
|
Object value;
|
|
17
17
|
switch(q.get("operation").getAsString()) {
|
|
18
|
-
case "fingerprint":
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
18
|
+
case "fingerprint":value=saved(fingerprint);break;
|
|
19
|
+
// One pass for a save receipt: identity plus the inspected metadata of the same exact bytes.
|
|
20
|
+
case "capture":{
|
|
21
|
+
Map<String,Object> receipt=new LinkedHashMap<>(saved(fingerprint));
|
|
22
|
+
receipt.put("inspected",InsightSnapshotInspect.inspect((ProgramDB)currentProgram,q.getAsJsonObject("parameters")));
|
|
23
|
+
value=receipt;break;
|
|
24
|
+
}
|
|
22
25
|
case "fields":value=InsightSnapshotFields.inspect((ProgramDB)currentProgram,q.getAsJsonArray("selectors"));break;
|
|
23
26
|
case "inspect":value=InsightSnapshotInspect.inspect((ProgramDB)currentProgram,q.getAsJsonObject("parameters"));break;
|
|
24
27
|
default:throw new IllegalArgumentException();
|
|
25
28
|
}
|
|
26
|
-
|
|
29
|
+
// Still unchanged and still the same saved source as at the start.
|
|
30
|
+
if(!fingerprint.equals(saved()))throw new IllegalStateException("Native view changed while inspecting");
|
|
27
31
|
println("INSIGHT_NATIVE:"+new GsonBuilder().serializeNulls().create().toJson(Map.of("value",value)));
|
|
28
32
|
}
|
|
33
|
+
/** The saved state as Ghidra identifies it. A worker built from other helper sources is replaced before it is used. */
|
|
34
|
+
private String saved()throws Exception{return InsightNativeFingerprint.saved(currentProgram);}
|
|
35
|
+
private Map<String,Object> saved(String fingerprint){
|
|
36
|
+
var c=((ProgramDB)currentProgram).getChanges();
|
|
37
|
+
return Map.of("fingerprint",fingerprint,"modified",currentProgram.getDomainFile().isCheckedOut()&¤tProgram.getDomainFile().modifiedSinceCheckout(),"version",currentProgram.getDomainFile().getVersion(),"fileId",currentProgram.getDomainFile().getFileID(),
|
|
38
|
+
"dataTypeChanges",c.getDataTypeChanges(),"dataTypeAdditions",c.getDataTypeAdditions(),"symbolChanges",c.getSymbolChanges(),"symbolAdditions",c.getSymbolAdditions());
|
|
39
|
+
}
|
|
29
40
|
}
|