calltrace-rs 1.1.4

High-performance function call tracing library for C/C++ applications using GCC instrumentation with Rust safety guarantees
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
//! DWARF Debug Information Analysis
//!
//! This module parses DWARF debugging information to extract function signatures,
//! parameter types, and other metadata required for argument capture.

use crate::error::{CallTraceError, Result};
use std::collections::HashMap;
use std::ffi::c_void;
use std::fs;

/// Function information extracted from DWARF
#[derive(Debug, Clone)]
pub struct FunctionInfo {
    pub name: String,
    pub address: u64,
    pub size: Option<u64>,
    pub parameters: Vec<ParameterInfo>,
    pub return_type: Option<TypeInfo>,
    pub source_file: Option<String>,
    pub line_number: Option<u32>,
}

/// Parameter information for function arguments
#[derive(Debug, Clone)]
pub struct ParameterInfo {
    pub name: String,
    pub type_info: TypeInfo,
    pub location: Option<String>, // DW_AT_location if available
}

/// Type information extracted from DWARF
#[derive(Debug, Clone)]
pub struct TypeInfo {
    pub name: String,
    pub size: Option<u64>,
    pub is_pointer: bool,
    pub is_const: bool,
    pub is_struct: bool,
    pub is_array: bool,
    pub array_size: Option<u64>,
    pub base_type: Option<Box<TypeInfo>>,
}

/// DWARF analyzer context that caches parsed information
pub struct DwarfAnalyzer {
    executable_path: String,
    function_cache: HashMap<u64, FunctionInfo>,
    type_cache: HashMap<u64, TypeInfo>,
    symbol_cache: HashMap<u64, String>, // Cache for resolved symbols
    base_address: Option<u64>,          // Program base address
    #[cfg(feature = "dwarf_support")]
    dwarf_data: Option<DwarfData>,
}

/// Cached DWARF data
#[cfg(feature = "dwarf_support")]
struct DwarfData {
    #[allow(dead_code)]
    dwarf: (), // Simplified for now
    #[allow(dead_code)]
    file_data: Vec<u8>, // Keep file data alive
}

impl DwarfAnalyzer {
    /// Create a new DWARF analyzer for the specified executable
    pub fn new(executable_path: &str) -> Result<Self> {
        // Try to get the real executable path
        let real_exe_path = std::fs::read_link("/proc/self/exe")
            .unwrap_or_else(|_| executable_path.into())
            .to_string_lossy()
            .to_string();

        let mut analyzer = DwarfAnalyzer {
            executable_path: real_exe_path,
            function_cache: HashMap::new(),
            type_cache: HashMap::new(),
            symbol_cache: HashMap::new(),
            base_address: None,
            #[cfg(feature = "dwarf_support")]
            dwarf_data: None,
        };

        // Try to load DWARF data
        #[cfg(feature = "dwarf_support")]
        if let Err(e) = analyzer.load_dwarf_data() {
            // Log warning but continue - we can still work with limited functionality
            eprintln!("Warning: Failed to load DWARF data: {}", e);
        }

        // Initialize base address
        analyzer.base_address = analyzer.get_program_base_address();

        Ok(analyzer)
    }

    /// Load DWARF debugging information from the executable
    #[cfg(feature = "dwarf_support")]
    fn load_dwarf_data(&mut self) -> Result<()> {
        let file_data = fs::read(&self.executable_path)
            .map_err(|e| CallTraceError::DwarfError(format!("Failed to read executable: {}", e)))?;

        // TODO: Temporary simplified implementation
        // In the future, this will parse object file and load DWARF sections:
        /*
        let object = object::File::parse(&file_data[..])?;
        let load_section = |id: gimli::SectionId| -> std::result::Result<Cow<[u8]>, gimli::Error> {
            match object.section_by_name(id.name()) {
                Some(ref section) => Ok(section
                    .uncompressed_data()
                    .unwrap_or(Cow::Borrowed(&[][..]))),
                None => Ok(Cow::Borrowed(&[][..])),
            }
        };
        let dwarf_cow = Dwarf::load(&load_section)?;
        */
        // Keep file data alive for future use
        self.dwarf_data = Some(DwarfData {
            dwarf: (),
            file_data,
        });

        Ok(())
    }

