Skip to content

Commit ac857bc

Browse files
committed
payload rework
1 parent 45345e4 commit ac857bc

File tree

21 files changed

+130
-126
lines changed

21 files changed

+130
-126
lines changed

crates/stdlib/src/bz2.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ mod _bz2 {
7979
state
8080
.decompress(data, max_length, BUFSIZ, vm)
8181
.map_err(|e| match e {
82-
DecompressError::Decompress(err) => vm.new_os_error(err.to_string()),
82+
DecompressError::Decompress(err) => vm.new_simple_os_error(err.to_string()),
8383
DecompressError::Eof(err) => err.to_pyexception(vm),
8484
})
8585
}

crates/stdlib/src/lzma.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,7 @@ mod _lzma {
182182
state
183183
.decompress(data, max_length, BUFSIZ, vm)
184184
.map_err(|e| match e {
185-
DecompressError::Decompress(err) => vm.new_os_error(err.to_string()),
185+
DecompressError::Decompress(err) => vm.new_simple_os_error(err.to_string()),
186186
DecompressError::Eof(err) => err.to_pyexception(vm),
187187
})
188188
}

crates/stdlib/src/openssl.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1480,7 +1480,7 @@ mod _ssl {
14801480
vm.ctx.exceptions.file_not_found_error.to_owned(),
14811481
e.to_string(),
14821482
),
1483-
_ => vm.new_os_error(e.to_string()),
1483+
_ => vm.new_simple_os_error(e.to_string()),
14841484
}
14851485
})?;
14861486

