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
//! JSON Output Generation
//!
//! This module generates structured JSON output for call trees with full
//! argument information and thread relationships.

use crate::call_tree::{CallTreeManager, NodeId, ThreadCallTree};
use crate::error::{CallTraceError, Result};
use crate::register_reader::{ArgumentValue, CapturedArgument};
use libc;
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::Write;

/// Complete trace session output
#[derive(Debug, Serialize, Deserialize)]
pub struct TraceSession {
    pub metadata: SessionMetadata,
    pub threads: Vec<ThreadTrace>,
    pub thread_relationships: Vec<ThreadRelationship>,
    pub statistics: SessionStatistics,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub crash: Option<CrashInfo>,
}

/// Crash information for JSON output
#[derive(Debug, Serialize, Deserialize)]
pub struct CrashInfo {
    pub signal: i32,
    pub signal_name: String,
    pub thread_id: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fault_address: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub instruction_pointer: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stack_pointer: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub register_context: Option<crate::register_reader::RegisterContext>,
    pub backtrace: Vec<StackFrame>,
    pub crash_time: String,
    pub crash_timestamp: f64,
}

/// Stack frame for JSON output
#[derive(Debug, Serialize, Deserialize)]
pub struct StackFrame {
    pub address: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub function_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub library_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub offset: Option<String>,
}

/// Session metadata
#[derive(Debug, Serialize, Deserialize)]
pub struct SessionMetadata {
    pub start_time: String,
    pub end_time: String,
    pub duration_ms: f64,
    pub process_info: ProcessInfo,
    pub calltrace_version: String,
}

/// Process information
#[derive(Debug, Serialize, Deserialize)]
pub struct ProcessInfo {
    pub pid: u32,
    pub architecture: String,
    pub executable_path: Option<String>,
    pub environment_variables: std::collections::HashMap<String, String>,
}

/// Per-thread trace information
#[derive(Debug, Serialize, Deserialize)]
pub struct ThreadTrace {
    pub thread_id: u64,
    pub thread_name: String,
    pub is_main_thread: bool,
    pub start_time: String,
    pub end_time: Option<String>,
    pub parent_thread_id: Option<u64>,
    pub creation_function: Option<String>,
    pub statistics: ThreadStatistics,
    pub call_tree: Option<CallNodeJson>,
}

/// Thread relationship information for JSON
#[derive(Debug, Serialize, Deserialize)]
pub struct ThreadRelationship {
    pub parent_thread_id: u64,
    pub child_thread_id: u64,
    pub creation_function: String,
    pub creation_time: String,
}

/// Call tree node in JSON format
#[derive(Debug, Serialize, Deserialize)]
pub struct CallNodeJson {
    pub id: u32,
    pub function: String,
    pub address: String,
    pub call_site: String,
    pub start_time: String,
    pub end_time: Option<String>,
    pub duration_us: Option<u64>,
    pub call_depth: usize,
    pub signature: Option<String>,
    pub arguments: Vec<ArgumentJson>,
    pub return_value: Option<ArgumentValueJson>,
    pub children: Vec<CallNodeJson>,

    // Thread creation info
    pub is_pthread_create: bool,
    pub created_thread_id: Option<u64>,

    // Source location (if available)
    pub source_file: Option<String>,
    pub line_number: Option<u32>,
}

/// Function argument in JSON format
#[derive(Debug, Serialize, Deserialize)]
pub struct ArgumentJson {
    pub name: String,
    pub type_name: String,
    pub value: ArgumentValueJson,
    pub location: ArgumentLocationJson,
}

/// Argument value in JSON format
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type", content = "value")]
pub enum ArgumentValueJson {
    Integer(u64),
    Float(f32),
    Double(f64),
    Pointer {
        address: String,
        string_value: Option<String>,
    },
    String(String),
    Raw(String),    // Hex-encoded raw bytes
    Object(String), // Complex types (struct, array, union) as string description
    Error(String),
}

