zshrs 0.11.5

The first compiled Unix shell — bytecode VM, worker pool, AOP intercept, Rkyv caching
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
//! `signals.h` port — signal-handling constants + macro wrappers.
//!
//! Port of `Src/signals.h`. Defines:
//!   - Pseudo-signal indexes (`SIGZERR`, `SIGDEBUG`, `SIGEXIT`,
//!     `VSIGCOUNT`, `TRAPCOUNT`).
//!   - SIGRTMIN/SIGRTMAX-aware index/number conversion macros
//!     (`SIGNUM`, `SIGIDX`).
//!   - Signal-queueing macros (`queue_signals`/`unqueue_signals`/
//!     `dont_queue_signals`/`restore_queue_signals`/
//!     `run_queued_signals`/`queue_signal_level`).
//!   - Block helpers (`child_block`/`child_unblock`/`winch_block`/
//!     `winch_unblock`).
//!   - Convenience wrappers (`signal_ignore`/`signal_default`).
//!
//! C source: 0 structs/enums/fns. ~25 #defines.
//!
//! Macro casing preserved verbatim per the casing rule. The
//! signal-queue mutable state (`queue_front`/`queue_rear`/
//! `queueing_enabled`/`signal_queue[]`/`signal_mask_queue[]`) lives
//! in `signals.rs` (the .c port); this header port covers the
//! constants + the queueing-API call shape.

use std::sync::atomic::{AtomicI32, Ordering};
use crate::ported::signals::{queue_front, queue_rear, signal_queue, signal_mask_queue};

// ---------------------------------------------------------------------------
// Pseudo-signal indexes (c:34-46).
// ---------------------------------------------------------------------------

/// Port of the platform's `SIGCOUNT` value (computed by autoconf
/// from `<signal.h>`). Equal to `NSIG - 1` on every supported host
/// — the highest valid signal number for the standard signal table.
/// libc-rs doesn't expose `NSIG` on Linux/macOS so we hardcode the
/// value `<signal.h>` would emit.
#[cfg(target_os = "linux")]
pub const SIGCOUNT: i32 = 64;                                            // Linux NSIG = 65

#[cfg(target_os = "macos")]
pub const SIGCOUNT: i32 = 31;                                            // macOS NSIG = 32

#[cfg(not(any(target_os = "linux", target_os = "macos")))]
pub const SIGCOUNT: i32 = 31;                                            // POSIX baseline

/// Port of `#define SIGZERR` from `Src/signals.h:34`. Pseudo-signal
/// index for the ZERR trap (fires after every command that exits
/// with a nonzero status).
pub const SIGZERR: i32 = SIGCOUNT + 1;                                   // c:34

/// Port of `#define SIGDEBUG` from `Src/signals.h:35`. Pseudo-signal
/// index for the DEBUG trap (fires before every command).
pub const SIGDEBUG: i32 = SIGCOUNT + 2;                                  // c:35

/// Port of `#define VSIGCOUNT` from `Src/signals.h:36`. Total
/// number of "virtual" signal-table slots = SIGCOUNT (real signals)
/// + 3 (zero + ZERR + DEBUG).
pub const VSIGCOUNT: i32 = SIGCOUNT + 3;                                 // c:36

/// Port of `#define TRAPCOUNT` from `Src/signals.h:38/42`. With
/// `SIGRTMIN`/`SIGRTMAX` available (every Linux/musl/BSD host),
/// expands to `VSIGCOUNT + (SIGRTMAX - SIGRTMIN + 1)` so the trap
/// table covers real-time signals too. macOS/BSD libc binding
/// doesn't expose SIGRTMIN/SIGRTMAX as Rust constants — the c:42
/// `#else` arm (TRAPCOUNT = VSIGCOUNT) applies.
#[cfg(target_os = "linux")]
pub const TRAPCOUNT: i32 = VSIGCOUNT + 32;                               // c:38 (Linux RT range = 32)

#[cfg(not(target_os = "linux"))]
pub const TRAPCOUNT: i32 = VSIGCOUNT;                                    // c:42

