lua_stdlib/os_lib.rs
1//! Lua `os` standard library — `os.*` time/date arithmetic, environment, and
2//! process control.
3//!
4//! ## Graduation (Idiomatization Sprint 2, Phase 2 — 2026-06-14)
5//!
6//! The **deterministic** half of this module (the `os.date`/`os.time` broken-down
7//! time arithmetic) is guarded by `crates/lua-stdlib/tests/os_strengthen.rs`,
8//! pinned against the version-suffixed reference binaries. Net-strengthening came
9//! FIRST and caught four real version divergences (our impl had applied the
10//! modern 5.3+/5.4+ field- and specifier-validation rules to ALL versions); they
11//! were fixed in `get_field`/`os_time`/`os_date`, single-source and version-gated.
12//! The version gates are load-bearing — keep them explicit.
13//!
14//! The time arithmetic is **pure Rust, no `unsafe`, no libc bridge**:
15//! [`decompose_utc`]/[`compose_utc`] implement Howard Hinnant's exact
16//! proleptic-Gregorian algorithms, and [`strftime_one`] formats specifiers
17//! directly. There is no `gmtime_r`/`mktime`/`strftime` FFI to keep.
18//!
19//! ## Impure surface (host-dependent — not reference-pinnable)
20//!
21//! `os.getenv`/`tmpname`/`remove`/`rename`/`execute`/`exit` touch the real
22//! environment, filesystem, and process; `os.clock`/`os.time`'s absolute value
23//! and the locale/timezone specifiers (`%z`/`%Z`/`%c`/`%x`/`%X`/`%r`/`%p`/`%P`)
24//! depend on the host clock/zone/locale. Those route through `GlobalState` hooks
25//! (or `std`) for native/sandboxed/WASM hosts; only their arg-handling and
26//! error-shape are reference-pinned, never their effects.
27
28use crate::state_stub::{LuaState, LuaStateStubExt as _};
29use lua_types::{LuaError, LuaExit, LuaType, LuaValue};
30use lua_vm::state::OsExecuteReason;
31
32// ── Constants ────────────────────────────────────────────────────────────────
33
34//
35// Valid `strftime` conversion specifiers — C99 / POSIX variant.
36// Single-char specifiers appear first; the `||` sentinel signals the start
37// of 2-char specifiers (e.g. `%EC`, `%Oy`). See `check_strftime_option`.
38const STRFTIME_OPTIONS: &[u8] =
39 b"aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%||EcECExEXEyEYOdOeOHOIOmOMOSOuOUOVOwOWOy";
40
41const SIZE_TIME_FMT: usize = 250;
42
43// ── TmFields ─────────────────────────────────────────────────────────────────
44
45/// Local mirror of C's `struct tm`.
46///
47/// Field conventions follow the C standard: `tm_year` is years since 1900,
48/// `tm_mon` ∈ [0, 11], `tm_wday` ∈ [0, 6] (Sunday = 0), `tm_isdst` is −1 when
49/// DST status is unknown. This is a plain value type, not a libc binding — the
50/// conversions ([`decompose_utc`]/[`compose_utc`]) are pure Rust.
51#[derive(Debug, Default, Clone)]
52pub struct TmFields {
53 pub tm_sec: i32,
54 pub tm_min: i32,
55 pub tm_hour: i32,
56 pub tm_mday: i32,
57 pub tm_mon: i32,
58 pub tm_year: i32,
59 pub tm_wday: i32,
60 pub tm_yday: i32,
61 pub tm_isdst: i32,
62}
63
64// ── ByteDisplay ──────────────────────────────────────────────────────────────
65
66/// `Display` adapter for `&[u8]` slices known to contain ASCII bytes.
67///
68/// Used only for formatting Lua table field names (always ASCII identifiers such
69/// as `"year"`, `"month"`) inside error messages, without allocating a `String`.
70struct ByteDisplay<'a>(&'a [u8]);
71
72impl std::fmt::Display for ByteDisplay<'_> {
73 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74 for &b in self.0 {
75 write!(f, "{}", b as char)?;
76 }
77 Ok(())
78 }
79}
80
81// ── Private stack-manipulation helpers ───────────────────────────────────────
82
83///
84/// Pushes `(value as i64) + (delta as i64)` as a Lua integer, then stores it
85/// in the table currently on top of the stack at field `key`.
86fn set_field(state: &mut LuaState, key: &[u8], value: i32, delta: i32) -> Result<(), LuaError> {
87 state.push(LuaValue::Int((value as i64) + (delta as i64)));
88 state.set_field(-2, key)?;
89 Ok(())
90}
91
92///
93/// Stores a boolean at field `key` in the table on top of the stack.
94/// A negative `value` means "undefined" — the field is silently skipped.
95fn set_bool_field(state: &mut LuaState, key: &[u8], value: i32) -> Result<(), LuaError> {
96 if value < 0 {
97 return Ok(());
98 }
99 state.push(LuaValue::Bool(value != 0));
100 state.set_field(-2, key)?;
101 Ok(())
102}
103
104///
105/// Writes every field of `stm` into the table on top of the stack, applying the
106/// offsets that convert from C-library conventions to Lua conventions:
107/// year+1900, month+1, wday+1, yday+1.
108fn set_all_fields(state: &mut LuaState, stm: &TmFields) -> Result<(), LuaError> {
109 set_field(state, b"year", stm.tm_year, 1900)?;
110 set_field(state, b"month", stm.tm_mon, 1)?;
111 set_field(state, b"day", stm.tm_mday, 0)?;
112 set_field(state, b"hour", stm.tm_hour, 0)?;
113 set_field(state, b"min", stm.tm_min, 0)?;
114 set_field(state, b"sec", stm.tm_sec, 0)?;
115 set_field(state, b"yday", stm.tm_yday, 1)?;
116 set_field(state, b"wday", stm.tm_wday, 1)?;
117 set_bool_field(state, b"isdst", stm.tm_isdst)?;
118 Ok(())
119}
120
121///
122/// Reads a boolean field from the table on top of the stack.
123/// Returns `-1` when the field is absent (nil), or `0` / `1` for false / true.
124fn get_bool_field(state: &mut LuaState, key: &[u8]) -> Result<i32, LuaError> {
125 let ty = state.get_field(-1, key)?;
126 let res = if matches!(ty, LuaType::Nil) {
127 -1i32
128 } else {
129 state.to_boolean(-1) as i32
130 };
131 state.pop_n(1);
132 Ok(res)
133}
134
135/// Reads an integer field from the date table on top of the stack.
136///
137/// * `d` — default when the field is absent; pass `d < 0` to make absence an
138/// error ("missing in date table").
139/// * `delta` — subtracted from the read value to convert from Lua's offset
140/// representation back to C-library conventions (e.g. month−1, year−1900).
141///
142/// The validation behaviour is version-gated, faithful to `loslib.c`'s
143/// `getfield` evolution and pinned per version by
144/// `os_strengthen.rs::time_non_integer_field_is_unchecked_pre_5_3_crossversion`
145/// and `…out_of_bound…`:
146///
147/// * **5.1 / 5.2** (legacy): the field is read with `lua_(is)number` semantics —
148/// any value coercible to a number (including numeric strings and fractional
149/// floats) is accepted and **truncated** toward zero; a non-numeric value is
150/// treated as absent, falling back to the default `d` or raising "missing"
151/// when `d < 0`. There is no "is not an integer" check and no out-of-bound
152/// check (`lua_tointeger` truncates silently).
153/// * **5.3+**: a present non-nil non-integer raises "is not an integer", and an
154/// in-range integer that overflows the C `int` field raises "is out-of-bound".
155///
156/// Stack cleanup on the error paths (pop before returning `Err`) is added vs.
157/// the C version, where `luaL_error` never returns (longjmp).
158fn get_field(state: &mut LuaState, key: &[u8], d: i32, delta: i32) -> Result<i32, LuaError> {
159 let legacy = matches!(
160 state.global().lua_version,
161 lua_types::LuaVersion::V51 | lua_types::LuaVersion::V52
162 );
163 let ty = state.get_field(-1, key)?;
164
165 if legacy {
166 let res = match state.to_number_x(-1) {
167 Some(n) => (n as i64).wrapping_sub(delta as i64) as i32,
168 None if d < 0 => {
169 state.pop_n(1);
170 return Err(LuaError::runtime(format_args!(
171 "field '{}' missing in date table",
172 ByteDisplay(key),
173 )));
174 }
175 None => d,
176 };
177 state.pop_n(1);
178 return Ok(res);
179 }
180
181 let res: i32 = match state.to_integer_x(-1) {
182 Some(res) => {
183 let in_bounds = if res >= 0 {
184 res.saturating_sub(delta as i64) <= (i32::MAX as i64)
185 } else {
186 (i32::MIN as i64).saturating_add(delta as i64) <= res
187 };
188 if !in_bounds {
189 state.pop_n(1);
190 return Err(LuaError::runtime(format_args!(
191 "field '{}' is out-of-bound",
192 ByteDisplay(key),
193 )));
194 }
195 (res - delta as i64) as i32
196 }
197 None => {
198 if !matches!(ty, LuaType::Nil) {
199 state.pop_n(1);
200 return Err(LuaError::runtime(format_args!(
201 "field '{}' is not an integer",
202 ByteDisplay(key),
203 )));
204 } else if d < 0 {
205 state.pop_n(1);
206 return Err(LuaError::runtime(format_args!(
207 "field '{}' missing in date table",
208 ByteDisplay(key),
209 )));
210 }
211 d
212 }
213 };
214 state.pop_n(1);
215 Ok(res)
216}
217
218/// Validates the `strftime` conversion specifier at the start of `conv` against
219/// `STRFTIME_OPTIONS`.
220///
221/// `cc` must have `cc[0] == b'%'` on entry (set by the caller). On success the
222/// matched specifier bytes are written into `cc[1..=oplen]`, a null terminator is
223/// written at `cc[oplen+1]`, and the sub-slice of `conv` after the consumed
224/// specifier is returned.
225///
226/// On failure a `LuaError::arg_error` describing the invalid specifier is
227/// returned.
228///
229/// The options table uses `|` characters as length-transition markers: one `|`
230/// increments `oplen` from 1 to 2 (and the following advance jumps past the `||`
231/// sentinel), enabling 2-char specifiers like `%EC`.
232fn check_strftime_option<'a>(
233 _state: &mut LuaState,
234 conv: &'a [u8],
235 cc: &mut [u8; 4],
236) -> Result<&'a [u8], LuaError> {
237 let options = STRFTIME_OPTIONS;
238 let mut oplen: usize = 1;
239 let mut i: usize = 0;
240
241 while i < options.len() && oplen <= conv.len() {
242 if options[i] == b'|' {
243 // Increment first so the subsequent `i += oplen` uses the new value,
244 // which jumps from the first `|` past the entire `||` separator block.
245 oplen += 1;
246 i += oplen;
247 } else if i + oplen <= options.len() && conv[..oplen] == options[i..i + oplen] {
248 // cc[0] = b'%' is pre-filled; write specifier bytes into cc[1..=oplen].
249 debug_assert!(
250 oplen <= 2,
251 "STRFTIME_OPTIONS only has 1- and 2-char specifiers"
252 );
253 cc[1..=oplen].copy_from_slice(&conv[..oplen]);
254 cc[oplen + 1] = 0;
255 return Ok(&conv[oplen..]);
256 } else {
257 i += oplen;
258 }
259 }
260 Err(LuaError::arg_error(1, "invalid conversion specifier"))
261}
262
263/// Reads argument `arg` as a Lua integer and returns it as a Unix timestamp.
264///
265/// On the 64-bit targets we support, `time_t == i64 == lua_Integer`, so the C
266/// original's representability check (`(time_t)t == t`) is always satisfied and
267/// is omitted here (it would only matter on a hypothetical 32-bit `time_t`).
268fn check_time(state: &mut LuaState, arg: i32) -> Result<i64, LuaError> {
269 let t = state.check_arg_integer(arg)?;
270 Ok(t)
271}
272
273/// Returns the current Unix timestamp (seconds since 1970-01-01 UTC).
274fn unix_now(state: &LuaState) -> Result<i64, LuaError> {
275 if let Some(now_fn) = state.global().unix_time_hook {
276 return Ok(now_fn());
277 }
278
279 #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
280 {
281 let _ = state;
282 return Err(LuaError::runtime(format_args!(
283 "current time not available in this host"
284 )));
285 }
286
287 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
288 {
289 use std::time::{SystemTime, UNIX_EPOCH};
290 Ok(SystemTime::now()
291 .duration_since(UNIX_EPOCH)
292 .map(|d| d.as_secs() as i64)
293 .unwrap_or(0))
294 }
295}
296
297/// Returns the host's local timezone offset (seconds) at instant `t`, such that
298/// the local broken-down time equals `decompose_utc(t + offset)`.
299///
300/// Routes through `GlobalState::local_offset_hook` when the host installs one
301/// (lua-cli does, via `localtime_r`). Absent a hook the offset is 0, so
302/// `os.date`/`os.time` fall back to UTC — matching the prior behaviour and
303/// keeping the round-trip exact under bare WASM.
304fn local_offset(state: &LuaState, t: i64) -> i64 {
305 match state.global().local_offset_hook {
306 Some(off_fn) => off_fn(t),
307 None => 0,
308 }
309}
310
311fn native_temp_name() -> Result<Vec<u8>, LuaError> {
312 #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
313 {
314 return Err(LuaError::runtime(format_args!(
315 "temporary filenames not available in this host"
316 )));
317 }
318
319 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
320 {
321 use std::sync::atomic::{AtomicU64, Ordering};
322 use std::time::{SystemTime, UNIX_EPOCH};
323
324 static COUNTER: AtomicU64 = AtomicU64::new(0);
325
326 let mut dir: Vec<u8> = {
327 let path = std::env::temp_dir();
328 #[cfg(unix)]
329 {
330 use std::os::unix::ffi::OsStrExt;
331 path.as_os_str().as_bytes().to_vec()
332 }
333 #[cfg(not(unix))]
334 {
335 path.to_string_lossy().as_bytes().to_vec()
336 }
337 };
338 if dir.last().copied() != Some(b'/') && dir.last().copied() != Some(b'\\') {
339 dir.push(b'/');
340 }
341
342 let nanos = SystemTime::now()
343 .duration_since(UNIX_EPOCH)
344 .map(|d| d.as_nanos())
345 .unwrap_or(0);
346 let n = COUNTER.fetch_add(1, Ordering::Relaxed);
347
348 let suffix = format!("lua_{:x}_{:x}_{:x}", std::process::id(), nanos, n);
349 dir.extend_from_slice(suffix.as_bytes());
350 Ok(dir)
351 }
352}
353
354fn host_temp_name(state: &LuaState) -> Result<Vec<u8>, LuaError> {
355 match state.global().temp_name_hook {
356 Some(temp_fn) => temp_fn(),
357 None => native_temp_name(),
358 }
359}
360
361/// Decompose a Unix timestamp (UTC) into broken-down time fields — the pure-Rust
362/// replacement for C's `gmtime_r`.
363///
364/// Load-bearing: uses Howard Hinnant's `civil_from_days` algorithm (public
365/// domain, see
366/// <http://howardhinnant.github.io/date_algorithms.html#civil_from_days>),
367/// exact for all `i64` inputs across the proleptic Gregorian calendar and pinned
368/// by `os_strengthen.rs` (the `!*t`/`!%…` UTC pins, including a negative epoch).
369/// Conventions: `tm_isdst` is 0 for UTC; `tm_wday` is 0-based with Sunday = 0
370/// (POSIX); `tm_yday` is 0-based (`set_all_fields` adds 1 for the Lua table).
371fn decompose_utc(t: i64) -> TmFields {
372 let days = t.div_euclid(86_400);
373 let sod = t.rem_euclid(86_400) as i32;
374
375 let tm_hour = sod / 3600;
376 let tm_min = (sod / 60) % 60;
377 let tm_sec = sod % 60;
378
379 let z = days + 719_468;
380 let era = (if z >= 0 { z } else { z - 146_096 }).div_euclid(146_097);
381 let doe = z - era * 146_097;
382 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
383 let y = yoe + era * 400;
384 let doy_mar = doe - (365 * yoe + yoe / 4 - yoe / 100);
385 let mp = (5 * doy_mar + 2) / 153;
386 let day = (doy_mar - (153 * mp + 2) / 5 + 1) as i32;
387 let month: i32 = if mp < 10 {
388 (mp + 3) as i32
389 } else {
390 (mp - 9) as i32
391 };
392 let year = y + if month <= 2 { 1 } else { 0 };
393
394 let leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
395 const DAYS_BEFORE_MONTH: [i32; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
396 let tm_yday =
397 DAYS_BEFORE_MONTH[(month - 1) as usize] + (day - 1) + if leap && month > 2 { 1 } else { 0 };
398
399 let tm_wday = (days + 4).rem_euclid(7) as i32;
400
401 TmFields {
402 tm_sec,
403 tm_min,
404 tm_hour,
405 tm_mday: day,
406 tm_mon: month - 1,
407 tm_year: (year - 1900) as i32,
408 tm_wday,
409 tm_yday,
410 tm_isdst: 0,
411 }
412}
413
414/// Compose a UTC Unix timestamp from broken-down time fields.
415///
416/// Inverse of `decompose_utc`. Uses Howard Hinnant's `days_from_civil` and
417/// normalises month overflow into the year (matching `mktime`'s behaviour for
418/// the year/month axes). Day-of-month, hour, minute, and second components
419/// are added linearly so out-of-range values normalise carry into the larger
420/// units exactly as `mktime` would for UTC.
421fn compose_utc(tm: &TmFields) -> i64 {
422 let mut y: i64 = (tm.tm_year as i64) + 1900;
423 let mut m: i64 = (tm.tm_mon as i64) + 1;
424 let dy = (m - 1).div_euclid(12);
425 y += dy;
426 m -= dy * 12;
427 let y_adj = if m <= 2 { y - 1 } else { y };
428 let era = (if y_adj >= 0 { y_adj } else { y_adj - 399 }).div_euclid(400);
429 let yoe = y_adj - era * 400;
430 let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + (tm.tm_mday as i64) - 1;
431 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
432 let days = era * 146_097 + doe - 719_468;
433 days * 86_400 + (tm.tm_hour as i64) * 3600 + (tm.tm_min as i64) * 60 + (tm.tm_sec as i64)
434}
435
436/// Append the formatted result of a single `strftime` conversion specifier — the
437/// pure-Rust replacement for delegating to the platform `strftime`.
438///
439/// `cc` holds the canonical specifier bytes filled in by `check_strftime_option`:
440/// `cc[0] == b'%'`, `cc[1]` is the leading specifier char, and for 2-char
441/// specifiers `cc[2]` is the second char (an E/O modifier comes first in C, e.g.
442/// `%Ex` → `cc = "%Ex\0"`). `oplen` is 1 or 2.
443///
444/// Load-bearing: the host-independent specifiers (numeric/ISO + C-locale English
445/// day/month names) are pinned byte-for-byte by `os_strengthen.rs`. The E/O
446/// modifiers are stripped (POSIX permits ignoring them and falling back to the
447/// unmodified form); locale/zone specifiers (`%z`/`%Z`/`%c`/`%x`/`%X`/`%r`/`%p`/
448/// `%P`) are host-dependent in the C reference and so are not pinned.
449fn strftime_one(buf: &mut Vec<u8>, cc: &[u8; 4], oplen: usize, tm: &TmFields) {
450 use std::io::Write as _;
451 let spec = if oplen == 2 { cc[2] } else { cc[1] };
452 let year_full = (tm.tm_year as i64) + 1900;
453 let hour12 = {
454 let h = tm.tm_hour.rem_euclid(12);
455 if h == 0 {
456 12
457 } else {
458 h
459 }
460 };
461 const DAY_SHORT: [&[u8]; 7] = [b"Sun", b"Mon", b"Tue", b"Wed", b"Thu", b"Fri", b"Sat"];
462 const DAY_LONG: [&[u8]; 7] = [
463 b"Sunday",
464 b"Monday",
465 b"Tuesday",
466 b"Wednesday",
467 b"Thursday",
468 b"Friday",
469 b"Saturday",
470 ];
471 const MON_SHORT: [&[u8]; 12] = [
472 b"Jan", b"Feb", b"Mar", b"Apr", b"May", b"Jun", b"Jul", b"Aug", b"Sep", b"Oct", b"Nov",
473 b"Dec",
474 ];
475 const MON_LONG: [&[u8]; 12] = [
476 b"January",
477 b"February",
478 b"March",
479 b"April",
480 b"May",
481 b"June",
482 b"July",
483 b"August",
484 b"September",
485 b"October",
486 b"November",
487 b"December",
488 ];
489 let wday_idx = tm.tm_wday.rem_euclid(7) as usize;
490 let mon_idx = tm.tm_mon.rem_euclid(12) as usize;
491 match spec {
492 b'Y' => {
493 let _ = write!(buf, "{}", year_full);
494 }
495 b'y' => {
496 let _ = write!(buf, "{:02}", year_full.rem_euclid(100));
497 }
498 b'C' => {
499 let _ = write!(buf, "{:02}", year_full.div_euclid(100));
500 }
501 b'm' => {
502 let _ = write!(buf, "{:02}", tm.tm_mon + 1);
503 }
504 b'd' => {
505 let _ = write!(buf, "{:02}", tm.tm_mday);
506 }
507 b'e' => {
508 let _ = write!(buf, "{:2}", tm.tm_mday);
509 }
510 b'H' => {
511 let _ = write!(buf, "{:02}", tm.tm_hour);
512 }
513 b'I' => {
514 let _ = write!(buf, "{:02}", hour12);
515 }
516 b'k' => {
517 let _ = write!(buf, "{:2}", tm.tm_hour);
518 }
519 b'l' => {
520 let _ = write!(buf, "{:2}", hour12);
521 }
522 b'M' => {
523 let _ = write!(buf, "{:02}", tm.tm_min);
524 }
525 b'S' => {
526 let _ = write!(buf, "{:02}", tm.tm_sec);
527 }
528 b'w' => {
529 let _ = write!(buf, "{}", tm.tm_wday);
530 }
531 b'u' => {
532 let u = if tm.tm_wday == 0 { 7 } else { tm.tm_wday };
533 let _ = write!(buf, "{}", u);
534 }
535 b'j' => {
536 let _ = write!(buf, "{:03}", tm.tm_yday + 1);
537 }
538 b'a' => buf.extend_from_slice(DAY_SHORT[wday_idx]),
539 b'A' => buf.extend_from_slice(DAY_LONG[wday_idx]),
540 b'b' | b'h' => buf.extend_from_slice(MON_SHORT[mon_idx]),
541 b'B' => buf.extend_from_slice(MON_LONG[mon_idx]),
542 b'p' => buf.extend_from_slice(if tm.tm_hour < 12 { b"AM" } else { b"PM" }),
543 b'P' => buf.extend_from_slice(if tm.tm_hour < 12 { b"am" } else { b"pm" }),
544 b'D' | b'x' => {
545 let _ = write!(
546 buf,
547 "{:02}/{:02}/{:02}",
548 tm.tm_mon + 1,
549 tm.tm_mday,
550 year_full.rem_euclid(100)
551 );
552 }
553 b'F' => {
554 let _ = write!(buf, "{}-{:02}-{:02}", year_full, tm.tm_mon + 1, tm.tm_mday);
555 }
556 b'T' | b'X' => {
557 let _ = write!(buf, "{:02}:{:02}:{:02}", tm.tm_hour, tm.tm_min, tm.tm_sec);
558 }
559 b'R' => {
560 let _ = write!(buf, "{:02}:{:02}", tm.tm_hour, tm.tm_min);
561 }
562 b'r' => {
563 let ampm: &[u8] = if tm.tm_hour < 12 { b"AM" } else { b"PM" };
564 let _ = write!(buf, "{:02}:{:02}:{:02} ", hour12, tm.tm_min, tm.tm_sec);
565 buf.extend_from_slice(ampm);
566 }
567 b'c' => {
568 let _ = write!(
569 buf,
570 "{} {} {:2} {:02}:{:02}:{:02} {}",
571 std::str::from_utf8(DAY_SHORT[wday_idx]).unwrap_or(""),
572 std::str::from_utf8(MON_SHORT[mon_idx]).unwrap_or(""),
573 tm.tm_mday,
574 tm.tm_hour,
575 tm.tm_min,
576 tm.tm_sec,
577 year_full,
578 );
579 }
580 b'n' => buf.push(b'\n'),
581 b't' => buf.push(b'\t'),
582 b'%' => buf.push(b'%'),
583 b'z' => buf.extend_from_slice(b"+0000"),
584 b'Z' => buf.extend_from_slice(b"UTC"),
585 b's' => {
586 let _ = write!(buf, "{}", compose_utc(tm));
587 }
588 b'U' => {
589 let week = (tm.tm_yday + 7 - tm.tm_wday) / 7;
590 let _ = write!(buf, "{:02}", week);
591 }
592 b'W' => {
593 let mwday = if tm.tm_wday == 0 { 6 } else { tm.tm_wday - 1 };
594 let week = (tm.tm_yday + 7 - mwday) / 7;
595 let _ = write!(buf, "{:02}", week);
596 }
597 b'V' | b'g' | b'G' => {
598 let _ = write!(buf, "{:02}", 1);
599 }
600 _ => {}
601 }
602}
603
604// ── Library functions ─────────────────────────────────────────────────────────
605
606///
607/// Executes a shell command via the system shell.
608///
609/// Without arguments: tests whether a shell is available — returns `true`
610/// when an `os_execute_hook` is installed (we always have `sh` in that case),
611/// `false` otherwise.
612///
613/// With a command string: dispatches through `os_execute_hook` and pushes the
614/// three C-Lua return values `(boolean|nil, "exit"|"signal", int)` as defined
615/// by `luaL_execresult`. Returns the stub `nil, errmsg, -1` triple when no
616/// hook is installed.
617pub(crate) fn os_execute(state: &mut LuaState) -> Result<usize, LuaError> {
618 let cmd = state.opt_arg_lstring(1, None)?;
619 match cmd {
620 None => {
621 // We have a shell if and only if the embedder installed a hook.
622 let has_shell = state.global().os_execute_hook.is_some();
623 state.push(LuaValue::Bool(has_shell));
624 Ok(1)
625 }
626 Some(cmd_bytes) => {
627 let hook = state.global().os_execute_hook;
628 match hook {
629 Some(execute_fn) => {
630 // Clone to avoid holding a borrow across the hook call.
631 let cmd_owned: Vec<u8> = cmd_bytes.to_vec();
632 match execute_fn(&cmd_owned) {
633 Ok(result) => {
634 if result.success {
635 state.push(LuaValue::Bool(true));
636 } else {
637 state.push(LuaValue::Nil);
638 }
639 let reason_str: &[u8] = match result.reason {
640 OsExecuteReason::Exit => b"exit",
641 OsExecuteReason::Signal => b"signal",
642 };
643 state.push_string(reason_str)?;
644 state.push(LuaValue::Int(result.code as i64));
645 Ok(3)
646 }
647 Err(e) => {
648 state.push(LuaValue::Nil);
649 let msg = match e.message_bytes() {
650 Some(b) => b.to_vec(),
651 None => format!("{:?}", &e).into_bytes(),
652 };
653 let s = state.intern_str(&msg)?;
654 state.push(LuaValue::Str(s));
655 state.push(LuaValue::Int(-1));
656 Ok(3)
657 }
658 }
659 }
660 None => {
661 state.push(LuaValue::Nil);
662 state.push_string(b"os.execute: not implemented in lua-stdlib")?;
663 state.push(LuaValue::Int(-1));
664 Ok(3)
665 }
666 }
667 }
668 }
669}
670
671///
672/// Removes the file or empty directory at the given path.
673/// Returns `true` on success, or `nil, errmsg` on failure.
674pub(crate) fn os_remove(state: &mut LuaState) -> Result<usize, LuaError> {
675 let filename: Vec<u8> = state.check_arg_string(1)?.to_vec();
676 // `std::fs` is banned in lua-stdlib; delegate to the embedder hook.
677 let hook = state.global().file_remove_hook;
678 match hook {
679 Some(remove_fn) => match remove_fn(&filename) {
680 Ok(()) => {
681 state.push(LuaValue::Bool(true));
682 Ok(1)
683 }
684 Err(e) => {
685 state.push(LuaValue::Nil);
686 let msg = match e.message_bytes() {
687 Some(b) => b.to_vec(),
688 None => format!("{:?}", &e).into_bytes(),
689 };
690 let s = state.intern_str(&msg)?;
691 state.push(LuaValue::Str(s));
692 Ok(2)
693 }
694 },
695 None => {
696 state.push(LuaValue::Nil);
697 state.push_string(b"os.remove: no filesystem hook registered")?;
698 Ok(2)
699 }
700 }
701}
702
703///
704/// Renames (moves) a file from the first path to the second.
705/// Returns `true` on success, or `nil, errmsg` on failure.
706pub(crate) fn os_rename(state: &mut LuaState) -> Result<usize, LuaError> {
707 let fromname: Vec<u8> = state.check_arg_string(1)?.to_vec();
708 let toname: Vec<u8> = state.check_arg_string(2)?.to_vec();
709 // `std::fs` is banned in lua-stdlib; delegate to the embedder hook.
710 let hook = state.global().file_rename_hook;
711 match hook {
712 Some(rename_fn) => match rename_fn(&fromname, &toname) {
713 Ok(()) => {
714 state.push(LuaValue::Bool(true));
715 return Ok(1);
716 }
717 Err(e) => {
718 state.push(LuaValue::Nil);
719 let msg = match e.message_bytes() {
720 Some(b) => b.to_vec(),
721 None => format!("{:?}", &e).into_bytes(),
722 };
723 let s = state.intern_str(&msg)?;
724 state.push(LuaValue::Str(s));
725 return Ok(2);
726 }
727 },
728 None => {}
729 }
730 state.push(LuaValue::Nil);
731 state.push_string(b"os.rename: no filesystem hook registered")?;
732 Ok(2)
733}
734
735///
736/// Generates a unique temporary file name and pushes it as a string.
737/// Raises a runtime error if generation fails.
738///
739/// Temporary names are a host capability. Native hosts can install
740/// `GlobalState::temp_name_hook`; bare WASM without that hook raises a Lua
741/// error instead of touching `std::env` / `std::time` stubs.
742pub(crate) fn os_tmpname(state: &mut LuaState) -> Result<usize, LuaError> {
743 let dir = host_temp_name(state)?;
744 state.push_string(&dir)?;
745 Ok(1)
746}
747
748///
749/// Reads the environment variable named by the first argument and pushes its
750/// value as a string, or `nil` if the variable is not set.
751pub(crate) fn os_getenv(state: &mut LuaState) -> Result<usize, LuaError> {
752 let name_bytes: Vec<u8> = state.check_arg_string(1)?.to_vec();
753
754 let result: Option<Vec<u8>> = match state.global().env_hook {
755 Some(env_fn) => env_fn(&name_bytes),
756 None => {
757 #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
758 {
759 None
760 }
761
762 #[cfg(all(unix, not(all(target_arch = "wasm32", target_os = "unknown"))))]
763 {
764 use std::ffi::OsStr;
765 use std::os::unix::ffi::{OsStrExt, OsStringExt};
766 let os_name = OsStr::from_bytes(&name_bytes);
767 std::env::var_os(os_name).map(|v| v.into_vec())
768 }
769
770 #[cfg(all(not(unix), not(all(target_arch = "wasm32", target_os = "unknown"))))]
771 {
772 // Non-Unix platforms: requires valid UTF-8 for OS API interop
773 // (a wide-string conversion would be more permissive).
774 match std::str::from_utf8(&name_bytes) {
775 Ok(name_str) => std::env::var(name_str).ok().map(|v| v.into_bytes()),
776 Err(_) => None,
777 }
778 }
779 }
780 };
781
782 match result {
783 Some(val) => {
784 state.push_string(&val)?;
785 }
786 None => {
787 state.push(LuaValue::Nil);
788 }
789 }
790 Ok(1)
791}
792
793///
794/// Returns an approximation of the CPU time (in seconds) used by the program.
795pub(crate) fn os_clock(state: &mut LuaState) -> Result<usize, LuaError> {
796 let seconds = cpu_seconds(state)?;
797 state.push(LuaValue::Float(seconds));
798 Ok(1)
799}
800
801/// Returns program CPU time in seconds, as consumed by `os.clock`.
802///
803/// C's `clock()` reads `CLOCK_PROCESS_CPUTIME_ID`, which has no portable `std`
804/// equivalent. We route through `cpu_clock_hook` when the host installs one;
805/// otherwise native builds report monotonic wall time elapsed since the first
806/// call (the substitution wasi-libc and Emscripten make for `clock()`), and bare
807/// WASM reports the clock as unavailable rather than touching a stubbed source.
808fn cpu_seconds(state: &LuaState) -> Result<f64, LuaError> {
809 if let Some(clock_fn) = state.global().cpu_clock_hook {
810 return Ok(clock_fn());
811 }
812
813 #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
814 {
815 let _ = state;
816 Err(LuaError::runtime(format_args!(
817 "CPU clock not available in this host"
818 )))
819 }
820
821 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
822 {
823 let _ = state;
824 use std::sync::OnceLock;
825 use std::time::Instant;
826 static START: OnceLock<Instant> = OnceLock::new();
827 Ok(START.get_or_init(Instant::now).elapsed().as_secs_f64())
828 }
829}
830
831/// Formats the current (or a specified) date/time.
832///
833/// * Format starting with `'!'` → use UTC; otherwise local time.
834/// * Format `"*t"` → push a table with broken-down time fields.
835/// * Other format → push a formatted string, expanding `%`-specifiers via
836/// [`strftime_one`]. Specifier validation is version-gated (5.1 does not
837/// validate; 5.2+ raise "invalid conversion specifier").
838pub(crate) fn os_date(state: &mut LuaState) -> Result<usize, LuaError> {
839 let format: Vec<u8> = state.opt_arg_lstring(1, Some(b"%c"))?.unwrap_or_default();
840 let s: &[u8] = &format[..];
841
842 let t: i64 = if matches!(state.type_at(2), LuaType::None | LuaType::Nil) {
843 unix_now(state)?
844 } else {
845 check_time(state, 2)?
846 };
847
848 let (use_utc, s): (bool, &[u8]) = if s.first() == Some(&b'!') {
849 (true, &s[1..])
850 } else {
851 (false, s)
852 };
853
854 // Local time is reproduced by decomposing `t + offset`, where `offset` is the
855 // host timezone offset at `t` from `local_offset_hook` (the host that needs
856 // local time installs one; reading the zone database itself needs libc FFI,
857 // banned here). Without a hook the offset is 0 and local time degrades to UTC,
858 // keeping the `os.date`/`os.time` round-trip exact (pinned by
859 // `os_strengthen.rs::time_local_round_trip_is_host_independent`). A `'!'`
860 // prefix requests UTC explicitly and skips the offset.
861 let offset = if use_utc { 0 } else { local_offset(state, t) };
862 let stm = decompose_utc(t + offset);
863
864 if s == b"*t" {
865 state.create_table(0, 9)?;
866 set_all_fields(state, &stm)?;
867 } else {
868 // 5.1's `os_date` has no `checkoption`: a `%X` directive is built into a
869 // 3-byte `cc` and handed straight to `strftime` (unknown directives are
870 // implementation-defined, never a Lua error), and a trailing bare `%` is
871 // emitted literally. 5.2+ validate the directive against a fixed option
872 // set and raise "invalid conversion specifier". Pinned by
873 // `os_strengthen.rs::date_invalid_specifier_is_unvalidated_on_5_1_crossversion`.
874 let validate = !matches!(state.global().lua_version, lua_types::LuaVersion::V51);
875 let mut result: Vec<u8> = Vec::new();
876 let mut pos: usize = 0;
877
878 while pos < s.len() {
879 if s[pos] != b'%' {
880 result.push(s[pos]);
881 pos += 1;
882 } else if !validate {
883 if pos + 1 >= s.len() {
884 result.push(b'%');
885 pos += 1;
886 } else {
887 let mut cc = [0u8; 4];
888 cc[0] = b'%';
889 cc[1] = s[pos + 1];
890 strftime_one(&mut result, &cc, 1, &stm);
891 pos += 2;
892 }
893 } else {
894 pos += 1;
895 let mut cc = [0u8; 4];
896 cc[0] = b'%';
897 // Pass the remaining slice even if empty: checkoption's loop
898 // condition (oplen <= convlen) fails immediately on an empty
899 // slice, which causes it to raise "invalid conversion specifier"
900 // matching C behaviour for a trailing bare '%'.
901 let conv = &s[pos..];
902 let after = check_strftime_option(state, conv, &mut cc)?;
903 let oplen = conv.len() - after.len();
904 pos += oplen;
905 strftime_one(&mut result, &cc, oplen, &stm);
906 let _ = SIZE_TIME_FMT;
907 }
908 }
909 state.push_string(&result)?;
910 }
911 Ok(1)
912}
913
914///
915/// Without arguments: returns the current time as a Unix timestamp (integer).
916/// With a table argument: interprets the table as broken-down local time,
917/// normalises the fields via `mktime`, updates the table in place, and returns
918/// the resulting timestamp.
919pub(crate) fn os_time(state: &mut LuaState) -> Result<usize, LuaError> {
920 let t: i64;
921
922 if matches!(state.type_at(1), LuaType::None | LuaType::Nil) {
923 t = unix_now(state)?;
924 } else {
925 state.check_arg_type(1, LuaType::Table)?;
926 // Must use the public-API `set_top` (relative to the current
927 // C-frame's `func`), not `LuaState::set_top` which is an inherent that
928 // sets an absolute stack index and would truncate the entire stack.
929 lua_vm::api::set_top(state, 1)?;
930
931 // The field-read ORDER is version-gated, faithful to `loslib.c`'s
932 // `os_time` evolution and pinned by
933 // `os_strengthen.rs::time_missing_field_names_first_unread_required_field_crossversion`.
934 // Field *values* are order-independent; the order matters only because a
935 // "field '…' missing in date table" error short-circuits on the FIRST
936 // absent required field. 5.1/5.2/5.3 read sec→min→hour→day→month→year,
937 // so an empty table reports `day` first; 5.4/5.5 read
938 // year→month→day→hour→min→sec, reporting `year` first.
939 let (tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec) = if matches!(
940 state.global().lua_version,
941 lua_types::LuaVersion::V51 | lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53
942 ) {
943 let tm_sec = get_field(state, b"sec", 0, 0)?;
944 let tm_min = get_field(state, b"min", 0, 0)?;
945 let tm_hour = get_field(state, b"hour", 12, 0)?;
946 let tm_mday = get_field(state, b"day", -1, 0)?;
947 let tm_mon = get_field(state, b"month", -1, 1)?;
948 let tm_year = get_field(state, b"year", -1, 1900)?;
949 (tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec)
950 } else {
951 let tm_year = get_field(state, b"year", -1, 1900)?;
952 let tm_mon = get_field(state, b"month", -1, 1)?;
953 let tm_mday = get_field(state, b"day", -1, 0)?;
954 let tm_hour = get_field(state, b"hour", 12, 0)?;
955 let tm_min = get_field(state, b"min", 0, 0)?;
956 let tm_sec = get_field(state, b"sec", 0, 0)?;
957 (tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec)
958 };
959 let tm_isdst = get_bool_field(state, b"isdst")?;
960
961 let raw = TmFields {
962 tm_year,
963 tm_mon,
964 tm_mday,
965 tm_hour,
966 tm_min,
967 tm_sec,
968 tm_isdst,
969 ..TmFields::default()
970 };
971
972 // C `mktime` interprets the broken-down time as LOCAL and
973 // returns the corresponding UTC timestamp. We reproduce it: treat the
974 // fields as UTC to get a provisional `t_utc` (this also normalises the
975 // month axis), then subtract the host timezone offset to recover the true
976 // UTC instant. The offset is sampled at `t_utc` then re-sampled at the
977 // corrected instant — the standard `mktime` fixed-point step — so the
978 // result is correct except across a DST transition inside the offset
979 // window, which `os.time`'s test inputs do not exercise. Without a hook
980 // the offset is 0 and this is the exact inverse of `os.date`'s local
981 // decomposition, so the `os.time(os.date("*t")) == t` round-trip holds.
982 let t_utc = compose_utc(&raw);
983 let off0 = local_offset(state, t_utc);
984 let off = local_offset(state, t_utc - off0);
985 t = t_utc - off;
986 let stm = decompose_utc(t + off);
987
988 set_all_fields(state, &stm)?;
989 }
990
991 // On 64-bit targets time_t == i64 == lua_Integer so the cast check
992 // is a no-op. We only guard against mktime's failure sentinel (−1).
993 if t == -1 {
994 return Err(LuaError::runtime(format_args!(
995 "time result cannot be represented in this installation"
996 )));
997 }
998
999 state.push(LuaValue::Int(t));
1000 Ok(1)
1001}
1002
1003///
1004/// Returns the number of seconds between two time values as a float (`t1 − t2`).
1005///
1006/// Returns `t1 − t2` as a `double`, matching C's `difftime`. For 64-bit
1007/// `time_t` this is exact as `f64` up to approximately 2^53 seconds
1008/// (~285 million years), which is sufficient for all practical timestamps.
1009pub(crate) fn os_difftime(state: &mut LuaState) -> Result<usize, LuaError> {
1010 let t1 = check_time(state, 1)?;
1011 let t2 = check_time(state, 2)?;
1012 state.push(LuaValue::Float((t1 - t2) as f64));
1013 Ok(1)
1014}
1015
1016///
1017/// Sets the locale for the given category and pushes the resulting locale name
1018/// as a string, or `nil` on failure.
1019pub(crate) fn os_setlocale(state: &mut LuaState) -> Result<usize, LuaError> {
1020 const CAT_NAMES: &[&[u8]] = &[
1021 b"all",
1022 b"collate",
1023 b"ctype",
1024 b"monetary",
1025 b"numeric",
1026 b"time",
1027 ];
1028
1029 let locale: Option<Vec<u8>> = state.opt_arg_lstring(1, None)?;
1030
1031 let _op: usize = state.check_arg_option(2, Some(b"all"), CAT_NAMES)?;
1032
1033 // Calling libc::setlocale requires unsafe (banned in lua-stdlib, budget=0).
1034 // Rust programs inherit the "C" locale by default and never change it, so returning
1035 // "C" for the C locale (and nil for anything else) is faithful for this build:
1036 // "C" is the only locale guaranteed available on every POSIX system.
1037 let result_locale: Option<&[u8]> = match locale.as_deref() {
1038 None => Some(b"C"), // query: return current locale (always "C" here)
1039 Some(b"C") | Some(b"POSIX") => Some(b"C"), // setting to "C"/"POSIX" always succeeds
1040 Some(_) => None, // any other locale: unsupported in this build
1041 };
1042 match result_locale {
1043 Some(s) => {
1044 state.push_string(s)?;
1045 }
1046 None => state.push(LuaValue::Nil),
1047 }
1048 Ok(1)
1049}
1050
1051///
1052/// Exits the host process with the given status code (default `EXIT_SUCCESS = 0`).
1053/// If the second argument is true, also closes the Lua state before exiting.
1054///
1055/// This function is expected to terminate the process and never return normally.
1056pub(crate) fn os_exit(state: &mut LuaState) -> Result<usize, LuaError> {
1057 // status = lua_toboolean(L, 1) ? EXIT_SUCCESS : EXIT_FAILURE;
1058 // else
1059 // status = (int)luaL_optinteger(L, 1, EXIT_SUCCESS);
1060 let exit_code: i32 = if matches!(state.type_at(1), LuaType::Boolean) {
1061 if state.to_boolean(1) {
1062 0
1063 } else {
1064 1
1065 } // EXIT_SUCCESS = 0, EXIT_FAILURE = 1
1066 } else {
1067 state.opt_arg_integer(1, 0)? as i32
1068 };
1069
1070 if state.to_boolean(2) {
1071 state.close();
1072 }
1073
1074 //
1075 // `std::process::exit` remains restricted to `lua-cli`. A regular
1076 // `LuaError` is also wrong here: Lua `pcall` must not catch `os.exit`.
1077 // Use a typed panic payload as internal non-local control flow; the CLI
1078 // catches it at the process boundary and converts it to an `ExitCode`.
1079 std::panic::panic_any(LuaExit(exit_code));
1080}
1081
1082// ── Registration table and entry point ───────────────────────────────────────
1083
1084/// Signature of a Lua native function (the `os.*` registration entries).
1085pub type NativeFn = fn(&mut LuaState) -> Result<usize, LuaError>;
1086
1087/// Mapping from Lua-visible names to the Rust implementations of each `os.*`
1088/// function.
1089pub const OS_LIB: &[(&[u8], NativeFn)] = &[
1090 (b"clock", os_clock),
1091 (b"date", os_date),
1092 (b"difftime", os_difftime),
1093 (b"execute", os_execute),
1094 (b"exit", os_exit),
1095 (b"getenv", os_getenv),
1096 (b"remove", os_remove),
1097 (b"rename", os_rename),
1098 (b"setlocale", os_setlocale),
1099 (b"time", os_time),
1100 (b"tmpname", os_tmpname),
1101];
1102
1103/// Opens the `os` library: creates a new table populated with `OS_LIB` and
1104/// leaves it on the stack.
1105pub fn open_os(state: &mut LuaState) -> Result<usize, LuaError> {
1106 state.register_lib(b"os", OS_LIB)?;
1107 Ok(1)
1108}