Skip to main content

rt/
lib.rs

1// rt -- the runtime under everything: allocator, memory intrinsics, exact SSE float
2// semantics, the minimal OS calls the runtime itself needs, panic handling.
3//
4//   rt::os::{pages_alloc, pages_free, write_stdout, write_stderr, exit, yield_now}   (and on
5//   Linux the raw syscall helpers plat builds on); write_stderr_crash: stderr for crash paths,
6//   which gives up a stuck non-blocking stderr instead of waiting for it (Linux)
7//   rt::kernel the Linux kernel ABI per architecture: SYS_*, O_*, Stat, clone_args (also as rt::os::*)
8//   rt::fx   cvtt / cvt / sqrt / minss / maxss / floor_i / ceil_i / div255
9//   rt::x87  the extended-precision steps of f64 <-> decimal text (ini.s), fpatan
10//   rt::sync SpinLock
11//   rt::cpu  CPU feature bits (CPUID, cached; force_baseline for --simd sse2)
12//   rt::crash the crash hook, CrashInfo, report (exit 3) -- also for panics
13//   rt::boot  what build_rs.py builds into a program (name, manifest, assets) for plat's start
14//   rt::main!(body)  the entry symbol of console programs (boot first, then body); with the
15//            feature std also their fn main
16//   rt::panic_hook()  (feature std) std's panics take the crash report of rt's panic handler
17//   rt::abort_on_unwind(f)  a panic that leaves f ends the program (feature unwind; else f())
18//   rt::panic_take()  (feature unwind) the last panic of the calling thread, as text
19//   rt::Alloc  (feature std, Windows and Linux) rt's allocator for a program with std that wants it
20//   rt::VERSION, VERSION_MAJOR / _MINOR / _PATCH   the library's version (the root Cargo.toml, SemVer;
21//            docs/VERSIONING.md), also as plat::VERSION and ui::VERSION
22//   rt::app_version!()  the app's own version (version= of apps/NAME/PACKAGE)
23//   rt::plugin_abi!  the calling convention of plugins and modules: win64 on x86-64, C elsewhere (abi.rs)
24//
25// One of the four library crates that may contain `unsafe` (rt, simd, plat, gpu; and the module
26// runtimes modrt and modplat).
27#![no_std]
28
29extern crate alloc;
30#[cfg(feature = "std")]
31extern crate std;
32
33/// the library's version, "MAJOR.MINOR.PATCH" (the root Cargo.toml; docs/VERSIONING.md says what a
34/// change of each part promises).  Not the app's version: that is `rt::app_version!()`.
35pub const VERSION: &str = env!("CARGO_PKG_VERSION");
36/// the first number of VERSION (incompatible API changes; while 0, the MINOR number counts them)
37pub const VERSION_MAJOR: u32 = version_part(VERSION, 0);
38/// the second number of VERSION
39pub const VERSION_MINOR: u32 = version_part(VERSION, 1);
40/// the third number of VERSION
41pub const VERSION_PATCH: u32 = version_part(VERSION, 2);
42const _: () = assert!(version_part(VERSION, 3) == u32::MAX, "the version in Cargo.toml must be MAJOR.MINOR.PATCH");
43
44/// the n-th number of "1.2.3" (or "1.2.3-pre+build"); u32::MAX when it has no n-th number
45const fn version_part(v: &str, n: usize) -> u32 {
46    let b = v.as_bytes();
47    let (mut i, mut part, mut value, mut digits) = (0, 0, 0u32, 0);
48    while i <= b.len() {
49        let c = if i < b.len() { b[i] } else { b'.' };
50        if c.is_ascii_digit() && digits < 9 {
51            value = value * 10 + (c - b'0') as u32;
52            digits += 1;
53        } else if c == b'.' || c == b'-' || c == b'+' {
54            if digits == 0 {
55                return u32::MAX;
56            }
57            if part == n {
58                return value;
59            }
60            if c != b'.' {
61                return u32::MAX; // the pre-release / build part has no numbers to count
62            }
63            (part, value, digits) = (part + 1, 0, 0);
64        } else {
65            return u32::MAX;
66        }
67        i += 1;
68    }
69    u32::MAX
70}
71
72/// The app's own version: `version=` of apps/NAME/PACKAGE, which build_rs.py hands to rustc as
73/// JFGUI_VERSION (every program of the app); "0.0.0" without one.  An expression of type
74/// `&'static str`: `const APP_VERSION: &str = rt::app_version!();`, `update::Config::new(app,
75/// rt::app_version!(), ..)`.
76#[macro_export]
77macro_rules! app_version {
78    () => {
79        match option_env!("JFGUI_VERSION") {
80            Some(v) => v,
81            None => "0.0.0",
82        }
83    };
84}
85
86/// Define the common app entry symbol without requiring the GUI crate in headless tools.  It
87/// first hands what build_rs.py built in (boot.rs: the app's name, its manifest, its assets)
88/// to the platform layer, which installs them as ui::main! does; a refused manifest ends the
89/// program with exit code 2.  A Cargo build hands the manifest over as a file
90/// (JFGUI_PERMISSIONS_FILE with --cfg jfgui_manifest), because an environment variable of a build
91/// script holds one line only.
92///
93/// In a program with std (feature `std`) it also defines `fn main`, which hands over to plat's
94/// start of a std program (`jfgui_std_start`: crash handlers, the panic hook, then `jfgui_main`,
95/// the end through `std::process::exit`); the crate then has neither `#![no_std]` nor `#![no_main]`.
96///
97/// The unit tests of a library crate that holds it (`cargo test --lib`) need no `test_main!`: this
98/// `jfgui_main` links their test binary (never called there), and the panic check leaves the test
99/// build out (`cfg(test)`: Cargo builds tests with unwind whatever the profiles say; doc tests
100/// build the crate without it, docs/GUIDE.md "An app with std").  A `test_main!` next to it
101/// would define `jfgui_main` twice (E0428)
102#[cfg(not(feature = "std"))]
103#[macro_export]
104macro_rules! main {
105    ($body:expr) => {
106        $crate::__jfgui_main!($body);
107    };
108}
109
110/// (see above)
111#[cfg(feature = "std")]
112#[macro_export]
113macro_rules! main {
114    ($body:expr) => {
115        $crate::__jfgui_main!($body);
116        $crate::__std_main!();
117    };
118}
119
120/// (E16) the `jfgui_main` a program's main! defines, for the test binary of a library crate with
121/// std and without main! (a style crate's `cargo test`): plat's start of a std program refers to
122/// it, so without it the tests do not link.  Never called (the test harness has its own main); no
123/// panic check (tests unwind).  `#[cfg(test)] rt::test_main!();` in the crate's lib.rs, also under
124/// `#![forbid(unsafe_code)]` (the expansion allows no lint: unsafe_code skips external macros).  A
125/// crate with main! needs none: its main!'s `jfgui_main` links the tests
126#[macro_export]
127macro_rules! test_main {
128    () => {
129        #[allow(dead_code)]
130        #[unsafe(no_mangle)]
131        fn jfgui_main() -> i32 {
132            0
133        }
134    };
135}
136
137/// rt::main!'s check of the panic strategy: JFLib's runtime needs `panic = "abort"`, a program with
138/// std built with the feature `unwind` may unwind as well.  Not in the unit tests of the crate
139/// with main! (`cfg(test)` is the app crate's, where this expands): Cargo builds tests with unwind
140#[cfg(not(feature = "unwind"))]
141#[doc(hidden)]
142#[macro_export]
143macro_rules! __rt_panic_check {
144    () => {
145        #[cfg(all(panic = "unwind", not(test)))]
146        compile_error!("JFLib needs panic = \"abort\": add [profile.dev] and [profile.release] with panic = \"abort\" to this project's Cargo.toml (a program with std may turn on jflib's feature unwind instead)");
147    };
148}
149
150/// (see above)
151#[cfg(feature = "unwind")]
152#[doc(hidden)]
153#[macro_export]
154macro_rules! __rt_panic_check {
155    () => {};
156}
157
158/// rt::main!'s `jfgui_main`, without and with std
159#[doc(hidden)]
160#[macro_export]
161macro_rules! __jfgui_main {
162    ($body:expr) => {
163        $crate::__rt_panic_check!();
164        #[allow(unexpected_cfgs)]
165        #[unsafe(no_mangle)]
166        fn jfgui_main() -> i32 {
167            #[cfg(jfgui_manifest)]
168            const JF_MANIFEST: Option<&str> = Some(include_str!(env!("JFGUI_PERMISSIONS_FILE")));
169            #[cfg(not(jfgui_manifest))]
170            const JF_MANIFEST: Option<&str> = option_env!("JFGUI_PERMISSIONS");
171            #[cfg(jfgui_assets)]
172            static ASSETS: &[u8] = include_bytes!(env!("JFGUI_ASSETS"));
173            #[cfg(not(jfgui_assets))]
174            static ASSETS: &[u8] = &[];
175            let boot = $crate::boot::Boot { app: option_env!("JFGUI_APP"), manifest: JF_MANIFEST, assets: ASSETS };
176            if let Err(code) = $crate::boot::start(&boot) {
177                return code;
178            }
179            $body
180        }
181    };
182}
183
184/// the `fn main` of a program with std: plat's start (jfgui_std_start), which calls jfgui_main.  In
185/// a library crate (an app whose program only links it, like the template) it is not the entry
186/// point and stays unused: the program's own main calls `plat::std_start()`.
187#[doc(hidden)]
188#[macro_export]
189macro_rules! __std_main {
190    () => {
191        #[allow(dead_code)]
192        fn main() {
193            unsafe extern "Rust" {
194                fn jfgui_std_start() -> !;
195            }
196            // SAFETY: plat defines it in a program with std; it takes no arguments.
197            unsafe { jfgui_std_start() }
198        }
199    };
200}
201
202pub mod boot;
203#[cfg_attr(any(target_arch = "wasm32", target_os = "android", target_arch = "aarch64"), path = "portable/cpu.rs")]
204pub mod cpu; // (Intel Macs: CPUID and x87 as on Windows and Linux, docs/INTEL_MAC.md decision 2a; Apple Silicon is aarch64)
205pub mod crash;
206#[cfg_attr(target_arch = "aarch64", path = "aarch64/fx.rs")] #[cfg_attr(all(not(target_arch = "aarch64"), any(target_arch = "wasm32", target_os = "android")), path = "portable/fx.rs")]
207pub mod fx;
208#[cfg(target_os = "linux")]
209pub mod kernel;
210// Android and Apple: the system's malloc and memory functions (android.rs, apple.rs)
211#[cfg(not(any(target_os = "android", target_vendor = "apple")))]
212#[cfg_attr(target_arch = "wasm32", path = "portable/mem.rs")]
213#[cfg_attr(feature = "std", allow(dead_code))] // std brings the allocator and the memory functions
214mod mem;
215/// rt's allocator, for a program with std that wants it instead of the system's:
216/// `#[global_allocator] static ALLOC: jflib::rt::Alloc = jflib::rt::Alloc::new();`
217#[cfg(all(feature = "std", not(any(target_os = "android", target_arch = "wasm32", target_vendor = "apple"))))]
218pub use mem::Alloc;
219#[cfg_attr(target_arch = "wasm32", path = "portable/os.rs")]
220#[cfg_attr(target_os = "android", path = "android.rs")]
221#[cfg_attr(target_vendor = "apple", path = "apple.rs")]
222pub mod os;
223pub mod sync;
224#[cfg_attr(any(target_arch = "wasm32", target_os = "android", target_arch = "aarch64"), path = "portable/math.rs")]
225#[allow(clippy::duplicate_mod)] // where x87 is the portable arithmetic, `portable` below names the same file
226pub mod x87;
227
228/// Portable arithmetic, available on native targets for exact backend comparisons.
229#[cfg(not(target_arch = "wasm32"))]
230pub mod portable {
231    pub mod fx;
232    pub mod math;
233}
234
235/// panic: one line on stderr, the crash hook (CK_PANIC), exit code 3
236#[cfg(not(feature = "std"))]
237#[panic_handler]
238fn panic(info: &core::panic::PanicInfo) -> ! {
239    panic_report(info)
240}
241
242#[cfg(feature = "std")]
243mod hosted;
244#[cfg(feature = "std")]
245pub use hosted::panic_hook;
246#[cfg(feature = "unwind")]
247pub use hosted::{abort_on_unwind, panic_take};
248
249/// run `f`; with the feature `unwind` (a program with std built with `panic = "unwind"`) a panic
250/// that leaves it ends the program as an uncaught panic: JFLib's crash report, exit code 3.  plat
251/// runs its threads and the program's start through it.  Without that feature a panic never
252/// unwinds, and this is `f()`.
253#[cfg(not(feature = "unwind"))]
254#[inline(always)]
255pub fn abort_on_unwind<R>(f: impl FnOnce() -> R) -> R {
256    f()
257}
258
259pub(crate) fn panic_report(info: &dyn core::fmt::Display) -> ! {
260    use core::fmt::Write;
261    if crash::busy() {
262        os::exit(3); // a panic inside the crash hook
263    }
264    let mut s = crash::StackText::<1024>::new(); // no allocation on the crash path
265    let _ = writeln!(s, "panic: {info}");
266    os::write_stderr_crash(s.bytes());
267    let text = s.as_str().trim_end();
268    let mut ci = crash::CrashInfo::empty();
269    ci.kind = crash::CK_PANIC;
270    ci.msg = text.strip_prefix("panic: ").unwrap_or(text);
271    crash::report(&ci)
272}
273
274// rt::plugin_abi! (macro_export: at the crate root)
275mod abi;