在 2026-10-27 17:45, Martin Storsjö 写道:
On Wed, 23 Sep 2026, LIU Hao wrote:From 44c8b4fbbccfb56834f511d190d5ea84ed2cc1ef Mon Sep 17 00:00:00 2001 From: LIU Hao <[email protected]> Date: Wed, 23 Sep 2026 19:20:40 +0800 Subject: [PATCH] crt/mingw-aligned-malloc: Check for size overflows in fallback implementation Previously, when an argument for `size` was close to `SIZE_MAX`, calculation of the actual size for `{m,re}alloc()` might wrap around to a small integer, causing `__mingw_aligned_offset_{m,re}alloc()` to return a non-null pointer to memory that wasn't sufficiently large, which could lead to heap corruption. When size calculation overflows, these functions now set `errno` to `ENOMEM` and return a null pointer. Reference: https://sourceforge.net/p/mingw-w64/bugs/1039/ Signed-off-by: LIU Hao <[email protected]> --- mingw-w64-crt/misc/mingw-aligned-malloc.c | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/mingw-w64-crt/misc/mingw-aligned-malloc.c b/mingw-w64-crt/misc/mingw-aligned-malloc.c index 02872c921..3b3286888 100644 --- a/mingw-w64-crt/misc/mingw-aligned-malloc.c +++ b/mingw-w64-crt/misc/mingw-aligned-malloc.c @@ -35,6 +35,7 @@ void * __mingw_aligned_offset_malloc (size_t size, size_t alignment, size_t offset) { void *p0, *p; + size_t total_size; if (NOT_POWER_OF_TWO (alignment)) { @@ -51,7 +52,13 @@ __mingw_aligned_offset_malloc (size_t size, size_t alignment, size_t offset) machine, since malloc is already 8-byte aligned, as long as we enforce alignment >= 8 ...but oh well. */ - p0 = malloc (size + (alignment + GAP (offset) + sizeof (void *))); + if (__builtin_add_overflow (size, alignment + GAP (offset) + sizeof (void *), + &total_size)) + { + errno = ENOMEM; + return ((void *) 0); + } + p0 = malloc (total_size);This should be ok, thanks.I didn't proofread that the semantics around __builtin_add_overflow are correct, but if this passes our CI it should be fine.Although one potential concern (which might not be a blocker) is for how long __builtin_add_overflow has existed in GCC - some of our users like to keep building with very old GCC/binutils. If that is a problem I guess it should be possible to manually check things like "if (size >= __SIZE_MAX__ - (offsets))", but that's more error prone...
The proof is as follows: 1. Right before this hunk, `alignment` is always set to a power of two, which is non-zero. 2. `GAP (offset)` is a modulo of `sizeof (void *)`, so it's <= 7. 3. Therefore `alignment + GAP (offset) + sizeof (void *)` can't overflow for any inputs. 4. Only `size` is a user-supplied parameter. -- Best regards, LIU Hao
OpenPGP_signature.asc
Description: OpenPGP digital signature
_______________________________________________ Mingw-w64-public mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/mingw-w64-public
