summaryrefslogtreecommitdiffstats
path: root/third_party/rlbox_wasm2c_sandbox/src/wasm2c_rt_mem.c
blob: 1bdf6f715c0e506b4efcf540899e5d572e9f485f (plain)
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
#include "wasm2c_rt_mem.h"
#include "wasm-rt.h"

#include <errno.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

enum
{
  MMAP_PROT_NONE = 0,
  MMAP_PROT_READ = 1,
  MMAP_PROT_WRITE = 2,
  MMAP_PROT_EXEC = 4
};

/* Memory map flags */
enum
{
  MMAP_MAP_NONE = 0,
  /* Put the mapping into 0 to 2 G, supported only on x86_64 */
  MMAP_MAP_32BIT = 1,
  /* Don't interpret addr as a hint: place the mapping at exactly
     that address. */
  MMAP_MAP_FIXED = 2
};

// Try reserving an aligned memory space.
// Returns pointer to allocated space on success, 0 on failure.
static void* os_mmap_aligned(void* addr,
                             size_t requested_length,
                             int prot,
                             int flags,
                             size_t alignment,
                             size_t alignment_offset);
// Unreserve the memory space
static void os_munmap(void* addr, size_t size);
// Allocates and sets the permissions on the previously reserved memory space
// Returns 0 on success, non zero on failure.
static int os_mmap_commit(void* curr_heap_end_pointer,
                          size_t expanded_size,
                          int prot);

wasm_rt_memory_t* w2c_env_memory(struct w2c_env* instance)
{
  return instance->sandbox_memory_info;
}

wasm_rt_funcref_table_t* w2c_env_0x5F_indirect_function_table(
  struct w2c_env* instance)
{
  return instance->sandbox_callback_table;
}

#define WASM_PAGE_SIZE 65536
#define RLBOX_FOUR_GIG 0x100000000ull

#if UINTPTR_MAX == 0xffffffffffffffff
// Guard page of 4GiB
#  define WASM_HEAP_GUARD_PAGE_SIZE 0x100000000ull
// Heap aligned to 4GB
#  define WASM_HEAP_ALIGNMENT 0x100000000ull
// By default max heap is 4GB
#  define WASM_HEAP_DEFAULT_MAX_PAGES 65536
#elif UINTPTR_MAX == 0xffffffff
// No guard pages
#  define WASM_HEAP_GUARD_PAGE_SIZE 0
// Unaligned heap
#  define WASM_HEAP_ALIGNMENT 0
// Default max heap is 16MB
#  define WASM_HEAP_DEFAULT_MAX_PAGES 256
#else
#  error "Unknown pointer size"
#endif

static uint64_t compute_heap_reserve_space(uint32_t chosen_max_pages)
{
  const uint64_t heap_reserve_size =
    ((uint64_t)chosen_max_pages) * WASM_PAGE_SIZE + WASM_HEAP_GUARD_PAGE_SIZE;
  return heap_reserve_size;
}

w2c_mem_capacity get_valid_wasm2c_memory_capacity(uint64_t min_capacity,
                                                  bool is_mem_32)
{
  const w2c_mem_capacity err_val = { false /* is_valid */,
                                     false /* is_mem_32 */,
                                     0 /* max_pages */,
                                     0 /* max_size */ };

  // We do not handle memory 64
  if (!is_mem_32) {
    return err_val;
  }

  const uint64_t default_capacity =
    ((uint64_t)WASM_HEAP_DEFAULT_MAX_PAGES) * WASM_PAGE_SIZE;

  if (min_capacity <= default_capacity) {
    // Handle 0 case and small values
    const w2c_mem_capacity ret = { true /* is_valid */,
                                   true /* is_mem_32 */,
                                   WASM_HEAP_DEFAULT_MAX_PAGES /* max_pages */,
                                   default_capacity /* max_size */ };
    return ret;
  } else if (min_capacity > UINT32_MAX) {
    // Handle out of range values
    return err_val;
  }

  const uint64_t page_size_minus_1 = WASM_PAGE_SIZE - 1;
  // Get number of pages greater than min_capacity
  const uint64_t capacity_pages = ((min_capacity - 1) / page_size_minus_1) + 1;

  const w2c_mem_capacity ret = { true /* is_valid */,
                                 true /* is_mem_32 */,
                                 capacity_pages /* max_pages */,
                                 capacity_pages *
                                   WASM_PAGE_SIZE /* max_size */ };
  return ret;
}

