xref: /xnu-8792.61.2/libkern/os/alloc_util.h (revision 42e220869062b56f8d7d0726fd4c88954f87902c)
1 /*
2  * Copyright (c) 2021 Apple Inc. All rights reserved.
3  *
4  * @APPLE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. Please obtain a copy of the License at
10  * http://www.opensource.apple.com/apsl/ and read it before using this
11  * file.
12  *
13  * The Original Code and all software distributed under the License are
14  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18  * Please see the License for the specific language governing rights and
19  * limitations under the License.
20  *
21  * @APPLE_LICENSE_HEADER_END@
22  */
23 
24 #ifndef _OS_ALLOC_UTIL_H
25 #define _OS_ALLOC_UTIL_H
26 
27 #include <sys/cdefs.h>
28 #if defined(__cplusplus) && __cplusplus >= 201103L
29 extern "C++" {
30 #include <os/cpp_util.h>
31 }
32 #endif
33 
34 /*!
35  * @macro os_is_ptr_like
36  *
37  * @abstract
38  * Tell whether the given expression resembles a pointer.
39  *
40  * @discussion
41  * When pointer bounds are enabled, only types that are actually classified
42  * as pointers will be considered pointer-like. Otherwise, any pointer-sized
43  * type will be considered pointer-like.
44  *
45  * @param P             the expression to be checked
46  */
47 #if __has_ptrcheck
48 #define os_is_ptr_like(P) (__builtin_classify_type(P) == 5)
49 #else  /* __has_ptrcheck */
50 #define os_is_ptr_like(P) (sizeof(P) == sizeof(void *))
51 #endif /* __has_ptrcheck */
52 
53 /*!
54  * @macro os_ptr_load_and_erase
55  *
56  * @abstract
57  * Load the value of @c elem into a temporary, set @c elem to NULL, and
58  * return the value.
59  *
60  * @param elem          the pointer whose value will be taken, and which will
61  *                      be set to NULL.
62  */
63 #define os_ptr_load_and_erase(elem) ({                        \
64 	_Static_assert(os_is_ptr_like(elem),                      \
65 	    "elem isn't pointer sized");                          \
66 	__auto_type *__single __eptr = &(elem);                   \
67 	__auto_type __elem = *__eptr;                             \
68 	_Pragma("clang diagnostic push")                          \
69 	_Pragma("clang diagnostic ignored \"-Wold-style-cast\"")  \
70 	*__eptr = (__typeof__(__elem))NULL;                       \
71 	_Pragma("clang diagnostic pop")                           \
72 	__elem;                                                   \
73 })
74 
75 #endif /* _OS_ALLOC_UTIL_H */
76