Search code examples
cglibc

swprintf with -D_FORTIFY_SOURCE=2 throws a buffer overflow


This is the first time I work with wchar and I found something surprising about it. I can't find the answer so I will share my experiences.

I have a simple test program (based on a swprintf example)

#include <stdio.h>
#include <wchar.h>

int main()
{
    wchar_t str_unicode[100] = {0};

    swprintf(str_unicode, sizeof(str_unicode), L"%3d\n", 120);

    fputws(str_unicode, stdout);

    return 0;
}

Compiling it with or without optimization works fine:

gcc -O2 test.c -o test

Running it also works fine:

./test
120

But in my current project, I use -D_FORTIFY_SOURCE=2, and it makes this simple program crash:

gcc -O2 -D_FORTIFY_SOURCE=2 test.c -o test
./test 
*** buffer overflow detected ***: terminated
[1]    28569 IOT instruction (core dumped)  ./test

I have more details with valgrind, and it seems that __swprintf_chk fails.

valgrind ./test    
==30068== Memcheck, a memory error detector
==30068== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==30068== Using Valgrind-3.16.1 and LibVEX; rerun with -h for copyright info
==30068== Command: ./test
==30068== 
*** buffer overflow detected ***: terminated
==30068== 
==30068== Process terminating with default action of signal 6 (SIGABRT): dumping core
==30068==    at 0x48A29E5: raise (in /usr/lib64/libc-2.32.so)
==30068==    by 0x488B8A3: abort (in /usr/lib64/libc-2.32.so)
==30068==    by 0x48E5006: __libc_message (in /usr/lib64/libc-2.32.so)
==30068==    by 0x4975DF9: __fortify_fail (in /usr/lib64/libc-2.32.so)
==30068==    by 0x4974695: __chk_fail (in /usr/lib64/libc-2.32.so)
==30068==    by 0x49752C4: __swprintf_chk (in /usr/lib64/libc-2.32.so)
==30068==    by 0x401086: main (in /home/pierre/workdir/test)
==30068== 
==30068== HEAP SUMMARY:
==30068==     in use at exit: 0 bytes in 0 blocks
==30068==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==30068== 
==30068== All heap blocks were freed -- no leaks are possible
==30068== 
==30068== For lists of detected and suppressed errors, rerun with: -s
==30068== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
[1]    30068 IOT instruction (core dumped)  valgrind ./test

I don't understand why this check fails, the buffer size is more than enough (100) for a single integer. Is it a bug in libc? Or did I do something wrong?

My GCC version is 10.3.1

gcc --version
gcc (GCC) 10.3.1 20210422 (Red Hat 10.3.1-1)

Solution

  • Your problem is the second parameter of the function call -

    swprintf(str_unicode, sizeof(str_unicode), L"%3d\n", 120);

    You passed in the size in bytes of the entire array - i.e. 400 bytes if sizeof(wchar_t) == 4.

    But swprintf's second parameter is the number of cells in the wchar_t array - i.e. 100 cells in your example.

    Change your function call to:

    swprintf(str_unicode, sizeof(str_unicode) / sizeof(wchar_t), L"%3d\n", 120);