ghostscope 0.1.1

Command-line entrypoint that drives GhostScope compiler, loader, and UI end-to-end.
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
use crate::config::{MergedConfig, ParsedArgs};
use crate::core::GhostSession;
use crate::runtime::{dwarf_loader, info_handlers, source_handlers, trace_handlers};
use anyhow::Result;
use ghostscope_ui::{EventRegistry, RuntimeChannels, RuntimeCommand, RuntimeStatus};
use tracing::{error, info};

/// Run GhostScope in TUI mode with merged configuration
pub async fn run_tui_coordinator_with_config(config: MergedConfig) -> Result<()> {
    info!("Starting GhostScope in TUI mode with merged configuration");

    // Pass the UI configuration to the TUI system
    let ui_config = config.get_ui_config();

    // Clone config for session creation before converting to ParsedArgs
    let config_for_session = config.clone();

    // Convert MergedConfig back to ParsedArgs for existing code compatibility
    // TODO: Refactor to use MergedConfig directly throughout the TUI system
    let parsed_args = ParsedArgs {
        binary_path: config.binary_path,
        target_path: config.target_path,
        binary_args: config.binary_args,
        log_file: Some(config.log_file),
        enable_logging: config.enable_logging,
        enable_console_logging: config.enable_console_logging,
        log_level: config.log_level,
        config: None, // Not needed for runtime conversion
        debug_file: config.debug_file,
        script: config.script,
        script_file: config.script_file,
        pid: config.pid,
        tui_mode: config.tui_mode,
        should_save_llvm_ir: config.should_save_llvm_ir,
        should_save_ebpf: config.should_save_ebpf,
        should_save_ast: config.should_save_ast,
        layout_mode: config.layout_mode,
        has_explicit_log_flag: false, // Not relevant for TUI conversion
        has_explicit_console_log_flag: false, // Not relevant for TUI conversion
        force_perf_event_array: config.ebpf_config.force_perf_event_array,
        enable_sysmon_for_shared_lib: config.ebpf_config.enable_sysmon_for_shared_lib,
        allow_loose_debug_match: config.dwarf_allow_loose_debug_match,
        source_panel: false,
        no_source_panel: false,
    };

    run_tui_coordinator_with_ui_config_and_merged_config(parsed_args, ui_config, config_for_session)
        .await
}

/// Internal function to run TUI coordinator with UI configuration
async fn run_tui_coordinator_with_ui_config_and_merged_config(
    parsed_args: ParsedArgs,
    ui_config: ghostscope_ui::UiConfig,
    merged_config: MergedConfig,
) -> Result<()> {
    info!("Starting GhostScope in TUI mode");

    // Create event communication channels
    let (event_registry, runtime_channels) = EventRegistry::new();

    // Initialize DWARF information processing in background
    let dwarf_task = {
        let status_sender = runtime_channels.create_status_sender();
        let config_clone = merged_config.clone();
        tokio::spawn(async move {
            // Pass MergedConfig directly to ensure search_paths are available during DWARF loading
            let session =
                dwarf_loader::initialize_dwarf_processing(&config_clone, status_sender).await?;
            Ok::<_, anyhow::Error>(session)
        })
    };

    // Start the runtime coordination task with session from DWARF processing
    let runtime_task = tokio::spawn(async move {
        // Wait for DWARF processing to complete and get the session
        match dwarf_task.await {
            Ok(Ok(session)) => {
                // Build compile options from merged config using the same logic as CLI
                // Derive a binary path hint from the session (main executable), if available
                let binary_path_hint = crate::util::derive_binary_path_hint(&session);

                let compile_options = merged_config.get_compile_options(
                    parsed_args.should_save_llvm_ir,
                    parsed_args.should_save_ebpf,
                    parsed_args.should_save_ast,
                    binary_path_hint,
                );

                run_runtime_coordinator(runtime_channels, Some(session), compile_options).await
            }
            Ok(Err(e)) => {
                error!("DWARF processing failed: {}", e);
                // Fall back to defaults if session failed
                let compile_options = merged_config.get_compile_options(
                    parsed_args.should_save_llvm_ir,
                    parsed_args.should_save_ebpf,
                    parsed_args.should_save_ast,
                    None,
                );
                run_runtime_coordinator(runtime_channels, None, compile_options).await
            }
            Err(e) => {
                error!("DWARF task panicked: {}", e);
                let compile_options = merged_config.get_compile_options(
                    parsed_args.should_save_llvm_ir,
                    parsed_args.should_save_ebpf,
                    parsed_args.should_save_ast,
                    None,
                );
                run_runtime_coordinator(runtime_channels, None, compile_options).await
            }
        }
    });

    // Run TUI mode and runtime coordination concurrently
    let tui_result = ghostscope_ui::run_tui_mode_with_config(event_registry, ui_config).await;
    let runtime_result = runtime_task.await.unwrap_or_else(|e| {
        error!("Runtime task failed: {}", e);
        Err(anyhow::anyhow!("Runtime task panicked"))
    });

    // Return the first error encountered, or Ok if both succeeded
    tui_result.and(runtime_result)
}

