rush-sh 0.8.0

A POSIX sh-compatible shell written in Rust
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
//! Signal Management Module
//!
//! This module provides signal handling infrastructure for the Rush shell, including:
//! - Signal event queuing and processing
//! - Thread-safe signal queue with overflow protection
//! - Integration with trap handlers
//!
//! # Signal Queue Mechanism
//!
//! Signals are handled asynchronously using a global queue:
//! 1. Signal handler thread (via signal_hook) enqueues signal events into `SIGNAL_QUEUE`
//! 2. Main execution thread processes pending signals at safe points
//! 3. Queue has a maximum size to prevent memory exhaustion
//! 4. Oldest signals are dropped when queue is full
//!
//! # Thread Safety vs Async-Signal-Safety
//!
//! **IMPORTANT**: The signal queue uses `Arc<Mutex<VecDeque<SignalEvent>>>` which provides
//! thread safety but is **NOT async-signal-safe**. This means:
//!
//! - ✅ Safe to call from dedicated signal-handling threads (like signal_hook provides)
//! - ✅ Safe to call from normal application threads
//! - ❌ **NOT safe** to call directly from POSIX signal handlers (sigaction)
//!
//! The `Mutex::lock()` and `eprintln!()` operations used in this module can deadlock or
//! cause undefined behavior if called from a POSIX signal handler context.
//!
//! ## Recommended Signal Handling Approaches
//!
//! For true async-signal-safety, consider these alternatives:
//!
//! 1. **signal_hook's iterator pattern** (current approach):
//!    - Uses a dedicated thread to receive signals
//!    - Calls `enqueue_signal` from that thread (safe)
//!
//! 2. **Self-pipe trick**:
//!    - Signal handler writes to a pipe (async-signal-safe)
//!    - Main thread reads from pipe and processes signals
//!
//! 3. **Lock-free atomic buffers**:
//!    - Use atomic operations instead of mutexes
//!    - Requires careful implementation to avoid race conditions
//!
//! 4. **signalfd (Linux-specific)**:
//!    - Converts signals to file descriptor events
//!    - Can be integrated with event loops
//!
//! # Usage
//!
//! ```rust,no_run
//! use rush_sh::state::{enqueue_signal, process_pending_signals, ShellState};
//!
//! // In signal handler thread (via signal_hook):
//! enqueue_signal("INT", 2);
//!
//! // In main execution loop:
//! let mut shell_state = ShellState::new();
//! process_pending_signals(&mut shell_state);
//! ```

use lazy_static::lazy_static;
use std::collections::VecDeque;
use std::sync::{Arc, Mutex};
use std::time::Instant;

use super::ShellState;

lazy_static! {
    /// Global queue for pending signal events
    ///
    /// Signals are enqueued by the signal handler thread and dequeued by the main thread.
    /// This provides a thread-safe mechanism for asynchronous signal handling.
    ///
    /// # Safety Warning
    ///
    /// This queue uses `Mutex` which is **NOT async-signal-safe**. It must only be accessed from:
    /// - Dedicated signal-handling threads (like signal_hook provides)
    /// - Normal application threads
    ///
    /// **Never** access this queue directly from a POSIX signal handler (sigaction) as it can
    /// cause deadlocks or undefined behavior.
    pub static ref SIGNAL_QUEUE: Arc<Mutex<VecDeque<SignalEvent>>> =
        Arc::new(Mutex::new(VecDeque::new()));
}

/// Maximum number of signals to queue before dropping old ones
///
/// This prevents unbounded memory growth if signals arrive faster than they can be processed.
/// When the queue is full, the oldest signal is dropped to make room for new ones.
///
/// # Implementation Note
///
/// The overflow handling in [`enqueue_signal`] uses `eprintln!()` which is not async-signal-safe.
/// This is acceptable because `enqueue_signal` is designed to be called from a dedicated
/// signal-handling thread, not from POSIX signal handlers.
const MAX_SIGNAL_QUEUE_SIZE: usize = 100;