/// Port of `#define SIGEXIT` from `Src/signals.h:46`. Pseudo-signal
/// index for the EXIT trap (fires when the shell exits).
pub const SIGEXIT: i32 = 0;                                              // c:46

// ---------------------------------------------------------------------------
// Signal name table — port of the `sigs[SIGCOUNT+4]` array generated
// by `Src/signames2.awk` at build time. The C source feeds this awk
// the platform's `<signal.h>` and produces `signames.c` with one
// `"NAME"` entry per real signal plus the bookend pseudo-signal
// names (`"EXIT"` at slot 0, `"ZERR"` / `"DEBUG"` after the real
// signals, `NULL` terminator).
//
// Rust port collects the same data at compile time using the
// `libc::SIG*` constants. Each entry is `(canonical_name, signum)`;
// `sigs_name(idx)` and `sigs_number(name)` provide the same
// dispatch the awk-generated array gives C callers.
// ---------------------------------------------------------------------------

/// Port of `sigs[]` from `signames.c` (auto-generated). Lists the
/// canonical zsh signal name for every real signal — name without
/// the `SIG` prefix. Entries are platform-conditional via libc
/// constants so the table matches the running OS's `<signal.h>`.
pub static SIGS: &[(&str, i32)] = &[                                      // c:signames.c sigs[]
    ("HUP",    libc::SIGHUP),    ("INT",    libc::SIGINT),
    ("QUIT",   libc::SIGQUIT),   ("ILL",    libc::SIGILL),
    ("TRAP",   libc::SIGTRAP),   ("ABRT",   libc::SIGABRT),
    ("BUS",    libc::SIGBUS),    ("FPE",    libc::SIGFPE),
    ("KILL",   libc::SIGKILL),   ("USR1",   libc::SIGUSR1),
    ("SEGV",   libc::SIGSEGV),   ("USR2",   libc::SIGUSR2),
    ("PIPE",   libc::SIGPIPE),   ("ALRM",   libc::SIGALRM),
    ("TERM",   libc::SIGTERM),   ("CHLD",   libc::SIGCHLD),
    ("CONT",   libc::SIGCONT),   ("STOP",   libc::SIGSTOP),
    ("TSTP",   libc::SIGTSTP),   ("TTIN",   libc::SIGTTIN),
    ("TTOU",   libc::SIGTTOU),   ("URG",    libc::SIGURG),
    ("XCPU",   libc::SIGXCPU),   ("XFSZ",   libc::SIGXFSZ),
    ("VTALRM", libc::SIGVTALRM), ("PROF",   libc::SIGPROF),
    ("WINCH",  libc::SIGWINCH),  ("IO",     libc::SIGIO),
    ("SYS",    libc::SIGSYS),
];

/// Port of `alt_sigs[]` from `Src/jobs.c:2740`. Cross-platform name
/// aliases — names like `CLD` / `IO` / `IOT` map to the same number
/// as the canonical zsh name on platforms where the underlying
/// C macro pair coincides.
pub static ALT_SIGS: &[(&str, i32)] = &[                                  // c:jobs.c:2740
    ("CLD", libc::SIGCHLD),                                               // c:2742-2746
    ("IOT", libc::SIGABRT),                                               // c:2752-2756
    ("ERR", SIGZERR),                                                     // c:2762
];

/// Port of the `sig_msg[]` array from `signames.c` (auto-generated
/// by signames2.awk). Pretty-printed messages keyed by signal number,
/// used in the `printjob`/`printtime` output paths when zsh wants
/// to render a signal as e.g. `"hangup"` or `"floating point exception"`
/// rather than just `"SIGFPE"`. Each entry is `(signum, message)`.
pub static SIG_MSG: &[(i32, &str)] = &[                                   // c:signames.c sig_msg[]
    (libc::SIGHUP,    "hangup"),
    (libc::SIGINT,    "interrupt"),
    (libc::SIGQUIT,   "quit"),
    (libc::SIGILL,    "illegal hardware instruction"),
    (libc::SIGTRAP,   "trace trap"),
    (libc::SIGABRT,   "abort"),
    (libc::SIGBUS,    "bus error"),
    (libc::SIGFPE,    "floating point exception"),
    (libc::SIGKILL,   "killed"),
    (libc::SIGUSR1,   "user-defined signal 1"),
    (libc::SIGSEGV,   "segmentation fault"),
    (libc::SIGUSR2,   "user-defined signal 2"),
    (libc::SIGPIPE,   "broken pipe"),
    (libc::SIGALRM,   "alarm"),
    (libc::SIGTERM,   "terminated"),
    (libc::SIGCHLD,   "death of child"),
    (libc::SIGCONT,   "continued"),
    (libc::SIGSTOP,   "stopped (signal)"),
    (libc::SIGTSTP,   "stopped"),
    (libc::SIGTTIN,   "stopped (tty input)"),
    (libc::SIGTTOU,   "stopped (tty output)"),
    (libc::SIGURG,    "urgent condition"),
    (libc::SIGXCPU,   "cpu limit exceeded"),
    (libc::SIGXFSZ,   "file size limit exceeded"),
    (libc::SIGVTALRM, "virtual time alarm"),
    (libc::SIGPROF,   "profile signal"),
    (libc::SIGWINCH,  "window size changed"),
    (libc::SIGIO,     "i/o ready"),
    (libc::SIGSYS,    "invalid system call"),
];

/// Look up the canonical signal name for `idx` (sans `SIG` prefix).
/// Returns `"EXIT"` for slot 0, `"ZERR"`/`"DEBUG"` for the pseudo-
/// signal slots, the SIGS-table name for real signals, or `None`
/// when out of range. Mirrors C's `sigs[idx]` indexed lookup.
pub fn sigs_name(idx: i32) -> Option<&'static str> {                      // c:signames.c sigs[]
    if idx == 0           { return Some("EXIT"); }                        // c:slot 0
    if idx == SIGZERR     { return Some("ZERR"); }                        // c:SIGCOUNT+1
    if idx == SIGDEBUG    { return Some("DEBUG"); }                       // c:SIGCOUNT+2
    SIGS.iter().find(|(_, n)| *n == idx).map(|(name, _)| *name)
}

/// Reverse of `sigs_name` — accepts a name (with or without leading
/// `SIG`) and returns the libc signal number. Walks SIGS first, then
/// ALT_SIGS for cross-platform aliases.
pub fn sigs_number(name: &str) -> Option<i32> {                           // c:jobs.c:2828 lookup
    let bare = name.strip_prefix("SIG").unwrap_or(name);
    SIGS.iter().find(|(n, _)| *n == bare).map(|(_, num)| *num)
        .or_else(|| ALT_SIGS.iter().find(|(n, _)| *n == bare).map(|(_, num)| *num))
}

// ---------------------------------------------------------------------------
// SIGRTMIN/SIGRTMAX-aware index ↔ number conversion (c:39-44).
// ---------------------------------------------------------------------------

/// Port of `#define SIGNUM(x)` from `Src/signals.h:39`. Convert a
/// trap-table index back to a real signal number. Indexes >=
/// `VSIGCOUNT` are real-time-signal slots — those map back to
/// `SIGRTMIN + (x - VSIGCOUNT)`. Other indexes pass through unchanged.
#[inline]
#[allow(non_snake_case)]
pub fn SIGNUM(x: i32) -> i32 {                                           // c:39
    #[cfg(target_os = "linux")]
    {
        if x >= VSIGCOUNT {
            x - VSIGCOUNT + libc::SIGRTMIN()
        } else {
            x
        }
    }
    #[cfg(not(target_os = "linux"))]
    { x }
}

