1 /* Test to verify that realpath() doesn't cause false positives due
2 to GCC attribute malloc.
3
4 Test failure exposes the presence of the attribute in the following
5 declaration:
6
7 __attribute__ ((__malloc__ (free, 1))) char*
8 realpath (const char *, char *);
9
10 Copyright (C) 2021-2022 Free Software Foundation, Inc.
11 This file is part of the GNU C Library.
12
13 The GNU C Library is free software; you can redistribute it and/or
14 modify it under the terms of the GNU Lesser General Public
15 License as published by the Free Software Foundation; either
16 version 2.1 of the License, or (at your option) any later version.
17
18 The GNU C Library is distributed in the hope that it will be useful,
19 but WITHOUT ANY WARRANTY; without even the implied warranty of
20 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 Lesser General Public License for more details.
22
23 You should have received a copy of the GNU Lesser General Public
24 License along with the GNU C Library; if not, see
25 <https://www.gnu.org/licenses/>. */
26
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <malloc.h>
30
31 #if defined __GNUC__ && __GNUC__ >= 11
32 /* Turn GCC -Wmismatched-dealloc warnings into errors to expose false
33 positives. */
34 # pragma GCC diagnostic push
35 # pragma GCC diagnostic error "-Wmismatched-dealloc"
36
37 /* Associate dealloc as the only deallocator suitable for pointers
38 returned from alloc.
39 GCC automatically disables inlining of allocator and deallocator
40 functions marked with the argument form of attribute malloc but
41 it doesn't hurt to disable it explicitly. */
42 __attribute ((noipa)) void dealloc (void *);
43 __attribute ((malloc (dealloc, 1))) char* alloc (void);
44 #endif
45
dealloc(void * p)46 void dealloc (void *p)
47 {
48 free (p);
49 }
50
alloc(void)51 char* alloc (void)
52 {
53 return (char *)malloc (8);
54 }
55
56 static int
do_test(void)57 do_test (void)
58 {
59 char *resolved_path = alloc ();
60 char *ret = realpath ("/", resolved_path);
61 dealloc (ret);
62
63 resolved_path = alloc ();
64 ret = realpath ("/", resolved_path);
65 dealloc (resolved_path);
66
67 /* The following should emit a warning (but doesn't with GCC 11):
68 resolved_path = alloc ();
69 ret = realpath ("/", resolved_path);
70 free (ret); // expect -Wmismatched-dealloc
71 */
72
73 return 0;
74 }
75
76 #if defined __GNUC__ && __GNUC__ >= 11
77 /* Restore -Wmismatched-dealloc setting. */
78 # pragma GCC diagnostic pop
79 #endif
80
81 #define TEST_FUNCTION do_test ()
82 #include "../test-skeleton.c"
83