/// Represents a signal event that needs to be processed
///
/// Signal events are created when a signal is received and queued for later processing
/// by the main execution thread. Each event captures the signal name, number, and timestamp.
///
/// # Safety Note
///
/// Creating a `SignalEvent` calls `Instant::now()` which may not be async-signal-safe on all
/// platforms. This struct should only be instantiated from safe contexts (dedicated signal
/// threads, not POSIX signal handlers).
#[derive(Debug, Clone)]
pub struct SignalEvent {
    /// Signal name (e.g., "INT", "TERM", "HUP")
    pub signal_name: String,
    /// Signal number (e.g., 2 for SIGINT, 15 for SIGTERM)
    pub signal_number: i32,
    /// When the signal was received (for debugging and ordering)
    pub timestamp: Instant,
}

impl SignalEvent {
    /// Create a new signal event with the current timestamp
    ///
    /// # Arguments
    ///
    /// * `signal_name` - The name of the signal (e.g., "INT", "TERM")
    /// * `signal_number` - The numeric signal value (e.g., 2, 15)
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use rush_sh::state::signals::SignalEvent;
    ///
    /// let event = SignalEvent::new("INT".to_string(), 2);
    /// assert_eq!(event.signal_name, "INT");
    /// assert_eq!(event.signal_number, 2);
    /// ```
    pub fn new(signal_name: String, signal_number: i32) -> Self {
        Self {
            signal_name,
            signal_number,
            timestamp: Instant::now(),
        }
    }
}

/// Enqueue a signal event for later processing
///
/// This function is called by a dedicated signal handler thread when a signal is received.
/// If the queue is full, the oldest event is dropped to make room for the new one.
///
/// # Arguments
///
/// * `signal_name` - The name of the signal (e.g., "INT", "TERM")
/// * `signal_number` - The numeric signal value (e.g., 2, 15)
///
/// # Safety Warning - NOT Async-Signal-Safe
///
/// **CRITICAL**: This function is **NOT async-signal-safe** and must **NOT** be called directly
/// from POSIX signal handlers (sigaction). It uses:
/// - `Mutex::lock()` - can deadlock if called from signal handler
/// - `eprintln!()` - not async-signal-safe, can cause undefined behavior
///
/// ## Safe Usage Contexts
///
/// ✅ **Safe to call from**:
/// - Dedicated signal-handling threads (like signal_hook's iterator pattern)
/// - Normal application threads
/// - After receiving signals via safe relay mechanisms (signalfd, self-pipe)
///
/// ❌ **NEVER call from**:
/// - POSIX signal handlers registered with sigaction
/// - Any context where async-signal-safety is required
///
/// ## Recommended Patterns
///
/// If you need true async-signal-safety, use one of these approaches instead:
///
/// 1. **signal_hook iterator** (current approach):
///    ```rust,no_run
///    use rush_sh::state::enqueue_signal;
///    use signal_hook::consts::{SIGINT, SIGTERM};
///    use signal_hook::iterator::Signals;
///    use std::thread;
///
///    let mut signals = Signals::new(&[SIGINT, SIGTERM]).unwrap();
///    thread::spawn(move || {
///        for sig in signals.forever() {
///            // Map signal number to name
///            let signal_name = match sig {
///                SIGINT => "INT",
///                SIGTERM => "TERM",
///                _ => continue, // Skip unknown signals
///            };
///            enqueue_signal(signal_name, sig); // Safe: called from dedicated thread
///        }
///    });
///    ```
///
/// 2. **Self-pipe trick**:
///    - Signal handler writes signal number to pipe (async-signal-safe)
///    - Main thread reads from pipe and calls `enqueue_signal`
///
/// 3. **Lock-free atomic buffer**:
///    - Replace `Mutex<VecDeque>` with atomic operations
///    - More complex but truly async-signal-safe
///
/// # Examples
///
/// ```rust,no_run
/// use rush_sh::state::enqueue_signal;
///
/// // ✅ SAFE: Called from signal_hook's dedicated thread
/// enqueue_signal("INT", 2);
///
/// // ❌ UNSAFE: Never do this in a sigaction handler!
/// // extern "C" fn signal_handler(sig: i32) {
/// //     enqueue_signal("INT", sig); // DEADLOCK RISK!
/// // }
/// ```
pub fn enqueue_signal(signal_name: &str, signal_number: i32) {
    match SIGNAL_QUEUE.lock() {
        Ok(mut queue) => {
            // If queue is full, remove oldest event
            if queue.len() >= MAX_SIGNAL_QUEUE_SIZE {
                queue.pop_front();
                eprintln!("Warning: Signal queue overflow, dropping oldest signal");
            }

            queue.push_back(SignalEvent::new(signal_name.to_string(), signal_number));
        }
        Err(_) => {
            // Lock poisoned - another thread panicked while holding the lock
            // Cannot safely enqueue; signal is dropped to avoid cascading failures
            #[cfg(debug_assertions)]
            eprintln!(
                "Warning: Signal queue lock poisoned, dropping signal {}",
                signal_name
            );
        }
    }
}

