scientific-method-engine 19.9.0__tar.gz → 19.10.0__tar.gz

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 (97) hide show
  1. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/PKG-INFO +2 -1
  2. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/README.md +1 -0
  3. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/pyproject.toml +1 -1
  4. scientific_method_engine-19.10.0/src/scientific_method_engine/ghidra/RunQueryPlan.java +122 -0
  5. scientific_method_engine-19.10.0/src/scientific_method_engine/ghidra/scientificmethod/QueryBatch.java +151 -0
  6. scientific_method_engine-19.10.0/tests/java/QueryBatchHarness.java +79 -0
  7. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/.gitignore +0 -0
  8. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/LICENSE +0 -0
  9. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/__init__.py +0 -0
  10. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/__main__.py +0 -0
  11. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/cli.py +0 -0
  12. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/ClearNoReturnFunctions.java +0 -0
  13. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/CreateFunctions.java +0 -0
  14. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/ExportBoundedFlow.java +0 -0
  15. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/ExportCallEdges.java +0 -0
  16. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/ExportFunctionFingerprints.java +0 -0
  17. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/ExportFunctionInventory.java +0 -0
  18. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/MergeFallThroughFragment.java +0 -0
  19. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/RecoverCitedFunctions.java +0 -0
  20. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/RepairReturningCallers.java +0 -0
  21. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/ReportCallArguments.java +0 -0
  22. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/ReportCallPaths.java +0 -0
  23. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/ReportCallSitesWithScalars.java +0 -0
  24. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/ReportCallsToRange.java +0 -0
  25. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/ReportConstantFirstArgumentCalls.java +0 -0
  26. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/ReportDataBytes.java +0 -0
  27. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/ReportDecompileMatches.java +0 -0
  28. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/ReportDecompileWindow.java +0 -0
  29. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/ReportFilePatternInMemory.java +0 -0
  30. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/ReportFirstArgumentCallSummary.java +0 -0
  31. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/ReportFunctionScalarConstants.java +0 -0
  32. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/ReportFunctionSummary.java +0 -0
  33. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/ReportInstructionContext.java +0 -0
  34. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/ReportInstructionWindow.java +0 -0
  35. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/ReportMemoryBlockForFileOffset.java +0 -0
  36. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/ReportMemoryBlocks.java +0 -0
  37. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/ReportRandomnessCandidates.java +0 -0
  38. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/ReportRangeBoundaries.java +0 -0
  39. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/ReportReferences.java +0 -0
  40. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/ReportScalarConstants.java +0 -0
  41. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/ReportStringReferences.java +0 -0
  42. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/ReportSymbolReferences.java +0 -0
  43. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/scientificmethod/FirstArgumentLookBack.java +0 -0
  44. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/scientificmethod/InstructionStart.java +0 -0
  45. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/scientificmethod/OperandConstants.java +0 -0
  46. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/ghidra/scientificmethod/Xxh3.java +0 -0
  47. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/x86/__init__.py +0 -0
  48. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/x86/argument_frames.py +0 -0
  49. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/x86/derived_counts.py +0 -0
  50. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/x86/dispatch.py +0 -0
  51. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/x86/effect_order.py +0 -0
  52. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/x86/image.py +0 -0
  53. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/x86/inventory.py +0 -0
  54. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/x86/loops.py +0 -0
  55. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/x86/machine.py +0 -0
  56. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/x86/memory_scopes.py +0 -0
  57. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/x86/pcode.py +0 -0
  58. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/x86/pcode_backend.py +0 -0
  59. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/x86/pe.py +0 -0
  60. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/x86/ranges.py +0 -0
  61. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/x86/reach.py +0 -0
  62. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/x86/relational.py +0 -0
  63. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/x86/reports.py +0 -0
  64. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/x86/result_flow.py +0 -0
  65. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/x86/scan_index.py +0 -0
  66. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/x86/table_bounds.py +0 -0
  67. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/x86/trace.py +0 -0
  68. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/src/scientific_method_engine/x86/values.py +0 -0
  69. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/oracle.py +0 -0
  70. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/test_config_encoding.py +0 -0
  71. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/test_continuation_budget.py +0 -0
  72. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/test_derived_counts.py +0 -0
  73. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/test_dispatch.py +0 -0
  74. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/test_effect_order.py +0 -0
  75. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/test_enter_frames.py +0 -0
  76. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/test_entry_frame.py +0 -0
  77. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/test_indirect_far_transfers.py +0 -0
  78. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/test_interrupt_models.py +0 -0
  79. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/test_inventory_check.py +0 -0
  80. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/test_join_terms.py +0 -0
  81. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/test_loops.py +0 -0
  82. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/test_memory_scopes.py +0 -0
  83. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/test_nested_frame_request.py +0 -0
  84. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/test_oracle.py +0 -0
  85. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/test_pe.py +0 -0
  86. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/test_ranges.py +0 -0
  87. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/test_reach.py +0 -0
  88. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/test_relational_controls.py +0 -0
  89. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/test_return_checks.py +0 -0
  90. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/test_scan_index.py +0 -0
  91. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/test_successor_rule.py +0 -0
  92. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/test_table_bounds.py +0 -0
  93. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/test_table_continuations.py +0 -0
  94. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/test_term_limit.py +0 -0
  95. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/test_upstream_gaps.py +0 -0
  96. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/test_volatile_memory.py +0 -0
  97. {scientific_method_engine-19.9.0 → scientific_method_engine-19.10.0}/tests/test_x86.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: scientific-method-engine
