@eyeauras/insight-cli 0.7.0 → 0.8.0

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.
Files changed (117) hide show
  1. package/.cli-package-build.json +1 -1
  2. package/SKILL.md +1 -1
  3. package/dist/src/activity-audit.d.ts +7 -0
  4. package/dist/src/activity-audit.js +14 -4
  5. package/dist/src/analysis-storage.d.ts +5 -1
  6. package/dist/src/analysis-storage.js +9 -2
  7. package/dist/src/audit-retention.d.ts +8 -2
  8. package/dist/src/audit-retention.js +68 -7
  9. package/dist/src/cli.js +19 -5
  10. package/dist/src/context-diagnostics.d.ts +1 -1
  11. package/dist/src/context-diagnostics.js +10 -2
  12. package/dist/src/contexts.d.ts +118 -10
  13. package/dist/src/contexts.js +851 -199
  14. package/dist/src/debugger.js +2 -1
  15. package/dist/src/diagnostic-error.js +1 -1
  16. package/dist/src/inline-script.js +3 -4
  17. package/dist/src/lifecycle.d.ts +11 -0
  18. package/dist/src/lifecycle.js +34 -6
  19. package/dist/src/native-inputs.d.ts +6 -0
  20. package/dist/src/native-inputs.js +30 -6
  21. package/dist/src/native-queries.js +1 -6
  22. package/dist/src/native-service.d.ts +40 -0
  23. package/dist/src/native-service.js +406 -0
  24. package/dist/src/research.d.ts +29 -1
  25. package/dist/src/research.js +106 -27
  26. package/dist/src/server.d.ts +38 -1
  27. package/dist/src/server.js +160 -12
  28. package/dist/src/storage-gc.js +1 -1
  29. package/dist/src/sync-policy.js +2 -1
  30. package/dist/src/timed-backend.js +8 -0
  31. package/dist/src/timing-report.d.ts +32 -0
  32. package/dist/src/timing-report.js +74 -0
  33. package/dist/src/tool-runtime/identity.js +86 -1
  34. package/dist/src/tool-runtime/supervisor.js +6 -5
  35. package/dist/src/transport.d.ts +35 -0
  36. package/dist/src/transport.js +77 -7
  37. package/dist/src/unresolved-guidance.d.ts +46 -0
  38. package/dist/src/unresolved-guidance.js +55 -0
  39. package/dist/src/windbg.d.ts +1 -1
  40. package/dist/src/worker-lease.d.ts +17 -0
  41. package/dist/src/worker-lease.js +50 -0
  42. package/dist/src/workspace.d.ts +3 -9
  43. package/dist/src/workspace.js +9 -41
  44. package/package.json +1 -1
  45. package/references/native/InsightHeadlessMain.java +9 -2
  46. package/references/native/InsightNativeCheckout.java +113 -43
  47. package/references/native/InsightNativeFingerprint.java +28 -1
  48. package/references/native/InsightNativeRead.java +32 -9
  49. package/references/native/InsightNativeService.java +43 -0
  50. package/references/native/InsightNativeView.java +17 -6
  51. package/references/native/InsightOwnedScripts.java +170 -0
  52. package/references/native/InsightWorkerLease.java +132 -0
  53. package/references/recovery.md +68 -3
  54. package/references/research.md +38 -4
  55. package/references/setup.md +5 -1
  56. package/skill-bundle/insight-artifacts/SKILL.md +1 -1
  57. package/skill-bundle/insight-artifacts/references/recovery.md +68 -3
  58. package/skill-bundle/insight-binary/SKILL.md +1 -1
  59. package/skill-bundle/insight-capture/SKILL.md +1 -1
  60. package/skill-bundle/insight-cli/SKILL.md +1 -1
  61. package/skill-bundle/insight-cli/references/recovery.md +68 -3
  62. package/skill-bundle/insight-cli/references/setup.md +5 -1
  63. package/skill-bundle/insight-die/SKILL.md +1 -1
  64. package/skill-bundle/insight-dnspy/SKILL.md +1 -1
  65. package/skill-bundle/insight-dotnet-dump/SKILL.md +1 -1
  66. package/skill-bundle/insight-dotnet-stack/SKILL.md +1 -1
  67. package/skill-bundle/insight-dotnet-trace/SKILL.md +1 -1
  68. package/skill-bundle/insight-frida/SKILL.md +1 -1
  69. package/skill-bundle/insight-ghidra/SKILL.md +1 -1
  70. package/skill-bundle/insight-ghidra/references/recovery.md +68 -3
  71. package/skill-bundle/insight-ghidra/references/research.md +38 -4
  72. package/skill-bundle/insight-ghidra/references/setup.md +5 -1
  73. package/skill-bundle/insight-ilspy/SKILL.md +1 -1
  74. package/skill-bundle/insight-interop/SKILL.md +1 -1
  75. package/skill-bundle/insight-lldb/SKILL.md +1 -1
  76. package/skill-bundle/insight-llvm/SKILL.md +1 -1
  77. package/skill-bundle/insight-managed-heap/SKILL.md +1 -1
  78. package/skill-bundle/insight-managed-metadata/SKILL.md +1 -1
  79. package/skill-bundle/insight-mitmproxy/SKILL.md +1 -1
  80. package/skill-bundle/insight-overview/SKILL.md +1 -1
  81. package/skill-bundle/insight-procmon/SKILL.md +1 -1
  82. package/skill-bundle/insight-re/SKILL.md +1 -1
  83. package/skill-bundle/insight-re/references/recovery.md +68 -3
  84. package/skill-bundle/insight-sevenzip/SKILL.md +1 -1
  85. package/skill-bundle/insight-strace/SKILL.md +1 -1
  86. package/skill-bundle/insight-tshark/SKILL.md +1 -1
  87. package/skill-bundle/insight-windbg/SKILL.md +1 -1
  88. package/skill-bundle/manifest.json +1 -1
  89. package/skills/insight-artifacts/SKILL.md +1 -1
  90. package/skills/insight-artifacts/references/recovery.md +68 -3
  91. package/skills/insight-binary/SKILL.md +1 -1
  92. package/skills/insight-capture/SKILL.md +1 -1
  93. package/skills/insight-die/SKILL.md +1 -1
  94. package/skills/insight-dnspy/SKILL.md +1 -1
  95. package/skills/insight-dotnet-dump/SKILL.md +1 -1
  96. package/skills/insight-dotnet-stack/SKILL.md +1 -1
  97. package/skills/insight-dotnet-trace/SKILL.md +1 -1
  98. package/skills/insight-frida/SKILL.md +1 -1
  99. package/skills/insight-ghidra/SKILL.md +1 -1
  100. package/skills/insight-ghidra/references/recovery.md +68 -3
  101. package/skills/insight-ghidra/references/research.md +38 -4
  102. package/skills/insight-ghidra/references/setup.md +5 -1
  103. package/skills/insight-ilspy/SKILL.md +1 -1
  104. package/skills/insight-interop/SKILL.md +1 -1
  105. package/skills/insight-lldb/SKILL.md +1 -1
  106. package/skills/insight-llvm/SKILL.md +1 -1
  107. package/skills/insight-managed-heap/SKILL.md +1 -1
  108. package/skills/insight-managed-metadata/SKILL.md +1 -1
  109. package/skills/insight-mitmproxy/SKILL.md +1 -1
  110. package/skills/insight-overview/SKILL.md +1 -1
  111. package/skills/insight-procmon/SKILL.md +1 -1
  112. package/skills/insight-re/SKILL.md +1 -1
  113. package/skills/insight-re/references/recovery.md +68 -3
  114. package/skills/insight-sevenzip/SKILL.md +1 -1
  115. package/skills/insight-strace/SKILL.md +1 -1
  116. package/skills/insight-tshark/SKILL.md +1 -1
  117. package/skills/insight-windbg/SKILL.md +1 -1
