From ba2e17db6f6f80f01977525cb9cb0d04518be163 Mon Sep 17 00:00:00 2001 From: Bruno Haible Date: Fri, 1 Dec 2023 19:39:26 +0100 Subject: [PATCH] obstack: Avoid undefined behaviour. Reported by Alexey Palienko in . * lib/obstack.in.h: Include . (__BPTR_ALIGN): Remove macro. (__PTR_ALIGN): For the optimized case, compute the alignment through uintptr_t, instead of computing NULL + something. --- ChangeLog | 10 ++++++++++ lib/obstack.h | 24 ++++++++++-------------- 2 files changed, 20 insertions(+), 14 deletions(-) diff --git a/ChangeLog b/ChangeLog index e53cfffcb6..49fdf2c845 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,13 @@ +2023-12-01 Bruno Haible + + obstack: Avoid undefined behaviour. + Reported by Alexey Palienko in + . + * lib/obstack.h: Include . + (__BPTR_ALIGN): Remove macro. + (__PTR_ALIGN): For the optimized case, compute the alignment through + uintptr_t, instead of computing NULL + something. + 2023-12-01 Bruno Haible sethostname tests: Fix a compilation error on FreeBSD 14.0. diff --git a/lib/obstack.h b/lib/obstack.h index 1e66e4d4c8..14a56e7a17 100644 --- a/lib/obstack.h +++ b/lib/obstack.h @@ -108,6 +108,7 @@ #endif #include /* For size_t and ptrdiff_t. */ +#include /* For uintptr_t. */ #include /* For __GNU_LIBRARY__, and memcpy. */ #if __STDC_VERSION__ < 199901L || defined __HP_cc @@ -131,20 +132,15 @@ /* If B is the base of an object addressed by P, return the result of aligning P to the next multiple of A + 1. B and P must be of type - char *. A + 1 must be a power of 2. */ - -#define __BPTR_ALIGN(B, P, A) ((B) + (((P) - (B) + (A)) & ~(A))) - -/* Similar to __BPTR_ALIGN (B, P, A), except optimize the common case - where pointers can be converted to integers, aligned as integers, - and converted back again. If ptrdiff_t is narrower than a - pointer (e.g., the AS/400), play it safe and compute the alignment - relative to B. Otherwise, use the faster strategy of computing the - alignment relative to 0. */ - -#define __PTR_ALIGN(B, P, A) \ - __BPTR_ALIGN (sizeof (ptrdiff_t) < sizeof (void *) ? (B) : (char *) 0, \ - P, A) + char *. A + 1 must be a power of 2. + If ptrdiff_t is narrower than a pointer (e.g., the AS/400), play it + safe and compute the alignment relative to B. Otherwise, use the + faster strategy of computing the alignment through uintptr_t. */ + +#define __PTR_ALIGN(B, P, A) \ + (sizeof (ptrdiff_t) < sizeof (void *) \ + ? (B) + (((P) - (B) + (A)) & ~(A)) \ + : (P) + ((- (uintptr_t) (P)) & (A))) #ifndef __attribute_pure__ # define __attribute_pure__ _GL_ATTRIBUTE_PURE -- 2.39.5