mirror of
https://github.com/RustPython/RustPython.git
synced 2026-10-29 11:14:38 +08:00
Preserve Windows time conversion error classes (#9022)
* Cover Windows time conversion error classes Require OSError with EINVAL for representable timestamps rejected by the Windows C runtime, while preserving OverflowError for float(2**63). This initial regression-only commit intentionally exposes the current Windows error mapping before the implementation follows. AI assistance covered source comparison, regression design, and automated Linux baseline/reference controls. Native Windows results are pending. No human validation is claimed. Assisted-by: Codex:model-version-unavailable * Record native Windows time conversion outcomes The first hosted regression run failed on CPython 3.14.7 as well as RustPython because a presumed-invalid CRT timestamp succeeded. Add bounded diagnostics before the unchanged assertions to capture full version/build metadata and every conversion result, including negative half-day controls. No implementation or canonical test changes are included. The existing time snippet still passes the repository pytest runner on Linux CPython 3.14.7 and the current RustPython baseline. Native diagnostic results remain pending. Assisted-by: Codex:model-version-unavailable * Use the observed UCRT rejection boundary in time regression Hosted Windows diagnostics show that CPython 3.14.7 and RustPython both accept gmtime(-1) and gmtime(-43200), while -86400 is rejected by all three converters. Correct only the newly added shared negative test value. CPython raises OSError(errno 22) for every selected rejected value, while the RustPython baseline raises OverflowError. Canonical tests and the recorded diagnostics remain unchanged. The existing snippet passes both Linux reference and baseline controls. Assisted source investigation and automated verification used no manual validation. Assisted-by: Codex:model-version-unavailable * Preserve Windows CRT time conversion errors Return CRT errno failures from the Windows calendar helpers and translate them to Python OSError. Adapt the datetime caller while retaining its Unix behavior. Use an exclusive signed float upper bound so float(2**63) still raises OverflowError before reaching the CRT. Keep Windows negative-time FILETIME fallback and time64 ABI changes outside this Python 3.14 extraction. Existing datetime local-error coverage is retained and a UTC error control is added for the observed rejected timestamp -86400. Hosted native diagnostics prove CPython 3.14.7 raises OSError(errno 22) where the baseline raises OverflowError. Windows-GNU host_env check and warnings-denied Clippy pass. Selected canonical datetime and complete time/datetime snippet Linux controls pass, with six existing baseline canonical skips. Fixed native Windows verification remains pending CI. AI assistance covered source comparison, implementation, regression design, and automated verification. No manual validation is claimed. Assisted-by: Codex:model-version-unavailable
This commit is contained in:
1 parent
d4b43b860d
commit
87aedfb7c5
5 files changed
+111
-9
No files matched your search
@@ -146,18 +146,24 @@ pub fn current_time_t() -> TimeT {
|
||||
|
||||
#[cfg(windows)]
|
||||
#[cfg_attr(target_env = "musl", allow(deprecated))]
|
||||
pub fn gmtime_from_timestamp(when: TimeT) -> Option<libc::tm> {
|
||||
pub fn gmtime_from_timestamp(when: TimeT) -> std::io::Result<libc::tm> {
|
||||
let mut out = core::mem::MaybeUninit::<libc::tm>::uninit();
|
||||
let err = unsafe { _gmtime64_s(out.as_mut_ptr(), &when) };
|
||||
(err == 0).then(|| unsafe { out.assume_init() })
|
||||
if err != 0 {
|
||||
return Err(crate::os::io_error_from_errno(err));
|
||||
}
|
||||
Ok(unsafe { out.assume_init() })
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[cfg_attr(target_env = "musl", allow(deprecated))]
|
||||
pub fn localtime_from_timestamp(when: TimeT) -> Option<libc::tm> {
|
||||
pub fn localtime_from_timestamp(when: TimeT) -> std::io::Result<libc::tm> {
|
||||
let mut out = core::mem::MaybeUninit::<libc::tm>::uninit();
|
||||
let err = unsafe { _localtime64_s(out.as_mut_ptr(), &when) };
|
||||
(err == 0).then(|| unsafe { out.assume_init() })
|
||||
if err != 0 {
|
||||
return Err(crate::os::io_error_from_errno(err));
|
||||
}
|
||||
Ok(unsafe { out.assume_init() })
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
|
||||
@@ -9,6 +9,8 @@ pub(crate) use _datetime::{PyTzInfo, datetime_type, module_def, timedelta_from_s
|
||||
|
||||
#[pymodule]
|
||||
mod _datetime {
|
||||
#[cfg(windows)]
|
||||
use crate::vm::convert::ToPyException;
|
||||
use crate::vm::{
|
||||
AsObject, Py, PyObject, PyObjectCell, PyObjectRef, PyPayload, PyRef, PyResult,
|
||||
VirtualMachine,
|
||||
@@ -1825,6 +1827,9 @@ mod _datetime {
|
||||
} else {
|
||||
rustpython_host_env::time::gmtime_from_timestamp(t_c)
|
||||
};
|
||||
#[cfg(windows)]
|
||||
let tm = tm.map_err(|error| error.to_pyexception(vm))?;
|
||||
#[cfg(unix)]
|
||||
let Some(tm) = tm else {
|
||||
return Err(vm.new_last_errno_error());
|
||||
};
|
||||
|
||||
@@ -914,7 +914,9 @@ mod decl {
|
||||
}
|
||||
let secs = float.floor();
|
||||
#[cfg_attr(target_env = "musl", allow(deprecated))]
|
||||
if secs < libc::time_t::MIN as f64 || secs > libc::time_t::MAX as f64 {
|
||||
let minimum = libc::time_t::MIN as f64;
|
||||
// The signed maximum rounds up when represented by f64.
|
||||
if !(minimum..-minimum).contains(&secs) {
|
||||
return Err(vm.new_overflow_error("timestamp out of range for platform time_t"));
|
||||
}
|
||||
#[cfg_attr(target_env = "musl", allow(deprecated))]
|
||||
@@ -1248,6 +1250,7 @@ mod platform {
|
||||
use crate::{
|
||||
PyRef, PyResult, VirtualMachine,
|
||||
builtins::{PyNamespace, PyUtf8StrRef},
|
||||
convert::ToPyException,
|
||||
};
|
||||
use core::time::Duration;
|
||||
use rustpython_host_env::time as host_time;
|
||||
@@ -1281,8 +1284,8 @@ mod platform {
|
||||
when: host_time::TimeT,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<StructTimeData> {
|
||||
let tm = host_time::gmtime_from_timestamp(when)
|
||||
.ok_or_else(|| vm.new_overflow_error("timestamp out of range for platform time_t"))?;
|
||||
let tm =
|
||||
host_time::gmtime_from_timestamp(when).map_err(|error| error.to_pyexception(vm))?;
|
||||
Ok(struct_time_from_tm(vm, tm, "UTC", 0))
|
||||
}
|
||||
|
||||
@@ -1290,8 +1293,8 @@ mod platform {
|
||||
when: host_time::TimeT,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<StructTimeData> {
|
||||
let tm = host_time::localtime_from_timestamp(when)
|
||||
.ok_or_else(|| vm.new_overflow_error("timestamp out of range for platform time_t"))?;
|
||||
let tm =
|
||||
host_time::localtime_from_timestamp(when).map_err(|error| error.to_pyexception(vm))?;
|
||||
|
||||
// Get timezone info from Windows API
|
||||
let info = get_tz_info();
|
||||
|
||||
@@ -3949,6 +3949,12 @@ def test_timestamp_errno():
|
||||
assert error.errno == errno.EINVAL
|
||||
else:
|
||||
raise AssertionError("Windows localtime accepted a negative timestamp")
|
||||
try:
|
||||
datetime_module.datetime.fromtimestamp(-86400, datetime_module.timezone.utc)
|
||||
except OSError as error:
|
||||
assert error.errno == errno.EINVAL
|
||||
else:
|
||||
raise AssertionError("Windows gmtime accepted an out-of-range timestamp")
|
||||
|
||||
|
||||
test_astimezone_subclass_state()
|
||||
|
||||
@@ -1,6 +1,88 @@
|
||||
import sys
|
||||
import time
|
||||
|
||||
if sys.platform == "win32":
|
||||
# Record the native runtime before evaluating the range regression below.
|
||||
print("Windows time runtime:", sys.version, sys.implementation, sys.flags)
|
||||
print("Windows time word size:", sys.maxsize)
|
||||
if hasattr(sys, "getwindowsversion"):
|
||||
print("Windows version:", sys.getwindowsversion())
|
||||
try:
|
||||
import sysconfig
|
||||
|
||||
build_keys = (
|
||||
"Py_DEBUG",
|
||||
"Py_GIL_DISABLED",
|
||||
"Py_ENABLE_SHARED",
|
||||
"SIZEOF_TIME_T",
|
||||
"CC",
|
||||
"CFLAGS",
|
||||
)
|
||||
print(
|
||||
"Windows time build:",
|
||||
dict(zip(build_keys, sysconfig.get_config_vars(*build_keys))),
|
||||
)
|
||||
except Exception as error:
|
||||
print("Windows time build unavailable:", type(error).__name__, str(error))
|
||||
for converter in (time.gmtime, time.localtime, time.ctime):
|
||||
for timestamp in (
|
||||
0,
|
||||
-1,
|
||||
-43200,
|
||||
-43201,
|
||||
-86400,
|
||||
2**40,
|
||||
2**63 - 1,
|
||||
-(2**63),
|
||||
-float(2**63),
|
||||
float(2**63),
|
||||
):
|
||||
try:
|
||||
result = converter(timestamp)
|
||||
except Exception as error:
|
||||
print(
|
||||
"Windows time result:",
|
||||
converter.__name__,
|
||||
repr(timestamp),
|
||||
type(error).__name__,
|
||||
str(error),
|
||||
getattr(error, "errno", None),
|
||||
getattr(error, "winerror", None),
|
||||
)
|
||||
else:
|
||||
print(
|
||||
"Windows time result:",
|
||||
converter.__name__,
|
||||
repr(timestamp),
|
||||
"success",
|
||||
repr(result),
|
||||
)
|
||||
|
||||
if sys.platform != "wasi":
|
||||
for converter in (time.gmtime, time.localtime, time.ctime):
|
||||
# 2**63 is outside signed time_t even though its maximum rounds up to
|
||||
# that value when represented as a float.
|
||||
try:
|
||||
converter(float(2**63))
|
||||
except OverflowError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("out-of-range timestamp did not raise OverflowError")
|
||||
|
||||
if sys.platform == "win32":
|
||||
import errno
|
||||
|
||||
for converter in (time.gmtime, time.localtime, time.ctime):
|
||||
# Python 3.14 preserves UCRT conversion failures as OSError. Use a
|
||||
# negative timestamp below gmtime's near-epoch allowance in UCRT.
|
||||
for timestamp in (-86400, 2**40, 2**63 - 1, -(2**63), -float(2**63)):
|
||||
try:
|
||||
converter(timestamp)
|
||||
except OSError as error:
|
||||
assert error.errno == errno.EINVAL, (converter, timestamp, error)
|
||||
else:
|
||||
raise AssertionError("UCRT timestamp failure did not raise OSError")
|
||||
|
||||
x = time.gmtime(1000)
|
||||
|
||||
assert x.tm_year == 1970
|
||||
|
||||
Reference in new issue
Block a user