jonesy 0.7.11

Jonesy is here to help you not panic!
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
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
#![allow(unused_variables)] // TODO Just for now
#![allow(dead_code)] // TODO Just for now

use crate::heuristics::is_dependency_path;
use capstone::arch::BuildsCapstone;
use capstone::{Capstone, Insn, arch};
use dashmap::DashMap;
/// Here's how to use gimli with a MachO binary to get function information and then find call sites
/// Note that DWARF doesn't directly encode "function A calls
/// function B" - it provides accurate function boundaries and source locations, which you combine with disassembly.
use gimli::{
    AttributeValue, ColumnType, DebuggingInformationEntry, Dwarf, EndianSlice, Reader,
    RunTimeEndian, SectionId, Unit,
};
use goblin::Object;
use goblin::archive::Archive;
use goblin::container::{Container, Ctx, Endian};
use goblin::mach::segment::SectionData;
use goblin::mach::segment::{Section, Segment};
use goblin::mach::symbols::N_OSO;
use goblin::mach::{Mach, MachO};
use ouroboros::self_referencing;
use rayon::prelude::*;
use regex::Regex;
use rustc_demangle::demangle;
use std::borrow::Cow;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::{fs, io};

type DwarfReader<'a> = EndianSlice<'a, RunTimeEndian>;

/// Source location tuple: (file, line, column)
type SourceLocation = (Option<String>, Option<u32>, Option<u32>);

/// Result type for get_functions_from_dwarf: (functions, inlined, string_tables)
type DwarfFunctionResult = (Vec<FunctionInfo>, Vec<FunctionInfo>, StringTables);

/// Check if a file path matches a crate source pattern.
/// Supports multi-pattern format with "|" separator for workspace mode.
/// Check if a file path matches the crate source pattern.
/// For single-crate projects with pattern "src/", uses the valid_files set
/// to exclude dependency paths that happen to start with src/.
pub fn matches_crate_pattern(file_path: &str, crate_pattern: &str) -> bool {
    matches_crate_pattern_validated(file_path, crate_pattern, None)
}

/// Check if a file path matches the crate source pattern, with optional validation.
/// When valid_files is provided and pattern is generic ("src/"), validates against actual project files.
pub fn matches_crate_pattern_validated(
    file_path: &str,
    crate_pattern: &str,
    valid_files: Option<&ValidSourceFiles>,
) -> bool {
    // Check if path matches the pattern first
    let matches = crate_pattern
        .split('|')
        .any(|pattern| !pattern.is_empty() && file_path.contains(pattern));

    if !matches {
        return false;
    }

    // For single-crate projects (pattern is just "src/"), validate against actual project files
    // This prevents false positives from dependencies with relative src/ paths in DWARF
    // The allowlist check comes BEFORE dependency heuristics to ensure legitimate project files
    // (like "library/src/..." or "src/__generated.rs") are not incorrectly excluded
    if let Some(valid) = valid_files {
        if valid.needs_validation(crate_pattern) {
            return valid.contains(file_path);
        }
    }

    // Only apply dependency heuristics when we don't have an allowlist for validation
    // This is for workspace patterns like "flowc/src/" where we rely on pattern specificity
    if is_dependency_path(file_path) {
        return false;
    }

    true
}

/// A set of valid source files for a project.
/// Used to filter out dependency paths that have relative src/ paths.
#[derive(Debug, Default)]
pub struct ValidSourceFiles {
    /// Set of valid file paths (relative to project root, e.g., "src/main.rs")
    files: std::collections::HashSet<String>,
    /// Canonical project root path for absolute path matching
    project_root: Option<std::path::PathBuf>,
}

impl ValidSourceFiles {
    /// Build a set of valid source files by scanning the entire project directory.
    /// This handles all cases including #[path] directives pointing outside src/.
    /// Excludes target/, .git/, and other non-source directories.
    pub fn from_project_root(project_root: &std::path::Path) -> Self {
        let mut files = std::collections::HashSet::new();

        // Scan the entire project for .rs files, excluding build artifacts
        Self::scan_project_directory(project_root, project_root, &mut files);

        // Store canonical project root for absolute path matching
        let canonical_root = std::fs::canonicalize(project_root).ok();

        Self {
            files,
            project_root: canonical_root,
        }
    }

    /// Recursively scan directory for .rs files, excluding non-source directories
    fn scan_project_directory(
        project_root: &std::path::Path,
        dir: &std::path::Path,
        files: &mut std::collections::HashSet<String>,
    ) {
        // Directories to exclude (build artifacts, version control, examples, tests, benches)
        const EXCLUDED_DIRS: &[&str] = &[
            "target",
            ".git",
            ".hg",
            ".svn",
            "node_modules",
            ".cargo",
            ".rustup",
            "examples",
            "tests",
            "benches",
        ];

        let Ok(entries) = std::fs::read_dir(dir) else {
            return;
        };

        for entry in entries.filter_map(|e| e.ok()) {
            let path = entry.path();
            let name = entry.file_name();
            let name_str = name.to_string_lossy();

            if path.is_file() && name_str.ends_with(".rs") && name_str != "build.rs" {
                // Store path relative to project root
                if let Ok(rel_path) = path.strip_prefix(project_root) {
                    files.insert(rel_path.to_string_lossy().to_string());
                }
            } else if path.is_dir()
                && !name_str.starts_with('.')
                && !EXCLUDED_DIRS.contains(&name_str.as_ref())
            {
                Self::scan_project_directory(project_root, &path, files);
            }
        }
    }

    /// Check if this file set should be used for validation.
    /// Only validates when the pattern is generic (just "src/").
    fn needs_validation(&self, pattern: &str) -> bool {
        // Validate for single-crate projects where pattern is generic
        // Workspace patterns like "flowc/src/" are specific enough
        pattern == "src/" && !self.files.is_empty()
    }

    /// Check if a file path is in the valid set.
    fn contains(&self, file_path: &str) -> bool {
        // Direct match (relative paths)
        if self.files.contains(file_path) {
            return true;
        }

        // Also check with leading "./" stripped
        if let Some(stripped) = file_path.strip_prefix("./") {
            if self.files.contains(stripped) {
                return true;
            }
        }

        // Check if file_path ends with any of our valid files
        // This handles paths like "examples/panic/src/main.rs" when we have "src/main.rs"
        // The check requires matching on "/" boundary to avoid partial filename matches
        for valid_file in &self.files {
            // Build suffix to match: "/" + valid_file (e.g., "/src/main.rs")
            let suffix = format!("/{}", valid_file);
            if file_path.ends_with(&suffix) {
                return true;
            }
        }

        // For absolute paths, check if they resolve to a file in our project
        // Use canonical path comparison to avoid false positives from suffix matching
        if let Some(project_root) = &self.project_root {
            let file_path_buf = std::path::Path::new(file_path);
            if file_path_buf.is_absolute() {
                // Try to canonicalize and check if it starts with project root
                if let Ok(canonical_file) = std::fs::canonicalize(file_path_buf) {
                    if let Ok(relative) = canonical_file.strip_prefix(project_root) {
                        // Check if this relative path is in our set
                        let rel_str = relative.to_string_lossy();
                        return self.files.contains(rel_str.as_ref());
                    }
                }
            }
        }

        false
    }
}

