ghostscope-dwarf 0.1.5

DWARF parser and symbolizer used by GhostScope to resolve variables and types at runtime.
Documentation
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
//! Main DWARF analyzer - unified entry point for all DWARF operations

use crate::{
    core::{
        mapping::ModuleMapping, CallerFrameRecovery, DebugInfoSource, ModuleAddress, Result,
        SectionType, SourceLocation,
    },
    loader::ExplicitDebugFile,
    objfile::LoadedObjfile,
    semantics::{CompactUnwindRow, CompactUnwindTable, PcContext, VisibleVariable},
};
use ghostscope_debuginfod::DebuginfodClient;
use object::{Object, ObjectSection};
use std::collections::{HashMap, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};

mod module_resolution;
mod plan_global;
mod plan_pc;
mod source_resolution;
mod type_lookup;

pub use module_resolution::ModuleDefaultPolicy;
pub use source_resolution::{SourceLineAddressSearch, SourceLineQuerySearch};
pub use type_lookup::TypeLookupAmbiguity;

#[cfg(test)]
use crate::{
    core::{AddressExpr, Availability, Provenance, VariableLocation},
    semantics::VariableReadPlan,
};

/// Events emitted during module loading process
#[derive(Debug, Clone)]
pub enum ModuleLoadingEvent {
    /// Module discovered during process scanning
    Discovered {
        module_path: String,
        current: usize,
        total: usize,
    },
    /// Module loading started
    LoadingStarted {
        module_path: String,
        current: usize,
        total: usize,
    },
    /// Module loading completed successfully
    LoadingCompleted {
        module_path: String,
        stats: ModuleLoadingStats,
        current: usize,
        total: usize,
    },
    /// Module loading failed
    LoadingFailed {
        module_path: String,
        error: String,
        current: usize,
        total: usize,
    },
}

/// Statistics for a loaded module
#[derive(Debug, Clone)]
pub struct ModuleLoadingStats {
    pub functions: usize,
    pub variables: usize,
    pub types: usize,
    pub debug_info_source: DebugInfoSource,
    pub load_time_ms: u64,
    pub parse_time_ms: u64,
    pub index_time_ms: u64,
    pub module_total_time_ms: u64,
}

/// Rich query result for a single address within a module.
#[derive(Debug, Clone)]
pub struct AddressQueryResult {
    pub module_path: PathBuf,
    pub address: u64,
    pub source_file: Option<String>,
    pub source_line: Option<u32>,
    pub source_column: Option<u32>,
    pub function_name: Option<String>,
    pub is_inline: Option<bool>,
    pub variables: Vec<VisibleVariable>,
    pub parameters: Vec<VisibleVariable>,
}

/// Runtime mapping metadata for a loaded module.
#[derive(Debug, Clone)]
pub struct LoadedModuleRuntimeInfo {
    pub module_path: PathBuf,
    pub loaded_address: Option<u64>,
    pub load_bias: Option<u64>,
    pub size: u64,
}

/// Rich query result for a function lookup across modules.
#[derive(Debug, Clone)]
pub struct FunctionQueryResult {
    pub function_name: String,
    pub addresses: Vec<AddressQueryResult>,
}

/// DWARF analyzer - unified entry point for all DWARF analysis
#[derive(Debug)]
pub struct DwarfAnalyzer {
    /// Process ID
    pid: u32,
    /// Module path -> module data mapping
    modules: HashMap<PathBuf, LoadedObjfile>,
    /// Cached PC semantic contexts for repeated symbol/source lookups.
    pc_context_cache: RwLock<PcContextCache>,
}

const PC_CONTEXT_CACHE_MAX_ENTRIES: usize = 8192;

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct PcContextCacheKey {
    module_path: PathBuf,
    address: u64,
}

#[derive(Debug)]
struct PcContextCache {
    entries: HashMap<PathBuf, HashMap<u64, PcContext>>,
    insertion_order: VecDeque<PcContextCacheKey>,
    len: usize,
    max_entries: usize,
}

impl Default for PcContextCache {
    fn default() -> Self {
        Self {
            entries: HashMap::new(),
            insertion_order: VecDeque::new(),
            len: 0,
            max_entries: PC_CONTEXT_CACHE_MAX_ENTRIES,
        }
    }
}

impl PcContextCache {
    fn get(&self, module_path: &Path, address: u64) -> Option<PcContext> {
        self.entries
            .get(module_path)
            .and_then(|entries| entries.get(&address))
            .cloned()
    }

    fn insert(&mut self, module_path: PathBuf, address: u64, context: PcContext) {
        if self.max_entries == 0 {
            return;
        }

        let key = PcContextCacheKey {
            module_path,
            address,
        };
        let module_entries = self.entries.entry(key.module_path.clone()).or_default();
        if module_entries.insert(address, context).is_none() {
            self.insertion_order.push_back(key.clone());
            self.len += 1;
        }

        while self.len > self.max_entries {
            let Some(expired) = self.insertion_order.pop_front() else {
                break;
            };
            if let Some(module_entries) = self.entries.get_mut(&expired.module_path) {
                if module_entries.remove(&expired.address).is_some() {
                    self.len -= 1;
                }
                if module_entries.is_empty() {
                    self.entries.remove(&expired.module_path);
                }
            }
        }
    }
}

impl DwarfAnalyzer {
    fn build_address_query_result(
        &self,
        module_address: &ModuleAddress,
    ) -> Result<AddressQueryResult> {
        self.build_address_query_result_with_source_hint(module_address, None)
    }

    fn build_address_query_result_with_source_hint(
        &self,
        module_address: &ModuleAddress,
        source_hint: Option<(&str, u32)>,
    ) -> Result<AddressQueryResult> {
        let mut variables = Vec::new();
        let mut parameters = Vec::new();

        for variable in self.visible_variables_at_address(module_address)? {
            if variable.is_parameter {
                parameters.push(variable);
            } else {
                variables.push(variable);
            }
        }

        let source_location = if let Some((file_path, line_number)) = source_hint {
            self.modules
                .get(&module_address.module_path)
                .and_then(|module_data| {
                    module_data.lookup_source_location_for_source_line(
                        module_address.address,
                        file_path,
                        line_number,
                    )
                })
        } else {
            self.lookup_source_location(module_address)
        };
        let function_name = self.find_function_name_by_module_address(module_address);
        let is_inline = self.is_inline_at(module_address);

        Ok(AddressQueryResult {
            module_path: module_address.module_path.clone(),
            address: module_address.address,
            source_file: source_location.as_ref().map(|sl| sl.file_path.clone()),
            source_line: source_location.as_ref().map(|sl| sl.line_number),
            source_column: source_location.as_ref().and_then(|sl| sl.column),
            function_name,
            is_inline,
            variables,
            parameters,
        })
    }