@@ -62,8 +62,6 @@ export interface NativeCheckout {
62
62
  request: string;
63
63
  message: string;
64
64
  };
65
- /** Saved buffers proved to hold no private work although Ghidra rewrote them on open; the release accepts only these. */
66
- opened?: string;
67
65
  }
68
66
  export interface GhidraContext extends Scope {
69
67
  /** Internal storage key, never a caller's backend selector. */
@@ -190,15 +188,11 @@ export declare class Workspace {
190
188
  private giveUp;
191
189
  /** An abandoned or otherwise unknown terminal effect keeps all of its native evidence. */
192
190
  uncertainOutcome(scope: Scope): boolean;
193
- /** Receipt-only comparison; native state is verified separately before any release. */
194
- unchangedNative(context: GhidraContext): boolean;
195
191
  /**
196
- * Saved buffers hold no private work when they equal the shared base, or equal what Ghidra itself wrote when a
197
- * worker opened a pristine checkout of that base. Equal bytes are the proof; what Ghidra rewrote is irrelevant.
192
+ * Whether the working copy holds no private work, as Ghidra itself reported it when the copy was last saved or
193
+ * observed (`modifiedSinceCheckout`). Native state is observed again before any release.
198
194
  */
199
- unchangedBuffers(target: string, base: Record<string, unknown>, fingerprint: unknown): boolean;
200
- /** Saved buffers of pristine checkouts of one shared version, as each was left by its worker's own open. */
201
- openedReferences(target: string, base: Record<string, unknown>): Set<string>;
195
+ unchangedNative(context: GhidraContext): boolean;
202
196
  /** Another context's unresolved operation may still need this checkout's private view. */
203
197
  checkoutReferenced(context: GhidraContext, root?: string | undefined): boolean;
204
198
  /** Applied requests keep their results; their superseded before-images are not recovery inputs. */
@@ -1,6 +1,6 @@
1
1
  import { DatabaseSync } from 'node:sqlite';
2
2
  import { auditEvent, bindAudit, auditHash } from './activity-audit.js';
3
- import { chmodSync, mkdirSync, readFileSync, readdirSync, realpathSync } from 'node:fs';
3
+ import { chmodSync, mkdirSync, readFileSync, realpathSync } from 'node:fs';
4
4
  import { basename, join } from 'node:path';
5
5
  import { randomUUID } from 'node:crypto';
6
6
  import { Artifacts } from './artifacts.js';
@@ -336,55 +336,23 @@ export class Workspace {
336
336
  return this.db.prepare("SELECT data FROM requests WHERE context=? AND state='failed'").all(this.context(scope).id).map(row => JSON.parse(String(row.data)))
337
337
  .some(row => !row.dropped && row.result?.outcome === 'unknown');
338
338
  }
339
- /** Receipt-only comparison; native state is verified separately before any release. */
339
+ /**
340
+ * Whether the working copy holds no private work, as Ghidra itself reported it when the copy was last saved or
341
+ * observed (`modifiedSinceCheckout`). Native state is observed again before any release.
342
+ */
340
343
  unchangedNative(context) {
341
344
  if (context.nativeCheckout?.state === 'verified')
342
345
  return true;
343
- if (context.workingSnapshot?.kind !== 'native' || context.baseSnapshot?.kind !== 'native')
346
+ if (context.workingSnapshot?.kind !== 'native')
344
347
  return false;
345
348
  try {
346
- const [local, base] = [context.workingSnapshot, context.baseSnapshot].map(value => JSON.parse(readFileSync(this.artifacts.path(value), 'utf8')));
347
- return this.unchangedBuffers(context.target, base, local.fingerprint);
349
+ const local = JSON.parse(readFileSync(this.artifacts.path(context.workingSnapshot), 'utf8'));
350
+ return local.source === 'checkout' && local.modified === false;
348
351
  }
349
352
  catch {
350
353
  return false;
351
354
  }
352
355
  }
353
- /**
354
- * Saved buffers hold no private work when they equal the shared base, or equal what Ghidra itself wrote when a
355
- * worker opened a pristine checkout of that base. Equal bytes are the proof; what Ghidra rewrote is irrelevant.
356
- */
357
- unchangedBuffers(target, base, fingerprint) {
358
- if (typeof fingerprint !== 'string' || !/^[a-f0-9]{64}$/.test(fingerprint) || base.source !== 'server' || typeof base.fingerprint !== 'string')
359
- return false;
360
- return fingerprint === base.fingerprint || this.openedReferences(target, base).has(fingerprint);
361
- }
362
- /** Saved buffers of pristine checkouts of one shared version, as each was left by its worker's own open. */
363
- openedReferences(target, base) {
364
- const revision = Number(base.version);
365
- const found = new Set(), root = join(this.directory, 'ghidra-native', 'shared-views', id(target), 'opened');
366
- let names;
367
- try {
368
- names = readdirSync(root);
369
- }
370
- catch {
371
- return found;
372
- }
373
- for (const name of names) {
374
- const match = /^v(\d+)-([a-f0-9]{64})\.json$/.exec(name);
375
- if (!match || Number(match[1]) !== revision)
376
- continue;
377
- try {
378
- const row = JSON.parse(readFileSync(join(root, name), 'utf8'));
379
- // Earlier receipts inferred pristine state from control metadata alone; they cannot authorize deletion.
380
- if (row.schema === 2 && row.preOpen?.fingerprint === base.fingerprint && row.preOpen.fileId === base.fileId && row.preOpen.baseVersion === revision &&
381
- Number.isSafeInteger(row.preOpen.checkoutId) && row.preOpen.checkoutId >= 0 && row.target === target && row.version === revision && row.fileId === base.fileId && row.base === base.fingerprint && row.origin === base.origin && row.repository === base.repository && row.opened === match[2])
382
- found.add(match[2]);
383
- }
384
- catch { }
385
- }
386
- return found;
387
- }
388
356
  /** Another context's unresolved operation may still need this checkout's private view. */
389
357
  checkoutReferenced(context, root = context.nativeCheckout?.root) {
390
358
  const seen = new Set();
@@ -702,7 +670,7 @@ export class Workspace {
702
670
  const context = this.context(scope);
703
671
  if (checkout.state !== 'verified' || stable(context.nativeCheckout) !== stable(checkout))
704
672
  fail('binding', 'Native disposal ownership changed before retention.');
705
- const { opened, ...binding } = checkout, active = { ...binding, state: 'active' };
673
+ const active = { ...checkout, state: 'active' };
706
674
  this.knownSnapshot(snapshot);
707
675
  const saved = object(JSON.parse(readFileSync(this.artifacts.path(snapshot), 'utf8')));
708
676
  if (snapshot.kind !== 'native' || saved.engine !== 'native-checkout-v1' || saved.source !== 'checkout' || stable(saved.checkout) !== stable(active) ||
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eyeauras/insight-cli",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "type": "module",
5
5
  "description": "Agent-facing durable sessions and isolated Ghidra research contexts",
6
6
  "main": "./dist/src/index.js",
@@ -3,9 +3,16 @@ import com.xebyte.headless.GhidraMCPHeadlessServer;
3
3
 
4
4
  /** Preserve caller-selected names in the owned facade, including structure fields. */
5
5
  class InsightHeadlessMain {
6
- public static void main(String[] args) {
6
+ public static void main(String[] args) throws Exception {
7
7
  insight.nativecheckout.InsightOfflineAuthenticator.install();
8
+ InsightWorkerLease.start();
8
9
  NamingPolicy.getInstance().setStrictNamingEnforcement(false, "insight facade");
9
- GhidraMCPHeadlessServer.main(args);
10
+ // The steps of GhidraMCPHeadlessServer.main, keeping the instance so that owned helper scripts can run in-process.
11
+ GhidraMCPHeadlessServer server=new GhidraMCPHeadlessServer();
12
+ InsightOwnedScripts.bind(server);
13
+ try{server.launch(new ghidra.GhidraApplicationLayout(),args);}
14
+ catch(Exception failure){
15
+ System.err.println("Failed to launch headless server: "+failure.getMessage());failure.printStackTrace();System.exit(1);
16
+ }
10
17
  }
11
18
  }
@@ -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.of(p),"version",file.getVersion(),"fileId",file.getFileID(),
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
- static String authorized(JsonObject q){return text(q,q.has("opened")?"opened":"fingerprint");}
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
- if(!Objects.equals(receipt.get("checkoutId"),q.get("checkoutId"))||!Objects.equals(receipt.get("fingerprint"),q.get("fingerprint"))||
65
- !Objects.equals(receipt.get("version"),q.get("verifiedVersion")))return false;
66
- // Completed older receipts already ended the checkout. Preserve their deletion-only recovery.
67
- if(!receipt.has("savedFingerprint")&&!receipt.has("fileId"))return true;
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,Map<String,Object> saved){
72
- return receipt.has("fileId")&&receipt.has("savedFingerprint")&&Objects.equals(receipt.get("state"),new JsonPrimitive("release_intent"))&&sameRelease(receipt,q)&&
73
- Objects.equals(saved.get("fileId"),text(receipt,"fileId"))&&Objects.equals(saved.get("fingerprint"),text(receipt,"savedFingerprint"));
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);Project project=null;GhidraServerManager server=null;
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
- require(args.length==1,"Owned request required");
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();output.println(GSON.toJson(out));System.exit(0);
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();output.println("{\"state\":\""+(operation.equals("drop")?"dropped":"released")+"\"}");System.exit(0);
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
- saved(file,owner);require(file.checkout(false,MONITOR),"Native checkout denied");
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
- require(Objects.equals(actual.get("fileId"),backupsAfter.get(keep))&&Objects.equals(actual.get("fingerprint"),before.get("fingerprint")),"Native discard backup differs from saved private buffers");
301
- out.put("retainedKeepFile",keep);out.put("disposableBackups",Map.of(keep,Map.of("schema",2,"fileId",actual.get("fileId"),"fingerprint",actual.get("fingerprint"))));
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(before.equals(saved(file,owner))&&file.getCheckoutStatus().getCheckoutId()==checkout&&file.getCheckoutStatus().getCheckoutVersion()==base,"Backup refusal did not preserve local state");
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(before.equals(saved(file,owner))&&file.getCheckoutStatus().getCheckoutId()==checkout&&file.getCheckoutStatus().getCheckoutVersion()==base,"Native conflict did not preserve local state");
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(before.equals(saved(file,owner))&&Arrays.stream(repository.getVersions("/",name)).noneMatch(v->("insight native "+request).equals(v.getComment())),"Check-in outcome is unknown");
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(),"fingerprint",text(q,"fingerprint"),
356
- "fileId",text(q,"fileId"),"savedFingerprint",authorized(q)));
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
- require(!q.has("opened")||q.has("openedVerified")&&q.get("openedVerified").getAsBoolean(),"Pristine-open proof is unverified; private work must be retained");
359
- require(file.getCheckoutStatus().getCheckoutVersion()==q.get("verifiedVersion").getAsInt()&&!file.canRecover(),"Unpublished native work must be retained");
360
- Object local=saved(file,owner).get("fingerprint");
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,saved(file,owner)),"Unproved surviving native file must be retained");
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);require(InsightNativeFingerprint.of(p).equals(text(q,"fingerprint")),"Native export changed saved buffers");
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.put("saved",saved(file,owner));out.put("modified",file.modifiedSinceCheckout());out.put("fileId",file.getFileID());out.put("checkedOut",file.isCheckedOut());
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
- output.println(GSON.toJson(out));System.exit(0);
398
- }catch(Throwable failure){failure.printStackTrace(System.err);if(project!=null)project.close();if(server!=null)server.disconnect();
399
- output.println(GSON.toJson(Map.of("state","unknown","diagnostic",failure.getClass().getSimpleName(),"reason",Objects.toString(failure.getMessage(),failure.toString()),"code",failure instanceof InsightNativeMigration.Required?"migration":"unknown")));System.exit(0);}
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
- /** Saved native buffers only; never fabricates or replaces native ancestry/change sets. */
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(Path.of(args[0]))).getAsJsonObject();
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
- Application.initializeApplication(new GhidraApplicationLayout(),new HeadlessGhidraApplicationConfiguration());
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();output.println("{\"state\":\"absent\"}");System.exit(0);}
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
- String fingerprint=InsightNativeFingerprint.of(db);
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
- if(q.has("fingerprint")&&!fingerprint.equals(q.get("fingerprint").getAsString()))throw new SecurityException("Exact native buffers differ");
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();output.println(new GsonBuilder().serializeNulls().create().toJson(result));System.exit(0);
55
- }catch(Throwable failure){failure.printStackTrace(System.err);output.println(new Gson().toJson(Map.of("state","unknown","diagnostic",failure.getClass().getSimpleName(),"reason",Objects.toString(failure.getMessage(),failure.toString()),"code",failure instanceof InsightNativeMigration.Required?"migration":"unknown")));System.exit(0);}
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
  }