Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
emscripten-core
GitHub Repository: emscripten-core/emscripten
Path: blob/main/src/runtime_stack_check.js
4128 views
1
/**
2
* @license
3
* Copyright 2019 The Emscripten Authors
4
* SPDX-License-Identifier: MIT
5
*/
6
7
#if STACK_OVERFLOW_CHECK
8
// Initializes the stack cookie. Called at the startup of main and at the startup of each thread in pthreads mode.
9
function writeStackCookie() {
10
var max = _emscripten_stack_get_end();
11
#if RUNTIME_DEBUG
12
dbg(`writeStackCookie: ${ptrToString(max)}`);
13
#endif
14
#if ASSERTIONS
15
assert((max & 3) == 0);
16
#endif
17
// If the stack ends at address zero we write our cookies 4 bytes into the
18
// stack. This prevents interference with SAFE_HEAP and ASAN which also
19
// monitor writes to address zero.
20
if (max == 0) {
21
max += 4;
22
}
23
// The stack grow downwards towards _emscripten_stack_get_end.
24
// We write cookies to the final two words in the stack and detect if they are
25
// ever overwritten.
26
{{{ makeSetValue('max', 0, '0x02135467', 'u32') }}};
27
{{{ makeSetValue('max', 4, '0x89BACDFE', 'u32') }}};
28
#if CHECK_NULL_WRITES
29
// Also test the global address 0 for integrity.
30
{{{ makeSetValue(0, 0, 0x63736d65 /* 'emsc' */, 'u32') }}};
31
#endif
32
}
33
34
function checkStackCookie() {
35
#if !MINIMAL_RUNTIME
36
if (ABORT) return;
37
#endif
38
var max = _emscripten_stack_get_end();
39
#if RUNTIME_DEBUG >= 2
40
dbg(`checkStackCookie: ${ptrToString(max)}`);
41
#endif
42
// See writeStackCookie().
43
if (max == 0) {
44
max += 4;
45
}
46
var cookie1 = {{{ makeGetValue('max', 0, 'u32') }}};
47
var cookie2 = {{{ makeGetValue('max', 4, 'u32') }}};
48
if (cookie1 != 0x02135467 || cookie2 != 0x89BACDFE) {
49
abort(`Stack overflow! Stack cookie has been overwritten at ${ptrToString(max)}, expected hex dwords 0x89BACDFE and 0x2135467, but received ${ptrToString(cookie2)} ${ptrToString(cookie1)}`);
50
}
51
#if CHECK_NULL_WRITES
52
// Also test the global address 0 for integrity.
53
if ({{{ makeGetValue(0, 0, 'u32') }}} != 0x63736d65 /* 'emsc' */) {
54
abort('Runtime error: The application has corrupted its heap memory area (address zero)!');
55
}
56
#endif
57
}
58
#endif
59
60