    /// Get function information for a given address
    pub fn get_function_info(&mut self, address: u64) -> Result<FunctionInfo> {
        // Check cache first
        if let Some(cached) = self.function_cache.get(&address) {
            return Ok(cached.clone());
        }

        // Try to extract from DWARF data
        #[cfg(feature = "dwarf_support")]
        if let Some(info) = self.extract_function_info_from_dwarf(address)? {
            self.function_cache.insert(address, info.clone());
            return Ok(info);
        }

        // Fallback: create minimal function info using dladdr
        let fallback_info = self.create_fallback_function_info(address)?;
        self.function_cache.insert(address, fallback_info.clone());
        Ok(fallback_info)
    }

    /// Extract function information from DWARF data
    #[cfg(feature = "dwarf_support")]
    fn extract_function_info_from_dwarf(&mut self, _address: u64) -> Result<Option<FunctionInfo>> {
        // TODO: Temporary simplified implementation due to gimli API changes
        // Full implementation will be restored after updating to new gimli API
        Ok(None)
    }

    /*
    // TODO: Restore these functions with updated gimli API

    /// Extract function name from DIE
    #[cfg(feature = "dwarf_support")]
    fn extract_function_name(
        &self,
        dwarf: &Dwarf<gimli::EndianSlice<'static, gimli::LittleEndian>>,
        unit: &gimli::Unit<gimli::EndianSlice<'static, gimli::LittleEndian>>,
        entry: &gimli::DebuggingInformationEntry<gimli::EndianSlice<'static, gimli::LittleEndian>>,
    ) -> Result<Option<String>> {
        // Try DW_AT_name first
        if let Some(name_attr) = entry.attr_value(gimli::DW_AT_name)
            .map_err(|e| CallTraceError::DwarfError(format!("Error reading name: {}", e)))?
        {
            if let gimli::AttributeValue::DebugStrRef(offset) = name_attr {
                let name = dwarf.debug_str.get_str(offset)
                    .map_err(|e| CallTraceError::DwarfError(format!("Error reading string: {}", e)))?;
                return Ok(Some(name.to_string_lossy().to_string()));
            }
        }

        // Try DW_AT_linkage_name for mangled names
        if let Some(linkage_attr) = entry.attr_value(gimli::DW_AT_linkage_name)
            .map_err(|e| CallTraceError::DwarfError(format!("Error reading linkage name: {}", e)))?
        {
            if let gimli::AttributeValue::DebugStrRef(offset) = linkage_attr {
                let name = dwarf.debug_str.get_str(offset)
                    .map_err(|e| CallTraceError::DwarfError(format!("Error reading string: {}", e)))?;
                let demangled = demangle_function_name(&name.to_string_lossy());
                return Ok(Some(demangled));
            }
        }

        Ok(None)
    }

    /// Extract function parameters from DIE
    #[cfg(feature = "dwarf_support")]
    fn extract_function_parameters(
        &mut self,
        dwarf: &Dwarf<gimli::EndianSlice<'static, gimli::LittleEndian>>,
        unit: &gimli::Unit<gimli::EndianSlice<'static, gimli::LittleEndian>>,
        entry: &gimli::DebuggingInformationEntry<gimli::EndianSlice<'static, gimli::LittleEndian>>,
    ) -> Result<Vec<ParameterInfo>> {
        let mut parameters = Vec::new();
        let mut children = entry.children();

        while let Some(child) = children.next()
            .map_err(|e| CallTraceError::DwarfError(format!("Error reading child: {}", e)))?
        {
            if child.tag() == gimli::DW_TAG_formal_parameter {
                if let Some(param) = self.extract_parameter_info(dwarf, unit, &child)? {
                    parameters.push(param);
                }
            }
        }

        Ok(parameters)
    }

    /// Extract individual parameter information
    #[cfg(feature = "dwarf_support")]
    fn extract_parameter_info(
        &mut self,
        dwarf: &Dwarf<gimli::EndianSlice<'static, gimli::LittleEndian>>,
        unit: &gimli::Unit<gimli::EndianSlice<'static, gimli::LittleEndian>>,
        entry: &gimli::DebuggingInformationEntry<gimli::EndianSlice<'static, gimli::LittleEndian>>,
    ) -> Result<Option<ParameterInfo>> {
        // Extract parameter name
        let name = if let Some(name_attr) = entry.attr_value(gimli::DW_AT_name)
            .map_err(|e| CallTraceError::DwarfError(format!("Error reading param name: {}", e)))?
        {
            if let gimli::AttributeValue::DebugStrRef(offset) = name_attr {
                dwarf.debug_str.get_str(offset)
                    .map_err(|e| CallTraceError::DwarfError(format!("Error reading param string: {}", e)))?
                    .to_string_lossy().to_string()
            } else {
                "unnamed".to_string()
            }
        } else {
            "unnamed".to_string()
        };

        // Extract type information
        let type_info = if let Some(type_attr) = entry.attr_value(gimli::DW_AT_type)
            .map_err(|e| CallTraceError::DwarfError(format!("Error reading param type: {}", e)))?
        {
            if let gimli::AttributeValue::UnitRef(type_offset) = type_attr {
                self.extract_type_info_from_offset(dwarf, unit, type_offset)?
            } else {
                TypeInfo {
                    name: "unknown".to_string(),
                    size: None,
                    is_pointer: false,
                    is_const: false,
                    is_struct: false,
                    is_array: false,
                    array_size: None,
                    base_type: None,
                }
            }
        } else {
            TypeInfo {
                name: "unknown".to_string(),
                size: None,
                is_pointer: false,
                is_const: false,
                is_struct: false,
                is_array: false,
                array_size: None,
                base_type: None,
            }
        };

        // Extract location information (register, stack offset, etc.)
        let location = if let Some(loc_attr) = entry.attr_value(gimli::DW_AT_location)
            .map_err(|e| CallTraceError::DwarfError(format!("Error reading param location: {}", e)))?
        {
            // This would parse DWARF location expressions
            // For now, we'll just indicate that location data exists
            Some("dwarf_location".to_string())
        } else {
            None
        };

        Ok(Some(ParameterInfo {
            name,
            type_info,
            location,
        }))
    }

    /// Extract type information from a type offset
    #[cfg(feature = "dwarf_support")]
    fn extract_type_info_from_offset(
        &mut self,
        dwarf: &Dwarf<gimli::EndianSlice<'static, gimli::LittleEndian>>,
        unit: &gimli::Unit<gimli::EndianSlice<'static, gimli::LittleEndian>>,
        type_offset: gimli::UnitOffset,
    ) -> Result<TypeInfo> {
        // Check cache first
        let cache_key = type_offset.0 as u64;
        if let Some(cached_type) = self.type_cache.get(&cache_key) {
            return Ok(cached_type.clone());
        }

        // Get the type DIE
        let mut entries = unit.entries_at_offset(type_offset)
            .map_err(|e| CallTraceError::DwarfError(format!("Error getting type entry: {}", e)))?;

        let (_, type_entry) = entries.next_entry()
            .map_err(|e| CallTraceError::DwarfError(format!("Error reading type entry: {}", e)))?
            .ok_or_else(|| CallTraceError::DwarfError("Type entry not found".to_string()))?;

        let type_info = self.extract_type_info_from_die(dwarf, unit, &type_entry)?;

        // Cache the result
        self.type_cache.insert(cache_key, type_info.clone());

        Ok(type_info)
    }

    /// Extract detailed type information from a type DIE
    #[cfg(feature = "dwarf_support")]
    fn extract_type_info_from_die(
        &mut self,
        dwarf: &Dwarf<gimli::EndianSlice<'static, gimli::LittleEndian>>,
        unit: &gimli::Unit<gimli::EndianSlice<'static, gimli::LittleEndian>>,
        entry: &gimli::DebuggingInformationEntry<gimli::EndianSlice<'static, gimli::LittleEndian>>,
    ) -> Result<TypeInfo> {
        let tag = entry.tag();

        match tag {
            gimli::DW_TAG_base_type => {
                self.extract_base_type_info(dwarf, unit, entry)
            }
            gimli::DW_TAG_pointer_type => {
                self.extract_pointer_type_info(dwarf, unit, entry)
            }
            gimli::DW_TAG_array_type => {
                self.extract_array_type_info(dwarf, unit, entry)
            }
            gimli::DW_TAG_structure_type | gimli::DW_TAG_class_type => {
                self.extract_struct_type_info(dwarf, unit, entry)
            }
            gimli::DW_TAG_const_type => {
                self.extract_const_type_info(dwarf, unit, entry)
            }
            gimli::DW_TAG_typedef => {
                self.extract_typedef_info(dwarf, unit, entry)
            }
            _ => {
                // Fallback for unknown types
                Ok(TypeInfo {
                    name: format!("unknown_type_{:?}", tag),
                    size: entry.attr_value(gimli::DW_AT_byte_size)
                        .ok()
                        .flatten()
                        .and_then(|v| {
                            if let gimli::AttributeValue::Udata(size) = v {
                                Some(size)
                            } else {
                                None
                            }
                        }),
                    is_pointer: false,
                    is_const: false,
                    is_struct: false,
                    is_array: false,
                    array_size: None,
                    base_type: None,
                })
            }
        }
    }

    /// Extract return type information
    #[cfg(feature = "dwarf_support")]
    fn extract_return_type(
        &mut self,
        dwarf: &Dwarf<gimli::EndianSlice<'static, gimli::LittleEndian>>,
        unit: &gimli::Unit<gimli::EndianSlice<'static, gimli::LittleEndian>>,
        entry: &gimli::DebuggingInformationEntry<gimli::EndianSlice<'static, gimli::LittleEndian>>,
    ) -> Result<Option<TypeInfo>> {
        if let Some(type_attr) = entry.attr_value(gimli::DW_AT_type)
            .map_err(|e| CallTraceError::DwarfError(format!("Error reading return type: {}", e)))?
        {
            if let gimli::AttributeValue::UnitRef(type_offset) = type_attr {
                let type_info = self.extract_type_info_from_offset(dwarf, unit, type_offset)?;
                return Ok(Some(type_info));
            }
        }

        // No return type means void
        Ok(None)
    }

    /// Extract source file and line number information
    #[cfg(feature = "dwarf_support")]
    fn extract_source_location(
        &self,
        dwarf: &Dwarf<gimli::EndianSlice<'static, gimli::LittleEndian>>,
        unit: &gimli::Unit<gimli::EndianSlice<'static, gimli::LittleEndian>>,
        entry: &gimli::DebuggingInformationEntry<gimli::EndianSlice<'static, gimli::LittleEndian>>,
    ) -> Result<(Option<String>, Option<u32>)> {
        let mut source_file = None;
        let mut line_number = None;

        // Extract line number
        if let Some(line_attr) = entry.attr_value(gimli::DW_AT_decl_line)
            .map_err(|e| CallTraceError::DwarfError(format!("Error reading line: {}", e)))?
        {
            if let gimli::AttributeValue::Udata(line) = line_attr {
                line_number = Some(line as u32);
            }
        }

        // Extract source file
        if let Some(file_attr) = entry.attr_value(gimli::DW_AT_decl_file)
            .map_err(|e| CallTraceError::DwarfError(format!("Error reading file: {}", e)))?
        {
            if let gimli::AttributeValue::Udata(file_index) = file_attr {
                // This would require parsing the line number table to get the actual filename
                // For now, we'll just use the file index
                source_file = Some(format!("file_{}", file_index));
            }
        }

        Ok((source_file, line_number))
    }

    /// Extract base type information (int, char, float, etc.)
    #[cfg(feature = "dwarf_support")]
    fn extract_base_type_info(
        &self,
        dwarf: &Dwarf<gimli::EndianSlice<'static, gimli::LittleEndian>>,
        _unit: &gimli::Unit<gimli::EndianSlice<'static, gimli::LittleEndian>>,
        entry: &gimli::DebuggingInformationEntry<gimli::EndianSlice<'static, gimli::LittleEndian>>,
    ) -> Result<TypeInfo> {
        // Extract type name
        let name = if let Some(name_attr) = entry.attr_value(gimli::DW_AT_name)
            .map_err(|e| CallTraceError::DwarfError(format!("Error reading base type name: {}", e)))?
        {
            if let gimli::AttributeValue::DebugStrRef(offset) = name_attr {
                dwarf.debug_str.get_str(offset)
                    .map_err(|e| CallTraceError::DwarfError(format!("Error reading base type string: {}", e)))?
                    .to_string_lossy().to_string()
            } else {
                "unknown_base_type".to_string()
            }
        } else {
            "unknown_base_type".to_string()
        };

        // Extract size
        let size = entry.attr_value(gimli::DW_AT_byte_size)
            .map_err(|e| CallTraceError::DwarfError(format!("Error reading base type size: {}", e)))?
            .and_then(|v| {
                if let gimli::AttributeValue::Udata(size) = v {
                    Some(size)
                } else {
                    None
                }
            });

        Ok(TypeInfo {
            name,
            size,
            is_pointer: false,
            is_const: false,
            is_struct: false,
            is_array: false,
            array_size: None,
            base_type: None,
        })
    }

    /// Extract pointer type information
    #[cfg(feature = "dwarf_support")]
    fn extract_pointer_type_info(
        &mut self,
        dwarf: &Dwarf<gimli::EndianSlice<'static, gimli::LittleEndian>>,
        unit: &gimli::Unit<gimli::EndianSlice<'static, gimli::LittleEndian>>,
        entry: &gimli::DebuggingInformationEntry<gimli::EndianSlice<'static, gimli::LittleEndian>>,
    ) -> Result<TypeInfo> {
        // Get the pointed-to type
        let base_type = if let Some(type_attr) = entry.attr_value(gimli::DW_AT_type)
            .map_err(|e| CallTraceError::DwarfError(format!("Error reading pointer target type: {}", e)))?
        {
            if let gimli::AttributeValue::UnitRef(type_offset) = type_attr {
                Some(Box::new(self.extract_type_info_from_offset(dwarf, unit, type_offset)?))
            } else {
                None
            }
        } else {
            // Void pointer
            None
        };

        // Construct pointer type name
        let name = if let Some(ref base) = base_type {
            format!("{}*", base.name)
        } else {
            "void*".to_string()
        };

        // Pointer size (typically 8 bytes on 64-bit systems)
        let size = entry.attr_value(gimli::DW_AT_byte_size)
            .map_err(|e| CallTraceError::DwarfError(format!("Error reading pointer size: {}", e)))?
            .and_then(|v| {
                if let gimli::AttributeValue::Udata(size) = v {
                    Some(size)
                } else {
                    None
                }
            })
            .or(Some(8)); // Default to 8 bytes

        Ok(TypeInfo {
            name,
            size,
            is_pointer: true,
            is_const: false,
            is_struct: false,
            is_array: false,
            array_size: None,
            base_type,
        })
    }

    /// Extract array type information
    #[cfg(feature = "dwarf_support")]
    fn extract_array_type_info(
        &mut self,
        dwarf: &Dwarf<gimli::EndianSlice<'static, gimli::LittleEndian>>,
        unit: &gimli::Unit<gimli::EndianSlice<'static, gimli::LittleEndian>>,
        entry: &gimli::DebuggingInformationEntry<gimli::EndianSlice<'static, gimli::LittleEndian>>,
    ) -> Result<TypeInfo> {
        // Get the element type
        let base_type = if let Some(type_attr) = entry.attr_value(gimli::DW_AT_type)
            .map_err(|e| CallTraceError::DwarfError(format!("Error reading array element type: {}", e)))?
        {
            if let gimli::AttributeValue::UnitRef(type_offset) = type_attr {
                Some(Box::new(self.extract_type_info_from_offset(dwarf, unit, type_offset)?))
            } else {
                None
            }
        } else {
            None
        };

        // Extract array dimensions by looking at subrange_type children
        let mut array_size = None;
        let mut children = entry.children();

        while let Some(child) = children.next()
            .map_err(|e| CallTraceError::DwarfError(format!("Error reading array child: {}", e)))?
        {
            if child.tag() == gimli::DW_TAG_subrange_type {
                // Try to get the count or upper bound
                if let Some(count_attr) = child.attr_value(gimli::DW_AT_count)
                    .map_err(|e| CallTraceError::DwarfError(format!("Error reading array count: {}", e)))?
                {
                    if let gimli::AttributeValue::Udata(count) = count_attr {
                        array_size = Some(count);
                        break;
                    }
                } else if let Some(upper_attr) = child.attr_value(gimli::DW_AT_upper_bound)
                    .map_err(|e| CallTraceError::DwarfError(format!("Error reading array upper bound: {}", e)))?
                {
                    if let gimli::AttributeValue::Udata(upper) = upper_attr {
                        // Upper bound is typically count - 1 for zero-based arrays
                        array_size = Some(upper + 1);
                        break;
                    }
                }
            }
        }

        // Construct array type name
        let name = if let Some(ref base) = base_type {
            if let Some(size) = array_size {
                format!("{}[{}]", base.name, size)
            } else {
                format!("{}[]", base.name)
            }
        } else {
            "unknown_array".to_string()
        };

        // Calculate total size
        let total_size = if let (Some(ref base), Some(count)) = (&base_type, array_size) {
            base.size.map(|element_size| element_size * count)
        } else {
            None
        };

        Ok(TypeInfo {
            name,
            size: total_size,
            is_pointer: false,
            is_const: false,
            is_struct: false,
            is_array: true,
            array_size,
            base_type,
        })
    }

    /// Extract structure/class type information
    #[cfg(feature = "dwarf_support")]
    fn extract_struct_type_info(
        &self,
        dwarf: &Dwarf<gimli::EndianSlice<'static, gimli::LittleEndian>>,
        _unit: &gimli::Unit<gimli::EndianSlice<'static, gimli::LittleEndian>>,
        entry: &gimli::DebuggingInformationEntry<gimli::EndianSlice<'static, gimli::LittleEndian>>,
    ) -> Result<TypeInfo> {
        // Extract struct name
        let name = if let Some(name_attr) = entry.attr_value(gimli::DW_AT_name)
            .map_err(|e| CallTraceError::DwarfError(format!("Error reading struct name: {}", e)))?
        {
            if let gimli::AttributeValue::DebugStrRef(offset) = name_attr {
                dwarf.debug_str.get_str(offset)
                    .map_err(|e| CallTraceError::DwarfError(format!("Error reading struct string: {}", e)))?
                    .to_string_lossy().to_string()
            } else {
                "anonymous_struct".to_string()
            }
        } else {
            "anonymous_struct".to_string()
        };

        // Extract size
        let size = entry.attr_value(gimli::DW_AT_byte_size)
            .map_err(|e| CallTraceError::DwarfError(format!("Error reading struct size: {}", e)))?
            .and_then(|v| {
                if let gimli::AttributeValue::Udata(size) = v {
                    Some(size)
                } else {
                    None
                }
            });

        // Note: In a complete implementation, we would also extract member information
        // This would involve iterating through DW_TAG_member children

        Ok(TypeInfo {
            name,
            size,
            is_pointer: false,
            is_const: false,
            is_struct: true,
            is_array: false,
            array_size: None,
            base_type: None,
        })
    }

    /// Extract const type information
    #[cfg(feature = "dwarf_support")]
    fn extract_const_type_info(
        &mut self,
        dwarf: &Dwarf<gimli::EndianSlice<'static, gimli::LittleEndian>>,
        unit: &gimli::Unit<gimli::EndianSlice<'static, gimli::LittleEndian>>,
        entry: &gimli::DebuggingInformationEntry<gimli::EndianSlice<'static, gimli::LittleEndian>>,
    ) -> Result<TypeInfo> {
        // Get the underlying type
        let mut base_type_info = if let Some(type_attr) = entry.attr_value(gimli::DW_AT_type)
            .map_err(|e| CallTraceError::DwarfError(format!("Error reading const target type: {}", e)))?
        {
            if let gimli::AttributeValue::UnitRef(type_offset) = type_attr {
                self.extract_type_info_from_offset(dwarf, unit, type_offset)?
            } else {
                TypeInfo {
                    name: "unknown".to_string(),
                    size: None,
                    is_pointer: false,
                    is_const: false,
                    is_struct: false,
                    is_array: false,
                    array_size: None,
                    base_type: None,
                }
            }
        } else {
            TypeInfo {
                name: "unknown".to_string(),
                size: None,
                is_pointer: false,
                is_const: false,
                is_struct: false,
                is_array: false,
                array_size: None,
                base_type: None,
            }
        };

        // Mark as const and update name
        base_type_info.is_const = true;
        base_type_info.name = format!("const {}", base_type_info.name);

        Ok(base_type_info)
    }

    /// Extract typedef information
    #[cfg(feature = "dwarf_support")]
    fn extract_typedef_info(
        &mut self,
        dwarf: &Dwarf<gimli::EndianSlice<'static, gimli::LittleEndian>>,
        unit: &gimli::Unit<gimli::EndianSlice<'static, gimli::LittleEndian>>,
        entry: &gimli::DebuggingInformationEntry<gimli::EndianSlice<'static, gimli::LittleEndian>>,
    ) -> Result<TypeInfo> {
        // Extract typedef name
        let typedef_name = if let Some(name_attr) = entry.attr_value(gimli::DW_AT_name)
            .map_err(|e| CallTraceError::DwarfError(format!("Error reading typedef name: {}", e)))?
        {
            if let gimli::AttributeValue::DebugStrRef(offset) = name_attr {
                dwarf.debug_str.get_str(offset)
                    .map_err(|e| CallTraceError::DwarfError(format!("Error reading typedef string: {}", e)))?
                    .to_string_lossy().to_string()
            } else {
                "unknown_typedef".to_string()
            }
        } else {
            "unknown_typedef".to_string()
        };

        // Get the underlying type
        let mut base_type_info = if let Some(type_attr) = entry.attr_value(gimli::DW_AT_type)
            .map_err(|e| CallTraceError::DwarfError(format!("Error reading typedef target type: {}", e)))?
        {
            if let gimli::AttributeValue::UnitRef(type_offset) = type_attr {
                self.extract_type_info_from_offset(dwarf, unit, type_offset)?
            } else {
                TypeInfo {
                    name: "unknown".to_string(),
                    size: None,
                    is_pointer: false,
                    is_const: false,
                    is_struct: false,
                    is_array: false,
                    array_size: None,
                    base_type: None,
                }
            }
        } else {
            TypeInfo {
                name: "unknown".to_string(),
                size: None,
                is_pointer: false,
                is_const: false,
                is_struct: false,
                is_array: false,
                array_size: None,
                base_type: None,
            }
        };

        // Use the typedef name but preserve other type information
        base_type_info.name = typedef_name;

        Ok(base_type_info)
    }
    */