@@ -3550,10 +3550,10 @@ mod _ssl {
35503550

35513551
let mut combined_pem = String::new();
35523552
let entries = read_dir(root)
3553-
.map_err(|err| vm.new_os_error(format!("read cert root: {}", err)))?;
3553+
.map_err(|err| vm.new_simple_os_error(format!("read cert root: {}", err)))?;
35543554
for entry in entries {
35553555
let entry =
3556-
entry.map_err(|err| vm.new_os_error(format!("iter cert root: {}", err)))?;
3556+
entry.map_err(|err| vm.new_simple_os_error(format!("iter cert root: {}", err)))?;
35573557

35583558
let path = entry.path();
35593559
if !path.is_file() {
@@ -3563,7 +3563,7 @@ mod _ssl {
35633563
File::open(&path)
35643564
.and_then(|mut file| file.read_to_string(&mut combined_pem))
35653565
.map_err(|err| {
3566-
vm.new_os_error(format!("open cert file {}: {}", path.display(), err))
3566+
vm.new_simple_os_error(format!("open cert file {}: {}", path.display(), err))
35673567
})?;
35683568

35693569
combined_pem.push('\n');

crates/stdlib/src/select.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -580,7 +580,7 @@ mod decl {
580580
return Err(vm.new_value_error("negative sizehint"));
581581
}
582582
if !matches!(args.flags, 0 | libc::EPOLL_CLOEXEC) {
583-
return Err(vm.new_os_error("invalid flags".to_owned()));
583+
return Err(vm.new_simple_os_error("invalid flags".to_owned()));
584584
}
585585
Self::new()
586586
.map_err(|e| e.into_pyexception(vm))?

crates/stdlib/src/socket.rs

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -945,7 +945,7 @@ mod _socket {
945945
ArgStrOrBytesLike::Str(s) => vm.fsencode(s)?,
946946
};
947947
socket2::SockAddr::unix(path)
948-
.map_err(|_| vm.new_os_error("AF_UNIX path too long".to_owned()).into())
948+
.map_err(|_| vm.new_simple_os_error("AF_UNIX path too long".to_owned()).into())
949949
}
950950
c::AF_INET => {
951951
let tuple: PyTupleRef = addr.downcast().map_err(|obj| {
@@ -996,7 +996,7 @@ mod _socket {
996996
}
997997
Ok(addr6.into())
998998
}
999-
_ => Err(vm.new_os_error(format!("{caller}(): bad family")).into()),
999+
_ => Err(vm.new_simple_os_error(format!("{caller}(): bad family")).into()),
10001000
}
10011001
}
10021002

@@ -1421,10 +1421,10 @@ mod _socket {
14211421
.map(|(_, _, buf)| buf.len())
14221422
.try_fold(0, |sum, len| {
14231423
let space = checked_cmsg_space(len).ok_or_else(|| {
1424-
vm.new_os_error("ancillary data item too large".to_owned())
1424+
vm.new_simple_os_error("ancillary data item too large".to_owned())
14251425
})?;
14261426
usize::checked_add(sum, space)
1427-
.ok_or_else(|| vm.new_os_error("too much ancillary data".to_owned()))
1427+
.ok_or_else(|| vm.new_simple_os_error("too much ancillary data".to_owned()))
14281428
})?;
14291429

14301430
let mut cmsg_buffer = vec![0u8; capacity];
@@ -1553,7 +1553,7 @@ mod _socket {
15531553
} else {
15541554
if buflen <= 0 || buflen > 1024 {
15551555
return Err(vm
1556-
.new_os_error("getsockopt buflen out of range".to_owned())
1556+
.new_simple_os_error("getsockopt buflen out of range".to_owned())
15571557
.into());
15581558
}
15591559
let mut buf = vec![0u8; buflen as usize];
@@ -1739,7 +1739,7 @@ mod _socket {
17391739
gethostname::gethostname()
17401740
.into_string()
17411741
.map(|hostname| vm.ctx.new_str(hostname))
1742-
.map_err(|err| vm.new_os_error(err.into_string().unwrap()))
1742+
.map_err(|err| vm.new_simple_os_error(err.into_string().unwrap()))
17431743
}
17441744

17451745
#[cfg(all(unix, not(target_os = "redox")))]
@@ -1755,15 +1755,15 @@ mod _socket {
17551755
.parse::<Ipv4Addr>()
17561756
.map(|ip_addr| Vec::<u8>::from(ip_addr.octets()))
17571757
.map_err(|_| {
1758-
vm.new_os_error("illegal IP address string passed to inet_aton".to_owned())
1758+
vm.new_simple_os_error("illegal IP address string passed to inet_aton".to_owned())
17591759
})
17601760
}
17611761

17621762
#[pyfunction]
17631763
fn inet_ntoa(packed_ip: ArgBytesLike, vm: &VirtualMachine) -> PyResult<PyStrRef> {
17641764
let packed_ip = packed_ip.borrow_buf();
17651765
let packed_ip = <&[u8; 4]>::try_from(&*packed_ip)
1766-
.map_err(|_| vm.new_os_error("packed IP wrong length for inet_ntoa".to_owned()))?;
1766+
.map_err(|_| vm.new_simple_os_error("packed IP wrong length for inet_ntoa".to_owned()))?;
17671767
Ok(vm.ctx.new_str(Ipv4Addr::from(*packed_ip).to_string()))
17681768
}
17691769

@@ -1785,7 +1785,7 @@ mod _socket {
17851785
let cstr_proto = cstr_opt_as_ptr(&cstr_proto);
17861786
let serv = unsafe { c::getservbyname(cstr_name.as_ptr() as _, cstr_proto as _) };
17871787
if serv.is_null() {
1788-
return Err(vm.new_os_error("service/proto not found".to_owned()));
1788+
return Err(vm.new_simple_os_error("service/proto not found".to_owned()));
17891789
}
17901790
let port = unsafe { (*serv).s_port };
17911791
Ok(u16::from_be(port as u16))
@@ -1807,7 +1807,7 @@ mod _socket {
18071807
let cstr_proto = cstr_opt_as_ptr(&cstr_proto);
18081808
let serv = unsafe { c::getservbyport(port.to_be() as _, cstr_proto as _) };
18091809
if serv.is_null() {
1810-
return Err(vm.new_os_error("port/proto not found".to_owned()));
1810+
return Err(vm.new_simple_os_error("port/proto not found".to_owned()));
18111811
}
18121812
let s = unsafe { ffi::CStr::from_ptr((*serv).s_name as _) };
18131813
Ok(s.to_string_lossy().into_owned())
@@ -2024,16 +2024,16 @@ mod _socket {
20242024
c::AF_INET => ip_string
20252025
.as_str()
20262026
.parse::<Ipv4Addr>()
2027-
.map_err(|_| vm.new_os_error(ERROR_MSG.to_owned()))?
2027+
.map_err(|_| vm.new_simple_os_error(ERROR_MSG.to_owned()))?
20282028
.octets()
20292029
.to_vec(),
20302030
c::AF_INET6 => ip_string
20312031
.as_str()
20322032
.parse::<Ipv6Addr>()
2033-
.map_err(|_| vm.new_os_error(ERROR_MSG.to_owned()))?
2033+
.map_err(|_| vm.new_simple_os_error(ERROR_MSG.to_owned()))?
20342034
.octets()
20352035
.to_vec(),
2036-
_ => return Err(vm.new_os_error("Address family not supported by protocol".to_owned())),
2036+
_ => return Err(vm.new_simple_os_error("Address family not supported by protocol".to_owned())),
20372037
};
20382038
Ok(ip_addr)
20392039
}
@@ -2063,7 +2063,7 @@ mod _socket {
20632063
let cstr = name.to_cstring(vm)?;
20642064
let proto = unsafe { c::getprotobyname(cstr.as_ptr() as _) };
20652065
if proto.is_null() {
2066-
return Err(vm.new_os_error("protocol not found".to_owned()));
2066+
return Err(vm.new_simple_os_error("protocol not found".to_owned()));
20672067
}
20682068
let num = unsafe { (*proto).p_proto };
20692069
Ok(vm.ctx.new_int(num).into())
@@ -2096,14 +2096,14 @@ mod _socket {
20962096
let mut ainfo = res.next().unwrap();
20972097
if res.next().is_some() {
20982098
return Err(vm
2099-
.new_os_error("sockaddr resolved to multiple addresses".to_owned())
2099+
.new_simple_os_error("sockaddr resolved to multiple addresses".to_owned())
21002100
.into());
21012101
}
21022102
match &mut ainfo.sockaddr {
21032103
SocketAddr::V4(_) => {
21042104
if address.len() != 2 {
21052105
return Err(vm
2106-
.new_os_error("IPv4 sockaddr must be 2 tuple".to_owned())
2106+
.new_simple_os_error("IPv4 sockaddr must be 2 tuple".to_owned())
21072107
.into());
21082108
}
21092109
}
@@ -2146,7 +2146,7 @@ mod _socket {
21462146

21472147
let ret = unsafe { c::if_nametoindex(name.as_ptr() as _) };
21482148
if ret == 0 {
2149-
Err(vm.new_os_error("no interface with this name".to_owned()))
2149+
Err(vm.new_simple_os_error("no interface with this name".to_owned()))
21502150
} else {
21512151
Ok(ret)
21522152
}
@@ -2271,7 +2271,7 @@ mod _socket {
22712271
let ainfo = res.next().unwrap()?;
22722272
if res.next().is_some() {
22732273
return Err(vm
2274-
.new_os_error("wildcard resolved to multiple address".to_owned())
2274+
.new_simple_os_error("wildcard resolved to multiple address".to_owned())
22752275
.into());
22762276
}
22772277
return Ok(ainfo.sockaddr);
@@ -2281,7 +2281,7 @@ mod _socket {
22812281
c::AF_INET | c::AF_UNSPEC => {}
22822282
_ => {
22832283
return Err(vm
2284-
.new_os_error("address family mismatched".to_owned())
2284+
.new_simple_os_error("address family mismatched".to_owned())
22852285
.into());
22862286
}
22872287
}

crates/stdlib/src/ssl.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1890,7 +1890,7 @@ mod _ssl {
18901890
// Validate that the file contains DH parameters
18911891
// Read the file and check for DH PARAMETERS header
18921892
let contents =
1893-
std::fs::read_to_string(&path_str).map_err(|e| vm.new_os_error(e.to_string()))?;
1893+
std::fs::read_to_string(&path_str).map_err(|e| vm.new_simple_os_error(e.to_string()))?;
18941894

18951895
if !contents.contains("BEGIN DH PARAMETERS")
18961896
&& !contents.contains("BEGIN X9.42 DH PARAMETERS")
@@ -2258,7 +2258,7 @@ mod _ssl {
22582258
std::io::ErrorKind::NotFound | std::io::ErrorKind::PermissionDenied => {
22592259
e.into_pyexception(vm)
22602260
}
2261-
_ => vm.new_os_error(e.to_string()),
2261+
_ => vm.new_simple_os_error(e.to_string()),
22622262
})?;
22632263

22642264
match self.try_parse_crl(&data) {
@@ -2468,7 +2468,7 @@ mod _ssl {
24682468
// Clear the error so it's only raised once
24692469
*self.deferred_cert_error.write() = None;
24702470
// Raise OSError with the stored error message
2471-
return Err(vm.new_os_error(error_msg));
2471+
return Err(vm.new_simple_os_error(error_msg));
24722472
}
24732473
Ok(())
24742474
}
@@ -2683,10 +2683,10 @@ mod _ssl {
26832683
let py_socket: PyRef<PySocket> = self.sock.clone().try_into_value(vm)?;
26842684
let socket = py_socket
26852685
.sock()
2686-
.map_err(|e| vm.new_os_error(format!("Failed to get socket: {e}")))?;
2686+
.map_err(|e| vm.new_simple_os_error(format!("Failed to get socket: {e}")))?;
26872687

26882688
let timed_out = sock_select(&socket, kind, timeout)
2689-
.map_err(|e| vm.new_os_error(format!("select failed: {e}")))?;
2689+
.map_err(|e| vm.new_simple_os_error(format!("select failed: {e}")))?;
26902690

26912691
Ok(timed_out)
26922692
}
@@ -3923,7 +3923,7 @@ mod _ssl {
39233923
let mut buf = vec![0u8; SSL3_RT_MAX_PLAIN_LENGTH];
39243924
let written = conn
39253925
.write_tls(&mut buf.as_mut_slice())
3926-
.map_err(|e| vm.new_os_error(format!("TLS write failed: {e}")))?;
3926+
.map_err(|e| vm.new_simple_os_error(format!("TLS write failed: {e}")))?;
39273927

39283928
if written == 0 {
39293929
break;
@@ -3976,7 +3976,7 @@ mod _ssl {
39763976
// Process any remaining packets and check peer_has_closed
39773977
let io_state = conn
39783978
.process_new_packets()
3979-
.map_err(|e| vm.new_os_error(format!("Failed to process packets: {e}")))?;
3979+
.map_err(|e| vm.new_simple_os_error(format!("Failed to process packets: {e}")))?;
39803980

39813981
Ok(io_state.peer_has_closed())
39823982
}
@@ -4418,7 +4418,7 @@ mod _ssl {
44184418
let rng = SystemRandom::new();
44194419
let mut buf = vec![0u8; n_usize];
44204420
rng.fill(&mut buf)
4421-
.map_err(|_| vm.new_os_error("Failed to generate random bytes"))?;
4421+
.map_err(|_| vm.new_simple_os_error("Failed to generate random bytes"))?;
44224422
Ok(PyBytesRef::from(vm.ctx.new_bytes(buf)))
44234423
}
44244424

@@ -4437,7 +4437,7 @@ mod _ssl {
44374437
fn _test_decode_cert(path: PyStrRef, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
44384438
// Read certificate file
44394439
let cert_data = std::fs::read(path.as_str()).map_err(|e| {
4440-
vm.new_os_error(format!(
4440+
vm.new_simple_os_error(format!(
44414441
"Failed to read certificate file {}: {}",
44424442
path.as_str(),
44434443
e

crates/vm/src/builtins/int.rs

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -207,23 +207,26 @@ fn inner_truediv(i1: &BigInt, i2: &BigInt, vm: &VirtualMachine) -> PyResult {
207207
impl Constructor for PyInt {
208208
type Args = IntOptions;
209209

210-
fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
210+
fn py_new_ref(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
211211
if cls.is(vm.ctx.types.bool_type) {
212212
return Err(vm.new_type_error("int.__new__(bool) is not safe, use bool.__new__()"));
213213
}
214214

215215
// Optimization: return exact int as-is
216216
if cls.is(vm.ctx.types.int_type) && args.args.len() == 1 && args.kwargs.is_empty() {
217-
if args.args[0].class().is(vm.ctx.types.int_type) {
218-
let mut args = args;
219-
return Ok(args.args.pop().expect("length checked"));
217+
unsafe {
218+
if args.args[0].class().is(vm.ctx.types.int_type) {
219+
let mut args = args;
220+
let int_arg = args.args.pop().expect("length checked");
221+
return Ok(int_arg.downcast_unchecked());
222+
}
220223
}
221224
}
222225

223226
let options: Self::Args = args.bind(vm)?;
224227

225228
let payload = Self::py_new(&cls, options, vm)?;
226-
payload.into_ref_with_type(vm, cls).map(Into::into)
229+
payload.into_ref_with_type(vm, cls)
227230
}
228231

229232
fn py_new(_cls: &Py<PyType>, options: Self::Args, vm: &VirtualMachine) -> PyResult<Self> {

crates/vm/src/exceptions.rs

Lines changed: 12 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1468,43 +1468,32 @@ pub(super) mod types {
14681468
})
14691469
}
14701470

1471-
#[cfg(not(target_arch = "wasm32"))]
14721471
fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
14731472
// We need this method, because of how `CPython` copies `init`
14741473
// from `BaseException` in `SimpleExtendsException` macro.
14751474
// See: `BaseException_new`
14761475
if *cls.name() == *vm.ctx.exceptions.os_error.name() {
1477-
if let Some(error) = Self::optional_new(args.args.to_vec(), vm) {
1478-
return error.to_pyresult(vm);
1476+
let args_vec = args.args.to_vec();
1477+
let len = args_vec.len();
1478+
if (2..=5).contains(&len) {
1479+
let errno = &args_vec[0];
1480+
if let Some(error) = errno
1481+
.downcast_ref::<PyInt>()
1482+
.and_then(|errno| errno.try_to_primitive::<i32>(vm).ok())
1483+
.and_then(|errno| super::errno_to_exc_type(errno, vm))
1484+
.and_then(|typ| vm.invoke_exception(typ.to_owned(), args_vec).ok())
1485+
{
1486+
return error.to_pyresult(vm);
1487+
}
14791488
}
14801489
}
14811490
let payload = Self::py_new(&cls, args, vm)?;
14821491
payload.into_ref_with_type(vm, cls).map(Into::into)
14831492
}
1484-
1485-
#[cfg(target_arch = "wasm32")]
1486-
fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
1487-
let payload = Self::py_new(&cls, args, vm)?;
1488-
payload.into_ref_with_type(vm, cls).map(Into::into)
1489-
}
14901493
}
14911494

14921495
#[pyexception(with(Constructor))]
14931496
impl PyOSError {
1494-
#[cfg(not(target_arch = "wasm32"))]
1495-
fn optional_new(args: Vec<PyObjectRef>, vm: &VirtualMachine) -> Option<PyBaseExceptionRef> {
1496-
let len = args.len();
1497-
if (2..=5).contains(&len) {
1498-
let errno = &args[0];
1499-
errno
1500-
.downcast_ref::<PyInt>()
1501-
.and_then(|errno| errno.try_to_primitive::<i32>(vm).ok())
1502-
.and_then(|errno| super::errno_to_exc_type(errno, vm))
1503-
.and_then(|typ| vm.invoke_exception(typ.to_owned(), args.to_vec()).ok())
1504-
} else {
1505-
None
1506-
}
1507-
}
15081497
#[pyslot]
15091498
#[pymethod(name = "__init__")]
15101499
pub fn slot_init(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {

crates/vm/src/stdlib/builtins.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -488,9 +488,9 @@ mod builtins {
488488
ReadlineResult::Interrupt => {
489489
Err(vm.new_exception_empty(vm.ctx.exceptions.keyboard_interrupt.to_owned()))
490490
}
491-
ReadlineResult::Io(e) => Err(vm.new_os_error(e.to_string())),
491+
ReadlineResult::Io(e) => Err(vm.new_simple_os_error(e.to_string())),
492492
#[cfg(unix)]
493-
ReadlineResult::OsError(num) => Err(vm.new_os_error(num.to_string())),
493+
ReadlineResult::OsError(num) => Err(vm.new_simple_os_error(num.to_string())),
494494
ReadlineResult::Other(e) => Err(vm.new_runtime_error(e.to_string())),
495495
}
496496
} else {

0 commit comments

Comments
 (0)