scientific-method-engine 7.0.0__tar.gz → 7.1.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 (68) hide show
  1. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/PKG-INFO +1 -1
  2. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/pyproject.toml +1 -1
  3. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/x86/reports.py +143 -17
  4. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/x86/trace.py +20 -4
  5. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/tests/test_pe.py +114 -0
  6. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/.gitignore +0 -0
  7. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/LICENSE +0 -0
  8. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/README.md +0 -0
  9. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/__init__.py +0 -0
  10. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/__main__.py +0 -0
  11. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/cli.py +0 -0
  12. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/ClearNoReturnFunctions.java +0 -0
  13. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/CreateFunctions.java +0 -0
  14. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/ExportBoundedFlow.java +0 -0
  15. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/ExportCallEdges.java +0 -0
  16. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/ExportFunctionFingerprints.java +0 -0
  17. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/ExportFunctionInventory.java +0 -0
  18. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/MergeFallThroughFragment.java +0 -0
  19. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/RecoverCitedFunctions.java +0 -0
  20. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/RepairReturningCallers.java +0 -0
  21. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/ReportCallArguments.java +0 -0
  22. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/ReportCallPaths.java +0 -0
  23. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/ReportCallSitesWithScalars.java +0 -0
  24. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/ReportCallsToRange.java +0 -0
  25. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/ReportConstantFirstArgumentCalls.java +0 -0
  26. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/ReportDataBytes.java +0 -0
  27. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/ReportDecompileMatches.java +0 -0
  28. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/ReportDecompileWindow.java +0 -0
  29. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/ReportFilePatternInMemory.java +0 -0
  30. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/ReportFirstArgumentCallSummary.java +0 -0
  31. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/ReportFunctionScalarConstants.java +0 -0
  32. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/ReportFunctionSummary.java +0 -0
  33. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/ReportInstructionContext.java +0 -0
  34. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/ReportInstructionWindow.java +0 -0
  35. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/ReportMemoryBlockForFileOffset.java +0 -0
  36. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/ReportMemoryBlocks.java +0 -0
  37. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/ReportRandomnessCandidates.java +0 -0
  38. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/ReportReferences.java +0 -0
  39. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/ReportScalarConstants.java +0 -0
  40. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/ReportStringReferences.java +0 -0
  41. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/ReportSymbolReferences.java +0 -0
  42. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/ghidra/scientificmethod/FirstArgumentLookBack.java +0 -0
  43. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/x86/__init__.py +0 -0
  44. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/x86/argument_frames.py +0 -0
  45. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/x86/dispatch.py +0 -0
  46. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/x86/effect_order.py +0 -0
  47. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/x86/image.py +0 -0
  48. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/x86/loops.py +0 -0
  49. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/x86/machine.py +0 -0
  50. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/x86/memory_scopes.py +0 -0
  51. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/x86/pcode.py +0 -0
  52. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/x86/pcode_backend.py +0 -0
  53. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/x86/pe.py +0 -0
  54. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/x86/relational.py +0 -0
  55. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/x86/result_flow.py +0 -0
  56. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/src/scientific_method_engine/x86/values.py +0 -0
  57. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/tests/oracle.py +0 -0
  58. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/tests/test_continuation_budget.py +0 -0
  59. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/tests/test_dispatch.py +0 -0
  60. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/tests/test_effect_order.py +0 -0
  61. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/tests/test_entry_frame.py +0 -0
  62. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/tests/test_loops.py +0 -0
  63. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/tests/test_memory_scopes.py +0 -0
  64. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/tests/test_nested_frame_request.py +0 -0
  65. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/tests/test_oracle.py +0 -0
  66. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/tests/test_relational_controls.py +0 -0
  67. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.0}/tests/test_table_continuations.py +0 -0
  68. {scientific_method_engine-7.0.0 → scientific_method_engine-7.1.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: 7.0.0
3
+ Version: 7.1.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 = "7.0.0"
8
+ version = "7.1.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"
@@ -204,6 +204,107 @@ CFG_OPERAND = "entry-CFG operand past a stop; values and callee effects unresolv
204
204
  PORT_OPERAND = "operand past a PE32 port access; values and continuation unresolved"
205
205
 
206
206
 
207
+ # dependsOn reasons in ``uses`` for the calls and port accesses a conditionalAccesses row is reached past.
208
+ STEPPED_CALL = "call past a stop; assumed to return"
209
+ STEPPED_PORT = "port access past a stop; assumed to continue"
210
+ OPEN_CALL = "call open at a stop inside its callee; continued at its return site, assumed to return"
211
+
212
+
213
+ def _function_exit(image, start, limit, follow_flat_ports, cache):
214
+ """Walk one function's CFG from ``start``, stepping over calls, and say whether it reaches a return.
215
+
216
+ Returns the decoded sites on a route from ``start`` to a return instruction, whether one was
217
+ reached, and whether the walk stopped at ``limit`` first. A PE32 port access ends its branch
218
+ unless ``follow_flat_ports``. In the PE32 model an IRET stops ``trace``, so it is no return here.
219
+ ``cache`` keeps each walk's result, as several open calls and stops share the same walks.
220
+ """
221
+ key = (start, follow_flat_ports)
222
+ if key in cache:
223
+ return cache[key]
224
+ pending, seen, successors, exits = [start], {}, {}, []
225
+ while pending:
226
+ at = pending.pop()
227
+ if at in seen:
228
+ continue
229
+ if len(seen) >= limit:
230
+ cache[key] = {}, False, True
231
+ return cache[key]
232
+ ins = image.decode(at)
233
+ if ins is None:
234
+ continue
235
+ seen[at] = ins
236
+ m = base_mnemonic(ins)
237
+ if unsupported_transfer(image, ins):
238
+ continue
239
+ following = successors[at] = []
240
+ if at in image.indirect_jumps:
241
+ following.extend(row["target"] for row in image.indirect_jumps[at]["rows"])
242
+ elif m in RETURNS:
243
+ if not (image.flat and m in ("iret", "iretd")):
244
+ exits.append(at)
245
+ else:
246
+ if m == "ljmp" or m.startswith(("j", "loop")):
247
+ target, _ = call_target(image, at, ins)
248
+ if target is not None:
249
+ following.append(target)
250
+ if not (m in ("jmp", "ljmp") or m in INTERRUPTS or m == "hlt"
251
+ or (m in PORTS and image.flat and not follow_flat_ports)):
252
+ following.append(at + ins.size)
253
+ pending.extend(following)
254
+ # Only the sites a return is reachable from lie on the way to it; a branch that never returns is left out.
255
+ callers = {}
256
+ for at, following in successors.items():
257
+ for target in following:
258
+ callers.setdefault(target, []).append(at)
259
+ on_route, pending = set(exits), list(exits)
260
+ while pending:
261
+ for at in callers.get(pending.pop(), ()):
262
+ if at not in on_route:
263
+ on_route.add(at)
264
+ pending.append(at)
265
+ cache[key] = {at: seen[at] for at in on_route}, bool(exits), False
266
+ return cache[key]
267
+
268
+
269
+ def _caller_continuations(image, stop, reason, stack, limit, cache):
270
+ """Return sites at which ``uses`` continues its inventory past a stop inside a called function.
271
+
272
+ ``stack`` holds the traced calls still open at ``stop`` as (call site, return site) pairs,
273
+ outermost first. A return site is continued only when the CFG from the stop, or from the
274
+ return site inside it, reaches a return of the called function. Each continuation depends on
275
+ the stop, on every open call from the stop out to that return site, and on every call or PE32
276
+ port access stepped over on the way to those returns. Returns (return site, dependsOn,
277
+ reached without crossing a PE32 port access) rows and the gaps of walks that reached ``limit``.
278
+ """
279
+ rows = []
280
+ ins = image.decode(stop)
281
+ # A stop at a return instruction is the return itself failing, so no caller continuation is assumed.
282
+ if ins is None or base_mnemonic(ins) in RETURNS:
283
+ return rows, []
284
+ depends = [{"site": stop, "reason": reason}]
285
+ start, port_free = stop, not (image.flat and base_mnemonic(ins) in PORTS)
286
+ for call_site, return_site in reversed(stack):
287
+ route, exits, truncated = _function_exit(image, start, limit, True, cache)
288
+ if truncated:
289
+ return rows, [{"site": start, "reason": "instruction limit"}]
290
+ if not exits:
291
+ break
292
+ if port_free:
293
+ # This walk decodes a subset of the one above, so it cannot reach the limit.
294
+ port_free = _function_exit(image, start, limit, False, cache)[1]
295
+ for at, ins in sorted(route.items()):
296
+ if at == stop:
297
+ continue
298
+ if ins.mnemonic in ("call", "lcall"):
299
+ depends.append({"site": at, "reason": STEPPED_CALL})
300
+ elif image.flat and base_mnemonic(ins) in PORTS:
301
+ depends.append({"site": at, "reason": STEPPED_PORT})
302
+ depends.append({"site": call_site, "reason": OPEN_CALL})
303
+ start = return_site
304
+ rows.append((start, list(depends), port_free))
305
+ return rows, []
306
+
307
+
207
308
  def uses(image, config):
208
309
  query = config.get("query", {})
209
310
  offset = integer(query.get("offset"), 0, image.mask, "query offset")
@@ -233,6 +334,8 @@ def uses(image, config):
233
334
  entry_limit = integer(config.get("entryLimit", 64), 1, 256, "entryLimit")
234
335
  # CFG points where value propagation stopped (or never started), with why; operands after them are inventoried below.
235
336
  stops = {}
337
+ # The traced calls still open at each stop, so the inventory can continue at their return sites.
338
+ open_calls = {}
236
339
  established = entries(image)
237
340
  for index, at in enumerate(established):
238
341
  if remaining <= 0 or index >= entry_limit:
@@ -241,17 +344,18 @@ def uses(image, config):
241
344
  stops.setdefault(root, "entry not traced: entry or total instruction budget exhausted")
242
345
  break
243
346
  report = trace(image, {**config, "entry": at, "totalSteps": remaining, "stringIterations": string_remaining},
244
- continue_declared_jumps=False, track_loops=False)
347
+ continue_declared_jumps=False, track_loops=False, call_stacks=True)
245
348
  remaining -= report["stepsUsed"]
