-
Notifications
You must be signed in to change notification settings - Fork 202
/
libos_vma.c
1778 lines (1472 loc) · 57.5 KB
/
libos_vma.c
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
/* SPDX-License-Identifier: LGPL-3.0-or-later */
/* Copyright (C) 2014 Stony Brook University
* Copyright (C) 2020 Invisible Things Lab
*/
#include <stddef.h> /* needed by <linux/signal.h> for size_t */
#include <stdalign.h>
#include <stdbool.h>
#include <stdint.h>
#include "api.h"
#include "assert.h"
#include "avl_tree.h"
#include "libos_checkpoint.h"
#include "libos_defs.h"
#include "libos_flags_conv.h"
#include "libos_handle.h"
#include "libos_internal.h"
#include "libos_lock.h"
#include "libos_rwlock.h"
#include "libos_tcb.h"
#include "libos_utils.h"
#include "libos_vma.h"
#include "linux_abi/memory.h"
/* The amount of total memory usage, all accesses must be protected by `vma_tree_lock`. */
static size_t g_total_memory_size = 0;
/* The peak amount of total memory usage, all accesses must use atomics, writes must also hold
* `vma_tree_lock`. */
static size_t g_peak_total_memory_size = 0;
/* Filter flags that will be saved in `struct libos_vma`. For example there is no need for saving
* MAP_FIXED or unsupported flags. */
static int filter_saved_flags(int flags) {
return flags & (MAP_SHARED | MAP_SHARED_VALIDATE | MAP_PRIVATE | MAP_ANONYMOUS | MAP_GROWSDOWN
| MAP_HUGETLB | MAP_HUGE_2MB | MAP_HUGE_1GB | MAP_STACK
| VMA_UNMAPPED | VMA_INTERNAL | VMA_TAINTED);
}
/* TODO: split flags into internal (Gramine) and Linux; also to consider: completely remove Linux
* flags - we only need MAP_SHARED/MAP_PRIVATE and possibly MAP_STACK/MAP_GROWSDOWN */
struct libos_vma {
uintptr_t begin;
uintptr_t end;
int prot;
int flags;
struct libos_handle* file;
uint64_t offset; // offset inside `file`, where `begin` starts
union {
/* If this `vma` is used, it is included in `vma_tree` using this node. */
struct avl_tree_node tree_node;
/* Otherwise it might be cached in per thread vma cache, or might be on a temporary list
* of to-be-freed vmas (used by _vma_bkeep_remove). Such lists use the field below. */
struct libos_vma* next_free;
};
char comment[VMA_COMMENT_LEN];
};
static void copy_comment(struct libos_vma* vma, const char* comment) {
size_t size = MIN(sizeof(vma->comment), strlen(comment) + 1);
memcpy(vma->comment, comment, size);
vma->comment[sizeof(vma->comment) - 1] = '\0';
}
static void copy_vma(struct libos_vma* old_vma, struct libos_vma* new_vma) {
new_vma->begin = old_vma->begin;
new_vma->end = old_vma->end;
new_vma->prot = old_vma->prot;
new_vma->flags = old_vma->flags;
new_vma->file = old_vma->file;
if (new_vma->file) {
if (new_vma->file->inode)
(void)__atomic_add_fetch(&new_vma->file->inode->num_mmapped, 1, __ATOMIC_RELAXED);
get_handle(new_vma->file);
}
new_vma->offset = old_vma->offset;
copy_comment(new_vma, old_vma->comment);
}
static bool vma_tree_cmp(struct avl_tree_node* node_a, struct avl_tree_node* node_b) {
struct libos_vma* a = container_of(node_a, struct libos_vma, tree_node);
struct libos_vma* b = container_of(node_b, struct libos_vma, tree_node);
return a->end <= b->end;
}
static bool is_addr_in_vma(uintptr_t addr, struct libos_vma* vma) {
return vma->begin <= addr && addr < vma->end;
}
/* Returns whether `addr` is smaller or inside a vma (`node`). */
static bool cmp_addr_to_vma(void* addr, struct avl_tree_node* node) {
struct libos_vma* vma = container_of(node, struct libos_vma, tree_node);
return (uintptr_t)addr < vma->end;
}
/*
* "vma_tree" holds all vmas with the assumption that no 2 overlap (though they could be adjacent).
* Currently we do not merge similar adjacent vmas - if we ever start doing it, this code needs
* to be revisited as there might be some optimizations that would break due to it.
*/
static struct avl_tree vma_tree = {.cmp = vma_tree_cmp};
static struct libos_rwlock vma_tree_lock;
static bool vma_tree_lock_created = false;
static inline void vma_rwlock_read_lock(struct libos_rwlock* l) {
if (!vma_tree_lock_created)
return;
rwlock_read_lock(l);
}
static inline void vma_rwlock_read_unlock(struct libos_rwlock* l) {
if (!vma_tree_lock_created)
return;
rwlock_read_unlock(l);
}
static inline void vma_rwlock_write_lock(struct libos_rwlock* l) {
if (!vma_tree_lock_created)
return;
rwlock_write_lock(l);
}
static inline void vma_rwlock_write_unlock(struct libos_rwlock* l) {
if (!vma_tree_lock_created)
return;
rwlock_write_unlock(l);
}
#ifdef DEBUG
static inline bool vma_rwlock_is_read_locked(struct libos_rwlock* l) {
if (!vma_tree_lock_created)
return true;
return rwlock_is_read_locked(l);
}
static inline bool vma_rwlock_is_write_locked(struct libos_rwlock* l) {
if (!vma_tree_lock_created)
return true;
return rwlock_is_write_locked(l);
}
#endif
/* VMA code is supposed to use the vma_* wrappers of RW lock; hide the actual RW lock funcs */
#define rwlock_is_write_locked(x) false
#define rwlock_is_read_locked(x) false
#define rwlock_read_lock(x) static_assert(false, "hidden func")
#define rwlock_read_unlock(x) static_assert(false, "hidden func")
#define rwlock_write_lock(x) static_assert(false, "hidden func")
#define rwlock_write_unlock(x) static_assert(false, "hidden func")
static void total_memory_size_add(size_t length) {
assert(vma_rwlock_is_write_locked(&vma_tree_lock));
g_total_memory_size += length;
/* We can read `g_peak_total_memory_size` non atomically, because writes are protected by
* `vma_tree_lock`, which we hold. Store needs to be atomic to synchronize with readers. */
if (g_peak_total_memory_size < g_total_memory_size) {
__atomic_store_n(&g_peak_total_memory_size, g_total_memory_size, __ATOMIC_RELAXED);
}
}
static void total_memory_size_sub(size_t length) {
assert(vma_rwlock_is_write_locked(&vma_tree_lock));
assert(g_total_memory_size >= length);
g_total_memory_size -= length;
}
static struct libos_vma* node2vma(struct avl_tree_node* node) {
if (!node) {
return NULL;
}
return container_of(node, struct libos_vma, tree_node);
}
static struct libos_vma* _get_next_vma(struct libos_vma* vma) {
assert(vma_rwlock_is_read_locked(&vma_tree_lock) || vma_rwlock_is_write_locked(&vma_tree_lock));
return node2vma(avl_tree_next(&vma->tree_node));
}
static struct libos_vma* _get_prev_vma(struct libos_vma* vma) {
assert(vma_rwlock_is_read_locked(&vma_tree_lock) || vma_rwlock_is_write_locked(&vma_tree_lock));
return node2vma(avl_tree_prev(&vma->tree_node));
}
static struct libos_vma* _get_last_vma(void) {
assert(vma_rwlock_is_read_locked(&vma_tree_lock) || vma_rwlock_is_write_locked(&vma_tree_lock));
return node2vma(avl_tree_last(&vma_tree));
}
static struct libos_vma* _get_first_vma(void) {
assert(vma_rwlock_is_read_locked(&vma_tree_lock) || vma_rwlock_is_write_locked(&vma_tree_lock));
return node2vma(avl_tree_first(&vma_tree));
}
/* Returns the vma that contains `addr`. If there is no such vma, returns the closest vma with
* higher address. */
static struct libos_vma* _lookup_vma(uintptr_t addr) {
assert(vma_rwlock_is_read_locked(&vma_tree_lock) || vma_rwlock_is_write_locked(&vma_tree_lock));
struct avl_tree_node* node = avl_tree_lower_bound_fn(&vma_tree, (void*)addr, cmp_addr_to_vma);
if (!node) {
return NULL;
}
return container_of(node, struct libos_vma, tree_node);
}
typedef bool (*traverse_visitor)(struct libos_vma* vma, void* visitor_arg);
/*
* Walks through all VMAs which contain at least one byte from the [begin, end) range.
*
* `visitor` returns whether to continue iteration. It must be as simple as possible, because
* it's called with the VMA lock held.
*
* Returns whether the traversed range was continuously covered by VMAs. This is useful for
* emulating errors in memory management syscalls.
*/
// TODO: Probably other VMA functions could make use of this helper.
static bool _traverse_vmas_in_range(uintptr_t begin, uintptr_t end, traverse_visitor visitor,
void* visitor_arg) {
assert(vma_rwlock_is_read_locked(&vma_tree_lock) || vma_rwlock_is_write_locked(&vma_tree_lock));
assert(begin <= end);
if (begin == end)
return true;
struct libos_vma* vma = _lookup_vma(begin);
if (!vma || end <= vma->begin)
return false;
struct libos_vma* prev = NULL;
bool is_continuous = vma->begin <= begin;
while (1) {
if (!visitor(vma, visitor_arg))
break;
prev = vma;
vma = _get_next_vma(vma);
if (!vma || end <= vma->begin) {
is_continuous &= end <= prev->end;
break;
}
is_continuous &= prev->end == vma->begin;
}
return is_continuous;
}
static void split_vma(struct libos_vma* old_vma, struct libos_vma* new_vma, uintptr_t addr) {
assert(old_vma->begin < addr && addr < old_vma->end);
copy_vma(old_vma, new_vma);
new_vma->begin = addr;
if (new_vma->file) {
new_vma->offset += new_vma->begin - old_vma->begin;
}
old_vma->end = addr;
}
/*
* This function might need a preallocated vma in `new_vma_ptr`, because it might need to split
* an existing vma into two parts. If the vma is provided and this function happens to use it,
* `*new_vma_ptr` will be set to NULL.
* It returns a list of vmas that need to be freed in `vmas_to_free`.
* Range [begin, end) can consist of multiple vmas even with holes in between, but they all must be
* either internal or non-internal.
*/
static int _vma_bkeep_remove(uintptr_t begin, uintptr_t end, bool is_internal,
struct libos_vma** new_vma_ptr, struct libos_vma** vmas_to_free) {
assert(vma_rwlock_is_write_locked(&vma_tree_lock));
assert(!new_vma_ptr || *new_vma_ptr);
assert(IS_ALLOC_ALIGNED_PTR(begin) && IS_ALLOC_ALIGNED_PTR(end));
struct libos_vma* vma = _lookup_vma(begin);
if (!vma) {
return 0;
}
struct libos_vma* first_vma = vma;
while (vma && vma->begin < end) {
if (!!(vma->flags & VMA_INTERNAL) != is_internal) {
if (is_internal) {
log_warning("LibOS tried to free a user vma!");
} else {
log_warning("user app tried to free an internal vma!");
}
return -EACCES;
}
vma = _get_next_vma(vma);
}
vma = first_vma;
if (vma->begin < begin) {
if (end < vma->end) {
if (!new_vma_ptr) {
log_warning("need an additional vma to free this range!");
return -ENOMEM;
}
struct libos_vma* new_vma = *new_vma_ptr;
*new_vma_ptr = NULL;
split_vma(vma, new_vma, end);
vma->end = begin;
avl_tree_insert(&vma_tree, &new_vma->tree_node);
total_memory_size_sub(end - begin);
return 0;
}
total_memory_size_sub(vma->end - begin);
vma->end = begin;
vma = _get_next_vma(vma);
if (!vma) {
return 0;
}
}
while (vma->end <= end) {
/* We need to search for the next node before deletion. */
struct libos_vma* next = _get_next_vma(vma);
avl_tree_delete(&vma_tree, &vma->tree_node);
total_memory_size_sub(vma->end - vma->begin);
vma->next_free = NULL;
*vmas_to_free = vma;
vmas_to_free = &vma->next_free;
if (!next) {
return 0;
}
vma = next;
}
if (vma->begin < end) {
if (vma->file) {
vma->offset += end - vma->begin;
}
total_memory_size_sub(end - vma->begin);
vma->begin = end;
}
return 0;
}
static void free_vmas_freelist(struct libos_vma* vma);
/* This function uses at most 1 vma (in `bkeep_mmap_any`). `alloc_vma` depends on this behavior. */
static void* _vma_malloc(size_t size) {
void* addr = NULL;
size = ALLOC_ALIGN_UP(size);
if (bkeep_mmap_any(size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | VMA_INTERNAL,
NULL, 0, "vma", &addr) < 0) {
return NULL;
}
int ret = PalVirtualMemoryAlloc(addr, size, PAL_PROT_WRITE | PAL_PROT_READ);
if (ret < 0) {
struct libos_vma* vmas_to_free = NULL;
vma_rwlock_write_lock(&vma_tree_lock);
/* Since we are freeing a range we just created, additional vma is not needed. */
ret = _vma_bkeep_remove((uintptr_t)addr, (uintptr_t)addr + size, /*is_internal=*/true, NULL,
&vmas_to_free);
vma_rwlock_write_unlock(&vma_tree_lock);
if (ret < 0) {
log_error("Removing a vma we just created failed: %s", unix_strerror(ret));
BUG();
}
free_vmas_freelist(vmas_to_free);
return NULL;
}
return addr;
}
/* We never free `vma_mgr`. */
static void _vma_free(void* ptr, size_t size) {
__UNUSED(ptr);
__UNUSED(size);
BUG();
}
#undef system_malloc
#undef system_free
#define system_malloc _vma_malloc
#define system_free _vma_free
#define OBJ_TYPE struct libos_vma
#include "memmgr.h"
static struct libos_lock vma_mgr_lock;
static MEM_MGR vma_mgr = NULL;
/*
* We use a following per-thread caching mechanism of VMAs:
* Each thread has a singly linked list of free VMAs, with maximal length of 3.
* Allocation first checks if there is a cached VMA, deallocation adds it to cache, unless it is
* full (3 entries already present).
* Note that 3 is configurable number as long as it is a power of 2 minus 1 and `struct libos_vma`
* alignment is not less that it. This is needed for storing the list length in lower bits of
* the pointer (small optimization not to add more fields to TCB - can be removed if the max list
* size needs to be increased or any supported architecture does not allow for it).
*/
#ifndef __x86_64__
/* If this optimization will work on the architecture you port Gramine to, add it to the check
* above. */
#error "This optimization requires specific representation of pointers."
#endif
#define VMA_CACHE_SIZE 3ull
static_assert((VMA_CACHE_SIZE & (VMA_CACHE_SIZE + 1)) == 0,
"VMA_CACHE_SIZE must be a power of 2 minus 1!");
static struct libos_vma* cache2ptr(void* vma) {
static_assert(
alignof(struct libos_vma) >= VMA_CACHE_SIZE + 1,
"We need some lower bits of pointers to `struct libos_vma` for this optimization!");
return (struct libos_vma*)((uintptr_t)vma & ~VMA_CACHE_SIZE);
}
static void* create_cache_ptr(struct libos_vma* vma, size_t size) {
assert(size <= VMA_CACHE_SIZE);
return (void*)((uintptr_t)vma | size);
}
static size_t cache2size(void* vma) {
return (size_t)((uintptr_t)vma & VMA_CACHE_SIZE);
}
static struct libos_vma* get_from_thread_vma_cache(void) {
struct libos_vma* vma = cache2ptr(LIBOS_TCB_GET(vma_cache));
if (!vma) {
return NULL;
}
LIBOS_TCB_SET(vma_cache, vma->next_free);
return vma;
}
static bool add_to_thread_vma_cache(struct libos_vma* vma) {
assert(cache2size(vma) == 0);
void* ptr = LIBOS_TCB_GET(vma_cache);
size_t size = cache2size(ptr);
if (size >= VMA_CACHE_SIZE) {
return false;
}
vma->next_free = ptr;
LIBOS_TCB_SET(vma_cache, create_cache_ptr(vma, size + 1));
return true;
}
static void remove_from_thread_vma_cache(struct libos_vma* to_remove) {
assert(to_remove);
struct libos_vma* first_vma = cache2ptr(LIBOS_TCB_GET(vma_cache));
if (first_vma == to_remove) {
LIBOS_TCB_SET(vma_cache, first_vma->next_free);
return;
}
struct libos_vma* vma = first_vma;
bool found = false;
while (vma) {
struct libos_vma* next = cache2ptr(vma->next_free);
if (next == to_remove) {
found = true;
break;
}
vma = next;
}
if (!found) {
return;
}
LIBOS_TCB_SET(vma_cache, create_cache_ptr(first_vma, cache2size(first_vma) - 1));
vma = first_vma;
while (vma) {
struct libos_vma* next = cache2ptr(vma->next_free);
if (next == to_remove) {
vma->next_free = next->next_free;
return;
}
vma->next_free = create_cache_ptr(next, cache2size(vma->next_free) - 1);
vma = next;
}
}
static struct libos_vma* alloc_vma(void) {
struct libos_vma* vma = get_from_thread_vma_cache();
if (vma) {
goto out;
}
lock(&vma_mgr_lock);
vma = get_mem_obj_from_mgr(vma_mgr);
if (!vma) {
/* `enlarge_mem_mgr` below will call _vma_malloc, which uses at most 1 vma - so we
* temporarily provide it. */
struct libos_vma tmp_vma = {0};
/* vma cache is empty, as we checked it before. */
if (!add_to_thread_vma_cache(&tmp_vma)) {
log_error("Failed to add tmp vma to cache!");
BUG();
}
if (!enlarge_mem_mgr(vma_mgr, size_align_up(DEFAULT_VMA_COUNT))) {
remove_from_thread_vma_cache(&tmp_vma);
goto out_unlock;
}
struct libos_vma* vma_migrate = get_mem_obj_from_mgr(vma_mgr);
if (!vma_migrate) {
log_error("Failed to allocate a vma right after enlarge_mem_mgr!");
BUG();
}
vma_rwlock_write_lock(&vma_tree_lock);
/* Currently `tmp_vma` is always used (added to `vma_tree`), but this assumption could
* easily be changed (e.g. if we implement VMAs merging).*/
struct avl_tree_node* node = &tmp_vma.tree_node;
if (node->parent || vma_tree.root == node) {
/* `tmp_vma` is in `vma_tree`, we need to migrate it. */
copy_vma(&tmp_vma, vma_migrate);
avl_tree_swap_node(&vma_tree, node, &vma_migrate->tree_node);
vma_migrate = NULL;
}
vma_rwlock_write_unlock(&vma_tree_lock);
if (vma_migrate) {
free_mem_obj_to_mgr(vma_mgr, vma_migrate);
}
remove_from_thread_vma_cache(&tmp_vma);
vma = get_mem_obj_from_mgr(vma_mgr);
}
out_unlock:
unlock(&vma_mgr_lock);
out:
if (vma) {
memset(vma, 0, sizeof(*vma));
}
return vma;
}
static void free_vma(struct libos_vma* vma) {
if (vma->file) {
if (vma->file->inode) {
uint64_t old_num_mmapped = __atomic_fetch_sub(&vma->file->inode->num_mmapped, 1,
__ATOMIC_RELAXED);
assert(old_num_mmapped > 0);
(void)old_num_mmapped;
}
put_handle(vma->file);
}
if (add_to_thread_vma_cache(vma)) {
return;
}
lock(&vma_mgr_lock);
free_mem_obj_to_mgr(vma_mgr, vma);
unlock(&vma_mgr_lock);
}
static void free_vmas_freelist(struct libos_vma* vma) {
while (vma) {
struct libos_vma* next = vma->next_free;
free_vma(vma);
vma = next;
}
}
static int _bkeep_initial_vma(struct libos_vma* new_vma) {
assert(vma_rwlock_is_write_locked(&vma_tree_lock));
struct libos_vma* tmp_vma = _lookup_vma(new_vma->begin);
if (tmp_vma && tmp_vma->begin < new_vma->end) {
return -EEXIST;
} else {
avl_tree_insert(&vma_tree, &new_vma->tree_node);
total_memory_size_add(new_vma->end - new_vma->begin);
return 0;
}
}
static int pal_mem_bkeep_alloc(size_t size, uintptr_t* out_addr);
static int pal_mem_bkeep_free(uintptr_t addr, size_t size);
#define ASLR_BITS 12
/* This variable is written to only once, during initialization, so it does not need to
* be atomic. */
static void* g_aslr_addr_top = NULL;
int init_vma(void) {
PalSetMemoryBookkeepingUpcalls(pal_mem_bkeep_alloc, pal_mem_bkeep_free);
size_t initial_ranges_count = 0;
for (size_t i = 0; i < g_pal_public_state->initial_mem_ranges_len; i++) {
if (!g_pal_public_state->initial_mem_ranges[i].is_free) {
initial_ranges_count++;
}
}
struct libos_vma init_vmas[1 + initial_ranges_count];
init_vmas[0].begin = 0; // vma for creation of memory manager
size_t idx = 0;
for (size_t i = 0; i < g_pal_public_state->initial_mem_ranges_len; i++) {
if (g_pal_public_state->initial_mem_ranges[i].is_free) {
continue;
}
init_vmas[1 + idx].begin = g_pal_public_state->initial_mem_ranges[i].start;
init_vmas[1 + idx].end = g_pal_public_state->initial_mem_ranges[i].end;
init_vmas[1 + idx].prot = PAL_PROT_TO_LINUX(g_pal_public_state->initial_mem_ranges[i].prot);
init_vmas[1 + idx].flags = MAP_PRIVATE | MAP_ANONYMOUS | VMA_INTERNAL;
init_vmas[1 + idx].file = NULL;
init_vmas[1 + idx].offset = 0;
copy_comment(&init_vmas[1 + idx], g_pal_public_state->initial_mem_ranges[i].comment);
assert(IS_ALLOC_ALIGNED(init_vmas[1 + idx].begin)
&& IS_ALLOC_ALIGNED(init_vmas[1 + idx].end));
idx++;
}
assert(1 + idx == ARRAY_SIZE(init_vmas));
vma_rwlock_write_lock(&vma_tree_lock);
int ret = 0;
/* First of init_vmas is reserved for later usage. */
for (size_t i = 1; i < ARRAY_SIZE(init_vmas); i++) {
assert(init_vmas[i].begin <= init_vmas[i].end);
/* Skip empty areas. */
if (init_vmas[i].begin == init_vmas[i].end) {
log_debug("Skipping bookkeeping of empty region at 0x%lx (comment: \"%s\")",
init_vmas[i].begin, init_vmas[i].comment);
continue;
}
if (!IS_ALLOC_ALIGNED(init_vmas[i].begin) || !IS_ALLOC_ALIGNED(init_vmas[i].end)) {
log_error("Unaligned VMA region: 0x%lx-0x%lx (%s)", init_vmas[i].begin,
init_vmas[i].end, init_vmas[i].comment);
ret = -EINVAL;
break;
}
ret = _bkeep_initial_vma(&init_vmas[i]);
if (ret < 0) {
log_error("Failed to bookkeep initial VMA region 0x%lx-0x%lx (%s)",
init_vmas[i].begin, init_vmas[i].end, init_vmas[i].comment);
break;
}
log_debug("Initial VMA region 0x%lx-0x%lx (%s) bookkeeped", init_vmas[i].begin,
init_vmas[i].end, init_vmas[i].comment);
}
vma_rwlock_write_unlock(&vma_tree_lock);
/* From now on if we return with an error we might leave a structure local to this function in
* vma_tree. We do not bother with removing them - this is initialization of VMA subsystem, if
* it fails the whole application startup fails and we should never call any of functions in
* this file. */
if (ret < 0) {
return ret;
}
g_aslr_addr_top = g_pal_public_state->memory_address_end;
if (!g_pal_public_state->disable_aslr) {
/* Inspired by: https://elixir.bootlin.com/linux/v5.6.3/source/arch/x86/mm/mmap.c#L80 */
size_t gap_max_size = (g_pal_public_state->memory_address_end
- g_pal_public_state->memory_address_start) / 6 * 5;
/* We do address space randomization only if we have at least ASLR_BITS to randomize. */
if (gap_max_size / ALLOC_ALIGNMENT >= (1ul << ASLR_BITS)) {
size_t gap = 0;
int ret = PalRandomBitsRead(&gap, sizeof(gap));
if (ret < 0) {
return pal_to_unix_errno(ret);
}
/* Resulting distribution is not ideal, but it should not be an issue here. */
gap = ALLOC_ALIGN_DOWN(gap % gap_max_size);
g_aslr_addr_top = (char*)g_aslr_addr_top - gap;
log_debug("ASLR top address adjusted to %p", g_aslr_addr_top);
} else {
log_warning("Not enough space to make meaningful address space randomization.");
}
}
/* We need 1 vma to create the memmgr. */
if (!add_to_thread_vma_cache(&init_vmas[0])) {
log_error("Failed to add tmp vma to cache!");
BUG();
}
vma_mgr = create_mem_mgr(DEFAULT_VMA_COUNT);
if (!vma_mgr) {
log_error("Failed to create VMA memory manager!");
return -ENOMEM;
}
if (!create_lock(&vma_mgr_lock)) {
return -ENOMEM;
}
if (!rwlock_create(&vma_tree_lock)) {
return -ENOMEM;
}
vma_tree_lock_created = true;
/* Now we need to migrate temporary initial vmas. */
struct libos_vma* vmas_to_migrate_to[ARRAY_SIZE(init_vmas)];
for (size_t i = 0; i < ARRAY_SIZE(vmas_to_migrate_to); i++) {
vmas_to_migrate_to[i] = alloc_vma();
if (!vmas_to_migrate_to[i]) {
return -ENOMEM;
}
}
vma_rwlock_write_lock(&vma_tree_lock);
for (size_t i = 0; i < ARRAY_SIZE(init_vmas); i++) {
/* Skip empty areas. */
if (init_vmas[i].begin == init_vmas[i].end) {
continue;
}
copy_vma(&init_vmas[i], vmas_to_migrate_to[i]);
avl_tree_swap_node(&vma_tree, &init_vmas[i].tree_node, &vmas_to_migrate_to[i]->tree_node);
vmas_to_migrate_to[i] = NULL;
}
vma_rwlock_write_unlock(&vma_tree_lock);
for (size_t i = 0; i < ARRAY_SIZE(vmas_to_migrate_to); i++) {
if (vmas_to_migrate_to[i]) {
free_vma(vmas_to_migrate_to[i]);
}
}
return 0;
}
static void _add_unmapped_vma(uintptr_t begin, uintptr_t end, struct libos_vma* vma) {
assert(vma_rwlock_is_write_locked(&vma_tree_lock));
vma->begin = begin;
vma->end = end;
vma->prot = PROT_NONE;
vma->flags = VMA_INTERNAL | VMA_UNMAPPED;
vma->file = NULL;
vma->offset = 0;
copy_comment(vma, "");
avl_tree_insert(&vma_tree, &vma->tree_node);
total_memory_size_add(vma->end - vma->begin);
}
// TODO change so that vma1 is provided by caller
int bkeep_munmap(void* addr, size_t length, bool is_internal, void** tmp_vma_ptr) {
assert(tmp_vma_ptr);
if (!length || !IS_ALLOC_ALIGNED(length) || !IS_ALLOC_ALIGNED_PTR(addr)) {
return -EINVAL;
}
struct libos_vma* vma1 = alloc_vma();
if (!vma1) {
return -ENOMEM;
}
/* Unmapping may succeed even without this vma, so if this allocation fails we move on. */
struct libos_vma* vma2 = alloc_vma();
struct libos_vma* vmas_to_free = NULL;
vma_rwlock_write_lock(&vma_tree_lock);
int ret = _vma_bkeep_remove((uintptr_t)addr, (uintptr_t)addr + length, is_internal,
vma2 ? &vma2 : NULL, &vmas_to_free);
if (ret >= 0) {
_add_unmapped_vma((uintptr_t)addr, (uintptr_t)addr + length, vma1);
*tmp_vma_ptr = (void*)vma1;
vma1 = NULL;
}
vma_rwlock_write_unlock(&vma_tree_lock);
free_vmas_freelist(vmas_to_free);
if (vma1) {
free_vma(vma1);
}
if (vma2) {
free_vma(vma2);
}
/*
* TODO: We call `remove_r_debug()` on the assumption that `addr` might be the beginning of a
* loaded ELF object. However, `remove_r_debug()` assumes that `addr` is the load base, while
* the first mapping of an ELF object might begin later than its load base.
*/
remove_r_debug(addr);
return ret;
}
void bkeep_remove_tmp_vma(void* _vma) {
struct libos_vma* vma = (struct libos_vma*)_vma;
assert(vma->flags == (VMA_INTERNAL | VMA_UNMAPPED));
vma_rwlock_write_lock(&vma_tree_lock);
avl_tree_delete(&vma_tree, &vma->tree_node);
total_memory_size_sub(vma->end - vma->begin);
vma_rwlock_write_unlock(&vma_tree_lock);
free_vma(vma);
}
void bkeep_convert_tmp_vma_to_user(void* _vma) {
struct libos_vma* vma = (struct libos_vma*)_vma;
vma_rwlock_write_lock(&vma_tree_lock);
assert(vma->flags == (VMA_INTERNAL | VMA_UNMAPPED));
vma->flags &= ~VMA_INTERNAL;
vma_rwlock_write_unlock(&vma_tree_lock);
}
static bool is_file_prot_matching(struct libos_handle* file_hdl, int prot) {
return !(prot & PROT_WRITE) || (file_hdl->flags & O_RDWR);
}
int bkeep_mmap_fixed(void* addr, size_t length, int prot, int flags, struct libos_handle* file,
uint64_t offset, const char* comment) {
assert(flags & (MAP_FIXED | MAP_FIXED_NOREPLACE));
if (!length || !IS_ALLOC_ALIGNED(length) || !IS_ALLOC_ALIGNED_PTR(addr)) {
return -EINVAL;
}
struct libos_vma* new_vma = alloc_vma();
if (!new_vma) {
return -ENOMEM;
}
/* Unmapping may succeed even without this vma, so if this allocation fails we move on. */
struct libos_vma* vma1 = alloc_vma();
new_vma->begin = (uintptr_t)addr;
new_vma->end = new_vma->begin + length;
new_vma->prot = prot;
new_vma->flags = filter_saved_flags(flags) | ((file && (prot & PROT_WRITE)) ? VMA_TAINTED : 0);
new_vma->file = file;
if (new_vma->file) {
get_handle(new_vma->file);
if (new_vma->file->inode)
(void)__atomic_add_fetch(&new_vma->file->inode->num_mmapped, 1, __ATOMIC_RELAXED);
}
new_vma->offset = file ? offset : 0;
copy_comment(new_vma, comment ?: "");
struct libos_vma* vmas_to_free = NULL;
vma_rwlock_write_lock(&vma_tree_lock);
int ret = 0;
if (flags & MAP_FIXED_NOREPLACE) {
struct libos_vma* tmp_vma = _lookup_vma(new_vma->begin);
if (tmp_vma && tmp_vma->begin < new_vma->end) {
ret = -EEXIST;
}
} else {
ret = _vma_bkeep_remove(new_vma->begin, new_vma->end, !!(flags & VMA_INTERNAL),
vma1 ? &vma1 : NULL, &vmas_to_free);
}
if (ret >= 0) {
avl_tree_insert(&vma_tree, &new_vma->tree_node);
total_memory_size_add(new_vma->end - new_vma->begin);
}
vma_rwlock_write_unlock(&vma_tree_lock);
free_vmas_freelist(vmas_to_free);
if (vma1) {
free_vma(vma1);
}
if (ret < 0) {
free_vma(new_vma);
}
return ret;
}
static void vma_update_prot(struct libos_vma* vma, int prot) {
vma->prot = prot & (PROT_NONE | PROT_READ | PROT_WRITE | PROT_EXEC);
if (vma->file && (prot & PROT_WRITE)) {
vma->flags |= VMA_TAINTED;
}
}
static int _vma_bkeep_change(uintptr_t begin, uintptr_t end, int prot, bool is_internal,
struct libos_vma** new_vma_ptr1, struct libos_vma** new_vma_ptr2) {
assert(vma_rwlock_is_write_locked(&vma_tree_lock));
assert(IS_ALLOC_ALIGNED_PTR(begin) && IS_ALLOC_ALIGNED_PTR(end));
assert(begin < end);
struct libos_vma* vma = _lookup_vma(begin);
if (!vma) {
return -ENOMEM;
}
struct libos_vma* prev = NULL;
struct libos_vma* first_vma = vma;
if (begin < vma->begin) {
return -ENOMEM;
}
bool is_continuous = true;
while (1) {
if (!!(vma->flags & VMA_INTERNAL) != is_internal) {
return -EACCES;
}
if (prot & PROT_GROWSDOWN) {
if (!(vma->flags & MAP_GROWSDOWN)) {
return -EINVAL;
}
}
if (vma->file && (vma->flags & MAP_SHARED)) {
if (!is_file_prot_matching(vma->file, prot)) {
return -EACCES;
}
}
if (end <= vma->end) {
break;
}
prev = vma;
vma = _get_next_vma(vma);
if (!vma) {
is_continuous = false;
break;
}
is_continuous &= prev->end == vma->begin;
}
if (!is_continuous) {
/* When Linux fails with such an error, it still changes permissions of the first
* continuous fragment, but we just return an error. */
return -ENOMEM;
}
vma = first_vma;
/* For PROT_GROWSDOWN we just pretend that `vma->begin == begin`. */
if (vma->begin < begin && !(prot & PROT_GROWSDOWN)) {
struct libos_vma* new_vma1 = *new_vma_ptr1;
*new_vma_ptr1 = NULL;
split_vma(vma, new_vma1, begin);
vma_update_prot(new_vma1, prot);
struct libos_vma* next = _get_next_vma(vma);
avl_tree_insert(&vma_tree, &new_vma1->tree_node);
if (end < new_vma1->end) {
struct libos_vma* new_vma2 = *new_vma_ptr2;
*new_vma_ptr2 = NULL;
split_vma(new_vma1, new_vma2, end);
vma_update_prot(new_vma2, vma->prot);
avl_tree_insert(&vma_tree, &new_vma2->tree_node);
return 0;
}
/* Error checking at the begining ensures we always have the next node. */
assert(next);
vma = next;
}
while (vma->end <= end) {
vma_update_prot(vma, prot);
#ifdef DEBUG
struct libos_vma* prev = vma;
#endif
vma = _get_next_vma(vma);
if (!vma) {