#[allow(clippy::large_enum_variant)]
pub enum SymbolTable<'a> {
    MachO(Mach<'a>),
    Archive(Archive<'a>),
}

/// A line entry for crate source code, used for fast lookups
#[derive(Debug, Clone)]
pub struct CrateLineEntry {
    pub address: u64,
    pub line: u32,
    pub column: Option<u32>,
}

/// Pre-built line table containing only crate source entries, sorted by address.
/// Used for fast binary search in get_crate_line_at_address.
#[derive(Debug)]
pub struct CrateLineTable {
    entries: Vec<CrateLineEntry>,
}

impl CrateLineTable {
    /// Build a line table with only entries from crate source files.
    pub fn build<R: Reader>(dwarf: &Dwarf<R>, crate_src_path: &str) -> Result<Self, gimli::Error> {
        let mut entries = Vec::new();

        let mut units = dwarf.units();
        while let Some(header) = units.next()? {
            let unit = dwarf.unit(header)?;

            if let Some(program) = &unit.line_program {
                let mut rows = program.clone().rows();

                while let Some((header, row)) = rows.next_row()? {
                    if let Some(file_entry) = row.file(header) {
                        let file_name = dwarf
                            .attr_string(&unit, file_entry.path_name())?
                            .to_string_lossy()?
                            .into_owned();

                        let full_path = if let Some(dir) = file_entry.directory(header) {
                            let dir_str = dwarf
                                .attr_string(&unit, dir)?
                                .to_string_lossy()?
                                .into_owned();
                            if dir_str.is_empty() {
                                file_name
                            } else {
                                format!("{}/{}", dir_str, file_name)
                            }
                        } else {
                            file_name
                        };

                        // Only include entries from crate source
                        if matches_crate_pattern(&full_path, crate_src_path)
                            && let Some(line) = row.line()
                        {
                            let column = match row.column() {
                                ColumnType::LeftEdge => None,
                                ColumnType::Column(c) => Some(c.get() as u32),
                            };
                            entries.push(CrateLineEntry {
                                address: row.address(),
                                line: line.get() as u32,
                                column,
                            });
                        }
                    }
                }
            }
        }

        // Sort by address for binary search
        entries.sort_by_key(|e| e.address);

        Ok(Self { entries })
    }

    /// Find the crate line and column at a specific address within a function.
    /// Returns the line and column of the last entry in [func_start, call_site_addr].
    pub fn get_line(&self, func_start: u64, call_site_addr: u64) -> (Option<u32>, Option<u32>) {
        // Find entries in range [func_start, call_site_addr]
        let start_idx = self.entries.partition_point(|e| e.address < func_start);
        let end_idx = self
            .entries
            .partition_point(|e| e.address <= call_site_addr);

        // Return the last entry in range (highest address)
        if end_idx > start_idx {
            let entry = &self.entries[end_idx - 1];
            (Some(entry.line), entry.column)
        } else {
            (None, None)
        }
    }

    /// Get the number of entries
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns true if the table has no entries
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

/// A line entry for full source location lookups.
/// Uses file_id for string interning to reduce memory pressure.
#[derive(Debug, Clone)]
pub struct FullLineEntry {
    pub address: u64,
    /// Index into FullLineTable's file_pool for the file path
    file_id: u32,
    pub line: u32,
    pub column: Option<u32>,
}

/// Pre-built line table containing ALL line entries, sorted by address.
/// Uses string interning for file paths to reduce memory pressure.
/// Instead of storing 1M+ duplicate path strings, stores file IDs that
/// index into a deduplicated file pool.
#[derive(Debug)]
pub struct FullLineTable {
    entries: Vec<FullLineEntry>,
    /// Deduplicated file path pool
    file_pool: Vec<String>,
}

impl FullLineTable {
    /// Build a complete line table from DWARF debug info.
    /// Uses string interning to deduplicate file paths and reduce memory usage.
    pub fn build<R: Reader>(dwarf: &Dwarf<R>) -> Result<Self, gimli::Error> {
        let mut entries = Vec::new();
        let mut file_pool = Vec::new();
        let mut file_to_id: ahash::AHashMap<String, u32> = ahash::AHashMap::new();

        let mut units = dwarf.units();
        while let Some(header) = units.next()? {
            let unit = dwarf.unit(header)?;

            if let Some(program) = &unit.line_program {
                let mut rows = program.clone().rows();

                while let Some((header, row)) = rows.next_row()? {
                    if let Some(file_entry) = row.file(header) {
                        let file_name = dwarf
                            .attr_string(&unit, file_entry.path_name())?
                            .to_string_lossy()?
                            .into_owned();

                        let full_path = if let Some(dir) = file_entry.directory(header) {
                            let dir_str = dwarf
                                .attr_string(&unit, dir)?
                                .to_string_lossy()?
                                .into_owned();
                            if dir_str.is_empty() {
                                file_name
                            } else {
                                format!("{}/{}", dir_str, file_name)
                            }
                        } else {
                            file_name
                        };

                        // Intern the file path to reduce memory usage
                        // Use two-step get/insert to avoid cloning on cache hits
                        let file_id = if let Some(&id) = file_to_id.get(&full_path) {
                            id
                        } else {
                            let id = file_pool.len() as u32;
                            file_pool.push(full_path.clone());
                            file_to_id.insert(full_path, id);
                            id
                        };

                        // Include all entries, even without line numbers (use 0 like original)
                        // to match the original get_source_location behavior
                        let line = row.line().map(|l| l.get() as u32).unwrap_or(0);
                        let column = match row.column() {
                            ColumnType::LeftEdge => None,
                            ColumnType::Column(c) => Some(c.get() as u32),
                        };
                        entries.push(FullLineEntry {
                            address: row.address(),
                            file_id,
                            line,
                            column,
                        });
                    }
                }
            }
        }

        // Sort by address for binary search (stable sort preserves unit order for
        // entries with same address, which get_source_location relies on)
        entries.sort_by_key(|e| e.address);

        Ok(Self { entries, file_pool })
    }

    /// Get source location for an address using binary search.
    /// Returns the entry whose address is <= the query address.
    /// For entries with the same address, returns the first one (from earliest unit,
    /// matching original get_source_location behavior).
    pub fn get_source_location(&self, addr: u64) -> SourceLocation {
        // Find the first entry with address > addr
        let idx = self.entries.partition_point(|e| e.address <= addr);

        if idx > 0 {
            // Found an entry with address <= addr. Now find the FIRST entry at this address.
            // Use binary search to keep this O(log n) instead of linear scan.
            let target_addr = self.entries[idx - 1].address;
            let first_idx = self.entries[..idx].partition_point(|e| e.address < target_addr);
            let entry = &self.entries[first_idx];
            // Look up file path from the interned pool
            let file = self.file_pool.get(entry.file_id as usize).cloned();
            (file, Some(entry.line), entry.column)
        } else {
            (None, None, None)
        }
    }

    /// Find the best crate-source line for a call site where stdlib code is inlined.
    ///
    /// When stdlib code (like `unwrap()`) is inlined into a crate function,
    /// the DWARF line table at the call instruction address points to the stdlib
    /// source (e.g., `option.rs:1014`), not the crate source line where the call
    /// was written. This method finds a better line by:
    ///
    /// 1. First searching backward from the call site for the nearest crate-source
    ///    entry (handles cases where there's a crate entry just before the inlined code).
    /// 2. If backward search only finds the function-start line, searches forward
    ///    to find the next crate-source entry after the inlined code and reports the
    ///    line just before it (typically the line containing the actual call expression).
    ///
    /// The search is bounded by `func_start`/`func_end` to avoid crossing function
    /// boundaries.
    pub fn get_nearest_crate_line(
        &self,
        addr: u64,
        func_start: u64,
        func_end: u64,
        func_start_line: Option<u32>,
        crate_src_path: &str,
    ) -> (Option<u32>, Option<u32>) {
        // Find entries up to and including addr
        let end_idx = self.entries.partition_point(|e| e.address <= addr);
        if end_idx == 0 {
            return (None, None);
        }

        // Search backward from the call site for the nearest crate-source entry
        for i in (0..end_idx).rev() {
            let entry = &self.entries[i];
            if entry.address < func_start {
                break;
            }
            if let Some(file) = self.file_pool.get(entry.file_id as usize) {
                if matches_crate_pattern(file, crate_src_path) && entry.line > 0 {
                    // Found a crate entry, but if it's just the function start,
                    // try searching forward for a better line
                    if func_start_line.is_some_and(|fl| entry.line == fl) {
                        break; // Fall through to forward search
                    }
                    return (Some(entry.line), entry.column);
                }
            }
        }

        // Backward search only found the function start. Search forward from
        // the call site to find the next crate-source entry (typically the
        // function epilogue / closing brace). The line just before that is
        // likely where the actual call expression is.
        for i in end_idx..self.entries.len() {
            let entry = &self.entries[i];
            if entry.address >= func_end {
                break;
            }
            if let Some(file) = self.file_pool.get(entry.file_id as usize) {
                if matches_crate_pattern(file, crate_src_path) && entry.line > 0 {
                    // Found the next crate entry (e.g., closing brace).
                    // The call is on the line before the epilogue.
                    if let Some(func_line) = func_start_line {
                        if entry.line > func_line + 1 {
                            return (Some(entry.line - 1), None);
                        }
                    }
                    return (Some(entry.line), entry.column);
                }
            }
        }

        (None, None)
    }

    /// Get the number of entries
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns true if the table has no entries
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Build both CrateLineTable and FullLineTable in a single pass over DWARF.
    /// This is more efficient than building each separately since we only iterate
    /// the line program once.
    pub fn build_both<R: Reader>(
        dwarf: &Dwarf<R>,
        crate_src_path: &str,
    ) -> Result<(CrateLineTable, FullLineTable), gimli::Error> {
        let mut crate_entries = Vec::new();
        let mut full_entries = Vec::new();
        let mut file_pool = Vec::new();
        let mut file_to_id: ahash::AHashMap<String, u32> = ahash::AHashMap::new();

        let mut units = dwarf.units();
        while let Some(header) = units.next()? {
            let unit = dwarf.unit(header)?;

            if let Some(program) = &unit.line_program {
                let mut rows = program.clone().rows();
                // Track last crate entry to carry forward at crate→stdlib transitions.
                // When inlined stdlib code (e.g., unwrap) appears, the DWARF line table
                // switches from crate source to stdlib source. We emit a synthetic crate
                // entry at the transition address so get_line() resolves to the call site
                // rather than falling back to the function start.
                let mut last_crate_line: Option<(u32, Option<u32>)> = None;
                let mut last_was_crate = false;

                while let Some((header, row)) = rows.next_row()? {
                    if let Some(file_entry) = row.file(header) {
                        let file_name = dwarf
                            .attr_string(&unit, file_entry.path_name())?
                            .to_string_lossy()?
                            .into_owned();

                        let full_path = if let Some(dir) = file_entry.directory(header) {
                            let dir_str = dwarf
                                .attr_string(&unit, dir)?
                                .to_string_lossy()?
                                .into_owned();
                            if dir_str.is_empty() {
                                file_name
                            } else {
                                format!("{}/{}", dir_str, file_name)
                            }
                        } else {
                            file_name
                        };

                        // Check crate match before interning (needs &full_path)
                        let is_crate_match = matches_crate_pattern(&full_path, crate_src_path);

                        // Intern the file path (avoid double clone on cache miss)
                        let file_id = if let Some(&id) = file_to_id.get(&full_path) {
                            id
                        } else {
                            let id = file_pool.len() as u32;
                            file_pool.push(full_path.clone());
                            file_to_id.insert(full_path, id);
                            id
                        };

                        // Add to full line table (all entries)
                        let line = row.line().map(|l| l.get() as u32).unwrap_or(0);
                        let column = match row.column() {
                            ColumnType::LeftEdge => None,
                            ColumnType::Column(c) => Some(c.get() as u32),
                        };
                        full_entries.push(FullLineEntry {
                            address: row.address(),
                            file_id,
                            line,
                            column,
                        });

                        // Add to crate line table if matches pattern and has line
                        if is_crate_match && line > 0 {
                            crate_entries.push(CrateLineEntry {
                                address: row.address(),
                                line,
                                column,
                            });
                            last_crate_line = Some((line, column));
                            last_was_crate = true;
                        } else {
                            // Transition from crate to non-crate (stdlib): emit synthetic
                            // crate entry at this address with the last crate line info
                            if last_was_crate {
                                if let Some((prev_line, prev_col)) = last_crate_line {
                                    crate_entries.push(CrateLineEntry {
                                        address: row.address(),
                                        line: prev_line,
                                        column: prev_col,
                                    });
                                }
                            }
                            last_was_crate = false;
                        }
                    }
                }
            }
        }

        // Sort by address for binary search
        // crate_entries: par_sort is safe (get_line returns last entry, order doesn't matter)
        // full_entries: stable sort needed (get_source_location returns first entry)
        crate_entries.par_sort_by_key(|e| e.address);
        full_entries.sort_by_key(|e| e.address);

        Ok((
            CrateLineTable {
                entries: crate_entries,
            },
            FullLineTable {
                entries: full_entries,
                file_pool,
            },
        ))
    }
}

/// Interned string tables for function names and file paths.
/// Reduces memory by deduplicating strings and enables compact FunctionInfo.
#[derive(Debug, Default)]
pub struct StringTables {
    /// Deduplicated function names
    names: Vec<String>,
    /// Map for O(1) name lookup during interning
    name_map: HashMap<String, u32>,
    /// Deduplicated file paths
    files: Vec<String>,
    /// Map for O(1) file lookup during interning
    file_map: HashMap<String, u32>,
}

impl StringTables {
    /// Create empty string tables
    pub fn new() -> Self {
        Self::default()
    }

    /// Intern a function name, returning its index.
    /// If the name already exists, returns the existing index.
    pub fn intern_name(&mut self, name: String) -> u32 {
        if let Some(&idx) = self.name_map.get(&name) {
            idx
        } else {
            let idx = self.names.len() as u32;
            self.name_map.insert(name.clone(), idx);
            self.names.push(name);
            idx
        }
    }

    /// Intern a file path, returning its index + 1.
    /// Returns 0 for None. Index is offset by 1 to use 0 as sentinel.
    pub fn intern_file(&mut self, file: Option<String>) -> u32 {
        match file {
            None => 0,
            Some(f) => {
                if let Some(&idx) = self.file_map.get(&f) {
                    idx + 1 // Offset by 1 (0 = None)
                } else {
                    let idx = self.files.len() as u32;
                    self.file_map.insert(f.clone(), idx);
                    self.files.push(f);
                    idx + 1 // Offset by 1 (0 = None)
                }
            }
        }
    }

    /// Get a name by index
    #[inline]
    pub fn get_name(&self, idx: u32) -> &str {
        &self.names[idx as usize]
    }

    /// Get a file by index (0 = None)
    #[inline]
    pub fn get_file(&self, idx: u32) -> Option<&str> {
        if idx == 0 {
            None
        } else {
            Some(&self.files[(idx - 1) as usize])
        }
    }
}

/// Function info extracted from DWARF of the calling function.
/// Uses indices into StringTables for compact memory layout (32 bytes).
#[derive(Debug, Clone, Copy)]
pub struct FunctionInfo {
    /// Start address of the function
    pub start_address: u64,
    /// End address of the function
    pub end_address: u64,
    /// Index into StringTables.names
    pub name_idx: u32,
    /// Index into StringTables.files (0 = None, otherwise idx + 1)
    pub file_idx: u32,
    /// Line number (0 = None)
    pub line: u32,
}

/// Bucket size for spatial partitioning of inlined functions.
/// Using 64 bytes provides fine-grained partitioning with low per-bucket counts.
const INLINED_BUCKET_SHIFT: u32 = 12; // 2^12 = 4096 bytes (optimal per benchmarking)
const INLINED_BUCKET_SIZE: u64 = 1 << INLINED_BUCKET_SHIFT;

/// Index for O(log n) function lookup by address.
/// Functions are sorted by start_address for binary search.
/// Inlined functions use bucketed lookup for faster searches.
/// Owns the StringTables for name/file lookups.
#[derive(Debug)]
pub struct FunctionIndex {
    /// Functions sorted by start_address (non-inlined subprograms)
    functions: Vec<FunctionInfo>,
    /// Inlined functions (stored for ownership)
    inlined: Vec<FunctionInfo>,
    /// Bucketed index for fast inlined function lookup.
    /// Maps bucket_id -> indices into `inlined` vec.
    /// Each function appears in all buckets its address range spans.
    inlined_buckets: HashMap<u64, Vec<usize>>,
    /// Interned strings for function names and file paths
    strings: StringTables,
}

impl FunctionIndex {
    /// Compute bucket ID for an address
    #[inline]
    fn bucket_id(addr: u64) -> u64 {
        addr >> INLINED_BUCKET_SHIFT
    }

    /// Build a function index from a list of functions.
    /// Sorts the functions by start_address for binary search.
    pub fn new(mut functions: Vec<FunctionInfo>, strings: StringTables) -> Self {
        functions.sort_by_key(|f| f.start_address);
        // Note: DWARF may have overlapping function ranges (e.g., from inlining).
        // We don't assert non-overlapping here because it's common in real binaries.
        // The binary search will find one valid function, which is sufficient.
        Self {
            functions,
            inlined: Vec::new(),
            inlined_buckets: HashMap::new(),
            strings,
        }
    }

    /// Build a function index with separate inlined function tracking.
    /// Uses bucketed spatial partitioning for fast inlined function lookup.
    pub fn new_with_inlined(
        mut functions: Vec<FunctionInfo>,
        inlined: Vec<FunctionInfo>,
        strings: StringTables,
    ) -> Self {
        functions.sort_by_key(|f| f.start_address);

        // Build bucket index for inlined functions
        // Each function is added to all buckets its address range spans
        let mut inlined_buckets: HashMap<u64, Vec<usize>> = HashMap::new();
        for (idx, func) in inlined.iter().enumerate() {
            let start_bucket = Self::bucket_id(func.start_address);
            let end_bucket = Self::bucket_id(func.end_address.saturating_sub(1));
            for bucket in start_bucket..=end_bucket {
                inlined_buckets.entry(bucket).or_default().push(idx);
            }
        }

        Self {
            functions,
            inlined,
            inlined_buckets,
            strings,
        }
    }

    /// Get the function name for a FunctionInfo
    #[inline]
    pub fn get_name(&self, func: &FunctionInfo) -> &str {
        self.strings.get_name(func.name_idx)
    }

    /// Get the file path for a FunctionInfo (None if not available)
    #[inline]
    pub fn get_file(&self, func: &FunctionInfo) -> Option<&str> {
        self.strings.get_file(func.file_idx)
    }

    /// Get the line number for a FunctionInfo (None if 0)
    #[inline]
    pub fn get_line(&self, func: &FunctionInfo) -> Option<u32> {
        if func.line == 0 {
            None
        } else {
            Some(func.line)
        }
    }

    /// Get a reference to the string tables
    pub fn strings(&self) -> &StringTables {
        &self.strings
    }

    /// Find the function containing the given address using binary search.
    /// Returns a reference to the function if found.
    /// Note: This returns the containing function, not inlined functions.
    /// Use `find_function_name` to get the most specific function name.
    #[inline]
    pub fn find_containing(&self, addr: u64) -> Option<&FunctionInfo> {
        if self.functions.is_empty() {
            return None;
        }

        // Binary search for the largest start_address <= addr
        let idx = match self
            .functions
            .binary_search_by_key(&addr, |f| f.start_address)
        {
            Ok(i) => i,            // Exact match on start_address
            Err(0) => return None, // addr is before first function
            Err(i) => i - 1,       // Use previous function
        };

        let func = &self.functions[idx];
        // Check if addr is within this function's range
        if addr >= func.start_address && addr < func.end_address {
            Some(func)
        } else {
            None
        }
    }

    /// Find the most specific function name for an address.
    /// This checks inlined functions first (more specific), then falls back
    /// to the containing function. Use this when displaying function names.
    #[inline]
    pub fn find_function_name(&self, addr: u64) -> Option<&str> {
        // First check inlined functions (more specific)
        if let Some(inlined) = self.find_in_inlined(addr) {
            return Some(self.strings.get_name(inlined.name_idx));
        }
        // Fall back to containing function
        self.find_containing(addr)
            .map(|f| self.strings.get_name(f.name_idx))
    }

    /// Find an inlined function containing the given address.
    /// Uses bucketed lookup for O(k) where k is functions in the bucket,
    /// instead of O(n) scanning all inlined functions.
    #[inline]
    fn find_in_inlined(&self, addr: u64) -> Option<&FunctionInfo> {
        // Look up the bucket for this address
        let bucket = Self::bucket_id(addr);
        let indices = self.inlined_buckets.get(&bucket)?;

        // Search only functions in this bucket for the smallest containing range
        let mut best: Option<&FunctionInfo> = None;
        let mut best_size: u64 = u64::MAX;

        for &idx in indices {
            let func = &self.inlined[idx];
            if addr >= func.start_address && addr < func.end_address {
                let size = func.end_address - func.start_address;
                if size < best_size {
                    best = Some(func);
                    best_size = size;
                }
            }
        }

        best
    }

    /// Get a reference to the underlying functions slice.
    pub fn functions(&self) -> &[FunctionInfo] {
        &self.functions
    }
}

/// Information about a call site
/// Uses Cow<'a, str> for caller_name to support both borrowed (from SymbolIndex)
/// and owned (from DWARF) strings without allocation in the hot path.
#[derive(Debug, Clone)]
pub struct CallerInfo<'a> {
    /// Demangled name of the calling function
    pub caller_name: Cow<'a, str>,
    /// Start address of the calling function
    pub caller_start_address: u64,
    /// File of the calling function (from DWARF, if available)
    pub caller_file: Option<String>,
    /// Address of the calling instruction
    pub call_site_addr: u64,
    /// Source location of the calling instruction
    pub file: Option<String>,
    /// Line number of the calling instruction
    pub line: Option<u32>,
    /// Column number of the calling instruction
    pub column: Option<u32>,
}

/// Self-referencing struct that owns the buffer and the parsed MachO that borrows from it
#[self_referencing]
pub struct DSymInfo {
    pub debug_buffer: Vec<u8>,
    #[borrows(debug_buffer)]
    #[covariant]
    pub debug_macho: Mach<'this>,
}

/// Information about an object file from the debug map
#[derive(Debug)]
pub struct ObjectFileInfo {
    /// Path to the object file
    pub path: PathBuf,
    /// Raw bytes of the object file
    pub buffer: Vec<u8>,
    /// Symbol address translations: object file address -> final binary address
    pub addr_map: HashMap<u64, u64>,
}

/// Debug map information parsed from the binary's symbol table
pub struct DebugMapInfo {
    /// Object files referenced by the debug map
    pub object_files: Vec<ObjectFileInfo>,
}

/// Debug info source - either embedded in binary or from a separate dSYM file/bundle
pub enum DebugInfo {
    /// Debug info is embedded in the binary
    Embedded,
    /// Debug info is in a separate dSYM bundle
    DSym(Box<DSymInfo>),
    /// Debug info from object files via debug map
    DebugMap(Box<DebugMapInfo>),
    /// No debug info available
    None,
}

impl DebugInfo {
    /// Returns a reference to the debug MachO if this is a DSym variant
    pub fn debug_macho(&self) -> Option<&Mach<'_>> {
        match self {
            DebugInfo::DSym(info) => Some(info.borrow_debug_macho()),
            _ => None,
        }
    }

    /// Returns a reference to the debug buffer if this is a DSym variant
    pub fn debug_buffer(&self) -> Option<&[u8]> {
        match self {
            DebugInfo::DSym(info) => Some(info.borrow_debug_buffer()),
            _ => None,
        }
    }
}

