From d596848fd9a66e3c0c5128f049fb80c85da122b8 Mon Sep 17 00:00:00 2001 From: Jelle Zijlstra Date: Wed, 21 Oct 2026 12:13:16 -0700 Subject: [PATCH] [3.14] gh-159739: Handle overlapping buffers in struct.pack_into (GH-159985) `struct.pack_into()` can use the same bytearray as both the destination and an `s` or `p` value. The copy then passes overlapping regions to `memcpy`, which is undefined in C and can produce platform-dependent results or a sanitizer abort. `memmove` makes the overlapping copy defined. (cherry picked from commit 31a7d994a559a421814ca9e8edfcab21ae4a5b36) Co-authored-by: Jelle Zijlstra --- .../Library/2026-10-20-00-00-00.gh-issue-159739.eb8987.rst | 2 ++ Modules/_struct.c | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2026-10-20-00-00-00.gh-issue-159739.eb8987.rst diff --git a/Misc/NEWS.d/next/Library/2026-10-20-00-00-00.gh-issue-159739.eb8987.rst b/Misc/NEWS.d/next/Library/2026-10-20-00-00-00.gh-issue-159739.eb8987.rst new file mode 100644 index 000000000000000..11c88411bb9125a --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-10-20-00-00-00.gh-issue-159739.eb8987.rst @@ -0,0 +1,2 @@ +Avoid undefined behavior when :func:`struct.pack_into` copies a bytearray into +overlapping output. diff --git a/Modules/_struct.c b/Modules/_struct.c index 788dd39164f68c7..c4afd44cff0e3b6 100644 --- a/Modules/_struct.c +++ b/Modules/_struct.c @@ -2202,7 +2202,7 @@ s_pack_internal(PyStructObject *soself, PyObject *const *args, int offset, if (n > code->size) n = code->size; if (n > 0) - memcpy(res, p, n); + memmove(res, p, n); } else if (e->format == 'p') { Py_ssize_t n; int isstring; @@ -2228,7 +2228,7 @@ s_pack_internal(PyStructObject *soself, PyObject *const *args, int offset, n = code->size - 1; } if (n > 0) - memcpy(res + 1, p, n); + memmove(res + 1, p, n); if (n > 255) n = 255; if (n > 0) {