ghostscope 0.1.1

Command-line entrypoint that drives GhostScope compiler, loader, and UI end-to-end.
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
//! Globals program script execution tests
//! - Validates printing of globals via local aliases in function scope
//! - Checks struct formatting, string extraction, and formatted prints

mod common;

use common::{init, FIXTURES};
use regex::Regex;
use std::process::Stdio;
use std::time::Duration;
use tokio::process::Command;

async fn run_ghostscope_with_script_for_pid(
    script_content: &str,
    timeout_secs: u64,
    pid: u32,
) -> anyhow::Result<(i32, String, String)> {
    common::runner::GhostscopeRunner::new()
        .with_script(script_content)
        .with_pid(pid)
        .timeout_secs(timeout_secs)
        .enable_sysmon_shared_lib(false)
        .run()
        .await
}

async fn run_ghostscope_with_script_for_pid_perf(
    script_content: &str,
    timeout_secs: u64,
    pid: u32,
) -> anyhow::Result<(i32, String, String)> {
    common::runner::GhostscopeRunner::new()
        .with_script(script_content)
        .with_pid(pid)
        .timeout_secs(timeout_secs)
        .force_perf_event_array(true)
        .enable_sysmon_shared_lib(false)
        .run()
        .await
}

// Helper that enables CLI logging to console for capturing compile-time failures clearly
async fn run_ghostscope_with_script_for_pid_with_log(
    script_content: &str,
    timeout_secs: u64,
    pid: u32,
) -> anyhow::Result<(i32, String, String)> {
    common::runner::GhostscopeRunner::new()
        .with_script(script_content)
        .with_pid(pid)
        .timeout_secs(timeout_secs)
        .enable_sysmon_shared_lib(false)
        .run()
        .await
}

#[tokio::test]
async fn test_memcmp_hex_helper_on_globals() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // gm -> "Hello, Global!" → prefix "Hello, " = 48 65 6c 6c 6f 2c 20
    // lm -> "LIB_MESSAGE" → prefix "LIB_" = 4c 49 42 5f
    let script = r#"
trace globals_program.c:32 {
    if memcmp(gm, hex("48656c6c6f2c20"), 7) { print "HEX_OK"; }
    if memcmp(lm, hex("4c49425f"), 4) { print "HEX_LM"; }
}
"#;

    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 4, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");
    assert!(
        stdout.contains("HEX_OK"),
        "Expected HEX_OK. STDOUT: {stdout}"
    );
    assert!(
        stdout.contains("HEX_LM"),
        "Expected HEX_LM. STDOUT: {stdout}"
    );
    Ok(())
}

#[tokio::test]
async fn test_if_memcmp_failure_emits_exprerror_and_suppress_else() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Force a failing user read in condition via a DWARF pointer that can be NULL at runtime:
    // G_STATE.lib is NULL on some ticks, memcmp will fail probe_read_user.
    // Soft-abort semantics: emit ExprError, suppress both then and else, but keep subsequent prints.
    let script = r#"
trace globals_program.c:32 {
    if memcmp(G_STATE.lib, hex("00"), 1) { print "THEN"; } else { print "ELSE"; }
    print "AFTER";
}
"#;
    let (exit_code, stdout, stderr) =
        run_ghostscope_with_script_for_pid_perf(script, 3, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    // Should have ExprError line and AFTER; should not see THEN/ELSE
    assert!(
        stdout.contains("ExprError"),
        "Expected ExprError warning. STDOUT: {stdout}"
    );
    assert!(stdout.contains("AFTER"), "Expected AFTER. STDOUT: {stdout}");
    assert!(
        !stdout.contains("THEN"),
        "THEN should be suppressed. STDOUT: {stdout}"
    );
    assert!(stdout.contains("ELSE"), "Expected ELSE. STDOUT: {stdout}");
    Ok(())
}

#[tokio::test]
async fn test_struct_arithmetic_is_rejected_with_friendly_error() -> anyhow::Result<()> {
    init();

    // Launch the globals_program fixture to obtain a PID
    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let prog = tokio::process::Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Script attempts struct arithmetic: should be rejected at compile with friendly message
    // Use a stable function entry to avoid source-path resolution flakiness
    let script = r#"
trace tick_once {
    print G_STATE + 1;
}
"#;

    // Use helper with logging enabled to capture error message
    let (_exit_code, stdout_buf, stderr_buf) =
        run_ghostscope_with_script_for_pid_with_log(script, 3, pid).await?;

    // Expect a compile/load failure banner and the friendly TypeError message
    // Banner can be either the direct compilation failure or the final summary with zero configs
    let has_banner = stderr_buf.contains("Script compilation failed")
        || stderr_buf.contains("No uprobe configurations created");
    let has_friendly = stderr_buf
        .contains("Unsupported arithmetic/ordered comparison involving struct/union/array")
        || stderr_buf.contains("Pointer arithmetic requires a pointer or array expression");
    assert!(
        has_banner && has_friendly,
        "Expected friendly struct arithmetic rejection.\nSTDERR: {stderr_buf}\nSTDOUT: {stdout_buf}"
    );

    Ok(())
}

#[tokio::test]
async fn test_unknown_member_on_global_reports_members() -> anyhow::Result<()> {
    // Friendly error when accessing a non-existent member of a global struct
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Access a member that does not exist; expect a concise member list in error
    let script = r#"
trace globals_program.c:32 {
    print G_STATE.no_such_member;
}
"#;
    let (_exit_code, _stdout, stderr) =
        run_ghostscope_with_script_for_pid_with_log(script, 3, pid).await?;
    let _ = prog.kill().await.is_ok();

    // Look for our friendly message
    let has_msg = stderr.contains("Unknown member 'no_such_member' in struct")
        || stderr.contains("Unknown member 'no_such_member' in union");
    assert!(
        has_msg,
        "Expected unknown-member friendly message. STDERR: {stderr}"
    );
    Ok(())
}

#[tokio::test]
async fn test_else_if_continues_after_error() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // First if may fail at runtime via DWARF read (G_STATE.lib == NULL on even ticks),
    // else-if checks gm first byte == 'H' (0x48) should succeed, else suppressed
    let script = r#"
trace globals_program.c:32 {
    if memcmp(G_STATE.lib, hex("00"), 1) { print "A"; }
    else if memcmp(gm, hex("48"), 1) { print "B"; }
    else { print "C"; }
}
"#;

    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 4, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout} ");

    // Expect ExprError (from first if, when G_STATE.lib is NULL), and B printed; A/C should not appear
    assert!(
        stdout.contains("ExprError"),
        "Expected ExprError warning. STDOUT: {stdout}"
    );
    // Check per-line tokens to avoid false positives on 'A' letter inside other words
    let mut saw_b_token = false;
    let mut saw_a_token = false;
    let mut saw_c_token = false;
    for line in stdout.lines() {
        let t = line.trim();
        if t == "B" {
            saw_b_token = true;
        }
        if t == "A" {
            saw_a_token = true;
        }
        if t == "C" {
            saw_c_token = true;
        }
    }
    assert!(saw_b_token, "Expected B from else-if. STDOUT: {stdout}");
    assert!(!saw_a_token, "A should not be printed. STDOUT: {stdout}");
    assert!(
        !saw_c_token,
        "C should be suppressed due to else-if true. STDOUT: {stdout}"
    );
    Ok(())
}

#[tokio::test]
async fn test_script_signed_ints_regression() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Regression: script ints should keep signed semantics (I8/I16/I32), not U*
    let script = r#"
trace globals_program.c:32 {
    let a = -1;
    let b = -2;
    let c = -3;
    print a;
    print b;
    print c;
    print "FMT:{}|{}|{}", a, b, c;
}
"#;
    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 2, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    // Variable prints
    assert!(
        stdout.contains("a = -1"),
        "Expected a = -1. STDOUT: {stdout}"
    );
    assert!(
        stdout.contains("b = -2"),
        "Expected b = -2. STDOUT: {stdout}"
    );
    assert!(
        stdout.contains("c = -3"),
        "Expected c = -3. STDOUT: {stdout}"
    );
    // Formatted prints
    assert!(
        stdout.contains("FMT:-1|-2|-3"),
        "Expected formatted signed values. STDOUT: {stdout}"
    );
    Ok(())
}

