scientific-method-engine 10.1.1__tar.gz → 12.0.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 (74) hide show
  1. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/PKG-INFO +14 -1
  2. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/README.md +13 -0
  3. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/pyproject.toml +1 -1
  4. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/x86/machine.py +6 -3
  5. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/x86/pcode_backend.py +24 -1
  6. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/x86/trace.py +86 -9
  7. scientific_method_engine-12.0.0/tests/test_enter_frames.py +135 -0
  8. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/tests/test_entry_frame.py +2 -2
  9. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/tests/test_oracle.py +13 -0
  10. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/tests/test_pe.py +20 -0
  11. scientific_method_engine-12.0.0/tests/test_return_checks.py +247 -0
  12. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/tests/test_x86.py +1 -1
  13. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/.gitignore +0 -0
  14. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/LICENSE +0 -0
  15. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/__init__.py +0 -0
  16. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/__main__.py +0 -0
  17. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/cli.py +0 -0
  18. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/ClearNoReturnFunctions.java +0 -0
  19. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/CreateFunctions.java +0 -0
  20. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/ExportBoundedFlow.java +0 -0
  21. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/ExportCallEdges.java +0 -0
  22. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/ExportFunctionFingerprints.java +0 -0
  23. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/ExportFunctionInventory.java +0 -0
  24. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/MergeFallThroughFragment.java +0 -0
  25. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/RecoverCitedFunctions.java +0 -0
  26. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/RepairReturningCallers.java +0 -0
  27. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/ReportCallArguments.java +0 -0
  28. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/ReportCallPaths.java +0 -0
  29. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/ReportCallSitesWithScalars.java +0 -0
  30. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/ReportCallsToRange.java +0 -0
  31. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/ReportConstantFirstArgumentCalls.java +0 -0
  32. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/ReportDataBytes.java +0 -0
  33. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/ReportDecompileMatches.java +0 -0
  34. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/ReportDecompileWindow.java +0 -0
  35. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/ReportFilePatternInMemory.java +0 -0
  36. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/ReportFirstArgumentCallSummary.java +0 -0
  37. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/ReportFunctionScalarConstants.java +0 -0
  38. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/ReportFunctionSummary.java +0 -0
  39. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/ReportInstructionContext.java +0 -0
  40. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/ReportInstructionWindow.java +0 -0
  41. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/ReportMemoryBlockForFileOffset.java +0 -0
  42. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/ReportMemoryBlocks.java +0 -0
  43. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/ReportRandomnessCandidates.java +0 -0
  44. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/ReportReferences.java +0 -0
  45. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/ReportScalarConstants.java +0 -0
  46. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/ReportStringReferences.java +0 -0
  47. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/ReportSymbolReferences.java +0 -0
  48. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/scientificmethod/FirstArgumentLookBack.java +0 -0
  49. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/ghidra/scientificmethod/InstructionStart.java +0 -0
  50. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/x86/__init__.py +0 -0
  51. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/x86/argument_frames.py +0 -0
  52. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/x86/dispatch.py +0 -0
  53. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/x86/effect_order.py +0 -0
  54. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/x86/image.py +0 -0
  55. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/x86/loops.py +0 -0
  56. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/x86/memory_scopes.py +0 -0
  57. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/x86/pcode.py +0 -0
  58. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/x86/pe.py +0 -0
  59. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/x86/relational.py +0 -0
  60. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/x86/reports.py +0 -0
  61. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/x86/result_flow.py +0 -0
  62. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/src/scientific_method_engine/x86/values.py +0 -0
  63. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/tests/oracle.py +0 -0
  64. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/tests/test_continuation_budget.py +0 -0
  65. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/tests/test_dispatch.py +0 -0
  66. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/tests/test_effect_order.py +0 -0
  67. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/tests/test_indirect_far_transfers.py +0 -0
  68. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/tests/test_interrupt_models.py +0 -0
  69. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/tests/test_loops.py +0 -0
  70. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/tests/test_memory_scopes.py +0 -0
  71. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/tests/test_nested_frame_request.py +0 -0
  72. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/tests/test_relational_controls.py +0 -0
  73. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/tests/test_successor_rule.py +0 -0
  74. {scientific_method_engine-10.1.1 → scientific_method_engine-12.0.0}/tests/test_table_continuations.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: scientific-method-engine
3
- Version: 10.1.1
3
+ Version: 12.0.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
@@ -188,3 +188,16 @@ so the function's return balances and its paths can be read to the end. The repo
188
188
  gives the offsets, or the reasons the frame is not established, in which case the query runs as
189
189
  it would without the input. See the
