ghostscope-compiler 0.1.5

Compiles GhostScope trace definitions into DWARF-aware eBPF programs ready for injection.
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
use crate::script::ast::{Program, Statement, TracePattern};
use crate::CompileError;
// BinaryAnalyzer is now internal to ghostscope-binary, use DwarfAnalyzer instead
use ghostscope_dwarf::ModuleDefaultPolicy;
use inkwell::context::Context;
use std::borrow::Cow;
use std::collections::hash_map::DefaultHasher;
use std::fmt::Write as _;
use std::hash::{Hash, Hasher};
use tracing::{debug, error, info, warn};

/// Resolved target information from DWARF queries
#[derive(Debug, Clone)]
pub struct ResolvedTarget {
    pub function_name: Option<String>,
    pub function_address: Option<u64>,
    pub binary_path: String,
    pub uprobe_offset: Option<u64>,
    pub pattern: TracePattern,
}

/// Complete uprobe configuration ready for attachment
#[derive(Debug, Clone)]
pub struct UProbeConfig {
    /// The trace pattern this uprobe corresponds to
    pub trace_pattern: TracePattern,

    /// Target binary path
    pub binary_path: String,

    /// Function name (for FunctionName patterns)
    pub function_name: Option<String>,

    /// Resolved function address in the binary
    pub function_address: Option<u64>,

    /// Calculated uprobe offset (for aya uprobe attachment)
    pub uprobe_offset: Option<u64>,

    /// Process ID to attach to (None means attach to all instances)
    pub target_pid: Option<u32>,

    /// eBPF bytecode for this uprobe
    pub ebpf_bytecode: Vec<u8>,

    /// eBPF function name for this uprobe (e.g., "ghostscope_main_0", "ghostscope_printf_1")
    pub ebpf_function_name: String,

    /// Trace ID assigned by compiler (starts from starting_trace_id and increments)
    pub assigned_trace_id: u32,

    /// Trace context containing all strings, types, and variable names used in this uprobe
    pub trace_context: ghostscope_protocol::TraceContext,

    /// BPF-facing compact DWARF CFI rows used by the `bt` unwinder.
    pub backtrace_unwind_rows: Vec<ghostscope_protocol::BacktraceUnwindRow>,

    /// Module cookie to row range entries used by the `bt` unwinder.
    pub backtrace_module_row_ranges: Vec<(u64, ghostscope_protocol::BacktraceModuleRowRange)>,

    /// Optional eBPF tail-call step program used by the `bt` unwinder.
    pub backtrace_tail_call_program: Option<crate::ebpf::context::BacktraceTailCallProgram>,

    /// Global 1-based index of this address within the resolved target list (if applicable)
    pub resolved_address_index: Option<usize>,
}

/// Compilation result containing all uprobe configurations
#[derive(Debug)]
pub struct CompilationResult {
    pub uprobe_configs: Vec<UProbeConfig>,
    pub trace_count: usize,
    pub target_info: String,
    pub failed_targets: Vec<FailedTarget>, // New field for failed compilation info
    pub next_available_trace_id: u32,      // Next trace_id that can be used by trace_manager
}

/// Information about a target that failed to compile
#[derive(Debug, Clone)]
pub struct FailedTarget {
    pub target_name: String,
    pub pc_address: u64,
    pub error_message: String,
}

/// Unified AST compiler that performs DWARF queries and code generation in single pass
pub struct AstCompiler<'a> {
    process_analyzer: Option<&'a ghostscope_dwarf::DwarfAnalyzer>,
    uprobe_configs: Vec<UProbeConfig>,
    failed_targets: Vec<FailedTarget>, // Track failed compilation attempts
    binary_path_hint: Option<String>,
    current_trace_id: u32, // Current trace_id counter (increments for each uprobe)
    compile_options: crate::CompileOptions, // Compilation options (save + eBPF map config)
}

impl<'a> AstCompiler<'a> {
    pub fn new(
        process_analyzer: Option<&'a ghostscope_dwarf::DwarfAnalyzer>,
        binary_path_hint: Option<String>,
        starting_trace_id: u32,
        compile_options: crate::CompileOptions,
    ) -> Self {
        Self {
            process_analyzer,
            uprobe_configs: Vec::new(),
            failed_targets: Vec::new(),
            binary_path_hint,
            current_trace_id: starting_trace_id,
            compile_options,
        }
    }

