Skip to content

Commit 31a7d99

Browse files
authored
gh-159739: Handle overlapping buffers in struct.pack_into (#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.
1 parent 080fc54 commit 31a7d99

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
@@ -2409,7 +2409,7 @@ s_pack_internal(PyStructObject *soself, PyObject *const *args,
24092409
if (n > code->size)
24102410
n = code->size;
24112411
if (n > 0)
2412-
memcpy(res, p, n);
2412+
memmove(res, p, n);
24132413
} else if (strcmp(e->format, "p") == 0) {
24142414
Py_ssize_t n;
24152415
int isstring;
@@ -2435,7 +2435,7 @@ s_pack_internal(PyStructObject *soself, PyObject *const *args,
24352435
n = code->size - 1;
24362436
}
24372437
if (n > 0)
2438-
memcpy(res + 1, p, n);
2438+
memmove(res + 1, p, n);
24392439
if (n > 255)
24402440
n = 255;
24412441
if (n > 0) {

0 commit comments

Comments
 (0)