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#[cfg(not(feature = "std"))]
97#[macro_export]
98macro_rules! main {
99    ($body:expr) => {
100        $crate::__jfgui_main!($body);
101    };
102}
103
104/// (see above)
105#[cfg(feature = "std")]
106#[macro_export]
107macro_rules! main {
108    ($body:expr) => {
109        $crate::__jfgui_main!($body);
110        $crate::__std_main!();
111    };
112}
113
114/// (E16) the `jfgui_main` a program's main! defines, for the test binary of a library crate with
115/// std (a style crate's `cargo test`): plat's start of a std program refers to it, so without it
116/// the tests do not link.  Never called (the test harness has its own main); no panic check
117/// (tests unwind).  `#[cfg(test)] rt::test_main!();` in the crate's lib.rs, also under
118/// `#![forbid(unsafe_code)]` (the expansion allows no lint: unsafe_code skips external macros)
119#[macro_export]
120macro_rules! test_main {
121    () => {
122        #[allow(dead_code)]
123        #[unsafe(no_mangle)]
124        fn jfgui_main() -> i32 {
125            0
126        }
127    };
128}
129
130/// rt::main!'s check of the panic strategy: JFLib's runtime needs `panic = "abort"`, a program with
131/// std built with the feature `unwind` may unwind as well
132#[cfg(not(feature = "unwind"))]
133#[doc(hidden)]
134#[macro_export]
135macro_rules! __rt_panic_check {
136    () => {
137        #[cfg(panic = "unwind")]
138        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)");
139    };
140}
141
142/// (see above)
143#[cfg(feature = "unwind")]
144#[doc(hidden)]
145#[macro_export]
146macro_rules! __rt_panic_check {
147    () => {};
148}
149
150/// rt::main!'s `jfgui_main`, without and with std
151#[doc(hidden)]
152#[macro_export]
153macro_rules! __jfgui_main {
154    ($body:expr) => {
155        $crate::__rt_panic_check!();
156        #[allow(unexpected_cfgs)]
157        #[unsafe(no_mangle)]
158        fn jfgui_main() -> i32 {
159            #[cfg(jfgui_manifest)]
160            const JF_MANIFEST: Option<&str> = Some(include_str!(env!("JFGUI_PERMISSIONS_FILE")));
161            #[cfg(not(jfgui_manifest))]
162            const JF_MANIFEST: Option<&str> = option_env!("JFGUI_PERMISSIONS");
163            #[cfg(jfgui_assets)]
164            static ASSETS: &[u8] = include_bytes!(env!("JFGUI_ASSETS"));
165            #[cfg(not(jfgui_assets))]
166            static ASSETS: &[u8] = &[];
167            let boot = $crate::boot::Boot { app: option_env!("JFGUI_APP"), manifest: JF_MANIFEST, assets: ASSETS };
168            if let Err(code) = $crate::boot::start(&boot) {
169                return code;
170            }
171            $body
172        }
173    };
174}
175
176/// the `fn main` of a program with std: plat's start (jfgui_std_start), which calls jfgui_main.  In
177/// a library crate (an app whose program only links it, like the template) it is not the entry
178/// point and stays unused: the program's own main calls `plat::std_start()`.
179#[doc(hidden)]
180#[macro_export]
181macro_rules! __std_main {
182    () => {
183        #[allow(dead_code)]
184        fn main() {
185            unsafe extern "Rust" {
186                fn jfgui_std_start() -> !;
187            }
188            // SAFETY: plat defines it in a program with std; it takes no arguments.
189            unsafe { jfgui_std_start() }
190        }
191    };
192}
193
194pub mod boot;
195#[cfg_attr(any(target_arch = "wasm32", target_os = "android", target_vendor = "apple", target_arch = "aarch64"), path = "portable/cpu.rs")]
196pub mod cpu;
197pub mod crash;
198#[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")]
199pub mod fx;
200#[cfg(target_os = "linux")]
201pub mod kernel;
202// Android and Apple: the system's malloc and memory functions (android.rs, apple.rs)
203#[cfg(not(any(target_os = "android", target_vendor = "apple")))]
204#[cfg_attr(target_arch = "wasm32", path = "portable/mem.rs")]
205#[cfg_attr(feature = "std", allow(dead_code))] // std brings the allocator and the memory functions
206mod mem;
207/// rt's allocator, for a program with std that wants it instead of the system's:
208/// `#[global_allocator] static ALLOC: jflib::rt::Alloc = jflib::rt::Alloc::new();`
209#[cfg(all(feature = "std", not(any(target_os = "android", target_arch = "wasm32", target_vendor = "apple"))))]
210pub use mem::Alloc;
211#[cfg_attr(target_arch = "wasm32", path = "portable/os.rs")]
212#[cfg_attr(target_os = "android", path = "android.rs")]
213#[cfg_attr(target_vendor = "apple", path = "apple.rs")]
214pub mod os;
215pub mod sync;
216#[cfg_attr(any(target_arch = "wasm32", target_os = "android", target_vendor = "apple", target_arch = "aarch64"), path = "portable/math.rs")]
217#[allow(clippy::duplicate_mod)] // where x87 is the portable arithmetic, `portable` below names the same file
218pub mod x87;
219
220/// Portable arithmetic, available on native targets for exact backend comparisons.
221#[cfg(not(target_arch = "wasm32"))]
222pub mod portable {
223    pub mod fx;
224    pub mod math;
225}
226
227/// panic: one line on stderr, the crash hook (CK_PANIC), exit code 3
228#[cfg(not(feature = "std"))]
229#[panic_handler]
230fn panic(info: &core::panic::PanicInfo) -> ! {
231    panic_report(info)
232}
233
234#[cfg(feature = "std")]
235mod hosted;
236#[cfg(feature = "std")]
237pub use hosted::panic_hook;
238#[cfg(feature = "unwind")]
239pub use hosted::{abort_on_unwind, panic_take};
240
241/// run `f`; with the feature `unwind` (a program with std built with `panic = "unwind"`) a panic
242/// that leaves it ends the program as an uncaught panic: JFLib's crash report, exit code 3.  plat
243/// runs its threads and the program's start through it.  Without that feature a panic never
244/// unwinds, and this is `f()`.
245#[cfg(not(feature = "unwind"))]
246#[inline(always)]
247pub fn abort_on_unwind<R>(f: impl FnOnce() -> R) -> R {
248    f()
249}
250
251pub(crate) fn panic_report(info: &dyn core::fmt::Display) -> ! {
252    use core::fmt::Write;
253    if crash::busy() {
254        os::exit(3); // a panic inside the crash hook
255    }
256    let mut s = crash::StackText::<1024>::new(); // no allocation on the crash path
257    let _ = writeln!(s, "panic: {info}");
258    os::write_stderr_crash(s.bytes());
259    let text = s.as_str().trim_end();
260    let mut ci = crash::CrashInfo::empty();
261    ci.kind = crash::CK_PANIC;
262    ci.msg = text.strip_prefix("panic: ").unwrap_or(text);
263    crash::report(&ci)
264}
265
266// rt::plugin_abi! (macro_export: at the crate root)
267mod abi;