@php-wasm/node 1.1.2 → 1.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/asyncify/7_2_34/php_7_2.wasm +0 -0
  2. package/asyncify/7_3_33/php_7_3.wasm +0 -0
  3. package/asyncify/7_4_33/php_7_4.wasm +0 -0
  4. package/asyncify/8_0_30/php_8_0.wasm +0 -0
  5. package/asyncify/8_1_23/php_8_1.wasm +0 -0
  6. package/asyncify/8_2_10/php_8_2.wasm +0 -0
  7. package/asyncify/8_3_0/php_8_3.wasm +0 -0
  8. package/asyncify/8_4_0/php_8_4.wasm +0 -0
  9. package/asyncify/php_7_2.js +351 -157
  10. package/asyncify/php_7_3.js +350 -156
  11. package/asyncify/php_7_4.js +349 -155
  12. package/asyncify/php_8_0.js +353 -159
  13. package/asyncify/php_8_1.js +352 -158
  14. package/asyncify/php_8_2.js +353 -159
  15. package/asyncify/php_8_3.js +353 -159
  16. package/asyncify/php_8_4.js +352 -158
  17. package/fs_ext.node +0 -0
  18. package/index.cjs +9896 -2782
  19. package/index.js +9780 -2782
  20. package/jspi/7_2_34/php_7_2.wasm +0 -0
  21. package/jspi/7_3_33/php_7_3.wasm +0 -0
  22. package/jspi/7_4_33/php_7_4.wasm +0 -0
  23. package/jspi/8_0_30/php_8_0.wasm +0 -0
  24. package/jspi/8_1_23/php_8_1.wasm +0 -0
  25. package/jspi/8_2_10/php_8_2.wasm +0 -0
  26. package/jspi/8_3_0/php_8_3.wasm +0 -0
  27. package/jspi/8_4_0/php_8_4.wasm +0 -0
  28. package/jspi/php_7_2.js +1130 -340
  29. package/jspi/php_7_3.js +1130 -340
  30. package/jspi/php_7_4.js +1130 -340
  31. package/jspi/php_8_0.js +1130 -340
  32. package/jspi/php_8_1.js +1129 -339
  33. package/jspi/php_8_2.js +1129 -339
  34. package/jspi/php_8_3.js +1129 -339
  35. package/jspi/php_8_4.js +1129 -339
  36. package/lib/file-lock-manager-for-node.d.ts +149 -0
  37. package/lib/file-lock-manager.d.ts +96 -0
  38. package/lib/index.d.ts +2 -0
  39. package/lib/load-runtime.d.ts +31 -2
  40. package/package.json +10 -9
package/jspi/php_8_0.js CHANGED
@@ -8,7 +8,7 @@ import path from 'path';
8
8
 
9
9
  const dependencyFilename = path.join(__dirname, '8_0_30', 'php_8_0.wasm');
10
10
  export { dependencyFilename };
