Skip to content

struct module has undefined behavior when loading bools #125118

Description

@alex

Bug report

Bug description:

cpython/Modules/_struct.c

Lines 489 to 491 in a5fc509

_Bool x;
memcpy((char *)&x, p, sizeof x);
return PyBool_FromLong(x != 0);

Bool values are required to be either 0 or 1, but this memcpy will copy an arbitrary value to it. This produces UBSAN reports like:


Modules/_struct.c:491:28: runtime error: load of value 32, which is not a valid value for type 'bool'
--
  | #0 0x786c2573cc3e in nu_bool cpython3/Modules/_struct.c:491:28
  | #1 0x786c2572fad0 in s_unpack_internal cpython3/Modules/_struct.c:1684:21
  | #2 0x786c2572a1f3 in unpack_impl cpython3/Modules/_struct.c:2399:12
  | #3 0x786c2572a1f3 in unpack cpython3/Modules/clinic/_struct.c.h:295:20
  | #4 0x5c0517b46548 in cfunction_vectorcall_FASTCALL cpython3/Objects/methodobject.c:436:24
  | #5 0x5c0516f89796 in _PyObject_VectorcallTstate cpython3/Include/internal/pycore_call.h:167:11
  | #6 0x5c0516f89796 in object_vacall cpython3/Objects/call.c:819:14
  | #7 0x5c0516f89c88 in PyObject_CallFunctionObjArgs cpython3/Objects/call.c:926:14
  | #8 0x5c0516f4e5c3 in fuzz_struct_unpack cpython3/Modules/_xxtestfuzz/fuzzer.c:125:26
  | #9 0x5c0516f4e5c3 in _run_fuzz cpython3/Modules/_xxtestfuzz/fuzzer.c:569:14
  | #10 0x5c0516f4e5c3 in LLVMFuzzerTestOneInput cpython3/Modules/_xxtestfuzz/fuzzer.c:639:11
  | #11 0x5c0516eb0870 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:614:13
  | #12 0x5c0516e9bae5 in fuzzer::RunOneTest(fuzzer::Fuzzer*, char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:327:6
  | #13 0x5c0516ea157f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:862:9
  | #14 0x5c0516ecc822 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10
  | #15 0x786c27c3c082 in __libc_start_main /build/glibc-LcI20x/glibc-2.31/csu/libc-start.c:308:16
  | #16 0x5c0516e93ccd in _start

(https://oss-fuzz.com/testcase-detail/5186406032080896)

This should probably copy to an integer type that's the same width as _Bool.

CPython versions tested on:

CPython main branch

Operating systems tested on:

No response

Linked PRs

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions