Adding tzset, timezone awareness, and some tweaks
This commit is contained in:
committed by
Jeremy Soller
parent
94e264d253
commit
c14b2cee4c
+255
-155
@@ -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<OnceCell<BTreeSet<CString>>> = Mutex::new(OnceCell::new());
|
||||
|
||||
// Hold `TIMEZONE_LOCK` when updating `tzname`, `timezone`, and `daylight`.
|
||||
static TIMEZONE_LOCK: Mutex<(Option<CString>, Option<CString>)> = 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::<timespec>::uninit();
|
||||
let mut ts = mem::MaybeUninit::<timespec>::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<tm> 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<time_t> {
|
||||
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<FixedOffset>
|
||||
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<CString>, Option<CString>)>) {
|
||||
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<Tz>) -> 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<CString>, Option<CString>)>,
|
||||
std: &DateTime<Tz>,
|
||||
dst: Option<DateTime<Tz>>,
|
||||
) {
|
||||
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(),
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user