-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
posix.zig
7433 lines (6816 loc) · 289 KB
/
posix.zig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! POSIX API layer.
//!
//! This is more cross platform than using OS-specific APIs, however, it is
//! lower-level and less portable than other namespaces such as `std.fs` and
//! `std.process`.
//!
//! These APIs are generally lowered to libc function calls if and only if libc
//! is linked. Most operating systems other than Windows, Linux, and WASI
//! require always linking libc because they use it as the stable syscall ABI.
//!
//! Operating systems that are not POSIX-compliant are sometimes supported by
//! this API layer; sometimes not. Generally, an implementation will be
//! provided only if such implementation is straightforward on that operating
//! system. Otherwise, programmers are expected to use OS-specific logic to
//! deal with the exception.
const builtin = @import("builtin");
const root = @import("root");
const std = @import("std.zig");
const mem = std.mem;
const fs = std.fs;
const max_path_bytes = fs.max_path_bytes;
const maxInt = std.math.maxInt;
const cast = std.math.cast;
const assert = std.debug.assert;
const native_os = builtin.os.tag;
test {
_ = @import("posix/test.zig");
}
/// Whether to use libc for the POSIX API layer.
const use_libc = builtin.link_libc or switch (native_os) {
.windows, .wasi => true,
else => false,
};
const linux = std.os.linux;
const windows = std.os.windows;
const wasi = std.os.wasi;
/// A libc-compatible API layer.
pub const system = if (use_libc)
std.c
else switch (native_os) {
.linux => linux,
.plan9 => std.os.plan9,
else => struct {
pub const ucontext_t = void;
pub const pid_t = void;
pub const pollfd = void;
pub const fd_t = void;
pub const uid_t = void;
pub const gid_t = void;
},
};
pub const AF = system.AF;
pub const AF_SUN = system.AF_SUN;
pub const AI = system.AI;
pub const ARCH = system.ARCH;
pub const AT = system.AT;
pub const AT_SUN = system.AT_SUN;
pub const CLOCK = system.CLOCK;
pub const CPU_COUNT = system.CPU_COUNT;
pub const CTL = system.CTL;
pub const DT = system.DT;
pub const E = system.E;
pub const Elf_Symndx = system.Elf_Symndx;
pub const F = system.F;
pub const FD_CLOEXEC = system.FD_CLOEXEC;
pub const Flock = system.Flock;
pub const HOST_NAME_MAX = system.HOST_NAME_MAX;
pub const HW = system.HW;
pub const IFNAMESIZE = system.IFNAMESIZE;
pub const IOV_MAX = system.IOV_MAX;
pub const IPPROTO = system.IPPROTO;
pub const KERN = system.KERN;
pub const Kevent = system.Kevent;
pub const MADV = system.MADV;
pub const MAP = system.MAP;
pub const MAX_ADDR_LEN = system.MAX_ADDR_LEN;
pub const MFD = system.MFD;
pub const MMAP2_UNIT = system.MMAP2_UNIT;
pub const MSF = system.MSF;
pub const MSG = system.MSG;
pub const NAME_MAX = system.NAME_MAX;
pub const O = system.O;
pub const PATH_MAX = system.PATH_MAX;
pub const POLL = system.POLL;
pub const POSIX_FADV = system.POSIX_FADV;
pub const PR = system.PR;
pub const PROT = system.PROT;
pub const REG = system.REG;
pub const RLIM = system.RLIM;
pub const RR = system.RR;
pub const S = system.S;
pub const SA = system.SA;
pub const SC = system.SC;
pub const SEEK = system.SEEK;
pub const SHUT = system.SHUT;
pub const SIG = system.SIG;
pub const SIOCGIFINDEX = system.SIOCGIFINDEX;
pub const SO = system.SO;
pub const SOCK = system.SOCK;
pub const SOL = system.SOL;
pub const STDERR_FILENO = system.STDERR_FILENO;
pub const STDIN_FILENO = system.STDIN_FILENO;
pub const STDOUT_FILENO = system.STDOUT_FILENO;
pub const SYS = system.SYS;
pub const Sigaction = system.Sigaction;
pub const Stat = system.Stat;
pub const T = system.T;
pub const TCP = system.TCP;
pub const VDSO = system.VDSO;
pub const W = system.W;
pub const _SC = system._SC;
pub const addrinfo = system.addrinfo;
pub const blkcnt_t = system.blkcnt_t;
pub const blksize_t = system.blksize_t;
pub const clock_t = system.clock_t;
pub const clockid_t = system.clockid_t;
pub const cpu_set_t = system.cpu_set_t;
pub const dev_t = system.dev_t;
pub const dl_phdr_info = system.dl_phdr_info;
pub const empty_sigset = system.empty_sigset;
pub const fd_t = system.fd_t;
pub const file_obj = system.file_obj;
pub const filled_sigset = system.filled_sigset;
pub const gid_t = system.gid_t;
pub const ifreq = system.ifreq;
pub const ino_t = system.ino_t;
pub const mcontext_t = system.mcontext_t;
pub const mode_t = system.mode_t;
pub const msghdr = system.msghdr;
pub const msghdr_const = system.msghdr_const;
pub const nfds_t = system.nfds_t;
pub const nlink_t = system.nlink_t;
pub const off_t = system.off_t;
pub const pid_t = system.pid_t;
pub const pollfd = system.pollfd;
pub const port_event = system.port_event;
pub const port_notify = system.port_notify;
pub const port_t = system.port_t;
pub const rlim_t = system.rlim_t;
pub const rlimit = system.rlimit;
pub const rlimit_resource = system.rlimit_resource;
pub const rusage = system.rusage;
pub const sa_family_t = system.sa_family_t;
pub const siginfo_t = system.siginfo_t;
pub const sigset_t = system.sigset_t;
pub const sockaddr = system.sockaddr;
pub const socklen_t = system.socklen_t;
pub const stack_t = system.stack_t;
pub const time_t = system.time_t;
pub const timespec = system.timespec;
pub const timestamp_t = system.timestamp_t;
pub const timeval = system.timeval;
pub const timezone = system.timezone;
pub const ucontext_t = system.ucontext_t;
pub const uid_t = system.uid_t;
pub const user_desc = system.user_desc;
pub const utsname = system.utsname;
pub const termios = system.termios;
pub const CSIZE = system.CSIZE;
pub const NCCS = system.NCCS;
pub const cc_t = system.cc_t;
pub const V = system.V;
pub const speed_t = system.speed_t;
pub const tc_iflag_t = system.tc_iflag_t;
pub const tc_oflag_t = system.tc_oflag_t;
pub const tc_cflag_t = system.tc_cflag_t;
pub const tc_lflag_t = system.tc_lflag_t;
pub const F_OK = system.F_OK;
pub const R_OK = system.R_OK;
pub const W_OK = system.W_OK;
pub const X_OK = system.X_OK;
pub const iovec = extern struct {
base: [*]u8,
len: usize,
};
pub const iovec_const = extern struct {
base: [*]const u8,
len: usize,
};
pub const ACCMODE = enum(u2) {
RDONLY = 0,
WRONLY = 1,
RDWR = 2,
};
pub const TCSA = enum(c_uint) {
NOW,
DRAIN,
FLUSH,
_,
};
pub const winsize = extern struct {
row: u16,
col: u16,
xpixel: u16,
ypixel: u16,
};
pub const LOCK = struct {
pub const SH = 1;
pub const EX = 2;
pub const NB = 4;
pub const UN = 8;
};
pub const LOG = struct {
/// system is unusable
pub const EMERG = 0;
/// action must be taken immediately
pub const ALERT = 1;
/// critical conditions
pub const CRIT = 2;
/// error conditions
pub const ERR = 3;
/// warning conditions
pub const WARNING = 4;
/// normal but significant condition
pub const NOTICE = 5;
/// informational
pub const INFO = 6;
/// debug-level messages
pub const DEBUG = 7;
};
pub const socket_t = if (native_os == .windows) windows.ws2_32.SOCKET else fd_t;
/// Obtains errno from the return value of a system function call.
///
/// For some systems this will obtain the value directly from the syscall return value;
/// for others it will use a thread-local errno variable. Therefore, this
/// function only returns a well-defined value when it is called directly after
/// the system function call whose errno value is intended to be observed.
pub fn errno(rc: anytype) E {
if (use_libc) {
return if (rc == -1) @enumFromInt(std.c._errno().*) else .SUCCESS;
}
const signed: isize = @bitCast(rc);
const int = if (signed > -4096 and signed < 0) -signed else 0;
return @enumFromInt(int);
}
/// Closes the file descriptor.
///
/// Asserts the file descriptor is open.
///
/// This function is not capable of returning any indication of failure. An
/// application which wants to ensure writes have succeeded before closing must
/// call `fsync` before `close`.
///
/// The Zig standard library does not support POSIX thread cancellation.
pub fn close(fd: fd_t) void {
if (native_os == .windows) {
return windows.CloseHandle(fd);
}
if (native_os == .wasi and !builtin.link_libc) {
_ = std.os.wasi.fd_close(fd);
return;
}
switch (errno(system.close(fd))) {
.BADF => unreachable, // Always a race condition.
.INTR => return, // This is still a success. See https://github.com/ziglang/zig/issues/2425
else => return,
}
}
pub const FChmodError = error{
AccessDenied,
InputOutput,
SymLinkLoop,
FileNotFound,
SystemResources,
ReadOnlyFileSystem,
} || UnexpectedError;
/// Changes the mode of the file referred to by the file descriptor.
///
/// The process must have the correct privileges in order to do this
/// successfully, or must have the effective user ID matching the owner
/// of the file.
pub fn fchmod(fd: fd_t, mode: mode_t) FChmodError!void {
if (!fs.has_executable_bit) @compileError("fchmod unsupported by target OS");
while (true) {
const res = system.fchmod(fd, mode);
switch (errno(res)) {
.SUCCESS => return,
.INTR => continue,
.BADF => unreachable,
.FAULT => unreachable,
.INVAL => unreachable,
.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.AccessDenied,
.ROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
}
}
}
pub const FChmodAtError = FChmodError || error{
/// A component of `path` exceeded `NAME_MAX`, or the entire path exceeded
/// `PATH_MAX`.
NameTooLong,
/// `path` resolves to a symbolic link, and `AT.SYMLINK_NOFOLLOW` was set
/// in `flags`. This error only occurs on Linux, where changing the mode of
/// a symbolic link has no meaning and can cause undefined behaviour on
/// certain filesystems.
///
/// The procfs fallback was used but procfs was not mounted.
OperationNotSupported,
/// The procfs fallback was used but the process exceeded its open file
/// limit.
ProcessFdQuotaExceeded,
/// The procfs fallback was used but the system exceeded it open file limit.
SystemFdQuotaExceeded,
};
/// Changes the `mode` of `path` relative to the directory referred to by
/// `dirfd`. The process must have the correct privileges in order to do this
/// successfully, or must have the effective user ID matching the owner of the
/// file.
///
/// On Linux the `fchmodat2` syscall will be used if available, otherwise a
/// workaround using procfs will be employed. Changing the mode of a symbolic
/// link with `AT.SYMLINK_NOFOLLOW` set will also return
/// `OperationNotSupported`, as:
///
/// 1. Permissions on the link are ignored when resolving its target.
/// 2. This operation has been known to invoke undefined behaviour across
/// different filesystems[1].
///
/// [1]: https://sourceware.org/legacy-ml/libc-alpha/2020-02/msg00467.html.
pub inline fn fchmodat(dirfd: fd_t, path: []const u8, mode: mode_t, flags: u32) FChmodAtError!void {
if (!fs.has_executable_bit) @compileError("fchmodat unsupported by target OS");
// No special handling for linux is needed if we can use the libc fallback
// or `flags` is empty. Glibc only added the fallback in 2.32.
const skip_fchmodat_fallback = native_os != .linux or
std.c.versionCheck(.{ .major = 2, .minor = 32, .patch = 0 }) or
flags == 0;
// This function is marked inline so that when flags is comptime-known,
// skip_fchmodat_fallback will be comptime-known true.
if (skip_fchmodat_fallback)
return fchmodat1(dirfd, path, mode, flags);
return fchmodat2(dirfd, path, mode, flags);
}
fn fchmodat1(dirfd: fd_t, path: []const u8, mode: mode_t, flags: u32) FChmodAtError!void {
const path_c = try toPosixPath(path);
while (true) {
const res = system.fchmodat(dirfd, &path_c, mode, flags);
switch (errno(res)) {
.SUCCESS => return,
.INTR => continue,
.BADF => unreachable,
.FAULT => unreachable,
.INVAL => unreachable,
.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.OperationNotSupported,
.PERM => return error.AccessDenied,
.ROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
}
}
}
fn fchmodat2(dirfd: fd_t, path: []const u8, mode: mode_t, flags: u32) FChmodAtError!void {
const global = struct {
var has_fchmodat2: bool = true;
};
const path_c = try toPosixPath(path);
const use_fchmodat2 = (builtin.os.isAtLeast(.linux, .{ .major = 6, .minor = 6, .patch = 0 }) orelse false) and
@atomicLoad(bool, &global.has_fchmodat2, .monotonic);
while (use_fchmodat2) {
// Later on this should be changed to `system.fchmodat2`
// when the musl/glibc add a wrapper.
const res = linux.fchmodat2(dirfd, &path_c, mode, flags);
switch (E.init(res)) {
.SUCCESS => return,
.INTR => continue,
.BADF => unreachable,
.FAULT => unreachable,
.INVAL => unreachable,
.ACCES => return error.AccessDenied,
.IO => return error.InputOutput,
.LOOP => return error.SymLinkLoop,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOTDIR => return error.FileNotFound,
.OPNOTSUPP => return error.OperationNotSupported,
.PERM => return error.AccessDenied,
.ROFS => return error.ReadOnlyFileSystem,
.NOSYS => {
@atomicStore(bool, &global.has_fchmodat2, false, .monotonic);
break;
},
else => |err| return unexpectedErrno(err),
}
}
// Fallback to changing permissions using procfs:
//
// 1. Open `path` as a `PATH` descriptor.
// 2. Stat the fd and check if it isn't a symbolic link.
// 3. Generate the procfs reference to the fd via `/proc/self/fd/{fd}`.
// 4. Pass the procfs path to `chmod` with the `mode`.
var pathfd: fd_t = undefined;
while (true) {
const rc = system.openat(dirfd, &path_c, .{ .PATH = true, .NOFOLLOW = true, .CLOEXEC = true }, @as(mode_t, 0));
switch (errno(rc)) {
.SUCCESS => {
pathfd = @intCast(rc);
break;
},
.INTR => continue,
.FAULT => unreachable,
.INVAL => unreachable,
.ACCES => return error.AccessDenied,
.PERM => return error.AccessDenied,
.LOOP => return error.SymLinkLoop,
.MFILE => return error.ProcessFdQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NFILE => return error.SystemFdQuotaExceeded,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
else => |err| return unexpectedErrno(err),
}
}
defer close(pathfd);
const stat = fstatatZ(pathfd, "", AT.EMPTY_PATH) catch |err| switch (err) {
error.NameTooLong => unreachable,
error.FileNotFound => unreachable,
error.InvalidUtf8 => unreachable,
else => |e| return e,
};
if ((stat.mode & S.IFMT) == S.IFLNK)
return error.OperationNotSupported;
var procfs_buf: ["/proc/self/fd/-2147483648\x00".len]u8 = undefined;
const proc_path = std.fmt.bufPrintZ(procfs_buf[0..], "/proc/self/fd/{d}", .{pathfd}) catch unreachable;
while (true) {
const res = system.chmod(proc_path, mode);
switch (errno(res)) {
// Getting NOENT here means that procfs isn't mounted.
.NOENT => return error.OperationNotSupported,
.SUCCESS => return,
.INTR => continue,
.BADF => unreachable,
.FAULT => unreachable,
.INVAL => unreachable,
.ACCES => return error.AccessDenied,
.IO => return error.InputOutput,
.LOOP => return error.SymLinkLoop,
.NOMEM => return error.SystemResources,
.NOTDIR => return error.FileNotFound,
.PERM => return error.AccessDenied,
.ROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
}
}
}
pub const FChownError = error{
AccessDenied,
InputOutput,
SymLinkLoop,
FileNotFound,
SystemResources,
ReadOnlyFileSystem,
} || UnexpectedError;
/// Changes the owner and group of the file referred to by the file descriptor.
/// The process must have the correct privileges in order to do this
/// successfully. The group may be changed by the owner of the directory to
/// any group of which the owner is a member. If the owner or group is
/// specified as `null`, the ID is not changed.
pub fn fchown(fd: fd_t, owner: ?uid_t, group: ?gid_t) FChownError!void {
switch (native_os) {
.windows, .wasi => @compileError("Unsupported OS"),
else => {},
}
while (true) {
const res = system.fchown(fd, owner orelse ~@as(uid_t, 0), group orelse ~@as(gid_t, 0));
switch (errno(res)) {
.SUCCESS => return,
.INTR => continue,
.BADF => unreachable, // Can be reached if the fd refers to a directory opened without `Dir.OpenOptions{ .iterate = true }`
.FAULT => unreachable,
.INVAL => unreachable,
.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.AccessDenied,
.ROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
}
}
}
pub const RebootError = error{
PermissionDenied,
} || UnexpectedError;
pub const RebootCommand = switch (native_os) {
.linux => union(linux.LINUX_REBOOT.CMD) {
RESTART: void,
HALT: void,
CAD_ON: void,
CAD_OFF: void,
POWER_OFF: void,
RESTART2: [*:0]const u8,
SW_SUSPEND: void,
KEXEC: void,
},
else => @compileError("Unsupported OS"),
};
pub fn reboot(cmd: RebootCommand) RebootError!void {
switch (native_os) {
.linux => {
switch (linux.E.init(linux.reboot(
.MAGIC1,
.MAGIC2,
cmd,
switch (cmd) {
.RESTART2 => |s| s,
else => null,
},
))) {
.SUCCESS => {},
.PERM => return error.PermissionDenied,
else => |err| return std.posix.unexpectedErrno(err),
}
switch (cmd) {
.CAD_OFF => {},
.CAD_ON => {},
.SW_SUSPEND => {},
.HALT => unreachable,
.KEXEC => unreachable,
.POWER_OFF => unreachable,
.RESTART => unreachable,
.RESTART2 => unreachable,
}
},
else => @compileError("Unsupported OS"),
}
}
pub const GetRandomError = OpenError;
/// Obtain a series of random bytes. These bytes can be used to seed user-space
/// random number generators or for cryptographic purposes.
/// When linking against libc, this calls the
/// appropriate OS-specific library call. Otherwise it uses the zig standard
/// library implementation.
pub fn getrandom(buffer: []u8) GetRandomError!void {
if (native_os == .windows) {
return windows.RtlGenRandom(buffer);
}
if (builtin.link_libc and @TypeOf(system.arc4random_buf) != void) {
system.arc4random_buf(buffer.ptr, buffer.len);
return;
}
if (native_os == .wasi) switch (wasi.random_get(buffer.ptr, buffer.len)) {
.SUCCESS => return,
else => |err| return unexpectedErrno(err),
};
if (@TypeOf(system.getrandom) != void) {
var buf = buffer;
const use_c = native_os != .linux or
std.c.versionCheck(std.SemanticVersion{ .major = 2, .minor = 25, .patch = 0 });
while (buf.len != 0) {
const num_read: usize, const err = if (use_c) res: {
const rc = std.c.getrandom(buf.ptr, buf.len, 0);
break :res .{ @bitCast(rc), errno(rc) };
} else res: {
const rc = linux.getrandom(buf.ptr, buf.len, 0);
break :res .{ rc, linux.E.init(rc) };
};
switch (err) {
.SUCCESS => buf = buf[num_read..],
.INVAL => unreachable,
.FAULT => unreachable,
.INTR => continue,
else => return unexpectedErrno(err),
}
}
return;
}
if (native_os == .emscripten) {
const err = errno(std.c.getentropy(buffer.ptr, buffer.len));
switch (err) {
.SUCCESS => return,
else => return unexpectedErrno(err),
}
}
return getRandomBytesDevURandom(buffer);
}
fn getRandomBytesDevURandom(buf: []u8) !void {
const fd = try openZ("/dev/urandom", .{ .ACCMODE = .RDONLY, .CLOEXEC = true }, 0);
defer close(fd);
const st = try fstat(fd);
if (!S.ISCHR(st.mode)) {
return error.NoDevice;
}
const file: fs.File = .{ .handle = fd };
const stream = file.reader();
stream.readNoEof(buf) catch return error.Unexpected;
}
/// Causes abnormal process termination.
/// If linking against libc, this calls the abort() libc function. Otherwise
/// it raises SIGABRT followed by SIGKILL and finally lo
/// Invokes the current signal handler for SIGABRT, if any.
pub fn abort() noreturn {
@branchHint(.cold);
// MSVCRT abort() sometimes opens a popup window which is undesirable, so
// even when linking libc on Windows we use our own abort implementation.
// See https://github.com/ziglang/zig/issues/2071 for more details.
if (native_os == .windows) {
if (builtin.mode == .Debug) {
@breakpoint();
}
windows.kernel32.ExitProcess(3);
}
if (!builtin.link_libc and native_os == .linux) {
// The Linux man page says that the libc abort() function
// "first unblocks the SIGABRT signal", but this is a footgun
// for user-defined signal handlers that want to restore some state in
// some program sections and crash in others.
// So, the user-installed SIGABRT handler is run, if present.
raise(SIG.ABRT) catch {};
// Disable all signal handlers.
sigprocmask(SIG.BLOCK, &linux.all_mask, null);
// Only one thread may proceed to the rest of abort().
if (!builtin.single_threaded) {
const global = struct {
var abort_entered: bool = false;
};
while (@cmpxchgWeak(bool, &global.abort_entered, false, true, .seq_cst, .seq_cst)) |_| {}
}
// Install default handler so that the tkill below will terminate.
const sigact = Sigaction{
.handler = .{ .handler = SIG.DFL },
.mask = empty_sigset,
.flags = 0,
};
sigaction(SIG.ABRT, &sigact, null);
_ = linux.tkill(linux.gettid(), SIG.ABRT);
const sigabrtmask: linux.sigset_t = [_]u32{0} ** 31 ++ [_]u32{1 << (SIG.ABRT - 1)};
sigprocmask(SIG.UNBLOCK, &sigabrtmask, null);
// Beyond this point should be unreachable.
@as(*allowzero volatile u8, @ptrFromInt(0)).* = 0;
raise(SIG.KILL) catch {};
exit(127); // Pid 1 might not be signalled in some containers.
}
switch (native_os) {
.uefi, .wasi, .emscripten, .cuda, .amdhsa => @trap(),
else => system.abort(),
}
}
pub const RaiseError = UnexpectedError;
pub fn raise(sig: u8) RaiseError!void {
if (builtin.link_libc) {
switch (errno(system.raise(sig))) {
.SUCCESS => return,
else => |err| return unexpectedErrno(err),
}
}
if (native_os == .linux) {
var set: sigset_t = undefined;
// block application signals
sigprocmask(SIG.BLOCK, &linux.app_mask, &set);
const tid = linux.gettid();
const rc = linux.tkill(tid, sig);
// restore signal mask
sigprocmask(SIG.SETMASK, &set, null);
switch (errno(rc)) {
.SUCCESS => return,
else => |err| return unexpectedErrno(err),
}
}
@compileError("std.posix.raise unimplemented for this target");
}
pub const KillError = error{ ProcessNotFound, PermissionDenied } || UnexpectedError;
pub fn kill(pid: pid_t, sig: u8) KillError!void {
switch (errno(system.kill(pid, sig))) {
.SUCCESS => return,
.INVAL => unreachable, // invalid signal
.PERM => return error.PermissionDenied,
.SRCH => return error.ProcessNotFound,
else => |err| return unexpectedErrno(err),
}
}
/// Exits all threads of the program with the specified status code.
pub fn exit(status: u8) noreturn {
if (builtin.link_libc) {
std.c.exit(status);
}
if (native_os == .windows) {
windows.kernel32.ExitProcess(status);
}
if (native_os == .wasi) {
wasi.proc_exit(status);
}
if (native_os == .linux and !builtin.single_threaded) {
linux.exit_group(status);
}
if (native_os == .uefi) {
const uefi = std.os.uefi;
// exit() is only available if exitBootServices() has not been called yet.
// This call to exit should not fail, so we don't care about its return value.
if (uefi.system_table.boot_services) |bs| {
_ = bs.exit(uefi.handle, @enumFromInt(status), 0, null);
}
// If we can't exit, reboot the system instead.
uefi.system_table.runtime_services.resetSystem(.ResetCold, @enumFromInt(status), 0, null);
}
system.exit(status);
}
pub const ReadError = error{
InputOutput,
SystemResources,
IsDir,
OperationAborted,
BrokenPipe,
ConnectionResetByPeer,
ConnectionTimedOut,
NotOpenForReading,
SocketNotConnected,
/// This error occurs when no global event loop is configured,
/// and reading from the file descriptor would block.
WouldBlock,
/// reading a timerfd with CANCEL_ON_SET will lead to this error
/// when the clock goes through a discontinuous change
Canceled,
/// In WASI, this error occurs when the file descriptor does
/// not hold the required rights to read from it.
AccessDenied,
/// This error occurs in Linux if the process to be read from
/// no longer exists.
ProcessNotFound,
/// Unable to read file due to lock.
LockViolation,
} || UnexpectedError;
/// Returns the number of bytes that were read, which can be less than
/// buf.len. If 0 bytes were read, that means EOF.
/// If `fd` is opened in non blocking mode, the function will return error.WouldBlock
/// when EAGAIN is received.
///
/// Linux has a limit on how many bytes may be transferred in one `read` call, which is `0x7ffff000`
/// on both 64-bit and 32-bit systems. This is due to using a signed C int as the return value, as
/// well as stuffing the errno codes into the last `4096` values. This is noted on the `read` man page.
/// The limit on Darwin is `0x7fffffff`, trying to read more than that returns EINVAL.
/// The corresponding POSIX limit is `maxInt(isize)`.
pub fn read(fd: fd_t, buf: []u8) ReadError!usize {
if (buf.len == 0) return 0;
if (native_os == .windows) {
return windows.ReadFile(fd, buf, null);
}
if (native_os == .wasi and !builtin.link_libc) {
const iovs = [1]iovec{iovec{
.base = buf.ptr,
.len = buf.len,
}};
var nread: usize = undefined;
switch (wasi.fd_read(fd, &iovs, iovs.len, &nread)) {
.SUCCESS => return nread,
.INTR => unreachable,
.INVAL => unreachable,
.FAULT => unreachable,
.AGAIN => unreachable,
.BADF => return error.NotOpenForReading, // Can be a race condition.
.IO => return error.InputOutput,
.ISDIR => return error.IsDir,
.NOBUFS => return error.SystemResources,
.NOMEM => return error.SystemResources,
.NOTCONN => return error.SocketNotConnected,
.CONNRESET => return error.ConnectionResetByPeer,
.TIMEDOUT => return error.ConnectionTimedOut,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
// Prevents EINVAL.
const max_count = switch (native_os) {
.linux => 0x7ffff000,
.macos, .ios, .watchos, .tvos, .visionos => maxInt(i32),
else => maxInt(isize),
};
while (true) {
const rc = system.read(fd, buf.ptr, @min(buf.len, max_count));
switch (errno(rc)) {
.SUCCESS => return @intCast(rc),
.INTR => continue,
.INVAL => unreachable,
.FAULT => unreachable,
.NOENT => return error.ProcessNotFound,
.AGAIN => return error.WouldBlock,
.CANCELED => return error.Canceled,
.BADF => return error.NotOpenForReading, // Can be a race condition.
.IO => return error.InputOutput,
.ISDIR => return error.IsDir,
.NOBUFS => return error.SystemResources,
.NOMEM => return error.SystemResources,
.NOTCONN => return error.SocketNotConnected,
.CONNRESET => return error.ConnectionResetByPeer,
.TIMEDOUT => return error.ConnectionTimedOut,
else => |err| return unexpectedErrno(err),
}
}
}
/// Number of bytes read is returned. Upon reading end-of-file, zero is returned.
///
/// For POSIX systems, if `fd` is opened in non blocking mode, the function will
/// return error.WouldBlock when EAGAIN is received.
/// On Windows, if the application has a global event loop enabled, I/O Completion Ports are
/// used to perform the I/O. `error.WouldBlock` is not possible on Windows.
///
/// This operation is non-atomic on the following systems:
/// * Windows
/// On these systems, the read races with concurrent writes to the same file descriptor.
///
/// This function assumes that all vectors, including zero-length vectors, have
/// a pointer within the address space of the application.
pub fn readv(fd: fd_t, iov: []const iovec) ReadError!usize {
if (native_os == .windows) {
// TODO improve this to use ReadFileScatter
if (iov.len == 0) return 0;
const first = iov[0];
return read(fd, first.base[0..first.len]);
}
if (native_os == .wasi and !builtin.link_libc) {
var nread: usize = undefined;
switch (wasi.fd_read(fd, iov.ptr, iov.len, &nread)) {
.SUCCESS => return nread,
.INTR => unreachable,
.INVAL => unreachable,
.FAULT => unreachable,
.AGAIN => unreachable, // currently not support in WASI
.BADF => return error.NotOpenForReading, // can be a race condition
.IO => return error.InputOutput,
.ISDIR => return error.IsDir,
.NOBUFS => return error.SystemResources,
.NOMEM => return error.SystemResources,
.NOTCONN => return error.SocketNotConnected,
.CONNRESET => return error.ConnectionResetByPeer,
.TIMEDOUT => return error.ConnectionTimedOut,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
while (true) {
const rc = system.readv(fd, iov.ptr, @min(iov.len, IOV_MAX));
switch (errno(rc)) {
.SUCCESS => return @intCast(rc),
.INTR => continue,
.INVAL => unreachable,
.FAULT => unreachable,
.NOENT => return error.ProcessNotFound,
.AGAIN => return error.WouldBlock,
.BADF => return error.NotOpenForReading, // can be a race condition
.IO => return error.InputOutput,
.ISDIR => return error.IsDir,
.NOBUFS => return error.SystemResources,
.NOMEM => return error.SystemResources,
.NOTCONN => return error.SocketNotConnected,
.CONNRESET => return error.ConnectionResetByPeer,
.TIMEDOUT => return error.ConnectionTimedOut,
else => |err| return unexpectedErrno(err),
}
}
}
pub const PReadError = ReadError || error{Unseekable};
/// Number of bytes read is returned. Upon reading end-of-file, zero is returned.
///
/// Retries when interrupted by a signal.
///
/// For POSIX systems, if `fd` is opened in non blocking mode, the function will
/// return error.WouldBlock when EAGAIN is received.
/// On Windows, if the application has a global event loop enabled, I/O Completion Ports are
/// used to perform the I/O. `error.WouldBlock` is not possible on Windows.
///
/// Linux has a limit on how many bytes may be transferred in one `pread` call, which is `0x7ffff000`
/// on both 64-bit and 32-bit systems. This is due to using a signed C int as the return value, as
/// well as stuffing the errno codes into the last `4096` values. This is noted on the `read` man page.
/// The limit on Darwin is `0x7fffffff`, trying to read more than that returns EINVAL.
/// The corresponding POSIX limit is `maxInt(isize)`.
pub fn pread(fd: fd_t, buf: []u8, offset: u64) PReadError!usize {
if (buf.len == 0) return 0;
if (native_os == .windows) {
return windows.ReadFile(fd, buf, offset);
}
if (native_os == .wasi and !builtin.link_libc) {
const iovs = [1]iovec{iovec{
.base = buf.ptr,
.len = buf.len,
}};
var nread: usize = undefined;
switch (wasi.fd_pread(fd, &iovs, iovs.len, offset, &nread)) {
.SUCCESS => return nread,
.INTR => unreachable,
.INVAL => unreachable,
.FAULT => unreachable,
.AGAIN => unreachable,
.BADF => return error.NotOpenForReading, // Can be a race condition.
.IO => return error.InputOutput,
.ISDIR => return error.IsDir,
.NOBUFS => return error.SystemResources,
.NOMEM => return error.SystemResources,
.NOTCONN => return error.SocketNotConnected,
.CONNRESET => return error.ConnectionResetByPeer,
.TIMEDOUT => return error.ConnectionTimedOut,
.NXIO => return error.Unseekable,
.SPIPE => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
// Prevent EINVAL.
const max_count = switch (native_os) {
.linux => 0x7ffff000,
.macos, .ios, .watchos, .tvos, .visionos => maxInt(i32),
else => maxInt(isize),
};
const pread_sym = if (lfs64_abi) system.pread64 else system.pread;