xref: /freebsd/contrib/pkgconf/tests/api/oom.h (revision 592efe252472a3385acf36b1f49ecf710a7f3d9c)
1 /*
2  * oom.h
3  * Exhaustive allocation-failure test driver, built on the fuzzer/alloc-inject
4  * fault injector.
5  *
6  * SPDX-License-Identifier: pkgconf
7  *
8  * Copyright (c) 2026 pkgconf authors (see AUTHORS).
9  *
10  * Permission to use, copy, modify, and/or distribute this software for any
11  * purpose with or without fee is hereby granted, provided that the above
12  * copyright notice and this permission notice appear in all copies.
13  *
14  * This software is provided 'as is' and without any warranty, express or
15  * implied.  In no event shall the authors be liable for any damages arising
16  * from the use of this software.
17  */
18 
19 #ifndef TEST_API_OOM_H
20 #define TEST_API_OOM_H
21 
22 #include "test-api.h"
23 #include "alloc-inject.h"
24 
25 /*
26  * Exhaustively fail each successive allocation an expression makes until it can
27  * complete with none failing.  Every injected failure must be reported
28  * gracefully (NULL for OOM_TEST_PTR, false for OOM_TEST_BOOL); on the run where
29  * no allocation fails the value succeeds and the loop ends.  Under ASAN this
30  * also asserts each partial-construction error path leaks nothing.
31  */
32 #define OOM_TEST_PTR(objvar, make_expr, free_stmt)	\
33 	do {	\
34 		for (unsigned long _oom_n = 1; ; _oom_n++)	\
35 		{	\
36 			alloc_inject_arm(_oom_n);	\
37 			(objvar) = (make_expr);	\
38 			bool _oom_f = alloc_inject_fired();	\
39 			alloc_inject_disarm();	\
40 			if (!_oom_f) { free_stmt; break; }	\
41 			TEST_ASSERT_NULL(objvar);	\
42 			free_stmt;	\
43 		}	\
44 	} while (0)
45 
46 #define OOM_TEST_BOOL(make_expr)	\
47 	do {	\
48 		for (unsigned long _oom_n = 1; ; _oom_n++)	\
49 		{	\
50 			alloc_inject_arm(_oom_n);	\
51 			bool _oom_ok = (make_expr);	\
52 			bool _oom_f = alloc_inject_fired();	\
53 			alloc_inject_disarm();	\
54 			if (!_oom_f) { TEST_ASSERT_TRUE(_oom_ok); break; }	\
55 			TEST_ASSERT_FALSE(_oom_ok);	\
56 		}	\
57 	} while (0)
58 
59 #endif // TEST_API_OOM_H
60