    /// Main entry point: compile AST with integrated DWARF queries and code generation
    pub fn compile_program(
        &mut self,
        program: &Program,
        pid: Option<u32>,
    ) -> Result<CompilationResult, CompileError> {
        info!(
            "Starting unified AST compilation with {} statements",
            program.statements.len()
        );

        // AST will be saved immediately when we know the target details in generate_ebpf_for_target

        if program.statements.is_empty() {
            return Err(CompileError::Other(
                "script must contain at least one top-level trace statement".to_string(),
            ));
        }

        // Single-pass traversal: process each statement immediately
        // Continue processing even if some trace points fail
        let mut successful_trace_points = 0;
        let mut failed_trace_points = 0;
        let mut first_error: Option<String> = None;

        for (index, stmt) in program.statements.iter().enumerate() {
            match stmt {
                Statement::TracePoint { pattern, body } => {
                    debug!("Processing trace point {}: {:?}", index, pattern);
                    match self.process_trace_point(pattern, body, pid, index) {
                        Ok(_) => {
                            successful_trace_points += 1;
                            info!(
                                "✓ Successfully processed trace point {}: {:?}",
                                index, pattern
                            );
                        }
                        Err(e) => {
                            failed_trace_points += 1;
                            let error_msg = e.user_message().into_owned();
                            error!(
                                "❌ Failed to process trace point {}: {:?} - Error: {}",
                                index, pattern, error_msg
                            );

                            // Save first error for detailed error message
                            if first_error.is_none() {
                                first_error = Some(error_msg.clone());
                            }

                            // Check if failed_targets was already populated by process_trace_point
                            // (e.g., when all addresses failed for a function)
                            // If not, add a general failed target entry
                            let has_failed_for_this_pattern =
                                self.failed_targets.iter().any(|ft| match pattern {
                                    TracePattern::FunctionName(name) => ft.target_name == *name,
                                    TracePattern::SourceLine {
                                        file_path,
                                        line_number,
                                    } => ft.target_name == format!("{file_path}:{line_number}"),
                                    TracePattern::Address(addr) => {
                                        ft.target_name == format!("0x{addr:x}")
                                            && ft.pc_address == *addr
                                    }
                                    TracePattern::AddressInModule { module, address } => {
                                        ft.target_name == format!("{module}:0x{address:x}")
                                            && ft.pc_address == *address
                                    }
                                    _ => false,
                                });

                            if !has_failed_for_this_pattern {
                                let target_name = match pattern {
                                    TracePattern::FunctionName(name) => name.clone(),
                                    TracePattern::SourceLine {
                                        file_path,
                                        line_number,
                                    } => format!("{file_path}:{line_number}"),
                                    TracePattern::Address(addr) => format!("0x{addr:x}"),
                                    TracePattern::AddressInModule { module, address } => {
                                        format!("{module}:0x{address:x}")
                                    }
                                    _ => format!("trace_point_{index}"),
                                };
                                let pc_address = match pattern {
                                    TracePattern::Address(addr) => *addr,
                                    TracePattern::AddressInModule { address, .. } => *address,
                                    _ => 0,
                                };

                                self.failed_targets.push(FailedTarget {
                                    target_name,
                                    pc_address,
                                    error_message: error_msg,
                                });
                            }
                        }
                    }
                }
                _ => {
                    let message = Self::top_level_statement_error(stmt);
                    error!("{message}");
                    return Err(CompileError::Other(message));
                }
            }
        }

        if successful_trace_points > 0 && failed_trace_points == 0 {
            info!(
                "All {} trace points processed successfully",
                successful_trace_points
            );
        } else if successful_trace_points > 0 && failed_trace_points > 0 {
            warn!(
                "Partial success: {} trace points successful, {} failed",
                successful_trace_points, failed_trace_points
            );
        } else if failed_trace_points > 0 {
            // All trace points failed - return error with first failure reason
            error!("All {} trace points failed to process", failed_trace_points);
            return Err(CompileError::Other(
                self.format_all_trace_points_failed_error(first_error),
            ));
        }

        // Generate target info summary
        let target_info = self.generate_target_info_summary();

        info!(
            "Compilation completed: {} uprobe configs generated",
            self.uprobe_configs.len()
        );

        let trace_count = self.uprobe_configs.len();
        Ok(CompilationResult {
            uprobe_configs: std::mem::take(&mut self.uprobe_configs),
            failed_targets: std::mem::take(&mut self.failed_targets),
            trace_count,
            target_info,
            next_available_trace_id: self.current_trace_id,
        })
    }