/// Argument location information
#[derive(Debug, Serialize, Deserialize)]
pub struct ArgumentLocationJson {
    pub class: String, // "integer", "sse", "memory"
    pub register_index: Option<usize>,
    pub stack_offset: Option<usize>,
    pub size: usize,
}

/// Thread statistics
#[derive(Debug, Serialize, Deserialize)]
pub struct ThreadStatistics {
    pub total_function_calls: u64,
    pub max_call_depth: usize,
    pub total_errors: u64,
}

/// Session statistics
#[derive(Debug, Serialize, Deserialize)]
pub struct SessionStatistics {
    pub total_threads: u64,
    pub total_function_calls: u64,
    pub total_nodes: u64,
    pub session_duration_us: u64,
}

/// JSON output generator
pub struct JsonOutputGenerator {
    pretty_print: bool,
    include_arguments: bool,
    include_source_info: bool,
}

impl JsonOutputGenerator {
    /// Create a new JSON output generator
    pub fn new() -> Self {
        Self {
            pretty_print: true,
            include_arguments: true,
            include_source_info: true,
        }
    }

    /// Configure output options
    pub fn configure(
        &mut self,
        pretty_print: bool,
        include_arguments: bool,
        include_source_info: bool,
    ) {
        self.pretty_print = pretty_print;
        self.include_arguments = include_arguments;
        self.include_source_info = include_source_info;
    }

    /// Generate JSON output from call tree manager
    pub fn generate_output(&self, manager: &CallTreeManager) -> Result<TraceSession> {
        let stats = manager.get_statistics();

        // Generate session metadata
        let current_time_us = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_micros() as u64;
        let session_start_us = current_time_us.saturating_sub(stats.session_duration_us);

        let metadata = SessionMetadata {
            start_time: format_timestamp(session_start_us),
            end_time: format_timestamp(current_time_us),
            duration_ms: stats.session_duration_us as f64 / 1000.0,
            process_info: ProcessInfo {
                pid: std::process::id(),
                architecture: crate::string_constants::X86_64.to_string(),
                executable_path: None, // Could be obtained from /proc/self/exe
                environment_variables: collect_environment_variables(),
            },
            calltrace_version: env!("CARGO_PKG_VERSION").to_string(),
        };

        // Generate thread traces
        let mut threads = Vec::new();
        let thread_ids = manager.get_thread_ids();

        for thread_id in thread_ids {
            if let Some(thread_tree) = manager.get_thread_tree(thread_id) {
                let tree = thread_tree.read().unwrap();
                let thread_trace = self.generate_thread_trace(&tree, manager)?;
                threads.push(thread_trace);
            }
        }

        // Generate thread relationships
        let thread_relationships = Vec::new(); // TODO: Extract from manager

        // Generate session statistics
        let session_stats = SessionStatistics {
            total_threads: stats.total_threads,
            total_function_calls: 0, // TODO: Sum from all threads
            total_nodes: stats.total_nodes,
            session_duration_us: stats.session_duration_us,
        };

        Ok(TraceSession {
            metadata,
            threads,
            thread_relationships,
            statistics: session_stats,
            crash: None,
        })
    }

    /// Generate trace information for a single thread
    fn generate_thread_trace(
        &self,
        thread_tree: &ThreadCallTree,
        manager: &CallTreeManager,
    ) -> Result<ThreadTrace> {
        let call_tree = if let Some(root_id) = thread_tree.root_node {
            self.generate_call_node_json(root_id, manager)?
        } else {
            None
        };

        Ok(ThreadTrace {
            thread_id: thread_tree.thread_id,
            thread_name: thread_tree.thread_name.clone(),
            is_main_thread: thread_tree.is_main_thread,
            start_time: format_timestamp(thread_tree.start_time),
            end_time: thread_tree.end_time.map(format_timestamp),
            parent_thread_id: thread_tree.parent_thread_id,
            creation_function: thread_tree.creation_function.clone(),
            statistics: ThreadStatistics {
                total_function_calls: thread_tree.total_calls,
                max_call_depth: thread_tree.max_depth,
                total_errors: thread_tree.total_errors,
            },
            call_tree,
        })
    }