wasm_rt_memory_t create_wasm2c_memory(uint32_t initial_pages,
                                      const w2c_mem_capacity* custom_capacity)
{

  if (custom_capacity && !custom_capacity->is_valid) {
    wasm_rt_memory_t ret = { 0 };
    return ret;
  }

  const uint32_t byte_length = initial_pages * WASM_PAGE_SIZE;
  const uint64_t chosen_max_pages =
    custom_capacity ? custom_capacity->max_pages : WASM_HEAP_DEFAULT_MAX_PAGES;
  const uint64_t heap_reserve_size =
    compute_heap_reserve_space(chosen_max_pages);

  uint8_t* data = 0;
  const uint64_t retries = 10;
  for (uint64_t i = 0; i < retries; i++) {
    data = (uint8_t*)os_mmap_aligned(0,
                                     heap_reserve_size,
                                     MMAP_PROT_NONE,
                                     MMAP_MAP_NONE,
                                     WASM_HEAP_ALIGNMENT,
                                     0 /* alignment_offset */);
    if (data) {
      int ret =
        os_mmap_commit(data, byte_length, MMAP_PROT_READ | MMAP_PROT_WRITE);
      if (ret != 0) {
        // failed to set permissions
        os_munmap(data, heap_reserve_size);
        data = 0;
      }
      break;
    }
  }

  wasm_rt_memory_t ret;
  ret.data = data;
  ret.max_pages = chosen_max_pages;
  ret.pages = initial_pages;
  ret.size = byte_length;
  return ret;
}

void destroy_wasm2c_memory(wasm_rt_memory_t* memory)
{
  if (memory->data != 0) {
    const uint64_t heap_reserve_size =
      compute_heap_reserve_space(memory->max_pages);
    os_munmap(memory->data, heap_reserve_size);
    memory->data = 0;
  }
}

#undef WASM_HEAP_DEFAULT_MAX_PAGES
#undef WASM_HEAP_ALIGNMENT
#undef WASM_HEAP_GUARD_PAGE_SIZE
#undef RLBOX_FOUR_GIG
#undef WASM_PAGE_SIZE

// Based on
// https://web.archive.org/web/20191012035921/http://nadeausoftware.com/articles/2012/01/c_c_tip_how_use_compiler_predefined_macros_detect_operating_system#BSD
// Check for windows (non cygwin) environment
#if defined(_WIN32)

#  include <windows.h>

static size_t os_getpagesize()
{
  SYSTEM_INFO S;
  GetNativeSystemInfo(&S);
  return S.dwPageSize;
}

static void* win_mmap(void* hint,
                      size_t size,
                      int prot,
                      int flags,
                      DWORD alloc_flag)
{
  DWORD flProtect = PAGE_NOACCESS;
  size_t request_size, page_size;
  void* addr;

  page_size = os_getpagesize();
  request_size = (size + page_size - 1) & ~(page_size - 1);

  if (request_size < size)
    /* integer overflow */
    return NULL;

  if (request_size == 0)
    request_size = page_size;

  if (prot & MMAP_PROT_EXEC) {
    if (prot & MMAP_PROT_WRITE)
      flProtect = PAGE_EXECUTE_READWRITE;
    else
      flProtect = PAGE_EXECUTE_READ;
  } else if (prot & MMAP_PROT_WRITE)
    flProtect = PAGE_READWRITE;
  else if (prot & MMAP_PROT_READ)
    flProtect = PAGE_READONLY;

  addr = VirtualAlloc((LPVOID)hint, request_size, alloc_flag, flProtect);
  return addr;
}

static void* os_mmap_aligned(void* addr,
                             size_t requested_length,
                             int prot,
                             int flags,
                             size_t alignment,
                             size_t alignment_offset)
{
  size_t padded_length = requested_length + alignment + alignment_offset;
  uintptr_t unaligned =
    (uintptr_t)win_mmap(addr, padded_length, prot, flags, MEM_RESERVE);

  if (!unaligned) {
    return (void*)unaligned;
  }

  // Round up the next address that has addr % alignment = 0
  const size_t alignment_corrected = alignment == 0 ? 1 : alignment;
  uintptr_t aligned_nonoffset =
    (unaligned + (alignment_corrected - 1)) & ~(alignment_corrected - 1);

  // Currently offset 0 is aligned according to alignment
  // Alignment needs to be enforced at the given offset
  uintptr_t aligned = 0;
  if ((aligned_nonoffset - alignment_offset) >= unaligned) {
    aligned = aligned_nonoffset - alignment_offset;
  } else {
    aligned = aligned_nonoffset - alignment_offset + alignment;
  }

  if (aligned == unaligned && padded_length == requested_length) {
    return (void*)aligned;
  }

  // Sanity check
  if (aligned < unaligned ||
      (aligned + (requested_length - 1)) > (unaligned + (padded_length - 1)) ||
      (aligned + alignment_offset) % alignment_corrected != 0) {
    os_munmap((void*)unaligned, padded_length);
    return NULL;
  }

  // windows does not support partial unmapping, so unmap and remap
  os_munmap((void*)unaligned, padded_length);
  aligned = (uintptr_t)win_mmap(
    (void*)aligned, requested_length, prot, flags, MEM_RESERVE);
  return (void*)aligned;
}

static void os_munmap(void* addr, size_t size)
{
  DWORD alloc_flag = MEM_RELEASE;
  if (addr) {
    if (VirtualFree(addr, 0, alloc_flag) == 0) {
      size_t page_size = os_getpagesize();
      size_t request_size = (size + page_size - 1) & ~(page_size - 1);
      int64_t curr_err = errno;
      printf("os_munmap error addr:%p, size:0x%zx, errno:%" PRId64 "\n",
             addr,
             request_size,
             curr_err);
    }
  }
}

