-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathheap.cpp
More file actions
1468 lines (1339 loc) · 42 KB
/
Copy pathheap.cpp
File metadata and controls
1468 lines (1339 loc) · 42 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
#include "heap.h"
#include "common.h"
#include "errors.h"
#include "processes.h"
#include "types.h"
#include <algorithm>
#include <atomic>
#include <cerrno>
#include <charconv>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <limits>
#include <map>
#include <mutex>
#include <utility>
#include <vector>
#ifdef __linux__
// Alpine hack: rename duplicate prctl_mm_map (sys/prctl.h also includes it)
#define prctl_mm_map _prctl_mm_map
#include <linux/prctl.h>
#undef prctl_mm_map
#include <sys/prctl.h>
#endif
#include <mimalloc.h>
#include <sys/mman.h>
#include <unistd.h>
// Pre-initialization logging macros
#define LOG_OUT(msg) write(STDOUT_FILENO, msg, strlen(msg))
#define LOG_ERR(msg) write(STDERR_FILENO, msg, strlen(msg))
namespace {
constexpr uintptr_t kLowMemoryStart = 0x00110000UL; // 1 MiB + 64 KiB
constexpr uintptr_t kHeapMax = 0x70000000UL;
#ifdef __APPLE__
// On macOS, our program is mapped at 0x7E001000
constexpr uintptr_t kTopDownStart = 0x7D000000UL;
constexpr uintptr_t kTwoGB = 0x7E000000UL;
#else
constexpr uintptr_t kTopDownStart = 0x7F000000UL; // Just below 2GB
constexpr uintptr_t kTwoGB = 0x80000000UL;
#endif
constexpr std::size_t kGuestArenaSize = 64ULL * 1024ULL * 1024ULL; // 64 MiB
constexpr std::size_t kArenaMaxObjSize = 8ULL * 1024ULL * 1024ULL; // 8 MiB
constexpr std::size_t kVirtualAllocationGranularity = 64ULL * 1024ULL;
struct Arena {
mi_arena_id_t arenaId = nullptr;
void *start = nullptr;
size_t size = 0;
};
std::recursive_mutex g_arenasMutex;
std::vector<Arena> g_arenas;
std::atomic_uint32_t g_heapTag(1);
// Each thread gets its own set of mi_heap objects corresponding to each allocated arena
thread_local wibo::detail::HeapInternal g_guestHeap(0);
std::mutex g_mappingsMutex;
std::map<uintptr_t, MEMORY_BASIC_INFORMATION> *g_mappings = nullptr;
struct VirtualAllocation {
uintptr_t base = 0;
std::size_t size = 0;
DWORD allocationProtect = 0;
DWORD type = MEM_PRIVATE;
std::vector<DWORD> pageProtect;
};
std::map<uintptr_t, VirtualAllocation> g_virtualAllocations;
const uintptr_t kDefaultMmapMinAddr = 0x10000u;
#ifdef __linux__
uintptr_t readMmapMinAddr() {
char buf[64];
int fd = open("/proc/sys/vm/mmap_min_addr", O_RDONLY | O_CLOEXEC, 0);
if (fd < 0) {
return kDefaultMmapMinAddr;
}
ssize_t rd = read(fd, buf, sizeof(buf) - 1);
close(fd);
if (rd <= 0) {
return kDefaultMmapMinAddr;
}
uintptr_t value = 0;
auto result = std::from_chars(buf, buf + rd, value);
if (result.ec != std::errc()) {
LOG_ERR("heap: failed to parse mmap_min_addr\n");
return kDefaultMmapMinAddr;
}
if (value < kDefaultMmapMinAddr) {
value = kDefaultMmapMinAddr;
}
return value;
}
#endif
inline uintptr_t mmapMinAddr() {
#ifdef __linux__
static uintptr_t minAddr = readMmapMinAddr();
return minAddr;
#else
return kDefaultMmapMinAddr;
#endif
}
inline void setVirtualAllocationName(void *ptr, std::size_t len, const char *name) {
#ifdef __linux__
if (name) {
prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, ptr, len, name);
}
#endif
}
constexpr uintptr_t alignDown(uintptr_t value, std::size_t alignment) {
const uintptr_t mask = static_cast<uintptr_t>(alignment) - 1;
return value & ~mask;
}
constexpr uintptr_t alignUp(uintptr_t value, std::size_t alignment) {
const uintptr_t mask = static_cast<uintptr_t>(alignment) - 1;
if (mask == std::numeric_limits<uintptr_t>::max()) {
return value;
}
if (value > std::numeric_limits<uintptr_t>::max() - mask) {
return std::numeric_limits<uintptr_t>::max();
}
return (value + mask) & ~mask;
}
constexpr bool addOverflows(uintptr_t base, std::size_t amount) {
return base > std::numeric_limits<uintptr_t>::max() - static_cast<uintptr_t>(amount);
}
constexpr uintptr_t regionEnd(const VirtualAllocation ®ion) { return region.base + region.size; }
std::map<uintptr_t, VirtualAllocation>::iterator findRegionIterator(uintptr_t address) {
auto it = g_virtualAllocations.upper_bound(address);
if (it == g_virtualAllocations.begin()) {
return g_virtualAllocations.end();
}
--it;
if (address >= regionEnd(it->second)) {
return g_virtualAllocations.end();
}
return it;
}
VirtualAllocation *lookupRegion(uintptr_t address) {
auto it = findRegionIterator(address);
if (it == g_virtualAllocations.end()) {
return nullptr;
}
return &it->second;
}
constexpr bool rangeWithinRegion(const VirtualAllocation ®ion, uintptr_t start, std::size_t length) {
if (length == 0) {
return start >= region.base && start <= regionEnd(region);
}
if (start < region.base) {
return false;
}
if (addOverflows(start, length)) {
return false;
}
return (start + length) <= regionEnd(region);
}
void markCommitted(VirtualAllocation ®ion, uintptr_t start, std::size_t length, DWORD protect) {
if (length == 0) {
return;
}
const std::size_t pageSize = wibo::heap::systemPageSize();
const std::size_t firstPage = (start - region.base) / pageSize;
const std::size_t pageCount = length / pageSize;
for (std::size_t i = 0; i < pageCount; ++i) {
region.pageProtect[firstPage + i] = protect;
}
}
void markDecommitted(VirtualAllocation ®ion, uintptr_t start, std::size_t length) {
if (length == 0) {
return;
}
const std::size_t pageSize = wibo::heap::systemPageSize();
const std::size_t firstPage = (start - region.base) / pageSize;
const std::size_t pageCount = length / pageSize;
for (std::size_t i = 0; i < pageCount; ++i) {
region.pageProtect[firstPage + i] = 0;
}
}
bool overlapsExistingMappingLocked(uintptr_t base, std::size_t length) {
if (g_mappings == nullptr || length == 0) {
return false;
}
if (addOverflows(base, length - 1)) {
return true;
}
uintptr_t end = base + length;
auto it = g_mappings->upper_bound(base);
if (it != g_mappings->begin()) {
--it;
}
for (; it != g_mappings->end(); ++it) {
const auto &info = it->second;
if (info.RegionSize == 0) {
continue;
}
uintptr_t mapStart = reinterpret_cast<uintptr_t>(fromGuestPtr(info.BaseAddress));
uintptr_t mapEnd = mapStart + static_cast<uintptr_t>(info.RegionSize);
if (mapEnd <= base) {
continue;
}
if (mapStart >= end) {
break;
}
return true;
}
return false;
}
void recordGuestMappingLocked(uintptr_t base, std::size_t size, DWORD allocationProtect, DWORD state, DWORD protect,
DWORD type) {
if (g_mappings == nullptr) {
return;
}
MEMORY_BASIC_INFORMATION info{};
info.BaseAddress = toGuestPtr(reinterpret_cast<void *>(base));
info.AllocationBase = toGuestPtr(reinterpret_cast<void *>(base));
info.AllocationProtect = allocationProtect;
info.RegionSize = size;
info.State = state;
info.Protect = protect;
info.Type = type;
(*g_mappings)[base] = info;
}
void eraseGuestMappingLocked(uintptr_t base) {
if (g_mappings == nullptr) {
return;
}
g_mappings->erase(base);
}
int posixProtectFromWin32(DWORD flProtect) {
switch (flProtect & 0xFF) {
case PAGE_NOACCESS:
return PROT_NONE;
case PAGE_READONLY:
return PROT_READ;
case PAGE_READWRITE:
case PAGE_WRITECOPY:
return PROT_READ | PROT_WRITE;
case PAGE_EXECUTE:
return PROT_EXEC;
case PAGE_EXECUTE_READ:
return PROT_READ | PROT_EXEC;
case PAGE_EXECUTE_READWRITE:
case PAGE_EXECUTE_WRITECOPY:
return PROT_READ | PROT_WRITE | PROT_EXEC;
default:
DEBUG_LOG("heap: unhandled flProtect %u, defaulting to RW\n", flProtect);
return PROT_READ | PROT_WRITE;
}
}
wibo::heap::VmStatus vmStatusFromErrno(int err) {
switch (err) {
case ENOMEM:
return wibo::heap::VmStatus::NoMemory;
case EACCES:
case EPERM:
return wibo::heap::VmStatus::NoAccess;
case EINVAL:
return wibo::heap::VmStatus::InvalidParameter;
case EBUSY:
return wibo::heap::VmStatus::Rejected;
default:
return wibo::heap::VmStatus::UnknownError;
}
}
void refreshGuestMappingLocked(const VirtualAllocation ®ion) {
if (g_mappings == nullptr) {
return;
}
bool allCommitted = true;
bool anyCommitted = false;
DWORD firstProtect = 0;
bool uniformProtect = true;
for (DWORD pageProtect : region.pageProtect) {
if (pageProtect == 0) {
allCommitted = false;
continue;
}
anyCommitted = true;
if (firstProtect == 0) {
firstProtect = pageProtect;
} else if (firstProtect != pageProtect) {
uniformProtect = false;
}
}
DWORD state = allCommitted && anyCommitted ? MEM_COMMIT : MEM_RESERVE;
DWORD protect = PAGE_NOACCESS;
if (state == MEM_COMMIT) {
if (uniformProtect && firstProtect != 0) {
protect = firstProtect;
} else {
protect = PAGE_NOACCESS;
}
}
DWORD allocationProtect = region.allocationProtect != 0 ? region.allocationProtect : PAGE_NOACCESS;
recordGuestMappingLocked(region.base, region.size, allocationProtect, state, protect, region.type);
}
bool mapAtAddrLocked(uintptr_t addr, std::size_t size, const char *name, void **outPtr) {
void *p = mmap(reinterpret_cast<void *>(addr), size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
if (p == MAP_FAILED) {
return false;
}
setVirtualAllocationName(p, size, name);
recordGuestMappingLocked(reinterpret_cast<uintptr_t>(p), size, PAGE_READWRITE, MEM_RESERVE, PAGE_READWRITE,
MEM_PRIVATE);
if (outPtr) {
*outPtr = p;
}
return true;
}
bool findFreeMappingLocked(std::size_t size, uintptr_t minAddr, uintptr_t maxAddr, bool preferTop, uintptr_t *outAddr) {
if (outAddr == nullptr || size == 0 || g_mappings == nullptr) {
return false;
}
const uintptr_t pageSize = wibo::heap::systemPageSize();
const uintptr_t alignedSize = alignUp(static_cast<uintptr_t>(size), pageSize);
const uintptr_t granularity = kVirtualAllocationGranularity;
uintptr_t searchMin = static_cast<uintptr_t>(minAddr);
uintptr_t searchMax = static_cast<uintptr_t>(maxAddr);
if (searchMax <= searchMin || alignedSize > (searchMax - searchMin)) {
return false;
}
auto tryGap = [&](uintptr_t gapStart, uintptr_t gapEnd, uintptr_t &result) -> bool {
if (gapEnd <= gapStart) {
return false;
}
uintptr_t lower = alignUp(gapStart, granularity);
if (lower >= gapEnd) {
return false;
}
if (!preferTop) {
if (lower + alignedSize <= gapEnd) {
result = lower;
return true;
}
return false;
}
if (gapEnd < alignedSize) {
return false;
}
uintptr_t upper = gapEnd - alignedSize;
uintptr_t chosen = alignDown(upper, granularity);
if (chosen < lower) {
return false;
}
if (chosen + alignedSize > gapEnd) {
return false;
}
result = chosen;
return true;
};
bool foundTopCandidate = false;
uintptr_t bestCandidate = 0;
auto considerGap = [&](uintptr_t gapStart, uintptr_t gapEnd) -> bool {
uintptr_t candidate = 0;
if (!tryGap(gapStart, gapEnd, candidate)) {
return false;
}
if (!preferTop) {
*outAddr = candidate;
return true;
}
if (!foundTopCandidate || candidate > bestCandidate) {
bestCandidate = candidate;
foundTopCandidate = true;
}
return false;
};
uintptr_t cursor = alignUp(searchMin, granularity);
for (auto &g_mapping : *g_mappings) {
uintptr_t mapStart = g_mapping.first;
uintptr_t mapEnd = mapStart + static_cast<uintptr_t>(g_mapping.second.RegionSize);
if (mapEnd <= searchMin) {
continue;
}
if (mapStart >= searchMax) {
if (considerGap(cursor, searchMax)) {
return true;
}
break;
}
if (mapStart > cursor) {
uintptr_t gapEnd = std::min(mapStart, searchMax);
if (considerGap(cursor, gapEnd)) {
return true;
}
}
if (mapEnd > cursor) {
cursor = alignUp(mapEnd, pageSize);
}
if (cursor >= searchMax) {
break;
}
}
if (cursor < searchMax) {
if (considerGap(cursor, searchMax)) {
return true;
}
}
if (foundTopCandidate) {
*outAddr = bestCandidate;
return true;
}
return false;
}
bool mapArena(std::size_t size, uintptr_t minAddr, uintptr_t maxAddr, bool preferTop, const char *name, Arena &out) {
std::lock_guard lk(g_mappingsMutex);
const std::size_t ps = wibo::heap::systemPageSize();
size = (size + ps - 1) & ~(ps - 1);
uintptr_t cand = 0;
void *p = nullptr;
if (findFreeMappingLocked(size, minAddr, maxAddr, preferTop, &cand)) {
DEBUG_LOG("heap: found free mapping at %lx\n", cand);
if (mapAtAddrLocked(cand, size, name, &p)) {
out.start = p;
out.size = size;
return true;
}
}
return false;
}
bool createArenaLocked(size_t size) {
Arena arena;
if (!mapArena(size, kLowMemoryStart, kHeapMax, true, "wibo heap arena", arena)) {
DEBUG_LOG("heap: failed to find free mapping for arena\n");
return false;
}
if (!mi_manage_os_memory_ex(arena.start, arena.size,
/*is_committed*/ false,
/*is_pinned*/ false,
/*is_zero*/ true,
/*numa_node*/ -1,
/*exclusive*/ true, &arena.arenaId)) {
DEBUG_LOG("heap: failed to create mi_arena\n");
return false;
}
DEBUG_LOG("heap: created arena %d at %p..%p (%zu MiB)\n", arena.arenaId, arena.start,
reinterpret_cast<uint8_t *>(arena.start) + arena.size, arena.size >> 20);
g_arenas.push_back(arena);
return true;
}
mi_heap_t *heapForArena(std::vector<mi_heap_t *> &heaps, uint32_t arenaIdx, uint32_t heapTag) {
if (heaps.size() <= arenaIdx) {
heaps.resize(arenaIdx + 1, nullptr);
}
if (heaps[arenaIdx] == nullptr) {
mi_arena_id_t arenaId;
{
std::lock_guard lk(g_arenasMutex);
if (arenaIdx >= g_arenas.size()) {
return nullptr;
}
arenaId = g_arenas[arenaIdx].arenaId;
}
mi_heap_t *h = mi_heap_new_ex(static_cast<int>(heapTag), heapTag != 0, arenaId);
if (h == nullptr) {
return nullptr;
}
heaps[arenaIdx] = h;
}
return heaps[arenaIdx];
}
template <typename CallbackFn>
inline auto tryWithArena(wibo::detail::HeapInternal &internal, uint32_t arenaIdx, CallbackFn &&cb)
-> std::invoke_result_t<CallbackFn, mi_heap_t *, uint32_t> {
mi_heap_t *heap = heapForArena(internal.heaps, arenaIdx, internal.heapTag);
if (!heap) {
return {};
}
return std::forward<CallbackFn>(cb)(heap, arenaIdx);
}
template <typename CallbackFn>
inline auto tryWithAnyArena(wibo::detail::HeapInternal &internal, CallbackFn &&cb)
-> std::invoke_result_t<CallbackFn, mi_heap_t *, uint32_t> {
using R = std::invoke_result_t<CallbackFn, mi_heap_t *, uint32_t>;
R ret = tryWithArena(internal, internal.arenaHint, cb);
if (ret) {
return ret;
}
// Loop without locking (arenas won't be removed)
uint32_t numArenas = static_cast<uint32_t>(g_arenas.size());
for (uint32_t i = 0; i < numArenas; ++i) {
if (i == internal.arenaHint) {
continue;
}
ret = tryWithArena(internal, i, cb);
if (ret) {
internal.arenaHint = i;
return ret;
}
}
std::lock_guard lk(g_arenasMutex);
// Was a new arena created while we were looping?
for (uint32_t i = numArenas; i < g_arenas.size(); ++i) {
ret = tryWithArena(internal, i, cb);
if (ret) {
internal.arenaHint = i;
return ret;
}
}
DEBUG_LOG("heap: no arena available, creating new arena\n");
if (createArenaLocked(kGuestArenaSize)) {
uint32_t newArenaIdx = static_cast<uint32_t>(g_arenas.size() - 1);
ret = tryWithArena(internal, newArenaIdx, cb);
if (ret) {
internal.arenaHint = newArenaIdx;
return ret;
}
}
return {};
}
void *doAlloc(wibo::detail::HeapInternal &internal, size_t size, bool zero) {
if (size >= kArenaMaxObjSize) {
DEBUG_LOG("heap: large malloc %zu bytes, using virtualAlloc\n", size);
void *addr = nullptr;
const auto result = wibo::heap::virtualAlloc(&addr, &size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (result != wibo::heap::VmStatus::Success) {
return nullptr;
}
return addr;
}
return tryWithAnyArena(internal, [size, zero](mi_heap_t *heap, uint32_t) {
return (zero ? mi_heap_zalloc_aligned : mi_heap_malloc_aligned)(heap, size, 8);
});
}
void *doRealloc(wibo::detail::HeapInternal &internal, void *ptr, size_t newSize, bool zero) {
bool isInHeap = mi_is_in_heap_region(ptr);
if (newSize >= kArenaMaxObjSize || !isInHeap) {
DEBUG_LOG("heap: large realloc %zu bytes, using virtualAlloc\n", newSize);
size_t oldSize;
if (isInHeap) {
oldSize = mi_usable_size(ptr);
} else {
// Get size from virtualQuery
MEMORY_BASIC_INFORMATION info;
auto result = wibo::heap::virtualQuery(ptr, &info);
if (result != wibo::heap::VmStatus::Success) {
return nullptr;
}
oldSize = info.RegionSize;
}
void *ret = nullptr;
if (newSize >= kArenaMaxObjSize) {
auto result = wibo::heap::virtualAlloc(&ret, &newSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (result != wibo::heap::VmStatus::Success) {
return nullptr;
}
} else {
ret = doAlloc(internal, newSize, zero);
}
if (!ret) {
return nullptr;
}
std::memcpy(ret, ptr, std::min(oldSize, newSize));
if (isInHeap) {
mi_free(ptr);
} else {
auto result = wibo::heap::virtualFree(ptr, 0, MEM_RELEASE);
if (result != wibo::heap::VmStatus::Success) {
return nullptr;
}
}
return ret;
}
return tryWithAnyArena(internal, [ptr, newSize, zero](mi_heap_t *heap, uint32_t) {
return (zero ? mi_heap_rezalloc_aligned : mi_heap_realloc_aligned)(heap, ptr, newSize, 8);
});
}
bool doFree(void *ptr) {
if (ptr == nullptr) {
return false;
}
if (mi_is_in_heap_region(ptr)) {
mi_free(ptr);
} else {
DEBUG_LOG("heap: free(%p) -> virtualFree\n", ptr);
auto result = wibo::heap::virtualFree(ptr, 0, MEM_RELEASE);
if (result != wibo::heap::VmStatus::Success) {
return false;
}
}
return true;
}
} // anonymous namespace
namespace wibo {
Heap::Heap() : threadId(getThreadId()), internal(g_heapTag++) {}
Heap::~Heap() {
if (getThreadId() != threadId) {
DEBUG_LOG("heap: ~Heap() failed; heap owned by another thread\n");
return;
}
for (mi_heap_t *h : internal.heaps) {
if (h) {
mi_heap_destroy(h);
}
}
internal.heaps.clear();
}
void *Heap::malloc(size_t size, bool zero) {
if (getThreadId() != threadId) {
DEBUG_LOG("heap: malloc(%zu) failed; heap owned by another thread\n", size);
return nullptr;
}
return doAlloc(internal, size, zero);
}
void *Heap::realloc(void *ptr, size_t newSize, bool zero) {
if (getThreadId() != threadId) {
DEBUG_LOG("heap: realloc(%p, %zu) failed; heap owned by another thread\n", ptr, newSize);
return nullptr;
}
return doRealloc(internal, ptr, newSize, zero);
}
// NOLINTNEXTLINE(readability-convert-member-functions-to-static)
bool Heap::free(void *ptr) { return doFree(ptr); }
}; // namespace wibo
namespace wibo::heap {
uintptr_t systemPageSize() {
static uintptr_t cached = []() {
long detected = sysconf(_SC_PAGESIZE);
if (detected <= 0) {
return static_cast<uintptr_t>(4096);
}
return static_cast<uintptr_t>(detected);
}();
return cached;
}
void *guestMalloc(std::size_t size, bool zero) { return doAlloc(g_guestHeap, size, zero); }
void *guestRealloc(void *ptr, std::size_t newSize, bool zero) { return doRealloc(g_guestHeap, ptr, newSize, zero); }
bool guestFree(void *ptr) { return doFree(ptr); }
size_t guestSize(const void *ptr) {
if (mi_is_in_heap_region(ptr)) {
return mi_usable_size(ptr);
} else {
MEMORY_BASIC_INFORMATION info;
auto result = wibo::heap::virtualQuery(ptr, &info);
if (result != wibo::heap::VmStatus::Success) {
return SIZE_MAX;
}
return info.RegionSize;
}
}
uintptr_t allocationGranularity() { return kVirtualAllocationGranularity; }
DWORD win32ErrorFromVmStatus(VmStatus status) {
switch (status) {
case VmStatus::Success:
return ERROR_SUCCESS;
case VmStatus::InvalidParameter:
return ERROR_INVALID_PARAMETER;
case VmStatus::InvalidAddress:
case VmStatus::Rejected:
return ERROR_INVALID_ADDRESS;
case VmStatus::NoAccess:
return ERROR_NOACCESS;
case VmStatus::NotSupported:
return ERROR_NOT_SUPPORTED;
case VmStatus::NoMemory:
return ERROR_NOT_ENOUGH_MEMORY;
case VmStatus::UnknownError:
default:
return ERROR_INVALID_PARAMETER;
}
}
NTSTATUS ntStatusFromVmStatus(VmStatus status) { return wibo::statusFromWinError(win32ErrorFromVmStatus(status)); }
VmStatus virtualReset(void *baseAddress, std::size_t regionSize) {
if (!baseAddress) {
return VmStatus::InvalidAddress;
}
if (regionSize == 0) {
return VmStatus::InvalidParameter;
}
uintptr_t request = reinterpret_cast<uintptr_t>(baseAddress);
if (addOverflows(request, regionSize)) {
return VmStatus::InvalidParameter;
}
const uintptr_t pageSize = wibo::heap::systemPageSize();
uintptr_t start = alignDown(request, pageSize);
uintptr_t end = alignUp(request + static_cast<uintptr_t>(regionSize), pageSize);
std::size_t length = static_cast<std::size_t>(end - start);
if (length == 0) {
return VmStatus::InvalidParameter;
}
{
std::lock_guard allocLock(g_mappingsMutex);
VirtualAllocation *region = lookupRegion(start);
if (!region || !rangeWithinRegion(*region, start, length)) {
return VmStatus::InvalidAddress;
}
}
#ifdef MADV_FREE
int advice = MADV_FREE;
#else
int advice = MADV_DONTNEED;
#endif
if (madvise(reinterpret_cast<void *>(start), length, advice) != 0) {
return vmStatusFromErrno(errno);
}
return VmStatus::Success;
}
VmStatus virtualAlloc(void **baseAddress, std::size_t *regionSize, DWORD allocationType, DWORD protect, DWORD type) {
if (!regionSize) {
return VmStatus::InvalidParameter;
}
std::size_t requestedSize = *regionSize;
if (requestedSize == 0) {
return VmStatus::InvalidParameter;
}
void *requestedAddress = baseAddress ? *baseAddress : nullptr;
DWORD unsupportedFlags = allocationType & (MEM_WRITE_WATCH | MEM_PHYSICAL | MEM_LARGE_PAGES | MEM_RESET_UNDO);
if (unsupportedFlags != 0) {
return VmStatus::NotSupported;
}
bool reserve = (allocationType & MEM_RESERVE) != 0;
bool commit = (allocationType & MEM_COMMIT) != 0;
bool reset = (allocationType & MEM_RESET) != 0;
bool topDown = (allocationType & MEM_TOP_DOWN) != 0;
if (!reserve && commit && requestedAddress == nullptr) {
reserve = true;
}
const uintptr_t pageSize = wibo::heap::systemPageSize();
if (reset) {
if (reserve || commit) {
return VmStatus::InvalidParameter;
}
if (requestedAddress == nullptr) {
return VmStatus::InvalidAddress;
}
uintptr_t requestVal = reinterpret_cast<uintptr_t>(requestedAddress);
uintptr_t start = alignDown(requestVal, pageSize);
uintptr_t end = alignUp(requestVal + static_cast<uintptr_t>(requestedSize), pageSize);
std::size_t length = static_cast<std::size_t>(end - start);
VmStatus status = virtualReset(requestedAddress, requestedSize);
if (status == VmStatus::Success) {
if (baseAddress) {
*baseAddress = reinterpret_cast<void *>(start);
}
*regionSize = length;
}
return status;
}
if (!reserve && !commit) {
return VmStatus::InvalidParameter;
}
std::unique_lock allocLock(g_mappingsMutex);
if (reserve) {
uintptr_t base = 0;
std::size_t length = 0;
if (requestedAddress != nullptr) {
uintptr_t request = reinterpret_cast<uintptr_t>(requestedAddress);
base = alignDown(request, kVirtualAllocationGranularity);
std::size_t offset = static_cast<std::size_t>(request - base);
if (addOverflows(offset, requestedSize)) {
return VmStatus::InvalidParameter;
}
std::size_t span = requestedSize + offset;
uintptr_t alignedSpan = alignUp(static_cast<uintptr_t>(span), pageSize);
if (alignedSpan == 0) {
return VmStatus::InvalidParameter;
}
length = static_cast<std::size_t>(alignedSpan);
if (length == 0) {
return VmStatus::InvalidParameter;
}
if (base >= kTwoGB || (base + length) > kTwoGB) {
return VmStatus::InvalidAddress;
}
if (overlapsExistingMappingLocked(base, length)) {
return VmStatus::InvalidAddress;
}
} else {
uintptr_t aligned = alignUp(static_cast<uintptr_t>(requestedSize), pageSize);
if (aligned == 0) {
return VmStatus::InvalidParameter;
}
length = static_cast<std::size_t>(aligned);
if (!findFreeMappingLocked(length, kLowMemoryStart, kTopDownStart, topDown, &base)) {
return VmStatus::NoMemory;
}
if (base >= kTwoGB || (base + length) > kTwoGB) {
return VmStatus::NoMemory;
}
}
int prot = commit ? posixProtectFromWin32(protect) : PROT_NONE;
int flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED;
if (!commit) {
flags |= MAP_NORESERVE;
}
void *mapped = mmap(reinterpret_cast<void *>(base), length, prot, flags, -1, 0);
if (mapped == MAP_FAILED) {
return vmStatusFromErrno(errno);
}
if (type == MEM_IMAGE) {
setVirtualAllocationName(mapped, length, "wibo guest image");
} else {
setVirtualAllocationName(mapped, length, "wibo guest allocated");
}
uintptr_t actualBase = reinterpret_cast<uintptr_t>(mapped);
VirtualAllocation allocation{};
allocation.base = actualBase;
allocation.size = length;
allocation.allocationProtect = protect;
allocation.type = type;
allocation.pageProtect.assign(length / pageSize, commit ? protect : 0);
g_virtualAllocations[actualBase] = std::move(allocation);
refreshGuestMappingLocked(g_virtualAllocations[actualBase]);
if (baseAddress) {
*baseAddress = reinterpret_cast<void *>(actualBase);
}
*regionSize = length;
return VmStatus::Success;
}
if (requestedAddress == nullptr) {
return VmStatus::InvalidAddress;
}
uintptr_t request = reinterpret_cast<uintptr_t>(requestedAddress);
if (addOverflows(request, requestedSize)) {
return VmStatus::InvalidParameter;
}
uintptr_t start = alignDown(request, pageSize);
uintptr_t end = alignUp(request + static_cast<uintptr_t>(requestedSize), pageSize);
std::size_t length = static_cast<std::size_t>(end - start);
if (length == 0) {
return VmStatus::InvalidParameter;
}
VirtualAllocation *region = lookupRegion(start);
if (!region || !rangeWithinRegion(*region, start, length)) {
return VmStatus::InvalidAddress;
}
const std::size_t pageCount = length / pageSize;
std::vector<std::pair<uintptr_t, std::size_t>> runs;
runs.reserve(pageCount);
for (std::size_t i = 0; i < pageCount; ++i) {
std::size_t pageIndex = ((start - region->base) / pageSize) + i;
if (pageIndex >= region->pageProtect.size()) {
return VmStatus::InvalidAddress;
}
if (region->pageProtect[pageIndex] != 0) {
continue;
}
uintptr_t runBase = start + i * pageSize;
std::size_t runLength = pageSize;
while (i + 1 < pageCount) {
std::size_t nextIndex = ((start - region->base) / pageSize) + i + 1;
if (region->pageProtect[nextIndex] != 0) {
break;
}
++i;
runLength += pageSize;
}
runs.emplace_back(runBase, runLength);
}
for (const auto &run : runs) {
void *res = mmap(reinterpret_cast<void *>(run.first), run.second, posixProtectFromWin32(protect),
MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
if (res == MAP_FAILED) {
return vmStatusFromErrno(errno);
}
setVirtualAllocationName(res, run.second, "wibo guest committed");
markCommitted(*region, run.first, run.second, protect);
}
refreshGuestMappingLocked(*region);
if (baseAddress) {
*baseAddress = reinterpret_cast<void *>(start);
}
*regionSize = length;
return VmStatus::Success;
}
VmStatus virtualFree(void *baseAddress, std::size_t regionSize, DWORD freeType) {
if (!baseAddress) {
return VmStatus::InvalidAddress;
}
if ((freeType & (MEM_COALESCE_PLACEHOLDERS | MEM_PRESERVE_PLACEHOLDER)) != 0) {
return VmStatus::NotSupported;
}
const bool release = (freeType & MEM_RELEASE) != 0;
const bool decommit = (freeType & MEM_DECOMMIT) != 0;
if (release == decommit) {
return VmStatus::InvalidParameter;
}
const uintptr_t pageSize = wibo::heap::systemPageSize();
std::lock_guard lk(g_mappingsMutex);
if (release) {
uintptr_t base = reinterpret_cast<uintptr_t>(baseAddress);
auto it = g_virtualAllocations.find(base);
if (it == g_virtualAllocations.end()) {
auto containing = findRegionIterator(base);
if (regionSize != 0 && containing != g_virtualAllocations.end()) {
return VmStatus::InvalidParameter;
}
return VmStatus::InvalidAddress;
}
if (regionSize != 0) {
return VmStatus::InvalidParameter;
}
std::size_t length = it->second.size;
g_virtualAllocations.erase(it);
// Replace with PROT_NONE + MAP_NORESERVE to release physical memory
void *res = mmap(reinterpret_cast<void *>(base), length, PROT_NONE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED | MAP_NORESERVE, -1, 0);
if (res == MAP_FAILED) {
return vmStatusFromErrno(errno);
}
setVirtualAllocationName(res, length, "wibo reserved");
eraseGuestMappingLocked(base);
return VmStatus::Success;
}
uintptr_t request = reinterpret_cast<uintptr_t>(baseAddress);
auto regionIt = findRegionIterator(request);