    /// Generate JSON representation of a call node and its children
    fn generate_call_node_json(
        &self,
        node_id: NodeId,
        manager: &CallTreeManager,
    ) -> Result<Option<CallNodeJson>> {
        let node_ref = manager.get_any_node(node_id).ok_or_else(|| {
            CallTraceError::InvalidArgument(format!("Node {} not found", node_id))
        })?;

        let node = node_ref.read().unwrap();

        // Generate arguments JSON
        let arguments = if self.include_arguments {
            node.arguments
                .iter()
                .map(|arg| self.convert_argument_to_json(arg))
                .collect()
        } else {
            Vec::new()
        };

        // Generate return value JSON
        let return_value = if self.include_arguments {
            node.return_value
                .as_ref()
                .map(|rv| self.convert_return_value_to_json(rv))
        } else {
            None
        };

        // Generate children recursively
        let mut children = Vec::new();
        for &child_id in &node.children {
            if let Some(child_json) = self.generate_call_node_json(child_id, manager)? {
                children.push(child_json);
            }
        }

        // Extract source information if available
        let (source_file, line_number) = if self.include_source_info {
            node.function_info.as_ref().map_or((None, None), |info| {
                (info.source_file.clone(), info.line_number)
            })
        } else {
            (None, None)
        };

        // Use function name if available, otherwise keep the address but make it cleaner
        let function_display_name = if !node.function_name.starts_with("0x") {
            // We have a real function name from DWARF or dladdr
            node.function_name.clone()
        } else {
            // For addresses, try to make them more readable by showing offset from base
            crate::format_address_with_prefix("func", node.function_address & 0xFFFF)
        };

        Ok(Some(CallNodeJson {
            id: node.id,
            function: function_display_name,
            address: crate::format_address(node.function_address),
            call_site: crate::format_address(node.call_site),
            start_time: format_timestamp(node.start_time),
            end_time: node.end_time.map(format_timestamp),
            duration_us: node.duration_us,
            call_depth: node.call_depth,
            signature: node.function_info.as_ref().map(|_| "TODO".to_string()), // TODO: Extract signature
            arguments,
            return_value,
            children,
            is_pthread_create: node.is_pthread_create,
            created_thread_id: node.created_thread_id,
            source_file,
            line_number,
        }))
    }

    /// Convert a return value to JSON format
    fn convert_return_value_to_json(&self, return_value: &ArgumentValue) -> ArgumentValueJson {
        match return_value {
            ArgumentValue::Integer(val) => ArgumentValueJson::Integer(*val),
            ArgumentValue::Float(val) => ArgumentValueJson::Float(*val),
            ArgumentValue::Double(val) => ArgumentValueJson::Double(*val),
            ArgumentValue::Pointer(addr) => ArgumentValueJson::Pointer {
                address: crate::format_address(*addr),
                string_value: None, // TODO: Extract string value if available
            },
            ArgumentValue::String(s) => ArgumentValueJson::String(s.clone()),
            ArgumentValue::Raw(bytes) => ArgumentValueJson::Raw(hex::encode(bytes)),
            ArgumentValue::Struct {
                type_name,
                members: _,
                size,
            } => {
                // TODO: Full struct serialization
                ArgumentValueJson::Object(format!("struct {} (size: {})", type_name, size))
            }
            ArgumentValue::Array {
                element_type,
                elements: _,
                count,
                element_size,
            } => {
                // TODO: Full array serialization
                ArgumentValueJson::Object(format!(
                    "{}[{}] (element_size: {})",
                    element_type, count, element_size
                ))
            }
            ArgumentValue::Union {
                type_name,
                raw_data: _,
                size,
            } => ArgumentValueJson::Object(format!("union {} (size: {})", type_name, size)),
            ArgumentValue::Null => ArgumentValueJson::Pointer {
                address: crate::string_constants::NULL_ADDRESS.to_string(),
                string_value: Some(crate::string_constants::NULL_STRING.to_string()),
            },
            ArgumentValue::Unknown {
                type_name,
                raw_data,
                error,
            } => {
                let error_info = error
                    .as_ref()
                    .map(|e| format!(": {}", e))
                    .unwrap_or_default();
                ArgumentValueJson::Object(format!(
                    "unknown {} (size: {}){}",
                    type_name,
                    raw_data.len(),
                    error_info
                ))
            }
        }
    }