pub fn read_symbols(buffer: &'_ [u8]) -> io::Result<SymbolTable<'_>> {
    // Use goblin's Object::parse to auto-detect the file type
    match Object::parse(buffer).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))? {
        Object::Mach(mach) => Ok(SymbolTable::MachO(mach)),
        Object::Archive(archive) => Ok(SymbolTable::Archive(archive)),
        Object::Elf(_) => Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "ELF format not supported (macOS only)",
        )),
        Object::PE(_) => Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "PE format not supported (macOS only)",
        )),
        Object::COFF(_) => Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "COFF format not supported (macOS only)",
        )),
        _ => Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "Unknown binary format",
        )),
    }
}

/// Return true if `macho` has a `__DWARF` segment or a section names `__debug_*` in any segment
pub(crate) fn has_dwarf_info(macho: &MachO) -> bool {
    for segment in macho.segments.iter() {
        if let Ok(name) = segment.name()
            && name == "__DWARF"
        {
            return true;
        }

        // Also check for debug sections in any segment
        if let Ok(sections) = segment.sections() {
            for (section, _) in sections {
                if let Ok(name) = section.name()
                    && name.starts_with("__debug_")
                {
                    return true;
                }
            }
        }
    }

    false
}

/// Returns the first symbol found whose name matches the given regex pattern.
/// The pattern is matched against the demangled symbol name.
/// Example: "rust_panic$" matches symbols ending in "rust_panic"
pub fn find_symbol_containing(
    macho: &MachO,
    pattern: &str,
) -> Result<Option<(String, String)>, regex::Error> {
    let regex = Regex::new(pattern)?;
    let symbols = match macho.symbols.as_ref() {
        Some(s) => s,
        None => return Ok(None),
    };
    for (sym_name, _) in symbols.iter().flatten() {
        let stripped = sym_name.strip_prefix("_").unwrap_or(sym_name);
        let demangled = format!("{:#}", demangle(stripped));
        if regex.is_match(&demangled) {
            return Ok(Some((sym_name.to_string(), demangled)));
        }
    }
    Ok(None)
}

/// Returns all symbols whose demangled names match any of the given patterns.
/// Returns a vector of (mangled_name, demangled_name) tuples.
pub fn find_all_symbols_matching(
    macho: &MachO,
    patterns: &[&str],
) -> Result<Vec<(String, String)>, regex::Error> {
    let regexes: Vec<Regex> = patterns
        .iter()
        .map(|p| Regex::new(p))
        .collect::<Result<Vec<_>, _>>()?;

    let mut results = Vec::new();
    let symbols = match macho.symbols.as_ref() {
        Some(s) => s,
        None => return Ok(results),
    };

    for (sym_name, _) in symbols.iter().flatten() {
        let stripped = sym_name.strip_prefix("_").unwrap_or(sym_name);
        let demangled = format!("{:#}", demangle(stripped));
        for regex in &regexes {
            if regex.is_match(&demangled) {
                results.push((sym_name.to_string(), demangled.clone()));
                break; // Only add once even if multiple patterns match
            }
        }
    }
    Ok(results)
}

// TODO Restrict this to text segments?
/// Returns the address of the first defined symbol found whose name matches `name` exactly.
/// Skips undefined/import symbols which have n_value == 0.
pub fn find_symbol_address(macho: &MachO, name: &str) -> Option<u64> {
    let symbols = macho.symbols.as_ref()?;
    for symbol in symbols.iter() {
        if let Ok((sym_name, nlist)) = symbol
            && sym_name == name
            && !nlist.is_undefined()
            && nlist.n_value != 0
        {
            return Some(nlist.n_value);
        }
    }
    None
}
fn get_text_section<'a>(macho: &MachO, buffer: &'a [u8]) -> Option<(u64, &'a [u8])> {
    get_section_by_name(macho, buffer, "__text")
}

fn get_section_by_name<'a>(macho: &MachO, buffer: &'a [u8], name: &str) -> Option<(u64, &'a [u8])> {
    for segment in &macho.segments {
        for (section, section_data) in segment.sections().unwrap() {
            if section.name().unwrap() == name {
                let offset = section.offset as usize;
                let size = section.size as usize;
                return Some((section.addr, &buffer[offset..offset + size]));
            }
        }
    }
    None
}

/// Find a segment by name
fn find_segment<'a>(macho: &'a MachO, segment_name: &str) -> Option<&'a Segment<'a>> {
    for segment in macho.segments.iter() {
        if let Ok(name) = segment.name()
            && name == segment_name
        {
            return Some(segment);
        }
    }
    None
}

/// Entry in the symbol index with lazy demangling.
/// Stores mangled name and caches demangled result on first access.
/// Uses OnceLock for thread-safe lazy initialization (required for rayon).
struct SymbolEntry {
    address: u64,
    /// Mangled symbol name (without leading underscore)
    mangled: String,
    /// Lazily computed demangled name (thread-safe)
    demangled: std::sync::OnceLock<String>,
}

impl SymbolEntry {
    fn new(address: u64, mangled: String) -> Self {
        Self {
            address,
            mangled,
            demangled: std::sync::OnceLock::new(),
        }
    }

    /// Get the demangled name, computing it lazily on first access.
    fn demangled(&self) -> &str {
        self.demangled
            .get_or_init(|| format!("{:#}", demangle(&self.mangled)))
    }
}

impl std::fmt::Debug for SymbolEntry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SymbolEntry")
            .field("address", &self.address)
            .field("mangled", &self.mangled)
            .field("demangled", &self.demangled.get())
            .finish()
    }
}

/// Precomputed sorted symbol index for efficient function lookups.
/// Build once with `SymbolIndex::new()` and reuse for many lookups.
/// Uses lazy demangling to avoid upfront cost of demangling all symbols.
#[derive(Debug)]
pub struct SymbolIndex {
    /// Sorted by address, with lazy demangling
    entries: Vec<SymbolEntry>,
}

impl SymbolIndex {
    /// Build a symbol index from a MachO binary. Call once, reuse for many lookups.
    /// Symbol names are demangled lazily on first access for better performance.
    /// Uses parallel sorting for large symbol tables.
    pub fn new(macho: &MachO) -> Option<Self> {
        use rayon::prelude::*;

        let symbols = macho.symbols.as_ref()?;

        // First pass: collect raw symbol data (sequential - iterator not Send)
        let raw_symbols: Vec<(u64, &str)> = symbols
            .iter()
            .filter_map(|s| s.ok())
            .filter(|(name, nlist)| !nlist.is_undefined() && !name.is_empty())
            .map(|(name, nlist)| (nlist.n_value, name))
            .collect();

        // Second pass: process in parallel (strip prefix, create entries)
        let mut entries: Vec<SymbolEntry> = raw_symbols
            .par_iter()
            .map(|(addr, name)| {
                let stripped = name.strip_prefix("_").unwrap_or(name);
                SymbolEntry::new(*addr, stripped.to_string())
            })
            .collect();

        // Parallel sort by address
        entries.par_sort_by_key(|e| e.address);
        Some(Self { entries })
    }

    /// Find the function containing `addr` using binary search.
    /// Returns a borrowed reference to the name (caller must ensure SymbolIndex outlives usage).
    /// Demangling is performed lazily on first access to each symbol.
    pub fn find_containing(&self, addr: u64) -> Option<(u64, &str)> {
        // Binary search for the largest address <= addr
        match self.entries.binary_search_by_key(&addr, |e| e.address) {
            Ok(i) => Some((self.entries[i].address, self.entries[i].demangled())),
            Err(0) => None, // addr is before all functions
            Err(i) => Some((self.entries[i - 1].address, self.entries[i - 1].demangled())),
        }
    }
}

// TODO segments() seems to create copies that it returns, see if we can get references instead
fn find_sections<'a>(macho: &'a MachO, section_name: &str) -> Vec<(Section, SectionData<'a>)> {
    macho
        .segments
        .iter()
        .filter_map(|segment| segment.sections().ok())
        .flatten()
        .filter_map(move |(section, data)| {
            if section.name().unwrap() == section_name {
                Some((section, data))
            } else {
                None
            }
        })
        .collect()
}

/// Pre-computed call graph mapping target addresses to their callers.
/// This allows O(1) lookup instead of O(n) scanning for each query.
/// Lifetime 'a comes from SymbolIndex - caller_name may borrow from it.
pub struct CallGraph<'a> {
    /// Maps target_addr -> list of CallerInfo
    edges: HashMap<u64, Vec<CallerInfo<'a>>>,
}

/// Extracted instruction data for parallel processing (avoids Insn lifetime issues)
struct InsnData {
    address: u64,
    call_target: Option<u64>,
}

/// ARM64 instruction size in bytes (fixed-size ISA)
const ARM64_INSN_SIZE: usize = 4;

/// Minimum chunk size for parallel disassembly (avoid overhead for small sections)
const MIN_CHUNK_SIZE: usize = 64 * 1024; // 64KB

/// ARM64 BL instruction mask: bits [31:26] must be 100101
const BL_MASK: u32 = 0xFC000000;
const BL_OPCODE: u32 = 0x94000000;

/// ARM64 B instruction mask: bits [31:26] must be 000101
const B_MASK: u32 = 0xFC000000;
const B_OPCODE: u32 = 0x14000000;

/// Decode ARM64 BL/B instruction target address from raw bytes.
/// BL encoding: 100101 imm26
/// B encoding: 000101 imm26
/// Target = PC + sign_extend(imm26) * 4
fn decode_branch_target(insn_bytes: u32, pc: u64) -> u64 {
    // Extract 26-bit immediate
    let imm26 = insn_bytes & 0x03FFFFFF;
    // Sign-extend to 32 bits and multiply by 4 (shift left 2)
    let offset = ((imm26 as i32) << 6) >> 4;
    // Add to PC
    (pc as i64 + offset as i64) as u64
}