    /// Get program base address from /proc/self/maps
    fn get_program_base_address(&self) -> Option<u64> {
        use std::fs;

        let maps = fs::read_to_string("/proc/self/maps").ok()?;
        for line in maps.lines() {
            if line.contains(&self.executable_path) && line.contains("r-xp") {
                let parts: Vec<&str> = line.split('-').collect();
                if let Some(base_str) = parts.first() {
                    return u64::from_str_radix(base_str, 16).ok();
                }
            }
        }
        None
    }

    /// Create fallback function info using dladdr
    fn create_fallback_function_info(&self, address: u64) -> Result<FunctionInfo> {
        use libc::{dladdr, Dl_info};
        use std::ffi::CStr;

        let mut info: Dl_info = unsafe { std::mem::zeroed() };
        let result = unsafe { dladdr(address as *const c_void, &mut info) };

        let name = if result != 0 && !info.dli_sname.is_null() {
            let raw_name = unsafe {
                CStr::from_ptr(info.dli_sname)
                    .to_string_lossy()
                    .into_owned()
            };

            // Try to demangle C++ function names
            demangle_function_name(&raw_name)
        } else {
            format!("0x{:x}", address)
        };

        Ok(FunctionInfo {
            name,
            address,
            size: None,
            parameters: Vec::new(), // No parameter info available
            return_type: None,
            source_file: None,
            line_number: None,
        })
    }

