-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathlibuv_reactor.c
More file actions
5096 lines (4090 loc) · 143 KB
/
libuv_reactor.c
File metadata and controls
5096 lines (4090 loc) · 143 KB
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
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Edmond |
+----------------------------------------------------------------------+
*/
#include "libuv_reactor.h"
#include <Zend/zend_async_API.h>
#include <Zend/zend_closures.h>
#include <main/php.h>
#include <main/SAPI.h>
#include "exceptions.h"
#include "php_async.h"
#include "php_main.h"
#include "thread.h"
#include "thread_pool.h"
#include "zend_common.h"
#ifdef ZTS
#include "TSRM.h"
#endif
#ifdef PHP_WIN32
#include "win32/unistd.h"
#include "win32/codepage.h"
#else
#include <sys/wait.h>
#include <signal.h>
#include <unistd.h>
#include <errno.h>
#endif
#ifdef ZEND_SIGNALS
#include "Zend/zend_signal.h"
/* Storage for original sigaction handlers (typically zend_signal_handler_defer)
* that were installed before libuv took over signal handling. These are restored
* when libuv releases the signal, so zend_signal_deactivate() sees the expected
* handler and does not emit a warning. */
static struct sigaction async_saved_sigactions[NSIG];
static bool async_signal_active[NSIG] = { false };
static void libuv_restore_signal_handler(int signum)
{
if (signum > 0 && signum < NSIG && async_signal_active[signum]) {
sigaction(signum, &async_saved_sigactions[signum], NULL);
async_signal_active[signum] = false;
}
}
#endif
static void libuv_reactor_stop_with_exception(void);
/* DNS private flags (bits 13+, private range for event subtypes) */
#define LIBUV_DNS_F_CALLBACK_DONE (1u << 13) /* libuv callback has fired */
#define LIBUV_DNS_F_DISPOSE_PENDING (1u << 14) /* dispose requested, callback owns the memory */
// Forward declarations for global signal management
static void libuv_add_signal_event(int signum, zend_async_event_t *event);
static void libuv_remove_signal_event(int signum, zend_async_event_t *event);
static void libuv_add_process_event(zend_async_event_t *event);
static void libuv_remove_process_event(zend_async_event_t *event);
static void libuv_handle_process_events(void);
static void libuv_handle_signal_events(const int signum);
static void libuv_signal_close_cb(uv_handle_t *handle);
// Forward declarations for cleanup functions
static void libuv_cleanup_signal_handlers(void);
static void libuv_cleanup_signal_events(void);
static void libuv_cleanup_process_events(void);
static void uv_stat_to_zend_stat(const uv_stat_t *uv_statbuf, zend_stat_t *zend_statbuf);
///////////////////////////////////////////////////////////
/// Child thread registry
///
/// Process-global registry that tracks every OS thread spawned by the
/// reactor (both event-backed threads and lightweight pool workers).
///
/// Purpose: let the main thread block before php_module_shutdown until
/// all child threads have released TSRM and are safe to outrun.
///
/// - Add: main thread under registry_mutex, after uv_thread_create
/// returns successfully, keyed by the OS handle.
/// - Remove: child thread itself, right after ts_free_thread() and
/// before returning from the OS entry point, so that entries only
/// disappear once the thread has stopped touching Zend/TSRM state.
/// - Quiesce: main thread waits on registry_cond until the table is
/// empty, then caller may proceed into php_module_shutdown.
///////////////////////////////////////////////////////////
static HashTable child_thread_registry;
static uv_mutex_t child_thread_registry_mutex;
static uv_cond_t child_thread_registry_cond;
static bool child_thread_registry_inited = false;
static void libuv_thread_registry_init(void)
{
if (child_thread_registry_inited) {
return;
}
zend_hash_init(&child_thread_registry, 8, NULL, NULL, 1 /* persistent */);
if (uv_mutex_init(&child_thread_registry_mutex) != 0) {
zend_error_noreturn(E_CORE_ERROR,
"libuv: failed to init child_thread_registry_mutex");
}
if (uv_cond_init(&child_thread_registry_cond) != 0) {
uv_mutex_destroy(&child_thread_registry_mutex);
zend_error_noreturn(E_CORE_ERROR,
"libuv: failed to init child_thread_registry_cond");
}
child_thread_registry_inited = true;
}
static void libuv_thread_registry_add(zend_async_thread_handle_t handle)
{
libuv_thread_registry_init();
uv_mutex_lock(&child_thread_registry_mutex);
/* value payload is unused — the key alone is what we track */
zval placeholder;
ZVAL_NULL(&placeholder);
zend_hash_index_add(&child_thread_registry, (zend_ulong) handle, &placeholder);
uv_mutex_unlock(&child_thread_registry_mutex);
}
static void libuv_thread_registry_remove(zend_async_thread_handle_t handle)
{
if (!child_thread_registry_inited) {
return;
}
uv_mutex_lock(&child_thread_registry_mutex);
zend_hash_index_del(&child_thread_registry, (zend_ulong) handle);
if (zend_hash_num_elements(&child_thread_registry) == 0) {
uv_cond_broadcast(&child_thread_registry_cond);
}
uv_mutex_unlock(&child_thread_registry_mutex);
}
/* {{{ libuv_reactor_quiesce — block until every child thread has
* released TSRM. Called from main thread at the very top of
* php_module_shutdown, before any module gets destroyed. */
static void libuv_reactor_quiesce(void)
{
#ifdef ZTS
ZEND_ASSERT(tsrm_is_main_thread());
#endif
if (!child_thread_registry_inited) {
return;
}
uv_mutex_lock(&child_thread_registry_mutex);
while (zend_hash_num_elements(&child_thread_registry) > 0) {
uv_cond_wait(&child_thread_registry_cond, &child_thread_registry_mutex);
}
uv_mutex_unlock(&child_thread_registry_mutex);
}
/* }}} */
/* Exposed to thread.c so child threads can self-remove after ts_free_thread. */
void async_libuv_thread_registry_remove(zend_async_thread_handle_t handle)
{
libuv_thread_registry_remove(handle);
}
///////////////////////////////////////////////////////////
/// Event info methods for deadlock diagnostics
///////////////////////////////////////////////////////////
static const char *io_type_name(const zend_async_io_type type)
{
switch (type) {
case ZEND_ASYNC_IO_TYPE_PIPE:
return "pipe";
case ZEND_ASYNC_IO_TYPE_FILE:
return "file";
case ZEND_ASYNC_IO_TYPE_TCP:
return "tcp";
case ZEND_ASYNC_IO_TYPE_UDP:
return "udp";
case ZEND_ASYNC_IO_TYPE_TTY:
return "tty";
default:
return "unknown";
}
}
static zend_string *libuv_poll_info(zend_async_event_t *event)
{
const zend_async_poll_event_t *poll = (zend_async_poll_event_t *) event;
if (poll->is_socket) {
return zend_strpprintf(0,
"Poll(socket=" ZEND_LONG_FMT ", events=%s%s)",
(zend_long) poll->socket,
(poll->events & ASYNC_READABLE) ? "r" : "",
(poll->events & ASYNC_WRITABLE) ? "w" : "");
}
return zend_strpprintf(0,
"Poll(fd=" ZEND_LONG_FMT ", events=%s%s)",
(zend_long) poll->file,
(poll->events & ASYNC_READABLE) ? "r" : "",
(poll->events & ASYNC_WRITABLE) ? "w" : "");
}
static zend_string *libuv_poll_proxy_info(zend_async_event_t *event)
{
const zend_async_poll_proxy_t *proxy = (zend_async_poll_proxy_t *) event;
return zend_strpprintf(0,
"PollProxy(events=%s%s)",
(proxy->events & ASYNC_READABLE) ? "r" : "",
(proxy->events & ASYNC_WRITABLE) ? "w" : "");
}
static zend_string *libuv_timer_info(zend_async_event_t *event)
{
const zend_async_timer_event_t *timer = (zend_async_timer_event_t *) event;
return zend_strpprintf(0, "Timer(timeout=%ums, %s)", timer->timeout, timer->is_periodic ? "periodic" : "once");
}
static zend_string *libuv_signal_info(zend_async_event_t *event)
{
const zend_async_signal_event_t *signal = (zend_async_signal_event_t *) event;
return zend_strpprintf(0, "Signal(signum=%d)", signal->signal);
}
static zend_string *libuv_process_info(zend_async_event_t *event)
{
const zend_async_process_event_t *proc = (zend_async_process_event_t *) event;
return zend_strpprintf(0, "Process(pid=" ZEND_LONG_FMT ")", (zend_long) proc->process);
}
static zend_string *libuv_filesystem_info(zend_async_event_t *event)
{
const zend_async_filesystem_event_t *fs = (zend_async_filesystem_event_t *) event;
return zend_strpprintf(0, "FilesystemWatch(path=%s)", fs->path ? ZSTR_VAL(fs->path) : "<null>");
}
static zend_string *libuv_dns_nameinfo_info(zend_async_event_t *event)
{
return zend_string_init(ZEND_STRL("DNSNameInfo"), 0);
}
static zend_string *libuv_dns_addrinfo_info(zend_async_event_t *event)
{
const zend_async_dns_addrinfo_t *addr = (zend_async_dns_addrinfo_t *) event;
return zend_strpprintf(0,
"DNSAddrInfo(node=%s, service=%s)",
addr->node ? addr->node : "<null>",
addr->service ? addr->service : "<null>");
}
static zend_string *libuv_exec_info(zend_async_event_t *event)
{
const zend_async_exec_event_t *exec = (zend_async_exec_event_t *) event;
return zend_strpprintf(0, "Exec(cmd=%.80s)", exec->cmd ? exec->cmd : "<null>");
}
static zend_string *libuv_trigger_info(zend_async_event_t *event)
{
return zend_string_init(ZEND_STRL("Trigger"), 0);
}
static zend_string *libuv_io_info(zend_async_event_t *event)
{
const async_io_t *aio = (async_io_t *) event;
const zend_async_io_t *io = &aio->base;
if (io->type == ZEND_ASYNC_IO_TYPE_TCP || io->type == ZEND_ASYNC_IO_TYPE_UDP) {
return zend_strpprintf(
0, "IO(type=%s, socket=" ZEND_LONG_FMT ")", io_type_name(io->type), (zend_long) io->descriptor.socket);
}
return zend_strpprintf(
0, "IO(type=%s, fd=" ZEND_LONG_FMT ")", io_type_name(io->type), (zend_long) io->descriptor.fd);
}
static zend_string *libuv_listen_info(zend_async_event_t *event)
{
const zend_async_listen_event_t *listen = (zend_async_listen_event_t *) event;
return zend_strpprintf(0, "Listen(host=%s, port=%d)", listen->host ? listen->host : "<null>", listen->port);
}
static zend_string *libuv_task_info(zend_async_event_t *event)
{
return zend_string_init(ZEND_STRL("ThreadPoolTask"), 0);
}
#define UVLOOP (&ASYNC_G(uvloop))
#define LIBUV_REACTOR ((zend_async_globals *) ASYNC_GLOBALS)
#define LIBUV_REACTOR_VAR zend_async_globals *reactor = LIBUV_REACTOR;
#define LIBUV_REACTOR_VAR_FROM(var) zend_async_globals *reactor = (zend_async_globals *) var;
#define WATCHER ASYNC_G(watcherThread)
#define IF_EXCEPTION_STOP_REACTOR \
if (UNEXPECTED(EG(exception) != NULL)) { \
libuv_reactor_stop_with_exception(); \
}
#define ASYNC_OF_EXCEPTION_MESSAGE "Async mode is disabled. Reactor API cannot be used."
#define START_REACTOR_OR_RETURN \
if (UNEXPECTED(ASYNC_G(reactor_started) == false)) { \
libuv_reactor_startup(); \
if (UNEXPECTED(EG(exception) != NULL)) { \
return NULL; \
} \
}
#define START_REACTOR_OR_RETURN_NULL \
if (UNEXPECTED(ASYNC_G(reactor_started) == false)) { \
libuv_reactor_startup(); \
if (UNEXPECTED(EG(exception) != NULL)) { \
return NULL; \
} \
}
#define EVENT_START_PROLOGUE(event) \
if (UNEXPECTED(ZEND_ASYNC_EVENT_IS_CLOSED(event))) { \
return true; \
} \
if (event->loop_ref_count > 0) { \
event->loop_ref_count++; \
return true; \
}
#define EVENT_STOP_PROLOGUE(event) \
if (event->loop_ref_count > 1) { \
event->loop_ref_count--; \
if (UNEXPECTED(ZEND_ASYNC_EVENT_IS_CLOSED(event))) { \
event->loop_ref_count = 0; \
} else { \
return true; \
} \
} \
if (UNEXPECTED(ZEND_ASYNC_EVENT_IS_CLOSED(event))) { \
event->loop_ref_count = 0; \
return true; \
}
static zend_always_inline void close_event(zend_async_event_t *event)
{
if (event->loop_ref_count > 0) {
event->loop_ref_count = 1;
event->stop(event);
ZEND_ASYNC_EVENT_SET_CLOSED(event);
}
}
/* {{{ libuv_reactor_startup */
bool libuv_reactor_startup(void)
{
if (ASYNC_G(reactor_started)) {
return true;
}
if (ZEND_ASYNC_IS_OFF) {
async_throw_error(ASYNC_OF_EXCEPTION_MESSAGE);
return false;
}
const int result = uv_loop_init(UVLOOP);
if (result != 0) {
async_throw_error("Failed to initialize loop: %s", uv_strerror(result));
return false;
}
uv_loop_set_data(UVLOOP, ASYNC_GLOBALS);
zend_hash_init(&ASYNC_G(active_io_handles), 16, NULL, NULL, 0);
ASYNC_G(reactor_started) = true;
return true;
}
/* }}} */
/* {{{ libuv_reactor_stop_with_exception */
static void libuv_reactor_stop_with_exception(void)
{
// TODO: implement libuv_reactor_stop_with_exception
}
/* }}} */
/* }}} */
/* {{{ libuv_reactor_shutdown */
bool libuv_reactor_shutdown(void)
{
if (EXPECTED(ASYNC_G(reactor_started))) {
// Cleanup global signal management structures
libuv_cleanup_signal_handlers();
libuv_cleanup_signal_events();
libuv_cleanup_process_events();
/* Drain pending uv_close callbacks (e.g. poll events disposed
* during shutdown_executor via curl free_obj). */
int alive = uv_loop_alive(UVLOOP);
if (alive != 0) {
uv_run(UVLOOP, UV_RUN_NOWAIT);
}
uv_loop_close(UVLOOP);
ASYNC_G(reactor_started) = false;
zend_hash_destroy(&ASYNC_G(active_io_handles));
}
return true;
}
/* }}} */
/* {{{ libuv_reactor_execute */
bool libuv_reactor_execute(bool no_wait)
{
// OPTIMIZATION: Skip uv_run() if no libuv handles to avoid unnecessary clock_gettime() calls
if (!uv_loop_alive(UVLOOP)) {
return false;
}
const bool has_handles = uv_run(UVLOOP, no_wait ? UV_RUN_NOWAIT : UV_RUN_ONCE);
return has_handles && ZEND_ASYNC_ACTIVE_EVENT_COUNT > 0;
}
/* }}} */
/* {{{ libuv_reactor_loop_alive */
bool libuv_reactor_loop_alive(void)
{
if (!ASYNC_G(reactor_started)) {
return false;
}
return ZEND_ASYNC_ACTIVE_EVENT_COUNT > 0 && uv_loop_alive(UVLOOP) != 0;
}
/* }}} */
/* {{{ libuv_close_handle_cb */
static void libuv_close_handle_cb(uv_handle_t *handle)
{
pefree(handle->data, 0);
}
/* }}} */
/* {{{ libuv_close_poll_handle_cb */
static void libuv_close_poll_handle_cb(uv_handle_t *handle)
{
async_poll_event_t *poll = (async_poll_event_t *) handle->data;
/* Check if PHP requested descriptor closure after event cleanup */
if (ZEND_ASYNC_EVENT_SHOULD_CLOSE_FD(&poll->event.base)) {
if (poll->event.is_socket && ZEND_VALID_SOCKET(poll->event.socket)) {
/* Socket cleanup - just close, no blocking operations in LibUV callback */
#ifdef PHP_WIN32
closesocket(poll->event.socket);
#else
close(poll->event.socket);
#endif
} else if (!poll->event.is_socket && poll->event.file != ZEND_FD_NULL) {
/* File descriptor cleanup — zend_file_descriptor_t is CRT fd on all platforms */
close(poll->event.file);
}
}
pefree(poll, 0);
}
/* }}} */
/* {{{ libuv_add_callback */
static bool libuv_add_callback(zend_async_event_t *event, zend_async_event_callback_t *callback)
{
return zend_async_callbacks_push(event, callback);
}
/* }}} */
/* {{{ libuv_remove_callback */
static bool libuv_remove_callback(zend_async_event_t *event, zend_async_event_callback_t *callback)
{
return zend_async_callbacks_remove(event, callback);
}
/* }}} */
/////////////////////////////////////////////////////////////////////////////
/// Poll API
//////////////////////////////////////////////////////////////////////////////
/* Forward declaration */
static zend_always_inline void
async_poll_notify_proxies(async_poll_event_t *poll, async_poll_event triggered_events, zend_object *exception);
/* {{{ on_poll_event */
static void on_poll_event(uv_poll_t *handle, int status, int events)
{
async_poll_event_t *poll = handle->data;
zend_object *exception = NULL;
if (status < 0 && status != UV_EBADF) {
exception = async_new_exception(async_ce_input_output_exception, "Input output error: %s", uv_strerror(status));
}
// !WARNING!
// LibUV may return the UV_EBADF code when the remote host closes
// the connection while the descriptor is still present in the EventLoop.
// For POLL events, we handle this by ignoring the situation
// so that the coroutine receives the ASYNC_DISCONNECT flag.
// This code can be considered "incorrect"; however, this solution is acceptable.
//
if (UNEXPECTED(status == UV_EBADF)) {
events = ASYNC_DISCONNECT;
}
/* Filter spurious READABLE events on sockets.
* libuv uv_poll may signal readable when no data is actually available.
* Use recv(MSG_PEEK) to verify; if WOULDBLOCK — remove the flag. */
if (status >= 0 && poll->event.is_socket && (events & ASYNC_READABLE)) {
char peek_buf;
const int peek_ret = recv(poll->event.socket, &peek_buf, 1, MSG_PEEK);
if (peek_ret < 0) {
#ifdef PHP_WIN32
const int err = WSAGetLastError();
if (err == WSAEWOULDBLOCK) {
events &= ~ASYNC_READABLE;
}
#else
if (errno == EAGAIN
#if EAGAIN != EWOULDBLOCK
|| errno == EWOULDBLOCK
#endif
) {
events &= ~ASYNC_READABLE;
}
#endif
if (events == 0) {
return;
}
}
}
poll->event.triggered_events = events;
/* Check if there are active proxies */
if (poll->proxies_count > 0) {
/* Notify all matching proxies */
async_poll_notify_proxies(poll, events, exception);
} else {
/* Standard base event notification */
ZEND_ASYNC_CALLBACKS_NOTIFY(&poll->event.base, NULL, exception);
}
if (exception != NULL) {
zend_object_release(exception);
}
IF_EXCEPTION_STOP_REACTOR;
}
/* }}} */
/* {{{ libuv_poll_start */
static bool libuv_poll_start(zend_async_event_t *event)
{
EVENT_START_PROLOGUE(event);
async_poll_event_t *poll = (async_poll_event_t *) (event);
const int error = uv_poll_start(&poll->uv_handle, poll->event.events, on_poll_event);
if (error < 0) {
async_throw_error("Failed to start poll handle: %s", uv_strerror(error));
return false;
}
event->loop_ref_count++;
ZEND_ASYNC_INCREASE_EVENT_COUNT(event);
return true;
}
/* }}} */
/* {{{ libuv_poll_stop */
static bool libuv_poll_stop(zend_async_event_t *event)
{
EVENT_STOP_PROLOGUE(event);
async_poll_event_t *poll = (async_poll_event_t *) (event);
const int error = uv_poll_stop(&poll->uv_handle);
event->loop_ref_count = 0;
ZEND_ASYNC_DECREASE_EVENT_COUNT(event);
if (error < 0) {
async_throw_error("Failed to stop poll handle: %s", uv_strerror(error));
return false;
}
return true;
}
/* }}} */
/* {{{ libuv_poll_dispose */
static bool libuv_poll_dispose(zend_async_event_t *event)
{
if (ZEND_ASYNC_EVENT_REFCOUNT(event) > 1) {
ZEND_ASYNC_EVENT_DEL_REF(event);
return true;
}
if (event->loop_ref_count > 0) {
event->loop_ref_count = 1;
event->stop(event);
}
zend_async_callbacks_free(event);
async_poll_event_t *poll = (async_poll_event_t *) (event);
/* Free proxies array if exists */
if (poll->proxies != NULL) {
pefree(poll->proxies, 0);
poll->proxies = NULL;
}
/* Use poll-specific callback for poll events that may need descriptor cleanup.
* If the reactor is already shut down, uv_close cannot run — free directly. */
if (UNEXPECTED(!ASYNC_G(reactor_started))) {
pefree(poll, 0);
} else {
uv_close((uv_handle_t *) &poll->uv_handle, libuv_close_poll_handle_cb);
}
return true;
}
/* }}} */
/* {{{ async_poll_notify_proxies */
static zend_always_inline void
async_poll_notify_proxies(async_poll_event_t *poll, async_poll_event triggered_events, zend_object *exception)
{
/* Process each proxy that matches triggered events */
for (uint32_t i = 0; i < poll->proxies_count; i++) {
zend_async_poll_proxy_t *proxy = poll->proxies[i];
if ((triggered_events & proxy->events) != 0) {
/* Increase ref count to prevent disposal during processing */
ZEND_ASYNC_EVENT_ADD_REF(&proxy->base);
/* Calculate events relevant to this proxy */
async_poll_event proxy_events = triggered_events & proxy->events;
/* Set triggered events and notify callbacks */
proxy->triggered_events = proxy_events;
ZEND_ASYNC_CALLBACKS_NOTIFY_FROM_HANDLER(&proxy->base, &proxy_events, exception);
/* Release reference after processing */
ZEND_ASYNC_EVENT_RELEASE(&proxy->base);
}
}
}
/* }}} */
/* {{{ async_poll_add_proxy */
static zend_always_inline void async_poll_add_proxy(async_poll_event_t *poll, zend_async_poll_proxy_t *proxy)
{
if (poll->proxies == NULL) {
poll->proxies = (zend_async_poll_proxy_t **) pecalloc(4, sizeof(zend_async_poll_proxy_t *), 0);
poll->proxies_capacity = 2;
}
if (poll->proxies_count == poll->proxies_capacity) {
poll->proxies_capacity *= 2;
poll->proxies = (zend_async_poll_proxy_t **) perealloc(
poll->proxies, poll->proxies_capacity * sizeof(zend_async_poll_proxy_t *), 0);
}
poll->proxies[poll->proxies_count++] = proxy;
}
/* }}} */
/* {{{ async_poll_remove_proxy */
static zend_always_inline void async_poll_remove_proxy(async_poll_event_t *poll, zend_async_poll_proxy_t *proxy)
{
for (uint32_t i = 0; i < poll->proxies_count; i++) {
if (poll->proxies[i] == proxy) {
/* Move last element to this position */
poll->proxies[i] = poll->proxies[--poll->proxies_count];
break;
}
}
}
/* }}} */
/* {{{ async_poll_aggregate_events */
static zend_always_inline async_poll_event async_poll_aggregate_events(async_poll_event_t *poll)
{
async_poll_event aggregated = 0;
for (uint32_t i = 0; i < poll->proxies_count; i++) {
aggregated |= poll->proxies[i]->events;
/* Early exit if all possible events are set */
if (aggregated == (ASYNC_READABLE | ASYNC_WRITABLE | ASYNC_DISCONNECT | ASYNC_PRIORITIZED)) {
break;
}
}
return aggregated;
}
/* }}} */
/* {{{ libuv_poll_proxy_start */
static bool libuv_poll_proxy_start(zend_async_event_t *event)
{
EVENT_START_PROLOGUE(event);
zend_async_poll_proxy_t *proxy = (zend_async_poll_proxy_t *) event;
async_poll_event_t *poll = (async_poll_event_t *) proxy->poll_event;
/* Add proxy to the array */
async_poll_add_proxy(poll, proxy);
/* Check if all proxy events are already set in base event */
if ((poll->event.events & proxy->events) != proxy->events) {
/* Add missing proxy events to base event */
poll->event.events |= proxy->events;
const int error = uv_poll_start(&poll->uv_handle, poll->event.events, on_poll_event);
if (error < 0) {
async_throw_error("Failed to update poll handle events: %s", uv_strerror(error));
return false;
}
}
ZEND_ASYNC_INCREASE_EVENT_COUNT(event);
event->loop_ref_count = 1;
return true;
}
/* }}} */
/* {{{ libuv_poll_proxy_stop */
static bool libuv_poll_proxy_stop(zend_async_event_t *event)
{
EVENT_STOP_PROLOGUE(event);
zend_async_poll_proxy_t *proxy = (zend_async_poll_proxy_t *) event;
async_poll_event_t *poll = (async_poll_event_t *) proxy->poll_event;
/* Remove proxy from the array */
async_poll_remove_proxy(poll, proxy);
/* Recalculate events from remaining proxies */
async_poll_event new_events = async_poll_aggregate_events(poll);
/* Update base event */
if (poll->event.events != new_events && poll->event.base.ref_count > 1) {
poll->event.events = new_events;
/* Restart with new events */
const int error = uv_poll_start(&poll->uv_handle, new_events, on_poll_event);
if (error < 0) {
async_throw_error("Failed to update poll handle events: %s", uv_strerror(error));
}
}
event->loop_ref_count = 0;
ZEND_ASYNC_DECREASE_EVENT_COUNT(event);
return true;
}
/* }}} */
/* {{{ libuv_poll_proxy_dispose */
static bool libuv_poll_proxy_dispose(zend_async_event_t *event)
{
if (ZEND_ASYNC_EVENT_REFCOUNT(event) > 1) {
ZEND_ASYNC_EVENT_DEL_REF(event);
return true;
}
zend_async_poll_proxy_t *proxy = (zend_async_poll_proxy_t *) event;
async_poll_event_t *poll = (async_poll_event_t *) proxy->poll_event;
if (event->loop_ref_count > 0) {
event->loop_ref_count = 1;
event->stop(event);
}
zend_async_callbacks_free(event);
/* Release reference to base poll event */
ZEND_ASYNC_EVENT_RELEASE(&poll->event.base);
pefree(proxy, 0);
return true;
}
/* }}} */
/* {{{ libuv_new_poll_event */
zend_async_poll_event_t *
libuv_new_poll_event(zend_file_descriptor_t fh, zend_socket_t socket, async_poll_event events, size_t extra_size)
{
START_REACTOR_OR_RETURN_NULL;
async_poll_event_t *poll =
pecalloc(1, extra_size != 0 ? sizeof(async_poll_event_t) + extra_size : sizeof(async_poll_event_t), 0);
int error = 0;
if (socket != 0) {
error = uv_poll_init_socket(UVLOOP, &poll->uv_handle, socket);
poll->event.is_socket = true;
poll->event.socket = socket;
} else if (fh != ZEND_FD_NULL) {
#ifdef PHP_WIN32
async_throw_error("Windows does not support file descriptor polling");
pefree(poll, 0);
return NULL;
#else
error = uv_poll_init(UVLOOP, &poll->uv_handle, (int) fh);
poll->event.is_socket = false;
poll->event.file = fh;
#endif
} else {
}
if (error < 0) {
async_throw_error("Failed to initialize poll handle: %s", uv_strerror(error));
pefree(poll, 0);
return NULL;
}
// Link the handle to the loop.
poll->uv_handle.data = poll;
poll->event.events = events;
poll->event.base.extra_offset = sizeof(async_poll_event_t);
poll->event.base.ref_count = 1;
// Initialize the event methods
poll->event.base.add_callback = libuv_add_callback;
poll->event.base.del_callback = libuv_remove_callback;
poll->event.base.start = libuv_poll_start;
poll->event.base.stop = libuv_poll_stop;
poll->event.base.dispose = libuv_poll_dispose;
poll->event.base.info = libuv_poll_info;
return &poll->event;
}
/* }}} */
/* {{{ libuv_new_socket_event */
zend_async_poll_event_t *libuv_new_socket_event(zend_socket_t socket, async_poll_event events, size_t extra_size)
{
return libuv_new_poll_event(ZEND_FD_NULL, socket, events, extra_size);
}
/* }}} */
/* {{{ libuv_new_poll_proxy_event */
zend_async_poll_proxy_t *
libuv_new_poll_proxy_event(zend_async_poll_event_t *poll_event, async_poll_event events, size_t extra_size)
{
START_REACTOR_OR_RETURN_NULL;
zend_async_poll_proxy_t *proxy = pecalloc(
1, extra_size != 0 ? sizeof(zend_async_poll_proxy_t) + extra_size : sizeof(zend_async_poll_proxy_t), 0);
/* Set up proxy */
proxy->poll_event = poll_event;
proxy->events = events;
/* Add reference to base poll event */
ZEND_ASYNC_EVENT_ADD_REF(&poll_event->base);
/* Initialize base event structure */
proxy->base.extra_offset = sizeof(zend_async_poll_proxy_t);
proxy->base.ref_count = 1;
/* Initialize proxy methods */
proxy->base.add_callback = libuv_add_callback;
proxy->base.del_callback = libuv_remove_callback;
proxy->base.start = libuv_poll_proxy_start;
proxy->base.stop = libuv_poll_proxy_stop;
proxy->base.dispose = libuv_poll_proxy_dispose;
proxy->base.info = libuv_poll_proxy_info;
return proxy;
}
/* }}} */
/////////////////////////////////////////////////////////////////////////////////
/// Timer API
/////////////////////////////////////////////////////////////////////////////////
/* {{{ on_timer_event */
static void on_timer_event(uv_timer_t *handle)
{
async_timer_event_t *timer_event = handle->data;
// If the timer is not periodic, we close it after the first execution.
if (false == timer_event->event.is_periodic) {
close_event(&timer_event->event.base);
}
ZEND_ASYNC_CALLBACKS_NOTIFY(&timer_event->event.base, NULL, NULL);
IF_EXCEPTION_STOP_REACTOR;
}
/* }}} */
/* {{{ libuv_timer_start */
static bool libuv_timer_start(zend_async_event_t *event)
{
EVENT_START_PROLOGUE(event);
async_timer_event_t *timer = (async_timer_event_t *) (event);
const int error = uv_timer_start(&timer->uv_handle,
on_timer_event,
timer->event.timeout,
timer->event.is_periodic ? timer->event.timeout : 0);
if (error < 0) {
async_throw_error("Failed to start timer handle: %s", uv_strerror(error));
return false;
}
event->loop_ref_count++;
ZEND_ASYNC_INCREASE_EVENT_COUNT(event);
return true;
}
/* }}} */
/* {{{ libuv_timer_stop */
static bool libuv_timer_stop(zend_async_event_t *event)
{
EVENT_STOP_PROLOGUE(event);
async_timer_event_t *timer = (async_timer_event_t *) (event);
const int error = uv_timer_stop(&timer->uv_handle);
event->loop_ref_count = 0;
ZEND_ASYNC_DECREASE_EVENT_COUNT(event);
if (error < 0) {
async_throw_error("Failed to stop timer handle: %s", uv_strerror(error));
return false;
}
return true;
}
/* }}} */
/* {{{ libuv_timer_dispose */
static bool libuv_timer_dispose(zend_async_event_t *event)
{