    fn query_module_addresses(
        &self,
        module_addresses: Vec<ModuleAddress>,
    ) -> Result<Vec<AddressQueryResult>> {
        module_addresses
            .iter()
            .map(|module_address| self.build_address_query_result(module_address))
            .collect()
    }

    fn query_module_addresses_for_source_line(
        &self,
        module_addresses: Vec<ModuleAddress>,
        file_path: &str,
        line_number: u32,
    ) -> Result<Vec<AddressQueryResult>> {
        module_addresses
            .iter()
            .map(|module_address| {
                self.build_address_query_result_with_source_hint(
                    module_address,
                    Some((file_path, line_number)),
                )
            })
            .collect()
    }

    fn query_module_addresses_best_effort(
        &self,
        module_addresses: Vec<ModuleAddress>,
        query_label: &str,
    ) -> Result<Vec<AddressQueryResult>> {
        let mut results = Vec::new();
        let mut first_error: Option<(ModuleAddress, String)> = None;

        for module_address in &module_addresses {
            match self.build_address_query_result(module_address) {
                Ok(result) => results.push(result),
                Err(error) => {
                    let error_string = error.to_string();
                    tracing::warn!(
                        "Skipping failed address query for {} at {}:0x{:x}: {}",
                        query_label,
                        module_address.module_display(),
                        module_address.address,
                        error_string
                    );

                    if first_error.is_none() {
                        first_error = Some((module_address.clone(), error_string));
                    }
                }
            }
        }

        if results.is_empty() {
            if let Some((module_address, error)) = first_error {
                return Err(anyhow::anyhow!(
                    "Failed to analyze any address for {} (first failure at {}:0x{:x}: {})",
                    query_label,
                    module_address.module_display(),
                    module_address.address,
                    error
                ));
            }
        }

        Ok(results)
    }

    fn query_module_addresses_for_source_line_best_effort(
        &self,
        module_addresses: Vec<ModuleAddress>,
        file_path: &str,
        line_number: u32,
        query_label: &str,
    ) -> Result<Vec<AddressQueryResult>> {
        let mut results = Vec::new();
        let mut first_error: Option<(ModuleAddress, String)> = None;

        for module_address in &module_addresses {
            match self.build_address_query_result_with_source_hint(
                module_address,
                Some((file_path, line_number)),
            ) {
                Ok(result) => results.push(result),
                Err(error) => {
                    let error_string = error.to_string();
                    tracing::warn!(
                        "Skipping failed address query for {} at {}:0x{:x}: {}",
                        query_label,
                        module_address.module_display(),
                        module_address.address,
                        error_string
                    );

                    if first_error.is_none() {
                        first_error = Some((module_address.clone(), error_string));
                    }
                }
            }
        }

        if results.is_empty() {
            if let Some((module_address, error)) = first_error {
                return Err(anyhow::anyhow!(
                    "Failed to analyze any address for {} (first failure at {}:0x{:x}: {})",
                    query_label,
                    module_address.module_display(),
                    module_address.address,
                    error
                ));
            }
        }

        Ok(results)
    }

    fn find_function_name_by_module_address(
        &self,
        module_address: &ModuleAddress,
    ) -> Option<String> {
        self.loaded_module_path_for(&module_address.module_path)
            .and_then(|module_path| self.modules.get(module_path))
            .and_then(|module_data| {
                module_data.find_function_name_by_address(module_address.address)
            })
    }

    fn sorted_module_paths(&self) -> Vec<&PathBuf> {
        let mut paths: Vec<&PathBuf> = self.modules.keys().collect();
        paths.sort();
        paths
    }

    pub(crate) fn loaded_module_path_for<P: AsRef<Path>>(
        &self,
        module_path: P,
    ) -> Option<&PathBuf> {
        let module_path = module_path.as_ref();
        if let Some((path, _)) = self.modules.get_key_value(module_path) {
            return Some(path);
        }

        self.sorted_module_paths()
            .into_iter()
            .find(|path| Self::module_paths_equivalent(path.as_path(), module_path))
    }

    /// Return the deterministic per-analyzer module id for a loaded module path.
    pub fn module_id_for_path<P: AsRef<Path>>(&self, module_path: P) -> Option<crate::ModuleId> {
        let module_path = self.loaded_module_path_for(module_path)?;
        self.sorted_module_paths()
            .into_iter()
            .position(|path| path.as_path() == module_path.as_path())
            .map(|index| crate::ModuleId(index as u32))
    }

    /// Resolve a semantic module id back to its loaded module path.
    pub fn module_path_for_id(&self, module: crate::ModuleId) -> Option<&Path> {
        self.sorted_module_paths()
            .get(module.0 as usize)
            .map(|path| path.as_path())
    }

    /// Create DWARF analyzer from PID (now uses parallel loading)
    pub async fn from_pid(pid: u32) -> Result<Self> {
        Self::from_pid_parallel(pid).await
    }

    /// Classify whether an address is inside an inlined subroutine instance
    /// Returns Some(true) if inline, Some(false) if a normal (non-inline) context,
    /// or None if the module/address cannot be resolved.
    pub fn is_inline_at(&self, module_address: &ModuleAddress) -> Option<bool> {
        if let Some(module_data) = self
            .loaded_module_path_for(&module_address.module_path)
            .and_then(|module_path| self.modules.get(module_path))
        {
            module_data.is_inline_at(module_address.address)
        } else {
            None
        }
    }

    /// Create DWARF analyzer from PID using parallel loading
    pub async fn from_pid_parallel(pid: u32) -> Result<Self> {
        Self::from_pid_parallel_with_config(pid, &[], false, |_event| {}).await
    }

    /// Create DWARF analyzer from PID using parallel loading with progress callback
    pub async fn from_pid_parallel_with_progress<F>(pid: u32, progress_callback: F) -> Result<Self>
    where
        F: Fn(ModuleLoadingEvent) + Send + Sync + 'static,
    {
        Self::from_pid_parallel_with_config(pid, &[], false, progress_callback).await
    }

    /// Create DWARF analyzer from PID using parallel loading with debug search paths and progress callback
    pub async fn from_pid_parallel_with_config<F>(
        pid: u32,
        debug_search_paths: &[String],
        allow_loose_debug_match: bool,
        progress_callback: F,
    ) -> Result<Self>
    where
        F: Fn(ModuleLoadingEvent) + Send + Sync + 'static,
    {
        Self::from_pid_parallel_with_config_and_debuginfod(
            pid,
            debug_search_paths,
            allow_loose_debug_match,
            None,
            progress_callback,
        )
        .await
    }

