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

            Bug ID: 92942
           Summary: missing -Wstringop-overflow for allocations with a
                    negative lower bound size
           Product: gcc
           Version: 10.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: ---

In LP64, only the buffer overflow in f() below is diagnosed.  The one in g() is
not because n is determined to be in the anti-range ~[4, 18446744071562067967],
i.e., the size of the object is considered to be between [0, 4] and [INT_MAX,
SIZE_MAX].  (In ILP32 both calls are diagnosed).

The warning should try to determine the type of the argument to malloc() and if
it's signed, assume it's not negative.

$ cat a.c && gcc -D_FORTIFY_SOURCE=2 -O2 -S -Wall a.c
#include <stdlib.h>
#include <string.h>

void* f (unsigned n)
{ 
  if (3 < n)
    n = 3;

  void *p = malloc (n);
  strcpy (p, "12345");   // buffer overflow detected
  return p;
}

void* g (int n)
{
  if (3 < n)
    n = 3;

  void *p = malloc (n);
  strcpy (p, "12345");   // buffer overflow not detected
  return p;
}
In file included from /usr/include/string.h:494,
                 from a.c:2:
In function ‘strcpy’,
    inlined from ‘f’ at a.c:10:3:
/usr/include/bits/string_fortified.h:90:10: warning: ‘__builtin_memcpy’ writing
6 bytes into a region of size between 0 and 3 [-Wstringop-overflow=]
   90 |   return __builtin___strcpy_chk (__dest, __src, __bos (__dest));
      |          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
a.c: In function ‘f’:
a.c:9:13: note: at offset 0 to an object with size at most 3 allocated by
‘malloc’ here
    9 |   void *p = malloc (n);
      |             ^~~~~~~~~~

Reply via email to