scientific-method-engine 10.0.0__tar.gz → 10.1.1__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 (72) hide show
  1. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/PKG-INFO +1 -1
  2. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/pyproject.toml +1 -1
  3. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/x86/machine.py +23 -12
  4. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/x86/relational.py +51 -3
  5. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/tests/test_relational_controls.py +143 -0
  6. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/.gitignore +0 -0
  7. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/LICENSE +0 -0
  8. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/README.md +0 -0
  9. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/__init__.py +0 -0
  10. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/__main__.py +0 -0
  11. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/cli.py +0 -0
  12. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/ClearNoReturnFunctions.java +0 -0
  13. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/CreateFunctions.java +0 -0
  14. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/ExportBoundedFlow.java +0 -0
  15. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/ExportCallEdges.java +0 -0
  16. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/ExportFunctionFingerprints.java +0 -0
  17. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/ExportFunctionInventory.java +0 -0
  18. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/MergeFallThroughFragment.java +0 -0
  19. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/RecoverCitedFunctions.java +0 -0
  20. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/RepairReturningCallers.java +0 -0
  21. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/ReportCallArguments.java +0 -0
  22. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/ReportCallPaths.java +0 -0
  23. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/ReportCallSitesWithScalars.java +0 -0
  24. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/ReportCallsToRange.java +0 -0
  25. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/ReportConstantFirstArgumentCalls.java +0 -0
  26. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/ReportDataBytes.java +0 -0
  27. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/ReportDecompileMatches.java +0 -0
  28. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/ReportDecompileWindow.java +0 -0
  29. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/ReportFilePatternInMemory.java +0 -0
  30. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/ReportFirstArgumentCallSummary.java +0 -0
  31. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/ReportFunctionScalarConstants.java +0 -0
  32. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/ReportFunctionSummary.java +0 -0
  33. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/ReportInstructionContext.java +0 -0
  34. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/ReportInstructionWindow.java +0 -0
  35. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/ReportMemoryBlockForFileOffset.java +0 -0
  36. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/ReportMemoryBlocks.java +0 -0
  37. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/ReportRandomnessCandidates.java +0 -0
  38. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/ReportReferences.java +0 -0
  39. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/ReportScalarConstants.java +0 -0
  40. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/ReportStringReferences.java +0 -0
  41. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/ReportSymbolReferences.java +0 -0
  42. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/scientificmethod/FirstArgumentLookBack.java +0 -0
  43. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/ghidra/scientificmethod/InstructionStart.java +0 -0
  44. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/x86/__init__.py +0 -0
  45. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/x86/argument_frames.py +0 -0
  46. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/x86/dispatch.py +0 -0
  47. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/x86/effect_order.py +0 -0
  48. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/x86/image.py +0 -0
  49. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/x86/loops.py +0 -0
  50. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/x86/memory_scopes.py +0 -0
  51. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/x86/pcode.py +0 -0
  52. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/x86/pcode_backend.py +0 -0
  53. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/x86/pe.py +0 -0
  54. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/x86/reports.py +0 -0
  55. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/x86/result_flow.py +0 -0
  56. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/x86/trace.py +0 -0
  57. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/src/scientific_method_engine/x86/values.py +0 -0
  58. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/tests/oracle.py +0 -0
  59. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/tests/test_continuation_budget.py +0 -0
  60. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/tests/test_dispatch.py +0 -0
  61. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/tests/test_effect_order.py +0 -0
  62. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/tests/test_entry_frame.py +0 -0
  63. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/tests/test_indirect_far_transfers.py +0 -0
  64. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/tests/test_interrupt_models.py +0 -0
  65. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/tests/test_loops.py +0 -0
  66. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/tests/test_memory_scopes.py +0 -0
  67. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/tests/test_nested_frame_request.py +0 -0
  68. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/tests/test_oracle.py +0 -0
  69. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/tests/test_pe.py +0 -0
  70. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/tests/test_successor_rule.py +0 -0
  71. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/tests/test_table_continuations.py +0 -0
  72. {scientific_method_engine-10.0.0 → scientific_method_engine-10.1.1}/tests/test_x86.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: scientific-method-engine
3
- Version: 10.0.0
3
+ Version: 10.1.1
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 = "10.0.0"
8
+ version = "10.1.1"
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"
@@ -123,7 +123,6 @@ class State:
123
123
  self.memory = {}
