File: emmalloc_memgrowth.cpp

package info (click to toggle)
emscripten 3.1.6~dfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 114,112 kB
  • sloc: ansic: 583,052; cpp: 391,943; javascript: 79,361; python: 54,180; sh: 49,997; pascal: 4,658; makefile: 3,426; asm: 2,191; lisp: 1,869; ruby: 488; cs: 142
file content (41 lines) | stat: -rw-r--r-- 1,056 bytes parent folder | download
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
#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");
#ifdef REPORT_RESULT
	REPORT_RESULT(0);
#endif
}