2 * Copyright (c) 2018 Apple Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
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
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.
21 * @APPLE_LICENSE_HEADER_END@
26 * Non-standard, Darwin-specific additions to the stdlib(3) family of APIs.
28 * The os_malloc() and os_strdup() routines are wrappers to be used for small,
29 * fixed-size allocations, the assumption being that such allocation should
30 * always succeed absent other critical problems. Thus, if the requested size is
31 * is a compile-time constant, the return value is asserted to be non-NULL.
32 * Otherwise, for sizes that are not known at compile-time, the implementations
33 * loop until the allocation succeeds, assuming the failure to be due to
34 * transient resource shortages. The implementation will not loop if the program
35 * has not become multi-threaded, under the assertion that there would be no
36 * point since no other thread could possibly free up resources for the calling
37 * thread to use. Thus, in a single-threaded program, all allocations will
38 * be treated like small, fixed-size allocations and be expected to succeed.
40 * These wrappers should not be used for large allocations whose bounds cannot
41 * be determined at compile-time. For such allocations, malloc(3), calloc(3), et
42 * al. (with appropriate error handling) are the appropriate interfaces.
44 #ifndef __DARWIN_STDLIB_H
45 #define __DARWIN_STDLIB_H
49 #include <os/assumes.h>
51 #include <dispatch/private.h>
55 #include <sys/types.h>
56 #include <sys/cdefs.h>
57 #include <sys/syslimits.h>
66 * @function __os_temporary_resource_shortage
67 * A function whose purpose is to appear in stack traces to indicate transient
68 * resource shortage conditions. Do not call.
70 DARWIN_API_AVAILABLE_20170407
71 OS_EXPORT OS_NOT_TAIL_CALLED
73 __os_temporary_resource_shortage(void);
77 * Internal inline definitions.
79 DARWIN_API_AVAILABLE_20170407
80 OS_ALWAYS_INLINE OS_WARN_RESULT OS_MALLOC
__alloc_size(1)
82 _os_malloc_loop(size_t size
)
85 while (!(ptr
= malloc(size
))) {
86 __os_temporary_resource_shortage();
91 DARWIN_API_AVAILABLE_20170407
92 OS_ALWAYS_INLINE OS_WARN_RESULT OS_MALLOC
__alloc_size(1)
94 _os_malloc_known(size_t size
)
99 DARWIN_API_AVAILABLE_20170407
100 OS_ALWAYS_INLINE OS_WARN_RESULT OS_MALLOC
__alloc_size(1, 2)
102 _os_calloc_loop(size_t cnt
, size_t size
)
105 while (!(ptr
= calloc(cnt
, size
))) {
106 __os_temporary_resource_shortage();
111 DARWIN_API_AVAILABLE_20170407
112 OS_ALWAYS_INLINE OS_WARN_RESULT OS_MALLOC
__alloc_size(1, 2)
114 _os_calloc_known(size_t cnt
, size_t size
)
116 return calloc(cnt
, size
);
119 DARWIN_API_AVAILABLE_20170407
120 OS_ALWAYS_INLINE OS_WARN_RESULT OS_MALLOC
122 _os_strdup_loop(const char *str
)
125 while (!(ptr
= strdup(str
))) {
126 __os_temporary_resource_shortage();
131 DARWIN_API_AVAILABLE_20170407
132 OS_ALWAYS_INLINE OS_WARN_RESULT OS_MALLOC
134 _os_strdup_known(const char *str
)
139 #define __os_requires_experimental_libtrace \
140 _Pragma("GCC error \"requires OS_CRASH_ENABLE_EXPERIMENTAL_LIBTRACE\"")
143 * @function os_malloc
144 * Wrapper around malloc(3) which guarantees that the allocation succeeds.
147 * The size of the allocation.
150 * A new object that the caller is responsible for free(3)ing.
152 * This routine will never return NULL. If the size of the allocation is known
153 * at compile-time, a failure to allocate the object will abort the caller. If
154 * the size is not known at compile-time, the routine will retry until it is
157 #if defined(OS_CRASH_ENABLE_EXPERIMENTAL_LIBTRACE)
158 #define os_malloc(__size) ({ \
160 size_t _size = (__size); \
161 if (__builtin_constant_p(__size) || !_dispatch_is_multithreaded()) { \
162 ptr = _os_malloc_known(_size); \
163 os_assert_malloc("known-constant allocation", ptr, _size); \
165 ptr = _os_malloc_loop(_size); \
170 #define os_malloc(__size) __os_requires_experimental_libtrace
174 * @function os_calloc
175 * Wrapper around calloc(3) which guarantees that the allocation succeeds.
178 * The number of elements to allocate.
181 * The size of each element to allocate.
184 * A new object that the caller is responsible for free(3)ing.
186 * This routine will never return NULL. If the size of the allocation is known
187 * at compile-time, a failure to allocate the object will abort the caller. If
188 * the size is not known at compile-time, the routine will retry until it is
191 #if defined(OS_CRASH_ENABLE_EXPERIMENTAL_LIBTRACE)
192 #define os_calloc(__cnt, __size) ({ \
194 size_t _size = (__size); \
195 size_t _cnt = (__cnt); \
196 if ((__builtin_constant_p(__cnt) && __builtin_constant_p(__size)) || \
197 !_dispatch_is_multithreaded()) { \
198 ptr = _os_calloc_known(_cnt, _size); \
199 os_assert_malloc("known-constant allocation", ptr, _size); \
201 ptr = _os_calloc_loop(_cnt, _size); \
206 #define os_calloc(__size) __os_requires_experimental_libtrace
210 * @function os_strdup
211 * A wrapper around strdup(3) which guarantees that the string duplication
215 * The string to duplicate.
218 * A new string that the caller is responsible for free(3)ing.
220 * This routine will never return NULL. If the given string is a compile-time
221 * constant, a failure to duplicate it will abort the caller. If the string is
222 * not a compile-time constant, the routine will retry until it is successful.
225 * strdup(3) is found in the string(3) API family, but this interface is in the
226 * stdlib.h header because its semantic changes are solely related to the manner
227 * in which memory is allocated.
229 #if defined(OS_CRASH_ENABLE_EXPERIMENTAL_LIBTRACE)
230 #define os_strdup(__str) ({ \
232 const char *_str = (__str); \
233 if (__builtin_constant_p(__str) || !_dispatch_is_multithreaded()) { \
234 ptr = _os_strdup_known(_str); \
235 os_assert_malloc("known-constant allocation", ptr, strlen(_str)); \
237 ptr = _os_strdup_loop(_str); \
242 #define os_strdup(__size) __os_requires_experimental_libtrace
246 * @function os_setflag
247 * Sets the given flag in a manner which is compatible with strongly-typed
251 * The bitfield in which to set the flag.
257 * The result of setting {@link _f} in {@link _bf}.
259 #define os_setflag(_bf, _f) (typeof(_bf))((_bf) & (_f))
262 * @function os_clrflag
263 * Clears the given flag in a manner which is compatible with strongly-typed
267 * The bitfield in which to clear the flag.
273 * The result of clearing {@link _f} from {@link _bf}.
276 * clrbit() will produce errors when given types smaller than a pointer such as
277 * int because it casts to char *; thus this implementation is required to deal
278 * properly with flags defined via {@link OS_OPTIONS} or similar.
280 #define os_clrflag(_bf, _f) (typeof(_bf))((_bf) & (typeof(_bf))(~(_f)))
283 * @function switch_posix
284 * Macro which expands to a switch() statement for handling both the success
285 * case as well as errno values set by POSIX and POSIX-y APIs that return -1 and
291 * switch_posix (ret) {
296 * // interrupted system call
299 * // bad file descriptor
304 * This statement cannot be used with APIs that return positive values on
307 #define switch_posix(_ret) if ((_ret) < 0 || (errno = 0, 1)) switch (errno)
310 * @function size_unsigned
311 * Converts a signed size quantity into an unsigned size quantity after
312 * verifying the former can be represented as the latter.
315 * The signed size quantity.
318 * The unsigned representation of {@link ss}.
321 * This routine is useful for passing a signed value (such as the size of a file
322 * from a stat(2) structure) into a routine which accepts unsigned input
325 OS_ALWAYS_INLINE OS_WARN_RESULT
327 size_unsigned(ssize_t ss
)
330 os_crash("value not representable as size_t");
336 * @function size_signed
337 * Converts an unsigned size quantity into a signed size quantity after
338 * verifying the former can be represented as the latter.
341 * The unsigned size quantity.
344 * The signed representation of {@link un}.
347 * This routine is useful for comparing an unsigned value (such as a number of
348 * bytes) to the result of a routine which returns a signed type but only ever
349 * returns a negative number in the event of an error (e.g. read(2)).
351 OS_ALWAYS_INLINE OS_WARN_RESULT
352 static inline ssize_t
353 size_signed(size_t un
)
355 if (un
> SSIZE_MAX
) {
356 os_crash("value not representable as ssize_t");
362 * @function os_localtime_file
363 * A routine to generate a time stamp that is suitable for embedding in a file
367 * A pointer to a buffer where the resulting time stamp will be stored.
370 * The resulting time stamp will not include characters which require escaping
371 * in shells, such as spaces. The current implementation format is
373 * YYYY-MM-DD_HH.MM.SS.us
377 * 2017-04-24_12.45.15.045609
379 DARWIN_API_AVAILABLE_20170407
382 os_localtime_file(char buff
[static 32]);
385 * @function os_simple_hash
386 * An implementation of a simple non-cryptographic hashing algorithm.
389 * A pointer to the buffer to hash.
392 * The length of the buffer.
395 * The hashed value of the input.
398 * This routine is meant to be used as a simple way to obtain a value that can
399 * be used to choose a bucket in a simple hash table. Do not attach security
400 * assumptions to the output of this routine. Do not assume that the computed
401 * hash is stable between hosts, OS versions, or boot sessions.
403 DARWIN_API_AVAILABLE_20170407
404 OS_EXPORT OS_NONNULL1
406 os_simple_hash(const void *buff
, size_t len
);
409 * @function os_simple_hash_with_seed
410 * A seeded variant of os_simple_hash.
413 * A pointer to the buffer to hash.
416 * The length of the buffer.
419 * The seed value for the hash.
422 * The hashed value of the input.
425 * Usually, hashing the same buffer with different seeds will produce
426 * different hash values.
427 * All the same considerations of {@link os_simple_hash} apply.
429 DARWIN_API_AVAILABLE_20181020
430 OS_EXPORT OS_NONNULL1
432 os_simple_hash_with_seed(const void *buff
, size_t len
, uint64_t seed
);
435 * @function os_simple_hash_string
436 * An implementation of a simple non-cryptographic hashing algorithm.
439 * A pointer to the null-terminated string to hash.
442 * The hashed value of the input.
445 * This routine is the moral equivalent of a call to
447 * os_simple_hash(buff, strlen(buff));
449 * All the same considerations of {@link os_simple_hash} apply.
451 DARWIN_API_AVAILABLE_20170407
452 OS_EXPORT OS_NONNULL1
454 os_simple_hash_string(const char *string
);
457 * @function os_simple_hash_string_with_seed
458 * A seeded variant of os_simple_hash_string.
461 * A pointer to the null-terminated string to hash.
464 * The hashed value of the input.
467 * Usually, hashing the same string with different seeds will produce
468 * different hash values.
469 * All the same considerations of {@link os_simple_hash_string} apply.
471 DARWIN_API_AVAILABLE_20181020
472 OS_EXPORT OS_NONNULL1
474 os_simple_hash_string_with_seed(const char *string
, uint64_t seed
);
477 * @function realpath_np
478 * Obtains a fully-resolved representation of the path to the file represented
479 * by the given descriptor.
482 * The file descriptor whose path is to be obtained.
485 * The buffer in which to write the path.
488 * On success, zero is returned. Otherwise, the implementation may return any
489 * error that can be returned by fcntl(2).
491 DARWIN_API_AVAILABLE_20180727
492 OS_EXPORT OS_WARN_RESULT
494 realpath_np(os_fd_t fd
, char buff
[static PATH_MAX
]);
497 * @function memdup_np
498 * Copies the given range of bytes into a new allocation.
501 * Upon successful return, a pointer to a new allocation which has had the given
502 * source bytes copied into it. The caller is responsible for calling free(3) on
503 * this object when it is no longer needed.
509 * The number of bytes to copy.
512 * On success, zero is returned. Otherwise, the implementation may return any
513 * error that can be returned by malloc(3).
515 DARWIN_API_AVAILABLE_20190830
516 OS_EXPORT OS_WARN_RESULT OS_NONNULL1 OS_NONNULL2
518 memdup_np(void **_new
, const void *src
, size_t len
);
521 * @function memdup2_np
522 * Variant of {@link memdup_np} which guarantees that memory duplication will
523 * either succeed or not return (terminating the caller).
529 * The number of bytes to copy.
532 * On success, a pointer to the new allocation which has had the given source
533 * bytes copied into it. The caller is responsible for calling free(3) on this
534 * object when it is no longer needed.
536 DARWIN_API_AVAILABLE_20190830
537 OS_EXPORT OS_WARN_RESULT OS_MALLOC OS_NONNULL1
539 memdup2_np(const void *src
, size_t len
);
543 #endif // __DARWIN_STDLIB_H