-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_test.py
More file actions
executable file
·3223 lines (2869 loc) · 121 KB
/
run_test.py
File metadata and controls
executable file
·3223 lines (2869 loc) · 121 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
import argparse
import contextlib
import importlib.util
import io
import shlex
import sys
import subprocess
import json
import re
import hashlib
import os
import shutil
import threading
import tempfile
import uuid
from dataclasses import dataclass
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import Optional
DEFAULT_ANALYZER = Path("./build/stack_usage_analyzer")
DEFAULT_TEST_DIR = Path("test")
DEFAULT_CACHE_DIR = Path(".cache/run_test")
@dataclass
class TestRunConfig:
analyzer: Path = DEFAULT_ANALYZER
test_dir: Path = DEFAULT_TEST_DIR
cache_dir: Path = DEFAULT_CACHE_DIR
jobs: int = 1
cache_enabled: bool = True
extra_analyzer_args: tuple[str, ...] = ()
RUN_CONFIG = TestRunConfig()
_CACHE_LOCK = threading.Lock()
_MEM_CACHE = {}
_FILE_HASH_CACHE = {}
def _get_file_hash(p: Path) -> str:
path_str = str(p)
try:
st = p.stat()
except OSError:
return ""
# Use st_mtime_ns as a cache key for the hash
cache_key = (path_str, st.st_mtime_ns, st.st_size)
with _CACHE_LOCK:
if cache_key in _FILE_HASH_CACHE:
return _FILE_HASH_CACHE[cache_key]
try:
h = hashlib.sha256(p.read_bytes()).hexdigest()
except OSError:
h = ""
with _CACHE_LOCK:
_FILE_HASH_CACHE[cache_key] = h
return h
# Set to True while the top-level parallel check phase is running.
# Prevents nested ThreadPoolExecutor creation (N² process explosion).
_PARALLEL_PHASE = False
# Pre-compiled regex patterns for hot paths
_RE_LOCATION = re.compile(r"\s*at line (\d+), column (\d+)\s*$")
_RE_LOCATION_STRICT = re.compile(r"^at line \d+, column \d+$")
_RE_FORTIFIED = re.compile(r"__([A-Za-z0-9_]+)_chk\b")
_RE_HEADLINE_WARN = re.compile(r"^\[\s*!{2}Warn\s*\]\s+.+$", flags=re.IGNORECASE)
_RE_HEADLINE_ERR = re.compile(r"^\[\s*!{2}Err\s*\]\s+.+$", flags=re.IGNORECASE)
_RE_HEADLINE_ERROR = re.compile(r"^\[\s*!{3}Error\s*\]\s+.+$", flags=re.IGNORECASE)
_RE_HEADLINE_LEGACY = re.compile(r"^\[\s*!{2}\s*\]\s+.+$")
_RE_DIAG_SUMMARY = re.compile(
r"^Diagnostics summary:\s*info=(\d+),\s*warning=(\d+),\s*error=(\d+)\s*$",
flags=re.MULTILINE,
)
_RE_STACK_LIMIT = re.compile(r"//\s*stack-limit\s*[:=]\s*(\S+)", re.IGNORECASE)
_RE_RESOURCE_MODEL = re.compile(r"//\s*resource-model\s*[:=]\s*(\S+)", re.IGNORECASE)
_RE_ESCAPE_MODEL = re.compile(r"//\s*escape-model\s*[:=]\s*(\S+)", re.IGNORECASE)
_RE_BUFFER_MODEL = re.compile(r"//\s*buffer-model\s*[:=]\s*(\S+)", re.IGNORECASE)
_RE_STRICT_DIAG = re.compile(r"//\s*strict-diagnostic-count\s*[:=]\s*(\S+)", re.IGNORECASE)
# Thread-safe stdout dispatcher for parallel check execution
class _ThreadDispatchStdout:
"""Route print() output to per-thread buffers when in parallel mode."""
def __init__(self, original):
self._original = original
self._buffers: dict[int, io.StringIO] = {}
def register_thread(self):
self._buffers[threading.get_ident()] = io.StringIO()
def unregister_thread(self) -> str:
buf = self._buffers.pop(threading.get_ident(), None)
return buf.getvalue() if buf else ""
def write(self, s):
buf = self._buffers.get(threading.get_ident())
if buf is not None:
return buf.write(s)
return self._original.write(s)
def flush(self):
buf = self._buffers.get(threading.get_ident())
if buf is None:
self._original.flush()
def __getattr__(self, name):
return getattr(self._original, name)
def is_fixture_source(path: Path) -> bool:
"""
Return True if this source file should be analyzed as a regression fixture.
"""
try:
rel = path.resolve().relative_to(RUN_CONFIG.test_dir.resolve())
except Exception:
rel = path
return not (len(rel.parts) > 0 and rel.parts[0] == "unit")
def collect_fixture_sources():
"""
Collect C/C++ fixtures under test/, excluding helper/unit-test sources.
"""
fixture_sources = []
for pattern in ("**/*.c", "**/*.cc", "**/*.cpp", "**/*.cxx"):
fixture_sources.extend(RUN_CONFIG.test_dir.glob(pattern))
return [path for path in sorted(fixture_sources) if is_fixture_source(path)]
def parse_args():
parser = argparse.ArgumentParser(
description="Run analyzer regression tests with optional parallelism and caching."
)
parser.add_argument(
"--jobs",
type=int,
default=1,
help="Number of worker threads for test parallelism: global checks, "
"per-file fixture checks, and parity checks all run concurrently (default: 1).",
)
parser.add_argument(
"--cache-dir",
default=str(RUN_CONFIG.cache_dir),
help="Directory used for analyzer output cache (default: .cache/run_test).",
)
parser.add_argument(
"--no-cache",
action="store_true",
help="Disable analyzer output cache.",
)
parser.add_argument(
"--clear-cache",
action="store_true",
help="Delete cache directory before running tests.",
)
parser.add_argument(
"--analyzer-arg",
action="append",
default=[],
help=(
"Extra argument forwarded to analyzer invocations that process source inputs. "
"Repeatable."
),
)
return parser.parse_args()
def _collect_cache_dependencies(args):
deps = []
candidates = {Path(__file__).resolve(), RUN_CONFIG.analyzer.resolve()}
for arg in args:
if arg.startswith("-") and "=" in arg:
value = arg.split("=", 1)[1]
if value:
p = Path(value)
if p.exists():
candidates.add(p.resolve())
continue
if arg.startswith("-"):
continue
p = Path(arg)
if p.exists():
candidates.add(p.resolve())
for p in sorted(candidates, key=lambda x: str(x)):
h = _get_file_hash(p)
if h:
deps.append([str(p), h])
return deps
def _cache_key_for_args(args, env_overrides: Optional[dict[str, str]] = None):
payload = {
"analyzer": str(RUN_CONFIG.analyzer.resolve()),
"args": list(args),
"cwd": str(Path.cwd()),
"deps": _collect_cache_dependencies(args),
"env": dict(sorted((env_overrides or {}).items())),
}
encoded = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
return hashlib.sha256(encoded).hexdigest()
def _cache_path_for_key(key):
return RUN_CONFIG.cache_dir / f"{key}.json"
def _cache_load(key):
if not RUN_CONFIG.cache_enabled:
return None
cache_path = _cache_path_for_key(key)
if not cache_path.exists():
return None
try:
data = json.loads(cache_path.read_text(encoding="utf-8"))
except Exception:
return None
return subprocess.CompletedProcess(
args=data.get("args", []),
returncode=int(data.get("returncode", 1)),
stdout=data.get("stdout", ""),
stderr=data.get("stderr", ""),
)
def _cache_store(key, result):
if not RUN_CONFIG.cache_enabled:
return
try:
RUN_CONFIG.cache_dir.mkdir(parents=True, exist_ok=True)
cache_path = _cache_path_for_key(key)
tmp_path = cache_path.with_suffix(
f"{cache_path.suffix}.{os.getpid()}.{threading.get_ident()}.tmp"
)
tmp_path.write_text(
json.dumps(
{
"args": result.args,
"returncode": result.returncode,
"stdout": result.stdout or "",
"stderr": result.stderr or "",
},
ensure_ascii=True,
),
encoding="utf-8",
)
tmp_path.replace(cache_path)
except Exception:
# Cache failures must not fail tests.
pass
def normalize(s: str) -> str:
"""
Normalize spacing to make comparisons more robust:
- remove unnecessary leading/trailing spaces per line
- replace runs of spaces with a single space
- keep line breaks
"""
lines = []
for line in s.splitlines():
line = line.rstrip("\n")
# "a b c" -> "a b c"
parts = line.strip().split()
normalized = " ".join(parts)
# Normalize spacing around pointer/reference symbols for cross-platform demangler output.
normalized = normalized.replace(" *", "*").replace("* ", "*")
normalized = normalized.replace(" &", "&").replace("& ", "&")
# Normalize fortified libc function names (e.g., "__strncpy_chk" -> "strncpy").
normalized = _RE_FORTIFIED.sub(r"\1", normalized)
lines.append(normalized)
return "\n".join(lines).strip()
def _location_tolerant_variants(expectation: str) -> list[str]:
"""
Build location-tolerant expectation variants for common source drift in
"at line X, column Y" headers (formatting refactors, brace style changes,
toolchain column shifts).
"""
lines = expectation.splitlines()
if not lines:
return []
match = _RE_LOCATION.match(lines[0])
if not match:
return []
line = int(match.group(1))
column = int(match.group(2))
variants: list[str] = []
# Keep tolerance small enough to catch wrong/stale expectations, while
# still absorbing routine formatting drift.
max_line_delta = 18
for line_delta in range(-max_line_delta, max_line_delta + 1):
for col_delta in (-2, -1, 0, 1, 2):
if line_delta == 0 and col_delta == 0:
continue
candidate_line = line + line_delta
candidate_column = column + col_delta
if candidate_line <= 0 or candidate_column < 0:
continue
alt_lines = list(lines)
alt_lines[0] = f"at line {candidate_line}, column {candidate_column}"
variants.append("\n".join(alt_lines))
return variants
def extract_expectations(c_path: Path):
"""
Extract expected comment blocks from a .c file.
Look for comments that start with "// at line" and take all following comment lines.
"""
expectations = []
negative_expectations = []
stack_limit = None
resource_model = None
escape_model = None
buffer_model = None
strict_diag_count = None
lines = c_path.read_text().splitlines()
i = 0
n = len(lines)
def parse_bool_directive(value: str):
token = value.strip().lower()
if token in {"1", "true", "yes", "on"}:
return True
if token in {"0", "false", "no", "off"}:
return False
return None
while i < n:
raw = lines[i]
stripped = raw.lstrip()
stack_match = _RE_STACK_LIMIT.match(stripped)
if stack_match:
stack_limit = stack_match.group(1)
i += 1
continue
resource_match = _RE_RESOURCE_MODEL.match(stripped)
if resource_match:
resource_model = resource_match.group(1)
i += 1
continue
escape_match = _RE_ESCAPE_MODEL.match(stripped)
if escape_match:
escape_model = escape_match.group(1)
i += 1
continue
buffer_match = _RE_BUFFER_MODEL.match(stripped)
if buffer_match:
buffer_model = buffer_match.group(1)
i += 1
continue
strict_match = _RE_STRICT_DIAG.match(stripped)
if strict_match:
parsed = parse_bool_directive(strict_match.group(1))
if parsed is not None:
strict_diag_count = parsed
i += 1
continue
stripped_line = stripped
if stripped_line.startswith("// not contains:"):
negative = stripped_line[len("// not contains:"):].strip()
if negative:
negative_expectations.append(negative)
i += 1
continue
# Start of an expectation block
if stripped.startswith("// at line"):
comment_block = [raw]
i += 1
# Collect all following "// ..." lines
while i < n and lines[i].lstrip().startswith("//"):
comment_block.append(lines[i])
i += 1
# Cleanup: remove "//" and indentation
cleaned_lines = []
for c in comment_block:
s = c.lstrip()
if s.startswith("//"):
s = s[2:] # remove "//"
cleaned_lines.append(s.lstrip())
expectation_text = "\n".join(cleaned_lines)
expectations.append(expectation_text)
else:
i += 1
return (
expectations,
negative_expectations,
stack_limit,
resource_model,
escape_model,
buffer_model,
strict_diag_count,
)
def _expectation_is_warning_or_error(expectation: str) -> bool:
norm = normalize(expectation).lower()
if "[" not in norm:
# Keep unknown legacy style expectations conservative.
return True
if "error" in norm:
return True
if "warn" in norm:
return True
# Legacy diagnostic style: "[!!] ..."
if "[!!]" in norm:
return True
return False
def _is_diagnostic_headline_line(line: str) -> bool:
s = normalize(line)
if not s:
return False
if _RE_HEADLINE_WARN.match(s):
return True
if _RE_HEADLINE_ERR.match(s):
return True
if _RE_HEADLINE_ERROR.match(s):
return True
# Legacy terse marker.
if _RE_HEADLINE_LEGACY.match(s):
return True
return False
def _parse_expectation_location_and_headlines(expectation: str):
lines = [normalize(line) for line in expectation.splitlines() if normalize(line)]
if not lines:
return None
if not _RE_LOCATION_STRICT.match(lines[0]):
return None
headlines = [line for line in lines[1:] if _is_diagnostic_headline_line(line)]
if not headlines:
return None
return lines[0], headlines
def _build_output_diagnostic_index_by_location(output: str):
index: dict[str, list[str]] = {}
current_location = None
for raw in output.splitlines():
line = normalize(raw)
if not line:
continue
if _RE_LOCATION_STRICT.match(line):
current_location = line
index.setdefault(current_location, [])
continue
if current_location and _is_diagnostic_headline_line(line):
index[current_location].append(line)
return index
def _expectation_matches_by_location_and_headlines(expectation: str, output_index) -> bool:
parsed = _parse_expectation_location_and_headlines(expectation)
if not parsed:
return False
location, headlines = parsed
location_candidates = {location}
for alt in _location_tolerant_variants(expectation):
alt_lines = [normalize(line) for line in alt.splitlines() if normalize(line)]
if alt_lines and _RE_LOCATION_STRICT.match(alt_lines[0]):
location_candidates.add(alt_lines[0])
for candidate in location_candidates:
observed = output_index.get(candidate, [])
if all(headline in observed for headline in headlines):
return True
return False
def _parse_total_warning_error_count(output: str):
matches = _RE_DIAG_SUMMARY.findall(output)
if not matches:
return None
_info, warning, error = matches[-1]
return int(warning) + int(error)
def _default_strict_diagnostic_count(c_path: Path) -> bool:
"""
Enable strict warning/error count by default for all fixture files.
Suites can opt-out per-file via: // strict-diagnostic-count: false
"""
return True
def fixture_path_with_fallback(*relative_candidates: str) -> Path:
"""
Resolve a fixture path under test/ from a list of relative candidates.
Returns the first existing candidate, or the first candidate path if none exist.
"""
if not relative_candidates:
raise ValueError("fixture_path_with_fallback requires at least one candidate")
for rel in relative_candidates:
candidate = RUN_CONFIG.test_dir / rel
if candidate.exists():
return candidate
return RUN_CONFIG.test_dir / relative_candidates[0]
def run_analyzer_on_file(
c_path: Path,
stack_limit=None,
resource_model=None,
escape_model=None,
buffer_model=None,
extra_args: tuple[str, ...] = (),
) -> str:
"""
Run the analyzer on a C file and capture stdout+stderr.
"""
args = [str(c_path)]
if stack_limit:
args.append(f"--stack-limit={stack_limit}")
if resource_model:
args.append(f"--resource-model={resource_model}")
if escape_model:
args.append(f"--escape-model={escape_model}")
if buffer_model:
args.append(f"--buffer-model={buffer_model}")
if extra_args:
args.extend(extra_args)
result = run_analyzer(args)
output = (result.stdout or "") + (result.stderr or "")
return output
def _runner_has_explicit_smt_args() -> bool:
for arg in RUN_CONFIG.extra_analyzer_args:
if arg.startswith("--smt"):
return True
return False
def _all_smt_rules() -> tuple[str, ...]:
"""
Rules currently integrated with SMT refinement.
Applied to all fixture files for the dedicated SMT+Z3 pass.
"""
return (
"recursion",
"integer-overflow",
"size-minus-k",
"stack-buffer",
"oob-read",
)
def _has_positional_input_arg(args) -> bool:
"""
Return True when args appear to include at least one positional input path.
"""
for arg in args:
if not arg.startswith("-"):
return True
return False
def _effective_analyzer_args(args):
"""
Merge optional runner-level analyzer args for invocations that analyze inputs.
Keep runner-provided compile overrides at the end so they have highest
precedence against compile database flags and per-check compile args.
"""
base = list(args)
if RUN_CONFIG.extra_analyzer_args and _has_positional_input_arg(base):
prefix_args = []
trailing_compile_override_args = []
extras = list(RUN_CONFIG.extra_analyzer_args)
i = 0
while i < len(extras):
token = extras[i]
if token == "--compile-arg":
trailing_compile_override_args.append(token)
if i + 1 < len(extras):
trailing_compile_override_args.append(extras[i + 1])
i += 2
continue
i += 1
continue
if token.startswith("--compile-arg="):
trailing_compile_override_args.append(token)
i += 1
continue
prefix_args.append(token)
i += 1
return [*prefix_args, *base, *trailing_compile_override_args]
return base
def run_analyzer(args, env_overrides: Optional[dict[str, str]] = None) -> subprocess.CompletedProcess:
"""
Run analyzer with custom args and return the CompletedProcess.
"""
effective_args = _effective_analyzer_args(args)
cmd = [str(RUN_CONFIG.analyzer)] + effective_args
key = _cache_key_for_args(effective_args, env_overrides)
with _CACHE_LOCK:
in_memory = _MEM_CACHE.get(key)
if in_memory is not None:
return subprocess.CompletedProcess(
args=cmd,
returncode=in_memory["returncode"],
stdout=in_memory["stdout"],
stderr=in_memory["stderr"],
)
cached = _cache_load(key)
if cached is not None:
cached.args = cmd
with _CACHE_LOCK:
_MEM_CACHE[key] = {
"returncode": cached.returncode,
"stdout": cached.stdout or "",
"stderr": cached.stderr or "",
}
return cached
env = os.environ.copy()
if env_overrides:
env.update(env_overrides)
result = subprocess.run(cmd, capture_output=True, text=True, env=env)
with _CACHE_LOCK:
_MEM_CACHE[key] = {
"returncode": result.returncode,
"stdout": result.stdout or "",
"stderr": result.stderr or "",
}
_cache_store(key, result)
return result
def run_analyzer_uncached(args, env_overrides: Optional[dict[str, str]] = None) -> subprocess.CompletedProcess:
"""
Run analyzer with custom args and bypass run_test.py cache layer.
Useful for checks that assert filesystem side effects.
"""
cmd = [str(RUN_CONFIG.analyzer)] + _effective_analyzer_args(args)
env = os.environ.copy()
if env_overrides:
env.update(env_overrides)
return subprocess.run(cmd, capture_output=True, text=True, env=env)
def fail_check(message: str, output: str = "") -> bool:
print(f" ❌ {message}")
if output:
print(output)
print()
return False
def expect_returncode_zero(result: subprocess.CompletedProcess, output: str, context: str) -> bool:
if result.returncode == 0:
return True
return fail_check(f"{context} (code {result.returncode})", output)
def expect_contains(output: str, needle: str, context: str) -> bool:
if needle in output:
return True
return fail_check(context, output)
def expect_not_contains(output: str, needle: str, context: str) -> bool:
if needle not in output:
return True
return fail_check(context, output)
def load_docker_entrypoint_module():
entrypoint_path = Path("scripts/docker/coretrace_entrypoint.py")
if not entrypoint_path.exists():
return None, f"entrypoint script not found: {entrypoint_path}"
module_name = f"coretrace_entrypoint_test_{uuid.uuid4().hex}"
spec = importlib.util.spec_from_file_location(module_name, entrypoint_path)
if spec is None or spec.loader is None:
return None, f"unable to load module spec: {entrypoint_path}"
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module, ""
def parse_stack_line(line: str, label: str):
"""
Parse stack lines like:
"local stack: 123 bytes"
"local stack: unknown (>= 256 bytes)"
Returns dict with unknown/value/lower_bound or None if not matched.
"""
label_re = re.escape(label)
m_unknown = re.search(
rf"{label_re}:\s*unknown(?:\s*\(>=\s*(\d+)\s*bytes\))?", line
)
if m_unknown:
lower_bound = int(m_unknown.group(1)) if m_unknown.group(1) else None
return {"unknown": True, "value": None, "lower_bound": lower_bound}
m_value = re.search(rf"{label_re}:\s*(\d+)\s*bytes", line)
if m_value:
return {"unknown": False, "value": int(m_value.group(1)), "lower_bound": None}
return None
def parse_human_functions(output: str):
"""
Parse human-readable output to extract per-function metadata.
"""
functions = {}
lines = output.splitlines()
i = 0
while i < len(lines):
line = lines[i]
if not line.startswith("Function: "):
i += 1
continue
# Detect the end of this function block.
j = i + 1
while j < len(lines) and not lines[j].startswith("Function: "):
if lines[j].startswith("Mode: ") or lines[j].startswith("File: "):
break
j += 1
block = lines[i:j]
if any(l.strip().startswith("local stack:") for l in block):
if "(line " in line:
i = j
continue
rest = line[len("Function: "):].strip()
if rest:
name = rest.split()[0]
functions[name] = {
"localStackUnknown": None,
"localStack": None,
"localStackLowerBound": None,
"maxStackUnknown": None,
"maxStack": None,
"maxStackLowerBound": None,
"isRecursive": False,
"hasInfiniteSelfRecursion": False,
"exceedsLimit": False,
}
summary_lines = []
for block_line in block[1:]:
stripped = block_line.strip()
if stripped.startswith("at line "):
break
summary_lines.append(block_line)
for block_line in summary_lines:
stripped = block_line.strip()
if stripped.startswith("local stack:"):
info = parse_stack_line(stripped, "local stack")
if info:
functions[name]["localStackUnknown"] = info["unknown"]
functions[name]["localStack"] = info["value"]
functions[name]["localStackLowerBound"] = info["lower_bound"]
elif stripped.startswith("max stack (including callees):"):
info = parse_stack_line(stripped, "max stack (including callees)")
if info:
functions[name]["maxStackUnknown"] = info["unknown"]
functions[name]["maxStack"] = info["value"]
functions[name]["maxStackLowerBound"] = info["lower_bound"]
# Recursion diagnostics may appear either directly in the summary
# or below an "at line ..." location line.
for block_line in block[1:]:
stripped = block_line.strip()
if "recursive or mutually recursive function detected" in stripped:
functions[name]["isRecursive"] = True
elif "unconditional self recursion detected" in stripped:
functions[name]["hasInfiniteSelfRecursion"] = True
# Stack overflow diagnostics can appear after a location line.
for block_line in block[1:]:
if "potential stack overflow: exceeds limit of" in block_line:
functions[name]["exceedsLimit"] = True
break
i = j
return functions
def extract_human_function_block(output: str, func_name: str):
"""
Return the human-readable block for a given function name, if present.
"""
lines = output.splitlines()
i = 0
while i < len(lines):
line = lines[i]
if line.startswith("Function: "):
rest = line[len("Function: "):].strip()
if rest and rest.split()[0] == func_name:
# Capture until next Function/Mode/File header.
j = i + 1
while j < len(lines):
if lines[j].startswith(("Function: ", "Mode: ", "File: ")):
break
j += 1
return "\n".join(lines[i:j]).strip()
i += 1
return ""
def parse_human_diagnostic_messages(output: str):
"""
Extract diagnostic message blocks from human-readable output.
"""
blocks = []
lines = output.splitlines()
i = 0
while i < len(lines):
stripped = lines[i].strip()
if stripped.startswith("Function:") and "(line " in stripped:
# Diagnostic blocks that start with a Function: header line.
block_lines = [lines[i]]
i += 1
while i < len(lines):
next_line = lines[i]
next_stripped = next_line.strip()
if next_stripped == "":
break
if next_stripped.startswith(("Function:", "Mode:", "File:")):
break
if next_stripped.startswith(("local stack:", "max stack (including callees):")):
break
if next_stripped.startswith("[") and not next_line[:1].isspace():
break
block_lines.append(next_line)
i += 1
blocks.append(normalize("\n".join(block_lines)))
if i < len(lines) and lines[i].strip() == "":
i += 1
continue
if stripped.startswith("at line ") and ", column " in stripped:
# Diagnostic blocks that follow a source location line.
block_lines = []
i += 1
while i < len(lines):
next_line = lines[i]
next_stripped = next_line.strip()
if next_stripped == "":
break
if next_stripped.startswith(("Function:", "Mode:", "File:")):
break
if next_stripped.startswith(("local stack:", "max stack (including callees):")):
break
if next_stripped.startswith("[") and not next_line[:1].isspace():
break
block_lines.append(next_line)
i += 1
if block_lines:
blocks.append(normalize("\n".join(block_lines)))
if i < len(lines) and lines[i].strip() == "":
i += 1
continue
if stripped.startswith("[!") or stripped.startswith("[!!]") or stripped.startswith("[!!!]"):
# Diagnostic blocks that appear without an explicit location line.
block_lines = [lines[i]]
i += 1
while i < len(lines):
next_line = lines[i]
next_stripped = next_line.strip()
if next_stripped == "":
break
if next_stripped.startswith(("Function:", "Mode:", "File:")):
break
if next_stripped.startswith(("local stack:", "max stack (including callees):")):
break
if next_stripped.startswith("[") and not next_line[:1].isspace():
break
block_lines.append(next_line)
i += 1
blocks.append(normalize("\n".join(block_lines)))
if i < len(lines) and lines[i].strip() == "":
i += 1
continue
i += 1
return blocks
def _check_human_vs_json_parity_sample(sample: Path):
lines = []
sample_ok = True
human = run_analyzer([str(sample)])
if human.returncode != 0:
lines.append(f" ❌ human run failed for {sample} (code {human.returncode})")
lines.append(human.stdout or "")
lines.append(human.stderr or "")
return False, "\n".join(lines).rstrip() + "\n"
structured = run_analyzer([str(sample), "--format=json"])
if structured.returncode != 0:
lines.append(f" ❌ json run failed for {sample} (code {structured.returncode})")
lines.append(structured.stdout or "")
lines.append(structured.stderr or "")
return False, "\n".join(lines).rstrip() + "\n"
try:
payload = json.loads(structured.stdout)
except json.JSONDecodeError as exc:
lines.append(f" ❌ invalid JSON output for {sample}: {exc}")
lines.append(structured.stdout or "")
return False, "\n".join(lines).rstrip() + "\n"
human_output = (human.stdout or "") + (human.stderr or "")
norm_human = normalize(human_output)
human_functions = parse_human_functions(human_output)
human_diag_blocks = parse_human_diagnostic_messages(human_output)
mode = payload.get("meta", {}).get("mode")
if mode and f"Mode: {mode}" not in human_output:
lines.append(f" ❌ mode mismatch for {sample} (json={mode})")
sample_ok = False
for f in payload.get("functions", []):
name = f.get("name", "")
if not name:
continue
if name not in human_functions:
lines.append(f" ❌ function missing in human output: {name}")
sample_ok = False
continue
hf = human_functions[name]
if hf["localStackUnknown"] is None:
lines.append(f" ❌ local stack missing in human output for: {name}")
sample_ok = False
elif f.get("localStackUnknown") != hf["localStackUnknown"]:
lines.append(f" ❌ local stack unknown flag mismatch for: {name}")
sample_ok = False
elif not f.get("localStackUnknown"):
if f.get("localStack") != hf["localStack"]:
lines.append(f" ❌ local stack value mismatch for: {name}")
sample_ok = False
elif hf["localStackLowerBound"] is not None:
json_lb = f.get("localStackLowerBound")
if json_lb != hf["localStackLowerBound"]:
lines.append(f" ❌ local stack lower bound mismatch for: {name}")
sample_ok = False
if hf["maxStackUnknown"] is None:
lines.append(f" ❌ max stack missing in human output for: {name}")
sample_ok = False
elif f.get("maxStackUnknown") != hf["maxStackUnknown"]:
lines.append(f" ❌ max stack unknown flag mismatch for: {name}")
sample_ok = False
elif not f.get("maxStackUnknown"):
if f.get("maxStack") != hf["maxStack"]:
lines.append(f" ❌ max stack value mismatch for: {name}")
sample_ok = False
elif hf["maxStackLowerBound"] is not None:
json_lb = f.get("maxStackLowerBound")
if json_lb != hf["maxStackLowerBound"]:
lines.append(f" ❌ max stack lower bound mismatch for: {name}")
sample_ok = False
if f.get("isRecursive") != hf["isRecursive"]:
lines.append(f" ❌ recursion flag mismatch for: {name}")
lines.append(f" human: {hf['isRecursive']} json: {f.get('isRecursive')}")
block = extract_human_function_block(human_output, name)
if block:
lines.append(" human block:")
lines.append(block)
else: