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
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
//! `zsh/zprof` module — port of `Src/Modules/zprof.c`.
//!
//! Shell-function profiling: every function call is wrapped via
//! `zprof_wrapper` to record entry/exit time, build a per-function
//! `Pfunc` table and a per-arc (caller→callee) `Parc` table, and
//! emit a sorted report from `bin_zprof`.
//!
//! C source: 11 fns total — `freepfuncs`, `freeparcs`, `findpfunc`,
//! `findparc`, `cmpsfuncs`, `cmptfuncs`, `cmpparcs`, `bin_zprof`,
//! `name_for_anonymous_function`, `zprof_wrapper`, plus 6 module
//! loaders. 3 structs: `pfunc` (c:38), `sfunc` (c:49), `parc` (c:57).
//! 6 file-statics: `calls`, `ncalls`, `arcs`, `narcs`, `stack`,
//! `zprof_module` (c:66-71).
//!
//! Order in this file mirrors C source order verbatim.

use std::sync::atomic::{AtomicBool, AtomicI32, Ordering};
use std::sync::{Mutex, OnceLock};
use crate::ported::zsh_h::OPT_ISSET;

// ---------------------------------------------------------------------------
// Structs (port of c:36-64).
// ---------------------------------------------------------------------------

/// Port of `struct pfunc` from `Src/Modules/zprof.c:38`.
/// Per-function aggregated profiling record.
///
/// C definition (c:38-45):
/// ```c
/// struct pfunc {
///     Pfunc next;     /* linked list — Vec replaces */
///     char *name;
///     long calls;
///     double time;
///     double self;
///     long num;
/// };
/// ```
#[derive(Debug, Clone, Default)]
pub struct Pfunc {                                                       // c:38
    pub name: String,                                                    // c:40
    pub calls: i64,                                                      // c:41
    pub time: f64,                                                       // c:42
    pub self_time: f64,                                                  // c:43 — `self` is a Rust keyword
    pub num: i64,                                                        // c:44
}

/// Port of `struct sfunc` from `Src/Modules/zprof.c:49`.
/// Per-active-call stack frame: linked stack the C `zprof_wrapper`
/// pushes on entry and pops on exit, used to compute self-time and
/// build the caller→callee arc.
///
/// C definition (c:49-53):
/// ```c
/// struct sfunc {
///     Pfunc p;       /* index into CALLS — Rust uses usize */
///     Sfunc prev;    /* linked list — Vec replaces */
///     double beg;
/// };
/// ```
#[derive(Debug, Clone, Copy)]
pub struct Sfunc {                                                       // c:49
    pub p: usize,                                                        // c:50 — index into CALLS
    pub beg: f64,                                                        // c:52
}

/// Port of `struct parc` from `Src/Modules/zprof.c:57`.
/// Per-(caller→callee) aggregated arc with timing.
///
/// C definition (c:57-64):
/// ```c
/// struct parc {
///     Parc next;     /* linked list — Vec replaces */
///     Pfunc from;    /* indices into CALLS */
///     Pfunc to;
///     long calls;
///     double time;
///     double self;
/// };
/// ```
#[derive(Debug, Clone, Default)]
pub struct Parc {                                                        // c:57
    pub from: usize,                                                     // c:59 — index into CALLS
    pub to: usize,                                                       // c:60 — index into CALLS
    pub calls: i64,                                                      // c:61
    pub time: f64,                                                       // c:62
    pub self_time: f64,                                                  // c:63 — `self` is a Rust keyword
}

// ---------------------------------------------------------------------------
// Helpers (port of c:73-136).
// ---------------------------------------------------------------------------

/// Port of `freepfuncs(Pfunc f)` from `Src/Modules/zprof.c:74`. C iterates
/// the linked list calling `zsfree(name)` + `zfree(node)` on each
/// entry. Rust port clears the `Vec`; the contained `String`s and
/// `Pfunc` slots are dropped at scope-exit.
///
/// C signature: `static void freepfuncs(Pfunc f)`.
pub fn freepfuncs(f: &mut Vec<Pfunc>) {                                  // c:74
    f.clear();                                                           // c:86-82 zsfree+zfree
}

/// Port of `freeparcs(Parc a)` from `Src/Modules/zprof.c:86`.
///
/// C signature: `static void freeparcs(Parc a)`.
pub fn freeparcs(a: &mut Vec<Parc>) {                                    // c:86
    a.clear();                                                           // c:97-93 zfree
}

/// Port of `findpfunc(char *name)` from `Src/Modules/zprof.c:97`. Linear-scan
/// lookup in the `calls` list for an entry with matching `name`.
///
/// C signature: `static Pfunc findpfunc(char *name)`. Returns NULL on
/// miss; Rust port returns `None`.
pub fn findpfunc(name: &str) -> Option<usize> {                          // c:97
    // c:109-103 — `for (f = calls; f; f = f->next) if (!strcmp(name, f->name)) return f;`
    let calls = CALLS.lock().unwrap();
    calls.iter().position(|f| f.name == name)
}

/// Port of `findparc(Pfunc f, Pfunc t)` from `Src/Modules/zprof.c:109`. Linear-scan
/// lookup in the `arcs` list for an arc with matching (from, to)
/// pair.
///
/// C signature: `static Parc findparc(Pfunc f, Pfunc t)`.
pub fn findparc(f: usize, t: usize) -> Option<usize> {               // c:109
    // c:109-115 — `for (a = arcs; a; a = a->next) if (a->f == f && a->t == t) return a;`
    let arcs = ARCS.lock().unwrap();
    arcs.iter().position(|a| a.from == f && a.to == t)
}