    /// Create DWARF analyzer from PID with debug search paths, debuginfod, and progress callback.
    pub async fn from_pid_parallel_with_config_and_debuginfod<F>(
        pid: u32,
        debug_search_paths: &[String],
        allow_loose_debug_match: bool,
        debuginfod_client: Option<Arc<DebuginfodClient>>,
        progress_callback: F,
    ) -> Result<Self>
    where
        F: Fn(ModuleLoadingEvent) + Send + Sync + 'static,
    {
        tracing::info!("Creating DWARF analyzer for PID {} (parallel)", pid);

        let module_runtime_info = Self::discover_pid_runtime_modules(pid)?;

        Self::from_pid_runtime_modules_with_config_and_debuginfod(
            pid,
            module_runtime_info,
            debug_search_paths,
            allow_loose_debug_match,
            debuginfod_client,
            progress_callback,
        )
        .await
    }

    /// Discover runtime module mappings for a PID.
    pub fn discover_pid_runtime_modules(pid: u32) -> Result<Vec<LoadedModuleRuntimeInfo>> {
        let mut coord = ghostscope_process::ProcessManager::new();
        coord.ensure_prefill_pid(pid)?;
        Ok(coord
            .cached_offsets_with_paths_for_pid(pid)
            .map(Self::runtime_modules_from_pid_offsets)
            .unwrap_or_default())
    }

    /// Convert cached process offsets into one runtime mapping per module path.
    pub fn runtime_modules_from_pid_offsets(
        entries: &[ghostscope_process::PidOffsetsEntry],
    ) -> Vec<LoadedModuleRuntimeInfo> {
        let mut seen = std::collections::HashSet::new();
        entries
            .iter()
            .filter(|entry| seen.insert(entry.module_path.clone()))
            .map(|entry| LoadedModuleRuntimeInfo {
                module_path: PathBuf::from(&entry.module_path),
                loaded_address: Some(entry.base),
                load_bias: Some(entry.offsets.text),
                size: entry.size,
            })
            .collect()
    }

    fn runtime_modules_to_module_mappings(
        runtime_modules: Vec<LoadedModuleRuntimeInfo>,
    ) -> Vec<ModuleMapping> {
        runtime_modules
            .into_iter()
            .map(|module| {
                let mut mapping = ModuleMapping::from_path(module.module_path);
                mapping.loaded_address = module.loaded_address;
                mapping.load_bias = module.load_bias;
                mapping.size = module.size;
                mapping
            })
            .collect()
    }

    /// Load newly discovered modules into an existing PID analyzer.
    pub async fn refresh_pid_runtime_modules_with_config_and_debuginfod<F>(
        &mut self,
        runtime_modules: Vec<LoadedModuleRuntimeInfo>,
        debug_search_paths: &[String],
        allow_loose_debug_match: bool,
        debuginfod_client: Option<Arc<DebuginfodClient>>,
        progress_callback: F,
    ) -> Result<usize>
    where
        F: Fn(ModuleLoadingEvent) + Send + Sync + 'static,
    {
        let mut new_runtime_modules = Vec::new();
        let mut updated_existing = 0usize;

        for runtime_module in runtime_modules {
            let existing = self.modules.iter_mut().find(|(path, _)| {
                Self::module_paths_equivalent(path.as_path(), &runtime_module.module_path)
            });

            if let Some((_path, loaded)) = existing {
                let mapping = loaded.module_mapping();
                if mapping.loaded_address != runtime_module.loaded_address
                    || mapping.load_bias != runtime_module.load_bias
                    || mapping.size != runtime_module.size
                {
                    loaded.update_runtime_mapping(
                        runtime_module.loaded_address,
                        runtime_module.load_bias,
                        runtime_module.size,
                    );
                    updated_existing += 1;
                }
            } else {
                new_runtime_modules.push(runtime_module);
            }
        }

        if updated_existing > 0 {
            self.clear_pc_context_cache();
            tracing::debug!(
                "Updated runtime mapping metadata for {} loaded module(s)",
                updated_existing
            );
        }

        if new_runtime_modules.is_empty() {
            return Ok(0);
        }

        tracing::info!(
            "Refreshing DWARF analyzer for PID {} with {} newly mapped module(s)",
            self.pid,
            new_runtime_modules.len()
        );

        let module_mappings = Self::runtime_modules_to_module_mappings(new_runtime_modules);

        for (index, mapping) in module_mappings.iter().enumerate() {
            progress_callback(ModuleLoadingEvent::Discovered {
                module_path: mapping.path.to_string_lossy().to_string(),
                current: index + 1,
                total: module_mappings.len(),
            });
        }

        let mut loader = crate::loader::ModuleLoader::new(module_mappings).parallel();
        if !debug_search_paths.is_empty() {
            loader = loader.with_debug_search_paths(debug_search_paths.to_vec());
        }
        loader = loader.with_loose_debug_match(allow_loose_debug_match);
        loader = loader.with_debuginfod_client(debuginfod_client);

        let modules = loader
            .with_progress_callback(progress_callback)
            .load()
            .await?;
        let loaded_count = modules.len();

        for module in modules {
            let module_path = module.module_path().clone();
            self.modules.insert(module_path, module);
        }

        if loaded_count > 0 {
            self.clear_pc_context_cache();
            tracing::info!(
                "DWARF analyzer for PID {} loaded {} new module(s)",
                self.pid,
                loaded_count
            );
        }

        Ok(loaded_count)
    }

    /// Create DWARF analyzer from an already discovered PID runtime module snapshot.
    pub async fn from_pid_runtime_modules_with_config_and_debuginfod<F>(
        pid: u32,
        runtime_modules: Vec<LoadedModuleRuntimeInfo>,
        debug_search_paths: &[String],
        allow_loose_debug_match: bool,
        debuginfod_client: Option<Arc<DebuginfodClient>>,
        progress_callback: F,
    ) -> Result<Self>
    where
        F: Fn(ModuleLoadingEvent) + Send + Sync + 'static,
    {
        Self::from_pid_runtime_modules_with_config_debuginfod_and_explicit_debug_file(
            pid,
            runtime_modules,
            debug_search_paths,
            allow_loose_debug_match,
            debuginfod_client,
            None,
            progress_callback,
        )
        .await
    }

