buffering: fix signed overflow in next_handle_id()

Not sure what the comment is talking about - signed overflow
is undefined behavior and we don't use -fwrapv or other flags
to make it defined. I can't see how a compiler could abuse it
here, but the overflow is nonetheless easily avoided.

Change-Id: Ibed6d7c0d841db2aa86b9d8ba4c6a0d08c413354
This commit is contained in:
Aidan MacDonald 2022-03-27 00:08:28 +00:00
parent bd444ebd0a
commit 7718b24401

View file

@ -71,8 +71,6 @@
/* amount of data to read in one read() call */ /* amount of data to read in one read() call */
#define BUFFERING_DEFAULT_FILECHUNK (1024*32) #define BUFFERING_DEFAULT_FILECHUNK (1024*32)
#define BUF_HANDLE_MASK 0x7FFFFFFF
enum handle_flags enum handle_flags
{ {
H_CANWRAP = 0x1, /* Handle data may wrap in buffer */ H_CANWRAP = 0x1, /* Handle data may wrap in buffer */
@ -295,12 +293,11 @@ static int next_handle_id(void)
{ {
static int cur_handle_id = 0; static int cur_handle_id = 0;
/* Wrap signed int is safe and 0 doesn't happen */ int next_hid = cur_handle_id + 1;
int next_hid = (cur_handle_id + 1) & BUF_HANDLE_MASK; if (next_hid == INT_MAX)
if (next_hid == 0) cur_handle_id = 0; /* next would overflow; reset the counter */
next_hid = 1; else
cur_handle_id = next_hid;
cur_handle_id = next_hid;
return next_hid; return next_hid;
} }