/// Main runtime coordinator that handles commands and manages eBPF sessions
async fn run_runtime_coordinator(
    mut runtime_channels: RuntimeChannels,
    mut session: Option<GhostSession>,
    compile_options: ghostscope_compiler::CompileOptions,
) -> Result<()> {
    info!("Runtime coordinator started");

    // Create trace sender for event polling task
    let trace_sender = runtime_channels.create_trace_sender();

    loop {
        tokio::select! {
            // Wait for events asynchronously from active traces' loaders
            result = async {
                if let Some(ref mut session) = session {
                    // Use trace_manager's built-in event polling method
                    session.trace_manager.wait_for_all_events_async().await
                } else {
                    // No session, return empty events and let the outer loop continue
                    Ok(Vec::new())
                }
            }, if session.is_some() => {
                match result {
                    Ok(events) => {
                        if let Some(ref _session) = session {
                            if !events.is_empty() {
                                tracing::debug!("Forwarding {} trace events to UI", events.len());
                            }
                            for event_data in events {
                                let _ = trace_sender.send(event_data);
                            }
                        }
                    }
                    Err(e) => {
                        error!("Fatal error receiving trace events: {}", e);
                        break;
                    }
                }
            }

            // Handle runtime commands
            Some(command) = runtime_channels.command_receiver.recv() => {
                match command {
                    RuntimeCommand::ExecuteScript { command: script, selected_index } => {
                        handle_execute_script(&mut session, &mut runtime_channels, script, selected_index, &compile_options).await;
                    }
                    RuntimeCommand::InfoTrace { trace_id } => {
                        match trace_id {
                            Some(id) => {
                                info_handlers::handle_info_trace(&session, &mut runtime_channels, id).await;
                            }
                            None => {
                                info_handlers::handle_info_trace_all(&session, &mut runtime_channels).await;
                            }
                        }
                    }
                    RuntimeCommand::InfoTraceAll => {
                        info_handlers::handle_info_trace_all(&session, &mut runtime_channels).await;
                    }
                    RuntimeCommand::InfoSource => {
                        info_handlers::handle_info_source(&session, &mut runtime_channels).await;
                    }
                    RuntimeCommand::InfoShare => {
                        info_handlers::handle_info_share(&session, &mut runtime_channels).await;
                    }
                    RuntimeCommand::InfoFile => {
                        info_handlers::handle_info_file(&session, &mut runtime_channels).await;
                    }
                    RuntimeCommand::RequestSourceCode => {
                        source_handlers::handle_main_source_request(&mut session, &mut runtime_channels).await;
                    }
                    RuntimeCommand::DisableTrace(trace_id) => {
                        trace_handlers::handle_disable_trace(&mut session, &mut runtime_channels, trace_id).await;
                    }
                    RuntimeCommand::EnableTrace(trace_id) => {
                        trace_handlers::handle_enable_trace(&mut session, &mut runtime_channels, trace_id).await;
                    }
                    RuntimeCommand::DisableAllTraces => {
                        trace_handlers::handle_disable_all_traces(&mut session, &mut runtime_channels).await;
                    }
                    RuntimeCommand::EnableAllTraces => {
                        trace_handlers::handle_enable_all_traces(&mut session, &mut runtime_channels).await;
                    }
                    RuntimeCommand::DeleteTrace(trace_id) => {
                        trace_handlers::handle_delete_trace(&mut session, &mut runtime_channels, trace_id).await;
                    }
                    RuntimeCommand::DeleteAllTraces => {
                        trace_handlers::handle_delete_all_traces(&mut session, &mut runtime_channels).await;
                    }
                    RuntimeCommand::InfoFunction { target, verbose } => {
                        info_handlers::handle_info_function(&mut session, &mut runtime_channels, target, verbose).await;
                    }
                    RuntimeCommand::InfoLine { target, verbose } => {
                        info_handlers::handle_info_line(&mut session, &mut runtime_channels, target, verbose).await;
                    }
                    RuntimeCommand::InfoAddress { target, verbose } => {
                        info_handlers::handle_info_address(&mut session, &mut runtime_channels, target, verbose).await;
                    }
                    RuntimeCommand::SaveTraces { filename, filter } => {
                        if let Some(ref session) = session {
                            handle_save_traces(session, &mut runtime_channels, filename, filter).await;
                        } else {
                            let _ = runtime_channels
                                .status_sender
                                .send(RuntimeStatus::TracesSaveFailed {
                                    error: "No debug session available".to_string(),
                                });
                        }
                    }
                    RuntimeCommand::LoadTraces { filename, traces } => {
                        handle_load_traces(&mut session, &mut runtime_channels, filename, traces).await;
                    }
                    RuntimeCommand::SrcPathList => {
                        if let Some(ref session) = session {
                            let info = session.source_path_resolver.get_all_rules();
                            let _ = runtime_channels.status_sender.send(RuntimeStatus::SrcPathInfo { info });
                        } else {
                            let _ = runtime_channels.status_sender.send(RuntimeStatus::SrcPathFailed {
                                error: "No debug session available".to_string(),
                            });
                        }
                    }
                    RuntimeCommand::SrcPathAddDir { dir } => {
                        if let Some(ref mut sess) = session {
                            sess.source_path_resolver.add_search_dir(dir.clone());
                            let _ = runtime_channels.status_sender.send(RuntimeStatus::SrcPathUpdated {
                                message: format!("Added search directory: {dir}"),
                            });
                        } else {
                            let _ = runtime_channels.status_sender.send(RuntimeStatus::SrcPathFailed {
                                error: "No debug session available".to_string(),
                            });
                            continue;
                        }
                        // Auto-reload source code and file list (outside the if-let to avoid borrow issues)
                        info!("Reloading source code and file list after srcpath change");
                        source_handlers::handle_main_source_request(&mut session, &mut runtime_channels).await;
                        source_handlers::handle_request_source_code(&session, &mut runtime_channels).await;
                    }
                    RuntimeCommand::SrcPathAddMap { from, to } => {
                        if let Some(ref mut sess) = session {
                            sess.source_path_resolver.add_substitution(from.clone(), to.clone());
                            let _ = runtime_channels.status_sender.send(RuntimeStatus::SrcPathUpdated {
                                message: format!("Added path mapping: {from} -> {to}"),
                            });
                        } else {
                            let _ = runtime_channels.status_sender.send(RuntimeStatus::SrcPathFailed {
                                error: "No debug session available".to_string(),
                            });
                            continue;
                        }
                        // Auto-reload source code and file list (outside the if-let to avoid borrow issues)
                        info!("Reloading source code and file list after srcpath change");
                        source_handlers::handle_main_source_request(&mut session, &mut runtime_channels).await;
                        source_handlers::handle_request_source_code(&session, &mut runtime_channels).await;
                    }
                    RuntimeCommand::SrcPathRemove { pattern } => {
                        let should_reload = if let Some(ref mut sess) = session {
                            if sess.source_path_resolver.remove(&pattern) {
                                let _ = runtime_channels.status_sender.send(RuntimeStatus::SrcPathUpdated {
                                    message: format!("Removed path rule: {pattern}"),
                                });
                                true
                            } else {
                                let _ = runtime_channels.status_sender.send(RuntimeStatus::SrcPathFailed {
                                    error: format!("No matching path rule found: {pattern}"),
                                });
                                false
                            }
                        } else {
                            let _ = runtime_channels.status_sender.send(RuntimeStatus::SrcPathFailed {
                                error: "No debug session available".to_string(),
                            });
                            false
                        };
                        if should_reload {
                            // Auto-reload source code and file list (outside the if-let to avoid borrow issues)
                            info!("Reloading source code and file list after srcpath change");
                            source_handlers::handle_main_source_request(&mut session, &mut runtime_channels).await;
                            source_handlers::handle_request_source_code(&session, &mut runtime_channels).await;
                        }
                    }
                    RuntimeCommand::SrcPathClear => {
                        if let Some(ref mut sess) = session {
                            sess.source_path_resolver.clear_runtime();
                            let _ = runtime_channels.status_sender.send(RuntimeStatus::SrcPathUpdated {
                                message: "Cleared all runtime path rules".to_string(),
                            });
                        } else {
                            let _ = runtime_channels.status_sender.send(RuntimeStatus::SrcPathFailed {
                                error: "No debug session available".to_string(),
                            });
                            continue;
                        }
                        // Auto-reload source code and file list (outside the if-let to avoid borrow issues)
                        info!("Reloading source code and file list after srcpath clear");
                        source_handlers::handle_main_source_request(&mut session, &mut runtime_channels).await;
                        source_handlers::handle_request_source_code(&session, &mut runtime_channels).await;
                    }
                    RuntimeCommand::SrcPathReset => {
                        if let Some(ref mut sess) = session {
                            sess.source_path_resolver.reset();
                            let _ = runtime_channels.status_sender.send(RuntimeStatus::SrcPathUpdated {
                                message: "Reset to config file path rules".to_string(),
                            });
                        } else {
                            let _ = runtime_channels.status_sender.send(RuntimeStatus::SrcPathFailed {
                                error: "No debug session available".to_string(),
                            });
                            continue;
                        }
                        // Auto-reload source code and file list (outside the if-let to avoid borrow issues)
                        info!("Reloading source code and file list after srcpath reset");
                        source_handlers::handle_main_source_request(&mut session, &mut runtime_channels).await;
                        source_handlers::handle_request_source_code(&session, &mut runtime_channels).await;
                    }
                    RuntimeCommand::Shutdown => {
                        info!("Shutdown requested");
                        break;
                    }
                }
            }
        }
    }

    info!("Runtime coordinator shutting down");
    Ok(())
}