    fn format_all_trace_points_failed_error(&self, first_error: Option<String>) -> String {
        let mut message = first_error.unwrap_or_else(|| "All trace points failed".to_string());
        if self.failed_targets.is_empty() {
            return message;
        }

        message.push_str("\n\nFailed targets:\n");
        for failed in &self.failed_targets {
            let _ = writeln!(
                message,
                "  - {} at 0x{:x}: {}",
                failed.target_name, failed.pc_address, failed.error_message
            );
        }
        message.push_str("\nTip: fix the reported compile-time errors above.");
        message
    }

    fn configured_target_path(&self) -> Option<&str> {
        self.compile_options
            .target_binary_path
            .as_deref()
            .map(str::trim)
            .filter(|path| !path.is_empty())
    }

    fn top_level_statement_error(statement: &Statement) -> String {
        let kind = match statement {
            Statement::Print(_) => "print",
            Statement::Backtrace(_) => "backtrace",
            Statement::Expr(_) => "expression",
            Statement::VarDeclaration { .. } | Statement::AliasDeclaration { .. } => "let",
            Statement::If { .. } => "if",
            Statement::Block(_) => "block",
            Statement::TracePoint { .. } => "trace",
        };
        format!(
            "top-level {kind} statement is not allowed in a script file; put executable statements inside a trace block, for example: trace <target> {{ ... }}"
        )
    }