190
190
  [narrower entry contract](https://github.com/kibertoad/refurbished-dinosaurs-toolkit/blob/main/docs/bounded-evidence-reporters.md#a-narrower-entry-inside-its-functions-frame).
191
+
192
+ Each `return` event carries `returnCheck`: the frame's and the instruction's return widths, SP's
193
+ offset from the frame's entry SP, and whether the return words were read and compared with the
194
+ call. A width mismatch and an unbalanced stack stop the path with separate reasons. A root return
195
+ never reads its return words, so `returned: true` on a root path says nothing about them. See the
196
+ [command overview](https://github.com/kibertoad/refurbished-dinosaurs-toolkit/blob/main/docs/bounded-evidence-reporters.md#commands).
197
+
198
+ A traced callee that rebuilds its return frame at the other width (`pop ax; push cs; push ax;
199
+ retf` over a near call, or a near return over a far frame it shortened) returns to its caller when
200
+ the return's words end where the call's frame ended (`returnCheck.endsAtFrameEnd`), the offset word
201
+ is the call's return IP, and the segment, popped or kept in CS, is the call's CS. Any other
202
+ conversion stops with the reason of the check it failed. See
203
+ [converted call frames](https://github.com/kibertoad/refurbished-dinosaurs-toolkit/blob/main/docs/bounded-evidence-reporters.md#converted-call-frames).
@@ -172,3 +172,16 @@ so the function's return balances and its paths can be read to the end. The repo
172
172
  gives the offsets, or the reasons the frame is not established, in which case the query runs as
173
173
  it would without the input. See the
174
174
  [narrower entry contract](https://github.com/kibertoad/refurbished-dinosaurs-toolkit/blob/main/docs/bounded-evidence-reporters.md#a-narrower-entry-inside-its-functions-frame).
175
+
176
+ Each `return` event carries `returnCheck`: the frame's and the instruction's return widths, SP's
177
+ offset from the frame's entry SP, and whether the return words were read and compared with the
178
+ call. A width mismatch and an unbalanced stack stop the path with separate reasons. A root return
179
+ never reads its return words, so `returned: true` on a root path says nothing about them. See the
180
+ [command overview](https://github.com/kibertoad/refurbished-dinosaurs-toolkit/blob/main/docs/bounded-evidence-reporters.md#commands).
181
+
182
+ A traced callee that rebuilds its return frame at the other width (`pop ax; push cs; push ax;
183
+ retf` over a near call, or a near return over a far frame it shortened) returns to its caller when
184
+ the return's words end where the call's frame ended (`returnCheck.endsAtFrameEnd`), the offset word
185
+ is the call's return IP, and the segment, popped or kept in CS, is the call's CS. Any other
186
+ conversion stops with the reason of the check it failed. See
187
+ [converted call frames](https://github.com/kibertoad/refurbished-dinosaurs-toolkit/blob/main/docs/bounded-evidence-reporters.md#converted-call-frames).
@@ -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.1.1"
8
+ version = "12.0.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"
@@ -190,11 +190,14 @@ class State:
190
190
  if frame["bp"] is not None:
191
191
  self.setreg(self.bp, op("add", base, const(frame["bp"], self.bits)), None)
192
192
 
193
- def frame_offset(self, value):
194
- """A register value as a signed offset from the current frame's entry SP, or None when it is not one."""
193
+ def frame_offset(self, value, absolute=False):
194
+ """A register value as a signed offset from the current frame's entry SP, or None when it is not one.
195
+
196
+ Two concrete values count as an offset from each other only with ``absolute``.
197
+ """
195
198
  base, delta = address_parts(self.frames[-1]["sp"])
196
199
  other, other_delta = address_parts(value)
197
- if other != base or base == ("absolute",):
200
+ if other != base or (base == ("absolute",) and not absolute):
198
201
  return None
199
202
  offset = (other_delta - delta) % (1 << self.bits)
200
203
  return offset - (1 << self.bits) if offset >> (self.bits - 1) else offset
@@ -611,9 +611,32 @@ def pop(state, ins, image):
611
611
  def leave(state, ins, image):
612
612
  if 0x66 in ins.prefix:
613
613
  raise StopPath("Operand-size override on LEAVE is unsupported")
614
+ # The CPU takes LEAVE's stack address size from SS, but SLEIGH lifts an address-size override
615
+ # with the other stack pointer width (ESP in real mode, SP in flat mode).
616
+ if 0x67 in ins.prefix:
617
+ raise StopPath("Address-size override on LEAVE is unsupported")
614
618
  run_plain(state, ins, image)
615
619
 
616
620
 
621
+ def enter(state, ins, image):
622
+ # SLEIGH lifts an operand-size override on ENTER with the default-size push, so p-code and the
623
+ # CPU would disagree on the saved frame pointer's width.
624
+ if 0x66 in ins.prefix:
625
+ raise StopPath("Operand-size override on ENTER is unsupported")
626
+ # The CPU takes ENTER's stack address size from SS, but SLEIGH lifts an address-size override
627
+ # with the other stack pointer width (ESP in real mode, SP in flat mode).
628
+ if 0x67 in ins.prefix:
629
+ raise StopPath("Address-size override on ENTER is unsupported")
630
+ # Nesting levels 0 and 1 lift to straight-line pushes and register writes, which run as p-code.
631
+ # Higher levels copy frame pointers from the caller's frame chain in a p-code loop. The CPU
632
+ # uses the level byte modulo 32, so the stop names that level.
633
+ f = Frame(state, ins, image)
634
+ if any(o.code == "CBRANCH" for o in f.ops):
635
+ raise StopPath(f"ENTER nesting level {ins.operands[1].imm & 0x1F} copies the caller's frame chain, "
636
+ "which is not modeled")
637
+ f.execute()
638
+
639
+
617
640
  def flags_frame(state, ins, image):
618
641
  # PUSHF/POPF keep the evidence layer's opaque flags snapshot; p-code supplies the width.
619
642
  ops, _ = LIFTER.ops(state.flat, ins.bytes, state.at)
@@ -970,7 +993,7 @@ def interrupt(state, ins, image):
970
993
  HANDLERS = {}
971
994
  for names, handler in ((("mov", "movzx", "movsx", "xchg"), move), (("nop",), nop), (("lea",), lea),
972
995
  (("lds", "les"), far_pointer), (("push",), push), (("pop",), pop), (("leave",), leave),
973
- (("pushf", "pushfd", "popf", "popfd"), flags_frame), (("cmp", "test"), compare),
996
+ (("enter",), enter), (("pushf", "pushfd", "popf", "popfd"), flags_frame), (("cmp", "test"), compare),
974
997
  (("add", "sub", "and", "or", "xor"), arithmetic), (("inc", "dec"), step), (("not",), invert),
975
998
  (("neg",), negate), (("adc", "sbb"), carry_arithmetic), (("clc", "stc", "cmc"), carry_flag),
976
999
  (("shl", "sal", "shr", "sar"), shift), (("rol", "ror", "rcl", "rcr"), rotate),
@@ -398,6 +398,73 @@ def snapshot(state):
398
398
  return {name: state.reg(name).report() for name in ALIASES}
399
399
 
400
400
 
401
+ # The stop for each failed combination of (widthMatches, stackBalanced) at a return.
402
+ RETURN_CHECK_STOPS = {(False, True): "return width differs from the call frame",
403
+ (True, False): "stack balance differs from the call",
404
+ (False, False): "return width and stack balance differ from the call frame"}
405
+ ENTRY_TARGET_UNREAD = "not read: the entry frame has no traced caller"
406
+ CHECK_FAILED_UNREAD = "not read: the width or stack balance check failed"
407
+ WORD_READ_STOPPED = "not compared: reading the return words stopped the path"
408
+ TARGET_CHECK_FAILED_UNREAD = "not read: the return target check failed"
409
+ WORD_VALUE_UNKNOWN = "not compared: the word read and the call's word are not both known values"
410
+ # The stop for a segment that is not the call's CS, by return kind and by whether both values are known.
411
+ # A near return over a far call frame the callee converted leaves CS as it is; it must be the call's.
412
+ SEGMENT_STOPS = {("retf", True): "far return segment changed",
413
+ ("retf", False): "far return segment is not known to be the call's",
414
+ ("ret", True): "CS after a near return over a far call frame is not the call's segment",
415
+ ("ret", False): "CS after a near return over a far call frame is not known to be the call's segment"}
416
+
417
+
418
+ def return_word_check(matches, known):
419
+ """The ``target`` or ``segment`` entry for a return word read from the stack. A word that is not
420
+ the call's is reported as different only when both values are known; otherwise neither a match
421
+ nor a difference was shown."""
422
+ return "matches the call" if matches else "does not match the call" if known else WORD_VALUE_UNKNOWN
423
+
424
+
425
+ def return_followed(check):
426
+ """Whether a return passed its frame checks: the width and balance match, or the frame is a traced
427
+ call frame its callee converted to the other width so that the popped words end at its end."""
428
+ if check["widthMatches"]:
429
+ return check["stackBalanced"]
430
+ return check["frame"] == "call" and check["endsAtFrameEnd"]
431
+
432
+
433
+ def return_check(state, frame, instruction_bytes, far):
434
+ """The checks a return makes against its frame, before any return word is read.
435
+
436
+ ``endsAtFrameEnd`` says whether the words the instruction pops end where the frame's return
437
+ words ended. With equal widths that is the balance check. With different widths it is the
438
+ condition for a converted frame: a traced callee that rebuilt its near frame as a far one, or
439
+ its far frame as a near one, so that its return leaves SP where the call's own return would.
440
+ A traced call's frame that meets it has its return words read and compared with the call as
441
+ for a matching return. The root frame has no traced caller, so its conversion is not followed.
442
+
443
+ ``target`` (and ``segment`` for a far return, or a near return over a traced far call frame)
444
+ records whether the return words were read and compared with the call. An entry frame's are
445
+ never read, so a returned root path says nothing about what its return words hold.
446
+ """
447
+ sp, entry_sp = state.reg(state.sp), frame["sp"]
448
+ offset = state.frame_offset(sp, absolute=True)
449
+ root = len(state.frames) == 1
450
+ width_matches = frame["returnBytes"] == instruction_bytes
451
+ balanced = sp.term == entry_sp.term
452
+ ends = balanced if width_matches else offset is not None and offset + instruction_bytes == frame["returnBytes"]
453
+ check = {"frame": "entry" if root else "call",
454
+ "frameBytes": frame["returnBytes"], "instructionBytes": instruction_bytes,
455
+ "widthMatches": width_matches, "spOffset": offset, "stackBalanced": balanced,
456
+ "endsAtFrameEnd": ends}
457
+ if "frameSource" in frame:
458
+ check["frameSource"] = frame["frameSource"]
459
+ check["target"] = (ENTRY_TARGET_UNREAD if root else WORD_READ_STOPPED if return_followed(check)
460
+ else CHECK_FAILED_UNREAD)
461
+ # A near return narrower than a traced call's frame is one over a far frame, whose CS it compares.
462
+ # A near return over a frame of its own width (a PE32 near call's four bytes) has no segment.
463
+ if far or not (root or width_matches):
464
+ check["segment"] = check["target"]
465
+ return check
466
+
467
+
401
468
  STRING_BUDGET_STOP = "String iteration budget exhausted"
402
469
  # The accepted range and default of each ordinary path budget input. continuationBudget takes the
403
470
  # same ranges under the names in CONTINUATION_BUDGET_FIELDS, except that its paths may be 0.
@@ -929,7 +996,7 @@ def trace(image, config, continue_declared_jumps=True, track_loops=True, arrive=
929
996
  if state.argument_window:
930
997
  call_event["argumentSlots"] = state.argument_slots(call_event["returnFrameBytes"], state.argument_window)
931
998
  state.frames.append({"entry": target, "sp": state.reg(state.sp), "returnBytes": call_event["returnFrameBytes"],
932
- "frameSource": "push-CS/near-call; matching far return required" if push_cs else m,
999
+ "frameSource": "push-CS/near-call" if push_cs else m,
933
1000
  "continuation": following, "returnIP": return_ip, "callSite": at,
934
1001
  "callerCS": state.reg("cs"), "localFlagsFrame": flags_frame})
935
1002
  if m == "lcall":
@@ -961,23 +1028,33 @@ def trace(image, config, continue_declared_jumps=True, track_loops=True, arrive=
961
1028
  raise StopPath("Far return is outside the PE32 flat model")
962
1029
  frame = state.frames[-1]
963
1030
  roles = result_contracts(state, contracts, frame["entry"])
1031
+ # The entry frame gets the same width and balance checks as a traced call. The return
1032
+ # words are read only for a traced call, after both checks pass or over a converted frame.
1033
+ check = return_check(state, frame, 4 if m == "retf" else image.bits // 8, m == "retf")
964
1034
  state.event("return", registers=snapshot(state), cleanupBytes=ins.operands[0].imm if ins.operands else 0,
965
1035
  resultContracts=roles, callSite=frame.get("callSite"),
966
- callerEntry=state.frames[-2]["entry"] if len(state.frames) > 1 else None)
967
- # The entry frame gets the same width and balance checks as a traced call.
968
- expected = 4 if m == "retf" else image.bits // 8
969
- if expected != frame["returnBytes"] or state.reg(state.sp).term != frame["sp"].term:
970
- raise StopPath("return frame or stack balance differs from the call")
1036
+ callerEntry=state.frames[-2]["entry"] if len(state.frames) > 1 else None, returnCheck=check)
1037
+ if not return_followed(check):
1038
+ raise StopPath(RETURN_CHECK_STOPS[check["widthMatches"], check["stackBalanced"]])
971
1039
  if len(state.frames) == 1:
972
1040
  finish(state, returned=True)
973
1041
  break
974
1042
  actual_ip = state.pop(image.bits // 8)
1043
+ check["target"] = return_word_check(actual_ip.number == frame["returnIP"], actual_ip.number is not None)
975
1044
  if actual_ip.number != frame["returnIP"]:
1045
+ if "segment" in check:
1046
+ check["segment"] = TARGET_CHECK_FAILED_UNREAD
976
1047
  raise StopPath("return target was overwritten or has unknown provenance")
977
- if m == "retf":
978
- actual_cs = state.pop(2)
1048
+ # A far return reads the segment word; a near return over a converted far frame keeps CS.
1049
+ actual_cs = state.pop(2) if m == "retf" else state.reg("cs") if "segment" in check else None
1050
+ if actual_cs is not None:
1051
+ # The same term is the same value, known or not. A different term is a different
1052
+ # segment only when both values are known.
1053
+ known = actual_cs.number is not None and frame["callerCS"].number is not None
1054
+ check["segment"] = return_word_check(actual_cs.term == frame["callerCS"].term, known)
979
1055
  if actual_cs.term != frame["callerCS"].term:
980
- raise StopPath("far return segment changed")
1056
+ raise StopPath(SEGMENT_STOPS["retf" if m == "retf" else "ret", known])
1057
+ if m == "retf":
981
1058
  state.setreg("cs", actual_cs, at)
982
1059
  if ins.operands:
983
1060
  state.setreg(state.sp, op("add", state.reg(state.sp), const(ins.operands[0].imm, image.bits), at), at)
@@ -0,0 +1,135 @@
1
+ """ENTER frames: the saved frame pointer, BP and the local allocation come from ENTER's p-code. Synthetic code only."""
2
+ import unittest
3
+
4
+ from test_x86 import Code, events, report
5
+
6
+ ENTRY_SP = ("unknown", "entry:sp")
7
+ INITIAL_BP = ("extract", ("unknown", "initial:ebp"), 0, 16, 32)
8
+ # mov ax, 1234h; leave; retf
9
+ BODY = "b8 34 12 c9 cb"
10
+
11
+
12
+ def below_entry(n):
13
+ """The offset expression for entry SP minus ``n``, wrapped to 16 bits."""
14
+ return ("offset", ENTRY_SP, -n % 0x10000)
15
+
16
+
17
+ def far(code, **extra):
18
+ return report(code, **{"returnBytes": 4, "maxSteps": 12, "maxPaths": 2, **extra})
19
+
20
+
21
+ def frame(size, level=0):
22
+ """ENTER size,level; mov ax, bp; mov cx, sp; leave; retf, with BP and SP copied out after ENTER."""
23
+ return far(f"c8 {size & 0xFF:02x} {size >> 8:02x} {level:02x} 89 e8 89 e1 c9 cb")
24
+
25
+
26
+ class EnterFrames(unittest.TestCase):
27
+ def test_enter_returns_as_the_explicit_prologue_does(self):
28
+ for size in ("04 00", "00 00"):
29
+ explicit = far("55 89 e5 83 ec " + size[:2] + " " + BODY)
30
+ entered = far(f"c8 {size} 00 " + BODY)
31
+ for r in (explicit, entered):
32
+ self.assertTrue(r["completeWithinModel"], r["paths"][0].get("stop"))
33
+ self.assertEqual(r["paths"][0]["registers"]["ax"]["value"], 0x1234)
34
+
35
+ def test_saved_frame_pointer_write_frame_pointer_and_allocation(self):
36
+ r = frame(4)
37
+ path = r["paths"][0]
38
+ self.assertTrue(r["completeWithinModel"], path.get("stop"))
39
+ saved = events(r, "write")
40
+ self.assertEqual(len(saved), 1)
41
+ self.assertEqual(saved[0]["site"], 0)
42
+ self.assertEqual(saved[0]["role"], "push")
43
+ self.assertEqual(saved[0]["width"], 2)
44
+ self.assertEqual(saved[0]["effectiveSegmentRegister"], "ss")
45
+ self.assertEqual(saved[0]["offset"]["expression"], below_entry(2))
46
+ self.assertEqual(saved[0]["value"]["expression"], INITIAL_BP)
47
+ # BP is the address of the saved frame pointer, and SP sits the local size below it.
48
+ self.assertEqual(path["registers"]["ax"]["expression"], below_entry(2))
49
+ self.assertIn(0, path["registers"]["ax"]["producers"])
50
+ self.assertEqual(path["registers"]["cx"]["expression"], below_entry(6))
51
+ self.assertIn(0, path["registers"]["cx"]["producers"])
52
+ # LEAVE reads the saved frame pointer back, so BP and SP return to their entry values.
53
+ restored = events(r, "read")[-1]
54
+ self.assertEqual((restored["role"], restored["offset"]["expression"]), ("pop", below_entry(2)))
55
+ self.assertEqual(path["registers"]["bp"]["expression"], INITIAL_BP)
56
+
57
+ def test_allocation_sizes_zero_and_the_word_edge_wrap(self):
58
+ self.assertEqual(frame(0)["paths"][0]["registers"]["cx"]["expression"], below_entry(2))
59
+ edge = frame(0xFFFF)
60
+ self.assertTrue(edge["completeWithinModel"], edge["paths"][0].get("stop"))
61
+ self.assertEqual(edge["paths"][0]["registers"]["cx"]["expression"], below_entry(2 + 0xFFFF))
62
+
63
+ def test_nesting_level_one_pushes_the_new_frame_pointer(self):
64
+ r = frame(4, level=1)
65
+ path = r["paths"][0]
66
+ self.assertTrue(r["completeWithinModel"], path.get("stop"))
67
+ writes = events(r, "write")
68
+ self.assertEqual([w["offset"]["expression"] for w in writes], [below_entry(2), below_entry(4)])
69
+ self.assertEqual(writes[1]["value"]["expression"], below_entry(2))
70
+ self.assertEqual(path["registers"]["ax"]["expression"], below_entry(2))
71
+ self.assertEqual(path["registers"]["cx"]["expression"], below_entry(8))
72
+ # p-code takes the level modulo 32, as the CPU does: 21h is level 1.
73
+ self.assertEqual(frame(4, level=0x21)["paths"][0]["registers"]["cx"]["expression"], below_entry(8))
74
+
75
+ def test_nesting_levels_that_copy_the_frame_chain_stop(self):
76
+ # The stop names the level the CPU uses, the byte modulo 32.
77
+ for byte, level in ((2, 2), (0x1F, 31), (0x22, 2), (0xFF, 31)):
78
+ r = far(f"c8 04 00 {byte:02x} " + BODY)
79
+ path = r["paths"][0]
80
+ self.assertFalse(r["completeWithinModel"])
81
+ self.assertFalse(path["returned"])
82
+ self.assertEqual(path["stop"], f"ENTER nesting level {level} copies the caller's frame chain, "
83
+ "which is not modeled")
84
+ self.assertEqual(events(r, "write"), [])
85
+
86
+ def test_operand_size_override_stops(self):
87
+ r = far("66 c8 04 00 00 " + BODY)
88
+ self.assertFalse(r["completeWithinModel"])
89
+ self.assertEqual(r["paths"][0]["stop"], "Operand-size override on ENTER is unsupported")
90
+
91
+ def test_address_size_override_stops_before_any_write(self):
92
+ # SLEIGH lifts 67 C8 in real mode with ESP and no SS base; the CPU still uses SS:SP.
93
+ r = far("67 c8 04 00 00 " + BODY)
94
+ self.assertFalse(r["completeWithinModel"])
95
+ self.assertEqual(r["paths"][0]["stop"], "Address-size override on ENTER is unsupported")
96
+ self.assertEqual(events(r, "write"), [])
97
+
98
+ def test_leave_with_an_address_size_override_stops(self):
99
+ # SLEIGH lifts 67 C9 in real mode with ESP and EBP; the CPU still restores SP from BP.
100
+ r = far("55 89 e5 b8 34 12 67 c9 cb")
101
+ self.assertFalse(r["completeWithinModel"])
102
+ self.assertEqual(r["paths"][0]["stop"], "Address-size override on LEAVE is unsupported")
103
+ self.assertEqual(events(r, "read"), [])
104
+
105
+ def test_a_frame_left_unrestored_does_not_return(self):
106
+ r = far("c8 04 00 00 b8 34 12 cb")
107
+ self.assertFalse(r["paths"][0]["returned"])
108
+ self.assertFalse(r["completeWithinModel"])
109
+
110
+ def test_step_limit_at_enter_stays_incomplete(self):
111
+ r = far("c8 04 00 00 " + BODY, maxSteps=1)
112
+ self.assertFalse(r["completeWithinModel"])
113
+ self.assertFalse(r["paths"][0]["returned"])
114
+ self.assertIn("step limit", r["paths"][0]["stop"])
115
+
116
+ def test_argument_bytes_reach_a_callee_through_its_enter_frame(self):
117
+ # push 1234h; push 5678h; call wrapper; ret | wrapper: enter 2,0; mov ax,[bp+4]; mov dx,[bp+6]; leave; ret 4
118
+ c = (Code().label("low").emit("68 34 12").label("high").emit("68 78 56").branch("e8", "wrapper").emit("c3")
119
+ .label("wrapper").emit("c8 02 00 00 8b 46 04 8b 56 06 c9 c2 04 00"))
120
+ r = report(c)
121
+ path = r["paths"][0]
122
+ self.assertTrue(r["completeWithinModel"], path.get("stop"))
123
+ arguments = [e for e in events(r, "read") if e.get("argument")]
124
+ self.assertEqual([(a["value"]["value"], a["argument"]["offsetFromEntrySP"], a["argument"]["pushProducers"])
125
+ for a in arguments],
126
+ [(0x5678, 2, [c.labels["high"]]), (0x1234, 4, [c.labels["low"]])])
127
+ self.assertEqual((path["registers"]["ax"]["value"], path["registers"]["dx"]["value"]), (0x5678, 0x1234))
128
+ # The wrapper's LEAVE and RET 4 restore the caller's frame.
129
+ returned = events(r, "call-return")[0]
130
+ self.assertEqual(returned["registers"]["sp"]["expression"], ENTRY_SP)
131
+ self.assertEqual(returned["registers"]["bp"]["expression"], INITIAL_BP)
132
+
133
+
134
+ if __name__ == "__main__":
135
+ unittest.main()
@@ -36,7 +36,7 @@ class EntryFrameTests(unittest.TestCase):
36
36
  c = cleanup()
37
37
  r = run(c, relationalControls=slot(c, "entryState"))
38
38
  self.assertNotIn("entryFrame", r)
39
- self.assertEqual({p["stop"] for p in r["paths"]}, {"return frame or stack balance differs from the call"})
39
+ self.assertEqual({p["stop"] for p in r["paths"]}, {"stack balance differs from the call"})
40
40
  self.assertEqual(verdict(r)["verdict"], "undecided")
41
41
 
42
42
  def test_the_observed_frame_lets_the_function_return_and_the_control_hold(self):
@@ -75,7 +75,7 @@ class EntryFrameTests(unittest.TestCase):
75
75
  self.assertFalse(frame["established"])
76
76
  self.assertEqual((frame["sp"], frame["arrivals"]), (None, 2))
77
77
  self.assertIn("different offsets: -4, -2", " ".join(frame["reasons"]))
78
- self.assertEqual({p["stop"] for p in r["paths"]}, {"return frame or stack balance differs from the call"})
78
+ self.assertEqual({p["stop"] for p in r["paths"]}, {"stack balance differs from the call"})
79
79
  result = verdict(r)
80
80
  self.assertEqual(result["verdict"], "undecided")
81
81
  self.assertIn("entryFrame was not established", " ".join(result["reasons"]))
@@ -62,6 +62,19 @@ class Stack(unittest.TestCase):
62
62
  def test_push_pop_and_leave(self):
63
63
  check(self, "b81100 50 6a22 5b 59 55 89e5 6a33 c9 c3", resolved=("bx", "cx", "sp"))
64
64
 
65
+ def test_converted_return_frames(self):
66
+ # call near; mov cx,sp; ret | pop ax; push cs; push ax; retf: the callee returns far over its near frame.
67
+ check(self, "e80300 89e1 c3 58 0e 50 cb", resolved=("ax", "cx", "sp"))
68
+ # push cs; call near; mov cx,sp; ret | pop ax; pop dx; push ax; ret 0: near over the push-CS far frame.
69
+ check(self, "0e e80300 89e1 c3 58 5a 50 c20000", resolved=("ax", "cx", "dx", "sp"))
70
+
71
+ def test_enter_frames(self):
72
+ # mov bp, 1111h; ENTER size,level; mov ax, bp; mov cx, sp; [mov bx,[bp-2]]; mov dx,[bp]; leave; ret
73
+ for enter in ("c8040000", "c8000000", "c8ffff00", "c8040020"):
74
+ check(self, "bd1111 " + enter + " 89e8 89e1 8b5600 c9 c3", resolved=("ax", "cx", "dx", "bp", "sp"))
75
+ for enter in ("c8040001", "c8040021"):
76
+ check(self, "bd1111 " + enter + " 89e8 89e1 8b5efe 8b5600 c9 c3", resolved=("ax", "bx", "cx", "dx", "bp", "sp"))
77
+
65
78
  def test_memory_operands(self):
66
79
  check(self, "bb1000 c7076655 ff37 8f4702 8b4702 c3", registers=DATA, resolved=("ax",))
67
80
 
@@ -392,6 +392,26 @@ class PEReporterTests(unittest.TestCase):
392
392
  self.assertEqual(arg['argument']['offsetFromEntrySP'], 4)
393
393
  self.assertEqual(arg['width'], 4)
394
394
 
395
+ def test_a_nested_near_return_over_a_four_byte_frame_has_no_segment_check(self):
396
+ # A PE32 near call's frame is four bytes, the width of its near return. Nothing reads a segment.
397
+ r = report('e8 01 00 00 00 c3 c3')
398
+ self.assertTrue(r['completeWithinModel'], r)
399
+ check = next(e for e in events(r, 'return') if e['depth'] == 1)['returnCheck']
400
+ self.assertEqual((check['frameBytes'], check['instructionBytes'], check['target']), (4, 4, 'matches the call'))
401
+ self.assertNotIn('segment', check)
402
+
403
+ def test_arguments_follow_an_enter_frame(self):
404
+ c = Code().emit('68 78 56 34 12').branch('e8', 'callee').emit('83 c4 04 c3')
405
+ c.label('callee').emit('c8 08 00 00 8b 45 08 c9 c3')
406
+ r = report(c, 'trace')
407
+ self.assertTrue(r['completeWithinModel'], r)
408
+ saved = next(e for e in events(r, 'write') if e['site'] == CODE_RAW + c.labels['callee'])
409
+ self.assertEqual((saved['role'], saved['width']), ('push', 4))
410
+ arg = next(e for e in events(r, 'read') if e.get('argument'))
411
+ self.assertEqual(arg['value']['value'], 0x12345678)
412
+ self.assertEqual(arg['argument']['offsetFromEntrySP'], 4)
413
+ self.assertEqual(arg['argument']['pushProducers'], [CODE_RAW])
414
+
395
415
  def test_callee_cleanup_and_pointer_plus_independent_word(self):
396
416
  c = Code().emit('68 00 20 40 00 66 68 07 00').branch('e8', 'callee').emit('c3')
397
417
  c.label('callee').emit('55 89 e5 66 8b 45 08 8b 55 0a c9 c2 06 00')
@@ -0,0 +1,247 @@
1
+ """Which checks a return made against its frame (returnCheck), and the stop each failure gives. Synthetic code only."""
2
+ import unittest
3
+ from test_x86 import events, report, run_report
4
+
5
+ ENTRY_UNREAD = "not read: the entry frame has no traced caller"
6
+ CHECK_FAILED = "not read: the width or stack balance check failed"
7
+ UNKNOWN_WORD = "not compared: the word read and the call's word are not both known values"
8
+
9
+
10
+ def only(result, kind="return", depth=None):
11
+ found = [e for e in events(result, kind) if depth is None or e["depth"] == depth]
12
+ assert len(found) == 1, found
13
+ return found[0]
14
+
15
+
16
+ def stops(result):
17
+ return {p["stop"] for p in result["paths"]}
18
+
19
+
20
+ class RootReturnChecks(unittest.TestCase):
21
+ def test_a_far_return_from_a_near_entry_fails_the_width_check_alone(self):
22
+ r = report("cb")
23
+ self.assertEqual(stops(r), {"return width differs from the call frame"})
24
+ self.assertFalse(r["completeWithinModel"])
25
+ self.assertEqual(only(r)["returnCheck"], {
26
+ "frame": "entry", "frameBytes": 2, "instructionBytes": 4, "widthMatches": False,
27
+ "spOffset": 0, "stackBalanced": True, "endsAtFrameEnd": False, "target": ENTRY_UNREAD,
28
+ "segment": ENTRY_UNREAD})
29
+
30
+ def test_a_near_return_from_a_far_entry_fails_the_width_check_alone(self):
31
+ r = report("c3", returnBytes=4)
32
+ self.assertEqual(stops(r), {"return width differs from the call frame"})
33
+ check = only(r)["returnCheck"]
34
+ self.assertEqual((check["frameBytes"], check["instructionBytes"], check["stackBalanced"]), (4, 2, True))
35
+ self.assertNotIn("segment", check)
36
+
37
+ def test_an_extra_push_fails_the_balance_check_alone(self):
38
+ r = report("50 c3")
39
+ self.assertEqual(stops(r), {"stack balance differs from the call"})
40
+ check = only(r)["returnCheck"]
41
+ self.assertEqual((check["widthMatches"], check["stackBalanced"], check["spOffset"]), (True, False, -2))
42
+
43
+ def test_both_failures_are_named_together(self):
44
+ r = report("50 cb")
45
+ self.assertEqual(stops(r), {"return width and stack balance differ from the call frame"})
46
+ check = only(r)["returnCheck"]
47
+ self.assertEqual((check["widthMatches"], check["stackBalanced"], check["spOffset"]), (False, False, -2))
48
+
49
+ def test_the_offset_counts_from_a_concrete_entry_sp(self):
50
+ check = only(report("50 c3", registers={"ss": 0x9000, "sp": 0x8000}))["returnCheck"]
51
+ self.assertEqual((check["spOffset"], check["stackBalanced"]), (-2, False))
52
+
53
+ def test_an_sp_at_no_offset_from_the_entry_reports_no_offset(self):
54
+ # mov sp, ax: SP takes an unknown value unrelated to the entry SP.
55
+ r = report("8b e0 c3")
56
+ self.assertEqual(stops(r), {"stack balance differs from the call"})
57
+ self.assertIsNone(only(r)["returnCheck"]["spOffset"])
58
+
59
+ def test_a_returned_root_path_says_its_return_words_were_not_read(self):
60
+ # Positive control: the declared far entry returns, but nothing checked the root frame's words.
61
+ r = report("cb", returnBytes=4)
62
+ self.assertTrue(r["completeWithinModel"])
63
+ self.assertTrue(r["paths"][0]["returned"])
64
+ self.assertEqual(only(r)["returnCheck"], {
65
+ "frame": "entry", "frameBytes": 4, "instructionBytes": 4, "widthMatches": True,
66
+ "spOffset": 0, "stackBalanced": True, "endsAtFrameEnd": True, "target": ENTRY_UNREAD,
67
+ "segment": ENTRY_UNREAD})
68
+
69
+ def test_a_root_frame_converted_by_its_own_body_is_not_followed(self):
70
+ # pop ax; push cs; push ax; retf from a near entry: the words end at the entry frame's end, but
71
+ # the root has no traced caller to compare them with, so the width and balance stop stays.
72
+ r = report("58 0e 50 cb")
73
+ self.assertEqual(stops(r), {"return width and stack balance differ from the call frame"})
74
+ check = only(r)["returnCheck"]
75
+ self.assertEqual((check["endsAtFrameEnd"], check["target"]), (True, ENTRY_UNREAD))
76
+
77
+
78
+ class TracedCallReturnChecks(unittest.TestCase):
79
+ def test_a_nested_near_return_compares_its_target(self):
80
+ r = report("e8 01 00 c3 c3")
81
+ self.assertTrue(r["completeWithinModel"])
82
+ self.assertEqual(only(r, depth=1)["returnCheck"], {
83
+ "frame": "call", "frameSource": "call", "frameBytes": 2, "instructionBytes": 2, "widthMatches": True,
84
+ "spOffset": 0, "stackBalanced": True, "endsAtFrameEnd": True, "target": "matches the call"})
85
+ self.assertEqual(only(r, depth=0)["returnCheck"]["target"], ENTRY_UNREAD)
86
+
87
+ def test_a_nested_far_return_compares_target_and_segment(self):
88
+ r = report("0e e8 01 00 cb cb", returnBytes=4)
89
+ self.assertTrue(r["completeWithinModel"])
90
+ check = only(r, depth=1)["returnCheck"]
91
+ self.assertEqual((check["frameBytes"], check["target"], check["segment"]), (4, "matches the call", "matches the call"))
92
+ self.assertEqual(check["frameSource"], "push-CS/near-call")
93
+
94
+ def test_an_overwritten_nested_target_is_compared_and_rejected(self):
95
+ # pop ax; push 5; ret
96
+ r = report("e8 01 00 c3 58 6a 05 c3")
97
+ self.assertEqual(stops(r), {"return target was overwritten or has unknown provenance"})
98
+ check = only(r, depth=1)["returnCheck"]
99
+ self.assertEqual((check["widthMatches"], check["stackBalanced"], check["target"]), (True, True, "does not match the call"))
100
+
101
+ def test_a_changed_nested_segment_is_compared_and_rejected(self):
102
+ # pop ax; pop bx; push 0; push ax; retf
103
+ r = report("0e e8 01 00 cb 58 5b 6a 00 50 cb", returnBytes=4)
104
+ self.assertEqual(stops(r), {"far return segment changed"})
105
+ check = only(r, depth=1)["returnCheck"]
106
+ self.assertEqual((check["target"], check["segment"]), ("matches the call", "does not match the call"))
107
+
108
+ def test_an_unknown_nested_target_is_not_reported_as_different(self):
109
+ # pop ax; push bx; ret: BX holds no known value, so the word is neither a match nor a difference.
110
+ r = report("e8 01 00 c3 58 53 c3")
111
+ self.assertEqual(stops(r), {"return target was overwritten or has unknown provenance"})
112
+ self.assertEqual(only(r, depth=1)["returnCheck"]["target"], UNKNOWN_WORD)
113
+
114
+ def test_an_unknown_far_target_leaves_the_segment_unread(self):
115
+ # pop ax; push bx; retf
116
+ r = report("0e e8 01 00 cb 58 53 cb", returnBytes=4)
117
+ check = only(r, depth=1)["returnCheck"]
118
+ self.assertEqual((check["target"], check["segment"]), (UNKNOWN_WORD, "not read: the return target check failed"))
119
+
120
+ def test_an_unknown_nested_segment_is_not_reported_as_different(self):
121
+ # pop ax; pop bx; push dx; push ax; retf
122
+ r = report("0e e8 01 00 cb 58 5b 52 50 cb", returnBytes=4)
123
+ self.assertEqual(stops(r), {"far return segment is not known to be the call's"})
124
+ check = only(r, depth=1)["returnCheck"]
125
+ self.assertEqual((check["target"], check["segment"]), ("matches the call", UNKNOWN_WORD))
126
+
127
+ def test_an_unbalanced_return_over_a_matching_frame_does_not_end_at_the_frame_end(self):
128
+ check = only(report("e8 01 00 c3 50 c3"), depth=1)["returnCheck"]
129
+ self.assertEqual((check["stackBalanced"], check["endsAtFrameEnd"], check["target"]), (False, False, CHECK_FAILED))
130
+
131
+
132
+ # The root calls near 4 and returns far at 3; the callee at 4 converts its near frame before its RETF.
133
+ NEAR_CALL_ROOT = "e8 01 00 cb "
134
+
135
+
136
+ def far_call(callee, segment):
137
+ """``lcall`` to ``callee`` (a hex string) in a region at ``segment``, from a root in segment 1000h."""
138
+ same = segment == 0x1000
139
+ data = bytes.fromhex("9a" + ("0600" if same else "0000") + segment.to_bytes(2, "little").hex() + "c3" + callee)
140
+ regions = [{"name": "caller", "start": 0, "end": 6, "ip": 0, "segment": 0x1000, "resident": True, "entries": [0],
141
+ "evidence": "synthetic declared code extent"},
142
+ {"name": "callee", "start": 6, "end": len(data), "ip": 6 if same else 0, "segment": segment,
143
+ "resident": True, "entries": [6], "evidence": "synthetic declared code extent"}]
144
+ config = {"regions": regions, "entry": 0, "relocations": [{"site": 3, "segment": segment, "evidence": "synthetic"}]}
145
+ return run_report(data, config, "trace")
146
+
147
+
148
+ class ConvertedCallFrames(unittest.TestCase):
149
+ """A traced callee that rebuilds its return frame at the other width before returning."""
150
+
151
+ def test_a_near_frame_converted_to_a_far_one_returns_through_the_caller(self):
152
+ # Positive control: pop ax; push cs; push ax; retf. The caller's far return then consumes the root frame.
153
+ r = report(NEAR_CALL_ROOT + "58 0e 50 cb", returnBytes=4)
154
+ path = r["paths"][0]
155
+ self.assertTrue(r["completeWithinModel"], path["stop"])
156
+ self.assertEqual(only(r, depth=1)["returnCheck"], {
157
+ "frame": "call", "frameSource": "call", "frameBytes": 2, "instructionBytes": 4, "widthMatches": False,
158
+ "spOffset": -2, "stackBalanced": False, "endsAtFrameEnd": True, "target": "matches the call",
159
+ "segment": "matches the call"})
160
+ self.assertEqual(path["registers"]["ax"]["value"], 3)
161
+ # The root return balances against the entry SP.
162
+ self.assertTrue(only(r, depth=0)["returnCheck"]["stackBalanced"])
163
+ self.assertEqual(only(r, "call-return")["callSite"], 0)
164
+
165
+ def test_the_ordinary_near_and_caller_built_far_controls_still_return(self):
166
+ self.assertTrue(report(NEAR_CALL_ROOT[:-3] + "c3 c3")["completeWithinModel"])
167
+ self.assertTrue(report("0e " + NEAR_CALL_ROOT + "cb", returnBytes=4)["completeWithinModel"])
168
+
169
+ def test_a_wrong_segment_word_stays_rejected(self):
170
+ # pop ax; push 0; push ax; retf: the stack ends where the call frame ended, but the segment is not CS.
171
+ r = report(NEAR_CALL_ROOT + "58 6a 00 50 cb", returnBytes=4)
172
+ self.assertEqual(stops(r), {"far return segment changed"})
173
+ self.assertFalse(r["completeWithinModel"])
174
+ check = only(r, depth=1)["returnCheck"]
175
+ self.assertEqual((check["endsAtFrameEnd"], check["target"], check["segment"]),
176
+ (True, "matches the call", "does not match the call"))
177
+
178
+ def test_an_unknown_segment_word_is_not_compared(self):
179
+ # pop ax; push dx; push ax; retf
180
+ r = report(NEAR_CALL_ROOT + "58 52 50 cb", returnBytes=4)
181
+ self.assertEqual(stops(r), {"far return segment is not known to be the call's"})
182
+ self.assertEqual(only(r, depth=1)["returnCheck"]["segment"], UNKNOWN_WORD)
183
+
184
+ def test_an_overwritten_or_unknown_offset_word_stays_rejected(self):
185
+ # pop ax; push cs; push 5; retf | push cs; retf (CS where the offset should be) | pop ax; push cs; push bx; retf
186
+ for code, target in (("58 0e 6a 05 cb", "does not match the call"), ("0e cb", "does not match the call"),
187
+ ("58 0e 53 cb", UNKNOWN_WORD)):
188
+ with self.subTest(code=code):
189
+ r = report(NEAR_CALL_ROOT + code, returnBytes=4)
190
+ self.assertEqual(stops(r), {"return target was overwritten or has unknown provenance"})
191
+ check = only(r, depth=1)["returnCheck"]
192
+ self.assertEqual((check["target"], check["segment"]), (target, "not read: the return target check failed"))
193
+
194
+ def test_an_incomplete_conversion_fails_the_width_check(self):
195
+ # pop ax; push cs; retf: the far return would pop a word of the caller's stack as its segment.
196
+ r = report(NEAR_CALL_ROOT + "58 0e cb", returnBytes=4)
197
+ self.assertEqual(stops(r), {"return width differs from the call frame"})
198
+ check = only(r, depth=1)["returnCheck"]
199
+ self.assertEqual((check["spOffset"], check["endsAtFrameEnd"], check["target"], check["segment"]),
200
+ (0, False, CHECK_FAILED, CHECK_FAILED))
201
+
202
+ def test_an_extra_word_left_on_a_converted_frame_fails_both_checks(self):
203
+ # pop ax; push cs; push ax; push ax; retf
204
+ r = report(NEAR_CALL_ROOT + "58 0e 50 50 cb", returnBytes=4)
205
+ self.assertEqual(stops(r), {"return width and stack balance differ from the call frame"})
206
+ self.assertFalse(only(r, depth=1)["returnCheck"]["endsAtFrameEnd"])
207
+
208
+ def test_a_converted_frame_releases_arguments_and_keeps_their_reads(self):
209
+ # push 7; call; retf | pop ax; push cs; push ax; push bp; mov bp,sp; mov bx,[bp+6]; pop bp; retf 2
210
+ r = report("6a 07 e8 01 00 cb 58 0e 50 55 89 e5 8b 5e 06 5d ca 02 00", returnBytes=4)
211
+ path = r["paths"][0]
212
+ self.assertTrue(r["completeWithinModel"], path["stop"])
213
+ self.assertEqual(path["registers"]["bx"]["value"], 7)
214
+ self.assertTrue(only(r, depth=0)["returnCheck"]["stackBalanced"])
215
+ argument = [e for e in events(r, "read") if e.get("argument")]
216
+ self.assertEqual([(a["argument"]["offsetFromEntrySP"], a["argument"]["width"], a["argument"]["returnFrameBytes"])
217
+ for a in argument], [(2, 2, 2)])
218
+
219
+ def test_a_far_frame_converted_to_a_near_one_returns_in_the_same_segment(self):
220
+ # push cs; call near; ret | pop ax; pop dx; push ax; ret: the near return leaves CS, which is the call's.
221
+ r = report("0e e8 01 00 c3 58 5a 50 c3")
222
+ self.assertTrue(r["completeWithinModel"], r["paths"][0]["stop"])
223
+ check = only(r, depth=1)["returnCheck"]
224
+ self.assertEqual((check["frameBytes"], check["instructionBytes"], check["spOffset"], check["endsAtFrameEnd"],
225
+ check["target"], check["segment"]), (4, 2, 2, True, "matches the call", "matches the call"))
226
+ self.assertTrue(far_call("58 5a 50 c3", 0x1000)["completeWithinModel"])
227
+
228
+ def test_a_near_return_over_a_far_call_into_another_segment_stays_rejected(self):
229
+ r = far_call("58 5a 50 c3", 0x2000)
230
+ self.assertEqual(stops(r), {"CS after a near return over a far call frame is not the call's segment"})
231
+ self.assertEqual(only(r, depth=1)["returnCheck"]["segment"], "does not match the call")
232
+
233
+ def test_a_near_return_over_an_unconverted_far_frame_fails_the_width_check(self):
234
+ # push cs; call near; ret | ret
235
+ r = report("0e e8 01 00 c3 c3")
236
+ self.assertEqual(stops(r), {"return width differs from the call frame"})
237
+ check = only(r, depth=1)["returnCheck"]
238
+ self.assertEqual((check["endsAtFrameEnd"], check["segment"]), (False, CHECK_FAILED))
239
+
240
+ def test_the_step_limit_at_the_converting_return_stops_before_it(self):
241
+ r = report(NEAR_CALL_ROOT + "58 0e 50 cb", returnBytes=4, maxSteps=4)
242
+ self.assertEqual(stops(r), {"step limit; loop progress unresolved"})
243
+ self.assertEqual(events(r, "return"), [])
244
+
245
+
246
+ if __name__ == "__main__":
247
+ unittest.main()
@@ -2689,7 +2689,7 @@ class ReporterTests(unittest.TestCase):
2689
2689
  code = Code().emit("0e").branch("e8", "callee").emit("c3").label("callee").emit("c3")
2690
2690
  result = report(code)
2691
2691
  self.assertFalse(result["completeWithinModel"])
2692
- self.assertIn("return frame", result["paths"][0]["stop"])
2692
+ self.assertEqual(result["paths"][0]["stop"], "return width differs from the call frame")
2693
2693
 
2694
2694
  def test_xchg_captures_memory_address_before_register_update(self):
2695
2695
  result = report("bb 20 02 b8 78 56 89 07 bb 20 02 87 1f c3", registers={"ds": 0x1234})