forked from swiftlang/swift-corelibs-foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCFRunLoop.c
4758 lines (4208 loc) · 176 KB
/
CFRunLoop.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
/* CFRunLoop.c
Copyright (c) 1998-2019, Apple Inc. and the Swift project authors
Portions Copyright (c) 2014-2019, Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
Responsibility: Michael LeHew
*/
#include <CoreFoundation/CFRunLoop.h>
#include <CoreFoundation/CFSet.h>
#include <CoreFoundation/CFBag.h>
#include <CoreFoundation/CFNumber.h>
#include <CoreFoundation/CFPreferences.h>
#include "CFInternal.h"
#include "CFPriv.h"
#include "CFRuntime_Internal.h"
#include "CFMachPort_Internal.h"
#include <math.h>
#include <stdio.h>
#include <limits.h>
#if __has_include(<unistd.h>)
#include <unistd.h>
#endif
#if _POSIX_THREADS
#include <pthread.h>
#endif
#if __HAS_DISPATCH__
#include <dispatch/dispatch.h>
#endif
extern void objc_terminate(void);
#if TARGET_OS_WIN32
// typeinfo.h has been removed in VS2019 16.3
#if __has_include(<typeinfo.h>)
#include <typeinfo.h>
#endif
#endif
#include "CFOverflow.h"
#if DEPLOYMENT_RUNTIME_OBJC
#define USE_DISPATCH_SOURCE_FOR_TIMERS __HAS_DISPATCH__
#else
#define USE_DISPATCH_SOURCE_FOR_TIMERS 0
#endif
#if USE_DISPATCH_SOURCE_FOR_TIMERS
#if !TARGET_OS_MAC
typedef uint32_t mach_port_t;
typedef uint32_t mach_port_name_t;
#endif
#endif
#if __HAS_DISPATCH__ && __has_include(<dispatch/private.h>)
#include <dispatch/private.h>
#else
extern dispatch_queue_t _dispatch_runloop_root_queue_create_4CF(const char *_Nullable label, unsigned long flags);
#if TARGET_OS_MAC
extern mach_port_t _dispatch_runloop_root_queue_get_port_4CF(dispatch_queue_t queue);
#endif
#endif
extern void _dispatch_source_set_runloop_timer_4CF(dispatch_source_t source, dispatch_time_t start, uint64_t interval, uint64_t leeway);
extern bool _dispatch_runloop_root_queue_perform_4CF(dispatch_queue_t queue);
#if TARGET_OS_MAC
typedef mach_port_t dispatch_runloop_handle_t;
#elif defined(__linux__) || defined(__FreeBSD__)
typedef int dispatch_runloop_handle_t;
#elif TARGET_OS_WIN32
typedef HANDLE dispatch_runloop_handle_t;
#else
typedef uint64_t dispatch_runloop_handle_t;
#endif
#if TARGET_OS_MAC
#include <sys/param.h>
#include <CoreFoundation/CFUserNotification.h>
#include <mach/mach.h>
#include <mach/clock_types.h>
#include <mach/clock.h>
#include <unistd.h>
#include <dlfcn.h>
extern void _dispatch_main_queue_callback_4CF(void *);
extern _CFThreadRef pthread_main_thread_np(void);
typedef struct voucher_s *voucher_t;
extern voucher_t _Nullable voucher_copy(void);
extern void os_release(void *object);
extern mach_port_t _dispatch_get_main_queue_port_4CF(void);
#elif TARGET_OS_WIN32 || TARGET_OS_CYGWIN
#include <process.h>
DISPATCH_EXPORT dispatch_runloop_handle_t _dispatch_get_main_queue_port_4CF(void);
DISPATCH_EXPORT void _dispatch_main_queue_callback_4CF(void * _Null_unspecified);
#define MACH_PORT_NULL 0
#define mach_port_name_t HANDLE
#define mach_port_t HANDLE
#elif TARGET_OS_LINUX
#include <dlfcn.h>
#include <poll.h>
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <sys/timerfd.h>
dispatch_runloop_handle_t _dispatch_get_main_queue_port_4CF(void);
extern void _dispatch_main_queue_callback_4CF(void *_Null_unspecified msg);
#else
dispatch_runloop_handle_t _dispatch_get_main_queue_port_4CF(void);
extern void _dispatch_main_queue_callback_4CF(void *_Null_unspecified msg);
#endif
#if TARGET_OS_WIN32 || TARGET_OS_LINUX || TARGET_OS_BSD
CF_EXPORT _CFThreadRef _CF_pthread_main_thread_np(void);
#define pthread_main_thread_np() _CF_pthread_main_thread_np()
#endif
#include <Block.h>
#if __has_include(<Block_private.h>)
#include <Block_private.h>
#elif __has_include("Block_private.h")
#include "Block_private.h"
#endif
// Open source CF may not have this defined.
#ifndef cf_trace
#define cf_trace(...) do {} while (0)
#endif
static int _LogCFRunLoop = 0;
static void _runLoopTimerWithBlockContext(CFRunLoopTimerRef timer, void *opaqueBlock);
// for conservative arithmetic safety, such that (TIMER_DATE_LIMIT + TIMER_INTERVAL_LIMIT + kCFAbsoluteTimeIntervalSince1970) * 10^9 < 2^63
#define TIMER_DATE_LIMIT 4039289856.0
#define TIMER_INTERVAL_LIMIT 504911232.0
#define HANDLE_DISPATCH_ON_BASE_INVOCATION_ONLY 0
#define CRASH(string, errcode) do { char msg[256]; snprintf(msg, 256, string, errcode); CRSetCrashLogMessage(msg); HALT; } while (0)
#if TARGET_OS_WIN32
static _CFThreadRef const kNilPthreadT = INVALID_HANDLE_VALUE;
#define pthreadPointer(a) (GetThreadId(a))
typedef int kern_return_t;
#define KERN_SUCCESS 0
#elif TARGET_OS_LINUX
static _CFThreadRef const kNilPthreadT = (_CFThreadRef)0;
#define pthreadPointer(a) ((void*)a)
typedef int kern_return_t;
#define KERN_SUCCESS 0
#else
static _CFThreadRef const kNilPthreadT = (_CFThreadRef)0;
typedef int kern_return_t;
#define KERN_SUCCESS 0
#define pthreadPointer(a) a
#define lockCount(a) a
#endif
#pragma mark -
#define CF_RUN_LOOP_PROBES 0
#pragma mark CFRunLoopProbes
#if CF_RUN_LOOP_PROBES
#include "CFRunLoopProbes.h"
#else
#define CFRUNLOOP_NEXT_TIMER_ARMED(arg0) do { } while (0)
#define CFRUNLOOP_NEXT_TIMER_ARMED_ENABLED() (0)
#define CFRUNLOOP_POLL() do { } while (0)
#define CFRUNLOOP_POLL_ENABLED() (0)
#define CFRUNLOOP_SLEEP() do { } while (0)
#define CFRUNLOOP_SLEEP_ENABLED() (0)
#define CFRUNLOOP_SOURCE_FIRED(arg0, arg1, arg2) do { } while (0)
#define CFRUNLOOP_SOURCE_FIRED_ENABLED() (0)
#define CFRUNLOOP_TIMER_CREATED(arg0, arg1, arg2, arg3, arg4, arg5, arg6) do { } while (0)
#define CFRUNLOOP_TIMER_CREATED_ENABLED() (0)
#define CFRUNLOOP_TIMER_FIRED(arg0, arg1, arg2, arg3, arg4) do { } while (0)
#define CFRUNLOOP_TIMER_FIRED_ENABLED() (0)
#define CFRUNLOOP_TIMER_RESCHEDULED(arg0, arg1, arg2, arg3, arg4, arg5) do { } while (0)
#define CFRUNLOOP_TIMER_RESCHEDULED_ENABLED() (0)
#define CFRUNLOOP_WAKEUP(arg0) do { } while (0)
#define CFRUNLOOP_WAKEUP_ENABLED() (0)
#define CFRUNLOOP_WAKEUP_FOR_DISPATCH() do { } while (0)
#define CFRUNLOOP_WAKEUP_FOR_DISPATCH_ENABLED() (0)
#define CFRUNLOOP_WAKEUP_FOR_NOTHING() do { } while (0)
#define CFRUNLOOP_WAKEUP_FOR_NOTHING_ENABLED() (0)
#define CFRUNLOOP_WAKEUP_FOR_SOURCE() do { } while (0)
#define CFRUNLOOP_WAKEUP_FOR_SOURCE_ENABLED() (0)
#define CFRUNLOOP_WAKEUP_FOR_TIMEOUT() do { } while (0)
#define CFRUNLOOP_WAKEUP_FOR_TIMEOUT_ENABLED() (0)
#define CFRUNLOOP_WAKEUP_FOR_TIMER() do { } while (0)
#define CFRUNLOOP_WAKEUP_FOR_TIMER_ENABLED() (0)
#define CFRUNLOOP_WAKEUP_FOR_WAKEUP() do { } while (0)
#define CFRUNLOOP_WAKEUP_FOR_WAKEUP_ENABLED() (0)
#endif
// NOTE: this is locally defined rather than in CFInternal.h as on Linux,
// `linux/sysctl.h` defines `struct __sysctl_args` with an `__unused` member
// which breaks the build.
#if TARGET_OS_WIN32 || TARGET_OS_CYGWIN || TARGET_OS_LINUX
#ifndef __unused
#if __has_attribute(unused)
#define __unused __attribute__((unused))
#else
#define __unused
#endif
#endif // !defined(__unused)
#endif
#define CFRUNLOOP_ARP_BEGIN(...)
#define CFRUNLOOP_ARP_END(...)
// In order to reuse most of the code across Mach and Windows v1 RunLoopSources, we define a
// simple abstraction layer spanning Mach ports and Windows HANDLES
#if TARGET_OS_MAC
typedef mach_port_t __CFPort;
#define CFPORT_NULL MACH_PORT_NULL
typedef mach_port_t __CFPortSet;
static void __THE_SYSTEM_HAS_NO_PORTS_AVAILABLE__(kern_return_t ret) __attribute__((noinline));
static void __THE_SYSTEM_HAS_NO_PORTS_AVAILABLE__(kern_return_t ret) { HALT; };
static __CFPort __CFPortAllocate(uintptr_t guard) {
__CFPort result = CFPORT_NULL;
mach_port_options_t options = {
.flags = MPO_CONTEXT_AS_GUARD | MPO_QLIMIT | MPO_INSERT_SEND_RIGHT | MPO_STRICT,
.mpl.mpl_qlimit = 1,
};
kern_return_t const ret = mach_port_construct(mach_task_self(), &options, (mach_port_context_t)guard, &result);
if (KERN_SUCCESS != ret) {
char msg[256];
snprintf(msg, 256, "*** The system has no mach ports available. You may be able to diagnose which application(s) are using ports by using 'top' or Activity Monitor. (%d) ***", ret);
CRSetCrashLogMessage(msg);
__THE_SYSTEM_HAS_NO_PORTS_AVAILABLE__(ret);
return CFPORT_NULL;
}
return result;
}
CF_INLINE void __CFPortFree(__CFPort port, uintptr_t guard) {
kern_return_t const ret = mach_port_destruct(mach_task_self(), port, -1, (mach_port_context_t)guard);
if (KERN_SUCCESS != ret) {
char msg[256];
snprintf(msg, 256, "*** Unable to destruct port. (0x%x, %d, %p) ***", port, ret, (void *)guard);
CRSetCrashLogMessage(msg);
HALT;
}
}
static void __NO_SPACE__(kern_return_t ret) __attribute__((noinline));
static void __NO_SPACE__(kern_return_t ret) { HALT; };
static void __RESOURCE_SHORTAGE__(kern_return_t ret) __attribute__((noinline));
static void __RESOURCE_SHORTAGE__(kern_return_t ret) { HALT; };
static void __THE_SYSTEM_HAS_NO_PORT_SETS_AVAILABLE__(kern_return_t ret) __attribute__((noinline));
static void __THE_SYSTEM_HAS_NO_PORT_SETS_AVAILABLE__(kern_return_t ret) {
if (ret == KERN_NO_SPACE) {
__NO_SPACE__(ret);
}
else if (ret == KERN_RESOURCE_SHORTAGE) {
__RESOURCE_SHORTAGE__(ret);
}
HALT;
};
CF_INLINE __CFPortSet __CFPortSetAllocate(void) {
__CFPortSet result;
kern_return_t ret = mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_PORT_SET, &result);
if (KERN_SUCCESS != ret) { __THE_SYSTEM_HAS_NO_PORT_SETS_AVAILABLE__(ret); }
return (KERN_SUCCESS == ret) ? result : CFPORT_NULL;
}
CF_INLINE kern_return_t __CFPortSetInsert(__CFPort port, __CFPortSet portSet) {
if (MACH_PORT_NULL == port) {
return -1;
}
return mach_port_insert_member(mach_task_self(), port, portSet);
}
CF_INLINE kern_return_t __CFPortSetRemove(__CFPort port, __CFPortSet portSet) {
if (MACH_PORT_NULL == port) {
return -1;
}
return mach_port_extract_member(mach_task_self(), port, portSet);
}
CF_INLINE void __CFPortSetFree(__CFPortSet portSet) {
// NOTE: we rely on the impl of mach_port destroy to extract each member, which it does
// ALSO NOTE: Per CoreOS port sets don't have ref counts, so this is equiv to mach_port_destroy, but faster/safer
const kern_return_t ret = mach_port_mod_refs(mach_task_self(), portSet, MACH_PORT_RIGHT_PORT_SET, -1);
if (ret != KERN_SUCCESS) {
CFLog(kCFLogLevelError, CFSTR("error (%d - %s) while trying to free port set: %d"), ret, mach_error_string(ret), portSet);
}
}
#elif TARGET_OS_WIN32 || TARGET_OS_CYGWIN
typedef HANDLE __CFPort;
#define CFPORT_NULL NULL
// A simple dynamic array of HANDLEs, which grows to a high-water mark
typedef struct ___CFPortSet {
uint16_t used;
uint16_t size;
HANDLE *handles;
CFLock_t lock; // insert and remove must be thread safe, like the Mach calls
} *__CFPortSet;
CF_INLINE __CFPort __CFPortAllocate(__unused uintptr_t guard) {
return CreateEventA(NULL, true, false, NULL);
}
CF_INLINE void __CFPortFree(__CFPort port, __unused uintptr_t guard) {
CloseHandle(port);
}
static __CFPortSet __CFPortSetAllocate(void) {
__CFPortSet result = (__CFPortSet)CFAllocatorAllocate(kCFAllocatorSystemDefault, sizeof(struct ___CFPortSet), 0);
result->used = 0;
result->size = 4;
result->handles = (HANDLE *)CFAllocatorAllocate(kCFAllocatorSystemDefault, result->size * sizeof(HANDLE), 0);
CF_LOCK_INIT_FOR_STRUCTS(result->lock);
return result;
}
static void __CFPortSetFree(__CFPortSet portSet) {
CFAllocatorDeallocate(kCFAllocatorSystemDefault, portSet->handles);
CFAllocatorDeallocate(kCFAllocatorSystemDefault, portSet);
}
// Returns portBuf if ports fit in that space, else returns another ptr that must be freed
static __CFPort *__CFPortSetGetPorts(__CFPortSet portSet, __CFPort *portBuf, uint32_t bufSize, uint32_t *portsUsed) {
__CFLock(&(portSet->lock));
__CFPort *result = portBuf;
if (bufSize < portSet->used)
result = (__CFPort *)CFAllocatorAllocate(kCFAllocatorSystemDefault, portSet->used * sizeof(HANDLE), 0);
if (portSet->used > 1) {
// rotate the ports to vaguely simulate round-robin behaviour
uint16_t lastPort = portSet->used - 1;
HANDLE swapHandle = portSet->handles[0];
memmove(portSet->handles, &portSet->handles[1], lastPort * sizeof(HANDLE));
portSet->handles[lastPort] = swapHandle;
}
memmove(result, portSet->handles, portSet->used * sizeof(HANDLE));
*portsUsed = portSet->used;
__CFUnlock(&(portSet->lock));
return result;
}
static kern_return_t __CFPortSetInsert(__CFPort port, __CFPortSet portSet) {
if (NULL == port) {
return -1;
}
__CFLock(&(portSet->lock));
if (portSet->used >= portSet->size) {
portSet->size += 4;
portSet->handles = __CFSafelyReallocateWithAllocator(kCFAllocatorSystemDefault, portSet->handles, portSet->size * sizeof(HANDLE), 0, NULL);
}
if (portSet->used >= MAXIMUM_WAIT_OBJECTS) {
CFLog(kCFLogLevelWarning, CFSTR("*** More than MAXIMUM_WAIT_OBJECTS (%d) ports add to a port set. The last ones will be ignored."), MAXIMUM_WAIT_OBJECTS);
}
portSet->handles[portSet->used++] = port;
__CFUnlock(&(portSet->lock));
return KERN_SUCCESS;
}
static kern_return_t __CFPortSetRemove(__CFPort port, __CFPortSet portSet) {
int i, j;
if (NULL == port) {
return -1;
}
__CFLock(&(portSet->lock));
for (i = 0; i < portSet->used; i++) {
if (portSet->handles[i] == port) {
for (j = i+1; j < portSet->used; j++) {
portSet->handles[j-1] = portSet->handles[j];
}
portSet->used--;
__CFUnlock(&(portSet->lock));
return true;
}
}
__CFUnlock(&(portSet->lock));
return KERN_SUCCESS;
}
#elif TARGET_OS_LINUX
// eventfd/timerfd descriptor
typedef int __CFPort;
#define CFPORT_NULL -1
#define MACH_PORT_NULL CFPORT_NULL
// epoll file descriptor
typedef int __CFPortSet;
#define CFPORTSET_NULL -1
static __CFPort __CFPortAllocate(__unused uintptr_t guard) {
return eventfd(0, EFD_CLOEXEC|EFD_NONBLOCK);
}
CF_INLINE void __CFPortFree(__CFPort port, __unused uintptr_t guard) {
close(port);
}
CF_INLINE __CFPortSet __CFPortSetAllocate(void) {
return epoll_create1(EPOLL_CLOEXEC);
}
CF_INLINE kern_return_t __CFPortSetInsert(__CFPort port, __CFPortSet portSet) {
if (CFPORT_NULL == port) {
return -1;
}
struct epoll_event event;
memset(&event, 0, sizeof(event));
event.data.fd = port;
event.events = EPOLLIN|EPOLLET;
return epoll_ctl(portSet, EPOLL_CTL_ADD, port, &event);
}
CF_INLINE kern_return_t __CFPortSetRemove(__CFPort port, __CFPortSet portSet) {
if (CFPORT_NULL == port) {
return -1;
}
return epoll_ctl(portSet, EPOLL_CTL_DEL, port, NULL);
}
CF_INLINE void __CFPortSetFree(__CFPortSet portSet) {
close(portSet);
}
#elif TARGET_OS_BSD
#include <sys/types.h>
#include <sys/event.h>
#include <sys/time.h>
#include <poll.h>
typedef uint64_t __CFPort;
#define CFPORT_NULL ((__CFPort)-1)
// _dispatch_get_main_queue_port_4CF is a uint64_t, i.e., a __CFPort.
// That is, we can't use one type for the queue handle in Dispatch and a
// different type for __CFPort in CF.
#define __CFPORT_PACK(rfd, wfd) (((uint64_t)(rfd) << 32) | ((uint32_t)(wfd)))
#define __CFPORT_UNPACK_W(port) ((uint32_t)((port) & 0xffffffff))
#define __CFPORT_UNPACK_R(port) ((uint32_t)((port) >> 32))
typedef struct ___CFPortSet {
int kq;
} *__CFPortSet;
#define CFPORTSET_NULL NULL
#define TIMEOUT_INFINITY UINT64_MAX
// Timers are not pipes; they are kevents on a parent kqueue.
// We must flag these to differentiate them from pipes, but we have
// to pack the (kqueue, timer ident) pair like a __CFPort.
#define __CFPORT_TIMER_PACK(ident, kq) \
((1ULL << 63) | ((uint64_t)(ident) << 32) | ((uint32_t)(kq)))
#define __CFPORT_IS_TIMER(port) ((port) & (1ULL << 63))
static __CFPort __CFPortAllocate(__unused uintptr_t guard) {
__CFPort port;
int fds[2];
int r = pipe2(fds, O_CLOEXEC | O_NONBLOCK);
if (r == -1) {
return CFPORT_NULL;
}
uint32_t rfd = (uint32_t)fds[0], wfd = (uint32_t)fds[1];
port = __CFPORT_PACK(rfd, wfd);
if (__CFPORT_IS_TIMER(port)) {
// This port is not distinguishable from a flagged packed timer.
close((int)(__CFPORT_UNPACK_W(port)));
close((int)(__CFPORT_UNPACK_R(port)));
return CFPORT_NULL;
}
return port;
}
static void __CFPortTrigger(__CFPort port) {
int wfd = (int)__CFPORT_UNPACK_W(port);
ssize_t result;
do {
result = write(wfd, "x", 1);
} while (result == -1 && errno == EINTR);
}
CF_INLINE void __CFPortFree(__CFPort port, __unused uintptr_t guard) {
close((int)(__CFPORT_UNPACK_W(port)));
close((int)(__CFPORT_UNPACK_R(port)));
}
#define __CFPORT_TIMER_UNPACK_ID(port) (((port) >> 32) & 0x7fffffff)
#define __CFPORT_TIMER_UNPACK_KQ(port) ((port) & 0xffffffff)
#define MAX_TIMERS 16
uintptr_t ident = 0;
static __CFPort mk_timer_create(__CFPortSet parent) {
if (ident > MAX_TIMERS) return CFPORT_NULL;
ident++;
int kq = parent->kq;
__CFPort port = __CFPORT_TIMER_PACK(ident, kq);
return port;
}
static kern_return_t mk_timer_arm(__CFPort timer, int64_t expire_tsr) {
uint64_t now = mach_absolute_time();
uint64_t expire_time = __CFTSRToNanoseconds(expire_tsr);
int64_t duration = 0;
if (now <= expire_time) {
duration = __CFTSRToTimeInterval(expire_time - now) * 1000;
}
int id = __CFPORT_TIMER_UNPACK_ID(timer);
struct kevent tev;
EV_SET(
&tev,
id,
EVFILT_TIMER,
EV_ADD | EV_ENABLE,
0,
duration,
(void *)timer);
int kq = __CFPORT_TIMER_UNPACK_KQ(timer);
int r = kevent(kq, &tev, 1, NULL, 0, NULL);
return KERN_SUCCESS;
}
static kern_return_t mk_timer_cancel(__CFPort timer, const void *unused) {
int id = __CFPORT_TIMER_UNPACK_ID(timer);
struct kevent tev;
EV_SET(
&tev,
id,
EVFILT_TIMER,
EV_DISABLE,
0,
0,
(void *)timer);
int kq = __CFPORT_TIMER_UNPACK_KQ(timer);
int r = kevent(kq, &tev, 1, NULL, 0, NULL);
return KERN_SUCCESS;
}
static kern_return_t mk_timer_destroy(__CFPort timer) {
int id = __CFPORT_TIMER_UNPACK_ID(timer);
struct kevent tev;
EV_SET(
&tev,
id,
EVFILT_TIMER,
EV_DELETE,
0,
0,
(void *)timer);
int kq = __CFPORT_TIMER_UNPACK_KQ(timer);
int r = kevent(kq, &tev, 1, NULL, 0, NULL);
ident--;
return KERN_SUCCESS;
}
CF_INLINE __CFPortSet __CFPortSetAllocate(void) {
struct ___CFPortSet *set = malloc(sizeof(struct ___CFPortSet));
set->kq = kqueue();
return set;
}
CF_INLINE kern_return_t __CFPortSetInsert(__CFPort port, __CFPortSet set) {
if (__CFPORT_IS_TIMER(port)) {
return 0;
}
struct kevent change;
EV_SET(&change,
__CFPORT_UNPACK_R(port),
EVFILT_READ,
EV_ADD | EV_ENABLE | EV_CLEAR | EV_RECEIPT,
0,
0,
(void *)port);
struct timespec timeout = {0, 0};
int r = kevent(set->kq, &change, 1, NULL, 0, &timeout);
return 0;
}
CF_INLINE kern_return_t __CFPortSetRemove(__CFPort port, __CFPortSet set) {
if (__CFPORT_IS_TIMER(port)) {
return 0;
}
struct kevent change;
EV_SET(&change,
__CFPORT_UNPACK_R(port),
EVFILT_READ,
EV_DELETE | EV_RECEIPT,
0,
0,
(void *)port);
struct timespec timeout = {0, 0};
int r = kevent(set->kq, &change, 1, NULL, 0, &timeout);
return 0;
}
CF_INLINE void __CFPortSetFree(__CFPortSet set) {
close(set->kq);
free(set);
}
static int __CFPollFileDescriptors(struct pollfd *fds, nfds_t nfds, uint64_t timeout) {
uint64_t elapsed = 0;
uint64_t start = mach_absolute_time();
int result = 0;
while (1) {
struct timespec ts = {0};
struct timespec *tsPtr = &ts;
if (timeout == TIMEOUT_INFINITY) {
tsPtr = NULL;
} else if (elapsed < timeout) {
uint64_t delta = timeout - elapsed;
ts.tv_sec = delta / 1000000000UL;
ts.tv_nsec = delta % 1000000000UL;
}
result = ppoll(fds, 1, tsPtr, NULL);
if (result == -1 && errno == EINTR) {
uint64_t end = mach_absolute_time();
elapsed += (end - start);
start = end;
} else {
return result;
}
}
}
static Boolean __CFRunLoopServiceFileDescriptors(__CFPortSet set, __CFPort port, uint64_t timeout, __CFPort *livePort) {
__CFPort awokenPort = CFPORT_NULL;
if (port != CFPORT_NULL) {
int rfd = __CFPORT_UNPACK_R(port);
struct pollfd fdInfo = {
.fd = rfd,
.events = POLLIN,
};
ssize_t result = __CFPollFileDescriptors(&fdInfo, 1, timeout);
if (result == 0)
return false;
awokenPort = port;
} else {
struct kevent awake;
struct timespec timeout = {0, 0};
int r = kevent(set->kq, NULL, 0, &awake, 1, &timeout);
if (r == 0) {
return false;
}
if (awake.flags == EV_ERROR) {
return false;
}
if (awake.filter == EVFILT_READ) {
char x;
r = read(awake.ident, &x, 1);
}
awokenPort = (__CFPort)awake.udata;
}
if (livePort)
*livePort = awokenPort;
return true;
}
#else
#error "CFPort* stubs for this platform must be implemented
#endif
#if !defined(__MACTYPES__) && !defined(_OS_OSTYPES_H)
#if defined(__BIG_ENDIAN__)
typedef struct UnsignedWide {
UInt32 hi;
UInt32 lo;
} UnsignedWide;
#elif defined(__LITTLE_ENDIAN__)
typedef struct UnsignedWide {
UInt32 lo;
UInt32 hi;
} UnsignedWide;
#endif
typedef UnsignedWide AbsoluteTime;
#endif
#if TARGET_OS_MAC
extern mach_port_name_t mk_timer_create(void);
extern kern_return_t mk_timer_destroy(mach_port_name_t name);
extern kern_return_t mk_timer_cancel(mach_port_name_t name, AbsoluteTime *result_time);
extern kern_return_t mk_timer_arm(mach_port_name_t name, uint64_t expire_time);
static uint32_t __CFSendTrivialMachMessage(mach_port_t port, uint32_t msg_id, CFOptionFlags options, uint32_t timeout) {
mach_msg_header_t header;
header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0);
header.msgh_size = sizeof(mach_msg_header_t);
header.msgh_remote_port = port;
header.msgh_local_port = MACH_PORT_NULL;
header.msgh_id = msg_id;
kern_return_t const result = mach_msg(&header, MACH_SEND_MSG|options, header.msgh_size, 0, MACH_PORT_NULL, timeout, MACH_PORT_NULL);
__CFMachMessageCheckForAndDestroyUnsentMessage(result, &header);
return result;
}
#elif TARGET_OS_LINUX
static int mk_timer_create(void) {
return timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC);
}
static kern_return_t mk_timer_destroy(int timer) {
return close(timer);
}
static kern_return_t mk_timer_arm(int timer, int64_t expire_time) {
struct itimerspec ts;
ts.it_value.tv_sec = expire_time / 1000000000UL;
ts.it_value.tv_nsec = expire_time % 1000000000UL;
// Non-repeating timer
ts.it_interval.tv_sec = 0;
ts.it_interval.tv_nsec = 0;
return timerfd_settime(timer, TFD_TIMER_ABSTIME, &ts, NULL);
}
static kern_return_t mk_timer_cancel(int timer, const void *unused) {
return mk_timer_arm(timer, 0);
}
CF_INLINE int64_t __CFUInt64ToAbsoluteTime(int64_t x) {
return x;
}
#elif TARGET_OS_WIN32
static HANDLE mk_timer_create(void) {
return CreateWaitableTimer(NULL, FALSE, NULL);
}
static kern_return_t mk_timer_destroy(HANDLE name) {
BOOL res = CloseHandle(name);
if (!res) {
DWORD err = GetLastError();
CFLog(kCFLogLevelError, CFSTR("CFRunLoop: Unable to destroy timer: %d"), err);
}
return (int)res;
}
static kern_return_t mk_timer_arm(HANDLE name, uint64_t expire_time) {
LARGE_INTEGER result;
// There is a race we know about here, (timer fire time calculated -> thread suspended -> timer armed == late timer fire), but we don't have a way to avoid it at this time, since the only way to specify an absolute value to the timer is to calculate the relative time first. Fixing that would probably require not using the TSR for timers on Windows.
uint64_t now = mach_absolute_time();
if (now > expire_time) {
result.QuadPart = 0;
} else {
uint64_t timeDiff = expire_time - now;
CFTimeInterval amountOfTimeToWait = __CFTSRToTimeInterval(timeDiff);
// Result is in 100 ns (10**-7 sec) units to be consistent with a FILETIME.
// CFTimeInterval is in seconds.
result.QuadPart = -(amountOfTimeToWait * 10000000);
}
BOOL res = SetWaitableTimer(name, &result, 0, NULL, NULL, FALSE);
if (!res) {
DWORD err = GetLastError();
CFLog(kCFLogLevelError, CFSTR("CFRunLoop: Unable to set timer: %d"), err);
}
return (int)res;
}
static kern_return_t mk_timer_cancel(HANDLE name, AbsoluteTime *result_time) {
BOOL res = CancelWaitableTimer(name);
if (!res) {
DWORD err = GetLastError();
CFLog(kCFLogLevelError, CFSTR("CFRunLoop: Unable to cancel timer: %d"), err);
}
return (int)res;
}
#elif TARGET_OS_BSD
/*
* This implementation of the mk_timer_* stubs is defined with the
* implementation of the CFPort* stubs.
*/
#else
#error "mk_timer_* stubs for this platform must be implemented"
#endif
CF_BREAKPOINT_FUNCTION(void _CFRunLoopError_MainThreadHasExited(void));
#pragma mark -
#pragma mark Modes
/* unlock a run loop and modes before doing callouts/sleeping */
/* never try to take the run loop lock with a mode locked */
/* be very careful of common subexpression elimination and compacting code, particular across locks and unlocks! */
/* run loop mode structures should never be deallocated, even if they become empty */
typedef struct __CFRunLoopMode *CFRunLoopModeRef;
struct __CFRunLoopMode {
CFRuntimeBase _base;
_CFRecursiveMutex _lock; /* must have the run loop locked before locking this */
CFStringRef _name;
Boolean _stopped;
char _padding[3];
CFMutableSetRef _sources0;
CFMutableSetRef _sources1;
CFMutableArrayRef _observers;
CFMutableArrayRef _timers;
CFMutableDictionaryRef _portToV1SourceMap;
__CFPortSet _portSet;
CFIndex _observerMask;
#if USE_DISPATCH_SOURCE_FOR_TIMERS
dispatch_source_t _timerSource;
dispatch_queue_t _queue;
Boolean _timerFired; // set to true by the source when a timer has fired
Boolean _dispatchTimerArmed;
#endif
__CFPort _timerPort;
Boolean _mkTimerArmed;
#if TARGET_OS_WIN32
DWORD _msgQMask;
void (*_msgPump)(void);
#endif
uint64_t _timerSoftDeadline; /* TSR */
uint64_t _timerHardDeadline; /* TSR */
};
CF_INLINE void __CFRunLoopModeLock(CFRunLoopModeRef rlm) {
_CFRecursiveMutexLock(&(rlm->_lock));
//CFLog(6, CFSTR("__CFRunLoopModeLock locked %p"), rlm);
}
CF_INLINE void __CFRunLoopModeUnlock(CFRunLoopModeRef rlm) {
//CFLog(6, CFSTR("__CFRunLoopModeLock unlocking %p"), rlm);
_CFRecursiveMutexUnlock(&(rlm->_lock));
}
static Boolean __CFRunLoopModeEqual(CFTypeRef cf1, CFTypeRef cf2) {
CFRunLoopModeRef rlm1 = (CFRunLoopModeRef)cf1;
CFRunLoopModeRef rlm2 = (CFRunLoopModeRef)cf2;
return CFEqual(rlm1->_name, rlm2->_name);
}
static CFHashCode __CFRunLoopModeHash(CFTypeRef cf) {
CFRunLoopModeRef rlm = (CFRunLoopModeRef)cf;
return CFHash(rlm->_name);
}
static CFStringRef __CFRunLoopModeCopyDescription(CFTypeRef cf) {
CFRunLoopModeRef rlm = (CFRunLoopModeRef)cf;
CFMutableStringRef result;
result = CFStringCreateMutable(kCFAllocatorSystemDefault, 0);
CFStringAppendFormat(result, NULL, CFSTR("<CFRunLoopMode %p [%p]>{name = %@, "), rlm, CFGetAllocator(rlm), rlm->_name);
CFStringAppendFormat(result, NULL, CFSTR("port set = 0x%x, "), rlm->_portSet);
#if USE_DISPATCH_SOURCE_FOR_TIMERS
CFStringAppendFormat(result, NULL, CFSTR("queue = %p, "), rlm->_queue);
CFStringAppendFormat(result, NULL, CFSTR("source = %p (%s), "), rlm->_timerSource, rlm->_timerFired ? "fired" : "not fired");
#endif
CFStringAppendFormat(result, NULL, CFSTR("timer port = 0x%x, "), rlm->_timerPort);
#if TARGET_OS_WIN32
CFStringAppendFormat(result, NULL, CFSTR("MSGQ mask = %p, "), rlm->_msgQMask);
#endif
CFStringAppendFormat(result, NULL, CFSTR("\n\tsources0 = %@,\n\tsources1 = %@,\n\tobservers = %@,\n\ttimers = %@,\n\tcurrently %0.09g (%lld) / soft deadline in: %0.09g sec (@ %lld) / hard deadline in: %0.09g sec (@ %lld)\n},\n"), rlm->_sources0, rlm->_sources1, rlm->_observers, rlm->_timers, CFAbsoluteTimeGetCurrent(), mach_absolute_time(), __CFTSRToTimeInterval(rlm->_timerSoftDeadline - mach_absolute_time()), rlm->_timerSoftDeadline, __CFTSRToTimeInterval(rlm->_timerHardDeadline - mach_absolute_time()), rlm->_timerHardDeadline);
return result;
}
static void __CFRunLoopModeDeallocate(CFTypeRef cf) {
CFRunLoopModeRef rlm = (CFRunLoopModeRef)cf;
if (NULL != rlm->_sources0) CFRelease(rlm->_sources0);
if (NULL != rlm->_sources1) CFRelease(rlm->_sources1);
if (NULL != rlm->_observers) CFRelease(rlm->_observers);
if (NULL != rlm->_timers) CFRelease(rlm->_timers);
if (NULL != rlm->_portToV1SourceMap) CFRelease(rlm->_portToV1SourceMap);
CFRelease(rlm->_name);
__CFPortSetFree(rlm->_portSet);
#if USE_DISPATCH_SOURCE_FOR_TIMERS
if (rlm->_timerSource) {
dispatch_source_cancel(rlm->_timerSource);
dispatch_release(rlm->_timerSource);
}
if (rlm->_queue) {
dispatch_release(rlm->_queue);
}
#endif
if (CFPORT_NULL != rlm->_timerPort) mk_timer_destroy(rlm->_timerPort);
_CFRecursiveMutexDestroy(&rlm->_lock);
memset((char *)cf + sizeof(CFRuntimeBase), 0x7C, sizeof(struct __CFRunLoopMode) - sizeof(CFRuntimeBase));
}
#pragma mark -
#pragma mark Run Loops
struct _block_item {
struct _block_item *_next;
CFTypeRef _mode; // CFString or CFSet
void (^_block)(void);
};
typedef struct _per_run_data {
uint32_t a;
uint32_t b;
uint32_t stopped;
uint32_t ignoreWakeUps;
} _per_run_data;
struct __CFRunLoop {
CFRuntimeBase _base;
_CFRecursiveMutex _lock; /* locked for accessing mode list */
__CFPort _wakeUpPort; // used for CFRunLoopWakeUp
volatile _per_run_data *_perRunData; // reset for runs of the run loop
_CFThreadRef _pthread;
uint32_t _winthread;
CFMutableSetRef _commonModes;
CFMutableSetRef _commonModeItems;
CFRunLoopModeRef _currentMode;
CFMutableSetRef _modes;
struct _block_item *_blocks_head;
struct _block_item *_blocks_tail;
CFAbsoluteTime _runTime;
CFAbsoluteTime _sleepTime;
CFTypeRef _counterpart;
_Atomic(uint8_t) _fromTSD;
Boolean _perCalloutARP;
CFLock_t _timerTSRLock;
};
/* Bit 0 of the base reserved bits is used for stopped state */
/* Bit 1 of the base reserved bits is used for sleeping state */
/* Bit 2 of the base reserved bits is used for deallocating state */
// When `rl` is 0, will push an ARP unconditionally. A hack to facilitate places where we had ARPs before.
static inline uintptr_t __CFRunLoopPerCalloutARPBegin(CFRunLoopRef rl) {
#if DEPLOYMENT_RUNTIME_OBJC
return !rl || rl->_perCalloutARP ? _CFAutoreleasePoolPush() : 0;
#else
return 0;
#endif
}
static inline void __CFRunLoopPerCalloutARPEnd(const uintptr_t pool) {
#if DEPLOYMENT_RUNTIME_OBJC
if (pool) {
@try {
_CFAutoreleasePoolPop(pool);
} @catch (NSException *e) {
os_log_error(_CFOSLog(), "Caught exception during runloop's autorelease pool drain of client objects %{public}@: %{private}@ userInfo: %{private}@", e.name, e.reason, e.userInfo);
objc_terminate();
} @catch (...) {
objc_terminate();
}
}