3
- Version: 19.9.0
3
+ Version: 19.10.0
4
4
  Summary: Bounded instruction-derived x86 evidence reports for segmented MZ/FBOV and PE32/i386 code.
5
5
  Project-URL: Source, https://github.com/kibertoad/refurbished-dinosaurs-toolkit/tree/main/packages/scientific-method-engine
6
6
  Author: kibertoad
@@ -98,6 +98,7 @@ Exporting for comparison (each writes one file and refuses to overwrite where no
98
98
  | `ExportBoundedFlow` | entry where an instruction starts, instruction limit (1..10000, the most instruction records exported), output path under `analysis/original/` | instruction metadata of one bounded flow as JSON, with `limitReached` (the walk stopped at the limit with flow left unread) and `noInstruction` (flow targets where no instruction starts). An entry where no instruction starts fails the script and writes nothing |
99
99
  | `ExportFunctionInventory` | output path `coverage/<build>/<file>.tsv` (must not exist, nor its `.provenance.tsv` and `.regions.tsv`), identifier of the database snapshot the export reads | the function inventory that `standard-coverage` and `inventory-check` read: each function's start in the Standard's notation, its body size and, for a body that is not one range from the start, its ranges; and beside it a `.provenance.tsv` with the imported file's `xxh3` and SHA-256, the Ghidra version, the snapshot and the SHA-256 of the script and of its Xxh3 helper; and a `.regions.tsv` that counts the instruction, defined-data and undefined bytes of each executable block, in all and outside every body, with rows for body bytes outside those blocks and for starts where no instruction starts. A body or executable block it cannot place in the notation fails the export, which then writes nothing ([Exporting a function inventory](https://github.com/kibertoad/refurbished-dinosaurs-toolkit/blob/main/docs/ghidra-workflow.md#exporting-a-function-inventory)) |
100
100
  | `ExportCallEdges` | output JSON path (must not exist), function limit (1..128), one or more function entries | the call and tail-jump edges of the functions Ghidra reaches breadth-first from the entries, with file offsets, Ghidra's flow type (after any flow override), `fallsThrough` (whether Ghidra continues to the next instruction at the site, after any fall-through override) and `fallsThroughTo`/`fallsThroughToAddress` (where a fall-through override sends Ghidra instead, or null), as the `ghidraCallEdges` input of `callees` |
101
+ | `RunQueryPlan` | local v1 plan JSON, new ignored output directory | one required source/project audit and 1..31 bounded read-only target queries in one loaded program; source/import SHA-256 checks, script fingerprints, per-target completion/rejection controls and explicit failed/limited/cancelled/not-run dispositions; see [query plans](https://github.com/kibertoad/refurbished-dinosaurs-toolkit/blob/main/docs/query-plans.md) |
101
102
  | `ExportFunctionFingerprints` | output TSV path (replaced only when the export completes) | per-function and per-instruction fingerprints with addresses normalized, for matching functions across versions |
102
103
 
103
104
  Repairing the analysis (these change the Ghidra program, so run them before reports and keep the
@@ -82,6 +82,7 @@ Exporting for comparison (each writes one file and refuses to overwrite where no
82
82
  | `ExportBoundedFlow` | entry where an instruction starts, instruction limit (1..10000, the most instruction records exported), output path under `analysis/original/` | instruction metadata of one bounded flow as JSON, with `limitReached` (the walk stopped at the limit with flow left unread) and `noInstruction` (flow targets where no instruction starts). An entry where no instruction starts fails the script and writes nothing |
83
83
  | `ExportFunctionInventory` | output path `coverage/<build>/<file>.tsv` (must not exist, nor its `.provenance.tsv` and `.regions.tsv`), identifier of the database snapshot the export reads | the function inventory that `standard-coverage` and `inventory-check` read: each function's start in the Standard's notation, its body size and, for a body that is not one range from the start, its ranges; and beside it a `.provenance.tsv` with the imported file's `xxh3` and SHA-256, the Ghidra version, the snapshot and the SHA-256 of the script and of its Xxh3 helper; and a `.regions.tsv` that counts the instruction, defined-data and undefined bytes of each executable block, in all and outside every body, with rows for body bytes outside those blocks and for starts where no instruction starts. A body or executable block it cannot place in the notation fails the export, which then writes nothing ([Exporting a function inventory](https://github.com/kibertoad/refurbished-dinosaurs-toolkit/blob/main/docs/ghidra-workflow.md#exporting-a-function-inventory)) |
84
84
  | `ExportCallEdges` | output JSON path (must not exist), function limit (1..128), one or more function entries | the call and tail-jump edges of the functions Ghidra reaches breadth-first from the entries, with file offsets, Ghidra's flow type (after any flow override), `fallsThrough` (whether Ghidra continues to the next instruction at the site, after any fall-through override) and `fallsThroughTo`/`fallsThroughToAddress` (where a fall-through override sends Ghidra instead, or null), as the `ghidraCallEdges` input of `callees` |
85
+ | `RunQueryPlan` | local v1 plan JSON, new ignored output directory | one required source/project audit and 1..31 bounded read-only target queries in one loaded program; source/import SHA-256 checks, script fingerprints, per-target completion/rejection controls and explicit failed/limited/cancelled/not-run dispositions; see [query plans](https://github.com/kibertoad/refurbished-dinosaurs-toolkit/blob/main/docs/query-plans.md) |
85
86
  | `ExportFunctionFingerprints` | output TSV path (replaced only when the export completes) | per-function and per-instruction fingerprints with addresses normalized, for matching functions across versions |
86
87
 
87
88
  Repairing the analysis (these change the Ghidra program, so run them before reports and keep the
@@ -5,7 +5,7 @@ build-backend = "hatchling.build"
5
5
  [project]
6
6
  name = "scientific-method-engine"
7
7
  # The release workflow writes the published version from the package's release tag.
8
- version = "19.9.0"
8
+ version = "19.10.0"
9
9
  description = "Bounded instruction-derived x86 evidence reports for segmented MZ/FBOV and PE32/i386 code."
10
10
  readme = "README.md"
11
11
  requires-python = ">=3.12"
@@ -0,0 +1,122 @@
1
+ // Runs bounded read-only queries in one audited, already-loaded Ghidra program.
2
+ // @category Restoration
3
+
4
+ import com.google.gson.Gson;
5
+ import com.google.gson.GsonBuilder;
6
+ import generic.jar.ResourceFile;
7
+ import ghidra.app.script.GhidraScript;
8
+ import ghidra.app.script.GhidraScriptUtil;
9
+ import ghidra.app.script.ScriptControls;
10
+ import ghidra.framework.Application;
11
+ import java.io.PrintWriter;
12
+ import java.nio.charset.StandardCharsets;
13
+ import java.nio.file.Files;
14
+ import java.nio.file.Path;
15
+ import java.security.MessageDigest;
16
+ import java.util.LinkedHashMap;
17
+ import java.util.List;
18
+ import java.util.Map;
19
+ import java.util.concurrent.CancellationException;
20
+ import scientificmethod.QueryBatch;
21
+
22
+ public class RunQueryPlan extends GhidraScript {
23
+ private static final class Plan {
24
+ int version;
25
+ String source;
26
+ String sourceSha256;
27
+ String snapshot;
28
+ QueryBatch.Query audit;
29
+ List<QueryBatch.Query> queries;
30
+ }
31
+
32
+ private String sha256(byte[] bytes) throws Exception {
33
+ return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
34
+ }
35
+
36
+ private String resourceSha256(ResourceFile resource) throws Exception {
37
+ try (var stream = resource.getInputStream()) { return sha256(stream.readAllBytes()); }
38
+ }
39
+
40
+ @Override
41
+ protected void run() throws Exception {
42
+ String[] args = getScriptArgs();
43
+ if (args.length != 2 || currentProgram == null) {
44
+ throw new IllegalArgumentException("Supply query-plan.json and a NEW local output directory with a loaded program.");
45
+ }
46
+ Path planPath = Path.of(args[0]).toAbsolutePath();
47
+ Path destination = Path.of(args[1]).toAbsolutePath();
48
+ if (Files.size(planPath) > 262144) throw new IllegalArgumentException("Plan exceeds 256 KiB.");
49
+ byte[] planBytes = Files.readAllBytes(planPath);
50
+ Gson gson = new GsonBuilder().setPrettyPrinting().create();
51
+ Plan plan = gson.fromJson(new String(planBytes, StandardCharsets.UTF_8), Plan.class);
52
+ if (plan == null || plan.version != 1 || plan.source == null || plan.sourceSha256 == null ||
53
+ !plan.sourceSha256.matches("[a-fA-F0-9]{64}") || plan.snapshot == null || plan.snapshot.isBlank() ||
54
+ plan.snapshot.length() > 256 || plan.queries == null || plan.queries.isEmpty()) {
55
+ throw new IllegalArgumentException("Invalid v1 query plan.");
56
+ }
57
+ List<QueryBatch.Query> all = QueryBatch.validate(plan.audit, plan.queries);
58
+ Path source = Path.of(plan.source);
59
+ if (!source.isAbsolute()) throw new IllegalArgumentException("The plan's source must be an absolute path.");
60
+ String sourceHash = sha256(Files.readAllBytes(source));
61
+ if (!sourceHash.equalsIgnoreCase(plan.sourceSha256) ||
62
+ !sourceHash.equalsIgnoreCase(currentProgram.getExecutableSHA256())) {
63
+ throw new IllegalArgumentException("Source/import identity mismatch; no query ran.");
64
+ }
65
+ Files.createDirectory(destination); // Never overwrite another run.
66
+ Map<String, Object> report = new LinkedHashMap<>();
67
+ report.put("version", 1);
68
+ report.put("planSha256", sha256(planBytes));
69
+ report.put("sourceSha256", sourceHash);
70
+ report.put("ghidra", Application.getApplicationVersion());
71
+ report.put("program", currentProgram.getDomainFile().getPathname());
72
+ report.put("snapshot", plan.snapshot);
73
+ report.put("requested", all);
74
+ report.put("language", currentProgram.getLanguageID().toString());
75
+ report.put("compiler", currentProgram.getCompilerSpec().getCompilerSpecID().toString());
76
+ report.put("status", "running");
77
+ ResourceFile runner = getSourceFile();
78
+ report.put("runnerSha256", resourceSha256(runner));
79
+ report.put("helperSha256", resourceSha256(new ResourceFile(runner.getParentFile(), "scientificmethod/QueryBatch.java")));
80
+ long modification = currentProgram.getModificationNumber();
81
+ report.put("modificationNumber", modification);
82
+ Map<String, String> scripts = new LinkedHashMap<>();
83
+ report.put("scripts", scripts);
84
+ Path reportPath = destination.resolve("report.json");
85
+ Files.writeString(reportPath, gson.toJson(report));
86
+ List<QueryBatch.Result> results = QueryBatch.run(plan.audit, plan.queries, (query, output, error) -> {
87
+ if (monitor.isCancelled()) throw new CancellationException();
88
+ ResourceFile scriptFile = GhidraScriptUtil.findScriptByName(query.script);
89
+ if (scriptFile == null) throw new IllegalArgumentException("Script not found: " + query.script);
90
+ scripts.put(query.id, resourceSha256(scriptFile));
91
+ PrintWriter out = new PrintWriter(output, true);
92
+ PrintWriter err = new PrintWriter(error, true);
93
+ GhidraScript script = GhidraScriptUtil.getProvider(scriptFile).getScriptInstance(scriptFile, err);
94
+ script.setScriptArgs(query.args);
95
+ // Pass on the .properties locations, as GhidraScript.runScript does for sub-scripts.
96
+ if (potentialPropertiesFileLocs != null) script.setPotentialPropertiesFileLocations(potentialPropertiesFileLocs);
97
+ try { script.execute(getState(), new ScriptControls(out, err, monitor)); }
98
+ catch (ghidra.util.exception.CancelledException exception) { throw new CancellationException(); }
99
+ finally {
100
+ out.flush();
101
+ err.flush();
102
+ // Checked after every target, failed or not, so the target that changed the
103
+ // program is the one that fails and no later target runs on the changed program.
104
+ if (currentProgram.getModificationNumber() != modification) {
105
+ throw new QueryBatch.Stop("Program changed by this target; later targets not run.");
106
+ }
107
+ }
108
+ });
109
+ report.put("results", results);
110
+ boolean sourceUnchanged;
111
+ try { sourceUnchanged = sourceHash.equals(sha256(Files.readAllBytes(source))); }
112
+ catch (java.io.IOException exception) { sourceUnchanged = false; }
113
+ boolean programUnchanged = currentProgram.getModificationNumber() == modification;
114
+ boolean completed = sourceUnchanged && programUnchanged && results.stream().allMatch(result -> result.status.equals("completed"));
115
+ report.put("sourceUnchanged", sourceUnchanged);
116
+ report.put("programUnchanged", programUnchanged);
117
+ report.put("status", completed ? "completed" : "incomplete");
118
+ Files.writeString(reportPath, gson.toJson(report));
119
+ if (!completed) throw new IllegalStateException("Query plan incomplete; inspect every target in " + reportPath);
120
+ println("Query plan completed: " + reportPath);
121
+ }
122
+ }
@@ -0,0 +1,151 @@
1
+ package scientificmethod;
2
+
3
+ import java.io.Writer;
4
+ import java.util.ArrayList;
5
+ import java.util.HashSet;
6
+ import java.util.List;
7
+ import java.util.concurrent.CancellationException;
8
+ import java.util.regex.Pattern;
9
+
10
+ /** Bounded, sequential query execution in a caller-owned analysis session. */
11
+ public final class QueryBatch {
12
+ public static final int MAX_QUERIES = 32;
13
+ public static final int MAX_CHARACTERS = 262144;
14
+
15
+ public static final class Query {
16
+ public String id;
17
+ public String script;
18
+ public String[] args;
19
+ public String complete;
20
+ public String reject;
21
+ public int maxCharacters;
22
+ }
23
+
24
+ public static final class Result {
25
+ public String id;
26
+ public String status;
27
+ public String output;
28
+ public String error;
29
+ public Result(String id, String status, String output, String error) {
30
+ this.id = id;
31
+ this.status = status;
32
+ this.output = output;
33
+ this.error = error;
34
+ }
35
+ /** Set when the target's failure stops the batch; not part of the report. */
36
+ transient boolean stopsBatch;
37
+ }
38
+
39
+ @FunctionalInterface
40
+ public interface Executor {
41
+ void run(Query query, Writer output, Writer error) throws Exception;
42
+ }
43
+
44
+ /** Thrown by an executor when its target fails and no later target may run. */
45
+ public static final class Stop extends RuntimeException {
46
+ public Stop(String message) { super(message); }
47
+ }
48
+
49
+ private static final class Limit extends RuntimeException {
50
+ Limit() { super("Output limit reached."); }
51
+ }
52
+ private static final class Capture extends Writer {
53
+ private final StringBuilder text = new StringBuilder();
54
+ private final int maximum;
55
+ private boolean limited;
56
+ Capture(int maximum) { this.maximum = maximum; }
57
+ public void write(char[] buffer, int offset, int length) {
58
+ int remaining = maximum - text.length();
59
+ text.append(buffer, offset, Math.min(length, remaining));
60
+ if (length > remaining) { limited = true; throw new Limit(); }
61
+ }
62
+ public void flush() {}
63
+ public void close() {}
64
+ public String toString() { return text.toString(); }
65
+ }
66
+
67
+ /** Validate the audit and every target; returns them in run order, audit first. */
68
+ public static List<Query> validate(Query audit, List<Query> queries) {
69
+ if (queries == null) throw new IllegalArgumentException("Supply 1..31 bounded queries.");
70
+ ArrayList<Query> all = new ArrayList<>();
71
+ all.add(audit);
72
+ all.addAll(queries);
73
+ validate(all);
74
+ return all;
75
+ }
76
+
77
+ /** Validate every target before any script can run. Patterns are owner-supplied controls. */
78
+ public static void validate(List<Query> queries) {
79
+ if (queries == null || queries.isEmpty() || queries.size() > MAX_QUERIES) {
80
+ throw new IllegalArgumentException("Supply 1..32 bounded queries.");
81
+ }
82
+ HashSet<String> ids = new HashSet<>();
83
+ for (Query query : queries) {
84
+ if (query == null || query.id == null || !query.id.matches("[a-zA-Z0-9_-]{1,80}") || !ids.add(query.id)) {
85
+ throw new IllegalArgumentException("Query IDs must be unique simple names.");
86
+ }
87
+ if (query.script == null || !query.script.matches("[a-zA-Z0-9_]+\\.java") ||
88
+ query.script.equals("RunQueryPlan.java") || query.args == null || query.args.length > 64 ||
89
+ query.maxCharacters < 1 || query.maxCharacters > MAX_CHARACTERS ||
90
+ query.complete == null || query.complete.isEmpty() || query.reject == null || query.reject.isEmpty()) {
91
+ throw new IllegalArgumentException("Each query needs a script basename, bounded args/output and completion/rejection controls.");
92
+ }
93
+ for (String arg : query.args) {
94
+ if (arg == null || arg.length() > 4096) throw new IllegalArgumentException("Invalid query argument.");
95
+ }
96
+ Pattern.compile(query.complete);
97
+ Pattern.compile(query.reject);
98
+ }
99
+ }
100
+
101
+ /** A limit or missed control is never a successful negative result. */
102
+ public static Result execute(Query query, Executor executor) {
103
+ Capture output = new Capture(query.maxCharacters);
104
+ Capture error = new Capture(query.maxCharacters);
105
+ String status = "completed";
106
+ String failure = "";
107
+ boolean stopsBatch = false;
108
+ try { executor.run(query, output, error); }
109
+ catch (CancellationException exception) { status = "cancelled"; failure = "Session cancelled."; }
110
+ catch (Stop exception) { status = "failed"; failure = exception.getMessage(); stopsBatch = true; }
111
+ catch (Exception | LinkageError | AssertionError exception) {
112
+ status = "failed";
113
+ failure = exception.getClass().getSimpleName() + ": " + exception.getMessage();
114
+ }
115
+ if (!status.equals("cancelled") && (output.limited || error.limited)) status = "limited";
116
+ else if (status.equals("completed")) {
117
+ var rejected = Pattern.compile(query.reject).matcher(output.toString());
118
+ if (!error.toString().isEmpty()) { status = "failed"; failure = "Script wrote to stderr."; }
119
+ else if (rejected.find()) { status = "failed"; failure = "Rejection control matched: " + rejected.group(); }
120
+ else if (!Pattern.compile(query.complete).matcher(output.toString()).find()) {
121
+ status = "failed";
122
+ failure = "Completion control not observed.";
123
+ }
124
+ }
125
+ String diagnostic = error.toString() + failure;
126
+ if (diagnostic.length() > query.maxCharacters) diagnostic = diagnostic.substring(0, query.maxCharacters);
127
+ Result result = new Result(query.id, status, output.toString(), diagnostic);
128
+ result.stopsBatch = stopsBatch;
129
+ return result;
130
+ }
131
+
132
+ /**
133
+ * Audit failure, cancellation or a {@link Stop} stops the batch; any other query failure is
134
+ * local and later targets still run.
135
+ */
136
+ public static List<Result> run(Query audit, List<Query> queries, Executor executor) {
137
+ validate(audit, queries);
138
+ ArrayList<Result> results = new ArrayList<>();
139
+ Result audited = execute(audit, executor);
140
+ results.add(audited);
141
+ boolean stopped = !audited.status.equals("completed");
142
+ for (Query query : queries) {
143
+ Result result = stopped
144
+ ? new Result(query.id, "not-run", "", "Audit failed, session cancelled or batch stopped.")
145
+ : execute(query, executor);
146
+ results.add(result);
147
+ if (result.status.equals("cancelled") || result.stopsBatch) stopped = true;
148
+ }
149
+ return results;
150
+ }
151
+ }
@@ -0,0 +1,79 @@
1
+ import java.util.ArrayList;
2
+ import java.util.List;
3
+ import java.util.concurrent.CancellationException;
4
+ import scientificmethod.QueryBatch;
5
+
6
+ /** Synthetic executor controls; no Ghidra database or original program. */
7
+ public class QueryBatchHarness {
8
+ private static QueryBatch.Query query(String id) {
9
+ QueryBatch.Query q = new QueryBatch.Query();
10
+ q.id = id;
11
+ q.script = "Synthetic.java";
12
+ q.args = new String[0];
13
+ q.maxCharacters = 40;
14
+ q.complete = "DONE";
15
+ q.reject = "MISSING|CAPPED";
16
+ return q;
17
+ }
18
+ private static void check(boolean condition) { if (!condition) throw new AssertionError(); }
19
+ private static void invalid(List<QueryBatch.Query> queries) {
20
+ try { QueryBatch.validate(queries); throw new AssertionError("Accepted invalid plan"); }
21
+ catch (IllegalArgumentException expected) {}
22
+ }
23
+ public static void main(String[] args) {
24
+ ArrayList<String> calls = new ArrayList<>();
25
+ List<QueryBatch.Result> results = QueryBatch.run(query("audit"),
26
+ List.of(query("one"), query("missing"), query("limit"), query("last")), (q, out, err) -> {
27
+ calls.add(q.id);
28
+ if (q.id.equals("missing")) out.write("MISSING DONE");
29
+ else if (q.id.equals("limit")) out.write("x".repeat(41));
30
+ else out.write("DONE");
31
+ });
32
+ check(calls.equals(List.of("audit", "one", "missing", "limit", "last")));
33
+ check(results.stream().map(r -> r.status).toList().equals(List.of("completed", "completed", "failed", "limited", "completed")));
34
+ check(results.get(3).output.length() == 40);
35
+ check(QueryBatch.execute(query("stderr"), (q, out, err) -> { out.write("DONE"); err.write("error"); }).status.equals("failed"));
36
+ check(QueryBatch.execute(query("exception"), (q, out, err) -> { throw new Exception("missing script"); }).status.equals("failed"));
37
+ check(QueryBatch.execute(query("control"), (q, out, err) -> out.write("partial")).status.equals("failed"));
38
+ check(QueryBatch.execute(query("stderr-limit"), (q, out, err) -> err.write("x".repeat(41))).status.equals("limited"));
39
+ results = QueryBatch.run(query("audit"), List.of(query("one")), (q, out, err) -> out.write("bad audit"));
40
+ check(results.get(1).status.equals("not-run"));
41
+ results = QueryBatch.run(query("audit"), List.of(query("cancel"), query("last")), (q, out, err) -> {
42
+ if (q.id.equals("cancel")) throw new CancellationException();
43
+ out.write("DONE");
44
+ });
45
+ check(results.get(1).status.equals("cancelled") && results.get(2).status.equals("not-run"));
46
+ // A cancelled target that also reached its limit still stops the batch.
47
+ results = QueryBatch.run(query("audit"), List.of(query("cancel"), query("last")), (q, out, err) -> {
48
+ if (q.id.equals("cancel")) { try { out.write("x".repeat(41)); } catch (RuntimeException limit) {} throw new CancellationException(); }
49
+ out.write("DONE");
50
+ });
51
+ check(results.get(1).status.equals("cancelled") && results.get(2).status.equals("not-run"));
52
+ // The target that stops the batch fails; later targets are not run.
53
+ results = QueryBatch.run(query("audit"), List.of(query("mutate"), query("last")), (q, out, err) -> {
54
+ out.write("DONE");
55
+ if (q.id.equals("mutate")) throw new QueryBatch.Stop("changed");
56
+ });
57
+ check(results.get(1).status.equals("failed") && results.get(1).error.equals("changed"));
58
+ check(results.get(2).status.equals("not-run"));
59
+ // An error thrown by a script is a failed target, and the batch goes on.
60
+ results = QueryBatch.run(query("audit"), List.of(query("broken"), query("last")), (q, out, err) -> {
61
+ if (q.id.equals("broken")) throw new NoClassDefFoundError("Missing");
62
+ out.write("DONE");
63
+ });
64
+ check(results.get(1).status.equals("failed") && results.get(2).status.equals("completed"));
65
+ check(QueryBatch.execute(query("rejected"), (q, out, err) -> out.write("MISSING DONE")).error.contains("MISSING"));
66
+ invalid(List.of());
67
+ invalid(List.of(query("same"), query("same")));
68
+ ArrayList<QueryBatch.Query> many = new ArrayList<>();
69
+ for (int i = 0; i < 32; i++) many.add(query("q" + i));
70
+ QueryBatch.validate(many);
71
+ many.add(query("q32"));
72
+ invalid(many);
73
+ QueryBatch.Query q = query("bad"); q.maxCharacters = 262145; invalid(List.of(q));
74
+ q = query("bad"); q.script = "../Synthetic.java"; invalid(List.of(q));
75
+ q = query("bad"); q.complete = ""; invalid(List.of(q));
76
+ q = query("bad"); q.args = new String[] { null }; invalid(List.of(q));
77
+ System.out.println("QueryBatch synthetic controls passed.");
78
+ }
79
+ }