scientific-method-engine 15.0.0__tar.gz → 15.2.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 (82) hide show
  1. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/PKG-INFO +1 -1
  2. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/pyproject.toml +1 -1
  3. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/x86/image.py +26 -2
  4. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/x86/inventory.py +2 -1
  5. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/x86/reach.py +11 -4
  6. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/x86/reports.py +26 -25
  7. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/x86/trace.py +10 -6
  8. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/tests/test_inventory_check.py +85 -0
  9. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/tests/test_reach.py +18 -1
  10. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/.gitignore +0 -0
  11. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/LICENSE +0 -0
  12. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/README.md +0 -0
  13. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/__init__.py +0 -0
  14. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/__main__.py +0 -0
  15. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/cli.py +0 -0
  16. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/ClearNoReturnFunctions.java +0 -0
  17. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/CreateFunctions.java +0 -0
  18. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/ExportBoundedFlow.java +0 -0
  19. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/ExportCallEdges.java +0 -0
  20. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/ExportFunctionFingerprints.java +0 -0
  21. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/ExportFunctionInventory.java +0 -0
  22. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/MergeFallThroughFragment.java +0 -0
  23. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/RecoverCitedFunctions.java +0 -0
  24. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/RepairReturningCallers.java +0 -0
  25. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/ReportCallArguments.java +0 -0
  26. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/ReportCallPaths.java +0 -0
  27. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/ReportCallSitesWithScalars.java +0 -0
  28. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/ReportCallsToRange.java +0 -0
  29. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/ReportConstantFirstArgumentCalls.java +0 -0
  30. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/ReportDataBytes.java +0 -0
  31. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/ReportDecompileMatches.java +0 -0
  32. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/ReportDecompileWindow.java +0 -0
  33. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/ReportFilePatternInMemory.java +0 -0
  34. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/ReportFirstArgumentCallSummary.java +0 -0
  35. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/ReportFunctionScalarConstants.java +0 -0
  36. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/ReportFunctionSummary.java +0 -0
  37. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/ReportInstructionContext.java +0 -0
  38. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/ReportInstructionWindow.java +0 -0
  39. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/ReportMemoryBlockForFileOffset.java +0 -0
  40. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/ReportMemoryBlocks.java +0 -0
  41. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/ReportRandomnessCandidates.java +0 -0
  42. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/ReportRangeBoundaries.java +0 -0
  43. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/ReportReferences.java +0 -0
  44. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/ReportScalarConstants.java +0 -0
  45. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/ReportStringReferences.java +0 -0
  46. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/ReportSymbolReferences.java +0 -0
  47. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/scientificmethod/FirstArgumentLookBack.java +0 -0
  48. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/scientificmethod/InstructionStart.java +0 -0
  49. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/scientificmethod/OperandConstants.java +0 -0
  50. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/ghidra/scientificmethod/Xxh3.java +0 -0
  51. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/x86/__init__.py +0 -0
  52. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/x86/argument_frames.py +0 -0
  53. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/x86/dispatch.py +0 -0
  54. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/x86/effect_order.py +0 -0
  55. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/x86/loops.py +0 -0
  56. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/x86/machine.py +0 -0
  57. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/x86/memory_scopes.py +0 -0
  58. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/x86/pcode.py +0 -0
  59. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/x86/pcode_backend.py +0 -0
  60. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/x86/pe.py +0 -0
  61. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/x86/relational.py +0 -0
  62. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/x86/result_flow.py +0 -0
  63. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/src/scientific_method_engine/x86/values.py +0 -0
  64. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/tests/oracle.py +0 -0
  65. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/tests/test_continuation_budget.py +0 -0
  66. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/tests/test_dispatch.py +0 -0
  67. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/tests/test_effect_order.py +0 -0
  68. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/tests/test_enter_frames.py +0 -0
  69. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/tests/test_entry_frame.py +0 -0
  70. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/tests/test_indirect_far_transfers.py +0 -0
  71. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/tests/test_interrupt_models.py +0 -0
  72. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/tests/test_loops.py +0 -0
  73. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/tests/test_memory_scopes.py +0 -0
  74. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/tests/test_nested_frame_request.py +0 -0
  75. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/tests/test_oracle.py +0 -0
  76. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/tests/test_pe.py +0 -0
  77. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/tests/test_relational_controls.py +0 -0
  78. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/tests/test_return_checks.py +0 -0
  79. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/tests/test_successor_rule.py +0 -0
  80. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/tests/test_table_continuations.py +0 -0
  81. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.0}/tests/test_term_limit.py +0 -0
  82. {scientific_method_engine-15.0.0 → scientific_method_engine-15.2.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: 15.0.0
3
+ Version: 15.2.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
@@ -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 = "15.0.0"
8
+ version = "15.2.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"
@@ -17,6 +17,25 @@ def integer(value, low, high, label):
17
17
  return value
18
18
 
19
19
 
20
+ # The least maximum of instructionLimit and scanLimit, whatever the size of the declared code.
21
+ INSTRUCTION_LIMIT_FLOOR = 100000
22
+ SCAN_LIMIT_FLOOR = 1048576
23
+
24
+
25
+ def instruction_limit(image, value):
26
+ """``value`` checked as an ``instructionLimit``: an integer from 1 to 100,000 or the total bytes of the
27
+ declared regions, whichever is larger. A walk decodes each instruction start once and every start is a
28
+ byte of a declared region, so a limit of the declared size lets a walk finish however large the code."""
29
+ return integer(value, 1, max(INSTRUCTION_LIMIT_FLOOR, image.code_bytes), "instruction limit")
30
+
31
+
32
+ def scan_limit(image, value, label="scanLimit"):
33
+ """``value`` checked as a ``scanLimit``: an integer from 1 to 1,048,576 or the total bytes of the declared
34
+ regions, whichever is larger. A raw scan reads each byte of the declared regions once, so a limit of the
35
+ declared size lets it read them all. ``label`` names the limit in the error."""
36
+ return integer(value, 1, max(SCAN_LIMIT_FLOOR, image.code_bytes), label)
37
+
38
+
20
39
  def read_source(config, base):
21
40
  """Read the source a report config names and check its hash.
22
41
 
@@ -80,9 +99,11 @@ class Image:
80
99
  raise ValueError("Code region crosses the instruction address boundary")
81
100
  if not isinstance(r.get("evidence"), str) or not r["evidence"].strip():
82
101
  raise ValueError("Each region needs mapping/bounds evidence")
102
+ # A region may list no entries: it is scanned and places targets, and a walk enters it only
103
+ # through a transfer from an entry elsewhere.
83
104
  entries = r.get("entries")
84
- if not isinstance(entries, list) or not entries or len(entries) > 4096:
85
- raise ValueError("Each region needs 1..4096 established entry offsets")
105
+ if not isinstance(entries, list) or len(entries) > 4096:
106
+ raise ValueError("Each region needs a list of 0..4096 established entry offsets")
86
107
  for at in entries:
87
108
  integer(at, r["start"], r["end"] - 1, "entry")
88
109
  container = r.get("container")
@@ -92,6 +113,9 @@ class Image:
92
113
  raise ValueError("A region container needs view, start and end")
93
114
  integer(container.get("start"), 0, r["start"], "container start")
94
115
  integer(container.get("end"), r["end"], len(data), "container end")
116
+ if not any(r["entries"] for r in self.regions):
117
+ raise ValueError("Declare at least one established entry offset in some region")
118
+ self.code_bytes = sum(r["end"] - r["start"] for r in self.regions)
95
119
  self.segments = config.get("segments", [])
96
120
  if not isinstance(self.segments, list) or len(self.segments) > 256:
97
121
  raise ValueError("segments must be a list of at most 256 declared segment bounds")
@@ -3,6 +3,7 @@ import re
3
3
  from bisect import bisect_right
4
4
  from pathlib import Path
5
5
  from .image import integer
6
+ from .trace import LIMIT_REASON
6
7
 
7
8
  MAX_INVENTORY = 16 * 1024 * 1024
8
9
  MAX_ROWS = 200000
@@ -225,7 +226,7 @@ def inventory_check(image, config):
225
226
  stopped = {g.get("reason") for g in calls["gaps"]}
226
227
  if partial:
227
228
  summary += " The search is partial."
228
- if "instruction limit" in stopped:
229
+ if LIMIT_REASON in stopped:
229
230
  summary += " The entry-path walk stopped at its instruction limit, so it can reach more calls."
230
231
  summary += " Calls the search does not resolve can add targets."
231
232
  return {"inventory": {"path": config["inventory"], "rows": len(rows)},
@@ -1,7 +1,7 @@
1
1
  """Transitive reachability from established starts to target sites over the entry-path CFG."""
2
2
  from collections import deque
3
3
  from .image import integer
4
- from .trace import walk, cfg_step, base_mnemonic, unsupported_transfer, holding_instruction, INTERRUPTS, RETURNS
4
+ from .trace import walk, cfg_step, base_mnemonic, unsupported_transfer, holding_instruction, INTERRUPTS, RETURNS, LIMIT_REASON
5
5
  from .pcode_backend import interrupt_vector
6
6
 
7
7
  # The virtual root of the dominator computation; no file offset is negative.
@@ -224,6 +224,8 @@ def reach(image, config):
224
224
  call_sites.setdefault(target, []).append(site)
225
225
  leaf_rows = [{"routine": at, "reason": reason, "reached": at in distance, "callSites": call_sites.get(at, [])}
226
226
  for at, reason in leaves.items()]
227
+ # Kept apart from the gap rows, which the result limit can cut.
228
+ stopped = any(g["reason"] == LIMIT_REASON for g in walk_gaps)
227
229
  counts = {"routines": len(routine_starts), "instructions": len(seen), "unresolved": len(unresolved),
228
230
  "interrupts": len(interrupts), "gaps": len(gaps), "contested": len(contested)}
229
231
  return {"starts": starts, "targets": rows, "leaves": leaf_rows,
@@ -231,8 +233,9 @@ def reach(image, config):
231
233
  "unresolved": unresolved[:limit], "interrupts": interrupts[:limit], "gaps": gaps[:limit],
232
234
  "contested": sorted(contested)[:limit],
233
235
  "truncated": any(len(x) > limit for x in (unresolved, interrupts, gaps, contested)),
236
+ "instructionLimitReached": stopped,
234
237
  "controls": [{"site": at, "target": resolved_calls[at]} for at in controls],
235
- "negativeUsable": bool(controls) and not (unresolved or gaps or contested),
238
+ "negativeUsable": bool(controls) and not (stopped or unresolved or gaps or contested),
236
239
  "assumptions": ["each reached call returns to its next instruction",
237
240
  "each reached interrupt returns to its next instruction; interrupt handlers are not read",
238
241
  "each leaf calls nothing, for the reason it gives",
@@ -242,5 +245,9 @@ def reach(image, config):
242
245
  "interpretation": "Routes over the decoded entry-path CFG from the starts. A chain has the fewest calls; "
243
246
  "throughEveryRoute lists the routine starts every read route to the target passes, "
244
247
  "and an unresolved transfer may add a route that passes none of them. "
245
- "negativeUsable needs controls and no unresolved transfer, gap or contested instruction, "
246
- "and still rests on the listed assumptions and leaves."}
248
+ "negativeUsable needs controls, a walk that did not stop at its instruction limit, "
249
+ "and no unresolved transfer, gap or contested instruction, "
250
+ "and still rests on the listed assumptions and leaves. "
251
+ "When instructionLimitReached holds, the walk stopped before reading all it reaches: "
252
+ "every list and count covers only the part read, which part depends on the walk order, "
253
+ "and an unreached target may lie past the stop."}
@@ -11,8 +11,8 @@ from .relational import validate_controls, evaluate_controls
11
11
  from .argument_frames import WINDOW_BYTES, argument_frames, stack_cleanup
12
12
  from .memory_scopes import model_scopes
13
13
  from .result_flow import return_flows
14
- from .image import Image, integer
15
- from .trace import (trace, walk, cfg_step, call_target, unsupported_transfer, uncovered, holding_instruction, base_mnemonic, OVERLAP_REASON, CONTESTED_REASON,
14
+ from .image import Image, instruction_limit, integer, scan_limit
15
+ from .trace import (trace, walk, cfg_step, call_target, unsupported_transfer, uncovered, holding_instruction, base_mnemonic, OVERLAP_REASON, CONTESTED_REASON, LIMIT_REASON,
16
16
  RETURNS, INTERRUPTS, PORTS, PORT_INPUTS, port_width, budget_input, modeled_interrupt_sites)
17
17
  from .pcode_backend import interrupt_vector
18
18
 
@@ -107,7 +107,7 @@ def direct_calls(image, config):
107
107
  scans = config.get("searchRegions", [r["name"] for r in image.regions])
108
108
  if not isinstance(scans, list) or not scans or len(set(scans)) != len(scans):
109
109
  raise ValueError("searchRegions must be unique region names")
110
- scan_limit = integer(config.get("scanLimit", 65536), 1, 1048576, "scanLimit")
110
+ byte_limit = scan_limit(image, config.get("scanLimit", 65536))
111
111
  scanned_bytes, read = 0, {}
112
112
  for name in scans:
113
113
  r = next((r for r in image.regions if r["name"] == name), None)
@@ -116,7 +116,7 @@ def direct_calls(image, config):
116
116
  read[name] = (r["start"], r["end"])
117
117
  # Scan the entire declared region, including sites after the target returns.
118
118
  for at in range(r["start"], r["end"]):
119
- if scanned_bytes >= scan_limit:
119
+ if scanned_bytes >= byte_limit:
120
120
  gaps.append({"region": name, "unsearchedStart": at, "end": r["end"], "reason": "raw scan limit"})
121
121
  read[name] = (r["start"], at)
122
122
  break
@@ -265,7 +265,7 @@ def _function_exit(image, start, limit, follow_flat_ports, cache):
265
265
  at = pending.pop()
266
266
  if at in seen:
267
267
  continue
268
- if len(seen) >= limit:
268
+ if len(seen) >= limit and image.region(at) is not None:
269
269
  cache[key] = {}, False, True
270
270
  return cache[key]
271
271
  ins = image.decode(at)
@@ -315,7 +315,7 @@ def _caller_continuations(image, stop, reason, stack, limit, cache, modeled=froz
315
315
  for call_site, return_site in reversed(stack):
316
316
  route, exits, truncated = _function_exit(image, start, limit, True, cache)
317
317
  if truncated:
318
- return rows, [{"site": start, "reason": "instruction limit"}]
318
+ return rows, [{"site": start, "reason": LIMIT_REASON}]
319
319
  if not exits:
320
320
  break
321
321
  if port_free:
@@ -425,7 +425,7 @@ def uses(image, config):
425
425
  # Those operands stay out of matches: each names the stops whose CFG reaches it, so
426
426
  # reading one callee later shows exactly which accesses depended on it.
427
427
  reported = {(e["site"], e["kind"]) for e in matches + unresolved}
428
- instruction_limit = config.get("instructionLimit", 10000)
428
+ walk_limit = config.get("instructionLimit", 10000)
429
429
  # This inventory assumes execution continues past each stop, so it also follows interrupts, which
430
430
  # it assumes return to the next instruction, and PE32 port accesses, and names each one below.
431
431
  # A stop inside a called function would end the inventory at that function's return. The code
@@ -434,13 +434,13 @@ def uses(image, config):
434
434
  returning, exit_walks = [], {}
435
435
  for root, stacks in sorted(open_calls.items()):
436
436
  for stack in sorted(stacks):
437
- rows, frame_gaps = _caller_continuations(image, root, stops[root], stack, instruction_limit, exit_walks, modeled)
437
+ rows, frame_gaps = _caller_continuations(image, root, stops[root], stack, walk_limit, exit_walks, modeled)
438
438
  returning.extend(rows)
439
439
  gaps.extend(g for g in frame_gaps if g not in gaps)
440
440
  seeds = list(stops) + [start for start, _, _ in returning]
441
- after_stop, stop_gaps, _, _, _ = (walk(image, seeds, instruction_limit, follow_flat_ports=True, follow_interrupts=True)
441
+ after_stop, stop_gaps, _, _, _ = (walk(image, seeds, walk_limit, follow_flat_ports=True, follow_interrupts=True)
442
442
  if seeds else ({}, [], None, None, None))
443
- gaps.extend(g for g in stop_gaps if g["reason"] == "instruction limit")
443
+ gaps.extend(g for g in stop_gaps if g["reason"] == LIMIT_REASON)
444
444
  # In PE32 a site the stops reach only by continuing past a port access is named as such, even when
445
445
  # it also depends on an unread call. The walk that ends at port accesses must finish within the
446
446
  # limit for that claim; otherwise every row keeps the shared value. A return site counts as
@@ -449,8 +449,8 @@ def uses(image, config):
449
449
  if image.flat and (any(base_mnemonic(ins) in PORTS for ins in after_stop.values())
450
450
  or any(not port_free for _, _, port_free in returning)):
451
451
  port_free_seeds = list(stops) + [start for start, _, port_free in returning if port_free]
452
- before_ports, port_gaps, _, _, _ = walk(image, port_free_seeds, instruction_limit, follow_interrupts=True)
453
- if not any(g["reason"] == "instruction limit" for g in port_gaps):
452
+ before_ports, port_gaps, _, _, _ = walk(image, port_free_seeds, walk_limit, follow_interrupts=True)
453
+ if not any(g["reason"] == LIMIT_REASON for g in port_gaps):
454
454
  port_only = set(after_stop) - set(before_ports)
455
455
  # A call or interrupt past a stop was never traced either, so code after it also depends on it returning.
456
456
  starts = [(root, [{"site": root, "reason": reason}]) for root, reason in stops.items()]
@@ -469,7 +469,7 @@ def uses(image, config):
469
469
  named.extend(d for d in row_depends if d not in named)
470
470
  depends = {}
471
471
  for start, row_depends in by_start.items():
472
- reached, _, _, _, _ = walk(image, [start], instruction_limit, follow_flat_ports=True, follow_interrupts=True)
472
+ reached, _, _, _, _ = walk(image, [start], walk_limit, follow_flat_ports=True, follow_interrupts=True)
473
473
  for at in reached:
474
474
  named = depends.setdefault(at, [])
475
475
  named.extend(d for d in row_depends if d not in named)
@@ -521,10 +521,10 @@ def uses(image, config):
521
521
  raise ValueError(f"Positive variable-use control {at} missed; negative result rejected")
522
522
  raw = []
523
523
  scanned_bytes = 0
524
- scan_limit = integer(config.get("scanLimit", 65536), 1, 1048576, "scanLimit")
524
+ byte_limit = scan_limit(image, config.get("scanLimit", 65536))
525
525
  for r in image.regions:
526
526
  for at in range(r["start"], r["end"]):
527
- if scanned_bytes >= scan_limit:
527
+ if scanned_bytes >= byte_limit:
528
528
  gaps.append({"region": r["name"], "unsearchedStart": at, "end": r["end"], "reason": "raw scan limit"})
529
529
  break
530
530
  scanned_bytes += 1
@@ -569,7 +569,7 @@ def operand_candidates(image, config):
569
569
  raise ValueError("Candidate query must be an object")
570
570
  value = integer(query.get("offset"), 0, image.mask, "candidate literal")
571
571
  limit = integer(config.get("limit", 100), 1, 10000, "candidate result limit")
572
- scan_limit = integer(config.get("scanLimit", 100000), 1, 1048576, "candidate scan limit")
572
+ byte_limit = scan_limit(image, config.get("scanLimit", 100000), "candidate scan limit")
573
573
  seen, gaps, _, _, contested = walk(image, entries(image), config.get("instructionLimit", 10000))
574
574
  ambiguous = {g["site"] for g in gaps if g.get("reason") == OVERLAP_REASON} | set(contested)
575
575
  intervals = sorted((at, at + ins.size) for at, ins in seen.items())
@@ -580,7 +580,7 @@ def operand_candidates(image, config):
580
580
  for region in image.regions:
581
581
  end = region["start"]
582
582
  for at in range(region["start"], region["end"]):
583
- if scanned >= scan_limit:
583
+ if scanned >= byte_limit:
584
584
  break
585
585
  scanned += 1
586
586
  end = at + 1
@@ -877,7 +877,7 @@ def call_target_report(image, config):
877
877
  raise ValueError("Only the ptr16:16 far transfer encoding is supported")
878
878
  seen, gaps, _, _, contested = walk(image, entries(image), config.get("instructionLimit", 10000))
879
879
  # A walk stopped by its instruction limit leaves later boundaries unverified, not disproved.
880
- truncated = any(g.get("reason") == "instruction limit" for g in gaps)
880
+ truncated = any(g.get("reason") == LIMIT_REASON for g in gaps)
881
881
  boundary = ("entry-path instruction" if site in seen else CONTESTED_REASON if site in contested
882
882
  else "raw byte candidate; instruction boundary unverified"
883
883
  + ("; the entry walk stopped at its instruction limit" if truncated else ""))
@@ -940,7 +940,7 @@ def call_target_report(image, config):
940
940
  "interpretation": ("equal only to the raw operand, which names unrelocated bytes"
941
941
  if matched == ["raw operand"] else
942
942
  "kept beside the derived chain; it never replaces the relocation, descriptor or trampoline identities")}
943
- result["gaps"] = [g for g in gaps if g.get("site") == site or g.get("reason") == "instruction limit"]
943
+ result["gaps"] = [g for g in gaps if g.get("site") == site or g.get("reason") == LIMIT_REASON]
944
944
  result["walkComplete"] = not truncated
945
945
  return result
946
946
 
@@ -973,7 +973,7 @@ def body(image, entry, limit=10000):
973
973
  one it could not resolve), including targets that leave the body. Reports that need where the body goes
974
974
  from an instruction read flow instead of restating these rules.
975
975
  """
976
- integer(limit, 1, 100000, "instruction limit")
976
+ instruction_limit(image, limit)
977
977
  established = set(entries(image))
978
978
  pending, seen, exits, calls, gaps, assumed, shared = [entry], {}, [], [], [], [], set()
979
979
  hardware, flow = [], {}
@@ -984,8 +984,9 @@ def body(image, entry, limit=10000):
984
984
  at = pending.pop()
985
985
  if at in seen:
986
986
  continue
987
- if len(seen) >= limit:
988
- gaps.append({"site": at, "reason": "instruction limit"})
987
+ # As in walk, a site outside declared code is an unmapped edge even once the limit is reached.
988
+ if len(seen) >= limit and image.region(at) is not None:
989
+ gaps.append({"site": at, "reason": LIMIT_REASON})
989
990
  break
990
991
  ins = image.decode(at)
991
992
  if ins is None:
@@ -1089,7 +1090,7 @@ def callees(image, config):
1089
1090
  node_limit = integer(config.get("nodeLimit", 64), 1, 128, "callee node limit")
1090
1091
  edge_limit = integer(config.get("edgeLimit", 512), 1, 2048, "callee edge limit")
1091
1092
  depth_limit = integer(config.get("depthLimit", 16), 1, 128, "callee depth limit")
1092
- instruction_limit = integer(config.get("instructionLimit", 10000), 1, 100000, "instruction limit")
1093
+ body_limit = instruction_limit(image, config.get("instructionLimit", 10000))
1093
1094
  controls = config.get("controls", {})
1094
1095
  if not isinstance(controls, dict) or set(controls) - {"sharedSites", "recursiveSites", "writeSites", "ghidraAgreementSites"}:
1095
1096
  raise ValueError("Invalid callee controls")
@@ -1101,7 +1102,7 @@ def callees(image, config):
1101
1102
  nodes, edges, omitted = {}, [], []
1102
1103
 
1103
1104
  def read(entry):
1104
- b = body(image, entry, instruction_limit)
1105
+ b = body(image, entry, body_limit)
1105
1106
  observations = []
1106
1107
  for site, ins in sorted(b["instructions"].items()):
1107
1108
  for index, operand in enumerate(ins.operands):
@@ -1210,7 +1211,7 @@ def callees(image, config):
1210
1211
  edge["calleeSummary"] = edge["target"] if edge["target"] in summaries else None
1211
1212
  # A reused node that reaches the active path, or whose reached bodies were capped or are unusable, may lead
1212
1213
  # back into the active path, so such reuse is no shared-node control.
1213
- capped = {"depth limit", "node limit", "instruction limit"}
1214
+ capped = {"depth limit", "node limit", LIMIT_REASON}
1214
1215
 
1215
1216
  def shared_control(e):
1216
1217
  if e["classification"] != "sharedNodeReuse":
@@ -2,7 +2,7 @@
2
2
  from copy import deepcopy
3
3
  from typing import NamedTuple
4
4
  from capstone.x86 import X86_OP_IMM, X86_OP_REG, X86_OP_MEM
5
- from .image import integer
5
+ from .image import instruction_limit, integer
6
6
  from .machine import (State, StopPath, REGISTERS, ALIASES, BRANCH_CONDITIONS, string_instruction,
7
7
  string_count, string_effect, check_string_form, compare_string, repeated, string_width,
8
8
  FLAT_PORT_REASON)
@@ -83,6 +83,8 @@ def far_pointer_transfer(state, image):
83
83
  return target, provenance, segment_value
84
84
 
85
85
 
86
+ # The gap reason walk() records when it stops at its instruction limit with code left to read.
87
+ LIMIT_REASON = "instruction limit"
86
88
  OVERLAP_REASON = "overlapping entry-path instructions; boundary unresolved"
87
89
  RETURNS = {"ret": "near return", "retf": "far return", "iret": "interrupt return", "iretd": "interrupt return"}
88
90
  INTERRUPTS = ("int", "int1", "int3", "into")
@@ -238,7 +240,7 @@ def walk(image, entries, limit=10000, follow_flat_ports=False, follow_interrupts
238
240
  continues past under a call model (ADR 0017). A site in ``stops`` is never decoded:
239
241
  the walk reaches it and goes no further, so it is in no returned set.
240
242
  """
241
- integer(limit, 1, 100000, "instruction limit")
243
+ instruction_limit(image, limit)
242
244
  pending, seen, gaps, edges = list(entries), {}, [], []
243
245
  # Decoded successors of each instruction, so a proof can be checked for independence below.
244
246
  # A call's return site is reached only if the callee returns, and the site after an interrupt only
@@ -248,8 +250,10 @@ def walk(image, entries, limit=10000, follow_flat_ports=False, follow_interrupts
248
250
  at = pending.pop()
249
251
  if at in seen or at in stops:
250
252
  continue
251
- if len(seen) >= limit:
252
- gaps.append({"site": at, "reason": "instruction limit"})
253
+ # A limit of the declared code size can leave every byte of it decoded, so only a site in a
254
+ # declared region is one the limit stopped; a site outside is an unmapped edge.
255
+ if len(seen) >= limit and image.region(at) is not None:
256
+ gaps.append({"site": at, "reason": LIMIT_REASON})
253
257
  break
254
258
  ins = image.decode(at)
255
259
  if ins is None:
@@ -671,7 +675,7 @@ def trace(image, config, continue_declared_jumps=True, track_loops=True, arrive=
671
675
  # States stopped at a declared jump site, continued after the ordinary paths.
672
676
  deferred = []
673
677
  boundary_cache = {}
674
- boundary_budget = integer(config.get("instructionLimit", 10000), 1, 100000, "instruction limit")
678
+ boundary_budget = instruction_limit(image, config.get("instructionLimit", 10000))
675
679
  created = 1
676
680
  total_steps = 0
677
681
  total_string_steps = 0
@@ -841,7 +845,7 @@ def trace(image, config, continue_declared_jumps=True, track_loops=True, arrive=
841
845
  overlapping = sum(g["reason"] == OVERLAP_REASON for g in walk_gaps)
842
846
  boundary_budget -= max(1, len(seen) + len(contested) + overlapping)
843
847
  # A truncated walk never saw the instructions that could contest a target start.
844
- if any(g["reason"] == "instruction limit" for g in walk_gaps):
848
+ if any(g["reason"] == LIMIT_REASON for g in walk_gaps):
845
849
  seen = {}
846
850
  boundary_cache[root_entry] = seen
847
851
  seen = boundary_cache[root_entry]
@@ -214,6 +214,91 @@ class InventoryCheckTests(unittest.TestCase):
214
214
  self.assertEqual(piped.returncode, 1)
215
215
  self.assertIn("relative inventory path", piped.stderr)
216
216
 
217
+ def test_a_walk_past_100000_instructions_finishes_from_one_entry_through_regions_with_no_entries(self):
218
+ # 1000:0000 calls far 2000:0000 and 3000:0000. Each callee runs 60,000 NOPs, so the code holds
219
+ # 120,006 distinct instructions; the third ends with a call to its own last RET, which only a walk
220
+ # that reaches the end shows as an entry-path call.
221
+ first = bytes.fromhex("9a00000020" "9a00000030" "c3")
222
+ second = b"\x90" * 60000 + b"\xc3"
223
+ third = b"\x90" * 60000 + bytes.fromhex("e80000" "c3")
224
+ b, c = 16, 16 + (len(second) + 15) // 16 * 16
225
+ data = first.ljust(b, b"\0") + second.ljust(c - b, b"\0") + third
226
+ regions = [{"name": "first", "start": 0, "end": len(first), "ip": 0, "segment": 0x1000, "entries": [0],
227
+ "evidence": "synthetic resident code"},
228
+ {"name": "second", "start": b, "end": b + len(second), "ip": 0, "segment": 0x2000, "entries": [],
229
+ "evidence": "synthetic code no inventory row starts"},
230
+ {"name": "third", "start": c, "end": c + len(third), "ip": 0, "segment": 0x3000, "entries": [],
231
+ "evidence": "synthetic code no inventory row starts"}]
232
+ relocations = [{"site": 3, "segment": 0x2000, "evidence": "synthetic relocation"},
233
+ {"site": 8, "segment": 0x3000, "evidence": "synthetic relocation"}]
234
+ declared = len(first) + len(second) + len(third)
235
+ cfg = config(data, regions, relocations=relocations, scanLimit=declared, controls=[0, 5, c + 60000],
236
+ inventory=self.inventory("start\tsize\n1000:0000\t11\n"))
237
+ with self.assertRaisesRegex(ValueError, rf"instruction limit must be an integer in 1\.\.{declared}$"):
238
+ run_report(data, {**cfg, "instructionLimit": declared + 1}, "inventory-check")
239
+ r = run_report(data, {**cfg, "instructionLimit": declared}, "inventory-check")
240
+ self.assertEqual(r["gaps"], [])
241
+ self.assertNotIn("instruction limit", r["summary"])
242
+ self.assertEqual([(t["address"], t["status"], t["evidence"]) for t in r["targets"]],
243
+ [("2000:0000", "outside every row", "entry-path call"),
244
+ ("3000:0000", "outside every row", "entry-path call"),
245
+ ("3000:EA63", "outside every row", "entry-path call")])
246
+
247
+ def test_a_region_with_no_entries_places_targets_and_its_unreached_calls_stay_raw_candidates(self):
248
+ # 0000 calls far through an FBOV fixup to 0010 in an overlay region that lists no entries. 0010 is a
249
+ # RET; the call at 0011 back to it lies past that RET, so no walk reaches it.
250
+ data = bytes.fromhex("9a00000800" "c3") + bytes(10) + bytes.fromhex("c3" "e8fcff" "c3") + bytes(3)
251
+ resident = {"name": "resident", "start": 0, "end": 6, "ip": 0, "segment": 0x1000, "entries": [0],
252
+ "evidence": "synthetic resident code"}
253
+ overlay = {"name": "overlay", "start": 0x10, "end": 0x18, "ip": 0, "segment": 0x2000, "entries": [],
254
+ "container": {"view": "overlay 1", "start": 0x10, "end": 0x18}, "evidence": "synthetic overlay view"}
255
+ fixup = {"site": 3, "raw": 8, "descriptor": 1, "segment": 0x2000, "target": 0x10, "trampoline": 0x40,
256
+ "evidence": "synthetic FBOV descriptor/fixup"}
257
+ r = run_report(data, config(data, [resident, overlay], relocations=[fixup], controls=[0],
258
+ inventory=self.inventory("start\tsize\n1000:0000\t6\n")), "inventory-check")
259
+ self.assertEqual([(t["address"], t["status"], t["evidence"], t["callSites"]) for t in r["targets"]],
260
+ [("0x10", "outside every row", "entry-path call", {"entryPath": 1, "contested": 0, "rawCandidates": 1})])
261
+ self.assertEqual(r["gaps"], [])
262
+ for regions, message in (([{**resident, "entries": []}, overlay], "at least one established entry"),
263
+ ([resident, {k: v for k, v in overlay.items() if k != "entries"}], "0..4096"),
264
+ ([resident, {**overlay, "entries": [0x10] * 4097}], "0..4096")):
265
+ with self.subTest(message=message):
266
+ with self.assertRaisesRegex(ValueError, message):
267
+ run_report(data, config(data, regions, relocations=[fixup], target=0x10), "incoming")
268
+
269
+ def test_instruction_and_scan_limits_reach_the_size_of_the_declared_code(self):
270
+ def run(size, **limits):
271
+ # One RET, then zero bytes in 64 KiB regions; only the first region lists an entry.
272
+ data = b"\xc3" + bytes(size - 1)
273
+ regions = [{"name": f"r{i}", "start": start, "end": min(start + 0x10000, size), "ip": 0,
274
+ "segment": 0x1000 + i, "entries": [] if i else [0], "evidence": "synthetic code extent"}
275
+ for i, start in enumerate(range(0, size, 0x10000))]
276
+ return run_report(data, config(data, regions, target=0, **limits), "incoming")
277
+ self.assertEqual(run(16, instructionLimit=100000)["gaps"], [])
278
+ with self.assertRaisesRegex(ValueError, r"instruction limit must be an integer in 1\.\.100000$"):
279
+ run(16, instructionLimit=100001)
280
+ self.assertEqual(run(200000, instructionLimit=200000, scanLimit=200000)["gaps"], [])
281
+ with self.assertRaisesRegex(ValueError, r"1\.\.200000$"):
282
+ run(200000, instructionLimit=200001)
283
+ with self.assertRaisesRegex(ValueError, r"scanLimit must be an integer in 1\.\.1048576$"):
284
+ run(16, scanLimit=1048577)
285
+ size = 1048576 + 16
286
+ self.assertFalse(run(size, scanLimit=size)["partialSearch"])
287
+ with self.assertRaisesRegex(ValueError, rf"scanLimit must be an integer in 1\.\.{size}$"):
288
+ run(size, scanLimit=size + 1)
289
+
290
+ def test_a_walk_that_decodes_every_declared_byte_reports_no_instruction_limit(self):
291
+ # Two adjacent regions of NOPs, 120,000 one-byte instructions, so a walk at the largest limit decodes
292
+ # every declared byte and then falls through to 120000, outside declared code.
293
+ size = 120000
294
+ data = b"\x90" * size
295
+ regions = [{"name": "a", "start": 0, "end": 60000, "ip": 0, "segment": 0x1000, "entries": [0],
296
+ "evidence": "synthetic code extent"},
297
+ {"name": "b", "start": 60000, "end": size, "ip": 0, "segment": 0x2000, "entries": [],
298
+ "evidence": "synthetic code extent"}]
299
+ r = run_report(data, config(data, regions, target=0, instructionLimit=size, scanLimit=size), "incoming")
300
+ self.assertEqual(r["gaps"], [{"site": size, "reason": "undecoded or unmapped edge"}])
301
+
217
302
 
218
303
  if __name__ == "__main__":
219
304
  unittest.main()
@@ -61,6 +61,7 @@ class ReachTests(unittest.TestCase):
61
61
  self.assertEqual([(u["site"], u["kind"], u["routine"]) for u in r["unresolved"]], [(0x6, "call", 0x0)])
62
62
  self.assertIn("[0x200]", r["unresolved"][0]["instruction"])
63
63
  self.assertFalse(r["negativeUsable"])
64
+ self.assertFalse(r["instructionLimitReached"])
64
65
  self.assertEqual(r["controls"], [{"site": 0x3, "target": 0x18}, {"site": 0x20, "target": 0x28}])
65
66
 
66
67
  def test_a_leaf_is_reached_unread_and_its_reason_is_repeated(self):
@@ -144,9 +145,25 @@ class ReachTests(unittest.TestCase):
144
145
  self.assertFalse(r["negativeUsable"])
145
146
 
146
147
  def test_the_instruction_limit_is_a_gap(self):
147
- r = reach(indirectJumps=[TABLE], instructionLimit=3)
148
+ # The control at 0000 is read before the stop, so missing controls do not decide negativeUsable.
149
+ r = reach(indirectJumps=[TABLE], instructionLimit=3, controls=[0x0])
148
150
  self.assertIn("instruction limit", [g["reason"] for g in r["gaps"]])
149
151
  self.assertFalse(r["negativeUsable"])
152
+ self.assertTrue(r["instructionLimitReached"])
153
+ self.assertFalse(r["truncated"])
154
+
155
+ def test_the_instruction_limit_stop_is_reported_when_the_result_limit_cuts_its_gap(self):
156
+ # 0000 je 0004; 0002 holds undecodable bytes; 0004 nop; 0005 nop; 0006 ret.
157
+ data = bytes.fromhex("7402ffff9090c3")
158
+ r = run_report(data, config(data, targets=[6], instructionLimit=2, limit=1), "reach")
159
+ self.assertEqual(r["gaps"], [{"site": 2, "reason": "undecoded or unmapped edge"}])
160
+ self.assertEqual(r["counts"]["gaps"], 2)
161
+ self.assertTrue(r["instructionLimitReached"])
162
+ self.assertFalse(r["targets"][0]["reached"])
163
+ # With room to read everything, the same walk reaches the target and does not stop.
164
+ r = run_report(data, config(data, targets=[6], limit=1), "reach")
165
+ self.assertFalse(r["instructionLimitReached"])
166
+ self.assertTrue(r["targets"][0]["reached"])
150
167
 
151
168
  def test_the_result_limit_truncates_lists_and_keeps_counts(self):
152
169
  data = bytes.fromhex("ffd0ffd3c3") # call ax; call bx; ret