/// Process all pending signals in the queue
///
/// This function should be called at safe points during command execution to handle
/// any signals that have been received. For each signal, if a trap handler is set,
/// the handler is executed.
///
/// # Arguments
///
/// * `shell_state` - Mutable reference to the shell state for trap handler execution
///
/// # Behavior
///
/// - Processes all signals currently in the queue
/// - Executes trap handlers for signals that have them
/// - Preserves exit codes as per POSIX requirements
/// - Displays signal information when colors are enabled
///
/// # Examples
///
/// ```rust,no_run
/// use rush_sh::state::{ShellState, process_pending_signals};
///
/// let mut shell_state = ShellState::new();
/// process_pending_signals(&mut shell_state);
/// ```
pub fn process_pending_signals(shell_state: &mut ShellState) {
    // Drain all pending signals into a local collection while holding the lock
    let pending_signals = {
        if let Ok(mut queue) = SIGNAL_QUEUE.lock() {
            // Drain all signals from the queue into a local Vec
            let mut signals = Vec::new();
            while let Some(signal_event) = queue.pop_front() {
                signals.push(signal_event);
            }
            signals
        } else {
            // If we can't acquire the lock, return early
            return;
        }
    }; // Lock is dropped here

    // Process all signals without holding the lock
    // This prevents deadlock if a trap handler enqueues a signal
    for signal_event in pending_signals {
        // Handle SIGCHLD specially - reap children and update job status
        if signal_event.signal_name == "CHLD" {
            handle_sigchld(shell_state);
        }
        
        // Check if a trap is set for this signal
        if let Some(trap_cmd) = shell_state.get_trap(&signal_event.signal_name)
            && !trap_cmd.is_empty()
        {
            // Display signal information for debugging/tracking
            if shell_state.colors_enabled {
                eprintln!(
                    "{}Signal {} (signal {}) received at {:?}\x1b[0m",
                    shell_state.color_scheme.builtin,
                    signal_event.signal_name,
                    signal_event.signal_number,
                    signal_event.timestamp
                );
            } else {
                eprintln!(
                    "Signal {} (signal {}) received at {:?}",
                    signal_event.signal_name, signal_event.signal_number, signal_event.timestamp
                );
            }

            // Execute the trap handler
            // Note: This preserves the exit code as per POSIX requirements
            crate::executor::execute_trap_handler(&trap_cmd, shell_state);
        }
    }
}