    /// Process a trace point: resolve target + generate eBPF in one step
    fn process_trace_point(
        &mut self,
        pattern: &TracePattern,
        statements: &[Statement],
        pid: Option<u32>,
        index: usize,
    ) -> Result<(), CompileError> {
        match pattern {
            TracePattern::SourceLine {
                file_path,
                line_number,
            } => {
                let analyzer = self.process_analyzer.ok_or_else(|| {
                    CompileError::Other(
                        "No process analyzer available to resolve source line".to_string(),
                    )
                })?;
                let target_path = self.configured_target_path();
                let source_line = analyzer
                    .resolve_source_line_addresses_best_effort(
                        analyzer.source_line_candidates(file_path),
                        *line_number,
                        target_path,
                    )
                    .map_err(|e| CompileError::Other(e.to_string()))?;
                let module_addresses = source_line.addresses;

                if source_line.raw_address_count > 0 && module_addresses.is_empty() {
                    let target = target_path.unwrap_or("<unknown>");
                    return Err(CompileError::Other(format!(
                        "No addresses resolved for source line {file_path}:{line_number} in -t target '{target}'. When -t and -p are combined, -t takes precedence for trace target resolution."
                    )));
                }
                if module_addresses.is_empty() {
                    let detailed = analyzer.describe_source_line_failure(file_path, *line_number);
                    return Err(CompileError::Other(detailed));
                }

                debug!(
                    "Resolved {}:{} to {} address(es) for trace point {}",
                    file_path,
                    line_number,
                    module_addresses.len(),
                    index
                );

                // Validate optional single-index selection (1-based)
                if let Some(idx) = self.compile_options.selected_index {
                    if idx == 0 || idx > module_addresses.len() {
                        return Err(CompileError::Other(format!(
                            "Selected index {idx} is out of range for {file_path}:{line_number} (valid 1..={}). Use 'info' to view indices.",
                            module_addresses.len()
                        )));
                    }
                }

                // Optional single-index filter (1-based); otherwise process all
                let mut successful_addresses = 0;
                let mut failed_addresses = 0;
                // Iterate with indices (1-based) so we can propagate the global address index
                let iterator: Box<dyn Iterator<Item = (usize, &ghostscope_dwarf::ModuleAddress)>> =
                    if let Some(idx) = self.compile_options.selected_index {
                        let i = idx - 1; // safe due to validation above
                        Box::new(std::iter::once((idx, &module_addresses[i])))
                    } else {
                        Box::new(module_addresses.iter().enumerate().map(|(i, m)| (i + 1, m)))
                    };

                for (global_idx, module_address) in iterator {
                    // Convert DWARF PC (vaddr) to ELF file offset for uprobe
                    let file_off = self.process_analyzer.as_ref().and_then(|an| {
                        an.vaddr_to_file_offset(&module_address.module_path, module_address.address)
                    });

                    let target_info = ResolvedTarget {
                        function_name: Some(format!("{file_path}:{line_number}")),
                        // Keep function_address as DWARF PC for compile-time DWARF queries
                        function_address: Some(module_address.address),
                        binary_path: module_address.module_path.to_string_lossy().to_string(),
                        // Attach with absolute file offset if conversion succeeded
                        uprobe_offset: file_off,
                        pattern: pattern.clone(),
                    };

                    match self.generate_ebpf_for_target(
                        &target_info,
                        statements,
                        pid,
                        Some(global_idx),
                    ) {
                        Ok(uprobe_config) => {
                            self.uprobe_configs.push(uprobe_config);
                            successful_addresses += 1;
                            info!(
                                "✓ Successfully generated eBPF for {}:{} at 0x{:x}",
                                file_path, line_number, module_address.address
                            );
                        }
                        Err(e) => {
                            failed_addresses += 1;
                            error!(
                                "❌ Failed to generate eBPF for {}:{} at 0x{:x}: {}",
                                file_path, line_number, module_address.address, e
                            );

                            // Record this failed target
                            self.failed_targets.push(FailedTarget {
                                target_name: format!("{file_path}:{line_number}"),
                                pc_address: module_address.address,
                                error_message: e.user_message().into_owned(),
                            });

                            // Continue processing other addresses
                        }
                    }
                }

                // Log summary for this trace point
                if successful_addresses > 0 && failed_addresses == 0 {
                    info!(
                        "All {} addresses for {}:{} processed successfully",
                        successful_addresses, file_path, line_number
                    );
                } else if successful_addresses > 0 && failed_addresses > 0 {
                    warn!(
                        "Partial success for {}:{}: {} successful, {} failed addresses",
                        file_path, line_number, successful_addresses, failed_addresses
                    );
                } else {
                    error!(
                        "All {} addresses for {}:{} failed to process",
                        failed_addresses, file_path, line_number
                    );
                    // Don't return error here - let the caller decide based on overall results
                }
                Ok(())
            }
            TracePattern::Address(addr) => {
                let analyzer = self.process_analyzer.ok_or_else(|| {
                    CompileError::Other(
                        "No process analyzer available to resolve address".to_string(),
                    )
                })?;
                let module_path = analyzer
                    .resolve_address_module(
                        None,
                        self.configured_target_path(),
                        ModuleDefaultPolicy::MainExecutableOrSingleSharedLibrary,
                    )
                    .map_err(|e| CompileError::Other(e.to_string()))?;

                // Convert DWARF PC (vaddr) to ELF file offset for uprobe
                let file_off = analyzer.vaddr_to_file_offset(&module_path, *addr);
                let module_path = module_path.to_string_lossy().to_string();

                if file_off.is_none() {
                    return Err(CompileError::Other(format!(
                        "Address 0x{addr:x} is not within a loadable segment of '{module_path}' (cannot compute file offset)"
                    )));
                }

                let target_info = ResolvedTarget {
                    function_name: None,
                    function_address: Some(*addr),
                    binary_path: module_path,
                    uprobe_offset: file_off,
                    pattern: pattern.clone(),
                };

                match self.generate_ebpf_for_target(&target_info, statements, pid, None) {
                    Ok(uprobe_config) => {
                        self.uprobe_configs.push(uprobe_config);
                        info!("✓ Successfully generated eBPF for address 0x{:x}", addr);
                        Ok(())
                    }
                    Err(e) => {
                        let error_msg = e.user_message().into_owned();
                        error!(
                            "❌ Failed to generate eBPF for address 0x{:x}: {}",
                            addr, error_msg
                        );
                        self.failed_targets.push(FailedTarget {
                            target_name: format!("0x{addr:x}"),
                            pc_address: *addr,
                            error_message: error_msg,
                        });
                        Err(e)
                    }
                }
            }
            TracePattern::AddressInModule { module, address } => {
                let analyzer = self.process_analyzer.ok_or_else(|| {
                    CompileError::Other(
                        "No process analyzer available to resolve module".to_string(),
                    )
                })?;
                let module_path = analyzer
                    .resolve_address_module(
                        Some(module),
                        self.configured_target_path(),
                        ModuleDefaultPolicy::MainExecutableOrSingleSharedLibrary,
                    )
                    .map_err(|e| CompileError::Other(e.to_string()))?;

                // Convert DWARF PC (vaddr) to ELF file offset for uprobe
                let file_off = analyzer.vaddr_to_file_offset(&module_path, *address);
                let module_path = module_path.to_string_lossy().to_string();

                if file_off.is_none() {
                    return Err(CompileError::Other(format!(
                        "Address 0x{address:x} is not within a loadable segment of '{module_path}' (cannot compute file offset)"
                    )));
                }

                let target_info = ResolvedTarget {
                    function_name: None,
                    function_address: Some(*address),
                    binary_path: module_path,
                    uprobe_offset: file_off,
                    pattern: pattern.clone(),
                };

                match self.generate_ebpf_for_target(&target_info, statements, pid, None) {
                    Ok(uprobe_config) => {
                        self.uprobe_configs.push(uprobe_config);
                        info!(
                            "✓ Successfully generated eBPF for module-qualified address {}:0x{:x}",
                            module, address
                        );
                        Ok(())
                    }
                    Err(e) => {
                        let error_msg = e.user_message().into_owned();
                        error!(
                            "❌ Failed to generate eBPF for module-qualified address {}:0x{:x}: {}",
                            module, address, error_msg
                        );
                        self.failed_targets.push(FailedTarget {
                            target_name: format!("{module}:0x{address:x}"),
                            pc_address: *address,
                            error_message: error_msg,
                        });
                        Err(e)
                    }
                }
            }
            TracePattern::FunctionName(func_name) => {
                // Resolve all addresses for the function name and generate per-PC programs
                let module_addresses = if let Some(analyzer) = self.process_analyzer {
                    analyzer.lookup_function_addresses(func_name)
                } else {
                    Vec::new()
                };

                if module_addresses.is_empty() {
                    // Strict behavior: fail this trace point immediately instead of skipping silently
                    return Err(CompileError::Other(format!(
                        "No addresses resolved for function '{func_name}' - function not found in debug symbols"
                    )));
                }

                let original_address_count = module_addresses.len();
                let target_path = self.configured_target_path();
                let module_addresses = self
                    .process_analyzer
                    .ok_or_else(|| {
                        CompileError::Other(
                            "No process analyzer available to resolve -t target".to_string(),
                        )
                    })?
                    .filter_module_addresses_to_target(module_addresses, target_path)
                    .map_err(|e| CompileError::Other(e.to_string()))?;
                if original_address_count > 0 && module_addresses.is_empty() {
                    let target = target_path.unwrap_or("<unknown>");
                    return Err(CompileError::Other(format!(
                        "No addresses resolved for function '{func_name}' in -t target '{target}'. When -t and -p are combined, -t takes precedence for trace target resolution."
                    )));
                }

                let total_addresses: usize = module_addresses.len();
                debug!(
                    "Resolved function '{}' to {} address(es) across {} modules",
                    func_name,
                    total_addresses,
                    module_addresses.len()
                );

                // Validate optional single-index selection (1-based)
                if let Some(idx) = self.compile_options.selected_index {
                    if idx == 0 || idx > module_addresses.len() {
                        return Err(CompileError::Other(format!(
                            "Selected index {idx} is out of range for function '{func_name}' (valid 1..={}). Use 'info function {func_name}' to view indices.",
                            module_addresses.len()
                        )));
                    }
                }

                // We may need analyzer again to compute precise uprobe offsets
                // Optional single-index filter (1-based); otherwise process all addresses
                let mut successful_addresses = 0;
                let mut failed_addresses = 0;

                // Iterate with indices (1-based) so we can propagate the global address index
                let iterator: Box<dyn Iterator<Item = (usize, &ghostscope_dwarf::ModuleAddress)>> =
                    if let Some(idx) = self.compile_options.selected_index {
                        let i = idx - 1; // safe due to validation above
                        Box::new(std::iter::once((idx, &module_addresses[i])))
                    } else {
                        Box::new(module_addresses.iter().enumerate().map(|(i, m)| (i + 1, m)))
                    };

                for (global_idx, module_address) in iterator {
                    // Convert DWARF function address (vaddr) to ELF file offset for uprobe attach
                    let file_off = self.process_analyzer.as_ref().and_then(|an| {
                        an.vaddr_to_file_offset(&module_address.module_path, module_address.address)
                    });

                    let target_info = ResolvedTarget {
                        function_name: Some(func_name.clone()),
                        function_address: Some(module_address.address),
                        binary_path: module_address.module_path.to_string_lossy().to_string(),
                        uprobe_offset: file_off,
                        pattern: pattern.clone(),
                    };

                    match self.generate_ebpf_for_target(
                        &target_info,
                        statements,
                        pid,
                        Some(global_idx),
                    ) {
                        Ok(uprobe_config) => {
                            self.uprobe_configs.push(uprobe_config);
                            successful_addresses += 1;
                            info!(
                                "✓ Successfully generated eBPF for function '{}' at 0x{:x}",
                                func_name, module_address.address
                            );
                        }
                        Err(e) => {
                            failed_addresses += 1;
                            error!(
                                "❌ Failed to generate eBPF for function '{}' at 0x{:x}: {}",
                                func_name, module_address.address, e
                            );

                            // Record this failed target
                            self.failed_targets.push(FailedTarget {
                                target_name: func_name.clone(),
                                pc_address: module_address.address,
                                error_message: e.user_message().into_owned(),
                            });

                            // Continue processing other addresses
                        }
                    }
                }

                // Log summary for this trace point
                if successful_addresses > 0 && failed_addresses == 0 {
                    info!(
                        "All {} addresses for function '{}' processed successfully",
                        successful_addresses, func_name
                    );
                    Ok(())
                } else if successful_addresses > 0 && failed_addresses > 0 {
                    warn!(
                        "Partial success for function '{}': {} successful, {} failed addresses",
                        func_name, successful_addresses, failed_addresses
                    );
                    Ok(())
                } else {
                    // All addresses failed to process — record failures already captured above
                    // Defer final error shaping to the caller based on aggregated results
                    error!(
                        "All {} addresses for function '{}' failed to process",
                        failed_addresses, func_name
                    );
                    Ok(())
                }
            }
            _ => {
                unimplemented!();
            }
        }
    }