    /// Convert a captured argument to JSON format
    fn convert_argument_to_json(&self, arg: &CapturedArgument) -> ArgumentJson {
        let value_json = if arg.valid {
            match &arg.value {
                ArgumentValue::Integer(val) => ArgumentValueJson::Integer(*val),
                ArgumentValue::Float(val) => ArgumentValueJson::Float(*val),
                ArgumentValue::Double(val) => ArgumentValueJson::Double(*val),
                ArgumentValue::Pointer(addr) => ArgumentValueJson::Pointer {
                    address: crate::format_address(*addr),
                    string_value: None, // TODO: Extract string value if available
                },
                ArgumentValue::String(s) => ArgumentValueJson::String(s.clone()),
                ArgumentValue::Raw(bytes) => ArgumentValueJson::Raw(hex::encode(bytes)),
                ArgumentValue::Struct {
                    type_name,
                    members: _,
                    size,
                } => {
                    // TODO: Full struct serialization
                    ArgumentValueJson::Object(format!("struct {} (size: {})", type_name, size))
                }
                ArgumentValue::Array {
                    element_type,
                    elements: _,
                    count,
                    element_size,
                } => {
                    // TODO: Full array serialization
                    ArgumentValueJson::Object(format!(
                        "{}[{}] (element_size: {})",
                        element_type, count, element_size
                    ))
                }
                ArgumentValue::Union {
                    type_name,
                    raw_data: _,
                    size,
                } => ArgumentValueJson::Object(format!("union {} (size: {})", type_name, size)),
                ArgumentValue::Null => ArgumentValueJson::Pointer {
                    address: crate::string_constants::NULL_ADDRESS.to_string(),
                    string_value: Some(crate::string_constants::NULL_STRING.to_string()),
                },
                ArgumentValue::Unknown {
                    type_name,
                    raw_data,
                    error,
                } => {
                    let error_info = error
                        .as_ref()
                        .map(|e| format!(": {}", e))
                        .unwrap_or_default();
                    ArgumentValueJson::Object(format!(
                        "unknown {} (size: {}){}",
                        type_name,
                        raw_data.len(),
                        error_info
                    ))
                }
            }
        } else {
            ArgumentValueJson::Error(
                arg.error
                    .clone()
                    .unwrap_or_else(|| crate::string_constants::UNKNOWN_ERROR.to_string()),
            )
        };

        ArgumentJson {
            name: arg.name.clone(),
            type_name: arg.type_name.clone(),
            value: value_json,
            location: ArgumentLocationJson {
                class: format!("{:?}", arg.location.class).to_lowercase(),
                register_index: arg.location.register_index,
                stack_offset: arg.location.stack_offset,
                size: arg.location.size,
            },
        }
    }

    /// Write JSON output to file
    pub fn write_to_file(&self, trace_session: &TraceSession, file_path: &str) -> Result<()> {
        let mut file = File::create(file_path)
            .map_err(|e| CallTraceError::JsonError(serde_json::Error::io(e)))?;

        if self.pretty_print {
            let json_string = serde_json::to_string_pretty(trace_session)?;
            file.write_all(json_string.as_bytes())
                .map_err(|e| CallTraceError::JsonError(serde_json::Error::io(e)))?;
        } else {
            serde_json::to_writer(&mut file, trace_session)?;
        }

        Ok(())
    }