/// Port of `#define SIGIDX(x)` from `Src/signals.h:40`. Convert a
/// real signal number to its trap-table index. Numbers in the
/// `SIGRTMIN..=SIGRTMAX` range map to `(x - SIGRTMIN) + VSIGCOUNT`;
/// other numbers pass through unchanged.
#[inline]
#[allow(non_snake_case)]
pub fn SIGIDX(x: i32) -> i32 {                                           // c:40
    #[cfg(target_os = "linux")]
    {
        let rtmin = libc::SIGRTMIN();
        let rtmax = libc::SIGRTMAX();
        if x >= rtmin && x <= rtmax {
            x - rtmin + VSIGCOUNT
        } else {
            x
        }
    }
    #[cfg(not(target_os = "linux"))]
    { x }
}

// ---------------------------------------------------------------------------
// Queue size + per-signal queueing state (c:76, c:69-86, c:88-127).
//
// C uses module-globals: `queue_front`, `queue_rear`, `signal_queue[]`,
// `signal_mask_queue[]`, `queueing_enabled`, `queue_in` (debug only).
// The Rust port keeps `queueing_enabled` here as the central flag the
// queue_signals/unqueue_signals macros toggle; the actual queue
// arrays live in `signals.rs` per their C home (`Src/signals.c`).
// ---------------------------------------------------------------------------

/// Port of `#define MAX_QUEUE_SIZE` from `Src/signals.h:76`. Maximum
/// signal-queue depth before older entries get overwritten.
pub const MAX_QUEUE_SIZE: usize = 128;                                   // c:76

/// Port of the global `int queueing_enabled;` (Src/signals.c). The
// ---------------------------------------------------------------------------
// Signal-queueing macros (c:78-127). Ported as fns since Rust has
// no preprocessor macros. The mutable state (`queueing_enabled`,
// `queue_front`, `queue_rear`, `signal_queue[]`, `signal_mask_queue[]`)
// lives in `signals.rs` per `Src/signals.c:77-81`; these wrappers
// just call through.
// ---------------------------------------------------------------------------

/// Port of `#define queue_signals()` from `Src/signals.h:90/112`.
/// C body: `(queue_in++, queueing_enabled++)` — both counters bump.
#[inline]
#[allow(non_snake_case)]
pub fn queue_signals() {                                                 // c:90/112
    crate::ported::signals::queue_in.fetch_add(1, Ordering::SeqCst);
    crate::ported::signals::queueing_enabled.fetch_add(1, Ordering::SeqCst);
}

/// Port of `#define unqueue_signals()` from `Src/signals.h:92/114`.
/// C body decrements `queue_in` and `queueing_enabled`; when the
/// latter reaches 0, drains the signal queue via
/// `run_queued_signals()`.
#[inline]
#[allow(non_snake_case)]
pub fn unqueue_signals() {                                               // c:92/114
    crate::ported::signals::queue_in.fetch_sub(1, Ordering::SeqCst);
    let prev = crate::ported::signals::queueing_enabled.fetch_sub(1, Ordering::SeqCst);
    if prev == 1 {
        run_queued_signals();
    }
}

/// Port of `#define dont_queue_signals()` from `Src/signals.h:98/118`.
/// C body: `queue_in = queueing_enabled; queueing_enabled = 0`. The
/// `queue_in` snapshot lets `restore_queue_signals` later re-arm a
/// later DPUTS2 invariant check.
#[inline]
#[allow(non_snake_case)]
pub fn dont_queue_signals() {                                            // c:98/118
    let level = crate::ported::signals::queueing_enabled.swap(0, Ordering::SeqCst);
    crate::ported::signals::queue_in.store(level, Ordering::SeqCst);
    run_queued_signals();
}

/// Port of `#define restore_queue_signals(q)` from
/// `Src/signals.h:104/123`. Restore the queueing counter to a saved
/// value (typically captured before a section that called
/// `dont_queue_signals` or similar).
#[inline]
#[allow(non_snake_case)]
pub fn restore_queue_signals(q: i32) {                                   // c:104/123
    crate::ported::signals::queueing_enabled.store(q, Ordering::SeqCst);
}

/// Port of `#define queue_signal_level()` from `Src/signals.h:127`.
/// Read the current queueing-enabled level (caller can save + later
/// pass to `restore_queue_signals`).
#[inline]
#[allow(non_snake_case)]
pub fn queue_signal_level() -> i32 {                                     // c:127
    crate::ported::signals::queueing_enabled.load(Ordering::SeqCst)
}