#[tokio::test]
async fn test_trace_by_address_via_dwarf_line_lookup() -> anyhow::Result<()> {
    // End-to-end: resolve a DWARF PC for a known source line, then attach with trace 0xADDR { ... }
    init();

    // 1) Start the fixture program
    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;

    // Give the program some time to start
    tokio::time::sleep(Duration::from_millis(500)).await;

    // 2) Resolve a module-relative address (DWARF PC) for a stable source line in globals_program.c
    //    We reuse the same file:line that existing tests rely on and pick the first returned PC.
    let analyzer = ghostscope_dwarf::DwarfAnalyzer::from_exec_path(&binary_path)
        .await
        .map_err(|e| anyhow::anyhow!("Failed to load DWARF for test binary: {}", e))?;
    let addrs = analyzer.lookup_addresses_by_source_line("globals_program.c", 32);
    anyhow::ensure!(
        !addrs.is_empty(),
        "No DWARF addresses found for globals_program.c:32"
    );
    let pc = addrs[0].address;

    // 3) Build a script that attaches by address and prints a marker
    let script = format!("trace 0x{pc:x} {{\n    print \"ADDR_OK\";\n}}\n");

    // 4) Run ghostscope with -p and the script; in -p mode the default module is the main executable
    // Allow a bit more time for the shared library function to trigger
    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(&script, 4, pid).await?;
    let _ = prog.kill().await.is_ok();

    // 5) Validate output: should see the marker at least once
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");
    assert!(
        stdout.lines().any(|l| l.contains("ADDR_OK")),
        "Expected ADDR_OK in output. STDOUT: {stdout}"
    );

    Ok(())
}

async fn run_ghostscope_with_script_for_target(
    script_content: &str,
    timeout_secs: u64,
    target_path: &std::path::Path,
) -> anyhow::Result<(i32, String, String)> {
    common::runner::GhostscopeRunner::new()
        .with_script(script_content)
        .with_target(target_path)
        .timeout_secs(timeout_secs)
        .run()
        .await
}

#[tokio::test]
async fn test_special_vars_pid_tid_timestamp_globals() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    let script = format!(
        "trace globals_program.c:32 {{\n    print \"PID={} TID={} TS={}\", $pid, $tid, $timestamp;\n    if $pid == {} {{ print \"PID_EQ\"; }}\n}}\n",
        "{}", "{}", "{}", pid
    );

    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(&script, 3, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");
    assert!(
        stdout.contains("PID_EQ"),
        "Expected PID_EQ. STDOUT: {stdout}"
    );
    assert!(
        stdout.contains("PID=") || stdout.contains("PID:"),
        "Expected PID print. STDOUT: {stdout}"
    );

    Ok(())
}

#[tokio::test]
async fn test_trace_address_with_target_shared_library() -> anyhow::Result<()> {
    // Verify address tracing works when session is started with -t <libgvars.so>
    init();

    // Start an app that maps libgvars.so so that uprobe events occur
    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let _pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Resolve a function address inside libgvars.so (e.g., lib_tick entry)
    let lib_path = bin_dir.join("libgvars.so");
    anyhow::ensure!(
        lib_path.exists(),
        "libgvars.so not found at {}",
        lib_path.display()
    );
    let analyzer = ghostscope_dwarf::DwarfAnalyzer::from_exec_path(&lib_path)
        .await
        .map_err(|e| anyhow::anyhow!("Failed to load DWARF for lib: {}", e))?;
    let addrs = analyzer.lookup_function_addresses("lib_tick");
    anyhow::ensure!(
        !addrs.is_empty(),
        "No addresses for lib_tick in libgvars.so"
    );
    let pc = addrs[0].address;

    // Build script tracing at that address
    let script = format!("trace 0x{pc:x} {{\n    print \"LIB_ADDR_OK\";\n}}\n");

    // Run ghostscope in target mode (-t <libgvars.so>) with the script, collect output briefly
    let (exit_code, stdout, stderr) =
        run_ghostscope_with_script_for_target(&script, 2, &lib_path).await?;
    let _ = prog.kill().await.is_ok();

    assert_eq!(
        exit_code, 0,
        "stderr={stderr} stdout={stdout} script={script}",
    );
    assert!(
        stdout.lines().any(|l| l.contains("LIB_ADDR_OK")),
        "Expected LIB_ADDR_OK in output. STDOUT: {stdout}, script {script}"
    );
    Ok(())
}

#[tokio::test]
async fn test_trace_module_qualified_address_in_pid_mode() -> anyhow::Result<()> {
    // E2E: In PID mode, use module-qualified address 'module_suffix:0xADDR'
    // and verify the compiler resolves the module by suffix and attaches.
    init();

    // Start the fixture program which loads libgvars.so
    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Resolve a function address inside libgvars.so (e.g., lib_tick entry)
    let lib_path = bin_dir.join("libgvars.so");
    anyhow::ensure!(
        lib_path.exists(),
        "libgvars.so not found at {}",
        lib_path.display()
    );
    let analyzer = ghostscope_dwarf::DwarfAnalyzer::from_exec_path(&lib_path)
        .await
        .map_err(|e| anyhow::anyhow!("Failed to load DWARF for lib: {}", e))?;
    let addrs = analyzer.lookup_function_addresses("lib_tick");
    anyhow::ensure!(
        !addrs.is_empty(),
        "No addresses for lib_tick in libgvars.so"
    );
    let pc = addrs[0].address;

    // Use module-qualified address with suffix to target the library
    let script = format!("trace libgvars.so:0x{pc:x} {{\n    print \"LIB_MQUAL_OK\";\n}}\n");

    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(&script, 2, pid).await?;
    let _ = prog.kill().await.is_ok();

    assert_eq!(
        exit_code, 0,
        "stderr={stderr} stdout={stdout}, script={script}",
    );
    assert!(
        stdout.lines().any(|l| l.contains("LIB_MQUAL_OK")),
        "Expected LIB_MQUAL_OK in output. STDOUT: {stdout}, script: {script}"
    );

    Ok(())
}

#[tokio::test]
async fn test_address_of_with_hint_regression() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Ensure &LIB_STATE is computed with the correct module hint (prints as hex pointer)
    let script = r#"
trace globals_program.c:32 {
    print &LIB_STATE;
}
"#;
    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 1, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");
    assert!(
        stdout.contains("0x"),
        "Expected hex address. STDOUT: {stdout}"
    );
    Ok(())
}

#[tokio::test]
async fn test_unary_minus_nested() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Nested unary minus should work: -(-1) == 1
    let script = r#"
trace globals_program.c:32 {
    let d = -(-1);
    print d;
    print "X:{}", d;
}
"#;
    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 1, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");
    assert!(stdout.contains("d = 1"), "Expected d = 1. STDOUT: {stdout}");
    assert!(
        stdout.contains("X:1"),
        "Expected formatted 1. STDOUT: {stdout}"
    );
    Ok(())
}

#[tokio::test]
async fn test_string_comparison_globals_char_ptr_and_array() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // In tick_once, gm/lm are aliases to global rodata strings,
    // and s is alias to &G_STATE with name[32].
    let script = r#"
trace globals_program.c:32 {
    if (gm == "Hello, Global!") { print "GM_OK"; }
    if (lm == "LIB_MESSAGE") { print "LM_OK"; }
    if (s.name == "RUNNING") { print "GNAME_RUN"; }
}
"#;

    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 4, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    // Expect to see both char* matches (gm,lm)
    assert!(
        stdout.contains("GM_OK"),
        "Expected GM_OK for g_message. STDOUT: {stdout}"
    );
    assert!(
        stdout.contains("LM_OK"),
        "Expected LM_OK for lib_message. STDOUT: {stdout}"
    );
    // And ideally G_STATE.name comparison as RUNNING
    assert!(
        stdout.contains("GNAME_RUN"),
        "Expected GNAME_RUN for G_STATE.name. STDOUT: {stdout}"
    );
    Ok(())
}

