Skip to content

Commit e69b349

Browse files
jeongseok-metawjakob
authored andcommitted
Fix UB: memcpy requires valid pointers even with count=0 (#1198)
* Fix UB: memcpy requires valid pointers even with count=0 ASAN detected undefined behavior in nb_bound_method_vectorcall where memcpy was called with a potentially NULL args_in pointer. Root Cause: Per C standard section 7.24.1 paragraph 2, pointer arguments to memcpy must have valid values even when copying zero bytes. NULL is not a valid pointer value. When args_in can be NULL: According to Python vectorcall protocol PEP 590, when a bound method is called with zero positional arguments, the args_in pointer may be NULL. This is valid Python behavior - Python does not allocate an array when there are no arguments to pass. Why the guard checks size > 1: The code calculates size = nargs + 1 for the implicit self argument, then copies size - 1 elements from args_in. When nargs = 0: - size = 1 - We attempt to copy size - 1 = 0 elements - Even though copying 0 bytes, calling memcpy with NULL violates C standard Fix: Guard the memcpy to only execute when there are actual arguments to copy, i.e., when size > 1 and args_in is not NULL. This resolves ASAN failures in projects using batch array operations with nanobind bindings, where methods are frequently called with no arguments. * Remove redundant NULL check per code review
1 parent ab3456f commit e69b349

File tree

1 file changed

+2
-1
lines changed

1 file changed

+2
-1
lines changed

src/nb_func.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1096,7 +1096,8 @@ static PyObject *nb_bound_method_vectorcall(PyObject *self,
10961096
alloc = true;
10971097
}
10981098

1099-
memcpy(args + 1, args_in, sizeof(PyObject *) * (size - 1));
1099+
if (size)
1100+
memcpy(args + 1, args_in, sizeof(PyObject *) * (size - 1));
11001101
}
11011102

11021103
args[0] = mb->self;

0 commit comments

Comments
 (0)