    /// Generate eBPF bytecode for resolved target
    fn generate_ebpf_for_target(
        &mut self,
        target: &ResolvedTarget,
        statements: &[Statement],
        pid: Option<u32>,
        resolved_address_index: Option<usize>,
    ) -> Result<UProbeConfig, CompileError> {
        let context = Context::create();

        // Allocate trace_id for this uprobe
        let assigned_trace_id = self.current_trace_id;
        self.current_trace_id += 1;

        // Generate unified eBPF function name using the assigned trace_id
        let ebpf_function_name = self.generate_unified_function_name(target, assigned_trace_id);
        let compile_options = self.compile_options.clone();
        let binary_path_hint = self.binary_path_hint.clone();

        info!(
            "Generating eBPF code for '{}' (function: {})",
            target.function_name.as_deref().unwrap_or("unknown"),
            ebpf_function_name
        );

        // Save AST immediately when we know the target details (before generating LLVM IR)
        if let Some(compile_options) = self.get_compile_options() {
            if compile_options.save_ast {
                let ast_filename = self.generate_filename(target, assigned_trace_id, "txt");
                // Create a Program from statements to save
                let program = Program {
                    statements: statements.to_vec(),
                };
                if let Err(e) = self.save_ast_to_file(&program, &ast_filename) {
                    warn!("Failed to save AST to {}: {}", ast_filename, e);
                } else {
                    info!("Saved AST to: {}", ast_filename);
                }
            }
        }

        // Use the eBPF context implementation with full AST compilation.
        let mut codegen = crate::ebpf::context::EbpfContext::new_with_process_analyzer(
            &context,
            &ebpf_function_name,
            self.process_analyzer,
            Some(assigned_trace_id),
            &self.compile_options,
        )
        .map_err(|e| CompileError::LLVM(format!("Failed to create new codegen: {e}")))?;

        // Set compile-time context for DWARF queries
        if let Some(function_address) = target.function_address {
            codegen.set_compile_time_context(function_address, target.binary_path.clone());
        }

        info!(
            "Compiling full AST program with {} statements",
            statements.len()
        );

        // Use full AST compilation
        let (_main_function, trace_context) = codegen
            .compile_program(
                &crate::script::ast::Program { statements: vec![] }, // Empty program - statements passed separately
                &ebpf_function_name,
                statements,
                pid,
                target.function_address,
                Some(&target.binary_path),
            )
            .map_err(CompileError::CodeGen)?;

        info!(
            "Generated TraceContext for '{}' with {} strings and {} variables",
            ebpf_function_name,
            trace_context.string_count(),
            trace_context.variable_name_count()
        );

        let module = codegen.get_module();

        // Generate eBPF bytecode from LLVM module
        let ebpf_bytecode = Self::generate_ebpf_bytecode(
            module,
            &ebpf_function_name,
            target,
            assigned_trace_id,
            &compile_options,
            binary_path_hint.as_deref(),
        )?;

        // Use the TraceContext returned from compile_program (no need to get it again)

        Ok(UProbeConfig {
            trace_pattern: target.pattern.clone(),
            binary_path: target.binary_path.clone(),
            function_name: target.function_name.clone(),
            function_address: target.function_address,
            uprobe_offset: target.uprobe_offset,
            target_pid: pid,
            ebpf_bytecode,
            ebpf_function_name,
            assigned_trace_id,
            trace_context,
            backtrace_unwind_rows: codegen.backtrace_unwind_rows.clone(),
            backtrace_module_row_ranges: codegen
                .backtrace_module_row_ranges
                .iter()
                .map(|entry| (entry.cookie, entry.range))
                .collect(),
            backtrace_tail_call_program: codegen.backtrace_tail_call_program(),
            resolved_address_index,
        })
    }