#[tokio::test]
async fn test_print_format_current_global_member_leaf() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Current-module leaf member via formatted print
    let script = r#"
trace globals_program.c:32 {
    print "GY:{}", G_STATE.inner.y;
}
"#;
    // Collect exactly 2 events for deterministic delta/null checks
    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 2, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    let re = Regex::new(r"GY:([0-9]+(?:\.[0-9]+)?)").unwrap();
    let mut vals: Vec<f64> = Vec::new();
    for line in stdout.lines() {
        if let Some(c) = re.captures(line) {
            // Ensure scalar print (no struct pretty-print)
            assert!(
                !line.contains("Inner {"),
                "Expected scalar for G_STATE.inner.y, got struct: {line}"
            );
            vals.push(c[1].parse().unwrap_or(0.0));
        }
    }
    assert!(vals.len() >= 2, "Insufficient GY events. STDOUT: {stdout}");
    // inner.y increments by 0.5 per tick in globals_program
    let d = ((vals[1] - vals[0]) * 100.0).round() as i64;
    assert_eq!(
        d, 50,
        "G_STATE.inner.y should +0.5 per tick. STDOUT: {stdout}"
    );
    Ok(())
}

#[tokio::test]
async fn test_print_format_global_autoderef_pointer_member() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Test script: global base with one auto-deref in chain
    let script = r#"
trace globals_program.c:32 {
    print "X: {}", G_STATE.lib.inner.x;
}
"#;
    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 3, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    // Expect both a normal numeric output and a NullDeref error output while lib toggles
    let num_re = Regex::new(r"X:\s*(-?\d+)").unwrap();
    let err_re = Regex::new(r"X:\s*<error: null pointer dereference> \(int\*\)").unwrap();
    let mut has_num = false;
    let mut has_err = false;
    for line in stdout.lines() {
        if num_re.is_match(line) {
            has_num = true;
        }
        if err_re.is_match(line) {
            has_err = true;
        }
    }
    assert!(has_num, "Expected numeric X line. STDOUT: {stdout}");
    assert!(has_err, "Expected NullDeref X line. STDOUT: {stdout}");
    Ok(())
}

#[tokio::test]
async fn test_cross_type_comparisons_globals() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Cross-type comparisons (string equality separated into its own test):
    // - s_internal > 5 (DWARF int vs script int)
    // - p_lib_internal == 0 (DWARF pointer vs script int; often false depending on timing)
    // - s_internal > th (DWARF int vs script variable)
    let script = r#"
trace globals_program.c:32 {
    let th = 6;
    print "SI_GT5:{} PIN0:{} SI_GT_TH:{}",
        s_internal > 5,
        p_lib_internal == 0,
        s_internal > th;
}
"#;

    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 3, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    let re = Regex::new(r"SI_GT5:(true|false) PIN0:(true|false) SI_GT_TH:(true|false)").unwrap();
    let mut saw_line = false;
    let mut saw_pin0_flag = false;
    for line in stdout.lines() {
        if let Some(c) = re.captures(line) {
            saw_line = true;
            // PIN0 may be true/false depending on timing; just assert it appears
            if &c[2] == "true" || &c[2] == "false" {
                saw_pin0_flag = true;
            }
        }
    }
    assert!(
        saw_line,
        "Expected at least one comparison line. STDOUT: {stdout}"
    );
    assert!(saw_pin0_flag, "Expected PIN0 present. STDOUT: {stdout}");

    Ok(())
}

#[tokio::test]
async fn test_if_else_if_and_bare_expr_globals() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Use globals at a stable attach site; exercise bare expr + conditional with expressions
    let script = r#"
trace globals_program.c:32 {
    // bare expression print
    print s_internal > 5;
    if s_internal > 5 {
        print "wtf";
    } else if p_lib_internal == 0 {
        // else-if prints an expression result when lib ptr is null
        print p_lib_internal == 0;
    }
}
"#;

    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 4, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    // Expect bare expr name preserved for (s_internal>5) = true/false
    let has_expr_line = stdout
        .lines()
        .any(|l| l.contains("(s_internal>5) = true") || l.contains("(s_internal>5) = false"));
    assert!(
        has_expr_line,
        "Expected bare expression output for s_internal>5. STDOUT: {stdout}"
    );

    // Branch outputs are environment-dependent (timing-sensitive). If they appear it's ok,
    // but the core validation here is parsing/execution of expr in if/else-if, which
    // is covered by the bare expression line above. So we don't require branch prints.

    Ok(())
}

#[tokio::test]
async fn test_if_else_if_logical_ops_globals() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    let script = r#"
trace globals_program.c:32 {
    // Stable conditions to exercise both operators; first branch always true
    if 1 == 1 && s_bss_counter >= 0 { print "AND"; }
    else if 1 == 0 || p_lib_internal == 0 { print "OR"; }
}
"#;
    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 4, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    // Expect deterministic AND branch
    let has_and = stdout.lines().any(|l| l.contains("AND"));
    assert!(has_and, "Expected AND branch output. STDOUT: {stdout}");

    Ok(())
}

#[tokio::test]
async fn test_address_of_and_comparisons_globals() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Address-of on globals and in comparisons
    let script = r#"
trace globals_program.c:32 {
    print &G_STATE;              // pointer to global struct
    print (&G_STATE != 0);       // expression with address-of
    if &G_STATE != 0 { print "ADDR"; }
}
"#;

    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 4, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    // Hex pointer expected for &G_STATE
    assert!(
        stdout.contains("0x"),
        "Expected hex pointer for &G_STATE. STDOUT: {stdout}"
    );

    // Bare expr boolean with name
    let has_expr = stdout
        .lines()
        .any(|l| l.contains("(&G_STATE!=0) = true") || l.contains("(&G_STATE!=0) = false"));
    assert!(
        has_expr,
        "Expected (&G_STATE!=0) bare expr. STDOUT: {stdout}"
    );

    // Then branch
    assert!(
        stdout.contains("ADDR"),
        "Expected then-branch ADDR line. STDOUT: {stdout}"
    );

    Ok(())
}

#[tokio::test]
async fn test_string_equality_globals() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    let script = r#"
trace globals_program.c:32 {
    print "GM_EQ:{}", g_message == "Hello, Global!";
}
"#;

    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 3, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");
    // Expect GM_EQ:true at least once
    assert!(stdout.contains("GM_EQ:true") || stdout.contains("GM_EQ:false"));
    Ok(())
}

#[tokio::test]
async fn test_chain_tail_array_constant_index_increments() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // LIB_STATE.array[i] increments by +1 per tick in lib_tick(); via G_STATE.lib pointer
    let script = r#"
trace globals_program.c:32 {
    print "A0:{}", G_STATE.lib.array[0];
}
"#;

    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 3, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    // At this PC, G_STATE.lib may still be NULL (set later in tick_once), so A0 can alternate
    // between NULL error and numeric values. Require at least two A0 lines and at least one
    // numeric sample; if two numeric samples exist, ensure non-decreasing.
    let re_num = Regex::new(r"^\s*A0:(-?\d+)").unwrap();
    let re_err = Regex::new(r"^\s*A0:<error: null pointer dereference>").unwrap();
    let mut vals: Vec<i64> = Vec::new();
    let mut a0_lines = 0usize;
    for line in stdout.lines() {
        if line.trim_start().starts_with("A0:") {
            a0_lines += 1;
        }
        if let Some(c) = re_num.captures(line) {
            vals.push(c[1].parse::<i64>().unwrap_or(0));
        } else if re_err.is_match(line) {
            // count but no-op; we only enforce presence via a0_lines
        }
    }
    assert!(a0_lines >= 2, "Insufficient A0 events. STDOUT: {stdout}");
    assert!(
        !vals.is_empty(),
        "Expected at least one numeric A0 sample. STDOUT: {stdout}"
    );
    if vals.len() >= 2 {
        assert!(
            vals[1] >= vals[0],
            "A0 should not decrease. STDOUT: {stdout}"
        );
    }
    Ok(())
}

