Skip to content

Commit a96096c

Browse files
authored
[3.14] gh-159739: Handle overlapping buffers in struct.pack_into (GH-159985) (#160484)
`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)
1 parent df0ee5a commit a96096c

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
@@ -2202,7 +2202,7 @@ s_pack_internal(PyStructObject *soself, PyObject *const *args, int offset,
22022202
if (n > code->size)
22032203
n = code->size;
22042204
if (n > 0)
2205-
memcpy(res, p, n);
2205+
memmove(res, p, n);
22062206
} else if (e->format == 'p') {
22072207
Py_ssize_t n;
22082208
int isstring;
@@ -2228,7 +2228,7 @@ s_pack_internal(PyStructObject *soself, PyObject *const *args, int offset,
22282228
n = code->size - 1;
22292229
}
22302230
if (n > 0)
2231-
memcpy(res + 1, p, n);
2231+
memmove(res + 1, p, n);
22322232
if (n > 255)
22332233
n = 255;
22342234
if (n > 0) {

0 commit comments

Comments
 (0)