[Bug string/31332] Improve detection of buffer overflow at compile-time with FORTIFY_SOURCE

fweimer at redhat dot com sourceware-bugzilla@sourceware.org
Mon Feb 5 15:07:42 GMT 2024


https://sourceware.org/bugzilla/show_bug.cgi?id=31332

--- Comment #2 from Florian Weimer <fweimer at redhat dot com> ---
Comment on attachment 15350
  --> https://sourceware.org/bugzilla/attachment.cgi?id=15350
Test case with buffer overflow in memcpy call

Current GCC already warns about this:

#include <string.h>

__attribute__ ((weak))
void use (void *)
{
}

int main() {
  char buffer[5];
  char *src = "Hi guys";

  memcpy(buffer, src, strlen(src));
  use(buffer);

  return 0;
}

memcpy.c: In function ‘main’:
memcpy.c:12:3: warning: ‘memcpy’ forming offset [5, 6] is out of the bounds [0,
5] of object ‘buffer’ with type ‘char[5]’ [-Warray-bounds=]
   12 |   memcpy(buffer, src, strlen(src));
      |   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
memcpy.c:9:8: note: ‘buffer’ declared here
    9 |   char buffer[5];
      |        ^~~~~~

This can be turned into an error with -Werror=array-bounds. The advantage is
that GCC can provide some helpful context about buffer sizes and offsets, which
we can do from a header with an inline wrapper function.

The issue is that with your original test case is that the memcpy call is
already gone at the point when such warnings are generated.

(What's missing is a GCC compilation mode where operations on a pointer that
cannot be bounds-checked fail to compile, but to be useful, that would have to
cover pointer arithmetic as well, so a header-only solution doesn't help with
that, either.)

-- 
You are receiving this mail because:
You are on the CC list for the bug.


More information about the Glibc-bugs mailing list