Skip to content

Commit

Permalink
Remove most usage of withStackSave. NFC
Browse files Browse the repository at this point in the history
The remaining usage is all in library_wasmfs.js where it make the code
a fair amount more readable to continue to use `withStackSave()`
See emscripten-core#21763
  • Loading branch information
sbc100 committed Apr 15, 2024
1 parent 26cceae commit 2ff2071
Show file tree
Hide file tree
Showing 13 changed files with 141 additions and 127 deletions.
10 changes: 5 additions & 5 deletions src/library_dylink.js
Original file line number Diff line number Diff line change
Expand Up @@ -340,15 +340,15 @@ var LibraryDylink = {
},
$dlSetError__internal: true,
$dlSetError__deps: ['__dl_seterr', '$stringToUTF8OnStack', '$withStackSave'],
$dlSetError__deps: ['__dl_seterr', '$stringToUTF8OnStack', '$stackSave', '$stackRestore'],
$dlSetError: (msg) => {
#if DYLINK_DEBUG
dbg(`dlSetError: ${msg}`);
#endif
withStackSave(() => {
var cmsg = stringToUTF8OnStack(msg);
___dl_seterr(cmsg, 0);
});
var sp = stackSave();
var cmsg = stringToUTF8OnStack(msg);
___dl_seterr(cmsg, 0);
stackRestore(sp);
},
// We support some amount of allocation during startup in the case of
Expand Down
8 changes: 5 additions & 3 deletions src/library_exceptions.js
Original file line number Diff line number Diff line change
Expand Up @@ -287,8 +287,9 @@ var LibraryExceptions = {

#endif
#if WASM_EXCEPTIONS || !DISABLE_EXCEPTION_CATCHING
$getExceptionMessageCommon__deps: ['__get_exception_message', 'free', '$withStackSave', '$stackAlloc'],
$getExceptionMessageCommon: (ptr) => withStackSave(() => {
$getExceptionMessageCommon__deps: ['__get_exception_message', 'free', '$stackSave', '$stackRestore', '$stackAlloc'],
$getExceptionMessageCommon: (ptr) => {
var sp = stackSave();
var type_addr_addr = stackAlloc({{{ POINTER_SIZE }}});
var message_addr_addr = stackAlloc({{{ POINTER_SIZE }}});
___get_exception_message(ptr, type_addr_addr, message_addr_addr);
Expand All @@ -301,8 +302,9 @@ var LibraryExceptions = {
message = UTF8ToString(message_addr);
_free(message_addr);
}
stackRestore(sp);
return [type, message];
}),
},
#endif
#if WASM_EXCEPTIONS
$getCppExceptionTag: () =>
Expand Down
22 changes: 12 additions & 10 deletions src/library_html5.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*/

var LibraryHTML5 = {
$JSEvents__deps: ['$withStackSave',
$JSEvents__deps: [
#if PTHREADS
'_emscripten_run_callback_on_thread',
#endif
Expand Down Expand Up @@ -2303,7 +2303,7 @@ var LibraryHTML5 = {
#if OFFSCREENCANVAS_SUPPORT
_emscripten_set_offscreencanvas_size: 'emscripten_set_canvas_element_size',

$setOffscreenCanvasSizeOnTargetThread__deps: ['$stringToNewUTF8', '_emscripten_set_offscreencanvas_size_on_thread', '$withStackSave'],
$setOffscreenCanvasSizeOnTargetThread__deps: ['$stringToNewUTF8', '_emscripten_set_offscreencanvas_size_on_thread'],
$setOffscreenCanvasSizeOnTargetThread: (targetThread, targetCanvas, width, height) => {
targetCanvas = targetCanvas ? UTF8ToString(targetCanvas) : '';
var targetCanvasPtr = 0;
Expand Down Expand Up @@ -2346,7 +2346,7 @@ var LibraryHTML5 = {
},
#endif
$setCanvasElementSize__deps: ['emscripten_set_canvas_element_size', '$withStackSave', '$stringToUTF8OnStack'],
$setCanvasElementSize__deps: ['emscripten_set_canvas_element_size', '$stackSave', '$stackRestore', '$stringToUTF8OnStack'],
$setCanvasElementSize: (target, width, height) => {
#if GL_DEBUG
dbg(`setCanvasElementSize(target=${target},width=${width},height=${height}`);
Expand All @@ -2357,10 +2357,10 @@ var LibraryHTML5 = {
} else {
// This function is being called from high-level JavaScript code instead of asm.js/Wasm,
// and it needs to synchronously proxy over to another thread, so marshal the string onto the heap to do the call.
withStackSave(() => {
var targetInt = stringToUTF8OnStack(target.id);
_emscripten_set_canvas_element_size(targetInt, width, height);
});
var sp = stackSave();
var targetInt = stringToUTF8OnStack(target.id);
_emscripten_set_canvas_element_size(targetInt, width, height);
stackRestore(sp);
}
},

Expand Down Expand Up @@ -2428,16 +2428,18 @@ var LibraryHTML5 = {
#endif

// JavaScript-friendly API, returns pair [width, height]
$getCanvasElementSize__deps: ['emscripten_get_canvas_element_size', '$withStackSave', '$stringToUTF8OnStack'],
$getCanvasElementSize: (target) => withStackSave(() => {
$getCanvasElementSize__deps: ['emscripten_get_canvas_element_size', '$stackSave', '$stackRestore', '$stringToUTF8OnStack'],
$getCanvasElementSize: (target) => {
var sp = stackSave();
var w = stackAlloc(8);
var h = w + 4;

var targetInt = stringToUTF8OnStack(target.id);
var ret = _emscripten_get_canvas_element_size(targetInt, w, h);
var size = [{{{ makeGetValue('w', 0, 'i32')}}}, {{{ makeGetValue('h', 0, 'i32')}}}];
stackRestore(sp);
return size;
}),
},

emscripten_set_element_css_size__proxy: 'sync',
emscripten_set_element_css_size__deps: ['$JSEvents', '$findEventTarget'],
Expand Down
54 changes: 28 additions & 26 deletions src/library_pthread.js
Original file line number Diff line number Diff line change
Expand Up @@ -960,7 +960,7 @@ var LibraryPThread = {
$proxyToMainThreadPtr: (...args) => BigInt(proxyToMainThread(...args)),
#endif

$proxyToMainThread__deps: ['$withStackSave', '$stackAlloc', '_emscripten_run_on_main_thread_js'].concat(i53ConversionDeps),
$proxyToMainThread__deps: ['$stackSave', '$stackRestore', '$stackAlloc', '_emscripten_run_on_main_thread_js'].concat(i53ConversionDeps),
$proxyToMainThread__docs: '/** @type{function(number, (number|boolean), ...number)} */',
$proxyToMainThread: (funcIndex, emAsmAddr, sync, ...callArgs) => {
// EM_ASM proxying is done by passing a pointer to the address of the EM_ASM
Expand All @@ -973,34 +973,36 @@ var LibraryPThread = {
// all the args here.
// We also pass 'sync' to C separately, since C needs to look at it.
// Allocate a buffer, which will be copied by the C code.
return withStackSave(() => {
// First passed parameter specifies the number of arguments to the function.
// When BigInt support is enabled, we must handle types in a more complex
// way, detecting at runtime if a value is a BigInt or not (as we have no
// type info here). To do that, add a "prefix" before each value that
// indicates if it is a BigInt, which effectively doubles the number of
// values we serialize for proxying. TODO: pack this?
var serializedNumCallArgs = callArgs.length {{{ WASM_BIGINT ? "* 2" : "" }}};
var args = stackAlloc(serializedNumCallArgs * 8);
var b = {{{ getHeapOffset('args', 'i64') }}};
for (var i = 0; i < callArgs.length; i++) {
var arg = callArgs[i];
//
// First passed parameter specifies the number of arguments to the function.
// When BigInt support is enabled, we must handle types in a more complex
// way, detecting at runtime if a value is a BigInt or not (as we have no
// type info here). To do that, add a "prefix" before each value that
// indicates if it is a BigInt, which effectively doubles the number of
// values we serialize for proxying. TODO: pack this?
var serializedNumCallArgs = callArgs.length {{{ WASM_BIGINT ? "* 2" : "" }}};
var sp = stackSave();
var args = stackAlloc(serializedNumCallArgs * 8);
var b = {{{ getHeapOffset('args', 'i64') }}};
for (var i = 0; i < callArgs.length; i++) {
var arg = callArgs[i];
#if WASM_BIGINT
if (typeof arg == 'bigint') {
// The prefix is non-zero to indicate a bigint.
HEAP64[b + 2*i] = 1n;
HEAP64[b + 2*i + 1] = arg;
} else {
// The prefix is zero to indicate a JS Number.
HEAP64[b + 2*i] = 0n;
HEAPF64[b + 2*i + 1] = arg;
}
if (typeof arg == 'bigint') {
// The prefix is non-zero to indicate a bigint.
HEAP64[b + 2*i] = 1n;
HEAP64[b + 2*i + 1] = arg;
} else {
// The prefix is zero to indicate a JS Number.
HEAP64[b + 2*i] = 0n;
HEAPF64[b + 2*i + 1] = arg;
}
#else
HEAPF64[b + i] = arg;
HEAPF64[b + i] = arg;
#endif
}
return __emscripten_run_on_main_thread_js(funcIndex, emAsmAddr, serializedNumCallArgs, args, sync);
});
}
var rtn = __emscripten_run_on_main_thread_js(funcIndex, emAsmAddr, serializedNumCallArgs, args, sync);
stackRestore(sp);
return rtn;
},
// Reuse global JS array to avoid creating JS garbage for each proxied call
Expand Down
8 changes: 5 additions & 3 deletions src/library_sdl.js
Original file line number Diff line number Diff line change
Expand Up @@ -2157,12 +2157,14 @@ var LibrarySDL = {
// We support JPG, PNG, TIF because browsers do
IMG_Init: (flags) => flags,

IMG_Load_RW__deps: ['SDL_LockSurface', 'SDL_FreeRW', '$PATH_FS', '$withStackSave', '$stringToUTF8OnStack', '$stackAlloc'],
IMG_Load_RW__deps: ['SDL_LockSurface', 'SDL_FreeRW', '$PATH_FS', '$stackSave', '$stackResotre', '$stringToUTF8OnStack', '$stackAlloc'],
IMG_Load_RW__proxy: 'sync',
IMG_Load_RW: (rwopsID, freeSrc) => {
var sp = stackSave();
try {
// stb_image integration support
var cleanup = () => {
stackRestore(sp);
if (rwops && freeSrc) _SDL_FreeRW(rwopsID);
}
var addCleanup = (func) => {
Expand All @@ -2172,7 +2174,7 @@ var LibrarySDL = {
func();
}
}
var callStbImage = (func, params) => withStackSave(() => {
var callStbImage = (func, params) => {
var x = stackAlloc({{{ getNativeTypeSize('i32') }}});
var y = stackAlloc({{{ getNativeTypeSize('i32') }}});
var comp = stackAlloc({{{ getNativeTypeSize('i32') }}});
Expand All @@ -2187,7 +2189,7 @@ var LibrarySDL = {
size: {{{ makeGetValue('x', 0, 'i32') }}} * {{{ makeGetValue('y', 0, 'i32') }}} * {{{ makeGetValue('comp', 0, 'i32') }}},
bpp: {{{ makeGetValue('comp', 0, 'i32') }}}
};
});
};

var rwops = SDL.rwops[rwopsID];
if (rwops === undefined) {
Expand Down
10 changes: 5 additions & 5 deletions src/library_sockfs.js
Original file line number Diff line number Diff line change
Expand Up @@ -727,15 +727,15 @@ addToLibrary({
* Passing a NULL callback function to a emscripten_set_socket_*_callback call
* will deregister the callback registered for that Event.
*/
$_setNetworkCallback__deps: ['$withStackSave', '$stringToUTF8OnStack'],
$_setNetworkCallback__deps: ['$stackSave', '$stackRestore', '$stringToUTF8OnStack'],
$_setNetworkCallback: (event, userData, callback) => {
function _callback(data) {
try {
if (event === 'error') {
withStackSave(function() {
var msg = stringToUTF8OnStack(data[2]);
{{{ makeDynCall('viiii', 'callback') }}}(data[0], data[1], msg, userData);
});
var sp = stackSave();
var msg = stringToUTF8OnStack(data[2]);
{{{ makeDynCall('viiii', 'callback') }}}(data[0], data[1], msg, userData);
stackRestore();
} else {
{{{ makeDynCall('vii', 'callback') }}}(data, userData);
}
Expand Down
12 changes: 8 additions & 4 deletions src/library_wasmfs.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,9 @@ FS.init();
}

// Copy the file into a JS buffer on the heap.
var buf = withStackSave(() => __wasmfs_read_file(stringToUTF8OnStack(path)));
var sp = stackSave();
var buf = __wasmfs_read_file(stringToUTF8OnStack(path));
stackRestore(sp);

// The signed integer length resides in the first 8 bytes of the buffer.
var length = {{{ makeGetValue('buf', '0', 'i53') }}};
Expand Down Expand Up @@ -519,8 +521,9 @@ FS.init();
return FS_mknod(path, mode, 0);
},

$FS_writeFile__deps: ['_wasmfs_write_file'],
$FS_writeFile: (path, data) => withStackSave(() => {
$FS_writeFile__deps: ['_wasmfs_write_file', '$stackSave', '$stackRestore'],
$FS_writeFile: (path, data) => {
var sp = stackSave();
var pathBuffer = stringToUTF8OnStack(path);
if (typeof data == 'string') {
var buf = new Uint8Array(lengthBytesUTF8(data) + 1);
Expand All @@ -536,8 +539,9 @@ FS.init();
}
var ret = __wasmfs_write_file(pathBuffer, dataBuffer, data.length);
_free(dataBuffer);
stackRestore(sp);
return ret;
}),
},

$FS_mkdir__deps: ['_wasmfs_mkdir'],
$FS_mkdir: (path, mode = 511 /* 0777 */) => FS.handleError(withStackSave(() => {
Expand Down
33 changes: 17 additions & 16 deletions src/library_wasmfs_node.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ addToLibrary({
_wasmfs_node_readdir__docs: '/** @suppress {checkTypes} */',
_wasmfs_node_readdir__deps: [
'$wasmfsNodeConvertNodeCode',
'$withStackSave',
'$stackSave',
'$stackRestore',
'$stringToUTF8OnStack',
'_wasmfs_node_record_dirent',
],
Expand All @@ -69,21 +70,21 @@ addToLibrary({
return wasmfsNodeConvertNodeCode(e);
}
entries.forEach((entry) => {
withStackSave(() => {
let name = stringToUTF8OnStack(entry.name);
let type;
// TODO: Figure out how to use `cDefine` here.
if (entry.isFile()) {
type = 1;
} else if (entry.isDirectory()) {
type = 2;
} else if (entry.isSymbolicLink()) {
type = 3;
} else {
type = 0;
}
__wasmfs_node_record_dirent(vec, name, type);
});
let sp = stackSave();
let name = stringToUTF8OnStack(entry.name);
let type;
// TODO: Figure out how to use `cDefine` here.
if (entry.isFile()) {
type = 1;
} else if (entry.isDirectory()) {
type = 2;
} else if (entry.isSymbolicLink()) {
type = 3;
} else {
type = 0;
}
__wasmfs_node_record_dirent(vec, name, type);
stackRestore(sp);
});
// implicitly return 0
},
Expand Down
15 changes: 8 additions & 7 deletions src/library_wasmfs_opfs.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,8 @@ addToLibrary({

_wasmfs_opfs_get_entries__deps: [
'$wasmfsOPFSProxyFinish',
'$withStackSave',
'$stackSave',
'$stackRestore',
'_wasmfs_opfs_record_entry',
],
_wasmfs_opfs_get_entries: async function(ctx, dirID, entriesPtr, errPtr) {
Expand All @@ -162,13 +163,13 @@ addToLibrary({
let iter = dirHandle.entries();
for (let entry; entry = await iter.next(), !entry.done;) {
let [name, child] = entry.value;
withStackSave(() => {
let namePtr = stringToUTF8OnStack(name);
let type = child.kind == "file" ?
{{{ cDefine('File::DataFileKind') }}} :
{{{ cDefine('File::DirectoryKind') }}};
let sp = stackSave();
let namePtr = stringToUTF8OnStack(name);
let type = child.kind == "file" ?
{{{ cDefine('File::DataFileKind') }}} :
{{{ cDefine('File::DirectoryKind') }}};
__wasmfs_opfs_record_entry(entriesPtr, namePtr, type)
});
stackRestore(sp);
}
} catch {
let err = -{{{ cDefs.EIO }}};
Expand Down

0 comments on commit 2ff2071

Please sign in to comment.