-
Notifications
You must be signed in to change notification settings - Fork 11
/
buddy_alloc.h
2172 lines (1810 loc) · 72.3 KB
/
buddy_alloc.h
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
/*
* Copyright 2021 Stanislav Paskalev <spaskalev@protonmail.com>
*
* A binary buddy memory allocator
*
* To include and use it in your project do the following
* 1. Add buddy_alloc.h (this file) to your include directory
* 2. Include the header in places where you need to use the allocator
* 3. In one of your source files #define BUDDY_ALLOC_IMPLEMENTATION
* and then import the header. This will insert the implementation.
*
* Latest version is available at https://github.com/spaskalev/buddy_alloc
*/
#ifndef BUDDY_ALLOC_H
#define BUDDY_ALLOC_H
#ifndef BUDDY_HEADER
#include <limits.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <sys/types.h>
#ifndef BUDDY_PRINTF
#include <stdio.h>
#endif
#endif
#ifdef __cplusplus
#ifndef BUDDY_CPP_MANGLED
extern "C" {
#endif
#endif
struct buddy;
/* Returns the size of a buddy required to manage a block of the specified size */
size_t buddy_sizeof(size_t memory_size);
/*
* Returns the size of a buddy required to manage a block of the specified size
* using a non-default alignment.
*/
size_t buddy_sizeof_alignment(size_t memory_size, size_t alignment);
/* Initializes a binary buddy memory allocator at the specified location */
struct buddy *buddy_init(unsigned char *at, unsigned char *main, size_t memory_size);
/* Initializes a binary buddy memory allocator at the specified location using a non-default alignment */
struct buddy *buddy_init_alignment(unsigned char *at, unsigned char *main, size_t memory_size, size_t alignment);
/*
* Initializes a binary buddy memory allocator embedded in the specified arena.
* The arena's capacity is reduced to account for the allocator metadata.
*/
struct buddy *buddy_embed(unsigned char *main, size_t memory_size);
/*
* Returns the address of a previously-created buddy allocator at the arena.
* Use to get a new handle to the allocator when the arena is moved or copied.
*/
struct buddy *buddy_get_embed_at(unsigned char *main, size_t memory_size);
/*
* Initializes a binary buddy memory allocator embedded in the specified arena
* using a non-default alignment.
* The arena's capacity is reduced to account for the allocator metadata.
*/
struct buddy *buddy_embed_alignment(unsigned char *main, size_t memory_size, size_t alignment);
/*
* Returns the address of a previously-created buddy allocator at the arena.
* Use to get a new handle to the allocator when the arena is moved or copied.
*/
struct buddy *buddy_get_embed_at_alignment(unsigned char *main, size_t memory_size, size_t alignment);
/*
* Resizes the arena and allocator metadata to a new size.
*
* Existing allocations are preserved. If an allocation is to fall outside
* of the arena after a downsizing the resize operation fails.
*
* Returns a pointer to allocator on successful resize. This will be
* the same pointer when the allocator is external to the arena. If the
* allocator is embedded in the arena the old pointer to the allocator
* must not be used after resizing!
*
* Returns NULL on failure. The allocations and allocator pointer
* are preserved.
*/
struct buddy *buddy_resize(struct buddy *buddy, size_t new_memory_size);
/* Tests if the arena can be shrunk in half */
bool buddy_can_shrink(struct buddy *buddy);
/* Tests if the arena is completely empty */
bool buddy_is_empty(struct buddy *buddy);
/* Tests if the arena is completely full */
bool buddy_is_full(struct buddy *buddy);
/* Reports the arena size */
size_t buddy_arena_size(struct buddy *buddy);
/* Reports the arena's free size. Note that this is (often) not a continuous size
but the sum of all free slots in the buddy. */
size_t buddy_arena_free_size(struct buddy *buddy);
/*
* Allocation functions
*/
/* Use the specified buddy to allocate memory. See malloc. */
void *buddy_malloc(struct buddy *buddy, size_t requested_size);
/* Use the specified buddy to allocate zeroed memory. See calloc. */
void *buddy_calloc(struct buddy *buddy, size_t members_count, size_t member_size);
/* Realloc semantics are a joke. See realloc. */
void *buddy_realloc(struct buddy *buddy, void *ptr, size_t requested_size, bool ignore_data);
/* Realloc-like behavior that checks for overflow. See reallocarray */
void *buddy_reallocarray(struct buddy *buddy, void *ptr,
size_t members_count, size_t member_size, bool ignore_data);
/* Use the specified buddy to free memory. See free. */
void buddy_free(struct buddy *buddy, void *ptr);
enum buddy_safe_free_status {
BUDDY_SAFE_FREE_SUCCESS,
BUDDY_SAFE_FREE_BUDDY_IS_NULL,
BUDDY_SAFE_FREE_INVALID_ADDRESS,
BUDDY_SAFE_FREE_SIZE_MISMATCH,
BUDDY_SAFE_FREE_ALREADY_FREE,
};
/* A (safer) free with a size. Will not free unless the size fits the target span. */
enum buddy_safe_free_status buddy_safe_free(struct buddy *buddy, void *ptr, size_t requested_size);
/*
* Reservation functions
*/
/* Reserve a range by marking it as allocated. Useful for dealing with physical memory. */
void buddy_reserve_range(struct buddy *buddy, void *ptr, size_t requested_size);
/* Release a reserved memory range. Unsafe, this can mess up other allocations if called with wrong parameters! */
void buddy_unsafe_release_range(struct buddy *buddy, void *ptr, size_t requested_size);
/*
* Iteration functions
*/
/*
* Iterate through the free and allocated slots and call the provided function for each of them.
*
* If the provided function returns a non-NULL result the iteration stops and the result
* is returned to called. NULL is returned upon completing iteration without stopping.
*
* The iteration order is implementation-defined and may change between versions.
*/
void *buddy_walk(struct buddy *buddy, void *(fp)(void *ctx, void *addr, size_t slot_size, size_t allocated), void *ctx);
/*
* Miscellaneous functions
*/
/*
* Calculates the fragmentation in the allocator in a 0 - 255 range.
* NOTE: if you are using a non-power-of-two sized arena the maximum upper bound can be lower.
*/
unsigned char buddy_fragmentation(struct buddy *buddy);
#ifdef BUDDY_EXPERIMENTAL_CHANGE_TRACKING
/*
* Enable change tracking for this allocator instance.
*
* This will store a header at the start of the arena that contains the function pointer (tracker) and
* a void* (context). The tracker will be called with the context, the start of changed memory and its length.
*
* This function MUST be called before any allocations are performed!
*
* Change tracking is in effect only for allocation functions, resizing functions are excluded from it.
*
* This is an experimental feature designed to facilitate integration with https://github.com/spaskalev/libpvl
*
* The API is not (yet) part of the allocator contract and its semantic versioning!
*/
void buddy_enable_change_tracking(struct buddy* buddy, void* context, void (*tracker) (void*, unsigned char*, size_t));
#endif
#ifdef __cplusplus
#ifndef BUDDY_CPP_MANGLED
}
#endif
#endif
#endif /* BUDDY_ALLOC_H */
#ifdef BUDDY_ALLOC_IMPLEMENTATION
#undef BUDDY_ALLOC_IMPLEMENTATION
#ifdef __cplusplus
#ifndef BUDDY_CPP_MANGLED
extern "C" {
#endif
#endif
#ifndef BUDDY_ALLOC_ALIGN
#define BUDDY_ALLOC_ALIGN (sizeof(size_t) * CHAR_BIT)
#endif
#ifdef __cplusplus
#ifndef BUDDY_ALIGNOF
#define BUDDY_ALIGNOF(x) alignof(x)
#endif
#else /* not __cplusplus */
#ifndef BUDDY_ALIGNOF
#ifndef _MSC_VER
#define BUDDY_ALIGNOF(x) __alignof__(x)
#else
#define BUDDY_ALIGNOF(x) _Alignof(x)
#endif
#endif
#endif /* __cplusplus */
/* ssize_t is a POSIX extension */
#if defined(_MSC_VER) && !defined(_SSIZE_T_DEFINED)
#if _WIN64
typedef signed long long ssize_t;
#else
typedef signed long ssize_t;
#endif
#define _SSIZE_T_DEFINED
#endif
/* Support compiling with Pelles C */
#if defined(__POCC__) && defined(__POCC_TARGET__)
#if __POCC_TARGET__ == 3
typedef signed long long ssize_t;
#elif __POCC_TARGET__ == 1
typedef signed long ssize_t;
#else
#error Uknown POCC target
#endif
#endif
#ifndef BUDDY_PRINTF
#define BUDDY_PRINTF printf
#endif
/*
* Debug functions
*/
/* Implementation defined */
void buddy_debug(struct buddy *buddy);
struct buddy_change_tracker {
void* context;
void (*tracker) (void*, unsigned char*, size_t);
};
struct buddy_tree;
struct buddy_tree_pos {
size_t index;
size_t depth;
};
#ifdef __cplusplus
#define INVALID_POS buddy_tree_pos{ 0, 0 }
#else
#define INVALID_POS ((struct buddy_tree_pos){ 0, 0 })
#endif
struct buddy_tree_interval {
struct buddy_tree_pos from;
struct buddy_tree_pos to;
};
struct buddy_tree_walk_state {
struct buddy_tree_pos starting_pos;
struct buddy_tree_pos current_pos;
unsigned int going_up;
unsigned int walk_done;
};
/*
* Initialization functions
*/
/* Returns the size of a buddy allocation tree of the desired order*/
static size_t buddy_tree_sizeof(uint8_t order);
/* Initializes a buddy allocation tree at the specified location */
static struct buddy_tree *buddy_tree_init(unsigned char *at, uint8_t order);
/* Indicates whether this is a valid position for the tree */
static bool buddy_tree_valid(struct buddy_tree *t, struct buddy_tree_pos pos);
/* Returns the order of the specified buddy allocation tree */
static uint8_t buddy_tree_order(struct buddy_tree *t);
/*
* Resize the tree to the new order. When downsizing the left subtree is picked.
* Caller must ensure enough space for the new order.
*/
static void buddy_tree_resize(struct buddy_tree *t, uint8_t desired_order);
#ifdef BUDDY_EXPERIMENTAL_CHANGE_TRACKING
/* Enable change tracking state for this tree. */
static void buddy_tree_enable_change_tracking(struct buddy_tree *t);
#endif /* BUDDY_EXPERIMENTAL_CHANGE_TRACKING */
/*
* Navigation functions
*/
/* Returns a position at the root of a buddy allocation tree */
static struct buddy_tree_pos buddy_tree_root(void);
/* Returns the leftmost child node */
static struct buddy_tree_pos buddy_tree_leftmost_child(struct buddy_tree *t);
/* Returns the tree depth of the indicated position */
static inline size_t buddy_tree_depth(struct buddy_tree_pos pos);
/* Returns the left child node position. Does not check if that is a valid position */
static inline struct buddy_tree_pos buddy_tree_left_child(struct buddy_tree_pos pos);
/* Returns the right child node position. Does not check if that is a valid position */
static inline struct buddy_tree_pos buddy_tree_right_child(struct buddy_tree_pos pos);
/* Returns the current sibling node position. Does not check if that is a valid position */
static inline struct buddy_tree_pos buddy_tree_sibling(struct buddy_tree_pos pos);
/* Returns the parent node position or an invalid position if there is no parent node */
static inline struct buddy_tree_pos buddy_tree_parent(struct buddy_tree_pos pos);
/* Returns the right adjacent node position or an invalid position if there is no right adjacent node */
static struct buddy_tree_pos buddy_tree_right_adjacent(struct buddy_tree_pos pos);
/* Returns the at-depth index of the indicated position */
static size_t buddy_tree_index(struct buddy_tree_pos pos);
/* Return the interval of the deepest positions spanning the indicated position */
static struct buddy_tree_interval buddy_tree_interval(struct buddy_tree *t, struct buddy_tree_pos pos);
/* Checks if one interval contains another */
static bool buddy_tree_interval_contains(struct buddy_tree_interval outer,
struct buddy_tree_interval inner);
/* Return a walk state structure starting from the root of a tree */
static struct buddy_tree_walk_state buddy_tree_walk_state_root(void);
/* Walk the tree, keeping track in the provided state structure */
static unsigned int buddy_tree_walk(struct buddy_tree *t, struct buddy_tree_walk_state *state);
/*
* Allocation functions
*/
/* Returns the free capacity at or underneath the indicated position */
static size_t buddy_tree_status(struct buddy_tree *t, struct buddy_tree_pos pos);
/* Marks the indicated position as allocated and propagates the change */
static void buddy_tree_mark(struct buddy_tree *t, struct buddy_tree_pos pos);
enum buddy_tree_release_status {
BUDDY_TREE_RELEASE_SUCCESS,
BUDDY_TREE_RELEASE_FAIL_PARTIALLY_USED,
};
/* Marks the indicated position as free and propagates the change */
static enum buddy_tree_release_status buddy_tree_release(struct buddy_tree *t, struct buddy_tree_pos pos);
/* Returns a free position at the specified depth or an invalid position */
static struct buddy_tree_pos buddy_tree_find_free(struct buddy_tree *t, uint8_t depth);
/* Tests if the indicated position is available for allocation */
static bool buddy_tree_is_free(struct buddy_tree *t, struct buddy_tree_pos pos);
/* Tests if the tree can be shrank in half */
static bool buddy_tree_can_shrink(struct buddy_tree *t);
/*
* Integration functions
*/
/* Get a pointer to the parent buddy struct */
static struct buddy* buddy_tree_buddy(struct buddy_tree* t);
/*
* Debug functions
*/
/* Implementation defined */
static void buddy_tree_debug(struct buddy_tree *t, struct buddy_tree_pos pos, size_t start_size);
/* Implementation defined */
unsigned int buddy_tree_check_invariant(struct buddy_tree *t, struct buddy_tree_pos pos);
/* Report fragmentation in a 0 - 255 range */
static unsigned char buddy_tree_fragmentation(struct buddy_tree *t);
/*
* A char-backed bitset implementation
*/
static size_t bitset_sizeof(size_t elements);
struct bitset_range {
size_t from_bucket;
size_t to_bucket;
uint8_t from_index;
uint8_t to_index;
};
static inline struct bitset_range bitset_range(size_t from_pos, size_t to_pos);
static void bitset_set_range(unsigned char *bitset, struct bitset_range range);
static void bitset_clear_range(unsigned char *bitset, struct bitset_range range);
static size_t bitset_count_range(unsigned char *bitset, struct bitset_range range);
static inline void bitset_set(unsigned char *bitset, size_t pos);
static inline void bitset_clear(unsigned char *bitset, size_t pos);
static inline bool bitset_test(const unsigned char *bitset, size_t pos);
static void bitset_shift_left(unsigned char *bitset, size_t from_pos, size_t to_pos, size_t by);
static void bitset_shift_right(unsigned char *bitset, size_t from_pos, size_t to_pos, size_t by);
/*
* Debug functions
*/
/* Implementation defined */
void bitset_debug(unsigned char *bitset, size_t length);
/*
* Bits
*/
/* Returns the number of set bits in the given byte */
static unsigned int popcount_byte(unsigned char b);
/* Returns the index of the highest bit set (1-based) */
static size_t highest_bit_position(size_t value);
/* Returns the nearest larger or equal power of two */
static inline size_t ceiling_power_of_two(size_t value);
/* Return two to the power of order */
static inline size_t two_to_the_power_of(size_t order);
/*
* Math
*/
/* Calculates the integer square root of an integer */
static inline size_t integer_square_root(size_t f);
/*
Implementation
*/
const unsigned int BUDDY_RELATIVE_MODE = 1;
/*
* A binary buddy memory allocator
*/
struct buddy {
size_t memory_size;
size_t alignment;
union {
unsigned char *main;
ptrdiff_t main_offset;
} arena;
size_t buddy_flags;
};
struct buddy_embed_check {
unsigned int can_fit;
size_t offset;
size_t buddy_size;
};
static unsigned int is_valid_alignment(size_t alignment);
static size_t buddy_tree_order_for_memory(size_t memory_size, size_t alignment);
static size_t depth_for_size(struct buddy *buddy, size_t requested_size);
static inline size_t size_for_depth(struct buddy *buddy, size_t depth);
static unsigned char *address_for_position(struct buddy *buddy, struct buddy_tree_pos pos);
static struct buddy_tree_pos position_for_address(struct buddy *buddy, const unsigned char *addr);
static unsigned char *buddy_main(struct buddy *buddy);
static unsigned int buddy_relative_mode(struct buddy *buddy);
static struct buddy_tree *buddy_tree(struct buddy *buddy);
static size_t buddy_effective_memory_size(struct buddy *buddy);
static size_t buddy_virtual_slots(struct buddy *buddy);
static void buddy_toggle_virtual_slots(struct buddy *buddy, unsigned int state);
static void buddy_toggle_range_reservation(struct buddy *buddy, void *ptr, size_t requested_size, unsigned int state);
static struct buddy *buddy_resize_standard(struct buddy *buddy, size_t new_memory_size);
static struct buddy *buddy_resize_embedded(struct buddy *buddy, size_t new_memory_size);
static bool buddy_is_free(struct buddy *buddy, size_t from);
static struct buddy_embed_check buddy_embed_offset(size_t memory_size, size_t alignment);
static struct buddy_tree_pos deepest_position_for_offset(struct buddy *buddy, size_t offset);
size_t buddy_sizeof(size_t memory_size) {
return buddy_sizeof_alignment(memory_size, BUDDY_ALLOC_ALIGN);
}
size_t buddy_sizeof_alignment(size_t memory_size, size_t alignment) {
size_t buddy_tree_order;
if (!is_valid_alignment(alignment)) {
return 0; /* invalid */
}
if (memory_size < alignment) {
return 0; /* invalid */
}
buddy_tree_order = buddy_tree_order_for_memory(memory_size, alignment);
return sizeof(struct buddy) + buddy_tree_sizeof((uint8_t)buddy_tree_order);
}
struct buddy *buddy_init(unsigned char *at, unsigned char *main, size_t memory_size) {
return buddy_init_alignment(at, main, memory_size, BUDDY_ALLOC_ALIGN);
}
struct buddy *buddy_init_alignment(unsigned char *at, unsigned char *main, size_t memory_size,
size_t alignment) {
size_t at_alignment, main_alignment, buddy_size, buddy_tree_order;
struct buddy *buddy;
if (at == NULL) {
return NULL;
}
if (main == NULL) {
return NULL;
}
if (at == main) {
return NULL;
}
if (!is_valid_alignment(alignment)) {
return NULL; /* invalid */
}
at_alignment = ((uintptr_t) at) % BUDDY_ALIGNOF(struct buddy);
if (at_alignment != 0) {
return NULL;
}
main_alignment = ((uintptr_t) main) % BUDDY_ALIGNOF(size_t);
if (main_alignment != 0) {
return NULL;
}
/* Trim down memory to alignment */
if (memory_size % alignment) {
memory_size -= (memory_size % alignment);
}
buddy_size = buddy_sizeof_alignment(memory_size, alignment);
if (buddy_size == 0) {
return NULL;
}
buddy_tree_order = buddy_tree_order_for_memory(memory_size, alignment);
/* TODO check for overlap between buddy metadata and main block */
buddy = (struct buddy *) at;
buddy->arena.main = main;
buddy->memory_size = memory_size;
buddy->buddy_flags = 0;
buddy->alignment = alignment;
buddy_tree_init((unsigned char *)buddy + sizeof(*buddy), (uint8_t) buddy_tree_order);
buddy_toggle_virtual_slots(buddy, 1);
return buddy;
}
struct buddy *buddy_embed(unsigned char *main, size_t memory_size) {
return buddy_embed_alignment(main, memory_size, BUDDY_ALLOC_ALIGN);
}
struct buddy *buddy_get_embed_at(unsigned char *main, size_t memory_size) {
return buddy_get_embed_at_alignment(main, memory_size, BUDDY_ALLOC_ALIGN);
}
struct buddy *buddy_embed_alignment(unsigned char *main, size_t memory_size, size_t alignment) {
struct buddy_embed_check check_result;
struct buddy *buddy;
if (! main) {
return NULL;
}
if (!is_valid_alignment(alignment)) {
return NULL; /* invalid */
}
check_result = buddy_embed_offset(memory_size, alignment);
if (! check_result.can_fit) {
return NULL;
}
buddy = buddy_init_alignment(main+check_result.offset, main, check_result.offset, alignment);
if (! buddy) { /* regular initialization failed */
return NULL;
}
buddy->buddy_flags |= BUDDY_RELATIVE_MODE;
buddy->arena.main_offset = (unsigned char *)buddy - main;
return buddy;
}
struct buddy *buddy_get_embed_at_alignment(unsigned char *main, size_t memory_size, size_t alignment) {
struct buddy_embed_check check_result = buddy_embed_offset(memory_size, alignment);
if (!check_result.can_fit) {
return NULL;
}
return (struct buddy *)(main + check_result.offset);
}
struct buddy *buddy_resize(struct buddy *buddy, size_t new_memory_size) {
if (new_memory_size == buddy->memory_size) {
return buddy;
}
if (buddy_relative_mode(buddy)) {
return buddy_resize_embedded(buddy, new_memory_size);
} else {
return buddy_resize_standard(buddy, new_memory_size);
}
}
static struct buddy *buddy_resize_standard(struct buddy *buddy, size_t new_memory_size) {
size_t new_buddy_tree_order;
/* Trim down memory to alignment */
if (new_memory_size % buddy->alignment) {
new_memory_size -= (new_memory_size % buddy->alignment);
}
/* Account for tree use */
if (!buddy_is_free(buddy, new_memory_size)) {
return NULL;
}
/* Release the virtual slots */
buddy_toggle_virtual_slots(buddy, 0);
/* Calculate new tree order and resize it */
new_buddy_tree_order = buddy_tree_order_for_memory(new_memory_size, buddy->alignment);
buddy_tree_resize(buddy_tree(buddy), (uint8_t) new_buddy_tree_order);
/* Store the new memory size and reconstruct any virtual slots */
buddy->memory_size = new_memory_size;
buddy_toggle_virtual_slots(buddy, 1);
/* Resize successful */
return buddy;
}
static struct buddy *buddy_resize_embedded(struct buddy *buddy, size_t new_memory_size) {
struct buddy_embed_check check_result;
unsigned char *main, *buddy_destination;
struct buddy *resized, *relocated;
/* Ensure that the embedded allocator can fit */
check_result = buddy_embed_offset(new_memory_size, buddy->alignment);
if (! check_result.can_fit) {
return NULL;
}
/* Resize the allocator in the normal way */
resized = buddy_resize_standard(buddy, check_result.offset);
if (! resized) {
return NULL;
}
/* Get the absolute main address. The relative will be invalid after relocation. */
main = buddy_main(buddy);
/* Relocate the allocator */
buddy_destination = buddy_main(buddy) + check_result.offset;
memmove(buddy_destination, resized, check_result.buddy_size);
/* Update the main offset in the allocator */
relocated = (struct buddy *) buddy_destination;
relocated->arena.main_offset = buddy_destination - main;
return relocated;
}
bool buddy_can_shrink(struct buddy *buddy) {
if (buddy == NULL) {
return false;
}
return buddy_is_free(buddy, buddy->memory_size / 2);
}
bool buddy_is_empty(struct buddy *buddy) {
if (buddy == NULL) {
return false;
}
return buddy_is_free(buddy, 0);
}
bool buddy_is_full(struct buddy *buddy) {
struct buddy_tree *tree;
struct buddy_tree_pos pos;
if (buddy == NULL) {
return false;
}
tree = buddy_tree(buddy);
pos = buddy_tree_root();
return buddy_tree_status(tree, pos) == buddy_tree_order(tree);
}
size_t buddy_arena_size(struct buddy *buddy) {
if (buddy == NULL) {
return 0;
}
return buddy->memory_size;
}
size_t buddy_arena_free_size(struct buddy *buddy) {
size_t result = 0;
struct buddy_tree *tree = buddy_tree(buddy);
size_t tree_order = buddy_tree_order(tree);
struct buddy_tree_walk_state state = buddy_tree_walk_state_root();
do {
size_t pos_status = buddy_tree_status(tree, state.current_pos);
if (pos_status == (tree_order - state.current_pos.depth + 1)) { /* Fully-allocated */
state.going_up = 1;
} else if (pos_status == 0) { /* Free */
state.going_up = 1;
result += size_for_depth(buddy, state.current_pos.depth);
} else { /* Partial */
continue;
}
} while (buddy_tree_walk(tree, &state));
return result;
}
static unsigned int is_valid_alignment(size_t alignment) {
return ceiling_power_of_two(alignment) == alignment;
}
static size_t buddy_tree_order_for_memory(size_t memory_size, size_t alignment) {
size_t blocks = memory_size / alignment;
return highest_bit_position(ceiling_power_of_two(blocks));
}
void *buddy_malloc(struct buddy *buddy, size_t requested_size) {
size_t target_depth;
struct buddy_tree *tree;
struct buddy_tree_pos pos;
if (buddy == NULL) {
return NULL;
}
if (requested_size == 0) {
/*
* Batshit crazy code exists that calls malloc(0) and expects
* a result that can be safely passed to free().
* And even though this allocator will safely handle a free(NULL)
* the particular batshit code will expect a non-NULL malloc(0) result!
*
* See also https://wiki.sei.cmu.edu/confluence/display/c/MEM04-C.+Beware+of+zero-length+allocations
*/
requested_size = 1;
}
if (requested_size > buddy->memory_size) {
return NULL;
}
target_depth = depth_for_size(buddy, requested_size);
tree = buddy_tree(buddy);
pos = buddy_tree_find_free(tree, (uint8_t) target_depth);
if (! buddy_tree_valid(tree, pos)) {
return NULL; /* no slot found */
}
/* Allocate the slot */
buddy_tree_mark(tree, pos);
/* Find and return the actual memory address */
return address_for_position(buddy, pos);
}
void *buddy_calloc(struct buddy *buddy, size_t members_count, size_t member_size) {
size_t total_size;
void *result;
if (members_count == 0 || member_size == 0) {
/* See the gleeful remark in malloc */
members_count = 1;
member_size = 1;
}
/* Check for overflow */
if (((members_count * member_size)/members_count) != member_size) {
return NULL;
}
total_size = members_count * member_size;
result = buddy_malloc(buddy, total_size);
if (result) {
memset(result, 0, total_size);
}
return result;
}
void *buddy_realloc(struct buddy *buddy, void *ptr, size_t requested_size, bool ignore_data) {
struct buddy_tree *tree;
struct buddy_tree_pos origin, new_pos;
size_t current_depth, target_depth;
void *source, *destination;
/*
* realloc is a joke:
* - NULL ptr degrades into malloc
* - Zero size degrades into free
* - Same size as previous malloc/calloc/realloc is a no-op or a rellocation
* - Smaller size than previous *alloc decrease the allocated size with an optional rellocation
* - If the new allocation cannot be satisfied NULL is returned BUT the slot is preserved
* - Larger size than previous *alloc increase tha allocated size with an optional rellocation
*/
if (ptr == NULL) {
return buddy_malloc(buddy, requested_size);
}
if (requested_size == 0) {
buddy_free(buddy, ptr);
return NULL;
}
if (requested_size > buddy->memory_size) {
return NULL;
}
/* Find the position tracking this address */
tree = buddy_tree(buddy);
origin = position_for_address(buddy, (unsigned char *) ptr);
if (! buddy_tree_valid(tree, origin)) {
return NULL;
}
current_depth = buddy_tree_depth(origin);
target_depth = depth_for_size(buddy, requested_size);
/* Release the position and perform a search */
buddy_tree_release(tree, origin);
new_pos = buddy_tree_find_free(tree, (uint8_t) target_depth);
if (! buddy_tree_valid(tree, new_pos)) {
/* allocation failure, restore mark and return null */
buddy_tree_mark(tree, origin);
return NULL;
}
if (origin.index == new_pos.index) {
/* Allocated to the same slot, restore mark and return null */
buddy_tree_mark(tree, origin);
return ptr;
}
destination = address_for_position(buddy, new_pos);
if (! ignore_data) {
/* Copy the content */
source = address_for_position(buddy, origin);
memmove(destination, source, size_for_depth(buddy,
current_depth > target_depth ? current_depth : target_depth));
}
/* Allocate and return */
buddy_tree_mark(tree, new_pos);
return destination;
}
void *buddy_reallocarray(struct buddy *buddy, void *ptr,
size_t members_count, size_t member_size, bool ignore_data) {
if (members_count == 0 || member_size == 0) {
return buddy_realloc(buddy, ptr, 0, ignore_data);
}
/* Check for overflow */
if ((members_count * member_size)/members_count != member_size) {
return NULL;
}
return buddy_realloc(buddy, ptr, members_count * member_size, ignore_data);
}
void buddy_free(struct buddy *buddy, void *ptr) {
unsigned char *dst, *main;
struct buddy_tree *tree;
struct buddy_tree_pos pos;
if (buddy == NULL) {
return;
}
if (ptr == NULL) {
return;
}
dst = (unsigned char *)ptr;
main = buddy_main(buddy);
if ((dst < main) || (dst >= (main + buddy->memory_size))) {
return;
}
/* Find the position tracking this address */
tree = buddy_tree(buddy);
pos = position_for_address(buddy, dst);
if (! buddy_tree_valid(tree, pos)) {
return;
}
/* Release the position */
buddy_tree_release(tree, pos);
}
enum buddy_safe_free_status buddy_safe_free(struct buddy* buddy, void* ptr, size_t requested_size) {
unsigned char* dst, * main;
struct buddy_tree* tree;
struct buddy_tree_pos pos;
size_t allocated_size_for_depth;
enum buddy_tree_release_status status;
if (buddy == NULL) {
return BUDDY_SAFE_FREE_BUDDY_IS_NULL;
}
if (ptr == NULL) {
return BUDDY_SAFE_FREE_INVALID_ADDRESS;
}
dst = (unsigned char*)ptr;
main = buddy_main(buddy);
if ((dst < main) || (dst >= (main + buddy->memory_size))) {
return BUDDY_SAFE_FREE_INVALID_ADDRESS;
}
/* Find an allocated position tracking this address */
tree = buddy_tree(buddy);
pos = position_for_address(buddy, dst);
if (!buddy_tree_valid(tree, pos)) {
return BUDDY_SAFE_FREE_INVALID_ADDRESS;
}
allocated_size_for_depth = size_for_depth(buddy, pos.depth);
if (requested_size < buddy->alignment) {
requested_size = buddy->alignment;
}
if (requested_size > allocated_size_for_depth) {
return BUDDY_SAFE_FREE_SIZE_MISMATCH;
}
if (requested_size <= (allocated_size_for_depth / 2)) {
return BUDDY_SAFE_FREE_SIZE_MISMATCH;
}
/* Release the position */
status = buddy_tree_release(tree, pos);
switch (status) {
case BUDDY_TREE_RELEASE_FAIL_PARTIALLY_USED:
return BUDDY_SAFE_FREE_INVALID_ADDRESS;
case BUDDY_TREE_RELEASE_SUCCESS:
break;
}
return BUDDY_SAFE_FREE_SUCCESS;
}
void buddy_reserve_range(struct buddy *buddy, void *ptr, size_t requested_size) {
buddy_toggle_range_reservation(buddy, ptr, requested_size, 1);
}
void buddy_unsafe_release_range(struct buddy *buddy, void *ptr, size_t requested_size) {
buddy_toggle_range_reservation(buddy, ptr, requested_size, 0);
}
void *buddy_walk(struct buddy *buddy,
void *(fp)(void *ctx, void *addr, size_t slot_size, size_t allocated),
void *ctx) {
unsigned char *main;
size_t effective_memory_size, tree_order, pos_status, pos_size;
struct buddy_tree *tree;
unsigned char *addr;
struct buddy_tree_walk_state state;
struct buddy_tree_pos test_pos;
void *callback_result;
if (buddy == NULL) {
return NULL;
}
if (fp == NULL) {
return NULL;
}