    /// Generate summary of all targets for reporting
    fn generate_target_info_summary(&self) -> String {
        if self.uprobe_configs.is_empty() {
            return "no_targets".to_string();
        }

        let first_target = &self.uprobe_configs[0];
        match &first_target.function_name {
            Some(name) => name.clone(),
            None => format!("addr_0x{:x}", first_target.function_address.unwrap_or(0)),
        }
    }

    /// Generate unified eBPF function name for all contexts
    ///
    /// This is the SINGLE source of truth for eBPF function naming.
    /// All other naming logic should use this method to ensure consistency.
    /// Calculate 8-digit hex hash for module path with logging
    fn calculate_module_hash(&self, module_path: &str) -> String {
        let effective_path = self.effective_binary_path(module_path);
        let mut hasher = DefaultHasher::new();
        effective_path.hash(&mut hasher);
        let hash = hasher.finish();
        let truncated = (hash & 0xFFFF_FFFF) as u32;
        let hash_hex = format!("{truncated:08x}");

        info!("Module hash calculated: {} -> {}", effective_path, hash_hex);
        hash_hex
    }

    /// Generate unified function name with format: ghostscope_{module_hash}_{address_hex}_{trace_id}
    fn generate_unified_function_name(&self, target: &ResolvedTarget, trace_id: u32) -> String {
        let module_hash = self.calculate_module_hash(&target.binary_path);
        let effective_path = self.effective_binary_path(&target.binary_path);
        let address_hex = if let Some(addr) = target.function_address {
            format!("{addr:x}")
        } else {
            "unknown".to_string()
        };

        let function_name = format!("ghostscope_{module_hash}_{address_hex}_trace{trace_id}");
        info!(
            "Generated eBPF function name: {} (module: {}, address: 0x{}, trace_id: {})",
            function_name, effective_path, address_hex, trace_id
        );

        function_name
    }

