Skip to content

Commit

Permalink
Avoid undefined behavior when parsing bounds.
Browse files Browse the repository at this point in the history
Signed integer overflow is undefined behavior, so use unsigned long
internally while parsing numbers, and substitute INT_MAX at the end if
overflow occurred.
  • Loading branch information
dag-erling committed Apr 26, 2024
1 parent 6522653 commit 8dbc127
Showing 1 changed file with 20 additions and 7 deletions.
27 changes: 20 additions & 7 deletions lib/tre-parse.c
Original file line number Diff line number Diff line change
Expand Up @@ -576,22 +576,35 @@ tre_parse_bracket(tre_parse_ctx_t *ctx, tre_ast_node_t **result)
}


/* Parses a positive decimal integer. Returns -1 if the string does not
contain a valid number. */
/* Parses a positive decimal integer capped at INT_MAX. Returns -1 if the
string does not contain a valid number. */
static int
tre_parse_int(const tre_char_t **regex, const tre_char_t *regex_end)
{
int num = -1;
unsigned long num = 0;
int overflow = 0;
const tre_char_t *r = *regex;
while (r < regex_end && *r >= L'0' && *r <= L'9')
{
if (num < 0)
num = 0;
num = num * 10 + *r - L'0';
if (!overflow)
{
if (num * 10 + *r - L'0' < num)
{
overflow = 1;
}
else
{
num = num * 10 + *r - L'0';
if (num > INT_MAX)
overflow = 1;
}
}
r++;
}
if (r == *regex)
return -1;
*regex = r;
return num;
return overflow ? INT_MAX : (int)num;
}


Expand Down

0 comments on commit 8dbc127

Please sign in to comment.