124
124
  # Keys grouped by (segment, base) so a write scans only groups that can alias it.
125
125
  self.memory_groups = {}
126
- self.memory_epoch = 0
127
126
  # The order of the write event that stored each modeled byte. lost_memory holds the
128
127
  # byteProducers "unwritten" row of bytes with no value that an ordinary write explains (a
129
128
  # possibly aliasing write dropped them) or that a preservesMemory scope kept without a
@@ -136,7 +135,8 @@ class State:
136
135
  self.memory_cleared = None
137
136
  self.writes = {}
138
137
  # Bytes a preservesMemory scope kept without a value (ADR 0009): key -> the unknown term
139
- # name they had before the modeled call. They stay unread: no value, no producer.
138
+ # name they had before the modeled call. They stay unread: no value, no producer. Every other
139
+ # byte with no value reads a term named by the event its "unwritten" row names (unread_term).
140
140
  self.unread_memory = {}
141
141
  self.events = []
142
142
  # Bytes above each traced call's return frame that the call event records (argument_slots); 0 records none.
@@ -262,15 +262,25 @@ class State:
262
262
  self.writes.clear()
263
263
  # The caller records the event that explains the loss right after clearing.
264
264
  self.memory_cleared = len(self.events)
265
- self.memory_epoch += 1
266
265
 
267
- def unread_term(self, key):
268
- """Name the unknown term of a byte with no modeled value: a kept scope term or the epoch's."""
269
- return self.unread_memory.get(key, f"memory:{self.memory_epoch}:{key}")
266
+ def unread_term(self, key, unwritten=None):
267
+ """Name the unknown term of a byte with no modeled value: a kept scope term, or one named by
268
+ the newest event that may have stored the byte.
270
269
 
271
- def byte(self, key):
270
+ That event is the one the byte's ``unwritten`` row names (pass the row when it is already
271
+ built): the newest write that may alias it, the write that dropped its value, the modeled
272
+ call that cleared memory, or none. Reads of the byte name the same term until such an event
273
+ happens, so a reload across writes that cannot store the byte reads the earlier term, and the
274
+ term changes exactly when the reported cause does.
275
+ """
276
+ if key in self.unread_memory:
277
+ return self.unread_memory[key]
278
+ order = (unwritten or self.unwritten(key))["order"]
279
+ return f"memory:{'entry' if order is None else order}:{key}"
280
+
281
+ def byte(self, key, unwritten=None):
272
282
  """The modeled value of one memory byte, or an unknown term produced by the current site."""
273
- return self.memory[key] if key in self.memory else unknown(self.unread_term(key), 8, self.at)
283
+ return self.memory[key] if key in self.memory else unknown(self.unread_term(key, unwritten), 8, self.at)
274
284
 
275
285
  def latest_aliasing_write(self, group, domain):
276
286
  """The order of the newest write outside `group` that may have stored a byte of `domain`, or None."""
@@ -392,8 +402,6 @@ class State:
392
402
  dropped_values = dropped_unread = 0
393
403
  if write is not None:
394
404
  write = Value(write.bits, write.term, sources(write, site=self.at))
395
- self.memory_epoch += 1
396
-
397
405
  written = written_domain(seg, base, delta, width, self.bits, self.flat)
398
406
  self.writes.setdefault((seg, base), {})[written] = len(self.events)
399
407
  for group, members in list(self.memory_groups.items()):
@@ -426,9 +434,12 @@ class State:
426
434
  self.memory_groups.setdefault((seg, base), set()).update(keys)
427
435
  value = write
428
436
  missing = []
437
+ rows = [self.byte_writer(i, key) for i, key in enumerate(keys)]
429
438
  else:
430
439
  missing = [i for i, key in enumerate(keys) if key not in self.memory]
431
- value = join([self.byte(key) for key in keys])
440
+ # Each row's "unwritten" cause names the term of a byte with no value, so it is built once.
441
+ rows = [self.byte_writer(i, key) for i, key in enumerate(keys)]
442
+ value = join([self.byte(key, row.get("unwritten")) for key, row in zip(keys, rows)])
432
443
  relevant = []
433
444
  for g in self.guards:
434
445
  left = g.get("left", {}).get("expression")
