Repository navigation
Expand file tree
/
Copy pathmalloc_interpose.c
More file actions
1122 lines (1022 loc) · 36.3 KB
/
Copy pathmalloc_interpose.c
File metadata and controls
1122 lines (1022 loc) · 36.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License"). You may not use this file except in compliance
* with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* malloc interposition via dlsym(RTLD_NEXT)
*
* This file implements lazy initialization of libumem to avoid the
* pthread_create/malloc circular dependency deadlock, the pattern
* profiling tools (valgrind, ASan) use. (An earlier version cited
* docs/PTHREAD_RESEARCH.md; that file is not in the tree.)
*
* Key design:
* 1. Use dlsym(RTLD_NEXT) to get real libc malloc
* 2. State machine: UNINIT → BOOTSTRAP → READY
* 3. Route early calls to bootstrap allocator (mmap-based)
* 4. Track pointer ownership to know which free path to use
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include "config.h"
#include <dlfcn.h>
#include <stddef.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#ifdef HAVE_MALLOC_H
#include <malloc.h>
#endif
#include <pthread.h>
#include <stdatomic.h>
#include <stdlib.h>
#include "umem_impl.h"
#include "malloc_guard.h"
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
/*
* External: umem readiness state and functions. The UMEM_READY_* values
* come from umem_impl.h (included above); this file used to keep its own
* copies of two of them.
*/
extern int umem_ready;
extern thread_t umem_init_thr;
extern thread_t umem_update_thr;
extern int umem_init(void);
extern void *umem_malloc(size_t);
extern void umem_malloc_free(void *);
/* Bootstrap allocator functions from malloc.c */
extern void *bootstrap_malloc(size_t);
extern void bootstrap_free(void *);
extern int is_bootstrap_pointer(void *);
extern int process_free(void *, int, size_t *);
/* Bootstrap header structure (from malloc.c) */
#define BOOTSTRAP_MAGIC 0xB007B007B007B007ULL
typedef struct bootstrap_header {
uint64_t magic;
size_t size;
} bootstrap_header_t;
/* State machine for interposition */
typedef enum {
INTERPOSE_UNINIT, /* Before first malloc call */
INTERPOSE_BOOTSTRAP, /* Resolving libc or initializing umem */
INTERPOSE_READY /* Fully initialized, use umem */
} interpose_state_t;
/* Direct initialization - ATOMIC_VAR_INIT deprecated in C17 */
static atomic_int interpose_state = INTERPOSE_UNINIT;
/* Pointers to real libc functions */
static void *(*libc_malloc)(size_t) = NULL;
static void (*libc_free)(void *) = NULL;
static void *(*libc_calloc)(size_t, size_t) = NULL;
static void *(*libc_realloc)(void *, size_t) = NULL;
static void *(*libc_memalign)(size_t, size_t) = NULL;
/*
* ===========================================================================
* POINTER OWNERSHIP
* ===========================================================================
*
* Under interposition a pointer reaching free()/realloc()/
* malloc_usable_size() can come from four different owners. Every one of
* those entry points MUST classify it the same way: a pointer one of them
* recognizes and another does not is how a static-buffer or libc pointer
* ends up in umem's metadata decoder. That is what interpose_owner_of()
* below is for -- it is the single classifier all three use.
*
* OWN_STATIC Storage carved out of a static bump buffer during
* dlsym(3) resolution, before any real allocator exists.
* LIFETIME: permanent. Never freed, never reused -- see
* static_alloc().
* OWN_BOOTSTRAP mmap'd by bootstrap_malloc() (malloc.c), carrying a
* bootstrap_header_t. Freed with bootstrap_free().
* OWN_LIBC Obtained from the real libc allocator during the bootstrap
* window (only libc memalign(3) does this). Recorded in
* libc_ptrs[] together with its size; freed with libc_free.
* OWN_UMEM Everything else once interposition is READY: umem's own
* malloc_data_t-tagged storage.
*/
typedef enum {
OWN_UNKNOWN,
OWN_STATIC,
OWN_BOOTSTRAP,
OWN_LIBC,
OWN_UMEM
} interpose_owner_t;
/*
* Static bump buffer for allocations made while resolving libc symbols.
*
* dlsym(3) may call calloc() internally, which would recurse back into us
* before libc_malloc is known. Storage handed out here is PERMANENT: the
* bump offset never moves backward and the buffer is never reset. That is
* deliberate and is the core of the P1.1 fix -- any scheme that recycles this
* storage can hand the same bytes to two live callers. The total is a few
* hundred bytes for the process lifetime.
*
* Each chunk carries a header so malloc_usable_size()/realloc() know the
* exact size, rather than guessing and over-reading.
*
* THREAD SAFETY: static_buffer_used is advanced under static_buffer_lock.
* in_dlsym is only ever set by resolve_libc_functions(), which runs from the
* library constructor before the process has created a second thread.
*/
#define STATIC_BUFFER_SIZE 4096
#define STATIC_CHUNK_MAGIC 0x5A5A0BEEFULL
typedef struct static_chunk {
uint64_t magic;
size_t size; /* usable bytes following this header */
} static_chunk_t;
static char static_buffer[STATIC_BUFFER_SIZE]
__attribute__((aligned(16)));
static size_t static_buffer_used = 0;
static pthread_mutex_t static_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
static int in_dlsym = 0;
/*
* Carve `size` permanent bytes out of the static buffer. Returns NULL when
* exhausted -- never wraps, never reuses.
*/
static void *
static_alloc(size_t size)
{
size_t need;
static_chunk_t *chunk = NULL;
/* header + 16-byte-aligned payload, with overflow checks */
if (size > SIZE_MAX - 15)
return (NULL);
need = (size + 15) & ~(size_t)15;
if (need > SIZE_MAX - sizeof (static_chunk_t))
return (NULL);
need += sizeof (static_chunk_t);
(void) pthread_mutex_lock(&static_buffer_lock);
if (need <= STATIC_BUFFER_SIZE - static_buffer_used) {
chunk = (static_chunk_t *)&static_buffer[static_buffer_used];
static_buffer_used += need;
}
(void) pthread_mutex_unlock(&static_buffer_lock);
if (chunk == NULL)
return (NULL);
chunk->magic = STATIC_CHUNK_MAGIC;
chunk->size = need - sizeof (static_chunk_t);
return ((void *)(chunk + 1));
}
static int
is_static_pointer(const void *ptr)
{
return (ptr >= (const void *)static_buffer &&
ptr < (const void *)(static_buffer + STATIC_BUFFER_SIZE));
}
static size_t
get_static_size(void *ptr)
{
static_chunk_t *chunk = (static_chunk_t *)ptr - 1;
if (!is_static_pointer(chunk) || chunk->magic != STATIC_CHUNK_MAGIC)
return (0);
return (chunk->size);
}
/*
* libc pointer tracking.
*
* Records pointer AND size: without the size, realloc() of one of these had
* to guess the old length (it copied the NEW size from the OLD pointer, an
* over-read on growth) on any platform lacking malloc_usable_size(3).
*
* Slots are reused once cleared. The table used to be append-only, so a
* program doing sustained memalign/free churn during the bootstrap window
* exhausted all 512 entries and every later libc pointer became untracked --
* and an untracked libc pointer reaching free() is handed to umem's decoder.
*
* INVARIANT: a libc allocation is either recorded here or has been handed to
* libc_free(). It is never live-and-unrecorded, which is why tracking
* failure fails the allocation (see track_libc_ptr callers) and why the
* record is released only AFTER the operation that replaces it has succeeded.
*
* THREAD SAFETY: every field is accessed under libc_ptr_lock.
*/
#define MAX_LIBC_PTRS 512
struct libc_ptr_ent {
void *ptr;
size_t size;
};
static struct libc_ptr_ent libc_ptrs[MAX_LIBC_PTRS];
static pthread_mutex_t libc_ptr_lock = PTHREAD_MUTEX_INITIALIZER;
/*
* Number of live entries in libc_ptrs[]. This is the fast-path gate for
* is_libc_pointer(), and it exists because of a measured ~500x collapse:
*
* The table only ever gains entries from bootstrap-phase memalign() --
* i.e. before umem is READY -- and is EMPTY for the entire steady-state
* life of almost every process. Yet free() consulted it unconditionally,
* taking the process-global libc_ptr_lock and scanning all 512 slots on
* every single call. A global mutex on the hottest path in the library,
* acquired to search an empty table.
*
* Measured on c7i.metal-48xl (192 vCPU), multi 16:64, null-controlled
* (preload-arm sd 3.75%): the LD_PRELOAD interposer ran 3.0 Mops/s at one
* thread and 0.8 Mops/s at 192 -- NEGATIVE scaling -- while the umem_alloc
* API path on the same build did 398 Mops/s at 192 (glibc: 421). Every
* earlier comparison in this repo measured the API path, which is why a
* 500x gap on the drop-in path went unseen.
*
* Reads of the count are relaxed and lock-free. That is sound because the
* count is only a GATE: a nonzero read falls through to the locked, exact
* scan; a zero read means "no libc entry can match", and that is true at
* the instant of the read. Could an entry be added after a zero read?
* Only by bootstrap memalign(), which by construction hands a pointer to
* the caller before anyone can free() it -- so a pointer being freed while
* the count reads zero was never in the table. (Track increments BEFORE
* publishing the pointer; untrack decrements AFTER the slot is cleared, so
* a stale nonzero only costs a lock, never a miss.)
*/
static atomic_size_t libc_ptr_live = 0;
/*
* Fork participation.
*
* static_buffer_lock and libc_ptr_lock are taken by ORDINARY free() and
* realloc() on every call (see interpose_owner_of()). Without fork handling a
* child could inherit either one held by a thread that does not exist in the
* child, and the child's very next free() would block forever.
*
* libumem.so's fork handler calls these weak hooks (see umem_fork.c): they run
* BEFORE umem_init_lock and every allocator lock on the prepare side, and
* after them on the release side, because free() acquires these locks before
* it enters the allocator.
*
* In the child the locks are RE-INITIALIZED rather than unlocked: the owning
* thread may be gone, and unlocking a mutex this thread does not own is
* undefined. Re-initializing is safe because a post-fork child has exactly
* one thread, so no other thread can be mid-critical-section. The protected
* data itself (the static buffer offset and the tracking table) is plain
* memory copied by fork and remains consistent: entries describe allocations
* the child has inherited and may legitimately free.
*/
void
umem_interpose_lockup(void)
{
(void) pthread_mutex_lock(&static_buffer_lock);
(void) pthread_mutex_lock(&libc_ptr_lock);
}
void
umem_interpose_release(void)
{
(void) pthread_mutex_unlock(&libc_ptr_lock);
(void) pthread_mutex_unlock(&static_buffer_lock);
}
void
umem_interpose_release_child(void)
{
(void) pthread_mutex_init(&libc_ptr_lock, NULL);
(void) pthread_mutex_init(&static_buffer_lock, NULL);
/*
* calloc_depth is per-thread (initial-exec TLS). The single surviving
* child thread inherits ITS OWN value, which is 0 unless fork() was
* called from inside calloc() -- impossible, since calloc() does not
* fork. Threads that vanished took their own copies with them, so
* there is nothing to reset here.
*/
}
/*
* Record a libc allocation. Returns 0 if the table is full, in which case
* the caller MUST NOT return the pointer to the application.
*/
static int
track_libc_ptr(void *ptr, size_t size)
{
size_t i;
int ok = 0;
if (ptr == NULL)
return (0);
(void) pthread_mutex_lock(&libc_ptr_lock);
for (i = 0; i < MAX_LIBC_PTRS; i++) {
if (libc_ptrs[i].ptr == NULL) {
/* Count up BEFORE the pointer becomes findable. */
atomic_fetch_add_explicit(&libc_ptr_live, 1,
memory_order_release);
libc_ptrs[i].ptr = ptr;
libc_ptrs[i].size = size;
ok = 1;
break;
}
}
(void) pthread_mutex_unlock(&libc_ptr_lock);
return (ok);
}
/*
* Look up a libc allocation WITHOUT releasing the record; optionally reports
* its size. Ownership stays with the table so a caller that then fails can
* leave the allocation recognizable.
*/
static int
is_libc_pointer(void *ptr, size_t *sizep)
{
size_t i;
int found = 0;
if (ptr == NULL)
return (0);
/*
* Fast path: an empty table cannot contain ptr. This single relaxed
* load replaces a mutex acquire + 512-slot scan on every free(), and
* is the whole fix for the negative thread scaling described above.
*/
if (atomic_load_explicit(&libc_ptr_live, memory_order_acquire) == 0)
return (0);
(void) pthread_mutex_lock(&libc_ptr_lock);
for (i = 0; i < MAX_LIBC_PTRS; i++) {
if (libc_ptrs[i].ptr == ptr) {
if (sizep != NULL)
*sizep = libc_ptrs[i].size;
found = 1;
break;
}
}
(void) pthread_mutex_unlock(&libc_ptr_lock);
return (found);
}
/*
* Release the ownership record for a libc allocation. Call this only once
* the allocation is actually about to be handed to libc_free().
*/
static void
untrack_libc_ptr(void *ptr)
{
size_t i;
if (ptr == NULL)
return;
(void) pthread_mutex_lock(&libc_ptr_lock);
for (i = 0; i < MAX_LIBC_PTRS; i++) {
if (libc_ptrs[i].ptr == ptr) {
libc_ptrs[i].ptr = NULL;
libc_ptrs[i].size = 0;
/* Count down AFTER the slot is cleared. */
atomic_fetch_sub_explicit(&libc_ptr_live, 1,
memory_order_release);
break;
}
}
(void) pthread_mutex_unlock(&libc_ptr_lock);
}
/*
* Get the usable size of a bootstrap allocation.
* Bootstrap allocations have a header before the returned pointer.
*/
static size_t
get_bootstrap_size(void *ptr)
{
bootstrap_header_t *hdr;
if (ptr == NULL)
return (0);
hdr = (bootstrap_header_t *)ptr - 1;
if (hdr->magic != BOOTSTRAP_MAGIC)
return (0);
/* Return data size (total size minus header) */
return (hdr->size - sizeof(bootstrap_header_t));
}
/*
* The single ownership classifier. free(), realloc() and
* malloc_usable_size() all route through this so they cannot disagree.
* *sizep, when non-NULL, receives the usable size for every owner except
* OWN_UNKNOWN.
*/
static interpose_owner_t
interpose_owner_of(void *ptr, size_t *sizep)
{
size_t size;
if (ptr == NULL)
return (OWN_UNKNOWN);
if (is_static_pointer(ptr)) {
if (sizep != NULL)
*sizep = get_static_size(ptr);
return (OWN_STATIC);
}
if (is_bootstrap_pointer(ptr)) {
if (sizep != NULL)
*sizep = get_bootstrap_size(ptr);
return (OWN_BOOTSTRAP);
}
if (is_libc_pointer(ptr, &size)) {
if (sizep != NULL)
*sizep = size;
return (OWN_LIBC);
}
if (atomic_load(&interpose_state) == INTERPOSE_READY) {
if (process_free(ptr, 0, &size) != 0) {
if (sizep != NULL)
*sizep = size;
return (OWN_UMEM);
}
}
return (OWN_UNKNOWN);
}
/*
* Per-thread calloc recursion depth.
*
* WHY THIS IS PER-THREAD (it used to be a process-global int):
* A global flag set on every ordinary calloc() makes every OTHER thread
* that enters calloc() concurrently believe it is recursing. With the old
* shared static bump buffer as the recursion path that produced
* overlapping live allocations; with any recursion path it is simply
* wrong -- recursion is a property of one call stack, i.e. of one thread.
*
* WHY initial-exec TLS IS SAFE HERE:
* The old comment claimed __thread could not be used because "we'd need
* TLS to be initialized to access it". That is true of the general-dynamic
* model, whose access goes through __tls_get_addr() and can allocate. It
* is not true of initial-exec: the variable lives in the static TLS block,
* which pthread_create() allocates and zeroes BEFORE the new thread runs
* any code, and access is a single register-relative load with no call and
* no allocation. The calloc() that TLS setup performs happens on the
* CREATING thread, whose static TLS block has long existed. malloc_guard.c
* already depends on exactly this for umem_malloc()'s own guard.
* Constraint (shared with malloc_guard.h): LD_PRELOAD only, not dlopen --
* which is already this library's only supported mode.
*/
static __thread int calloc_depth __attribute__((tls_model("initial-exec")));
/*
* Zero-fill an allocation calloc() is about to return.
*
* This exists as a separate noinline function, and not as a plain memset()
* call inside calloc(), because GCC's strlen/memset pass rewrites an
* adjacent
*
* p = malloc(n); memset(p, 0, n);
*
* pair into
*
* p = calloc(n, 1);
*
* Inside calloc() itself that is unbounded self-recursion. This was not
* theoretical: with the memset written inline the generated calloc() ended in
* "jmp calloc@plt" and the process spun at 100% CPU issuing zero syscalls
* with flat RSS. (The pre-fix code escaped the transform only by accident,
* because its `volatile int in_calloc` stores sat between the two calls.)
*
* An opaque asm barrier is kept as well so the property does not depend on
* the pass's willingness to look through a static function, nor on
* -fno-builtin-malloc surviving in AM_CFLAGS. Cost is nil next to the
* memset itself.
*/
static void __attribute__((noinline))
calloc_zero_fill(void *p, size_t n)
{
__asm__ __volatile__("" : : "r"(p) : "memory");
(void) memset(p, 0, n);
}
/*
* Resolve libc malloc functions using dlsym(RTLD_NEXT)
*/
static void
resolve_libc_functions(void)
{
in_dlsym = 1;
libc_malloc = dlsym(RTLD_NEXT, "malloc");
libc_free = dlsym(RTLD_NEXT, "free");
libc_calloc = dlsym(RTLD_NEXT, "calloc");
libc_realloc = dlsym(RTLD_NEXT, "realloc");
libc_memalign = dlsym(RTLD_NEXT, "memalign");
in_dlsym = 0;
}
/*
* The interposer is its own object, and its malloc()/free() frames sit
* between the caller and libumem.so on every audited stack: register its text
* with getpcstack()'s internal-frame skip too (T9).
*/
__attribute__((constructor))
static void
umem_interpose_pcstack_init(void)
{
extern void umem_pcstack_internal(const void *addr);
umem_pcstack_internal((const void *)(uintptr_t)&umem_interpose_pcstack_init);
}
/*
* Constructor: Resolve libc functions before any malloc calls
* This is called automatically when the library is loaded via LD_PRELOAD.
*
* This constructor MUST run before libumem's __umem_init constructor,
* because __umem_init may call pthread functions which call malloc. What
* guarantees that is LOAD ORDER, not the constructor(101) below: numbered
* constructor priorities only order constructors WITHIN a single shared
* object, and malloc_interpose lives in libumem_malloc.so while __umem_init
* is in libumem.so. The LD_PRELOAD'd libumem_malloc.so loads before
* libumem.so is pulled in as its NEEDED dependency, so its constructors
* run first. The 101 is a no-op across the boundary and is kept only as
* documentation of intent; the Solaris/illumos ld has no numbered
* .init_array, so the plain form is used there. (This comment used to
* say "We use priority 101 to ensure this runs first", which the
* paragraph after it then contradicted.)
*
* NOTE: We do NOT call umem_init() here because that would trigger
* pthread_create which calls malloc, creating a deadlock. Instead,
* we let malloc calls during the bootstrap phase use the bootstrap
* allocator, and umem will be initialized lazily on first use.
*/
#if defined(__sun) || defined(__SVR4)
__attribute__((constructor))
#else
__attribute__((constructor(101)))
#endif
static void
umem_interpose_init(void)
{
/* Tell libumem we're acting as the process malloc. This
* disables backtrace(3)-based stack capture in the slab
* paths, which would otherwise dlopen libgcc_s through us
* and recurse fatally. */
extern int umem_malloc_is_interposing;
umem_malloc_is_interposing = 1;
/* Resolve libc functions */
atomic_store(&interpose_state, INTERPOSE_BOOTSTRAP);
resolve_libc_functions();
/*
* Disable abort on recoverable errors in interpose mode.
*
* WHY (the legitimate reason): under LD_PRELOAD we are handed pointers
* from allocators that are not us -- libc malloc for anything allocated
* before we loaded, shared libraries carrying their own allocator, and
* plain application bugs. Aborting the process on the first such
* pointer makes libumem unusable as a drop-in.
*
* THIS IS NOT "THE SAME AS GLIBC", and the comment here used to say it
* was. glibc ABORTS on an invalid free ("free(): invalid pointer").
* Continuing is strictly weaker than glibc for this case, and P5.8
* examined exactly that: with umem_abort = 0, a pointer whose header
* passed the magic check proceeded to free memory libumem does not own.
*
* WHAT MAKES CONTINUING DEFENSIBLE NOW, and it was not before: as of
* P5.8, process_free() validates BEFORE it mutates -- ownership of the
* header, ownership of [base, base+size), and the size against the
* layout the magic named -- and a pointer that fails is refused having
* changed nothing. So "log and continue" now continues from a state
* the allocator never touched, rather than from a half-applied free.
* That is the difference between tolerating a foreign pointer and
* acting on a forged one.
*
* The remaining gap versus glibc is DETECTION LOUDNESS, not corruption:
* a program with a double-free bug gets a log line from us where glibc
* would kill it. Set UMEM_OPTIONS=abort to get the abort back --
* the option exists as of this comment; the earlier text named
* "abort=1", which no option table entry ever implemented and which
* the flag parser would have rejected for taking a value. (Its
* inverse has always been UMEM_DEBUG=noabort -- a different
* variable -- which is part of why nobody noticed.)
*
* ORDER: this constructor runs at load; umem_init() parses
* UMEM_OPTIONS on the first allocation, after it. So the env
* setting wins, which is the intent.
*/
extern uint_t umem_abort;
umem_abort = 0;
}
/*
* interpose_try_ready -- in BOOTSTRAP state, get umem initialized if this
* thread may, and move to READY once it is. Called by every allocation entry
* point that would otherwise serve the request from a bootstrap table.
*
* WHO CALLS umem_init(). Every thread except the one already running it.
* umem_init() elects one initializer under umem_init_lock and makes every
* other caller wait on umem_init_cv until it finishes, so a thread that
* arrives mid-init waits there (microseconds) and then takes the umem path.
* The initializer's OWN recursive allocations (pthread_create, dlsym and the
* like inside umem_init()) must not call it again; they fall through to the
* bootstrap allocator, which is what the bootstrap tables exist for.
*
* A once-only flag used to stand in for that election. A thread that lost
* the race skipped umem_init() and served every allocation from
* bootstrap_malloc() -- one mmap and one slot of the 256-entry registry each
* -- until init finished; memalign() never called umem_init() at all and used
* the 512-entry libc-pointer table instead. With two threads making a
* process's first allocations together (routine on illumos, where nothing
* allocates before main()) the tables filled within a few hundred calls and
* the allocation failed with ENOMEM.
*
* umem_init_thr is written under umem_init_lock and read unlocked here. A
* stale read in a thread that is NOT the initializer can only say "not me",
* which is right; the initializer always sees its own store. After a failed
* init (UMEM_READY_INIT_FAILED) nothing calls umem_init() again, as before.
*
* NOR THE UPDATE THREAD. umem_init() starts it near the end and then
* re-takes umem_update_lock before it can finish; the update thread holds
* that lock in its first pthread_cond_timedwait(), and FreeBSD's libthr
* allocates the condvar there. Had that allocation waited here for
* umem_init(), each thread would wait for the other (test_aligned_contracts
* hung in make check on FreeBSD 15.1). umem_update_thr is published, under
* umem_update_lock, before the new thread passes its startup handshake, so
* every allocation it makes after that sees it; it is served from the
* bootstrap tables until init finishes, as the initializer's recursion is.
*
* NB: callers test interpose_state == INTERPOSE_BOOTSTRAP inline before
* calling. Out of line, an unconditional call cost every READY malloc() a
* call/return: the per-call ratio probe fell from 0.51 to 0.48 on Graviton3.
*/
static void
interpose_try_ready(void)
{
if (umem_ready == UMEM_READY_STARTUP ||
(umem_ready == UMEM_READY_INITING &&
umem_init_thr != thr_self() && umem_update_thr != thr_self()))
(void) umem_init();
if (umem_ready == UMEM_READY) {
int expected = INTERPOSE_BOOTSTRAP;
atomic_compare_exchange_strong(&interpose_state,
&expected, INTERPOSE_READY);
}
}
/*
* malloc - main interposition point
*
* malloc() and free() carry UMEM_HOT_ALIGN for the reason umem_alloc() and
* umem_free() do (umem_impl.h): without it their placement follows whatever
* precedes them in this file. On UltraSPARC T-series an unrelated 128-byte
* growth of umem_interpose_init() moved them and took repro_interpose_free_ratio
* from 0.22 to 0.14; pinned, both trees measured 0.30-0.34.
*/
UMEM_HOT_ALIGN void *
malloc(size_t size)
{
/*
* Handle dlsym's malloc calls with the permanent static buffer.
* dlsym may call malloc/calloc internally, so we provide storage
* that does not depend on any allocator existing yet.
*/
if (in_dlsym)
return (static_alloc(size));
/*
* umem is initialized lazily from here: umem_init() is normally called
* by umem_alloc(), but the interposer never calls umem_alloc() while
* in BOOTSTRAP state, so nothing else would start it.
*/
if (__builtin_expect(atomic_load(&interpose_state) ==
INTERPOSE_BOOTSTRAP, 0))
interpose_try_ready();
/* Fast path: fully initialized */
if (__builtin_expect(atomic_load(&interpose_state) == INTERPOSE_READY, 1)) {
return (umem_malloc(size));
}
/*
* Pre-constructor or during umem_init(): use bootstrap allocator.
* This handles recursive malloc calls during initialization.
*/
return (bootstrap_malloc(size));
}
/*
* free - must handle mixed allocation sources
*/
UMEM_HOT_ALIGN void
free(void *ptr)
{
if (ptr == NULL)
return;
/*
* Steady-state fast path. Once READY, the overwhelmingly common case
* is a umem-owned pointer, and interpose_owner_of() classifies it by
* running process_free(ptr, 0, ...) -- a full header decode -- only
* for umem_malloc_free() to run process_free(ptr, 1, ...) and decode
* the SAME header again. Two decodes per free on the hot path.
*
* The static check is a range compare on this file's own buffer and
* must stay first (those pointers have no umem header). The libc
* check is gated on the live count (see libc_ptr_live). Everything
* else goes to umem_malloc_free(), which itself does step 1 of
* process_free()'s validation order (bootstrap pointer -> munmap) and
* then validates and either frees or reports -- exactly what the
* classify-then-free sequence did, in one pass. Since P5.8 a rejected
* pointer leaves state untouched, so skipping the pre-classification
* loses no safety. A bootstrap check here would be the same read of
* ptr[-1] that umem_malloc_free() is about to make.
*/
if (__builtin_expect(atomic_load(&interpose_state) == INTERPOSE_READY, 1) &&
!is_static_pointer(ptr) &&
/*
* is_libc_pointer()'s gate, inline. A nonzero count falls to
* interpose_owner_of() below, which does the locked scan.
*/
atomic_load_explicit(&libc_ptr_live, memory_order_acquire) == 0) {
umem_malloc_free(ptr);
return;
}
switch (interpose_owner_of(ptr, NULL)) {
case OWN_STATIC:
/*
* Permanent storage from the dlsym-resolution buffer. It is
* never reused, so "freeing" it is a no-op by design: reuse
* is exactly what would let two callers hold the same bytes.
*/
return;
case OWN_BOOTSTRAP:
bootstrap_free(ptr);
return;
case OWN_LIBC:
/* Release the record only as we hand it back to libc. */
untrack_libc_ptr(ptr);
if (libc_free != NULL)
libc_free(ptr);
return;
case OWN_UMEM:
umem_malloc_free(ptr);
return;
case OWN_UNKNOWN:
break;
}
/*
* Unrecognized. Before interposition is READY the pointer most
* likely predates us, so libc owns it. Once READY, hand it to umem,
* which logs a recoverable error (umem_abort is 0 in interpose mode --
* see umem_interpose_init() for why, and for why that is weaker than
* glibc rather than "the same as") rather than crashing on a foreign
* pointer. Since P5.8, process_free() refuses such a pointer without
* mutating allocator state, so continuing here cannot leave a
* half-applied free behind.
*/
if (atomic_load(&interpose_state) != INTERPOSE_READY) {
if (libc_free != NULL)
libc_free(ptr);
return;
}
umem_malloc_free(ptr);
}
/*
* malloc_usable_size - report the usable size of an interposer-owned pointer.
*
* Must be interposed for the same reason realloc() must: without it the
* application's malloc_usable_size() reaches libc, which reads libc malloc
* metadata that does not exist in front of umem/bootstrap/static storage.
* Uses the same classifier as free()/realloc().
*
* FreeBSD's <malloc_np.h> (reached through <stdlib.h>) declares it taking a
* const pointer, glibc's <malloc.h> a plain one; a definition that disagrees
* with the platform prototype does not compile, so match whichever applies.
*/
#ifdef __FreeBSD__
#define UMEM_MUS_CONST const
#else
#define UMEM_MUS_CONST
#endif
size_t
malloc_usable_size(UMEM_MUS_CONST void *ptr)
{
size_t size = 0;
/* The classifier only reads; the cast just drops FreeBSD's const. */
if (interpose_owner_of((void *)(uintptr_t)ptr, &size) == OWN_UNKNOWN)
return (0);
return (size);
}
/*
* calloc - allocate and zero
*
* The recursion guard is per-thread (calloc_depth) and the recursion path is
* bootstrap_malloc(), not a shared bump buffer. Two consequences, both
* required by P1.1:
* - One thread's ordinary calloc() cannot push another thread onto the
* recursion path.
* - Storage handed out on the recursion path is individually owned
* (mmap + header) and freeable, so nothing has to be "recycled" while it
* might still be live.
*/
void *
calloc(size_t nelem, size_t elsize)
{
size_t size;
void *ret;
/* Check for overflow BEFORE any size calculations */
if (nelem > 0 && elsize > 0) {
if (SIZE_MAX / elsize < nelem) {
errno = ENOMEM;
return (NULL);
}
}
size = nelem * elsize;
/*
* Handle dlsym's calloc calls with the permanent static buffer.
* dlsym may call calloc internally on some systems.
*/
if (in_dlsym) {
ret = static_alloc(size);
if (ret == NULL) {
errno = ENOMEM;
return (NULL);
}
calloc_zero_fill(ret, size);
return (ret);
}
/*
* Recursive calloc on THIS thread (pthread_create -> allocate_dtv ->
* calloc -> malloc -> ... -> calloc). Break the cycle with the
* bootstrap allocator, which needs no TLS and no umem.
*/
if (calloc_depth > 0) {
ret = bootstrap_malloc(size);
if (ret == NULL) {
errno = ENOMEM;
return (NULL);
}
calloc_zero_fill(ret, size);
return (ret);
}
calloc_depth++;
ret = malloc(size);
if (ret != NULL)
calloc_zero_fill(ret, size);
calloc_depth--;
return (ret);
}
/*
* realloc - resize allocation
*
* Ownership rule (P1.7c): the old allocation's ownership record is released
* only after the replacement has been allocated AND the contents copied. A
* realloc that fails must leave the original live, intact, and still
* recognized by free() and by a later realloc().
*/
void *
realloc(void *ptr, size_t size)
{
void *new_ptr;
size_t old_size = 0;
interpose_owner_t owner;
if (ptr == NULL)
return (malloc(size));
if (size == 0) {
free(ptr);
return (NULL);
}
owner = interpose_owner_of(ptr, &old_size);
switch (owner) {
case OWN_UMEM:
if (size == old_size)
return (ptr);
break;
case OWN_STATIC:
case OWN_BOOTSTRAP:
case OWN_LIBC:
if (old_size == 0) {
/* Recognized owner but unusable size: corrupt header. */
errno = EINVAL;
return (NULL);
}
break;
case OWN_UNKNOWN:
/*
* Not ours. Before READY this is a pre-interposition libc
* pointer and libc_realloc can handle it correctly (it knows
* its own metadata). After READY an unrecognized pointer is
* invalid: we must not guess a length by reading foreign
* metadata, which is what the old malloc_usable_size()
* fallback did.
*/
if (atomic_load(&interpose_state) != INTERPOSE_READY &&
libc_realloc != NULL)
return (libc_realloc(ptr, size));
errno = EINVAL;
return (NULL);
}
new_ptr = malloc(size);
if (new_ptr == NULL) {
/*
* Failure: ptr is untouched and still recorded under its
* original owner. errno is set by malloc().
*/
return (NULL);
}
(void) memcpy(new_ptr, ptr, MIN(old_size, size));
/* Only now does the old allocation stop being the live one. */
free(ptr);
return (new_ptr);
}
/*
* memalign - allocate aligned memory
*/
void *
memalign(size_t align, size_t size)
{
void *ret;
/* Validate alignment: must be a nonzero power of two. */
if (align == 0 || (align & (align - 1)) != 0) {
errno = EINVAL;
return (NULL);
}