Skip to content

Commit 08fd98b

Browse files
[3.15] gh-159739: Handle overlapping buffers in struct.pack_into (GH-159985) (#160101)
`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 31a7d99) Co-authored-by: Jelle Zijlstra <jelle@openai.com>
1 parent b25122e commit 08fd98b

2 files changed

Lines changed: 4 additions & 2 deletions

File tree

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Avoid undefined behavior when :func:`struct.pack_into` copies a bytearray into
2+
overlapping output.

‎Modules/_struct.c‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2366,7 +2366,7 @@ s_pack_internal(PyStructObject *soself, PyObject *const *args,
23662366
if (n > code->size)
23672367
n = code->size;
23682368
if (n > 0)
2369-
memcpy(res, p, n);
2369+
memmove(res, p, n);
23702370
} else if (strcmp(e->format, "p") == 0) {
23712371
Py_ssize_t n;
23722372
int isstring;
@@ -2392,7 +2392,7 @@ s_pack_internal(PyStructObject *soself, PyObject *const *args,
23922392
n = code->size - 1;
23932393
}
23942394
if (n > 0)
2395-
memcpy(res + 1, p, n);
2395+
memmove(res + 1, p, n);
23962396
if (n > 255)
23972397
n = 255;
23982398
if (n > 0) {

0 commit comments

Comments
 (0)