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 Jun 30, 2024
1 parent 32f4cfd commit f4dd24c
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 f4dd24c

Please sign in to comment.