    /// Get the number of cached functions
    pub fn cache_size(&self) -> usize {
        self.function_cache.len()
    }

    /// Clear the function cache
    pub fn clear_cache(&mut self) {
        self.function_cache.clear();
        self.type_cache.clear();
        self.symbol_cache.clear();
    }
}

impl Drop for DwarfAnalyzer {
    fn drop(&mut self) {
        // Clean up any resources
        self.clear_cache();
    }
}

/// Helper function to demangle C++ function names
pub fn demangle_function_name(mangled: &str) -> String {
    // Try multiple demangling approaches

    // First try: Use cxa_demangle from libc++abi
    if let Some(demangled) = try_cxa_demangle(mangled) {
        return demangled;
    }

    // Second try: Use external c++filt tool
    if let Some(demangled) = try_cppfilt_demangle(mangled) {
        return demangled;
    }

    // Fallback: Return original mangled name
    mangled.to_string()
}

/// Try to demangle using libc++abi's cxa_demangle function
fn try_cxa_demangle(mangled: &str) -> Option<String> {
    use std::ffi::{CStr, CString};
    use std::ptr;

    // Only process names that look like C++ mangled names
    if !mangled.starts_with("_Z") && !mangled.starts_with("__Z") {
        return None;
    }

    let c_mangled = CString::new(mangled).ok()?;
    let mut status: libc::c_int = 0;

    unsafe {
        // Try to get __cxa_demangle dynamically to avoid linking issues
        let cxa_demangle_fn = libc::dlsym(libc::RTLD_DEFAULT, c"__cxa_demangle".as_ptr());
        if cxa_demangle_fn.is_null() {
            // __cxa_demangle not available (e.g., in C programs without libstdc++)
            return None;
        }

        // Cast to the correct function pointer type
        type CxaDemangleFn = extern "C" fn(
            *const libc::c_char,
            *mut libc::c_char,
            *mut libc::size_t,
            *mut libc::c_int,
        ) -> *mut libc::c_char;

        let demangle_fn: CxaDemangleFn = std::mem::transmute(cxa_demangle_fn);

        let result = demangle_fn(
            c_mangled.as_ptr(),
            ptr::null_mut(),
            ptr::null_mut(),
            &mut status,
        );

        if status == 0 && !result.is_null() {
            let demangled_cstr = CStr::from_ptr(result);
            let demangled = demangled_cstr.to_string_lossy().into_owned();

            // Free the memory allocated by __cxa_demangle
            libc::free(result as *mut libc::c_void);

            Some(demangled)
        } else {
            None
        }
    }
}

