Skip to content

Commit 90b408c

Browse files
committed
Add localtime_r shim
1 parent 4b4e1dd commit 90b408c

File tree

5 files changed

+273
-0
lines changed

5 files changed

+273
-0
lines changed

Cargo.lock

Lines changed: 144 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ smallvec = "1.7"
2424
aes = { version = "0.8.3", features = ["hazmat"] }
2525
measureme = "11"
2626
ctrlc = "3.2.5"
27+
chrono = { version = "0.4.38", default-features = false, features = ["clock"] }
2728

2829
# Copied from `compiler/rustc/Cargo.toml`.
2930
# But only for some targets, it fails for others. Rustc configures this in its CI, but we can't

src/shims/time.rs

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
1+
use std::ffi::OsString;
2+
use std::fmt::Write;
13
use std::time::{Duration, SystemTime};
24

5+
use chrono::{DateTime, Datelike, Local, Timelike, Utc};
6+
37
use crate::concurrency::thread::MachineCallback;
48
use crate::*;
59

@@ -107,6 +111,80 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
107111
Ok(0)
108112
}
109113

114+
// The localtime() function shall convert the time in seconds since the Epoch pointed to by
115+
// timer into a broken-down time, expressed as a local time.
116+
// https://linux.die.net/man/3/localtime_r
117+
fn localtime_r(
118+
&mut self,
119+
timep: &OpTy<'tcx, Provenance>,
120+
result_op: &OpTy<'tcx, Provenance>,
121+
) -> InterpResult<'tcx, Pointer<Option<Provenance>>> {
122+
let this = self.eval_context_mut();
123+
124+
this.assert_target_os_is_unix("localtime_r");
125+
this.check_no_isolation("`localtime_r`")?;
126+
127+
let timep = this.deref_pointer(timep)?;
128+
let result = this.deref_pointer_as(result_op, this.libc_ty_layout("tm"))?;
129+
130+
// The input "represents the number of seconds elapsed since the Epoch,
131+
// 1970-01-01 00:00:00 +0000 (UTC)".
132+
let sec_since_epoch: i64 = this
133+
.read_scalar(&timep)?
134+
.to_int(this.libc_ty_layout("time_t").size)?
135+
.try_into()
136+
.unwrap();
137+
let dt_utc: DateTime<Utc> =
138+
DateTime::from_timestamp(sec_since_epoch, 0).expect("Invalid timestamp");
139+
// Convert that to local time, then return the broken-down time value.
140+
let dt: DateTime<Local> = DateTime::from(dt_utc);
141+
142+
// This value is always set to -1, because there is no way to know if dst is in effect with
143+
// chrono crate yet.
144+
// This may not be consistent with libc::localtime_r's result.
145+
let tm_isdst = -1;
146+
147+
// tm_zone represents the timezone value in the form of: +0730, +08, -0730 or -08.
148+
// This may not be consistent with libc::localtime_r's result.
149+
let offset_in_second = Local::now().offset().local_minus_utc();
150+
let tm_gmtoff = offset_in_second;
151+
let mut tm_zone = String::new();
152+
if offset_in_second < 0 {
153+
tm_zone.push('-');
154+
} else {
155+
tm_zone.push('+');
156+
}
157+
let offset_hour = offset_in_second.abs() / 3600;
158+
write!(tm_zone, "{:02}", offset_hour).unwrap();
159+
let offset_min = (offset_in_second.abs() % 3600) / 60;
160+
if offset_min != 0 {
161+
write!(tm_zone, "{:02}", offset_min).unwrap();
162+
}
163+
164+
// FIXME: String de-duplication is needed so that we only allocate this string only once
165+
// even when there are multiple calls to this function.
166+
let tm_zone_ptr =
167+
this.alloc_os_str_as_c_str(&OsString::from(tm_zone), MiriMemoryKind::Machine.into())?;
168+
169+
this.write_pointer(tm_zone_ptr, &this.project_field_named(&result, "tm_zone")?)?;
170+
this.write_int_fields_named(
171+
&[
172+
("tm_sec", dt.second().into()),
173+
("tm_min", dt.minute().into()),
174+
("tm_hour", dt.hour().into()),
175+
("tm_mday", dt.day().into()),
176+
("tm_mon", dt.month0().into()),
177+
("tm_year", dt.year().checked_sub(1900).unwrap().into()),
178+
("tm_wday", dt.weekday().num_days_from_sunday().into()),
179+
("tm_yday", dt.ordinal0().into()),
180+
("tm_isdst", tm_isdst),
181+
("tm_gmtoff", tm_gmtoff.into()),
182+
],
183+
&result,
184+
)?;
185+
186+
Ok(result.ptr())
187+
}
110188
#[allow(non_snake_case, clippy::arithmetic_side_effects)]
111189
fn GetSystemTimeAsFileTime(
112190
&mut self,

src/shims/unix/foreign_items.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,11 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
234234
let result = this.gettimeofday(tv, tz)?;
235235
this.write_scalar(Scalar::from_i32(result), dest)?;
236236
}
237+
"localtime_r" => {
238+
let [timep, result_op] = this.check_shim(abi, Abi::C {unwind: false}, link_name, args)?;
239+
let result = this.localtime_r(timep, result_op)?;
240+
this.write_pointer(result, dest)?;
241+
}
237242
"clock_gettime" => {
238243
let [clk_id, tp] =
239244
this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;

tests/pass-dep/shims/libc-misc.rs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,50 @@ fn test_posix_gettimeofday() {
213213
assert_eq!(is_error, -1);
214214
}
215215

216+
fn test_localtime_r() {
217+
use std::ffi::CStr;
218+
use std::{env, ptr};
219+
220+
// Set timezone to GMT.
221+
let key = "TZ";
222+
env::set_var(key, "GMT");
223+
224+
const TIME_SINCE_EPOCH: libc::time_t = 1712475836;
225+
let custom_time_ptr = &TIME_SINCE_EPOCH;
226+
let mut tm = libc::tm {
227+
tm_sec: 0,
228+
tm_min: 0,
229+
tm_hour: 0,
230+
tm_mday: 0,
231+
tm_mon: 0,
232+
tm_year: 0,
233+
tm_wday: 0,
234+
tm_yday: 0,
235+
tm_isdst: 0,
236+
tm_gmtoff: 0,
237+
tm_zone: std::ptr::null_mut::<libc::c_char>(),
238+
};
239+
let res = unsafe { libc::localtime_r(custom_time_ptr, &mut tm) };
240+
241+
assert_eq!(tm.tm_sec, 56);
242+
assert_eq!(tm.tm_min, 43);
243+
assert_eq!(tm.tm_hour, 7);
244+
assert_eq!(tm.tm_mday, 7);
245+
assert_eq!(tm.tm_mon, 3);
246+
assert_eq!(tm.tm_year, 124);
247+
assert_eq!(tm.tm_wday, 0);
248+
assert_eq!(tm.tm_yday, 97);
249+
assert_eq!(tm.tm_isdst, -1);
250+
assert_eq!(tm.tm_gmtoff, 0);
251+
unsafe { assert_eq!(CStr::from_ptr(tm.tm_zone).to_str().unwrap(), "+00") };
252+
253+
// The returned value is the pointer passed in.
254+
assert!(ptr::eq(res, &mut tm));
255+
256+
//Remove timezone setting.
257+
env::remove_var(key);
258+
}
259+
216260
fn test_isatty() {
217261
// Testing whether our isatty shim returns the right value would require controlling whether
218262
// these streams are actually TTYs, which is hard.
@@ -365,6 +409,7 @@ fn main() {
365409
test_posix_realpath_errors();
366410

367411
test_thread_local_errno();
412+
test_localtime_r();
368413

369414
test_isatty();
370415

0 commit comments

Comments
 (0)