/// Handle script execution command
async fn handle_execute_script(
    session: &mut Option<GhostSession>,
    runtime_channels: &mut RuntimeChannels,
    script: String,
    selected_index: Option<usize>,
    compile_options: &ghostscope_compiler::CompileOptions,
) {
    info!("Executing script: {}", script);

    if let Some(ref mut session) = session {
        // Clone compile options to inject selected index filter for this compile
        let mut options = compile_options.clone();
        options.selected_index = selected_index;

        let details = match crate::script::compile_and_load_script_for_tui(
            &script, session, &options,
        )
        .await
        {
            Ok(details) => {
                info!(
                    "✓ Script compilation completed: {} total, {} success, {} failed",
                    details.total_count, details.success_count, details.failed_count
                );
                details
            }
            Err(e) => {
                error!("❌ Script compilation failed: {}", e);
                // Return details with all failures
                ghostscope_ui::events::ScriptCompilationDetails {
                    trace_ids: vec![],
                    results: vec![ghostscope_ui::events::ScriptExecutionResult {
                        pc_address: 0,
                        target_name: script.clone(),
                        binary_path: String::new(),
                        status: ghostscope_ui::events::ExecutionStatus::Failed(e.to_string()),
                        source_file: None,
                        source_line: None,
                        is_inline: None,
                    }],
                    total_count: 1,
                    success_count: 0,
                    failed_count: 1,
                }
            }
        };

        let _ = runtime_channels
            .status_sender
            .send(RuntimeStatus::ScriptCompilationCompleted { details });
    } else {
        // No session available - return details with failure
        let details = ghostscope_ui::events::ScriptCompilationDetails {
            trace_ids: vec![],
            results: vec![ghostscope_ui::events::ScriptExecutionResult {
                pc_address: 0,
                target_name: script.clone(),
                binary_path: String::new(),
                status: ghostscope_ui::events::ExecutionStatus::Failed(
                    "No debug session available".to_string(),
                ),
                source_file: None,
                source_line: None,
                is_inline: None,
            }],
            total_count: 1,
            success_count: 0,
            failed_count: 1,
        };

        let _ = runtime_channels
            .status_sender
            .send(RuntimeStatus::ScriptCompilationCompleted { details });
    }
}