    /// Create DWARF analyzer from an already discovered PID runtime module snapshot,
    /// with optional debuginfod and a user-provided debug file for one module.
    pub async fn from_pid_runtime_modules_with_config_debuginfod_and_explicit_debug_file<F>(
        pid: u32,
        runtime_modules: Vec<LoadedModuleRuntimeInfo>,
        debug_search_paths: &[String],
        allow_loose_debug_match: bool,
        debuginfod_client: Option<Arc<DebuginfodClient>>,
        explicit_debug_file: Option<ExplicitDebugFile>,
        progress_callback: F,
    ) -> Result<Self>
    where
        F: Fn(ModuleLoadingEvent) + Send + Sync + 'static,
    {
        tracing::info!(
            "Creating DWARF analyzer for PID {} from {} runtime module mappings",
            pid,
            runtime_modules.len()
        );

        let module_mappings = Self::runtime_modules_to_module_mappings(runtime_modules);

        tracing::info!(
            "Discovered {} modules for PID {}",
            module_mappings.len(),
            pid
        );

        // Notify discovery completion
        for (index, mapping) in module_mappings.iter().enumerate() {
            progress_callback(ModuleLoadingEvent::Discovered {
                module_path: mapping.path.to_string_lossy().to_string(),
                current: index + 1,
                total: module_mappings.len(),
            });
        }

        // Load all modules in parallel with progress tracking
        let mut loader = crate::loader::ModuleLoader::new(module_mappings).parallel();

        // Configure debug search paths if provided
        if !debug_search_paths.is_empty() {
            loader = loader.with_debug_search_paths(debug_search_paths.to_vec());
        }
        loader = loader.with_loose_debug_match(allow_loose_debug_match);
        loader = loader.with_explicit_debug_file(explicit_debug_file);
        loader = loader.with_debuginfod_client(debuginfod_client);

        let modules = loader
            .with_progress_callback(progress_callback)
            .load()
            .await?;

        tracing::info!(
            "Created DWARF analyzer for PID {} with {} modules (parallel)",
            pid,
            modules.len()
        );

        Ok(Self::from_modules(pid, modules))
    }

    /// Create DWARF analyzer from executable path (single module mode, now async parallel)
    pub async fn from_exec_path<P: AsRef<std::path::Path>>(exec_path: P) -> Result<Self> {
        Self::from_exec_path_with_config(exec_path, &[], false).await
    }

    /// Create DWARF analyzer from executable path with debug search paths
    pub async fn from_exec_path_with_config<P: AsRef<std::path::Path>>(
        exec_path: P,
        debug_search_paths: &[String],
        allow_loose_debug_match: bool,
    ) -> Result<Self> {
        Self::from_exec_path_with_config_and_debuginfod(
            exec_path,
            debug_search_paths,
            allow_loose_debug_match,
            None,
        )
        .await
    }

    /// Create DWARF analyzer from executable path with debug search paths and debuginfod.
    pub async fn from_exec_path_with_config_and_debuginfod<P: AsRef<std::path::Path>>(
        exec_path: P,
        debug_search_paths: &[String],
        allow_loose_debug_match: bool,
        debuginfod_client: Option<Arc<DebuginfodClient>>,
    ) -> Result<Self> {
        Self::from_exec_path_with_config_and_debuginfod_and_progress(
            exec_path,
            debug_search_paths,
            allow_loose_debug_match,
            debuginfod_client,
            |_event| {},
        )
        .await
    }

    /// Create DWARF analyzer from executable path with debug search paths and progress callback
    pub async fn from_exec_path_with_config_and_progress<P, F>(
        exec_path: P,
        debug_search_paths: &[String],
        allow_loose_debug_match: bool,
        progress_callback: F,
    ) -> Result<Self>
    where
        P: AsRef<std::path::Path>,
        F: Fn(ModuleLoadingEvent) + Send + Sync + 'static,
    {
        Self::from_exec_path_with_config_and_debuginfod_and_progress(
            exec_path,
            debug_search_paths,
            allow_loose_debug_match,
            None,
            progress_callback,
        )
        .await
    }

    /// Create DWARF analyzer from executable path with debug search paths, debuginfod, and progress callback.
    pub async fn from_exec_path_with_config_and_debuginfod_and_progress<P, F>(
        exec_path: P,
        debug_search_paths: &[String],
        allow_loose_debug_match: bool,
        debuginfod_client: Option<Arc<DebuginfodClient>>,
        progress_callback: F,
    ) -> Result<Self>
    where
        P: AsRef<std::path::Path>,
        F: Fn(ModuleLoadingEvent) + Send + Sync + 'static,
    {
        Self::from_exec_path_with_config_debuginfod_explicit_debug_file_and_progress(
            exec_path,
            debug_search_paths,
            allow_loose_debug_match,
            debuginfod_client,
            None,
            progress_callback,
        )
        .await
    }

    /// Create DWARF analyzer from executable path with debug search paths,
    /// debuginfod, an optional explicit debug file, and progress callback.
    pub async fn from_exec_path_with_config_debuginfod_explicit_debug_file_and_progress<P, F>(
        exec_path: P,
        debug_search_paths: &[String],
        allow_loose_debug_match: bool,
        debuginfod_client: Option<Arc<DebuginfodClient>>,
        explicit_debug_file: Option<PathBuf>,
        progress_callback: F,
    ) -> Result<Self>
    where
        P: AsRef<std::path::Path>,
        F: Fn(ModuleLoadingEvent) + Send + Sync + 'static,
    {
        let exec_path = exec_path.as_ref().to_path_buf();
        tracing::info!(
            "Creating DWARF analyzer for executable: {}",
            exec_path.display()
        );

        let mut analyzer = Self {
            pid: 0, // No specific PID in exec mode
            modules: HashMap::new(),
            pc_context_cache: RwLock::new(PcContextCache::default()),
        };

        // Create a single module mapping for the executable
        // No loaded address since we're not analyzing a running process
        let module_mapping = ModuleMapping {
            path: exec_path.clone(),
            loaded_address: None, // No process mapping in exec path mode
            load_bias: None,
            size: 0, // Will be determined from file size if needed
        };
        let module_path = exec_path.to_string_lossy().to_string();

        progress_callback(ModuleLoadingEvent::Discovered {
            module_path: module_path.clone(),
            current: 1,
            total: 1,
        });
        progress_callback(ModuleLoadingEvent::LoadingStarted {
            module_path: module_path.clone(),
            current: 1,
            total: 1,
        });

        // Load the single module using parallel loading
        let start_time = std::time::Instant::now();
        match LoadedObjfile::load_parallel(
            module_mapping,
            debug_search_paths,
            allow_loose_debug_match,
            explicit_debug_file,
            debuginfod_client,
        )
        .await
        {
            Ok(module_data) => {
                let (functions, variables, types) = module_data.get_lightweight_index().get_stats();
                let (parse_time_ms, index_time_ms, module_total_time_ms) =
                    module_data.get_load_timing_ms();
                progress_callback(ModuleLoadingEvent::LoadingCompleted {
                    module_path,
                    stats: ModuleLoadingStats {
                        functions,
                        variables,
                        types,
                        debug_info_source: module_data.get_debug_info_source().clone(),
                        load_time_ms: start_time.elapsed().as_millis() as u64,
                        parse_time_ms,
                        index_time_ms,
                        module_total_time_ms,
                    },
                    current: 1,
                    total: 1,
                });
                analyzer.modules.insert(exec_path.clone(), module_data);
                tracing::info!(
                    "Created DWARF analyzer for executable {} with 1 module",
                    exec_path.display()
                );
            }
            Err(e) => {
                progress_callback(ModuleLoadingEvent::LoadingFailed {
                    module_path,
                    error: e.to_string(),
                    current: 1,
                    total: 1,
                });
                return Err(crate::DwarfError::ModuleLoadError(format!(
                    "Failed to load executable {}: {}",
                    exec_path.display(),
                    e
                ))
                .into());
            }
        }

        Ok(analyzer)
    }