246
349
  string_remaining -= report["stringIterationsUsed"]
247
350
  if not report["completeWithinModel"]:
248
351
  gaps.append({"entry": at, "reason": "incomplete path effects", "stops": list({p["stop"] for p in report["paths"] if p["stop"]})})
249
- for p in report["paths"]:
250
- if p["stop"] and p["stopSite"] is not None:
251
- stops.setdefault(p["stopSite"], p["stop"])
252
- for g in report["gaps"]:
253
- if "site" in g:
254
- stops.setdefault(g["site"], g["reason"])
352
+ stopped = [(p["stopSite"], p["stop"], p["callStack"]) for p in report["paths"]
353
+ if p["stop"] and p["stopSite"] is not None]
354
+ stopped += [(g["site"], g["reason"], g.get("callStack")) for g in report["gaps"] if "site" in g]
355
+ for site, reason, stack in stopped:
356
+ stops.setdefault(site, reason)
357
+ if stack:
358
+ open_calls.setdefault(site, set()).add(tuple((f["callSite"], f["continuation"]) for f in stack))
255
359
  for path in report["paths"]:
256
360
  for e in path["events"]:
257
361
  if e["kind"] not in ("read", "write") or mode not in ("both", e["kind"]):
@@ -289,29 +393,51 @@ def uses(image, config):
289
393
  instruction_limit = config.get("instructionLimit", 10000)
