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
//! cosca-owned fd-mapping `pre_exec`: dup2's parent-process descriptors onto child descriptor
//! numbers, replacing the `command-fds` dependency.
//!
//! # Why cosca owns this now
//! `command-fds` 0.3.3 has two bugs that together made an out-of-range [`Fd`](crate::stdio::Fd)
//! either abort the child or silently vanish rather than fail the spawn cleanly:
//! - its `map_fds` computes `max(every parent/child fd) + 1` as a temporary-fd floor with
//! unchecked `i32` arithmetic, which overflows for `child_fd == i32::MAX` — and even when it
//! does not overflow, that single global floor can sit above the process' `RLIMIT_NOFILE`
//! even when plenty of lower numbers are free, refusing a spawn that should have succeeded;
//! - it calls nix 0.31.3's `dup2_raw`, which does not check `dup2`'s return value before
//! wrapping it in an `OwnedFd` — on ANY `dup2` failure (e.g. `EBADF` for an out-of-range
//! target) that constructs an `OwnedFd` around the sentinel `-1`, which aborts when std's
//! own file-descriptor validity checks later see it. Reported upstream as
//! nix-rust/nix#2797 (unfixed as of nix 0.31.3); not cosca's to fix.
//!
//! A negative `Fd` never reaches this module at all: [`Command::fd`](crate::Command::fd) rejects
//! it directly, via its own `slot.raw() < 0` check.
//!
//! This module ports `command-fds`' actual algorithm (the collision-avoiding temporary-fd
//! shuffle, and the `FD_CLOEXEC`-clearing `preserved_fds` the macOS fd marker uses, here
//! [`install_preserved`]) but:
//! - picks each temporary with its own `F_DUPFD_CLOEXEC(fd, 3)` search, re-requesting above any
//! result that lands on another mapping's `child_fd`, instead of one global floor computed
//! from the highest fd anywhere in the set — so one distant `child_fd` no longer inflates
//! every other mapping's temporary past a tight `RLIMIT_NOFILE` (see [`dup_avoiding`]). That
//! retry is bounded by the number of `child_fd`s: `F_DUPFD_CLOEXEC` always returns a
//! genuinely free number, so at most one collision can occur per `child_fd`;
//! - relocates, in the parent before any fork, any mapping whose `parent_fd` sits below fd 3
//! (see [`install`]) — std's OWN stdio setup (`.stdin()`/`.stdout()`/`.stderr()`) runs its
//! `dup2`s in the child BEFORE any `pre_exec` hook, so a mapping source left at fd 0/1/2
//! would otherwise be silently clobbered before this module's own `pre_exec` ever ran;
//! - checks every post-fork syscall (raw `libc` or rustix) and turns a failure into an
//! `io::Error` — except the one `close` of a temporary this module exclusively owns (see
//! [`dup_avoiding`]), whose result is intentionally ignored: on Linux a same-process `close`
//! can legitimately report `EIO`/`EINTR` well after the descriptor is released (e.g. a flush
//! error on an NFS/FUSE-backed mapping source), so treating that as fatal would abort an
//! otherwise-fine spawn;
//! - retries a syscall interrupted by `EINTR`, with no arbitrary bound (mirrors the
//! codebase's other `pre_exec`/raw-syscall retry sites — see e.g.
//! `containment::cgroup::channel`).
//!
//! An out-of-range but syscall-representable `child_fd` (e.g. 1_000_000, or `i32::MAX`) is
//! deliberately NOT rejected here: it is a normal spawn-time condition (bounded by the child's
//! own `RLIMIT_NOFILE`) and is left to fail exactly the way any other post-fork syscall failure
//! does — `dup2` returns `EBADF`, the checked closure returns that as an `io::Error`, and
//! std's own child-to-parent error pipe turns that into an ordinary `Err` from `Command::spawn`.
//!
//! That last step has one known exception: std allocates its error pipe itself, inside
//! `spawn()`, AFTER this module's own dup2 plan has already been built from the caller's
//! `child_fd`s. Nothing here steers a `child_fd` away from whatever number that pipe's write end
//! lands on. If a caller's `child_fd` equals that number, this module's own pass 2 dup2s the
//! caller's mapping onto it — closing std's error channel before the child ever calls `exec`. A
//! dup2 or exec failure after that point (including the out-of-range case above) writes std's
//! errno bytes into the caller's mapped fd instead of reaching the parent, and `spawn()` wrongly
//! returns `Ok`. Not fixed here: filed as #192, to land with a cosca-owned error channel.
use io;
use ;
use CommandExt;
/// A parent-fd -> child-fd mapping to install as part of `std_cmd`'s `pre_exec` dup2 plan.
/// Owns `parent_fd` so it stays open (and valid to dup2 from) until the spawn completes.
pub
/// Register `mappings` as the LAST `pre_exec` hook on `std_cmd`. Callers MUST register this
/// after every containment pre_exec hook (see the ordering rationale in
/// `child::spawn::spawn_unelevated` and `tokio::spawn::spawn_uncommitted`): it must run last so
/// it cannot dup2 over an fd a containment hook still needs.
///
/// A no-op (registers nothing) for an empty `mappings`.
///
/// Every `child_fd` must already be non-negative — enforced once, upstream, at
/// [`Command::fd`](crate::Command::fd); only asserted here, not re-checked (it is a contract,
/// not user input at this point). A duplicate `child_fd` IS re-checked here, in every build
/// profile, and rejected with an ordinary `Err`: both production callers build `mappings` from a
/// `BTreeMap<Fd, _>`, whose keys are already unique, but nothing about this function's own
/// `Vec<FdMapping>` signature enforces that for every caller. An out-of-range `child_fd` is NOT
/// rejected here — see the module docs for why that is a normal (child-side, `EBADF`) spawn
/// failure rather than a parent-side refusal.
///
/// Before building the plan, relocates (in the parent, before any fork) any mapping whose
/// `parent_fd` sits below fd 3, via `F_DUPFD_CLOEXEC(fd, 3)` — see the module docs for why a
/// low-numbered source would otherwise be clobbered by std's own stdio setup. That relocation is
/// the only parent-side failure mode left: an ordinary `Err` (e.g. `EMFILE`) if the duplicate
/// itself cannot be made.
///
/// The vacated original number is deliberately NOT freed at this point: it stays open, owned by
/// the returned `Plan` (see `Plan::_retired`), until `std_cmd` itself drops. Freeing it any
/// earlier would let `std_cmd.spawn()`'s own internal fd allocation — most importantly its
/// child-to-parent CLOEXEC error-reporting pipe, which `spawn()` opens at the lowest free number —
/// claim that exact number in the parent. Std's OWN child-side stdio dup2 runs before any
/// `pre_exec` hook (including this module's own), so if that pipe's write end landed on a freed
/// 0/1/2 slot, std's own dup2 would close it before this module's `pre_exec` ever got a chance to
/// run, and a post-fork failure would then have nowhere left to report to.
pub
/// Register `fds` to survive `exec` without renumbering — clears `FD_CLOEXEC` on each, in the
/// child only. The cosca-owned equivalent of `command-fds`' `preserved_fds`, used by
/// `containment::fdmarker` to keep the marker write end open at the fd number it was placed
/// at.
///
/// `cfg`-gated to macOS, the only platform with a caller (`containment::fdmarker`): an
/// unconditional definition is dead code (and so a `-D warnings` clippy failure) on every other
/// Unix this module also compiles for.
pub
/// The dup2 plan, precomputed in the parent so the `pre_exec` closure does no allocation.
/// `fcntl(fd, F_DUPFD_CLOEXEC, min)` — a fresh, `FD_CLOEXEC`-set duplicate of `fd`, at the
/// lowest available number `>= min`. Retries `EINTR`.
/// A `FD_CLOEXEC` temporary duplicate of `fd`, at a number not in `forbidden` (every `child_fd`
/// in this mapping set). Starts the search at 3 and re-requests above any candidate that lands
/// on a forbidden number, closing the collision first so its number is free again for whichever
/// mapping actually wants it.
///
/// Bounded by `forbidden.len()` retries: each collision raises `min` past that exact number, and
/// nothing in this loop ever frees a lower number back up, so the same forbidden number can
/// never be returned twice — each retry permanently rules out one more element of `forbidden`.
///
/// Async-signal-safe: no allocation. `dup_fd_cloexec_at_or_above`'s `?` can propagate an ordinary
/// OS failure (e.g. `EMFILE` — too many open files) as-is. Separately, `min`'s `checked_add` can
/// overflow, but only if `forbidden` contains `i32::MAX` AND the process has enough open-file
/// headroom for `F_DUPFD_CLOEXEC` to actually hand back `i32::MAX` — not reachable in practice.
/// `dup2(oldfd, newfd)` — closes `newfd` first if it was already open. Retries `EINTR`.
/// `fcntl(fd, F_SETFD, 0)` — clears every fd flag (in practice just `FD_CLOEXEC`). Retries
/// `EINTR`.
/// Retry a raw libc call that reports failure as `-1` with `errno` set, absorbing `EINTR`. No
/// arbitrary retry bound: a syscall that is not interrupted returns on its first attempt; this
/// only loops while a signal keeps re-interrupting it.
///
/// Async-signal-safe: `f` is a plain syscall wrapper, and `io::Error::last_os_error()` reads
/// `errno` (via the platform's own thread-local accessor — `__errno_location` on Linux,
/// `__error` on macOS) without allocating.