/// Port of `cmpsfuncs(Pfunc *a, Pfunc *b)` from `Src/Modules/zprof.c:121`. The qsort
/// comparator: descending by `self`. C uses `Pfunc *` pointers
/// because qsort passes opaque ptrs; Rust takes refs directly.
///
/// C body:
/// ```c
/// return ((*a)->self > (*b)->self ? -1 :
///         ((*a)->self != (*b)->self));
/// ```
/// (i.e. -1 if a > b, 0 if equal, +1 if a < b — descending order.)
pub fn cmpsfuncs(a: &Pfunc, b: &Pfunc) -> std::cmp::Ordering {           // c:121
    b.self_time.partial_cmp(&a.self_time).unwrap_or(std::cmp::Ordering::Equal)
}

/// Port of `cmptfuncs(Pfunc *a, Pfunc *b)` from `Src/Modules/zprof.c:127`. Comparator
/// for descending by total `time`.
pub fn cmptfuncs(a: &Pfunc, b: &Pfunc) -> std::cmp::Ordering {           // c:127
    b.time.partial_cmp(&a.time).unwrap_or(std::cmp::Ordering::Equal)
}

/// Port of `cmpparcs(Parc *a, Parc *b)` from `Src/Modules/zprof.c:133`. Comparator
/// for descending by arc `time`.
pub fn cmpparcs(a: &Parc, b: &Parc) -> std::cmp::Ordering {              // c:133
    b.time.partial_cmp(&a.time).unwrap_or(std::cmp::Ordering::Equal)
}

// ---------------------------------------------------------------------------
// `bin_zprof` (port of c:139-214).
// ---------------------------------------------------------------------------

/// Port of `bin_zprof(UNUSED(char *nam), UNUSED(char **args), Options ops, UNUSED(int func))` from `Src/Modules/zprof.c:139`.
///
/// C signature: `static int bin_zprof(char *nam, char **args,
///                                     Options ops, int func)`.
/// Builtin spec: `"c"` (c:315) — the `-c` option clears the tables.
/// No positional args (`0,0` arity at c:315).
///
/// `-c` set → free both tables and reset counters. `-c` unset →
/// sort by self-time, print the c:170 header + per-function row,
/// re-sort by total-time, print the c:184 per-function caller/callee
/// blocks.
/// WARNING: param names don't match C — Rust=(_nam, _args, _func) vs C=(nam, args, ops, func)
pub fn bin_zprof(_nam: &str, _args: &[String],                               // c:139
                 ops: &crate::ported::zsh_h::options, _func: i32) -> i32 {
    // c:140 — `if (OPT_ISSET(ops,'c'))`
    let opt_c = OPT_ISSET(ops, b'c');

    if opt_c {
        // c:141-147 — free both tables + reset counters.
        let mut calls = CALLS.lock().unwrap();
        freepfuncs(&mut calls);                                          // c:142
        NCALLS.store(0, Ordering::SeqCst);                               // c:144
        let mut arcs = ARCS.lock().unwrap();
        freeparcs(&mut arcs);                                            // c:145
        NARCS.store(0, Ordering::SeqCst);                                // c:147
        return 0;                                                        // c:213
    }

    // c:149-211 — print path.
    let calls = CALLS.lock().unwrap();
    let arcs = ARCS.lock().unwrap();

    // c:149-163 — gather + total. C uses a VARARR Pfunc fs[ncalls+1]
    // and a VARARR Parc as[narcs+1] with NULL sentinels; Rust uses
    // index arrays. `total` is the sum of self-times across all funcs.
    let mut fs: Vec<usize> = (0..calls.len()).collect();                 // c:149-159
    let as_arcs: Vec<usize> = (0..arcs.len()).collect();                 // c:151-163
    let mut total: f64 = 0.0;                                            // c:154
    for &i in &fs {
        total += calls[i].self_time;                                     // c:158 total += f->self;
    }

    // c:165-166 — `qsort(fs, ncalls, sizeof(f), cmpsfuncs);`
    fs.sort_by(|&a, &b| cmpsfuncs(&calls[a], &calls[b]));

    // c:170 — header.
    println!("num  calls                time                       self            name");
    println!("-----------------------------------------------------------------------------------");

    // c:171-180 — primary listing, also assigns `num` in display order.
    // Mutating `num` in C requires reborrowing — release the read lock
    // briefly to take a write lock, then reacquire read order.
    drop(calls);
    {
        let mut calls_w = CALLS.lock().unwrap();
        for (i, &idx) in fs.iter().enumerate() {                         // c:171
            calls_w[idx].num = (i + 1) as i64;                           // c:173
        }
    }
    let calls = CALLS.lock().unwrap();
    for &idx in &fs {                                                    // c:171 again, after num assignment
        let f = &calls[idx];
        let avg_t = if f.calls > 0 { f.time / f.calls as f64 } else { 0.0 };
        let avg_s = if f.calls > 0 { f.self_time / f.calls as f64 } else { 0.0 };
        let pct_t = if total != 0.0 { (f.time / total) * 100.0 } else { 0.0 };
        let pct_s = if total != 0.0 { (f.self_time / total) * 100.0 } else { 0.0 };
        println!(
            "{:2}) {:4}       {:8.2} {:8.2}  {:6.2}%  {:8.2} {:8.2}  {:6.2}%  {}",
            f.num, f.calls,                                              // c:172-179 printf
            f.time, avg_t, pct_t,
            f.self_time, avg_s, pct_s,
            f.name
        );
    }

    // c:181-182 — `qsort(fs, ncalls, sizeof(f), cmptfuncs);`
    let mut fs_t: Vec<usize> = fs.clone();
    fs_t.sort_by(|&a, &b| cmptfuncs(&calls[a], &calls[b]));

    // c:184-211 — per-function caller/callee blocks.
    for &fp_idx in &fs_t {                                               // c:184
        println!();
        println!("-----------------------------------------------------------------------------------");
        println!();
        let f = &calls[fp_idx];

        // c:186-194 — callers (arcs where to == fp).
        for &ap in &as_arcs {                                            // c:186
            let a = &arcs[ap];
            if a.to == fp_idx {                                          // c:187
                let avg_t = if a.calls > 0 { a.time / a.calls as f64 } else { 0.0 };
                let avg_s = if a.calls > 0 { a.self_time / a.calls as f64 } else { 0.0 };
                let pct_t = if total != 0.0 { (a.time / total) * 100.0 } else { 0.0 };
                let from_name = &calls[a.from].name;
                let from_num = calls[a.from].num;
                println!(
                    "    {:4}/{:<4}  {:8.2} {:8.2}  {:6.2}%  {:8.2} {:8.2}             {} [{}]",
                    a.calls, f.calls,                                    // c:188-193 printf
                    a.time, avg_t, pct_t,
                    a.self_time, avg_s,
                    from_name, from_num
                );
            }
        }

        // c:195-201 — the function's own row.
        let avg_t = if f.calls > 0 { f.time / f.calls as f64 } else { 0.0 };
        let avg_s = if f.calls > 0 { f.self_time / f.calls as f64 } else { 0.0 };
        let pct_t = if total != 0.0 { (f.time / total) * 100.0 } else { 0.0 };
        let pct_s = if total != 0.0 { (f.self_time / total) * 100.0 } else { 0.0 };
        println!(
            "{:2}) {:4}       {:8.2} {:8.2}  {:6.2}%  {:8.2} {:8.2}  {:6.2}%  {}",
            f.num, f.calls,                                              // c:195-201 printf
            f.time, avg_t, pct_t,
            f.self_time, avg_s, pct_s,
            f.name
        );

        // c:202-210 — callees (arcs where from == fp), iterated in
        // reverse to match C's `for (ap = as + narcs - 1; ap >= as; ap--)`.
        for &ap in as_arcs.iter().rev() {                                // c:202
            let a = &arcs[ap];
            if a.from == fp_idx {                                        // c:203
                let avg_t = if a.calls > 0 { a.time / a.calls as f64 } else { 0.0 };
                let avg_s = if a.calls > 0 { a.self_time / a.calls as f64 } else { 0.0 };
                let pct_t = if total != 0.0 { (a.time / total) * 100.0 } else { 0.0 };
                let to_name = &calls[a.to].name;
                let to_num = calls[a.to].num;
                let to_calls = calls[a.to].calls;
                println!(
                    "    {:4}/{:<4}  {:8.2} {:8.2}  {:6.2}%  {:8.2} {:8.2}             {} [{}]",
                    a.calls, to_calls,                                   // c:204-209 printf
                    a.time, avg_t, pct_t,
                    a.self_time, avg_s,
                    to_name, to_num
                );
            }
        }
    }

    0                                                                    // c:217
}

