Fix BZ#23400 (creating temporary files in source tree), and undefined behavior in...
[glibc.git] / stdlib / test-bz22786.c
blobd1aa69106ccf6ac5b0422ded32e041f73f362dcb
1 /* Bug 22786: test for buffer overflow in realpath.
2 Copyright (C) 2018 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <http://www.gnu.org/licenses/>. */
19 /* This file must be run from within a directory called "stdlib". */
21 #include <errno.h>
22 #include <limits.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <sys/stat.h>
28 #include <sys/types.h>
29 #include <support/check.h>
30 #include <support/support.h>
31 #include <support/temp_file.h>
32 #include <support/test-driver.h>
33 #include <libc-diag.h>
35 static int
36 do_test (void)
38 const char *dir = support_create_temp_directory ("bz22786.");
39 const char *lnk = xasprintf ("%s/symlink", dir);
40 const size_t path_len = (size_t) INT_MAX + strlen (lnk) + 1;
42 TEST_VERIFY_EXIT (symlink (".", lnk) == 0);
44 DIAG_PUSH_NEEDS_COMMENT;
45 #if __GNUC_PREREQ (7, 0)
46 /* GCC 7 warns about too-large allocations; here we need such
47 allocation to succeed for the test to work. */
48 DIAG_IGNORE_NEEDS_COMMENT (7, "-Walloc-size-larger-than=");
49 #endif
50 char *path = xmalloc (path_len);
51 DIAG_POP_NEEDS_COMMENT;
53 /* Construct very long path = "/tmp/bz22786.XXXX/symlink/aaaa....." */
54 char *p = mempcpy (path, lnk, strlen (lnk));
55 *(p++) = '/';
56 memset (p, 'a', path_len - (p - path) - 2);
57 p[path_len - (p - path) - 1] = '\0';
59 /* This call crashes before the fix for bz22786 on 32-bit platforms. */
60 p = realpath (path, NULL);
62 if (p != NULL || errno != ENAMETOOLONG)
64 printf ("realpath: %s (%m)", p);
65 return EXIT_FAILURE;
68 /* Cleanup. */
69 unlink (lnk);
71 return 0;
74 #define TEST_FUNCTION do_test
75 #include <support/test-driver.c>