Skip to content

Commit da616fd

Browse files
committed
refactor memory allocation in places that might happen before malloc is ready
1 parent efe2a0b commit da616fd

File tree

4 files changed

+11
-4
lines changed

4 files changed

+11
-4
lines changed

src/jsifier.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -271,7 +271,7 @@ function JSify(data, functionsOnly) {
271271
print('STATIC_BASE = ' + Runtime.GLOBAL_BASE + ';\n');
272272
print('STATICTOP = STATIC_BASE + ' + Runtime.alignMemory(Variables.nextIndexedOffset) + ';\n');
273273
} else {
274-
print('gb = parentModule["_malloc"]({{{ STATIC_BUMP }}});\n');
274+
print('gb = getMemory({{{ STATIC_BUMP }}});\n');
275275
print('// STATICTOP = STATIC_BASE + ' + Runtime.alignMemory(Variables.nextIndexedOffset) + ';\n'); // comment as metadata only
276276
}
277277
}

src/preamble.js

+7
Original file line numberDiff line numberDiff line change
@@ -433,6 +433,13 @@ function allocate(slab, types, allocator, ptr) {
433433
}
434434
Module['allocate'] = allocate;
435435

436+
// Allocate memory during any stage of startup - static memory early on, dynamic memory later, malloc when ready
437+
function getMemory(size) {
438+
if (!staticSealed) return Runtime.staticAlloc(size);
439+
if (typeof _sbrk !== 'undefined' && !_sbrk.called) return Runtime.dynamicAlloc(size);
440+
return _malloc(size);
441+
}
442+
436443
function Pointer_stringify(ptr, /* optional */ length) {
437444
if (length === 0 || !ptr) return '';
438445
// TODO: use TextDecoder

src/shell_sharedlib.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
var gb = 0;
1212
// Each module has its own stack
13-
var STACKTOP = parentModule['_malloc'](TOTAL_STACK);
13+
var STACKTOP = getMemory(TOTAL_STACK);
1414
assert(STACKTOP % 8 == 0);
1515
var STACK_MAX = STACKTOP + TOTAL_STACK;
1616
Module.cleanups.push(function() {

tools/emterpretify.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1025,13 +1025,13 @@ def post_process_code(code):
10251025

10261026
# set up emterpreter stack top (note we must use malloc if in a shared lib, or other enviroment where static memory is sealed)
10271027
js = ['''
1028-
var EMTSTACKTOP = (staticSealed ? _malloc : Runtime.staticAlloc)(%s);
1028+
var EMTSTACKTOP = getMemory(%s);
10291029
var EMT_STACK_MAX = EMTSTACKTOP + %d;
10301030
''' % (EMT_STACK_MAX, EMT_STACK_MAX)]
10311031

10321032
# write out our bytecode, and runtime relocation logic
10331033
js += ['''
1034-
var eb = (staticSealed ? _malloc : Runtime.staticAlloc)(%s);
1034+
var eb = getMemory(%s);
10351035
assert(eb %% 8 === 0);
10361036
__ATPRERUN__.push(function() {
10371037
''' % len(all_code)]

0 commit comments

Comments
 (0)