290
394
  # This inventory assumes execution continues past each stop, so it also follows PE32 port accesses
291
395
  # and names each one below.
292
- after_stop, stop_gaps, _, _, _ = (walk(image, list(stops), instruction_limit, follow_flat_ports=True)
293
- if stops else ({}, [], None, None, None))
396
+ # A stop inside a called function would end the inventory at that function's return. The code
397
+ # after each call still open at the stop is inventoried too, from the call's return site, and
398
+ # depends on the stop and on every call between them returning.
399
+ returning, exit_walks = [], {}
400
+ for root, stacks in sorted(open_calls.items()):
401
+ for stack in sorted(stacks):
402
+ rows, frame_gaps = _caller_continuations(image, root, stops[root], stack, instruction_limit, exit_walks)
403
+ returning.extend(rows)
404
+ gaps.extend(g for g in frame_gaps if g not in gaps)
405
+ seeds = list(stops) + [start for start, _, _ in returning]
406
+ after_stop, stop_gaps, _, _, _ = (walk(image, seeds, instruction_limit, follow_flat_ports=True)
407
+ if seeds else ({}, [], None, None, None))
294
408
  gaps.extend(g for g in stop_gaps if g["reason"] == "instruction limit")
295
409
  # In PE32 a site the stops reach only by continuing past a port access is named as such, even when
296
410
  # it also depends on an unread call. The walk that ends at port accesses must finish within the
