pthread-main.js 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. // Pthread Web Worker startup routine:
  2. // This is the entry point file that is loaded first by each Web Worker
  3. // that executes pthreads on the Emscripten application.
  4. // Thread-local:
  5. var threadInfoStruct = 0; // Info area for this thread in Emscripten HEAP (shared). If zero, this worker is not currently hosting an executing pthread.
  6. var selfThreadId = 0; // The ID of this thread. 0 if not hosting a pthread.
  7. var parentThreadId = 0; // The ID of the parent pthread that launched this thread.
  8. var tempDoublePtr = 0; // A temporary memory area for global float and double marshalling operations.
  9. // Thread-local: Each thread has its own allocated stack space.
  10. var STACK_BASE = 0;
  11. var STACKTOP = 0;
  12. var STACK_MAX = 0;
  13. // These are system-wide memory area parameters that are set at main runtime startup in main thread, and stay constant throughout the application.
  14. var buffer; // All pthreads share the same Emscripten HEAP as SharedArrayBuffer with the main execution thread.
  15. var DYNAMICTOP_PTR = 0;
  16. var TOTAL_MEMORY = 0;
  17. var STATICTOP = 0;
  18. var staticSealed = true; // When threads are being initialized, the static memory area has been already sealed a long time ago.
  19. var DYNAMIC_BASE = 0;
  20. var ENVIRONMENT_IS_PTHREAD = true;
  21. // Cannot use console.log or console.error in a web worker, since that would risk a browser deadlock! https://bugzilla.mozilla.org/show_bug.cgi?id=1049091
  22. // Therefore implement custom logging facility for threads running in a worker, which queue the messages to main thread to print.
  23. var Module = {};
  24. function threadPrint() {
  25. var text = Array.prototype.slice.call(arguments).join(' ');
  26. console.log(text);
  27. }
  28. function threadPrintErr() {
  29. var text = Array.prototype.slice.call(arguments).join(' ');
  30. console.error(text);
  31. }
  32. function threadAlert() {
  33. var text = Array.prototype.slice.call(arguments).join(' ');
  34. postMessage({cmd: 'alert', text: text, threadId: selfThreadId});
  35. }
  36. Module['print'] = threadPrint;
  37. Module['printErr'] = threadPrintErr;
  38. this.alert = threadAlert;
  39. this.onmessage = function(e) {
  40. if (e.data.cmd === 'load') { // Preload command that is called once per worker to parse and load the Emscripten code.
  41. // Initialize the thread-local field(s):
  42. tempDoublePtr = e.data.tempDoublePtr;
  43. // Initialize the global "process"-wide fields:
  44. buffer = e.data.buffer;
  45. Module['TOTAL_MEMORY'] = TOTAL_MEMORY = e.data.TOTAL_MEMORY;
  46. STATICTOP = e.data.STATICTOP;
  47. DYNAMIC_BASE = e.data.DYNAMIC_BASE;
  48. DYNAMICTOP_PTR = e.data.DYNAMICTOP_PTR;
  49. PthreadWorkerInit = e.data.PthreadWorkerInit;
  50. importScripts(e.data.url);
  51. if (typeof FS !== 'undefined') FS.createStandardStreams();
  52. postMessage({ cmd: 'loaded' });
  53. } else if (e.data.cmd === 'objectTransfer') {
  54. PThread.receiveObjectTransfer(e.data);
  55. } else if (e.data.cmd === 'run') { // This worker was idle, and now should start executing its pthread entry point.
  56. threadInfoStruct = e.data.threadInfoStruct;
  57. __register_pthread_ptr(threadInfoStruct, /*isMainBrowserThread=*/0, /*isMainRuntimeThread=*/0); // Pass the thread address inside the asm.js scope to store it for fast access that avoids the need for a FFI out.
  58. assert(threadInfoStruct);
  59. selfThreadId = e.data.selfThreadId;
  60. parentThreadId = e.data.parentThreadId;
  61. assert(selfThreadId);
  62. assert(parentThreadId);
  63. // TODO: Emscripten runtime has these variables twice(!), once outside the asm.js module, and a second time inside the asm.js module.
  64. // Review why that is? Can those get out of sync?
  65. STACK_BASE = STACKTOP = e.data.stackBase;
  66. STACK_MAX = STACK_BASE + e.data.stackSize;
  67. assert(STACK_BASE != 0);
  68. assert(STACK_MAX > STACK_BASE);
  69. Runtime.establishStackSpace(e.data.stackBase, e.data.stackBase + e.data.stackSize);
  70. var result = 0;
  71. PThread.receiveObjectTransfer(e.data);
  72. PThread.setThreadStatus(_pthread_self(), 1/*EM_THREAD_STATUS_RUNNING*/);
  73. try {
  74. // HACK: Some code in the wild has instead signatures of form 'void *ThreadMain()', which seems to be ok in native code.
  75. // To emulate supporting both in test suites, use the following form. This is brittle!
  76. if (typeof asm['dynCall_ii'] !== 'undefined') {
  77. result = asm.dynCall_ii(e.data.start_routine, e.data.arg); // pthread entry points are always of signature 'void *ThreadMain(void *arg)'
  78. } else {
  79. result = asm.dynCall_i(e.data.start_routine); // as a hack, try signature 'i' as fallback.
  80. }
  81. } catch(e) {
  82. if (e === 'Canceled!') {
  83. PThread.threadCancel();
  84. return;
  85. } else {
  86. Atomics.store(HEAPU32, (threadInfoStruct + 4 /*{{{ C_STRUCTS.pthread.threadExitCode }}}*/ ) >> 2, -2 /*A custom entry specific to Emscripten denoting that the thread crashed.*/);
  87. Atomics.store(HEAPU32, (threadInfoStruct + 0 /*{{{ C_STRUCTS.pthread.threadStatus }}}*/ ) >> 2, 1); // Mark the thread as no longer running.
  88. _emscripten_futex_wake(threadInfoStruct + 0 /*{{{ C_STRUCTS.pthread.threadStatus }}}*/, 0x7FFFFFFF/*INT_MAX*/); // wake all threads
  89. throw e;
  90. }
  91. }
  92. // The thread might have finished without calling pthread_exit(). If so, then perform the exit operation ourselves.
  93. // (This is a no-op if explicit pthread_exit() had been called prior.)
  94. if (!Module['noExitRuntime']) PThread.threadExit(result);
  95. else console.log('pthread noExitRuntime: not quitting.');
  96. } else if (e.data.cmd === 'cancel') { // Main thread is asking for a pthread_cancel() on this thread.
  97. if (threadInfoStruct && PThread.thisThreadCancelState == 0/*PTHREAD_CANCEL_ENABLE*/) {
  98. PThread.threadCancel();
  99. }
  100. } else {
  101. Module['printErr']('pthread-main.js received unknown command ' + e.data.cmd);
  102. }
  103. }