/// Scan for ARM64 BL and B instructions in parallel by dividing into chunks.
/// BL = branch with link (function calls)
/// B = unconditional branch (tail calls to other functions)
/// Directly scans raw bytes for patterns - no disassembly needed.
/// This is much faster than using Capstone for full disassembly.
fn parallel_disassemble_arm64(text_data: &[u8], text_addr: u64) -> Vec<InsnData> {
    let num_threads = rayon::current_num_threads();

    // Calculate chunk size, ensuring alignment to instruction boundary
    let ideal_chunk_size = text_data.len() / num_threads;
    let chunk_size = if ideal_chunk_size < MIN_CHUNK_SIZE {
        // Data too small to benefit from parallelization
        text_data.len()
    } else {
        // Align to 4-byte instruction boundary
        (ideal_chunk_size / ARM64_INSN_SIZE) * ARM64_INSN_SIZE
    };

    if chunk_size >= text_data.len() {
        // Single chunk - use sequential scanning
        return scan_branch_instructions(text_data, text_addr);
    }

    // Create chunks with their base addresses
    let chunks: Vec<(usize, &[u8], u64)> = text_data
        .chunks(chunk_size)
        .enumerate()
        .map(|(i, chunk)| {
            let chunk_addr = text_addr + (i * chunk_size) as u64;
            (i, chunk, chunk_addr)
        })
        .collect();

    // Scan chunks in parallel for BL and B instructions
    let results: Vec<Vec<InsnData>> = chunks
        .par_iter()
        .map(|(_i, chunk, chunk_addr)| scan_branch_instructions(chunk, *chunk_addr))
        .collect();

    // Flatten results from all chunks
    results.into_iter().flatten().collect()
}

/// Scan a chunk of ARM64 code for BL and B instructions.
/// BL = branch with link (function calls)
/// B = unconditional branch (tail calls to other functions)
/// Directly checks raw bytes against opcode patterns.
fn scan_branch_instructions(data: &[u8], base_addr: u64) -> Vec<InsnData> {
    data.chunks_exact(ARM64_INSN_SIZE)
        .enumerate()
        .filter_map(|(i, bytes)| {
            let insn = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
            let is_bl = (insn & BL_MASK) == BL_OPCODE;
            let is_b = (insn & B_MASK) == B_OPCODE;
            if is_bl || is_b {
                let pc = base_addr + (i * ARM64_INSN_SIZE) as u64;
                let target = decode_branch_target(insn, pc);
                Some(InsnData {
                    address: pc,
                    call_target: Some(target),
                })
            } else {
                None
            }
        })
        .collect()
}

/// Sequential disassembly using Capstone - kept for non-ARM64 platforms.
#[allow(dead_code)]
fn sequential_disassemble_arm64(text_data: &[u8], text_addr: u64) -> Vec<InsnData> {
    let Ok(cs) = Capstone::new()
        .arm64()
        .mode(arch::arm64::ArchMode::Arm)
        .build()
    else {
        eprintln!("Warning: failed to initialize Capstone disassembler");
        return Vec::new();
    };

    let Ok(instructions) = cs.disasm_all(text_data, text_addr) else {
        eprintln!("Warning: disassembly failed for text section at {text_addr:#x}");
        return Vec::new();
    };

    instructions
        .iter()
        .filter_map(|insn| {
            // Match both BL (branch with link) and B (branch) for tail call detection
            let mnemonic = insn.mnemonic();
            if mnemonic == Some("bl") || mnemonic == Some("b") {
                let operand = insn.op_str()?;
                let addr_str = operand.trim_start_matches("#0x");
                let call_target = u64::from_str_radix(addr_str, 16).ok();
                Some(InsnData {
                    address: insn.address(),
                    call_target,
                })
            } else {
                None
            }
        })
        .collect()
}

impl<'a> CallGraph<'a> {
    /// Build a call graph by scanning all instructions once (no debug info).
    /// Uses parallel disassembly and parallel processing for faster analysis.
    /// Symbol names are borrowed from the provided SymbolIndex.
    pub fn build(
        macho: &MachO,
        buffer: &[u8],
        symbol_index: Option<&'a SymbolIndex>,
    ) -> Result<Self, Box<dyn std::error::Error>> {
        let Some((text_addr, text_data)) = get_text_section(macho, buffer) else {
            return Ok(Self {
                edges: HashMap::new(),
            });
        };

        // Parallel disassembly - divides text section into chunks (ARM64 only)
        #[cfg(target_arch = "aarch64")]
        let insn_data = parallel_disassemble_arm64(text_data, text_addr);

        #[cfg(not(target_arch = "aarch64"))]
        let insn_data = sequential_disassemble_arm64(text_data, text_addr);

        // Process bl instructions in parallel (the expensive part is function lookup)
        let edges: DashMap<u64, Vec<CallerInfo<'a>>> = DashMap::new();

        insn_data.par_iter().for_each(|data| {
            if let Some(call_target) = data.call_target
                && let Some((func_addr, func_name)) =
                    symbol_index.and_then(|idx| idx.find_containing(data.address))
            {
                edges.entry(call_target).or_default().push(CallerInfo {
                    caller_name: Cow::Borrowed(func_name), // No allocation - borrows from SymbolIndex
                    caller_start_address: func_addr,
                    caller_file: None,
                    call_site_addr: data.address,
                    file: None,
                    line: None,
                    column: None,
                });
            }
        });

        // Convert DashMap to HashMap and sort each caller list for deterministic ordering
        let mut edges: HashMap<u64, Vec<CallerInfo<'a>>> = edges.into_iter().collect();
        for callers in edges.values_mut() {
            callers.sort_by_key(|c| c.call_site_addr);
        }
        Ok(Self { edges })
    }

    /// Build a call graph by scanning all instructions once (no debug info).
    /// Non-parallel version for comparison or single-threaded mode.
    #[allow(dead_code)]
    pub fn build_sequential(
        macho: &MachO,
        buffer: &[u8],
        symbol_index: Option<&'a SymbolIndex>,
    ) -> Result<Self, Box<dyn std::error::Error>> {
        let mut edges: HashMap<u64, Vec<CallerInfo<'a>>> = HashMap::new();

        let Some((text_addr, text_data)) = get_text_section(macho, buffer) else {
            return Ok(Self { edges });
        };

        let cs = Capstone::new()
            .arm64()
            .mode(arch::arm64::ArchMode::Arm)
            .build()?;

        let instructions = cs
            .disasm_all(text_data, text_addr)
            .map_err(|e| format!("Disassembly failed: {e}"))?;

        for instruction in instructions.iter() {
            if let Some((call_target, caller_info)) =
                process_instruction_basic(symbol_index, instruction)
            {
                edges.entry(call_target).or_default().push(caller_info);
            }
        }

        Ok(Self { edges })
    }

    /// Build a call graph with debug info enrichment.
    /// Uses parallel disassembly and parallel processing for faster analysis.
    /// DWARF names are owned, symbol fallback names borrow from the provided SymbolIndex.
    pub fn build_with_debug_info(
        binary_macho: &MachO,
        binary_buffer: &[u8],
        debug_macho: &MachO,
        debug_buffer: &[u8],
        crate_src_path: Option<&str>,
        show_timings: bool,
        symbol_index: Option<&'a SymbolIndex>,
    ) -> Result<Self, Box<dyn std::error::Error>> {
        use std::time::Instant;

        // Pre-load DWARF info once (shared across threads)
        let step = Instant::now();
        let (functions, inlined, strings) = get_functions_from_dwarf(debug_macho, debug_buffer)?;
        let num_functions = functions.len();
        let num_inlined = inlined.len();
        // Build function index for O(log n) lookups instead of O(n) linear search
        let function_index = FunctionIndex::new_with_inlined(functions, inlined, strings);
        if show_timings {
            eprintln!(
                "    [cg timing] get_functions_from_dwarf: {:?} ({} functions, {} inlined)",
                step.elapsed(),
                num_functions,
                num_inlined
            );
        }

        let step = Instant::now();
        let dwarf = load_dwarf_sections(debug_macho, debug_buffer)?;
        if show_timings {
            eprintln!("    [cg timing] load_dwarf_sections: {:?}", step.elapsed());
        }

        let Some((text_addr, text_data)) = get_text_section(binary_macho, binary_buffer) else {
            return Ok(Self {
                edges: HashMap::new(),
            });
        };
        if show_timings {
            eprintln!(
                "    [cg timing] text section size: {} bytes",
                text_data.len()
            );
        }

        // Parallel disassembly - divides text section into chunks (ARM64 only)
        let step = Instant::now();
        #[cfg(target_arch = "aarch64")]
        let insn_data = parallel_disassemble_arm64(text_data, text_addr);

        #[cfg(not(target_arch = "aarch64"))]
        let insn_data = sequential_disassemble_arm64(text_data, text_addr);
        if show_timings {
            // insn_data contains only BL/B branch instructions (not all instructions)
            eprintln!(
                "    [cg timing] scan for branch instructions: {:?} ({} found)",
                step.elapsed(),
                insn_data.len()
            );
        }

        // Build both line tables in a single pass (saves iterating DWARF twice)
        let step = Instant::now();
        let (crate_line_table, full_line_table) = if let Some(path) = crate_src_path {
            let (crate_table, full_table) = FullLineTable::build_both(&dwarf, path)?;
            (Some(crate_table), full_table)
        } else {
            (None, FullLineTable::build(&dwarf)?)
        };
        if show_timings {
            eprintln!(
                "    [cg timing] build line tables: {:?} (crate: {} entries, full: {} entries)",
                step.elapsed(),
                crate_line_table.as_ref().map(|t| t.len()).unwrap_or(0),
                full_line_table.len()
            );
        }

        // Process bl instructions in parallel
        let step = Instant::now();
        let edges: DashMap<u64, Vec<CallerInfo<'a>>> = DashMap::new();

        insn_data.par_iter().for_each(|data| {
            if let Some(call_target) = data.call_target
                && let Some((target, caller_info)) = process_instruction_data_with_crate_table(
                    data,
                    &function_index,
                    crate_src_path,
                    &full_line_table,
                    crate_line_table.as_ref(),
                    symbol_index,
                )
            {
                edges.entry(target).or_default().push(caller_info);
            }
        });
        if show_timings {
            eprintln!("    [cg timing] process instructions: {:?}", step.elapsed(),);
        }

        // Convert DashMap to HashMap and sort each caller list for deterministic ordering
        let mut edges: HashMap<u64, Vec<CallerInfo<'a>>> = edges.into_iter().collect();
        for callers in edges.values_mut() {
            callers.sort_by_key(|c| c.call_site_addr);
        }
        Ok(Self { edges })
    }

    /// Get all callers of a target address.
    /// Returns a slice reference to avoid cloning CallerInfo instances.
    pub fn get_callers(&self, target_addr: u64) -> &[CallerInfo<'a>] {
        self.edges
            .get(&target_addr)
            .map(|v| v.as_slice())
            .unwrap_or(&[])
    }

    /// Create an empty call graph.
    pub fn empty() -> Self {
        Self {
            edges: HashMap::new(),
        }
    }
}

/// ARM64 relocation type for BL/B instructions (branch with 26-bit offset)
const ARM64_RELOC_BRANCH26: u8 = 2;

/// Line entry for DWARF line table lookups
#[derive(Debug, Clone)]
struct ObjectLineEntry {
    address: u64,
    file: String,
    line: u32,
    column: Option<u32>,
}

/// Line table built from DWARF debug info for address -> file/line lookups.
/// Used for enriching LibraryCallGraph with source location info.
struct ObjectLineTable {
    entries: Vec<ObjectLineEntry>,
}

impl ObjectLineTable {
    /// Build a line table from DWARF debug info.
    fn build<R: Reader>(dwarf: &Dwarf<R>) -> Result<Self, gimli::Error> {
        let mut entries = Vec::new();

        let mut units = dwarf.units();
        while let Some(header) = units.next()? {
            let unit = dwarf.unit(header)?;

            if let Some(program) = &unit.line_program {
                // Build file path lookup from line program header
                let header = program.header();
                let mut file_paths: Vec<String> = Vec::new();

                // Index 0 is reserved, start from index 1
                file_paths.push(String::new()); // placeholder for index 0

                for file_entry in header.file_names() {
                    let file_name = dwarf
                        .attr_string(&unit, file_entry.path_name())?
                        .to_string_lossy()?
                        .into_owned();

                    let full_path = if let Some(dir) = file_entry.directory(header) {
                        let dir_str = dwarf
                            .attr_string(&unit, dir)?
                            .to_string_lossy()?
                            .into_owned();
                        if dir_str.is_empty() {
                            file_name
                        } else {
                            format!("{}/{}", dir_str, file_name)
                        }
                    } else {
                        file_name
                    };
                    file_paths.push(full_path);
                }

                // Iterate rows and collect entries
                let mut rows = program.clone().rows();
                while let Some((_, row)) = rows.next_row()? {
                    let file_idx = row.file_index() as usize;
                    if let Some(line) = row.line() {
                        if file_idx < file_paths.len() && file_idx > 0 {
                            let column = match row.column() {
                                ColumnType::LeftEdge => None,
                                ColumnType::Column(c) => Some(c.get() as u32),
                            };
                            entries.push(ObjectLineEntry {
                                address: row.address(),
                                file: file_paths[file_idx].clone(),
                                line: line.get() as u32,
                                column,
                            });
                        }
                    }
                }
            }
        }

        // Sort by address for binary search
        entries.sort_by_key(|e| e.address);

        Ok(Self { entries })
    }

    /// Look up file/line/column for an address. Returns (file, line, column) if found.
    fn lookup(&self, address: u64) -> Option<(Option<String>, Option<u32>, Option<u32>)> {
        if self.entries.is_empty() {
            return None;
        }

        // Binary search for the largest address <= target
        let idx = match self.entries.binary_search_by_key(&address, |e| e.address) {
            Ok(i) => i,
            Err(0) => return None, // address is before first entry
            Err(i) => i - 1,       // use previous entry
        };

        let entry = &self.entries[idx];
        Some((Some(entry.file.clone()), Some(entry.line), entry.column))
    }

