File: emmalloc_memgrowth.cpp

package info (click to toggle)
emscripten 3.1.69%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 121,860 kB
  • sloc: ansic: 636,110; cpp: 425,974; javascript: 78,401; python: 58,404; sh: 49,154; pascal: 5,237; makefile: 3,366; asm: 2,415; lisp: 1,869
file content (34 lines) | stat: -rw-r--r-- 1,056 bytes parent folder | download | duplicates (2)
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
#include <stdio.h>
#include <stdlib.h>
#include <emscripten/heap.h>

uint64_t nextAllocationSize = 16*1024*1024;
bool allocHasFailed = false;

void grow_memory() {
  uint8_t *ptr = (uint8_t*)malloc((size_t)nextAllocationSize);
  EM_ASM({}, ptr); // Pass ptr out to confuse LLVM that it is used, so it won't optimize it away in -O1 and higher.
  size_t heapSize = emscripten_get_heap_size();
  printf("Allocated %zu: %d. Heap size: %zu\n", (size_t)nextAllocationSize, ptr ? 1 : 0, heapSize);
  if (ptr) {
    if (!allocHasFailed) {
      nextAllocationSize *= 2;
      // Make sure we don't overflow, and also exercise malloc(-1) to gracefully return 0 in ABORTING_MALLOC=0 mode.
      if (nextAllocationSize > 0xFFFFFFFFULL)
        nextAllocationSize = 0xFFFFFFFFULL;
    }
  } else {
    nextAllocationSize /= 2;
    allocHasFailed = true;
  }
}

int main() {
  // Exhaust all available memory.
  for(int i = 0; i < 50; ++i) {
    grow_memory();
  }
  // If we get this far without crashing on OOM, we are ok!
  printf("Test finished!\n");
  return 0;
}