/// Handle SIGCHLD signal by reaping terminated/stopped children
///
/// This function uses waitpid() with WNOHANG and WUNTRACED flags to check for
/// child process state changes without blocking. It updates the job table with
/// the new status of any changed processes.
///
/// # Arguments
///
/// * `shell_state` - Mutable reference to the shell state containing the job table
///
/// # Behavior
///
/// - Loops to reap all terminated/stopped children
/// - Updates job status in the job table
/// - Distinguishes between Exited, Stopped, and Signaled states
/// - Does not print notifications (that's done by check_background_jobs)
fn handle_sigchld(shell_state: &mut ShellState) {
    loop {
        // Use waitpid with WNOHANG to check for any child state changes without blocking
        // WUNTRACED allows us to detect stopped children (SIGTSTP, SIGSTOP, etc.)
        let result = unsafe {
            let mut status: libc::c_int = 0;
            let pid = libc::waitpid(
                -1, // Wait for any child process
                &mut status as *mut libc::c_int,
                libc::WNOHANG | libc::WUNTRACED, // Don't block, report stopped children
            );
            
            if pid > 0 {
                // Child state changed
                Some((pid as u32, status))
            } else if pid == 0 {
                // No children ready (WNOHANG returned immediately)
                None
            } else {
                // pid < 0: error occurred
                // Check errno to distinguish EINTR from other errors
                let errno = *libc::__errno_location();
                if errno == libc::EINTR {
                    // Interrupted by signal, retry the waitpid call
                    Some((0, 0)) // Sentinel value to indicate retry
                } else {
                    // Other error (e.g., ECHILD - no children), give up
                    None
                }
            }
        };
        
        match result {
            Some((pid, status)) if pid > 0 => {
                // Determine the new job status based on the wait status
                let job_status = if libc::WIFEXITED(status) {
                    // Process exited normally
                    let exit_code = libc::WEXITSTATUS(status);
                    crate::state::JobStatus::Done(exit_code)
                } else if libc::WIFSIGNALED(status) {
                    // Process was terminated by a signal
                    let signal = libc::WTERMSIG(status);
                    crate::state::JobStatus::Done(128 + signal)
                } else if libc::WIFSTOPPED(status) {
                    // Process was stopped (e.g., by SIGTSTP)
                    crate::state::JobStatus::Stopped
                } else {
                    // Unknown status, treat as done with error
                    crate::state::JobStatus::Done(1)
                };
                
                // Update the job status in the job table
                if let Ok(mut job_table) = shell_state.job_table.try_borrow_mut() {
                    job_table.update_job_status(pid, job_status);
                }
            }
            Some((0, 0)) => {
                // Sentinel value indicating EINTR - retry the loop
                continue;
            }
            None | Some(_) => {
                // No more children to reap, or invalid state
                break;
            }
        }
    }
}

/// Check for completed or stopped background jobs and print notifications
///
/// This function should be called before displaying the prompt in interactive mode.
/// It checks the job table for jobs that have completed or stopped, prints appropriate
/// notifications, and removes completed jobs from the table.
///
/// # Arguments
///
/// * `shell_state` - Mutable reference to the shell state containing the job table
///
/// # Output Format
///
/// - Completed jobs: `[job_id]+ Done    command`
/// - Stopped jobs: `[job_id]+ Stopped command`
/// - The `+` indicates the current job, `-` indicates the previous job
///
/// # Examples
///
/// ```rust,no_run
/// use rush_sh::state::{ShellState, check_background_jobs};
///
/// let mut shell_state = ShellState::new();
/// check_background_jobs(&mut shell_state);
/// ```
pub fn check_background_jobs(shell_state: &mut ShellState) {
    // Collect job IDs and their status to avoid borrowing issues
    let jobs_to_notify: Vec<(usize, crate::state::JobStatus, String, char)> = {
        if let Ok(job_table) = shell_state.job_table.try_borrow() {
            let current_job = job_table.get_current_job();
            let previous_job = job_table.get_previous_job();
            
            job_table
                .get_all_jobs()
                .iter()
                .filter(|job| {
                    // Include both Stopped and Done jobs for notification
                    // Only Running jobs should be excluded
                    matches!(job.status, crate::state::JobStatus::Stopped | crate::state::JobStatus::Done(_))
                })
                .map(|job| {
                    let is_current = Some(job.job_id) == current_job;
                    let is_previous = Some(job.job_id) == previous_job;
                    let marker = if is_current {
                        '+'
                    } else if is_previous {
                        '-'
                    } else {
                        ' '
                    };
                    (
                        job.job_id,
                        job.status.clone(),
                        job.command.clone(),
                        marker,
                    )
                })
                .collect()
        } else {
            Vec::new()
        }
    };
    
    // Print notifications and collect completed job IDs
    let mut completed_jobs = Vec::new();
    for (job_id, status, command, marker) in jobs_to_notify {
        match status {
            crate::state::JobStatus::Done(exit_code) => {
                if exit_code == 0 {
                    println!("[{}]{} Done    {}", job_id, marker, command);
                } else {
                    println!("[{}]{} Done({})    {}", job_id, marker, exit_code, command);
                }
                completed_jobs.push((job_id, marker));
            }
            crate::state::JobStatus::Stopped => {
                println!("[{}]{} Stopped {}", job_id, marker, command);
            }
            _ => {}
        }
    }
    
    // Remove completed jobs from the table
    if let Ok(mut job_table) = shell_state.job_table.try_borrow_mut() {
        for (job_id, _marker) in completed_jobs {
            job_table.remove_job(job_id);
        }
    }
}