#[tokio::test]
async fn test_builtins_strncmp_starts_with_globals() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Validate strncmp/starts_with builtins on globals
    let script = r#"
trace globals_program.c:32 {
    print "SN1:{}", strncmp(gm, "Hello", 5);
    print "SW1:{}", starts_with(gm, "Hello");
    print "SN2:{}", strncmp(lm, "LIB_", 4);
}
"#;

    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 3, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    // Expect true for SN1 and SW1; LM starts with LIB_ should be true as well
    assert!(
        stdout.lines().any(|l| l.contains("SN1:true")),
        "Expected SN1:true. STDOUT: {stdout}"
    );
    assert!(
        stdout.lines().any(|l| l.contains("SW1:true")),
        "Expected SW1:true. STDOUT: {stdout}"
    );
    assert!(
        stdout.lines().any(|l| l.contains("SN2:true")),
        "Expected SN2:true. STDOUT: {stdout}"
    );
    Ok(())
}

#[tokio::test]
async fn test_builtin_strncmp_generic_ptr_and_null() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // At this PC, s.lib flips between NULL and &LIB_STATE each tick
    // When non-NULL, the first bytes are 'LIB' (name field), so strncmp should be true
    // When NULL, read fails and builtin returns false
    let script = r#"
trace globals_program.c:32 {
    print "SL:{}", strncmp(s.lib, "LIB", 3);
}
"#;

    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 5, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    let saw_true = stdout.lines().any(|l| l.contains("SL:true"));
    let saw_false = stdout.lines().any(|l| l.contains("SL:false"));
    assert!(saw_true, "Expected SL:true at least once. STDOUT: {stdout}");
    assert!(
        saw_false,
        "Expected SL:false at least once. STDOUT: {stdout}"
    );
    Ok(())
}

#[tokio::test]
async fn test_rodata_char_element() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Print first character of executable/library rodata messages
    let script = r#"
trace globals_program.c:32 {
    // variable-print (name = value)
    print g_message[0];
    print lib_message[0];

    // format-print (pure value in placeholder)
    print "G0:{}", g_message[0];
    print "L0:{}", lib_message[0];
}
"#;
    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 3, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    // Expect char-literal outputs (or numeric+char if simple path is used)
    // Accept either:
    //   name = 'X'
    // or
    //   name = 72 ('H')
    let _re_char_only = r"\s*='(?:.|\x[0-9a-fA-F]{2})'";
    let _re_num_and_char = r"\s*=\s*\d+\s*\('(?:.|\x[0-9a-fA-F]{2})'\)";
    let _re_num_only = r"\s*=\s*\d+";
    let re_g1 = Regex::new(r"^\s*g_message\[0\]\s*='[^']'").unwrap();
    let re_g2 = Regex::new(r"^\s*g_message\[0\]\s*=\s*\d+\s*\('[^']'\)").unwrap();
    let re_g3 = Regex::new(r"^\s*g_message\[0\]\s*=\s*\d+").unwrap();
    let re_l1 = Regex::new(r"^\s*lib_message\[0\]\s*='[^']'").unwrap();
    let re_l2 = Regex::new(r"^\s*lib_message\[0\]\s*=\s*\d+\s*\('[^']'\)").unwrap();
    let re_l3 = Regex::new(r"^\s*lib_message\[0\]\s*=\s*\d+").unwrap();
    let has_g = stdout
        .lines()
        .any(|l| re_g1.is_match(l) || re_g2.is_match(l) || re_g3.is_match(l));
    let has_l = stdout
        .lines()
        .any(|l| re_l1.is_match(l) || re_l2.is_match(l) || re_l3.is_match(l));
    // Also expect formatted outputs; accept char or numeric depending on DWARF encoding
    let re_fmt_val = r"(?:'[^']'|\d+)";
    let re_fmt_g = Regex::new(&format!(r"^\s*G0:{re_fmt_val}")).unwrap();
    let re_fmt_l = Regex::new(&format!(r"^\s*L0:{re_fmt_val}")).unwrap();
    let has_fmt_g = stdout.lines().any(|l| re_fmt_g.is_match(l));
    let has_fmt_l = stdout.lines().any(|l| re_fmt_l.is_match(l));
    assert!(
        has_g && has_l && has_fmt_g && has_fmt_l,
        "Expected variable and formatted char outputs. STDOUT: {stdout}"
    );
    Ok(())
}

#[tokio::test]
async fn test_format_specifiers_memory_and_pointer() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    let script = r#"
trace globals_program.c:32 {
    // Hex dump first 4 bytes of g_message
    print "HX={:x.4}", g_message;
    // ASCII dump first 5 bytes of s.name
    print "AS={:s.5}", s.name;
    // Dynamic star length 4 on lm (lib_message)
    print "DS={:s.*}", 4, lm;
    // Pointer formatting for &G_STATE
    print "P={:p}", &G_STATE;
}
"#;

    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 3, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    use regex::Regex;
    // Expect hex bytes pattern (four bytes)
    let re_hex4 = Regex::new(r"HX=([0-9a-fA-F]{2}(\s+[0-9a-fA-F]{2}){3})").unwrap();
    // Expect ASCII substrings
    let has_as = stdout.lines().any(|l| {
        l.contains("AS=INIT")
            || l.contains("AS=RUNNI")
            || l.contains("AS=LIB")
            || l.contains("AS=HELLO")
    });
    let has_ds = stdout
        .lines()
        .any(|l| l.contains("DS=LIB_") || l.contains("DS=Hell"));
    // Pointer has 0x prefix
    let has_ptr = stdout.lines().any(|l| l.contains("P=0x"));

    let has_hex = stdout.lines().any(|l| re_hex4.is_match(l));
    assert!(has_hex, "Expected hex dump HX=. STDOUT: {stdout}");
    assert!(has_as, "Expected ASCII dump AS=. STDOUT: {stdout}");
    assert!(has_ds, "Expected dynamic star ASCII DS=. STDOUT: {stdout}");
    assert!(has_ptr, "Expected pointer P=0x.... STDOUT: {stdout}");
    Ok(())
}

#[tokio::test]
async fn test_large_pattern_dump_and_checks() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Validate:
    // - First 16 bytes of lib_pattern are 00..0f (hex)
    // - Byte at index 100 is 100
    // - Byte at index 255 is 255
    // - Dynamic {:x.*} with length=10 shows 00..09
    let script = r#"
trace globals_program.c:32 {
    print "LPX16={:x.16}", lib_pattern;
    print "LPD10={:x.*}", 10, lib_pattern;
    print "B100={} B255={}", lib_pattern[100], lib_pattern[255];
}
"#;

    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 4, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    use regex::Regex;
    let re_first16 = Regex::new(r"LPX16=00(\s+01)(\s+02)(\s+03)(\s+04)(\s+05)(\s+06)(\s+07)(\s+08)(\s+09)(\s+0a)(\s+0b)(\s+0c)(\s+0d)(\s+0e)(\s+0f)").unwrap();
    let has_first16 = stdout.lines().any(|l| re_first16.is_match(l));
    let has_dyn10 = stdout
        .lines()
        .any(|l| l.contains("LPD10=00 01 02 03 04 05 06 07 08 09"));
    let has_b100 = stdout.lines().any(|l| l.contains("B100=100"));
    let has_b255 = stdout.lines().any(|l| l.contains("B255=255"));

    assert!(
        has_first16,
        "Expected first 16 bytes 00..0f. STDOUT: {stdout}"
    );
    assert!(
        has_dyn10,
        "Expected dynamic 10 bytes 00..09. STDOUT: {stdout}"
    );
    assert!(has_b100, "Expected B100=100. STDOUT: {stdout}");
    assert!(has_b255, "Expected B255=255. STDOUT: {stdout}");
    Ok(())
}