    /// Create analyzer from pre-loaded modules (for Builder pattern)
    pub(crate) fn from_modules(pid: u32, modules: Vec<LoadedObjfile>) -> Self {
        let mut analyzer = Self {
            pid,
            modules: HashMap::new(),
            pc_context_cache: RwLock::new(PcContextCache::default()),
        };

        for module in modules {
            let module_path = module.module_path().clone();
            analyzer.modules.insert(module_path, module);
        }

        tracing::info!(
            "Created DWARF analyzer for PID {} with {} pre-loaded modules",
            pid,
            analyzer.modules.len()
        );

        analyzer
    }

    fn clear_pc_context_cache(&self) {
        if let Ok(mut cache) = self.pc_context_cache.write() {
            *cache = PcContextCache::default();
        }
    }

    /// Lookup function addresses across all modules
    /// Returns: Vec<ModuleAddress> - one for each address where the function is found
    pub fn lookup_function_addresses(&self, name: &str) -> Vec<ModuleAddress> {
        let mut results = Vec::new();

        for (module_path, module_data) in &self.modules {
            let addresses = module_data.lookup_function_addresses_any(name);

            // Create a ModuleAddress for each address found in this module
            for address in addresses {
                tracing::debug!(
                    "Function '{}' found in module {} at address: 0x{:x}",
                    name,
                    module_path.display(),
                    address
                );
                results.push(ModuleAddress::new(module_path.clone(), address));
            }
        }

        // Deterministic ordering: module path asc, then address asc
        results.sort_by(|a, b| {
            let pa = a.module_path.to_string_lossy();
            let pb = b.module_path.to_string_lossy();
            match pa.cmp(&pb) {
                std::cmp::Ordering::Equal => a.address.cmp(&b.address),
                other => other,
            }
        });
        results
    }

    /// Query function debug information across all modules.
    pub fn query_function(&self, name: &str) -> Result<FunctionQueryResult> {
        let module_addresses = self.lookup_function_addresses(name);
        let addresses = self.query_module_addresses(module_addresses)?;
        Ok(FunctionQueryResult {
            function_name: name.to_string(),
            addresses,
        })
    }

    /// Query function debug information across all modules, skipping addresses
    /// that fail to resolve so callers can still display partial results.
    pub fn query_function_best_effort(&self, name: &str) -> Result<FunctionQueryResult> {
        let module_addresses = self.lookup_function_addresses(name);
        let addresses = self
            .query_module_addresses_best_effort(module_addresses, &format!("function '{name}'"))?;
        Ok(FunctionQueryResult {
            function_name: name.to_string(),
            addresses,
        })
    }

    /// Convert a module-relative virtual address (DWARF PC) to an ELF file offset
    /// Returns None if the module is unknown or the address is not within a PT_LOAD segment
    pub fn vaddr_to_file_offset<P: AsRef<std::path::Path>>(
        &self,
        module_path: P,
        vaddr: u64,
    ) -> Option<u64> {
        let path_buf = module_path.as_ref().to_path_buf();
        if let Some(module_data) = self.modules.get(&path_buf) {
            module_data.vaddr_to_file_offset(vaddr)
        } else {
            None
        }
    }

    /// Recover the direct caller frame at a module address as PlanExprOp[].
    pub fn recover_caller_frame(
        &self,
        module_address: &ModuleAddress,
        registers: &[u16],
    ) -> Result<Option<CallerFrameRecovery>> {
        if let Some(module_data) = self
            .loaded_module_path_for(&module_address.module_path)
            .and_then(|module_path| self.modules.get(module_path))
        {
            module_data.recover_caller_frame(module_address.address, registers)
        } else {
            Ok(None)
        }
    }

    /// Recover the direct caller frame at a previously resolved PC context.
    pub fn recover_caller_frame_for_context(
        &self,
        ctx: &PcContext,
        registers: &[u16],
    ) -> Result<Option<CallerFrameRecovery>> {
        let module_address = self.module_address_for_context(ctx)?;
        self.recover_caller_frame(&module_address, registers)
    }

    /// Build compact unwind rows for the module referenced by a PC context.
    pub fn compact_unwind_table_for_context(
        &self,
        ctx: &PcContext,
    ) -> Result<Option<Arc<CompactUnwindTable>>> {
        let module_path = self
            .module_path_for_id(ctx.module)
            .ok_or_else(|| anyhow::anyhow!("Semantic module id {:?} is not loaded", ctx.module))?;
        self.modules
            .get(module_path)
            .ok_or_else(|| anyhow::anyhow!("Module {} not loaded", module_path.display()))?
            .compact_unwind_table(ctx.module)
    }

    /// Resolve the compact unwind row that covers a previously resolved PC context.
    pub fn compact_unwind_row_for_context(
        &self,
        ctx: &PcContext,
    ) -> Result<Option<CompactUnwindRow>> {
        let module_path = self
            .module_path_for_id(ctx.module)
            .ok_or_else(|| anyhow::anyhow!("Semantic module id {:?} is not loaded", ctx.module))?;
        self.modules
            .get(module_path)
            .ok_or_else(|| anyhow::anyhow!("Module {} not loaded", module_path.display()))?
            .compact_unwind_row(ctx.module, ctx.normalized_pc)
    }

    /// Build compact unwind rows for a loaded semantic module id.
    pub fn compact_unwind_table_for_module(
        &self,
        module: crate::ModuleId,
    ) -> Result<Option<Arc<CompactUnwindTable>>> {
        let module_path = self
            .module_path_for_id(module)
            .ok_or_else(|| anyhow::anyhow!("Semantic module id {:?} is not loaded", module))?;
        self.modules
            .get(module_path)
            .ok_or_else(|| anyhow::anyhow!("Module {} not loaded", module_path.display()))?
            .compact_unwind_table(module)
    }

    /// Get all loaded module paths
    pub fn get_loaded_modules(&self) -> Vec<&PathBuf> {
        self.modules.keys().collect()
    }

