1#include <unistd.h>
 2#include <stdlib.h>
 3#include <errno.h>
 4#include <__macro_PAGESIZE.h>
 5
 6// Bare-bones implementation of sbrk.
 7void *sbrk(intptr_t increment) {
 8    // sbrk(0) returns the current memory size.
 9    if (increment == 0) {
10        // The wasm spec doesn't guarantee that memory.grow of 0 always succeeds.
11        return (void *)(__builtin_wasm_memory_size(0) * PAGESIZE);
12    }
13
14    // We only support page-size increments.
15    if (increment % PAGESIZE != 0) {
16        abort();
17    }
18
19    // WebAssembly doesn't support shrinking linear memory.
20    if (increment < 0) {
21        abort();
22    }
23
24    uintptr_t old = __builtin_wasm_memory_grow(0, (uintptr_t)increment / PAGESIZE);
25
26    if (old == SIZE_MAX) {
27        errno = ENOMEM;
28        return (void *)-1;
29    }
30
31    return (void *)(old * PAGESIZE);
32}