#[tokio::test]
async fn test_format_capture_len_zero_and_exceed_cap() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // With project-level ghostscope.toml setting mem_dump_cap=64,
    // - len=0 should yield empty
    // - len=128 should truncate to 64 bytes
    let script = r#"
trace globals_program.c:32 {
    let z = 0;
    let big = 128;
    print "Z0={:x.z$}", lib_pattern;     // expect empty
    print "XC={:x.big$}", lib_pattern;   // expect 64 bytes due to cap
}
"#;

    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 4, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    use regex::Regex;
    // Z0 should be exactly 'Z0=' with no hex bytes following
    let re_z0_empty = Regex::new(r"^\s*Z0=\s*$").unwrap();
    let has_z0_empty = stdout.lines().any(|l| re_z0_empty.is_match(l));

    // 64 bytes hex: two hex digits repeated 64 times with optional spaces between
    let re_64_hex = Regex::new(r"XC=([0-9a-fA-F]{2}(\s+[0-9a-fA-F]{2}){63})").unwrap();
    let has_trunc_64 = stdout.lines().any(|l| re_64_hex.is_match(l));

    assert!(has_z0_empty, "Expected Z0= (empty). STDOUT: {stdout}");
    assert!(
        has_trunc_64,
        "Expected XC= to contain exactly 64 bytes due to cap. STDOUT: {stdout}"
    );

    Ok(())
}

#[tokio::test]
async fn test_format_negative_len_clamped_to_zero() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Negative lengths should clamp to 0 and produce empty output
    let script = r#"
trace globals_program.c:32 {
    let neg = -5;
    print "ZN1={:x.neg$}", lib_pattern;   // capture negative -> empty
    print "ZN2={:x.*}", -10, lib_pattern; // star negative -> empty
}
"#;

    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 4, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    use regex::Regex;
    let re_empty1 = Regex::new(r"^\s*ZN1=\s*$").unwrap();
    let re_empty2 = Regex::new(r"^\s*ZN2=\s*$").unwrap();
    let has_zn1 = stdout.lines().any(|l| re_empty1.is_match(l));
    let has_zn2 = stdout.lines().any(|l| re_empty2.is_match(l));

    assert!(has_zn1, "Expected ZN1= (empty). STDOUT: {stdout}");
    assert!(has_zn2, "Expected ZN2= (empty). STDOUT: {stdout}");
    Ok(())
}

#[tokio::test]
async fn test_format_specifiers_capture_len() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    let script = r#"
trace globals_program.c:32 {
    let n = 4;
    // Capture length from script variable for ASCII and HEX
    print "CL={:s.n$}", lm;
    print "CH={:x.n$}", g_message;
}
"#;

    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 3, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    use regex::Regex;
    // Hex 4 bytes
    let re_hex4 = Regex::new(r"CH=([0-9a-fA-F]{2}(\s+[0-9a-fA-F]{2}){3})").unwrap();
    let has_hex = stdout.lines().any(|l| re_hex4.is_match(l));
    // ASCII 4 bytes from lm or g_message
    let has_cl = stdout
        .lines()
        .any(|l| l.contains("CL=LIB_") || l.contains("CL=Hell"));

    assert!(has_hex, "Expected hex dump CH=. STDOUT: {stdout}");
    assert!(has_cl, "Expected capture-len ASCII CL=. STDOUT: {stdout}");
    Ok(())
}

#[tokio::test]
async fn test_alias_to_complex_dwarf_expr_index_and_address_of() -> anyhow::Result<()> {
    // Validate that script alias can bind to a complex DWARF expression (array member),
    // and support both address-of and constant index on the alias.
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    let script = r#"
trace globals_program.c:32 {
    let a = G_STATE.array;      // alias to DWARF array member
    print "APTR={:p}", &a;      // address-of alias
    print "A0={}", a[0];        // index on alias
    print "A1={}", a[1];
}
"#;

    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 4, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    // Expect pointer print and at least one A0/A1 line
    assert!(
        stdout.contains("APTR=0x"),
        "Expected APTR pointer line. STDOUT: {stdout}"
    );
    let has_a0 = stdout
        .lines()
        .any(|l| l.trim_start().starts_with("A0=") || l.trim_start().starts_with("A0:"));
    let has_a1 = stdout
        .lines()
        .any(|l| l.trim_start().starts_with("A1=") || l.trim_start().starts_with("A1:"));
    assert!(
        has_a0,
        "Expected A0 line from alias index. STDOUT: {stdout}"
    );
    assert!(
        has_a1,
        "Expected A1 line from alias index. STDOUT: {stdout}"
    );
    Ok(())
}

#[tokio::test]
async fn test_alias_to_aggregate_and_chain_and_string_prefix() -> anyhow::Result<()> {
    // Simulate nginx-like alias-to-aggregate + deep chain string access:
    // let a = s; print a.inner.x; starts_with(a.name, "RUN"/"INI");
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    let script = r#"
trace globals_program.c:32 {
    let a = s;                    // alias to pointer-to-aggregate (GlobalState*)
    print "AX:{}", a.inner.x;     // member chain from alias
    // probe string prefix on nested char[N]
    print "RUN?{}", starts_with(a.name, "RUN");
    print "INI?{}", starts_with(a.name, "INI");
    // also alias a nested aggregate and read numeric
    let b = a.inner;
    print "BX:{}", b.x;
}
"#;

    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 4, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    // Should see numeric AX and BX lines
    let re_ax = Regex::new(r"^\s*AX:(-?\d+)").unwrap();
    let re_bx = Regex::new(r"^\s*BX:(-?\d+)").unwrap();
    let has_ax = stdout.lines().any(|l| re_ax.is_match(l));
    let has_bx = stdout.lines().any(|l| re_bx.is_match(l));
    assert!(
        has_ax,
        "Expected AX numeric via alias chain. STDOUT: {stdout}"
    );
    assert!(
        has_bx,
        "Expected BX numeric via nested alias. STDOUT: {stdout}"
    );

    // At runtime name toggles (INIT -> RUNNING occasionally). Accept either prefix condition being true
    let saw_run_true = stdout.lines().any(|l| l.contains("RUN?true"));
    let saw_ini_true = stdout.lines().any(|l| l.contains("INI?true"));
    assert!(
        saw_run_true || saw_ini_true,
        "Expected one of RUN?true/INI?true. STDOUT: {stdout}"
    );
    Ok(())
}

#[tokio::test]
async fn test_alias_rodata_string_builtins() -> anyhow::Result<()> {
    // Alias to rodata strings (locals gm/lm) and validate starts_with/strncmp
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    let script = r#"
trace globals_program.c:32 {
    let sg = gm; // alias to g_message (const char*)
    let sl = lm; // alias to lib_message (const char*)
    print "GST:{}", starts_with(sg, "Hell");
    print "GSN:{}", strncmp(sg, "Hello", 5);
    print "LST:{}", starts_with(sl, "LIB_");
    print "LSN:{}", strncmp(sl, "LIB_", 4);
}
"#;

    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 3, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");
    // All should be true at least once
    for tag in ["GST:true", "GSN:true", "LST:true", "LSN:true"] {
        assert!(
            stdout.contains(tag),
            "Expected {tag} at least once. STDOUT: {stdout}"
        );
    }
    Ok(())
}

