Repository navigation
Match CPython OSError initialization and display #10172
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -1668,6 +1668,8 @@ impl OSErrorBuilder { | |
| filename2, | ||
| } = self; | ||
|
|
||
| #[cfg(windows)] | ||
| let has_winerror = winerror.is_some(); | ||
| let args = if let Some(errno) = errno { | ||
| let winerror = cfg_select! { | ||
| windows => winerror.to_pyobject(vm), | ||
|
|
@@ -1685,8 +1687,16 @@ impl OSErrorBuilder { | |
| vec![strerror.to_pyobject(vm)] | ||
| }; | ||
|
|
||
| vm.new_payload_exception::<PyOSError>(exc_type, args.into()) | ||
| .expect("new_os_error usage error") | ||
| let exc = vm | ||
| .new_payload_exception::<PyOSError>(exc_type, args.into()) | ||
| .expect("new_os_error usage error"); | ||
| // The builder uses None as an argument placeholder, not an explicit | ||
| // Python winerror value. Keep the underlying native field unset. | ||
| #[cfg(windows)] | ||
| if !has_winerror { | ||
| exc.clear_winerror(vm); | ||
| } | ||
| exc | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -2676,37 +2686,13 @@ pub(super) mod types { | |
| impl Constructor for PyOSError { | ||
| type Args = FuncArgs; | ||
|
|
||
| fn py_new(_cls: &Py<PyType>, args: FuncArgs, vm: &VirtualMachine) -> PyResult<Self> { | ||
| let len = args.args.len(); | ||
| // CPython only sets errno/strerror when args len is 2-5 | ||
| let (errno, strerror) = if (2..=5).contains(&len) { | ||
| (Some(args.args[0].clone()), Some(args.args[1].clone())) | ||
| } else { | ||
| (None, None) | ||
| }; | ||
| let filename = if (3..=5).contains(&len) { | ||
| Some(args.args[2].clone()) | ||
| } else { | ||
| None | ||
| }; | ||
| let filename2 = if len == 5 { | ||
| args.args.get(4).cloned() | ||
| } else { | ||
| None | ||
| }; | ||
| // Truncate args for base exception when 3-5 args | ||
| let base_args = if (3..=5).contains(&len) { | ||
| args.args[..2].to_vec() | ||
| } else { | ||
| args.args.to_vec() | ||
| }; | ||
| let base_exception = PyBaseException::new(base_args, vm); | ||
| fn py_new(_cls: &Py<PyType>, _args: FuncArgs, vm: &VirtualMachine) -> PyResult<Self> { | ||
| Ok(Self { | ||
| base: PyException(base_exception), | ||
| errno: errno.into(), | ||
| strerror: strerror.into(), | ||
| filename: filename.into(), | ||
| filename2: filename2.into(), | ||
| base: PyException(PyBaseException::new(vec![], vm)), | ||
| errno: None.into(), | ||
| strerror: None.into(), | ||
| filename: None.into(), | ||
| filename2: None.into(), | ||
| #[cfg(windows)] | ||
| winerror: None.into(), | ||
| written: AtomicCell::new(-1), | ||
|
|
@@ -2715,17 +2701,7 @@ pub(super) mod types { | |
|
|
||
| fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { | ||
| if oserror_use_init(&cls) { | ||
| let payload = Self { | ||
| base: PyException(PyBaseException::new(vec![], vm)), | ||
| errno: None.into(), | ||
| strerror: None.into(), | ||
| filename: None.into(), | ||
| filename2: None.into(), | ||
| #[cfg(windows)] | ||
| winerror: None.into(), | ||
| written: AtomicCell::new(-1), | ||
| }; | ||
| return payload | ||
| return Self::py_new(&cls, args, vm)? | ||
| .into_ref_with_type_lazy_dict(vm, cls) | ||
| .map(Into::into); | ||
| } | ||
|
|
@@ -2744,16 +2720,14 @@ pub(super) mod types { | |
| let len = args_vec.len(); | ||
| if (2..=5).contains(&len) { | ||
| let errno = &args_vec[0]; | ||
| if let Some(error) = errno | ||
| if let Some(typ) = errno | ||
| .downcast_ref::<PyInt>() | ||
| .and_then(|errno| errno.try_to_primitive::<i32>(vm).ok()) | ||
| .and_then(|errno| super::errno_to_exc_type(errno, vm)) | ||
| .and_then(|typ| { | ||
| vm.new_payload_exception::<Self>(typ.to_owned(), args_vec.into()) | ||
| .ok() | ||
| }) | ||
| { | ||
| return error.to_pyresult(vm); | ||
| return vm | ||
| .new_payload_exception::<Self>(typ.to_owned(), args_vec.into())? | ||
| .to_pyresult(vm); | ||
| } | ||
| } | ||
| } | ||
|
|
@@ -2785,74 +2759,61 @@ pub(super) mod types { | |
| #[allow(deprecated)] | ||
| let exc: &Py<PyOSError> = zelf.downcast_ref::<PyOSError>().unwrap(); | ||
|
|
||
| // Check if this is BlockingIOError - need to handle characters_written | ||
| let is_blocking_io_error = zelf | ||
| .class() | ||
| .is(vm.ctx.exceptions.blocking_io_error.as_ref()); | ||
|
|
||
| // SAFETY: slot_init is called during object initialization, | ||
| // so fields are None and swap result can be safely ignored | ||
| let mut set_filename = true; | ||
| if len <= 5 { | ||
| // Only set errno/strerror when args len is 2-5 | ||
| if 2 <= len { | ||
| let _ = unsafe { exc.errno.swap(Some(new_args.args[0].clone())) }; | ||
| let _ = unsafe { exc.strerror.swap(Some(new_args.args[1].clone())) }; | ||
| } | ||
| if 3 <= len { | ||
| let third_arg = &new_args.args[2]; | ||
| // BlockingIOError's 3rd argument can be the number of characters written | ||
| if is_blocking_io_error | ||
| && !vm.is_none(third_arg) | ||
| && crate::protocol::PyNumber::check(third_arg) | ||
| && let Ok(written) = third_arg.try_index(vm) | ||
| && let Ok(n) = written.try_to_primitive::<isize>(vm) | ||
| if (2..=5).contains(&len) { | ||
| let mut took_filename = false; | ||
| if let Some(filename) = new_args.args.get(2).filter(|obj| !vm.is_none(obj)) { | ||
| if zelf.class().is(vm.ctx.exceptions.blocking_io_error) | ||
| && crate::protocol::PyNumber::check(filename) | ||
| { | ||
| exc.written.store(n); | ||
| set_filename = false; | ||
| // The count leaves neither filename taken, so both are | ||
| // put back the way `py_new` found them. | ||
| let _ = unsafe { exc.filename.swap(None) }; | ||
| let _ = unsafe { exc.filename2.swap(None) }; | ||
| } | ||
| if set_filename { | ||
| let _ = unsafe { exc.filename.swap(Some(third_arg.clone())) }; | ||
| let written = filename | ||
| .try_index(vm)? | ||
| .try_to_primitive::<isize>(vm) | ||
| .map_err(|_| { | ||
| vm.new_value_error(format!( | ||
| "cannot fit '{}' into an index-sized integer", | ||
| super::truncated_type_name(filename, 200) | ||
| )) | ||
| })?; | ||
| exc.written.store(written); | ||
| } else { | ||
| took_filename = true; | ||
| exc.filename | ||
| .swap_to_temporary_refs(Some(filename.clone()), vm); | ||
| if let Some(filename2) = new_args.args.get(4).filter(|obj| !vm.is_none(obj)) { | ||
| exc.filename2 | ||
| .swap_to_temporary_refs(Some(filename2.clone()), vm); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #[cfg(windows)] | ||
| if 4 <= len { | ||
| { | ||
| let winerror = new_args.args.get(3).cloned(); | ||
| // Store original winerror | ||
| let _ = unsafe { exc.winerror.swap(winerror.clone()) }; | ||
|
|
||
| // Convert winerror to errno and update errno + args[0] | ||
| if let Some(errno) = winerror | ||
| .as_ref() | ||
| .and_then(|w| w.downcast_ref::<crate::builtins::PyInt>()) | ||
| .and_then(|w| w.try_to_primitive::<i32>(vm).ok()) | ||
| .map(crate::host_env::os::winerror_to_errno) | ||
| { | ||
| let errno_obj = vm.new_pyobj(errno); | ||
| let _ = unsafe { exc.errno.swap(Some(errno_obj.clone())) }; | ||
| new_args.args[0] = errno_obj; | ||
| new_args.args[0] = vm.new_pyobj(errno); | ||
| } | ||
| exc.winerror.swap_to_temporary_refs(winerror, vm); | ||
| } | ||
| } | ||
| exc.errno | ||
| .swap_to_temporary_refs(Some(new_args.args[0].clone()), vm); | ||
| exc.strerror | ||
| .swap_to_temporary_refs(Some(new_args.args[1].clone()), vm); | ||
|
|
||
| // A second filename, and the two arguments the rest are cut back | ||
| // to, both follow the filename itself having been taken. | ||
| let has_filename = exc | ||
| .filename | ||
| .load_owned() | ||
| .as_ref() | ||
| .is_some_and(|f| !vm.is_none(f)); | ||
| if (3..=5).contains(&len) && has_filename { | ||
| if let Some(filename2) = new_args.args.get(4) | ||
| && !vm.is_none(filename2) | ||
| { | ||
| let _ = unsafe { exc.filename2.swap(Some(filename2.clone())) }; | ||
| // Only a filename taken from these arguments shortens args. An | ||
| // existing filename on a reinitialized object does not count. | ||
| if took_filename { | ||
| new_args.args.truncate(2); | ||
| } | ||
| new_args.args.truncate(2); | ||
| } else { | ||
| exc.errno.swap_to_temporary_refs(None, vm); | ||
| exc.strerror.swap_to_temporary_refs(None, vm); | ||
| #[cfg(windows)] | ||
| exc.winerror.swap_to_temporary_refs(None, vm); | ||
| } | ||
| PyBaseException::slot_init(zelf, new_args, vm) | ||
| } | ||
|
|
@@ -2880,90 +2841,40 @@ pub(super) mod types { | |
|
|
||
| #[pyexception(with(Constructor, Initializer))] | ||
| impl PyOSError { | ||
| #[cfg(windows)] | ||
| pub(super) fn clear_winerror(&self, vm: &VirtualMachine) { | ||
| self.winerror.swap_to_temporary_refs(None, vm); | ||
| } | ||
|
|
||
| #[pyslot] | ||
| fn slot_str(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<PyStrRef> { | ||
| let obj = zelf; | ||
|
|
||
| // Get OSError fields directly | ||
| let errno_field = obj.get_attr("errno", vm).ok().filter(|v| !vm.is_none(v)); | ||
| let strerror = obj.get_attr("strerror", vm).ok().filter(|v| !vm.is_none(v)); | ||
| let filename = obj.get_attr("filename", vm).ok().filter(|v| !vm.is_none(v)); | ||
| let filename2 = obj | ||
| .get_attr("filename2", vm) | ||
| .ok() | ||
| .filter(|v| !vm.is_none(v)); | ||
| #[allow(deprecated)] | ||
| let exc: &Py<Self> = zelf.downcast_ref().expect("OSError payload"); | ||
| let filename = exc.filename.load_owned(); | ||
| let filename2 = exc.filename2.load_owned(); | ||
| let strerror = exc.strerror.load_owned(); | ||
| let errno = exc.errno.load_owned(); | ||
| #[cfg(not(windows))] | ||
| let (label, code) = ("Errno", errno); | ||
| #[cfg(windows)] | ||
| let winerror = obj.get_attr("winerror", vm).ok().filter(|v| !vm.is_none(v)); | ||
| let (label, code) = match exc.winerror.load_owned() { | ||
| Some(winerror) => ("WinError", Some(winerror)), | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
| None => ("Errno", errno), | ||
|
Comment on lines
+2860
to
+2862
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
For errno-only errors on Windows, Useful? React with 👍 / 👎. |
||
| }; | ||
|
|
||
| // Windows: winerror takes priority over errno | ||
| #[cfg(windows)] | ||
| if let Some(ref win_err) = winerror { | ||
| let code = win_err.str(vm)?; | ||
| if let Some(ref f) = filename { | ||
| let msg = strerror | ||
| .as_ref() | ||
| .map(|s| s.str(vm)) | ||
| .transpose()? | ||
| .map_or_else(|| "None".to_owned(), |s| s.to_string()); | ||
|
|
||
| if let Some(ref f2) = filename2 { | ||
| return Ok(vm.ctx.new_str(format!( | ||
| "[WinError {}] {}: {} -> {}", | ||
| code, | ||
| msg, | ||
| f.repr(vm)?, | ||
| f2.repr(vm)? | ||
| ))); | ||
| if filename.is_some() || (code.is_some() && strerror.is_some()) { | ||
| let code = code.unwrap_or_else(|| vm.ctx.none()).str(vm)?; | ||
| let msg = strerror.unwrap_or_else(|| vm.ctx.none()).str(vm)?; | ||
| let mut result = wtf8_concat!("[", label, " ", code.as_wtf8(), "] ", msg.as_wtf8()); | ||
| if let Some(filename) = filename { | ||
| result.push_str(": "); | ||
| result.push_wtf8(filename.repr(vm)?.as_wtf8()); | ||
| if let Some(filename2) = filename2 { | ||
| result.push_str(" -> "); | ||
| result.push_wtf8(filename2.repr(vm)?.as_wtf8()); | ||
| } | ||
| return Ok(vm.ctx.new_str(format!( | ||
| "[WinError {}] {}: {}", | ||
| code, | ||
| msg, | ||
| f.repr(vm)? | ||
| ))); | ||
| } | ||
| // winerror && strerror (no filename) | ||
| if let Some(ref s) = strerror { | ||
| return Ok(vm | ||
| .ctx | ||
| .new_str(format!("[WinError {}] {}", code, s.str(vm)?))); | ||
| } | ||
| } | ||
|
|
||
| // Non-Windows or fallback: use errno | ||
| if let Some(ref f) = filename { | ||
| let errno_str = errno_field | ||
| .as_ref() | ||
| .map(|e| e.str(vm)) | ||
| .transpose()? | ||
| .map_or_else(|| "None".to_owned(), |s| s.to_string()); | ||
| let msg = strerror | ||
| .as_ref() | ||
| .map(|s| s.str(vm)) | ||
| .transpose()? | ||
| .map_or_else(|| "None".to_owned(), |s| s.to_string()); | ||
| if let Some(ref f2) = filename2 { | ||
| return Ok(vm.ctx.new_str(format!( | ||
| "[Errno {}] {}: {} -> {}", | ||
| errno_str, | ||
| msg, | ||
| f.repr(vm)?, | ||
| f2.repr(vm)? | ||
| ))); | ||
| } | ||
| return Ok(vm.ctx.new_str(format!( | ||
| "[Errno {}] {}: {}", | ||
| errno_str, | ||
| msg, | ||
| f.repr(vm)? | ||
| ))); | ||
| } | ||
|
|
||
| // errno && strerror (no filename) | ||
| if let (Some(e), Some(s)) = (&errno_field, &strerror) { | ||
| return Ok(vm | ||
| .ctx | ||
| .new_str(format!("[Errno {}] {}", e.str(vm)?, s.str(vm)?))); | ||
| return Ok(vm.ctx.new_str(result)); | ||
| } | ||
|
|
||
| // fallback to BaseException.__str__ | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Preserve absent winerror through reconstruction.
On Windows,
vm.new_errno_error(9, "bad descriptor")retains(9, "bad descriptor", None, None, None)inargs. This clears only the native field.__reduce__returns those arguments, so reconstruction stores the fourthNoneas an explicitwinerror. The message changes from[Errno 9] bad descriptorto[WinError None] bad descriptor. (raw.githubusercontent.com)When trailing builder fields are absent, construct the shortest argument tuple. Keep explicitly supplied Python
Noneand actual Windows codes unchanged.