/// Try to demangle using external c++filt tool
fn try_cppfilt_demangle(mangled: &str) -> Option<String> {
    use std::process::Command;

    // Only process names that look like C++ mangled names
    if !mangled.starts_with("_Z") && !mangled.starts_with("__Z") {
        return None;
    }

    // Try to run c++filt command
    let output = Command::new("c++filt").arg(mangled).output().ok()?;

    if output.status.success() {
        let demangled = String::from_utf8(output.stdout).ok()?;
        let trimmed = demangled.trim();

        // If c++filt actually demangled something, it should be different from input
        if trimmed != mangled && !trimmed.is_empty() {
            Some(trimmed.to_string())
        } else {
            None
        }
    } else {
        None
    }
}

/*
/// Extract type information from a DWARF DIE
#[cfg(feature = "dwarf_support")]
#[allow(dead_code)]
fn extract_type_info<R: Reader>(
    _dwarf: &Dwarf<R>,
    _unit: &gimli::Unit<R>,
    _entry: &DebuggingInformationEntry<R>,
) -> Result<TypeInfo> {
    // This would extract detailed type information from DWARF
    // Including struct layouts, array sizes, pointer levels, etc.

    Ok(TypeInfo {
        name: "unknown".to_string(),
        size: None,
        is_pointer: false,
        is_const: false,
        is_struct: false,
        is_array: false,
        array_size: None,
        base_type: None,
    })
}
*/