/// Port of `name_for_anonymous_function(char *name)` from `Src/Modules/zprof.c:217`.
/// Anonymous functions don't have a real name; the profiler synthesises
/// `name [filename:lineno]` using the current `funcstack[0]` frame.
///
/// C signature: `static char *name_for_anonymous_function(char *name)`.
/// Rust port takes the placeholder name + `(filename, lineno)` pair
/// the caller pulls from the funcstack.
/// WARNING: param names don't match C — Rust=(name, filename, lineno) vs C=(name)
pub fn name_for_anonymous_function(name: &str, filename: &str, lineno: i32) -> String {  // c:217
    // c:217 — `convbase(lineno, funcstack[0].flineno, 10);`
    // c:224-230 — `parts[] = { name, " [", filename, ":", lineno, "]", NULL };`
    // c:232 — `return sepjoin(parts, "", 1);`
    format!("{} [{}:{}]", name, filename, lineno)
}

/// Port of `zprof_wrapper(Eprog prog, FuncWrap w, char *name)` from `Src/Modules/zprof.c:236`. The
/// per-function-call wrapper hook: records call entry, measures wall
/// time, runs the wrapped function via `runshfunc`, then accumulates
/// self/total time on the function's `pfunc` entry and on the
/// (caller→callee) `parc` arc.
///
/// C signature: `static int zprof_wrapper(Eprog prog, FuncWrap w, char *name)`.
///
/// C body (c:238-311):
/// 1. Resolve `name_for_lookups` via `name_for_anonymous_function` for
///    anonymous funcs (c:246-250).
/// 2. If `zprof_module` is loaded (c:252), find-or-create the Pfunc
///    (c:254-262), find-or-create the caller→callee Parc (c:263-274),
///    push the Sfunc frame and record start time (c:275-283).
/// 3. `runshfunc(prog, w, name)` (c:285) — runs the wrapped function.
/// 4. On return, recompute elapsed time, update Pfunc.self_time
///    (c:293), Pfunc.time when non-recursive (c:294-296), Parc.calls/
///    self/time (c:297-307), pop the stack frame (c:301).
///
/// zshrs's call-execution path doesn't have an `addwrapper`-installable
/// runshfunc callback, so the live integration is the executor's
/// funcstack push/pop hooks (in `crate::ported::exec`). This entry is
/// the static-link stub that mirrors C's `return 0;` exit path; the
/// actual timing accumulation happens via direct CALLS/ARCS/STACK
/// updates from the executor when `ZPROF_MODULE` is true.
/// Port of `static int zprof_wrapper(Eprog prog, FuncWrap w, char *name)`
/// from `Src/Modules/zprof.c:236`.
///
/// ```c
/// static int
/// zprof_wrapper(Eprog prog, FuncWrap w, char *name)
/// {
///     int active = 0;
///     struct sfunc sf, *sp;
///     Pfunc f = NULL;
///     Parc a = NULL;
///     struct timespec ts;
///     double prev = 0, now;
///     char *name_for_lookups;
///     if (is_anonymous_function_name(name))
///         name_for_lookups = name_for_anonymous_function(name);
///     else
///         name_for_lookups = name;
///     if (zprof_module && !(zprof_module->node.flags & MOD_UNLOAD)) {
///         active = 1;
///         if (!(f = findpfunc(name_for_lookups))) { ... append calls ... }
///         if (stack) {
///             if (!(a = findparc(stack->p, f))) { ... append arcs ... }
///         }
///         sf.prev = stack; sf.p = f; stack = &sf;
///         f->calls++;
///         zgettime_monotonic_if_available(&ts);
///         sf.beg = prev = ms_now(ts);
///     }
///     runshfunc(prog, w, name);
///     if (active) {
///         if (zprof_module && !(zprof_module->node.flags & MOD_UNLOAD)) {
///             zgettime_monotonic_if_available(&ts);
///             now = ms_now(ts);
///             f->self += now - sf.beg;
///             for (sp = sf.prev; sp && sp->p != f; sp = sp->prev);
///             if (!sp) f->time += now - prev;
///             if (a) { a->calls++; a->self += now - sf.beg; }
///             stack = sf.prev;
///             if (stack) { stack->beg += now - prev;
///                          if (a) a->time += now - prev; }
///         } else stack = sf.prev;
///     }
///     return 0;
/// }
/// ```
#[allow(non_snake_case)]
pub fn zprof_wrapper(prog: *const crate::ported::zsh_h::eprog,              // c:236
                     w: *const crate::ported::zsh_h::funcwrap,
                     name: &str) -> i32 {
    let mut active: i32 = 0;                                                 // c:238
    let mut sf = Sfunc { p: 0, beg: 0.0 };                                   // c:239 struct sfunc sf
    let mut f: Option<usize> = None;                                         // c:240 Pfunc f = NULL
    let mut a: Option<usize> = None;                                         // c:241 Parc a = NULL
    let mut prev: f64 = 0.0;                                                 // c:243 double prev = 0

    // c:246-250 — resolve display name for anonymous functions.
    // `is_anonymous_function_name(name)` is `!strcmp(name, "(anon)")`
    // per Src/exec.c:5303-5306. ANONYMOUS_FUNCTION_NAME = "(anon)".
    let name_for_lookups: String = if name == "(anon)" {                     // c:246
        // `name_for_anonymous_function(name)` (exec.c:5292): walks the
        // funcstack to recover the source filename + line. The Rust
        // port (above in this file) takes (name, filename, lineno);
        // without the funcstack walk wired here, pass empty placeholders
        // so the call shape is preserved.
        name_for_anonymous_function(name, "", 0)                             // c:247
    } else {                                                                 // c:248
        name.to_string()                                                     // c:249
    };

    if ZPROF_MODULE.load(Ordering::SeqCst) {                                 // c:252
        active = 1;                                                          // c:253
        f = findpfunc(&name_for_lookups);                                    // c:254
        if f.is_none() {                                                     // c:254
            // c:255-261 — `f = zalloc(...); f->name = ztrdup(...); f->next = calls; calls = f; ncalls++;`
            let new_pfunc = Pfunc {                                          // c:255
                name: crate::ported::mem::ztrdup(&name_for_lookups),         // c:256
                calls: 0,                                                    // c:257
                time: 0.0,                                                   // c:258 self/time = 0
                self_time: 0.0,                                              // c:258
                num: 0,
            };
            let mut calls = CALLS.lock().unwrap();
            f = Some(calls.len());                                           // c:260 head-insert in C; Rust appends
            calls.push(new_pfunc);                                           // c:260
            NCALLS.fetch_add(1, Ordering::SeqCst);                           // c:261
        }
        // c:263 — `if (stack)` — top-of-stack frame exists.
        let stack_top: Option<Sfunc> = {                                     // c:263
            let st = STACK.lock().unwrap();
            st.last().copied()
        };
        if let Some(top) = stack_top {                                       // c:263
            a = findparc(top.p, f.unwrap());                                 // c:264
            if a.is_none() {                                                 // c:264
                let new_parc = Parc {                                        // c:265
                    from: top.p,                                             // c:266
                    to: f.unwrap(),                                          // c:267
                    calls: 0,                                                // c:268
                    self_time: 0.0,                                          // c:269
                    time: 0.0,                                               // c:269
                };
                let mut arcs = ARCS.lock().unwrap();
                a = Some(arcs.len());                                        // c:271
                arcs.push(new_parc);                                         // c:271
                NARCS.fetch_add(1, Ordering::SeqCst);                        // c:272
            }
        }
        // c:275-277 — `sf.prev = stack; sf.p = f; stack = &sf;`
        sf.p = f.unwrap();                                                   // c:276
        STACK.lock().unwrap().push(sf);                                      // c:277 stack = &sf

        // c:279 — `f->calls++;`
        {
            let mut calls = CALLS.lock().unwrap();
            calls[f.unwrap()].calls += 1;                                    // c:279
        }
        // c:280-283 — read monotonic clock, compute prev (ms).
        let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 };               // c:280
        crate::ported::compat::zgettime_monotonic_if_available(&mut ts);     // c:281
        sf.beg = (ts.tv_sec as f64) * 1000.0 + (ts.tv_nsec as f64) / 1_000_000.0;  // c:282-283
        prev = sf.beg;                                                       // c:282
        // Update the stack-top copy we just pushed.
        let mut st = STACK.lock().unwrap();
        if let Some(top) = st.last_mut() { top.beg = sf.beg; }
    }

    // c:285 — `runshfunc(prog, w, name);`
    // runshfunc isn't yet ported as a free fn — the wrapped invocation
    // happens at the executor level (src/exec.rs::dispatch_function_call).
    // Keep the C call slot visible; live integration occurs there.
    let _ = (prog, w);                                                       // c:285 runshfunc(prog, w, name)

    if active != 0 {                                                         // c:286
        if ZPROF_MODULE.load(Ordering::SeqCst) {                             // c:287
            let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 };           // c:288
            crate::ported::compat::zgettime_monotonic_if_available(&mut ts); // c:289
            let now = (ts.tv_sec as f64) * 1000.0 + (ts.tv_nsec as f64) / 1_000_000.0;  // c:291-292

            // c:293 — `f->self += now - sf.beg;`
            {
                let mut calls = CALLS.lock().unwrap();
                if let Some(idx) = f {
                    calls[idx].self_time += now - sf.beg;                    // c:293
                }
            }
            // c:294 — recursion-detect: walk sf.prev looking for f.
            let recursion: bool = {                                          // c:294
                let st = STACK.lock().unwrap();
                let cur_f = f.unwrap();
                // sf.prev = the frame underneath sf — walk it down.
                st.iter().rev().skip(1).any(|fr| fr.p == cur_f)
            };
            if !recursion {                                                  // c:295
                let mut calls = CALLS.lock().unwrap();
                if let Some(idx) = f {
                    calls[idx].time += now - prev;                           // c:296
                }
            }
            if let Some(arc_idx) = a {                                       // c:297
                let mut arcs = ARCS.lock().unwrap();
                arcs[arc_idx].calls += 1;                                    // c:298
                arcs[arc_idx].self_time += now - sf.beg;                     // c:299
            }
            // c:301 — `stack = sf.prev;`
            {
                let mut st = STACK.lock().unwrap();
                st.pop();                                                    // c:301
            }
            // c:303-307 — propagate elapsed up to caller frame.
            let mut st = STACK.lock().unwrap();
            if let Some(top) = st.last_mut() {                               // c:303
                top.beg += now - prev;                                       // c:304
                if let Some(arc_idx) = a {                                   // c:305
                    drop(st);
                    let mut arcs = ARCS.lock().unwrap();
                    arcs[arc_idx].time += now - prev;                        // c:306
                }
            }
        } else {                                                             // c:308
            // c:309 — `stack = sf.prev;`
            let mut st = STACK.lock().unwrap();
            st.pop();
        }
    }
    0                                                                        // c:311
}

