From c14b2cee4cebb6c6cac1ea2438042ec2748eb96f Mon Sep 17 00:00:00 2001 From: Darley Barreto Date: Thu, 2 Jan 2025 20:19:34 +0000 Subject: [PATCH] Adding `tzset`, timezone awareness, and some tweaks --- Cargo.lock | 123 ++++++ Cargo.toml | 2 + src/header/time/mod.rs | 410 +++++++++++------- tests/Makefile | 1 + .../bins_dynamic/time/localtime_r.stderr | 0 .../bins_dynamic/time/localtime_r.stdout | 0 .../bins_static/time/localtime_r.stderr | 0 .../bins_static/time/localtime_r.stdout | 0 tests/time/localtime_r.c | 112 +++++ 9 files changed, 493 insertions(+), 155 deletions(-) create mode 100644 tests/expected/bins_dynamic/time/localtime_r.stderr create mode 100644 tests/expected/bins_dynamic/time/localtime_r.stdout create mode 100644 tests/expected/bins_static/time/localtime_r.stderr create mode 100644 tests/expected/bins_static/time/localtime_r.stdout create mode 100644 tests/time/localtime_r.c diff --git a/Cargo.lock b/Cargo.lock index a33799b9f1..3b8efb3e5d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,15 @@ # It is not intended for manual editing. version = 3 +[[package]] +name = "aho-corasick" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" +dependencies = [ + "memchr", +] + [[package]] name = "autocfg" version = "1.4.0" @@ -79,6 +88,36 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +[[package]] +name = "chrono" +version = "0.4.39" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e36cc9d416881d2e24f9a963be5fb1cd90966419ac844274161d10488b3e825" +dependencies = [ + "num-traits", +] + +[[package]] +name = "chrono-tz" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd6dd8046d00723a59a2f8c5f295c515b9bb9a331ee4f8f3d4dd49e428acd3b6" +dependencies = [ + "chrono", + "chrono-tz-build", + "phf", +] + +[[package]] +name = "chrono-tz-build" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e94fea34d77a245229e7746bd2beb786cd2a896f306ff491fb8cecb3074b10a7" +dependencies = [ + "parse-zoneinfo", + "phf_codegen", +] + [[package]] name = "cipher" version = "0.4.4" @@ -235,6 +274,15 @@ dependencies = [ "autocfg", ] +[[package]] +name = "parse-zoneinfo" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f2a05b18d44e2957b88f96ba460715e295bc1d7510468a2f3d3b44535d26c24" +dependencies = [ + "regex", +] + [[package]] name = "password-hash" version = "0.5.0" @@ -257,6 +305,44 @@ dependencies = [ "sha2", ] +[[package]] +name = "phf" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ade2d8b8f33c7333b51bcf0428d37e217e9f32192ae4772156f65063b8ce03dc" +dependencies = [ + "phf_shared", +] + +[[package]] +name = "phf_codegen" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8d39688d359e6b34654d328e262234662d16cc0f60ec8dcbe5e718709342a5a" +dependencies = [ + "phf_generator", + "phf_shared", +] + +[[package]] +name = "phf_generator" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e4cc64c2ad9ebe670cb8fd69dd50ae301650392e81c05f9bfcb2d5bdbc24b0" +dependencies = [ + "phf_shared", + "rand", +] + +[[package]] +name = "phf_shared" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90fcb95eef784c2ac79119d1dd819e162b5da872ce6f3c3abe1e8ca1c082f72b" +dependencies = [ + "siphasher", +] + [[package]] name = "plain" version = "0.2.3" @@ -356,6 +442,35 @@ dependencies = [ "bitflags", ] +[[package]] +name = "regex" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" + [[package]] name = "relibc" version = "0.2.5" @@ -365,6 +480,8 @@ dependencies = [ "bitflags", "cbitset", "cc", + "chrono", + "chrono-tz", "dlmalloc", "generic-rt", "goblin", @@ -463,6 +580,12 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" +[[package]] +name = "siphasher" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d" + [[package]] name = "subtle" version = "2.6.1" diff --git a/Cargo.toml b/Cargo.toml index a6adf74745..5dc3ad7469 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,6 +46,8 @@ scrypt = { version = "0.11", default-features = false, features = ["simple"] } pbkdf2 = { version = "0.12", features = ["sha2"] } sha2 = { version = "0.10", default-features = false } generic-rt = { path = "generic-rt" } +chrono-tz = {version = "0.10", default-features = false} +chrono = {version = "0.4", default-features = false, features = ["alloc"]} libm = "0.2" [dependencies.goblin] diff --git a/src/header/time/mod.rs b/src/header/time/mod.rs index 3942ecb206..0abe45a680 100644 --- a/src/header/time/mod.rs +++ b/src/header/time/mod.rs @@ -1,11 +1,22 @@ //! time implementation for Redox, following http://pubs.opengroup.org/onlinepubs/7908799/xsh/time.h.html -use core::convert::{TryFrom, TryInto}; - use crate::{ + c_str::{CStr, CString}, error::ResultExt, - header::errno::EOVERFLOW, + header::{errno::EOVERFLOW, stdlib::getenv, unistd::readlink}, platform::{self, types::*, Pal, Sys}, + sync::{Mutex, MutexGuard}, +}; +use alloc::collections::BTreeSet; +use chrono::{ + offset::MappedLocalTime, DateTime, Datelike, FixedOffset, NaiveDate, NaiveDateTime, Offset, + TimeZone, Timelike, +}; +use chrono_tz::{OffsetComponents, OffsetName, Tz}; +use core::{ + cell::OnceCell, + convert::{TryFrom, TryInto}, + mem, ptr, }; pub use self::constants::*; @@ -34,7 +45,7 @@ impl timespec { Some(if later_nsec > earlier_nsec { timespec { tv_sec: later.tv_sec.checked_sub(earlier.tv_sec)?, - tv_nsec: (later_nsec - earlier_nsec) as c_long, + tv_nsec: (later_nsec - earlier_nsec) as _, } } else { timespec { @@ -49,84 +60,49 @@ impl timespec { impl<'a> From<&'a timespec> for syscall::TimeSpec { fn from(tp: ×pec) -> Self { Self { - tv_sec: tp.tv_sec as i64, - tv_nsec: tp.tv_nsec as i32, + tv_sec: tp.tv_sec as _, + tv_nsec: tp.tv_nsec as _, } } } #[repr(C)] pub struct tm { - pub tm_sec: c_int, - pub tm_min: c_int, - pub tm_hour: c_int, - pub tm_mday: c_int, - pub tm_mon: c_int, - pub tm_year: c_int, - pub tm_wday: c_int, - pub tm_yday: c_int, - pub tm_isdst: c_int, - pub tm_gmtoff: c_long, - pub tm_zone: *const c_char, + pub tm_sec: c_int, // 0 - 60 + pub tm_min: c_int, // 0 - 59 + pub tm_hour: c_int, // 0 - 23 + pub tm_mday: c_int, // 1 - 31 + pub tm_mon: c_int, // 0 - 11 + pub tm_year: c_int, // years since 1900 + pub tm_wday: c_int, // 0 - 6 (Sunday - Saturday) + pub tm_yday: c_int, // 0 - 365 + pub tm_isdst: c_int, // >0 if DST, 0 if not, <0 if unknown + pub tm_gmtoff: c_long, // offset from UTC in seconds + pub tm_zone: *const c_char, // timezone abbreviation } unsafe impl Sync for tm {} // The C Standard says that localtime and gmtime return the same pointer. -static mut TM: tm = tm { - tm_sec: 0, - tm_min: 0, - tm_hour: 0, - tm_mday: 0, - tm_mon: 0, - tm_year: 0, - tm_wday: 0, - tm_yday: 0, - tm_isdst: 0, - tm_gmtoff: 0, - tm_zone: UTC, -}; +static mut TM: tm = blank_tm(); // The C Standard says that ctime and asctime return the same pointer. static mut ASCTIME: [c_char; 26] = [0; 26]; -// We don't handle timezones, so just initialize the timezone info to GMT -// TODO: timezones #[repr(transparent)] -pub struct TzName { - tz: [*mut c_char; 2], -} +pub struct TzName([*mut c_char; 2]); unsafe impl Sync for TzName {} -static mut TZ_STD: [c_char; 8] = [ - b'U' as c_char, - b'T' as c_char, - b'C' as c_char, - 0, - 0, - 0, - 0, - 0, -]; -static mut TZ_DST: [c_char; 8] = [ - b'U' as c_char, - b'T' as c_char, - b'C' as c_char, - 0, - 0, - 0, - 0, - 0, -]; +// Name storage for the `tm_zone` field. +static TIMEZONE_NAMES: Mutex>> = Mutex::new(OnceCell::new()); + +// Hold `TIMEZONE_LOCK` when updating `tzname`, `timezone`, and `daylight`. +static TIMEZONE_LOCK: Mutex<(Option, Option)> = Mutex::new((None, None)); #[allow(non_upper_case_globals)] #[no_mangle] -pub static mut tzname: TzName = TzName { - tz: [unsafe { TZ_DST.as_mut_ptr() }, unsafe { - TZ_DST.as_mut_ptr() - }], -}; +pub static mut tzname: TzName = TzName([ptr::null_mut(); 2]); #[allow(non_upper_case_globals)] #[no_mangle] @@ -220,14 +196,14 @@ pub unsafe extern "C" fn asctime_r(tm: *const tm, buf: *mut c_char) -> *mut c_ch Err(_) => { /* asctime()/asctime_r() or the equivalent sprintf() call * have no defined errno setting */ - core::ptr::null_mut() + ptr::null_mut() } } } #[no_mangle] pub extern "C" fn clock() -> clock_t { - let mut ts = core::mem::MaybeUninit::::uninit(); + let mut ts = mem::MaybeUninit::::uninit(); if unsafe { clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ts.as_mut_ptr()) } != 0 { return -1; @@ -271,26 +247,14 @@ pub unsafe extern "C" fn ctime(clock: *const time_t) -> *mut c_char { #[no_mangle] pub unsafe extern "C" fn ctime_r(clock: *const time_t, buf: *mut c_char) -> *mut c_char { // Using MaybeUninit seems to cause a panic during the build process - let mut tm1 = tm { - tm_sec: 0, - tm_min: 0, - tm_hour: 0, - tm_mday: 0, - tm_mon: 0, - tm_year: 0, - tm_wday: 0, - tm_yday: 0, - tm_isdst: 0, - tm_gmtoff: 0, - tm_zone: core::ptr::null_mut(), - }; + let mut tm1 = blank_tm(); localtime_r(clock, &mut tm1); asctime_r(&tm1, buf) } #[no_mangle] pub extern "C" fn difftime(time1: time_t, time0: time_t) -> c_double { - (time1 - time0) as c_double + (time1 - time0) as _ } // #[no_mangle] @@ -303,18 +267,6 @@ pub unsafe extern "C" fn gmtime(timer: *const time_t) -> *mut tm { gmtime_r(timer, &mut TM) } -const MONTH_DAYS: [[c_int; 12]; 2] = [ - // Non-leap years: - [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], - // Leap years: - [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], -]; - -#[inline(always)] -fn leap_year(year: c_int) -> bool { - year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) -} - #[no_mangle] pub unsafe extern "C" fn gmtime_r(clock: *const time_t, result: *mut tm) -> *mut tm { /* For the details of the algorithm used here, see @@ -405,7 +357,7 @@ pub unsafe extern "C" fn gmtime_r(clock: *const time_t, result: *mut tm) -> *mut } Err(_) => { platform::ERRNO.set(EOVERFLOW); - core::ptr::null_mut() + ptr::null_mut() } } } @@ -417,74 +369,76 @@ pub unsafe extern "C" fn localtime(clock: *const time_t) -> *mut tm { #[no_mangle] pub unsafe extern "C" fn localtime_r(clock: *const time_t, t: *mut tm) -> *mut tm { - // TODO: Change tm_isdst, tm_gmtoff, tm_zone - gmtime_r(clock, t) + let mut lock = TIMEZONE_LOCK.lock(); + clear_timezone(&mut lock); + + let utc_time = *clock; + let tz = time_zone(); + + // Convert UTC time to local time + let (std_time, dst_time) = match tz.timestamp_opt(utc_time, 0) { + MappedLocalTime::Single(t) => (t, None), + // This variant contains the two possible results, in the order (earliest, latest). + MappedLocalTime::Ambiguous(t1, t2) => (t2, Some(t1)), + MappedLocalTime::None => return t, + }; + + ptr::write(t, datetime_to_tm(&std_time)); + set_timezone(&mut lock, &std_time, dst_time); + t } #[no_mangle] pub unsafe extern "C" fn mktime(timeptr: *mut tm) -> time_t { - /* For the details of the algorithm used here, see - * https://howardhinnant.github.io/date_algorithms.html#days_from_civil - */ + let mut lock = TIMEZONE_LOCK.lock(); + clear_timezone(&mut lock); - fn inner(timeptr_mut: &mut tm) -> Option { - let year = time_t::try_from(timeptr_mut.tm_year) - .ok() - .and_then(|tm_year| tm_year.checked_add(1900))?; - let month = time_t::try_from(timeptr_mut.tm_mon).ok()?; - let mday = time_t::try_from(timeptr_mut.tm_mday).ok()?; + let year = (*timeptr).tm_year + 1900; + let month = ((*timeptr).tm_mon + 1) as _; + let day = (*timeptr).tm_mday as _; + let hour = (*timeptr).tm_hour as _; + let minute = (*timeptr).tm_min as _; + let second = (*timeptr).tm_sec as _; - let hour = time_t::try_from(timeptr_mut.tm_hour).ok()?; - let min = time_t::try_from(timeptr_mut.tm_min).ok()?; - let sec = time_t::try_from(timeptr_mut.tm_sec).ok()?; - - // TODO: handle tm_isdst - - let year_transformed = if month < 2 { year - 1 } else { year }; - - let era = year_transformed.div_euclid(YEARS_PER_ERA); - let year_of_era = year_transformed.rem_euclid(YEARS_PER_ERA); - - let day_of_year = - (153 * (if month > 1 { month - 2 } else { month + 10 }) + 2) / 5 + mday - 1; // adapted for zero-based months - - let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year; - let unix_days = era * DAYS_PER_ERA + day_of_era - 719468; - let secs_of_day = hour * (60 * 60) + min * 60 + sec; - - let unix_secs = unix_days - .checked_mul(SECS_PER_DAY) - .and_then(|day_secs| day_secs.checked_add(secs_of_day))?; - - // Normalize input struct with values from their standard ranges - let mut normalized_tm = tm { - tm_sec: 0, - tm_min: 0, - tm_hour: 0, - tm_mday: 0, - tm_mon: 0, - tm_year: 0, - tm_wday: 0, - tm_yday: 0, - tm_isdst: 0, - tm_gmtoff: 0, - tm_zone: UTC, - }; - if unsafe { gmtime_r(&unix_secs, &mut normalized_tm).is_null() } { - None - } else { - *timeptr_mut = normalized_tm; - Some(unix_secs) - } - } - - match inner(&mut *timeptr) { - Some(unix_secs) => unix_secs, + let naive_local = match NaiveDate::from_ymd_opt(year, month, day) + .and_then(|date| date.and_hms_opt(hour, minute, second)) + { + Some(datetime) => datetime, None => { platform::ERRNO.set(EOVERFLOW); - -1 as time_t + return -1; } + }; + + let offset = FixedOffset::east((*timeptr).tm_gmtoff as _); + let tz = time_zone(); + + // Create DateTime + let datetime = match offset.from_local_datetime(&naive_local) { + MappedLocalTime::Single(datetime) => datetime, + _ => { + platform::ERRNO.set(EOVERFLOW); + return -1; + } + }; + + // Convert to UTC and get timestamp + let tz_datetime = datetime.with_timezone(&tz); + let timestamp = tz_datetime.timestamp(); + + ptr::write(timeptr, datetime_to_tm(&tz_datetime)); + + // Convert UTC time to local time + if let (Some(std_time), dst_time) = match tz.timestamp_opt(timestamp, 0) { + MappedLocalTime::Single(t) => (Some(t), None), + // This variant contains the two possible results, in the order (earliest, latest). + MappedLocalTime::Ambiguous(t1, t2) => (Some(t2), Some(t1)), + MappedLocalTime::None => (None, None), + } { + set_timezone(&mut lock, &std_time, dst_time); } + + timestamp } #[no_mangle] @@ -552,9 +506,20 @@ pub extern "C" fn timer_delete(timerid: timer_t) -> c_int { } #[no_mangle] -pub extern "C" fn tzset() { - // no-op because we only do UTC - // TODO: timezones, parse env var TZ +pub unsafe extern "C" fn tzset() { + let mut lock = TIMEZONE_LOCK.lock(); + unsafe { clear_timezone(&mut lock) }; + + let tz = time_zone(); + let datetime = now(); + let (std_time, dst_time) = match tz.from_local_datetime(&datetime) { + MappedLocalTime::Single(t) => (t, None), + // This variant contains the two possible results, in the order (earliest, latest). + MappedLocalTime::Ambiguous(t1, t2) => (t2, Some(t1)), + MappedLocalTime::None => return, + }; + + set_timezone(&mut lock, &std_time, dst_time) } // #[no_mangle] @@ -577,9 +542,144 @@ pub extern "C" fn timer_getoverrun(timerid: timer_t) -> c_int { unimplemented!(); } -/* -#[no_mangle] -pub extern "C" fn func(args) -> c_int { - unimplemented!(); +fn clear_timezone(guard: &mut MutexGuard<'_, (Option, Option)>) { + guard.0 = None; + guard.1 = None; + unsafe { + tzname.0[0] = ptr::null_mut(); + tzname.0[1] = ptr::null_mut(); + timezone = 0; + daylight = 0; + } +} + +fn get_system_time_zone<'a>() -> Option<&'a str> { + // Resolve the symlink for localtime + const BSIZE: size_t = 100; + let mut buffer: [u8; BSIZE] = [0; BSIZE]; + + #[cfg(not(target_os = "redox"))] + let (localtime, prefix) = (c"/etc/localtime", "/usr/share/zoneinfo/"); + + #[cfg(target_os = "redox")] + let (localtime, prefix) = (c"/etc/localtime", "/usr/share/zoneinfo/"); + + if unsafe { readlink(localtime.as_ptr().cast(), buffer.as_mut_ptr().cast(), BSIZE) } == -1 { + return None; + } + + let path = unsafe { CStr::from_ptr(buffer.as_mut_ptr().cast()) }; + + if let Ok(tz_name) = path.to_str() { + if let Some(stripped) = tz_name.strip_prefix(prefix) { + return Some(stripped); + } + } + + None +} + +fn get_current_time_zone<'a>() -> &'a str { + // Check the `TZ` environment variable + let tz_env = unsafe { getenv(b"TZ\0".as_ptr() as _) }; + if !tz_env.is_null() { + if let Ok(tz) = unsafe { CStr::from_ptr(tz_env) }.to_str() { + return tz; + } + } + + // Fallback to the system's default time zone + if let Some(tz) = get_system_time_zone() { + return tz; + } + + // If all else fails, use UTC + "UTC" +} + +#[inline(always)] +fn time_zone() -> Tz { + get_current_time_zone().parse().unwrap_or(Tz::UTC) +} + +#[inline(always)] +fn now() -> NaiveDateTime { + let mut now = timespec::default(); + unsafe { + Sys::clock_gettime(CLOCK_REALTIME, &mut now); + } + NaiveDateTime::from_timestamp(now.tv_sec, now.tv_nsec as _) +} + +unsafe fn datetime_to_tm(local_time: &DateTime) -> tm { + let tz = local_time.timezone().name(); + let mut t = blank_tm(); + // Populate the `tm` structure + t.tm_sec = local_time.second() as _; + t.tm_min = local_time.minute() as _; + t.tm_hour = local_time.hour() as _; + t.tm_mday = local_time.day() as _; + t.tm_mon = local_time.month0() as _; // 0-based month + t.tm_year = (local_time.year() - 1900) as _; // Years since 1900 + t.tm_wday = local_time.weekday().num_days_from_sunday() as _; + t.tm_yday = local_time.ordinal0() as _; // 0-based day of year + + let offset = local_time.offset(); + t.tm_isdst = offset.dst_offset().num_hours() as _; + // Get the UTC offset in seconds + t.tm_gmtoff = offset.fix().local_minus_utc() as _; + + let tm_zone = { + let mut timezone_names = TIMEZONE_NAMES.lock(); + timezone_names.get_or_init(BTreeSet::new); + let cstr = CString::new(tz).unwrap(); + timezone_names.get_mut().unwrap().insert(cstr.clone()); + timezone_names.get().unwrap().get(&cstr).unwrap().as_ptr() + }; + + t.tm_zone = tm_zone.cast(); + t +} + +unsafe fn set_timezone( + guard: &mut MutexGuard<'_, (Option, Option)>, + std: &DateTime, + dst: Option>, +) { + let ut_offset = std.offset(); + + guard.0 = Some(CString::new(ut_offset.abbreviation().expect("Wrong timezone")).unwrap()); + tzname.0[0] = guard.0.as_ref().unwrap().as_ptr().cast_mut(); + + match dst { + Some(dst) => { + guard.1 = + Some(CString::new(dst.offset().abbreviation().expect("Wrong timezone")).unwrap()); + tzname.0[1] = guard.1.as_ref().unwrap().as_ptr().cast_mut(); + daylight = 1; + } + None => { + guard.1 = None; + tzname.0[1] = guard.0.as_ref().unwrap().as_ptr().cast_mut(); + daylight = 0; + } + } + + timezone = -c_long::from(ut_offset.fix().local_minus_utc()); +} + +const fn blank_tm() -> tm { + tm { + tm_year: 0, + tm_mon: 0, + tm_mday: 0, + tm_hour: 0, + tm_min: 0, + tm_sec: 0, + tm_wday: 0, + tm_yday: 0, + tm_isdst: -1, + tm_gmtoff: 0, + tm_zone: ptr::null_mut(), + } } -*/ diff --git a/tests/Makefile b/tests/Makefile index 8deabf2c5c..d0c5dd3de5 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -101,6 +101,7 @@ EXPECT_NAMES=\ time/constants \ time/gmtime \ time/localtime \ + time/localtime_r \ time/macros \ time/mktime \ time/strftime \ diff --git a/tests/expected/bins_dynamic/time/localtime_r.stderr b/tests/expected/bins_dynamic/time/localtime_r.stderr new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/expected/bins_dynamic/time/localtime_r.stdout b/tests/expected/bins_dynamic/time/localtime_r.stdout new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/expected/bins_static/time/localtime_r.stderr b/tests/expected/bins_static/time/localtime_r.stderr new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/expected/bins_static/time/localtime_r.stdout b/tests/expected/bins_static/time/localtime_r.stdout new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/time/localtime_r.c b/tests/time/localtime_r.c new file mode 100644 index 0000000000..3d96f23a94 --- /dev/null +++ b/tests/time/localtime_r.c @@ -0,0 +1,112 @@ +#include +#include +#include +#include + +void test_localtime_r_epoch() { + time_t t = 0; // Unix epoch (1970-01-01 00:00:00) + struct tm result; + + assert(localtime_r(&t, &result) != NULL); + assert(result.tm_year == 70); // Year 1970 - 1900 + assert(result.tm_mon == 0); // January + assert(result.tm_mday == 1); // 1st of January + assert(result.tm_hour == 0); // Midnight + assert(result.tm_min == 0); + assert(result.tm_sec == 0); + + assert(result.tm_isdst == -1 || result.tm_isdst == 0); +} + +void test_localtime_r_non_epoch() { + time_t t = 1609459200; // January 1, 2021 00:00:00 UTC (New Year 2021) + struct tm result; + + assert(localtime_r(&t, &result) != NULL); + assert(result.tm_year == 121); // Year 2021 - 1900 + assert(result.tm_mon == 0); // January + assert(result.tm_mday == 1); // 1st of January + assert(result.tm_hour == 0); // Midnight + assert(result.tm_min == 0); + assert(result.tm_sec == 0); +} + +void test_localtime_r_dst() { + time_t t = 1615708800; // March 14 2021 08:00:00 UTC + struct tm result; + + assert(localtime_r(&t, &result) != NULL); // Ensure localtime_r does not fail + assert(result.tm_year == 121); // Year 2021 - 1900 + assert(result.tm_mon == 2); // March + assert(result.tm_mday == 14); // 14th + assert(result.tm_hour == 8); // 08:00:00 local time + assert(result.tm_min == 0); + assert(result.tm_sec == 0); +} + +void test_localtime_r_large_time() { + time_t t = 32503680000; // A large value: 1 January 3000 (UTC) + struct tm result; + + assert(localtime_r(&t, &result) != NULL); // Ensure localtime_r does not fail + assert(result.tm_year == 1100); // Year 3000 - 1900 = 1100 + assert(result.tm_mon == 0); // January + assert(result.tm_mday == 1); // 1st of January + assert(result.tm_hour == 0); // Midnight + assert(result.tm_min == 0); + assert(result.tm_sec == 0); +} + +void test_dst_transition() { + time_t t = 1615809600; // March 15 2021, 08:00:00 UTC + struct tm result; + + setenv("TZ", "America/New_York", 1); + tzset(); + + localtime_r(&t, &result); + + assert(result.tm_year == 121); // Year 2021 - 1900 = 121 + assert(result.tm_mon == 2); // March (0-based index) + assert(result.tm_mday == 15); // 15th + assert(result.tm_hour == 8); // 00:00:00 local time + assert(result.tm_min == 0); + assert(result.tm_sec == 0); + + assert(result.tm_isdst == 1); // DST should be active + + assert(strcmp(tzname[0], "EST") == 0 || strcmp(tzname[0], "EDT") == 0); // Standard or DST name + assert(strcmp(tzname[1], "EDT") == 0); // Should be the DST version of the timezone +} + +void test_standard_time() { + time_t t = 1609459200; // January 1, 2021, 00:00:00 UTC + struct tm result; + + setenv("TZ", "Asia/Tokyo", 1); + tzset(); + + localtime_r(&t, &result); + + assert(result.tm_year == 121); // Year 2021 - 1900 = 121 + assert(result.tm_mon == 0); // January (0-based index) + assert(result.tm_mday == 1); // 1st + assert(result.tm_hour == 9); // 09:00:00 local time + assert(result.tm_min == 0); + assert(result.tm_sec == 0); + + assert(result.tm_isdst == 0); // DST should NOT be active + + assert(strcmp(tzname[0], "JST") == 0); // Standard time name + assert(strcmp(tzname[1], "EST") != 0); // Should NOT be in DST +} + +int main() { + test_localtime_r_epoch(); + test_localtime_r_non_epoch(); + test_localtime_r_dst(); + test_localtime_r_large_time(); + test_dst_transition(); + test_standard_time(); + return 0; +}