11
- export const dependenciesTotalSize = 17167385;
11
+ export const dependenciesTotalSize = 17169869;
12
12
  export function init(RuntimeName, PHPLoader) {
13
13
  // The rest of the code comes from the built php.js file and esm-suffix.js
14
14
  // include: shell.js
@@ -5227,7 +5227,360 @@ export function init(RuntimeName, PHPLoader) {
5227
5227
 
5228
5228
  var syscallGetVarargP = syscallGetVarargI;
5229
5229
 
5230
- function ___syscall_fcntl64(fd, cmd, varargs) {
5230
+ var stringToUTF8 = (str, outPtr, maxBytesToWrite) =>
5231
+ stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite);
5232
+
5233
+ Module['stringToUTF8'] = stringToUTF8;
5234
+
5235
+ var stackAlloc = (sz) => __emscripten_stack_alloc(sz);
5236
+
5237
+ /** @suppress {duplicate } */ var stringToUTF8OnStack = (str) => {
5238
+ var size = lengthBytesUTF8(str) + 1;
5239
+ var ret = stackAlloc(size);
5240
+ stringToUTF8(str, ret, size);
5241
+ return ret;
5242
+ };
5243
+
5244
+ var allocateUTF8OnStack = stringToUTF8OnStack;
5245
+
5246
+ var PHPWASM = {
5247
+ init: function () {
5248
+ // The /internal directory is required by the C module. It's where the
5249
+ // stdout, stderr, and headers information are written for the JavaScript
5250
+ // code to read later on.
5251
+ FS.mkdir('/internal');
5252
+ // The files from the shared directory are shared between all the
5253
+ // PHP processes managed by PHPProcessManager.
5254
+ FS.mkdir('/internal/shared');
5255
+ // The files from the preload directory are preloaded using the
5256
+ // auto_prepend_file php.ini directive.
5257
+ FS.mkdir('/internal/shared/preload');
5258
+ // Create stdout and stderr devices. We can't just use Emscripten's
5259
+ // default stdout and stderr devices because they stop processing data
5260
+ // on the first null byte. However, when dealing with binary data,
5261
+ // null bytes are valid and common.
5262
+ FS.registerDevice(FS.makedev(64, 0), {
5263
+ open: () => {},
5264
+ close: () => {},
5265
+ read: () => 0,
5266
+ write: (stream, buffer, offset, length, pos) => {
5267
+ const chunk = buffer.subarray(offset, offset + length);
5268
+ PHPWASM.onStdout(chunk);
5269
+ return length;
5270
+ },
5271
+ });
5272
+ FS.mkdev('/internal/stdout', FS.makedev(64, 0));
5273
+ FS.registerDevice(FS.makedev(63, 0), {
5274
+ open: () => {},
5275
+ close: () => {},
5276
+ read: () => 0,
5277
+ write: (stream, buffer, offset, length, pos) => {
5278
+ const chunk = buffer.subarray(offset, offset + length);
5279
+ PHPWASM.onStderr(chunk);
5280
+ return length;
5281
+ },
5282
+ });
5283
+ FS.mkdev('/internal/stderr', FS.makedev(63, 0));
5284
+ FS.registerDevice(FS.makedev(62, 0), {
5285
+ open: () => {},
5286
+ close: () => {},
5287
+ read: () => 0,
5288
+ write: (stream, buffer, offset, length, pos) => {
5289
+ const chunk = buffer.subarray(offset, offset + length);
5290
+ PHPWASM.onHeaders(chunk);
5291
+ return length;
5292
+ },
5293
+ });
5294
+ FS.mkdev('/internal/headers', FS.makedev(62, 0));
5295
+ // Handle events.
5296
+ PHPWASM.EventEmitter = ENVIRONMENT_IS_NODE
5297
+ ? require('events').EventEmitter
5298
+ : class EventEmitter {
5299
+ constructor() {
5300
+ this.listeners = {};
5301
+ }
5302
+ emit(eventName, data) {
5303
+ if (this.listeners[eventName]) {
5304
+ this.listeners[eventName].forEach(
5305
+ (callback) => {
5306
+ callback(data);
5307
+ }
5308
+ );
5309
+ }
5310
+ }
5311
+ once(eventName, callback) {
5312
+ const self = this;
5313
+ function removedCallback() {
5314
+ callback(...arguments);
5315
+ self.removeListener(eventName, removedCallback);
5316
+ }
5317
+ this.on(eventName, removedCallback);
5318
+ }
5319
+ removeAllListeners(eventName) {
5320
+ if (eventName) {
5321
+ delete this.listeners[eventName];
5322
+ } else {
5323
+ this.listeners = {};
5324
+ }
5325
+ }
5326
+ removeListener(eventName, callback) {
5327
+ if (this.listeners[eventName]) {
5328
+ const idx =
5329
+ this.listeners[eventName].indexOf(callback);
5330
+ if (idx !== -1) {
5331
+ this.listeners[eventName].splice(idx, 1);
5332
+ }
5333
+ }
5334
+ }
5335
+ };
5336
+ // Clean up the fd -> childProcess mapping when the fd is closed:
5337
+ const originalClose = FS.close;
5338
+ FS.close = function (stream) {
5339
+ originalClose(stream);
5340
+ delete PHPWASM.child_proc_by_fd[stream.fd];
5341
+ };
5342
+ PHPWASM.child_proc_by_fd = {};
5343
+ PHPWASM.child_proc_by_pid = {};
5344
+ PHPWASM.input_devices = {};
5345
+ const originalWrite = TTY.stream_ops.write;
5346
+ TTY.stream_ops.write = function (stream, ...rest) {
5347
+ const retval = originalWrite(stream, ...rest);
5348
+ // Implicit flush since PHP's fflush() doesn't seem to trigger the fsync event
5349
+ // @TODO: Fix this at the wasm level
5350
+ stream.tty.ops.fsync(stream.tty);
5351
+ return retval;
5352
+ };
5353
+ const originalPutChar = TTY.stream_ops.put_char;
5354
+ TTY.stream_ops.put_char = function (tty, val) {
5355
+ /**
5356
+ * Buffer newlines that Emscripten normally ignores.
5357
+ *
5358
+ * Emscripten doesn't do it by default because its default
5359
+ * print function is console.log that implicitly adds a newline. We are overwriting
5360
+ * it with an environment-specific function that outputs exaclty what it was given,
5361
+ * e.g. in Node.js it's process.stdout.write(). Therefore, we need to mak sure
5362
+ * all the newlines make it to the output buffer.
5363
+ */ if (val === 10) tty.output.push(val);
5364
+ return originalPutChar(tty, val);
5365
+ };
5366
+ },
5367
+ onHeaders: function (chunk) {
5368
+ if (Module['onHeaders']) {
5369
+ Module['onHeaders'](chunk);
5370
+ return;
5371
+ }
5372
+ console.log('headers', {
5373
+ chunk,
5374
+ });
5375
+ },
5376
+ onStdout: function (chunk) {
5377
+ if (Module['onStdout']) {
5378
+ Module['onStdout'](chunk);
5379
+ return;
5380
+ }
5381
+ if (ENVIRONMENT_IS_NODE) {
5382
+ process.stdout.write(chunk);
5383
+ } else {
5384
+ console.log('stdout', {
5385
+ chunk,
5386
+ });
5387
+ }
5388
+ },
5389
+ onStderr: function (chunk) {
5390
+ if (Module['onStderr']) {
5391
+ Module['onStderr'](chunk);
5392
+ return;
5393
+ }
5394
+ if (ENVIRONMENT_IS_NODE) {
5395
+ process.stderr.write(chunk);
5396
+ } else {
5397
+ console.warn('stderr', {
5398
+ chunk,
5399
+ });
5400
+ }
5401
+ },
5402
+ getAllWebSockets: function (sock) {
5403
+ const webSockets = new Set();
5404
+ if (sock.server) {
5405
+ sock.server.clients.forEach((ws) => {
5406
+ webSockets.add(ws);
5407
+ });
5408
+ }
5409
+ for (const peer of PHPWASM.getAllPeers(sock)) {
5410
+ webSockets.add(peer.socket);
5411
+ }
5412
+ return Array.from(webSockets);
5413
+ },
5414
+ getAllPeers: function (sock) {
5415
+ const peers = new Set();
5416
+ if (sock.server) {
5417
+ sock.pending
5418
+ .filter((pending) => pending.peers)
5419
+ .forEach((pending) => {
5420
+ for (const peer of Object.values(pending.peers)) {
5421
+ peers.add(peer);
5422
+ }
5423
+ });
5424
+ }
5425
+ if (sock.peers) {
5426
+ for (const peer of Object.values(sock.peers)) {
5427
+ peers.add(peer);
5428
+ }
5429
+ }
5430
+ return Array.from(peers);
5431
+ },
5432
+ awaitData: function (ws) {
5433
+ return PHPWASM.awaitEvent(ws, 'message');
5434
+ },
5435
+ awaitConnection: function (ws) {
5436
+ if (ws.OPEN === ws.readyState) {
5437
+ return [Promise.resolve(), PHPWASM.noop];
5438
+ }
5439
+ return PHPWASM.awaitEvent(ws, 'open');
5440
+ },
5441
+ awaitClose: function (ws) {
5442
+ if ([ws.CLOSING, ws.CLOSED].includes(ws.readyState)) {
5443
+ return [Promise.resolve(), PHPWASM.noop];
5444
+ }
5445
+ return PHPWASM.awaitEvent(ws, 'close');
5446
+ },
5447
+ awaitError: function (ws) {
5448
+ if ([ws.CLOSING, ws.CLOSED].includes(ws.readyState)) {
5449
+ return [Promise.resolve(), PHPWASM.noop];
5450
+ }
5451
+ return PHPWASM.awaitEvent(ws, 'error');
5452
+ },
5453
+ awaitEvent: function (ws, event) {
5454
+ let resolve;
5455
+ const listener = () => {
5456
+ resolve();
5457
+ };
5458
+ const promise = new Promise(function (_resolve) {
5459
+ resolve = _resolve;
5460
+ ws.once(event, listener);
5461
+ });
5462
+ const cancel = () => {
5463
+ ws.removeListener(event, listener);
5464
+ // Rejecting the promises bubbles up and kills the entire
5465
+ // node process. Let's resolve them on the next tick instead
5466
+ // to give the caller some space to unbind any handlers.
5467
+ setTimeout(resolve);
5468
+ };
5469
+ return [promise, cancel];
5470
+ },
5471
+ noop: function () {},
5472
+ spawnProcess: function (command, args, options) {
5473
+ if (Module['spawnProcess']) {
5474
+ const spawnedPromise = Module['spawnProcess'](
5475
+ command,
5476
+ args,
5477
+ options
5478
+ );
5479
+ return Promise.resolve(spawnedPromise).then(function (spawned) {
5480
+ if (!spawned || !spawned.on) {
5481
+ throw new Error(
5482
+ 'spawnProcess() must return an EventEmitter but returned a different type.'
5483
+ );
5484
+ }
5485
+ return spawned;
5486
+ });
5487
+ }
5488
+ if (ENVIRONMENT_IS_NODE) {
5489
+ return require('child_process').spawn(command, args, {
5490
+ ...options,
5491
+ shell: true,
5492
+ stdio: ['pipe', 'pipe', 'pipe'],
5493
+ timeout: 100,
5494
+ });
5495
+ }
5496
+ const e = new Error(
5497
+ 'popen(), proc_open() etc. are unsupported in the browser. Call php.setSpawnHandler() ' +
5498
+ 'and provide a callback to handle spawning processes, or disable a popen(), proc_open() ' +
5499
+ 'and similar functions via php.ini.'
5500
+ );
5501
+ e.code = 'SPAWN_UNSUPPORTED';
5502
+ throw e;
5503
+ },
5504
+ shutdownSocket: function (socketd, how) {
5505
+ // This implementation only supports websockets at the moment
5506
+ const sock = getSocketFromFD(socketd);
5507
+ const peer = Object.values(sock.peers)[0];
5508
+ if (!peer) {
5509
+ return -1;
5510
+ }
5511
+ try {
5512
+ peer.socket.close();
5513
+ SOCKFS.websocket_sock_ops.removePeer(sock, peer);
5514
+ return 0;
5515
+ } catch (e) {
5516
+ console.log('Socket shutdown error', e);
5517
+ return -1;
5518
+ }
5519
+ },
5520
+ };
5521
+
5522
+ function _js_getpid() {
5523
+ return PHPLoader.processId ?? 42;
5524
+ }
5525
+
5526
+ function _js_wasm_trace(format, ...args) {
5527
+ if (PHPLoader.trace instanceof Function) {
5528
+ PHPLoader.trace(_js_getpid(), format, ...args);
5529
+ }
5530
+ }
5531
+
5532
+ function _fd_close(fd) {
5533
+ _js_wasm_trace('fd_close(%d)', fd);
5534
+ const [vfsPath, pathResolutionErrno] = locking.get_vfs_path_from_fd(fd);
5535
+ if (pathResolutionErrno !== 0) {
5536
+ _js_wasm_trace(
5537
+ 'fd_close(%d) get_vfs_path_from_fd error %d',
5538
+ fd,
5539
+ pathResolutionErrno
5540
+ );
5541
+ return -ERRNO_CODES.EBADF;
5542
+ }
5543
+ const result = _builtin_fd_close(fd);
5544
+ if (result === 0 && locking.maybeLockedFds.has(fd)) {
5545
+ const nativeFilePath =
5546
+ locking.get_native_path_from_vfs_path(vfsPath);
5547
+ return PHPLoader.fileLockManager
5548
+ .releaseLocksForProcessFd(
5549
+ PHPLoader.processId,
5550
+ fd,
5551
+ nativeFilePath
5552
+ )
5553
+ .then(() => {
5554
+ _js_wasm_trace('fd_close(%d) release locks success', fd);
5555
+ })
5556
+ .catch((e) => {
5557
+ _js_wasm_trace("fd_close(%d) error '%s'", fd, e);
5558
+ })
5559
+ .then(() => {
5560
+ _js_wasm_trace('fd_close(%d) result %d', fd, result);
5561
+ return result;
5562
+ })
5563
+ .finally(() => {
5564
+ locking.maybeLockedFds.delete(fd);
5565
+ });
5566
+ } else {
5567
+ _js_wasm_trace('fd_close(%d) result %d', fd, result);
5568
+ return result;
5569
+ }
5570
+ }
5571
+
5572
+ function _builtin_fd_close(fd) {
5573
+ try {
5574
+ var stream = SYSCALLS.getStreamFromFD(fd);
5575
+ FS.close(stream);
5576
+ return 0;
5577
+ } catch (e) {
5578
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
5579
+ return e.errno;
5580
+ }
5581
+ }
5582
+
5583
+ function _builtin_fcntl64(fd, cmd, varargs) {
5231
5584
  SYSCALLS.varargs = varargs;
5232
5585
  try {
5233
5586
  var stream = SYSCALLS.getStreamFromFD(fd);
@@ -5282,6 +5635,439 @@ export function init(RuntimeName, PHPLoader) {
5282
5635
  }
5283
5636
  }
5284
5637
 
5638
+ var locking = {
5639
+ maybeLockedFds: new Set(),
5640
+ F_RDLCK: 0,
5641
+ F_WRLCK: 1,
5642
+ F_UNLCK: 2,
5643
+ lockStateToFcntl: {
5644
+ shared: 0,
5645
+ exclusive: 1,
5646
+ unlocked: 2,
5647
+ },
5648
+ fcntlToLockState: {
5649
+ 0: 'shared',
5650
+ 1: 'exclusive',
5651
+ 2: 'unlocked',
5652
+ },
5653
+ is_shared_fs_node(node) {
5654
+ if (node?.isSharedFS) {
5655
+ return true;
5656
+ }
5657
+ // Handle PROXYFS nodes which wrap other nodes.
5658
+ if (!node?.mount?.opts?.fs?.lookupPath) {
5659
+ return false;
5660
+ }
5661
+ const vfsPath = NODEFS.realPath(node);
5662
+ const underlyingNode = node.mount.opts.fs.lookupPath(vfsPath)?.node;
5663
+ return !!underlyingNode?.isSharedFS;
5664
+ },
5665
+ is_path_to_shared_fs(path) {
5666
+ const { node } = FS.lookupPath(path);
5667
+ return locking.is_shared_fs_node(node);
5668
+ },
5669
+ get_fd_access_mode(fd) {
5670
+ const emscripten_F_GETFL = Number('3');
5671
+ const emscripten_O_ACCMODE = Number('2097155');
5672
+ return (
5673
+ _builtin_fcntl64(fd, emscripten_F_GETFL) & emscripten_O_ACCMODE
5674
+ );
5675
+ },
5676
+ get_vfs_path_from_fd(fd) {
5677
+ try {
5678
+ return [FS.readlink(`/proc/self/fd/${fd}`), 0];
5679
+ } catch (error) {
5680
+ return [null, ERRNO_CODES.EBADF];
5681
+ }
5682
+ },
5683
+ get_native_path_from_vfs_path(vfsPath) {
5684
+ const { node } = FS.lookupPath(vfsPath);
5685
+ return NODEFS.realPath(node);
5686
+ },
5687
+ check_lock_params(fd, l_type) {
5688
+ const emscripten_O_RDONLY = Number('0');
5689
+ const emscripten_O_WRONLY = Number('1');
5690
+ const accessMode = locking.get_fd_access_mode(fd);
5691
+ if (
5692
+ (l_type === locking.F_WRLCK &&
5693
+ accessMode === emscripten_O_RDONLY) ||
5694
+ (l_type === locking.F_RDLCK &&
5695
+ accessMode === emscripten_O_WRONLY)
5696
+ ) {
5697
+ return ERRNO_CODES.EBADF;
5698
+ }
5699
+ return 0;
5700
+ },
5701
+ };
5702
+
5703
+ async function ___syscall_fcntl64(fd, cmd, varargs) {
5704
+ // Necessary to use varargs accessor
5705
+ SYSCALLS.varargs = varargs;
5706
+ // These constants are replaced by Emscripten during the build process
5707
+ const emscripten_F_GETLK = Number('12');
5708
+ const emscripten_F_SETLK = Number('13');
5709
+ const emscripten_F_SETLKW = Number('14');
5710
+ const emscripten_SEEK_SET = Number('0');
5711
+ // NOTE: With the exception of l_type, these offsets are not exposed to
5712
+ // JS by Emscripten, so we hardcode them here.
5713
+ const emscripten_flock_l_type_offset = 0;
5714
+ const emscripten_flock_l_whence_offset = 2;
5715
+ const emscripten_flock_l_start_offset = 8;
5716
+ const emscripten_flock_l_len_offset = 16;
5717
+ const emscripten_flock_l_pid_offset = 24;
5718
+ /**
5719
+ * Read the flock struct at the given address.
5720
+ *
5721
+ * @param {bigint} flockStructAddress - the address of the flock struct
5722
+ * @returns the flock struct
5723
+ */ function read_flock_struct(flockStructAddress) {
5724
+ /*
5725
+ * NOTE: Since we are using HEAP<WORD_SIZE> vars like HEAP16 and HEAP64,
5726
+ * we need to adjust offsets to address the word size of each HEAP.
5727
+ *
5728
+ * For example, an offset of 64 bytes is the following for each HEAP:
5729
+ * - HEAP8: 64 (the 64th byte)
5730
+ * - HEAP16: 32 (the 32nd 16-bit word)
5731
+ * - HEAP32: 16 (the 16th 32-bit word)
5732
+ * - HEAP64: 8 (the 8th 64-bit word)
5733
+ *
5734
+ * We get a word offset by dividing the byte offset by the word size.
5735
+ */ return {
5736
+ l_type: HEAP16[ // Shift right by 1 to divide by 2^1.
5737
+ (flockStructAddress + emscripten_flock_l_type_offset) >> 1
5738
+ ],
5739
+ l_whence:
5740
+ HEAP16[ // Shift right by 1 to divide by 2^1.
5741
+ (flockStructAddress +
5742
+ emscripten_flock_l_whence_offset) >>
5743
+ 1
5744
+ ],
5745
+ l_start:
5746
+ HEAP64[ // Shift right by 3 to divide by 2^3.
5747
+ (flockStructAddress +
5748
+ emscripten_flock_l_start_offset) >>
5749
+ 3
5750
+ ],
5751
+ l_len: HEAP64[ // Shift right by 3 to divide by 2^3.
5752
+ (flockStructAddress + emscripten_flock_l_len_offset) >> 3
5753
+ ],
5754
+ l_pid: HEAP32[ // Shift right by 2 to divide by 2^2.
5755
+ (flockStructAddress + emscripten_flock_l_pid_offset) >> 2
5756
+ ],
5757
+ };
5758
+ }
5759
+ /**
5760
+ * Update the flock struct at the given address with the given fields.
5761
+ *
5762
+ * @param {bigint} flockStructAddress - the address of the flock struct
5763
+ * @param {object} fields - the fields to update
5764
+ */ function update_flock_struct(flockStructAddress, fields) {
5765
+ /*
5766
+ * NOTE: Since we are using HEAP<WORD_SIZE> vars like HEAP16 and HEAP64,
5767
+ * we need to adjust offsets to address the word size of each HEAP.
5768
+ *
5769
+ * For example, an offset of 64 bytes is the following for each HEAP:
5770
+ * - HEAP8: 64 (the 64th byte)
5771
+ * - HEAP16: 32 (the 32nd 16-bit word)
5772
+ * - HEAP32: 16 (the 16th 32-bit word)
5773
+ * - HEAP64: 8 (the 8th 64-bit word)
5774
+ *
5775
+ * We get a word offset by dividing the byte offset by the word size.
5776
+ */ if (fields.l_type !== undefined) {
5777
+ HEAP16[ // Shift right by 1 to divide by 2^1.
5778
+ (flockStructAddress + emscripten_flock_l_type_offset) >> 1
5779
+ ] = fields.l_type;
5780
+ }
5781
+ if (fields.l_whence !== undefined) {
5782
+ HEAP16[ // Shift right by 1 to divide by 2^1.
5783
+ (flockStructAddress + emscripten_flock_l_whence_offset) >> 1
5784
+ ] = fields.l_whence;
5785
+ }
5786
+ if (fields.l_start !== undefined) {
5787
+ HEAP64[ // Shift right by 3 to divide by 2^3.
5788
+ (flockStructAddress + emscripten_flock_l_start_offset) >> 3
5789
+ ] = fields.l_start;
5790
+ }
5791
+ if (fields.l_len !== undefined) {
5792
+ HEAP64[ // Shift right by 3 to divide by 2^3.
5793
+ (flockStructAddress + emscripten_flock_l_len_offset) >> 3
5794
+ ] = fields.l_len;
5795
+ }
5796
+ if (fields.l_pid !== undefined) {
5797
+ HEAP32[ // Shift right by 2 to divide by 2^2.
5798
+ (flockStructAddress + emscripten_flock_l_pid_offset) >> 2
5799
+ ] = fields.l_pid;
5800
+ }
5801
+ }
5802
+ /**
5803
+ * Resolve the base address of the range depending on the whence and start offset.
5804
+ *
5805
+ * @param {number} fd - the file descriptor
5806
+ * @param {number} whence - what the start offset is relative to
5807
+ * @param {bigint} startOffset - the offset from the whence
5808
+ * @returns The resolved offset and the errno. If there is an error,
5809
+ * the resolved offset is null, and the errno is non-zero.
5810
+ */ function get_base_address(fd, whence, startOffset) {
5811
+ let baseAddress;
5812
+ switch (whence) {
5813
+ case emscripten_SEEK_SET:
5814
+ baseAddress = 0n;
5815
+ break;
5816
+
5817
+ case emscripten_SEEK_CUR:
5818
+ baseAddress = FS.lseek(fd, 0, whence);
5819
+ break;
5820
+
5821
+ case emscripten_SEEK_END:
5822
+ baseAddress = _wasm_get_end_offset(fd);
5823
+ break;
5824
+
5825
+ default:
5826
+ return [null, ERRNO_CODES.EINVAL];
5827
+ }
5828
+ if (baseAddress == -1) {
5829
+ // We cannot resolve the offset within the file.
5830
+ // Let's treat this as a problem with the file descriptor.
5831
+ return [null, ERRNO_CODES.EBADF];
5832
+ }
5833
+ const resolvedOffset = baseAddress + startOffset;
5834
+ if (resolvedOffset < 0) {
5835
+ // This is not a valid offset. Report args as invalid.
5836
+ return [null, ERRNO_CODES.EINVAL];
5837
+ }
5838
+ return [resolvedOffset, 0];
5839
+ }
5840
+ const pid = PHPLoader.processId;
5841
+ switch (cmd) {
5842
+ case emscripten_F_GETLK: {
5843
+ _js_wasm_trace('fcntl(%d, F_GETLK)', fd);
5844
+ let vfsPath;
5845
+ let errno;
5846
+ [vfsPath, errno] = locking.get_vfs_path_from_fd(fd);
5847
+ if (errno !== 0) {
5848
+ _js_wasm_trace(
5849
+ 'fcntl(%d, F_GETLK) %s get_vfs_path_from_fd errno %d',
5850
+ fd,
5851
+ vfsPath,
5852
+ errno
5853
+ );
5854
+ return -ERRNO_CODES.EBADF;
5855
+ }
5856
+ if (!locking.is_path_to_shared_fs(vfsPath)) {
5857
+ _js_wasm_trace(
5858
+ "fcntl(%d, F_GETLK) locking is not implemented for non-NodeFS path '%s'",
5859
+ fd,
5860
+ vfsPath
5861
+ );
5862
+ // If not a NodeFS path, we can't lock it.
5863
+ // Default to succeeding as Emscripten does.
5864
+ update_flock_struct(flockStructAddr, {
5865
+ l_type: F_UNLCK,
5866
+ });
5867
+ return 0;
5868
+ }
5869
+ const flockStructAddr = syscallGetVarargP();
5870
+ const flockStruct = read_flock_struct(flockStructAddr);
5871
+ if (!(flockStruct.l_type in locking.fcntlToLockState)) {
5872
+ return -ERRNO_CODES.EINVAL;
5873
+ }
5874
+ errno = locking.check_lock_params(fd, flockStruct.l_type);
5875
+ if (errno !== 0) {
5876
+ _js_wasm_trace(
5877
+ 'fcntl(%d, F_GETLK) %s check_lock_params errno %d',
5878
+ fd,
5879
+ vfsPath,
5880
+ errno
5881
+ );
5882
+ return -ERRNO_CODES.EINVAL;
5883
+ }
5884
+ const requestedLockType =
5885
+ locking.fcntlToLockState[flockStruct.l_type];
5886
+ let absoluteStartOffset;
5887
+ [absoluteStartOffset, errno] = get_base_address(
5888
+ fd,
5889
+ flockStruct.l_whence,
5890
+ flockStruct.l_start
5891
+ );
5892
+ if (errno !== 0) {
5893
+ _js_wasm_trace(
5894
+ 'fcntl(%d, F_GETLK) %s get_base_address errno %d',
5895
+ fd,
5896
+ vfsPath,
5897
+ errno
5898
+ );
5899
+ return -ERRNO_CODES.EINVAL;
5900
+ }
5901
+ const nativeFilePath =
5902
+ locking.get_native_path_from_vfs_path(vfsPath);
5903
+ return PHPLoader.fileLockManager
5904
+ .findFirstConflictingByteRangeLock(nativeFilePath, {
5905
+ type: requestedLockType,
5906
+ start: absoluteStartOffset,
5907
+ end: absoluteStartOffset + flockStruct.l_len,
5908
+ pid,
5909
+ })
5910
+ .then((conflictingLock) => {
5911
+ if (conflictingLock === undefined) {
5912
+ _js_wasm_trace(
5913
+ 'fcntl(%d, F_GETLK) %s findFirstConflictingByteRangeLock type=unlocked start=0x%x end=0x%x',
5914
+ fd,
5915
+ vfsPath,
5916
+ absoluteStartOffset,
5917
+ absoluteStartOffset + flockStruct.l_len
5918
+ );
5919
+ update_flock_struct(flockStructAddr, {
5920
+ l_type: F_UNLCK,
5921
+ });
5922
+ return 0;
5923
+ }
5924
+ _js_wasm_trace(
5925
+ 'fcntl(%d, F_GETLK) %s findFirstConflictingByteRangeLock type=%s start=0x%x end=0x%x conflictingLock %d',
5926
+ fd,
5927
+ vfsPath,
5928
+ conflictingLock.type,
5929
+ conflictingLock.start,
5930
+ conflictingLock.end,
5931
+ conflictingLock.pid
5932
+ );
5933
+ const fcntlLockState =
5934
+ locking.lockStateToFcntl[conflictingLock.type];
5935
+ update_flock_struct(flockStructAddr, {
5936
+ l_type: fcntlLockState,
5937
+ l_whence: emscripten_SEEK_SET,
5938
+ l_start: conflictingLock.start,
5939
+ l_len: conflictingLock.end - conflictingLock.start,
5940
+ l_pid: conflictingLock.pid,
5941
+ });
5942
+ return 0;
5943
+ })
5944
+ .catch((e) => {
5945
+ _js_wasm_trace(
5946
+ 'fcntl(%d, F_GETLK) %s findFirstConflictingByteRangeLock error %s',
5947
+ fd,
5948
+ vfsPath,
5949
+ e
5950
+ );
5951
+ return -ERRNO_CODES.EINVAL;
5952
+ });
5953
+ }
5954
+
5955
+ case emscripten_F_SETLK: {
5956
+ _js_wasm_trace('fcntl(%d, F_SETLK)', fd);
5957
+ let vfsPath;
5958
+ let errno;
5959
+ [vfsPath, errno] = locking.get_vfs_path_from_fd(fd);
5960
+ if (errno !== 0) {
5961
+ _js_wasm_trace(
5962
+ 'fcntl(%d, F_SETLK) %s get_vfs_path_from_fd errno %d',
5963
+ fd,
5964
+ vfsPath,
5965
+ errno
5966
+ );
5967
+ return -errno;
5968
+ }
5969
+ if (!locking.is_path_to_shared_fs(vfsPath)) {
5970
+ _js_wasm_trace(
5971
+ 'fcntl(%d, F_SETLK) locking is not implemented for non-NodeFS path %s',
5972
+ fd,
5973
+ vfsPath
5974
+ );
5975
+ // If not a NodeFS path, we can't lock it.
5976
+ // Default to succeeding as Emscripten does.
5977
+ return 0;
5978
+ }
5979
+ var flockStructAddr = syscallGetVarargP();
5980
+ const flockStruct = read_flock_struct(flockStructAddr);
5981
+ let absoluteStartOffset;
5982
+ [absoluteStartOffset, errno] = get_base_address(
5983
+ fd,
5984
+ flockStruct.l_whence,
5985
+ flockStruct.l_start
5986
+ );
5987
+ if (errno !== 0) {
5988
+ _js_wasm_trace(
5989
+ 'fcntl(%d, F_SETLK) %s get_base_address errno %d',
5990
+ fd,
5991
+ vfsPath,
5992
+ errno
5993
+ );
5994
+ return -errno;
5995
+ }
5996
+ if (!(flockStruct.l_type in locking.fcntlToLockState)) {
5997
+ _js_wasm_trace(
5998
+ 'fcntl(%d, F_SETLK) %s invalid lock type %d',
5999
+ fd,
6000
+ vfsPath,
6001
+ flockStruct.l_type
6002
+ );
6003
+ return -ERRNO_CODES.EINVAL;
6004
+ }
6005
+ errno = locking.check_lock_params(fd, flockStruct.l_type);
6006
+ if (errno !== 0) {
6007
+ _js_wasm_trace(
6008
+ 'fcntl(%d, F_SETLK) %s check_lock_params errno %d',
6009
+ fd,
6010
+ vfsPath,
6011
+ errno
6012
+ );
6013
+ return -errno;
6014
+ }
6015
+ locking.maybeLockedFds.add(fd);
6016
+ const requestedLockType =
6017
+ locking.fcntlToLockState[flockStruct.l_type];
6018
+ const rangeLock = {
6019
+ type: requestedLockType,
6020
+ start: absoluteStartOffset,
6021
+ end: absoluteStartOffset + flockStruct.l_len,
6022
+ pid,
6023
+ };
6024
+ const nativeFilePath =
6025
+ locking.get_native_path_from_vfs_path(vfsPath);
6026
+ _js_wasm_trace(
6027
+ 'fcntl(%d, F_SETLK) %s calling lockFileByteRange for range lock %s',
6028
+ fd,
6029
+ vfsPath,
6030
+ rangeLock
6031
+ );
6032
+ return PHPLoader.fileLockManager
6033
+ .lockFileByteRange(nativeFilePath, rangeLock)
6034
+ .then((succeeded) => {
6035
+ _js_wasm_trace(
6036
+ 'fcntl(%d, F_SETLK) %s lockFileByteRange returned %d for range lock %s',
6037
+ fd,
6038
+ vfsPath,
6039
+ succeeded,
6040
+ rangeLock
6041
+ );
6042
+ return succeeded ? 0 : -ERRNO_CODES.EAGAIN;
6043
+ })
6044
+ .catch((e) => {
6045
+ _js_wasm_trace(
6046
+ 'fcntl(%d, F_SETLK) %s lockFileByteRange error %s for range lock %s',
6047
+ fd,
6048
+ vfsPath,
6049
+ e,
6050
+ rangeLock
6051
+ );
6052
+ return -ERRNO_CODES.EINVAL;
6053
+ });
6054
+ }
6055
+
6056
+ // @TODO: Implement waiting for lock
6057
+ case emscripten_F_SETLKW: {
6058
+ // We do not yet support the blocking form of flock().
6059
+ // We respond with EDEADLK to indicate failure
6060
+ // because it is a known errno for a failed F_SETLKW command.
6061
+ return -ERRNO_CODES.EDEADLK;
6062
+ }
6063
+
6064
+ default:
6065
+ return _builtin_fcntl64(fd, cmd, varargs);
6066
+ }
6067
+ }
6068
+
6069
+ ___syscall_fcntl64.isAsync = true;
6070
+
5285
6071
  function ___syscall_fdatasync(fd) {
5286
6072
  try {
5287
6073
  var stream = SYSCALLS.getStreamFromFD(fd);
@@ -5313,11 +6099,6 @@ export function init(RuntimeName, PHPLoader) {
5313
6099
  }
5314
6100
  }
5315
6101
 
5316
- var stringToUTF8 = (str, outPtr, maxBytesToWrite) =>
5317
- stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite);
5318
-
5319
- Module['stringToUTF8'] = stringToUTF8;
5320
-
5321
6102
  function ___syscall_getcwd(buf, size) {
5322
6103
  try {
5323
6104
  if (size === 0) return -28;
@@ -6577,17 +7358,6 @@ export function init(RuntimeName, PHPLoader) {
6577
7358
  return 0;
6578
7359
  };
6579
7360
 
6580
- function _fd_close(fd) {
6581
- try {
6582
- var stream = SYSCALLS.getStreamFromFD(fd);
6583
- FS.close(stream);
6584
- return 0;
6585
- } catch (e) {
6586
- if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
6587
- return e.errno;
6588
- }
6589
- }
6590
-
6591
7361
  function _fd_fdstat_get(fd, pbuf) {
6592
7362
  try {
6593
7363
  var rightsBase = 0;
@@ -6824,312 +7594,125 @@ export function init(RuntimeName, PHPLoader) {
6824
7594
  return -2;
6825
7595
  }
6826
7596
  }
6827
- }
6828
- if (addr != null) {
6829
- ai = allocaddrinfo(family, type, proto, node, addr, port);
6830
- HEAPU32[out >> 2] = ai;
6831
- return 0;
6832
- }
6833
- if (flags & 4) {
6834
- return -2;
6835
- }
6836
- // try as a hostname
6837
- // resolve the hostname to a temporary fake address
6838
- node = DNS.lookup_name(node);
6839
- addr = inetPton4(node);
6840
- if (family === 0) {
6841
- family = 2;
6842
- } else if (family === 10) {
6843
- addr = [0, 0, _htonl(65535), addr];
6844
- }
6845
- ai = allocaddrinfo(family, type, proto, null, addr, port);
6846
- HEAPU32[out >> 2] = ai;
6847
- return 0;
6848
- };
6849
-
6850
- var _getnameinfo = (sa, salen, node, nodelen, serv, servlen, flags) => {
6851
- var info = readSockaddr(sa, salen);
6852
- if (info.errno) {
6853
- return -6;
6854
- }
6855
- var port = info.port;
6856
- var addr = info.addr;
6857
- var overflowed = false;
6858
- if (node && nodelen) {
6859
- var lookup;
6860
- if (flags & 1 || !(lookup = DNS.lookup_addr(addr))) {
6861
- if (flags & 8) {
6862
- return -2;
6863
- }
6864
- } else {
6865
- addr = lookup;
6866
- }
6867
- var numBytesWrittenExclNull = stringToUTF8(addr, node, nodelen);
6868
- if (numBytesWrittenExclNull + 1 >= nodelen) {
6869
- overflowed = true;
6870
- }
6871
- }
6872
- if (serv && servlen) {
6873
- port = '' + port;
6874
- var numBytesWrittenExclNull = stringToUTF8(port, serv, servlen);
6875
- if (numBytesWrittenExclNull + 1 >= servlen) {
6876
- overflowed = true;
6877
- }
6878
- }
6879
- if (overflowed) {
6880
- // Note: even when we overflow, getnameinfo() is specced to write out the truncated results.
6881
- return -12;
6882
- }
6883
- return 0;
6884
- };
6885
-
6886
- var Protocols = {
6887
- list: [],
6888
- map: {},
6889
- };
6890
-
6891
- var _setprotoent = (stayopen) => {
6892
- // void setprotoent(int stayopen);
6893
- // Allocate and populate a protoent structure given a name, protocol number and array of aliases
6894
- function allocprotoent(name, proto, aliases) {
6895
- // write name into buffer
6896
- var nameBuf = _malloc(name.length + 1);
6897
- stringToAscii(name, nameBuf);
6898
- // write aliases into buffer
6899
- var j = 0;
6900
- var length = aliases.length;
6901
- var aliasListBuf = _malloc((length + 1) * 4);
6902
- // Use length + 1 so we have space for the terminating NULL ptr.
6903
- for (var i = 0; i < length; i++, j += 4) {
6904
- var alias = aliases[i];
6905
- var aliasBuf = _malloc(alias.length + 1);
6906
- stringToAscii(alias, aliasBuf);
6907
- HEAPU32[(aliasListBuf + j) >> 2] = aliasBuf;
6908
- }
6909
- HEAPU32[(aliasListBuf + j) >> 2] = 0;
6910
- // Terminating NULL pointer.
6911
- // generate protoent
6912
- var pe = _malloc(12);
6913
- HEAPU32[pe >> 2] = nameBuf;
6914
- HEAPU32[(pe + 4) >> 2] = aliasListBuf;
6915
- HEAP32[(pe + 8) >> 2] = proto;
6916
- return pe;
6917
- }
6918
- // Populate the protocol 'database'. The entries are limited to tcp and udp, though it is fairly trivial
6919
- // to add extra entries from /etc/protocols if desired - though not sure if that'd actually be useful.
6920
- var list = Protocols.list;
6921
- var map = Protocols.map;
6922
- if (list.length === 0) {
6923
- var entry = allocprotoent('tcp', 6, ['TCP']);
6924
- list.push(entry);
6925
- map['tcp'] = map['6'] = entry;
6926
- entry = allocprotoent('udp', 17, ['UDP']);
6927
- list.push(entry);
6928
- map['udp'] = map['17'] = entry;
6929
- }
6930
- _setprotoent.index = 0;
6931
- };
6932
-
6933
- var _getprotobyname = (name) => {
6934
- // struct protoent *getprotobyname(const char *);
6935
- name = UTF8ToString(name);
6936
- _setprotoent(true);
6937
- var result = Protocols.map[name];
6938
- return result;
6939
- };
6940
-
6941
- var _getprotobynumber = (number) => {
6942
- // struct protoent *getprotobynumber(int proto);
6943
- _setprotoent(true);
6944
- var result = Protocols.map[number];
6945
- return result;
6946
- };
6947
-
6948
- var stackAlloc = (sz) => __emscripten_stack_alloc(sz);
6949
-
6950
- /** @suppress {duplicate } */ var stringToUTF8OnStack = (str) => {
6951
- var size = lengthBytesUTF8(str) + 1;
6952
- var ret = stackAlloc(size);
6953
- stringToUTF8(str, ret, size);
6954
- return ret;
6955
- };
6956
-
6957
- var allocateUTF8OnStack = stringToUTF8OnStack;
6958
-
6959
- var PHPWASM = {
6960
- init: function () {
6961
- // The /internal directory is required by the C module. It's where the
6962
- // stdout, stderr, and headers information are written for the JavaScript
6963
- // code to read later on.
6964
- FS.mkdir('/internal');
6965
- // The files from the shared directory are shared between all the
6966
- // PHP processes managed by PHPProcessManager.
6967
- FS.mkdir('/internal/shared');
6968
- // The files from the preload directory are preloaded using the
6969
- // auto_prepend_file php.ini directive.
6970
- FS.mkdir('/internal/shared/preload');
6971
- PHPWASM.EventEmitter = ENVIRONMENT_IS_NODE
6972
- ? require('events').EventEmitter
6973
- : class EventEmitter {
6974
- constructor() {
6975
- this.listeners = {};
6976
- }
6977
- emit(eventName, data) {
6978
- if (this.listeners[eventName]) {
6979
- this.listeners[eventName].forEach(
6980
- (callback) => {
6981
- callback(data);
6982
- }
6983
- );
6984
- }
6985
- }
6986
- once(eventName, callback) {
6987
- const self = this;
6988
- function removedCallback() {
6989
- callback(...arguments);
6990
- self.removeListener(eventName, removedCallback);
6991
- }
6992
- this.on(eventName, removedCallback);
6993
- }
6994
- removeAllListeners(eventName) {
6995
- if (eventName) {
6996
- delete this.listeners[eventName];
6997
- } else {
6998
- this.listeners = {};
6999
- }
7000
- }
7001
- removeListener(eventName, callback) {
7002
- if (this.listeners[eventName]) {
7003
- const idx =
7004
- this.listeners[eventName].indexOf(callback);
7005
- if (idx !== -1) {
7006
- this.listeners[eventName].splice(idx, 1);
7007
- }
7008
- }
7009
- }
7010
- };
7011
- PHPWASM.child_proc_by_fd = {};
7012
- PHPWASM.child_proc_by_pid = {};
7013
- PHPWASM.input_devices = {};
7014
- },
7015
- getAllWebSockets: function (sock) {
7016
- const webSockets = new Set();
7017
- if (sock.server) {
7018
- sock.server.clients.forEach((ws) => {
7019
- webSockets.add(ws);
7020
- });
7021
- }
7022
- for (const peer of PHPWASM.getAllPeers(sock)) {
7023
- webSockets.add(peer.socket);
7024
- }
7025
- return Array.from(webSockets);
7026
- },
7027
- getAllPeers: function (sock) {
7028
- const peers = new Set();
7029
- if (sock.server) {
7030
- sock.pending
7031
- .filter((pending) => pending.peers)
7032
- .forEach((pending) => {
7033
- for (const peer of Object.values(pending.peers)) {
7034
- peers.add(peer);
7035
- }
7036
- });
7037
- }
7038
- if (sock.peers) {
7039
- for (const peer of Object.values(sock.peers)) {
7040
- peers.add(peer);
7041
- }
7042
- }
7043
- return Array.from(peers);
7044
- },
7045
- awaitData: function (ws) {
7046
- return PHPWASM.awaitEvent(ws, 'message');
7047
- },
7048
- awaitConnection: function (ws) {
7049
- if (ws.OPEN === ws.readyState) {
7050
- return [Promise.resolve(), PHPWASM.noop];
7051
- }
7052
- return PHPWASM.awaitEvent(ws, 'open');
7053
- },
7054
- awaitClose: function (ws) {
7055
- if ([ws.CLOSING, ws.CLOSED].includes(ws.readyState)) {
7056
- return [Promise.resolve(), PHPWASM.noop];
7057
- }
7058
- return PHPWASM.awaitEvent(ws, 'close');
7059
- },
7060
- awaitError: function (ws) {
7061
- if ([ws.CLOSING, ws.CLOSED].includes(ws.readyState)) {
7062
- return [Promise.resolve(), PHPWASM.noop];
7063
- }
7064
- return PHPWASM.awaitEvent(ws, 'error');
7065
- },
7066
- awaitEvent: function (ws, event) {
7067
- let resolve;
7068
- const listener = () => {
7069
- resolve();
7070
- };
7071
- const promise = new Promise(function (_resolve) {
7072
- resolve = _resolve;
7073
- ws.once(event, listener);
7074
- });
7075
- const cancel = () => {
7076
- ws.removeListener(event, listener);
7077
- // Rejecting the promises bubbles up and kills the entire
7078
- // node process. Let's resolve them on the next tick instead
7079
- // to give the caller some space to unbind any handlers.
7080
- setTimeout(resolve);
7081
- };
7082
- return [promise, cancel];
7083
- },
7084
- noop: function () {},
7085
- spawnProcess: function (command, args, options) {
7086
- if (Module['spawnProcess']) {
7087
- const spawnedPromise = Module['spawnProcess'](
7088
- command,
7089
- args,
7090
- options
7091
- );
7092
- return Promise.resolve(spawnedPromise).then(function (spawned) {
7093
- if (!spawned || !spawned.on) {
7094
- throw new Error(
7095
- 'spawnProcess() must return an EventEmitter but returned a different type.'
7096
- );
7097
- }
7098
- return spawned;
7099
- });
7597
+ }
7598
+ if (addr != null) {
7599
+ ai = allocaddrinfo(family, type, proto, node, addr, port);
7600
+ HEAPU32[out >> 2] = ai;
7601
+ return 0;
7602
+ }
7603
+ if (flags & 4) {
7604
+ return -2;
7605
+ }
7606
+ // try as a hostname
7607
+ // resolve the hostname to a temporary fake address
7608
+ node = DNS.lookup_name(node);
7609
+ addr = inetPton4(node);
7610
+ if (family === 0) {
7611
+ family = 2;
7612
+ } else if (family === 10) {
7613
+ addr = [0, 0, _htonl(65535), addr];
7614
+ }
7615
+ ai = allocaddrinfo(family, type, proto, null, addr, port);
7616
+ HEAPU32[out >> 2] = ai;
7617
+ return 0;
7618
+ };
7619
+
7620
+ var _getnameinfo = (sa, salen, node, nodelen, serv, servlen, flags) => {
7621
+ var info = readSockaddr(sa, salen);
7622
+ if (info.errno) {
7623
+ return -6;
7624
+ }
7625
+ var port = info.port;
7626
+ var addr = info.addr;
7627
+ var overflowed = false;
7628
+ if (node && nodelen) {
7629
+ var lookup;
7630
+ if (flags & 1 || !(lookup = DNS.lookup_addr(addr))) {
7631
+ if (flags & 8) {
7632
+ return -2;
7633
+ }
7634
+ } else {
7635
+ addr = lookup;
7100
7636
  }
7101
- if (ENVIRONMENT_IS_NODE) {
7102
- return require('child_process').spawn(command, args, {
7103
- ...options,
7104
- shell: true,
7105
- stdio: ['pipe', 'pipe', 'pipe'],
7106
- timeout: 100,
7107
- });
7637
+ var numBytesWrittenExclNull = stringToUTF8(addr, node, nodelen);
7638
+ if (numBytesWrittenExclNull + 1 >= nodelen) {
7639
+ overflowed = true;
7108
7640
  }
7109
- const e = new Error(
7110
- 'popen(), proc_open() etc. are unsupported in the browser. Call php.setSpawnHandler() ' +
7111
- 'and provide a callback to handle spawning processes, or disable a popen(), proc_open() ' +
7112
- 'and similar functions via php.ini.'
7113
- );
7114
- e.code = 'SPAWN_UNSUPPORTED';
7115
- throw e;
7116
- },
7117
- shutdownSocket: function (socketd, how) {
7118
- // This implementation only supports websockets at the moment
7119
- const sock = getSocketFromFD(socketd);
7120
- const peer = Object.values(sock.peers)[0];
7121
- if (!peer) {
7122
- return -1;
7641
+ }
7642
+ if (serv && servlen) {
7643
+ port = '' + port;
7644
+ var numBytesWrittenExclNull = stringToUTF8(port, serv, servlen);
7645
+ if (numBytesWrittenExclNull + 1 >= servlen) {
7646
+ overflowed = true;
7123
7647
  }
7124
- try {
7125
- peer.socket.close();
7126
- SOCKFS.websocket_sock_ops.removePeer(sock, peer);
7127
- return 0;
7128
- } catch (e) {
7129
- console.log('Socket shutdown error', e);
7130
- return -1;
7648
+ }
7649
+ if (overflowed) {
7650
+ // Note: even when we overflow, getnameinfo() is specced to write out the truncated results.
7651
+ return -12;
7652
+ }
7653
+ return 0;
7654
+ };
7655
+
7656
+ var Protocols = {
7657
+ list: [],
7658
+ map: {},
7659
+ };
7660
+
7661
+ var _setprotoent = (stayopen) => {
7662
+ // void setprotoent(int stayopen);
7663
+ // Allocate and populate a protoent structure given a name, protocol number and array of aliases
7664
+ function allocprotoent(name, proto, aliases) {
7665
+ // write name into buffer
7666
+ var nameBuf = _malloc(name.length + 1);
7667
+ stringToAscii(name, nameBuf);
7668
+ // write aliases into buffer
7669
+ var j = 0;
7670
+ var length = aliases.length;
7671
+ var aliasListBuf = _malloc((length + 1) * 4);
7672
+ // Use length + 1 so we have space for the terminating NULL ptr.
7673
+ for (var i = 0; i < length; i++, j += 4) {
7674
+ var alias = aliases[i];
7675
+ var aliasBuf = _malloc(alias.length + 1);
7676
+ stringToAscii(alias, aliasBuf);
7677
+ HEAPU32[(aliasListBuf + j) >> 2] = aliasBuf;
7131
7678
  }
7132
- },
7679
+ HEAPU32[(aliasListBuf + j) >> 2] = 0;
7680
+ // Terminating NULL pointer.
7681
+ // generate protoent
7682
+ var pe = _malloc(12);
7683
+ HEAPU32[pe >> 2] = nameBuf;
7684
+ HEAPU32[(pe + 4) >> 2] = aliasListBuf;
7685
+ HEAP32[(pe + 8) >> 2] = proto;
7686
+ return pe;
7687
+ }
7688
+ // Populate the protocol 'database'. The entries are limited to tcp and udp, though it is fairly trivial
7689
+ // to add extra entries from /etc/protocols if desired - though not sure if that'd actually be useful.
7690
+ var list = Protocols.list;
7691
+ var map = Protocols.map;
7692
+ if (list.length === 0) {
7693
+ var entry = allocprotoent('tcp', 6, ['TCP']);
7694
+ list.push(entry);
7695
+ map['tcp'] = map['6'] = entry;
7696
+ entry = allocprotoent('udp', 17, ['UDP']);
7697
+ list.push(entry);
7698
+ map['udp'] = map['17'] = entry;
7699
+ }
7700
+ _setprotoent.index = 0;
7701
+ };
7702
+
7703
+ var _getprotobyname = (name) => {
7704
+ // struct protoent *getprotobyname(const char *);
7705
+ name = UTF8ToString(name);
7706
+ _setprotoent(true);
7707
+ var result = Protocols.map[name];
7708
+ return result;
7709
+ };
7710
+
7711
+ var _getprotobynumber = (number) => {
7712
+ // struct protoent *getprotobynumber(int proto);
7713
+ _setprotoent(true);
7714
+ var result = Protocols.map[number];
7715
+ return result;
7133
7716
  };
7134
7717
 
7135
7718
  function _js_create_input_device(deviceId) {
@@ -7167,6 +7750,98 @@ export function init(RuntimeName, PHPLoader) {
7167
7750
  return allocateUTF8OnStack(devicePath);
7168
7751
  }
7169
7752
 
7753
+ async function _js_flock(fd, op) {
7754
+ _js_wasm_trace('js_flock(%d, %d)', fd, op);
7755
+ // Emscripten does not expose these constants to JS, so we hardcode them here.
7756
+ // Based on
7757
+ // https://github.com/emscripten-core/emscripten/blob/76860cc47cef67f5712a7a03a247bc1baabf7ba4/system/lib/libc/musl/include/sys/file.h#L7-L10
7758
+ const emscripten_LOCK_SH = 1;
7759
+ const emscripten_LOCK_EX = 2;
7760
+ const emscripten_LOCK_NB = 4;
7761
+ const emscripten_LOCK_UN = 8;
7762
+ const flockToLockOpType = {
7763
+ [emscripten_LOCK_SH]: 'shared',
7764
+ [emscripten_LOCK_EX]: 'exclusive',
7765
+ [emscripten_LOCK_UN]: 'unlocked',
7766
+ };
7767
+ let vfsPath;
7768
+ let errno;
7769
+ [vfsPath, errno] = locking.get_vfs_path_from_fd(fd);
7770
+ if (errno !== 0) {
7771
+ _js_wasm_trace(
7772
+ 'js_flock(%d, %d) get_vfs_path_from_fd errno %d',
7773
+ fd,
7774
+ op,
7775
+ vfsPath,
7776
+ errno
7777
+ );
7778
+ return -errno;
7779
+ }
7780
+ if (!locking.is_path_to_shared_fs(vfsPath)) {
7781
+ _js_wasm_trace(
7782
+ 'flock(%d, %d) locking is not implemented for non-NodeFS path %s',
7783
+ fd,
7784
+ op,
7785
+ vfsPath
7786
+ );
7787
+ // If not a NodeFS path, we can't lock it.
7788
+ // Default to succeeding as Emscripten does.
7789
+ return 0;
7790
+ }
7791
+ errno = locking.check_lock_params(fd, op);
7792
+ if (errno !== 0) {
7793
+ _js_wasm_trace(
7794
+ 'js_flock(%d, %d) check_lock_params errno %d',
7795
+ fd,
7796
+ op,
7797
+ errno
7798
+ );
7799
+ return -errno;
7800
+ }
7801
+ // @TODO: Consider supporting blocking mode of flock()
7802
+ if (op & (emscripten_LOCK_NB === 0)) {
7803
+ _js_wasm_trace(
7804
+ 'js_flock(%d, %d) blocking mode of flock() is not implemented',
7805
+ fd,
7806
+ op
7807
+ );
7808
+ // We do not yet support the blocking form of flock().
7809
+ // We respond with EINVAL to indicate failure
7810
+ // because it is a known errno for a failed blocking flock().
7811
+ return -ERRNO_CODES.EINVAL;
7812
+ }
7813
+ const maskedOp =
7814
+ op & (emscripten_LOCK_SH | emscripten_LOCK_EX | emscripten_LOCK_UN);
7815
+ const lockOpType = flockToLockOpType[maskedOp];
7816
+ if (lockOpType === undefined) {
7817
+ _js_wasm_trace(
7818
+ 'js_flock(%d, %d) invalid flock() operation',
7819
+ fd,
7820
+ op
7821
+ );
7822
+ return -ERRNO_CODES.EINVAL;
7823
+ }
7824
+ const nativeFilePath = locking.get_native_path_from_vfs_path(vfsPath);
7825
+ const obtainedLock = await PHPLoader.fileLockManager.lockWholeFile(
7826
+ nativeFilePath,
7827
+ {
7828
+ type: lockOpType,
7829
+ pid: PHPLoader.processId,
7830
+ fd,
7831
+ }
7832
+ );
7833
+ _js_wasm_trace(
7834
+ 'js_flock(%d, %d) lockWholeFile %s returned %d',
7835
+ fd,
7836
+ op,
7837
+ vfsPath,
7838
+ obtainedLock
7839
+ );
7840
+ return obtainedLock ? 0 : -ERRNO_CODES.EWOULDBLOCK;
7841
+ }
7842
+
7843
+ _js_flock.isAsync = true;
7844
+
7170
7845
  function _js_open_process(
7171
7846
  command,
7172
7847
  argsPtr,
@@ -7192,7 +7867,7 @@ export function init(RuntimeName, PHPLoader) {
7192
7867
  argsArray.push(UTF8ToString(HEAPU32[charPointer >> 2]));
7193
7868
  }
7194
7869
  }
7195
- const cwdstr = cwdPtr ? UTF8ToString(cwdPtr) : null;
7870
+ const cwdstr = cwdPtr ? UTF8ToString(cwdPtr) : FS.cwd();
7196
7871
  let envObject = null;
7197
7872
  if (envLength) {
7198
7873
  envObject = {};
@@ -7265,6 +7940,15 @@ export function init(RuntimeName, PHPLoader) {
7265
7940
  PHPWASM.child_proc_by_fd[ProcInfo.stderrParentFd] = ProcInfo;
7266
7941
  PHPWASM.child_proc_by_pid[ProcInfo.pid] = ProcInfo;
7267
7942
  cp.on('exit', function (code) {
7943
+ for (const fd of [
7944
+ // The child process exited. Let's clean up its output streams:
7945
+ ProcInfo.stdoutChildFd,
7946
+ ProcInfo.stderrChildFd,
7947
+ ]) {
7948
+ if (FS.streams[fd] && !FS.isClosed(FS.streams[fd])) {
7949
+ FS.close(FS.streams[fd]);
7950
+ }
7951
+ }
7268
7952
  ProcInfo.exitCode = code;
7269
7953
  ProcInfo.exited = true;
7270
7954
  // Emit events for the wasm_poll_socket function.
@@ -7315,12 +7999,52 @@ export function init(RuntimeName, PHPLoader) {
7315
7999
  * listen to the 'exit' event.
7316
8000
  */ try {
7317
8001
  await new Promise((resolve, reject) => {
7318
- cp.on('spawn', resolve);
7319
- cp.on('error', reject);
8002
+ /**
8003
+ * There was no `await` between the `spawnProcess` call
8004
+ * and the `await` below so the process haven't had a chance
8005
+ * to run any of the exit-related callbacks yet.
8006
+ *
8007
+ * Good.
8008
+ *
8009
+ * Let's listen to all the lifecycle events and resolve
8010
+ * the promise when the process starts or immediately crashes.
8011
+ */ let resolved = false;
8012
+ cp.on('spawn', () => {
8013
+ if (resolved) return;
8014
+ resolved = true;
8015
+ resolve();
8016
+ });
8017
+ cp.on('error', (e) => {
8018
+ if (resolved) return;
8019
+ resolved = true;
8020
+ reject(e);
8021
+ });
8022
+ cp.on('exit', function (code) {
8023
+ if (resolved) return;
8024
+ resolved = true;
8025
+ if (code === 0) {
8026
+ resolve();
8027
+ } else {
8028
+ reject(
8029
+ new Error(`Process exited with code ${code}`)
8030
+ );
8031
+ }
8032
+ });
8033
+ /**
8034
+ * If the process haven't even started after 5 seconds, something
8035
+ * is wrong. Perhaps we're missing an event listener, or perhaps
8036
+ * the `spawnProcess` implementation failed to dispatch the relevant
8037
+ * event. Either way, let's crash to avoid blocking the proc_open()
8038
+ * call indefinitely.
8039
+ */ setTimeout(() => {
8040
+ if (resolved) return;
8041
+ resolved = true;
8042
+ reject(new Error('Process timed out'));
8043
+ }, 5e3);
7320
8044
  });
7321
8045
  } catch (e) {
7322
8046
  console.error(e);
7323
- wakeUp(1);
8047
+ wakeUp(ProcInfo.pid);
7324
8048
  return;
7325
8049
  }
7326
8050
  // Now we want to pass data from the STDIN source supplied by PHP
@@ -7390,6 +8114,21 @@ export function init(RuntimeName, PHPLoader) {
7390
8114
  return 0;
7391
8115
  }
7392
8116
 
8117
+ var _js_release_file_locks = async function js_release_file_locks() {
8118
+ _js_wasm_trace('js_release_file_locks()');
8119
+ const pid = PHPLoader.processId;
8120
+ return await PHPLoader.fileLockManager
8121
+ .releaseLocksForProcess(pid)
8122
+ .then(() => {
8123
+ _js_wasm_trace('js_release_file_locks succeeded');
8124
+ })
8125
+ .catch((e) => {
8126
+ _js_wasm_trace('js_release_file_locks error %s', e);
8127
+ });
8128
+ };
8129
+
8130
+ _js_release_file_locks.isAsync = true;
8131
+
7393
8132
  function _js_waitpid(pid, exitCodePtr) {
7394
8133
  if (!PHPWASM.child_proc_by_pid[pid]) {
7395
8134
  return -1;
@@ -8030,14 +8769,7 @@ export function init(RuntimeName, PHPLoader) {
8030
8769
  const POLLNVAL = 32;
8031
8770
  return returnCallback((wakeUp) => {
8032
8771
  const polls = [];
8033
- if (socketd in PHPWASM.child_proc_by_fd) {
8034
- const procInfo = PHPWASM.child_proc_by_fd[socketd];
8035
- if (procInfo.exited) {
8036
- wakeUp(0);
8037
- return;
8038
- }
8039
- polls.push(PHPWASM.awaitEvent(procInfo.stdout, 'data'));
8040
- } else if (FS.isSocket(FS.getStream(socketd)?.node.mode)) {
8772
+ if (FS.isSocket(FS.getStream(socketd)?.node.mode)) {
8041
8773
  const sock = getSocketFromFD(socketd);
8042
8774
  if (!sock) {
8043
8775
  wakeUp(0);
@@ -8071,7 +8803,12 @@ export function init(RuntimeName, PHPLoader) {
8071
8803
  polls.push(PHPWASM.awaitConnection(ws));
8072
8804
  lookingFor.add('POLLOUT');
8073
8805
  }
8074
- if (events & POLLHUP) {
8806
+ if (
8807
+ events & POLLHUP ||
8808
+ events & POLLIN ||
8809
+ events & POLLOUT ||
8810
+ events & POLLERR
8811
+ ) {
8075
8812
  polls.push(PHPWASM.awaitClose(ws));
8076
8813
  lookingFor.add('POLLHUP');
8077
8814
  }
@@ -8080,6 +8817,13 @@ export function init(RuntimeName, PHPLoader) {
8080
8817
  lookingFor.add('POLLERR');
8081
8818
  }
8082
8819
  }
8820
+ } else if (socketd in PHPWASM.child_proc_by_fd) {
8821
+ const procInfo = PHPWASM.child_proc_by_fd[socketd];
8822
+ if (procInfo.exited) {
8823
+ wakeUp(0);
8824
+ return;
8825
+ }
8826
+ polls.push(PHPWASM.awaitEvent(procInfo.stdout, 'data'));
8083
8827
  } else {
8084
8828
  setTimeout(function () {
8085
8829
  wakeUp(1);
@@ -8311,9 +9055,13 @@ export function init(RuntimeName, PHPLoader) {
8311
9055
  /** @export */ getprotobyname: _getprotobyname,
8312
9056
  /** @export */ getprotobynumber: _getprotobynumber,
8313
9057
  /** @export */ js_create_input_device: _js_create_input_device,
9058
+ /** @export */ js_flock: _js_flock,
9059
+ /** @export */ js_getpid: _js_getpid,
8314
9060
  /** @export */ js_open_process: _js_open_process,
8315
9061
  /** @export */ js_process_status: _js_process_status,
9062
+ /** @export */ js_release_file_locks: _js_release_file_locks,
8316
9063
  /** @export */ js_waitpid: _js_waitpid,
9064
+ /** @export */ js_wasm_trace: _js_wasm_trace,
8317
9065
  /** @export */ proc_exit: _proc_exit,
8318
9066
  /** @export */ strptime: _strptime,
8319
9067
  /** @export */ wasm_close: _wasm_close,
@@ -8339,6 +9087,12 @@ export function init(RuntimeName, PHPLoader) {
8339
9087
 
8340
9088
  var _fflush = (a0) => (_fflush = wasmExports['fflush'])(a0);
8341
9089
 
9090
+ var _flock = (Module['_flock'] = (a0, a1) =>
9091
+ (_flock = Module['_flock'] = wasmExports['flock'])(a0, a1));
9092
+
9093
+ var _getpid = (Module['_getpid'] = () =>
9094
+ (_getpid = Module['_getpid'] = wasmExports['getpid'])());
9095
+
8342
9096
  var _wasm_popen = (Module['_wasm_popen'] = (a0, a1) =>
8343
9097
  (_wasm_popen = Module['_wasm_popen'] = wasmExports['wasm_popen'])(
8344
9098
  a0,
@@ -8366,13 +9120,6 @@ export function init(RuntimeName, PHPLoader) {
8366
9120
  (___wrap_select = Module['___wrap_select'] =
8367
9121
  wasmExports['__wrap_select'])(a0, a1, a2, a3, a4));
8368
9122
 
8369
- var _wasm_add_cli_arg = (Module['_wasm_add_cli_arg'] = (a0) =>
8370
- (_wasm_add_cli_arg = Module['_wasm_add_cli_arg'] =
8371
- wasmExports['wasm_add_cli_arg'])(a0));
8372
-
8373
- var _run_cli = (Module['_run_cli'] = () =>
8374
- (_run_cli = Module['_run_cli'] = wasmExports['run_cli'])());
8375
-
8376
9123
  var _wasm_set_sapi_name = (Module['_wasm_set_sapi_name'] = (a0) =>
8377
9124
  (_wasm_set_sapi_name = Module['_wasm_set_sapi_name'] =
8378
9125
  wasmExports['wasm_set_sapi_name'])(a0));
@@ -8381,6 +9128,13 @@ export function init(RuntimeName, PHPLoader) {
8381
9128
  (_wasm_set_phpini_path = Module['_wasm_set_phpini_path'] =
8382
9129
  wasmExports['wasm_set_phpini_path'])(a0));
8383
9130
 
9131
+ var _wasm_add_cli_arg = (Module['_wasm_add_cli_arg'] = (a0) =>
9132
+ (_wasm_add_cli_arg = Module['_wasm_add_cli_arg'] =
9133
+ wasmExports['wasm_add_cli_arg'])(a0));
9134
+
9135
+ var _run_cli = (Module['_run_cli'] = () =>
9136
+ (_run_cli = Module['_run_cli'] = wasmExports['run_cli'])());
9137
+
8384
9138
  var _wasm_add_SERVER_entry = (Module['_wasm_add_SERVER_entry'] = (a0, a1) =>
8385
9139
  (_wasm_add_SERVER_entry = Module['_wasm_add_SERVER_entry'] =
8386
9140
  wasmExports['wasm_add_SERVER_entry'])(a0, a1));
@@ -8453,6 +9207,16 @@ export function init(RuntimeName, PHPLoader) {
8453
9207
  var _wasm_free = (Module['_wasm_free'] = (a0) =>
8454
9208
  (_wasm_free = Module['_wasm_free'] = wasmExports['wasm_free'])(a0));
8455
9209
 
9210
+ var _wasm_get_end_offset = (Module['_wasm_get_end_offset'] = (a0) =>
9211
+ (_wasm_get_end_offset = Module['_wasm_get_end_offset'] =
9212
+ wasmExports['wasm_get_end_offset'])(a0));
9213
+
9214
+ var _wasm_trace = (Module['_wasm_trace'] = (a0, a1) =>
9215
+ (_wasm_trace = Module['_wasm_trace'] = wasmExports['wasm_trace'])(
9216
+ a0,
9217
+ a1
9218
+ ));
9219
+
8456
9220
  var ___funcs_on_exit = () =>
8457
9221
  (___funcs_on_exit = wasmExports['__funcs_on_exit'])();
8458
9222
 
@@ -8600,6 +9364,32 @@ export function init(RuntimeName, PHPLoader) {
8600
9364
  PHPLoader['free'] =
8601
9365
  typeof _free === 'function' ? _free : PHPLoader['_wasm_free'];
8602
9366
 
9367
+ if (typeof NODEFS === 'object') {
9368
+ // We override NODEFS.createNode() to add an `isSharedFS` flag to all NODEFS
9369
+ // nodes. This way we can tell whether file-locking is needed and possible
9370
+ // for an FS node, even if wrapped with PROXYFS.
9371
+ const originalCreateNode = NODEFS.createNode;
9372
+ NODEFS.createNode = function createNodeWithSharedFlag() {
9373
+ const node = originalCreateNode.apply(NODEFS, arguments);
9374
+ node.isSharedFS = true;
9375
+ return node;
9376
+ };
9377
+
9378
+ var originalHashAddNode = FS.hashAddNode;
9379
+ FS.hashAddNode = function hashAddNodeIfNotSharedFS(node) {
9380
+ if (
9381
+ typeof locking === 'object' &&
9382
+ locking?.is_shared_fs_node(node)
9383
+ ) {
9384
+ // Avoid caching shared VFS nodes so multiple instances
9385
+ // can access the same underlying filesystem without
9386
+ // conflicting caches.
9387
+ return;
9388
+ }
9389
+ return originalHashAddNode.apply(FS, arguments);
9390
+ };
9391
+ }
9392
+
8603
9393
  return PHPLoader;
8604
9394
 
8605
9395
  // Close the opening bracket from esm-prefix.js: