Repository navigation
Expand file tree
/
Copy pathallocator.h
More file actions
2045 lines (1876 loc) · 62.8 KB
/
Copy pathallocator.h
File metadata and controls
2045 lines (1876 loc) · 62.8 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
/*
** Bundled memory allocator.
** based on LuaJITs allocator, HEAVILY modified to be mostly standalone.
**
** Beware: this is a HEAVILY CUSTOMIZED version of dlmalloc.
** The original bears the following remark:
**
** This is a version (aka dlmalloc) of malloc/free/realloc written by
** Doug Lea and released to the public domain, as explained at
** http://creativecommons.org/licenses/publicdomain.
**
** * Version pre-2.8.4 Wed Mar 29 19:46:29 2006 (dl at gee)
**
** No additional copyright is claimed over the customizations.
** Please do NOT bother the original author about this version here!
**
** If you want to use dlmalloc in another project, you should get
** the original from: ftp://gee.cs.oswego.edu/pub/misc/
** For thread-safe derivatives, take a look at:
** - ptmalloc: http://www.malloc.de/
** - nedmalloc: http://www.nedprod.com/programs/portable/nedmalloc/
*/
#ifndef _LJ_ALLOC_H
#define _LJ_ALLOC_H
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#if defined(__GLIBC__) || defined(__MUSL__)
#include <malloc.h>
#endif
#if (defined(__linux__) || defined(__CYGWIN__)) && !defined(_GNU_SOURCE)
#define _GNU_SOURCE
#endif
#if defined(__STRICT_ANSI__) || defined(__PCC__)
#define MEMPOOL_INLINE static
#else
#if defined(__GNUC__) || defined(__TINYC__)
#define MEMPOOL_INLINE static __attribute__((always_inline)) inline
#else
#define MEMPOOL_INLINE static inline
#endif
#endif
#if defined(__cplusplus)
#define MEMPOOL_CPP_BEGINEXTERN() extern "C" {
#define MEMPOOL_CPP_ENDEXTERN() }
#else
#define MEMPOOL_CPP_BEGINEXTERN()
#define MEMPOOL_CPP_ENDEXTERN()
#endif
/* Select native OS if no target OS defined. */
#if defined(MEMPOOL_CONFIG_FORCEGENERIC) && (MEMPOOL_CONFIG_FORCEGENERIC == 1)
#define MEMPOOL_TARGET_GENERIC
#else
#if defined(__linux__)
#if defined(__SDCC) || defined(__riscv)
#define MEMPOOL_TARGET_GENERIC
#else
#define MEMPOOL_TARGET_LINUX
#endif
#elif defined(_WIN32) || defined(_WIN64) || defined(_MSC_VER) || defined(__CYGWIN__)
#define MEMPOOL_TARGET_WINDOWS
#elif defined(__MACH__) && defined(__APPLE__)
#define MEMPOOL_TARGET_OSX
#elif(defined(__sun__) && defined(__svr4__))
#define MEMPOOL_TARGET_POSIX
#else
#define MEMPOOL_TARGET_GENERIC
#endif
#endif
/* if no platform can be detected, or for testing; forces MEMPOOL_TARGET_GENERIC, which uses malloc/free */
#if !defined(MEMPOOL_CONFIG_FORCEGENERIC)
#define MEMPOOL_CONFIG_FORCEGENERIC 0
#endif
/*
#if defined(MEMPOOL_TARGET_WINDOWS)
#undef MEMPOOL_TARGET_WINDOWS
#define MEMPOOL_TARGET_GENERIC
#endif
*/
#if defined(MEMPOOL_TARGET_WINDOWS)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#if defined(_MSC_VER)
#include <intrin.h>
#endif
#else
#if defined(MEMPOOL_TARGET_LINUX)
#include <errno.h>
#include <sys/mman.h>
#endif
#endif
#ifdef __CELLOS_LV2__
#define MEMPOOL_TARGET_PS3 1
#endif
#ifdef __ORBIS__
#define MEMPOOL_TARGET_PS4 1
#undef NULL
#define NULL ((void*)0)
#endif
/* Set target architecture properties. */
#if defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) || defined(__amd64) || defined(_M_AMD64)
#define MEMPOOL_ARCH_IS64BIT
#endif
#ifndef MEMPOOL_PAGESIZE
#define MEMPOOL_PAGESIZE 4096
#endif
#if !defined(MEMPOOL_LIKELY)
#if defined(__GNUC__)
#define MEMPOOL_LIKELY(x) __builtin_expect(!!(x), 1)
#define MEMPOOL_UNLIKELY(x) __builtin_expect(!!(x), 0)
#else
#define MEMPOOL_LIKELY(x) x
#define MEMPOOL_UNLIKELY(x) x
#endif
#endif
/* Bin types, widths and sizes */
#define MEMPOOL_CONST_MAXSIZET (~0)
#define MEMPOOL_CONST_MALLOCALIGNMENT (8)
/* #define MEMPOOL_CONST_DEFAULTGRANULARITY (128 * 1024) */
#define MEMPOOL_CONST_DEFAULTGRANULARITY (32 * 1024)
/* #define MEMPOOL_CONST_DEFAULTTRIMTHRESHOLD (2 * (1024 * 1024)) */
#define MEMPOOL_CONST_DEFAULTTRIMTHRESHOLD (1 * (1024 * 1024))
/* #define MEMPOOL_CONST_DEFAULTMMAPTHRESHOLD (128 * 1024) */
#define MEMPOOL_CONST_DEFAULTMMAPTHRESHOLD (32 * 1024)
#define MEMPOOL_CONST_MAXRELEASECHECKRATE (255)
/* ------------------- size_t and alignment properties -------------------- */
/* The byte and bit size of a size_t */
#define MEMPOOL_CONST_SIZETSIZE (sizeof(size_t))
#define MEMPOOL_CONST_SIZETBITSIZE (sizeof(size_t) << 3)
/* Some constants coerced to size_t */
/* Annoying but necessary to avoid errors on some platforms */
#define MEMPOOL_CONST_SIZETONE (1)
#define MEMPOOL_CONST_SIZETTWO (2)
#define MEMPOOL_CONST_TWOSIZETSIZES (MEMPOOL_CONST_SIZETSIZE << 1)
#define MEMPOOL_CONST_FOURSIZETSIZES (MEMPOOL_CONST_SIZETSIZE << 2)
#define MEMPOOL_CONST_SIXSIZETSIZES (MEMPOOL_CONST_FOURSIZETSIZES + MEMPOOL_CONST_TWOSIZETSIZES)
#define MEMPOOL_CONST_NSMALLBINS (32)
#define MEMPOOL_CONST_NTREEBINS (32)
#define MEMPOOL_CONST_SMALLBINSHIFT (3)
#define MEMPOOL_CONST_TREEBINSHIFT (8)
#define MEMPOOL_CONST_MINLARGESIZE (MEMPOOL_CONST_SIZETONE << MEMPOOL_CONST_TREEBINSHIFT)
#define MEMPOOL_CONST_MAXSMALLSIZE (MEMPOOL_CONST_MINLARGESIZE - MEMPOOL_CONST_SIZETONE)
#define MEMPOOL_CONST_MAXSMALLREQUEST (MEMPOOL_CONST_MAXSMALLSIZE - MEMPOOL_CHUNK_ALIGNMASK - MEMPOOL_CHUNK_OVERHEAD)
/* weird cornercase in which mremap doesn't get declared despite _GNU_SOURCE. fucking dumb */
#if defined(MEMPOOL_TARGET_LINUX) || defined(MEMPOOL_TARGET_POSIX)
MEMPOOL_CPP_BEGINEXTERN()
void* mremap(void* old_address, size_t old_size, size_t new_size, int flags, ...);
MEMPOOL_CPP_ENDEXTERN()
#endif
/* Described below */
typedef size_t MempoolBindex;
/* Described below */
typedef unsigned int MempoolBinMap;
typedef struct MempoolPlainChunk MempoolPlainChunk;
typedef struct MempoolSegment MempoolSegment;
typedef struct MempoolTreeChunk MempoolTreeChunk;
typedef struct MempoolState MempoolState;
struct MempoolPlainChunk
{
/* Size of previous chunk (if free). */
size_t prev_foot;
/* Size and inuse bits. */
size_t head;
/* double links -- used only if free. */
MempoolPlainChunk *fd;
MempoolPlainChunk *bk;
};
struct MempoolTreeChunk
{
/* The first four fields must be compatible with MempoolPlainChunk */
size_t prev_foot;
size_t head;
MempoolTreeChunk *fd;
MempoolTreeChunk *bk;
MempoolTreeChunk *child[2];
MempoolTreeChunk *parent;
MempoolBindex index;
};
struct MempoolSegment
{
/* base address */
char *base;
/* allocated size */
size_t size;
MempoolSegment *next;
};
struct MempoolState
{
bool forcegeneric;
MempoolBinMap smallmap;
MempoolBinMap treemap;
size_t dvsize;
size_t topsize;
MempoolPlainChunk* dv;
MempoolPlainChunk* top;
size_t trim_check;
size_t release_checks;
MempoolPlainChunk* smallbins[(MEMPOOL_CONST_NSMALLBINS+1)*2];
MempoolTreeChunk* treebins[MEMPOOL_CONST_NTREEBINS];
MempoolSegment seg;
};
MEMPOOL_CPP_BEGINEXTERN()
/**
* the only functions you should be using
*/
/* creates a memory pool state. required to use mempool_user* */
void *mempool_createpool(bool forcegeneric);
/* destroys a memory pool */
void mempool_destroypool(void *msp);
void *mempool_usermalloc(void *msp, size_t nsize);
void *mempool_userfree(void *msp, void *ptr);
void *mempool_userrealloc(void *msp, void *ptr, size_t nsize);
MEMPOOL_CPP_ENDEXTERN()
/*
* if need be, everything below this comment can be moved into a separate file
*/
/* The bit mask value corresponding to MEMPOOL_CONST_MALLOCALIGNMENT */
#define MEMPOOL_CHUNK_ALIGNMASK (MEMPOOL_CONST_MALLOCALIGNMENT - MEMPOOL_CONST_SIZETONE)
/* -------------------------- MMAP support ------------------------------- */
#define MEMPOOL_ON_MFAIL ((void*)(MEMPOOL_CONST_MAXSIZET))
#define MEMPOOL_ON_CMFAIL ((char*)(MEMPOOL_ON_MFAIL)) /* defined for convenience */
#define MEMPOOL_ISDIRECTBIT (MEMPOOL_CONST_SIZETONE)
#if defined(MEMPOOL_TARGET_WINDOWS)
#if defined(MEMPOOL_ARCH_IS64BIT)
/* Number of top bits of the lower 32 bits of an address that must be zero.
** Apparently 0 gives us full 64 bit addresses and 1 gives us the lower 2GB.
*/
#define MEMPOOL_NTAVM_ZEROBITS 1
#else
#define mempool_util_initmmap() ((void)0)
#endif
#else
#define MEMPOOL_MMAP_PROT (PROT_READ | PROT_WRITE)
#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
#define MAP_ANONYMOUS MAP_ANON
#endif
#define MEMPOOL_MMAP_FLAGS (MAP_PRIVATE | MAP_ANONYMOUS)
#if defined(MEMPOOL_ARCH_IS64BIT)
/* 64 bit mode needs special support for allocating memory in the lower 2GB. */
#if defined(MAP_32BIT)
#elif defined(MEMPOOL_TARGET_OSX) || defined(MEMPOOL_TARGET_PS4)
/* OSX mmap() uses a naive first-fit linear search.
** That's perfect for us. Except that -pagezero_size must be set for OSX,
** otherwise the lower 4GB are blocked. And the 32GB RLIMIT_DATA needs
** to be reduced to 250MB.
*/
#if defined(MEMPOOL_TARGET_OSX)
#define MEMPOOL_MMAP_REGION_START ((uintptr_t)0x10000)
#elif defined(MEMPOOL_TARGET_PS4)
#define MEMPOOL_MMAP_REGION_START ((uintptr_t)0x4000)
#else
#define MEMPOOL_MMAP_REGION_START ((uintptr_t)0x10000000)
#endif
#define MEMPOOL_MMAP_REGION_END ((uintptr_t)0x80000000)
#if !defined(MEMPOOL_TARGET_PS4)
#include <sys/resource.h>
#endif
#else
#if 0
#warning "NYI: need an equivalent of MAP_32BIT for this 64 bit OS"
#endif
#endif
#endif
#define mempool_util_initmmap() ((void)0)
#define mempool_util_calldirectmmap(fg, s) mempool_util_callvirtalloc(fg, s)
#if defined(MEMPOOL_TARGET_LINUX)
#define mempool_util_callvirtremap(addr, osz, nsz, mv) mempool_util_callvirtremapactual((addr), (osz), (nsz), (mv))
#define MEMPOOL_CALLMREMAPNOMOVE 0
/* #define CALL_MREMAP_MAYMOVE 1 */
#if defined(MEMPOOL_ARCH_IS64BIT)
#define MEMPOOL_CALLMREMAPMV MEMPOOL_CALLMREMAPNOMOVE
#else
#define MEMPOOL_CALLMREMAPMV CALL_MREMAP_MAYMOVE
#endif
#endif
#endif
#ifndef mempool_util_callvirtremap
#define mempool_util_callvirtremap(addr, osz, nsz, mv) ((void)osz, MEMPOOL_ON_MFAIL)
#endif
/* ------------------- Chunks sizes and alignments ----------------------- */
#define MEMPOOL_MCHUNK_SIZE (sizeof(MempoolPlainChunk))
#define MEMPOOL_CHUNK_OVERHEAD (MEMPOOL_CONST_SIZETSIZE)
/* Direct chunks need a second word of overhead ... */
#define MEMPOOL_DIRECT_CHUNK_OVERHEAD (MEMPOOL_CONST_TWOSIZETSIZES)
/* ... and additional padding for fake next-chunk at foot */
#define MEMPOOL_DIRECTFOOTPAD (MEMPOOL_CONST_FOURSIZETSIZES)
/* The smallest size we can malloc is an aligned minimal chunk */
#define MEMPOOL_MINCHUNKSIZE \
((MEMPOOL_MCHUNK_SIZE + MEMPOOL_CHUNK_ALIGNMASK) & ~MEMPOOL_CHUNK_ALIGNMASK)
/* Bounds on request (not chunk) sizes. */
#define MEMPOOL_REQUESTS_MAX ((~MEMPOOL_MINCHUNKSIZE + 1) << 2)
#define MEMPOOL_REQUESTS_MIN (MEMPOOL_MINCHUNKSIZE - MEMPOOL_CHUNK_OVERHEAD - MEMPOOL_CONST_SIZETONE)
/* the number of bytes to offset an address to align it */
MEMPOOL_INLINE size_t mempool_util_alignoffset(void* a)
{
if(((size_t)a & MEMPOOL_CHUNK_ALIGNMASK) == 0)
{
return 0;
}
return ((MEMPOOL_CONST_MALLOCALIGNMENT - ((size_t)a & MEMPOOL_CHUNK_ALIGNMASK)) & MEMPOOL_CHUNK_ALIGNMASK);
}
/* conversion from malloc headers to user pointers, and back */
MEMPOOL_INLINE void* mempool_util_chunk2mem(void* p)
{
return ((void*)((char*)p + MEMPOOL_CONST_TWOSIZETSIZES));
}
MEMPOOL_INLINE MempoolPlainChunk* mempool_util_mem2chunk(void* mem)
{
return ((MempoolPlainChunk*)((char*)mem - MEMPOOL_CONST_TWOSIZETSIZES));
}
/* chunk associated with aligned address a */
MEMPOOL_INLINE MempoolPlainChunk* mempool_util_alignaschunk(char* a)
{
return (MempoolPlainChunk*)(a + mempool_util_alignoffset(mempool_util_chunk2mem(a)));
}
/* pad request bytes into a usable size */
MEMPOOL_INLINE size_t mempool_util_padrequest(size_t req)
{
return (((req) + MEMPOOL_CHUNK_OVERHEAD + MEMPOOL_CHUNK_ALIGNMASK) & ~MEMPOOL_CHUNK_ALIGNMASK);
}
/* pad request, checking for minimum (but not maximum) */
MEMPOOL_INLINE size_t mempool_util_request2size(size_t req)
{
return (((req) < MEMPOOL_REQUESTS_MIN) ? MEMPOOL_MINCHUNKSIZE : mempool_util_padrequest(req));
}
/* ------------------ Operations on head and foot fields ----------------- */
#define MEMPOOL_PINUSE_BIT (MEMPOOL_CONST_SIZETONE)
#define MEMPOOL_CINUSE_BIT (MEMPOOL_CONST_SIZETTWO)
#define MEMPOOL_INUSE_BITS (MEMPOOL_PINUSE_BIT | MEMPOOL_CINUSE_BIT)
/* Head value for fenceposts */
#define MEMPOOL_FENCEPOST_HEAD (MEMPOOL_INUSE_BITS | MEMPOOL_CONST_SIZETSIZE)
/* extraction of fields from head words */
#define mempool_util_cinuse(p) ((p)->head & MEMPOOL_CINUSE_BIT)
#define mempool_util_pinuse(p) ((p)->head & MEMPOOL_PINUSE_BIT)
#define mempool_util_chunksize(p) ((p)->head & ~(MEMPOOL_INUSE_BITS))
#define mempool_util_clearpinuse(p) ((p)->head &= ~MEMPOOL_PINUSE_BIT)
/* Treat space at ptr +/- offset as a chunk */
#define mempool_util_chunkplusoffset(p, s) ((MempoolPlainChunk*)(((char*)(p)) + (s)))
#define mempool_util_chunkminusoffset(p, s) ((MempoolPlainChunk*)(((char*)(p)) - (s)))
/* Set cinuse and pinuse of this chunk and pinuse of next chunk */
#define mempool_util_setinuseandpinuse(p, s) \
{ \
(p)->head = (s | MEMPOOL_PINUSE_BIT | MEMPOOL_CINUSE_BIT); \
((MempoolPlainChunk*)(((char*)(p)) + (s)))->head |= MEMPOOL_PINUSE_BIT; \
}
/* Set size, cinuse and pinuse bit of this chunk */
#define mempool_util_setsizeandpinuseofinusechunk(p, s) \
{ \
(p)->head = ((s) | MEMPOOL_PINUSE_BIT | MEMPOOL_CINUSE_BIT); \
}
/* Ptr to next or previous physical MempoolPlainChunk. */
MEMPOOL_INLINE MempoolPlainChunk* mempool_util_nextchunk(MempoolPlainChunk* p)
{
return ((MempoolPlainChunk*)(((char*)p) + (p->head & ~MEMPOOL_INUSE_BITS)));
}
/* Get/set size at footer */
MEMPOOL_INLINE void mempool_util_setfoot(MempoolPlainChunk* p, size_t s)
{
((MempoolPlainChunk*)((char*)p + s))->prev_foot = s;
}
/* Set size, pinuse bit, and foot */
MEMPOOL_INLINE void mempool_util_setsizeand_pinuseoffreechunk(MempoolPlainChunk* p, size_t s)
{
p->head = (s | MEMPOOL_PINUSE_BIT);
mempool_util_setfoot(p, s);
}
/* Set size, pinuse bit, foot, and clear next pinuse */
MEMPOOL_INLINE void mempool_util_setfreewithpinuse(MempoolPlainChunk* p, size_t s, MempoolPlainChunk* n)
{
mempool_util_clearpinuse(n);
mempool_util_setsizeand_pinuseoffreechunk(p, s);
}
MEMPOOL_INLINE bool mempool_util_isdirect(MempoolPlainChunk* p)
{
return (!(p->head & MEMPOOL_PINUSE_BIT) && (p->prev_foot & MEMPOOL_ISDIRECTBIT));
}
/* Get the internal overhead associated with chunk p */
MEMPOOL_INLINE size_t mempool_util_overheadfor(MempoolPlainChunk* p)
{
return (mempool_util_isdirect(p) ? MEMPOOL_DIRECT_CHUNK_OVERHEAD : MEMPOOL_CHUNK_OVERHEAD);
}
/* ---------------------- Overlaid data structures ----------------------- */
/* A little helper macro for trees */
MEMPOOL_INLINE MempoolTreeChunk* mempool_util_leftmostchild(MempoolTreeChunk* t)
{
return (t->child[0] != 0 ? t->child[0] : t->child[1]);
}
MEMPOOL_INLINE bool mempool_util_isstateinitialized(MempoolState* mst)
{
return (mst->top != 0);
}
/* -------------------------- system alloc setup ------------------------- */
/* page-align a size */
MEMPOOL_INLINE size_t mempool_util_pagealign(size_t sz)
{
return ((sz + (MEMPOOL_PAGESIZE - MEMPOOL_CONST_SIZETONE)) & ~(MEMPOOL_PAGESIZE - MEMPOOL_CONST_SIZETONE));
}
/* granularity-align a size */
MEMPOOL_INLINE size_t mempool_util_granularityalign(size_t sz)
{
return ((sz + (MEMPOOL_CONST_DEFAULTGRANULARITY - MEMPOOL_CONST_SIZETONE)) & ~(MEMPOOL_CONST_DEFAULTGRANULARITY - MEMPOOL_CONST_SIZETONE));
}
/* True if segment segm holds address a */
MEMPOOL_INLINE bool mempool_util_segmentholds(MempoolSegment* segm, void* a)
{
return ((char*)a >= segm->base && (char*)a < segm->base + segm->size);
}
MEMPOOL_INLINE size_t mempool_util_virtalign(size_t sz)
{
#if defined(MEMPOOL_TARGET_WINDOWS)
return mempool_util_granularityalign(sz);
#else
return mempool_util_pagealign(sz);
#endif
}
#if defined(MEMPOOL_TARGET_WINDOWS)
#if defined(MEMPOOL_ARCH_IS64BIT)
/* Undocumented, but hey, that's what we all love so much about Windows. */
typedef long (*PNTAVM)(HANDLE handle, void** addr, ULONG zbits, size_t* size, ULONG alloctype, ULONG prot);
static PNTAVM ntavm;
#endif
MEMPOOL_INLINE void mempool_util_initmmap()
{
ntavm = (PNTAVM)GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtAllocateVirtualMemory");
}
/* Win64 32 bit MMAP via NtAllocateVirtualMemory. */
MEMPOOL_INLINE void* mempool_util_callvirtalloc(bool forcegeneric, size_t size)
{
#if defined(MEMPOOL_ARCH_IS64BIT)
long st;
DWORD olderr;
void* ptr;
#else
void* ptr;
DWORD olderr;
#endif
(void)forcegeneric;
#if defined(MEMPOOL_ARCH_IS64BIT)
olderr = GetLastError();
ptr = NULL;
st = ntavm(INVALID_HANDLE_VALUE, &ptr, MEMPOOL_NTAVM_ZEROBITS, &size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
SetLastError(olderr);
return st == 0 ? ptr : MEMPOOL_ON_MFAIL;
#else
olderr = GetLastError();
ptr = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
SetLastError(olderr);
return ptr ? ptr : MEMPOOL_ON_MFAIL;
#endif
}
/* For direct MMAP, use MEM_TOP_DOWN to minimize interference */
MEMPOOL_INLINE void* mempool_util_calldirectmmap(bool forcegeneric, size_t size)
{
#if defined(MEMPOOL_ARCH_IS64BIT)
long st;
DWORD olderr;
void* ptr;
#else
void* ptr;
DWORD olderr;
#endif
(void)forcegeneric;
#if defined(MEMPOOL_ARCH_IS64BIT)
olderr = GetLastError();
ptr = NULL;
st = ntavm(INVALID_HANDLE_VALUE, &ptr, MEMPOOL_NTAVM_ZEROBITS, &size, MEM_RESERVE | MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE);
SetLastError(olderr);
return st == 0 ? ptr : MEMPOOL_ON_MFAIL;
#else
olderr = GetLastError();
ptr = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE);
SetLastError(olderr);
return ptr ? ptr : MEMPOOL_ON_MFAIL;
#endif
}
/* This function supports releasing coalesed segments */
MEMPOOL_INLINE int mempool_util_callvirtfree(bool forcegeneric, void* ptr, size_t size)
{
char* cptr;
DWORD olderr;
MEMORY_BASIC_INFORMATION minfo;
(void)forcegeneric;
olderr = GetLastError();
cptr = (char*)ptr;
while(size)
{
if(VirtualQuery(cptr, &minfo, sizeof(minfo)) == 0)
{
return -1;
}
if(minfo.BaseAddress != cptr || minfo.AllocationBase != cptr || minfo.State != MEM_COMMIT || minfo.RegionSize > size)
{
return -1;
}
if(VirtualFree(cptr, 0, MEM_RELEASE) == 0)
{
return -1;
}
cptr += minfo.RegionSize;
size -= minfo.RegionSize;
}
SetLastError(olderr);
return 0;
}
#else
MEMPOOL_INLINE void* mempool_util_callvirtalloc(bool forcegeneric, size_t size)
{
if(forcegeneric)
{
goto ongeneric;
}
#if defined(MEMPOOL_ARCH_IS64BIT)
/* 64 bit mode needs special support for allocating memory in the lower 2GB. */
#if defined(MAP_32BIT)
/* Actually this only gives us max. 1GB in current Linux kernels. */
int olderr;
void* ptr;
olderr = errno;
ptr = mmap(NULL, size, MEMPOOL_MMAP_PROT, MAP_32BIT | MEMPOOL_MMAP_FLAGS, -1, 0);
errno = olderr;
return ptr;
#elif defined(MEMPOOL_TARGET_OSX) || defined(MEMPOOL_TARGET_PS4)
int olderr;
int retry;
void* p;
#if !defined(MEMPOOL_TARGET_PS4)
struct rlimit rlim;
#endif
static uintptr_t allochint = MEMPOOL_MMAP_REGION_START;
#if !defined(MEMPOOL_TARGET_PS4)
static int rlimit_modified = 0;
#endif
olderr = errno;
/* Hint for next allocation. Doesn't need to be thread-safe. */
retry = 0;
#if !defined(MEMPOOL_TARGET_PS4)
if(MEMPOOL_UNLIKELY(rlimit_modified == 0))
{
rlim.rlim_cur = rlim.rlim_max = MEMPOOL_MMAP_REGION_START;
setrlimit(RLIMIT_DATA, &rlim); /* Ignore result. May fail below. */
rlimit_modified = 1;
}
#endif
for(;;)
{
p = mmap((void*)allochint, size, MEMPOOL_MMAP_PROT, MEMPOOL_MMAP_FLAGS, -1, 0);
if((uintptr_t)p >= MEMPOOL_MMAP_REGION_START && (uintptr_t)p + size < MEMPOOL_MMAP_REGION_END)
{
allochint = (uintptr_t)p + size;
errno = olderr;
return p;
}
if(p != MEMPOOL_ON_CMFAIL)
{
munmap(p, size);
}
if(retry)
{
break;
}
retry = 1;
allochint = MEMPOOL_MMAP_REGION_START;
}
errno = olderr;
return MEMPOOL_ON_CMFAIL
#endif
#else
/* 32 bit mode is easy. */
#if !defined(MEMPOOL_TARGET_GENERIC)
int olderr;
void* ptr;
olderr = errno;
ptr = mmap(NULL, size, MEMPOOL_MMAP_PROT, MEMPOOL_MMAP_FLAGS, -1, 0);
errno = olderr;
return ptr;
#endif
#endif
ongeneric:
return malloc(size);
}
MEMPOOL_INLINE int mempool_util_callvirtfree(bool forcegeneric, void* ptr, size_t size)
{
#if !defined(MEMPOOL_TARGET_GENERIC)
int ret;
int olderr;
#endif
if(forcegeneric)
{
goto ongeneric;
}
#if !defined(MEMPOOL_TARGET_GENERIC)
olderr = errno;
ret = munmap(ptr, size);
errno = olderr;
return ret;
#endif
ongeneric:
(void)size;
free(ptr);
return 0;
}
#if defined(MEMPOOL_TARGET_LINUX)
/* Need to define _GNU_SOURCE to get the mremap prototype. */
MEMPOOL_INLINE void* mempool_util_callvirtremapactual(void* ptr, size_t osz, size_t nsz, int flags)
{
int olderr;
olderr = errno;
ptr = mremap(ptr, osz, nsz, flags);
errno = olderr;
return ptr;
}
#endif
#endif
/* In generic mode the host allocator (malloc/free) keeps released segments in
** its own arena, so the pages are never given back to the OS the way munmap
** would. Nudge the host allocator to actually release the free memory. */
#if defined(MEMPOOL_TARGET_GENERIC)
#if defined(__GLIBC__) || defined(__MUSL__)
MEMPOOL_INLINE void mempool_util_releasetoos()
{
malloc_trim(0);
}
#else
MEMPOOL_INLINE void mempool_util_releasetoos()
{
(void)0;
}
#endif
#else
MEMPOOL_INLINE void mempool_util_releasetoos()
{
(void)0;
}
#endif
/*
* do not attempt to optimize these two functions further.
* bad things will happen if you do.
*/
MEMPOOL_INLINE int mempool_util_nativebitscanreverse(uint64_t x)
{
static const char bsr_debruijntable[64] = {
0, 47, 1, 56, 48, 27, 2, 60, 57, 49, 41, 37, 28, 16, 3, 61,
54, 58, 35, 52, 50, 42, 21, 44, 38, 32, 29, 23, 17, 11, 4, 62,
46, 55, 26, 59, 40, 36, 15, 53, 34, 51, 20, 43, 31, 22, 10, 45,
25, 39, 14, 33, 19, 30, 9, 24, 13, 18, 8, 12, 7, 6, 5, 63,
};
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
x |= x >> 32;
return bsr_debruijntable[(x * 0x03f79d71b4cb0a89) >> 58];
}
MEMPOOL_INLINE int mempool_util_nativebitscanforward(uint64_t x)
{
uint32_t l;
uint32_t r;
x &= -x;
l = x | x >> 32;
r = !!(x >> 32);
r <<= 1;
r += !!((l & 0xffff0000));
r <<= 1;
r += !!((l & 0xff00ff00));
r <<= 1;
r += !!((l & 0xf0f0f0f0));
r <<= 1;
r += !!((l & 0xcccccccc));
r <<= 1;
r += !!((l & 0xaaaaaaaa));
return r;
}
/* Return segment holding given address */
MEMPOOL_INLINE MempoolSegment* mempool_util_segmentholding(MempoolState* mctx, char* addr)
{
MempoolSegment* sp;
sp = &mctx->seg;
for(;;)
{
if(addr >= sp->base && addr < sp->base + sp->size)
{
return sp;
}
if((sp = sp->next) == 0)
{
return NULL;
}
}
return NULL;
}
/* Return true if segment contains a segment link */
MEMPOOL_INLINE int mempool_util_hassegmentlink(MempoolState* mctx, MempoolSegment* ss)
{
MempoolSegment* sp;
sp = &mctx->seg;
for(;;)
{
if((char*)sp >= ss->base && (char*)sp < ss->base + ss->size)
{
return 1;
}
if((sp = sp->next) == 0)
{
return 0;
}
}
return 0;
}
/*
mempool_util_topfootsize is padding at the end of a segment, including space
that may be needed to place segment records and fenceposts when new
noncontiguous segments are added.
*/
MEMPOOL_INLINE size_t mempool_util_topfootsize()
{
return (mempool_util_alignoffset(mempool_util_chunk2mem(0)) + mempool_util_padrequest(sizeof(MempoolSegment)) + MEMPOOL_MINCHUNKSIZE);
}
/* ---------------------------- Indexing Bins ---------------------------- */
MEMPOOL_INLINE bool mempool_util_issmall(size_t s)
{
return ((s >> MEMPOOL_CONST_SMALLBINSHIFT) < MEMPOOL_CONST_NSMALLBINS);
}
MEMPOOL_INLINE MempoolBindex mempool_util_smallindex(MempoolBindex s)
{
return (s >> MEMPOOL_CONST_SMALLBINSHIFT);
}
MEMPOOL_INLINE size_t mempool_util_smallindex2size(MempoolBindex i)
{
return (i << MEMPOOL_CONST_SMALLBINSHIFT);
}
/* addressing by index. See above about smallbin repositioning */
MEMPOOL_INLINE MempoolPlainChunk* mempool_util_smallbinat(MempoolState* mst, size_t i)
{
return ((MempoolPlainChunk*)((char*)&(mst->smallbins[i << 1])));
}
MEMPOOL_INLINE MempoolTreeChunk** mempool_util_treebinat(MempoolState* mst, size_t i)
{
return (&(mst->treebins[i]));
}
/* assign tree index for size sz to variable desti */
MEMPOOL_INLINE void mempool_util_computetreeindex(size_t sz, size_t* desti)
{
unsigned int x;
unsigned int k;
x = (unsigned int)(sz >> MEMPOOL_CONST_TREEBINSHIFT);
if(x == 0)
{
(*desti) = 0;
}
else if(x > 0xFFFF)
{
(*desti) = MEMPOOL_CONST_NTREEBINS - 1;
}
else
{
k = mempool_util_nativebitscanreverse(x);
(*desti) = (MempoolBindex)((k << 1) + ((sz >> (k + (MEMPOOL_CONST_TREEBINSHIFT - 1)) & 1)));
}
}
/* Shift placing maximum resolved bit in a treebin at i as sign bit */
MEMPOOL_INLINE size_t mempool_util_leftshiftfortreeindex(size_t i)
{
if(i == MEMPOOL_CONST_NTREEBINS - 1)
{
return 0;
}
return ((MEMPOOL_CONST_SIZETBITSIZE - MEMPOOL_CONST_SIZETONE) - ((i >> 1) + MEMPOOL_CONST_TREEBINSHIFT - 2));
}
/* ------------------------ Operations on bin maps ----------------------- */
/* bit corresponding to given index */
MEMPOOL_INLINE MempoolBinMap mempool_util_idx2bit(size_t i)
{
return ((MempoolBinMap)(1) << i);
}
/* Mark/Clear bits with given index */
MEMPOOL_INLINE void mempool_util_marksmallmap(MempoolState* mst, size_t i)
{
mst->smallmap |= mempool_util_idx2bit(i);
}
MEMPOOL_INLINE void mempool_util_clearsmallmap(MempoolState* mst, size_t i)
{
mst->smallmap &= ~mempool_util_idx2bit(i);
}
MEMPOOL_INLINE bool mempool_util_smallmapismarked(MempoolState* mst, size_t i)
{
return (mst->smallmap & mempool_util_idx2bit(i));
}
MEMPOOL_INLINE void mempool_util_marktreemap(MempoolState* mst, size_t i)
{
mst->treemap |= mempool_util_idx2bit(i);
}
MEMPOOL_INLINE void mempool_util_cleartreemap(MempoolState* mst, size_t i)
{
mst->treemap &= ~mempool_util_idx2bit(i);
}
MEMPOOL_INLINE bool mempool_util_treemapismarked(MempoolState* mst, size_t i)
{
return (mst->treemap & mempool_util_idx2bit(i));
}
/* mask with all bits to left of least bit of x on */
MEMPOOL_INLINE MempoolBinMap mempool_util_leftbits(MempoolBinMap x)
{
return ((x << 1) | (~(x << 1) + 1));
}
/* Set cinuse bit and pinuse bit of next chunk */
MEMPOOL_INLINE void mempool_util_setinuse(MempoolPlainChunk* p, size_t s)
{
p->head = ((p->head & MEMPOOL_PINUSE_BIT) | s | MEMPOOL_CINUSE_BIT);
((MempoolPlainChunk*)(((char*)p) + s))->head |= MEMPOOL_PINUSE_BIT;
}
/* ----------------------- Operations on smallbins ----------------------- */
/* Link a free chunk into a smallbin */
MEMPOOL_INLINE void mempool_util_insertsmallchunk(MempoolState* mst, MempoolPlainChunk* p, size_t sz)
{
MempoolBindex i;
MempoolPlainChunk* b;
MempoolPlainChunk* f;
i = mempool_util_smallindex(sz);
b = mempool_util_smallbinat(mst, i);
f = b;
if(!mempool_util_smallmapismarked(mst, i))
{
mempool_util_marksmallmap(mst, i);
}
else
{
f = b->fd;
}
b->fd = p;
f->bk = p;
p->fd = f;
p->bk = b;
}
/* Unlink a chunk from a smallbin */
MEMPOOL_INLINE void mempool_util_unlinksmallchunk(MempoolState* mst, MempoolPlainChunk* p, size_t sz)
{
MempoolBindex i;
MempoolPlainChunk* b;
MempoolPlainChunk* f;
f = p->fd;
b = p->bk;
i = mempool_util_smallindex(sz);
if(f == b)
{
mempool_util_clearsmallmap(mst, i);
}
else
{
f->bk = b;
b->fd = f;
}
}
/* Unlink the first chunk from a smallbin */
MEMPOOL_INLINE void mempool_util_unlinkfirstsmallchunk(MempoolState* mst, MempoolPlainChunk* b, MempoolPlainChunk* p, size_t i)
{
MempoolPlainChunk* f;
f = p->fd;
if(b == f)
{
mempool_util_clearsmallmap(mst, i);
}
else
{
b->fd = f;
f->bk = b;
}
}