    /// Get loaded module paths with process mapping metadata, when available.
    pub fn loaded_module_runtime_info(&self) -> Vec<LoadedModuleRuntimeInfo> {
        let mut modules: Vec<_> = self
            .modules
            .values()
            .map(|module| {
                let mapping = module.module_mapping();
                LoadedModuleRuntimeInfo {
                    module_path: mapping.path.clone(),
                    loaded_address: mapping.loaded_address,
                    load_bias: mapping.load_bias,
                    size: mapping.size,
                }
            })
            .collect();
        modules.sort_by(|left, right| left.module_path.cmp(&right.module_path));
        modules
    }

    /// Get the ELF entry address for a loaded module, when present.
    pub fn module_entry_address<P: AsRef<Path>>(&self, module_path: P) -> Option<u64> {
        self.modules
            .get(module_path.as_ref())
            .and_then(|module| module.entry_address())
    }

    /// Classify the section type for a link-time virtual address in a specific module
    pub fn classify_section_for_address<P: AsRef<Path>>(
        &self,
        module_path: P,
        vaddr: u64,
    ) -> Option<SectionType> {
        let path = module_path.as_ref();
        if let Some(module_data) = self.modules.get(path) {
            module_data.classify_section_for_vaddr(vaddr)
        } else {
            None
        }
    }

    /// Lookup function address by name - returns first match
    /// Returns ModuleAddress for the first function found
    pub fn lookup_function_address_by_name(&self, function_name: &str) -> Option<ModuleAddress> {
        let module_addresses = self.lookup_function_addresses(function_name);

        if let Some(first_module_address) = module_addresses.first() {
            tracing::info!(
                "Found function '{}' in module '{}' at address 0x{:x}",
                function_name,
                first_module_address.module_display(),
                first_module_address.address
            );
            Some(first_module_address.clone())
        } else {
            tracing::warn!("Function '{}' not found in any module", function_name);
            None
        }
    }

    /// Lookup source location by module address
    /// Returns source location for the given module address
    pub fn lookup_source_location(&self, module_address: &ModuleAddress) -> Option<SourceLocation> {
        if let Some(module_data) = self
            .loaded_module_path_for(&module_address.module_path)
            .and_then(|module_path| self.modules.get(module_path))
        {
            module_data.lookup_source_location(module_address.address)
        } else {
            tracing::warn!("Module {} not found", module_address.module_display());
            None
        }
    }

    /// Lookup addresses by source line (cross-module)
    /// Returns: Vec<ModuleAddress> for all matches
    pub fn lookup_addresses_by_source_line(
        &self,
        file_path: &str,
        line_number: u32,
    ) -> Vec<ModuleAddress> {
        let mut results = Vec::new();

        // Check each module for this source:line combination
        for (module_path, module_data) in &self.modules {
            let addresses = module_data.lookup_addresses_by_source_line(file_path, line_number);

            // Add all addresses from this module
            for address in addresses {
                results.push(ModuleAddress::new(module_path.clone(), address));
            }
        }

        if !results.is_empty() {
            tracing::info!(
                "Found {} addresses for {}:{} across {} modules",
                results.len(),
                file_path,
                line_number,
                self.modules.len()
            );
        }

        results.sort_by(|a, b| {
            let pa = a.module_path.to_string_lossy();
            let pb = b.module_path.to_string_lossy();
            match pa.cmp(&pb) {
                std::cmp::Ordering::Equal => a.address.cmp(&b.address),
                other => other,
            }
        });
        results
    }

    /// Query source-line debug information across all modules.
    pub fn query_source_line(
        &self,
        file_path: &str,
        line_number: u32,
    ) -> Result<Vec<AddressQueryResult>> {
        let module_addresses = self.lookup_addresses_by_source_line(file_path, line_number);
        self.query_module_addresses_for_source_line(module_addresses, file_path, line_number)
    }

    /// Query source-line debug information across all modules, skipping
    /// addresses that fail to resolve so callers can still display partial
    /// results.
    pub fn query_source_line_best_effort(
        &self,
        file_path: &str,
        line_number: u32,
    ) -> Result<Vec<AddressQueryResult>> {
        let module_addresses = self.lookup_addresses_by_source_line(file_path, line_number);
        self.query_module_addresses_for_source_line_best_effort(
            module_addresses,
            file_path,
            line_number,
            &format!("source line '{file_path}:{line_number}'"),
        )
    }

    /// Query a specific address within a module.
    pub fn query_address<P: AsRef<Path>>(
        &self,
        module_path: P,
        address: u64,
    ) -> Result<AddressQueryResult> {
        let module_address = ModuleAddress::new(module_path.as_ref().to_path_buf(), address);
        self.build_address_query_result(&module_address)
    }

    /// Get all function names (cross-module)
    pub fn get_all_function_names(&self) -> Vec<String> {
        let mut all_names = std::collections::HashSet::new();
        for module_data in self.modules.values() {
            for name in module_data.get_function_names() {
                all_names.insert(name.clone());
            }
        }
        all_names.into_iter().collect()
    }

    /// Get statistics for debugging
    pub fn get_stats(&self) -> AnalyzerStats {
        let mut total_functions = 0;
        let mut total_variables = 0;
        let mut total_line_headers = 0;

        for module_data in self.modules.values() {
            total_functions += module_data.get_function_names().len();
            total_variables += module_data.get_variable_names().len();
            total_line_headers += module_data.get_line_header_count();
        }

        AnalyzerStats {
            pid: self.pid,
            module_count: self.modules.len(),
            total_functions,
            total_variables,
            total_line_headers,
        }
    }

    /// Get module statistics (compatible with ghostscope-binary's ModuleStats)
    pub fn get_module_stats(&self) -> ModuleStats {
        let mut total_symbols = 0;
        let mut executable_modules = 0;
        let mut library_modules = 0;
        let mut modules_with_debug_info = 0;

        for (module_path, module_data) in &self.modules {
            let function_names = module_data.get_function_names();
            total_symbols += function_names.len();
            if !matches!(
                module_data.get_debug_info_source(),
                DebugInfoSource::Missing
            ) {
                modules_with_debug_info += 1;
            }

            // Check if module is executable (main binary) or library
            if self.is_main_executable_module(module_path) {
                executable_modules += 1;
            } else {
                library_modules += 1;
            }
        }

        ModuleStats {
            total_modules: self.modules.len(),
            executable_modules,
            library_modules,
            total_symbols,
            modules_with_debug_info,
        }
    }

    /// Get main executable module information
    pub fn get_main_executable(&self) -> Option<MainExecutableInfo> {
        // Find the main executable module (usually the first non-library module)
        for module_path in self.modules.keys() {
            if self.is_main_executable_module(module_path) {
                return Some(MainExecutableInfo {
                    path: module_path.to_string_lossy().to_string(),
                });
            }
        }
        None
    }

