1 /* instrumented_alloc.c -- Memory allocation instrumented to fail when
2 requested, for testing purposes.
3 Copyright (C) 2018-2020 Free Software Foundation, Inc.
5 Redistribution and use in source and binary forms, with or without
6 modification, are permitted provided that the following conditions are
9 (1) Redistributions of source code must retain the above copyright
10 notice, this list of conditions and the following disclaimer.
12 (2) Redistributions in binary form must reproduce the above copyright
13 notice, this list of conditions and the following disclaimer in
14 the documentation and/or other materials provided with the
17 (3) The name of the author may not be used to
18 endorse or promote products derived from this software without
19 specific prior written permission.
21 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
22 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
24 DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
25 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
26 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
29 STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
30 IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 POSSIBILITY OF SUCH DAMAGE. */
33 /* Include all the header files of alloc here, to make sure they're not
34 processed when including alloc.c below, such that the redefinitions of malloc
35 and realloc are only effective in alloc.c itself. This does not work for
36 config.h, because it's not wrapped in "#ifndef CONFIG_H\n#define CONFIG_H"
37 and "#endif" but that does not seem to be harmful. */
43 #include <sys/types.h>
46 #include "backtrace.h"
49 extern void *instrumented_malloc (size_t size
);
50 extern void *instrumented_realloc (void *ptr
, size_t size
);
52 #define malloc instrumented_malloc
53 #define realloc instrumented_realloc
58 static uint64_t nr_allocs
= 0;
59 static uint64_t fail_at_alloc
= 0;
61 extern int at_fail_alloc_p (void);
62 extern uint64_t get_nr_allocs (void);
63 extern void set_fail_at_alloc (uint64_t);
66 instrumented_malloc (size_t size
)
70 if (at_fail_alloc_p ())
81 instrumented_realloc (void *ptr
, size_t size
)
87 if (at_fail_alloc_p ())
91 res
= realloc (ptr
, size
);
99 at_fail_alloc_p (void)
101 return fail_at_alloc
== nr_allocs
+ 1;
111 set_fail_at_alloc (uint64_t nr
)