/// Handle save traces command
async fn handle_save_traces(
    session: &GhostSession,
    runtime_channels: &mut RuntimeChannels,
    filename: Option<String>,
    filter: ghostscope_ui::components::command_panel::trace_persistence::SaveFilter,
) {
    use ghostscope_ui::components::command_panel::trace_persistence::{
        TraceConfig, TracePersistence,
    };
    use ghostscope_ui::RuntimeStatus;

    // Create TracePersistence instance
    let mut persistence = TracePersistence::new();

    // Set binary path if available
    if let Some(ref binary_path) = session.binary_path() {
        persistence.set_binary_path(binary_path.clone());
    }

    // Set PID if available
    if let Some(pid) = session.pid() {
        persistence.set_pid(pid);
    }

    // Collect trace information directly from trace manager snapshots (includes pc)
    let trace_ids = session.trace_manager.get_all_trace_ids();
    for trace_id in trace_ids {
        if let Some(snapshot) = session.trace_manager.get_trace_snapshot(trace_id) {
            // Prefer the index stored in the trace snapshot; fallback to None
            let selected_index = snapshot.address_global_index;

            let config = TraceConfig {
                id: snapshot.trace_id,
                target: snapshot.target_display.clone(),
                script: snapshot.script_content.clone(),
                status: if snapshot.is_enabled {
                    ghostscope_ui::events::TraceStatus::Active
                } else {
                    ghostscope_ui::events::TraceStatus::Disabled
                },
                binary_path: snapshot.binary_path.clone(),
                selected_index,
            };
            persistence.add_trace(config);
        }
    }

    // Save traces to file
    match persistence.save_traces(filename.as_deref(), filter) {
        Ok(result) => {
            let _ = runtime_channels
                .status_sender
                .send(RuntimeStatus::TracesSaved {
                    filename: result.filename.to_string_lossy().to_string(),
                    saved_count: result.saved_count,
                    total_count: result.total_count,
                });
        }
        Err(e) => {
            let _ = runtime_channels
                .status_sender
                .send(RuntimeStatus::TracesSaveFailed {
                    error: e.to_string(),
                });
        }
    }
}