// `bintab` — port of `static struct builtin bintab[]` (zprof.c:309).


// `module_features` — port of `static struct features module_features`
// from zprof.c:323.



/// Port of `setup_(UNUSED(Module m))` from `Src/Modules/zprof.c:332`.
/// C body: `zprof_module = m; return 0;`
#[allow(unused_variables)]
pub fn setup_(m: *const module) -> i32 {                                // c:332
    ZPROF_MODULE.store(true, Ordering::SeqCst);                          // c:340
    0                                                                    // c:348
}

/// Port of `features_(UNUSED(Module m), UNUSED(char ***features))` from `Src/Modules/zprof.c:340`.
/// C body: `*features = featuresarray(m, &module_features); return 0;`
pub fn features_(m: *const module, features: &mut Vec<String>) -> i32 { // c:340
    *features = featuresarray(m, module_features());
    0                                                                    // c:355
}

/// Port of `enables_(UNUSED(Module m), UNUSED(int **enables))` from `Src/Modules/zprof.c:348`.
/// C body: `return handlefeatures(m, &module_features, enables);`
pub fn enables_(m: *const module, enables: &mut Option<Vec<i32>>) -> i32 { // c:348
    handlefeatures(m, module_features(), enables) // c:355
}

/// Port of `boot_(UNUSED(Module m))` from `Src/Modules/zprof.c:355`.
#[allow(unused_variables)]
pub fn boot_(m: *const module) -> i32 {                                 // c:355
    let mut calls = CALLS.lock().unwrap();
    calls.clear();                                                       // c:367
    NCALLS.store(0, Ordering::SeqCst);                                   // c:367
    let mut arcs = ARCS.lock().unwrap();
    arcs.clear();                                                        // c:367
    NARCS.store(0, Ordering::SeqCst);                                    // c:367
    STACK.lock().unwrap().clear();                                       // c:367
    0                                                                    // c:367 addwrapper return
}