#[tokio::test]
async fn test_alias_rodata_string_builtins_perf() -> anyhow::Result<()> {
    // Same as above but using perf_event array transport
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    let script = r#"
trace globals_program.c:32 {
    let sg = gm; // alias to g_message (const char*)
    let sl = lm; // alias to lib_message (const char*)
    print "GST:{}", starts_with(sg, "Hell");
    print "GSN:{}", strncmp(sg, "Hello", 5);
    print "LST:{}", starts_with(sl, "LIB_");
    print "LSN:{}", strncmp(sl, "LIB_", 4);
}
"#;
    let (exit_code, stdout, stderr) =
        run_ghostscope_with_script_for_pid_perf(script, 3, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");
    for tag in ["GST:true", "GSN:true", "LST:true", "LSN:true"] {
        assert!(
            stdout.contains(tag),
            "Expected {tag} at least once. STDOUT: {stdout}"
        );
    }
    Ok(())
}

#[tokio::test]
async fn test_alias_address_of_cross_module_uses_correct_hint() -> anyhow::Result<()> {
    // Validate that taking &alias where alias resolves to a library global
    // uses the library's ASLR offsets (module hint captured after DWARF query).
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Touch an executable symbol first (to set a prior module hint), then
    // alias a library global and take its address; compare with &LIB_STATE.
    let script = r#"
trace globals_program.c:32 {
    print "MX:{}", G_STATE.counter;  // touch main exe symbol first
    let a = LIB_STATE;               // alias to library global (cross-module)
    print "PA={:p}", &a;             // &alias must equal &LIB_STATE
    print "PL={:p}", &LIB_STATE;
}
"#;

    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 4, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    let re_pa = Regex::new(r"PA=0x([0-9a-fA-F]+)").unwrap();
    let re_pl = Regex::new(r"PL=0x([0-9a-fA-F]+)").unwrap();
    let mut last_pa: Option<u64> = None;
    let mut last_pl: Option<u64> = None;
    for line in stdout.lines() {
        if let Some(c) = re_pa.captures(line) {
            if let Ok(v) = u64::from_str_radix(&c[1], 16) {
                last_pa = Some(v);
            }
        }
        if let Some(c) = re_pl.captures(line) {
            if let Ok(v) = u64::from_str_radix(&c[1], 16) {
                last_pl = Some(v);
            }
        }
    }
    let pa = last_pa.ok_or_else(|| anyhow::anyhow!("missing PA"))?;
    let pl = last_pl.ok_or_else(|| anyhow::anyhow!("missing PL"))?;
    assert_eq!(pa, pl, "&alias should equal &LIB_STATE (cross-module hint)");
    Ok(())
}

#[tokio::test]
async fn test_top_level_array_member_struct_field() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Top-level array-of-struct member access: g_slots[1].x
    let script = r#"
trace globals_program.c:32 {
    print "SX:{}", g_slots[1].x;
}
"#;
    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 3, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    let re = Regex::new(r"SX:(-?\d+)").unwrap();
    let has = stdout.lines().any(|l| re.is_match(l));
    assert!(
        has,
        "Expected struct field numeric via g_slots[1].x. STDOUT: {stdout}"
    );
    Ok(())
}

#[tokio::test]
async fn test_tick_once_entry_strings_and_structs() -> anyhow::Result<()> {
    init();

    // Build and start globals_program (Debug)
    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Attach at a source line after local aliases are initialized (line 26 is first non-comment after 19..24)
    let script = r#"
trace globals_program.c:26 {
    print s.name;       // char[32] -> string
    print ls.name;      // from shared library
    print s;            // struct GlobalState pretty print
    print *ls;          // deref pointer to struct
}
"#;
    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 2, pid).await?;

    let _ = prog.kill().await.is_ok();

    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    // s.name should be a quoted string (either "INIT" or updated value)
    let has_s_name = stdout.contains("\"INIT\"") || stdout.contains("\"RUNNING\"");
    assert!(has_s_name, "Expected s.name string. STDOUT: {stdout}");

    // ls.name (library) should be "LIB"
    assert!(
        stdout.contains("\"LIB\""),
        "Expected ls.name == \"LIB\". STDOUT: {stdout}"
    );

    // Pretty struct prints for s or *ls should be present
    let has_struct = stdout.contains("GlobalState {") || stdout.contains("*ls = GlobalState {");
    assert!(
        has_struct,
        "Expected pretty struct output. STDOUT: {stdout}"
    );

    Ok(())
}

#[tokio::test]
async fn test_tick_once_formatted_counters() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Verify formatted output combining fields from exe and lib globals via locals
    let script = r#"
trace tick_once {
    print "G:{} L:{}", s.counter, ls.counter;
}
"#;
    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 2, pid).await?;
    let _ = prog.kill().await.is_ok();

    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");
    assert!(
        stdout.contains("G:") && stdout.contains("L:"),
        "Expected formatted counters. STDOUT: {stdout}"
    );

    Ok(())
}

#[tokio::test]
async fn test_tick_once_pointer_values() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Validate pointers to rodata appear as addresses; attach after locals are set
    let script = r#"
trace globals_program.c:26 {
    print gm; // const char* to executable rodata
    print lm; // const char* to library rodata
}
"#;
    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 2, pid).await?;
    let _ = prog.kill().await.is_ok();

    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");
    assert!(
        stdout.contains("0x"),
        "Expected hexadecimal pointer output. STDOUT: {stdout}"
    );
    Ok(())
}

#[tokio::test]
async fn test_two_events_evolution_and_statics() -> anyhow::Result<()> {
    init();

    // Build and start globals_program (Debug)
    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Attach at initialized locals line; print counters and statics via local pointers
    let script = r#"
trace globals_program.c:26 {
    print s.counter;
    print ls.counter;
    print *p_s_internal;
    print *p_s_bss;
    print *p_lib_internal;
}

"#;
    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 3, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    // Parse first two occurrences for each metric
    let re_s = Regex::new(r"s\.counter\s*=\s*(\d+)").unwrap();
    let re_ls = Regex::new(r"ls\.counter\s*=\s*(\d+)").unwrap();
    let re_si = Regex::new(r"\*p_s_internal\s*=\s*(\d+)").unwrap();
    let re_sb = Regex::new(r"\*p_s_bss\s*=\s*(\d+)").unwrap();
    let re_li = Regex::new(r"\*p_lib_internal\s*=\s*(\d+)").unwrap();
    let re_li_err =
        Regex::new(r"\*p_lib_internal\s*=\s*<error: null pointer dereference>").unwrap();

    let mut s_vals = Vec::new();
    let mut ls_vals = Vec::new();
    let mut si_vals = Vec::new();
    let mut sb_vals = Vec::new();
    let mut li_vals = Vec::new();
    let mut li_errs = 0usize;
    for line in stdout.lines() {
        if let Some(c) = re_s.captures(line) {
            s_vals.push(c[1].parse::<i64>().unwrap_or(0));
        }
        if let Some(c) = re_ls.captures(line) {
            ls_vals.push(c[1].parse::<i64>().unwrap_or(0));
        }
        if let Some(c) = re_si.captures(line) {
            si_vals.push(c[1].parse::<i64>().unwrap_or(0));
        }
        if let Some(c) = re_sb.captures(line) {
            sb_vals.push(c[1].parse::<i64>().unwrap_or(0));
        }
        if let Some(c) = re_li.captures(line) {
            li_vals.push(c[1].parse::<i64>().unwrap_or(0));
        } else if re_li_err.is_match(line) {
            li_errs += 1;
        }
    }

    // Ensure exactly two events captured for deterministic checks on exe-side
    assert!(
        s_vals.len() >= 2 && ls_vals.len() >= 2 && si_vals.len() >= 2 && sb_vals.len() >= 2,
        "Insufficient events for delta checks (exe-side). STDOUT: {stdout}"
    );

    // Check program logic deltas between first two hits
    assert!(s_vals[1] >= s_vals[0], "s.counter should be non-decreasing");
    assert_eq!(ls_vals[1] - ls_vals[0], 2, "ls.counter should +2 per tick");
    assert_eq!(si_vals[1] - si_vals[0], 2, "s_internal should +2 per tick");
    assert_eq!(
        sb_vals[1] - sb_vals[0],
        3,
        "s_bss_counter should +3 per tick"
    );
    // lib side over two events:
    // - If we have two numeric samples, enforce +5 delta.
    // - Otherwise accept two NULL-deref errors (the call to lib_get_internal_counter_ptr() may
    //   not have executed yet at the anchor PC), or mixed 1 value + 1 NULL.
    if li_vals.len() >= 2 {
        assert_eq!(
            li_vals[1] - li_vals[0],
            5,
            "lib_internal_counter should +5 per tick"
        );
    } else {
        assert!(
            (li_vals.len() == 1 && li_errs >= 1) || (li_vals.is_empty() && li_errs >= 2),
            "Expected lib_internal to be numeric twice, or NULL twice, or mixed once over two events. STDOUT: {stdout}"
        );
    }

    Ok(())
}
#[tokio::test]
async fn test_direct_globals_current_module() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Directly print globals without local aliases
    let script = r#"