/// Handle load traces command
async fn handle_load_traces(
    session: &mut Option<GhostSession>,
    runtime_channels: &mut RuntimeChannels,
    filename: String,
    traces: Vec<ghostscope_ui::events::TraceDefinition>,
) {
    use ghostscope_ui::RuntimeStatus;

    if session.is_none() {
        let _ = runtime_channels
            .status_sender
            .send(RuntimeStatus::TracesLoadFailed {
                filename,
                error: "No debug session available".to_string(),
            });
        return;
    }

    // Send all trace scripts for execution
    // The UI will track individual ScriptCompilationCompleted responses
    for trace in &traces {
        // Build the trace command
        let script_command = format!("trace {} {{\n{}\n}}", trace.target, trace.script);

        // Execute the script (this sends the command but doesn't wait for result)
        let default_compile_options = ghostscope_compiler::CompileOptions::default();
        handle_execute_script(
            session,
            runtime_channels,
            script_command,
            trace.selected_index,
            &default_compile_options,
        )
        .await;

        // TODO: Handle disabled traces from //@disabled markers
        // Currently ignoring disabled state - would need to track trace_id from
        // ScriptCompilationCompleted response and then send disable command
    }

    // Don't send TracesLoaded here - let the UI track individual completions
    // and send the final summary when all are done
}