Skip to content

Commit

Permalink
fix: Crash during PThread initialization on big-endian machine
Browse files Browse the repository at this point in the history
  • Loading branch information
slavek-kucera committed Feb 19, 2025
1 parent c50c33d commit 13d97b3
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
6 changes: 3 additions & 3 deletions src/lib/libpthread.js
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ var LibraryPThread = {

threadStatusAsString(pthreadPtr) {
var profilerBlock = {{{ makeGetValue('pthreadPtr', C_STRUCTS.pthread.profilerBlock, '*') }}};
var status = (profilerBlock == 0) ? 0 : Atomics.load(HEAPU32, {{{ getHeapOffset('profilerBlock + ' + C_STRUCTS.thread_profiler_block.threadStatus, 'i32') }}});
var status = (profilerBlock == 0) ? 0 : (nativeByteOrder32(Atomics.load(HEAPU32, {{{ getHeapOffset('profilerBlock + ' + C_STRUCTS.thread_profiler_block.threadStatus, 'i32') }}})) >>> 0);
return PThread.threadStatusToString(status);
},
#endif
Expand Down Expand Up @@ -1228,13 +1228,13 @@ var LibraryPThread = {
// safe to access from sending threads that need to notify the waiting
// thread.
// TODO: How to make this work with wasm64?
var wait = Atomics.waitAsync(HEAP32, {{{ getHeapOffset('pthread_ptr', 'i32') }}}, pthread_ptr);
var wait = Atomics.waitAsync(HEAP32, {{{ getHeapOffset('pthread_ptr', 'i32') }}}, nativeByteOrder32(pthread_ptr));
#if ASSERTIONS
assert(wait.async);
#endif
wait.value.then(checkMailbox);
var waitingAsync = pthread_ptr + {{{ C_STRUCTS.pthread.waiting_async }}};
Atomics.store(HEAP32, {{{ getHeapOffset('waitingAsync', 'i32') }}}, 1);
Atomics.store(HEAP32, {{{ getHeapOffset('waitingAsync', 'i32') }}}, nativeByteOrder32(1));
}
// If `Atomics.waitAsync` is not implemented, then we will always fall back
// to postMessage and there is no need to do anything here.
Expand Down
13 changes: 13 additions & 0 deletions src/runtime_shared.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,19 @@ function updateMemoryViews() {
#endif
}

#if SUPPORT_BIG_ENDIAN
var nativeByteOrder32 = (() => {
var h16 = new Int16Array(1);
var h8 = new Int8Array(h16.buffer);
h16[0] = 42;
return h8[0] === 42 && h8[1] === 0; // little endian ordering
})()
/* little endian */ ? (v => v)
/* big endian */ : (v => ((v >> 24) & 0xff) | ((v >> 8) & 0xff00) | ((v & 0xff00) << 8) | ((v & 0xff) << 24));
#else
var nativeByteOrder32 = (v => v);
#endif

#if ENVIRONMENT_MAY_BE_NODE && MIN_NODE_VERSION < 160000
// The performance global was added to node in v16.0.0:
// https://nodejs.org/api/globals.html#performance
Expand Down

0 comments on commit 13d97b3

Please sign in to comment.