trace globals_program.c:32 {
    print G_STATE;
    print s_internal;
    print s_bss_counter;
    // Also verify print format with direct globals
    print "FMT:{}|{}", s_internal, s_bss_counter;
}
"#;
    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 4, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    // Expect at least some struct pretty print and integer values present
    assert!(
        stdout.contains("G_STATE") && stdout.contains("GlobalState"),
        "Expected G_STATE struct print. STDOUT: {stdout}"
    );

    let re_si = Regex::new(r"s_internal\s*=\s*(-?\d+)").unwrap();
    let re_sb = Regex::new(r"s_bss_counter\s*=\s*(-?\d+)").unwrap();
    let mut si_vals = Vec::new();
    let mut sb_vals = Vec::new();
    for line in stdout.lines() {
        if let Some(c) = re_si.captures(line) {
            si_vals.push(c[1].parse::<i64>().unwrap_or(0));
        }
        if let Some(c) = re_sb.captures(line) {
            sb_vals.push(c[1].parse::<i64>().unwrap_or(0));
        }
    }
    // We expect at least 2 hits for each
    assert!(
        si_vals.len() >= 2 && sb_vals.len() >= 2,
        "Insufficient events. STDOUT: {stdout}"
    );
    // Check deltas align with logic: +2 and +3 per tick
    assert_eq!(si_vals[1] - si_vals[0], 2, "s_internal should +2 per tick");
    assert_eq!(
        sb_vals[1] - sb_vals[0],
        3,
        "s_bss_counter should +3 per tick"
    );
    // Verify formatted line FMT:{}|{} reflects the same counters and deltas
    let re_fmt = Regex::new(r"FMT:(-?\d+)\|(-?\d+)").unwrap();
    let mut f_a = Vec::new();
    let mut f_b = Vec::new();
    for line in stdout.lines() {
        if let Some(c) = re_fmt.captures(line) {
            f_a.push(c[1].parse::<i64>().unwrap_or(0));
            f_b.push(c[2].parse::<i64>().unwrap_or(0));
        }
    }
    assert!(
        f_a.len() >= 2 && f_b.len() >= 2,
        "Insufficient FMT events. STDOUT: {stdout}"
    );
    assert_eq!(f_a[1] - f_a[0], 2, "FMT s_internal delta +2");
    assert_eq!(f_b[1] - f_b[0], 3, "FMT s_bss_counter delta +3");
    Ok(())
}

#[tokio::test]
async fn test_direct_global_cross_module() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Cross-module global: offsets are auto-populated in -p mode; expect successful struct print
    let script = r#"
trace globals_program.c:32 {
    print LIB_STATE;
    // Also emit formatted cross-module counter to ensure format-path works for globals
    print "LIBCNT:{}", LIB_STATE.counter;
}
"#;
    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 2, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    // Expect pretty struct output for LIB_STATE
    assert!(
        stdout.contains("LIB_STATE"),
        "Expected LIB_STATE in output. STDOUT: {stdout}"
    );
    // Accept either typedef name or resolved struct display
    assert!(
        stdout.contains("GlobalState {") || (stdout.contains("{") && stdout.contains("name:")),
        "Expected pretty struct print for LIB_STATE. STDOUT: {stdout}"
    );
    // Verify formatted LIBCNT increments across at least two events
    let re = Regex::new(r"LIBCNT:(-?\d+)").unwrap();
    let mut vals = Vec::new();
    for line in stdout.lines() {
        if let Some(c) = re.captures(line) {
            vals.push(c[1].parse::<i64>().unwrap_or(0));
        }
    }
    assert!(
        vals.len() >= 2,
        "Insufficient LIBCNT events. STDOUT: {stdout}"
    );
    assert_eq!(vals[1] - vals[0], 2, "LIB_STATE.counter should +2 per tick");
    Ok(())
}

#[tokio::test]
async fn test_rodata_direct_strings() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Directly print rodata arrays as strings (executable + library)
    let script = r#"
trace globals_program.c:32 {
    print g_message;    // executable .rodata (char[...])
    print lib_message;  // library .rodata (char[...])
    // Also check formatted path for strings
    print "FMT:{}|{}", g_message, lib_message;
}
"#;
    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 2, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    // Expect two quoted strings present (best-effort; content may vary across builds)
    let got_g_message = stdout
        .lines()
        .any(|l| l.contains("g_message = \"") && l.contains("\""));
    let got_lib_message = stdout
        .lines()
        .any(|l| l.contains("lib_message = \"") && l.contains("\""));
    assert!(
        got_g_message && got_lib_message,
        "Expected direct string prints for rodata. STDOUT: {stdout}"
    );
    // Look for a formatted line with both quoted strings
    let fmt_has_strings = stdout
        .lines()
        .any(|l| l.contains("FMT:") && l.matches('"').count() >= 2);
    assert!(
        fmt_has_strings,
        "Expected formatted strings line. STDOUT: {stdout}"
    );
    Ok(())
}

#[tokio::test]
async fn test_bss_first_byte_evolves() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap().to_path_buf();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Read first byte of executable/library .bss buffers via locals 'gb'/'lb'
    let script = r#"
trace globals_program.c:32 {
    print *gb; // g_bss_buffer[0]
    print *lb; // lib_bss[0]
    // Also formatted first bytes from both buffers
    print "BF:{}|{}", *gb, *lb;
}
"#;
    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 3, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    let re_gb = Regex::new(r"\*gb\s*=\s*(-?\d+)").unwrap();
    let re_lb = Regex::new(r"\*lb\s*=\s*(-?\d+)").unwrap();
    let mut gb_vals = Vec::new();
    let mut lb_vals = Vec::new();
    for line in stdout.lines() {
        if let Some(c) = re_gb.captures(line) {
            gb_vals.push(c[1].parse::<i64>().unwrap_or(0));
        }
        if let Some(c) = re_lb.captures(line) {
            lb_vals.push(c[1].parse::<i64>().unwrap_or(0));
        }
    }
    assert!(
        gb_vals.len() >= 2 && lb_vals.len() >= 2,
        "Insufficient events. STDOUT: {stdout}"
    );
    // Each tick_once increments first byte by 1
    assert!(
        gb_vals[1] >= gb_vals[0],
        "gb[0] should not decrease. STDOUT: {stdout}"
    );
    assert!(
        lb_vals[1] >= lb_vals[0],
        "lb[0] should not decrease. STDOUT: {stdout}"
    );
    // Ensure formatted BF line present and non-decreasing as well
    let re = Regex::new(r"BF:(-?\d+)\|(-?\d+)").unwrap();
    let mut fa = Vec::new();
    let mut fb = Vec::new();
    for line in stdout.lines() {
        if let Some(c) = re.captures(line) {
            fa.push(c[1].parse::<i64>().unwrap_or(0));
            fb.push(c[2].parse::<i64>().unwrap_or(0));
        }
    }
    assert!(
        fa.len() >= 2 && fb.len() >= 2,
        "Insufficient BF events. STDOUT: {stdout}"
    );
    assert!(
        fa[1] >= fa[0] && fb[1] >= fb[0],
        "BF values should not decrease. STDOUT: {stdout}"
    );
    Ok(())
}

#[tokio::test]
async fn test_print_variable_global_member_direct() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap().to_path_buf();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Directly print global member fields in variable mode
    let script = r#"