static int os_mmap_commit(void* curr_heap_end_pointer,
                          size_t expanded_size,
                          int prot)
{
  uintptr_t addr = (uintptr_t)win_mmap(
    curr_heap_end_pointer, expanded_size, prot, MMAP_MAP_NONE, MEM_COMMIT);
  int ret = addr ? 0 : -1;
  return ret;
}

#elif !defined(_WIN32) && (defined(__unix__) || defined(__unix) ||             \
                           (defined(__APPLE__) && defined(__MACH__)))

#  include <sys/mman.h>
#  include <unistd.h>

static size_t os_getpagesize()
{
  return getpagesize();
}

static void* os_mmap(void* hint, size_t size, int prot, int flags)
{
  int map_prot = PROT_NONE;
  int map_flags = MAP_ANONYMOUS | MAP_PRIVATE;
  uint64_t request_size, page_size;
  void* addr;

  page_size = (uint64_t)os_getpagesize();
  request_size = (size + page_size - 1) & ~(page_size - 1);

  if ((size_t)request_size < size)
    /* integer overflow */
    return NULL;

  if (request_size > 16 * (uint64_t)UINT32_MAX)
    /* At most 16 G is allowed */
    return NULL;

  if (prot & MMAP_PROT_READ)
    map_prot |= PROT_READ;

  if (prot & MMAP_PROT_WRITE)
    map_prot |= PROT_WRITE;

  if (prot & MMAP_PROT_EXEC)
    map_prot |= PROT_EXEC;

#  if defined(BUILD_TARGET_X86_64) || defined(BUILD_TARGET_AMD_64)
#    ifndef __APPLE__
  if (flags & MMAP_MAP_32BIT)
    map_flags |= MAP_32BIT;
#    endif
#  endif

  if (flags & MMAP_MAP_FIXED)
    map_flags |= MAP_FIXED;

  addr = mmap(hint, request_size, map_prot, map_flags, -1, 0);

  if (addr == MAP_FAILED)
    return NULL;

  return addr;
}

static void* os_mmap_aligned(void* addr,
                             size_t requested_length,
                             int prot,
                             int flags,
                             size_t alignment,
                             size_t alignment_offset)
{
  size_t padded_length = requested_length + alignment + alignment_offset;
  uintptr_t unaligned = (uintptr_t)os_mmap(addr, padded_length, prot, flags);

  if (!unaligned) {
    return (void*)unaligned;
  }

  // Round up the next address that has addr % alignment = 0
  const size_t alignment_corrected = alignment == 0 ? 1 : alignment;
  uintptr_t aligned_nonoffset =
    (unaligned + (alignment_corrected - 1)) & ~(alignment_corrected - 1);

  // Currently offset 0 is aligned according to alignment
  // Alignment needs to be enforced at the given offset
  uintptr_t aligned = 0;
  if ((aligned_nonoffset - alignment_offset) >= unaligned) {
    aligned = aligned_nonoffset - alignment_offset;
  } else {
    aligned = aligned_nonoffset - alignment_offset + alignment;
  }

  // Sanity check
  if (aligned < unaligned ||
      (aligned + (requested_length - 1)) > (unaligned + (padded_length - 1)) ||
      (aligned + alignment_offset) % alignment_corrected != 0) {
    os_munmap((void*)unaligned, padded_length);
    return NULL;
  }

  {
    size_t unused_front = aligned - unaligned;
    if (unused_front != 0) {
      os_munmap((void*)unaligned, unused_front);
    }
  }

  {
    size_t unused_back =
      (unaligned + (padded_length - 1)) - (aligned + (requested_length - 1));
    if (unused_back != 0) {
      os_munmap((void*)(aligned + requested_length), unused_back);
    }
  }

  return (void*)aligned;
}

static void os_munmap(void* addr, size_t size)
{
  uint64_t page_size = (uint64_t)os_getpagesize();
  uint64_t request_size = (size + page_size - 1) & ~(page_size - 1);

  if (addr) {
    if (munmap(addr, request_size)) {
      printf("os_munmap error addr:%p, size:0x%" PRIx64 ", errno:%d\n",
             addr,
             request_size,
             errno);
    }
  }
}

static int os_mmap_commit(void* addr, size_t size, int prot)
{
  int map_prot = PROT_NONE;
  uint64_t page_size = (uint64_t)os_getpagesize();
  uint64_t request_size = (size + page_size - 1) & ~(page_size - 1);

  if (!addr)
    return 0;

  if (prot & MMAP_PROT_READ)
    map_prot |= PROT_READ;

  if (prot & MMAP_PROT_WRITE)
    map_prot |= PROT_WRITE;

  if (prot & MMAP_PROT_EXEC)
    map_prot |= PROT_EXEC;

  return mprotect(addr, request_size, map_prot);
}

#else
#  error "Unknown OS"
#endif