    /// Find the last crate source line entry in the range [func_start, call_site_addr].
    /// This provides more precise line numbers for calls within a function.
    fn get_crate_line_in_range(
        &self,
        func_start: u64,
        call_site_addr: u64,
        crate_src_path: &str,
    ) -> Option<(String, u32, Option<u32>)> {
        if self.entries.is_empty() {
            return None;
        }

        // Find entries in range [func_start, call_site_addr]
        let start_idx = self.entries.partition_point(|e| e.address < func_start);
        let end_idx = self
            .entries
            .partition_point(|e| e.address <= call_site_addr);

        // Search backwards from end to find the last crate source entry
        for i in (start_idx..end_idx).rev() {
            let entry = &self.entries[i];
            if matches_crate_pattern(&entry.file, crate_src_path) {
                return Some((entry.file.clone(), entry.line, entry.column));
            }
        }

        None
    }
}

/// Call graph for library analysis - uses symbol names instead of addresses.
/// This allows cross-object-file resolution in archives (rlib/staticlib).
pub struct LibraryCallGraph {
    /// Maps target symbol name -> list of CallerInfo (aggregated from all .o files)
    /// Uses 'static lifetime because LibraryCallGraph owns all its data
    edges: HashMap<String, Vec<CallerInfo<'static>>>,
}

impl LibraryCallGraph {
    /// Build a library call graph from a single object file.
    /// Uses relocations to find call targets by symbol name.
    /// Also enriches caller info with file/line from DWARF debug info.
    ///
    /// # Arguments
    /// * `macho` - Parsed MachO from the object file
    /// * `buffer` - Raw bytes of the object file
    /// * `crate_src_path` - Optional crate source path pattern for precise line numbers
    pub fn build_from_object(
        macho: &MachO,
        buffer: &[u8],
        crate_src_path: Option<&str>,
    ) -> Result<Self, Box<dyn std::error::Error>> {
        let mut edges: HashMap<String, Vec<CallerInfo<'static>>> = HashMap::new();

        // Get symbols for lookup
        let symbols: Vec<(String, u64)> = macho
            .symbols
            .as_ref()
            .map(|s| {
                s.iter()
                    .filter_map(|sym| {
                        let (name, nlist) = sym.ok()?;
                        Some((name.to_string(), nlist.n_value))
                    })
                    .collect()
            })
            .unwrap_or_default();

        // Build symbol index for finding containing functions
        let symbol_index = SymbolIndex::new(macho);

        // Load DWARF for file/line lookups
        let dwarf = load_dwarf_sections(macho, buffer).ok();
        let line_lookup = dwarf.as_ref().and_then(|d| ObjectLineTable::build(d).ok());

        // Create a context for parsing relocations
        let container = if macho.is_64 {
            Container::Big
        } else {
            Container::Little
        };
        let endian = if macho.little_endian {
            Endian::Little
        } else {
            Endian::Big
        };
        let ctx = Ctx::new(container, endian);

        // Find __text section and process its relocations
        for segment in macho.segments.iter() {
            if let Ok(sections) = segment.sections() {
                for (section, _data) in sections {
                    let section_name = section.name().unwrap_or("");
                    if section_name != "__text" {
                        continue;
                    }

                    // Get the section's base address for calculating call site addresses
                    let section_addr = section.addr;

                    // Iterate relocations for this section
                    for reloc in section.iter_relocations(buffer, ctx) {
                        let Ok(reloc_info) = reloc else {
                            continue;
                        };

                        // Only process ARM64_RELOC_BRANCH26 (BL/B instructions)
                        if reloc_info.r_type() != ARM64_RELOC_BRANCH26 {
                            continue;
                        }

                        // Must be an external symbol reference
                        if !reloc_info.is_extern() {
                            continue;
                        }

                        // Get the symbol name being called
                        let sym_index = reloc_info.r_symbolnum();
                        let Some((target_sym_name, _)) = symbols.get(sym_index) else {
                            continue;
                        };

                        // Calculate the call site address
                        let call_site_addr = section_addr + reloc_info.r_address as u64;

                        // Find what function contains this call site
                        let Some((func_addr, func_name)) = symbol_index
                            .as_ref()
                            .and_then(|idx| idx.find_containing(call_site_addr))
                        else {
                            continue;
                        };
                        let func_name = func_name.to_string();

                        // Demangle the target symbol name
                        let target_demangled = {
                            let stripped =
                                target_sym_name.strip_prefix("_").unwrap_or(target_sym_name);
                            format!("{:#}", demangle(stripped))
                        };

                        // Look up file/line/column from DWARF at call site
                        let (file, line, column) = line_lookup
                            .as_ref()
                            .and_then(|lt| lt.lookup(call_site_addr))
                            .unwrap_or((None, None, None));

                        // If call site points to library code, find the last crate source
                        // line between function start and call site for precise line numbers
                        let (file, line, column) = if file
                            .as_ref()
                            .is_some_and(|f| is_dependency_path(f))
                        {
                            // Try to find precise line in crate source
                            if let Some(crate_path) = crate_src_path
                                && let Some(lt) = line_lookup.as_ref()
                                && let Some((crate_file, crate_line, crate_col)) = lt
                                    .get_crate_line_in_range(func_addr, call_site_addr, crate_path)
                            {
                                (Some(crate_file), Some(crate_line), crate_col)
                            } else {
                                // Fall back to function start address
                                line_lookup
                                    .as_ref()
                                    .and_then(|lt| lt.lookup(func_addr))
                                    .unwrap_or((None, None, None))
                            }
                        } else {
                            (file, line, column)
                        };

                        // Record the call: target_symbol -> caller
                        edges.entry(target_demangled).or_default().push(CallerInfo {
                            caller_name: Cow::Owned(func_name),
                            caller_start_address: func_addr,
                            caller_file: file.clone(),
                            call_site_addr,
                            file,
                            line,
                            column,
                        });
                    }
                }
            }
        }

        Ok(Self { edges })
    }

    /// Merge another LibraryCallGraph into this one.
    pub fn merge(&mut self, other: Self) {
        for (target, callers) in other.edges {
            self.edges.entry(target).or_default().extend(callers);
        }
    }

    /// Get all callers of a symbol by name (demangled).
    pub fn get_callers(&self, symbol_name: &str) -> Vec<CallerInfo<'static>> {
        self.edges.get(symbol_name).cloned().unwrap_or_default()
    }

    /// Get all callers of symbols matching a pattern.
    pub fn get_callers_matching(&self, pattern: &Regex) -> Vec<(&str, &[CallerInfo<'static>])> {
        self.edges
            .iter()
            .filter(|(name, _)| pattern.is_match(name))
            .map(|(name, callers)| (name.as_str(), callers.as_slice()))
            .collect()
    }

    /// Get all target symbol names in the call graph.
    pub fn target_symbols(&self) -> impl Iterator<Item = &str> {
        self.edges.keys().map(|s| s.as_str())
    }

    /// Check if empty.
    pub fn is_empty(&self) -> bool {
        self.edges.is_empty()
    }

    /// Create an empty library call graph.
    pub fn empty() -> Self {
        Self {
            edges: HashMap::new(),
        }
    }
}

/// Process a single instruction and extract call information (basic version without debug info).
/// Returns (call_target, CallerInfo) if this is a bl/b instruction, None otherwise.
fn process_instruction_basic<'a>(
    symbol_index: Option<&'a SymbolIndex>,
    instruction: &Insn,
) -> Option<(u64, CallerInfo<'a>)> {
    // Match both BL (branch with link) and B (branch) for tail call detection
    let mnemonic = instruction.mnemonic();
    if mnemonic != Some("bl") && mnemonic != Some("b") {
        return None;
    }

    let operand = instruction.op_str()?;
    let addr_str = operand.trim_start_matches("#0x");
    let call_target = u64::from_str_radix(addr_str, 16).ok()?;
    let (func_addr, func_name) =
        symbol_index.and_then(|idx| idx.find_containing(instruction.address()))?;

    Some((
        call_target,
        CallerInfo {
            caller_name: Cow::Borrowed(func_name),
            caller_start_address: func_addr,
            caller_file: None,
            call_site_addr: instruction.address(),
            file: None,
            line: None,
            column: None,
        },
    ))
}

/// Process instruction data using pre-built line tables for fast O(log n) lookups.
/// Falls back to symbol table lookup if DWARF doesn't contain the function.
/// DWARF names use Cow::Owned, symbol fallback uses Cow::Borrowed from SymbolIndex.
fn process_instruction_data_with_crate_table<'a>(
    data: &InsnData,
    function_index: &FunctionIndex,
    crate_src_path: Option<&str>,
    full_line_table: &FullLineTable,
    crate_line_table: Option<&CrateLineTable>,
    symbol_index: Option<&'a SymbolIndex>,
) -> Option<(u64, CallerInfo<'a>)> {
    let call_target = data.call_target?;

    // Find the function containing this call - try DWARF first, fall back to symbol table
    // Uses O(log n) binary search instead of O(n) linear search
    if let Some(func) = function_index.find_containing(data.address) {
        // Found in DWARF - use full debug info
        // Get source location using O(log n) binary search on pre-built table
        let func_file = function_index.get_file(func).map(|s| s.to_string());
        let func_line = function_index.get_line(func);
        // Clone once for caller_file, then move func_file into match
        let caller_file = func_file.clone();
        let (file, mut line, mut column) = match (func_file, func_line) {
            (Some(f), Some(l)) => {
                // Fast path: use DWARF function info directly
                (Some(f), Some(l), None)
            }
            (func_file, func_line) => {
                // Use pre-built full line table for O(log n) lookup
                let (line_file, line_line, line_column) =
                    full_line_table.get_source_location(func.start_address);
                (
                    func_file.or(line_file),
                    func_line.or(line_line),
                    line_column,
                )
            }
        };

        // For functions in the crate source, find actual call line using pre-built table
        let file_in_crate = file.as_ref().is_some_and(|f| {
            crate_src_path.is_some_and(|crate_path| matches_crate_pattern(f, crate_path))
        });
        if file_in_crate {
            // Use pre-built crate line table for O(log n) lookup
            if let Some(table) = crate_line_table {
                let (crate_line, crate_column) = table.get_line(func.start_address, data.address);
                if crate_line.is_some() {
                    // If the crate line table only found the function-start line,
                    // try the full line table as a fallback. When stdlib code is
                    // inlined (e.g., unwrap()), the DWARF line entries at the call
                    // address point to stdlib source, so the crate line table only
                    // has the function definition entry. The full line table can
                    // find the nearest crate-source line by searching backward.
                    if crate_line == func_line {
                        if let Some(crate_path) = crate_src_path {
                            let (full_line, full_column) = full_line_table.get_nearest_crate_line(
                                data.address,
                                func.start_address,
                                func.end_address,
                                func_line,
                                crate_path,
                            );
                            if full_line.is_some() && full_line != func_line {
                                line = full_line;
                                column = full_column;
                            } else {
                                line = crate_line;
                                column = crate_column;
                            }
                        } else {
                            line = crate_line;
                            column = crate_column;
                        }
                    } else {
                        line = crate_line;
                        column = crate_column;
                    }
                }
            }
        }

        // Get function name - only do expensive inlined lookup for crate source functions
        // For non-crate functions, use the containing function's name (fast path)
        let func_name = function_index.get_name(func);
        let display_name: Cow<'a, str> = if file_in_crate {
            // Crate function: get the most specific name (checks inlined functions)
            Cow::Owned(
                function_index
                    .find_function_name(data.address)
                    .map(|s| {
                        let stripped = s.strip_prefix('_').unwrap_or(s);
                        format!("{:#}", demangle(stripped))
                    })
                    .unwrap_or_else(|| func_name.to_string()),
            )
        } else {
            // Non-crate function: use containing function name directly (skip inlined search)
            Cow::Owned(func_name.to_string())
        };

        // Note: We intentionally use the inlined function's name but keep the
        // containing function's address range (start/end) for call graph building.
        // The caller.file/line fields are the function *definition* location,
        // while CallerInfo.file/line/column below are the actual *call site*.
        Some((
            call_target,
            CallerInfo {
                caller_name: display_name,
                caller_start_address: func.start_address,
                caller_file,
                call_site_addr: data.address,
                file,
                line,
                column,
            },
        ))
    } else if let Some((func_addr, func_name)) =
        symbol_index.and_then(|idx| idx.find_containing(data.address))
    {
        // Fallback: found in symbol table but not in DWARF (e.g., expect_failed, unwrap_failed)
        // Don't use line table for source location - addresses outside DWARF functions
        // would incorrectly get source info from adjacent functions.
        // These are typically stdlib internals that we don't need source info for anyway.
        Some((
            call_target,
            CallerInfo {
                caller_name: Cow::Borrowed(func_name), // No allocation - borrows from SymbolIndex
                caller_start_address: func_addr,
                caller_file: None,
                call_site_addr: data.address,
                file: None,
                line: None,
                column: None,
            },
        ))
    } else {
        // Function not found in DWARF or symbol table - skip this edge
        None
    }
}