    /// Check if a module is the main executable (not a shared library)
    fn is_main_executable_module(&self, module_path: &Path) -> bool {
        // Heuristic: main executable usually doesn't have .so extension and contains the process name
        let filename = module_path
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or("");

        // Not a shared library
        !filename.contains(".so") &&
        // Not a system library path
        !module_path.to_string_lossy().starts_with("/lib") &&
        !module_path.to_string_lossy().starts_with("/usr/lib")
    }

    /// Get list of all function names across all modules
    pub fn list_functions(&self) -> Vec<String> {
        let mut all_functions = Vec::new();

        for module_data in self.modules.values() {
            let function_names = module_data.get_function_names();
            for name in function_names {
                all_functions.push(name.clone());
            }
        }

        // Remove duplicates and sort
        all_functions.sort();
        all_functions.dedup();

        tracing::debug!(
            "Listed {} unique functions across {} modules",
            all_functions.len(),
            self.modules.len()
        );

        all_functions
    }

    /// Lookup functions by pattern (simplified - exact match only for now)
    pub fn lookup_functions_by_pattern(&self, pattern: &str) -> Vec<String> {
        let all_functions = self.list_functions();
        all_functions
            .into_iter()
            .filter(|name| name.contains(pattern))
            .collect()
    }

    /// Get all function names (alias for compatibility)
    pub fn lookup_all_function_names(&self) -> Vec<String> {
        self.list_functions()
    }

    /// Get PID (accessor for private field)
    pub fn get_pid(&self) -> u32 {
        self.pid
    }

    /// Get shared library information (compatibility method)
    pub fn get_shared_library_info(&self) -> Vec<SharedLibraryInfo> {
        self.modules
            .iter()
            .filter(|(path, _)| self.is_shared_library(path))
            .map(|(path, module_data)| {
                let mapping = module_data.module_mapping();
                let debug_file_path = module_data
                    .get_debug_file_path()
                    .map(|p| p.to_string_lossy().to_string());

                SharedLibraryInfo {
                    from_address: mapping.loaded_address.unwrap_or(0),
                    to_address: mapping.loaded_address.map_or(0, |addr| addr + mapping.size),
                    symbols_read: !module_data.get_function_names().is_empty(),
                    // Reflect actual DWARF availability (embedded or via .gnu_debuglink)
                    debug_info_available: module_data.has_dwarf_info(),
                    library_path: path.to_string_lossy().to_string(),
                    size: mapping.size,
                    debug_file_path,
                }
            })
            .collect()
    }

    /// Get executable file information (for "info file" command)
    pub fn get_executable_file_info(&self) -> Option<ExecutableFileInfo> {
        // Find the primary executable (not a shared library)
        let executable = self
            .modules
            .iter()
            .find(|(path, _)| !self.is_shared_library(path))?;

        let (exe_path, module_data) = executable;
        let file_path = exe_path.to_string_lossy().to_string();

        // Parse the ELF file to get detailed information
        let file_bytes = std::fs::read(exe_path).ok()?;
        let obj = object::File::parse(&file_bytes[..]).ok()?;

        // Get file type
        let file_type = match obj.format() {
            object::BinaryFormat::Elf => {
                if obj.is_64() {
                    "ELF 64-bit executable"
                } else {
                    "ELF 32-bit executable"
                }
            }
            _ => "Unknown format",
        }
        .to_string();

        // Check if has symbols
        let has_symbols = !module_data.get_function_names().is_empty()
            || obj.symbols().count() > 0
            || obj.dynamic_symbols().count() > 0;

        // Check if has debug info - check if DWARF was successfully loaded
        // This includes both embedded DWARF and debug link external files
        let has_debug_info = module_data.has_dwarf_info();

        // Get debug file path if using separate debug file (e.g., via .gnu_debuglink)
        let debug_file_path = module_data.get_debug_file_path();

        // Load bias for PID mode from module mapping (if available)
        let load_bias = if self.pid != 0 {
            module_data.module_mapping().loaded_address.unwrap_or(0)
        } else {
            0
        };

        // Get entry point (add load bias in PID mode)
        let entry_point = Some(obj.entry() + load_bias);

        // Get .text section info (add load bias in PID mode)
        let text_section = obj.section_by_name(".text").map(|section| {
            let addr = section.address() + load_bias;
            let size = section.size();
            SectionInfo {
                start_address: addr,
                end_address: addr + size,
                size,
            }
        });

        // Get .data section info (add load bias in PID mode)
        let data_section = obj.section_by_name(".data").map(|section| {
            let addr = section.address() + load_bias;
            let size = section.size();
            SectionInfo {
                start_address: addr,
                end_address: addr + size,
                size,
            }
        });

        // Determine mode description based on pid
        let mode_description = if self.pid != 0 {
            format!("Attached to process {} (PID mode)", self.pid)
        } else {
            "Static analysis mode (target file specified with -t)".to_string()
        };

        Some(ExecutableFileInfo {
            file_path,
            file_type,
            entry_point,
            has_symbols,
            has_debug_info,
            debug_file_path: debug_file_path.map(|p| p.to_string_lossy().to_string()),
            text_section,
            data_section,
            mode_description,
        })
    }

    // NOTE: Runtime section offsets are handled by ghostscope-coordinator.

    /// Check if a module is a shared library
    fn is_shared_library(&self, module_path: &Path) -> bool {
        let filename = module_path
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or("");

        // Shared libraries typically have .so extension or contain .so
        filename.contains(".so")
            || module_path.to_string_lossy().starts_with("/lib")
            || module_path.to_string_lossy().starts_with("/usr/lib")
    }

    /// Get grouped file info by module (compatibility method)
    pub fn get_grouped_file_info_by_module(&self) -> Result<Vec<(String, Vec<SimpleFileInfo>)>> {
        let mut grouped = Vec::new();

        for (module_path, module_data) in &self.modules {
            let files = module_data.get_all_files();
            if !files.is_empty() {
                let simple_files: Vec<SimpleFileInfo> = files
                    .into_iter()
                    .map(|source_file| SimpleFileInfo {
                        full_path: source_file.full_path,
                        basename: source_file.filename,
                        directory: source_file.directory_path,
                    })
                    .collect();

                grouped.push((module_path.to_string_lossy().to_string(), simple_files));
            }
        }

        Ok(grouped)
    }
}

///
/// Module statistics compatible with ghostscope-binary
#[derive(Debug, Clone)]
pub struct ModuleStats {
    pub total_modules: usize,
    pub executable_modules: usize,
    pub library_modules: usize,
    pub total_symbols: usize,
    pub modules_with_debug_info: usize,
}

/// Main executable information
#[derive(Debug, Clone)]
pub struct MainExecutableInfo {
    pub path: String,
}

/// Statistics for debugging and monitoring
#[derive(Debug, Clone)]
pub struct AnalyzerStats {
    pub pid: u32,
    pub module_count: usize,
    pub total_functions: usize,
    pub total_variables: usize,
    pub total_line_headers: usize,
}

