From 7ff5ab770a6848aa162861cbb39cf312dd2ad779 Mon Sep 17 00:00:00 2001 From: Ben Kimock Date: Sat, 15 Oct 2022 22:17:11 -0400 Subject: [PATCH] Avoid calling slice::from_raw_parts with a null pointer --- newsfragments/2687.fixed.md | 1 + src/impl_/extract_argument.rs | 8 ++++++-- 2 files changed, 7 insertions(+), 2 deletions(-) create mode 100644 newsfragments/2687.fixed.md diff --git a/newsfragments/2687.fixed.md b/newsfragments/2687.fixed.md new file mode 100644 index 00000000000..ec74ebd20e4 --- /dev/null +++ b/newsfragments/2687.fixed.md @@ -0,0 +1 @@ +Fix UB in `FunctionDescription::extract_arguments_fastcall` due to creating slices from a null pointer. diff --git a/src/impl_/extract_argument.rs b/src/impl_/extract_argument.rs index 1ce60c14a90..30eba8b509e 100644 --- a/src/impl_/extract_argument.rs +++ b/src/impl_/extract_argument.rs @@ -221,7 +221,7 @@ impl FunctionDescription { /// Equivalent of `extract_arguments_tuple_dict` which uses the Python C-API "fastcall" convention. /// /// # Safety - /// - `args` must be a pointer to a C-style array of valid `ffi::PyObject` pointers. + /// - `args` must be a pointer to a C-style array of valid `ffi::PyObject` pointers, or NULL. /// - `kwnames` must be a pointer to a PyTuple, or NULL. /// - `nargs + kwnames.len()` is the total length of the `args` array. #[cfg(not(Py_LIMITED_API))] @@ -240,7 +240,11 @@ impl FunctionDescription { // Safety: Option<&PyAny> has the same memory layout as `*mut ffi::PyObject` let args = args as *const Option<&PyAny>; let positional_args_provided = nargs as usize; - let args_slice = std::slice::from_raw_parts(args, positional_args_provided); + let args_slice = if args.is_null() { + &[] + } else { + std::slice::from_raw_parts(args, positional_args_provided) + }; let num_positional_parameters = self.positional_parameter_names.len();