297
- # limit for that claim; otherwise every row keeps the shared value.
411
+ # limit for that claim; otherwise every row keeps the shared value. A return site counts as
412
+ # reached without a port access only when its callees return without crossing one.
298
413
  port_only = set()
299
- if image.flat and any(base_mnemonic(ins) in PORTS for ins in after_stop.values()):
300
- before_ports, port_gaps, _, _, _ = walk(image, list(stops), instruction_limit)
414
+ if image.flat and (any(base_mnemonic(ins) in PORTS for ins in after_stop.values())
415
+ or any(not port_free for _, _, port_free in returning)):
416
+ port_free_seeds = list(stops) + [start for start, _, port_free in returning if port_free]
417
+ before_ports, port_gaps, _, _, _ = walk(image, port_free_seeds, instruction_limit)
301
418
  if not any(g["reason"] == "instruction limit" for g in port_gaps):
302
419
  port_only = set(after_stop) - set(before_ports)
303
420
  # A call past a stop was never traced either, so code after it also depends on it returning.
304
- starts = [(root, root, reason) for root, reason in stops.items()]
305
- starts += [(at, at + ins.size, "call past a stop; assumed to return")
421
+ starts = [(root, [{"site": root, "reason": reason}]) for root, reason in stops.items()]
422
+ starts += [(at + ins.size, [{"site": at, "reason": STEPPED_CALL}])
306
423
  for at, ins in after_stop.items() if ins.mnemonic in ("call", "lcall") and at not in stops]
307
424
  if image.flat:
308
- starts += [(at, at + ins.size, "port access past a stop; assumed to continue")
425
+ starts += [(at + ins.size, [{"site": at, "reason": STEPPED_PORT}])
309
426
  for at, ins in after_stop.items() if base_mnemonic(ins) in PORTS and at not in stops]
427
+ starts += [(start, row_depends) for start, row_depends, _ in returning]
428
+ # Several rows can share a start (one return site of many open calls), so each start is walked once.
429
+ by_start = {}
430
+ for start, row_depends in starts:
431
+ named = by_start.setdefault(start, [])
432
+ named.extend(d for d in row_depends if d not in named)
310
433
  depends = {}
311
- for site, start, reason in sorted(starts):
434
+ for start, row_depends in by_start.items():
312
435
  reached, _, _, _, _ = walk(image, [start], instruction_limit, follow_flat_ports=True)
313
436
  for at in reached:
314
- depends.setdefault(at, []).append({"site": site, "reason": reason})
437
+ named = depends.setdefault(at, [])
438
+ named.extend(d for d in row_depends if d not in named)
439
+ for named in depends.values():
440
+ named.sort(key=lambda d: (d["site"], d["reason"]))
315
441
  conditional = []
316
442
  for at, ins in sorted(after_stop.items()):
317
443
  if ins.mnemonic == "lea":
@@ -371,7 +371,7 @@ def entry_frame(image, config, entry):
371
371
  "traced paths under the query's own inputs; bp null leaves BP unknown"}
372
372
 
373
373
 
374
- def trace(image, config, continue_declared_jumps=True, track_loops=True, arrive=None):
374
+ def trace(image, config, continue_declared_jumps=True, track_loops=True, arrive=None, call_stacks=False):
375
375
  """Trace bounded paths, preserving declared-table continuations as separate conditional evidence.
376
376
 
377
377
  Ordinary paths run first. A path stopped at a declared indirect jump is then
@@ -382,6 +382,10 @@ def trace(image, config, continue_declared_jumps=True, track_loops=True, arrive=
382
382
  Callers that never report the paths pass track_loops=False, and their paths
383
383
  carry no ``loops`` record. entry_frame passes arrive, the query entry:
384
384
  each path stops at its first arrival at the site with an ``arrival`` record.
385
+ Callers that continue past a stop at the return sites of its callers pass
386
+ call_stacks=True, and each stopped path carries ``callStack``: the traced
387
+ calls still open at the stop, outermost first, with each one's return site.
388
+ A path limit gap inside a called function carries the same ``callStack``.
385
389
  """
386
390
  entry = integer(config.get("entry"), 0, len(image.data) - 1, "entry")
387
391
  if not any(entry in r["entries"] for r in image.regions):
@@ -461,6 +465,16 @@ def trace(image, config, continue_declared_jumps=True, track_loops=True, arrive=
461
465
  charge(count.number)
462
466
  string_effect(s, ins, count, remaining)
463
467
 
468
+ def open_calls(s):
469
+ return [{"callSite": f["callSite"], "continuation": f["continuation"]} for f in s.frames[1:]]
470
+
471
+ def path_limit(site, s, reason):
472
+ # A path dropped at site shares the open calls of s; a caller continuing past it needs them.
473
+ gap = {"site": site, "reason": reason}
474
+ if call_stacks and len(s.frames) > 1:
475
+ gap["callStack"] = open_calls(s)
476
+ global_gaps.append(gap)
477
+
464
478
  def finish(s, reason=None, returned=False):
465
479
  if continuing and reason and reason.startswith(STRING_BUDGET_STOP):
466
480
  # machine.py names no budget; a continuation's string iterations come from continuationBudget.
@@ -473,6 +487,8 @@ def trace(image, config, continue_declared_jumps=True, track_loops=True, arrive=
473
487
  "bp": s.frame_offset(s.reg(s.bp))}
474
488
  if s.loops is not None:
475
489
  path["loops"] = s.loops.report()
490
+ if call_stacks and not returned:
491
+ path["callStack"] = open_calls(s)
476
492
  assumptions = getattr(s, "declared_jump_assumptions", [])
477
493
  if assumptions:
478
494
  path["declaredJumpAssumptions"] = assumptions
@@ -637,7 +653,7 @@ def trace(image, config, continue_declared_jumps=True, track_loops=True, arrive=
637
653
  for choice in (0, 1):
638
654
  if choice == 0:
639
655
  if created >= max_paths:
640
- global_gaps.append({"site": at, "reason": "path limit at unknown direction flag"})
656
+ path_limit(at, state, "path limit at unknown direction flag")
641
657
  continue
642
658
  child = deepcopy(state); created += 1
643
659
  else:
@@ -697,7 +713,7 @@ def trace(image, config, continue_declared_jumps=True, track_loops=True, arrive=
697
713
  raise StopPath("modeled far return segment changed")
698
714
  for case in model["cases"]:
699
715
  if created >= max_paths:
700
- global_gaps.append({"site": at, "reason": "path limit at modeled call"})
716
+ path_limit(at, state, "path limit at modeled call")
701
717
  break
702
718
  child = deepcopy(state)
703
719
  created += 1
@@ -847,7 +863,7 @@ def trace(image, config, continue_declared_jumps=True, track_loops=True, arrive=
847
863
  state = branches.pop()
848
864
  for child in branches:
849
865
  if created >= max_paths:
850
- global_gaps.append({"site": at, "reason": "path limit"})
866
+ path_limit(at, state, "path limit")
851
867
  else:
852
868
  pending.append(child)
853
869
  created += 1
@@ -194,6 +194,120 @@ class PEReporterTests(unittest.TestCase):
194
194
  r = report('ff d0 d9 1d 00 20 40 00 c3', 'uses', query={'offset': DATA_VA, 'width': 4, 'access': 'read'})
195
195
  self.assertEqual(r['conditionalAccesses'], [])
196
196
 
197
+ def test_uses_continues_at_the_return_site_of_a_call_open_at_a_stop(self):
198
+ cfg = 'entry-CFG operand past a stop; values and callee effects unresolved'
199
+ port = 'operand past a PE32 port access; values and continuation unresolved'
200
+ port_reason = 'port access in the flat model depends on I/O privilege, which is not modeled'
201
+ call_reason = 'unresolved call: computed transfer remains unresolved'
202
+ open_call = 'call open at a stop inside its callee; continued at its return site, assumed to return'
203
+ # call f; mov [DATA_VA], eax; ret; f: <stop>; ret
204
+ for name, code, stop, reason, classification in (
205
+ ('port access', 'e8 06 00 00 00 a3 00 20 40 00 c3 66 ba c8 03 ee c3', 15, port_reason, port),
206
+ ('unread call', 'e8 06 00 00 00 a3 00 20 40 00 c3 ff d0 c3', 11, call_reason, cfg)):
207
+ with self.subTest(name):
208
+ r = report(code, 'uses', query={'offset': DATA_VA, 'width': 4}, controls=[CODE_RAW + 5])
209
+ self.assertEqual(r['matches'], [])
210
+ row, = r['conditionalAccesses']
211
+ self.assertEqual((row['site'] - CODE_RAW, row['classification']), (5, classification))
212
+ self.assertEqual([(d['site'] - CODE_RAW, d['reason']) for d in row['dependsOn']],
213
+ [(0, open_call), (stop, reason)])
214
+ self.assertFalse(r['negativeUsable'])
215
+
216
+ def test_uses_continues_at_every_return_site_of_a_nested_stop(self):
217
+ # call f; mov [DATA_VA], eax; ret; f: call g; mov [DATA_VA+4], eax; ret; g: push eax; call eax; pop eax; ret
218
+ c = Code().branch('e8', 'f').emit('a3 00 20 40 00 c3')
219
+ c.label('f').branch('e8', 'g').emit('a3 04 20 40 00 c3')
220
+ c.label('g').emit('50 ff d0 58 c3')
221
+ f, g = c.labels['f'], c.labels['g']
222
+ stop = g + 1
223
+ open_call = 'call open at a stop inside its callee; continued at its return site, assumed to return'
224
+ r = report(c, 'uses', query={'offset': DATA_VA, 'width': 8}, controls=[CODE_RAW + 5, CODE_RAW + f + 5])
225
+ rows = [(e['site'] - CODE_RAW, e['classification'], [(d['site'] - CODE_RAW, d['reason']) for d in e['dependsOn']])
226
+ for e in r['conditionalAccesses']]
227
+ unread = (stop, 'unresolved call: computed transfer remains unresolved')
228
+ cfg = 'entry-CFG operand past a stop; values and callee effects unresolved'
229
+ # Each caller's store depends on the stop and on every open call from the stop out to it.
230
+ self.assertEqual(rows, [(5, cfg, [(0, open_call), (f, open_call), unread]),
231
+ (f + 5, cfg, [(f, open_call), unread])])
232
+ self.assertFalse(r['negativeUsable'])
233
+
234
+ def test_uses_names_a_call_stepped_over_on_the_way_to_a_return_site(self):
235
+ # call f; mov [DATA_VA], eax; ret; f: call eax; call h; ret; h: ret
236
+ c = Code().branch('e8', 'f').emit('a3 00 20 40 00 c3')
237
+ c.label('f').emit('ff d0').branch('e8', 'h').emit('c3').label('h').emit('c3')
238
+ f = c.labels['f']
239
+ r = report(c, 'uses', query={'offset': DATA_VA, 'width': 4}, controls=[CODE_RAW + 5])
240
+ row, = r['conditionalAccesses']
241
+ self.assertEqual([(d['site'] - CODE_RAW, d['reason']) for d in row['dependsOn']],
242
+ [(0, 'call open at a stop inside its callee; continued at its return site, assumed to return'),
243
+ (f, 'unresolved call: computed transfer remains unresolved'),
244
+ (f + 2, 'call past a stop; assumed to return')])
245
+
246
+ def test_uses_leaves_out_a_call_on_a_branch_that_never_returns(self):
247
+ # call f; mov [DATA_VA], eax; ret; f: call eax; test eax, eax; jz L; ret; L: call g; jmp $; g: ret
248
+ c = Code().branch('e8', 'f').emit('a3 00 20 40 00 c3')
249
+ c.label('f').emit('ff d0 85 c0').branch('74', 'L').emit('c3')
250
+ c.label('L').branch('e8', 'g').emit('eb fe').label('g').emit('c3')
251
+ f = c.labels['f']
252
+ r = report(c, 'uses', query={'offset': DATA_VA, 'width': 4}, controls=[CODE_RAW + 5])
253
+ row, = r['conditionalAccesses']
254
+ self.assertEqual([(d['site'] - CODE_RAW, d['reason']) for d in row['dependsOn']],
255
+ [(0, 'call open at a stop inside its callee; continued at its return site, assumed to return'),
256
+ (f, 'unresolved call: computed transfer remains unresolved')])
257
+
258
+ def test_uses_continues_at_the_return_site_of_a_path_limit_inside_a_callee(self):
259
+ # call f; mov [ebx], eax; ret; f: test eax, eax; jz L; mov ebx, DATA_VA; ret; L: mov ebx, CODE_VA; ret
260
+ # One path: the branch that points ebx at the query is dropped at the path limit.
261
+ c = Code().branch('e8', 'f').emit('89 03 c3')
262
+ c.label('f').emit('85 c0').branch('74', 'L').emit('bb 00 20 40 00 c3').label('L').emit('bb 00 10 40 00 c3')
263
+ branch = c.labels['f'] + 2
264
+ r = report(c, 'uses', query={'offset': DATA_VA, 'width': 4}, maxPaths=1)
265
+ self.assertEqual([(e['site'] - CODE_RAW, e['address'], [(d['site'] - CODE_RAW, d['reason']) for d in e['dependsOn']])
266
+ for e in r['conditionalAccesses']],
267
+ [(5, 'possible alias',
268
+ [(0, 'call open at a stop inside its callee; continued at its return site, assumed to return'),
269
+ (branch, 'path limit')])])
270
+ self.assertFalse(r['negativeUsable'])
271
+ # The trace command's gaps carry no call stack.
272
+ self.assertNotIn('callStack', report(c, maxPaths=1)['gaps'][0])
273
+
274
+ def test_uses_does_not_continue_past_a_pe32_iret(self):
275
+ # call f; mov [DATA_VA], eax; ret; f: call eax; iretd. IRET stops the PE32 trace, so it returns to no caller.
276
+ r = report('e8 06 00 00 00 a3 00 20 40 00 c3 ff d0 cf', 'uses', query={'offset': DATA_VA, 'width': 4})
277
+ self.assertEqual(r['conditionalAccesses'], [])
278
+ self.assertFalse(r['negativeUsable'])
279
+
280
+ def test_uses_keeps_a_stop_in_the_entry_function_without_a_caller_continuation(self):
281
+ # call eax; mov [DATA_VA], eax; ret: no call is open at the stop, so dependsOn names the stop alone.
282
+ r = report('ff d0 a3 00 20 40 00 c3', 'uses', query={'offset': DATA_VA, 'width': 4}, controls=[CODE_RAW + 2])
283
+ row, = r['conditionalAccesses']
284
+ self.assertEqual(row['dependsOn'], [{'site': CODE_RAW, 'reason': 'unresolved call: computed transfer remains unresolved'}])
285
+ self.assertFalse(r['negativeUsable'])
286
+
287
+ def test_uses_does_not_continue_past_a_callee_that_cannot_return(self):
288
+ # call f; mov [DATA_VA], eax; ret; f: call eax; jmp $
289
+ code = 'e8 06 00 00 00 a3 00 20 40 00 c3 ff d0 eb fe'
290
+ r = report(code, 'uses', query={'offset': DATA_VA, 'width': 4})
291
+ self.assertEqual(r['conditionalAccesses'], [])
292
+ self.assertFalse(r['negativeUsable'])
293
+ with self.assertRaisesRegex(ValueError, 'Positive variable-use control 517 missed'):
294
+ report(code, 'uses', query={'offset': DATA_VA, 'width': 4}, controls=[CODE_RAW + 5])
295
+ # A stop at the callee's return is that return failing, so its caller is not continued either.
296
+ # call f; mov [DATA_VA], eax; ret; f: push 0; ret
297
+ r = report('e8 06 00 00 00 a3 00 20 40 00 c3 6a 00 c3', 'uses', query={'offset': DATA_VA, 'width': 4})
298
+ self.assertEqual(r['conditionalAccesses'], [])
299
+ self.assertFalse(r['negativeUsable'])
300
+
301
+ def test_uses_records_the_limit_of_a_walk_to_a_callee_return(self):
302
+ # call f; mov [DATA_VA], eax; ret; f: mov dx, 0x3c8; out dx, al; nop * 10; ret
303
+ code = 'e8 06 00 00 00 a3 00 20 40 00 c3 66 ba c8 03 ee' + ' 90' * 10 + ' c3'
304
+ for limit, rows in ((100, [5]), (6, [])):
305
+ with self.subTest(limit=limit):
306
+ r = report(code, 'uses', query={'offset': DATA_VA, 'width': 4}, instructionLimit=limit)
307
+ self.assertEqual([e['site'] - CODE_RAW for e in r['conditionalAccesses']], rows)
308
+ self.assertEqual({'site': CODE_RAW + 15, 'reason': 'instruction limit'} in r['gaps'], limit == 6)
309
+ self.assertFalse(r['negativeUsable'])
310
+
197
311
  def test_pop_addresses_its_destination_after_the_stack_pointer_moves(self):
198
312
  # push 1; push 2; push 3; pop dword [esp+4]; pop eax; pop ebx; ret
199
313
  regs = report('6a 01 6a 02 6a 03 8f 44 24 04 58 5b c3')['paths'][0]['registers']