queue: c.dispatch.queue_tbacking_allocator_needs_mutex: boolbacking_allocator_mutex: Mutexbacking_allocator: AllocatorDoes not need to be thread-safe if not used elsewhere.
main_fiber: Fibermain_loop_stack: [*]align(builtin.target.stackAlignment()) u8exit_semaphore: c.dispatch.semaphore_tuse_sendfile: UseSendfileuse_fcopyfile: UseFcopyfileleeway: u64futexes: [1 << 8]Futexinit_stderr_writer: c.dispatch.once_tstderr_mutex: Mutexstderr_writer: File.Writerstderr_mode: Io.Terminal.Modescan_environ: c.dispatch.once_tenviron: Environopen_dev_null: c.dispatch.once_tdev_null_file: File.OpenError!Filecsprng_mutex: Mutexcsprng: CsprngEmpirically saw >4KB being used by the llvm aarch64 backend.
Errors that can occur between fork() and execv()
This is either usize or u32. Since, either is fine, let's use the same addBuf function for both writing to a file and sending network messages.
pub fn allocator(ev: *Evented) std.mem.Allocatorfn alloc(userdata: *anyopaque, len: usize, alignment: std.mem.Alignment, ret_addr: usize) ?[*]u8fn resize(userdata: *anyopaque, memory: []u8, alignment: std.mem.Alignment, new_len: usize, ret_addr: usize) boolfn remap(userdata: *anyopaque, memory: []u8, alignment: Alignment, new_len: usize, ret_addr: usize) ?[*]u8fn free(userdata: *anyopaque, memory: []u8, alignment: std.mem.Alignment, ret_addr: usize) voidpub fn io(ev: *Evented) Iopub fn init(ev: *Evented, backing_allocator: Allocator, options: InitOptions) !voidpub fn deinit(ev: *Evented) voidfn yield(ev: *Evented, pending_task: SwitchMessage.PendingTask) voidfn mainLoopEntry() callconv(.naked) voidfn mainLoop(ev: *Evented, message: *const SwitchMessage) callconv(.c) noreturninline fn contextSwitch(message: *const SwitchMessage) *const SwitchMessagefn crashHandler(userdata: ?*anyopaque) voidfn async(userdata: ?*anyopaque, result: []u8, result_alignment: Alignment, context: []const u8, context_alignment: Alignment, start: *const fn(context: *const anyopaque, result: *anyopaque) void) ?*std.Io.AnyFuturefn concurrent(userdata: ?*anyopaque, result_len: usize, result_alignment: Alignment, context: []const u8, context_alignment: Alignment, start: *const fn(context: *const anyopaque, result: *anyopaque) void) Io.ConcurrentError!*std.Io.AnyFuturefn await(userdata: ?*anyopaque, future: *std.Io.AnyFuture, result: []u8, result_alignment: Alignment) voidfn cancel(userdata: ?*anyopaque, future: *std.Io.AnyFuture, result: []u8, result_alignment: Alignment) voidfn groupAsync(userdata: ?*anyopaque, type_erased: *Io.Group, context: []const u8, context_alignment: Alignment, start: *const fn(context: *const anyopaque) void) voidfn groupConcurrent(userdata: ?*anyopaque, type_erased: *Io.Group, context: []const u8, context_alignment: Alignment, start: *const fn(context: *const anyopaque) void) Io.ConcurrentError!voidfn groupAwait(userdata: ?*anyopaque, type_erased: *Io.Group, initial_token: *anyopaque) Io.Cancelable!voidfn groupCancel(userdata: ?*anyopaque, type_erased: *Io.Group, initial_token: *anyopaque) voidfn recancel(userdata: ?*anyopaque) voidfn swapCancelProtection(userdata: ?*anyopaque, new: Io.CancelProtection) Io.CancelProtectionfn checkCancel(userdata: ?*anyopaque) Io.Cancelable!voidfn futexForAddress(ev: *Evented, address: usize) *Futexfn futexWait(userdata: ?*anyopaque, ptr: *const u32, expected: u32, timeout: Io.Timeout) Io.Cancelable!voidfn futexWaitUncancelable(userdata: ?*anyopaque, ptr: *const u32, expected: u32) voidfn futexWake(userdata: ?*anyopaque, ptr: *const u32, max_waiters: u32) voidfn operate(userdata: ?*anyopaque, operation: Io.Operation) Io.Cancelable!Io.Operation.Resultfn fileReadStreaming(ev: *Evented, file: File, data: []const []u8) File.ReadStreamingError!usizefn fileReadStreamingLimit(handle: File.Handle, data: []const []u8, limit: Io.Limit) File.ReadStreamingError!usizefn fileWriteStreaming(ev: *Evented, file: File, header: []const u8, data: []const []const u8, splat: usize) File.Writer.Error!usizefn fileWriteStreamingLimit(handle: File.Handle, header: []const u8, data: []const []const u8, splat: usize, limit: Io.Limit) File.Writer.Error!usizefn deviceIoControl(o: *const Io.Operation.DeviceIoControl) Io.Cancelable!i32fn batchAwaitAsync(userdata: ?*anyopaque, batch: *Io.Batch) Io.Cancelable!voidfn batchAwaitConcurrent(userdata: ?*anyopaque, batch: *Io.Batch, timeout: Io.Timeout) Io.Batch.AwaitConcurrentError!voidfn batchCancel(userdata: ?*anyopaque, batch: *Io.Batch) voidfn batchDrainSubmitted(ev: *Evented, batch: *Io.Batch, concurrency: bool) (Io.ConcurrentError || Io.Cancelable)!?c.dispatch.queue_tIf concurrency is false, error.ConcurrencyUnavailable is unreachable.
fn batchSourceEvent(context: ?*anyopaque) callconv(.c) voidfn batchSourceCancel(context: ?*anyopaque) callconv(.c) voidfn dirCreateDir(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, permissions: Dir.Permissions) Dir.CreateDirError!voidfn dirCreateDirPath(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, permissions: Dir.Permissions) Dir.CreateDirPathError!Dir.CreatePathStatusfn dirCreateDirPathOpen(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, permissions: Dir.Permissions, options: Dir.OpenOptions) Dir.CreateDirPathOpenError!Dirfn dirOpenDir(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.OpenOptions) Dir.OpenError!Dirfn dirStat(userdata: ?*anyopaque, dir: Dir) Dir.StatError!Dir.Statfn dirStatFile(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.StatFileOptions) Dir.StatFileError!File.Statfn dirAccess(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.AccessOptions) Dir.AccessError!voidfn dirCreateFile(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, flags: Dir.CreateFileOptions) File.OpenError!Filefn dirCreateFileAtomic(userdata: ?*anyopaque, dir: Dir, dest_path: []const u8, options: Dir.CreateFileAtomicOptions) Dir.CreateFileAtomicError!File.Atomicfn atomicFileInit(ev: *Evented, dest_basename: []const u8, permissions: File.Permissions, dir: Dir, close_dir_on_deinit: bool) Dir.CreateFileAtomicError!File.Atomicfn dirOpenFile(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, flags: Dir.OpenFileOptions) File.OpenError!Filefn dirClose(userdata: ?*anyopaque, dirs: []const Dir) voidfn dirRead(userdata: ?*anyopaque, dr: *Dir.Reader, buffer: []Dir.Entry) Dir.Reader.Error!usizefn dirRealPath(userdata: ?*anyopaque, dir: Dir, out_buffer: []u8) Dir.RealPathError!usizefn realPath(ev: *Evented, fd: c.fd_t, out_buffer: []u8) File.RealPathError!usizefn dirRealPathFile(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, out_buffer: []u8) Dir.RealPathFileError!usizefn dirDeleteFile(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8) Dir.DeleteFileError!voidfn dirDeleteDir(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8) Dir.DeleteDirError!voidfn dirRename(userdata: ?*anyopaque, old_dir: Dir, old_sub_path: []const u8, new_dir: Dir, new_sub_path: []const u8) Dir.RenameError!voidfn dirRenamePreserve(userdata: ?*anyopaque, old_dir: Dir, old_sub_path: []const u8, new_dir: Dir, new_sub_path: []const u8) Dir.RenamePreserveError!voidfn dirSymLink(userdata: ?*anyopaque, dir: Dir, target_path: []const u8, sym_link_path: []const u8, flags: Dir.SymLinkFlags) Dir.SymLinkError!voidfn dirReadLink(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, buffer: []u8) Dir.ReadLinkError!usizefn dirSetOwner(userdata: ?*anyopaque, dir: Dir, owner: ?File.Uid, group: ?File.Gid) Dir.SetOwnerError!voidfn fchown(fd: c.fd_t, owner: ?File.Uid, group: ?File.Gid) File.SetOwnerError!voidfn dirSetFileOwner(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, owner: ?File.Uid, group: ?File.Gid, options: Dir.SetFileOwnerOptions) Dir.SetFileOwnerError!voidfn dirSetPermissions(userdata: ?*anyopaque, dir: Dir, permissions: Dir.Permissions) Dir.SetPermissionsError!voidfn dirSetFilePermissions(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, permissions: Dir.Permissions, options: Dir.SetFilePermissionsOptions) Dir.SetFilePermissionsError!voidfn dirSetTimestamps(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.SetTimestampsOptions) Dir.SetTimestampsError!voidfn dirHardLink(userdata: ?*anyopaque, old_dir: Dir, old_sub_path: []const u8, new_dir: Dir, new_sub_path: []const u8, options: Dir.HardLinkOptions) Dir.HardLinkError!voidfn fileStat(userdata: ?*anyopaque, file: File) File.StatError!File.Statfn fileLength(userdata: ?*anyopaque, file: File) File.LengthError!u64fn fileClose(userdata: ?*anyopaque, files: []const File) voidfn fileWritePositional(userdata: ?*anyopaque, file: File, header: []const u8, data: []const []const u8, splat: usize, offset: u64) File.WritePositionalError!usizefn fileWriteFileStreaming(userdata: ?*anyopaque, file: File, header: []const u8, file_reader: *File.Reader, limit: Io.Limit) File.Writer.WriteFileError!usizefn fileWriteFilePositional(userdata: ?*anyopaque, file: File, header: []const u8, file_reader: *File.Reader, limit: Io.Limit, offset: u64) File.WriteFilePositionalError!usizefn fileReadPositional(userdata: ?*anyopaque, file: File, data: []const []u8, offset: u64) File.ReadPositionalError!usizefn fileSeekBy(userdata: ?*anyopaque, file: File, offset: i64) File.SeekError!voidfn fileSeekTo(userdata: ?*anyopaque, file: File, offset: u64) File.SeekError!voidfn lseek(ev: *Evented, fd: c.fd_t, offset: u64, whence: i32) File.SeekError!voidfn fileSync(userdata: ?*anyopaque, file: File) File.SyncError!voidfn fileIsTty(userdata: ?*anyopaque, file: File) Io.Cancelable!boolfn fileEnableAnsiEscapeCodes(userdata: ?*anyopaque, file: File) File.EnableAnsiEscapeCodesError!voidfn fileSetLength(userdata: ?*anyopaque, file: File, length: u64) File.SetLengthError!voidfn fileSetOwner(userdata: ?*anyopaque, file: File, owner: ?File.Uid, group: ?File.Gid) File.SetOwnerError!voidfn fileSetPermissions(userdata: ?*anyopaque, file: File, permissions: File.Permissions) File.SetPermissionsError!voidfn fchmod(ev: *Evented, fd: c.fd_t, mode: c.mode_t) File.SetPermissionsError!voidfn fileSetTimestamps(userdata: ?*anyopaque, file: File, options: File.SetTimestampsOptions) File.SetTimestampsError!voidfn fileLock(userdata: ?*anyopaque, file: File, lock: File.Lock) File.LockError!voidfn fileTryLock(userdata: ?*anyopaque, file: File, lock: File.Lock) File.LockError!boolfn fileUnlock(userdata: ?*anyopaque, file: File) voidfn fileDowngradeLock(userdata: ?*anyopaque, file: File) File.DowngradeLockError!voidfn fileRealPath(userdata: ?*anyopaque, file: File, out_buffer: []u8) File.RealPathError!usizefn fileHardLink(userdata: ?*anyopaque, file: File, new_dir: Dir, new_sub_path: []const u8, options: File.HardLinkOptions) File.HardLinkError!voidfn linkat(old_dir: c.fd_t, old_path: [*: 0]const u8, new_dir: c.fd_t, new_path: [*: 0]const u8, flags: u32) File.HardLinkError!voidfn fileMemoryMapCreate(userdata: ?*anyopaque, file: File, options: File.MemoryMap.CreateOptions) File.MemoryMap.CreateError!File.MemoryMapfn fileMemoryMapDestroy(userdata: ?*anyopaque, mm: *File.MemoryMap) voidfn fileMemoryMapSetLength(userdata: ?*anyopaque, mm: *File.MemoryMap, new_len: usize) File.MemoryMap.SetLengthError!voidfn fileMemoryMapRead(userdata: ?*anyopaque, mm: *File.MemoryMap) File.ReadPositionalError!voidfn fileMemoryMapWrite(userdata: ?*anyopaque, mm: *File.MemoryMap) File.WritePositionalError!voidfn processExecutableOpen(userdata: ?*anyopaque, flags: Dir.OpenFileOptions) process.OpenExecutableError!Filefn processExecutablePath(userdata: ?*anyopaque, out_buffer: []u8) process.ExecutablePathError!usizefn lockStderr(userdata: ?*anyopaque, terminal_mode: ?Io.Terminal.Mode) Io.Cancelable!Io.LockedStderrfn tryLockStderr(userdata: ?*anyopaque, terminal_mode: ?Io.Terminal.Mode) Io.Cancelable!?Io.LockedStderrfn initLockedStderr(ev: *Evented, terminal_mode: ?Io.Terminal.Mode) Io.Cancelable!Io.LockedStderrfn initStderrWriter(context: ?*anyopaque) callconv(.c) voidfn unlockStderr(userdata: ?*anyopaque) voidfn processCurrentPath(userdata: ?*anyopaque, buffer: []u8) process.CurrentPathError!usizefn processSetCurrentDir(userdata: ?*anyopaque, dir: Dir) process.SetCurrentDirError!voidfn processSetCurrentPath(userdata: ?*anyopaque, dir_path: []const u8) process.SetCurrentPathError!voidfn processReplace(userdata: ?*anyopaque, options: process.ReplaceOptions) process.ReplaceErrorfn processReplacePath(userdata: ?*anyopaque, dir: Dir, options: process.ReplaceOptions) process.ReplaceErrorfn processSpawn(userdata: ?*anyopaque, options: process.SpawnOptions) process.SpawnError!process.Childfn processSpawnPath(userdata: ?*anyopaque, dir: Dir, options: process.SpawnOptions) process.SpawnError!process.Childfn spawn(ev: *Evented, options: process.SpawnOptions) process.SpawnError!Spawnedfn openDevNullFile(context: ?*anyopaque) callconv(.c) voidfn setUpChild(ev: *Evented, options: structfn setUpChildIo(ev: *Evented, stdio: process.SpawnOptions.StdIo, pipe_fd: c.fd_t, std_fileno: i32, dev_null_fd: c.fd_t) !voidfn pipe2(flags: c.O) PipeError![2]c.fd_tfn destroyPipe(pipe: [2]c.fd_t) voidfn dup2(ev: *Evented, old_fd: c.fd_t, new_fd: c.fd_t) DupError!voidfn execv(ev: *Evented, arg0_expand: process.ArgExpansion, file: [*: 0]const u8, child_argv: [*: null]?[*: 0]const u8, env_block: process.Environ.PosixBlock, PATH: []const u8) process.ReplaceErrorfn execvPath(ev: *Evented, path: [*: 0]const u8, child_argv: [*: null]const ?[*: 0]const u8, env_block: process.Environ.PosixBlock) process.ReplaceErrorThis function ignores PATH environment variable.
fn childWait(userdata: ?*anyopaque, child: *process.Child) process.Child.WaitError!process.Child.Termfn childKill(userdata: ?*anyopaque, child: *process.Child) voidfn childCleanup(ev: *Evented, child: *process.Child) voidfn progressParentFile(userdata: ?*anyopaque) std.Progress.ParentFileError!Filefn scanEnviron(context: ?*anyopaque) callconv(.c) voidfn now(userdata: ?*anyopaque, clock: Io.Clock) Io.Timestampfn clockResolution(userdata: ?*anyopaque, clock: Io.Clock) Io.Clock.ResolutionError!Io.Durationfn sleep(userdata: ?*anyopaque, timeout: Io.Timeout) Io.Cancelable!voidfn timeFromTimeout(ev: *Evented, timeout: Io.Timeout) c.dispatch.time_tfn random(userdata: ?*anyopaque, buffer: []u8) voidfn randomSecure(userdata: ?*anyopaque, buffer: []u8) Io.RandomSecureError!voidfn netListenIpUnavailable(userdata: ?*anyopaque, address: *const net.IpAddress, options: net.IpAddress.ListenOptions) net.IpAddress.ListenError!net.Socketfn netAcceptUnavailable(userdata: ?*anyopaque, listen_handle: net.Socket.Handle, options: net.Server.AcceptOptions) net.Server.AcceptError!net.Socketfn netBindIpUnavailable(userdata: ?*anyopaque, address: *const net.IpAddress, options: net.IpAddress.BindOptions) net.IpAddress.BindError!net.Socketfn netConnectIpUnavailable(userdata: ?*anyopaque, address: *const net.IpAddress, options: net.IpAddress.ConnectOptions) net.IpAddress.ConnectError!net.Socketfn netListenUnixUnavailable(userdata: ?*anyopaque, address: *const net.UnixAddress, options: net.UnixAddress.ListenOptions) net.UnixAddress.ListenError!net.Socket.Handlefn netConnectUnixUnavailable(userdata: ?*anyopaque, address: *const net.UnixAddress) net.UnixAddress.ConnectError!net.Socket.Handlefn netSocketCreatePairUnavailable(userdata: ?*anyopaque, options: net.Socket.CreatePairOptions) net.Socket.CreatePairError![2]net.Socketfn netWriteFileUnavailable(userdata: ?*anyopaque, socket_handle: net.Socket.Handle, header: []const u8, file_reader: *File.Reader, limit: Io.Limit) net.Stream.Writer.WriteFileError!usizefn netClose(userdata: ?*anyopaque, sockets: []const net.Socket) voidfn netShutdownUnavailable(userdata: ?*anyopaque, handle: net.Socket.Handle, how: net.ShutdownHow) net.ShutdownError!voidfn netInterfaceNameResolveUnavailable(userdata: ?*anyopaque, name: *const net.Interface.Name) net.Interface.Name.ResolveError!net.Interfacefn netInterfaceNameUnavailable(userdata: ?*anyopaque, interface: net.Interface) net.Interface.NameError!net.Interface.Namefn netLookupUnavailable(userdata: ?*anyopaque, host_name: net.HostName, resolved: *Io.Queue(net.HostName.LookupResult), options: net.HostName.LookupOptions) net.HostName.LookupError!voidfn readAll(ev: *Evented, file: File, buffer: []u8) File.ReadStreamingError!voidfn writeAll(ev: *Evented, file: File, buffer: []const u8) (File.Writer.Error || errorfn addConstBuf(v: []iovec_const, i: *iovlen_t, remaining: ?*usize, bytes: []const u8) voidfn addBuf(comptime is_const: bool, vec: []if(is_const) iovec_const else iovec, vec_len: *iovlen_t, remaining: *Io.Limit, bytes: if(is_const) []const u8 else []u8) void1
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986const Alignment = std.mem.Alignment;
const Allocator = std.mem.Allocator;
const Argv0 = Io.Threaded.Argv0;
const assert = std.debug.assert;
const builtin = @import("builtin");
const c = std.c;
const ChdirError = Io.Threaded.ChdirError;
const clockToPosix = Io.Threaded.clockToPosix;
const closeFd = Io.Threaded.closeFd;
const Csprng = Io.Threaded.Csprng;
const default_PATH = Io.Threaded.default_PATH;
const Dir = Io.Dir;
const Environ = Io.Threaded.Environ;
const errnoBug = Io.Threaded.errnoBug;
const Evented = @This();
const fallbackSeed = Io.Threaded.fallbackSeed;
const File = Io.File;
const Io = std.Io;
const iovec = std.posix.iovec;
const iovec_const = std.posix.iovec_const;
const log = std.log.scoped(.dispatch);
const max_iovecs_len = Io.Threaded.max_iovecs_len;
const nanosecondsFromPosix = Io.Threaded.nanosecondsFromPosix;
const net = Io.net;
const pathToPosix = Io.Threaded.pathToPosix;
const process = std.process;
const recoverableOsBugDetected = Io.Threaded.recoverableOsBugDetected;
const setTimestampToPosix = Io.Threaded.setTimestampToPosix;
const splat_buffer_size = Io.Threaded.splat_buffer_size;
const statFromPosix = Io.Threaded.statFromPosix;
const statusToTerm = Io.Threaded.statusToTerm;
const std = @import("std");
const timestampFromPosix = Io.Threaded.timestampFromPosix;
const unexpectedErrno = std.posix.unexpectedErrno;
const UseSendfile = Io.Threaded.UseSendfile;
const UseFcopyfile = Io.Threaded.UseFcopyfile;
/// Empirically saw >4KB being used by the llvm aarch64 backend.
const main_loop_stack_size = 8 * 1024;
queue: c.dispatch.queue_t,
backing_allocator_needs_mutex: bool,
backing_allocator_mutex: Mutex,
/// Does not need to be thread-safe if not used elsewhere.
backing_allocator: Allocator,
main_fiber: Fiber,
main_loop_stack: [*]align(builtin.target.stackAlignment()) u8,
exit_semaphore: c.dispatch.semaphore_t,
use_sendfile: UseSendfile,
use_fcopyfile: UseFcopyfile,
leeway: u64,
futexes: [1 << 8]Futex,
init_stderr_writer: c.dispatch.once_t,
stderr_mutex: Mutex,
stderr_writer: File.Writer,
stderr_mode: Io.Terminal.Mode,
scan_environ: c.dispatch.once_t,
environ: Environ,
open_dev_null: c.dispatch.once_t,
dev_null_file: File.OpenError!File,
csprng_mutex: Mutex,
csprng: Csprng,
const Thread = struct {
main_context: Io.fiber.Context,
current_context: ?*Io.fiber.Context,
seed_csprng: c.dispatch.once_t,
csprng: Csprng,
threadlocal var self: Thread = .{
.main_context = undefined,
.current_context = null,
.seed_csprng = .init,
.csprng = undefined,
};
noinline fn current() *Thread {
return &self;
}
fn currentFiber(thread: *Thread) *Fiber {
assert(thread.current_context != &thread.main_context);
return @fieldParentPtr("context", thread.current_context.?);
}
const List = struct {
allocated: []Thread,
reserved: u32,
active: u32,
};
};
const Fiber = struct {
required_align: void align(4),
evented: *Evented,
context: Io.fiber.Context,
link: union {
awaiter: ?*Fiber,
group: struct { prev: ?*Fiber, next: ?*Fiber },
},
awaiting_group: Group,
cancel_status: CancelStatus,
cancel_protection: CancelProtection,
var next_name: u64 = 0;
const CancelStatus = packed struct(usize) {
requested: bool,
awaiting: Awaiting,
const unrequested: CancelStatus = .{ .requested = false, .awaiting = .nothing };
const Awaiting = enum(@Int(.unsigned, @bitSizeOf(usize) - shift)) {
nothing = 0,
group = 1,
_,
const shift = 1;
fn subWrap(lhs: Awaiting, rhs: Awaiting) Awaiting {
return @fromBackingInt(@intCast(@backingInt(lhs) -% @backingInt(rhs)));
}
fn fromCancelable(cancelable: *Cancelable) Awaiting {
return @fromBackingInt(@intCast(@shrExact(@intFromPtr(cancelable), shift)));
}
fn toCancelable(awaiting: Awaiting) *Cancelable {
return @ptrFromInt(@shlExact(@as(usize, @backingInt(awaiting)), shift));
}
};
fn changeAwaiting(
cancel_status: *CancelStatus,
old_awaiting: Awaiting,
new_awaiting: Awaiting,
) bool {
const old_cancel_status = @atomicRmw(CancelStatus, cancel_status, .Add, .{
.requested = false,
.awaiting = new_awaiting.subWrap(old_awaiting),
}, .release);
assert(old_cancel_status.awaiting == old_awaiting);
return old_cancel_status.requested;
}
};
const CancelProtection = packed struct {
user: Io.CancelProtection,
acknowledged: bool,
const unblocked: CancelProtection = .{ .user = .unblocked, .acknowledged = false };
fn check(cancel_protection: CancelProtection) Io.CancelProtection {
return @fromBackingInt(@intCast(@intFromBool(cancel_protection != unblocked)));
}
fn acknowledge(cancel_protection: *CancelProtection) void {
assert(!cancel_protection.acknowledged);
cancel_protection.acknowledged = true;
}
fn recancel(cancel_protection: *CancelProtection) void {
assert(cancel_protection.acknowledged);
cancel_protection.acknowledged = false;
}
test check {
try std.testing.expectEqual(Io.CancelProtection.unblocked, check(.unblocked));
try std.testing.expectEqual(Io.CancelProtection.blocked, check(.{
.user = .unblocked,
.acknowledged = true,
}));
try std.testing.expectEqual(Io.CancelProtection.blocked, check(.{
.user = .blocked,
.acknowledged = false,
}));
try std.testing.expectEqual(Io.CancelProtection.blocked, check(.{
.user = .blocked,
.acknowledged = true,
}));
}
};
const finished: ?*Fiber = @ptrFromInt(@alignOf(Fiber));
const max_result_align: Alignment = .@"16";
const max_result_size = max_result_align.forward(512);
/// This includes any stack realignments that need to happen, and also the
/// initial frame return address slot and argument frame, depending on target.
const min_stack_size = 60 * 1024 * 1024;
const max_context_align: Alignment = .@"16";
const max_context_size = max_context_align.forward(1024);
const max_closure_size: usize = @sizeOf(AsyncClosure);
const max_closure_align: Alignment = .of(AsyncClosure);
const allocation_size = std.mem.alignForward(
usize,
max_closure_align.max(max_context_align).forward(
max_result_align.forward(@sizeOf(Fiber)) + max_result_size + min_stack_size,
) + max_closure_size + max_context_size,
std.heap.page_size_max,
);
fn create(ev: *Evented) error{OutOfMemory}!*Fiber {
return @ptrCast(try ev.allocator().alignedAlloc(u8, .of(Fiber), allocation_size));
}
fn destroy(fiber: *Fiber, ev: *Evented) void {
ev.allocator().free(fiber.allocatedSlice());
}
fn allocatedSlice(f: *Fiber) []align(@alignOf(Fiber)) u8 {
return @as([*]align(@alignOf(Fiber)) u8, @ptrCast(f))[0..allocation_size];
}
fn allocatedEnd(f: *Fiber) [*]u8 {
const allocated_slice = f.allocatedSlice();
return allocated_slice[allocated_slice.len..].ptr;
}
fn resultPointer(f: *Fiber, comptime Result: type) *Result {
return @ptrCast(@alignCast(f.resultBytes(.of(Result))));
}
fn resultBytes(f: *Fiber, alignment: Alignment) [*]u8 {
return @ptrFromInt(alignment.forward(@intFromPtr(f) + @sizeOf(Fiber)));
}
const Queue = struct { head: *Fiber, tail: *Fiber };
/// Like a `*Fiber`, but 2 bits smaller than a pointer (because the LSBs are always 0 due to
/// alignment) so that those two bits can be used in a `packed struct`.
const PackedPtr = enum(@Int(.unsigned, @bitSizeOf(usize) - 2)) {
null = 0,
all_ones = std.math.maxInt(@Int(.unsigned, @bitSizeOf(usize) - 2)),
_,
const Split = packed struct(usize) { low: u2, high: PackedPtr };
fn pack(ptr: ?*Fiber) PackedPtr {
const split: Split = @bitCast(@intFromPtr(ptr));
assert(split.low == 0);
return split.high;
}
fn unpack(ptr: PackedPtr) ?*Fiber {
const split: Split = .{ .low = 0, .high = ptr };
return @ptrFromInt(@as(usize, @bitCast(split)));
}
};
fn requestCancel(fiber: *Fiber, ev: *Evented) void {
const cancel_status = @atomicRmw(
Fiber.CancelStatus,
&fiber.cancel_status,
.Or,
.{ .requested = true, .awaiting = .nothing },
.acquire,
);
assert(!cancel_status.requested);
switch (cancel_status.awaiting) {
.nothing => {},
.group => {
// The awaiter received a cancelation request while awaiting a group,
// so propagate the cancelation to the group.
if (fiber.awaiting_group.cancel(ev, null)) {
fiber.awaiting_group = undefined;
ev.queue.async(fiber, &Fiber.@"resume");
}
},
_ => |awaiting| awaiting.toCancelable().async(),
}
}
fn @"resume"(context: ?*anyopaque) callconv(.c) void {
const fiber: *Fiber = @ptrCast(@alignCast(context));
const thread: *Thread = .current();
const message: SwitchMessage = .{
.contexts = .{
.old = &thread.main_context,
.new = &fiber.context,
},
.pending_task = .nothing,
};
contextSwitch(&message).handle(fiber.evented);
}
};
pub fn allocator(ev: *Evented) std.mem.Allocator {
return if (ev.backing_allocator_needs_mutex) .{
.ptr = ev,
.vtable = &.{
.alloc = alloc,
.resize = resize,
.remap = remap,
.free = free,
},
} else ev.backing_allocator;
}
fn alloc(userdata: *anyopaque, len: usize, alignment: std.mem.Alignment, ret_addr: usize) ?[*]u8 {
const ev: *Evented = @ptrCast(@alignCast(userdata));
ev.backing_allocator_mutex.lockUncancelable(ev);
defer ev.backing_allocator_mutex.unlock();
return ev.backing_allocator.rawAlloc(len, alignment, ret_addr);
}
fn resize(
userdata: *anyopaque,
memory: []u8,
alignment: std.mem.Alignment,
new_len: usize,
ret_addr: usize,
) bool {
const ev: *Evented = @ptrCast(@alignCast(userdata));
ev.backing_allocator_mutex.lockUncancelable(ev);
defer ev.backing_allocator_mutex.unlock();
return ev.backing_allocator.rawResize(memory, alignment, new_len, ret_addr);
}
fn remap(
userdata: *anyopaque,
memory: []u8,
alignment: Alignment,
new_len: usize,
ret_addr: usize,
) ?[*]u8 {
const ev: *Evented = @ptrCast(@alignCast(userdata));
ev.backing_allocator_mutex.lockUncancelable(ev);
defer ev.backing_allocator_mutex.unlock();
return ev.backing_allocator.rawRemap(memory, alignment, new_len, ret_addr);
}
fn free(userdata: *anyopaque, memory: []u8, alignment: std.mem.Alignment, ret_addr: usize) void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
ev.backing_allocator_mutex.lockUncancelable(ev);
defer ev.backing_allocator_mutex.unlock();
return ev.backing_allocator.rawFree(memory, alignment, ret_addr);
}
pub fn io(ev: *Evented) Io {
return .{
.userdata = ev,
.vtable = &.{
.crashHandler = crashHandler,
.async = async,
.concurrent = concurrent,
.await = await,
.cancel = cancel,
.groupAsync = groupAsync,
.groupConcurrent = groupConcurrent,
.groupAwait = groupAwait,
.groupCancel = groupCancel,
.recancel = recancel,
.swapCancelProtection = swapCancelProtection,
.checkCancel = checkCancel,
.futexWait = futexWait,
.futexWaitUncancelable = futexWaitUncancelable,
.futexWake = futexWake,
.operate = operate,
.batchAwaitAsync = batchAwaitAsync,
.batchAwaitConcurrent = batchAwaitConcurrent,
.batchCancel = batchCancel,
.dirCreateDir = dirCreateDir,
.dirCreateDirPath = dirCreateDirPath,
.dirCreateDirPathOpen = dirCreateDirPathOpen,
.dirOpenDir = dirOpenDir,
.dirStat = dirStat,
.dirStatFile = dirStatFile,
.dirAccess = dirAccess,
.dirCreateFile = dirCreateFile,
.dirCreateFileAtomic = dirCreateFileAtomic,
.dirOpenFile = dirOpenFile,
.dirClose = dirClose,
.dirRead = dirRead,
.dirRealPath = dirRealPath,
.dirRealPathFile = dirRealPathFile,
.dirDeleteFile = dirDeleteFile,
.dirDeleteDir = dirDeleteDir,
.dirRename = dirRename,
.dirRenamePreserve = dirRenamePreserve,
.dirSymLink = dirSymLink,
.dirReadLink = dirReadLink,
.dirSetOwner = dirSetOwner,
.dirSetFileOwner = dirSetFileOwner,
.dirSetPermissions = dirSetPermissions,
.dirSetFilePermissions = dirSetFilePermissions,
.dirSetTimestamps = dirSetTimestamps,
.dirHardLink = dirHardLink,
.fileStat = fileStat,
.fileLength = fileLength,
.fileClose = fileClose,
.fileWritePositional = fileWritePositional,
.fileWriteFileStreaming = fileWriteFileStreaming,
.fileWriteFilePositional = fileWriteFilePositional,
.fileReadPositional = fileReadPositional,
.fileSeekBy = fileSeekBy,
.fileSeekTo = fileSeekTo,
.fileSync = fileSync,
.fileIsTty = fileIsTty,
.fileEnableAnsiEscapeCodes = fileEnableAnsiEscapeCodes,
.fileSupportsAnsiEscapeCodes = fileIsTty,
.fileSetLength = fileSetLength,
.fileSetOwner = fileSetOwner,
.fileSetPermissions = fileSetPermissions,
.fileSetTimestamps = fileSetTimestamps,
.fileLock = fileLock,
.fileTryLock = fileTryLock,
.fileUnlock = fileUnlock,
.fileDowngradeLock = fileDowngradeLock,
.fileRealPath = fileRealPath,
.fileHardLink = fileHardLink,
.fileMemoryMapCreate = fileMemoryMapCreate,
.fileMemoryMapDestroy = fileMemoryMapDestroy,
.fileMemoryMapSetLength = fileMemoryMapSetLength,
.fileMemoryMapRead = fileMemoryMapRead,
.fileMemoryMapWrite = fileMemoryMapWrite,
.processExecutableOpen = processExecutableOpen,
.processExecutablePath = processExecutablePath,
.lockStderr = lockStderr,
.tryLockStderr = tryLockStderr,
.unlockStderr = unlockStderr,
.processCurrentPath = processCurrentPath,
.processSetCurrentDir = processSetCurrentDir,
.processSetCurrentPath = processSetCurrentPath,
.processReplace = processReplace,
.processReplacePath = processReplacePath,
.processSpawn = processSpawn,
.processSpawnPath = processSpawnPath,
.childWait = childWait,
.childKill = childKill,
.progressParentFile = progressParentFile,
.now = now,
.clockResolution = clockResolution,
.sleep = sleep,
.random = random,
.randomSecure = randomSecure,
.netListenIp = netListenIpUnavailable,
.netAccept = netAcceptUnavailable,
.netBindIp = netBindIpUnavailable,
.netConnectIp = netConnectIpUnavailable,
.netListenUnix = netListenUnixUnavailable,
.netConnectUnix = netConnectUnixUnavailable,
.netSocketCreatePair = netSocketCreatePairUnavailable,
.netWriteFile = netWriteFileUnavailable,
.netClose = netClose,
.netShutdown = netShutdownUnavailable,
.netInterfaceNameResolve = netInterfaceNameResolveUnavailable,
.netInterfaceName = netInterfaceNameUnavailable,
.netLookup = netLookupUnavailable,
},
};
}
pub const InitOptions = struct {
backing_allocator_needs_mutex: bool = true,
target_queue: ?c.dispatch.queue_t = .TARGET_DEFAULT,
/// Upper limit on the allowable delay in processing timeouts in order to improve power
/// consumption and system performance.
leeway: Io.Duration = .fromMilliseconds(10),
/// Affects the following operations:
/// * `processExecutablePath` on OpenBSD and Haiku.
argv0: Argv0 = .empty,
/// Affects the following operations:
/// * `fileIsTty`
/// * `processSpawn`, `processSpawnPath`, `processReplace`, `processReplacePath`
environ: process.Environ = .empty,
};
pub fn init(ev: *Evented, backing_allocator: Allocator, options: InitOptions) !void {
const queue = c.dispatch.queue_create_with_target(
"org.ziglang.std.Io.Dispatch",
.CONCURRENT(),
options.target_queue,
) orelse return error.SystemResources;
errdefer queue.as_object().release();
const main_loop_stack = try backing_allocator.alignedAlloc(
u8,
.fromByteUnits(builtin.target.stackAlignment()),
main_loop_stack_size,
);
errdefer backing_allocator.free(main_loop_stack);
const exit_semaphore = c.dispatch.semaphore_create(0) orelse return error.SystemResources;
errdefer exit_semaphore.as_object().release();
ev.* = .{
.queue = queue,
.backing_allocator_needs_mutex = options.backing_allocator_needs_mutex,
.backing_allocator_mutex = undefined,
.backing_allocator = backing_allocator,
.main_fiber = .{
.required_align = {},
.evented = ev,
.context = undefined,
.link = .{ .awaiter = null },
.awaiting_group = undefined,
.cancel_status = .unrequested,
.cancel_protection = .unblocked,
},
.main_loop_stack = main_loop_stack.ptr,
.exit_semaphore = exit_semaphore,
.use_fcopyfile = .default,
.use_sendfile = .default,
.leeway = std.math.lossyCast(u64, options.leeway.toNanoseconds()),
.futexes = undefined,
.init_stderr_writer = .init,
.stderr_mutex = undefined,
.stderr_writer = .{
.io = ev.io(),
.interface = Io.File.Writer.initInterface(&.{}),
.file = .stderr(),
.mode = .streaming,
},
.stderr_mode = .no_color,
.scan_environ = if (options.environ.block.isEmpty()) .done else .init,
.environ = .{ .process_environ = options.environ },
.open_dev_null = .init,
.dev_null_file = error.FileNotFound,
.csprng_mutex = undefined,
.csprng = .uninitialized,
};
try ev.backing_allocator_mutex.init(queue);
errdefer ev.backing_allocator_mutex.deinit();
var initialized_futexes: usize = 0;
errdefer for (ev.futexes[0..initialized_futexes]) |*futex| futex.deinit();
for (&ev.futexes) |*futex| {
try futex.init(queue);
initialized_futexes += 1;
}
try ev.stderr_mutex.init(queue);
errdefer ev.stderr_mutex.deinit();
try ev.csprng_mutex.init(queue);
errdefer ev.csprng_mutex.deinit();
const thread: *Thread = .current();
thread.main_context = switch (builtin.cpu.arch) {
.aarch64 => .{
.sp = @intFromPtr(main_loop_stack[main_loop_stack_size..].ptr),
.fp = @intFromPtr(ev),
.pc = @intFromPtr(&mainLoopEntry),
},
.x86_64 => .{
.rsp = @intFromPtr(main_loop_stack[main_loop_stack_size..].ptr) - 8,
.rbp = @intFromPtr(ev),
.rip = @intFromPtr(&mainLoopEntry),
},
else => |arch| @compileError("unimplemented architecture: " ++ @tagName(arch)),
};
thread.current_context = &ev.main_fiber.context;
}
pub fn deinit(ev: *Evented) void {
assert(Thread.current().currentFiber() == &ev.main_fiber);
ev.yield(.exit);
ev.csprng_mutex.deinit();
if (ev.dev_null_file) |file| fileClose(ev, &.{file}) else |_| {}
ev.stderr_mutex.deinit();
for (&ev.futexes) |*futex| futex.deinit();
ev.exit_semaphore.as_object().release();
ev.backing_allocator_mutex.deinit();
ev.backing_allocator.free(ev.main_loop_stack[0..main_loop_stack_size]);
ev.queue.as_object().release();
}
fn yield(ev: *Evented, pending_task: SwitchMessage.PendingTask) void {
const thread: *Thread = .current();
const message: SwitchMessage = .{
.contexts = .{
.old = thread.current_context.?,
.new = &thread.main_context,
},
.pending_task = pending_task,
};
contextSwitch(&message).handle(ev);
}
fn mainLoopEntry() callconv(.naked) void {
switch (builtin.cpu.arch) {
.aarch64 => asm volatile (
\\ mov x0, fp
\\ mov fp, #0
\\ b %[mainLoop]
:
: [mainLoop] "X" (&mainLoop),
),
.x86_64 => asm volatile (
\\ movq %%rbp, %%rdi
\\ xor %%ebp, %%ebp
\\ jmp %[mainLoop:P]
:
: [mainLoop] "X" (&mainLoop),
),
else => |arch| @compileError("unimplemented architecture: " ++ @tagName(arch)),
}
}
fn mainLoop(ev: *Evented, message: *const SwitchMessage) callconv(.c) noreturn {
message.handle(ev);
assert(ev.exit_semaphore.wait(.FOREVER) == 0);
Fiber.@"resume"(&ev.main_fiber);
unreachable; // switched to dead fiber
}
const SwitchMessage = struct {
contexts: Io.fiber.Switch,
pending_task: PendingTask,
const PendingTask = union(enum) {
nothing,
await: *Fiber,
activate: c.dispatch.object_t,
@"resume": c.dispatch.object_t,
group_await: Group,
group_cancel: Group,
mutex_wait: *Mutex.Waiter,
futex_wait: *Futex.Waiter,
futex_wake: *Futex.Waker,
sleep_wait: *SleepWaiter,
after: c.dispatch.time_t,
destroy,
exit,
};
fn handle(message: *const SwitchMessage, ev: *Evented) void {
const thread: *Thread = .current();
thread.current_context = message.contexts.new;
switch (message.pending_task) {
.nothing => {},
.await => |awaiting| {
const awaiter: *Fiber = @alignCast(@fieldParentPtr("context", message.contexts.old));
if (@atomicRmw(?*Fiber, &awaiting.link.awaiter, .Xchg, awaiter, .acq_rel) ==
Fiber.finished) ev.queue.async(awaiter, &Fiber.@"resume");
},
.activate => |object| object.activate(),
.@"resume" => |object| object.@"resume"(),
.group_await => |group| {
const fiber: *Fiber = @alignCast(@fieldParentPtr("context", message.contexts.old));
if (group.await(ev, fiber)) ev.queue.async(fiber, &Fiber.@"resume");
},
.group_cancel => |group| {
const fiber: *Fiber = @alignCast(@fieldParentPtr("context", message.contexts.old));
if (group.cancel(ev, fiber)) ev.queue.async(fiber, &Fiber.@"resume");
},
.mutex_wait => |waiter| {
waiter.sleeper =
.init(ev.queue, @alignCast(@fieldParentPtr("context", message.contexts.old)));
switch (waiter.sleeper.fiber.cancel_protection.check()) {
.unblocked => {},
.blocked => waiter.cancelable = .blocked,
}
waiter.mutex.queue.async(waiter, &Mutex.Waiter.add);
},
.futex_wait => |waiter| {
waiter.sleeper =
.init(ev.queue, @alignCast(@fieldParentPtr("context", message.contexts.old)));
switch (waiter.sleeper.fiber.cancel_protection.check()) {
.unblocked => {},
.blocked => waiter.cancelable = .blocked,
}
waiter.futex.queue.async(waiter, &Futex.Waiter.add);
},
.futex_wake => |waker| {
waker.sleeper =
.init(ev.queue, @alignCast(@fieldParentPtr("context", message.contexts.old)));
waker.futex.queue.async(waker, &Futex.Waker.remove);
},
.sleep_wait => |waiter| {
waiter.sleeper =
.init(ev.queue, @alignCast(@fieldParentPtr("context", message.contexts.old)));
const queue = waiter.cancelable.queue;
switch (waiter.sleeper.fiber.cancel_protection.check()) {
.unblocked => {},
.blocked => waiter.cancelable = .blocked,
}
queue.async(waiter, &SleepWaiter.start);
},
.after => |when| {
const fiber: *Fiber = @alignCast(@fieldParentPtr("context", message.contexts.old));
when.after(ev.queue, fiber, &Fiber.@"resume");
},
.destroy => {
const fiber: *Fiber = @alignCast(@fieldParentPtr("context", message.contexts.old));
fiber.destroy(ev);
},
.exit => _ = ev.exit_semaphore.signal(),
}
}
};
inline fn contextSwitch(message: *const SwitchMessage) *const SwitchMessage {
return @fieldParentPtr("contexts", Io.fiber.contextSwitch(&message.contexts));
}
const Cancelable = struct {
required_align: void align(2) = {},
queue: c.dispatch.queue_t,
cancel: c.dispatch.function_t,
const fn_ptr_align = std.meta.alignment(c.dispatch.function_t);
const is_blocked: c.dispatch.function_t = @ptrFromInt(fn_ptr_align * 1);
const is_requested: c.dispatch.function_t = @ptrFromInt(fn_ptr_align * 2);
const blocked: Cancelable = .{ .queue = undefined, .cancel = is_blocked };
const RequestedError = error{CancelRequested};
fn enter(cancelable: *Cancelable, fiber: *Fiber) RequestedError!void {
const function = cancelable.cancel;
assert(function != is_requested);
if (function == is_blocked) {
@branchHint(.unlikely);
return;
}
if (@cmpxchgStrong(
Fiber.CancelStatus,
&fiber.cancel_status,
.{ .requested = false, .awaiting = .nothing },
.{ .requested = false, .awaiting = .fromCancelable(cancelable) },
.release,
.monotonic,
)) |cancel_status| {
assert(cancel_status.requested and cancel_status.awaiting == .nothing);
cancelable.cancel = is_requested;
return error.CancelRequested;
}
}
fn leave(cancelable: *Cancelable, fiber: *Fiber) RequestedError!void {
const function = cancelable.cancel;
assert(function != is_requested);
if (function == is_blocked) {
@branchHint(.unlikely);
return;
}
const cancel_status = @atomicRmw(Fiber.CancelStatus, &fiber.cancel_status, .And, .{
.requested = true,
.awaiting = .nothing,
}, .monotonic);
assert(cancel_status.awaiting.toCancelable() == cancelable);
if (cancel_status.requested) return error.CancelRequested;
}
fn async(cancelable: *Cancelable) void {
const function = cancelable.cancel;
assert(function != is_blocked and function != is_requested);
cancelable.queue.async(cancelable, function);
}
fn requested(cancelable: *Cancelable, fiber: *Fiber) void {
const function = cancelable.cancel;
assert(function != is_blocked and function != is_requested);
assert(@atomicLoad(Fiber.CancelStatus, &fiber.cancel_status, .monotonic) == Fiber.CancelStatus{
.requested = true,
.awaiting = .fromCancelable(cancelable),
});
cancelable.cancel = is_requested;
@atomicStore(Fiber.CancelStatus, &fiber.cancel_status, .{
.requested = true,
.awaiting = .nothing,
}, .monotonic);
}
fn acknowledge(cancelable: *Cancelable, fiber: *Fiber) Io.Cancelable!void {
if (cancelable.cancel == is_requested) {
@branchHint(.unlikely);
fiber.cancel_protection.acknowledge();
return error.Canceled;
}
}
};
const Sleeper = struct {
queue: c.dispatch.queue_t,
fiber: *Fiber,
fn init(queue: c.dispatch.queue_t, fiber: *Fiber) Sleeper {
queue.as_object().retain();
return .{ .queue = queue, .fiber = fiber };
}
fn wake(context: ?*anyopaque) callconv(.c) void {
const sleeper: *Sleeper = @ptrCast(@alignCast(context));
const queue = sleeper.queue;
sleeper.queue = undefined;
queue.async(sleeper.fiber, &Fiber.@"resume");
queue.as_object().release();
}
};
const Mutex = struct {
state: State,
queue: c.dispatch.queue_t,
waiters: std.DoublyLinkedList,
const State = packed struct(usize) {
locked: bool,
num_waiters: NumWaiters,
const NumWaiters = @Int(.unsigned, @bitSizeOf(usize) - 1);
};
const Waiter = struct {
sleeper: Sleeper = undefined,
cancelable: Cancelable,
mutex: *Mutex,
node: std.DoublyLinkedList.Node = .{},
fn add(context: ?*anyopaque) callconv(.c) void {
const waiter: *Waiter = @ptrCast(@alignCast(context));
waiter.cancelable.enter(waiter.sleeper.fiber) catch |err| switch (err) {
error.CancelRequested => return waiter.wake(),
};
var state = @atomicRmw(State, &waiter.mutex.state, .Add, .{
.locked = false,
.num_waiters = 1,
}, .monotonic);
state.num_waiters += 1;
while (!state.locked) {
@branchHint(.unlikely);
state = @cmpxchgWeak(State, &waiter.mutex.state, state, .{
.locked = true,
.num_waiters = state.num_waiters - 1,
}, .acquire, .monotonic) orelse break;
} else return waiter.mutex.waiters.append(&waiter.node);
waiter.cancelable.leave(waiter.sleeper.fiber) catch |err| switch (err) {
error.CancelRequested => {
waiter.node.next = &waiter.node;
return;
},
};
waiter.wake();
}
fn canceled(context: ?*anyopaque) callconv(.c) void {
const cancelable: *Cancelable = @ptrCast(@alignCast(context));
const waiter: *Waiter = @fieldParentPtr("cancelable", cancelable);
cancelable.requested(waiter.sleeper.fiber);
const mutex = waiter.mutex;
if (waiter.node.next != &waiter.node) {
@branchHint(.likely);
mutex.waiters.remove(&waiter.node);
assert(@atomicRmw(State, &mutex.state, .Sub, .{
.locked = false,
.num_waiters = 1,
}, .monotonic).num_waiters >= 1);
}
waiter.node = undefined;
waiter.wake();
}
fn remove(context: ?*anyopaque) callconv(.c) void {
const mutex: *Mutex = @ptrCast(@alignCast(context));
var state = @atomicLoad(State, &mutex.state, .monotonic);
while (!state.locked and state.num_waiters > 0) {
@branchHint(.likely);
state = @cmpxchgWeak(State, &mutex.state, state, .{
.locked = true,
.num_waiters = state.num_waiters - 1,
}, .acquire, .monotonic) orelse break;
} else return;
var num_removed: State.NumWaiters = 0;
while (mutex.waiters.popFirst()) |node| {
@branchHint(.likely);
const waiter: *Waiter = @fieldParentPtr("node", node);
node.* = undefined;
waiter.cancelable.leave(waiter.sleeper.fiber) catch |err| switch (err) {
error.CancelRequested => {
num_removed += 1;
node.next = node;
continue;
},
};
break;
}
if (num_removed > 0) {
@branchHint(.unlikely);
assert(@atomicRmw(State, &mutex.state, .Sub, .{
.locked = false,
.num_waiters = num_removed,
}, .monotonic).num_waiters >= num_removed);
}
}
fn wake(waiter: *Waiter) void {
Sleeper.wake(&waiter.sleeper);
}
};
fn init(mutex: *Mutex, queue: c.dispatch.queue_t) error{SystemResources}!void {
mutex.* = .{
.state = .{ .locked = false, .num_waiters = 0 },
.queue = c.dispatch.queue_create_with_target(
"org.ziglang.std.Io.Dispatch.Mutex",
.SERIAL(),
queue,
) orelse return error.SystemResources,
.waiters = .{},
};
}
fn deinit(mutex: *Mutex) void {
assert(mutex.state == State{ .locked = false, .num_waiters = 0 });
assert(mutex.waiters.first == null and mutex.waiters.last == null);
mutex.queue.as_object().release();
mutex.* = undefined;
}
fn tryLock(mutex: *Mutex) bool {
const state =
@atomicRmw(State, &mutex.state, .Or, .{ .locked = true, .num_waiters = 0 }, .acquire);
if (state.locked) {
@branchHint(.unlikely);
}
return !state.locked;
}
fn lock(mutex: *Mutex, ev: *Evented) Io.Cancelable!void {
if (mutex.tryLock()) return;
var waiter: Waiter = .{
.cancelable = .{ .queue = mutex.queue, .cancel = &Mutex.Waiter.canceled },
.mutex = mutex,
};
ev.yield(.{ .mutex_wait = &waiter });
try waiter.cancelable.acknowledge(waiter.sleeper.fiber);
}
fn lockUncancelable(mutex: *Mutex, ev: *Evented) void {
if (mutex.tryLock()) return;
var waiter: Waiter = .{ .cancelable = .blocked, .mutex = mutex };
ev.yield(.{ .mutex_wait = &waiter });
waiter.cancelable.acknowledge(waiter.sleeper.fiber) catch |err| switch (err) {
error.Canceled => unreachable, // blocked
};
}
fn unlock(mutex: *Mutex) void {
const state = @atomicRmw(State, &mutex.state, .And, .{
.locked = false,
.num_waiters = std.math.maxInt(State.NumWaiters),
}, .release);
if (state.num_waiters > 0) {
@branchHint(.unlikely);
mutex.queue.async(mutex, &Waiter.remove);
}
}
};
fn crashHandler(userdata: ?*anyopaque) void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
const thread = &Thread.self;
if (thread.current_context == null) std.process.abort();
if (thread.current_context == &thread.main_context) std.process.abort();
const fiber = thread.currentFiber();
@atomicStore(
Fiber.CancelStatus,
&fiber.cancel_status,
.{ .requested = true, .awaiting = .nothing },
.monotonic,
);
fiber.cancel_protection = .{ .user = .blocked, .acknowledged = true };
}
const AsyncClosure = struct {
evented: *Evented,
fiber: *Fiber,
start: *const fn (context: *const anyopaque, result: *anyopaque) void,
result_align: Alignment,
fn fromFiber(fiber: *Fiber) *AsyncClosure {
return @ptrFromInt(Fiber.max_context_align.max(.of(AsyncClosure)).backward(
@intFromPtr(fiber.allocatedEnd()) - Fiber.max_context_size,
) - @sizeOf(AsyncClosure));
}
fn contextPointer(closure: *AsyncClosure) [*]align(Fiber.max_context_align.toByteUnits()) u8 {
return @alignCast(@as([*]u8, @ptrCast(closure)) + @sizeOf(AsyncClosure));
}
fn entry() callconv(.naked) void {
switch (builtin.cpu.arch) {
.aarch64 => asm volatile (
\\ mov x0, sp
\\ b %[call]
:
: [call] "X" (&call),
),
.x86_64 => asm volatile (
\\ leaq 8(%%rsp), %%rdi
\\ jmp %[call:P]
:
: [call] "X" (&call),
),
else => |arch| @compileError("unimplemented architecture: " ++ @tagName(arch)),
}
}
fn call(
closure: *AsyncClosure,
message: *const SwitchMessage,
) callconv(.withStackAlign(.c, @alignOf(AsyncClosure))) noreturn {
const ev = closure.evented;
const fiber = closure.fiber;
message.handle(ev);
closure.start(closure.contextPointer(), fiber.resultBytes(closure.result_align));
if (@atomicRmw(?*Fiber, &fiber.link.awaiter, .Xchg, Fiber.finished, .acq_rel)) |awaiter|
ev.queue.async(awaiter, &Fiber.@"resume");
ev.yield(.nothing);
unreachable; // switched to dead fiber
}
};
fn async(
userdata: ?*anyopaque,
result: []u8,
result_alignment: Alignment,
context: []const u8,
context_alignment: Alignment,
start: *const fn (context: *const anyopaque, result: *anyopaque) void,
) ?*std.Io.AnyFuture {
const ev: *Evented = @ptrCast(@alignCast(userdata));
return concurrent(ev, result.len, result_alignment, context, context_alignment, start) catch {
start(context.ptr, result.ptr);
return null;
};
}
fn concurrent(
userdata: ?*anyopaque,
result_len: usize,
result_alignment: Alignment,
context: []const u8,
context_alignment: Alignment,
start: *const fn (context: *const anyopaque, result: *anyopaque) void,
) Io.ConcurrentError!*std.Io.AnyFuture {
assert(result_alignment.compare(.lte, Fiber.max_result_align)); // TODO
assert(context_alignment.compare(.lte, Fiber.max_context_align)); // TODO
assert(result_len <= Fiber.max_result_size); // TODO
assert(context.len <= Fiber.max_context_size); // TODO
const ev: *Evented = @ptrCast(@alignCast(userdata));
const fiber = Fiber.create(ev) catch |err| switch (err) {
error.OutOfMemory => return error.ConcurrencyUnavailable,
};
const closure: *AsyncClosure = .fromFiber(fiber);
fiber.* = .{
.required_align = {},
.evented = ev,
.context = switch (builtin.cpu.arch) {
.aarch64 => .{
.sp = @intFromPtr(closure),
.fp = 0,
.pc = @intFromPtr(&AsyncClosure.entry),
},
.x86_64 => .{
.rsp = @intFromPtr(closure) - 8,
.rbp = 0,
.rip = @intFromPtr(&AsyncClosure.entry),
},
else => |arch| @compileError("unimplemented architecture: " ++ @tagName(arch)),
},
.link = .{ .awaiter = null },
.awaiting_group = undefined,
.cancel_status = .unrequested,
.cancel_protection = .unblocked,
};
closure.* = .{
.evented = ev,
.fiber = fiber,
.start = start,
.result_align = result_alignment,
};
@memcpy(closure.contextPointer(), context);
ev.queue.async(fiber, &Fiber.@"resume");
return @ptrCast(fiber);
}
fn await(
userdata: ?*anyopaque,
future: *std.Io.AnyFuture,
result: []u8,
result_alignment: Alignment,
) void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
const awaiting: *Fiber = @ptrCast(@alignCast(future));
if (@atomicLoad(?*Fiber, &awaiting.link.awaiter, .acquire) != Fiber.finished)
ev.yield(.{ .await = awaiting });
@memcpy(result, awaiting.resultBytes(result_alignment));
awaiting.destroy(ev);
}
fn cancel(
userdata: ?*anyopaque,
future: *std.Io.AnyFuture,
result: []u8,
result_alignment: Alignment,
) void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
const future_fiber: *Fiber = @ptrCast(@alignCast(future));
future_fiber.requestCancel(ev);
await(ev, future, result, result_alignment);
}
const Group = struct {
ptr: *Io.Group,
const List = packed struct(usize) {
cancel_requested: bool,
awaiter_delayed: bool,
fibers: Fiber.PackedPtr,
};
fn listPtr(group: Group) *List {
return @ptrCast(&group.ptr.token);
}
const Mutex = packed struct(u32) {
locked: bool,
contended: bool,
shared2: u30,
};
fn mutexPtr(group: Group) *Group.Mutex {
return switch (comptime builtin.cpu.arch.endian()) {
.little => @ptrCast(&group.ptr.state),
.big => @ptrCast(@alignCast(
@as([*]u8, @ptrCast(&group.ptr.state)) + @sizeOf(usize) - @sizeOf(u32),
)),
};
}
const Awaiter = packed struct(usize) {
locked: bool,
contended: bool,
awaiter: Fiber.PackedPtr,
};
fn awaiterPtr(group: Group) *Awaiter {
return @ptrCast(&group.ptr.state);
}
fn lock(group: Group, ev: *Evented) void {
const mutex = group.mutexPtr();
{
const old_state = @atomicRmw(
Group.Mutex,
mutex,
.Or,
.{ .locked = true, .contended = false, .shared2 = 0 },
.acquire,
);
if (!old_state.locked) {
@branchHint(.likely);
return;
}
if (old_state.contended) {
futexWaitUncancelable(ev, @ptrCast(mutex), @bitCast(old_state));
}
}
while (true) {
var old_state = @atomicRmw(
Group.Mutex,
mutex,
.Or,
.{ .locked = true, .contended = true, .shared2 = 0 },
.acquire,
);
if (!old_state.locked) {
@branchHint(.likely);
return;
}
old_state.contended = true;
futexWaitUncancelable(ev, @ptrCast(mutex), @bitCast(old_state));
}
}
fn unlock(group: Group, ev: *Evented) void {
const mutex = group.mutexPtr();
const old_state = @atomicRmw(
Group.Mutex,
mutex,
.And,
.{ .locked = false, .contended = false, .shared2 = std.math.maxInt(u30) },
.release,
);
assert(old_state.locked);
if (old_state.contended) futexWake(ev, @ptrCast(mutex), 1);
}
fn addFiber(group: Group, ev: *Evented, fiber: *Fiber) void {
group.lock(ev);
defer group.unlock(ev);
const list_ptr = group.listPtr();
const list = @atomicLoad(List, list_ptr, .monotonic);
if (list.cancel_requested) fiber.cancel_status = .{ .requested = true, .awaiting = .nothing };
const old_head = list.fibers.unpack();
if (old_head) |head| head.link.group.prev = fiber;
fiber.link.group.next = old_head;
@atomicStore(List, list_ptr, .{
.cancel_requested = list.cancel_requested,
.awaiter_delayed = list.awaiter_delayed,
.fibers = .pack(fiber),
}, .monotonic);
}
fn removeFiber(group: Group, ev: *Evented, fiber: *Fiber) ?*Fiber {
group.lock(ev);
defer group.unlock(ev);
const list_ptr = group.listPtr();
const list = @atomicLoad(List, list_ptr, .monotonic);
if (fiber.link.group.next) |next| next.link.group.prev = fiber.link.group.prev;
if (fiber.link.group.prev) |prev| {
prev.link.group.next = fiber.link.group.next;
} else if (fiber.link.group.next) |new_head| {
@atomicStore(List, list_ptr, .{
.cancel_requested = list.cancel_requested,
.awaiter_delayed = list.awaiter_delayed,
.fibers = .pack(new_head),
}, .monotonic);
} else if (@atomicLoad(Awaiter, group.awaiterPtr(), .monotonic).awaiter.unpack()) |awaiter| {
if (!awaiter.cancel_status.changeAwaiting(.group, .nothing) or list.cancel_requested) {
@atomicStore(List, list_ptr, .{
.cancel_requested = false,
.awaiter_delayed = false,
.fibers = .null,
}, .release);
assert(awaiter.awaiting_group.ptr == group.ptr);
awaiter.awaiting_group = undefined;
return awaiter;
}
// Race with `Fiber.requestCancel`
@atomicStore(List, list_ptr, .{
.cancel_requested = false,
.awaiter_delayed = true,
.fibers = .null,
}, .monotonic);
} else @atomicStore(List, list_ptr, .{
.cancel_requested = false,
.awaiter_delayed = false,
.fibers = .null,
}, .release);
return null;
}
fn await(group: Group, ev: *Evented, awaiter: *Fiber) bool {
group.lock(ev);
defer group.unlock(ev);
if (@atomicLoad(List, group.listPtr(), .monotonic).fibers.unpack()) |_| {
if (group.registerAwaiter(awaiter) and awaiter.cancel_protection.check() == .unblocked) {
// The awaiter already had an unacknowledged cancelation request before
// attempting to await a group, so propagate the cancelation to the group.
assert(!group.cancelLocked(ev, null));
}
return false;
}
return true;
}
fn cancel(group: Group, ev: *Evented, maybe_awaiter: ?*Fiber) bool {
group.lock(ev);
defer group.unlock(ev);
return group.cancelLocked(ev, maybe_awaiter);
}
/// Assumes the mutex is held.
fn cancelLocked(group: Group, ev: *Evented, maybe_awaiter: ?*Fiber) bool {
const list_ptr = group.listPtr();
const list = @atomicRmw(
List,
list_ptr,
.Add,
.{ .cancel_requested = true, .awaiter_delayed = false, .fibers = .null },
.monotonic,
);
assert(!list.cancel_requested);
if (list.fibers.unpack()) |head| {
var maybe_fiber: ?*Fiber = head;
while (maybe_fiber) |fiber| {
fiber.requestCancel(ev);
maybe_fiber = fiber.link.group.next;
}
if (maybe_awaiter) |awaiter| _ = group.registerAwaiter(awaiter);
return false;
}
@atomicStore(
List,
list_ptr,
.{ .cancel_requested = false, .awaiter_delayed = false, .fibers = .null },
.release,
);
return if (maybe_awaiter) |_| true else list.awaiter_delayed;
}
/// Assumes the mutex is held.
fn registerAwaiter(group: Group, awaiter: *Fiber) bool {
awaiter.awaiting_group = group;
assert(@atomicRmw(
Awaiter,
group.awaiterPtr(),
.Add,
.{ .locked = false, .contended = false, .awaiter = .pack(awaiter) },
.monotonic,
).awaiter == .null);
return awaiter.cancel_status.changeAwaiting(.nothing, .group);
}
const AsyncClosure = struct {
evented: *Evented,
group: Group,
fiber: *Fiber,
start: *const fn (context: *const anyopaque) void,
fn fromFiber(fiber: *Fiber) *Group.AsyncClosure {
return @ptrFromInt(Fiber.max_context_align.max(.of(Group.AsyncClosure)).backward(
@intFromPtr(fiber.allocatedEnd()) - Fiber.max_context_size,
) - @sizeOf(Group.AsyncClosure));
}
fn contextPointer(
closure: *Group.AsyncClosure,
) [*]align(Fiber.max_context_align.toByteUnits()) u8 {
return @alignCast(@as([*]u8, @ptrCast(closure)) + @sizeOf(Group.AsyncClosure));
}
fn entry() callconv(.naked) void {
switch (builtin.cpu.arch) {
.aarch64 => asm volatile (
\\ mov x0, sp
\\ b %[call]
:
: [call] "X" (&call),
),
.x86_64 => asm volatile (
\\ leaq 8(%%rsp), %%rdi
\\ jmp %[call:P]
:
: [call] "X" (&call),
),
else => |arch| @compileError("unimplemented architecture: " ++ @tagName(arch)),
}
}
fn call(
closure: *Group.AsyncClosure,
message: *const SwitchMessage,
) callconv(.withStackAlign(.c, @alignOf(Group.AsyncClosure))) noreturn {
const ev = closure.evented;
const fiber = closure.fiber;
message.handle(ev);
closure.start(closure.contextPointer());
if (closure.group.removeFiber(ev, fiber)) |awaiter| ev.queue.async(awaiter, &Fiber.@"resume");
ev.yield(.destroy);
unreachable; // switched to dead fiber
}
};
};
fn groupAsync(
userdata: ?*anyopaque,
type_erased: *Io.Group,
context: []const u8,
context_alignment: Alignment,
start: *const fn (context: *const anyopaque) void,
) void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
return groupConcurrent(ev, type_erased, context, context_alignment, start) catch {
start(context.ptr);
};
}
fn groupConcurrent(
userdata: ?*anyopaque,
type_erased: *Io.Group,
context: []const u8,
context_alignment: Alignment,
start: *const fn (context: *const anyopaque) void,
) Io.ConcurrentError!void {
assert(context_alignment.compare(.lte, Fiber.max_context_align)); // TODO
assert(context.len <= Fiber.max_context_size); // TODO
const ev: *Evented = @ptrCast(@alignCast(userdata));
const group: Group = .{ .ptr = type_erased };
const fiber = Fiber.create(ev) catch |err| switch (err) {
error.OutOfMemory => return error.ConcurrencyUnavailable,
};
const closure: *Group.AsyncClosure = .fromFiber(fiber);
fiber.* = .{
.required_align = {},
.evented = ev,
.context = switch (builtin.cpu.arch) {
.aarch64 => .{
.sp = @intFromPtr(closure),
.fp = 0,
.pc = @intFromPtr(&Group.AsyncClosure.entry),
},
.x86_64 => .{
.rsp = @intFromPtr(closure) - 8,
.rbp = 0,
.rip = @intFromPtr(&Group.AsyncClosure.entry),
},
else => |arch| @compileError("unimplemented architecture: " ++ @tagName(arch)),
},
.link = .{ .group = .{ .prev = null, .next = null } },
.awaiting_group = undefined,
.cancel_status = .unrequested,
.cancel_protection = .unblocked,
};
closure.* = .{
.evented = ev,
.group = group,
.fiber = fiber,
.start = start,
};
@memcpy(closure.contextPointer(), context);
group.addFiber(ev, fiber);
ev.queue.async(fiber, &Fiber.@"resume");
}
fn groupAwait(
userdata: ?*anyopaque,
type_erased: *Io.Group,
initial_token: *anyopaque,
) Io.Cancelable!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = initial_token;
ev.yield(.{ .group_await = .{ .ptr = type_erased } });
}
fn groupCancel(userdata: ?*anyopaque, type_erased: *Io.Group, initial_token: *anyopaque) void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = initial_token;
ev.yield(.{ .group_cancel = .{ .ptr = type_erased } });
}
fn recancel(userdata: ?*anyopaque) void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
Thread.current().currentFiber().cancel_protection.recancel();
}
fn swapCancelProtection(userdata: ?*anyopaque, new: Io.CancelProtection) Io.CancelProtection {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
const cancel_protection = &Thread.current().currentFiber().cancel_protection;
defer cancel_protection.user = new;
return cancel_protection.user;
}
fn checkCancel(userdata: ?*anyopaque) Io.Cancelable!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
const fiber = Thread.current().currentFiber();
switch (fiber.cancel_protection.check()) {
.unblocked => {
const cancel_status = @atomicLoad(Fiber.CancelStatus, &fiber.cancel_status, .monotonic);
assert(cancel_status.awaiting == .nothing);
if (cancel_status.requested) {
@branchHint(.unlikely);
fiber.cancel_protection.acknowledge();
return error.Canceled;
}
},
.blocked => {},
}
}
const Futex = struct {
num_waiters: usize,
queue: c.dispatch.queue_t,
waiters: std.DoublyLinkedList,
const Waiter = struct {
sleeper: Sleeper = undefined,
cancelable: Cancelable,
futex: *Futex,
node: std.DoublyLinkedList.Node = .{},
ptr: *const u32,
expected: u32,
timeout: c.dispatch.time_t = .FOREVER,
leeway: u64,
timer: ?c.dispatch.source_t = null,
const already_signaled: c.dispatch.source_t = @ptrFromInt(1);
fn add(context: ?*anyopaque) callconv(.c) void {
const waiter: *Waiter = @ptrCast(@alignCast(context));
const futex = waiter.futex;
_ = @atomicRmw(usize, &futex.num_waiters, .Add, 1, .acquire);
waiter.tryAdd() catch |err| switch (err) {
error.CancelRequested => {
wake(waiter);
assert(@atomicRmw(usize, &futex.num_waiters, .Sub, 1, .monotonic) >= 1);
},
};
}
fn tryAdd(waiter: *Waiter) Cancelable.RequestedError!void {
if (@atomicLoad(u32, waiter.ptr, .monotonic) != waiter.expected)
return error.CancelRequested;
try waiter.cancelable.enter(waiter.sleeper.fiber);
const futex = waiter.futex;
switch (waiter.timeout) {
.FOREVER => {},
else => |timeout| {
const timer = c.dispatch.source_create(.TIMER, 0, .none, futex.queue) orelse {
log.warn("failed to create timer for futex timeout", .{});
return error.CancelRequested;
};
timer.as_object().set_context(waiter);
timer.set_event_handler(&timedOut);
timer.set_cancel_handler(&wake);
timer.set_timer(timeout, c.dispatch.TIME_FOREVER, waiter.leeway);
timer.as_object().activate();
waiter.timer = timer;
},
}
futex.waiters.append(&waiter.node);
}
fn canceled(context: ?*anyopaque) callconv(.c) void {
const cancelable: *Cancelable = @ptrCast(@alignCast(context));
const waiter: *Waiter = @fieldParentPtr("cancelable", cancelable);
cancelable.requested(waiter.sleeper.fiber);
const futex = waiter.futex;
waiter.remove();
assert(@atomicRmw(usize, &futex.num_waiters, .Sub, 1, .monotonic) >= 1);
}
fn timedOut(context: ?*anyopaque) callconv(.c) void {
const waiter: *Waiter = @ptrCast(@alignCast(context));
const futex = waiter.futex;
waiter.tryRemove() catch |err| switch (err) {
error.CancelRequested => return,
};
assert(@atomicRmw(usize, &futex.num_waiters, .Sub, 1, .monotonic) >= 1);
}
fn tryRemove(waiter: *Waiter) Cancelable.RequestedError!void {
try waiter.cancelable.leave(waiter.sleeper.fiber);
waiter.remove();
}
fn remove(waiter: *Waiter) void {
waiter.futex.waiters.remove(&waiter.node);
if (waiter.timer) |timer| timer.cancel() else wake(waiter);
}
fn wake(context: ?*anyopaque) callconv(.c) void {
const waiter: *Waiter = @ptrCast(@alignCast(context));
if (waiter.timer) |timer| timer.as_object().release();
Sleeper.wake(&waiter.sleeper);
}
};
const Waker = struct {
sleeper: Sleeper = undefined,
futex: *Futex,
ptr: *const u32,
max_waiters: u32,
fn remove(context: ?*anyopaque) callconv(.c) void {
const waker: *Waker = @ptrCast(@alignCast(context));
const futex = waker.futex;
const ptr = waker.ptr;
const max_waiters = waker.max_waiters;
var num_removed: usize = 0;
var next_node = futex.waiters.first;
while (num_removed < max_waiters) {
const waiter: *Waiter = @fieldParentPtr("node", next_node orelse break);
next_node = waiter.node.next;
if (waiter.ptr != ptr) {
@branchHint(.unlikely);
continue;
}
waiter.tryRemove() catch |err| switch (err) {
error.CancelRequested => continue,
};
num_removed += 1;
}
assert(@atomicRmw(usize, &futex.num_waiters, .Sub, num_removed, .monotonic) >= num_removed);
var sleeper = waker.sleeper;
waker.* = undefined;
Sleeper.wake(&sleeper);
}
};
fn init(futex: *Futex, queue: c.dispatch.queue_t) error{SystemResources}!void {
futex.* = .{
.num_waiters = 0,
.queue = c.dispatch.queue_create_with_target(
"org.ziglang.std.Io.Dispatch.Futex",
.SERIAL(),
queue,
) orelse return error.SystemResources,
.waiters = .{},
};
}
fn deinit(futex: *Futex) void {
assert(futex.num_waiters == 0 and futex.waiters.first == null and futex.waiters.last == null);
futex.queue.as_object().release();
futex.* = undefined;
}
};
fn futexForAddress(ev: *Evented, address: usize) *Futex {
// Here we use Fibonacci hashing: the golden ratio can be used to evenly redistribute input
// values across a range, giving a poor, but extremely quick to compute, hash.
// This literal is the rounded value of '2^64 / phi' (where 'phi' is the golden ratio). The
// shift then converts it to '2^b / phi', where 'b' is the pointer bit width.
const fibonacci_multiplier = 0x9E3779B97F4A7C15 >> (64 - @bitSizeOf(usize));
const hashed = address *% fibonacci_multiplier;
comptime assert(std.math.isPowerOfTwo(ev.futexes.len));
// The high bits of `hashed` have better entropy than the low bits.
return &ev.futexes[hashed >> @clz(ev.futexes.len - 1)];
}
fn futexWait(
userdata: ?*anyopaque,
ptr: *const u32,
expected: u32,
timeout: Io.Timeout,
) Io.Cancelable!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
const futex = ev.futexForAddress(@intFromPtr(ptr));
var waiter: Futex.Waiter = .{
.cancelable = .{ .queue = futex.queue, .cancel = &Futex.Waiter.canceled },
.futex = futex,
.ptr = ptr,
.expected = expected,
.timeout = ev.timeFromTimeout(timeout),
.leeway = ev.leeway,
};
ev.yield(.{ .futex_wait = &waiter });
try waiter.cancelable.acknowledge(waiter.sleeper.fiber);
}
fn futexWaitUncancelable(userdata: ?*anyopaque, ptr: *const u32, expected: u32) void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
const futex = ev.futexForAddress(@intFromPtr(ptr));
var waiter: Futex.Waiter = .{
.cancelable = .blocked,
.futex = futex,
.ptr = ptr,
.expected = expected,
.leeway = ev.leeway,
};
ev.yield(.{ .futex_wait = &waiter });
waiter.cancelable.acknowledge(waiter.sleeper.fiber) catch |err| switch (err) {
error.Canceled => unreachable, // blocked
};
}
fn futexWake(userdata: ?*anyopaque, ptr: *const u32, max_waiters: u32) void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
if (max_waiters == 0) return;
const futex = ev.futexForAddress(@intFromPtr(ptr));
switch (@atomicRmw(usize, &futex.num_waiters, .Add, 0, .release)) {
0 => return,
else => {
@branchHint(.unlikely);
var waker: Futex.Waker = .{ .futex = futex, .ptr = ptr, .max_waiters = max_waiters };
ev.yield(.{ .futex_wake = &waker });
},
}
}
fn operate(userdata: ?*anyopaque, operation: Io.Operation) Io.Cancelable!Io.Operation.Result {
const ev: *Evented = @ptrCast(@alignCast(userdata));
switch (operation) {
.file_read_streaming => |o| return .{
.file_read_streaming = ev.fileReadStreaming(o.file, o.data) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| e,
},
},
.file_write_streaming => |o| return .{
.file_write_streaming = ev.fileWriteStreaming(
o.file,
o.header,
o.data,
o.splat,
) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| e,
},
},
.device_io_control => |*o| return .{ .device_io_control = try deviceIoControl(o) },
.net_receive => @panic("TODO implement net_receive operation"),
.net_send => @panic("TODO implement net_send operation"),
.net_read => @panic("TODO implement net_read operation"),
.net_write => @panic("TODO implement net_write operation"),
}
}
fn fileReadStreaming(ev: *Evented, file: File, data: []const []u8) File.ReadStreamingError!usize {
if (file.flags.nonblocking) nonblocking: {
return fileReadStreamingLimit(file.handle, data, .unlimited) catch |err| switch (err) {
error.WouldBlock => break :nonblocking,
else => |e| return e,
};
}
const source = c.dispatch.source_create(
.READ,
@bitCast(@as(isize, file.handle)),
.none,
ev.queue,
) orelse return error.SystemResources;
source.as_object().set_context(Thread.current().currentFiber());
source.set_event_handler(&Fiber.@"resume");
ev.yield(.{ .activate = source.as_object() });
const limit = source.get_data();
source.as_object().release();
while (true) return fileReadStreamingLimit(
file.handle,
data,
.limited(limit),
) catch |err| switch (err) {
error.WouldBlock => {
ev.yield(.nothing);
continue;
},
else => |e| return e,
};
}
fn fileReadStreamingLimit(
handle: File.Handle,
data: []const []u8,
limit: Io.Limit,
) File.ReadStreamingError!usize {
var iovecs: [max_iovecs_len]iovec = undefined;
var iovlen: iovlen_t = 0;
// .nothing can mean that the write side has been closed,
// in which case the buffer still needs to be drained
var remaining = if (limit == .nothing) .unlimited else limit;
for (data) |buf| addBuf(false, &iovecs, &iovlen, &remaining, buf);
if (iovlen == 0) return 0;
while (true) {
const rc = c.readv(handle, &iovecs, iovlen);
switch (c.errno(rc)) {
.SUCCESS => return if (rc == 0) error.EndOfStream else @intCast(rc),
.INTR => continue,
.INVAL => |err| return errnoBug(err),
.FAULT => |err| return errnoBug(err),
.AGAIN => return error.WouldBlock,
.BADF => |err| return errnoBug(err), // File descriptor used after closed
.IO => return error.InputOutput,
.ISDIR => return error.IsDir,
.NOBUFS => return error.SystemResources,
.NOMEM => return error.SystemResources,
.NOTCONN => return error.SocketUnconnected,
.CONNRESET => return error.ConnectionResetByPeer,
else => |err| return unexpectedErrno(err),
}
}
}
fn fileWriteStreaming(
ev: *Evented,
file: File,
header: []const u8,
data: []const []const u8,
splat: usize,
) File.Writer.Error!usize {
if (file.flags.nonblocking) nonblocking: {
return fileWriteStreamingLimit(
file.handle,
header,
data,
splat,
.unlimited,
) catch |err| switch (err) {
error.WouldBlock => break :nonblocking,
else => |e| return e,
};
}
const source = c.dispatch.source_create(
.WRITE,
@bitCast(@as(isize, file.handle)),
.none,
ev.queue,
) orelse return error.SystemResources;
source.as_object().set_context(Thread.current().currentFiber());
source.set_event_handler(&Fiber.@"resume");
ev.yield(.{ .activate = source.as_object() });
const limit = source.get_data();
source.as_object().release();
while (true) return fileWriteStreamingLimit(
file.handle,
header,
data,
splat,
.limited(limit),
) catch |err| switch (err) {
error.WouldBlock => {
ev.yield(.nothing);
continue;
},
else => |e| return e,
};
}
fn fileWriteStreamingLimit(
handle: File.Handle,
header: []const u8,
data: []const []const u8,
splat: usize,
limit: Io.Limit,
) File.Writer.Error!usize {
if (limit == .nothing) return 0;
var iovecs: [max_iovecs_len]iovec_const = undefined;
var iovlen: iovlen_t = 0;
var remaining = limit;
addBuf(true, &iovecs, &iovlen, &remaining, header);
for (data[0 .. data.len - 1]) |bytes| addBuf(true, &iovecs, &iovlen, &remaining, bytes);
const pattern = data[data.len - 1];
var backup_buffer: [splat_buffer_size]u8 = undefined;
if (iovecs.len - iovlen != 0 and remaining != .nothing) switch (splat) {
0 => {},
1 => addBuf(true, &iovecs, &iovlen, &remaining, pattern),
else => switch (pattern.len) {
0 => {},
1 => {
const splat_buffer = &backup_buffer;
const memset_len = @min(splat_buffer.len, splat);
const buf = splat_buffer[0..memset_len];
@memset(buf, pattern[0]);
addBuf(true, &iovecs, &iovlen, &remaining, buf);
var remaining_splat = splat - buf.len;
while (remaining_splat > splat_buffer.len and iovecs.len - iovlen != 0 and remaining != .nothing) {
assert(buf.len == splat_buffer.len);
addBuf(true, &iovecs, &iovlen, &remaining, splat_buffer);
remaining_splat -= splat_buffer.len;
}
addBuf(true, &iovecs, &iovlen, &remaining, splat_buffer[0..@min(remaining_splat, splat_buffer.len)]);
},
else => for (0..@min(splat, iovecs.len - iovlen)) |_| {
if (remaining == .nothing) break;
addBuf(true, &iovecs, &iovlen, &remaining, pattern);
},
},
};
if (iovlen == 0) return 0;
while (true) {
const rc = c.writev(handle, &iovecs, iovlen);
switch (c.errno(rc)) {
.SUCCESS => return @intCast(rc),
.INTR => continue,
.INVAL => |err| return errnoBug(err),
.FAULT => |err| return errnoBug(err),
.AGAIN => return error.WouldBlock,
.BADF => return error.NotOpenForWriting, // Can be a race condition.
.DESTADDRREQ => |err| return errnoBug(err), // `connect` was never called.
.DQUOT => return error.DiskQuota,
.FBIG => return error.FileTooBig,
.IO => return error.InputOutput,
.NOSPC => return error.NoSpaceLeft,
.PERM => return error.PermissionDenied,
.PIPE => return error.BrokenPipe,
.CONNRESET => |err| return errnoBug(err), // Not a socket handle.
.BUSY => return error.DeviceBusy,
else => |err| return unexpectedErrno(err),
}
}
}
fn deviceIoControl(o: *const Io.Operation.DeviceIoControl) Io.Cancelable!i32 {
while (true) {
const rc = c.ioctl(o.file.handle, @bitCast(o.code), @intFromPtr(o.arg));
switch (c.errno(rc)) {
.SUCCESS => return rc,
.INTR => {},
else => |err| return -@as(i32, @backingInt(err)),
}
}
}
const BatchWaiter = struct {
sleeper: Sleeper,
queue: c.dispatch.queue_t,
timer: ?c.dispatch.source_t = null,
const already_signaled: c.dispatch.source_t = @ptrFromInt(1);
fn signal(context: ?*anyopaque) callconv(.c) void {
const waiter: *BatchWaiter = @ptrCast(@alignCast(context));
if (waiter.timer) |timer| {
if (timer != already_signaled) timer.cancel();
} else {
waiter.timer = already_signaled;
waiter.queue.async(waiter, &@"suspend");
}
}
fn @"suspend"(context: ?*anyopaque) callconv(.c) void {
const waiter: *BatchWaiter = @ptrCast(@alignCast(context));
if (waiter.timer) |timer| if (timer != already_signaled) timer.as_object().release();
waiter.queue.as_object().@"suspend"();
waiter.wake();
}
fn wake(waiter: *BatchWaiter) void {
var sleeper = waiter.sleeper;
waiter.* = undefined;
Sleeper.wake(&sleeper);
}
};
fn batchAwaitAsync(userdata: ?*anyopaque, batch: *Io.Batch) Io.Cancelable!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
const queue = ev.batchDrainSubmitted(batch, false) catch |err| switch (err) {
error.ConcurrencyUnavailable => unreachable, // passed concurrency=false
error.Canceled => |e| return e,
} orelse return;
if (batch.pending.head == .none) return;
var waiter: BatchWaiter = .{
.sleeper = .init(ev.queue, Thread.current().currentFiber()),
.queue = queue,
};
if (batch.completed.head != .none) BatchWaiter.signal(&waiter);
queue.as_object().set_context(&waiter);
ev.yield(.{ .@"resume" = queue.as_object() });
}
fn batchAwaitConcurrent(
userdata: ?*anyopaque,
batch: *Io.Batch,
timeout: Io.Timeout,
) Io.Batch.AwaitConcurrentError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
const queue = try ev.batchDrainSubmitted(batch, true) orelse return;
if (batch.pending.head == .none) return;
var waiter: BatchWaiter = .{
.sleeper = .init(ev.queue, Thread.current().currentFiber()),
.queue = queue,
};
if (batch.completed.head == .none) switch (timeout) {
.none => {},
else => {
const timer = c.dispatch.source_create(.TIMER, 0, .none, queue) orelse
return error.ConcurrencyUnavailable;
assert(timer != BatchWaiter.already_signaled);
timer.as_object().set_context(&waiter);
timer.set_event_handler(&BatchWaiter.signal);
timer.set_cancel_handler(&BatchWaiter.@"suspend");
timer.set_timer(ev.timeFromTimeout(timeout), c.dispatch.TIME_FOREVER, ev.leeway);
timer.as_object().activate();
waiter.timer = timer;
},
} else BatchWaiter.signal(&waiter);
queue.as_object().set_context(&waiter);
ev.yield(.{ .@"resume" = queue.as_object() });
}
fn batchCancel(userdata: ?*anyopaque, batch: *Io.Batch) void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
var index = batch.pending.head;
while (index != .none) {
const storage = &batch.storage[index.toIndex()];
const pending = &storage.pending;
const operation_userdata: *BatchOperationUserdata = .fromErased(&pending.userdata);
assert(operation_userdata.batch == batch);
operation_userdata.source.cancel();
}
const queue: c.dispatch.queue_t = @ptrCast(batch.userdata orelse return);
if (batch.pending.head != .none) {
var waiter: BatchWaiter = .{
.sleeper = .init(ev.queue, Thread.current().currentFiber()),
.queue = queue,
.timer = BatchWaiter.already_signaled,
};
if (batch.pending.head == .none) queue.async(&waiter, &BatchWaiter.signal);
queue.as_object().set_context(&waiter);
ev.yield(.{ .@"resume" = queue.as_object() });
}
batch.userdata = null;
}
const BatchOperationUserdata = extern struct {
batch: *Io.Batch,
source: c.dispatch.source_t,
operation: extern union {
file_read_streaming: extern struct {
data_ptr: [*]const []u8,
data_len: usize,
},
file_write_streaming: extern struct {
header_ptr: [*]const u8,
header_len: usize,
data_ptr: [*]const []const u8,
data_len: usize,
splat: usize,
fn header(operation: *const @This()) []const u8 {
return operation.header_ptr[0..operation.header_len];
}
fn data(operation: *const @This()) []const []const u8 {
return operation.data_ptr[0..operation.data_len];
}
},
},
const Erased = Io.Operation.Storage.Pending.Userdata;
comptime {
assert(@sizeOf(BatchOperationUserdata) <= @sizeOf(Erased));
}
fn toErased(userdata: *BatchOperationUserdata) *Erased {
return @ptrCast(userdata);
}
fn fromErased(erased: *Erased) *BatchOperationUserdata {
return @ptrCast(erased);
}
};
/// If `concurrency` is false, `error.ConcurrencyUnavailable` is unreachable.
fn batchDrainSubmitted(
ev: *Evented,
batch: *Io.Batch,
concurrency: bool,
) (Io.ConcurrentError || Io.Cancelable)!?c.dispatch.queue_t {
var index = batch.submitted.head;
if (index == .none) return @ptrCast(batch.userdata);
errdefer batch.submitted.head = index;
const maybe_queue: ?c.dispatch.queue_t = if (batch.userdata) |batch_userdata|
@ptrCast(batch_userdata)
else maybe_queue: {
const queue = c.dispatch.queue_create_with_target(
"org.ziglang.std.Io.Dispatch.Batch",
.SERIAL(),
ev.queue,
) orelse if (concurrency) return error.ConcurrencyUnavailable else break :maybe_queue null;
queue.as_object().@"suspend"();
batch.userdata = queue;
break :maybe_queue queue;
};
while (index != .none) {
const storage = &batch.storage[index.toIndex()];
const next_index = storage.submission.node.next;
if (@as(?Io.Operation.Result, result: {
if (maybe_queue) |queue| switch (storage.submission.operation) {
.file_read_streaming => |operation| {
const data = for (operation.data, 0..) |buffer, data_index| {
if (buffer.len > 0) break operation.data[data_index..];
} else break :result .{ .file_read_streaming = 0 };
const source = c.dispatch.source_create(
.READ,
@bitCast(@as(isize, operation.file.handle)),
.none,
queue,
) orelse break :result .{ .file_read_streaming = error.SystemResources };
storage.* = .{ .pending = .{
.node = .{ .prev = batch.pending.tail, .next = .none },
.tag = .file_read_streaming,
.userdata = undefined,
} };
const operation_userdata: *BatchOperationUserdata =
.fromErased(&storage.pending.userdata);
operation_userdata.* = .{
.batch = batch,
.source = source,
.operation = .{ .file_read_streaming = .{
.data_ptr = data.ptr,
.data_len = data.len,
} },
};
source.as_object().set_context(storage);
source.set_event_handler(&batchSourceEvent);
source.set_cancel_handler(&batchSourceCancel);
source.as_object().activate();
break :result null;
},
.file_write_streaming => |operation| {
const data = for (operation.data, 0..) |buffer, data_index| {
if (buffer.len > 0) break operation.data[data_index..];
} else if (operation.header.len > 0)
operation.data[0..1]
else
break :result .{ .file_write_streaming = 0 };
const source = c.dispatch.source_create(
.WRITE,
@bitCast(@as(isize, operation.file.handle)),
.none,
queue,
) orelse break :result .{ .file_write_streaming = error.SystemResources };
storage.* = .{ .pending = .{
.node = .{ .prev = batch.pending.tail, .next = .none },
.tag = .file_write_streaming,
.userdata = undefined,
} };
const operation_userdata: *BatchOperationUserdata =
.fromErased(&storage.pending.userdata);
operation_userdata.* = .{
.batch = batch,
.source = source,
.operation = .{ .file_write_streaming = .{
.header_ptr = operation.header.ptr,
.header_len = operation.header.len,
.data_ptr = data.ptr,
.data_len = data.len,
.splat = operation.splat,
} },
};
source.as_object().set_context(storage);
source.set_event_handler(&batchSourceEvent);
source.set_cancel_handler(&batchSourceCancel);
source.as_object().activate();
break :result null;
},
.device_io_control => {},
.net_receive => @panic("TODO implement batched net_receive"),
.net_read => @panic("TODO implement batched net_read"),
.net_write => @panic("TODO implement batched net_write"),
};
if (concurrency) return error.ConcurrencyUnavailable;
break :result try operate(ev, storage.submission.operation);
})) |result| {
switch (batch.completed.tail) {
.none => batch.completed.head = index,
else => |tail_index| batch.storage[tail_index.toIndex()].completion.node.next = index,
}
batch.completed.tail = index;
storage.* = .{ .completion = .{ .node = .{ .next = .none }, .result = result } };
} else {
switch (batch.pending.tail) {
.none => batch.pending.head = index,
else => |tail_index| batch.storage[tail_index.toIndex()].pending.node.next = index,
}
batch.pending.tail = index;
}
index = next_index;
}
batch.submitted = .{ .head = .none, .tail = .none };
return maybe_queue;
}
fn batchSourceEvent(context: ?*anyopaque) callconv(.c) void {
const storage: *Io.Operation.Storage = @ptrCast(@alignCast(context));
const pending = &storage.pending;
const operation_userdata: *BatchOperationUserdata = .fromErased(&pending.userdata);
const batch = operation_userdata.batch;
const source = operation_userdata.source;
const index: Io.Operation.OptionalIndex = .fromIndex(storage - batch.storage.ptr);
const result: Io.Operation.Result = result: switch (pending.tag) {
.file_read_streaming => {
const operation = &operation_userdata.operation.file_read_streaming;
break :result .{ .file_read_streaming = fileReadStreamingLimit(
@intCast(source.get_handle()),
operation.data_ptr[0..operation.data_len],
.limited(source.get_data()),
) catch |err| switch (err) {
error.Canceled => return Thread.current().currentFiber().cancel_protection.recancel(),
error.WouldBlock => return,
else => |e| e,
} };
},
.file_write_streaming => {
const operation = &operation_userdata.operation.file_write_streaming;
break :result .{ .file_write_streaming = fileWriteStreamingLimit(
@intCast(source.get_handle()),
operation.header_ptr[0..operation.header_len],
operation.data_ptr[0..operation.data_len],
operation.splat,
.limited(source.get_data()),
) catch |err| switch (err) {
error.Canceled => return Thread.current().currentFiber().cancel_protection.recancel(),
error.WouldBlock => return,
else => |e| e,
} };
},
.device_io_control => unreachable,
.net_receive => @panic("TODO implement batched net_receive"),
.net_read => @panic("TODO implement batched net_read"),
.net_write => @panic("TODO implement batched net_write"),
};
switch (pending.node.prev) {
.none => batch.pending.head = pending.node.next,
else => |prev_index| batch.storage[prev_index.toIndex()].pending.node.next = pending.node.next,
}
switch (pending.node.next) {
.none => batch.pending.tail = pending.node.prev,
else => |next_index| batch.storage[next_index.toIndex()].pending.node.prev = pending.node.prev,
}
switch (batch.completed.tail) {
.none => batch.completed.head = index,
else => |tail_index| batch.storage[tail_index.toIndex()].completion.node.next = index,
}
storage.* = .{ .completion = .{ .node = .{ .next = .none }, .result = result } };
batch.completed.tail = index;
source.as_object().release();
const queue: c.dispatch.queue_t = @ptrCast(batch.userdata);
const waiter: *BatchWaiter = @ptrCast(@alignCast(queue.as_object().get_context()));
BatchWaiter.signal(waiter);
}
fn batchSourceCancel(context: ?*anyopaque) callconv(.c) void {
const storage: *Io.Operation.Storage = @ptrCast(@alignCast(context));
const pending = &storage.pending;
const operation_userdata: *BatchOperationUserdata = .fromErased(&pending.userdata);
const batch = operation_userdata.batch;
const source = operation_userdata.source;
const index: Io.Operation.OptionalIndex = .fromIndex(storage - batch.storage.ptr);
switch (pending.node.prev) {
.none => batch.pending.head = pending.node.next,
else => |prev_index| batch.storage[prev_index.toIndex()].pending.node.next = pending.node.next,
}
switch (pending.node.next) {
.none => batch.pending.tail = pending.node.prev,
else => |next_index| batch.storage[next_index.toIndex()].pending.node.prev = pending.node.prev,
}
const tail_index = batch.unused.tail;
switch (tail_index) {
.none => batch.unused.head = index,
else => batch.storage[tail_index.toIndex()].unused.next = index,
}
storage.* = .{ .unused = .{ .prev = tail_index, .next = .none } };
batch.unused.tail = index;
source.as_object().release();
if (batch.pending.head != .none) return;
const queue: c.dispatch.queue_t = @ptrCast(batch.userdata);
const waiter: *BatchWaiter = @ptrCast(@alignCast(queue.as_object().get_context()));
queue.as_object().release();
waiter.wake();
}
fn dirCreateDir(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
permissions: Dir.Permissions,
) Dir.CreateDirError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
var path_buffer: [c.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &path_buffer);
while (true) {
switch (c.errno(c.mkdirat(dir.handle, sub_path_posix, permissions.toMode()))) {
.SUCCESS => return,
.INTR => {},
.ACCES => return error.AccessDenied,
.PERM => return error.PermissionDenied,
.DQUOT => return error.DiskQuota,
.EXIST => return error.PathAlreadyExists,
.LOOP => return error.SymLinkLoop,
.MLINK => return error.LinkQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.NOTDIR => return error.NotDir,
.ROFS => return error.ReadOnlyFileSystem,
.ILSEQ => return error.BadPathName,
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.FAULT => |err| return errnoBug(err),
else => |err| return unexpectedErrno(err),
}
}
}
fn dirCreateDirPath(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
permissions: Dir.Permissions,
) Dir.CreateDirPathError!Dir.CreatePathStatus {
const ev: *Evented = @ptrCast(@alignCast(userdata));
var it = Dir.path.componentIterator(sub_path);
var status: Dir.CreatePathStatus = .existed;
var component = it.last() orelse return error.BadPathName;
while (true) {
if (dirCreateDir(ev, dir, component.path, permissions)) |_| {
status = .created;
} else |err| switch (err) {
error.PathAlreadyExists => {
// It is important to return an error if it's not a directory
// because otherwise a dangling symlink could cause an infinite
// loop.
const fstat = try dirStatFile(ev, dir, component.path, .{});
if (fstat.kind != .directory) return error.NotDir;
},
error.FileNotFound => |e| {
component = it.previous() orelse return e;
continue;
},
else => |e| return e,
}
component = it.next() orelse return status;
}
}
fn dirCreateDirPathOpen(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
permissions: Dir.Permissions,
options: Dir.OpenOptions,
) Dir.CreateDirPathOpenError!Dir {
const ev: *Evented = @ptrCast(@alignCast(userdata));
return dirOpenDir(ev, dir, sub_path, options) catch |err| switch (err) {
error.FileNotFound => {
_ = try dirCreateDirPath(ev, dir, sub_path, permissions);
return dirOpenDir(ev, dir, sub_path, options);
},
else => |e| return e,
};
}
fn dirOpenDir(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
options: Dir.OpenOptions,
) Dir.OpenError!Dir {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
var path_buffer: [c.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &path_buffer);
const flags: c.O = .{
.ACCMODE = .RDONLY,
.NOFOLLOW = !options.follow_symlinks,
.DIRECTORY = true,
.CLOEXEC = true,
};
while (true) {
const rc = c.openat(dir.handle, sub_path_posix, flags);
switch (c.errno(rc)) {
.SUCCESS => return .{ .handle = @intCast(rc) },
.INTR => {},
.INVAL => return error.BadPathName,
.ACCES => return error.AccessDenied,
.LOOP => return error.SymLinkLoop,
.MFILE => return error.ProcessFdQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NFILE => return error.SystemFdQuotaExceeded,
.NODEV => return error.NoDevice,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOTDIR => return error.NotDir,
.PERM => return error.PermissionDenied,
.NXIO => return error.NoDevice,
.ILSEQ => return error.BadPathName,
.FAULT => |err| return errnoBug(err),
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.BUSY => |err| return errnoBug(err), // O_EXCL not passed
else => |err| return unexpectedErrno(err),
}
}
}
fn dirStat(userdata: ?*anyopaque, dir: Dir) Dir.StatError!Dir.Stat {
const ev: *Evented = @ptrCast(@alignCast(userdata));
return fileStat(ev, .{
.handle = dir.handle,
.flags = .{ .nonblocking = false },
});
}
fn dirStatFile(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
options: Dir.StatFileOptions,
) Dir.StatFileError!File.Stat {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
var path_buffer: [c.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &path_buffer);
const flags: u32 = if (options.follow_symlinks) 0 else c.AT.SYMLINK_NOFOLLOW;
while (true) {
var stat = std.mem.zeroes(c.Stat);
switch (c.errno(c.fstatat(dir.handle, sub_path_posix, &stat, flags))) {
.SUCCESS => return statFromPosix(&stat),
.INTR => {},
.INVAL => |err| return errnoBug(err),
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.NOMEM => return error.SystemResources,
.ACCES => return error.AccessDenied,
.PERM => return error.PermissionDenied,
.FAULT => |err| return errnoBug(err),
.NAMETOOLONG => return error.NameTooLong,
.LOOP => return error.SymLinkLoop,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.FileNotFound,
.ILSEQ => return error.BadPathName,
else => |err| return unexpectedErrno(err),
}
}
}
fn dirAccess(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
options: Dir.AccessOptions,
) Dir.AccessError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
var path_buffer: [c.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &path_buffer);
const flags: u32 = if (options.follow_symlinks) 0 else c.AT.SYMLINK_NOFOLLOW;
const mode: u32 =
@as(u32, if (options.read) c.R_OK else 0) |
@as(u32, if (options.write) c.W_OK else 0) |
@as(u32, if (options.execute) c.X_OK else 0);
while (true) switch (c.errno(c.faccessat(dir.handle, sub_path_posix, mode, flags))) {
.SUCCESS => return,
.INTR => {},
.ACCES => return error.AccessDenied,
.PERM => return error.PermissionDenied,
.ROFS => return error.ReadOnlyFileSystem,
.LOOP => return error.SymLinkLoop,
.TXTBSY => return error.FileBusy,
.NOTDIR => return error.FileNotFound,
.NOENT => return error.FileNotFound,
.NAMETOOLONG => return error.NameTooLong,
.INVAL => |err| return errnoBug(err),
.FAULT => |err| return errnoBug(err),
.IO => return error.InputOutput,
.NOMEM => return error.SystemResources,
.ILSEQ => return error.BadPathName,
else => |err| return unexpectedErrno(err),
};
}
fn dirCreateFile(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
flags: Dir.CreateFileOptions,
) File.OpenError!File {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
var path_buffer: [c.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &path_buffer);
const os_flags: c.O = .{
.ACCMODE = if (flags.read) .RDWR else .WRONLY,
.NONBLOCK = flags.lock == .none or flags.lock_nonblocking,
.SHLOCK = flags.lock == .shared,
.EXLOCK = flags.lock == .exclusive,
.CREAT = true,
.TRUNC = flags.truncate,
.EXCL = flags.exclusive,
.CLOEXEC = true,
};
const fd: c.fd_t = while (true) {
const rc = c.openat(dir.handle, sub_path_posix, os_flags, flags.permissions.toMode());
switch (c.errno(rc)) {
.SUCCESS => break @intCast(rc),
.INTR => {},
.FAULT => |err| return errnoBug(err),
.INVAL => return error.BadPathName,
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.ACCES => return error.AccessDenied,
.FBIG => return error.FileTooBig,
.OVERFLOW => return error.FileTooBig,
.ISDIR => return error.IsDir,
.LOOP => return error.SymLinkLoop,
.MFILE => return error.ProcessFdQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NFILE => return error.SystemFdQuotaExceeded,
.NODEV => return error.NoDevice,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.NOTDIR => return error.NotDir,
.PERM => return error.PermissionDenied,
.EXIST => return error.PathAlreadyExists,
.BUSY => return error.DeviceBusy,
.OPNOTSUPP => return error.FileLocksUnsupported,
.AGAIN => return error.WouldBlock,
.TXTBSY => return error.FileBusy,
.ROFS => return error.ReadOnlyFileSystem,
.NXIO => return error.NoDevice,
.ILSEQ => return error.BadPathName,
else => |err| return unexpectedErrno(err),
}
};
errdefer closeFd(fd);
return .{
.handle = fd,
.flags = .{ .nonblocking = os_flags.NONBLOCK },
};
}
fn dirCreateFileAtomic(
userdata: ?*anyopaque,
dir: Dir,
dest_path: []const u8,
options: Dir.CreateFileAtomicOptions,
) Dir.CreateFileAtomicError!File.Atomic {
const ev: *Evented = @ptrCast(@alignCast(userdata));
if (Dir.path.dirname(dest_path)) |dirname| {
const new_dir = if (options.make_path)
dirCreateDirPathOpen(ev, dir, dirname, .default_dir, .{}) catch |err| switch (err) {
// None of these make sense in this context.
error.IsDir,
error.Streaming,
error.DiskQuota,
error.PathAlreadyExists,
error.LinkQuotaExceeded,
error.PipeBusy,
error.FileTooBig,
error.FileLocksUnsupported,
error.DeviceBusy,
=> return error.Unexpected,
else => |e| return e,
}
else
try dirOpenDir(ev, dir, dirname, .{});
return ev.atomicFileInit(Dir.path.basename(dest_path), options.permissions, new_dir, true);
}
return ev.atomicFileInit(dest_path, options.permissions, dir, false);
}
fn atomicFileInit(
ev: *Evented,
dest_basename: []const u8,
permissions: File.Permissions,
dir: Dir,
close_dir_on_deinit: bool,
) Dir.CreateFileAtomicError!File.Atomic {
while (true) {
var random_integer: u64 = undefined;
random(ev, @ptrCast(&random_integer));
const tmp_sub_path = std.fmt.hex(random_integer);
const file = dirCreateFile(ev, dir, &tmp_sub_path, .{
.permissions = permissions,
.exclusive = true,
}) catch |err| switch (err) {
error.PathAlreadyExists => continue,
error.DeviceBusy => continue,
error.FileBusy => continue,
error.IsDir => return error.Unexpected, // No path components.
error.FileTooBig => return error.Unexpected, // Creating, not opening.
error.FileLocksUnsupported => return error.Unexpected, // Not asking for locks.
error.PipeBusy => return error.Unexpected, // Not opening a pipe.
else => |e| return e,
};
return .{
.file = file,
.file_basename_hex = random_integer,
.dest_sub_path = dest_basename,
.file_open = true,
.file_exists = true,
.close_dir_on_deinit = close_dir_on_deinit,
.dir = dir,
};
}
}
fn dirOpenFile(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
flags: Dir.OpenFileOptions,
) File.OpenError!File {
const ev: *Evented = @ptrCast(@alignCast(userdata));
var path_buffer: [c.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &path_buffer);
const os_flags: c.O = .{
.ACCMODE = switch (flags.mode) {
.read_only => .RDONLY,
.write_only => .WRONLY,
.read_write => .RDWR,
},
.NONBLOCK = flags.lock == .none or flags.lock_nonblocking,
.SHLOCK = flags.lock == .shared,
.EXLOCK = flags.lock == .exclusive,
.NOFOLLOW = !flags.follow_symlinks,
.NOCTTY = !flags.allow_ctty,
.CLOEXEC = true,
};
const fd: c.fd_t = while (true) {
const rc = c.openat(dir.handle, sub_path_posix, os_flags);
switch (c.errno(rc)) {
.SUCCESS => break @intCast(rc),
.INTR => {},
.FAULT => |err| return errnoBug(err),
.INVAL => return error.BadPathName,
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.ACCES => return error.AccessDenied,
.FBIG => return error.FileTooBig,
.OVERFLOW => return error.FileTooBig,
.ISDIR => return error.IsDir,
.LOOP => return error.SymLinkLoop,
.MFILE => return error.ProcessFdQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NFILE => return error.SystemFdQuotaExceeded,
.NODEV => return error.NoDevice,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.NOTDIR => return error.NotDir,
.PERM => return error.PermissionDenied,
.EXIST => return error.PathAlreadyExists,
.BUSY => return error.DeviceBusy,
.OPNOTSUPP => return error.FileLocksUnsupported,
.AGAIN => return error.WouldBlock,
.TXTBSY => return error.FileBusy,
.NXIO => return error.NoDevice,
.ROFS => return error.ReadOnlyFileSystem,
.ILSEQ => return error.BadPathName,
else => |err| return unexpectedErrno(err),
}
};
errdefer closeFd(fd);
if (!flags.allow_directory) {
const is_dir = is_dir: {
const stat = fileStat(ev, .{
.handle = fd,
.flags = .{ .nonblocking = false },
}) catch |err| switch (err) {
// The directory-ness is either unknown or unknowable
error.Streaming => break :is_dir false,
else => |e| return e,
};
break :is_dir stat.kind == .directory;
};
if (is_dir) return error.IsDir;
}
return .{
.handle = fd,
.flags = .{ .nonblocking = os_flags.NONBLOCK },
};
}
fn dirClose(userdata: ?*anyopaque, dirs: []const Dir) void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
for (dirs) |dir| closeFd(dir.handle);
}
fn dirRead(userdata: ?*anyopaque, dr: *Dir.Reader, buffer: []Dir.Entry) Dir.Reader.Error!usize {
const ev: *Evented = @ptrCast(@alignCast(userdata));
const Header = extern struct {
seek: i64,
};
const header: *Header = @ptrCast(dr.buffer.ptr);
const header_end: usize = @sizeOf(Header);
if (dr.index < header_end) {
// Initialize header.
dr.index = header_end;
dr.end = header_end;
header.* = .{ .seek = 0 };
}
var buffer_index: usize = 0;
while (buffer.len - buffer_index != 0) {
if (dr.end - dr.index == 0) {
// Refill the buffer, unless we've already created references to
// buffered data.
if (buffer_index != 0) break;
if (dr.state == .reset) {
ev.lseek(dr.dir.handle, 0, c.SEEK.SET) catch |err| switch (err) {
error.Unseekable => return error.Unexpected,
else => |e| return e,
};
dr.state = .reading;
}
const dents_buffer = dr.buffer[header_end..];
const n: usize = while (true) {
const rc = c.getdirentries(dr.dir.handle, dents_buffer.ptr, dents_buffer.len, &header.seek);
switch (c.errno(rc)) {
.SUCCESS => break @intCast(rc),
.INTR => {},
.BADF => |err| return errnoBug(err), // Dir is invalid or was opened without iteration ability.
.FAULT => |err| return errnoBug(err),
.NOTDIR => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
else => |err| return unexpectedErrno(err),
}
};
if (n == 0) {
dr.state = .finished;
return 0;
}
dr.index = header_end;
dr.end = header_end + n;
}
const darwin_entry = @as(*align(1) c.dirent, @ptrCast(&dr.buffer[dr.index]));
const next_index = dr.index + darwin_entry.reclen;
dr.index = next_index;
const name = @as([*]u8, @ptrCast(&darwin_entry.name))[0..darwin_entry.namlen];
if (std.mem.eql(u8, name, ".") or std.mem.eql(u8, name, "..") or (darwin_entry.ino == 0))
continue;
const entry_kind: File.Kind = switch (darwin_entry.type) {
c.DT.BLK => .block_device,
c.DT.CHR => .character_device,
c.DT.DIR => .directory,
c.DT.FIFO => .named_pipe,
c.DT.LNK => .sym_link,
c.DT.REG => .file,
c.DT.SOCK => .unix_domain_socket,
c.DT.WHT => .whiteout,
else => .unknown,
};
buffer[buffer_index] = .{
.name = name,
.kind = entry_kind,
.inode = darwin_entry.ino,
};
buffer_index += 1;
}
return buffer_index;
}
fn dirRealPath(userdata: ?*anyopaque, dir: Dir, out_buffer: []u8) Dir.RealPathError!usize {
const ev: *Evented = @ptrCast(@alignCast(userdata));
return ev.realPath(dir.handle, out_buffer);
}
fn realPath(ev: *Evented, fd: c.fd_t, out_buffer: []u8) File.RealPathError!usize {
_ = ev;
var buffer: [c.PATH_MAX]u8 = undefined;
@memset(&buffer, 0);
while (true) {
switch (c.errno(c.fcntl(fd, c.F.GETPATH, &buffer))) {
.SUCCESS => break,
.INTR => {},
.ACCES => return error.AccessDenied,
.BADF => return error.FileNotFound,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NameTooLong,
.RANGE => return error.NameTooLong,
else => |err| return unexpectedErrno(err),
}
}
const n = std.mem.findScalar(u8, &buffer, 0) orelse buffer.len;
if (n > out_buffer.len) return error.NameTooLong;
@memcpy(out_buffer[0..n], buffer[0..n]);
return n;
}
fn dirRealPathFile(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
out_buffer: []u8,
) Dir.RealPathFileError!usize {
const ev: *Evented = @ptrCast(@alignCast(userdata));
var path_buffer: [c.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &path_buffer);
if (dir.handle == c.AT.FDCWD) {
if (out_buffer.len < c.PATH_MAX) return error.NameTooLong;
while (true) {
if (c.realpath(sub_path_posix, out_buffer.ptr)) |redundant_pointer| {
assert(redundant_pointer == out_buffer.ptr);
return std.mem.findScalar(u8, out_buffer, 0) orelse out_buffer.len;
}
const err: c.E = @fromBackingInt(@intCast(c._errno().*));
switch (err) {
.INTR => {},
.INVAL => return errnoBug(err),
.BADF => return errnoBug(err),
.FAULT => return errnoBug(err),
.ACCES => return error.AccessDenied,
.NOENT => return error.FileNotFound,
.OPNOTSUPP => return error.OperationUnsupported,
.NOTDIR => return error.NotDir,
.NAMETOOLONG => return error.NameTooLong,
.LOOP => return error.SymLinkLoop,
.IO => return error.InputOutput,
else => return unexpectedErrno(err),
}
}
}
const os_flags: c.O = .{
.NONBLOCK = true,
.CLOEXEC = true,
};
const fd: c.fd_t = while (true) {
const rc = c.openat(dir.handle, sub_path_posix, os_flags);
switch (c.errno(rc)) {
.SUCCESS => break @intCast(rc),
.INTR => {},
.FAULT => |err| return errnoBug(err),
.INVAL => return error.BadPathName,
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.ACCES => return error.AccessDenied,
.FBIG => return error.FileTooBig,
.OVERFLOW => return error.FileTooBig,
.ISDIR => return error.IsDir,
.LOOP => return error.SymLinkLoop,
.MFILE => return error.ProcessFdQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NFILE => return error.SystemFdQuotaExceeded,
.NODEV => return error.NoDevice,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.NOTDIR => return error.NotDir,
.PERM => return error.PermissionDenied,
.EXIST => return error.PathAlreadyExists,
.BUSY => return error.DeviceBusy,
.NXIO => return error.NoDevice,
.ILSEQ => return error.BadPathName,
else => |err| return unexpectedErrno(err),
}
};
defer closeFd(fd);
return ev.realPath(fd, out_buffer);
}
fn dirDeleteFile(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8) Dir.DeleteFileError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
var path_buffer: [c.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &path_buffer);
while (true) switch (c.errno(c.unlinkat(dir.handle, sub_path_posix, 0))) {
.SUCCESS => return,
.INTR => {},
// Some systems return permission errors when trying to delete a
// directory, so we need to handle that case specifically and
// translate the error.
.PERM => {
// Don't follow symlinks to match unlinkat (which acts on symlinks rather than follows them).
var st = std.mem.zeroes(c.Stat);
while (true) switch (c.errno(c.fstatat(
dir.handle,
sub_path_posix,
&st,
c.AT.SYMLINK_NOFOLLOW,
))) {
.SUCCESS => break,
.INTR => {},
else => return error.PermissionDenied,
};
if (st.mode & c.S.IFMT == c.S.IFDIR) return error.IsDir else return error.PermissionDenied;
},
.ACCES => return error.AccessDenied,
.BUSY => return error.FileBusy,
.FAULT => |err| return errnoBug(err),
.IO => return error.FileSystem,
.ISDIR => return error.IsDir,
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.NOMEM => return error.SystemResources,
.ROFS => return error.ReadOnlyFileSystem,
.EXIST => |err| return errnoBug(err),
.NOTEMPTY => |err| return errnoBug(err), // Not passing AT.REMOVEDIR
.ILSEQ => return error.BadPathName,
.INVAL => |err| return errnoBug(err), // invalid flags, or pathname has . as last component
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
else => |err| return unexpectedErrno(err),
};
}
fn dirDeleteDir(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8) Dir.DeleteDirError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
var path_buffer: [c.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &path_buffer);
while (true) switch (c.errno(c.unlinkat(dir.handle, sub_path_posix, c.AT.REMOVEDIR))) {
.SUCCESS => return,
.INTR => {},
.ACCES => return error.AccessDenied,
.PERM => return error.PermissionDenied,
.BUSY => return error.FileBusy,
.FAULT => |err| return errnoBug(err),
.IO => return error.FileSystem,
.ISDIR => |err| return errnoBug(err),
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.NOMEM => return error.SystemResources,
.ROFS => return error.ReadOnlyFileSystem,
.EXIST => |err| return errnoBug(err),
.NOTEMPTY => return error.DirNotEmpty,
.ILSEQ => return error.BadPathName,
.INVAL => |err| return errnoBug(err), // invalid flags, or pathname has . as last component
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
else => |err| return unexpectedErrno(err),
};
}
fn dirRename(
userdata: ?*anyopaque,
old_dir: Dir,
old_sub_path: []const u8,
new_dir: Dir,
new_sub_path: []const u8,
) Dir.RenameError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
var old_path_buffer: [c.PATH_MAX]u8 = undefined;
var new_path_buffer: [c.PATH_MAX]u8 = undefined;
const old_sub_path_posix = try pathToPosix(old_sub_path, &old_path_buffer);
const new_sub_path_posix = try pathToPosix(new_sub_path, &new_path_buffer);
while (true) switch (c.errno(c.renameat(old_dir.handle, old_sub_path_posix, new_dir.handle, new_sub_path_posix))) {
.SUCCESS => return,
.INTR => {},
.ACCES => return error.AccessDenied,
.PERM => return error.PermissionDenied,
.BUSY => return error.FileBusy,
.DQUOT => return error.DiskQuota,
.ISDIR => return error.IsDir,
.IO => return error.HardwareFailure,
.LOOP => return error.SymLinkLoop,
.MLINK => return error.LinkQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.EXIST => return error.DirNotEmpty,
.NOTEMPTY => return error.DirNotEmpty,
.ROFS => return error.ReadOnlyFileSystem,
.XDEV => return error.CrossDevice,
.ILSEQ => return error.BadPathName,
.FAULT => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
else => |err| return unexpectedErrno(err),
};
}
fn dirRenamePreserve(
userdata: ?*anyopaque,
old_dir: Dir,
old_sub_path: []const u8,
new_dir: Dir,
new_sub_path: []const u8,
) Dir.RenamePreserveError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
// Make a hard link then delete the original.
try dirHardLink(ev, old_dir, old_sub_path, new_dir, new_sub_path, .{ .follow_symlinks = false });
const prev = swapCancelProtection(ev, .blocked);
defer _ = swapCancelProtection(ev, prev);
dirDeleteFile(ev, old_dir, old_sub_path) catch {};
}
fn dirSymLink(
userdata: ?*anyopaque,
dir: Dir,
target_path: []const u8,
sym_link_path: []const u8,
flags: Dir.SymLinkFlags,
) Dir.SymLinkError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
_ = flags;
var target_path_buffer: [c.PATH_MAX]u8 = undefined;
var sym_link_path_buffer: [c.PATH_MAX]u8 = undefined;
const target_path_posix = try pathToPosix(target_path, &target_path_buffer);
const sym_link_path_posix = try pathToPosix(sym_link_path, &sym_link_path_buffer);
while (true) switch (c.errno(c.symlinkat(target_path_posix, dir.handle, sym_link_path_posix))) {
.SUCCESS => return,
.INTR => {},
.FAULT => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
.ACCES => return error.AccessDenied,
.PERM => return error.PermissionDenied,
.DQUOT => return error.DiskQuota,
.EXIST => return error.PathAlreadyExists,
.IO => return error.FileSystem,
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.ROFS => return error.ReadOnlyFileSystem,
.ILSEQ => return error.BadPathName,
else => |err| return unexpectedErrno(err),
};
}
fn dirReadLink(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
buffer: []u8,
) Dir.ReadLinkError!usize {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
var sub_path_buffer: [c.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &sub_path_buffer);
while (true) {
const rc = c.readlinkat(dir.handle, sub_path_posix, buffer.ptr, buffer.len);
switch (c.errno(rc)) {
.SUCCESS => return @intCast(rc),
.INTR => {},
.ACCES => return error.AccessDenied,
.FAULT => |err| return errnoBug(err),
.INVAL => return error.NotLink,
.IO => return error.FileSystem,
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOTDIR => return error.NotDir,
.ILSEQ => return error.BadPathName,
else => |err| return unexpectedErrno(err),
}
}
}
fn dirSetOwner(
userdata: ?*anyopaque,
dir: Dir,
owner: ?File.Uid,
group: ?File.Gid,
) Dir.SetOwnerError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
return fchown(dir.handle, owner, group);
}
fn fchown(fd: c.fd_t, owner: ?File.Uid, group: ?File.Gid) File.SetOwnerError!void {
const uid = owner orelse std.math.maxInt(c.uid_t);
const gid = group orelse std.math.maxInt(c.gid_t);
while (true) switch (c.errno(c.fchown(fd, uid, gid))) {
.SUCCESS => return,
.INTR => {},
.BADF => |err| return errnoBug(err), // likely fd refers to directory opened without `Dir.OpenOptions.iterate`
.FAULT => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
.ACCES => return error.AccessDenied,
.IO => return error.InputOutput,
.LOOP => return error.SymLinkLoop,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOTDIR => return error.FileNotFound,
.PERM => return error.PermissionDenied,
.ROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
};
}
fn dirSetFileOwner(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
owner: ?File.Uid,
group: ?File.Gid,
options: Dir.SetFileOwnerOptions,
) Dir.SetFileOwnerError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
var path_buffer: [c.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &path_buffer);
_ = ev;
while (true) switch (c.errno(c.fchownat(
dir.handle,
sub_path_posix,
owner orelse std.math.maxInt(c.uid_t),
group orelse std.math.maxInt(c.gid_t),
if (options.follow_symlinks) 0 else c.AT.SYMLINK_NOFOLLOW,
))) {
.SUCCESS => return,
.INTR => continue,
.BADF => |err| return errnoBug(err), // likely fd refers to directory opened without `Dir.OpenOptions.iterate`
.FAULT => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
.ACCES => return error.AccessDenied,
.IO => return error.InputOutput,
.LOOP => return error.SymLinkLoop,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOTDIR => return error.FileNotFound,
.PERM => return error.PermissionDenied,
.ROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
};
}
fn dirSetPermissions(
userdata: ?*anyopaque,
dir: Dir,
permissions: Dir.Permissions,
) Dir.SetPermissionsError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
return ev.fchmod(dir.handle, permissions.toMode());
}
fn dirSetFilePermissions(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
permissions: Dir.Permissions,
options: Dir.SetFilePermissionsOptions,
) Dir.SetFilePermissionsError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
var path_buffer: [c.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &path_buffer);
const mode = permissions.toMode();
const flags: u32 = if (options.follow_symlinks) 0 else c.AT.SYMLINK_NOFOLLOW;
while (true) switch (c.errno(c.fchmodat(dir.handle, sub_path_posix, mode, flags))) {
.SUCCESS => return,
.INTR => {},
.BADF => |err| return errnoBug(err),
.FAULT => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
.ACCES => return error.AccessDenied,
.IO => return error.InputOutput,
.LOOP => return error.SymLinkLoop,
.MFILE => return error.ProcessFdQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NFILE => return error.SystemFdQuotaExceeded,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.OPNOTSUPP => return error.OperationUnsupported,
.PERM => return error.PermissionDenied,
.ROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
};
}
fn dirSetTimestamps(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
options: Dir.SetTimestampsOptions,
) Dir.SetTimestampsError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
var times_buffer: [2]c.timespec = undefined;
const times = if (options.modify_timestamp == .now and options.access_timestamp == .now) null else p: {
times_buffer = .{
setTimestampToPosix(options.access_timestamp),
setTimestampToPosix(options.modify_timestamp),
};
break :p ×_buffer;
};
const flags: u32 = if (options.follow_symlinks) 0 else c.AT.SYMLINK_NOFOLLOW;
var path_buffer: [c.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &path_buffer);
while (true) switch (c.errno(c.utimensat(dir.handle, sub_path_posix, times, flags))) {
.SUCCESS => return,
.INTR => {},
.BADF => |err| return errnoBug(err), // always a race condition
.FAULT => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
.ACCES => return error.AccessDenied,
.PERM => return error.PermissionDenied,
.ROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
};
}
fn dirHardLink(
userdata: ?*anyopaque,
old_dir: Dir,
old_sub_path: []const u8,
new_dir: Dir,
new_sub_path: []const u8,
options: Dir.HardLinkOptions,
) Dir.HardLinkError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
var old_path_buffer: [c.PATH_MAX]u8 = undefined;
var new_path_buffer: [c.PATH_MAX]u8 = undefined;
const old_sub_path_posix = try pathToPosix(old_sub_path, &old_path_buffer);
const new_sub_path_posix = try pathToPosix(new_sub_path, &new_path_buffer);
const flags: u32 = if (options.follow_symlinks) c.AT.SYMLINK_FOLLOW else 0;
return linkat(old_dir.handle, old_sub_path_posix, new_dir.handle, new_sub_path_posix, flags);
}
fn fileStat(userdata: ?*anyopaque, file: File) File.StatError!File.Stat {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
while (true) {
var stat = std.mem.zeroes(c.Stat);
switch (c.errno(c.fstat(file.handle, &stat))) {
.SUCCESS => return statFromPosix(&stat),
.INTR => {},
.INVAL => |err| return errnoBug(err),
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.NOMEM => return error.SystemResources,
.ACCES => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
}
fn fileLength(userdata: ?*anyopaque, file: File) File.LengthError!u64 {
const ev: *Evented = @ptrCast(@alignCast(userdata));
const stat = try fileStat(ev, file);
return stat.size;
}
fn fileClose(userdata: ?*anyopaque, files: []const File) void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
for (files) |file| closeFd(file.handle);
}
fn fileWritePositional(
userdata: ?*anyopaque,
file: File,
header: []const u8,
data: []const []const u8,
splat: usize,
offset: u64,
) File.WritePositionalError!usize {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
var iovecs: [max_iovecs_len]iovec_const = undefined;
var iovlen: iovlen_t = 0;
var remaining: Io.Limit = .unlimited;
addBuf(true, &iovecs, &iovlen, &remaining, header);
for (data[0 .. data.len - 1]) |bytes| addBuf(true, &iovecs, &iovlen, &remaining, bytes);
const pattern = data[data.len - 1];
var backup_buffer: [splat_buffer_size]u8 = undefined;
if (iovecs.len - iovlen != 0 and remaining != .nothing) switch (splat) {
0 => {},
1 => addBuf(true, &iovecs, &iovlen, &remaining, pattern),
else => switch (pattern.len) {
0 => {},
1 => {
const splat_buffer = &backup_buffer;
const memset_len = @min(splat_buffer.len, splat);
const buf = splat_buffer[0..memset_len];
@memset(buf, pattern[0]);
addBuf(true, &iovecs, &iovlen, &remaining, buf);
var remaining_splat = splat - buf.len;
while (remaining_splat > splat_buffer.len and iovecs.len - iovlen != 0 and remaining != .nothing) {
assert(buf.len == splat_buffer.len);
addBuf(true, &iovecs, &iovlen, &remaining, splat_buffer);
remaining_splat -= splat_buffer.len;
}
addBuf(true, &iovecs, &iovlen, &remaining, splat_buffer[0..@min(remaining_splat, splat_buffer.len)]);
},
else => for (0..@min(splat, iovecs.len - iovlen)) |_| {
if (remaining == .nothing) break;
addBuf(true, &iovecs, &iovlen, &remaining, pattern);
},
},
};
if (iovlen == 0) return 0;
while (true) {
const rc = c.pwritev(file.handle, &iovecs, iovlen, @bitCast(offset));
switch (c.errno(rc)) {
.SUCCESS => return @intCast(rc),
.INTR => {},
.INVAL => |err| return errnoBug(err),
.FAULT => |err| return errnoBug(err),
.DESTADDRREQ => |err| return errnoBug(err), // `connect` was never called.
.CONNRESET => |err| return errnoBug(err), // Not a socket handle.
.BADF => return error.NotOpenForWriting,
.AGAIN => return error.WouldBlock,
.DQUOT => return error.DiskQuota,
.FBIG => return error.FileTooBig,
.IO => return error.InputOutput,
.NOSPC => return error.NoSpaceLeft,
.PERM => return error.PermissionDenied,
.PIPE => return error.BrokenPipe,
.BUSY => return error.DeviceBusy,
.TXTBSY => return error.FileBusy,
.NXIO => return error.Unseekable,
.SPIPE => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
else => |err| return unexpectedErrno(err),
}
}
}
fn fileWriteFileStreaming(
userdata: ?*anyopaque,
file: File,
header: []const u8,
file_reader: *File.Reader,
limit: Io.Limit,
) File.Writer.WriteFileError!usize {
const ev: *Evented = @ptrCast(@alignCast(userdata));
const reader_buffered = file_reader.interface.buffered();
if (reader_buffered.len >= @backingInt(limit)) {
const n = try fileWriteStreaming(ev, file, header, &.{limit.slice(reader_buffered)}, 1);
file_reader.interface.toss(n -| header.len);
return n;
}
const file_limit = @backingInt(limit) - reader_buffered.len;
const out_fd = file.handle;
const in_fd = file_reader.file.handle;
if (file_reader.size) |size| {
if (size - file_reader.pos == 0) {
if (reader_buffered.len != 0) {
const n = try fileWriteStreaming(ev, file, header, &.{limit.slice(reader_buffered)}, 1);
file_reader.interface.toss(n -| header.len);
return n;
} else {
return error.EndOfStream;
}
}
}
if (@atomicLoad(UseSendfile, &ev.use_sendfile, .monotonic) == .disabled) return error.Unimplemented;
const offset = std.math.cast(c.off_t, file_reader.pos) orelse return error.Unimplemented;
var hdtr_data: c.sf_hdtr = undefined;
var headers: [2]iovec_const = undefined;
var headers_i: u8 = 0;
if (header.len != 0) {
headers[headers_i] = .{ .base = header.ptr, .len = header.len };
headers_i += 1;
}
if (reader_buffered.len != 0) {
headers[headers_i] = .{ .base = reader_buffered.ptr, .len = reader_buffered.len };
headers_i += 1;
}
const hdtr: ?*c.sf_hdtr = if (headers_i == 0) null else b: {
hdtr_data = .{
.headers = &headers,
.hdr_cnt = headers_i,
.trailers = null,
.trl_cnt = 0,
};
break :b &hdtr_data;
};
const max_count = std.math.maxInt(i32); // Avoid EINVAL.
var len: c.off_t = @min(file_limit, max_count);
const flags = 0;
while (true) switch (c.errno(c.sendfile(in_fd, out_fd, offset, &len, hdtr, flags))) {
.SUCCESS => break,
.OPNOTSUPP, .NOTSOCK, .NOSYS => {
// Give calling code chance to observe before trying
// something else.
@atomicStore(UseSendfile, &ev.use_sendfile, .disabled, .monotonic);
return 0;
},
.INTR => if (len > 0) break,
.AGAIN => {
if (len == 0) return error.WouldBlock;
break;
},
else => |e| {
assert(error.Unexpected == switch (e) {
.NOTCONN => return error.BrokenPipe,
.IO => return error.InputOutput,
.PIPE => return error.BrokenPipe,
.BADF => |err| errnoBug(err),
.FAULT => |err| errnoBug(err),
.INVAL => |err| errnoBug(err),
else => |err| unexpectedErrno(err),
});
// Give calling code chance to observe the error before trying
// something else.
@atomicStore(UseSendfile, &ev.use_sendfile, .disabled, .monotonic);
return 0;
},
};
if (len == 0) {
file_reader.size = file_reader.pos;
return error.EndOfStream;
}
const u_len: usize = @bitCast(len);
file_reader.interface.toss(u_len -| header.len);
return u_len;
}
fn fileWriteFilePositional(
userdata: ?*anyopaque,
file: File,
header: []const u8,
file_reader: *File.Reader,
limit: Io.Limit,
offset: u64,
) File.WriteFilePositionalError!usize {
const ev: *Evented = @ptrCast(@alignCast(userdata));
const reader_buffered = file_reader.interface.buffered();
if (reader_buffered.len >= @backingInt(limit)) {
const n = try fileWritePositional(
ev,
file,
header,
&.{limit.slice(reader_buffered)},
1,
offset,
);
file_reader.interface.toss(n -| header.len);
return n;
}
const out_fd = file.handle;
const in_fd = file_reader.file.handle;
if (file_reader.size) |size| {
if (size - file_reader.pos == 0) {
if (reader_buffered.len != 0) {
const n = try fileWritePositional(
ev,
file,
header,
&.{limit.slice(reader_buffered)},
1,
offset,
);
file_reader.interface.toss(n -| header.len);
return n;
} else {
return error.EndOfStream;
}
}
}
if (@atomicLoad(UseFcopyfile, &ev.use_fcopyfile, .monotonic) == .disabled)
return error.Unimplemented;
if (file_reader.pos != 0) return error.Unimplemented;
if (offset != 0) return error.Unimplemented;
if (limit != .unlimited) return error.Unimplemented;
const size = file_reader.getSize() catch return error.Unimplemented;
if (header.len != 0 or reader_buffered.len != 0) {
const n = try fileWritePositional(
ev,
file,
header,
&.{limit.slice(reader_buffered)},
1,
offset,
);
file_reader.interface.toss(n -| header.len);
return n;
}
while (true) {
const rc = c.fcopyfile(in_fd, out_fd, null, .{ .DATA = true });
switch (c.errno(rc)) {
.SUCCESS => break,
.INTR => {},
.OPNOTSUPP => {
// Give calling code chance to observe before trying
// something else.
@atomicStore(UseFcopyfile, &ev.use_fcopyfile, .disabled, .monotonic);
return 0;
},
else => |e| {
assert(error.Unexpected == switch (e) {
.NOMEM => return error.SystemResources,
.INVAL => |err| errnoBug(err),
else => |err| unexpectedErrno(err),
});
return 0;
},
}
}
file_reader.pos = size;
return size;
}
fn fileReadPositional(
userdata: ?*anyopaque,
file: File,
data: []const []u8,
offset: u64,
) File.ReadPositionalError!usize {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
var iovecs: [max_iovecs_len]iovec = undefined;
var iovlen: iovlen_t = 0;
var remaining: Io.Limit = .unlimited;
for (data) |buf| addBuf(false, &iovecs, &iovlen, &remaining, buf);
if (iovlen == 0) return 0;
while (true) {
const rc = c.preadv(file.handle, &iovecs, iovlen, @bitCast(offset));
switch (c.errno(rc)) {
.SUCCESS => return @intCast(rc),
.INTR => {},
.NXIO => return error.Unseekable,
.SPIPE => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
.NOBUFS => return error.SystemResources,
.NOMEM => return error.SystemResources,
.AGAIN => return error.WouldBlock,
.IO => return error.InputOutput,
.ISDIR => return error.IsDir,
.NOTCONN => |err| return errnoBug(err), // not a socket
.CONNRESET => |err| return errnoBug(err), // not a socket
.INVAL => |err| return errnoBug(err),
.FAULT => |err| return errnoBug(err),
.BADF => return error.NotOpenForReading,
else => |err| return unexpectedErrno(err),
}
}
}
fn fileSeekBy(userdata: ?*anyopaque, file: File, offset: i64) File.SeekError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
return ev.lseek(file.handle, @bitCast(offset), c.SEEK.CUR);
}
fn fileSeekTo(userdata: ?*anyopaque, file: File, offset: u64) File.SeekError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
return ev.lseek(file.handle, offset, c.SEEK.SET);
}
fn lseek(ev: *Evented, fd: c.fd_t, offset: u64, whence: i32) File.SeekError!void {
_ = ev;
while (true) switch (c.errno(c.lseek(fd, @bitCast(offset), whence))) {
.SUCCESS => return,
.INTR => {},
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.INVAL => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
.SPIPE => return error.Unseekable,
.NXIO => return error.Unseekable,
else => |err| return unexpectedErrno(err),
};
}
fn fileSync(userdata: ?*anyopaque, file: File) File.SyncError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
while (true) switch (c.errno(c.fsync(file.handle))) {
.SUCCESS => return,
.INTR => {},
.BADF => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
.ROFS => |err| return errnoBug(err),
.IO => return error.InputOutput,
.NOSPC => return error.NoSpaceLeft,
.DQUOT => return error.DiskQuota,
else => |err| return unexpectedErrno(err),
};
}
fn fileIsTty(userdata: ?*anyopaque, file: File) Io.Cancelable!bool {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
while (true) {
const rc = c.isatty(file.handle);
switch (c.errno(rc - 1)) {
.SUCCESS => return true,
.INTR => {},
else => return false,
}
}
}
fn fileEnableAnsiEscapeCodes(userdata: ?*anyopaque, file: File) File.EnableAnsiEscapeCodesError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
if (!try fileIsTty(ev, file)) return error.NotTerminalDevice;
}
fn fileSetLength(userdata: ?*anyopaque, file: File, length: u64) File.SetLengthError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
const signed_len: i64 = @bitCast(length);
if (signed_len < 0) return error.FileTooBig; // Avoid ambiguous EINVAL errors.
while (true) switch (c.errno(c.ftruncate(file.handle, signed_len))) {
.SUCCESS => return,
.INTR => {},
.FBIG => return error.FileTooBig,
.IO => return error.InputOutput,
.PERM => return error.PermissionDenied,
.TXTBSY => return error.FileBusy,
.BADF => |err| return errnoBug(err), // Handle not open for writing.
.INVAL => return error.NonResizable, // This is returned for /dev/null for example.
else => |err| return unexpectedErrno(err),
};
}
fn fileSetOwner(
userdata: ?*anyopaque,
file: File,
owner: ?File.Uid,
group: ?File.Gid,
) File.SetOwnerError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
return fchown(file.handle, owner, group);
}
fn fileSetPermissions(
userdata: ?*anyopaque,
file: File,
permissions: File.Permissions,
) File.SetPermissionsError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
return ev.fchmod(file.handle, permissions.toMode());
}
fn fchmod(ev: *Evented, fd: c.fd_t, mode: c.mode_t) File.SetPermissionsError!void {
_ = ev;
while (true) switch (c.errno(c.fchmod(fd, mode))) {
.SUCCESS => return,
.INTR => {},
.BADF => |err| return errnoBug(err),
.FAULT => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
.ACCES => return error.AccessDenied,
.IO => return error.InputOutput,
.LOOP => return error.SymLinkLoop,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOTDIR => return error.FileNotFound,
.PERM => return error.PermissionDenied,
.ROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
};
}
fn fileSetTimestamps(
userdata: ?*anyopaque,
file: File,
options: File.SetTimestampsOptions,
) File.SetTimestampsError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
var times_buffer: [2]c.timespec = undefined;
const times = if (options.modify_timestamp == .now and options.access_timestamp == .now) null else p: {
times_buffer = .{
setTimestampToPosix(options.access_timestamp),
setTimestampToPosix(options.modify_timestamp),
};
break :p ×_buffer;
};
while (true) switch (c.errno(c.futimens(file.handle, times))) {
.SUCCESS => return,
.INTR => {},
.BADF => |err| return errnoBug(err), // always a race condition
.FAULT => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
.ACCES => return error.AccessDenied,
.PERM => return error.PermissionDenied,
.ROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
};
}
fn fileLock(userdata: ?*anyopaque, file: File, lock: File.Lock) File.LockError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
const operation: i32 = switch (lock) {
.none => c.LOCK.UN,
.shared => c.LOCK.SH,
.exclusive => c.LOCK.EX,
};
while (true) switch (c.errno(c.flock(file.handle, operation))) {
.SUCCESS => return,
.INTR => {},
.BADF => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err), // invalid parameters
.NOLCK => return error.SystemResources,
.AGAIN => |err| return errnoBug(err),
.OPNOTSUPP => return error.FileLocksUnsupported,
else => |err| return unexpectedErrno(err),
};
}
fn fileTryLock(userdata: ?*anyopaque, file: File, lock: File.Lock) File.LockError!bool {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
const operation: i32 = switch (lock) {
.none => c.LOCK.UN,
.shared => c.LOCK.SH | c.LOCK.NB,
.exclusive => c.LOCK.EX | c.LOCK.NB,
};
while (true) switch (c.errno(c.flock(file.handle, operation))) {
.SUCCESS => return true,
.INTR => {},
.AGAIN => return false,
.BADF => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err), // invalid parameters
.NOLCK => return error.SystemResources,
.OPNOTSUPP => return error.FileLocksUnsupported,
else => |err| return unexpectedErrno(err),
};
}
fn fileUnlock(userdata: ?*anyopaque, file: File) void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
while (true) switch (c.errno(c.flock(file.handle, c.LOCK.UN))) {
.SUCCESS => return,
.INTR => {},
.AGAIN => return recoverableOsBugDetected(), // unlocking can't block
.BADF => return recoverableOsBugDetected(), // File descriptor used after closed.
.INVAL => return recoverableOsBugDetected(), // invalid parameters
.NOLCK => return recoverableOsBugDetected(), // Resource deallocation.
.OPNOTSUPP => return recoverableOsBugDetected(), // We already got the lock.
else => return recoverableOsBugDetected(), // Resource deallocation must succeed.
};
}
fn fileDowngradeLock(userdata: ?*anyopaque, file: File) File.DowngradeLockError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
const operation = c.LOCK.SH | c.LOCK.NB;
while (true) switch (c.errno(c.flock(file.handle, operation))) {
.SUCCESS => return,
.INTR => {},
.AGAIN => |err| return errnoBug(err), // File was not locked in exclusive mode.
.BADF => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err), // invalid parameters
.NOLCK => |err| return errnoBug(err), // Lock already obtained.
.OPNOTSUPP => |err| return errnoBug(err), // Lock already obtained.
else => |err| return unexpectedErrno(err),
};
}
fn fileRealPath(userdata: ?*anyopaque, file: File, out_buffer: []u8) File.RealPathError!usize {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
var buffer: [c.PATH_MAX]u8 = undefined;
@memset(&buffer, 0);
while (true) {
switch (c.errno(c.fcntl(file.handle, c.F.GETPATH, &buffer))) {
.SUCCESS => break,
.INTR => {},
.ACCES => return error.AccessDenied,
.BADF => return error.FileNotFound,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NameTooLong,
.RANGE => return error.NameTooLong,
else => |err| return unexpectedErrno(err),
}
}
const n = std.mem.findScalar(u8, &buffer, 0) orelse buffer.len;
if (n > out_buffer.len) return error.NameTooLong;
@memcpy(out_buffer[0..n], buffer[0..n]);
return n;
}
fn fileHardLink(
userdata: ?*anyopaque,
file: File,
new_dir: Dir,
new_sub_path: []const u8,
options: File.HardLinkOptions,
) File.HardLinkError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
_ = file;
_ = new_dir;
_ = new_sub_path;
_ = options;
return error.OperationUnsupported;
}
fn linkat(
old_dir: c.fd_t,
old_path: [*:0]const u8,
new_dir: c.fd_t,
new_path: [*:0]const u8,
flags: u32,
) File.HardLinkError!void {
while (true) switch (c.errno(c.linkat(old_dir, old_path, new_dir, new_path, flags))) {
.SUCCESS => return,
.INTR => {},
.ACCES => return error.AccessDenied,
.DQUOT => return error.DiskQuota,
.EXIST => return error.PathAlreadyExists,
.IO => return error.HardwareFailure,
.LOOP => return error.SymLinkLoop,
.MLINK => return error.LinkQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.NOTDIR => return error.NotDir,
.PERM => return error.PermissionDenied,
.ROFS => return error.ReadOnlyFileSystem,
.XDEV => return error.CrossDevice,
.ILSEQ => return error.BadPathName,
.FAULT => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
else => |err| return unexpectedErrno(err),
};
}
fn fileMemoryMapCreate(
userdata: ?*anyopaque,
file: File,
options: File.MemoryMap.CreateOptions,
) File.MemoryMap.CreateError!File.MemoryMap {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
const prot: c.PROT = .{
.READ = options.protection.read,
.WRITE = options.protection.write,
.EXEC = options.protection.execute,
};
const flags: c.MAP = .{
.TYPE = .SHARED,
};
const page_align = std.heap.page_size_min;
const contents = while (true) {
const casted_offset = std.math.cast(i64, options.offset) orelse return error.Unseekable;
const rc = c.mmap(null, options.len, prot, flags, file.handle, casted_offset);
const err: c.E = if (rc != c.MAP_FAILED) .SUCCESS else @fromBackingInt(@intCast(c._errno().*));
switch (err) {
.SUCCESS => break @as([*]align(page_align) u8, @ptrCast(@alignCast(rc)))[0..options.len],
.INTR => {},
.ACCES => return error.AccessDenied,
.AGAIN => return error.LockedMemoryLimitExceeded,
.MFILE => return error.ProcessFdQuotaExceeded,
.NFILE => return error.SystemFdQuotaExceeded,
.NOMEM => return error.OutOfMemory,
.PERM => return error.PermissionDenied,
.OVERFLOW => return error.Unseekable,
.BADF => return errnoBug(err), // Always a race condition.
.INVAL => return errnoBug(err), // Invalid parameters to mmap()
else => return unexpectedErrno(err),
}
};
return .{
.file = file,
.offset = options.offset,
.memory = contents,
.section = {},
};
}
fn fileMemoryMapDestroy(userdata: ?*anyopaque, mm: *File.MemoryMap) void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
const memory = mm.memory;
if (memory.len == 0) return;
switch (c.errno(c.munmap(memory.ptr, memory.len))) {
.SUCCESS => {},
else => |err| if (builtin.mode == .debug)
std.log.err("failed to unmap {d} bytes at {*}: {t}", .{ memory.len, memory.ptr, err }),
}
mm.* = undefined;
}
fn fileMemoryMapSetLength(
userdata: ?*anyopaque,
mm: *File.MemoryMap,
new_len: usize,
) File.MemoryMap.SetLengthError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
const page_size = std.heap.pageSize();
const alignment: Alignment = .fromByteUnits(page_size);
const old_memory = mm.memory;
if (alignment.forward(new_len) == alignment.forward(old_memory.len)) {
mm.memory.len = new_len;
return;
}
return error.OperationUnsupported;
}
fn fileMemoryMapRead(userdata: ?*anyopaque, mm: *File.MemoryMap) File.ReadPositionalError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
_ = mm;
}
fn fileMemoryMapWrite(userdata: ?*anyopaque, mm: *File.MemoryMap) File.WritePositionalError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
_ = mm;
}
fn processExecutableOpen(
userdata: ?*anyopaque,
flags: Dir.OpenFileOptions,
) process.OpenExecutableError!File {
const ev: *Evented = @ptrCast(@alignCast(userdata));
// _NSGetExecutablePath() returns a path that might be a symlink to
// the executable. Here it does not matter since we open it.
var symlink_path_buf: [c.PATH_MAX + 1]u8 = undefined;
var n: u32 = symlink_path_buf.len;
const rc = c._NSGetExecutablePath(&symlink_path_buf, &n);
if (rc != 0) return error.NameTooLong;
const symlink_path = std.mem.sliceTo(&symlink_path_buf, 0);
return dirOpenFile(ev, .cwd(), symlink_path, flags);
}
fn processExecutablePath(userdata: ?*anyopaque, out_buffer: []u8) process.ExecutablePathError!usize {
const ev: *Evented = @ptrCast(@alignCast(userdata));
// _NSGetExecutablePath() returns a path that might be a symlink to
// the executable.
var symlink_path_buf: [c.PATH_MAX + 1]u8 = undefined;
var n: u32 = symlink_path_buf.len;
const rc = c._NSGetExecutablePath(&symlink_path_buf, &n);
if (rc != 0) return error.NameTooLong;
const symlink_path = std.mem.sliceTo(&symlink_path_buf, 0);
assert(Dir.path.isAbsolute(symlink_path));
return dirRealPathFile(ev, .cwd(), symlink_path, out_buffer) catch |err| switch (err) {
error.NetworkNotFound => unreachable, // Windows-only
error.FileBusy => unreachable, // Windows-only
else => |e| return e,
};
}
fn lockStderr(userdata: ?*anyopaque, terminal_mode: ?Io.Terminal.Mode) Io.Cancelable!Io.LockedStderr {
const ev: *Evented = @ptrCast(@alignCast(userdata));
try ev.stderr_mutex.lock(ev);
errdefer ev.stderr_mutex.unlock();
return ev.initLockedStderr(terminal_mode);
}
fn tryLockStderr(
userdata: ?*anyopaque,
terminal_mode: ?Io.Terminal.Mode,
) Io.Cancelable!?Io.LockedStderr {
const ev: *Evented = @ptrCast(@alignCast(userdata));
if (!ev.stderr_mutex.tryLock()) return null;
errdefer ev.stderr_mutex.unlock();
return try ev.initLockedStderr(terminal_mode);
}
fn initLockedStderr(ev: *Evented, terminal_mode: ?Io.Terminal.Mode) Io.Cancelable!Io.LockedStderr {
ev.init_stderr_writer.once(ev, &initStderrWriter);
return .{
.file_writer = &ev.stderr_writer,
.terminal_mode = terminal_mode orelse ev.stderr_mode,
};
}
fn initStderrWriter(context: ?*anyopaque) callconv(.c) void {
const ev: *Evented = @ptrCast(@alignCast(context));
const cancel_protection = swapCancelProtection(ev, .blocked);
defer assert(swapCancelProtection(ev, cancel_protection) == .blocked);
ev.scan_environ.once(ev, &scanEnviron);
const NO_COLOR = ev.environ.exist.NO_COLOR;
const CLICOLOR_FORCE = ev.environ.exist.CLICOLOR_FORCE;
ev.stderr_mode = Io.Terminal.Mode.detect(
ev.io(),
ev.stderr_writer.file,
NO_COLOR,
CLICOLOR_FORCE,
) catch |err| switch (err) {
error.Canceled => unreachable, // blocked
};
}
fn unlockStderr(userdata: ?*anyopaque) void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
if (ev.stderr_writer.err == null) ev.stderr_writer.interface.flush() catch {};
if (ev.stderr_writer.err) |err| {
switch (err) {
error.Canceled => Thread.current().currentFiber().cancel_protection.recancel(),
else => {},
}
ev.stderr_writer.err = null;
}
ev.stderr_writer.interface.end = 0;
ev.stderr_writer.interface.buffer.len = 0;
ev.stderr_mutex.unlock();
}
fn processCurrentPath(userdata: ?*anyopaque, buffer: []u8) process.CurrentPathError!usize {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
const err: c.E = if (c.getcwd(buffer.ptr, buffer.len)) |_| .SUCCESS else @fromBackingInt(@intCast(c._errno().*));
switch (err) {
.SUCCESS => return std.mem.findScalar(u8, buffer, 0).?,
.NOENT => return error.CurrentDirUnlinked,
.RANGE => return error.NameTooLong,
.FAULT => |e| return errnoBug(e),
.INVAL => |e| return errnoBug(e),
else => return unexpectedErrno(err),
}
}
fn processSetCurrentDir(userdata: ?*anyopaque, dir: Dir) process.SetCurrentDirError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
if (dir.handle == c.AT.FDCWD) return;
while (true) switch (c.errno(c.fchdir(dir.handle))) {
.SUCCESS => return,
.INTR => {},
.ACCES => return error.AccessDenied,
.NOTDIR => return error.NotDir,
.IO => return error.FileSystem,
.BADF => |err| return errnoBug(err),
else => |err| return unexpectedErrno(err),
};
}
fn processSetCurrentPath(userdata: ?*anyopaque, dir_path: []const u8) process.SetCurrentPathError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
var path_buffer: [c.PATH_MAX]u8 = undefined;
const dir_path_posix = try pathToPosix(dir_path, &path_buffer);
while (true) switch (c.errno(c.chdir(dir_path_posix))) {
.SUCCESS => return,
.INTR => {},
.ACCES => return error.AccessDenied,
.IO => return error.FileSystem,
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOTDIR => return error.NotDir,
.ILSEQ => return error.BadPathName,
.FAULT => |err| return errnoBug(err),
else => |err| return unexpectedErrno(err),
};
}
fn processReplace(userdata: ?*anyopaque, options: process.ReplaceOptions) process.ReplaceError {
const ev: *Evented = @ptrCast(@alignCast(userdata));
if (!process.can_replace) return error.OperationUnsupported;
ev.scan_environ.once(ev, &scanEnviron); // for PATH
const PATH = ev.environ.string.PATH orelse default_PATH;
var arena_allocator = std.heap.ArenaAllocator.init(ev.allocator());
defer arena_allocator.deinit();
const arena = arena_allocator.allocator();
const argv_buf = try arena.allocSentinel(?[*:0]const u8, options.argv.len, null);
for (options.argv, 0..) |arg, i| argv_buf[i] = (try arena.dupeSentinel(u8, arg, 0)).ptr;
const env_block = env_block: {
const prog_fd: i32 = -1;
if (options.environ_map) |environ_map| break :env_block try environ_map.createPosixBlock(arena, .{
.zig_progress_fd = prog_fd,
});
break :env_block try ev.environ.process_environ.createPosixBlock(arena, .{
.zig_progress_fd = prog_fd,
});
};
return ev.execv(options.expand_arg0, argv_buf.ptr[0].?, argv_buf.ptr, env_block, PATH);
}
fn processReplacePath(
userdata: ?*anyopaque,
dir: Dir,
options: process.ReplaceOptions,
) process.ReplaceError {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
_ = dir;
_ = options;
@panic("TODO processReplacePath");
}
fn processSpawn(userdata: ?*anyopaque, options: process.SpawnOptions) process.SpawnError!process.Child {
const ev: *Evented = @ptrCast(@alignCast(userdata));
const spawned = try ev.spawn(options);
defer fileClose(ev, &.{spawned.err_pipe});
// Wait for the child to report any errors in or before `execvpe`.
var child_err: ForkBailError = undefined;
ev.readAll(spawned.err_pipe, @ptrCast(&child_err)) catch |read_err| {
switch (read_err) {
error.Canceled => unreachable, // blocked
error.EndOfStream => {
// Write end closed by CLOEXEC at the time of the `execvpe` call,
// indicating success.
},
else => {
// Problem reading the error from the error reporting pipe. We
// don't know if the child is alive or dead. Better to assume it is
// alive so the resource does not risk being leaked.
},
}
return .{
.id = spawned.pid,
.thread_handle = {},
.stdin = spawned.stdin,
.stdout = spawned.stdout,
.stderr = spawned.stderr,
.request_resource_usage_statistics = options.request_resource_usage_statistics,
};
};
return child_err;
}
fn processSpawnPath(
userdata: ?*anyopaque,
dir: Dir,
options: process.SpawnOptions,
) process.SpawnError!process.Child {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
_ = dir;
_ = options;
@panic("TODO processSpawnPath");
}
const prog_fileno = @max(c.STDIN_FILENO, c.STDOUT_FILENO, c.STDERR_FILENO) + 1;
const Spawned = struct {
pid: c.pid_t,
err_pipe: File,
stdin: ?File,
stdout: ?File,
stderr: ?File,
};
fn spawn(ev: *Evented, options: process.SpawnOptions) process.SpawnError!Spawned {
// The child process does need to access (one end of) these pipes. However,
// we must initially set CLOEXEC to avoid a race condition. If another thread
// is racing to spawn a different child process, we don't want it to inherit
// these FDs in any scenario; that would mean that, for instance, calls to
// `poll` from the parent would not report the child's stdout as closing when
// expected, since the other child may retain a reference to the write end of
// the pipe. So, we create the pipes with CLOEXEC initially. After fork, we
// need to do something in the new child to make sure we preserve the reference
// we want. We could use `fcntl` to remove CLOEXEC from the FD, but as it
// turns out, we `dup2` everything anyway, so there's no need!
const pipe_flags: c.O = .{ .CLOEXEC = true };
const stdin_pipe = if (options.stdin == .pipe) try pipe2(pipe_flags) else undefined;
errdefer if (options.stdin == .pipe) {
destroyPipe(stdin_pipe);
};
const stdout_pipe = if (options.stdout == .pipe) try pipe2(pipe_flags) else undefined;
errdefer if (options.stdout == .pipe) {
destroyPipe(stdout_pipe);
};
const stderr_pipe = if (options.stderr == .pipe) try pipe2(pipe_flags) else undefined;
errdefer if (options.stderr == .pipe) {
destroyPipe(stderr_pipe);
};
const any_ignore =
options.stdin == .ignore or options.stdout == .ignore or options.stderr == .ignore;
const dev_null_file = if (any_ignore) dev_null_file: {
ev.open_dev_null.once(ev, &openDevNullFile);
break :dev_null_file try ev.dev_null_file;
} else undefined;
const prog_pipe: [2]c.fd_t = if (options.progress_node.index != .none)
// We use CLOEXEC for the same reason as in `pipe_flags`.
try pipe2(.{ .NONBLOCK = true, .CLOEXEC = true })
else
.{ -1, -1 };
errdefer destroyPipe(prog_pipe);
var arena_allocator = std.heap.ArenaAllocator.init(ev.allocator());
defer arena_allocator.deinit();
const arena = arena_allocator.allocator();
// The POSIX standard does not allow malloc() between fork() and execve(),
// and this allocator may be a libc allocator.
// I have personally observed the child process deadlocking when it tries
// to call malloc() due to a heap allocation between fork() and execve(),
// in musl v1.1.24.
// Additionally, we want to reduce the number of possible ways things
// can fail between fork() and execve().
// Therefore, we do all the allocation for the execve() before the fork().
// This means we must do the null-termination of argv and env vars here.
const argv_buf = try arena.allocSentinel(?[*:0]const u8, options.argv.len, null);
for (options.argv, 0..) |arg, i| argv_buf[i] = (try arena.dupeSentinel(u8, arg, 0)).ptr;
const env_block = env_block: {
const prog_fd: i32 = if (prog_pipe[1] == -1) -1 else prog_fileno;
if (options.environ_map) |environ_map| break :env_block try environ_map.createPosixBlock(arena, .{
.zig_progress_fd = prog_fd,
});
break :env_block try ev.environ.process_environ.createPosixBlock(arena, .{
.zig_progress_fd = prog_fd,
});
};
// This pipe communicates to the parent errors in the child between `fork` and `execvpe`.
// It is closed by the child (via CLOEXEC) without writing if `execvpe` succeeds.
const err_pipe: [2]File = err_pipe: {
const err_pipe = try pipe2(.{ .CLOEXEC = true });
break :err_pipe .{
.{ .handle = err_pipe[0], .flags = .{ .nonblocking = false } },
.{ .handle = err_pipe[1], .flags = .{ .nonblocking = false } },
};
};
errdefer fileClose(ev, &err_pipe);
ev.scan_environ.once(ev, &scanEnviron); // for PATH
const PATH = ev.environ.string.PATH orelse default_PATH;
const pid_result: c.pid_t = fork: {
const rc = c.fork();
switch (c.errno(rc)) {
.SUCCESS => break :fork @intCast(rc),
.AGAIN => return error.SystemResources,
.NOMEM => return error.SystemResources,
.NOSYS => return error.OperationUnsupported,
else => |err| return unexpectedErrno(err),
}
};
if (pid_result == 0) {
defer comptime unreachable; // We are the child.
const err = ev.setUpChild(.{
.stdin_pipe = stdin_pipe[0],
.stdout_pipe = stdout_pipe[1],
.stderr_pipe = stderr_pipe[1],
.dev_null_fd = dev_null_file.handle,
.prog_pipe = prog_pipe[1],
.argv_buf = argv_buf,
.env_block = env_block,
.PATH = PATH,
.spawn = options,
});
ev.writeAll(err_pipe[1], @ptrCast(&err)) catch {};
c.exit(1);
}
const pid: c.pid_t = @intCast(pid_result); // We are the parent.
errdefer comptime unreachable; // The child is forked; we must not error from now on
fileClose(ev, err_pipe[1..2]); // make sure only the child holds the write end open
if (options.stdin == .pipe) closeFd(stdin_pipe[0]);
if (options.stdout == .pipe) closeFd(stdout_pipe[1]);
if (options.stderr == .pipe) closeFd(stderr_pipe[1]);
if (prog_pipe[1] != -1) closeFd(prog_pipe[1]);
options.progress_node.setIpcFile(ev, .{ .handle = prog_pipe[0], .flags = .{ .nonblocking = true } });
return .{
.pid = pid,
.err_pipe = err_pipe[0],
.stdin = switch (options.stdin) {
.pipe => .{ .handle = stdin_pipe[1], .flags = .{ .nonblocking = false } },
else => null,
},
.stdout = switch (options.stdout) {
.pipe => .{ .handle = stdout_pipe[0], .flags = .{ .nonblocking = false } },
else => null,
},
.stderr = switch (options.stderr) {
.pipe => .{ .handle = stderr_pipe[0], .flags = .{ .nonblocking = false } },
else => null,
},
};
}
fn openDevNullFile(context: ?*anyopaque) callconv(.c) void {
const ev: *Evented = @ptrCast(@alignCast(context));
ev.dev_null_file = dirOpenFile(ev, .cwd(), "/dev/null", .{ .mode = .read_write });
}
/// Errors that can occur between fork() and execv()
const ForkBailError = process.SetCurrentDirError || ChdirError ||
process.SpawnError || process.ReplaceError;
fn setUpChild(ev: *Evented, options: struct {
stdin_pipe: c.fd_t,
stdout_pipe: c.fd_t,
stderr_pipe: c.fd_t,
dev_null_fd: c.fd_t,
prog_pipe: c.fd_t,
argv_buf: [:null]?[*:0]const u8,
env_block: process.Environ.Block,
PATH: []const u8,
spawn: process.SpawnOptions,
}) ForkBailError {
try ev.setUpChildIo(
options.spawn.stdin,
options.stdin_pipe,
c.STDIN_FILENO,
options.dev_null_fd,
);
try ev.setUpChildIo(
options.spawn.stdout,
options.stdout_pipe,
c.STDOUT_FILENO,
options.dev_null_fd,
);
try ev.setUpChildIo(
options.spawn.stderr,
options.stderr_pipe,
c.STDERR_FILENO,
options.dev_null_fd,
);
switch (options.spawn.cwd) {
.inherit => {},
.dir => |cwd_dir| try processSetCurrentDir(ev, cwd_dir),
.path => |cwd_path| try processSetCurrentPath(ev, cwd_path),
}
// Must happen after fchdir above, the cwd file descriptor might be
// equal to prog_fileno and be clobbered by this dup2 call.
if (options.prog_pipe != -1) try ev.dup2(options.prog_pipe, prog_fileno);
if (options.spawn.gid) |gid| while (true) switch (c.errno(c.setregid(gid, gid))) {
.SUCCESS => break,
.INTR => {},
.AGAIN => return error.ResourceLimitReached,
.INVAL => return error.InvalidUserId,
.PERM => return error.PermissionDenied,
else => return error.Unexpected,
};
if (options.spawn.uid) |uid| while (true) switch (c.errno(c.setreuid(uid, uid))) {
.SUCCESS => break,
.INTR => {},
.AGAIN => return error.ResourceLimitReached,
.INVAL => return error.InvalidUserId,
.PERM => return error.PermissionDenied,
else => return error.Unexpected,
};
if (options.spawn.pgid) |pid| while (true) switch (c.errno(c.setpgid(0, pid))) {
.SUCCESS => break,
.INTR => {},
.ACCES => return error.ProcessAlreadyExec,
.INVAL => return error.InvalidProcessGroupId,
.PERM => return error.PermissionDenied,
else => return error.Unexpected,
};
if (options.spawn.start_suspended) while (true) switch (c.errno(c.kill(0, .STOP))) {
.SUCCESS => break,
.INTR => {},
.PERM => return error.PermissionDenied,
else => return error.Unexpected,
};
return ev.execv(
options.spawn.expand_arg0,
options.argv_buf.ptr[0].?,
options.argv_buf.ptr,
options.env_block,
options.PATH,
);
}
fn setUpChildIo(
ev: *Evented,
stdio: process.SpawnOptions.StdIo,
pipe_fd: c.fd_t,
std_fileno: i32,
dev_null_fd: c.fd_t,
) !void {
switch (stdio) {
.pipe => try ev.dup2(pipe_fd, std_fileno),
.close => closeFd(std_fileno),
.inherit => {},
.ignore => try ev.dup2(dev_null_fd, std_fileno),
.file => |file| try ev.dup2(file.handle, std_fileno),
}
}
const PipeError = error{
SystemFdQuotaExceeded,
ProcessFdQuotaExceeded,
} || Io.UnexpectedError;
fn pipe2(flags: c.O) PipeError![2]c.fd_t {
var fds: [2]c.fd_t = undefined;
while (true) switch (c.errno(c.pipe(&fds))) {
.SUCCESS => break,
.INTR => {},
.NFILE => return error.SystemFdQuotaExceeded,
.MFILE => return error.ProcessFdQuotaExceeded,
else => |err| return unexpectedErrno(err),
};
errdefer {
closeFd(fds[0]);
closeFd(fds[1]);
}
// https://github.com/ziglang/zig/issues/18882
if (@as(u32, @bitCast(flags)) == 0) return fds;
// CLOEXEC is special, it's a file descriptor flag and must be set using
// F.SETFD.
if (flags.CLOEXEC) for (fds) |fd| while (true) switch (c.errno(c.fcntl(fd, c.F.SETFD, @as(u32, c.FD_CLOEXEC)))) {
.SUCCESS => break,
.INTR => {},
else => |err| return unexpectedErrno(err),
};
const new_flags: u32 = f: {
var new_flags = flags;
new_flags.CLOEXEC = false;
break :f @bitCast(new_flags);
};
// Set every other flag affecting the file status using F.SETFL.
if (new_flags != 0) for (fds) |fd| while (true) switch (c.errno(c.fcntl(fd, c.F.SETFL, new_flags))) {
.SUCCESS => break,
.INTR => {},
.INVAL => |err| return errnoBug(err),
else => |err| return unexpectedErrno(err),
};
return fds;
}
fn destroyPipe(pipe: [2]c.fd_t) void {
if (pipe[0] != -1) closeFd(pipe[0]);
if (pipe[0] != pipe[1]) closeFd(pipe[1]);
}
const DupError = error{
ProcessFdQuotaExceeded,
SystemResources,
} || Io.UnexpectedError || Io.Cancelable;
fn dup2(ev: *Evented, old_fd: c.fd_t, new_fd: c.fd_t) DupError!void {
_ = ev;
while (true) switch (c.errno(c.dup2(old_fd, new_fd))) {
.SUCCESS => return,
.BUSY, .INTR => {},
.INVAL => |err| return errnoBug(err), // invalid parameters
.BADF => |err| return errnoBug(err), // use after free
.MFILE => return error.ProcessFdQuotaExceeded,
.NOMEM => return error.SystemResources,
else => |err| return unexpectedErrno(err),
};
}
fn execv(
ev: *Evented,
arg0_expand: process.ArgExpansion,
file: [*:0]const u8,
child_argv: [*:null]?[*:0]const u8,
env_block: process.Environ.PosixBlock,
PATH: []const u8,
) process.ReplaceError {
const file_slice = std.mem.sliceTo(file, 0);
if (std.mem.findScalar(u8, file_slice, '/') != null) return ev.execvPath(file, child_argv, env_block);
// Use of PATH_MAX here is valid as the path_buf will be passed
// directly to the operating system in posixExecvPath.
var path_buf: [c.PATH_MAX]u8 = undefined;
var it = std.mem.tokenizeScalar(u8, PATH, ':');
var seen_eacces = false;
var err: process.ReplaceError = error.FileNotFound;
// In case of expanding arg0 we must put it back if we return with an error.
const prev_arg0 = child_argv[0];
defer switch (arg0_expand) {
.expand => child_argv[0] = prev_arg0,
.no_expand => {},
};
while (it.next()) |search_path| {
const path_len = search_path.len + file_slice.len + 1;
if (path_buf.len < path_len + 1) return error.NameTooLong;
@memcpy(path_buf[0..search_path.len], search_path);
path_buf[search_path.len] = '/';
@memcpy(path_buf[search_path.len + 1 ..][0..file_slice.len], file_slice);
path_buf[path_len] = 0;
const full_path = path_buf[0..path_len :0].ptr;
switch (arg0_expand) {
.expand => child_argv[0] = full_path,
.no_expand => {},
}
err = ev.execvPath(full_path, child_argv, env_block);
switch (err) {
error.AccessDenied => seen_eacces = true,
error.FileNotFound, error.NotDir => {},
else => |e| return e,
}
}
if (seen_eacces) return error.AccessDenied;
return err;
}
/// This function ignores PATH environment variable.
fn execvPath(
ev: *Evented,
path: [*:0]const u8,
child_argv: [*:null]const ?[*:0]const u8,
env_block: process.Environ.PosixBlock,
) process.ReplaceError {
_ = ev;
switch (c.errno(c.execve(path, child_argv, env_block.slice.ptr))) {
.FAULT => |err| return errnoBug(err), // Bad pointer parameter.
.@"2BIG" => return error.SystemResources,
.MFILE => return error.ProcessFdQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NFILE => return error.SystemFdQuotaExceeded,
.NOMEM => return error.SystemResources,
.ACCES => return error.AccessDenied,
.PERM => return error.PermissionDenied,
.INVAL => return error.InvalidExe,
.NOEXEC => return error.InvalidExe,
.IO => return error.FileSystem,
.LOOP => return error.FileSystem,
.ISDIR => return error.IsDir,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.TXTBSY => return error.FileBusy,
.BADEXEC => return error.InvalidExe,
.BADARCH => return error.InvalidExe,
else => |err| return unexpectedErrno(err),
}
}
fn childWait(userdata: ?*anyopaque, child: *process.Child) process.Child.WaitError!process.Child.Term {
const ev: *Evented = @ptrCast(@alignCast(userdata));
defer ev.childCleanup(child);
const pid = child.id.?;
const source = c.dispatch.source_create(
.PROC,
@bitCast(@as(isize, pid)),
.{ .PROC = .{ .EXIT = true } },
ev.queue,
) orelse return error.Unexpected;
source.as_object().set_context(Thread.current().currentFiber());
source.set_event_handler(&Fiber.@"resume");
ev.yield(.{ .activate = source.as_object() });
source.as_object().release();
var status: c_int = undefined;
var ru: c.rusage = undefined;
const ru_ptr = if (child.request_resource_usage_statistics) &ru else null;
while (true) switch (c.errno(c.wait4(pid, &status, 0, ru_ptr))) {
.SUCCESS => {
if (ru_ptr) |p| child.resource_usage_statistics.rusage = p.*;
return statusToTerm(@bitCast(status));
},
.INTR => {},
.CHILD => |err| return errnoBug(err), // Double-free.
else => |err| return unexpectedErrno(err),
};
}
fn childKill(userdata: ?*anyopaque, child: *process.Child) void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
defer ev.childCleanup(child);
const pid = child.id.?;
while (true) switch (c.errno(c.kill(pid, .TERM))) {
.SUCCESS => break,
.INTR => {},
.PERM => return,
.INVAL => |err| errnoBug(err) catch return,
.SRCH => |err| errnoBug(err) catch return,
else => |err| unexpectedErrno(err) catch return,
};
var status: c_int = undefined;
while (true) switch (c.errno(c.wait4(pid, &status, 0, null))) {
.SUCCESS => return,
.INTR => {},
.CHILD => |err| errnoBug(err) catch return, // Double-free.
else => |err| unexpectedErrno(err) catch return,
};
}
fn childCleanup(ev: *Evented, child: *process.Child) void {
if (child.stdin) |stdin| {
fileClose(ev, &.{stdin});
child.stdin = null;
}
if (child.stdout) |stdout| {
fileClose(ev, &.{stdout});
child.stdout = null;
}
if (child.stderr) |stderr| {
fileClose(ev, &.{stderr});
child.stderr = null;
}
child.id = null;
}
fn progressParentFile(userdata: ?*anyopaque) std.Progress.ParentFileError!File {
const ev: *Evented = @ptrCast(@alignCast(userdata));
ev.scan_environ.once(ev, &scanEnviron);
return ev.environ.zig_progress_file;
}
fn scanEnviron(context: ?*anyopaque) callconv(.c) void {
const ev: *Evented = @ptrCast(@alignCast(context));
ev.environ.scan(ev.allocator());
}
fn now(userdata: ?*anyopaque, clock: Io.Clock) Io.Timestamp {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
const clock_id: c.clockid_t = clockToPosix(clock);
var timespec: c.timespec = undefined;
switch (c.errno(c.clock_gettime(clock_id, ×pec))) {
.SUCCESS => return timestampFromPosix(×pec),
else => return .zero,
}
}
fn clockResolution(userdata: ?*anyopaque, clock: Io.Clock) Io.Clock.ResolutionError!Io.Duration {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
const clock_id: c.clockid_t = clockToPosix(clock);
var timespec: c.timespec = undefined;
return switch (c.errno(c.clock_getres(clock_id, ×pec))) {
.SUCCESS => .fromNanoseconds(nanosecondsFromPosix(×pec)),
.INVAL => return error.ClockUnavailable,
else => |err| return unexpectedErrno(err),
};
}
const SleepWaiter = struct {
sleeper: Sleeper = undefined,
cancelable: Cancelable,
timer: c.dispatch.source_t,
started: bool = false,
fn start(context: ?*anyopaque) callconv(.c) void {
const waiter: *SleepWaiter = @ptrCast(@alignCast(context));
waiter.cancelable.enter(waiter.sleeper.fiber) catch |err| switch (err) {
error.CancelRequested => waiter.timer.cancel(),
};
waiter.timer.as_object().activate();
}
fn timedOut(context: ?*anyopaque) callconv(.c) void {
const waiter: *SleepWaiter = @ptrCast(@alignCast(context));
waiter.cancelable.leave(waiter.sleeper.fiber) catch |err| switch (err) {
error.CancelRequested => return,
};
waiter.timer.cancel();
}
fn canceled(context: ?*anyopaque) callconv(.c) void {
const cancelable: *Cancelable = @ptrCast(@alignCast(context));
const waiter: *SleepWaiter = @fieldParentPtr("cancelable", cancelable);
cancelable.requested(waiter.sleeper.fiber);
waiter.timer.cancel();
}
fn wake(context: ?*anyopaque) callconv(.c) void {
const waiter: *SleepWaiter = @ptrCast(@alignCast(context));
var sleeper = waiter.sleeper;
waiter.* = undefined;
Sleeper.wake(&sleeper);
}
};
fn sleep(userdata: ?*anyopaque, timeout: Io.Timeout) Io.Cancelable!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
const queue = c.dispatch.queue_create_with_target(
"org.ziglang.std.Io.Dispatch.sleep",
.SERIAL(),
ev.queue,
) orelse {
log.warn("failed to create serial queue for sleep", .{});
return ev.yield(.{ .after = ev.timeFromTimeout(timeout) });
};
defer queue.as_object().release();
const timer = c.dispatch.source_create(.TIMER, 0, .none, queue) orelse {
log.warn("failed to create timer for sleep", .{});
return ev.yield(.{ .after = ev.timeFromTimeout(timeout) });
};
var waiter: SleepWaiter = .{
.cancelable = .{ .queue = queue, .cancel = &SleepWaiter.canceled },
.timer = timer,
};
timer.as_object().set_context(&waiter);
timer.set_event_handler(&SleepWaiter.timedOut);
timer.set_cancel_handler(&SleepWaiter.wake);
timer.set_timer(ev.timeFromTimeout(timeout), c.dispatch.TIME_FOREVER, ev.leeway);
ev.yield(.{ .sleep_wait = &waiter });
timer.as_object().release();
try waiter.cancelable.acknowledge(waiter.sleeper.fiber);
}
fn timeFromTimeout(ev: *Evented, timeout: Io.Timeout) c.dispatch.time_t {
return timeout: switch (timeout) {
.none => .FOREVER,
.duration => |duration| .time(switch (duration.clock) {
.real => .WALL_NOW,
else => .NOW,
}, std.math.lossyCast(i64, duration.raw.toNanoseconds())),
.deadline => |deadline| switch (deadline.clock) {
.real => .walltime(&.{
.sec = @intCast(@divFloor(deadline.raw.toNanoseconds(), std.time.ns_per_s)),
.nsec = @intCast(@mod(deadline.raw.toNanoseconds(), std.time.ns_per_s)),
}, 0),
else => continue :timeout .{ .duration = deadline.durationFromNow(ev.io()) },
},
};
}
const Random = struct {
evented: *Evented,
thread: *Thread,
buffer: []u8,
fn seed(context: ?*anyopaque) callconv(.c) void {
const rand: *Random = @ptrCast(@alignCast(context));
const ev = rand.evented;
ev.csprng_mutex.lockUncancelable(ev);
defer ev.csprng_mutex.unlock();
var buffer: [Csprng.seed_len]u8 = undefined;
if (!ev.csprng.isInitialized()) {
@branchHint(.unlikely);
const cancel_protection = swapCancelProtection(ev, .blocked);
defer assert(swapCancelProtection(ev, cancel_protection) == .blocked);
randomSecure(ev, &buffer) catch |err| switch (err) {
error.Canceled => unreachable, // blocked
error.EntropyUnavailable => fallbackSeed(ev, &buffer),
};
ev.csprng.rng = .init(buffer);
}
ev.csprng.rng.fill(&buffer);
rand.thread.csprng.rng = .init(buffer);
rand.thread.csprng.rng.fill(rand.buffer);
rand.buffer.len = 0;
}
};
fn random(userdata: ?*anyopaque, buffer: []u8) void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
if (buffer.len == 0) return;
const thread: *Thread = .current();
var rand: Random = .{ .evented = ev, .thread = thread, .buffer = buffer };
thread.seed_csprng.once(&rand, &Random.seed);
if (rand.buffer.len > 0) thread.csprng.rng.fill(buffer);
}
fn randomSecure(userdata: ?*anyopaque, buffer: []u8) Io.RandomSecureError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
if (buffer.len > 0) c.arc4random_buf(buffer.ptr, buffer.len);
}
fn netListenIpUnavailable(
userdata: ?*anyopaque,
address: *const net.IpAddress,
options: net.IpAddress.ListenOptions,
) net.IpAddress.ListenError!net.Socket {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
_ = address;
_ = options;
return error.NetworkDown;
}
fn netAcceptUnavailable(
userdata: ?*anyopaque,
listen_handle: net.Socket.Handle,
options: net.Server.AcceptOptions,
) net.Server.AcceptError!net.Socket {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
_ = listen_handle;
_ = options;
return error.NetworkDown;
}
fn netBindIpUnavailable(
userdata: ?*anyopaque,
address: *const net.IpAddress,
options: net.IpAddress.BindOptions,
) net.IpAddress.BindError!net.Socket {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
_ = address;
_ = options;
return error.NetworkDown;
}
fn netConnectIpUnavailable(
userdata: ?*anyopaque,
address: *const net.IpAddress,
options: net.IpAddress.ConnectOptions,
) net.IpAddress.ConnectError!net.Socket {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
_ = address;
_ = options;
return error.NetworkDown;
}
fn netListenUnixUnavailable(
userdata: ?*anyopaque,
address: *const net.UnixAddress,
options: net.UnixAddress.ListenOptions,
) net.UnixAddress.ListenError!net.Socket.Handle {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
_ = address;
_ = options;
return error.AddressFamilyUnsupported;
}
fn netConnectUnixUnavailable(
userdata: ?*anyopaque,
address: *const net.UnixAddress,
) net.UnixAddress.ConnectError!net.Socket.Handle {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
_ = address;
return error.AddressFamilyUnsupported;
}
fn netSocketCreatePairUnavailable(
userdata: ?*anyopaque,
options: net.Socket.CreatePairOptions,
) net.Socket.CreatePairError![2]net.Socket {
_ = userdata;
_ = options;
return error.OperationUnsupported;
}
fn netWriteFileUnavailable(
userdata: ?*anyopaque,
socket_handle: net.Socket.Handle,
header: []const u8,
file_reader: *File.Reader,
limit: Io.Limit,
) net.Stream.Writer.WriteFileError!usize {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
_ = socket_handle;
_ = header;
_ = file_reader;
_ = limit;
return error.Unimplemented;
}
fn netClose(userdata: ?*anyopaque, sockets: []const net.Socket) void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
for (sockets) |socket| closeFd(socket.handle);
}
fn netShutdownUnavailable(
userdata: ?*anyopaque,
handle: net.Socket.Handle,
how: net.ShutdownHow,
) net.ShutdownError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
_ = handle;
_ = how;
unreachable; // How you gonna shutdown something that was impossible to open?
}
fn netInterfaceNameResolveUnavailable(
userdata: ?*anyopaque,
name: *const net.Interface.Name,
) net.Interface.Name.ResolveError!net.Interface {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
_ = name;
return error.InterfaceNotFound;
}
fn netInterfaceNameUnavailable(
userdata: ?*anyopaque,
interface: net.Interface,
) net.Interface.NameError!net.Interface.Name {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = ev;
_ = interface;
return error.Unexpected;
}
fn netLookupUnavailable(
userdata: ?*anyopaque,
host_name: net.HostName,
resolved: *Io.Queue(net.HostName.LookupResult),
options: net.HostName.LookupOptions,
) net.HostName.LookupError!void {
const ev: *Evented = @ptrCast(@alignCast(userdata));
_ = host_name;
_ = options;
resolved.close(ev.io());
return error.NetworkDown;
}
fn readAll(ev: *Evented, file: File, buffer: []u8) File.ReadStreamingError!void {
var index: usize = 0;
while (buffer.len - index != 0) {
const len = try ev.fileReadStreaming(file, &.{buffer[index..]});
if (len == 0) return error.EndOfStream;
index += len;
}
}
fn writeAll(ev: *Evented, file: File, buffer: []const u8) (File.Writer.Error || error{EndOfStream})!void {
var index: usize = 0;
while (buffer.len - index != 0) {
const len = try ev.fileWriteStreaming(file, &.{}, &.{buffer[index..]}, 1);
if (len == 0) return error.EndOfStream;
index += len;
}
}
/// This is either usize or u32. Since, either is fine, let's use the same
/// `addBuf` function for both writing to a file and sending network messages.
const iovlen_t = @FieldType(c.msghdr_const, "iovlen");
fn addConstBuf(v: []iovec_const, i: *iovlen_t, remaining: ?*usize, bytes: []const u8) void {
if (v.len - i.* == 0) return;
const len = @min(remaining.*, bytes.len);
if (len == 0) return;
v[i.*] = .{ .base = bytes.ptr, .len = len };
i.* += 1;
remaining.* -= len;
}
fn addBuf(
comptime is_const: bool,
vec: []if (is_const) iovec_const else iovec,
vec_len: *iovlen_t,
remaining: *Io.Limit,
bytes: if (is_const) []const u8 else []u8,
) void {
if (vec.len - vec_len.* == 0) return;
const len = remaining.minInt(bytes.len);
if (len == 0) return;
vec[vec_len.*] = .{ .base = bytes.ptr, .len = len };
vec_len.* += 1;
remaining.* = remaining.subtract(len).?;
}
test {
_ = Fiber.CancelProtection;
}