authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2019-05-26 23:35:26-04:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2019-05-26 23:35:26-04:00
log0c6ab61b228211398841cf11912c7252362009b7
treed2a67490f5e580ba8a447d70edf427e6e0cc6ce0
parent2b42e910bf4696032158cc7ae268d3c69d699f70
signature Commit is signed but in an unrecognized format.

tests passing on linux


38 files changed, 348 insertions(+), 298 deletions(-)

build.zig+2-4
......@@ -166,10 +166,8 @@ fn dependOnLib(b: *Builder, lib_exe_obj: var, dep: LibraryDep) void {
166166}
167167
168168fn fileExists(filename: []const u8) !bool {
169 fs.File.exists(filename) catch |err| switch (err) {
170 error.PermissionDenied,
171 error.FileNotFound,
172 => return false,
169 fs.File.access(filename) catch |err| switch (err) {
170 error.FileNotFound => return false,
173171 else => return err,
174172 };
175173 return true;
doc/langref.html.in+2-2
......@@ -796,8 +796,8 @@ const assert = std.debug.assert;
796796threadlocal var x: i32 = 1234;
797797
798798test "thread local storage" {
799 const thread1 = try std.os.spawnThread({}, testTls);
800 const thread2 = try std.os.spawnThread({}, testTls);
799 const thread1 = try std.Thread.spawn({}, testTls);
800 const thread2 = try std.Thread.spawn({}, testTls);
801801 testTls({});
802802 thread1.wait();
803803 thread2.wait();
example/cat/main.zig+5-4
......@@ -1,12 +1,13 @@
11const std = @import("std");
22const io = std.io;
3const process = std.process;
4const File = std.fs.File;
35const mem = std.mem;
4const os = std.os;
56const warn = std.debug.warn;
67const allocator = std.debug.global_allocator;
78
89pub fn main() !void {
9 var args_it = os.args();
10 var args_it = process.args();
1011 const exe = try unwrapArg(args_it.next(allocator).?);
1112 var catted_anything = false;
1213 var stdout_file = try io.getStdOut();
......@@ -20,7 +21,7 @@ pub fn main() !void {
2021 } else if (arg[0] == '-') {
2122 return usage(exe);
2223 } else {
23 var file = os.File.openRead(arg) catch |err| {
24 var file = File.openRead(arg) catch |err| {
2425 warn("Unable to open file: {}\n", @errorName(err));
2526 return err;
2627 };
......@@ -41,7 +42,7 @@ fn usage(exe: []const u8) !void {
4142 return error.Invalid;
4243}
4344
44fn cat_file(stdout: *os.File, file: *os.File) !void {
45fn cat_file(stdout: *File, file: *File) !void {
4546 var buf: [1024 * 4]u8 = undefined;
4647
4748 while (true) {
example/guess_number/main.zig+1-2
......@@ -2,7 +2,6 @@ const builtin = @import("builtin");
22const std = @import("std");
33const io = std.io;
44const fmt = std.fmt;
5const os = std.os;
65
76pub fn main() !void {
87 var stdout_file = try io.getStdOut();
......@@ -11,7 +10,7 @@ pub fn main() !void {
1110 try stdout.print("Welcome to the Guess Number Game in Zig.\n");
1211
1312 var seed_bytes: [@sizeOf(u64)]u8 = undefined;
14 os.getRandomBytes(seed_bytes[0..]) catch |err| {
13 std.crypto.randomBytes(seed_bytes[0..]) catch |err| {
1514 std.debug.warn("unable to seed random number generator: {}", err);
1615 return err;
1716 };
example/hello_world/hello_libc.zig+1-1
......@@ -5,6 +5,6 @@ const c = @cImport({
55});
66
77export fn main(argc: c_int, argv: [*]?[*]u8) c_int {
8 c.fprintf(c.stderr, c"Hello, world!\n");
8 _ = c.fprintf(c.stderr, c"Hello, world!\n");
99 return 0;
1010}
src-self-hosted/compilation.zig+1
......@@ -301,6 +301,7 @@ pub const Compilation = struct {
301301 InvalidUtf8,
302302 BadPathName,
303303 DeviceBusy,
304 CurrentWorkingDirectoryUnlinked,
304305 };
305306
306307 pub const Event = union(enum) {
src-self-hosted/libc_installation.zig+3-3
......@@ -182,7 +182,7 @@ pub const LibCInstallation = struct {
182182 }
183183
184184 async fn findNativeIncludeDirLinux(self: *LibCInstallation, loop: *event.Loop) !void {
185 const cc_exe = std.process.getEnvPosix("CC") orelse "cc";
185 const cc_exe = std.os.getenv("CC") orelse "cc";
186186 const argv = []const []const u8{
187187 cc_exe,
188188 "-E",
......@@ -392,7 +392,7 @@ pub const LibCInstallation = struct {
392392
393393/// caller owns returned memory
394394async fn ccPrintFileName(loop: *event.Loop, o_file: []const u8, want_dirname: bool) ![]u8 {
395 const cc_exe = std.process.getEnvPosix("CC") orelse "cc";
395 const cc_exe = std.os.getenv("CC") orelse "cc";
396396 const arg1 = try std.fmt.allocPrint(loop.allocator, "-print-file-name={}", o_file);
397397 defer loop.allocator.free(arg1);
398398 const argv = []const []const u8{ cc_exe, arg1 };
......@@ -463,7 +463,7 @@ fn fileExists(path: []const u8) !bool {
463463 if (fs.File.access(path)) |_| {
464464 return true;
465465 } else |err| switch (err) {
466 error.FileNotFound, error.PermissionDenied => return false,
466 error.FileNotFound => return false,
467467 else => return error.FileSystem,
468468 }
469469}
src-self-hosted/main.zig+10-9
......@@ -702,6 +702,7 @@ const FmtError = error{
702702 ReadOnlyFileSystem,
703703 LinkQuotaExceeded,
704704 FileBusy,
705 CurrentWorkingDirectoryUnlinked,
705706} || fs.File.OpenError;
706707
707708async fn asyncFmtMain(
......@@ -851,7 +852,7 @@ fn cmdTargets(allocator: *Allocator, args: []const []const u8) !void {
851852}
852853
853854fn cmdVersion(allocator: *Allocator, args: []const []const u8) !void {
854 try stdout.print("{}\n", std.cstr.toSliceConst(c.ZIG_VERSION_STRING));
855 try stdout.print("{}\n", std.mem.toSliceConst(u8, c.ZIG_VERSION_STRING));
855856}
856857
857858const args_test_spec = []Flag{Flag.Bool("--help")};
......@@ -924,14 +925,14 @@ fn cmdInternalBuildInfo(allocator: *Allocator, args: []const []const u8) !void {
924925 \\ZIG_DIA_GUIDS_LIB {}
925926 \\
926927 ,
927 std.cstr.toSliceConst(c.ZIG_CMAKE_BINARY_DIR),
928 std.cstr.toSliceConst(c.ZIG_CXX_COMPILER),
929 std.cstr.toSliceConst(c.ZIG_LLVM_CONFIG_EXE),
930 std.cstr.toSliceConst(c.ZIG_LLD_INCLUDE_PATH),
931 std.cstr.toSliceConst(c.ZIG_LLD_LIBRARIES),
932 std.cstr.toSliceConst(c.ZIG_STD_FILES),
933 std.cstr.toSliceConst(c.ZIG_C_HEADER_FILES),
934 std.cstr.toSliceConst(c.ZIG_DIA_GUIDS_LIB),
928 std.mem.toSliceConst(u8, c.ZIG_CMAKE_BINARY_DIR),
929 std.mem.toSliceConst(u8, c.ZIG_CXX_COMPILER),
930 std.mem.toSliceConst(u8, c.ZIG_LLVM_CONFIG_EXE),
931 std.mem.toSliceConst(u8, c.ZIG_LLD_INCLUDE_PATH),
932 std.mem.toSliceConst(u8, c.ZIG_LLD_LIBRARIES),
933 std.mem.toSliceConst(u8, c.ZIG_STD_FILES),
934 std.mem.toSliceConst(u8, c.ZIG_C_HEADER_FILES),
935 std.mem.toSliceConst(u8, c.ZIG_DIA_GUIDS_LIB),
935936 );
936937}
937938
std/c.zig+9-4
......@@ -39,8 +39,8 @@ pub extern "c" fn open(path: [*]const u8, oflag: c_uint, ...) c_int;
3939pub extern "c" fn raise(sig: c_int) c_int;
4040pub extern "c" fn read(fd: fd_t, buf: [*]u8, nbyte: usize) isize;
4141pub extern "c" fn pread(fd: fd_t, buf: [*]u8, nbyte: usize, offset: u64) isize;
42pub extern "c" fn preadv(fd: c_int, iov: [*]const iovec, iovcnt: c_int, offset: usize) isize;
43pub extern "c" fn pwritev(fd: c_int, iov: [*]const iovec, iovcnt: c_int, offset: usize) isize;
42pub extern "c" fn preadv(fd: c_int, iov: [*]const iovec, iovcnt: c_uint, offset: usize) isize;
43pub extern "c" fn pwritev(fd: c_int, iov: [*]const iovec_const, iovcnt: c_uint, offset: usize) isize;
4444pub extern "c" fn stat(noalias path: [*]const u8, noalias buf: *Stat) c_int;
4545pub extern "c" fn write(fd: fd_t, buf: [*]const u8, nbyte: usize) isize;
4646pub extern "c" fn pwrite(fd: fd_t, buf: [*]const u8, nbyte: usize, offset: u64) isize;
......@@ -49,7 +49,7 @@ pub extern "c" fn munmap(addr: *align(page_size) c_void, len: usize) c_int;
4949pub extern "c" fn mprotect(addr: *align(page_size) c_void, len: usize, prot: c_uint) c_int;
5050pub extern "c" fn unlink(path: [*]const u8) c_int;
5151pub extern "c" fn getcwd(buf: [*]u8, size: usize) ?[*]u8;
52pub extern "c" fn waitpid(pid: c_int, stat_loc: *c_int, options: c_int) c_int;
52pub extern "c" fn waitpid(pid: c_int, stat_loc: *c_uint, options: c_uint) c_int;
5353pub extern "c" fn fork() c_int;
5454pub extern "c" fn access(path: [*]const u8, mode: c_uint) c_int;
5555pub extern "c" fn pipe(fds: *[2]fd_t) c_int;
......@@ -76,7 +76,12 @@ pub extern "c" fn sysctlbyname(name: [*]const u8, oldp: ?*c_void, oldlenp: ?*usi
7676pub extern "c" fn sysctlnametomib(name: [*]const u8, mibp: ?*c_int, sizep: ?*usize) c_int;
7777
7878pub extern "c" fn bind(socket: fd_t, address: ?*const sockaddr, address_len: socklen_t) c_int;
79pub extern "c" fn socket(domain: c_int, sock_type: c_int, protocol: c_int) c_int;
79pub extern "c" fn socket(domain: c_uint, sock_type: c_uint, protocol: c_uint) c_int;
80pub extern "c" fn listen(sockfd: fd_t, backlog: c_uint) c_int;
81pub extern "c" fn getsockname(sockfd: fd_t, noalias addr: *sockaddr, noalias addrlen: *socklen_t) c_int;
82pub extern "c" fn connect(sockfd: fd_t, sock_addr: *const sockaddr, addrlen: socklen_t) c_int;
83pub extern "c" fn accept4(sockfd: fd_t, addr: *sockaddr, addrlen: *socklen_t, flags: c_uint) c_int;
84pub extern "c" fn getsockopt(sockfd: fd_t, level: c_int, optname: c_int, optval: *c_void, optlen: *socklen_t) c_int;
8085pub extern "c" fn kill(pid: pid_t, sig: c_int) c_int;
8186pub extern "c" fn getdirentries(fd: fd_t, buf_ptr: [*]u8, nbytes: usize, basep: *i64) isize;
8287pub extern "c" fn openat(fd: c_int, path: [*]const u8, flags: c_int) c_int;
std/c/linux.zig+18-4
......@@ -1,13 +1,27 @@
11const std = @import("../std.zig");
22use std.c;
33
4pub extern "c" fn getrandom(buf_ptr: [*]u8, buf_len: usize, flags: c_uint) c_int;
5pub extern "c" fn sched_getaffinity(pid: c_int, size: usize, set: *cpu_set_t) c_int;
64extern "c" fn __errno_location() *c_int;
75pub const _errno = __errno_location;
86
7pub extern "c" fn getrandom(buf_ptr: [*]u8, buf_len: usize, flags: c_uint) c_int;
8pub extern "c" fn sched_getaffinity(pid: c_int, size: usize, set: *cpu_set_t) c_int;
9pub extern "c" fn eventfd(initval: c_uint, flags: c_uint) c_int;
10pub extern "c" fn epoll_ctl(epfd: fd_t, op: c_uint, fd: fd_t, event: *epoll_event) c_int;
11pub extern "c" fn epoll_create1(flags: c_uint) c_int;
12pub extern "c" fn epoll_wait(epfd: fd_t, events: [*]epoll_event, maxevents: c_uint, timeout: c_int) c_int;
13pub extern "c" fn epoll_pwait(
14 epfd: fd_t,
15 events: [*]epoll_event,
16 maxevents: c_int,
17 timeout: c_int,
18 sigmask: *const sigset_t,
19) c_int;
20pub extern "c" fn inotify_init1(flags: c_uint) c_int;
21pub extern "c" fn inotify_add_watch(fd: fd_t, pathname: [*]const u8, mask: u32) c_int;
22
923/// See std.elf for constants for this
10pub extern fn getauxval(__type: c_ulong) c_ulong;
24pub extern "c" fn getauxval(__type: c_ulong) c_ulong;
1125
1226pub const dl_iterate_phdr_callback = extern fn (info: *dl_phdr_info, size: usize, data: ?*c_void) c_int;
13pub extern fn dl_iterate_phdr(callback: dl_iterate_phdr_callback, data: ?*c_void) c_int;
27pub extern "c" fn dl_iterate_phdr(callback: dl_iterate_phdr_callback, data: ?*c_void) c_int;
std/child_process.zig+9-9
......@@ -54,10 +54,10 @@ pub const ChildProcess = struct {
5454 os.ChangeCurDirError || windows.CreateProcessError;
5555
5656 pub const Term = union(enum) {
57 Exited: i32,
58 Signal: i32,
59 Stopped: i32,
60 Unknown: i32,
57 Exited: u32,
58 Signal: u32,
59 Stopped: u32,
60 Unknown: u32,
6161 };
6262
6363 pub const StdIo = enum {
......@@ -155,7 +155,7 @@ pub const ChildProcess = struct {
155155 }
156156
157157 pub const ExecResult = struct {
158 term: os.ChildProcess.Term,
158 term: Term,
159159 stdout: []u8,
160160 stderr: []u8,
161161 };
......@@ -224,7 +224,7 @@ pub const ChildProcess = struct {
224224 if (windows.GetExitCodeProcess(self.handle, &exit_code) == 0) {
225225 break :x Term{ .Unknown = 0 };
226226 } else {
227 break :x Term{ .Exited = @bitCast(i32, exit_code) };
227 break :x Term{ .Exited = exit_code };
228228 }
229229 });
230230
......@@ -240,7 +240,7 @@ pub const ChildProcess = struct {
240240 self.handleWaitResult(status);
241241 }
242242
243 fn handleWaitResult(self: *ChildProcess, status: i32) void {
243 fn handleWaitResult(self: *ChildProcess, status: u32) void {
244244 self.term = self.cleanupAfterWait(status);
245245 }
246246
......@@ -259,7 +259,7 @@ pub const ChildProcess = struct {
259259 }
260260 }
261261
262 fn cleanupAfterWait(self: *ChildProcess, status: i32) !Term {
262 fn cleanupAfterWait(self: *ChildProcess, status: u32) !Term {
263263 defer {
264264 os.close(self.err_pipe[0]);
265265 os.close(self.err_pipe[1]);
......@@ -281,7 +281,7 @@ pub const ChildProcess = struct {
281281 return statusToTerm(status);
282282 }
283283
284 fn statusToTerm(status: i32) Term {
284 fn statusToTerm(status: u32) Term {
285285 return if (os.WIFEXITED(status))
286286 Term{ .Exited = os.WEXITSTATUS(status) }
287287 else if (os.WIFSIGNALED(status))
std/cstr.zig+1-1
......@@ -28,7 +28,7 @@ test "cstr fns" {
2828
2929fn testCStrFnsImpl() void {
3030 testing.expect(cmp(c"aoeu", c"aoez") == -1);
31 testing.expect(len(c"123456789") == 9);
31 testing.expect(mem.len(u8, c"123456789") == 9);
3232}
3333
3434/// Returns a mutable slice with 1 more byte of length which is a null byte.
std/dynamic_library.zig+13-25
......@@ -6,8 +6,7 @@ const os = std.os;
66const assert = std.debug.assert;
77const testing = std.testing;
88const elf = std.elf;
9const windows = os.windows;
10const win_util = @import("os/windows/util.zig");
9const windows = std.os.windows;
1110const maxInt = std.math.maxInt;
1211
1312pub const DynLib = switch (builtin.os) {
......@@ -102,17 +101,16 @@ pub fn linkmap_iterator(phdrs: []elf.Phdr) !LinkMap.Iterator {
102101pub const LinuxDynLib = struct {
103102 elf_lib: ElfLib,
104103 fd: i32,
105 map_addr: usize,
106 map_size: usize,
104 memory: []align(mem.page_size) u8,
107105
108106 /// Trusts the file
109107 pub fn open(allocator: *mem.Allocator, path: []const u8) !DynLib {
110108 const fd = try os.open(path, 0, os.O_RDONLY | os.O_CLOEXEC);
111 errdefer std.os.close(fd);
109 errdefer os.close(fd);
112110
113 const size = @intCast(usize, (try std.os.posixFStat(fd)).size);
111 const size = @intCast(usize, (try os.fstat(fd)).size);
114112
115 const addr = os.mmap(
113 const bytes = try os.mmap(
116114 null,
117115 size,
118116 os.PROT_READ | os.PROT_EXEC,
......@@ -120,21 +118,18 @@ pub const LinuxDynLib = struct {
120118 fd,
121119 0,
122120 );
123 errdefer os.munmap(addr, size);
124
125 const bytes = @intToPtr([*]align(mem.page_size) u8, addr)[0..size];
121 errdefer os.munmap(bytes);
126122
127123 return DynLib{
128124 .elf_lib = try ElfLib.init(bytes),
129125 .fd = fd,
130 .map_addr = addr,
131 .map_size = size,
126 .memory = bytes,
132127 };
133128 }
134129
135130 pub fn close(self: *DynLib) void {
136 os.munmap(self.map_addr, self.map_size);
137 std.os.close(self.fd);
131 os.munmap(self.memory);
132 os.close(self.fd);
138133 self.* = undefined;
139134 }
140135
......@@ -253,28 +248,21 @@ pub const WindowsDynLib = struct {
253248 dll: windows.HMODULE,
254249
255250 pub fn open(allocator: *mem.Allocator, path: []const u8) !WindowsDynLib {
256 const wpath = try win_util.sliceToPrefixedFileW(path);
251 const wpath = try windows.sliceToPrefixedFileW(path);
257252
258253 return WindowsDynLib{
259254 .allocator = allocator,
260 .dll = windows.LoadLibraryW(&wpath) orelse {
261 switch (windows.GetLastError()) {
262 windows.ERROR.FILE_NOT_FOUND => return error.FileNotFound,
263 windows.ERROR.PATH_NOT_FOUND => return error.FileNotFound,
264 windows.ERROR.MOD_NOT_FOUND => return error.FileNotFound,
265 else => |err| return windows.unexpectedError(err),
266 }
267 },
255 .dll = try windows.LoadLibraryW(&wpath),
268256 };
269257 }
270258
271259 pub fn close(self: *WindowsDynLib) void {
272 assert(windows.FreeLibrary(self.dll) != 0);
260 windows.FreeLibrary(self.dll);
273261 self.* = undefined;
274262 }
275263
276264 pub fn lookup(self: *WindowsDynLib, name: []const u8) ?usize {
277 return @ptrToInt(windows.GetProcAddress(self.dll, name.ptr));
265 return @ptrToInt(windows.kernel32.GetProcAddress(self.dll, name.ptr));
278266 }
279267};
280268
std/event/fs.zig+7-7
......@@ -36,7 +36,7 @@ pub const Request = struct {
3636 offset: usize,
3737 result: Error!void,
3838
39 pub const Error = os.PosixWriteError;
39 pub const Error = os.WriteError;
4040 };
4141
4242 pub const PReadV = struct {
......@@ -45,7 +45,7 @@ pub const Request = struct {
4545 offset: usize,
4646 result: Error!usize,
4747
48 pub const Error = os.PosixReadError;
48 pub const Error = os.ReadError;
4949 };
5050
5151 pub const Open = struct {
......@@ -172,7 +172,7 @@ pub async fn pwritevPosix(
172172 fd: fd_t,
173173 iovecs: []const os.iovec_const,
174174 offset: usize,
175) os.PosixWriteError!void {
175) os.WriteError!void {
176176 // workaround for https://github.com/ziglang/zig/issues/1194
177177 suspend {
178178 resume @handle();
......@@ -320,7 +320,7 @@ pub async fn preadvPosix(
320320 fd: fd_t,
321321 iovecs: []const os.iovec,
322322 offset: usize,
323) os.PosixReadError!usize {
323) os.ReadError!usize {
324324 // workaround for https://github.com/ziglang/zig/issues/1194
325325 suspend {
326326 resume @handle();
......@@ -786,7 +786,7 @@ pub fn Watch(comptime V: type) type {
786786
787787 switch (builtin.os) {
788788 builtin.Os.linux => {
789 const inotify_fd = try os.linuxINotifyInit1(os.linux.IN_NONBLOCK | os.linux.IN_CLOEXEC);
789 const inotify_fd = try os.inotify_init1(os.linux.IN_NONBLOCK | os.linux.IN_CLOEXEC);
790790 errdefer os.close(inotify_fd);
791791
792792 var result: *Self = undefined;
......@@ -977,7 +977,7 @@ pub fn Watch(comptime V: type) type {
977977 var basename_with_null_consumed = false;
978978 defer if (!basename_with_null_consumed) self.channel.loop.allocator.free(basename_with_null);
979979
980 const wd = try os.linuxINotifyAddWatchC(
980 const wd = try os.inotify_add_watchC(
981981 self.os_data.inotify_fd,
982982 dirname_with_null.ptr,
983983 os.linux.IN_CLOSE_WRITE | os.linux.IN_ONLYDIR | os.linux.IN_EXCL_UNLINK,
......@@ -1255,7 +1255,7 @@ pub fn Watch(comptime V: type) type {
12551255 ev = @ptrCast(*os.linux.inotify_event, ptr);
12561256 if (ev.mask & os.linux.IN_CLOSE_WRITE == os.linux.IN_CLOSE_WRITE) {
12571257 const basename_ptr = ptr + @sizeOf(os.linux.inotify_event);
1258 const basename_with_null = basename_ptr[0 .. std.cstr.len(basename_ptr) + 1];
1258 const basename_with_null = basename_ptr[0 .. std.mem.len(u8, basename_ptr) + 1];
12591259 const user_value = blk: {
12601260 const held = await (async watch.os_data.table_lock.acquire() catch unreachable);
12611261 defer held.release();
std/event/loop.zig+16-16
......@@ -99,7 +99,7 @@ pub const Loop = struct {
9999 /// have the correct pointer value.
100100 pub fn initMultiThreaded(self: *Loop, allocator: *mem.Allocator) !void {
101101 if (builtin.single_threaded) @compileError("initMultiThreaded unavailable when building in single-threaded mode");
102 const core_count = try os.cpuCount(allocator);
102 const core_count = try Thread.cpuCount();
103103 return self.initInternal(allocator, core_count);
104104 }
105105
......@@ -139,9 +139,9 @@ pub const Loop = struct {
139139 self.allocator.free(self.extra_threads);
140140 }
141141
142 const InitOsDataError = os.LinuxEpollCreateError || mem.Allocator.Error || os.LinuxEventFdError ||
143 os.SpawnThreadError || os.LinuxEpollCtlError || os.BsdKEventError ||
144 os.WindowsCreateIoCompletionPortError;
142 const InitOsDataError = os.EpollCreateError || mem.Allocator.Error || os.EventFdError ||
143 Thread.SpawnError || os.EpollCtlError || os.KEventError ||
144 windows.CreateIoCompletionPortError;
145145
146146 const wakeup_bytes = []u8{0x1} ** 8;
147147
......@@ -172,7 +172,7 @@ pub const Loop = struct {
172172 .handle = undefined,
173173 .overlapped = ResumeNode.overlapped_init,
174174 },
175 .eventfd = try os.linuxEventFd(1, os.EFD_CLOEXEC | os.EFD_NONBLOCK),
175 .eventfd = try os.eventfd(1, os.EFD_CLOEXEC | os.EFD_NONBLOCK),
176176 .epoll_op = os.EPOLL_CTL_ADD,
177177 },
178178 .next = undefined,
......@@ -180,17 +180,17 @@ pub const Loop = struct {
180180 self.available_eventfd_resume_nodes.push(eventfd_node);
181181 }
182182
183 self.os_data.epollfd = try os.linuxEpollCreate(os.EPOLL_CLOEXEC);
183 self.os_data.epollfd = try os.epoll_create1(os.EPOLL_CLOEXEC);
184184 errdefer os.close(self.os_data.epollfd);
185185
186 self.os_data.final_eventfd = try os.linuxEventFd(0, os.EFD_CLOEXEC | os.EFD_NONBLOCK);
186 self.os_data.final_eventfd = try os.eventfd(0, os.EFD_CLOEXEC | os.EFD_NONBLOCK);
187187 errdefer os.close(self.os_data.final_eventfd);
188188
189189 self.os_data.final_eventfd_event = os.epoll_event{
190190 .events = os.EPOLLIN,
191191 .data = os.epoll_data{ .ptr = @ptrToInt(&self.final_resume_node) },
192192 };
193 try os.linuxEpollCtl(
193 try os.epoll_ctl(
194194 self.os_data.epollfd,
195195 os.EPOLL_CTL_ADD,
196196 self.os_data.final_eventfd,
......@@ -211,7 +211,7 @@ pub const Loop = struct {
211211 var extra_thread_index: usize = 0;
212212 errdefer {
213213 // writing 8 bytes to an eventfd cannot fail
214 os.posixWrite(self.os_data.final_eventfd, wakeup_bytes) catch unreachable;
214 os.write(self.os_data.final_eventfd, wakeup_bytes) catch unreachable;
215215 while (extra_thread_index != 0) {
216216 extra_thread_index -= 1;
217217 self.extra_threads[extra_thread_index].wait();
......@@ -417,11 +417,11 @@ pub const Loop = struct {
417417 .events = flags,
418418 .data = os.linux.epoll_data{ .ptr = @ptrToInt(resume_node) },
419419 };
420 try os.linuxEpollCtl(self.os_data.epollfd, op, fd, &ev);
420 try os.epoll_ctl(self.os_data.epollfd, op, fd, &ev);
421421 }
422422
423423 pub fn linuxRemoveFd(self: *Loop, fd: i32) void {
424 os.linuxEpollCtl(self.os_data.epollfd, os.linux.EPOLL_CTL_DEL, fd, undefined) catch {};
424 os.epoll_ctl(self.os_data.epollfd, os.linux.EPOLL_CTL_DEL, fd, undefined) catch {};
425425 self.finishOneEvent();
426426 }
427427
......@@ -626,7 +626,7 @@ pub const Loop = struct {
626626 builtin.Os.linux => {
627627 self.posixFsRequest(&self.os_data.fs_end_request);
628628 // writing 8 bytes to an eventfd cannot fail
629 os.posixWrite(self.os_data.final_eventfd, wakeup_bytes) catch unreachable;
629 os.write(self.os_data.final_eventfd, wakeup_bytes) catch unreachable;
630630 return;
631631 },
632632 builtin.Os.macosx, builtin.Os.freebsd, builtin.Os.netbsd => {
......@@ -666,7 +666,7 @@ pub const Loop = struct {
666666 builtin.Os.linux => {
667667 // only process 1 event so we don't steal from other threads
668668 var events: [1]os.linux.epoll_event = undefined;
669 const count = os.linuxEpollWait(self.os_data.epollfd, events[0..], -1);
669 const count = os.epoll_wait(self.os_data.epollfd, events[0..], -1);
670670 for (events[0..count]) |ev| {
671671 const resume_node = @intToPtr(*ResumeNode, ev.data.ptr);
672672 const handle = resume_node.handle;
......@@ -783,10 +783,10 @@ pub const Loop = struct {
783783 switch (node.data.msg) {
784784 @TagType(fs.Request.Msg).End => return,
785785 @TagType(fs.Request.Msg).PWriteV => |*msg| {
786 msg.result = os.posix_pwritev(msg.fd, msg.iov.ptr, msg.iov.len, msg.offset);
786 msg.result = os.pwritev(msg.fd, msg.iov, msg.offset);
787787 },
788788 @TagType(fs.Request.Msg).PReadV => |*msg| {
789 msg.result = os.posix_preadv(msg.fd, msg.iov.ptr, msg.iov.len, msg.offset);
789 msg.result = os.preadv(msg.fd, msg.iov, msg.offset);
790790 },
791791 @TagType(fs.Request.Msg).Open => |*msg| {
792792 msg.result = os.openC(msg.path.ptr, msg.flags, msg.mode);
......@@ -800,7 +800,7 @@ pub const Loop = struct {
800800 break :blk;
801801 };
802802 defer os.close(fd);
803 msg.result = os.posixWrite(fd, msg.contents);
803 msg.result = os.write(fd, msg.contents);
804804 },
805805 }
806806 switch (node.data.finish) {
std/event/net.zig+15-12
......@@ -45,13 +45,13 @@ pub const Server = struct {
4545 ) !void {
4646 self.handleRequestFn = handleRequestFn;
4747
48 const sockfd = try os.posixSocket(os.AF_INET, os.SOCK_STREAM | os.SOCK_CLOEXEC | os.SOCK_NONBLOCK, os.PROTO_tcp);
48 const sockfd = try os.socket(os.AF_INET, os.SOCK_STREAM | os.SOCK_CLOEXEC | os.SOCK_NONBLOCK, os.PROTO_tcp);
4949 errdefer os.close(sockfd);
5050 self.sockfd = sockfd;
5151
52 try os.posixBind(sockfd, &address.os_addr);
53 try os.posixListen(sockfd, os.SOMAXCONN);
54 self.listen_address = std.net.Address.initPosix(try os.posixGetSockName(sockfd));
52 try os.bind(sockfd, &address.os_addr);
53 try os.listen(sockfd, os.SOMAXCONN);
54 self.listen_address = std.net.Address.initPosix(try os.getsockname(sockfd));
5555
5656 self.accept_coro = try async<self.loop.allocator> Server.handler(self);
5757 errdefer cancel self.accept_coro.?;
......@@ -64,7 +64,10 @@ pub const Server = struct {
6464 /// Stop listening
6565 pub fn close(self: *Server) void {
6666 self.loop.linuxRemoveFd(self.sockfd.?);
67 os.close(self.sockfd.?);
67 if (self.sockfd) |fd| {
68 os.close(fd);
69 self.sockfd = null;
70 }
6871 }
6972
7073 pub fn deinit(self: *Server) void {
......@@ -76,7 +79,7 @@ pub const Server = struct {
7679 while (true) {
7780 var accepted_addr: std.net.Address = undefined;
7881 // TODO just inline the following function here and don't expose it as posixAsyncAccept
79 if (os.posixAsyncAccept(self.sockfd.?, &accepted_addr.os_addr, os.SOCK_NONBLOCK | os.SOCK_CLOEXEC)) |accepted_fd| {
82 if (os.accept4_async(self.sockfd.?, &accepted_addr.os_addr, os.SOCK_NONBLOCK | os.SOCK_CLOEXEC)) |accepted_fd| {
8083 if (accepted_fd == -1) {
8184 // would block
8285 suspend; // we will get resumed by epoll_wait in the event loop
......@@ -105,7 +108,7 @@ pub const Server = struct {
105108};
106109
107110pub async fn connectUnixSocket(loop: *Loop, path: []const u8) !i32 {
108 const sockfd = try os.posixSocket(
111 const sockfd = try os.socket(
109112 os.AF_UNIX,
110113 os.SOCK_STREAM | os.SOCK_CLOEXEC | os.SOCK_NONBLOCK,
111114 0,
......@@ -120,9 +123,9 @@ pub async fn connectUnixSocket(loop: *Loop, path: []const u8) !i32 {
120123 if (path.len > @typeOf(sock_addr.path).len) return error.NameTooLong;
121124 mem.copy(u8, sock_addr.path[0..], path);
122125 const size = @intCast(u32, @sizeOf(os.sa_family_t) + path.len);
123 try os.posixConnectAsync(sockfd, &sock_addr, size);
126 try os.connect_async(sockfd, &sock_addr, size);
124127 try await try async loop.linuxWaitFd(sockfd, os.EPOLLIN | os.EPOLLOUT | os.EPOLLET);
125 try os.posixGetSockOptConnectError(sockfd);
128 try os.getsockoptError(sockfd);
126129
127130 return sockfd;
128131}
......@@ -249,12 +252,12 @@ pub async fn readv(loop: *Loop, fd: fd_t, data: []const []u8) !usize {
249252pub async fn connect(loop: *Loop, _address: *const std.net.Address) !File {
250253 var address = _address.*; // TODO https://github.com/ziglang/zig/issues/1592
251254
252 const sockfd = try os.posixSocket(os.AF_INET, os.SOCK_STREAM | os.SOCK_CLOEXEC | os.SOCK_NONBLOCK, os.PROTO_tcp);
255 const sockfd = try os.socket(os.AF_INET, os.SOCK_STREAM | os.SOCK_CLOEXEC | os.SOCK_NONBLOCK, os.PROTO_tcp);
253256 errdefer os.close(sockfd);
254257
255 try os.posixConnectAsync(sockfd, &address.os_addr, @sizeOf(os.sockaddr_in));
258 try os.connect_async(sockfd, &address.os_addr, @sizeOf(os.sockaddr_in));
256259 try await try async loop.linuxWaitFd(sockfd, os.EPOLLIN | os.EPOLLOUT | os.EPOLLET);
257 try os.posixGetSockOptConnectError(sockfd);
260 try os.getsockoptError(sockfd);
258261
259262 return File.openHandle(sockfd);
260263}
std/fs.zig+4-22
......@@ -38,24 +38,6 @@ pub const MAX_PATH_BYTES = switch (builtin.os) {
3838 else => @compileError("Unsupported OS"),
3939};
4040
41/// The result is a slice of `out_buffer`, from index `0`.
42pub fn getCwd(out_buffer: *[MAX_PATH_BYTES]u8) ![]u8 {
43 return os.getcwd(out_buffer);
44}
45
46/// Caller must free the returned memory.
47pub fn getCwdAlloc(allocator: *Allocator) ![]u8 {
48 var buf: [MAX_PATH_BYTES]u8 = undefined;
49 return mem.dupe(allocator, u8, try os.getcwd(&buf));
50}
51
52test "getCwdAlloc" {
53 // at least call it so it gets compiled
54 var buf: [1000]u8 = undefined;
55 const allocator = &std.heap.FixedBufferAllocator.init(&buf).allocator;
56 _ = getCwdAlloc(allocator) catch {};
57}
58
5941// here we replace the standard +/ with -_ so that it can be used in a file name
6042const b64_fs_encoder = base64.Base64Encoder.init("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", base64.standard_pad_char);
6143
......@@ -260,17 +242,17 @@ pub fn makePath(allocator: *Allocator, full_path: []const u8) !void {
260242
261243/// Returns `error.DirNotEmpty` if the directory is not empty.
262244/// To delete a directory recursively, see `deleteTree`.
263pub fn deleteDir(dir_path: []const u8) DeleteDirError!void {
245pub fn deleteDir(dir_path: []const u8) !void {
264246 return os.rmdir(dir_path);
265247}
266248
267249/// Same as `deleteDir` except the parameter is a null-terminated UTF8-encoded string.
268pub fn deleteDirC(dir_path: [*]const u8) DeleteDirError!void {
250pub fn deleteDirC(dir_path: [*]const u8) !void {
269251 return os.rmdirC(dir_path);
270252}
271253
272254/// Same as `deleteDir` except the parameter is a null-terminated UTF16LE-encoded string.
273pub fn deleteDirW(dir_path: [*]const u16) DeleteDirError!void {
255pub fn deleteDirW(dir_path: [*]const u16) !void {
274256 return os.rmdirW(dir_path);
275257}
276258
......@@ -362,7 +344,7 @@ pub fn deleteTree(allocator: *Allocator, full_path: []const u8) DeleteTreeError!
362344 };
363345 defer dir.close();
364346
365 var full_entry_buf = ArrayList(u8).init(allocator);
347 var full_entry_buf = std.ArrayList(u8).init(allocator);
366348 defer full_entry_buf.deinit();
367349
368350 while (try dir.next()) |entry| {
std/fs/file.zig+9-6
......@@ -137,24 +137,27 @@ pub const File = struct {
137137
138138 /// Test for the existence of `path`.
139139 /// `path` is UTF8-encoded.
140 pub fn exists(path: []const u8) !void {
140 /// In general it is recommended to avoid this function. For example,
141 /// instead of testing if a file exists and then opening it, just
142 /// open it and handle the error for file not found.
143 pub fn access(path: []const u8) !void {
141144 return os.access(path, os.F_OK);
142145 }
143146
144 /// Same as `exists` except the parameter is null-terminated.
145 pub fn existsC(path: [*]const u8) !void {
147 /// Same as `access` except the parameter is null-terminated.
148 pub fn accessC(path: [*]const u8) !void {
146149 return os.accessC(path, os.F_OK);
147150 }
148151
149 /// Same as `exists` except the parameter is null-terminated UTF16LE-encoded.
150 pub fn existsW(path: [*]const u16) !void {
152 /// Same as `access` except the parameter is null-terminated UTF16LE-encoded.
153 pub fn accessW(path: [*]const u16) !void {
151154 return os.accessW(path, os.F_OK);
152155 }
153156
154157 /// Upon success, the stream is in an uninitialized state. To continue using it,
155158 /// you must use the open() function.
156159 pub fn close(self: File) void {
157 os.close(self.handle);
160 return os.close(self.handle);
158161 }
159162
160163 /// Test whether the file refers to a terminal.
std/fs/path.zig+8-7
......@@ -9,6 +9,7 @@ const Allocator = mem.Allocator;
99const math = std.math;
1010const windows = std.os.windows;
1111const fs = std.fs;
12const process = std.process;
1213
1314pub const sep_windows = '\\';
1415pub const sep_posix = '/';
......@@ -390,7 +391,7 @@ pub fn resolve(allocator: *Allocator, paths: []const []const u8) ![]u8 {
390391pub fn resolveWindows(allocator: *Allocator, paths: []const []const u8) ![]u8 {
391392 if (paths.len == 0) {
392393 assert(windows.is_the_target); // resolveWindows called on non windows can't use getCwd
393 return fs.getCwdAlloc(allocator);
394 return process.getCwdAlloc(allocator);
394395 }
395396
396397 // determine which disk designator we will result with, if any
......@@ -485,7 +486,7 @@ pub fn resolveWindows(allocator: *Allocator, paths: []const []const u8) ![]u8 {
485486 },
486487 WindowsPath.Kind.None => {
487488 assert(windows.is_the_target); // resolveWindows called on non windows can't use getCwd
488 const cwd = try fs.getCwdAlloc(allocator);
489 const cwd = try process.getCwdAlloc(allocator);
489490 defer allocator.free(cwd);
490491 const parsed_cwd = windowsParsePath(cwd);
491492 result = try allocator.alloc(u8, max_size + parsed_cwd.disk_designator.len + 1);
......@@ -501,7 +502,7 @@ pub fn resolveWindows(allocator: *Allocator, paths: []const []const u8) ![]u8 {
501502 } else {
502503 assert(windows.is_the_target); // resolveWindows called on non windows can't use getCwd
503504 // TODO call get cwd for the result_disk_designator instead of the global one
504 const cwd = try fs.getCwdAlloc(allocator);
505 const cwd = try process.getCwdAlloc(allocator);
505506 defer allocator.free(cwd);
506507
507508 result = try allocator.alloc(u8, max_size + cwd.len + 1);
......@@ -571,7 +572,7 @@ pub fn resolveWindows(allocator: *Allocator, paths: []const []const u8) ![]u8 {
571572pub fn resolvePosix(allocator: *Allocator, paths: []const []const u8) ![]u8 {
572573 if (paths.len == 0) {
573574 assert(!windows.is_the_target); // resolvePosix called on windows can't use getCwd
574 return fs.getCwdAlloc(allocator);
575 return process.getCwdAlloc(allocator);
575576 }
576577
577578 var first_index: usize = 0;
......@@ -593,7 +594,7 @@ pub fn resolvePosix(allocator: *Allocator, paths: []const []const u8) ![]u8 {
593594 result = try allocator.alloc(u8, max_size);
594595 } else {
595596 assert(!windows.is_the_target); // resolvePosix called on windows can't use getCwd
596 const cwd = try fs.getCwdAlloc(allocator);
597 const cwd = try process.getCwdAlloc(allocator);
597598 defer allocator.free(cwd);
598599 result = try allocator.alloc(u8, max_size + cwd.len + 1);
599600 mem.copy(u8, result, cwd);
......@@ -632,7 +633,7 @@ pub fn resolvePosix(allocator: *Allocator, paths: []const []const u8) ![]u8 {
632633}
633634
634635test "resolve" {
635 const cwd = try fs.getCwdAlloc(debug.global_allocator);
636 const cwd = try process.getCwdAlloc(debug.global_allocator);
636637 if (windows.is_the_target) {
637638 if (windowsParsePath(cwd).kind == WindowsPath.Kind.Drive) {
638639 cwd[0] = asciiUpper(cwd[0]);
......@@ -646,7 +647,7 @@ test "resolve" {
646647
647648test "resolveWindows" {
648649 if (windows.is_the_target) {
649 const cwd = try fs.getCwdAlloc(debug.global_allocator);
650 const cwd = try process.getCwdAlloc(debug.global_allocator);
650651 const parsed_cwd = windowsParsePath(cwd);
651652 {
652653 const result = testResolveWindows([][]const u8{ "/usr/local", "lib\\zig\\std\\array_list.zig" });
std/heap.zig+1-1
......@@ -112,7 +112,7 @@ pub const DirectAllocator = struct {
112112 -1,
113113 0,
114114 ) catch return error.OutOfMemory;
115 if (alloc_size == n) return slice;
115 if (alloc_size == n) return slice[0..n];
116116
117117 const aligned_addr = mem.alignForward(@ptrToInt(slice.ptr), alignment);
118118
std/io/test.zig+4-4
......@@ -7,7 +7,7 @@ const DefaultPrng = std.rand.DefaultPrng;
77const expect = std.testing.expect;
88const expectError = std.testing.expectError;
99const mem = std.mem;
10const os = std.os;
10const fs = std.fs;
1111const File = std.fs.File;
1212
1313test "write a file, read it, then delete it" {
......@@ -58,7 +58,7 @@ test "write a file, read it, then delete it" {
5858 expect(mem.eql(u8, contents["begin".len .. contents.len - "end".len], data));
5959 expect(mem.eql(u8, contents[contents.len - "end".len ..], "end"));
6060 }
61 try os.deleteFile(tmp_file_name);
61 try fs.deleteFile(tmp_file_name);
6262}
6363
6464test "BufferOutStream" {
......@@ -316,7 +316,7 @@ test "BitStreams with File Stream" {
316316
317317 expectError(error.EndOfStream, bit_stream.readBitsNoEof(u1, 1));
318318 }
319 try os.deleteFile(tmp_file_name);
319 try fs.deleteFile(tmp_file_name);
320320}
321321
322322fn testIntSerializerDeserializer(comptime endian: builtin.Endian, comptime packing: io.Packing) !void {
......@@ -596,7 +596,7 @@ test "c out stream" {
596596
597597 const filename = c"tmp_io_test_file.txt";
598598 const out_file = std.c.fopen(filename, c"w") orelse return error.UnableToOpenTestFile;
599 defer std.os.deleteFileC(filename) catch {};
599 defer fs.deleteFileC(filename) catch {};
600600
601601 const out_stream = &io.COutStream.init(out_file).stream;
602602 try out_stream.print("hi: {}\n", i32(123));
std/os.zig+40-31
......@@ -284,7 +284,7 @@ pub fn read(fd: fd_t, buf: []u8) ReadError!usize {
284284/// Number of bytes read is returned. Upon reading end-of-file, zero is returned.
285285/// This function is for blocking file descriptors only. For non-blocking, see
286286/// `preadvAsync`.
287pub fn preadv(fd: fd_t, iov: [*]const iovec, count: usize, offset: u64) ReadError!usize {
287pub fn preadv(fd: fd_t, iov: []const iovec, offset: u64) ReadError!usize {
288288 if (darwin.is_the_target) {
289289 // Darwin does not have preadv but it does have pread.
290290 var off: usize = 0;
......@@ -301,7 +301,7 @@ pub fn preadv(fd: fd_t, iov: [*]const iovec, count: usize, offset: u64) ReadErro
301301 if (inner_off == v.iov_len) {
302302 iov_i += 1;
303303 inner_off = 0;
304 if (iov_i == count) {
304 if (iov_i == iov.len) {
305305 return off;
306306 }
307307 }
......@@ -323,9 +323,10 @@ pub fn preadv(fd: fd_t, iov: [*]const iovec, count: usize, offset: u64) ReadErro
323323 }
324324 }
325325 while (true) {
326 const rc = system.preadv(fd, iov, count, offset);
326 // TODO handle the case when iov_len is too large and get rid of this @intCast
327 const rc = system.preadv(fd, iov.ptr, @intCast(u32, iov.len), offset);
327328 switch (errno(rc)) {
328 0 => return rc,
329 0 => return @bitCast(usize, rc),
329330 EINTR => continue,
330331 EINVAL => unreachable,
331332 EFAULT => unreachable,
......@@ -407,7 +408,7 @@ pub fn write(fd: fd_t, bytes: []const u8) WriteError!void {
407408/// Write multiple buffers to a file descriptor. Keeps trying if it gets interrupted.
408409/// This function is for blocking file descriptors only. For non-blocking, see
409410/// `pwritevAsync`.
410pub fn pwritev(fd: fd_t, iov: [*]const iovec_const, count: usize, offset: u64) WriteError!void {
411pub fn pwritev(fd: fd_t, iov: []const iovec_const, offset: u64) WriteError!void {
411412 if (darwin.is_the_target) {
412413 // Darwin does not have pwritev but it does have pwrite.
413414 var off: usize = 0;
......@@ -424,7 +425,7 @@ pub fn pwritev(fd: fd_t, iov: [*]const iovec_const, count: usize, offset: u64) W
424425 if (inner_off == v.iov_len) {
425426 iov_i += 1;
426427 inner_off = 0;
427 if (iov_i == count) {
428 if (iov_i == iov.len) {
428429 return;
429430 }
430431 }
......@@ -449,7 +450,8 @@ pub fn pwritev(fd: fd_t, iov: [*]const iovec_const, count: usize, offset: u64) W
449450 }
450451
451452 while (true) {
452 const rc = system.pwritev(fd, iov, count, offset);
453 // TODO handle the case when iov_len is too large and get rid of this @intCast
454 const rc = system.pwritev(fd, iov.ptr, @intCast(u32, iov.len), offset);
453455 switch (errno(rc)) {
454456 0 => return,
455457 EINTR => continue,
......@@ -724,7 +726,7 @@ pub fn getcwd(out_buffer: []u8) GetCwdError![]u8 {
724726 EINVAL => unreachable,
725727 ENOENT => return error.CurrentWorkingDirectoryUnlinked,
726728 ERANGE => return error.NameTooLong,
727 else => return unexpectedErrno(err),
729 else => return unexpectedErrno(@intCast(usize, err)),
728730 }
729731}
730732
......@@ -1121,7 +1123,7 @@ pub fn readlinkC(file_path: [*]const u8, out_buffer: []u8) ReadLinkError![]u8 {
11211123 }
11221124 const rc = system.readlink(file_path, out_buffer.ptr, out_buffer.len);
11231125 switch (errno(rc)) {
1124 0 => return out_buffer[0..rc],
1126 0 => return out_buffer[0..@bitCast(usize, rc)],
11251127 EACCES => return error.AccessDenied,
11261128 EFAULT => unreachable,
11271129 EINVAL => unreachable,
......@@ -1307,7 +1309,7 @@ pub const BindError = error{
13071309
13081310/// addr is `*const T` where T is one of the sockaddr
13091311pub fn bind(fd: i32, addr: *const sockaddr) BindError!void {
1310 const rc = system.bind(fd, system, @sizeOf(sockaddr));
1312 const rc = system.bind(fd, addr, @sizeOf(sockaddr));
13111313 switch (errno(rc)) {
13121314 0 => return,
13131315 EACCES => return error.AccessDenied,
......@@ -1521,7 +1523,7 @@ pub fn epoll_wait(epfd: i32, events: []epoll_event, timeout: i32) usize {
15211523 // TODO get rid of the @intCast
15221524 const rc = system.epoll_wait(epfd, events.ptr, @intCast(u32, events.len), timeout);
15231525 switch (errno(rc)) {
1524 0 => return rc,
1526 0 => return @intCast(usize, rc),
15251527 EINTR => continue,
15261528 EBADF => unreachable,
15271529 EFAULT => unreachable,
......@@ -1613,12 +1615,10 @@ pub const ConnectError = error{
16131615/// Initiate a connection on a socket.
16141616/// This is for blocking file descriptors only.
16151617/// For non-blocking, see `connect_async`.
1616pub fn connect(sockfd: i32, sockaddr: *const sockaddr) ConnectError!void {
1618pub fn connect(sockfd: i32, sock_addr: *sockaddr, len: socklen_t) ConnectError!void {
16171619 while (true) {
1618 switch (errno(system.connect(sockfd, sockaddr, @sizeOf(sockaddr)))) {
1620 switch (errno(system.connect(sockfd, sock_addr, @sizeOf(sockaddr)))) {
16191621 0 => return,
1620 else => |err| return unexpectedErrno(err),
1621
16221622 EACCES => return error.PermissionDenied,
16231623 EPERM => return error.PermissionDenied,
16241624 EADDRINUSE => return error.AddressInUse,
......@@ -1636,19 +1636,18 @@ pub fn connect(sockfd: i32, sockaddr: *const sockaddr) ConnectError!void {
16361636 ENOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.
16371637 EPROTOTYPE => unreachable, // The socket type does not support the requested communications protocol.
16381638 ETIMEDOUT => return error.ConnectionTimedOut,
1639 else => |err| return unexpectedErrno(err),
16391640 }
16401641 }
16411642}
16421643
16431644/// Same as `connect` except it is for blocking socket file descriptors.
16441645/// It expects to receive EINPROGRESS`.
1645pub fn connect_async(sockfd: i32, sockaddr: *const c_void, len: u32) ConnectError!void {
1646pub fn connect_async(sockfd: i32, sock_addr: *sockaddr, len: socklen_t) ConnectError!void {
16461647 while (true) {
1647 switch (errno(system.connect(sockfd, sockaddr, len))) {
1648 0, EINPROGRESS => return,
1648 switch (errno(system.connect(sockfd, sock_addr, @sizeOf(sockaddr)))) {
16491649 EINTR => continue,
1650 else => |err| return unexpectedErrno(err),
1651
1650 0, EINPROGRESS => return,
16521651 EACCES => return error.PermissionDenied,
16531652 EPERM => return error.PermissionDenied,
16541653 EADDRINUSE => return error.AddressInUse,
......@@ -1664,13 +1663,14 @@ pub fn connect_async(sockfd: i32, sockaddr: *const c_void, len: u32) ConnectErro
16641663 ENOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.
16651664 EPROTOTYPE => unreachable, // The socket type does not support the requested communications protocol.
16661665 ETIMEDOUT => return error.ConnectionTimedOut,
1666 else => |err| return unexpectedErrno(err),
16671667 }
16681668 }
16691669}
16701670
16711671pub fn getsockoptError(sockfd: i32) ConnectError!void {
1672 var err_code: i32 = undefined;
1673 var size: u32 = @sizeOf(i32);
1672 var err_code: u32 = undefined;
1673 var size: u32 = @sizeOf(u32);
16741674 const rc = system.getsockopt(sockfd, SOL_SOCKET, SO_ERROR, @ptrCast([*]u8, &err_code), &size);
16751675 assert(size == 4);
16761676 switch (errno(rc)) {
......@@ -1702,11 +1702,13 @@ pub fn getsockoptError(sockfd: i32) ConnectError!void {
17021702 }
17031703}
17041704
1705pub fn waitpid(pid: i32, flags: u32) i32 {
1706 var status: i32 = undefined;
1705pub fn waitpid(pid: i32, flags: u32) u32 {
1706 // TODO allow implicit pointer cast from *u32 to *c_uint ?
1707 const Status = if (builtin.link_libc) c_uint else u32;
1708 var status: Status = undefined;
17071709 while (true) {
17081710 switch (errno(system.waitpid(pid, &status, flags))) {
1709 0 => return status,
1711 0 => return @bitCast(u32, status),
17101712 EINTR => continue,
17111713 ECHILD => unreachable, // The process specified does not exist. It would be a race condition to handle this error.
17121714 EINVAL => unreachable, // The options argument was invalid
......@@ -1892,11 +1894,19 @@ pub fn fork() ForkError!pid_t {
18921894}
18931895
18941896pub const MMapError = error{
1897 /// The underlying filesystem of the specified file does not support memory mapping.
1898 MemoryMappingNotSupported,
1899
1900 /// A file descriptor refers to a non-regular file. Or a file mapping was requested,
1901 /// but the file descriptor is not open for reading. Or `MAP_SHARED` was requested
1902 /// and `PROT_WRITE` is set, but the file descriptor is not open in `O_RDWR` mode.
1903 /// Or `PROT_WRITE` is set, but the file is append-only.
18951904 AccessDenied,
1905
1906 /// The `prot` argument asks for `PROT_EXEC` but the mapped area belongs to a file on
1907 /// a filesystem that was mounted no-exec.
18961908 PermissionDenied,
18971909 LockedMemoryLimitExceeded,
1898 SystemFdQuotaExceeded,
1899 MemoryMappingNotSupported,
19001910 OutOfMemory,
19011911 Unexpected,
19021912};
......@@ -1932,7 +1942,6 @@ pub fn mmap(
19321942 EAGAIN => return error.LockedMemoryLimitExceeded,
19331943 EBADF => unreachable, // Always a race condition.
19341944 EOVERFLOW => unreachable, // The number of pages used for length + offset would overflow.
1935 ENFILE => return error.SystemFdQuotaExceeded,
19361945 ENODEV => return error.MemoryMappingNotSupported,
19371946 EINVAL => unreachable, // Invalid parameters to mmap()
19381947 ENOMEM => return error.OutOfMemory,
......@@ -2265,7 +2274,7 @@ pub fn realpathC(pathname: [*]const u8, out_buffer: *[MAX_PATH_BYTES]u8) RealPat
22652274 ENAMETOOLONG => return error.NameTooLong,
22662275 ELOOP => return error.SymLinkLoop,
22672276 EIO => return error.InputOutput,
2268 else => |err| return unexpectedErrno(err),
2277 else => |err| return unexpectedErrno(@intCast(usize, err)),
22692278 };
22702279 return mem.toSlice(u8, result_path);
22712280}
......@@ -2349,7 +2358,7 @@ pub fn clock_gettime(clk_id: i32, tp: *timespec) ClockGetTimeError!void {
23492358}
23502359
23512360pub fn clock_getres(clk_id: i32, res: *timespec) ClockGetTimeError!void {
2352 switch (errno(system.clock_getres(clk_id, tp))) {
2361 switch (errno(system.clock_getres(clk_id, res))) {
23532362 0 => return,
23542363 EFAULT => unreachable,
23552364 EINVAL => return error.UnsupportedClock,
......@@ -2364,7 +2373,7 @@ pub const SchedGetAffinityError = error{
23642373
23652374pub fn sched_getaffinity(pid: pid_t) SchedGetAffinityError!cpu_set_t {
23662375 var set: cpu_set_t = undefined;
2367 switch (errno(system.sched_getaffinity(pid, &set))) {
2376 switch (errno(system.sched_getaffinity(pid, @sizeOf(cpu_set_t), &set))) {
23682377 0 => return set,
23692378 EFAULT => unreachable,
23702379 EINVAL => unreachable,
std/os/bits/darwin.zig+8-8
......@@ -219,7 +219,7 @@ pub const MAP_NOCACHE = 0x0400;
219219
220220/// don't reserve needed swap area
221221pub const MAP_NORESERVE = 0x0040;
222pub const MAP_FAILED = maxInt(usize);
222pub const MAP_FAILED = @intToPtr(*c_void, maxInt(usize));
223223
224224/// [XSI] no hang in wait/no child to reap
225225pub const WNOHANG = 0x00000001;
......@@ -749,26 +749,26 @@ pub const IPPROTO_UDP = 17;
749749pub const IPPROTO_IP = 0;
750750pub const IPPROTO_IPV6 = 41;
751751
752fn wstatus(x: i32) i32 {
752fn wstatus(x: u32) u32 {
753753 return x & 0o177;
754754}
755755const wstopped = 0o177;
756pub fn WEXITSTATUS(x: i32) i32 {
756pub fn WEXITSTATUS(x: u32) u32 {
757757 return x >> 8;
758758}
759pub fn WTERMSIG(x: i32) i32 {
759pub fn WTERMSIG(x: u32) u32 {
760760 return wstatus(x);
761761}
762pub fn WSTOPSIG(x: i32) i32 {
762pub fn WSTOPSIG(x: u32) u32 {
763763 return x >> 8;
764764}
765pub fn WIFEXITED(x: i32) bool {
765pub fn WIFEXITED(x: u32) bool {
766766 return wstatus(x) == 0;
767767}
768pub fn WIFSTOPPED(x: i32) bool {
768pub fn WIFSTOPPED(x: u32) bool {
769769 return wstatus(x) == wstopped and WSTOPSIG(x) != 0x13;
770770}
771pub fn WIFSIGNALED(x: i32) bool {
771pub fn WIFSIGNALED(x: u32) bool {
772772 return wstatus(x) != wstopped and wstatus(x) != 0;
773773}
774774
std/os/bits/freebsd.zig+11-17
......@@ -161,7 +161,7 @@ pub const CLOCK_SECOND = 13;
161161pub const CLOCK_THREAD_CPUTIME_ID = 14;
162162pub const CLOCK_PROCESS_CPUTIME_ID = 15;
163163
164pub const MAP_FAILED = maxInt(usize);
164pub const MAP_FAILED = @intToPtr(*c_void, maxInt(usize));
165165pub const MAP_SHARED = 0x0001;
166166pub const MAP_PRIVATE = 0x0002;
167167pub const MAP_FIXED = 0x0010;
......@@ -644,29 +644,23 @@ pub const TIOCGPKT = 0x80045438;
644644pub const TIOCGPTLCK = 0x80045439;
645645pub const TIOCGEXCL = 0x80045440;
646646
647fn unsigned(s: i32) u32 {
648 return @bitCast(u32, s);
647pub fn WEXITSTATUS(s: u32) u32 {
648 return (s & 0xff00) >> 8;
649649}
650fn signed(s: u32) i32 {
651 return @bitCast(i32, s);
650pub fn WTERMSIG(s: u32) u32 {
651 return s & 0x7f;
652652}
653pub fn WEXITSTATUS(s: i32) i32 {
654 return signed((unsigned(s) & 0xff00) >> 8);
655}
656pub fn WTERMSIG(s: i32) i32 {
657 return signed(unsigned(s) & 0x7f);
658}
659pub fn WSTOPSIG(s: i32) i32 {
653pub fn WSTOPSIG(s: u32) u32 {
660654 return WEXITSTATUS(s);
661655}
662pub fn WIFEXITED(s: i32) bool {
656pub fn WIFEXITED(s: u32) bool {
663657 return WTERMSIG(s) == 0;
664658}
665pub fn WIFSTOPPED(s: i32) bool {
666 return @intCast(u16, (((unsigned(s) & 0xffff) *% 0x10001) >> 8)) > 0x7f00;
659pub fn WIFSTOPPED(s: u32) bool {
660 return @intCast(u16, (((s & 0xffff) *% 0x10001) >> 8)) > 0x7f00;
667661}
668pub fn WIFSIGNALED(s: i32) bool {
669 return (unsigned(s) & 0xffff) -% 1 < 0xff;
662pub fn WIFSIGNALED(s: u32) bool {
663 return (s & 0xffff) -% 1 < 0xff;
670664}
671665
672666pub const winsize = extern struct {
std/os/bits/linux.zig+13-17
......@@ -1,5 +1,7 @@
1const builtin = @import("builtin");
12const std = @import("../../std.zig");
23const maxInt = std.math.maxInt;
4use @import("../bits.zig");
35
46pub use @import("linux/errno.zig");
57pub use switch (builtin.arch) {
......@@ -661,29 +663,23 @@ pub const TFD_CLOEXEC = O_CLOEXEC;
661663pub const TFD_TIMER_ABSTIME = 1;
662664pub const TFD_TIMER_CANCEL_ON_SET = (1 << 1);
663665
664fn unsigned(s: i32) u32 {
665 return @bitCast(u32, s);
666pub fn WEXITSTATUS(s: u32) u32 {
667 return (s & 0xff00) >> 8;
666668}
667fn signed(s: u32) i32 {
668 return @bitCast(i32, s);
669pub fn WTERMSIG(s: u32) u32 {
670 return s & 0x7f;
669671}
670pub fn WEXITSTATUS(s: i32) i32 {
671 return signed((unsigned(s) & 0xff00) >> 8);
672}
673pub fn WTERMSIG(s: i32) i32 {
674 return signed(unsigned(s) & 0x7f);
675}
676pub fn WSTOPSIG(s: i32) i32 {
672pub fn WSTOPSIG(s: u32) u32 {
677673 return WEXITSTATUS(s);
678674}
679pub fn WIFEXITED(s: i32) bool {
675pub fn WIFEXITED(s: u32) bool {
680676 return WTERMSIG(s) == 0;
681677}
682pub fn WIFSTOPPED(s: i32) bool {
683 return @intCast(u16, ((unsigned(s) & 0xffff) *% 0x10001) >> 8) > 0x7f00;
678pub fn WIFSTOPPED(s: u32) bool {
679 return @intCast(u16, ((s & 0xffff) *% 0x10001) >> 8) > 0x7f00;
684680}
685pub fn WIFSIGNALED(s: i32) bool {
686 return (unsigned(s) & 0xffff) -% 1 < 0xff;
681pub fn WIFSIGNALED(s: u32) bool {
682 return (s & 0xffff) -% 1 < 0xff;
687683}
688684
689685pub const winsize = extern struct {
......@@ -902,7 +898,7 @@ pub const dirent64 = extern struct {
902898pub const dl_phdr_info = extern struct {
903899 dlpi_addr: usize,
904900 dlpi_name: ?[*]const u8,
905 dlpi_phdr: [*]elf.Phdr,
901 dlpi_phdr: [*]std.elf.Phdr,
906902 dlpi_phnum: u16,
907903};
908904
std/os/bits/netbsd.zig+10-16
......@@ -152,7 +152,7 @@ pub const CLOCK_MONOTONIC = 3;
152152pub const CLOCK_THREAD_CPUTIME_ID = 0x20000000;
153153pub const CLOCK_PROCESS_CPUTIME_ID = 0x40000000;
154154
155pub const MAP_FAILED = maxInt(usize);
155pub const MAP_FAILED = @intToPtr(*c_void, maxInt(usize));
156156pub const MAP_SHARED = 0x0001;
157157pub const MAP_PRIVATE = 0x0002;
158158pub const MAP_REMAPDUP = 0x0004;
......@@ -516,34 +516,28 @@ pub const TIOCSWINSZ = 0x80087467;
516516pub const TIOCUCNTL = 0x80047466;
517517pub const TIOCXMTFRAME = 0x80087444;
518518
519fn unsigned(s: i32) u32 {
520 return @bitCast(u32, s);
519pub fn WEXITSTATUS(s: u32) u32 {
520 return (s >> 8) & 0xff;
521521}
522fn signed(s: u32) i32 {
523 return @bitCast(i32, s);
522pub fn WTERMSIG(s: u32) u32 {
523 return s & 0x7f;
524524}
525pub fn WEXITSTATUS(s: i32) i32 {
526 return signed((unsigned(s) >> 8) & 0xff);
527}
528pub fn WTERMSIG(s: i32) i32 {
529 return signed(unsigned(s) & 0x7f);
530}
531pub fn WSTOPSIG(s: i32) i32 {
525pub fn WSTOPSIG(s: u32) u32 {
532526 return WEXITSTATUS(s);
533527}
534pub fn WIFEXITED(s: i32) bool {
528pub fn WIFEXITED(s: u32) bool {
535529 return WTERMSIG(s) == 0;
536530}
537531
538pub fn WIFCONTINUED(s: i32) bool {
532pub fn WIFCONTINUED(s: u32) bool {
539533 return ((s & 0x7f) == 0xffff);
540534}
541535
542pub fn WIFSTOPPED(s: i32) bool {
536pub fn WIFSTOPPED(s: u32) bool {
543537 return ((s & 0x7f != 0x7f) and !WIFCONTINUED(s));
544538}
545539
546pub fn WIFSIGNALED(s: i32) bool {
540pub fn WIFSIGNALED(s: u32) bool {
547541 return !WIFSTOPPED(s) and !WIFCONTINUED(s) and !WIFEXITED(s);
548542}
549543
std/os/linux.zig+1-1
......@@ -382,7 +382,7 @@ pub fn unlinkat(dirfd: i32, path: [*]const u8, flags: u32) usize {
382382 return syscall3(SYS_unlinkat, @bitCast(usize, isize(dirfd)), @ptrToInt(path), flags);
383383}
384384
385pub fn waitpid(pid: i32, status: *i32, flags: u32) usize {
385pub fn waitpid(pid: i32, status: *u32, flags: u32) usize {
386386 return syscall4(SYS_wait4, @bitCast(usize, isize(pid)), @ptrToInt(status), flags, 0);
387387}
388388
std/os/linux/test.zig+1-1
......@@ -11,7 +11,7 @@ test "getpid" {
1111
1212test "timer" {
1313 const epoll_fd = linux.epoll_create();
14 var err = linux.getErrno(epoll_fd);
14 var err: usize = linux.getErrno(epoll_fd);
1515 expect(err == 0);
1616
1717 const timer_fd = linux.timerfd_create(linux.CLOCK_MONOTONIC, 0);
std/os/linux/vdso.zig+1-1
......@@ -5,7 +5,7 @@ const mem = std.mem;
55const maxInt = std.math.maxInt;
66
77pub fn lookup(vername: []const u8, name: []const u8) usize {
8 const vdso_addr = std.os.linuxGetAuxVal(std.elf.AT_SYSINFO_EHDR);
8 const vdso_addr = std.os.system.getauxval(std.elf.AT_SYSINFO_EHDR);
99 if (vdso_addr == 0) return 0;
1010
1111 const eh = @intToPtr(*elf.Ehdr, vdso_addr);
std/os/test.zig+16-19
......@@ -15,11 +15,11 @@ const AtomicRmwOp = builtin.AtomicRmwOp;
1515const AtomicOrder = builtin.AtomicOrder;
1616
1717test "makePath, put some files in it, deleteTree" {
18 try os.makePath(a, "os_test_tmp" ++ fs.path.sep_str ++ "b" ++ fs.path.sep_str ++ "c");
18 try fs.makePath(a, "os_test_tmp" ++ fs.path.sep_str ++ "b" ++ fs.path.sep_str ++ "c");
1919 try io.writeFile("os_test_tmp" ++ fs.path.sep_str ++ "b" ++ fs.path.sep_str ++ "c" ++ fs.path.sep_str ++ "file.txt", "nonsense");
2020 try io.writeFile("os_test_tmp" ++ fs.path.sep_str ++ "b" ++ fs.path.sep_str ++ "file2.txt", "blah");
21 try os.deleteTree(a, "os_test_tmp");
22 if (os.Dir.open(a, "os_test_tmp")) |dir| {
21 try fs.deleteTree(a, "os_test_tmp");
22 if (fs.Dir.open(a, "os_test_tmp")) |dir| {
2323 @panic("expected error");
2424 } else |err| {
2525 expect(err == error.FileNotFound);
......@@ -27,7 +27,7 @@ test "makePath, put some files in it, deleteTree" {
2727}
2828
2929test "access file" {
30 try os.makePath(a, "os_test_tmp");
30 try fs.makePath(a, "os_test_tmp");
3131 if (File.access("os_test_tmp" ++ fs.path.sep_str ++ "file.txt")) |ok| {
3232 @panic("expected error");
3333 } else |err| {
......@@ -35,8 +35,8 @@ test "access file" {
3535 }
3636
3737 try io.writeFile("os_test_tmp" ++ fs.path.sep_str ++ "file.txt", "");
38 try File.access("os_test_tmp" ++ fs.path.sep_str ++ "file.txt");
39 try os.deleteTree(a, "os_test_tmp");
38 try os.access("os_test_tmp" ++ fs.path.sep_str ++ "file.txt", os.F_OK);
39 try fs.deleteTree(a, "os_test_tmp");
4040}
4141
4242fn testThreadIdFn(thread_id: *Thread.Id) void {
......@@ -52,15 +52,12 @@ test "std.Thread.getCurrentId" {
5252 thread.wait();
5353 if (Thread.use_pthreads) {
5454 expect(thread_current_id == thread_id);
55 } else if (os.windows.is_the_target) {
56 expect(Thread.getCurrentId() != thread_current_id);
5557 } else {
56 switch (builtin.os) {
57 builtin.Os.windows => expect(Thread.getCurrentId() != thread_current_id),
58 else => {
59 // If the thread completes very quickly, then thread_id can be 0. See the
60 // documentation comments for `std.Thread.handle`.
61 expect(thread_id == 0 or thread_current_id == thread_id);
62 },
63 }
58 // If the thread completes very quickly, then thread_id can be 0. See the
59 // documentation comments for `std.Thread.handle`.
60 expect(thread_id == 0 or thread_current_id == thread_id);
6461 }
6562}
6663
......@@ -92,7 +89,7 @@ fn start2(ctx: *i32) u8 {
9289}
9390
9491test "cpu count" {
95 const cpu_count = try std.os.cpuCount(a);
92 const cpu_count = try Thread.cpuCount();
9693 expect(cpu_count >= 1);
9794}
9895
......@@ -105,7 +102,7 @@ test "AtomicFile" {
105102 \\ this is a test file
106103 ;
107104 {
108 var af = try os.AtomicFile.init(test_out_file, File.default_mode);
105 var af = try fs.AtomicFile.init(test_out_file, File.default_mode);
109106 defer af.deinit();
110107 try af.file.write(test_content);
111108 try af.finish();
......@@ -113,7 +110,7 @@ test "AtomicFile" {
113110 const content = try io.readFileAlloc(allocator, test_out_file);
114111 expect(mem.eql(u8, content, test_content));
115112
116 try os.deleteFile(test_out_file);
113 try fs.deleteFile(test_out_file);
117114}
118115
119116test "thread local storage" {
......@@ -145,10 +142,10 @@ test "getrandom" {
145142test "getcwd" {
146143 // at least call it so it gets compiled
147144 var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;
148 _ = os.getcwd(&buf) catch {};
145 _ = os.getcwd(&buf) catch undefined;
149146}
150147
151148test "realpath" {
152149 var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;
153 testing.expectError(error.FileNotFound, os.realpath("definitely_bogus_does_not_exist1234", &buf));
150 testing.expectError(error.FileNotFound, fs.realpath("definitely_bogus_does_not_exist1234", &buf));
154151}
std/os/windows.zig+38
......@@ -1180,6 +1180,44 @@ pub fn CreateProcessW(
11801180 }
11811181}
11821182
1183pub const LoadLibraryError = error{
1184 FileNotFound,
1185 Unexpected,
1186};
1187
1188pub fn LoadLibraryW(lpLibFileName: [*]const u16) LoadLibraryError!HMODULE {
1189 return kernel32.LoadLibraryW(lpLibFileName) orelse {
1190 switch (kernel32.GetLastError()) {
1191 ERROR.FILE_NOT_FOUND => return error.FileNotFound,
1192 ERROR.PATH_NOT_FOUND => return error.FileNotFound,
1193 ERROR.MOD_NOT_FOUND => return error.FileNotFound,
1194 else => |err| return unexpectedError(err),
1195 }
1196 };
1197}
1198
1199pub fn FreeLibrary(hModule: HMODULE) void {
1200 assert(kernel32.FreeLibrary(hModule) != 0);
1201}
1202
1203pub fn QueryPerformanceFrequency() u64 {
1204 // "On systems that run Windows XP or later, the function will always succeed"
1205 // https://docs.microsoft.com/en-us/windows/desktop/api/profileapi/nf-profileapi-queryperformancefrequency
1206 var result: LARGE_INTEGER = undefined;
1207 assert(kernel32.QueryPerformanceFrequency(&result) != 0);
1208 // The kernel treats this integer as unsigned.
1209 return @bitCast(u64, result);
1210}
1211
1212pub fn QueryPerformanceCounter() u64 {
1213 // "On systems that run Windows XP or later, the function will always succeed"
1214 // https://docs.microsoft.com/en-us/windows/desktop/api/profileapi/nf-profileapi-queryperformancecounter
1215 var result: LARGE_INTEGER = undefined;
1216 assert(kernel32.QueryPerformanceCounter(&result) != 0);
1217 // The kernel treats this integer as unsigned.
1218 return @bitCast(u64, result);
1219}
1220
11831221pub fn cStrToPrefixedFileW(s: [*]const u8) ![PATH_MAX_WIDE + 1]u16 {
11841222 return sliceToPrefixedFileW(mem.toSliceConst(u8, s));
11851223}
std/os/zen.zig+1-1
......@@ -80,7 +80,7 @@ pub const STDOUT_FILENO = 1;
8080pub const STDERR_FILENO = 2;
8181
8282// FIXME: let's borrow Linux's error numbers for now.
83use @import("../bits/linux/errno.zig");
83use @import("bits/linux/errno.zig");
8484// Get the errno from a syscall return value, or 0 for no error.
8585pub fn getErrno(r: usize) usize {
8686 const signed_r = @bitCast(isize, r);
std/process.zig+21-1
......@@ -1,7 +1,9 @@
11const builtin = @import("builtin");
22const std = @import("std.zig");
33const os = std.os;
4const fs = std.fs;
45const BufMap = std.BufMap;
6const Buffer = std.Buffer;
57const mem = std.mem;
68const math = std.math;
79const Allocator = mem.Allocator;
......@@ -13,6 +15,24 @@ pub const exit = os.exit;
1315pub const changeCurDir = os.chdir;
1416pub const changeCurDirC = os.chdirC;
1517
18/// The result is a slice of `out_buffer`, from index `0`.
19pub fn getCwd(out_buffer: *[fs.MAX_PATH_BYTES]u8) ![]u8 {
20 return os.getcwd(out_buffer);
21}
22
23/// Caller must free the returned memory.
24pub fn getCwdAlloc(allocator: *Allocator) ![]u8 {
25 var buf: [fs.MAX_PATH_BYTES]u8 = undefined;
26 return mem.dupe(allocator, u8, try os.getcwd(&buf));
27}
28
29test "getCwdAlloc" {
30 // at least call it so it gets compiled
31 var buf: [1000]u8 = undefined;
32 const allocator = &std.heap.FixedBufferAllocator.init(&buf).allocator;
33 _ = getCwdAlloc(allocator) catch undefined;
34}
35
1636/// Caller must free result when done.
1737/// TODO make this go through libc when we have it
1838pub fn getEnvMap(allocator: *Allocator) !BufMap {
......@@ -402,7 +422,7 @@ pub fn argsAlloc(allocator: *mem.Allocator) ![]const []u8 {
402422 var contents = try Buffer.initSize(allocator, 0);
403423 defer contents.deinit();
404424
405 var slice_list = ArrayList(usize).init(allocator);
425 var slice_list = std.ArrayList(usize).init(allocator);
406426 defer slice_list.deinit();
407427
408428 while (it.next(allocator)) |arg_or_err| {
std/thread.zig+36-20
......@@ -1,8 +1,10 @@
11const builtin = @import("builtin");
22const std = @import("std.zig");
33const os = std.os;
4const mem = std.mem;
45const windows = std.os.windows;
56const c = std.c;
7const assert = std.debug.assert;
68
79pub const Thread = struct {
810 data: Data,
......@@ -31,14 +33,12 @@ pub const Thread = struct {
3133 pub const Data = if (use_pthreads)
3234 struct {
3335 handle: Thread.Handle,
34 mmap_addr: usize,
35 mmap_len: usize,
36 memory: []align(mem.page_size) u8,
3637 }
3738 else switch (builtin.os) {
3839 .linux => struct {
3940 handle: Thread.Handle,
40 mmap_addr: usize,
41 mmap_len: usize,
41 memory: []align(mem.page_size) u8,
4242 },
4343 .windows => struct {
4444 handle: Thread.Handle,
......@@ -56,7 +56,7 @@ pub const Thread = struct {
5656 return c.pthread_self();
5757 } else
5858 return switch (builtin.os) {
59 .linux => linux.gettid(),
59 .linux => os.linux.gettid(),
6060 .windows => windows.GetCurrentThreadId(),
6161 else => @compileError("Unsupported OS"),
6262 };
......@@ -82,21 +82,21 @@ pub const Thread = struct {
8282 os.EDEADLK => unreachable,
8383 else => unreachable,
8484 }
85 os.munmap(self.data.mmap_addr, self.data.mmap_len);
85 os.munmap(self.data.memory);
8686 } else switch (builtin.os) {
8787 .linux => {
8888 while (true) {
8989 const pid_value = @atomicLoad(i32, &self.data.handle, .SeqCst);
9090 if (pid_value == 0) break;
91 const rc = linux.futex_wait(&self.data.handle, linux.FUTEX_WAIT, pid_value, null);
92 switch (linux.getErrno(rc)) {
91 const rc = os.linux.futex_wait(&self.data.handle, os.linux.FUTEX_WAIT, pid_value, null);
92 switch (os.linux.getErrno(rc)) {
9393 0 => continue,
9494 os.EINTR => continue,
9595 os.EAGAIN => continue,
9696 else => unreachable,
9797 }
9898 }
99 os.munmap(self.data.mmap_addr, self.data.mmap_len);
99 os.munmap(self.data.memory);
100100 },
101101 .windows => {
102102 assert(windows.WaitForSingleObject(self.data.handle, windows.INFINITE) == windows.WAIT_OBJECT_0);
......@@ -130,6 +130,10 @@ pub const Thread = struct {
130130 /// Not enough userland memory to spawn the thread.
131131 OutOfMemory,
132132
133 /// `mlockall` is enabled, and the memory needed to spawn the thread
134 /// would exceed the limit.
135 LockedMemoryLimitExceeded,
136
133137 Unexpected,
134138 };
135139
......@@ -219,7 +223,7 @@ pub const Thread = struct {
219223 }
220224 };
221225
222 const MAP_GROWSDOWN = if (builtin.os == .linux) linux.MAP_GROWSDOWN else 0;
226 const MAP_GROWSDOWN = if (os.linux.is_the_target) os.linux.MAP_GROWSDOWN else 0;
223227
224228 var stack_end_offset: usize = undefined;
225229 var thread_start_offset: usize = undefined;
......@@ -241,7 +245,7 @@ pub const Thread = struct {
241245 }
242246 // Finally, the Thread Local Storage, if any.
243247 if (!Thread.use_pthreads) {
244 if (linux.tls.tls_image) |tls_img| {
248 if (os.linux.tls.tls_image) |tls_img| {
245249 l = mem.alignForward(l, @alignOf(usize));
246250 tls_start_offset = l;
247251 l += tls_img.alloc_size;
......@@ -249,12 +253,24 @@ pub const Thread = struct {
249253 }
250254 break :blk l;
251255 };
252 const mmap_addr = try os.mmap(null, mmap_len, os.PROT_READ | os.PROT_WRITE, os.MAP_PRIVATE | os.MAP_ANONYMOUS | MAP_GROWSDOWN, -1, 0);
253 errdefer os.munmap(mmap_addr, mmap_len);
256 const mmap_slice = os.mmap(
257 null,
258 mem.alignForward(mmap_len, mem.page_size),
259 os.PROT_READ | os.PROT_WRITE,
260 os.MAP_PRIVATE | os.MAP_ANONYMOUS | MAP_GROWSDOWN,
261 -1,
262 0,
263 ) catch |err| switch (err) {
264 error.MemoryMappingNotSupported => unreachable, // no file descriptor
265 error.AccessDenied => unreachable, // no file descriptor
266 error.PermissionDenied => unreachable, // no file descriptor
267 else => |e| return e,
268 };
269 errdefer os.munmap(mmap_slice);
270 const mmap_addr = @ptrToInt(mmap_slice.ptr);
254271
255272 const thread_ptr = @alignCast(@alignOf(Thread), @intToPtr(*Thread, mmap_addr + thread_start_offset));
256 thread_ptr.data.mmap_addr = mmap_addr;
257 thread_ptr.data.mmap_len = mmap_len;
273 thread_ptr.data.memory = mmap_slice;
258274
259275 var arg: usize = undefined;
260276 if (@sizeOf(Context) != 0) {
......@@ -269,7 +285,7 @@ pub const Thread = struct {
269285 if (c.pthread_attr_init(&attr) != 0) return error.SystemResources;
270286 defer assert(c.pthread_attr_destroy(&attr) == 0);
271287
272 assert(c.pthread_attr_setstack(&attr, @intToPtr(*c_void, mmap_addr), stack_end_offset) == 0);
288 assert(c.pthread_attr_setstack(&attr, mmap_slice.ptr, stack_end_offset) == 0);
273289
274290 const err = c.pthread_create(&thread_ptr.data.handle, &attr, MainFuncs.posixThreadMain, @intToPtr(*c_void, arg));
275291 switch (err) {
......@@ -279,13 +295,13 @@ pub const Thread = struct {
279295 os.EINVAL => unreachable,
280296 else => return os.unexpectedErrno(@intCast(usize, err)),
281297 }
282 } else if (builtin.os == .linux) {
298 } else if (os.linux.is_the_target) {
283299 var flags: u32 = os.CLONE_VM | os.CLONE_FS | os.CLONE_FILES | os.CLONE_SIGHAND |
284300 os.CLONE_THREAD | os.CLONE_SYSVSEM | os.CLONE_PARENT_SETTID | os.CLONE_CHILD_CLEARTID |
285301 os.CLONE_DETACHED;
286302 var newtls: usize = undefined;
287 if (linux.tls.tls_image) |tls_img| {
288 newtls = linux.tls.copyTLS(mmap_addr + tls_start_offset);
303 if (os.linux.tls.tls_image) |tls_img| {
304 newtls = os.linux.tls.copyTLS(mmap_addr + tls_start_offset);
289305 flags |= os.CLONE_SETTLS;
290306 }
291307 const rc = os.linux.clone(MainFuncs.linuxThreadMain, mmap_addr + stack_end_offset, flags, arg, &thread_ptr.data.handle, newtls, &thread_ptr.data.handle);
......@@ -313,7 +329,7 @@ pub const Thread = struct {
313329 pub fn cpuCount() CpuCountError!usize {
314330 if (os.linux.is_the_target) {
315331 const cpu_set = try os.sched_getaffinity(0);
316 return os.CPU_COUNT(cpu_set);
332 return usize(os.CPU_COUNT(cpu_set)); // TODO should not need this usize cast
317333 }
318334 if (os.windows.is_the_target) {
319335 var system_info: windows.SYSTEM_INFO = undefined;
std/time.zig+7-17
......@@ -95,7 +95,7 @@ pub const Timer = struct {
9595 /// be less precise
9696 frequency: switch (builtin.os) {
9797 .windows => u64,
98 .macosx, .ios, .tvos, .watchos => darwin.mach_timebase_info_data,
98 .macosx, .ios, .tvos, .watchos => os.darwin.mach_timebase_info_data,
9999 else => void,
100100 },
101101 resolution: u64,
......@@ -119,20 +119,13 @@ pub const Timer = struct {
119119 var self: Timer = undefined;
120120
121121 if (os.windows.is_the_target) {
122 var freq: i64 = undefined;
123 var err = windows.QueryPerformanceFrequency(&freq);
124 if (err == windows.FALSE) return error.TimerUnsupported;
125 self.frequency = @intCast(u64, freq);
122 self.frequency = os.windows.QueryPerformanceFrequency();
126123 self.resolution = @divFloor(ns_per_s, self.frequency);
127
128 var start_time: i64 = undefined;
129 err = windows.QueryPerformanceCounter(&start_time);
130 assert(err != windows.FALSE);
131 self.start_time = @intCast(u64, start_time);
124 self.start_time = os.windows.QueryPerformanceCounter();
132125 } else if (os.darwin.is_the_target) {
133 darwin.mach_timebase_info(&self.frequency);
126 os.darwin.mach_timebase_info(&self.frequency);
134127 self.resolution = @divFloor(self.frequency.numer, self.frequency.denom);
135 self.start_time = darwin.mach_absolute_time();
128 self.start_time = os.darwin.mach_absolute_time();
136129 } else {
137130 //On Linux, seccomp can do arbitrary things to our ability to call
138131 // syscalls, including return any errno value it wants and
......@@ -177,13 +170,10 @@ pub const Timer = struct {
177170
178171 fn clockNative() u64 {
179172 if (os.windows.is_the_target) {
180 var result: i64 = undefined;
181 var err = windows.QueryPerformanceCounter(&result);
182 assert(err != windows.FALSE);
183 return @intCast(u64, result);
173 return os.windows.QueryPerformanceCounter();
184174 }
185175 if (os.darwin.is_the_target) {
186 return darwin.mach_absolute_time();
176 return os.darwin.mach_absolute_time();
187177 }
188178 var ts: os.timespec = undefined;
189179 os.clock_gettime(monotonic_clock_id, &ts) catch unreachable;
test/compare_output.zig+3-3
......@@ -377,7 +377,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
377377 \\ stdout.print("before\n") catch unreachable;
378378 \\ defer stdout.print("defer1\n") catch unreachable;
379379 \\ defer stdout.print("defer2\n") catch unreachable;
380 \\ var args_it = @import("std").os.args();
380 \\ var args_it = @import("std").process.args();
381381 \\ if (args_it.skip() and !args_it.skip()) return;
382382 \\ defer stdout.print("defer3\n") catch unreachable;
383383 \\ stdout.print("after\n") catch unreachable;
......@@ -444,7 +444,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
444444 \\const allocator = std.debug.global_allocator;
445445 \\
446446 \\pub fn main() !void {
447 \\ var args_it = os.args();
447 \\ var args_it = std.process.args();
448448 \\ var stdout_file = try io.getStdOut();
449449 \\ var stdout_adapter = stdout_file.outStream();
450450 \\ const stdout = &stdout_adapter.stream;
......@@ -485,7 +485,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
485485 \\const allocator = std.debug.global_allocator;
486486 \\
487487 \\pub fn main() !void {
488 \\ var args_it = os.args();
488 \\ var args_it = std.process.args();
489489 \\ var stdout_file = try io.getStdOut();
490490 \\ var stdout_adapter = stdout_file.outStream();
491491 \\ const stdout = &stdout_adapter.stream;
test/standalone/empty_env/main.zig+1-1
......@@ -1,6 +1,6 @@
11const std = @import("std");
22
33pub fn main() void {
4 const env_map = std.os.getEnvMap(std.debug.global_allocator) catch @panic("unable to get env map");
4 const env_map = std.process.getEnvMap(std.debug.global_allocator) catch @panic("unable to get env map");
55 std.testing.expect(env_map.count() == 0);
66}
test/tests.zig+1-1
......@@ -393,7 +393,7 @@ pub const CompareOutputContext = struct {
393393 debug.panic("Unable to spawn {}: {}\n", full_exe_path, @errorName(err));
394394 };
395395
396 const expected_exit_code: i32 = 126;
396 const expected_exit_code: u32 = 126;
397397 switch (term) {
398398 .Exited => |code| {
399399 if (code != expected_exit_code) {