    /// Generate JSON string
    pub fn to_string(&self, trace_session: &TraceSession) -> Result<String> {
        if self.pretty_print {
            serde_json::to_string_pretty(trace_session).map_err(CallTraceError::JsonError)
        } else {
            serde_json::to_string(trace_session).map_err(CallTraceError::JsonError)
        }
    }
}

impl Default for JsonOutputGenerator {
    fn default() -> Self {
        Self::new()
    }
}

/// Get function name from address using dladdr (currently unused)
#[allow(dead_code)]
fn get_function_name_from_address(address: u64) -> Option<String> {
    use libc::{dladdr, Dl_info};
    use std::ffi::{c_void, CStr};

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

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

            // Try to demangle C++ names
            Some(demangle_function_name(&name))
        }
    } else {
        None
    }
}

/// Simple C++ name demangling
#[allow(dead_code)]
fn demangle_function_name(mangled: &str) -> String {
    // Basic demangling for common patterns
    if mangled.starts_with("_Z") {
        // This is a mangled C++ name - in a real implementation,
        // you'd use a proper demangling library
        mangled.to_string() // Keep mangled for now
    } else {
        mangled.to_string()
    }
}

/// Format timestamp as human-readable string
fn format_timestamp(timestamp_us: u64) -> String {
    if timestamp_us == 0 {
        return "0".to_string();
    }

    // Convert microseconds to seconds and remaining microseconds
    let seconds = timestamp_us / 1_000_000;
    let microseconds = timestamp_us % 1_000_000;

    // Format as "seconds.microseconds"
    if microseconds == 0 {
        format!("{}", seconds)
    } else {
        format!("{}.{:06}", seconds, microseconds)
    }
}

/// Collect important environment variables for debugging and analysis
fn collect_environment_variables() -> std::collections::HashMap<String, String> {
    let mut env_vars = std::collections::HashMap::new();

    // Important system environment variables
    let important_vars = [
        "PATH",
        "LD_LIBRARY_PATH",
        "LD_PRELOAD",
        "USER",
        "HOME",
        "SHELL",
        "LANG",
        "LC_ALL",
        "LC_CTYPE",
        "TERM",
        "DISPLAY",
        "PWD",
        "TMPDIR",
        "TMP",
        "TEMP",
        // CallTrace specific variables
        "CALLTRACE_OUTPUT",
        "CALLTRACE_CAPTURE_ARGS",
        "CALLTRACE_MAX_DEPTH",
        "CALLTRACE_PRETTY_JSON",
        "CALLTRACE_DEBUG",
        "CALLTRACE_FILTER",
        // Common development variables
        "CARGO_TARGET_DIR",
        "RUST_LOG",
        "RUST_BACKTRACE",
        "DEBUG",
        "VERBOSE",
        // Build and compilation variables
        "CC",
        "CXX",
        "CFLAGS",
        "CXXFLAGS",
        "LDFLAGS",
    ];

    // Collect the specified important variables
    for var_name in &important_vars {
        if let Ok(value) = std::env::var(var_name) {
            env_vars.insert(var_name.to_string(), value);
        }
    }

    // Also collect any variables that start with CALLTRACE_ that weren't in the list above
    for (key, value) in std::env::vars() {
        if key.starts_with("CALLTRACE_") && !env_vars.contains_key(&key) {
            env_vars.insert(key, value);
        }
    }

    // Limit the number of environment variables to prevent excessive output
    const MAX_ENV_VARS: usize = 50;
    if env_vars.len() > MAX_ENV_VARS {
        // Keep only the first MAX_ENV_VARS items (important ones are added first)
        let mut limited_vars = std::collections::HashMap::new();
        for (key, value) in env_vars.into_iter().take(MAX_ENV_VARS) {
            limited_vars.insert(key, value);
        }
        env_vars = limited_vars;
    }

    env_vars
}

/// Add hex dependency for raw byte encoding
#[allow(dead_code)]
mod hex {
    pub fn encode(bytes: &[u8]) -> String {
        bytes.iter().map(|b| format!("{:02x}", b)).collect()
    }
}