/// Port of `#define run_queued_signals()` from `Src/signals.h:78-86`.
/// Drain queued signals by re-running the handler for each, restoring
/// the saved mask between deliveries.
///
/// C body (c:78-86):
/// ```c
/// while (queue_front != queue_rear) {
///     sigset_t oset;
///     queue_front = (queue_front + 1) % MAX_QUEUE_SIZE;
///     oset = signal_setmask(signal_mask_queue[queue_front]);
///     zhandler(signal_queue[queue_front]);
///     signal_setmask(oset);
/// }
/// ```
#[inline]
#[allow(non_snake_case)]
pub fn run_queued_signals() {                                            // c:78
    loop {
        let f = queue_front.load(Ordering::SeqCst);
        let r = queue_rear.load(Ordering::SeqCst);
        if f == r { break; }
        let nf = (f + 1) % MAX_QUEUE_SIZE;
        let sig = signal_queue[nf].load(Ordering::SeqCst);
        let mask = signal_mask_queue.lock().ok().and_then(|g| g.get(nf).copied());
        queue_front.store(nf, Ordering::SeqCst);
        if let Some(m) = mask {
            let _ = crate::ported::signals::signal_setmask(&m);
        }
        // Re-deliver via raise() so the installed handler runs again
        // with the original sig number.
        unsafe { libc::raise(sig); }
    }
}

// ---------------------------------------------------------------------------
// Block helpers (c:52-61).
//
// These wrap the lower-level `signal_block`/`signal_unblock` fns
// declared at c:129-130 (defined in signals.c). Rust ports as
// inline fns delegating to the same primitives in `signals.rs`.
// ---------------------------------------------------------------------------

/// Port of `#define child_block()` from `Src/signals.h:52`. Block
/// SIGCHLD so the parent can manipulate job-table state without
/// racing the reaper.
///
/// C body: `signal_block(signal_mask(SIGCHLD))`. The previous Rust
/// port was a no-op with a stale comment ("sigchld_mask not yet
/// wired") — but `signal_mask` and `signal_block` ARE both ported.
/// Without this block, the parent's job-table mutations could race
/// the SIGCHLD reaper inside wait_for_processes, corrupting jobtab
/// entries (e.g. setting STAT_DONE on a job the reaper hasn't seen).
#[inline]
#[allow(non_snake_case)]
#[cfg(unix)]
pub fn child_block() {                                                   // c:52
    let mask = crate::ported::signals::signal_mask(libc::SIGCHLD);
    let _ = crate::ported::signals::signal_block(&mask);
}

/// Non-unix no-op shim.
#[inline]
#[allow(non_snake_case)]
#[cfg(not(unix))]
pub fn child_block() {}

/// Port of `#define child_unblock()` from `Src/signals.h:53`.
/// Counterpart to `child_block`.
#[inline]
#[allow(non_snake_case)]
#[cfg(unix)]
pub fn child_unblock() {                                                 // c:53
    let mask = crate::ported::signals::signal_mask(libc::SIGCHLD);
    let _ = crate::ported::signals::signal_unblock(&mask);
}

/// Non-unix no-op shim.
#[inline]
#[allow(non_snake_case)]
#[cfg(not(unix))]
pub fn child_unblock() {}

/// Port of `#define winch_block()` from `Src/signals.h:56/59`.
/// Block SIGWINCH (terminal-resize signal) so prompt-redraw and
/// listing code can read terminal dimensions atomically.
///
/// C body: `signal_block(signal_mask(SIGWINCH))`. The previous Rust
/// port was a no-op with a stale comment ("signal_mask not yet
/// wired") — but `signal_mask` and `signal_block` ARE both ported
/// at `crate::ported::signals`. Now wired exactly per c:56.
#[inline]
#[allow(non_snake_case)]
#[cfg(unix)]
pub fn winch_block() {                                                   // c:56
    let mask = crate::ported::signals::signal_mask(libc::SIGWINCH);
    let _ = crate::ported::signals::signal_block(&mask);
}

