https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78149

            Bug ID: 78149
           Summary: missing warning on strncpy buffer overflow due to an
                    excessive bound
           Product: gcc
           Version: 7.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: middle-end
          Assignee: unassigned at gcc dot gnu.org
          Reporter: msebor at gcc dot gnu.org
  Target Milestone: ---

GCC makes an effort to detect and diagnose with a "will always overflow
destination buffer" warning calls to bounded checking functions such as strncpy
whose bound is known and in excess of the size of the destination buffer.

But the warning is not issued when the bound whose exact value is not known is
is in an invalid range (e.g., it's negative), or when the size of the
destination object is not known but the bound is obviously too large to be
meaningful (e.g., in excess of SIZE_MAX / 2).

Finally, no warning is issued for non-checking forms of the same functions.

In all these cases issuing a warning would be helpful in preventing the buffer
overflow that inevitably occurs when the code is executed.

$ cat t.c && /home/msebor/build/gcc-git/gcc/xgcc
-B/home/msebor/build/gcc-git/gcc -O2 -S -Wall -Wextra -Wpedantic t.c
char d [3];

char* strncpy (char*, const char*, __SIZE_TYPE__);

void __attribute__ ((noclone, noinline)) f (const char *s)
{
  strncpy (d, s, __SIZE_MAX__);
}

void __attribute__ ((noclone, noinline)) g0 (const char *s)
{
  __builtin___strncpy_chk (d, s, __SIZE_MAX__, __builtin_object_size (d, 1));
}

void __attribute__ ((noclone, noinline)) g1 (int max, const char *s)
{
  if (max > 0)
    max = -max;

  __builtin___strncpy_chk (d, s, max, __builtin_object_size (d, 1));
}

void __attribute__ ((noclone, noinline)) g2 (char *d, const char *s)
{
  __builtin___strncpy_chk (d, s, __SIZE_MAX__, __builtin_object_size (d, 1));
}
t.c: In function ‘g0’:
t.c:12:3: warning: call to __builtin___strncpy_chk will always overflow
destination buffer
   __builtin___strncpy_chk (d, s, __SIZE_MAX__, __builtin_object_size (d, 1));
   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Reply via email to