Line data Source code
1 : /*
2 : MIT License
3 :
4 : Copyright (c) 2026 - A bunch of nerds
5 :
6 : Permission is hereby granted, free of charge, to any person obtaining a copy
7 : of this software and associated documentation files (the "Software"), to deal
8 : in the Software without restriction, including without limitation the rights
9 : to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 : copies of the Software, and to permit persons to whom the Software is
11 : furnished to do so, subject to the following conditions:
12 :
13 : The above copyright notice and this permission notice shall be included in all
14 : copies or substantial portions of the Software.
15 :
16 : THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 : IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 : FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 : AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 : LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 : OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 : SOFTWARE.
23 : */
24 :
25 : #include <common.h>
26 : #include <internal/cgrowbuf.h>
27 : #include <internal/cpow2.h>
28 : #include <internal/cprocsintern.h>
29 : #include <internal/test_helpers/common.h>
30 : #include <internal/test_helpers/cprocsintern.h>
31 : #include <limits.h>
32 : #include <stdatomic.h>
33 : #include <time.h>
34 :
35 : // Give the version of the loaded library, as a number and as a string. A
36 : // program calls them to learn which release the dynamic loader picked, since
37 : // the macros only tell the version of the header it compiled with.
38 1 : unsigned int ccol_version(void) { return CCOL_VERSION_NUMBER; }
39 :
40 3 : const char *ccol_version_string(void) { return CCOL_VERSION_STRING; }
41 :
42 : // CCOL_COMMON_TSAN is set in a ThreadSanitizer build (GCC or Clang), where the
43 : // child of fork() annotates the rwlock it initializes again.
44 : #if defined(__SANITIZE_THREAD__)
45 : #define CCOL_COMMON_TSAN 1
46 : #elif defined(__has_feature)
47 : #if __has_feature(thread_sanitizer)
48 : #define CCOL_COMMON_TSAN 1
49 : #endif
50 : #endif
51 : #if defined(CCOL_COMMON_TSAN)
52 : int __tsan_mutex_pre_unlock(void *addr, unsigned flags);
53 : void __tsan_mutex_post_unlock(void *addr, unsigned flags);
54 : #endif
55 :
56 : // Initializes again, in the child of fork(), an rwlock that a prepare handler
57 : // write-locked. The fork child handlers of every module need it, because a
58 : // plain unlock in the child doesn't release such a lock. lock points at the
59 : // rwlock (void * because strict C11 has no rwlock type). Gives 0 or an error
60 : // number. ThreadSanitizer doesn't model the re-init, so in a TSan build we
61 : // first tell it the write lock is released (the two unlock annotations with no
62 : // unlock between them); the init then makes a new lock in its model too.
63 0 : int ccol__rw_lock_reinit_in_child_impl(void *lock) {
64 0 : ccol__rw_lock *rw = lock;
65 : #if defined(CCOL_COMMON_TSAN)
66 : (void)__tsan_mutex_pre_unlock(rw, 0);
67 : __tsan_mutex_post_unlock(rw, 0);
68 : #endif
69 0 : memset(rw, 0, sizeof(*rw));
70 0 : return ccol__rw_lock_init(*rw);
71 : }
72 :
73 : // Gives the smallest power of two that is >= input, or ccol_invalid_size when
74 : // it doesn't fit in a size_t. The containers use it to round a requested
75 : // capacity to the power-of-two sizes they grow by. One count of leading zeros
76 : // of input - 1 gives the exponent, which needs unsigned long as wide as size_t;
77 : // that holds on every target we support (LP64 and ILP32).
78 : _Static_assert(sizeof(unsigned long) == sizeof(size_t),
79 : "the power-of-two rounding needs size_t as wide as long");
80 22723 : size_t ccol__find_nearest_gte_power_of_two(size_t input) {
81 22723 : if (input <= 1) return 1;
82 22513 : unsigned long below = (unsigned long)(input - 1);
83 22513 : int bits = (int)(sizeof(unsigned long) * CHAR_BIT) - __builtin_clzl(below);
84 22513 : if (bits >= (int)(sizeof(unsigned long) * CHAR_BIT)) return ccol_invalid_size;
85 22504 : return (size_t)1 << bits;
86 : }
87 :
88 : // Growable byte buffer.
89 : //
90 : // Initializes b as an empty string in a 256-byte buffer allocated through mp.
91 : // The serializers and the logger's record builder start their output buffer
92 : // with it. On a failed allocation the buffer is NULL and b->oom is set, which
93 : // every later append respects.
94 260231 : void ccol_growbuf_init(ccol_growbuf *b, ccol_memmgmt_procs *mp) {
95 260231 : b->m_procs = mp;
96 260231 : b->buf = ccol__mem_alloc(mp, 256);
97 260229 : b->len = 0;
98 260229 : b->cap = b->buf ? 256 : 0;
99 260229 : b->oom = b->buf ? false : true;
100 260229 : if (b->buf) b->buf[0] = '\0';
101 260229 : }
102 :
103 : // Initializes b like ccol_growbuf_init, but with room for hint bytes plus the
104 : // NUL (64 at least), for a caller that knows roughly how much it will write and
105 : // wants to skip the growth steps. A failed allocation, or a hint of SIZE_MAX
106 : // (refused before hint + 1 can wrap to a tiny buffer), leaves the buffer NULL
107 : // and sets b->oom.
108 1796 : void ccol_growbuf_init_hint(ccol_growbuf *b, ccol_memmgmt_procs *mp,
109 : size_t hint) {
110 1796 : b->m_procs = mp;
111 1796 : b->len = 0;
112 1796 : if (hint == SIZE_MAX) {
113 1 : b->buf = NULL;
114 1 : b->cap = 0;
115 1 : b->oom = true;
116 1 : return;
117 : }
118 1795 : size_t cap = hint + 1 > 64 ? hint + 1 : 64;
119 1795 : b->buf = ccol__mem_alloc(mp, cap);
120 1795 : b->cap = b->buf ? cap : 0;
121 1795 : b->oom = b->buf ? false : true;
122 1795 : if (b->buf) b->buf[0] = '\0';
123 : }
124 :
125 : // Doubles the capacity of b until it holds needed bytes, for
126 : // ccol_growbuf_append_slow. It does nothing when b->oom is set, and sets b->oom
127 : // when the realloc fails or the size would overflow a size_t, leaving the old
128 : // buffer in place.
129 1435 : static void growbuf_grow(ccol_growbuf *b, size_t needed) {
130 1435 : if (b->oom) return;
131 1435 : size_t new_cap =
132 1435 : b->cap ? (b->cap > SIZE_MAX / 2 ? SIZE_MAX : b->cap * 2) : 256;
133 1538 : while (new_cap < needed) {
134 104 : if (new_cap > SIZE_MAX / 2) {
135 1 : b->oom = true;
136 1 : return;
137 : }
138 103 : new_cap *= 2;
139 : }
140 1434 : char *p = ccol__mem_realloc(b->m_procs, b->buf, new_cap);
141 1434 : if (!p) {
142 6 : b->oom = true;
143 6 : return;
144 : }
145 1428 : b->buf = p;
146 1428 : b->cap = new_cap;
147 : }
148 :
149 : // Appends n bytes of data to b and keeps the buffer NUL-terminated. It's the
150 : // out-of-line half of the inline ccol_growbuf_append, which handles the common
151 : // case of an append that fits; this one takes growth, empty appends and the oom
152 : // state. It does nothing once b->oom is set, and sets it when the size
153 : // overflows or growth fails. The size check runs before len + n + 1 is formed,
154 : // so a huge n latches oom instead of wrapping into an undersized copy. An empty
155 : // append returns before memcpy, because data may be NULL then.
156 1834 : void ccol_growbuf_append_slow(ccol_growbuf *b, const char *data, size_t n) {
157 1834 : if (b->oom) return;
158 1439 : if (n > SIZE_MAX - 1 - b->len) {
159 2 : b->oom = true;
160 2 : return;
161 : }
162 1437 : size_t needed = b->len + n + 1;
163 1437 : if (needed > b->cap) growbuf_grow(b, needed);
164 1437 : if (b->oom) return;
165 1430 : if (n == 0) return;
166 1428 : memcpy(b->buf + b->len, data, n);
167 1428 : b->len += n;
168 1428 : b->buf[b->len] = '\0';
169 : }
170 :
171 : // Allocator procs intern table.
172 : //
173 : // The state of one slot. A slot goes from EMPTY to WRITING when a thread claims
174 : // it and from WRITING to READY when the copy is written, and never back. A
175 : // thread claims only the first EMPTY slot after seeing every earlier one READY,
176 : // so the claimed slots are a prefix and a lookup can stop at the first EMPTY.
177 : enum {
178 : CCOL_PROCS_SLOT_EMPTY = 0,
179 : CCOL_PROCS_SLOT_WRITING = 1,
180 : CCOL_PROCS_SLOT_READY = 2
181 : };
182 :
183 : // The process-lifetime copies of the procs structs and the state of each slot.
184 : static ccol_memmgmt_procs ccol_procs_slots[CCOL_PROCS_INTERN_CAPACITY];
185 : static atomic_uchar ccol_procs_slot_state[CCOL_PROCS_INTERN_CAPACITY];
186 : #ifdef RUNNING_UNIT_TESTS
187 : // Test hooks: A delay between the claim and the publish of a slot (or, with
188 : // claim_wait_sightings set, the bound of a wait for that many sightings of a
189 : // slot being written), and the count of such sightings.
190 : _Atomic unsigned ccol__procs_intern_claim_delay_us_for_tests;
191 : _Atomic unsigned ccol__procs_intern_claim_wait_sightings_for_tests;
192 : _Atomic unsigned ccol__procs_intern_writing_sightings_for_tests;
193 : #endif
194 :
195 : // True when the two procs structs hold the same four functions. The intern
196 : // table uses it to find an existing copy of a caller's allocator.
197 13603 : static inline bool ccol_procs_same(const ccol_memmgmt_procs *a,
198 : const ccol_memmgmt_procs *b) {
199 3928 : return a->malloc == b->malloc && a->free == b->free &&
200 3928 : a->calloc == b->calloc && a->realloc == b->realloc;
201 : }
202 :
203 : // True when mp points at a slot of the intern table. Containers use it to keep
204 : // an interned pointer as it is instead of copying the struct. It compares
205 : // integers, because a relational comparison of pointers into different objects
206 : // is undefined.
207 146738 : bool ccol_procs_is_interned(const ccol_memmgmt_procs *mp) {
208 146738 : uintptr_t addr = (uintptr_t)mp;
209 146738 : uintptr_t base = (uintptr_t)&ccol_procs_slots[0];
210 142829 : return addr >= base && addr < base + sizeof(ccol_procs_slots) &&
211 139149 : (addr - base) % sizeof(ccol_memmgmt_procs) == 0;
212 : }
213 :
214 : // Waits until slot i, claimed by another thread, is READY in
215 : // ccol_procs_slot_state. ccol_procs_intern needs it because the slot may hold
216 : // the very content the lookup wants, and skipping it would give one content two
217 : // slots. It spins a little, then sleeps a microsecond at a time so a
218 : // descheduled claimer gets the CPU.
219 79 : static __attribute__((noinline, cold)) void ccol_procs_wait_ready(size_t i) {
220 79 : unsigned spins = 0;
221 79 : while (atomic_load_explicit(&ccol_procs_slot_state[i],
222 7047 : memory_order_acquire) != CCOL_PROCS_SLOT_READY) {
223 6968 : if (spins < 64) {
224 5056 : spins++;
225 : } else {
226 1912 : struct timespec ts = {0, 1000L};
227 1912 : nanosleep(&ts, NULL);
228 : }
229 : }
230 79 : }
231 :
232 : // Gives the process-lifetime copy of the allocator mp in *out, so cjson and
233 : // cyaml nodes never point at the caller's struct. It finds a slot with the same
234 : // four functions or claims the next EMPTY slot, lock free, in ccol_procs_slots
235 : // and ccol_procs_slot_state. A NULL mp gives NULL, and a pointer into the table
236 : // is returned as it is. The caller's struct is read once into a local so every
237 : // comparison and the copy see the same values. Gives ccol_success, or
238 : // ccol_container_full when the table is full.
239 4083 : ccol_retval ccol_procs_intern(ccol_memmgmt_procs *mp,
240 : ccol_memmgmt_procs **out) {
241 4083 : *out = NULL;
242 4083 : if (mp == NULL) return ccol_success;
243 4081 : if (ccol_procs_is_interned(mp)) {
244 2 : *out = mp;
245 2 : return ccol_success;
246 : }
247 4079 : ccol_memmgmt_procs want;
248 4079 : memcpy(&want, mp, sizeof(want));
249 13754 : for (size_t i = 0; i < CCOL_PROCS_INTERN_CAPACITY; i++) {
250 13748 : unsigned char st =
251 13748 : atomic_load_explicit(&ccol_procs_slot_state[i], memory_order_acquire);
252 13748 : if (st == CCOL_PROCS_SLOT_EMPTY) {
253 145 : unsigned char expected = CCOL_PROCS_SLOT_EMPTY;
254 145 : if (atomic_compare_exchange_strong_explicit(
255 : &ccol_procs_slot_state[i], &expected, CCOL_PROCS_SLOT_WRITING,
256 : memory_order_acq_rel, memory_order_acquire)) {
257 : #ifdef RUNNING_UNIT_TESTS
258 145 : unsigned delay_us = atomic_load_explicit(
259 : &ccol__procs_intern_claim_delay_us_for_tests, memory_order_relaxed);
260 145 : unsigned sightings = atomic_load_explicit(
261 : &ccol__procs_intern_claim_wait_sightings_for_tests,
262 : memory_order_relaxed);
263 145 : if (delay_us && sightings) {
264 : for (unsigned waited = 0;
265 3 : waited < delay_us &&
266 3 : atomic_load(&ccol__procs_intern_writing_sightings_for_tests) <
267 : sightings;
268 2 : waited += 100) {
269 2 : struct timespec ts = {0, 100000L};
270 2 : nanosleep(&ts, NULL);
271 : }
272 144 : } else if (delay_us) {
273 8 : struct timespec ts = {(time_t)(delay_us / 1000000u),
274 8 : (long)(delay_us % 1000000u) * 1000L};
275 8 : nanosleep(&ts, NULL);
276 : }
277 : #endif
278 145 : ccol_procs_slots[i] = want;
279 145 : atomic_store_explicit(&ccol_procs_slot_state[i], CCOL_PROCS_SLOT_READY,
280 : memory_order_release);
281 145 : *out = &ccol_procs_slots[i];
282 145 : return ccol_success;
283 : }
284 : st = expected;
285 : }
286 : #ifdef RUNNING_UNIT_TESTS
287 13603 : if (st == CCOL_PROCS_SLOT_WRITING)
288 79 : atomic_fetch_add(&ccol__procs_intern_writing_sightings_for_tests, 1);
289 : #endif
290 79 : if (st == CCOL_PROCS_SLOT_WRITING) ccol_procs_wait_ready(i);
291 13603 : if (ccol_procs_same(&ccol_procs_slots[i], &want)) {
292 3928 : *out = &ccol_procs_slots[i];
293 3928 : return ccol_success;
294 : }
295 : }
296 : return ccol_container_full;
297 : }
298 :
299 : #ifdef RUNNING_UNIT_TESTS
300 : // Test hooks for the intern table: The first one counts the claimed slots, the
301 : // second empties every slot from keep on, so a test can fill the table and put
302 : // it back.
303 6 : size_t ccol__procs_intern_used_for_tests(void) {
304 6 : size_t n = 0;
305 30 : while (n < CCOL_PROCS_INTERN_CAPACITY &&
306 30 : atomic_load_explicit(&ccol_procs_slot_state[n],
307 : memory_order_acquire) != CCOL_PROCS_SLOT_EMPTY)
308 24 : n++;
309 6 : return n;
310 : }
311 :
312 4 : void ccol__procs_intern_truncate_for_tests(size_t keep) {
313 245 : for (size_t i = keep; i < CCOL_PROCS_INTERN_CAPACITY; i++) {
314 241 : memset(&ccol_procs_slots[i], 0, sizeof(ccol_procs_slots[i]));
315 241 : atomic_store_explicit(&ccol_procs_slot_state[i], CCOL_PROCS_SLOT_EMPTY,
316 : memory_order_release);
317 : }
318 4 : }
319 : #endif
320 :
321 : #ifdef RUNNING_UNIT_TESTS
322 : // Fork-handler order recorder (test builds only). The names of the modules, for
323 : // the fatal messages.
324 : static const char *const ccol_atfork_module_names[ccol__atfork_module_count] = {
325 : "clogger", "cthreadcomm", "cthreadpool", "chttpserver", "chttpclient"};
326 :
327 : // The handlers that already ran in the fork being prepared, in order.
328 : // ccol__atfork_order_reset empties it after every fork.
329 : static unsigned char ccol_atfork_seq[ccol__atfork_module_count];
330 : static unsigned ccol_atfork_seq_len;
331 :
332 : // ccol_atfork_ran_before[a][b] records that a's handler ran before b's in an
333 : // earlier fork.
334 : static bool ccol_atfork_ran_before[ccol__atfork_module_count]
335 : [ccol__atfork_module_count];
336 :
337 : #if defined(CCOL__CLOEXEC_GATE)
338 : extern bool ccol__cloexec_gate_prepared_for_tests;
339 : #endif
340 :
341 : // Records that the prepare handler of ccol_module started. Every module's
342 : // prepare handler calls it in a test build, to prove that no two handlers run
343 : // in opposite orders in two forks (a real lock cycle) and that none runs after
344 : // the close-on-exec gate; either case ends the process. It reads
345 : // ccol__cloexec_gate_prepared_for_tests and updates ccol_atfork_seq and
346 : // ccol_atfork_ran_before. It takes no lock: Prepare handlers run one sequence
347 : // at a time under the C library's atfork lock, and a lock here would nest
348 : // inside the very handlers it checks. A handler already in the sequence was
349 : // registered twice and adds nothing.
350 1355 : void ccol__atfork_order_record(ccol__atfork_module ccol_module) {
351 1355 : if ((unsigned)ccol_module >= (unsigned)ccol__atfork_module_count) return;
352 : #if defined(CCOL__CLOEXEC_GATE)
353 : if (ccol__cloexec_gate_prepared_for_tests)
354 : ccol__fatal_err(
355 : "fork-prepare handler of %s ran after the close-on-exec gate, so a "
356 : "fork() can wait for a lock whose holder waits for the gate",
357 : ccol_atfork_module_names[ccol_module]);
358 : #endif
359 :
360 2987 : for (unsigned i = 0; i < ccol_atfork_seq_len; i++) {
361 1632 : if (ccol_atfork_seq[i] == (unsigned char)ccol_module) return;
362 : }
363 :
364 2984 : for (unsigned i = 0; i < ccol_atfork_seq_len; i++) {
365 1632 : ccol__atfork_module earlier = (ccol__atfork_module)ccol_atfork_seq[i];
366 1632 : if (ccol_atfork_ran_before[ccol_module][earlier]) {
367 3 : ccol__fatal_err(
368 : "fork-prepare handler order inverted: %s ran before %s in an earlier "
369 : "fork and after it in this one, so the locks the two handlers hold "
370 : "nest in opposite orders between two forks",
371 : ccol_atfork_module_names[ccol_module],
372 : ccol_atfork_module_names[earlier]);
373 : }
374 1629 : ccol_atfork_ran_before[earlier][ccol_module] = true;
375 : }
376 :
377 1352 : if (ccol_atfork_seq_len < (unsigned)ccol__atfork_module_count)
378 1352 : ccol_atfork_seq[ccol_atfork_seq_len++] = (unsigned char)ccol_module;
379 : }
380 :
381 : // Empties ccol_atfork_seq, so the next record starts the sequence of a new
382 : // fork. The recorder's parent and child handlers call it after each fork.
383 601 : void ccol__atfork_order_reset(void) { ccol_atfork_seq_len = 0; }
384 :
385 : // Registers ccol__atfork_order_reset as the parent and child handler, so every
386 : // fork starts with an empty sequence; guessing the start of a fork from a
387 : // handler running again would lose pairs. It runs from a constructor so it
388 : // comes ahead of every fork and every module handler.
389 41 : __attribute__((constructor)) static void ccol_atfork_order_register(void) {
390 41 : if (ccol__at_fork(NULL, ccol__atfork_order_reset, ccol__atfork_order_reset) !=
391 : 0) {
392 0 : ccol__fatal_err("cannot register the fork-prepare order recorder");
393 : }
394 41 : }
395 : #endif
396 :
397 : #if defined(CCOL__CLOEXEC_GATE)
398 : // The close-on-exec gate (see common.h). A thread that makes a descriptor in
399 : // two steps holds the read side across both, and the fork-prepare handler takes
400 : // the write side, so fork() waits until every such descriptor is close-on-exec.
401 : // A reader waits only for a fork and takes no other lock inside.
402 : // ccol_cloexec_gate_ok is false when the lock couldn't be initialized; the gate
403 : // then does nothing.
404 : static ccol__rw_lock ccol_cloexec_gate;
405 : static ccol__once_flag ccol_cloexec_gate_once = CCOL__ONCE_INIT;
406 : static ccol__once_flag ccol_cloexec_gate_reg_once = CCOL__ONCE_INIT;
407 : static bool ccol_cloexec_gate_ok;
408 :
409 : #ifdef RUNNING_UNIT_TESTS
410 : // Test counters of entries and exits, so a test can check every creation site.
411 : atomic_ulong ccol__cloexec_gate_enters_for_tests;
412 : atomic_ulong ccol__cloexec_gate_leaves_for_tests;
413 : // True from the gate's prepare handler until its parent or child handler;
414 : // ccol__atfork_order_record reads it. Only prepare handlers run in that window,
415 : // so it needs no lock.
416 : bool ccol__cloexec_gate_prepared_for_tests;
417 : // Prepare handler starts, counted before the wait for the write side.
418 : atomic_ulong ccol__cloexec_gate_prepares_for_tests;
419 : #endif
420 :
421 : // Initializes ccol_cloexec_gate once, on the first enter or prepare, and
422 : // records in ccol_cloexec_gate_ok whether that worked.
423 : static void ccol_cloexec_gate_init(void) {
424 : ccol_cloexec_gate_ok = ccol__rw_lock_init(ccol_cloexec_gate) == 0;
425 : }
426 :
427 : // Takes the read side of the close-on-exec gate. A site that makes a descriptor
428 : // in two steps calls it first, so no fork() lands between the steps. It does
429 : // nothing when the lock couldn't be initialized, and counts the entry in a test
430 : // build.
431 : void ccol__cloexec_gate_enter(void) {
432 : ccol__call_once(ccol_cloexec_gate_once, ccol_cloexec_gate_init);
433 : if (ccol_cloexec_gate_ok) ccol__rw_lock_rdlock(ccol_cloexec_gate);
434 : #ifdef RUNNING_UNIT_TESTS
435 : atomic_fetch_add_explicit(&ccol__cloexec_gate_enters_for_tests, 1,
436 : memory_order_relaxed);
437 : #endif
438 : }
439 :
440 : // Releases the read side of the gate once the descriptor is close-on-exec, and
441 : // counts the exit in a test build.
442 : void ccol__cloexec_gate_leave(void) {
443 : #ifdef RUNNING_UNIT_TESTS
444 : atomic_fetch_add_explicit(&ccol__cloexec_gate_leaves_for_tests, 1,
445 : memory_order_relaxed);
446 : #endif
447 : if (ccol_cloexec_gate_ok) ccol__rw_lock_unlock(ccol_cloexec_gate);
448 : }
449 :
450 : // Fork-prepare handler of the gate: Takes the write side, so fork() waits for
451 : // every thread between the two steps of a descriptor creation. It sets
452 : // ccol__cloexec_gate_prepared_for_tests in a test build.
453 : static void ccol_cloexec_gate_prepare(void) {
454 : #ifdef RUNNING_UNIT_TESTS
455 : atomic_fetch_add(&ccol__cloexec_gate_prepares_for_tests, 1);
456 : #endif
457 : ccol__call_once(ccol_cloexec_gate_once, ccol_cloexec_gate_init);
458 : if (ccol_cloexec_gate_ok) ccol__rw_lock_wrlock(ccol_cloexec_gate);
459 : #ifdef RUNNING_UNIT_TESTS
460 : ccol__cloexec_gate_prepared_for_tests = true;
461 : #endif
462 : }
463 :
464 : // Fork parent handler of the gate: Clears the prepared flag and releases the
465 : // write side, so the parent's threads can make descriptors again.
466 : static void ccol_cloexec_gate_parent(void) {
467 : #ifdef RUNNING_UNIT_TESTS
468 : ccol__cloexec_gate_prepared_for_tests = false;
469 : #endif
470 : if (ccol_cloexec_gate_ok) ccol__rw_lock_unlock(ccol_cloexec_gate);
471 : }
472 :
473 : // Fork child handler of the gate: Clears the prepared flag and initializes the
474 : // gate lock again, since in the child a plain unlock doesn't release a lock
475 : // that the forking thread took (see ccol__rw_lock_reinit_in_child). A failure
476 : // sets ccol_cloexec_gate_ok to false, which turns the gate off.
477 : static void ccol_cloexec_gate_child(void) {
478 : #ifdef RUNNING_UNIT_TESTS
479 : ccol__cloexec_gate_prepared_for_tests = false;
480 : #endif
481 : if (ccol_cloexec_gate_ok)
482 : ccol_cloexec_gate_ok =
483 : ccol__rw_lock_reinit_in_child(ccol_cloexec_gate) == 0;
484 : }
485 :
486 : // Registers the gate's fork handlers. The gate must run after every library
487 : // prepare handler, because a thread can hold a module lock while it waits to
488 : // enter the gate, and prepare handlers run in reverse registration order; so
489 : // the gate must register first. A failed registration leaves the gate working,
490 : // only fork() doesn't wait for it.
491 : static void ccol_cloexec_gate_do_register(void) {
492 : (void)ccol__at_fork_raw(ccol_cloexec_gate_prepare, ccol_cloexec_gate_parent,
493 : ccol_cloexec_gate_child);
494 : }
495 :
496 : // Registers the gate's fork handlers once. ccol__at_fork calls it before every
497 : // registration of the library, so the gate is always the first one in.
498 : void ccol__cloexec_gate_register(void) {
499 : ccol__call_once(ccol_cloexec_gate_reg_once, ccol_cloexec_gate_do_register);
500 : }
501 :
502 : // Registers the gate at load, so no constructor order, static link or first use
503 : // can put a module handler ahead of it.
504 : __attribute__((constructor)) static void ccol_cloexec_gate_at_load(void) {
505 : ccol__cloexec_gate_register();
506 : }
507 : #endif
|