// TODO Note that the address passed in is an n_value or Symbol table offset,
// which is not necessarily the same as the address of the symbol in memory.
// How can we fix that?
// TODO using [cfg] have implementations for other architectures
pub(crate) fn find_callers(
    macho: &MachO,
    buffer: &[u8],
    target_addr: u64,
) -> Result<Vec<CallerInfo<'static>>, Box<dyn std::error::Error>> {
    let mut callers = Vec::new();

    let Some((text_addr, text_data)) = get_text_section(macho, buffer) else {
        return Ok(callers);
    };

    let cs = Capstone::new()
        .arm64()
        .mode(arch::arm64::ArchMode::Arm)
        .build()?;

    let Ok(instructions) = cs.disasm_all(text_data, text_addr) else {
        return Ok(callers);
    };

    // Precompute symbol index once for efficient lookups
    let symbol_index = SymbolIndex::new(macho);

    for instruction in instructions.iter() {
        // Match both BL (branch with link) and B (branch) for tail call detection
        let mnemonic = instruction.mnemonic();
        if (mnemonic == Some("bl") || mnemonic == Some("b"))
            && let Some(operand) = instruction.op_str()
        {
            let addr_str = operand.trim_start_matches("#0x");
            if let Ok(call_target) = u64::from_str_radix(addr_str, 16)
                && call_target == target_addr
                && let Some((func_addr, func_name)) = symbol_index
                    .as_ref()
                    .and_then(|idx| idx.find_containing(instruction.address()))
            {
                callers.push(CallerInfo {
                    caller_name: Cow::Owned(func_name.to_string()),
                    caller_start_address: func_addr,
                    caller_file: None,
                    call_site_addr: instruction.address(),
                    file: None,
                    line: None,
                    column: None,
                });
            }
        }
    }

    Ok(callers)
}

/// Load DWARF sections from MachO binary
fn load_dwarf_sections<'a>(
    macho: &'a MachO,
    buffer: &'a [u8],
) -> Result<Dwarf<DwarfReader<'a>>, gimli::Error> {
    let endian = if macho.little_endian {
        RunTimeEndian::Little
    } else {
        RunTimeEndian::Big
    };

    // Helper to find a DWARF section in the MachO
    let find_section = |name: &str| -> Option<&'a [u8]> {
        for segment in macho.segments.iter() {
            if let Ok(sections) = segment.sections() {
                for (section, _) in sections {
                    // MachO DWARF sections are like "__debug_info" in the "__DWARF" segment
                    if let Ok(sect_name) = section.name() {
                        // Convert gimli section name to MachO format
                        // e.g., ".debug_info" -> "__debug_info"
                        let macho_name = format!("__{}", &name[1..]);
                        if sect_name == macho_name {
                            let start = section.offset as usize;
                            let end = start + section.size as usize;
                            return Some(&buffer[start..end]);
                        }
                    }
                }
            }
        }
        None
    };

    // Load each DWARF section
    let load_section = |id: SectionId| -> Result<DwarfReader<'a>, gimli::Error> {
        let data = find_section(id.name()).unwrap_or(&[]);
        Ok(EndianSlice::new(data, endian))
    };

    Dwarf::load(&load_section)
}

/// Intermediate struct for parsing - uses owned strings before interning
struct ParsedFunctionInfo {
    name: String,
    start_address: u64,
    end_address: u64,
    file: Option<String>,
    line: Option<u32>,
}

/// Extract all functions from DWARF debug info.
/// Returns functions, inlined functions, and the shared string tables.
pub fn get_functions_from_dwarf<'a>(
    macho: &'a MachO,
    buffer: &'a [u8],
) -> Result<DwarfFunctionResult, Box<dyn std::error::Error>> {
    let dwarf = load_dwarf_sections(macho, buffer)?;

    // Collect all unit headers first (fast)
    let mut headers = Vec::new();
    let mut units_iter = dwarf.units();
    while let Some(header) = units_iter.next()? {
        headers.push(header);
    }

    // Process compilation units in parallel - collect with owned strings
    let results: Vec<_> = headers
        .into_par_iter()
        .filter_map(|header| {
            let unit = dwarf.unit(header).ok()?;
            let mut funcs = Vec::new();
            let mut inl = Vec::new();

            let mut entries = unit.entries();
            while let Some((_, entry)) = entries.next_dfs().ok()? {
                match entry.tag() {
                    gimli::DW_TAG_subprogram => {
                        if let Ok(Some(func)) = parse_function_die(&dwarf, &unit, entry) {
                            funcs.push(func);
                        }
                    }
                    gimli::DW_TAG_inlined_subroutine => {
                        if let Ok(Some(func)) = parse_inlined_subroutine(&dwarf, &unit, entry) {
                            inl.push(func);
                        }
                    }
                    _ => {}
                }
            }
            Some((funcs, inl))
        })
        .collect();

    // Combine results and intern strings
    let mut strings = StringTables::new();
    let mut functions = Vec::new();
    let mut inlined = Vec::new();

    for (funcs, inl) in results {
        for parsed in funcs {
            functions.push(FunctionInfo {
                start_address: parsed.start_address,
                end_address: parsed.end_address,
                name_idx: strings.intern_name(parsed.name),
                file_idx: strings.intern_file(parsed.file),
                line: parsed.line.unwrap_or(0),
            });
        }
        for parsed in inl {
            inlined.push(FunctionInfo {
                start_address: parsed.start_address,
                end_address: parsed.end_address,
                name_idx: strings.intern_name(parsed.name),
                file_idx: strings.intern_file(parsed.file),
                line: parsed.line.unwrap_or(0),
            });
        }
    }

    Ok((functions, inlined, strings))
}

/// Parse a DW_TAG_subprogram DIE into ParsedFunctionInfo
fn parse_function_die<R: Reader>(
    dwarf: &Dwarf<R>,
    unit: &Unit<R>,
    entry: &DebuggingInformationEntry<R>,
) -> Result<Option<ParsedFunctionInfo>, gimli::Error> {
    let mut name: Option<String> = None;
    let mut has_linkage_name = false;
    let mut low_pc: Option<u64> = None;
    let mut high_pc: Option<u64> = None;
    let mut high_pc_is_offset = false;
    let mut file: Option<String> = None;
    let mut line: Option<u32> = None;
    let mut specification: Option<gimli::UnitOffset<R::Offset>> = None;

    let mut attrs = entry.attrs();
    while let Some(attr) = attrs.next()? {
        match attr.name() {
            gimli::DW_AT_name => {
                // Only use DW_AT_name as fallback if no linkage name was found
                if !has_linkage_name {
                    if let Ok(s) = dwarf.attr_string(unit, attr.value()) {
                        name = Some(s.to_string_lossy()?.into_owned());
                    }
                }
            }
            gimli::DW_AT_linkage_name | gimli::DW_AT_MIPS_linkage_name => {
                // Prefer linkage name — contains full qualified path after demangling
                if let Ok(s) = dwarf.attr_string(unit, attr.value()) {
                    let mangled = s.to_string_lossy()?.into_owned();
                    let stripped = mangled.strip_prefix('_').unwrap_or(&mangled);
                    name = Some(format!("{:#}", demangle(stripped)));
                    has_linkage_name = true;
                }
            }
            gimli::DW_AT_low_pc => {
                if let AttributeValue::Addr(addr) = attr.value() {
                    low_pc = Some(addr);
                }
            }
            gimli::DW_AT_high_pc => match attr.value() {
                AttributeValue::Addr(addr) => {
                    high_pc = Some(addr);
                }
                AttributeValue::Udata(offset) => {
                    high_pc = Some(offset);
                    high_pc_is_offset = true;
                }
                _ => {}
            },
            gimli::DW_AT_decl_file => {
                if let AttributeValue::FileIndex(idx) = attr.value() {
                    file = resolve_decl_file(dwarf, unit, idx)?;
                }
            }
            gimli::DW_AT_decl_line => {
                if let AttributeValue::Udata(l) = attr.value() {
                    line = Some(l as u32);
                }
            }
            gimli::DW_AT_specification => {
                // Reference to the declaration DIE that has name/file/line
                if let AttributeValue::UnitRef(offset) = attr.value() {
                    specification = Some(offset);
                }
            }
            _ => {}
        }
    }

    // If we have a specification reference but missing name/file/line, resolve from it
    if let Some(spec_offset) = specification {
        if name.is_none() || file.is_none() || line.is_none() {
            let (spec_name, spec_file, spec_line) =
                resolve_specification(dwarf, unit, spec_offset)?;
            if name.is_none() {
                name = spec_name;
            }
            if file.is_none() {
                file = spec_file;
            }
            if line.is_none() {
                line = spec_line;
            }
        }
    }

    // Calculate actual high_pc if it was an offset
    let high_pc = match (low_pc, high_pc, high_pc_is_offset) {
        (Some(low), Some(high), true) => Some(low + high),
        (_, high, false) => high,
        _ => None,
    };

    match (name, low_pc, high_pc) {
        (Some(name), Some(low_pc), Some(high_pc)) => Ok(Some(ParsedFunctionInfo {
            name,
            start_address: low_pc,
            end_address: high_pc,
            file,
            line,
        })),
        _ => Ok(None),
    }
}

/// Parse a DW_TAG_inlined_subroutine DIE into ParsedFunctionInfo.
/// Inlined subroutines use DW_AT_abstract_origin to reference the original function.
/// Handles both DW_AT_low_pc/DW_AT_high_pc and DW_AT_ranges (DWARF 5).
fn parse_inlined_subroutine<R: Reader<Offset = usize>>(
    dwarf: &Dwarf<R>,
    unit: &Unit<R>,
    entry: &DebuggingInformationEntry<R>,
) -> Result<Option<ParsedFunctionInfo>, gimli::Error> {
    let mut abstract_origin: Option<gimli::UnitOffset<usize>> = None;
    let mut low_pc: Option<u64> = None;
    let mut high_pc: Option<u64> = None;
    let mut high_pc_is_offset = false;
    let mut ranges_attr: Option<AttributeValue<R>> = None;

    let mut attrs = entry.attrs();
    while let Some(attr) = attrs.next()? {
        match attr.name() {
            gimli::DW_AT_abstract_origin => {
                if let AttributeValue::UnitRef(offset) = attr.value() {
                    abstract_origin = Some(offset);
                }
            }
            gimli::DW_AT_low_pc => {
                if let AttributeValue::Addr(addr) = attr.value() {
                    low_pc = Some(addr);
                }
            }
            gimli::DW_AT_high_pc => match attr.value() {
                AttributeValue::Addr(addr) => {
                    high_pc = Some(addr);
                }
                AttributeValue::Udata(offset) => {
                    high_pc = Some(offset);
                    high_pc_is_offset = true;
                }
                _ => {}
            },
            gimli::DW_AT_ranges => {
                // DWARF 5: inlined subroutines can use DW_AT_ranges for non-contiguous ranges
                ranges_attr = Some(attr.value());
            }
            _ => {}
        }
    }

    // Calculate actual high_pc if it was an offset
    let high_pc = match (low_pc, high_pc, high_pc_is_offset) {
        (Some(low), Some(high), true) => Some(low + high),
        (_, high, false) => high,
        _ => None,
    };

    // If we have ranges instead of low_pc/high_pc, use the first range
    // (FunctionInfo only stores a single range; multi-range support would require Vec)
    let (final_low_pc, final_high_pc) = if low_pc.is_some() && high_pc.is_some() {
        (low_pc, high_pc)
    } else if let Some(ranges_value) = ranges_attr {
        // Try to get the first range from DW_AT_ranges using gimli's attr_ranges helper
        if let Ok(Some(mut ranges)) = dwarf.attr_ranges(unit, ranges_value) {
            if let Ok(Some(range)) = ranges.next() {
                (Some(range.begin), Some(range.end))
            } else {
                (None, None)
            }
        } else {
            (None, None)
        }
    } else {
        (None, None)
    };

    // Resolve the function name from abstract_origin
    let name = if let Some(offset) = abstract_origin {
        resolve_abstract_origin_name(dwarf, unit, offset)?
    } else {
        None
    };

    match (name, final_low_pc, final_high_pc) {
        (Some(name), Some(low_pc), Some(high_pc)) => Ok(Some(ParsedFunctionInfo {
            name,
            start_address: low_pc,
            end_address: high_pc,
            file: None,
            line: None,
        })),
        _ => Ok(None),
    }
}

/// Resolve the function name from an abstract_origin reference.
fn resolve_abstract_origin_name<R: Reader>(
    dwarf: &Dwarf<R>,
    unit: &Unit<R>,
    offset: gimli::UnitOffset<R::Offset>,
) -> Result<Option<String>, gimli::Error> {
    let entry = unit.entry(offset)?;
    let mut name: Option<String> = None;

    let mut attrs = entry.attrs();
    while let Some(attr) = attrs.next()? {
        match attr.name() {
            gimli::DW_AT_linkage_name | gimli::DW_AT_MIPS_linkage_name => {
                // Prefer linkage name — contains full qualified path after demangling
                if let Ok(s) = dwarf.attr_string(unit, attr.value()) {
                    let mangled = s.to_string_lossy()?.into_owned();
                    let stripped = mangled.strip_prefix('_').unwrap_or(&mangled);
                    name = Some(format!("{:#}", demangle(stripped)));
                }
            }
            gimli::DW_AT_name => {
                if name.is_none() {
                    if let Ok(s) = dwarf.attr_string(unit, attr.value()) {
                        name = Some(s.to_string_lossy()?.into_owned());
                    }
                }
            }
            _ => {}
        }
    }

    Ok(name)
}

/// Resolve file path from DW_AT_decl_file attribute value.
/// Handles cases where directory may be absent or empty (basename-only entries).
fn resolve_decl_file<R: Reader>(
    dwarf: &Dwarf<R>,
    unit: &Unit<R>,
    file_idx: u64,
) -> Result<Option<String>, gimli::Error> {
    let Some(line_program) = &unit.line_program else {
        return Ok(None);
    };
    let Some(file_entry) = line_program.header().file(file_idx) else {
        return Ok(None);
    };
    let file_str = dwarf.attr_string(unit, file_entry.path_name())?;
    let file_name = file_str.to_string_lossy()?.into_owned();

    if let Some(dir) = file_entry.directory(line_program.header()) {
        let dir_str = dwarf.attr_string(unit, dir.clone())?;
        let dir_name = dir_str.to_string_lossy()?;
        if !dir_name.is_empty() {
            return Ok(Some(format!("{dir_name}/{file_name}")));
        }
    }

    Ok(Some(file_name))
}

/// Resolve name, file, and line from a DW_AT_specification reference.
/// Resolved specification data: (name, file, line)
type SpecificationResult = (Option<String>, Option<String>, Option<u32>);