/// Port of `cleanup_(UNUSED(Module m))` from `Src/Modules/zprof.c:367`.
/// C body: free pfuncs + parcs, deletewrapper, setfeatureenables.
pub fn cleanup_(m: *const module) -> i32 {                              // c:367
    let mut calls = CALLS.lock().unwrap();
    freepfuncs(&mut calls);                                              // c:377
    let mut arcs = ARCS.lock().unwrap();
    freeparcs(&mut arcs);                                                // c:377
    ZPROF_MODULE.store(false, Ordering::SeqCst);
    setfeatureenables(m, module_features(), None) // c:377
}

/// Port of `finish_(UNUSED(Module m))` from `Src/Modules/zprof.c:377`.
#[allow(unused_variables)]
pub fn finish_(m: *const module) -> i32 {                                   // c:377
    // C body c:379-380 — `return 0`. Faithful empty-body port; the
    //                    profiling tables get freed by cleanup_ via
    //                    setfeatureenables/zprof_cleanup.
    0
}

// ---------------------------------------------------------------------------
// Module loaders.
// ---------------------------------------------------------------------------

// =====================================================================
// static struct builtin bintab[]                                    c:309
// static struct features module_features                            c:323
// static struct funcwrap wrapper[]                                  c:328
// =====================================================================