    /// Get save options (helper method)
    fn get_compile_options(&self) -> Option<&crate::CompileOptions> {
        Some(&self.compile_options)
    }

    /// Pick a binary path, falling back to compiler hint when the resolved target is empty
    fn effective_binary_path<'b>(&'b self, target_path: &'b str) -> Cow<'b, str> {
        if target_path.is_empty() {
            if let Some(hint) = &self.binary_path_hint {
                Cow::Owned(hint.clone())
            } else {
                Cow::Borrowed("unknown")
            }
        } else {
            Cow::Borrowed(target_path)
        }
    }

    /// Generate filename for output files
    fn generate_filename(&self, target: &ResolvedTarget, trace_id: u32, extension: &str) -> String {
        let module_hash = self.calculate_module_hash(&target.binary_path);
        let address_hex = if let Some(addr) = target.function_address {
            format!("{addr:x}")
        } else {
            "unknown".to_string()
        };

        format!("gs_{module_hash}_{address_hex}_trace{trace_id}.{extension}")
    }

    fn generate_filename_with_hint(
        target: &ResolvedTarget,
        trace_id: u32,
        extension: &str,
        binary_path_hint: Option<&str>,
    ) -> String {
        let effective_path = if target.binary_path.is_empty() {
            binary_path_hint.unwrap_or("unknown")
        } else {
            target.binary_path.as_str()
        };
        let mut hasher = DefaultHasher::new();
        effective_path.hash(&mut hasher);
        let module_hash = format!("{:08x}", (hasher.finish() & 0xFFFF_FFFF) as u32);
        let address_hex = if let Some(addr) = target.function_address {
            format!("{addr:x}")
        } else {
            "unknown".to_string()
        };

        format!("gs_{module_hash}_{address_hex}_trace{trace_id}.{extension}")
    }