/// Used when a function definition references a separate declaration.
fn resolve_specification<R: Reader>(
    dwarf: &Dwarf<R>,
    unit: &Unit<R>,
    offset: gimli::UnitOffset<R::Offset>,
) -> Result<SpecificationResult, gimli::Error> {
    let entry = unit.entry(offset)?;
    let mut name: Option<String> = None;
    let mut file: Option<String> = None;
    let mut line: Option<u32> = None;

    let mut attrs = entry.attrs();
    while let Some(attr) = attrs.next()? {
        match attr.name() {
            gimli::DW_AT_linkage_name | gimli::DW_AT_MIPS_linkage_name => {
                // Prefer linkage name — contains full qualified path after demangling
                if let Ok(s) = dwarf.attr_string(unit, attr.value()) {
                    let mangled = s.to_string_lossy()?.into_owned();
                    let stripped = mangled.strip_prefix('_').unwrap_or(&mangled);
                    name = Some(format!("{:#}", demangle(stripped)));
                }
            }
            gimli::DW_AT_name => {
                if name.is_none() {
                    if let Ok(s) = dwarf.attr_string(unit, attr.value()) {
                        name = Some(s.to_string_lossy()?.into_owned());
                    }
                }
            }
            gimli::DW_AT_decl_file => {
                if let AttributeValue::FileIndex(idx) = attr.value() {
                    file = resolve_decl_file(dwarf, unit, idx)?;
                }
            }
            gimli::DW_AT_decl_line => {
                if let AttributeValue::Udata(l) = attr.value() {
                    line = Some(l as u32);
                }
            }
            _ => {}
        }
    }

    Ok((name, file, line))
}

/// Find all functions that call a target address, with source info
///
/// # Arguments
/// * `binary_macho` - Parsed MachO from the executable binary (contains __text section)
/// * `binary_buffer` - Raw bytes of the executable binary
/// * `debug_macho` - Parsed MachO containing DWARF info (can be same as binary_macho, or from dSYM)
/// * `debug_buffer` - Raw bytes containing DWARF info (can be same as binary_buffer, or from dSYM)
/// * `target_addr` - Address of the function to find callers for
/// * `crate_src_path` - Optional crate source path for precise line numbers in user code
pub fn find_callers_with_debug_info(
    binary_macho: &MachO,
    binary_buffer: &[u8],
    debug_macho: &MachO,
    debug_buffer: &[u8],
    target_addr: u64,
    crate_src_path: Option<&str>,
) -> Result<Vec<CallerInfo<'static>>, Box<dyn std::error::Error>> {
    // Get function info and DWARF from debug info (dSYM or embedded)
    let (functions, inlined, strings) = get_functions_from_dwarf(debug_macho, debug_buffer)?;
    // Build function index for O(log n) lookups
    let function_index = FunctionIndex::new_with_inlined(functions, inlined, strings);
    let dwarf = load_dwarf_sections(debug_macho, debug_buffer)?;
    // Build line table for consistent source location lookups (first entry semantics)
    let full_line_table = FullLineTable::build(&dwarf)?;
    let mut callers = Vec::new();

    // Get __text section from the binary (not dSYM)
    let Some((text_addr, text_data)) = get_text_section(binary_macho, binary_buffer) else {
        return Ok(callers);
    };

    // Use capstone for ARM64 disassembly
    let cs = Capstone::new()
        .arm64()
        .mode(arch::arm64::ArchMode::Arm)
        .build()?;

    let instructions = cs.disasm_all(text_data, text_addr)?;

    // Precompute symbol index once for efficient fallback lookups
    let symbol_index = SymbolIndex::new(binary_macho);

    for instruction in instructions.iter() {
        // Look for BL (branch with link) and B (branch) instructions
        // B is used for tail calls where the compiler optimizes `call; ret` into a single jump
        let mnemonic = instruction.mnemonic();
        if (mnemonic == Some("bl") || mnemonic == Some("b"))
            && let Some(operand) = instruction.op_str()
        {
            let addr_str = operand.trim_start_matches("#0x");
            if let Ok(call_target) = u64::from_str_radix(addr_str, 16)
                && call_target == target_addr
            {
                // Find the function containing this call - try DWARF first, fall back to symbol table
                // Uses O(log n) binary search instead of O(n) linear search
                if let Some(func) = function_index.find_containing(instruction.address()) {
                    // Found in DWARF - use full debug info with first-entry semantics
                    let (line_file, line_line, line_column) =
                        full_line_table.get_source_location(func.start_address);

                    // Prefer function's declaration file/line if available, then function start's line info
                    let decl_file = function_index.get_file(func).map(|s| s.to_string());
                    let decl_line = function_index.get_line(func);
                    let file = decl_file.clone().or(line_file);
                    let mut line = decl_line.or(line_line);
                    let mut column = line_column;

                    // For functions in the crate source, find the actual line where the call originates
                    if let (Some(f), Some(crate_path)) = (&file, crate_src_path)
                        && f.contains(crate_path)
                        && let Ok(Some((crate_line, crate_column))) = get_crate_line_at_address(
                            &dwarf,
                            func.start_address,
                            instruction.address(),
                            crate_path,
                        )
                    {
                        line = Some(crate_line);
                        column = crate_column;
                    }

                    // Get the most specific function name (checks inlined functions first)
                    // Demangle if it's a mangled Rust name
                    let func_name = function_index.get_name(func);
                    let display_name = function_index
                        .find_function_name(instruction.address())
                        .map(|s| {
                            let stripped = s.strip_prefix('_').unwrap_or(s);
                            format!("{:#}", demangle(stripped))
                        })
                        .unwrap_or_else(|| func_name.to_string());

                    // Note: See comment in process_instruction_data_with_crate_table
                    // for why we use inlined name but containing function's address range
                    callers.push(CallerInfo {
                        caller_name: Cow::Owned(display_name),
                        caller_start_address: func.start_address,
                        caller_file: decl_file,
                        call_site_addr: instruction.address(),
                        file,
                        line,
                        column,
                    });
                } else if let Some((func_addr, func_name)) = symbol_index
                    .as_ref()
                    .and_then(|idx| idx.find_containing(instruction.address()))
                {
                    // Fallback: found in symbol table but not in DWARF (e.g., expect_failed, unwrap_failed)
                    let (file, line, column) = full_line_table.get_source_location(func_addr);

                    callers.push(CallerInfo {
                        caller_name: Cow::Owned(func_name.to_string()),
                        caller_start_address: func_addr,
                        caller_file: None,
                        call_site_addr: instruction.address(),
                        file,
                        line,
                        column,
                    });
                }
            }
        }
    }

    Ok(callers)
}

/// Find the user code line and column closest to a specific address within a function.
/// This finds the last line entry in user code before the given call site address.
fn get_crate_line_at_address<R: Reader>(
    dwarf: &Dwarf<R>,
    func_start: u64,
    call_site_addr: u64,
    crate_src_path: &str,
) -> Result<Option<(u32, Option<u32>)>, gimli::Error> {
    let mut units = dwarf.units();
    let mut best_line: Option<u32> = None;
    let mut best_column: Option<u32> = None;
    let mut best_addr: u64 = 0;

    while let Some(header) = units.next()? {
        let unit = dwarf.unit(header)?;

        if let Some(program) = &unit.line_program {
            let mut rows = program.clone().rows();

            while let Some((header, row)) = rows.next_row()? {
                let addr = row.address();

                // Look for entries between function start and call site
                if addr >= func_start
                    && addr <= call_site_addr
                    && let Some(file_entry) = row.file(header)
                {
                    let file_name = dwarf
                        .attr_string(&unit, file_entry.path_name())?
                        .to_string_lossy()?
                        .into_owned();

                    let full_path = if let Some(dir) = file_entry.directory(header) {
                        let dir_str = dwarf
                            .attr_string(&unit, dir)?
                            .to_string_lossy()?
                            .into_owned();
                        if dir_str.is_empty() {
                            file_name
                        } else {
                            format!("{}/{}", dir_str, file_name)
                        }
                    } else {
                        file_name
                    };

                    // Check if this line is in the crate source
                    if matches_crate_pattern(&full_path, crate_src_path)
                        && let Some(line) = row.line()
                        && addr >= best_addr
                    {
                        best_addr = addr;
                        best_line = Some(line.get() as u32);
                        best_column = match row.column() {
                            ColumnType::LeftEdge => None,
                            ColumnType::Column(c) => Some(c.get() as u32),
                        };
                    }
                }
            }
        }
    }

    Ok(best_line.map(|l| (l, best_column)))
}

pub fn find_dsym(binary_path: &Path) -> Option<PathBuf> {
    // dSYM is typically at: /path/to/binary.dSYM/Contents/Resources/DWARF/binary
    let dsym_bundle = binary_path.with_extension("dSYM");

    if dsym_bundle.exists() {
        let binary_name = binary_path.file_name()?;
        let dwarf_path = dsym_bundle
            .join("Contents")
            .join("Resources")
            .join("DWARF")
            .join(binary_name);

        if dwarf_path.exists() {
            return Some(dwarf_path);
        }
    }
    None
}

/// Check if the binary has any DWARF debug sections
pub fn has_dwarf_sections(macho: &MachO) -> bool {
    for segment in macho.segments.iter() {
        if let Ok(sects) = segment.sections() {
            for (section, _) in sects {
                if let Ok(name) = section.name()
                    && name.starts_with("__debug_")
                {
                    return true;
                }
            }
        }
    }
    false
}

/// Extract object file paths from the debug map (OSO stab entries)
fn get_oso_paths(macho: &MachO) -> Vec<PathBuf> {
    let mut paths = Vec::new();

    if let Some(symbols) = &macho.symbols {
        for (name, nlist) in symbols.iter().flatten() {
            // N_OSO (0x66) indicates an object file reference
            if nlist.n_type == N_OSO && !name.is_empty() {
                paths.push(PathBuf::from(name));
            }
        }
    }

    // Deduplicate paths
    paths.sort();
    paths.dedup();
    paths
}

/// Build address translation map from object file symbols to final binary addresses
fn build_addr_translation_map(binary_macho: &MachO, obj_macho: &MachO) -> HashMap<u64, u64> {
    let mut addr_map = HashMap::new();

    // Get symbols from both binary and object file
    let Some(binary_symbols) = &binary_macho.symbols else {
        return addr_map;
    };
    let Some(obj_symbols) = &obj_macho.symbols else {
        return addr_map;
    };

    // Build a map of symbol name -> address in binary
    let mut binary_sym_addrs: HashMap<String, u64> = HashMap::new();
    for (name, nlist) in binary_symbols.iter().flatten() {
        if nlist.n_value > 0 && !name.is_empty() {
            binary_sym_addrs.insert(name.to_string(), nlist.n_value);
        }
    }

    // For each symbol in the object file, find its final address in the binary
    for (name, nlist) in obj_symbols.iter().flatten() {
        if nlist.n_value > 0
            && !name.is_empty()
            && let Some(&binary_addr) = binary_sym_addrs.get(name)
        {
            addr_map.insert(nlist.n_value, binary_addr);
        }
    }

    addr_map
}

/// Find callers with source info using the debug map
/// This searches all object files for DWARF info
pub fn find_callers_with_debug_map(
    binary_macho: &MachO,
    binary_buffer: &[u8],
    debug_map: &DebugMapInfo,
    target_addr: u64,
    _crate_src_path: Option<&str>,
) -> Result<Vec<CallerInfo<'static>>, Box<dyn std::error::Error>> {
    // First, get callers from the binary's text section
    let mut callers = find_callers(binary_macho, binary_buffer, target_addr)?;

    // Build a map of function name -> source info from all object files
    let mut func_source_map: HashMap<String, (Option<String>, Option<u32>)> = HashMap::new();

    for obj_info in &debug_map.object_files {
        // Parse the object file
        let Ok(Object::Mach(Mach::Binary(obj_macho))) = Object::parse(&obj_info.buffer) else {
            continue;
        };

        // Get functions from this object file
        // TODO: _inlined is currently unused in the debug-map fallback path.
        // Using inlined functions here would require mapping object file addresses
        // to binary addresses, which is complex. The main path (dSYM/embedded DWARF)
        // handles inlined functions correctly via FunctionIndex.find_function_name().
        let Ok((functions, _inlined, strings)) =
            get_functions_from_dwarf(&obj_macho, &obj_info.buffer)
        else {
            continue;
        };

        // Store source info by function name (both mangled and demangled)
        for func in functions {
            let file = strings.get_file(func.file_idx);
            if file.is_some() {
                let name = strings.get_name(func.name_idx);
                let line = if func.line == 0 {
                    None
                } else {
                    Some(func.line)
                };
                // Store by original name
                func_source_map.insert(name.to_string(), (file.map(|s| s.to_string()), line));

                // Also store by demangled name for matching
                let stripped = name.strip_prefix("_").unwrap_or(name);
                let demangled = format!("{:#}", demangle(stripped));
                if demangled != name {
                    func_source_map.insert(demangled, (file.map(|s| s.to_string()), line));
                }
            }
        }
    }

    // Enrich caller info with source locations from DWARF by matching function names
    for caller in &mut callers {
        // Try to find source info by function name
        // Note: caller_name is Cow<'static, str>, convert to string for lookup
        if let Some((file, line)) = func_source_map.get(caller.caller_name.as_ref()) {
            caller.caller_file = file.clone();
            caller.file = file.clone();
            caller.line = *line;
        }
    }

    Ok(callers)
}