use crate::ported::zsh_h::module;

// ---------------------------------------------------------------------------
// File-static globals — port of c:66-71.
// ---------------------------------------------------------------------------

/// Port of `static Pfunc calls;` from `Src/Modules/zprof.c:66`.
/// Per-function aggregated table; the C linked list becomes a
/// `Mutex<Vec<Pfunc>>` so `Pfunc *` becomes `usize` index.
pub static CALLS: Mutex<Vec<Pfunc>> = Mutex::new(Vec::new());            // c:66

/// Port of `static int ncalls;` from `Src/Modules/zprof.c:67`. Always
/// equals `CALLS.lock().len()` — kept as an explicit counter to
/// match C's `ncalls++` increment pattern.
pub static NCALLS: AtomicI32 = AtomicI32::new(0);                        // c:67

/// Port of `static Parc arcs;` from `Src/Modules/zprof.c:68`.
pub static ARCS: Mutex<Vec<Parc>> = Mutex::new(Vec::new());              // c:68

/// Port of `static int narcs;` from `Src/Modules/zprof.c:69`.
pub static NARCS: AtomicI32 = AtomicI32::new(0);                         // c:69

/// Port of `static Sfunc stack;` from `Src/Modules/zprof.c:70`. The
/// C linked stack becomes a `Mutex<Vec<Sfunc>>` (top of stack at
/// `last()`).
pub static STACK: Mutex<Vec<Sfunc>> = Mutex::new(Vec::new());            // c:70

/// Port of `static Module zprof_module;` from `Src/Modules/zprof.c:71`.
/// C uses a `Module` (struct module *) pointer to track which module
/// owns the wrapper; `zprof_wrapper` short-circuits when
/// `MOD_UNLOAD` is set on it. Module is ported as
/// `Box<crate::ported::zsh_h::module>` (zsh_h.rs:425) but recording
/// the raw `*const module` would deadlock with Sync/Send for the
/// static — `AtomicBool` captures the only state `zprof_wrapper`
/// actually inspects (loaded vs. unloading), matching the C
/// `MOD_UNLOAD` flag-check on the same pointer.
pub static ZPROF_MODULE: AtomicBool = AtomicBool::new(false);            // c:74



use crate::ported::zsh_h::features as features_t;

static MODULE_FEATURES: OnceLock<Mutex<features_t>> = OnceLock::new();


// Local stubs for the per-module entry points. C uses generic
// `featuresarray`/`handlefeatures`/`setfeatureenables` (module.c:
// 3275/3370/3445) but those take `Builtin` + `Features` pointer
// fields the Rust port doesn't carry. The hardcoded descriptor
// list mirrors the C bintab/conddefs/mathfuncs/paramdefs.
// WARNING: NOT IN ZPROF.C — Rust-only module-framework shim.
// C uses generic featuresarray/handlefeatures/setfeatureenables from
// Src/module.c:3275/3370/3445 with C-side Builtin/Features pointers;
// Rust per-module shims hardcode the bintab/conddefs/mathfuncs/paramdefs.
fn featuresarray(_m: *const module, _f: &Mutex<features_t>) -> Vec<String> {
    vec!["b:zprof".to_string()]
}

// WARNING: NOT IN ZPROF.C — Rust-only module-framework shim.
// C uses generic featuresarray/handlefeatures/setfeatureenables from
// Src/module.c:3275/3370/3445 with C-side Builtin/Features pointers;
// Rust per-module shims hardcode the bintab/conddefs/mathfuncs/paramdefs.
fn handlefeatures(
    _m: *const module,
    _f: &Mutex<features_t>,
    enables: &mut Option<Vec<i32>>,
) -> i32 {
    if enables.is_none() {
        *enables = Some(vec![1; 1]);
    }
    0
}

// WARNING: NOT IN ZPROF.C — Rust-only module-framework shim.
// C uses generic featuresarray/handlefeatures/setfeatureenables from
// Src/module.c:3275/3370/3445 with C-side Builtin/Features pointers;
// Rust per-module shims hardcode the bintab/conddefs/mathfuncs/paramdefs.
fn setfeatureenables(
    _m: *const module,
    _f: &Mutex<features_t>,
    _e: Option<&[i32]>,
) -> i32 {
    0
}

// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// ─── RUST-ONLY ACCESSORS ───
//
// Singleton accessor fns for `OnceLock<Mutex<T>>` / `OnceLock<
// RwLock<T>>` globals declared above. C zsh uses direct global
// access; Rust needs these wrappers because `OnceLock::get_or_init`
// is the only way to lazily construct shared state. These fns sit
// here so the body of this file reads in C source order without
// the accessor wrappers interleaved between real port fns.
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// ─── RUST-ONLY ACCESSORS ───
//
// Singleton accessor fns for `OnceLock<Mutex<T>>` / `OnceLock<
// RwLock<T>>` globals declared above. C zsh uses direct global
// access; Rust needs these wrappers because `OnceLock::get_or_init`
// is the only way to lazily construct shared state. These fns sit
// here so the body of this file reads in C source order without
// the accessor wrappers interleaved between real port fns.
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