@@ -441,7 +452,7 @@ class State:
441
452
  event = self.event("write" if write is not None else "read", segment=segment.report(), offset=offset.report(),
442
453
  width=width, effectiveSegmentRegister=addressing_register, segmentInterpretation="base" if self.flat else "selector-paragraph", interval={"segment": seg, "base": base, "start": delta, "end": delta + width},
443
454
  value=value.report(), missingByteProducers=missing,
444
- byteProducers=[self.byte_writer(i, key) for i, key in enumerate(keys)],
455
+ byteProducers=rows,
445
456
  guards=deepcopy(relevant), role=role,
446
457
  uncertainAliasesInvalidated=dropped_values, uncertainScopeBytesInvalidated=dropped_unread)
447
458
  f = self.frames[-1]
@@ -293,14 +293,55 @@ HIDDEN = "hidden-occurrences"
293
293
 
294
294
 
295
295
  def _atom_range(atom, ranges):
296
- if atom in ranges:
297
- return ranges[atom]
298
296
  if atom[0] == HIDDEN:
299
297
  return 0, inf
300
298
  if atom[0] == "signed":
301
299
  half = 1 << (atom[2] - 1)
302
300
  return -half, half - 1
303
- return 0, (1 << atom[1]) - 1
301
+ return _unsigned(atom[0], atom[1], ranges)
302
+
303
+
304
+ def _unsigned(term, bits, ranges):
305
+ """Bounds on the term's unsigned value at its width, read from bitwise structure and assumptions.
306
+
307
+ An assumed range, a constant, ``and``, ``or``, ``xor``, a shift right or division by a constant
308
+ (an arithmetic shift only when its operand's sign bit is clear), a remainder by a constant, a zero extension or an extracted field narrows the width's full
309
+ range; any other term keeps it.
310
+ """
311
+ if (term, bits) in ranges:
312
+ return ranges[(term, bits)]
313
+ top = (1 << bits) - 1
314
+ tag = term[0]
315
+ if tag == "constant":
316
+ return term[1] & top, term[1] & top
317
+ if tag in ("and", "or", "xor"):
318
+ (alo, ahi), (blo, bhi) = _unsigned(term[1], bits, ranges), _unsigned(term[2], bits, ranges)
319
+ if tag == "and":
320
+ return 0, min(ahi, bhi)
321
+ # Neither operand sets a bit above its own highest bit; OR keeps every bit of each operand.
322
+ return max(alo, blo) if tag == "or" else 0, (1 << max(ahi, bhi).bit_length()) - 1
323
+ if tag in ("shr", "sar", "udiv", "umod") and term[2][0] == "constant":
324
+ lo, hi = _unsigned(term[1], bits, ranges)
325
+ k = term[2][1] & top
326
+ if tag == "sar" and hi >> (bits - 1):
327
+ # An operand that may have its sign bit set shifts ones in from the top.
328
+ return 0, top
329
+ if tag in ("shr", "sar"):
330
+ # With the sign bit clear, an arithmetic shift right is the logical one.
331
+ # Shift terms carry x86's five-bit count mask; a count the mask changes keeps only the upper bound.
332
+ s = k & 31
333
+ return lo >> s if s == k else 0, hi >> s
334
+ if k == 0:
335
+ return 0, top
336
+ return (lo // k, hi // k) if tag == "udiv" else (0, min(hi, k - 1))
337
+ if tag == "zeroExtend" and term[3] == bits:
338
+ return _unsigned(term[1], term[2], ranges)
339
+ if tag == "extract" and term[3] == bits:
340
+ lo, hi = _unsigned(term[1], term[4], ranges)
341
+ low = term[2]
342
+ if hi >> low <= top:
343
+ return lo >> low, hi >> low
344
+ return 0, top
304
345
 
305
346
 
306
347
  def _interval(form, ranges):
@@ -529,6 +570,13 @@ def _ranges(control, path, anchor):
529
570
  if a["max"] >= 1 << atom[1]:
530
571
  raise ValueError(f"Relational control {control['name']} assumption range exceeds the value's width")
531
572
  ranges[atom] = (a["min"], a["max"])
573
+ # The assumed value's own expression may bound it too: keep the narrower range, and refuse an
574
+ # assumption the expression rules out, since a relation would hold over an empty range.
575
+ for atom, (lo, hi) in list(ranges.items()):
576
+ slo, shi = _unsigned(atom[0], atom[1], {k: v for k, v in ranges.items() if k != atom})
577
+ if lo > shi or hi < slo:
578
+ raise _Unresolved(f"the assumed range {lo}..{hi} is outside the range {slo}..{shi} the value's expression allows here")
579
+ ranges[atom] = max(lo, slo), min(hi, shi)
532
580
  return ranges
533
581
 
534
582
 
@@ -110,6 +110,60 @@ class OrderTests(unittest.TestCase):
110
110
  self.assertIn("not shown equal", occurrence["reason"])
111
111
  self.assertEqual(result["queryAssumptions"]["callModels"], [self.c.labels["service"]])
112
112
 
113
+ def reload(self, store, registers=FRAME, scopes=None):
114
+ # Load a word, test it, run `store` on the nonzero branch, then reload the same word. With
115
+ # `scopes`, a modeled service with those preservesMemory scopes follows the store.
116
+ self.c = Code().emit("a1 00 01 85 c0").label("test").branch("74", "out").emit(store)
117
+ if scopes is not None:
118
+ self.c.label("service").branch("e8", "external")
119
+ self.c.label("use").emit("8b 1e 00 01").label("out").emit("c3").label("external").emit("c3")
120
+ rule = control("reload", "order", before={"site": self.c.labels["test"], "event": "branch"},
121
+ branch={"taken": False}, sameValue={"before": "left", "at": "value"},
122
+ at={"site": self.c.labels["use"], "event": "read"})
123
+ models = [] if scopes is None else [{"site": self.c.labels["service"], "evidence": "synthetic unread service",
124
+ "preserves": ["ds"], "preservesMemory": scopes, "cases": [{}]}]
125
+ return verdict(run(self.c, [rule], registers=registers, callModels=models), "reload")
126
+
127
+ def test_a_reload_keeps_the_tested_word_across_writes_that_cannot_store_it(self):
128
+ for name, store, registers in (
129
+ ("no write", "", {}),
130
+ ("disjoint word", "c7 06 00 02 01 00", {}),
131
+ ("adjacent byte", "c6 06 02 01 05", {}),
132
+ ("another segment register with the same value", "26 c7 06 00 02 01 00", {"es": FRAME["ds"]}),
133
+ ("another segment whose bytes lie elsewhere", "26 c7 06 00 01 01 00", {"es": 0x5000})):
134
+ with self.subTest(name):
135
+ self.assertEqual(self.reload(store, {**FRAME, **registers})["verdict"], "held")
136
+
137
+ def test_a_reload_after_a_write_that_may_store_the_word_is_undecided(self):
138
+ for name, store, registers in (
139
+ ("same word", "c7 06 00 01 01 00", {}),
140
+ ("high byte", "c6 06 01 01 05", {}),
141
+ ("unknown offset", "c7 07 01 00", {}),
142
+ ("unknown segment", "26 c7 06 00 02 01 00", {}),
143
+ ("another segment register naming the same bytes", "26 c7 06 00 01 01 00", {"es": FRAME["ds"]})):
144
+ with self.subTest(name):
145
+ result = self.reload(store, {**FRAME, **registers})
146
+ self.assertEqual(result["verdict"], "undecided")
147
+ occurrence = next(o for p in result["paths"] for o in p["occurrences"])
148
+ self.assertIn("not shown equal", occurrence["reason"])
149
+
150
+ def test_a_reload_through_an_unknown_segment_keeps_the_word_across_a_write_at_another_offset(self):
151
+ # DS is unknown: both accesses use its one value, so the offsets alone keep them apart.
152
+ for store, expected in (("c7 06 00 02 01 00", "held"), ("c6 06 00 01 05", "undecided")):
153
+ with self.subTest(store):
154
+ self.assertEqual(self.reload(store, {"ss": 0x3000, "sp": 0xff00})["verdict"], expected)
155
+
156
+ def test_a_reload_after_a_modeled_service_is_undecided_unless_a_scope_keeps_the_word(self):
157
+ # Without a scope the service may store the word. A preservesMemory scope over it keeps the
158
+ # term the first load read, across a disjoint write before the call too.
159
+ word = {"segment": "ds", "base": "bx", "displacement": 0x100, "bytes": 2, "evidence": "synthetic kept word"}
160
+ for name, store, scopes, expected in (
161
+ ("no scope", "", [], "undecided"),
162
+ ("scope over the word", "", [word], "held"),
163
+ ("scope after a disjoint write", "c7 06 00 02 01 00", [word], "held")):
164
+ with self.subTest(name):
165
+ self.assertEqual(self.reload(store, {**FRAME, "bx": 0}, scopes)["verdict"], expected)
166
+
113
167
  def test_a_wrong_direction_before_an_unread_call_is_undecided(self):
114
168
  # The helper's test runs once traced, then again inside a modeled call before the access.
115
169
  self.c = (Code().branch("e8", "helper").label("service").branch("e8", "helper").label("use").emit("8a 07 c3")
@@ -594,6 +648,95 @@ class RelationTests(unittest.TestCase):
594
648
  self.assertEqual(verdict(run(c, [bounded], registers=FRAME), "byte")["verdict"], "held")
595
649
 
596
650
 
651
+ class BitwiseBoundTests(unittest.TestCase):
652
+ """Unsigned bounds read from masks, shifts, division and extracted fields of an unknown loaded word."""
653
+
654
+ def check(self, body, op, right, signed=False, before=""):
655
+ # mov bx,[0200h] (or the body's own load), then the body, then a checkpoint at the return.
656
+ self.c = Code().emit(before).emit(body).label("return").emit("c3")
657
+ left = {"field": "registers.bx", **({"signed": True} if signed else {})}
658
+ rule = control("bound", "relation", at={"site": self.c.labels["return"], "event": "checkpoint"}, op=op, left=left, right=right)
659
+ return verdict(run(self.c, [rule], registers=FRAME), "bound")
660
+
661
+ def test_a_constant_mask_bounds_an_unknown_word(self):
662
+ # and bx,3
663
+ held = self.check("8b 1e 00 02 81 e3 03 00", "le", 3)
664
+ self.assertEqual(held["verdict"], "held")
665
+ self.assertEqual(held["paths"][0]["occurrences"][0]["leftMinusRight"], {"min": -3, "max": 0})
666
+ self.assertEqual(self.check("8b 1e 00 02 81 e3 03 00", "le", 2)["verdict"], "undecided")
667
+ with self.assertRaisesRegex(ValueError, "bound violated"):
668
+ self.check("8b 1e 00 02 81 e3 03 00", "gt", 3)
669
+
670
+ def test_an_unmasked_word_stays_undecided(self):
671
+ self.assertEqual(self.check("8b 1e 00 02", "le", 3)["verdict"], "undecided")
672
+
673
+ def test_a_mask_with_the_sign_bit_leaves_the_signed_value_undecided(self):
674
+ # and bx,8003h: the unsigned value is at most 8003h, while the signed value may be negative.
675
+ self.assertEqual(self.check("8b 1e 00 02 81 e3 03 80", "le", 0x8003)["verdict"], "held")
676
+ self.assertEqual(self.check("8b 1e 00 02 81 e3 03 80", "ge", 0, signed=True)["verdict"], "undecided")
677
+ # With the sign bit masked off, the signed value is the unsigned one.
678
+ self.assertEqual(self.check("8b 1e 00 02 81 e3 03 00", "ge", 0, signed=True)["verdict"], "held")
679
+
680
+ def test_shifts_extracted_fields_and_division_by_constants_bound_the_value(self):
681
+ # shr bx,4
682
+ self.assertEqual(self.check("8b 1e 00 02 c1 eb 04", "le", 0x0fff)["verdict"], "held")
683
+ self.assertEqual(self.check("8b 1e 00 02 c1 eb 04", "le", 0x0ffe)["verdict"], "undecided")
684
+ # mov ax,[0200h]; and ax,0FF0h; movzx bx,ah: the high byte of the masked word is at most 0Fh.
685
+ self.assertEqual(self.check("a1 00 02 25 f0 0f 0f b6 dc", "le", 0x0f)["verdict"], "held")
686
+ self.assertEqual(self.check("a1 00 02 25 f0 0f 0f b6 dc", "le", 0x0e)["verdict"], "undecided")
687
+ # xor dx,dx; mov ax,[0200h]; mov cx,10; div cx; then the remainder or the quotient into BX.
688
+ divide = "31 d2 a1 00 02 b9 0a 00 f7 f1"
689
+ self.assertEqual(self.check(divide + " 89 d3", "le", 9)["verdict"], "held")
690
+ self.assertEqual(self.check(divide + " 89 d3", "le", 8)["verdict"], "undecided")
691
+ self.assertEqual(self.check(divide + " 89 c3", "le", 0xffff // 10)["verdict"], "held")
692
+ self.assertEqual(self.check(divide + " 89 c3", "le", 0xffff // 10 - 1)["verdict"], "undecided")
693
+
694
+ def test_an_arithmetic_shift_is_bounded_only_when_the_sign_bit_is_clear(self):
695
+ # and bx,7FFFh; sar bx,4: the sign bit is clear, so the shift is a logical one.
696
+ self.assertEqual(self.check("8b 1e 00 02 81 e3 ff 7f c1 fb 04", "le", 0x07ff)["verdict"], "held")
697
+ self.assertEqual(self.check("8b 1e 00 02 81 e3 ff 7f c1 fb 04", "le", 0x07fe)["verdict"], "undecided")
698
+ # sar bx,4 of an unmasked word may shift ones in from the top.
699
+ self.assertEqual(self.check("8b 1e 00 02 c1 fb 04", "le", 0xfffe)["verdict"], "undecided")
700
+
701
+ def test_or_keeps_its_constant_bits_and_the_operands_highest_bit(self):
702
+ # movzx bx,byte [0200h]; or bx,10h
703
+ self.assertEqual(self.check("0f b6 1e 00 02 83 cb 10", "ge", 0x10)["verdict"], "held")
704
+ self.assertEqual(self.check("0f b6 1e 00 02 83 cb 10", "le", 0xff)["verdict"], "held")
705
+ self.assertEqual(self.check("0f b6 1e 00 02 83 cb 10", "le", 0xfe)["verdict"], "undecided")
706
+
707
+ def test_an_assumed_range_bounds_the_masked_operand(self):
708
+ # mov bx,cx; and bx,0FFh, with CX assumed at most 7.
709
+ c = Code().emit("89 cb 81 e3 ff 00").label("return").emit("c3")
710
+ rule = control("bound", "relation", at={"site": c.labels["return"], "event": "checkpoint"}, op="le",
711
+ left={"field": "registers.bx"}, right=7)
712
+ self.assertEqual(verdict(run(c, [rule], registers=FRAME), "bound")["verdict"], "undecided")
713
+ assumed = {**rule, "assume": [{"value": {"entryRegister": "cx"}, "min": 0, "max": 7, "evidence": "synthetic caller range"}]}
714
+ self.assertEqual(verdict(run(c, [assumed], registers=FRAME), "bound")["verdict"], "held")
715
+
716
+ def test_an_assumption_on_a_masked_value_keeps_the_narrower_range(self):
717
+ # mov bx,[0200h]; and bx,3, with BX itself assumed at most 100: the mask still bounds it by 3.
718
+ c = Code().emit("8b 1e 00 02 81 e3 03 00").label("return").emit("c3")
719
+
720
+ def bound(op, right, lo, hi):
721
+ rule = control("bound", "relation", at={"site": c.labels["return"], "event": "checkpoint"}, op=op,
722
+ left={"field": "registers.bx"}, right=right,
723
+ assume=[{"value": {"field": "registers.bx"}, "min": lo, "max": hi, "evidence": "synthetic range"}])
724
+ return verdict(run(c, [rule], registers=FRAME), "bound")
725
+
726
+ self.assertEqual(bound("le", 3, 0, 100)["verdict"], "held")
727
+ self.assertEqual(bound("le", 1, 0, 1)["verdict"], "held")
728
+ # A range the mask rules out would make any relation hold, so the occurrence is undecided.
729
+ excluded = bound("ge", 5, 5, 10)
730
+ self.assertEqual(excluded["verdict"], "undecided")
731
+ self.assertIn("outside the range 0..3", excluded["paths"][0]["occurrences"][0]["reason"])
732
+
733
+ def test_a_stopped_path_leaves_a_masked_bound_undecided(self):
734
+ # One path calls through BX and stops before the masked load.
735
+ result = self.check("8b 1e 00 02 81 e3 03 00", "le", 3, before="85 c0 74 02 ff d3")
736
+ self.assertEqual(result["verdict"], "undecided")
737
+ self.assertIn("stopped", " ".join(result["reasons"]))
738
+
739
+
597
740
  class OriginTests(unittest.TestCase):
598
741
  def recursion(self, local=""):
599
742
  # The helper counts AX down and returns FFFF from its base case; the root tests the result.