/// Shared library information (compatible with ghostscope-ui)
#[derive(Debug, Clone)]
pub struct SharedLibraryInfo {
    pub from_address: u64,               // Starting address in memory
    pub to_address: u64,                 // Ending address in memory
    pub symbols_read: bool,              // Whether symbols were successfully read
    pub debug_info_available: bool,      // Whether debug information is available
    pub library_path: String,            // Full path to the library file
    pub size: u64,                       // Size of the library in memory
    pub debug_file_path: Option<String>, // Path to separate debug file (if via .gnu_debuglink)
}

/// Executable file information (for "info file" command)
#[derive(Debug, Clone)]
pub struct ExecutableFileInfo {
    pub file_path: String,
    pub file_type: String,
    pub entry_point: Option<u64>,
    pub has_symbols: bool,
    pub has_debug_info: bool,
    pub debug_file_path: Option<String>,
    pub text_section: Option<SectionInfo>,
    pub data_section: Option<SectionInfo>,
    pub mode_description: String,
}

/// Section information for executable files
#[derive(Debug, Clone)]
pub struct SectionInfo {
    pub start_address: u64,
    pub end_address: u64,
    pub size: u64,
}

/// Simple file information compatible with ghostscope-binary
#[derive(Debug, Clone)]
pub struct SimpleFileInfo {
    pub full_path: String,
    pub basename: String,
    pub directory: String,
}

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

    fn global_plan(name: &str, address: u64) -> VariableReadPlan {
        VariableReadPlan {
            name: name.to_string(),
            type_name: "int".to_string(),
            access_path: crate::VariableAccessPath::default(),
            module_path: None,
            dwarf_type: Some(crate::TypeInfo::BaseType {
                name: "int".to_string(),
                size: 4,
                encoding: gimli::constants::DW_ATE_signed.0 as u16,
            }),
            declaration: None,
            type_id: None,
            location: VariableLocation::Address(AddressExpr::constant(address)),
            availability: Availability::Available,
            scope_depth: 0,
            is_parameter: false,
            is_artificial: false,
            pc_range: None,
            inline_context: None,
            provenance: Provenance::Synthesized {
                detail: "test".to_string(),
            },
        }
    }

    fn visible_var(name: &str, scope_depth: usize) -> VisibleVariable {
        VisibleVariable {
            name: name.to_string(),
            type_name: "int".to_string(),
            dwarf_type: Some(crate::TypeInfo::BaseType {
                name: "int".to_string(),
                size: 4,
                encoding: gimli::constants::DW_ATE_signed.0 as u16,
            }),
            declaration: None,
            type_id: None,
            location: VariableLocation::RegisterValue { dwarf_reg: 0 },
            availability: Availability::Available,
            scope_depth,
            is_parameter: false,
            is_artificial: false,
        }
    }

    fn diagnostic(
        name: &str,
        scope_depth: usize,
        detail: &str,
    ) -> crate::semantics::VariableQueryDiagnostic {
        crate::semantics::VariableQueryDiagnostic {
            pc: 0x1234,
            name: Some(name.to_string()),
            scope_depth,
            availability: Availability::Unsupported(crate::UnsupportedReason::ExpressionShape {
                detail: detail.to_string(),
            }),
            detail: detail.to_string(),
        }
    }

    #[test]
    fn variable_selection_rejects_inner_diagnostic_over_outer_match() {
        let err = DwarfAnalyzer::select_visible_variable_by_name(
            0x1234,
            "state",
            vec![visible_var("state", 1)],
            &[diagnostic("state", 2, "DW_OP_bad is unsupported")],
        )
        .expect_err("inner unavailable variable should block outer fallback");

        assert!(err.to_string().contains("Unavailable variable 'state'"));
        assert!(err.to_string().contains("DW_OP_bad is unsupported"));
    }

    #[test]
    fn variable_selection_keeps_inner_match_over_outer_diagnostic() {
        let selected = DwarfAnalyzer::select_visible_variable_by_name(
            0x1234,
            "state",
            vec![visible_var("state", 2)],
            &[diagnostic("state", 1, "outer variable is unavailable")],
        )
        .expect("outer diagnostic should not block inner match")
        .expect("inner match should be returned");

        assert_eq!(selected.name, "state");
        assert_eq!(selected.scope_depth, 2);
    }

    #[test]
    fn global_plan_selection_rejects_ambiguous_matches() {
        let err = DwarfAnalyzer::select_unambiguous_global_plan(
            "state",
            vec![
                (PathBuf::from("/tmp/a"), global_plan("state", 0x1000)),
                (PathBuf::from("/tmp/b"), global_plan("state", 0x2000)),
            ],
        )
        .expect_err("multiple global candidates should be ambiguous");

        assert!(err.to_string().contains("Ambiguous global 'state'"));
        assert!(err.to_string().contains("2 matches"));
    }

    #[test]
    fn global_plan_selection_accepts_single_match() {
        let selected = DwarfAnalyzer::select_unambiguous_global_plan(
            "state",
            vec![(PathBuf::from("/tmp/a"), global_plan("state", 0x1000))],
        )
        .expect("single global candidate should be accepted")
        .expect("single global candidate should be returned");

        assert_eq!(selected.0, PathBuf::from("/tmp/a"));
        assert_eq!(selected.1.name, "state");
    }

    #[test]
    fn global_plan_selection_prefers_current_module_match() {
        let selected = DwarfAnalyzer::select_global_plan_with_preferred_module(
            "state",
            Path::new("/tmp/current"),
            vec![
                (PathBuf::from("/tmp/other"), global_plan("state", 0x2000)),
                (PathBuf::from("/tmp/current"), global_plan("state", 0x1000)),
            ],
        )
        .expect("current module candidate should be accepted")
        .expect("current module candidate should be returned");

        assert_eq!(selected.0, PathBuf::from("/tmp/current"));
        assert_eq!(
            selected.1.location,
            VariableLocation::Address(AddressExpr::constant(0x1000))
        );
    }

    #[test]
    fn global_plan_selection_rejects_ambiguous_current_module_matches() {
        let err = DwarfAnalyzer::select_global_plan_with_preferred_module(
            "state",
            Path::new("/tmp/current"),
            vec![
                (PathBuf::from("/tmp/current"), global_plan("state", 0x1000)),
                (PathBuf::from("/tmp/current"), global_plan("state", 0x1004)),
                (PathBuf::from("/tmp/other"), global_plan("state", 0x2000)),
            ],
        )
        .expect_err("duplicate current-module candidates should be ambiguous");

        assert!(err.to_string().contains("Ambiguous global 'state'"));
        assert!(err.to_string().contains("2 matches"));
        assert!(err.to_string().contains("/tmp/current"));
        assert!(!err.to_string().contains("/tmp/other"));
    }
}