Skip to main content

cosmo_compat/
lib.rs

1//! Shims for places where cosmopolitan's libc and Rust's std disagree.
2//!
3//! Link this into any cosmo target and the fixes apply themselves -- each is a
4//! `#[no_mangle]` definition that the linker prefers over the one in
5//! libcosmo.a, because an archive member is only pulled in to satisfy a symbol
6//! that is still undefined.
7
8// no_std so one shim serves both worlds: cosmo-ld wraps 123 libc symbols on
9// every cosmo link, so even a no_std binary has to supply the translators, and
10// nothing here needs more than core.
11#![cfg_attr(not(test), no_std)]
12use core::ffi::{c_char, c_int, c_void};
13
14// Stage-2 normalization (docs/DESIGN.md): translate OS constants at the libc
15// boundary so a binary compiled with Linux numbering runs on the host cosmo
16// landed it on. `gen` is generated by tools/gen-shim.py; `shim` holds the
17// hand-written __wrap_* functions cosmo-ld routes calls into.
18mod gen;
19mod net;
20mod socketpair;
21pub mod xlate;
22pub mod shim;
23
24/// Keep the two plain overrides alive through `lto = "fat"`.
25///
26/// Nothing in the Rust call graph references them -- std reaches both through
27/// an `extern "C"` declaration LTO cannot see -- so fat LTO internalizes them
28/// away and the libc bugs they exist to fix come back, silently and only in
29/// release builds. (The `__wrap_*` functions do not need this: `--wrap` makes
30/// the linker demand them, so losing one is a link error rather than a quiet
31/// regression.) `#[used]` emits `llvm.used`, which LTO honours.
32#[used]
33static KEEP_SHIMS: (
34   unsafe extern "C" fn(c_int, *mut c_char, usize) -> c_int,
35   unsafe extern "C" fn(c_int, c_int, *mut c_int, c_int) -> c_int,
36) = (__xpg_strerror_r, waitid);
37
38extern "C" {
39   fn strerror(errnum: c_int) -> *const c_char;
40   fn strlen(s: *const c_char) -> usize;
41   // Declared with the signature the runtime actually exports; anything else
42   // trips suspicious_runtime_symbol_definitions, and a mismatched redeclaration
43   // of a symbol the compiler may lower calls to is worth not guessing at.
44   fn memcpy(d: *mut c_void, s: *const c_void, n: usize) -> *mut c_void;
45}
46
47/// POSIX XSI `strerror_r`, which is what Rust's std actually calls.
48///
49/// std links this symbol and requires the XSI contract: return an `int`, zero
50/// on success. Cosmopolitan declares it `char *__xpg_strerror_r(int, char *,
51/// size_t)` -- the GNU contract -- so std reinterprets the returned pointer as
52/// an int, finds the sign bit set often enough to matter, and panics with
53/// "strerror_r failure". The effect is that formatting *any* io::Error blows
54/// up, which takes out ordinary error paths well before anything exotic.
55///
56/// Copying out of cosmo's `strerror` and returning 0 restores the contract.
57#[no_mangle]
58pub unsafe extern "C" fn __xpg_strerror_r(
59   errnum: c_int,
60   buf: *mut c_char,
61   buflen: usize,
62) -> c_int {
63   if buf.is_null() || buflen == 0 {
64      return 22; // EINVAL, per XSI
65   }
66   let msg = strerror(errnum);
67   if msg.is_null() {
68      *buf = 0;
69      return 0;
70   }
71   let n = core::cmp::min(strlen(msg), buflen - 1);
72   memcpy(buf.cast(), msg.cast(), n);
73   *buf.add(n) = 0;
74   0
75}
76
77extern "C" {
78   fn waitpid(pid: c_int, status: *mut c_int, options: c_int) -> c_int;
79}
80
81/// `waitid`, which cosmopolitan does not provide but std's `Process::wait`
82/// references unconditionally (its pidfd path, `P_PIDFD`, is compiled in for
83/// every linux target). Linking is the requirement; the semantics only matter
84/// if the function is ever reached, and on cosmo std never creates a pidfd, so
85/// it is not. Implemented over `waitpid` for the `P_PID`/`P_ALL` shapes anyway:
86/// `siginfo_t.si_status` receives the raw wait status and `si_pid` the pid, at
87/// the Linux offsets std reads (`si_pid` at byte 16, `si_status` at 24).
88#[no_mangle]
89pub unsafe extern "C" fn waitid(idtype: c_int, id: c_int, infop: *mut c_int, options: c_int) -> c_int {
90   const P_ALL: c_int = 0;
91   const P_PID: c_int = 1;
92   const WNOWAIT: c_int = 0x0100_0000;
93   let pid = match idtype { P_ALL => -1, P_PID => id, _ => return -1 };
94   let mut status: c_int = 0;
95   let r = waitpid(pid, &mut status, options & !WNOWAIT & 0xff);
96   if r < 0 { return -1; }
97   if !infop.is_null() {
98      *infop.add(4) = r;        // si_pid
99      *infop.add(6) = status;   // si_status
100   }
101   0
102}
103
104/// Built standalone by cargo-cosmo (tools/cargo-cosmo, `ensure_inject`): a
105/// staticlib needs a panic handler of its own. The shim never panics on
106/// purpose; if it does, abort rather than unwind through C.
107#[cfg(all(cosmo_compat_inject, not(test)))]
108#[panic_handler]
109fn inject_panic(_: &core::panic::PanicInfo) -> ! {
110   extern "C" { fn abort() -> !; }
111   unsafe { abort() }
112}