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;
use VecDeque;
use ;
use Instant;
use ShellState;
lazy_static!
/// 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).
/// 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!
/// // }
/// ```
/// 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);
/// ```
/// 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)
/// 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);
/// ```