/// Non-unix no-op shim.
#[inline]
#[allow(non_snake_case)]
#[cfg(not(unix))]
pub fn winch_block() {}

/// Port of `#define winch_unblock()` from `Src/signals.h:57/60`.
/// Counterpart to `winch_block`.
///
/// C body: `signal_unblock(signal_mask(SIGWINCH))`. Same wire-up
/// gap as winch_block — fixed now.
#[inline]
#[allow(non_snake_case)]
#[cfg(unix)]
pub fn winch_unblock() {                                                 // c:57
    let mask = crate::ported::signals::signal_mask(libc::SIGWINCH);
    let _ = crate::ported::signals::signal_unblock(&mask);
}

/// Non-unix no-op shim.
#[inline]
#[allow(non_snake_case)]
#[cfg(not(unix))]
pub fn winch_unblock() {}

// ---------------------------------------------------------------------------
// Convenience wrappers (c:64-67).
// ---------------------------------------------------------------------------

/// Port of `#define signal_ignore(S)` from `Src/signals.h:64`. Set
/// signal `s` to be ignored. C: `signal(S, SIG_IGN)` — returns the
/// PREVIOUS handler (the libc `signal(3)` contract). `init_signals`
/// at `Src/init.c:1418` reads this return value to detect a parent-
/// installed `SIG_IGN` on SIGHUP. Previously returned `()` — that
/// silently broke the c:1418 conditional, leaving the HUP option
/// always installed when the parent already had it set to SIG_IGN.
#[inline]
#[allow(non_snake_case)]
#[cfg(unix)]
pub fn signal_ignore(s: i32) -> libc::sighandler_t {                     // c:64
    unsafe { libc::signal(s, libc::SIG_IGN) }
}

/// Non-unix shim — same signature, no-op.
#[inline]
#[allow(non_snake_case)]
#[cfg(not(unix))]
pub fn signal_ignore(_s: i32) -> usize { 0 }

/// Port of `#define signal_default(S)` from `Src/signals.h:67`. Reset
/// signal `s` to its default action. C: `signal(S, SIG_DFL)` —
/// returns the PREVIOUS handler.
#[inline]
#[allow(non_snake_case)]
#[cfg(unix)]
pub fn signal_default(s: i32) -> libc::sighandler_t {                    // c:67
    unsafe { libc::signal(s, libc::SIG_DFL) }
}

/// Non-unix shim — same signature, no-op.
#[inline]
#[allow(non_snake_case)]
#[cfg(not(unix))]
pub fn signal_default(_s: i32) -> usize { 0 }

#[cfg(test)]
mod tests {
    use super::*;

    /// Verifies the pseudo-signal index ladder per c:34-46.
    #[test]
    fn pseudo_signal_indexes_correct() {
        assert_eq!(SIGEXIT, 0);
        assert_eq!(SIGZERR, SIGCOUNT + 1);
        assert_eq!(SIGDEBUG, SIGCOUNT + 2);
        assert_eq!(VSIGCOUNT, SIGCOUNT + 3);
        assert!(VSIGCOUNT > 0);
    }

    /// Verifies TRAPCOUNT >= VSIGCOUNT (= when no RT signals;
    /// > when RT signals are available).
    #[test]
    fn trapcount_at_least_vsigcount() {
        assert!(TRAPCOUNT >= VSIGCOUNT);
    }

    /// Verifies SIGNUM round-trips through SIGIDX for a non-RT signal.
    #[test]
    fn signum_sigidx_round_trip_for_normal_signal() {
        assert_eq!(SIGNUM(libc::SIGINT), libc::SIGINT);
        assert_eq!(SIGIDX(libc::SIGINT), libc::SIGINT);
    }

    /// Verifies MAX_QUEUE_SIZE per c:76.
    #[test]
    fn max_queue_size_is_128() {
        assert_eq!(MAX_QUEUE_SIZE, 128);
    }

