-
Notifications
You must be signed in to change notification settings - Fork 177
/
Copy pathlwt_unix_stubs.c
1217 lines (986 loc) · 33.9 KB
/
lwt_unix_stubs.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
/* This file is part of Lwt, released under the MIT license. See LICENSE.md for
details, or visit https://github.com/ocsigen/lwt/blob/master/LICENSE.md. */
#include "lwt_config.h"
#define _GNU_SOURCE
#define _POSIX_PTHREAD_SEMANTICS
#include <caml/alloc.h>
#include <caml/bigarray.h>
#include <caml/callback.h>
#include <caml/config.h>
#include <caml/custom.h>
#include <caml/fail.h>
#include <caml/memory.h>
#include <caml/mlvalues.h>
#include <caml/signals.h>
#include <assert.h>
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include "lwt_unix.h"
#if !defined(LWT_ON_WINDOWS)
#include <arpa/inet.h>
#include <dirent.h>
#include <fcntl.h>
#include <grp.h>
#include <netdb.h>
#include <netinet/in.h>
#include <pwd.h>
#include <sched.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/un.h>
#include <termios.h>
#include <unistd.h>
#endif
#if defined(HAVE_EVENTFD)
#include <sys/eventfd.h>
#endif
//#define DEBUG_MODE
#if defined(DEBUG_MODE)
#include <sys/syscall.h>
#define DEBUG(fmt, ...) \
{ \
fprintf(stderr, "lwt-debug[%d]: %s: " fmt "\n", \
(pid_t)syscall(SYS_gettid), __FUNCTION__, ##__VA_ARGS__); \
fflush(stderr); \
}
#else
#define DEBUG(fmt, ...)
#endif
/* +-----------------------------------------------------------------+
| Utils |
+-----------------------------------------------------------------+ */
void *lwt_unix_malloc(size_t size) {
void *ptr = malloc(size);
if (ptr == NULL) {
perror("cannot allocate memory");
abort();
}
return ptr;
}
void *lwt_unix_realloc(void *ptr, size_t size) {
void *new_ptr = realloc(ptr, size);
if (new_ptr == NULL) {
perror("cannot allocate memory");
abort();
}
return new_ptr;
}
char *lwt_unix_strdup(char *str) {
char *new_str = strdup(str);
if (new_str == NULL) {
perror("cannot allocate memory");
abort();
}
return new_str;
}
void lwt_unix_not_available(char const *feature) {
caml_raise_with_arg(*caml_named_value("lwt:not-available"),
caml_copy_string(feature));
}
/* +-----------------------------------------------------------------+
| Operation on bigarrays |
+-----------------------------------------------------------------+ */
CAMLprim value lwt_unix_blit(value val_buf1, value val_ofs1, value val_buf2,
value val_ofs2, value val_len) {
memmove((char *)Caml_ba_data_val(val_buf2) + Long_val(val_ofs2),
(char *)Caml_ba_data_val(val_buf1) + Long_val(val_ofs1),
Long_val(val_len));
return Val_unit;
}
CAMLprim value lwt_unix_blit_from_bytes(value val_buf1, value val_ofs1,
value val_buf2, value val_ofs2,
value val_len) {
memcpy((char *)Caml_ba_data_val(val_buf2) + Long_val(val_ofs2),
Bytes_val(val_buf1) + Long_val(val_ofs1), Long_val(val_len));
return Val_unit;
}
CAMLprim value lwt_unix_blit_from_string(value val_buf1, value val_ofs1,
value val_buf2, value val_ofs2,
value val_len) {
memcpy((char *)Caml_ba_data_val(val_buf2) + Long_val(val_ofs2),
String_val(val_buf1) + Long_val(val_ofs1), Long_val(val_len));
return Val_unit;
}
CAMLprim value lwt_unix_blit_to_bytes(value val_buf1, value val_ofs1,
value val_buf2, value val_ofs2,
value val_len) {
memcpy(Bytes_val(val_buf2) + Long_val(val_ofs2),
(char *)Caml_ba_data_val(val_buf1) + Long_val(val_ofs1),
Long_val(val_len));
return Val_unit;
}
CAMLprim value lwt_unix_fill_bytes(value val_buf, value val_ofs, value val_len,
value val_char) {
memset((char *)Caml_ba_data_val(val_buf) + Long_val(val_ofs),
Int_val(val_char), Long_val(val_len));
return Val_unit;
}
CAMLprim value lwt_unix_mapped(value v_bstr) {
return Val_bool(Caml_ba_array_val(v_bstr)->flags & CAML_BA_MAPPED_FILE);
}
/* +-----------------------------------------------------------------+
| Byte order |
+-----------------------------------------------------------------+ */
value lwt_unix_system_byte_order() {
#ifdef ARCH_BIG_ENDIAN
return Val_int(1);
#else
return Val_int(0);
#endif
}
/* +-----------------------------------------------------------------+
| Threading |
+-----------------------------------------------------------------+ */
#if defined(HAVE_PTHREAD)
int lwt_unix_launch_thread(void *(*start)(void *), void *data) {
pthread_t thread;
pthread_attr_t attr;
sigset_t mask, old_mask;
pthread_attr_init(&attr);
/* The thread is created in detached state so we do not have to join
it when it terminates: */
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
/* Block all signals, otherwise ocaml handlers defined with the
module Sys may be executed in the new thread, oops... */
sigfillset(&mask);
pthread_sigmask(SIG_SETMASK, &mask, &old_mask);
int zero_if_created_otherwise_errno =
pthread_create(&thread, &attr, start, data);
/* Restore the signal mask for the calling thread. */
pthread_sigmask(SIG_SETMASK, &old_mask, NULL);
pthread_attr_destroy(&attr);
return zero_if_created_otherwise_errno;
}
lwt_unix_thread lwt_unix_thread_self() { return pthread_self(); }
int lwt_unix_thread_equal(lwt_unix_thread thread1, lwt_unix_thread thread2) {
return pthread_equal(thread1, thread2);
}
void lwt_unix_mutex_init(lwt_unix_mutex *mutex) {
pthread_mutex_init(mutex, NULL);
}
void lwt_unix_mutex_destroy(lwt_unix_mutex *mutex) {
pthread_mutex_destroy(mutex);
}
void lwt_unix_mutex_lock(lwt_unix_mutex *mutex) { pthread_mutex_lock(mutex); }
void lwt_unix_mutex_unlock(lwt_unix_mutex *mutex) {
pthread_mutex_unlock(mutex);
}
void lwt_unix_condition_init(lwt_unix_condition *condition) {
pthread_cond_init(condition, NULL);
}
void lwt_unix_condition_destroy(lwt_unix_condition *condition) {
pthread_cond_destroy(condition);
}
void lwt_unix_condition_signal(lwt_unix_condition *condition) {
pthread_cond_signal(condition);
}
void lwt_unix_condition_broadcast(lwt_unix_condition *condition) {
pthread_cond_broadcast(condition);
}
void lwt_unix_condition_wait(lwt_unix_condition *condition,
lwt_unix_mutex *mutex) {
pthread_cond_wait(condition, mutex);
}
#elif defined(LWT_ON_WINDOWS)
int lwt_unix_launch_thread(void *(*start)(void *), void *data) {
HANDLE handle =
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)start, data, 0, NULL);
if (handle)
CloseHandle(handle);
return 0;
}
lwt_unix_thread lwt_unix_thread_self() { return GetCurrentThreadId(); }
int lwt_unix_thread_equal(lwt_unix_thread thread1, lwt_unix_thread thread2) {
return thread1 == thread2;
}
void lwt_unix_mutex_init(lwt_unix_mutex *mutex) {
InitializeCriticalSection(mutex);
}
void lwt_unix_mutex_destroy(lwt_unix_mutex *mutex) {
DeleteCriticalSection(mutex);
}
void lwt_unix_mutex_lock(lwt_unix_mutex *mutex) { EnterCriticalSection(mutex); }
void lwt_unix_mutex_unlock(lwt_unix_mutex *mutex) {
LeaveCriticalSection(mutex);
}
struct wait_list {
HANDLE event;
struct wait_list *next;
};
struct lwt_unix_condition {
CRITICAL_SECTION mutex;
struct wait_list *waiters;
};
void lwt_unix_condition_init(lwt_unix_condition *condition) {
InitializeCriticalSection(&condition->mutex);
condition->waiters = NULL;
}
void lwt_unix_condition_destroy(lwt_unix_condition *condition) {
DeleteCriticalSection(&condition->mutex);
}
void lwt_unix_condition_signal(lwt_unix_condition *condition) {
struct wait_list *node;
EnterCriticalSection(&condition->mutex);
node = condition->waiters;
if (node) {
condition->waiters = node->next;
SetEvent(node->event);
}
LeaveCriticalSection(&condition->mutex);
}
void lwt_unix_condition_broadcast(lwt_unix_condition *condition) {
struct wait_list *node;
EnterCriticalSection(&condition->mutex);
for (node = condition->waiters; node; node = node->next)
SetEvent(node->event);
condition->waiters = NULL;
LeaveCriticalSection(&condition->mutex);
}
void lwt_unix_condition_wait(lwt_unix_condition *condition,
lwt_unix_mutex *mutex) {
struct wait_list node;
/* Create the event for the notification. */
node.event = CreateEvent(NULL, FALSE, FALSE, NULL);
/* Add the node to the condition. */
EnterCriticalSection(&condition->mutex);
node.next = condition->waiters;
condition->waiters = &node;
LeaveCriticalSection(&condition->mutex);
/* Release the mutex. */
LeaveCriticalSection(mutex);
/* Wait for a signal. */
WaitForSingleObject(node.event, INFINITE);
/* The event is no more used. */
CloseHandle(node.event);
/* Re-acquire the mutex. */
EnterCriticalSection(mutex);
}
#else
#error "no threading library available!"
#endif
/* +-----------------------------------------------------------------+
| Socketpair on windows |
+-----------------------------------------------------------------+ */
#if defined(LWT_ON_WINDOWS)
#if OCAML_VERSION < 41400
static int win_set_inherit(HANDLE fd, BOOL inherit)
{
if (! SetHandleInformation(fd,
HANDLE_FLAG_INHERIT,
inherit ? HANDLE_FLAG_INHERIT : 0)) {
win32_maperr(GetLastError());
return -1;
}
return 0;
}
#endif
static SOCKET lwt_win_socket(int domain, int type, int protocol,
LPWSAPROTOCOL_INFO info,
BOOL inherit)
{
SOCKET s;
DWORD flags = WSA_FLAG_OVERLAPPED;
#ifndef WSA_FLAG_NO_HANDLE_INHERIT
#define WSA_FLAG_NO_HANDLE_INHERIT 0x80
#endif
if (! inherit)
flags |= WSA_FLAG_NO_HANDLE_INHERIT;
s = WSASocket(domain, type, protocol, info, 0, flags);
if (s == INVALID_SOCKET) {
if (! inherit && WSAGetLastError() == WSAEINVAL) {
/* WSASocket probably doesn't suport WSA_FLAG_NO_HANDLE_INHERIT,
* retry without. */
flags &= ~(DWORD)WSA_FLAG_NO_HANDLE_INHERIT;
s = WSASocket(domain, type, protocol, info, 0, flags);
if (s == INVALID_SOCKET)
goto err;
win_set_inherit((HANDLE) s, FALSE);
return s;
}
goto err;
}
return s;
err:
win32_maperr(WSAGetLastError());
return INVALID_SOCKET;
}
static void lwt_unix_socketpair(int domain, int type, int protocol,
SOCKET sockets[2], BOOL inherit) {
union {
struct sockaddr_in inaddr;
struct sockaddr_in6 inaddr6;
struct sockaddr addr;
} a;
SOCKET listener;
int addrlen;
int reuse = 1;
DWORD err;
if (domain != PF_INET && domain != PF_INET6)
unix_error(ENOPROTOOPT, "socketpair", Nothing);
sockets[0] = INVALID_SOCKET;
sockets[1] = INVALID_SOCKET;
listener = lwt_win_socket(domain, type, protocol, NULL, inherit);
if (listener == INVALID_SOCKET) goto failure;
memset(&a, 0, sizeof(a));
if (domain == PF_INET) {
a.inaddr.sin_family = domain;
a.inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
a.inaddr.sin_port = 0;
} else {
a.inaddr6.sin6_family = domain;
a.inaddr6.sin6_addr = in6addr_loopback;
a.inaddr6.sin6_port = 0;
}
if (setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse,
sizeof(reuse)) == -1)
goto failure;
addrlen = domain == PF_INET ? sizeof(a.inaddr) : sizeof(a.inaddr6);
if (bind(listener, &a.addr, addrlen) == SOCKET_ERROR) goto failure;
memset(&a, 0, sizeof(a));
if (getsockname(listener, &a.addr, &addrlen) == SOCKET_ERROR) goto failure;
if (domain == PF_INET) {
a.inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
a.inaddr.sin_family = AF_INET;
} else {
a.inaddr6.sin6_addr = in6addr_loopback;
a.inaddr6.sin6_family = AF_INET6;
}
if (listen(listener, 1) == SOCKET_ERROR) goto failure;
sockets[0] = lwt_win_socket(domain, type, protocol, NULL, inherit);
if (sockets[0] == INVALID_SOCKET) goto failure;
addrlen = domain == PF_INET ? sizeof(a.inaddr) : sizeof(a.inaddr6);
if (connect(sockets[0], &a.addr, addrlen) == SOCKET_ERROR)
goto failure;
sockets[1] = accept(listener, NULL, NULL);
if (sockets[1] == INVALID_SOCKET) goto failure;
closesocket(listener);
return;
failure:
err = WSAGetLastError();
closesocket(listener);
closesocket(sockets[0]);
closesocket(sockets[1]);
win32_maperr(err);
uerror("socketpair", Nothing);
}
static const int socket_domain_table[] =
{PF_UNIX, PF_INET, PF_INET6};
static const int socket_type_table[] =
{SOCK_STREAM, SOCK_DGRAM, SOCK_RAW, SOCK_SEQPACKET};
CAMLprim value lwt_unix_socketpair_stub(value cloexec, value domain, value type,
value protocol) {
CAMLparam4(cloexec, domain, type, protocol);
CAMLlocal1(result);
SOCKET sockets[2];
lwt_unix_socketpair(socket_domain_table[Int_val(domain)],
socket_type_table[Int_val(type)], Int_val(protocol),
sockets,
! unix_cloexec_p(cloexec));
result = caml_alloc_tuple(2);
Store_field(result, 0, win_alloc_socket(sockets[0]));
Store_field(result, 1, win_alloc_socket(sockets[1]));
CAMLreturn(result);
}
#endif
/* +-----------------------------------------------------------------+
| Notifications |
+-----------------------------------------------------------------+ */
/* The mutex used to send and receive notifications. */
static lwt_unix_mutex notification_mutex;
/* All pending notifications. */
static intnat *notifications = NULL;
/* The size of the notification buffer. */
static long notification_count = 0;
/* The index to the next available cell in the notification buffer. */
static long notification_index = 0;
/* The mode currently used for notifications. */
enum notification_mode {
/* Not yet initialized. */
NOTIFICATION_MODE_NOT_INITIALIZED,
/* Initialized but no mode defined. */
NOTIFICATION_MODE_NONE,
/* Using an eventfd. */
NOTIFICATION_MODE_EVENTFD,
/* Using a pipe. */
NOTIFICATION_MODE_PIPE,
/* Using a pair of sockets (only on windows). */
NOTIFICATION_MODE_WINDOWS
};
/* The current notification mode. */
static enum notification_mode notification_mode =
NOTIFICATION_MODE_NOT_INITIALIZED;
/* Send one notification. */
static int (*notification_send)();
/* Read one notification. */
static int (*notification_recv)();
static void init_notifications() {
lwt_unix_mutex_init(¬ification_mutex);
notification_count = 4096;
notifications =
(intnat *)lwt_unix_malloc(notification_count * sizeof(intnat));
}
static void resize_notifications() {
long new_notification_count = notification_count * 2;
intnat *new_notifications =
(intnat *)lwt_unix_malloc(new_notification_count * sizeof(intnat));
memcpy((void *)new_notifications, (void *)notifications,
notification_count * sizeof(intnat));
free(notifications);
notifications = new_notifications;
notification_count = new_notification_count;
}
void lwt_unix_send_notification(intnat id) {
int ret;
#if !defined(LWT_ON_WINDOWS)
sigset_t new_mask;
sigset_t old_mask;
int error;
sigfillset(&new_mask);
pthread_sigmask(SIG_SETMASK, &new_mask, &old_mask);
#else
DWORD error;
#endif
lwt_unix_mutex_lock(¬ification_mutex);
if (notification_index > 0) {
/* There is already a pending notification in the buffer, no
need to signal the main thread. */
if (notification_index == notification_count) resize_notifications();
notifications[notification_index++] = id;
} else {
/* There is none, notify the main thread. */
notifications[notification_index++] = id;
ret = notification_send();
#if defined(LWT_ON_WINDOWS)
if (ret == SOCKET_ERROR) {
error = WSAGetLastError();
if (error != WSANOTINITIALISED) {
lwt_unix_mutex_unlock(¬ification_mutex);
win32_maperr(error);
uerror("send_notification", Nothing);
} /* else we're probably shutting down, so ignore the error */
}
#else
if (ret < 0) {
error = errno;
lwt_unix_mutex_unlock(¬ification_mutex);
pthread_sigmask(SIG_SETMASK, &old_mask, NULL);
unix_error(error, "send_notification", Nothing);
}
#endif
}
lwt_unix_mutex_unlock(¬ification_mutex);
#if !defined(LWT_ON_WINDOWS)
pthread_sigmask(SIG_SETMASK, &old_mask, NULL);
#endif
}
value lwt_unix_send_notification_stub(value id) {
lwt_unix_send_notification(Long_val(id));
return Val_unit;
}
value lwt_unix_recv_notifications() {
int ret, i, current_index;
value result;
#if !defined(LWT_ON_WINDOWS)
sigset_t new_mask;
sigset_t old_mask;
int error;
sigfillset(&new_mask);
pthread_sigmask(SIG_SETMASK, &new_mask, &old_mask);
#else
DWORD error;
#endif
lwt_unix_mutex_lock(¬ification_mutex);
/* Receive the signal. */
ret = notification_recv();
#if defined(LWT_ON_WINDOWS)
if (ret == SOCKET_ERROR) {
error = WSAGetLastError();
lwt_unix_mutex_unlock(¬ification_mutex);
win32_maperr(error);
uerror("recv_notifications", Nothing);
}
#else
if (ret < 0) {
error = errno;
lwt_unix_mutex_unlock(¬ification_mutex);
pthread_sigmask(SIG_SETMASK, &old_mask, NULL);
unix_error(error, "recv_notifications", Nothing);
}
#endif
do {
/*
release the mutex while calling caml_alloc,
which may call gc and switch the thread,
resulting in a classical deadlock,
when thread in question tries another send
*/
current_index = notification_index;
lwt_unix_mutex_unlock(¬ification_mutex);
result = caml_alloc_tuple(current_index);
lwt_unix_mutex_lock(¬ification_mutex);
/* check that no new notifications appeared meanwhile (rare) */
} while (current_index != notification_index);
/* Read all pending notifications. */
for (i = 0; i < notification_index; i++)
Field(result, i) = Val_long(notifications[i]);
/* Reset the index. */
notification_index = 0;
lwt_unix_mutex_unlock(¬ification_mutex);
#if !defined(LWT_ON_WINDOWS)
pthread_sigmask(SIG_SETMASK, &old_mask, NULL);
#endif
return result;
}
#if defined(LWT_ON_WINDOWS)
static SOCKET socket_r, socket_w;
static int windows_notification_send() {
char buf = '!';
return send(socket_w, &buf, 1, 0);
}
static int windows_notification_recv() {
char buf;
return recv(socket_r, &buf, 1, 0);
}
value lwt_unix_init_notification() {
SOCKET sockets[2];
switch (notification_mode) {
case NOTIFICATION_MODE_NOT_INITIALIZED:
notification_mode = NOTIFICATION_MODE_NONE;
init_notifications();
break;
case NOTIFICATION_MODE_WINDOWS:
notification_mode = NOTIFICATION_MODE_NONE;
closesocket(socket_r);
closesocket(socket_w);
break;
case NOTIFICATION_MODE_NONE:
break;
default:
caml_failwith("notification system in unknown state");
}
/* Since pipes do not works with select, we need to use a pair of
sockets. */
lwt_unix_socketpair(AF_INET, SOCK_STREAM, IPPROTO_TCP, sockets, FALSE);
socket_r = sockets[0];
socket_w = sockets[1];
notification_mode = NOTIFICATION_MODE_WINDOWS;
notification_send = windows_notification_send;
notification_recv = windows_notification_recv;
return win_alloc_socket(socket_r);
}
#else /* defined(LWT_ON_WINDOWS) */
static void set_close_on_exec(int fd) {
int flags = fcntl(fd, F_GETFD, 0);
if (flags == -1 || fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1)
uerror("set_close_on_exec", Nothing);
}
#if defined(HAVE_EVENTFD)
static int notification_fd;
static int eventfd_notification_send() {
uint64_t buf = 1;
return write(notification_fd, (char *)&buf, 8);
}
static int eventfd_notification_recv() {
uint64_t buf;
return read(notification_fd, (char *)&buf, 8);
}
#endif /* defined(HAVE_EVENTFD) */
static int notification_fds[2];
static int pipe_notification_send() {
char buf = 0;
return write(notification_fds[1], &buf, 1);
}
static int pipe_notification_recv() {
char buf;
return read(notification_fds[0], &buf, 1);
}
value lwt_unix_init_notification() {
switch (notification_mode) {
#if defined(HAVE_EVENTFD)
case NOTIFICATION_MODE_EVENTFD:
notification_mode = NOTIFICATION_MODE_NONE;
if (close(notification_fd) == -1) uerror("close", Nothing);
break;
#endif
case NOTIFICATION_MODE_PIPE:
notification_mode = NOTIFICATION_MODE_NONE;
if (close(notification_fds[0]) == -1) uerror("close", Nothing);
if (close(notification_fds[1]) == -1) uerror("close", Nothing);
break;
case NOTIFICATION_MODE_NOT_INITIALIZED:
notification_mode = NOTIFICATION_MODE_NONE;
init_notifications();
break;
case NOTIFICATION_MODE_NONE:
break;
default:
caml_failwith("notification system in unknown state");
}
#if defined(HAVE_EVENTFD)
notification_fd = eventfd(0, 0);
if (notification_fd != -1) {
notification_mode = NOTIFICATION_MODE_EVENTFD;
notification_send = eventfd_notification_send;
notification_recv = eventfd_notification_recv;
set_close_on_exec(notification_fd);
return Val_int(notification_fd);
}
#endif
if (pipe(notification_fds) == -1) uerror("pipe", Nothing);
set_close_on_exec(notification_fds[0]);
set_close_on_exec(notification_fds[1]);
notification_mode = NOTIFICATION_MODE_PIPE;
notification_send = pipe_notification_send;
notification_recv = pipe_notification_recv;
return Val_int(notification_fds[0]);
}
#endif /* defined(LWT_ON_WINDOWS) */
/* +-----------------------------------------------------------------+
| Signals |
+-----------------------------------------------------------------+ */
#ifndef NSIG
#define NSIG 64
#endif
/* Notifications id for each monitored signal. */
static intnat signal_notifications[NSIG];
CAMLextern int caml_convert_signal_number(int);
/* Send a notification when a signal is received. */
static void handle_signal(int signum) {
if (signum >= 0 && signum < NSIG) {
intnat id = signal_notifications[signum];
if (id != -1) {
#if defined(LWT_ON_WINDOWS)
/* The signal handler must be reinstalled if we use the signal
function. */
signal(signum, handle_signal);
#endif
lwt_unix_send_notification(id);
}
}
}
CAMLprim value lwt_unix_handle_signal(value val_signum) {
handle_signal(caml_convert_signal_number(Int_val(val_signum)));
return Val_unit;
}
#if defined(LWT_ON_WINDOWS)
/* Handle Ctrl+C on windows. */
static BOOL WINAPI handle_break(DWORD event) {
intnat id = signal_notifications[SIGINT];
if (id == -1 || (event != CTRL_C_EVENT && event != CTRL_BREAK_EVENT))
return FALSE;
lwt_unix_send_notification(id);
return TRUE;
}
#endif
/* Install a signal handler. */
CAMLprim value lwt_unix_set_signal(value val_signum, value val_notification, value val_forwarded) {
#if !defined(LWT_ON_WINDOWS)
struct sigaction sa;
#endif
int signum = caml_convert_signal_number(Int_val(val_signum));
intnat notification = Long_val(val_notification);
if (signum < 0 || signum >= NSIG)
caml_invalid_argument("Lwt_unix.on_signal: unavailable signal");
signal_notifications[signum] = notification;
if (Bool_val(val_forwarded)) return Val_unit;
#if defined(LWT_ON_WINDOWS)
if (signum == SIGINT) {
if (!SetConsoleCtrlHandler(handle_break, TRUE)) {
signal_notifications[signum] = -1;
win32_maperr(GetLastError());
uerror("SetConsoleCtrlHandler", Nothing);
}
} else {
if (signal(signum, handle_signal) == SIG_ERR) {
signal_notifications[signum] = -1;
uerror("signal", Nothing);
}
}
#else
sa.sa_handler = handle_signal;
#if OCAML_VERSION >= 50000
sa.sa_flags = SA_ONSTACK;
#else
sa.sa_flags = 0;
#endif
sigemptyset(&sa.sa_mask);
if (sigaction(signum, &sa, NULL) == -1) {
signal_notifications[signum] = -1;
uerror("sigaction", Nothing);
}
#endif
return Val_unit;
}
/* Remove a signal handler. */
CAMLprim value lwt_unix_remove_signal(value val_signum, value val_forwarded) {
#if !defined(LWT_ON_WINDOWS)
struct sigaction sa;
#endif
/* The signal number is valid here since it was when we did the
set_signal. */
int signum = caml_convert_signal_number(Int_val(val_signum));
signal_notifications[signum] = -1;
if (Bool_val(val_forwarded)) return Val_unit;
#if defined(LWT_ON_WINDOWS)
if (signum == SIGINT)
SetConsoleCtrlHandler(NULL, FALSE);
else
signal(signum, SIG_DFL);
#else
sa.sa_handler = SIG_DFL;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sigaction(signum, &sa, NULL);
#endif
return Val_unit;
}
/* Mark all signals as non-monitored. */
CAMLprim value lwt_unix_init_signals(value Unit) {
int i;
for (i = 0; i < NSIG; i++) signal_notifications[i] = -1;
return Val_unit;
}
/* +-----------------------------------------------------------------+
| Job execution |
+-----------------------------------------------------------------+ */
/* Execute the given job. */
static void execute_job(lwt_unix_job job) {
DEBUG("executing the job");
lwt_unix_mutex_lock(&job->mutex);
/* Mark the job as running. */
job->state = LWT_UNIX_JOB_STATE_RUNNING;
lwt_unix_mutex_unlock(&job->mutex);
/* Execute the job. */
job->worker(job);
DEBUG("job done");
lwt_unix_mutex_lock(&job->mutex);
DEBUG("marking the job has done");
/* Job is done. If the main thread stopped until now, asynchronous
notification is not necessary. */
job->state = LWT_UNIX_JOB_STATE_DONE;
/* Send a notification if the main thread continued its execution
before the job terminated. */
if (job->fast == 0) {
lwt_unix_mutex_unlock(&job->mutex);
DEBUG("notifying the main thread");
lwt_unix_send_notification(job->notification_id);
} else {
lwt_unix_mutex_unlock(&job->mutex);
DEBUG("not notifying the main thread");
}
}
/* +-----------------------------------------------------------------+
| Thread pool |
+-----------------------------------------------------------------+ */
/* Number of thread waiting for a job in the pool. */
static int thread_waiting_count = 0;
/* Number of started threads. */
static int thread_count = 0;
/* Maximum number of system threads that can be started. */
static int pool_size = 1000;
/* Condition on which pool threads are waiting. */
static lwt_unix_condition pool_condition;
/* Queue of pending jobs. It points to the last enqueued job. */
static lwt_unix_job pool_queue = NULL;
/* The mutex which protect access to [pool_queue], [pool_condition]
and [thread_waiting_count]. */
static lwt_unix_mutex pool_mutex;
/* +-----------------------------------------------------------------+
| Threading stuff initialization |
+-----------------------------------------------------------------+ */
/* Whether threading has been initialized. */
static int threading_initialized = 0;
/* Initialize the pool of thread. */
void initialize_threading() {
if (threading_initialized == 0) {
lwt_unix_mutex_init(&pool_mutex);
lwt_unix_condition_init(&pool_condition);
threading_initialized = 1;
}
}
/* +-----------------------------------------------------------------+
| Worker loop |
+-----------------------------------------------------------------+ */
/* Function executed by threads of the pool.
* Note: all signals are masked for this thread. */
static void *worker_loop(void *data) {
lwt_unix_job job = (lwt_unix_job)data;
/* Execute the initial job if any. */
if (job != NULL) execute_job(job);
while (1) {
DEBUG("entering waiting section");