rt#
the runtime parts apps use: SSE / x87 float semantics, CPU features, locks, crash records -- crate root lib/rt/lib.rs
rt -- the runtime under everything: allocator, memory intrinsics, exact SSE float
semantics, the minimal OS calls the runtime itself needs, panic handling.
rt::os::{pages_alloc, pages_free, write_stdout, write_stderr, exit, yield_now} (and on
Linux the raw syscall helpers plat builds on); write_stderr_crash: stderr for crash paths,
which gives up a stuck non-blocking stderr instead of waiting for it (Linux)
rt::kernel the Linux kernel ABI per architecture: SYS_*, O_*, Stat, clone_args (also as rt::os::*;
Android has the table too, without rt::os's helpers: docs/ANDROID.md, decision 2)
rt::fx cvtt / cvt / sqrt / minss / maxss / floor_i / ceil_i / div255
rt::x87 the extended-precision steps of f64 <-> decimal text (ini.s), fpatan
rt::sync SpinLock
rt::cpu CPU feature bits (CPUID, cached; force_baseline for --simd sse2)
rt::crash the crash hook, CrashInfo, report (exit 3) -- also for panics
rt::boot what build_rs.py builds into a program (name, manifest, assets) for plat's start
rt::main!(body) the entry symbol of console programs (boot first, then body); with the
feature std also their fn main
rt::panic_hook() (feature std) std's panics take the crash report of rt's panic handler
rt::abort_on_unwind(f) a panic that leaves f ends the program (feature unwind; else f())
rt::panic_take() (feature unwind) the last panic of the calling thread, as text
rt::Alloc (feature std, Windows and Linux) rt's allocator for a program with std that wants it
rt::VERSION, VERSION_MAJOR / _MINOR / _PATCH the library's version (the root Cargo.toml, SemVer;
docs/VERSIONING.md), also as plat::VERSION and ui::VERSION
rt::app_version!() the app's own version (version= of apps/NAME/PACKAGE)
rt::plugin_abi! the calling convention of plugins and modules: win64 on x86-64, C elsewhere (abi.rs)
One of the four library crates that may contain `unsafe` (rt, simd, plat, gpu; and the module
runtimes modrt and modplat).
rt crate root#
/// the library's version, "MAJOR.MINOR.PATCH" (the root Cargo.toml; docs/VERSIONING.md says what a
/// change of each part promises). Not the app's version: that is `rt::app_version!()`.
VERSION: &str = env!("CARGO_PKG_VERSION")
/// the first number of VERSION (incompatible API changes; while 0, the MINOR number counts them)
VERSION_MAJOR: u32 = version_part(VERSION, 0)
/// the second number of VERSION
VERSION_MINOR: u32 = version_part(VERSION, 1)
/// the third number of VERSION
VERSION_PATCH: u32 = version_part(VERSION, 2)
app_version!(...)The app's own version:version=of apps/NAME/PACKAGE, which build_rs.py hands to rustc as JFGUI_VERSION (every program of the app); "0.0.0" without one. An expression of type \&'static str\\: \const APP_VERSION: &str = rt::app_version!();\\, \update::Config::new(app, rt::app_version!(), ..)\\.main!(...)Define the common app entry symbol without requiring the GUI crate in headless tools. It first hands what build_rs.py built in (boot.rs: the app's name, its manifest, its assets) to the platform layer, which installs them as ui::main! does; a refused manifest ends the program with exit code 2. A Cargo build hands the manifest over as a file (JFGUI_PERMISSIONS_FILE with --cfg jfgui_manifest), because an environment variable of a build script holds one line only.In a program with std (feature
std) it also definesfn main, which hands over to plat's start of a std program (jfgui_std_start: crash handlers, the panic hook, thenjfgui_main, the end throughstd::process::exit); the crate then has neither#![no_std]nor#![no_main].The unit tests of a library crate that holds it (
cargo test --lib) need notest_main!: thisjfgui_mainlinks their test binary (never called there), and the panic check leaves the test build out (cfg(test): Cargo builds tests with unwind whatever the profiles say; doc tests build the crate without it, docs/GUIDE.md "An app with std"). Atest_main!next to it would definejfgui_maintwice (E0428)main!(...)(see above)test_main!(...)(E16) thejfgui_maina program's main! defines, for the test binary of a library crate with std and without main! (a style crate'scargo test): plat's start of a std program refers to it, so without it the tests do not link. Never called (the test harness has its own main); no panic check (tests unwind).#[cfg(test)] rt::test_main!();in the crate's lib.rs, also under#. A crate with main! needs none: its main!'sjfgui_mainlinks the tests__rt_panic_check!(...)rt::main!'s check of the panic strategy: JFLib's runtime needspanic = "abort", a program with std built with the featureunwindmay unwind as well. Not in the unit tests of the crate with main! (cfg(test)is the app crate's, where this expands): Cargo builds tests with unwind__rt_panic_check!(...)(see above)__jfgui_main!(...)rt::main!'sjfgui_main, without and with std__std_main!(...)thefn mainof a program with std: plat's start (jfgui_std_start), which calls jfgui_main. In a library crate (an app whose program only links it, like the template) it is not the entry point and stays unused: the program's own main callsplat::std_start().fn abort_on_unwind<R>(f: impl FnOnce() -> R) -> Rrunf; with the featureunwind(a program with std built withpanic = "unwind") a panic that leaves it ends the program as an uncaught panic: JFLib's crash report, exit code 3. plat runs its threads and the program's start through it. Without that feature a panic never unwinds, and this isf().fn outline_lse() -> Option<bool>(tests, docs/ARM64.md ARM7) the way compiler-builtins' outline atomics went: Some(true) LSE, Some(false) the LL/SC loops (a CPU without LSE, or jfgui_ARM_LLSC=1); None where the program has none of them (x86-64; Windows and Apple on ARM64 inline their atomics; Android, glibc and std leave it to the C library)
mod portable
Portable arithmetic, available on native targets for exact backend comparisons.
rt/boot.rs#
Source: lib/rt/boot.rs
boot -- what build_rs.py builds into a program, handed to the platform layer before the
program's own code runs
Boot { app, manifest, assets } rt::main! fills it at compile time: JFGUI_APP (the app's
folder name), JFGUI_PERMISSIONS (apps/NAME/PERMISSIONS or
PERMISSIONS.<bin>), JFGUI_ASSETS (--cfg jfgui_assets, JFA1)
set_handler(f) (plat's process entry) f sets the program up: its name,
app://, its permissions
start(&boot) -> Result<(), i32> (rt::main!) the handler's verdict; Err = exit code. Without
a handler a manifest cannot be enforced: exit code 2
rt knows nothing of plat; plat registers itself here, so console programs get the same
start-up as ui::main! without the UI crate.
struct Bootwhat build_rs.py built into the programapp: Option<&'static str>-- the app's name for its folders (plat::vfs::set_app_id)manifest: Option<&'static str>-- the app's permission manifest (plat::policy::install)assets: &'static [u8]-- the app's assets, a JFA1 bundle (app://); empty without assets
type Handler = fn(&Boot) -> Result<(), i32>sets the program up -> Err(exit code)fn set_handler(f: Handler)(plat's process entry) the function that sets a program upfn start(b: &Boot) -> Result<(), i32>(rt::main!) set the program up before its own code runs
rt/cpu.rs#
Source: lib/rt/cpu.rs
cpu -- CPU feature detection for SIMD dispatch [src/core/cpu.s]
features() -> CPU_* bits cached; SSE2 is the baseline and has no bit
force_baseline() report 0 from now on (plat calls it at process start for
`--simd sse2`: baseline kernels only, to compare results)
cpuid(leaf) -> CpuidResult
CPU_AVX2 and CPU_FMA are only reported when the OS saves the YMM state (CPUID.1:ECX.OSXSAVE
and XGETBV(0) bits 1 and 2). Thread safe: every caller computes the same cached value.
Lives in rt so that simd (which may not depend on plat) dispatches on the same bits.
CPU_SSE41: u32 = 1
CPU_AVX2: u32 = 2 // AVX2 + OS-enabled YMM state
CPU_FMA: u32 = 4 // FMA3 + OS-enabled YMM state
CPU_POPCNT: u32 = 8
CPU_BMI2: u32 = 16
fn cpuid(leaf: u32) -> CpuidResultfn features() -> u32CPU_* bits (cached) [cpu_features]fn force_baseline()report no optional features from now on (--simd sse2)
rt/crash.rs#
Source: lib/rt/crash.rs
crash -- crash reports: the hook an app installs, the record the platform fills [docs/modules/CRASH.md]
set_hook(Some(f)) f(&CrashInfo) runs once when the process crashes or panics, after
the stderr line and before the process ends with exit code 3. A
crash inside it (or a second crashing thread) ends the process at
once; a stack overflow skips it.
set_pre_hook(Some(f)) the library's part (plat::log: the newest log lines), before the
app's hook; the same rules
report(&info) -> ! the end of every crash (the platform's fault handlers, the panic
handler): the pre-hook, the hook, then exit(3)
StackText<N> a fixed buffer for core::fmt -- crash paths do not allocate (the
allocator lock may be held by the crashing thread)
Rust adds one kind, CK_PANIC: the panic message is in CrashInfo::msg.
CK_ACCESS: u32 = 1 // access violation / SIGSEGV
CK_ILLEGAL: u32 = 2 // illegal or privileged instruction
CK_DIVIDE: u32 = 3 // integer division by zero / overflow, SIGFPE
CK_BUS: u32 = 4 // SIGBUS, misalignment, in-page error
CK_STACK: u32 = 5 // stack overflow (no hook: there is no stack left)
CK_OTHER: u32 = 6
CK_PANIC: u32 = 7 // a Rust panic (msg)
FRAMES_MAX: usize = 32
struct CrashInfo<'a>what the crash handler knows (the CRASHINFO record of ASMLIB)code: u32-- Windows exception code / Linux signal number (panic: 0)kind: u32-- CK_*access: u32-- access violations: 0 read, 1 write, 8 execute, 2 unknownaddr: u64-- data address of an access violation / bus error (0 = none)ip: u64-- instruction pointerbase: u64-- image base: offset = address - base (Linux 0: the .map lists addresses)code0: u64-- the executable code: code0..code1code1: u64regs: [u64; 17]-- rax rbx rcx rdx rsi rdi rbp rsp r8 .. r15 ripframes: [u64; FRAMES_MAX]-- the call chain: return addresses, innermost first (plat)nframes: u32msg: &'a str-- CK_PANIC: the message
impl CrashInfo<'_>
const fn empty() -> Selftype CrashHook = fn(&CrashInfo)fn set_hook(f: Option<CrashHook>)install (Some) or remove (None) the crash hook [plat_crash_hook]fn set_pre_hook(f: Option<CrashHook>)install (Some) or remove (None) the library's hook that runs before the app'sfn busy() -> boola crash is being reported (a second one ends the process at once)fn report(info: &CrashInfo) -> !run the hook once, then exit(3)struct StackText<const N: usize>formatting into a fixed buffer (overflow is cut off)
impl<const N: usize> StackText<N>
const fn new() -> Selffn bytes(&self) -> &[u8]fn as_str(&self) -> &str
rt/fx.rs#
Source: lib/rt/fx.rs
fx -- scalar SSE float operations with exactly the semantics the assembly uses
(cvttss2si, cvtss2si with round-half-even, sqrtss, minss, maxss), so float results
are bit-identical to ASMLIB. Rust never fuses a multiply and an add into an FMA.
fn cvtt(x: f32) -> i32cvttss2si: truncate towards zero (0x80000000 for NaN / out of range)fn cvt(x: f32) -> i32cvtss2si: round to nearest, ties to even (the default MXCSR mode)fn sqrt(x: f32) -> f32fn minss(a: f32, b: f32) -> f32minss a, b: a < b ? a : b (b when unordered)fn maxss(a: f32, b: f32) -> f32maxss a, b: a > b ? a : b (b when unordered)fn floor_i(x: f32) -> i32floor / ceil the way f_floor / f_ceil do it: truncate, then step if neededfn ceil_i(x: f32) -> i32fn div255(x: u32) -> u32round(x / 255) for x in 0..=65025: ((x + 128) * 257) >> 16 (pmulhuw), equal to (x + 128 + ((x + 128) >> 8)) >> 8fn sqrtd(x: f64) -> f64sqrtsdfn maxsd(a: f64, b: f64) -> f64maxsd a, b: a > b ? a : b (b when unordered)fn minsd(a: f64, b: f64) -> f64minsd a, b: a < b ? a : b (b when unordered)fn cvttd(x: f64) -> i32cvttsd2si (32-bit): truncate towards zero (0x80000000 for NaN / out of range)fn cvtd(x: f64) -> i32cvtsd2si (32-bit): round to nearest even (0x80000000 for NaN / out of range)fn cvtd64(x: f64) -> i64cvtsd2si (64-bit): round to nearest even (i64::MIN for NaN / out of range)fn cvttd64(x: f64) -> i64cvttsd2si (64-bit): truncate (i64::MIN for NaN / out of range)
rt/kernel.rs#
Source: lib/rt/kernel.rs
kernel -- the Linux kernel ABI, one table per architecture: system call numbers, open flags,
struct stat, the order of clone's arguments. Nothing else defines them (build_rs.py lint):
a wrong number compiles and calls something else (57 is fork on x86-64, close on ARM64), a wrong
flag means something else (O_NOFOLLOW here is O_LARGEFILE there). Both tables name the same
things, line by line; tools/kernel_table_check.py compares them with the kernel's headers.
Everything is also reached as rt::os::*, which has the helpers for the calls ARM64 does not
have (poll, fork, dup2, rename).
SYS_* system calls; SYS_ARCH_PRCTL only on x86-64
O_* open flags
Stat struct stat; Stat::default() to pass it to fstat / newfstatat
clone_args clone's arguments after flags and stack, in the kernel's order
The same on both architectures: AT_FDCWD, and what is not listed here (AT_* flags, S_IF*, errno
values, F_*, MAP_*, PROT_*, the clone flags, struct statfs).
/// the current directory as the base of a relative path in the *at calls
AT_FDCWD: usize = -100isize as usize
rt/sync.rs#
Source: lib/rt/sync.rs
sync -- a spin lock for short critical sections (allocator-free, usable in statics)
SpinLock::new(value) const
lock.lock() -> guard spins a little, then gives the time slice away
lock.try_lock() -> Option the guard only when the lock is free (crash paths)
For data that several threads touch briefly (the environment overrides, the pool
queue); long waits belong on a semaphore (plat::Sem).
struct SpinLock<T>struct Guard<'a, T>
impl<T> SpinLock<T>
const fn new(v: T) -> Selffn lock(&self) -> Guard<'_, T>fn try_lock(&self) -> Option<Guard<'_, T>>the guard when the lock is free now, else None (never waits)
rt/x87.rs#
Source: lib/rt/x87.rs
x87 -- the extended-precision steps of the decimal <-> double conversions [src/core/ini.s]
scale(m, e) -> f64 m * 10^e (e < 0: m / 10^-e), one rounding to double (f64_parse)
scale_round(v, k) -> i64 round(v * 10^k) (k < 0: v / 10^-k), to nearest (f64_format)
log10_round(v) -> i32 round(log10 v) as fyl2x computes it (f64_format)
pow(x, y) -> f64 x^y as fx_pow computes it (R6-icc) [src/fx/fx_lut.s]
exp2 / log2 / cos / sin fx_exp2 / fx_log2 / fx_cos / fx_sin (r10-fx) [src/fx/fx_lut.s]
rz_exp2 / rz_log2 PaintCraft's rz_exp2 / rz_log2 (pn-ui; other rounding) [dlg_rotzoom.s]
ASMLIB computes these on the x87 unit with 64-bit precision and round to nearest (the
control word is saved and restored in every call), 10^n as fld1 times the double table
1e0..1e22 (1e22 repeated for larger n). The same instructions run here, so the text a
double is written as and the double a text reads as are bit-identical to the assembly.
fn scale(m: u64, e: i32) -> f64m * 10^e or m / 10^-e (m < 2^63), rounded once to double [f64_parse .fp_calc]fn scale_round(v: f64, k: i32) -> i64frndint(v * 10^k) or frndint(v / 10^-k) as a 64-bit integer [f64_format .ff_scale]fn log10_round(v: f64) -> i32fldlg2 / fyl2x / fistp: log10 v rounded to the nearest integer [f64_format]fn atan2(y: f64, x: f64) -> f64fpatan: atan2(y, x) on the x87 unit, rounded once to double (the precision control does not apply to fpatan) [pathdata.s pd_atan2, dash.s dc_atan2]fn sincos(x: f64) -> (f64, f64)fsincos: (cos x, sin x) on the x87 unit, each rounded once to double (the precision control does not apply to fsincos) [ui_value.s deg_sincos]fn pow(x: f64, y: f64) -> f64fx_pow: x^y -- NaN when x or y is NaN, 1 for y == 0, 0 for x <= 0, x for y == 1, else 2^(y log2 x) on the x87 unit with 64-bit precision and round to nearest (fyl2x, then frndint / f2xm1 / fscale), rounded once to double [fx_lut.s fx_pow]fn rz_log2(x: f64) -> f64fyl2x with y = 1: log2(x) on the x87 unit, rounded once to double (fyl2x is not subject to the precision control) [PaintCraft dlg_rotzoom.s rz_log2]fn rz_exp2(x: f64) -> f642^x as rz_exp2 computes it (|x| < 2^30): i = cvtsd2si x, f = x - i (SSE), then on the x87 unit f2xm1 f, + 1 (faddp: rounded by the process's precision control, as in the assembly), fscale by i, rounded to double [PaintCraft dlg_rotzoom.s rz_exp2]
rt/portable/fx.rs#
Source: lib/rt/portable/fx.rs
Scalar IEEE-754 operations matching the native SSE conversion and operand-selection
rules. The square roots avoid libm imports and give correctly rounded results: binary32 by an
integer root, binary64 by Newton's method with an integer correction (sqrt_portable).
fn nearest(x: f64) -> f64Round a finite binary64 value to its nearest integer, with ties to even.fn arithmetic32(a: f32, b: f32, result: f32) -> f32Select and quiet NaN payloads as scalar SSE arithmetic does, including invalid operations.fn arithmetic64(a: f64, b: f64, result: f64) -> f64Binary64 SSE arithmetic NaN payload selection.fn cvtt(x: f32) -> i32SSE truncating f32 to i32 conversion, including the indefinite overflow value.fn cvt(x: f32) -> i32SSE nearest-even f32 to i32 conversion.fn cvttd(x: f64) -> i32SSE truncating f64 to i32 conversion.fn cvtd(x: f64) -> i32SSE nearest-even f64 to i32 conversion.fn cvttd64(x: f64) -> i64SSE truncating f64 to i64 conversion.fn cvtd64(x: f64) -> i64SSE nearest-even f64 to i64 conversion.fn sqrt(x: f32) -> f32Correctly rounded binary32 square root; preserves signed zero and quiets NaNs.fn sqrtd(x: f64) -> f64Correctly rounded binary64 square root; preserves signed zero and quiets NaNs. The same function as [sqrt_portable].fn sqrt_portable(x: f64) -> f64The correctly rounded binary64 square root from f64 operations and one 64 x 64 bit product, with the results ofsqrtsdfor every input (signed zero kept, NaN quieted, a negative number gives the negative default NaN): Newton's method gives an estimate within a few units in the last place, the integer test (R - 1/2)^2 < X <= (R + 1/2)^2 on the significand picks the right neighbour.rt::fx::sqrtdis this function where the processor has no square root rt uses (the browser, the x86-64 Android emulator); on the other targets it is here for comparisons and for lib/physics' and lib/geom's tests. Several times faster than the bit-by-bit integer root it replaced (docs/PHYSICS.md, measurements).#[inline]: compiled in the calling crate, with its optimisation level (rt has 1 in development builds).fn minss(a: f32, b: f32) -> f32SSE minimum: return the second operand for equal or unordered operands.fn maxss(a: f32, b: f32) -> f32SSE maximum: return the second operand for equal or unordered operands.fn minsd(a: f64, b: f64) -> f64Binary64 SSE minimum.fn maxsd(a: f64, b: f64) -> f64Binary64 SSE maximum.fn floor_i(x: f32) -> i32Native floor contract: truncate, then decrement if necessary.fn ceil_i(x: f32) -> i32Native ceiling contract: truncate, then increment if necessary.fn div255(x: u32) -> u32Rounded division by 255 for 0..=65025.
rt/portable/math.rs#
Source: lib/rt/portable/math.rs
Portable replacement for the native x87 entry points. Decimal scaling emulates the x87
64-bit significand after each multiply/divide. The transcendentals carry double-doubles
(below) and stay within about half an ulp; native x87 is the comparison reference.
fn scale(m: u64, e: i32) -> f64Decimal scaling with the same 64-bit significand intermediate rounding as x87.fn scale_round(v: f64, k: i32) -> i64Nearest-even integer after decimal scaling, including native indefinite overflow.fn log10_round(v: f64) -> i32Nearest integer decimal logarithm; nonpositive inputs produce the SSE indefinite value.fn log2(x: f64) -> f64Binary logarithm within about half an ulp (a table and a series in double-doubles).fn exp2(x: f64) -> f64Platform-independent base-two exponent within about half an ulp (double-doubles, rounded once, subnormal results too); finite underflow rounds into subnormals, 1024 on is inf.fn rz_log2(x: f64) -> f64Existing rotation/zoom base-two logarithm API.fn rz_exp2(x: f64) -> f64Existing rotation/zoom base-two exponent API.fn pow(x: f64, y: f64) -> f64Effect power contract: y=0 yields 1, nonpositive bases yield 0, NaNs propagate canonically. Else 2^(y log2 x) with log2 x and its product with y as double-doubles, rounded once: within 0.501 ulp in the tests (|y log2 x| up to 1074); x = +inf gives inf (y > 0) or 0.fn atan2(y: f64, x: f64) -> f64Quadrant-aware arctangent, including signed zeros and infinite operands: c + atan(n / d) or c - atan(n / d) with c = 0, pi/2 or pi as double-doubles, rounded once (within about half an ulp).fn sincos(x: f64) -> (f64, f64)Cosine and sine with shared quadrant reduction; return order matches the x87 API.fn cos(x: f64) -> f64Scalar cosine using the common angle reduction (the same bits as sincos).fn sin(x: f64) -> f64Scalar sine using the common angle reduction (the same bits as sincos).
rt/hosted.rs#
Source: lib/rt/hosted.rs
hosted -- what rt has for a program with the standard library (feature std, docs/CRATES.md
CR6); the only file of rt that names std, compiled only with that feature. std brings the panic
handler, the allocator and the memory functions then (lib.rs, mem.rs and os.rs leave theirs out).
panic_hook() std's panics end as rt's panic handler ends them without std
abort_on_unwind(f) (feature unwind) a panic that leaves f ends the program as an uncaught one
panic_take() (feature unwind) the last panic of the calling thread, as text
With the feature unwind and panic = "unwind" a panic unwinds: the hook only keeps its text (LAST)
and reports nothing, since the app may catch it. It is reported where it leaves JFLib's threads
and the program's start (abort_on_unwind) or reaches a function that cannot unwind (an extern
callback such as a window procedure: core panics once more there, with one of NOUNWIND's texts).
fn panic_hook()(feature std) std's panics end as rt's panic handler ends them without std: one line on stderr, the crash hook, exit code 3. plat's start of a std program installs it; replacing it withstd::panic::set_hookgives up JFLib's crash report for panics. With the featureunwindandpanic = "unwind"it reports only a panic nobody catches: one that leaves the program's start or a thread of JFLib's, or reaches a callback of the system ([abort_on_unwind]).fn abort_on_unwind<R>(f: impl FnOnce() -> R) -> R(featureunwind) runf; a panic that leaves it ends the program as an uncaught panic: JFLib's crash report (the panic's text on stderr, the crash hook), exit code 3. plat runs its threads and the program's start through it, so only the app's ownstd::panic::catch_unwind(on any thread) keeps a panic from ending the program. Withpanic = "abort"it isf().fn panic_take() -> Option<String>(featureunwind) the last panic on the calling thread as JFLib's crash report shows it ("panicked at FILE:LINE:COL:\nMESSAGE"), taken: for a panic the app caught withstd::panic::catch_unwind, whose payload holds the message alone. None when no panic came since the last call (or the program is built withpanic = "abort").