-
Notifications
You must be signed in to change notification settings - Fork 270
/
php_wasm.c
1867 lines (1676 loc) · 49.9 KB
/
php_wasm.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* PHP WebAssembly SAPI module.
*
* This file abstracts the entire PHP API with the minimal set
* of functions required to run PHP code from JavaScript.
*/
#include <main/php.h>
#include <main/SAPI.h>
#include <main/php_main.h>
#include <main/php_variables.h>
#include <main/php_ini.h>
#include <main/php_streams.h>
#include <zend_ini.h>
#include "ext/standard/php_standard.h"
#include <emscripten.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include "zend_globals_macros.h"
#include "zend_exceptions.h"
#include "zend_closures.h"
#include "zend_hash.h"
#include "rfc1867.h"
#include "SAPI.h"
#include "proc_open.h"
#include "dns_polyfill.h"
// Created by Dockerfile:
#include "php_wasm_asyncify.h"
unsigned int wasm_sleep(unsigned int time)
{
emscripten_sleep(time * 1000); // emscripten_sleep takes time in milliseconds
return time;
}
extern int *wasm_setsockopt(int sockfd, int level, int optname, intptr_t optval, size_t optlen, int dummy);
/**
* Shims popen(3) functionallity:
* https://man7.org/linux/man-pages/man3/popen.3.html
*
* Uses the same PHPWASM.spawnProcess callback as js_open_process,
* but waits for the process to exit and returns a path to a file
* with all the output bufferred.
*
* @TODO: get rid of this function and only rely on js_open_process
* instead.
*
* @param {int} command Command to execute
* @param {int} mode Mode to open the command in
* @param {int} exitCodePtr Pointer to the exit code
* @returns {int} File descriptor of the command output
*/
#ifdef PLAYGROUND_JSPI
EM_ASYNC_JS(char*, js_popen_to_file, (const char *command, const char *mode, uint8_t *exitCodePtr), {
const returnCallback = (resolver) => new Promise(resolver);
#else
EM_JS(char*, js_popen_to_file, (const char *command, const char *mode, uint8_t *exitCodePtr), {
const returnCallback = (resolver) => Asyncify.handleSleep(resolver);
#endif
// Parse args
if (!command)
return 1; // shell is available
const cmdstr = UTF8ToString(command);
if (!cmdstr.length)
return 0; // this is what glibc seems to do (shell works test?)
const modestr = UTF8ToString(mode);
if (!modestr.length)
return 0; // this is what glibc seems to do (shell works test?)
if (modestr === 'w')
{
console.error('popen($cmd, "w") is not implemented yet');
}
return returnCallback(async (wakeUp) => {
let cp;
try {
cp = PHPWASM.spawnProcess(cmdstr, []);
if (cp instanceof Promise) {
cp = await cp;
}
} catch (e) {
console.error(e);
if (e.code === 'SPAWN_UNSUPPORTED') {
return 1;
}
throw e;
}
const outByteArrays = [];
cp.stdout.on('data', function (data) {
outByteArrays.push(data);
});
const outputPath = '/tmp/popen_output';
cp.on('exit', function (exitCode) {
// Concat outByteArrays, an array of UInt8Arrays
// into a single Uint8Array.
const outBytes = new Uint8Array(
outByteArrays.reduce((acc, curr) => acc + curr.length, 0)
);
let offset = 0;
for (const byteArray of outByteArrays) {
outBytes.set(byteArray, offset);
offset += byteArray.length;
}
FS.writeFile(outputPath, outBytes);
HEAPU8[exitCodePtr] = exitCode;
wakeUp(allocateUTF8OnStack(outputPath)); // 2 is SIGINT
});
});
});
/**
* Shims poll(2) functionallity for asynchronous websockets:
* https://man7.org/linux/man-pages/man2/poll.2.html
*
* The semantics don't line up exactly with poll(2) but
* the intent does. This function is called in php_pollfd_for()
* to await a websocket-related event.
*
* @param {int} socketd The socket descriptor
* @param {int} events The events to wait for
* @param {int} timeout The timeout in milliseconds
* @returns {int} 1 if any event was triggered, 0 if the timeout expired
*/
#ifdef PLAYGROUND_JSPI
EM_ASYNC_JS(int, wasm_poll_socket, (php_socket_t socketd, int events, int timeout), {
const returnCallback = (resolver) => new Promise(resolver);
#else
EM_JS(int, wasm_poll_socket, (php_socket_t socketd, int events, int timeout), {
const returnCallback = (resolver) => Asyncify.handleSleep(resolver);
#endif
const POLLIN = 0x0001; /* There is data to read */
const POLLPRI = 0x0002; /* There is urgent data to read */
const POLLOUT = 0x0004; /* Writing now will not block */
const POLLERR = 0x0008; /* Error condition */
const POLLHUP = 0x0010; /* Hung up */
const POLLNVAL = 0x0020; /* Invalid request: fd not open */
return returnCallback((wakeUp) => {
const polls = [];
if (socketd in PHPWASM.child_proc_by_fd) {
// This is a child process-related socket.
const procInfo = PHPWASM.child_proc_by_fd[socketd];
if (procInfo.exited) {
wakeUp(0);
return;
}
polls.push(PHPWASM.awaitEvent(procInfo.stdout, 'data'));
} else if (FS.isSocket(FS.getStream(socketd)?.node.mode)) {
// This is, most likely, a websocket. Let's make sure.
const sock = getSocketFromFD(socketd);
if (!sock) {
wakeUp(0);
return;
}
const lookingFor = new Set();
if (events & POLLIN || events & POLLPRI) {
if (sock.server) {
for (const client of sock.pending) {
if ((client.recv_queue || []).length > 0) {
wakeUp(1);
return;
}
}
} else if ((sock.recv_queue || []).length > 0) {
wakeUp(1);
return;
}
}
const webSockets = PHPWASM.getAllWebSockets(sock);
if (!webSockets.length) {
wakeUp(0);
return;
}
for (const ws of webSockets) {
if (events & POLLIN || events & POLLPRI) {
polls.push(PHPWASM.awaitData(ws));
lookingFor.add('POLLIN');
}
if (events & POLLOUT) {
polls.push(PHPWASM.awaitConnection(ws));
lookingFor.add('POLLOUT');
}
if (events & POLLHUP) {
polls.push(PHPWASM.awaitClose(ws));
lookingFor.add('POLLHUP');
}
if (events & POLLERR || events & POLLNVAL) {
polls.push(PHPWASM.awaitError(ws));
lookingFor.add('POLLERR');
}
}
} else {
setTimeout(function () {
wakeUp(1);
}, timeout);
return;
}
if (polls.length === 0) {
console.warn(
'Unsupported poll event ' +
events +
', defaulting to setTimeout().'
);
setTimeout(function () {
wakeUp(0);
}, timeout);
return;
}
const promises = polls.map(([promise]) => promise);
const clearPolling = () => polls.forEach(([, clear]) => clear());
let awaken = false;
let timeoutId;
Promise.race(promises).then(function (results) {
if (!awaken) {
awaken = true;
wakeUp(1);
if (timeoutId) {
clearTimeout(timeoutId);
}
clearPolling();
}
});
if (timeout !== -1) {
timeoutId = setTimeout(function () {
if (!awaken) {
awaken = true;
wakeUp(0);
clearPolling();
}
}, timeout);
}
});
});
/**
* Shims read(2) functionallity.
* Enables reading from blocking pipes. By default, Emscripten
* will throw an EWOULDBLOCK error when trying to read from a
* blocking pipe. This function overrides that behavior and
* instead waits for the pipe to become readable.
*
* @see https://github.com/WordPress/wordpress-playground/issues/951
* @see https://github.com/emscripten-core/emscripten/issues/13214
*/
#ifdef PLAYGROUND_JSPI
EM_ASYNC_JS(__wasi_errno_t, js_fd_read, (__wasi_fd_t fd, const __wasi_iovec_t *iov, size_t iovcnt, __wasi_size_t *pnum), {
const returnCallback = (resolver) => new Promise(resolver);
#else
EM_JS(__wasi_errno_t, js_fd_read, (__wasi_fd_t fd, const __wasi_iovec_t *iov, size_t iovcnt, __wasi_size_t *pnum), {
const returnCallback = (resolver) => Asyncify.handleSleep(resolver);
#endif
if (Asyncify?.State?.Normal === undefined || Asyncify?.state === Asyncify?.State?.Normal) {
var returnCode;
var stream;
let num = 0;
try
{
stream = SYSCALLS.getStreamFromFD(fd);
const num = doReadv(stream, iov, iovcnt);
HEAPU32[pnum >> 2] = num;
return 0;
}
catch (e)
{
// Rethrow any unexpected non-filesystem errors.
if (typeof FS == "undefined" || !(e.name === "ErrnoError"))
{
throw e;
}
// Only return synchronously if this isn't an asynchronous pipe.
// Error code 6 indicates EWOULDBLOCK – this is our signal to wait.
// We also need to distinguish between a process pipe and a file pipe, otherwise
// reading from an empty file would block until the timeout.
if (e.errno !== 6 || !(stream?.fd in PHPWASM.child_proc_by_fd))
{
// On failure, yield 0 bytes read to indicate EOF.
HEAPU32[pnum >> 2] = 0;
return returnCode
}
}
}
// At this point we know we have to poll.
// You might wonder why we duplicate the code here instead of always using
// Asyncify.handleSleep(). The reason is performance. Most of the time,
// the read operation will work synchronously and won't require yielding
// back to JS. In these cases we don't want to pay the Asyncify overhead,
// save the stack, yield back to JS, restore the stack etc.
return returnCallback((wakeUp) => {
var retries = 0;
var interval = 50;
var timeout = 5000;
// We poll for data and give up after a timeout.
// We can't simply rely on PHP timeout here because we don't want
// to, say, block the entire PHPUnit test suite without any visible
// feedback.
var maxRetries = timeout / interval;
function poll() {
var returnCode;
var stream;
let num;
try {
stream = SYSCALLS.getStreamFromFD(fd);
num = doReadv(stream, iov, iovcnt);
returnCode = 0;
} catch (e) {
if (
typeof FS == 'undefined' ||
!(e.name === 'ErrnoError')
) {
console.error(e);
throw e;
}
returnCode = e.errno;
}
const success = returnCode === 0;
const failure = (
++retries > maxRetries ||
!(fd in PHPWASM.child_proc_by_fd) ||
PHPWASM.child_proc_by_fd[fd]?.exited ||
FS.isClosed(stream)
);
if (success) {
HEAPU32[pnum >> 2] = num;
wakeUp(0);
} else if (failure) {
// On failure, yield 0 bytes read to indicate EOF.
HEAPU32[pnum >> 2] = 0;
// If the failure is due to a timeout, return 0 to indicate that we
// reached EOF. Otherwise, propagate the error code.
wakeUp(returnCode === 6 ? 0 : returnCode);
} else {
setTimeout(poll, interval);
}
}
poll();
})
});
extern int __wasi_syscall_ret(__wasi_errno_t code);
// Exit code of the last exited child process call.
int wasm_pclose_ret = -1;
/**
* Passes a message to the JavaScript module and writes the response
* data, if any, to the response_buffer pointer.
*
* @param message The message to pass into JavaScript.
* @param response_buffer The address where the response will be stored. The
* JS module will allocate a memory block for the response buffer and write
* its address to **response_buffer. The caller is responsible for freeing
* that memory after use.
*
* @return The size of the response_buffer (it can contain null bytes).
*
* @note The caller should ensure that the memory allocated for response_buffer
* is freed after its use to prevent memory leaks. It's also recommended
* to handle exceptions and errors gracefully within the function to ensure
* the stability of the system.
*/
EM_ASYNC_JS(size_t, js_module_onMessage, (const char *data, char **response_buffer), {
if (Module['onMessage']) {
const dataStr = UTF8ToString(data);
return Module['onMessage'](dataStr)
.then((response) => {
const responseBytes =
typeof response === 'string'
? new TextEncoder().encode(response)
: response;
// Copy the response bytes to heap
const responseSize = responseBytes.byteLength;
const responsePtr = _malloc(responseSize + 1);
HEAPU8.set(responseBytes, responsePtr);
HEAPU8[responsePtr + responseSize] = 0;
HEAPU8[response_buffer] = responsePtr;
HEAPU8[response_buffer + 1] = responsePtr >> 8;
HEAPU8[response_buffer + 2] = responsePtr >> 16;
HEAPU8[response_buffer + 3] = responsePtr >> 24;
return responseSize;
})
.catch((e) => {
// Log the error and return NULL. Message passing
// separates JS context from the PHP context so we
// don't let PHP crash here.
console.error(e);
return -1;
});
}
});
// popen() shim
// -----------------------------------------------------------
// We have a custom popen handler because the original one calls
// fork() which emscripten does not support.
//
// This wasm_popen function is called by PHP_FUNCTION(popen) thanks
// to a patch applied in the Dockerfile.
//
// The `js_popen_to_file` is defined in phpwasm-emscripten-library.js.
// It runs the `cmd` command and returns the path to a file that contains the
// output. The exit code is assigned to the exit_code_ptr.
EMSCRIPTEN_KEEPALIVE FILE *wasm_popen(const char *cmd, const char *mode)
{
FILE *fp;
if (*mode == 'r')
{
uint8_t last_exit_code;
char *file_path = js_popen_to_file(cmd, mode, &last_exit_code);
fp = fopen(file_path, mode);
FG(pclose_ret) = last_exit_code;
wasm_pclose_ret = last_exit_code;
}
else if (*mode == 'w')
{
int current_procopen_call_id = ++procopen_call_id;
char *device_path = js_create_input_device(current_procopen_call_id);
int stdin_childend = current_procopen_call_id;
fp = fopen(device_path, mode);
php_file_descriptor_t stdout_pipe[2];
php_file_descriptor_t stderr_pipe[2];
if (0 != pipe(stdout_pipe) || 0 != pipe(stderr_pipe))
{
php_error_docref(NULL, E_WARNING, "unable to create pipe %s", strerror(errno));
errno = EINVAL;
return 0;
}
int *stdin = safe_emalloc(sizeof(int), 3, 0);
int *stdout = safe_emalloc(sizeof(int), 3, 0);
int *stderr = safe_emalloc(sizeof(int), 3, 0);
stdin[0] = 0;
stdin[1] = stdin_childend;
stdin[2] = (int) NULL;
stdout[0] = 1;
stdout[1] = stdout_pipe[0];
stdout[2] = stdout_pipe[1];
stderr[0] = 2;
stderr[1] = stderr_pipe[0];
stderr[2] = stderr_pipe[1];
int **descv = safe_emalloc(sizeof(int *), 3, 0);
descv[0] = stdin;
descv[1] = stdout;
descv[2] = stderr;
// the wasm way {{{
js_open_process(
cmd,
NULL,
0,
descv,
3,
"",
0,
0,
0
);
// }}}
efree(stdin);
efree(stdout);
efree(stderr);
efree(descv);
}
else
{
printf("wasm_popen: mode '%s' not supported (cmd: %s)! \n", mode, cmd);
errno = EINVAL;
return 0;
}
return fp;
}
/**
* Ship php_exec, the function powering the following PHP
* functions:
* * exec()
* * passthru()
* * system()
* * shell_exec()
*
* The wasm_php_exec function is called thanks
* to -Dphp_exec=wasm_php_exec in the Dockerfile and also a
* small patch that removes php_exec and marks wasm_php_exec()
* as external.
*
* {{{
*/
// These utility functions are copied from php-src/ext/standard/exec.c
static size_t strip_trailing_whitespace(char *buf, size_t bufl)
{
size_t l = bufl;
while (l-- > 0 && isspace(((unsigned char *)buf)[l]))
;
if (l != (bufl - 1))
{
bufl = l + 1;
buf[bufl] = '\0';
}
return bufl;
}
static size_t handle_line(int type, zval *array, char *buf, size_t bufl)
{
if (type == 1)
{
PHPWRITE(buf, bufl);
if (php_output_get_level() < 1)
{
sapi_flush();
}
}
else if (type == 2)
{
bufl = strip_trailing_whitespace(buf, bufl);
add_next_index_stringl(array, buf, bufl);
}
return bufl;
}
/**
* Shims read(2) functionallity.
* Enables reading from blocking pipes. By default, Emscripten
* will throw an EWOULDBLOCK error when trying to read from a
* blocking pipe. This function overrides that behavior and
* instead waits for the pipe to become readable.
*
* @see https://github.com/WordPress/wordpress-playground/issues/951
* @see https://github.com/emscripten-core/emscripten/issues/13214
*/
EMSCRIPTEN_KEEPALIVE ssize_t wasm_read(int fd, void *buf, size_t count)
{
struct __wasi_iovec_t iov = {
.buf = buf,
.buf_len = count};
size_t num;
if (__wasi_syscall_ret(js_fd_read(fd, &iov, 1, &num)))
{
return -1;
}
return num;
}
/*
* If type==0, only last line of output is returned (exec)
* If type==1, all lines will be printed and last lined returned (system)
* If type==2, all lines will be saved to given array (exec with &$array)
* If type==3, output will be printed binary, no lines will be saved or returned (passthru)
*/
EMSCRIPTEN_KEEPALIVE int wasm_php_exec(int type, const char *cmd, zval *array, zval *return_value)
{
FILE *fp;
char *buf;
int pclose_return;
char *b, *d = NULL;
php_stream *stream;
size_t buflen, bufl = 0;
#if PHP_SIGCHILD
void (*sig_handler)() = NULL;
#endif
#if PHP_SIGCHILD
sig_handler = signal(SIGCHLD, SIG_DFL);
#endif
// Reuse the process-opening logic
fp = wasm_popen(cmd, "r");
if (!fp)
{
php_error_docref(NULL, E_WARNING, "Unable to fork [%s]", cmd);
goto err;
}
stream = php_stream_fopen_from_pipe(fp, "rb");
buf = (char *)emalloc(EXEC_INPUT_BUF);
buflen = EXEC_INPUT_BUF;
if (type != 3)
{
b = buf;
while (php_stream_get_line(stream, b, EXEC_INPUT_BUF, &bufl))
{
/* no new line found, let's read some more */
if (b[bufl - 1] != '\n' && !php_stream_eof(stream))
{
if (buflen < (bufl + (b - buf) + EXEC_INPUT_BUF))
{
bufl += b - buf;
buflen = bufl + EXEC_INPUT_BUF;
buf = erealloc(buf, buflen);
b = buf + bufl;
}
else
{
b += bufl;
}
continue;
}
else if (b != buf)
{
bufl += b - buf;
}
bufl = handle_line(type, array, buf, bufl);
b = buf;
}
if (bufl)
{
if (buf != b)
{
/* Process remaining output */
bufl = handle_line(type, array, buf, bufl);
}
/* Return last line from the shell command */
bufl = strip_trailing_whitespace(buf, bufl);
RETVAL_STRINGL(buf, bufl);
}
else
{ /* should return NULL, but for BC we return "" */
RETVAL_EMPTY_STRING();
}
}
else
{
ssize_t read;
while ((read = php_stream_read(stream, buf, EXEC_INPUT_BUF)) > 0)
{
PHPWRITE(buf, read);
}
}
pclose_return = php_stream_close(stream);
if (pclose_return == -1)
{
pclose_return = wasm_pclose_ret;
}
efree(buf);
done:
#if PHP_SIGCHILD
if (sig_handler)
{
signal(SIGCHLD, sig_handler);
}
#endif
if (d)
{
efree(d);
}
return pclose_return;
err:
pclose_return = -1;
RETVAL_FALSE;
goto done;
}
// }}}
// -----------------------------------------------------------
int wasm_socket_has_data(php_socket_t fd);
/* hybrid select(2)/poll(2) for a single descriptor.
* timeouttv follows same rules as select(2), but is reduced to millisecond accuracy.
* Returns 0 on timeout, -1 on error, or the event mask (ala poll(2)).
*/
EMSCRIPTEN_KEEPALIVE inline int php_pollfd_for(php_socket_t fd, int events, struct timeval *timeouttv)
{
php_pollfd p;
int n;
p.fd = fd;
p.events = events;
p.revents = 0;
// must yield back to JS event loop to get the network response:
wasm_poll_socket(fd, events, php_tvtoto(timeouttv));
n = php_poll2(&p, 1, php_tvtoto(timeouttv));
if (n > 0)
{
return p.revents;
}
return n;
}
ZEND_BEGIN_ARG_INFO_EX(arginfo_post_message_to_js, 0, 1, 1)
ZEND_ARG_INFO(0, data)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_dl, 0)
ZEND_ARG_INFO(0, extension_filename)
ZEND_END_ARG_INFO()
/* Enable PHP to exchange messages with JavaScript */
PHP_FUNCTION(post_message_to_js)
{
char *data;
int data_len;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &data, &data_len) == FAILURE)
{
return;
}
char *response;
size_t response_len = js_module_onMessage(data, &response);
if (response_len != -1)
{
zend_string *return_string = zend_string_init(response, response_len, 0);
free(response);
RETURN_NEW_STR(return_string);
}
else
{
RETURN_NULL();
}
}
/**
* select(2).
*/
EMSCRIPTEN_KEEPALIVE int __wrap_select(int max_fd, fd_set *read_fds, fd_set *write_fds, fd_set *except_fds, struct timeval *timeouttv)
{
emscripten_sleep(0); // always yield to JS event loop
int timeoutms = php_tvtoto(timeouttv);
int n = 0;
for (int i = 0; i < max_fd; i++)
{
if (FD_ISSET(i, read_fds))
{
n += wasm_poll_socket(i, POLLIN | POLLOUT, timeoutms);
}
if (FD_ISSET(i, write_fds))
{
n += wasm_poll_socket(i, POLLOUT, timeoutms);
}
if (FD_ISSET(i, except_fds))
{
n += wasm_poll_socket(i, POLLERR, timeoutms);
FD_CLR(i, except_fds);
}
}
return n;
}
#if WITH_CLI_SAPI == 1
#include "sapi/cli/php_cli_process_title.h"
#if PHP_MAJOR_VERSION >= 8
#include "sapi/cli/php_cli_process_title_arginfo.h"
#endif
extern int wasm_shutdown(int sockfd, int how);
extern int wasm_close(int sockfd);
static const zend_function_entry additional_functions[] = {
ZEND_FE(dl, arginfo_dl)
ZEND_FE(dns_get_mx, arginfo_dns_get_mx)
ZEND_FALIAS(getmxrr, dns_get_mx, arginfo_getmxrr)
ZEND_FALIAS(checkdnsrr, dns_check_record, arginfo_checkdnsrr)
ZEND_FE(dns_check_record, arginfo_dns_check_record)
ZEND_FE(dns_get_record, arginfo_dns_get_record)
PHP_FE(cli_set_process_title, arginfo_cli_set_process_title)
PHP_FE(cli_get_process_title, arginfo_cli_get_process_title)
PHP_FE(post_message_to_js, arginfo_post_message_to_js){NULL, NULL, NULL}
};
typedef struct wasm_cli_arg
{
char *value;
struct wasm_cli_arg *next;
} wasm_cli_arg_t;
int cli_argc = 0;
wasm_cli_arg_t *cli_argv;
void wasm_add_cli_arg(char *arg)
{
++cli_argc;
wasm_cli_arg_t *ll_entry = (wasm_cli_arg_t *)malloc(sizeof(wasm_cli_arg_t));
ll_entry->value = strdup(arg);
ll_entry->next = cli_argv;
cli_argv = ll_entry;
}
/**
* The main() function comes from PHP CLI SAPI in sapi/cli/php_cli.c
* The file is provided by the linker and the main() function is not
* exported from the final .wasm file at the moment.
*/
int main(int argc, char *argv[]);
int run_cli()
{
// Convert the argv linkedlist to an array:
char **cli_argv_array = malloc(sizeof(char *) * (cli_argc));
wasm_cli_arg_t *current_arg = cli_argv;
int i = 0;
while (current_arg != NULL)
{
cli_argv_array[cli_argc - i - 1] = current_arg->value;
++i;
current_arg = current_arg->next;
}
return main(cli_argc, cli_argv_array);
}
#else
static const zend_function_entry additional_functions[] = {
ZEND_FE(dl, arginfo_dl)
ZEND_FE(dns_get_mx, arginfo_dns_get_mx)
ZEND_FALIAS(getmxrr, dns_get_mx, arginfo_getmxrr)
ZEND_FALIAS(checkdnsrr, dns_check_record, arginfo_checkdnsrr)
ZEND_FE(dns_check_record, arginfo_dns_check_record)
ZEND_FE(dns_get_record, arginfo_dns_get_record)
PHP_FE(post_message_to_js, arginfo_post_message_to_js){NULL, NULL, NULL}
};
#endif
#if !defined(TSRMLS_DC)
#define TSRMLS_DC
#endif
#if !defined(TSRMLS_D)
#define TSRMLS_D
#endif
#if !defined(TSRMLS_CC)
#define TSRMLS_CC
#endif
#if !defined(TSRMLS_C)
#define TSRMLS_C
#endif
#if !defined(TSRMLS_FETCH)
#define TSRMLS_FETCH()
#endif
typedef struct wasm_array_entry
{
char *key;
char *value;
struct wasm_array_entry *next;
} wasm_array_entry_t;
typedef struct wasm_uploaded_file
{
char *key,
*name,
*type,
*tmp_name;
int error, size;
struct wasm_uploaded_file *next;
} wasm_uploaded_file_t;
typedef struct
{
char *document_root,
*query_string,
*path_translated,
*request_uri,
*request_method,
*request_host,
*content_type,
*request_body,
*cookies;
struct wasm_array_entry *server_array_entries;
struct wasm_array_entry *env_array_entries;
int content_length,
request_port,
skip_shebang;
} wasm_server_context_t;
static wasm_server_context_t *wasm_server_context;
int wasm_sapi_module_startup(sapi_module_struct *sapi_module);
int wasm_sapi_shutdown_wrapper(sapi_module_struct *sapi_globals);
void wasm_sapi_module_shutdown();
static int wasm_sapi_deactivate(TSRMLS_D);
static size_t wasm_sapi_ub_write(const char *str, size_t str_length TSRMLS_DC);
static size_t wasm_sapi_read_post_body(char *buffer, size_t count_bytes);
#if PHP_MAJOR_VERSION >= 8
static void wasm_sapi_log_message(const char *message TSRMLS_DC, int syslog_type_int);
#else
#if (PHP_MAJOR_VERSION == 7 && PHP_MINOR_VERSION >= 1)
static void wasm_sapi_log_message(char *message TSRMLS_DC, int syslog_type_int);
#else
static void wasm_sapi_log_message(char *message TSRMLS_DC);
#endif
#endif
static void wasm_sapi_flush(void *server_context);
static int wasm_sapi_send_headers(sapi_headers_struct *sapi_headers TSRMLS_DC);
static void wasm_sapi_send_header(sapi_header_struct *sapi_header, void *server_context TSRMLS_DC);
static char *wasm_sapi_read_cookies(TSRMLS_D);
static void wasm_sapi_register_server_variables(zval *track_vars_array TSRMLS_DC);
void wasm_init_server_context();
static char *int_to_string(int i);
#if (PHP_MAJOR_VERSION >= 8)
static char *wasm_sapi_getenv(const char *name, size_t name_len)
#else
#if (PHP_MAJOR_VERSION == 7 && PHP_MINOR_VERSION >= 4)
static char *wasm_sapi_getenv(char *name, size_t name_len)
#else
static char *wasm_sapi_getenv(char *name, unsigned long name_len)
#endif
#endif
{
wasm_array_entry_t *current_entry = wasm_server_context->env_array_entries;
while (current_entry != NULL)
{
if (strncmp(current_entry->key, name, name_len) == 0)
{
return current_entry->value;
}
current_entry = current_entry->next;
}
return NULL;
}
SAPI_API sapi_module_struct php_wasm_sapi_module = {
"wasm", /* name */
#ifdef PLAYGROUND_JSPI
"PHP WASM SAPI (JSPI)", /* pretty name */
#else
"PHP WASM SAPI (Asyncify)", /* pretty name */
#endif
wasm_sapi_module_startup, /* startup */
wasm_sapi_shutdown_wrapper, /* shutdown */
NULL, /* activate */
wasm_sapi_deactivate, /* deactivate */
wasm_sapi_ub_write, /* unbuffered write */
wasm_sapi_flush, /* flush */
NULL, /* get uid */
wasm_sapi_getenv, /* getenv */
php_error, /* error handler */
NULL, /* header handler */
wasm_sapi_send_headers, /* send headers handler */
wasm_sapi_send_header, /* send header handler */
wasm_sapi_read_post_body, /* read POST data */
wasm_sapi_read_cookies, /* read Cookies */
wasm_sapi_register_server_variables, /* register server variables */
wasm_sapi_log_message, /* Log message */
NULL, /* Get request time */
NULL, /* Child terminate */
STANDARD_SAPI_MODULE_PROPERTIES};
int php_sapi_started = 0;
int wasm_set_sapi_name(char *name)
{
if(php_sapi_started == 1) {
return 1;
}