preprocessor: Fix #line overflow check [PR97602]

The preprocessor check for overflow (of linenum_type = unsigned int)
when reading the line number in a #line directive is incomplete; it
checks "reg < reg_prev" which doesn't cover all cases where
multiplying by 10 overflowed.  Fix this by checking for overflow
before rather than after it occurs (using essentially the same logic
as used by e.g. glibc printf when reading width and precision values
from strings).

Bootstrapped with no regressions for x86_64-pc-linux-gnu.

libcpp/
2020-11-27  Joseph Myers  <joseph@codesourcery.com>

	PR preprocessor/97602
	* directives.c (strtolinenum): Check for overflow before it
	occurs.  Correct comment.

gcc/testsuite/
2020-11-27  Joseph Myers  <joseph@codesourcery.com>

	PR preprocessor/97602
	* gcc.dg/cpp/line9.c, gcc.dg/cpp/line10.c: New tests.
This commit is contained in:
Joseph Myers 2020-11-27 22:40:01 +00:00
parent 5dbab7b3f4
commit 9ccffd1298
3 changed files with 16 additions and 6 deletions

View File

@ -0,0 +1,5 @@
/* Test #line overflow checks: bug 97602. */
/* { dg-do preprocess } */
/* { dg-options "-pedantic" } */
#line 4294967296 /* { dg-warning "line number out of range" } */

View File

@ -0,0 +1,5 @@
/* Test #line overflow checks: bug 97602. */
/* { dg-do preprocess } */
/* { dg-options "-pedantic" } */
#line 5000000000 /* { dg-warning "line number out of range" } */

View File

@ -915,12 +915,11 @@ read_flag (cpp_reader *pfile, unsigned int last)
/* Subroutine of do_line and do_linemarker. Convert a number in STR, /* Subroutine of do_line and do_linemarker. Convert a number in STR,
of length LEN, to binary; store it in NUMP, and return false if the of length LEN, to binary; store it in NUMP, and return false if the
number was well-formed, true if not. WRAPPED is set to true if the number was well-formed, true if not. WRAPPED is set to true if the
number did not fit into 'unsigned long'. */ number did not fit into 'linenum_type'. */
static bool static bool
strtolinenum (const uchar *str, size_t len, linenum_type *nump, bool *wrapped) strtolinenum (const uchar *str, size_t len, linenum_type *nump, bool *wrapped)
{ {
linenum_type reg = 0; linenum_type reg = 0;
linenum_type reg_prev = 0;
uchar c; uchar c;
*wrapped = false; *wrapped = false;
@ -929,11 +928,12 @@ strtolinenum (const uchar *str, size_t len, linenum_type *nump, bool *wrapped)
c = *str++; c = *str++;
if (!ISDIGIT (c)) if (!ISDIGIT (c))
return true; return true;
reg *= 10; if (reg > ((linenum_type) -1) / 10)
reg += c - '0';
if (reg < reg_prev)
*wrapped = true; *wrapped = true;
reg_prev = reg; reg *= 10;
if (reg > ((linenum_type) -1) - (c - '0'))
*wrapped = true;
reg += c - '0';
} }
*nump = reg; *nump = reg;
return false; return false;