    /// Verifies queue_signals / unqueue_signals balance the counter.
    #[test]
    fn queue_unqueue_balance() {
        let initial = queue_signal_level();
        queue_signals();
        assert_eq!(queue_signal_level(), initial + 1);
        queue_signals();
        assert_eq!(queue_signal_level(), initial + 2);
        unqueue_signals();
        assert_eq!(queue_signal_level(), initial + 1);
        unqueue_signals();
        assert_eq!(queue_signal_level(), initial);
    }

    /// Verifies dont_queue_signals zeroes the counter.
    #[test]
    fn dont_queue_signals_zeros_counter() {
        queue_signals();
        queue_signals();
        queue_signals();
        dont_queue_signals();
        assert_eq!(queue_signal_level(), 0);
    }

    /// Verifies restore_queue_signals sets the counter exactly.
    #[test]
    fn restore_queue_signals_sets_counter() {
        restore_queue_signals(0);
        restore_queue_signals(5);
        assert_eq!(queue_signal_level(), 5);
        restore_queue_signals(0);
    }

    /// `Src/signals.h:64` — `#define signal_ignore(S) signal(S, SIG_IGN)`.
    /// libc `signal(3)` returns the previous handler. Pin the round-
    /// trip: set SIG_IGN then SIG_DFL on a benign signal (SIGUSR2)
    /// and verify the returned previous-handler observation matches
    /// what we just installed. Previously the Rust port returned
    /// `()` — silently breaking `init_signals` at `Src/init.c:1418`
    /// which reads `signal_ignore(SIGHUP) == SIG_IGN` to detect a
    /// parent-installed-ignored HUP.
    #[cfg(unix)]
    #[test]
    fn signal_ignore_returns_previous_handler() {
        // Reset SIGUSR2 to default.
        let _ = signal_default(libc::SIGUSR2);
        // Install SIG_IGN — returns SIG_DFL (was reset above).
        let prev = signal_ignore(libc::SIGUSR2);
        assert_eq!(prev, libc::SIG_DFL,
            "c:64 — first signal_ignore must return prior SIG_DFL");
        // Install SIG_IGN again — returns SIG_IGN.
        let prev2 = signal_ignore(libc::SIGUSR2);
        assert_eq!(prev2, libc::SIG_IGN,
            "c:64 — second signal_ignore must return prior SIG_IGN");
        // Cleanup.
        let _ = signal_default(libc::SIGUSR2);
    }

    /// `Src/signals.h:67` — `#define signal_default(S) signal(S, SIG_DFL)`.
    /// Round-trip: install SIG_IGN, then signal_default — must
    /// return SIG_IGN (the prior handler).
    #[cfg(unix)]
    #[test]
    fn signal_default_returns_previous_handler() {
        let _ = signal_default(libc::SIGUSR2);
        let _ = signal_ignore(libc::SIGUSR2);
        let prev = signal_default(libc::SIGUSR2);
        assert_eq!(prev, libc::SIG_IGN,
            "c:67 — signal_default must return prior SIG_IGN");
        // Default→default returns SIG_DFL.
        let prev2 = signal_default(libc::SIGUSR2);
        assert_eq!(prev2, libc::SIG_DFL);
    }

    /// c:39-40 — `SIGNUM` and `SIGIDX` are inverses for every valid
    /// signal in `[0, VSIGCOUNT)`. Pin the round-trip property
    /// across the full range to catch a regen that breaks the
    /// formula at a corner (e.g. real-time signal boundary).
    #[cfg(unix)]
    #[test]
    fn signum_sigidx_round_trip_full_range() {
        for s in 1..VSIGCOUNT {
            let n = SIGNUM(s);
            let back = SIGIDX(n);
            assert_eq!(back, s,
                "round-trip failed at signal {}: SIGIDX(SIGNUM({})) = {}",
                s, s, back);
        }
    }

