2012-03-02 Kees Cook <keescook@chromium.org>
[glibc.git] / stdio-common / bug-vfprintf-nargs.c
blob13c66c0486743664060cf7e9ba70ad970b9bf00b
1 /* Test for vfprintf nargs allocation overflow (BZ #13656).
2 Copyright (C) 2012 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Contributed by Kees Cook <keescook@chromium.org>, 2012.
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; if not, write to the Free
18 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
19 02111-1307 USA. */
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <stdint.h>
24 #include <unistd.h>
25 #include <inttypes.h>
26 #include <string.h>
27 #include <signal.h>
29 static int
30 format_failed (const char *fmt, const char *expected)
32 char output[80];
34 printf ("%s : ", fmt);
36 memset (output, 0, sizeof output);
37 /* Having sprintf itself detect a failure is good. */
38 if (sprintf (output, fmt, 1, 2, 3, "test") > 0
39 && strcmp (output, expected) != 0)
41 printf ("FAIL (output '%s' != expected '%s')\n", output, expected);
42 return 1;
44 puts ("ok");
45 return 0;
48 static int
49 do_test (void)
51 int rc = 0;
52 char buf[64];
54 /* Regular positionals work. */
55 if (format_failed ("%1$d", "1") != 0)
56 rc = 1;
58 /* Regular width positionals work. */
59 if (format_failed ("%1$*2$d", " 1") != 0)
60 rc = 1;
62 /* Positional arguments are constructed via read_int, so nargs can only
63 overflow on 32-bit systems. On 64-bit systems, it will attempt to
64 allocate a giant amount of memory and possibly crash, which is the
65 expected situation. Since the 64-bit behavior is arch-specific, only
66 test this on 32-bit systems. */
67 if (sizeof (long int) == 4)
69 sprintf (buf, "%%1$d %%%" PRIdPTR "$d", UINT32_MAX / sizeof (int));
70 if (format_failed (buf, "1 %$d") != 0)
71 rc = 1;
74 return rc;
77 #define TEST_FUNCTION do_test ()
78 #include "../test-skeleton.c"