    /// Generate eBPF bytecode from LLVM module
    fn generate_ebpf_bytecode(
        module: &inkwell::module::Module,
        function_name: &str,
        target: &ResolvedTarget,
        assigned_trace_id: u32,
        compile_options: &crate::CompileOptions,
        binary_path_hint: Option<&str>,
    ) -> Result<Vec<u8>, CompileError> {
        use inkwell::targets::{FileType, Target, TargetTriple};
        use inkwell::OptimizationLevel;

        if compile_options.save_llvm_ir {
            let filename = Self::generate_filename_with_hint(
                target,
                assigned_trace_id,
                "ll",
                binary_path_hint,
            );
            if let Err(e) = module.print_to_file(&filename) {
                warn!("Failed to save LLVM IR to {}: {}", filename, e);
            } else {
                info!("Saved LLVM IR to: {}", filename);
            }
        }
        info!("Successfully generated LLVM module for {}", function_name);

        // Get target triple
        let triple = TargetTriple::create("bpf-pc-linux");
        info!("Created target triple: bpf-pc-linux for {}", function_name);

        // Get BPF target
        let llvm_target = Target::from_triple(&triple).map_err(|e| {
            error!("Failed to get target for {}: {}", function_name, e);
            CompileError::LLVM(format!("Failed to get target for {function_name}: {e}"))
        })?;
        info!("Successfully got LLVM target for {}", function_name);

        // Create target machine
        let target_machine = llvm_target
            .create_target_machine(
                &triple,
                "generic", // CPU
                "+alu32",  // Enable BPF ALU32 instructions
                OptimizationLevel::Default,
                inkwell::targets::RelocMode::PIC,
                inkwell::targets::CodeModel::Small,
            )
            .ok_or_else(|| {
                error!("Failed to create target machine for {}", function_name);
                CompileError::LLVM(format!(
                    "Failed to create target machine for {function_name}"
                ))
            })?;
        info!("Successfully created target machine for {}", function_name);

        // Validate module before generating object code
        info!("Validating LLVM module for {}...", function_name);
        if let Err(llvm_errors) = module.verify() {
            error!(
                "LLVM module validation failed for {}: {}",
                function_name, llvm_errors
            );
            return Err(CompileError::LLVM(format!(
                "Module validation failed for {function_name}: {llvm_errors}"
            )));
        }
        info!("Module validation passed for {}", function_name);

        // Generate eBPF object file
        info!("Generating eBPF object file for {}...", function_name);
        info!("About to call LLVM write_to_memory_buffer...");

        let object_code = {
            // Add a flush to ensure logs are written before potential crash
            use std::io::Write;
            let _ = std::io::stderr().flush();
            let _ = std::io::stdout().flush();

            info!("Calling target_machine.write_to_memory_buffer...");
            match target_machine.write_to_memory_buffer(module, FileType::Object) {
                Ok(code) => {
                    info!("Successfully generated object code for {}", function_name);
                    code
                }
                Err(e) => {
                    error!("LLVM compilation failed for {}: {}", function_name, e);
                    error!("This might be due to unsupported eBPF instructions or invalid LLVM IR");

                    return Err(CompileError::LLVM(format!(
                        "eBPF compilation failed for {function_name}: {e}. This often indicates unsupported instructions or invalid IR."
                    )));
                }
            }
        };

        info!(
            "Successfully generated object code for {}! Size: {}",
            function_name,
            object_code.get_size()
        );

        // Convert to Vec<u8>
        let bytecode = object_code.as_slice().to_vec();

        // Save eBPF object file and AST if requested
        if compile_options.save_ebpf {
            let filename =
                Self::generate_filename_with_hint(target, assigned_trace_id, "o", binary_path_hint);
            if let Err(e) = std::fs::write(&filename, &bytecode) {
                warn!("Failed to save eBPF object to {}: {}", filename, e);
            } else {
                info!("Saved eBPF object to: {}", filename);
            }
        }

        // AST has already been saved earlier in generate_ebpf_for_target
        Ok(bytecode)
    }

    /// Save AST to file
    fn save_ast_to_file(
        &mut self,
        program: &crate::script::ast::Program,
        filename: &str,
    ) -> Result<(), CompileError> {
        let mut ast_content = String::new();
        ast_content.push_str("=== AST Tree ===\n");
        ast_content.push_str("Program:\n");
        for (i, stmt) in program.statements.iter().enumerate() {
            ast_content.push_str(&format!("  Statement {i}: {stmt:?}\n"));
        }
        ast_content.push_str("=== End AST Tree ===\n");

        std::fs::write(filename, ast_content).map_err(|e| {
            CompileError::Other(format!("Failed to save AST file '{filename}': {e}"))
        })?;

        Ok(())
    }
}