    /// c:signames.c — `sigs_name(0)` is SIGEXIT, traditionally
    /// named "EXIT" (not numeric "0"). Pin so a regen that drops
    /// the pseudo-signal handling silently returns "0".
    #[cfg(unix)]
    #[test]
    fn sigs_name_pseudo_signal_exit() {
        let n = sigs_name(SIGEXIT);
        assert!(n.is_some(), "SIGEXIT (index 0) must have a name");
        // Conventionally "EXIT", but accept any non-numeric stem
        let s = n.unwrap();
        assert!(!s.is_empty(),
            "SIGEXIT name must be non-empty (got {:?})", s);
    }

    /// c:signames.c — `sigs_name` for a well-known signal returns
    /// the canonical name (e.g. SIGINT → "INT").
    #[cfg(unix)]
    #[test]
    fn sigs_name_sigint_resolves() {
        let n = sigs_name(libc::SIGINT);
        // SIGIDX(SIGINT) may differ from libc::SIGINT depending on
        // mapping; try direct + idx.
        let alt = sigs_name(SIGIDX(libc::SIGINT));
        assert!(n.is_some() || alt.is_some(),
            "SIGINT must resolve to a name via direct or SIGIDX path");
    }

    /// c:signames.c — `sigs_name(-1)` or huge index returns None.
    /// Defensive contract: out-of-range must be a safe miss, not
    /// an OOB index into the table.
    #[test]
    fn sigs_name_out_of_range_returns_none() {
        assert!(sigs_name(-1).is_none());
        assert!(sigs_name(99999).is_none());
        assert!(sigs_name(TRAPCOUNT + 100).is_none());
    }

    /// c:jobs.c:2828 — `sigs_number("INT")` resolves to SIGINT.
    /// Pin reverse lookup so users can `kill -INT pid`.
    #[cfg(unix)]
    #[test]
    fn sigs_number_resolves_canonical_short_name() {
        assert!(sigs_number("INT").is_some(),
            "sigs_number(INT) must resolve");
        assert!(sigs_number("TERM").is_some());
        assert!(sigs_number("HUP").is_some());
        assert!(sigs_number("KILL").is_some());
    }

    /// c:jobs.c — `sigs_number` for unknown name returns None.
    /// Pin defensive miss; user `kill -BOGUS` must fail-soft.
    #[test]
    fn sigs_number_unknown_returns_none() {
        assert!(sigs_number("ZZBOGUSXX").is_none());
        assert!(sigs_number("").is_none());
        assert!(sigs_number("not_a_signal").is_none());
    }

    /// c:78 — `run_queued_signals` is safe to call even when no
    /// signals have been queued. Pin no-panic contract for the
    /// no-op path.
    #[test]
    fn run_queued_signals_with_empty_queue_is_safe() {
        // Reset: ensure nothing queued.
        dont_queue_signals();
        run_queued_signals();
        run_queued_signals(); // re-entry safety
    }

    /// c:104/123 — `restore_queue_signals(-1)` MUST NOT panic.
    /// Defensive boundary because the C source's `oqs = qs` walk
    /// can produce arbitrary saved values; the restore must not
    /// crash on weird input.
    #[test]
    fn restore_queue_signals_negative_value_is_safe() {
        let saved = queue_signal_level();
        restore_queue_signals(-1);
        // Most impls clamp; just ensure no panic
        let _ = queue_signal_level();
        // Restore real state
        restore_queue_signals(saved.max(0));
    }

    /// c:34-38 — Every pseudo-signal index lies above SIGCOUNT.
    /// Pin layering: pseudo signals must NOT collide with real
    /// libc signal numbers, which are bounded by SIGCOUNT.
    #[test]
    fn pseudo_signals_above_libc_signal_range() {
        assert!(SIGZERR > SIGCOUNT,
            "SIGZERR ({}) must be > SIGCOUNT ({}) to avoid libc collision",
            SIGZERR, SIGCOUNT);
        assert!(SIGDEBUG > SIGCOUNT,
            "SIGDEBUG ({}) must be > SIGCOUNT ({})",
            SIGDEBUG, SIGCOUNT);
        // Each pseudo-signal is distinct
        assert_ne!(SIGZERR, SIGDEBUG);
        assert_ne!(SIGZERR, SIGEXIT);
        assert_ne!(SIGDEBUG, SIGEXIT);
    }
}