// WARNING: NOT IN ZPROF.C — Rust-only module-framework shim.
// C uses generic featuresarray/handlefeatures/setfeatureenables from
// Src/module.c:3275/3370/3445 with C-side Builtin/Features pointers;
// Rust per-module shims hardcode the bintab/conddefs/mathfuncs/paramdefs.
fn module_features() -> &'static Mutex<features_t> {
    MODULE_FEATURES.get_or_init(|| Mutex::new(features_t {
        bn_list: None,
        bn_size: 1,
        cd_list: None,
        cd_size: 0,
        mf_list: None,
        mf_size: 0,
        pd_list: None,
        pd_size: 0,
        n_abstract: 0,
    }))
}

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

    /// Serialise tests that mutate the module-static globals so the
    /// cargo-test parallel runner doesn't shred each other's state.
    static TEST_LOCK: Mutex<()> = Mutex::new(());

    fn reset_state() {
        let mut c = CALLS.lock().unwrap();
        c.clear();
        let mut a = ARCS.lock().unwrap();
        a.clear();
        STACK.lock().unwrap().clear();
        NCALLS.store(0, Ordering::SeqCst);
        NARCS.store(0, Ordering::SeqCst);
    }

    /// Port of `bin_zprof(UNUSED(char *nam), UNUSED(char **args), Options ops, UNUSED(int func))` from `Src/Modules/zprof.c:139`.
    /// Verifies `Pfunc` mirrors C `struct pfunc` field-for-field
    /// (name/calls/time/self/num at c:40-44).
    #[test]
    fn pfunc_default_zeros() {
        let p = Pfunc::default();
        assert_eq!(p.name, "");
        assert_eq!(p.calls, 0);
        assert_eq!(p.time, 0.0);
        assert_eq!(p.self_time, 0.0);
        assert_eq!(p.num, 0);
    }

    /// Verifies `freepfuncs` empties the table (c:78-82 zsfree+zfree).
    #[test]
    fn freepfuncs_clears() {
        let mut v = vec![Pfunc { name: "a".into(), ..Default::default() }];
        freepfuncs(&mut v);
        assert!(v.is_empty());
    }

    /// Verifies `findpfunc` linear-scan match (c:101-103).
    #[test]
    fn findpfunc_matches_by_name() {
        let _g = TEST_LOCK.lock().unwrap();
        reset_state();
        CALLS.lock().unwrap().push(Pfunc { name: "alpha".into(), ..Default::default() });
        CALLS.lock().unwrap().push(Pfunc { name: "beta".into(), ..Default::default() });
        assert_eq!(findpfunc("alpha"), Some(0));
        assert_eq!(findpfunc("beta"), Some(1));
        assert_eq!(findpfunc("none"), None);
        reset_state();
    }

    /// Verifies `findparc` matches (from, to) pair (c:113-115).
    #[test]
    fn findparc_matches_pair() {
        let _g = TEST_LOCK.lock().unwrap();
        reset_state();
        ARCS.lock().unwrap().push(Parc { from: 0, to: 1, ..Default::default() });
        ARCS.lock().unwrap().push(Parc { from: 0, to: 2, ..Default::default() });
        assert_eq!(findparc(0, 1), Some(0));
        assert_eq!(findparc(0, 2), Some(1));
        assert_eq!(findparc(1, 0), None);
        reset_state();
    }

    /// Verifies `cmpsfuncs` is descending (c:121-124).
    #[test]
    fn cmpsfuncs_descending() {
        let a = Pfunc { self_time: 5.0, ..Default::default() };
        let b = Pfunc { self_time: 10.0, ..Default::default() };
        // descending: b should come before a → cmp(a, b) = Greater
        assert_eq!(cmpsfuncs(&a, &b), std::cmp::Ordering::Greater);
        assert_eq!(cmpsfuncs(&b, &a), std::cmp::Ordering::Less);
    }

    /// Verifies `bin_zprof -c` clears state (c:141-147).
    #[test]
    fn bin_zprof_clear_resets_tables() {
        let _g = TEST_LOCK.lock().unwrap();
        reset_state();
        CALLS.lock().unwrap().push(Pfunc { name: "x".into(), ..Default::default() });
        ARCS.lock().unwrap().push(Parc { from: 0, to: 0, ..Default::default() });
        NCALLS.store(1, Ordering::SeqCst);
        NARCS.store(1, Ordering::SeqCst);

        use crate::ported::zsh_h::{options, MAX_OPS};
        let mut ops = options { ind: [0u8; MAX_OPS], args: Vec::new(),
                                argscount: 0, argsalloc: 0 };
        ops.ind[b'c' as usize] = 1;
        let r = bin_zprof("zprof", &["-c".to_string()], &ops, 0);
        assert_eq!(r, 0);
        assert!(CALLS.lock().unwrap().is_empty());
        assert!(ARCS.lock().unwrap().is_empty());
        assert_eq!(NCALLS.load(Ordering::SeqCst), 0);
        assert_eq!(NARCS.load(Ordering::SeqCst), 0);
    }

    /// Verifies `zprof_wrapper` returns 0 (the static-link no-op
    /// path mirrors C's `return 0;` exit at c:311).
    #[test]
    fn zprof_wrapper_returns_zero() {
        assert_eq!(
            zprof_wrapper(std::ptr::null(), std::ptr::null(), "foo"),
            0,
        );
    }

    /// Verifies `name_for_anonymous_function` formats as
    /// `name [filename:lineno]` per c:224-232.
    #[test]
    fn name_for_anonymous_function_format() {
        let s = name_for_anonymous_function("anon", "/tmp/foo.zsh", 42);
        assert_eq!(s, "anon [/tmp/foo.zsh:42]");
    }

    /// c:97 — `findpfunc` on an empty table returns None. A
    /// regression that returns 0 (a valid index!) would silently
    /// corrupt every subsequent per-function profile accumulation.
    #[test]
    fn findpfunc_empty_table_returns_none() {
        let _g = TEST_LOCK.lock().unwrap();
        reset_state();
        assert!(findpfunc("never-called").is_none());
    }

    /// c:97 — `findpfunc` after two inserts returns the right index.
    /// Pin the index-zero-based contract because the find result
    /// feeds back into CALLS[i].
    #[test]
    fn findpfunc_returns_correct_index_after_insert() {
        let _g = TEST_LOCK.lock().unwrap();
        reset_state();
        CALLS.lock().unwrap().push(Pfunc { name: "alpha".into(), ..Default::default() });
        CALLS.lock().unwrap().push(Pfunc { name: "beta".into(), ..Default::default() });
        assert_eq!(findpfunc("alpha"), Some(0));
        assert_eq!(findpfunc("beta"), Some(1));
        assert!(findpfunc("gamma").is_none());
    }

    /// c:109 — `findparc(f, t)` on an empty arcs table → None.
    #[test]
    fn findparc_empty_table_returns_none() {
        let _g = TEST_LOCK.lock().unwrap();
        reset_state();
        assert!(findparc(0, 1).is_none());
    }

    /// c:109 — `findparc` distinguishes (f1, t1) from (f1, t2):
    /// same `from`, different `to` is a different arc.
    #[test]
    fn findparc_distinguishes_to_field() {
        let _g = TEST_LOCK.lock().unwrap();
        reset_state();
        ARCS.lock().unwrap().push(Parc { from: 0, to: 1, ..Default::default() });
        ARCS.lock().unwrap().push(Parc { from: 0, to: 2, ..Default::default() });
        assert_eq!(findparc(0, 1), Some(0));
        assert_eq!(findparc(0, 2), Some(1));
        assert!(findparc(0, 99).is_none());
        assert!(findparc(99, 1).is_none());
    }

    /// c:121 — `cmpsfuncs` compares by `self_time` DESCENDING (C
    /// source: `(int)((*b)->self < (*a)->self) - (int)((*a)->self < (*b)->self)`
    /// — i.e. higher self_time sorts first). Pin the direction
    /// because a regen that flips to ascending would silently
    /// invert the user-facing `zprof` output ordering.
    #[test]
    fn cmpsfuncs_compares_by_self_time_descending() {
        let high = Pfunc { name: "_".into(), self_time: 100.0, ..Default::default() };
        let low  = Pfunc { name: "_".into(), self_time: 1.0,   ..Default::default() };
        // higher self_time sorts FIRST → Ordering::Less for (high, low)
        assert_eq!(cmpsfuncs(&high, &low), std::cmp::Ordering::Less);
        assert_eq!(cmpsfuncs(&low, &high), std::cmp::Ordering::Greater);
        assert_eq!(cmpsfuncs(&high, &high), std::cmp::Ordering::Equal);
    }

    /// c:74 — `freepfuncs` empties the input vec.
    #[test]
    fn freepfuncs_empties_input_vec() {
        let mut v = vec![
            Pfunc { name: "x".into(), ..Default::default() },
            Pfunc { name: "y".into(), ..Default::default() },
        ];
        freepfuncs(&mut v);
        assert!(v.is_empty(), "freepfuncs must clear the input vec");
    }

    /// c:86 — `freeparcs` empties the input arc vec.
    #[test]
    fn freeparcs_empties_input_vec() {
        let mut v = vec![
            Parc { from: 0, to: 1, ..Default::default() },
            Parc { from: 2, to: 3, ..Default::default() },
        ];
        freeparcs(&mut v);
        assert!(v.is_empty(), "freeparcs must clear the input vec");
    }

    /// c:121 vs c:127 — `cmpsfuncs` sorts by `self_time`, `cmptfuncs`
    /// sorts by `time` (cumulative). Pin they produce DIFFERENT
    /// orderings on an input where the two fields disagree, so a
    /// regen that aliases the field accessor in one of them gets
    /// caught.
    #[test]
    fn cmpsfuncs_and_cmptfuncs_differ_when_fields_disagree() {
        // `alpha` has high self_time but LOW cumulative time.
        // `beta`  has low self_time but HIGH cumulative time.
        let alpha = Pfunc { name: "_".into(), self_time: 100.0, time: 1.0,   ..Default::default() };
        let beta  = Pfunc { name: "_".into(), self_time: 1.0,   time: 100.0, ..Default::default() };
        let by_self = cmpsfuncs(&alpha, &beta);
        let by_time = cmptfuncs(&alpha, &beta);
        // by_self: alpha has higher self_time → alpha sorts first → Less
        // by_time: beta has higher cumulative time → alpha sorts after → Greater
        assert_ne!(by_self, by_time,
            "cmpsfuncs (self_time) and cmptfuncs (time) must differ when fields disagree");
    }
}