Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

Fix some issues handling pre-epoch timestamps in WASIp3 (#14485)

Alex Crichton248c2c9d87f8
diff --git a/crates/test-programs/src/bin/p3_file_settime_overflow.rs b/crates/test-programs/src/bin/p3_file_settime_overflow.rs
index 08cf070a37..5779c8d1e5 100644
--- a/crates/test-programs/src/bin/p3_file_settime_overflow.rs
+++ b/crates/test-programs/src/bin/p3_file_settime_overflow.rs
@@ -41,6 +41,101 @@ impl p3::exports::wasi::cli::run::Guest for Component {
ErrorCode::Overflow,
"expect set_times error to be an overflow"
);
+
+ let cases = [
+ (
+ Instant {
+ seconds: -1,
+ nanoseconds: 0,
+ },
+ Instant {
+ seconds: -1,
+ nanoseconds: 0,
+ },
+ ),
+ (
+ Instant {
+ seconds: -1,
+ nanoseconds: 500_000_000,
+ },
+ Instant {
+ seconds: -1,
+ nanoseconds: 500_000_000,
+ },
+ ),
+ (
+ Instant {
+ seconds: -1,
+ nanoseconds: 999_999_900,
+ },
+ Instant {
+ seconds: -1,
+ nanoseconds: 999_999_900,
+ },
+ ),
+ (
+ Instant {
+ seconds: -1,
+ nanoseconds: 1_500_000_000,
+ },
+ Instant {
+ seconds: 0,
+ nanoseconds: 500_000_000,
+ },
+ ),
+ ];
+
+ for (i, (timestamp, expected)) in cases.into_iter().enumerate() {
+ let filename = format!("set-times-{i}.txt");
+ let file = dir
+ .open_at(
+ PathFlags::empty(),
+ filename,
+ OpenFlags::CREATE,
+ DescriptorFlags::READ | DescriptorFlags::WRITE,
+ )
+ .await
+ .expect("creating a file");
+ file.set_times(
+ NewTimestamp::Timestamp(timestamp),
+ NewTimestamp::Timestamp(timestamp),
+ )
+ .await
+ .expect("setting the file's access timestamp");
+
+ let stat = file.stat().await.expect("stating the file");
+ let actual = stat
+ .data_access_timestamp
+ .expect("the file has an access timestamp");
+ assert_eq!(actual.seconds, expected.seconds);
+ assert_eq!(actual.nanoseconds, expected.nanoseconds);
+
+ let filename = format!("set-times-at-{i}.txt");
+ let file = dir
+ .open_at(
+ PathFlags::empty(),
+ filename.clone(),
+ OpenFlags::CREATE,
+ DescriptorFlags::READ | DescriptorFlags::WRITE,
+ )
+ .await
+ .expect("creating a file for set-times-at");
+ dir.set_times_at(
+ PathFlags::empty(),
+ filename,
+ NewTimestamp::Timestamp(timestamp),
+ NewTimestamp::Timestamp(timestamp),
+ )
+ .await
+ .expect("setting the file's access timestamp with set-times-at");
+
+ let stat = file.stat().await.expect("stating the set-times-at file");
+ let actual = stat
+ .data_access_timestamp
+ .expect("the set-times-at file has an access timestamp");
+ assert_eq!(actual.seconds, expected.seconds);
+ assert_eq!(actual.nanoseconds, expected.nanoseconds);
+ }
Ok(())
}
}
diff --git a/crates/wasi/src/clocks.rs b/crates/wasi/src/clocks.rs
index 0cc22c697b..faf03a718f 100644
--- a/crates/wasi/src/clocks.rs
+++ b/crates/wasi/src/clocks.rs
@@ -184,6 +184,8 @@ pub fn wall_clock() -> Box<dyn HostWallClock + Send> {
pub(crate) struct Datetime {
pub seconds: i64,
+ // When seconds are negative, nanos still represent a forward advancement in
+ // time. E.g. -1s and 999_999_999 nanos is -1ns.
pub nanoseconds: u32,
}
@@ -191,20 +193,37 @@ impl TryFrom<SystemTime> for Datetime {
type Error = DatetimeError;
fn try_from(time: SystemTime) -> Result<Self, Self::Error> {
- let epoch = SystemTime::UNIX_EPOCH;
-
- if time >= epoch {
- let duration = time.duration_since(epoch)?;
- Ok(Self {
+ match time.duration_since(SystemTime::UNIX_EPOCH) {
+ Ok(duration) => Ok(Self {
seconds: duration.as_secs().try_into()?,
nanoseconds: duration.subsec_nanos(),
- })
- } else {
- let duration = epoch.duration_since(time)?;
- Ok(Self {
- seconds: -duration.as_secs().try_into()?,
- nanoseconds: duration.subsec_nanos(),
- })
+ }),
+ Err(e) => {
+ // If time is before the epoch, the error gives us the duration
+ // from `time` to the epoch.
+ let duration = e.duration();
+ // So both seconds and nanoseconds are negative. We need to
+ // convert it to negative seconds and positive nanos which
+ // matches the WASI spec.
+ let nanoseconds = duration.subsec_nanos();
+ if nanoseconds == 0 {
+ Ok(Self {
+ // Negation cannot panic because duration.as_secs returns a
+ // u64.
+ seconds: (-i128::from(duration.as_secs())).try_into()?,
+ nanoseconds: 0,
+ })
+ } else {
+ Ok(Self {
+ // Negation and (- 1) cannot panic because duration.as_secs
+ // returns a u64.
+ seconds: (-i128::from(duration.as_secs()) - 1).try_into()?,
+ // Cannot panic because `subsec_nanos` guarantees the result
+ // is less than 1_000_000_000.
+ nanoseconds: 1_000_000_000 - nanoseconds,
+ })
+ }
+ }
}
}
}
diff --git a/crates/wasi/src/filesystem/primitives/unix/times.rs b/crates/wasi/src/filesystem/primitives/unix/times.rs
index e5ef1b883d..f454a6feee 100644
--- a/crates/wasi/src/filesystem/primitives/unix/times.rs
+++ b/crates/wasi/src/filesystem/primitives/unix/times.rs
@@ -22,3 +22,48 @@ pub(crate) fn to_timespec(ft: Option<SystemTime>) -> io::Result<Timespec> {
}
})
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::time::Duration;
+
+ #[test]
+ fn before_unix_epoch() {
+ let epoch = SystemTime::UNIX_EPOCH;
+ let cases = [
+ (
+ epoch.checked_sub(Duration::from_secs(1)),
+ Timespec {
+ tv_sec: -1,
+ tv_nsec: 0,
+ },
+ ),
+ (
+ epoch.checked_sub(Duration::from_millis(500)),
+ Timespec {
+ tv_sec: -1,
+ tv_nsec: 500_000_000,
+ },
+ ),
+ (
+ epoch.checked_sub(Duration::from_nanos(1)),
+ Timespec {
+ tv_sec: -1,
+ tv_nsec: 999_999_999,
+ },
+ ),
+ (
+ epoch.checked_add(Duration::from_millis(500)),
+ Timespec {
+ tv_sec: 0,
+ tv_nsec: 500_000_000,
+ },
+ ),
+ ];
+
+ for (time, expected) in cases {
+ assert_eq!(to_timespec(time).unwrap(), expected);
+ }
+ }
+}
diff --git a/crates/wasi/src/p3/filesystem/host.rs b/crates/wasi/src/p3/filesystem/host.rs
index 7bf55ba4f9..f558fbc2c8 100644
--- a/crates/wasi/src/p3/filesystem/host.rs
+++ b/crates/wasi/src/p3/filesystem/host.rs
@@ -59,30 +59,29 @@ fn get_writable_file(table: &ResourceTable, fd: &Resource<Descriptor>) -> Filesy
}
fn systemtime_from(t: system_clock::Instant) -> Result<std::time::SystemTime, ErrorCode> {
- if let Ok(seconds) = <i64 as TryInto<u64>>::try_into(t.seconds) {
- // Catch nanoseconds-into-seconds Overflow error explicitly:
- // unfortunately, Duration::new panics when input overflows
- let duration = core::time::Duration::new(
- seconds
- .checked_add(u64::from(t.nanoseconds / 1_000_000_000))
- .ok_or(ErrorCode::Overflow)?,
- t.nanoseconds % 1_000_000_000,
- );
- std::time::SystemTime::UNIX_EPOCH
+ let mut system_time = std::time::SystemTime::UNIX_EPOCH;
+
+ // Add or subtract the seconds based on sign.
+ if t.seconds >= 0 {
+ let duration =
+ core::time::Duration::new(t.seconds.try_into().map_err(|_| ErrorCode::Overflow)?, 0);
+ system_time = system_time
.checked_add(duration)
- .ok_or(ErrorCode::Overflow)
+ .ok_or(ErrorCode::Overflow)?;
} else {
- let duration = core::time::Duration::new(
- t.seconds
- .unsigned_abs()
- .checked_add(u64::from(t.nanoseconds / 1_000_000_000))
- .ok_or(ErrorCode::Overflow)?,
- t.nanoseconds % 1_000_000_000,
- );
- std::time::SystemTime::UNIX_EPOCH
+ let duration = core::time::Duration::new(t.seconds.unsigned_abs(), 0);
+ system_time = system_time
.checked_sub(duration)
- .ok_or(ErrorCode::Overflow)
- }
+ .ok_or(ErrorCode::Overflow)?;
+ };
+
+ // Always add the nanos
+ let duration = core::time::Duration::new(0, t.nanoseconds);
+ system_time = system_time
+ .checked_add(duration)
+ .ok_or(ErrorCode::Overflow)?;
+
+ Ok(system_time)
}
fn systemtimespec_from(t: NewTimestamp) -> Result<Option<SystemTime>, ErrorCode> {