This is the mail archive of the
libc-alpha@sourceware.org
mailing list for the glibc project.
Re: [PATCH] [BZ 20628] make mallinfo saturating
- From: Paul Eggert <eggert at cs dot ucla dot edu>
- To: DJ Delorie <dj at redhat dot com>, Carlos O'Donell <carlos at redhat dot com>
- Cc: libc-alpha at sourceware dot org
- Date: Wed, 5 Oct 2016 17:45:01 -0700
- Subject: Re: [PATCH] [BZ 20628] make mallinfo saturating
- Authentication-results: sourceware.org; auth=none
- References: <b69dd7d1-8f35-f278-9435-f8c702844950@cs.ucla.edu> <e1c66c09-a986-dcd8-346a-c6584ffa1085@redhat.com> <xn1szvrice.fsf@greed.delorie.com>
On 10/04/2016 01:04 PM, DJ Delorie wrote:
+/* Saturated add - add ADD to SUM. If the result exceeds the range of
+ "int", set SUM to UINT_MAX instead ((int)-1). Assumes ADD and SUM
+ are positive. The published ABI prevents us from bumping "int" to
+ a larger type. */
+#define SAT_ADD(SUM, ADD) \
+ ({ INTERNAL_SIZE_T tmp = (INTERNAL_SIZE_T)(SUM) + (INTERNAL_SIZE_T)(ADD); SUM = (tmp > UINT_MAX) ? -1 : tmp; })
+
+/* Likewise, but assign ADD to SUM. */
+#define SAT_SET(SUM, ADD) \
+ ({ SUM = ((INTERNAL_SIZE_T)(ADD) > UINT_MAX) ? -1 : (ADD); })
These don't look right, as INTERNAL_SIZE_T might not be wider than int,
which means the + in SAT_ADD will wrap around before SAT_ADD gets a
chance to check for overflow. Also, if SUM is INT_MIN then SAT_ADD(SUM,
1) should set it to INT_MIN + 1, but that doesn't happen when
INTERNAL_SIZE_T is wider than int.
How about something like the following instead?
#define MIN(a, b) ((a)<(b)?(a):(b))
/* Return the sum of the unsigned int A and the nonnegative integer B.
If the result is not representable as an unsigned int, return
UINT_MAX.
B's type may be any integer type. */
#define UINT_SATURATED_ADD(a, b) \
({ unsigned a1 = a, b1 = MIN (b, UINT_MAX), sum1 = a1 + b1; \
sum1 < a1 ? UINT_MAX : sum1; })
and then set 'm->smblks = UINT_SATURATED_ADD (m->sm_blks, nfastblocks);'
and 'm->hblks = UINT_SATURATED_ADD (0, mp_.n_mmaps);', etc.