/// Load debug map from the binary's symbol table
/// This reads OSO entries and loads DWARF from the referenced object files
fn load_debug_map(macho: &MachO, quiet: bool) -> Option<DebugMapInfo> {
    let oso_paths = get_oso_paths(macho);

    if oso_paths.is_empty() {
        return None;
    }

    let mut object_files = Vec::new();
    let mut loaded_count = 0;

    for path in oso_paths {
        // Skip if object file doesn't exist
        if !path.exists() {
            continue;
        }

        // Read the object file
        let Ok(buffer) = fs::read(&path) else {
            continue;
        };

        // Parse as MachO and check for DWARF
        let Ok(Object::Mach(Mach::Binary(obj_macho))) = Object::parse(&buffer) else {
            continue;
        };

        // Only include if it has debug info
        if !has_dwarf_sections(&obj_macho) {
            continue;
        }

        // Build address translation map
        let addr_map = build_addr_translation_map(macho, &obj_macho);

        object_files.push(ObjectFileInfo {
            path,
            buffer,
            addr_map,
        });
        loaded_count += 1;
    }

    if object_files.is_empty() {
        return None;
    }

    if !quiet {
        println!(
            "Using debug map: loaded {} object files with DWARF",
            loaded_count
        );
    }

    Some(DebugMapInfo { object_files })
}

/// Check if a dSYM bundle is stale (binary is newer than the dSYM)
fn is_dsym_stale(binary_path: &Path, dsym_path: &Path) -> bool {
    let binary_modified = match fs::metadata(binary_path).and_then(|m| m.modified()) {
        Ok(t) => t,
        Err(_) => return false, // Can't check, assume not stale
    };

    let dsym_modified = match fs::metadata(dsym_path).and_then(|m| m.modified()) {
        Ok(t) => t,
        Err(_) => return true, // Can't read dSYM metadata, regenerate
    };

    binary_modified > dsym_modified
}

// 1) No embedded debug info, no dSYM
// 2) No embedded debug info, dSYM
// 3) Embedded debug info, no dSYM
// 4) Embedded debug info, dSYM
pub fn load_debug_info(macho: &MachO, binary_path: &Path, quiet: bool) -> DebugInfo {
    // Look for dSYM symbol directory
    // Try both with and without extension since dsymutil behavior varies
    let file_name = binary_path.file_name().unwrap().to_str().unwrap();
    let file_stem = binary_path.file_stem().unwrap().to_str().unwrap();

    // Try .dSYM bundle with full filename first
    let dsym_base = binary_path.parent().unwrap_or(Path::new("."));
    let dsym_paths = [
        // Pattern: binary.dSYM/Contents/Resources/DWARF/binary
        dsym_base
            .join(format!("{}.dSYM", file_stem))
            .join("Contents/Resources/DWARF")
            .join(file_name),
        // Pattern: binary.dSYM/Contents/Resources/DWARF/binary (without extension)
        dsym_base
            .join(format!("{}.dSYM", file_stem))
            .join("Contents/Resources/DWARF")
            .join(file_stem),
        // Pattern: binary.ext.dSYM/Contents/Resources/DWARF/binary.ext
        binary_path
            .with_extension("dSYM")
            .join("Contents/Resources/DWARF")
            .join(file_name),
    ];

    for dsym_path in &dsym_paths {
        if dsym_path.exists() {
            // Check if dSYM is stale (binary is newer than dSYM)
            let dsym_stale = is_dsym_stale(binary_path, dsym_path);
            if dsym_stale {
                if !quiet {
                    println!("  dSYM is stale, will regenerate");
                }
            } else {
                if !quiet {
                    println!("  Using .dSYM bundle for debug info");
                }
                let debug_buffer = fs::read(dsym_path).unwrap();
                let dsym_info = DSymInfoBuilder {
                    debug_buffer,
                    debug_macho_builder: |buf: &Vec<u8>| Mach::parse(buf).unwrap(),
                }
                .build();
                return DebugInfo::DSym(Box::new(dsym_info));
            }
        }
    }

    if has_dwarf_sections(macho) {
        if !quiet {
            println!("  Using embedded DWARF debugging info");
        }
        return DebugInfo::Embedded;
    }

    // Try to auto-generate dSYM using dsymutil
    if let Some(dsym_info) = auto_generate_dsym(binary_path, quiet) {
        return DebugInfo::DSym(Box::new(dsym_info));
    }

    // Fall back to debug map (reading DWARF from object files)
    if let Some(debug_map) = load_debug_map(macho, quiet) {
        return DebugInfo::DebugMap(Box::new(debug_map));
    }

    if !quiet {
        println!("  No debug info found (no dSYM, embedded DWARF, or debug map)");
        println!(
            "Tip: Install dsymutil or run 'dsymutil {}' to generate debug symbols",
            binary_path.display()
        );
    }
    DebugInfo::None
}

/// Auto-generate dSYM by running dsymutil
fn auto_generate_dsym(binary_path: &Path, quiet: bool) -> Option<DSymInfo> {
    use std::process::Command;

    let dsym_path = binary_path.with_extension("dSYM");

    // Check if dsymutil is available
    let status = Command::new("dsymutil")
        .arg(binary_path)
        .arg("-o")
        .arg(&dsym_path)
        .status()
        .ok()?;

    if !status.success() {
        return None;
    }

    // Find the DWARF file inside the dSYM bundle
    let file_name = binary_path.file_name()?.to_str()?;
    let file_stem = binary_path.file_stem()?.to_str()?;

    let dwarf_paths = [
        dsym_path.join("Contents/Resources/DWARF").join(file_name),
        dsym_path.join("Contents/Resources/DWARF").join(file_stem),
    ];

    for dwarf_path in &dwarf_paths {
        if dwarf_path.exists() {
            if !quiet {
                println!("  Generated .dSYM bundle for debug info");
            }
            let debug_buffer = fs::read(dwarf_path).ok()?;
            let dsym_info = DSymInfoBuilder {
                debug_buffer,
                debug_macho_builder: |buf: &Vec<u8>| Mach::parse(buf).unwrap(),
            }
            .build();
            return Some(dsym_info);
        }
    }

    None
}

#[cfg(test)]
mod tests {
    use super::*;

    // Tests for matches_crate_pattern
    #[test]
    fn test_matches_crate_pattern_simple() {
        assert!(matches_crate_pattern("src/main.rs", "src/"));
        assert!(matches_crate_pattern("src/lib.rs", "src/"));
        assert!(matches_crate_pattern("src/module/mod.rs", "src/"));
    }

    #[test]
    fn test_matches_crate_pattern_no_match() {
        assert!(!matches_crate_pattern("tests/test.rs", "src/"));
        assert!(!matches_crate_pattern("examples/ex.rs", "src/"));
    }

    #[test]
    fn test_matches_crate_pattern_multi_pattern() {
        let pattern = "flowc/src/|flowr/src/";
        assert!(matches_crate_pattern("flowc/src/main.rs", pattern));
        assert!(matches_crate_pattern("flowr/src/lib.rs", pattern));
        assert!(!matches_crate_pattern("other/src/lib.rs", pattern));
    }

    #[test]
    fn test_matches_crate_pattern_workspace() {
        let pattern = "crate_a/src/|crate_b/src/";
        assert!(matches_crate_pattern("crate_a/src/lib.rs", pattern));
        assert!(matches_crate_pattern("crate_b/src/main.rs", pattern));
        assert!(!matches_crate_pattern("crate_c/src/lib.rs", pattern));
    }

    #[test]
    fn test_matches_crate_pattern_empty_pattern() {
        // Empty pattern should not match
        assert!(!matches_crate_pattern("src/main.rs", ""));
        // Pattern with empty segments should work
        assert!(matches_crate_pattern("src/main.rs", "|src/|"));
    }

    // Tests for ValidSourceFiles
    #[test]
    fn test_valid_source_files_needs_validation() {
        // Empty files means no validation needed
        let empty_valid = ValidSourceFiles::default();
        assert!(!empty_valid.needs_validation("src/"));

        // With files, "src/" pattern needs validation
        let mut files = std::collections::HashSet::new();
        files.insert("src/main.rs".to_string());
        let valid = ValidSourceFiles {
            files,
            project_root: None,
        };
        assert!(valid.needs_validation("src/"));
        // Workspace patterns don't need validation (specific enough)
        assert!(!valid.needs_validation("flowc/src/|flowr/src/"));
        assert!(!valid.needs_validation("my_crate/src/"));
    }

    #[test]
    fn test_valid_source_files_contains() {
        let mut files = std::collections::HashSet::new();
        files.insert("src/main.rs".to_string());
        files.insert("src/lib.rs".to_string());
        let valid = ValidSourceFiles {
            files,
            project_root: None,
        };

        assert!(valid.contains("src/main.rs"));
        assert!(valid.contains("src/lib.rs"));
        assert!(!valid.contains("src/other.rs"));
    }

    #[test]
    fn test_matches_crate_pattern_validated_with_allowlist() {
        let mut files = std::collections::HashSet::new();
        files.insert("src/main.rs".to_string());
        files.insert("src/module/mod.rs".to_string());
        let valid = ValidSourceFiles {
            files,
            project_root: Some(std::path::PathBuf::from("/project")),
        };

        // With validation, only files in the allowlist should match
        assert!(matches_crate_pattern_validated(
            "src/main.rs",
            "src/",
            Some(&valid)
        ));
        assert!(matches_crate_pattern_validated(
            "src/module/mod.rs",
            "src/",
            Some(&valid)
        ));
        // File not in allowlist should not match
        assert!(!matches_crate_pattern_validated(
            "src/other.rs",
            "src/",
            Some(&valid)
        ));
    }

    // Tests for decode_branch_target (ARM64)
    #[test]
    fn test_decode_branch_target_forward() {
        // BL instruction: offset = +4 (next instruction)
        // imm26 = 1, pc = 0x1000
        let insn = 0x94000001_u32; // BL +4
        let target = decode_branch_target(insn, 0x1000);
        assert_eq!(target, 0x1004);
    }

    #[test]
    fn test_decode_branch_target_backward() {
        // BL instruction with negative offset (high bit set in imm26)
        // This represents a backward branch
        let pc = 0x2000_u64;
        // imm26 = 0x3FFFFFF (-1 in 26-bit signed) => offset = -4
        let insn = 0x97FFFFFF_u32; // BL -4
        let target = decode_branch_target(insn, pc);
        assert_eq!(target, pc.wrapping_sub(4));
    }

    #[test]
    fn test_decode_branch_target_zero_offset() {
        // BL with offset 0 (branches to itself)
        let insn = 0x94000000_u32;
        let target = decode_branch_target(insn, 0x1000);
        assert_eq!(target, 0x1000);
    }

    // ========================================================================
    // Tests for dSYM detection and staleness
    // ========================================================================

    #[test]
    fn test_is_dsym_stale_binary_newer() {
        use std::fs;
        use std::thread;
        use std::time::Duration;

        let temp_dir = std::env::temp_dir().join("jonesy_test_dsym_stale");
        let _ = fs::create_dir_all(&temp_dir);

        let binary_path = temp_dir.join("test_binary");
        let dsym_path = temp_dir.join("test_binary.dSYM");

        // Create dSYM first (older)
        fs::write(&dsym_path, "fake dsym").unwrap();

        // Wait a bit to ensure different timestamps
        thread::sleep(Duration::from_millis(50));

        // Create binary second (newer)
        fs::write(&binary_path, "fake binary").unwrap();

        // Binary is newer than dSYM, so dSYM is stale
        assert!(
            is_dsym_stale(&binary_path, &dsym_path),
            "dSYM should be stale when binary is newer"
        );

        let _ = fs::remove_dir_all(&temp_dir);
    }

    #[test]
    fn test_is_dsym_stale_dsym_newer() {
        use std::fs;
        use std::thread;
        use std::time::Duration;

        let temp_dir = std::env::temp_dir().join("jonesy_test_dsym_fresh");
        let _ = fs::create_dir_all(&temp_dir);

        let binary_path = temp_dir.join("test_binary");
        let dsym_path = temp_dir.join("test_binary.dSYM");

        // Create binary first (older)
        fs::write(&binary_path, "fake binary").unwrap();

        // Wait a bit to ensure different timestamps
        thread::sleep(Duration::from_millis(50));

        // Create dSYM second (newer)
        fs::write(&dsym_path, "fake dsym").unwrap();

        // dSYM is newer than binary, so dSYM is not stale
        assert!(
            !is_dsym_stale(&binary_path, &dsym_path),
            "dSYM should not be stale when dSYM is newer"
        );

        let _ = fs::remove_dir_all(&temp_dir);
    }

    #[test]
    fn test_is_dsym_stale_binary_not_found() {
        use std::fs;

        let temp_dir = std::env::temp_dir().join("jonesy_test_dsym_no_binary");
        let _ = fs::create_dir_all(&temp_dir);

        let binary_path = temp_dir.join("nonexistent_binary");
        let dsym_path = temp_dir.join("test.dSYM");

        // Create dSYM but not binary
        fs::write(&dsym_path, "fake dsym").unwrap();

        // When binary doesn't exist, function returns false (can't check)
        assert!(
            !is_dsym_stale(&binary_path, &dsym_path),
            "Should return false when binary doesn't exist"
        );

        let _ = fs::remove_dir_all(&temp_dir);
    }

    #[test]
    fn test_is_dsym_stale_dsym_not_found() {
        use std::fs;

        let temp_dir = std::env::temp_dir().join("jonesy_test_dsym_no_dsym");
        let _ = fs::create_dir_all(&temp_dir);

        let binary_path = temp_dir.join("test_binary");
        let dsym_path = temp_dir.join("nonexistent.dSYM");

        // Create binary but not dSYM
        fs::write(&binary_path, "fake binary").unwrap();

        // When dSYM doesn't exist, function returns true (needs regeneration)
        assert!(
            is_dsym_stale(&binary_path, &dsym_path),
            "Should return true when dSYM doesn't exist"
        );

        let _ = fs::remove_dir_all(&temp_dir);
    }
}