trace globals_program.c:32 {
    print G_STATE.counter;
    print LIB_STATE.counter;
}
"#;
    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 3, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    let re_g = Regex::new(r"G_STATE\.counter\s*=\s*(-?\d+)").unwrap();
    let re_l = Regex::new(r"LIB_STATE\.counter\s*=\s*(-?\d+)").unwrap();
    let mut gv = Vec::new();
    let mut lv = Vec::new();
    for line in stdout.lines() {
        if let Some(c) = re_g.captures(line) {
            gv.push(c[1].parse::<i64>().unwrap_or(0));
        }
        if let Some(c) = re_l.captures(line) {
            lv.push(c[1].parse::<i64>().unwrap_or(0));
        }
    }
    assert!(
        gv.len() >= 2 && lv.len() >= 2,
        "Insufficient events. STDOUT: {stdout}"
    );
    // Ensure non-decreasing for current-module counter
    assert!(gv[1] >= gv[0], "G_STATE.counter should be non-decreasing");
    // Cross-module LIB_STATE.counter increments by +2 per tick
    assert_eq!(lv[1] - lv[0], 2, "LIB_STATE.counter should +2 per tick");
    Ok(())
}

#[tokio::test]
async fn test_print_format_global_member_direct() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap().to_path_buf();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Print format with global member (counter int)
    let script = r#"
trace globals_program.c:32 {
    print "LIBCNT:{}", LIB_STATE.counter;
}
"#;
    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 3, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    let re = Regex::new(r"LIBCNT:(-?\d+)").unwrap();
    let mut vals = Vec::new();
    for line in stdout.lines() {
        if let Some(c) = re.captures(line) {
            vals.push(c[1].parse::<i64>().unwrap_or(0));
        }
    }
    assert!(
        vals.len() >= 2,
        "Insufficient LIBCNT events. STDOUT: {stdout}"
    );
    assert_eq!(vals[1] - vals[0], 2, "LIB_STATE.counter should +2 per tick");
    Ok(())
}

#[tokio::test]
async fn test_print_format_global_member_leaf() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap().to_path_buf();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Ensure formatted multi-level member prints scalar value, not whole struct
    let script = r#"
trace globals_program.c:32 {
    print "LIBY:{}", LIB_STATE.inner.y;
}
"#;
    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 3, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    // Capture floating values and ensure delta ~ 1.25 between first two events
    let re = Regex::new(r"LIBY:([0-9]+(?:\.[0-9]+)?)").unwrap();
    let mut vals: Vec<f64> = Vec::new();
    for line in stdout.lines() {
        if let Some(c) = re.captures(line) {
            let v: f64 = c[1].parse().unwrap_or(0.0);
            // Line should not include full struct formatting
            assert!(
                !line.contains("Inner {"),
                "Leaf member should print scalar, got struct: {line}"
            );
            vals.push(v);
        }
    }
    assert!(
        vals.len() >= 2,
        "Insufficient LIBY events. STDOUT: {stdout}"
    );
    // Compare with tolerance by scaling to centi-precision
    let d = ((vals[1] - vals[0]) * 100.0).round() as i64;
    assert_eq!(
        d, 125,
        "LIB_STATE.inner.y should +1.25 per tick. STDOUT: {stdout}"
    );
    Ok(())
}

#[tokio::test]
async fn test_print_variable_global_member_leaf() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap().to_path_buf();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Variable mode: nested chain leaf prints as scalar
    let script = r#"
trace globals_program.c:32 {
    print LIB_STATE.inner.y;
}
"#;
    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 3, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    let re = Regex::new(r"LIB_STATE\.inner\.y\s*=\s*(-?[0-9]+(?:\.[0-9]+)?)").unwrap();
    let mut vals: Vec<f64> = Vec::new();
    for line in stdout.lines() {
        if let Some(c) = re.captures(line) {
            let v: f64 = c[1].parse().unwrap_or(0.0);
            vals.push(v);
        }
    }
    assert!(
        vals.len() >= 2,
        "Insufficient LIB_STATE.inner.y events. STDOUT: {stdout}"
    );
    let d = ((vals[1] - vals[0]) * 100.0).round() as i64;
    assert_eq!(d, 125, "inner.y should +1.25 per tick. STDOUT: {stdout}");
    Ok(())
}

// ============================================================================
// PerfEventArray Tests (--force-perf-event-array)
// These tests verify the same functionality but with PerfEventArray backend
// ============================================================================

#[tokio::test]
async fn test_print_format_current_global_member_leaf_perf() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap().to_path_buf();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Current-module leaf member via formatted print
    let script = r#"
trace globals_program.c:32 {
    print "GY:{}", G_STATE.inner.y;
}
"#;
    // Collect exactly 2 events for deterministic delta/null checks
    let (exit_code, stdout, stderr) =
        run_ghostscope_with_script_for_pid_perf(script, 2, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    let re = Regex::new(r"GY:([0-9]+(?:\.[0-9]+)?)").unwrap();
    let mut vals: Vec<f64> = Vec::new();
    for line in stdout.lines() {
        if let Some(c) = re.captures(line) {
            // Ensure scalar print (no struct pretty-print)
            assert!(
                !line.contains("Inner {"),
                "Expected scalar for G_STATE.inner.y, got struct: {line}"
            );
            vals.push(c[1].parse().unwrap_or(0.0));
        }
    }
    assert!(vals.len() >= 2, "Insufficient GY events. STDOUT: {stdout}");
    // inner.y increments by 0.5 per tick in globals_program
    let d = ((vals[1] - vals[0]) * 100.0).round() as i64;
    assert_eq!(
        d, 50,
        "G_STATE.inner.y should +0.5 per tick. STDOUT: {stdout}"
    );
    Ok(())
}

#[tokio::test]
async fn test_tick_once_entry_strings_and_structs_perf() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap().to_path_buf();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Attach at a source line after local aliases are initialized (line 26 is first non-comment after 19..24)
    let script = r#"
trace globals_program.c:26 {
    print s.name;       // char[32] -> string
    print ls.name;      // from shared library
    print s;            // struct GlobalState pretty print
    print *ls;          // deref pointer to struct
}
"#;

    let (exit_code, stdout, stderr) =
        run_ghostscope_with_script_for_pid_perf(script, 2, pid).await?;

    let _ = prog.kill().await.is_ok();

    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    // s.name should be a quoted string (either "INIT" or updated value)
    let has_s_name = stdout.contains("\"INIT\"") || stdout.contains("\"RUNNING\"");
    assert!(has_s_name, "Expected s.name string. STDOUT: {stdout}");

    // ls.name (library) should be "LIB"
    assert!(
        stdout.contains("\"LIB\""),
        "Expected ls.name == \"LIB\". STDOUT: {stdout}"
    );

    // Pretty struct prints for s or *ls should be present
    let has_struct = stdout.contains("GlobalState {") || stdout.contains("*ls = GlobalState {");
    assert!(
        has_struct,
        "Expected pretty struct output. STDOUT: {stdout}"
    );

    Ok(())
}

#[tokio::test]
async fn test_memcmp_numeric_pointer_literal_and_hex_len() -> anyhow::Result<()> {
    init();

    let binary_path = FIXTURES.get_test_binary("globals_program")?;
    let bin_dir = binary_path.parent().unwrap().to_path_buf();
    let mut prog = Command::new(&binary_path)
        .current_dir(bin_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let pid = prog
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;
    tokio::time::sleep(Duration::from_millis(500)).await;

    let script = r#"
trace globals_program.c:32 {
    // hex static length should work when comparing equal pointers
    if memcmp(&lib_pattern[0], &lib_pattern[0], 0x10) { print "LENHEX"; }
}
"#;

    let (exit_code, stdout, stderr) = run_ghostscope_with_script_for_pid(script, 4, pid).await?;
    let _ = prog.kill().await.is_ok();
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    // hex static length path succeeds
    assert!(
        stdout.contains("LENHEX"),
        "Expected LENHEX. STDOUT: {stdout}"
    );
    // no numeric pointer literal checks anymore
    Ok(())
}