authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2017-09-07 23:10:23-04:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2017-09-07 23:10:51-04:00
log9fb4d1fd6c521e1bc3b656315b9c693a9e8aa715
treee5500f9bcf0d0d857e4531a7b9873c64684f61a2
parent9dfaf3166d161e125d70fac7bca5aab1ad02625b

std: os.ChildProcess knows when its child died

using signal handlers

10 files changed, 384 insertions(+), 134 deletions(-)

src/ir.cpp+22
...@@ -11513,6 +11513,28 @@ static TypeTableEntry *ir_analyze_instruction_field_ptr(IrAnalyze *ira, IrInstru...@@ -11513,6 +11513,28 @@ static TypeTableEntry *ir_analyze_instruction_field_ptr(IrAnalyze *ira, IrInstru
11513 buf_ptr(&child_type->name), buf_ptr(field_name)));11513 buf_ptr(&child_type->name), buf_ptr(field_name)));
11514 return ira->codegen->builtin_types.entry_invalid;11514 return ira->codegen->builtin_types.entry_invalid;
11515 }11515 }
11516 } else if (child_type->id == TypeTableEntryIdArray) {
11517 if (buf_eql_str(field_name, "child")) {
11518 bool ptr_is_const = true;
11519 bool ptr_is_volatile = false;
11520 return ir_analyze_const_ptr(ira, &field_ptr_instruction->base,
11521 create_const_type(ira->codegen, child_type->data.array.child_type),
11522 ira->codegen->builtin_types.entry_type,
11523 ConstPtrMutComptimeConst, ptr_is_const, ptr_is_volatile);
11524 } else if (buf_eql_str(field_name, "len")) {
11525 bool ptr_is_const = true;
11526 bool ptr_is_volatile = false;
11527 return ir_analyze_const_ptr(ira, &field_ptr_instruction->base,
11528 create_const_unsigned_negative(ira->codegen->builtin_types.entry_num_lit_int,
11529 child_type->data.array.len, false),
11530 ira->codegen->builtin_types.entry_num_lit_int,
11531 ConstPtrMutComptimeConst, ptr_is_const, ptr_is_volatile);
11532 } else {
11533 ir_add_error(ira, &field_ptr_instruction->base,
11534 buf_sprintf("type '%s' has no member called '%s'",
11535 buf_ptr(&child_type->name), buf_ptr(field_name)));
11536 return ira->codegen->builtin_types.entry_invalid;
11537 }
11516 } else {11538 } else {
11517 ir_add_error(ira, &field_ptr_instruction->base,11539 ir_add_error(ira, &field_ptr_instruction->base,
11518 buf_sprintf("type '%s' does not support field access", buf_ptr(&child_type->name)));11540 buf_sprintf("type '%s' does not support field access", buf_ptr(&child_type->name)));
std/build.zig+2-2
...@@ -545,7 +545,7 @@ pub const Builder = struct {...@@ -545,7 +545,7 @@ pub const Builder = struct {
545 }545 }
546546
547 var child = os.ChildProcess.spawn(exe_path, args, cwd, env_map,547 var child = os.ChildProcess.spawn(exe_path, args, cwd, env_map,
548 StdIo.Inherit, StdIo.Inherit, StdIo.Inherit, self.allocator) %% |err|548 StdIo.Inherit, StdIo.Inherit, StdIo.Inherit, null, self.allocator) %% |err|
549 {549 {
550 %%io.stderr.printf("Unable to spawn {}: {}\n", exe_path, @errorName(err));550 %%io.stderr.printf("Unable to spawn {}: {}\n", exe_path, @errorName(err));
551 return err;551 return err;
...@@ -556,7 +556,7 @@ pub const Builder = struct {...@@ -556,7 +556,7 @@ pub const Builder = struct {
556 return err;556 return err;
557 };557 };
558 switch (term) {558 switch (term) {
559 Term.Clean => |code| {559 Term.Exited => |code| {
560 if (code != 0) {560 if (code != 0) {
561 %%io.stderr.printf("Process {} exited with error code {}\n", exe_path, code);561 %%io.stderr.printf("Process {} exited with error code {}\n", exe_path, code);
562 return error.UncleanExit;562 return error.UncleanExit;
std/linked_list.zig+35-50
...@@ -1,7 +1,6 @@...@@ -1,7 +1,6 @@
1const debug = @import("debug.zig");1const debug = @import("debug.zig");
2const assert = debug.assert;2const assert = debug.assert;
3const mem = @import("mem.zig");3const mem = @import("mem.zig");
4const Allocator = mem.Allocator;
54
6/// Generic doubly linked list.5/// Generic doubly linked list.
7pub fn LinkedList(comptime T: type) -> type {6pub fn LinkedList(comptime T: type) -> type {
...@@ -13,26 +12,29 @@ pub fn LinkedList(comptime T: type) -> type {...@@ -13,26 +12,29 @@ pub fn LinkedList(comptime T: type) -> type {
13 prev: ?&Node,12 prev: ?&Node,
14 next: ?&Node,13 next: ?&Node,
15 data: T,14 data: T,
15
16 pub fn init(data: &const T) -> Node {
17 Node {
18 .data = *data,
19 .prev = null,
20 .next = null,
21 }
22 }
16 };23 };
1724
18 first: ?&Node,25 first: ?&Node,
19 last: ?&Node,26 last: ?&Node,
20 len: usize,27 len: usize,
21 allocator: &Allocator,
2228
23 /// Initialize a linked list.29 /// Initialize a linked list.
24 ///30 ///
25 /// Arguments:
26 /// allocator: Dynamic memory allocator.
27 ///
28 /// Returns:31 /// Returns:
29 /// An empty linked list.32 /// An empty linked list.
30 pub fn init(allocator: &Allocator) -> Self {33 pub fn init() -> Self {
31 Self {34 Self {
32 .first = null,35 .first = null,
33 .last = null,36 .last = null,
34 .len = 0,37 .len = 0,
35 .allocator = allocator,
36 }38 }
37 }39 }
3840
...@@ -155,55 +157,38 @@ pub fn LinkedList(comptime T: type) -> type {...@@ -155,55 +157,38 @@ pub fn LinkedList(comptime T: type) -> type {
155 return first;157 return first;
156 }158 }
157159
158 /// Allocate a new node.160 }
159 ///161}
160 /// Returns:
161 /// A pointer to the new node.
162 pub fn allocateNode(list: &Self) -> %&Node {
163 list.allocator.create(Node)
164 }
165162
166 /// Deallocate a node.163pub fn testAllocateNode(comptime T: type, list: &LinkedList(T), allocator: &mem.Allocator) -> %&LinkedList(T).Node {
167 ///164 allocator.create(LinkedList(T).Node)
168 /// Arguments:165}
169 /// node: Pointer to the node to deallocate.
170 pub fn destroyNode(list: &Self, node: &Node) {
171 list.allocator.destroy(node);
172 }
173166
174 /// Allocate and initialize a node and its data.167pub fn testDestroyNode(comptime T: type, list: &LinkedList(T), node: &LinkedList(T).Node, allocator: &mem.Allocator) {
175 ///168 allocator.destroy(node);
176 /// Arguments:
177 /// data: The data to put inside the node.
178 ///
179 /// Returns:
180 /// A pointer to the new node.
181 pub fn createNode(list: &Self, data: &const T) -> %&Node {
182 var node = %return list.allocateNode();
183 *node = Node {
184 .prev = null,
185 .next = null,
186 .data = *data,
187 };
188 return node;
189 }
190 }
191}169}
192170
193test "basic linked list test" {171pub fn testCreateNode(comptime T: type, list: &LinkedList(T), data: &const T, allocator: &mem.Allocator) -> %&LinkedList(T).Node {
194 var list = LinkedList(u32).init(&debug.global_allocator);172 var node = %return testAllocateNode(T, list, allocator);
173 *node = LinkedList(T).Node.init(data);
174 return node;
175}
195176
196 var one = %%list.createNode(1);177test "basic linked list test" {
197 var two = %%list.createNode(2);178 const allocator = &debug.global_allocator;
198 var three = %%list.createNode(3);179 var list = LinkedList(u32).init();
199 var four = %%list.createNode(4);180
200 var five = %%list.createNode(5);181 var one = %%testCreateNode(u32, &list, 1, allocator);
182 var two = %%testCreateNode(u32, &list, 2, allocator);
183 var three = %%testCreateNode(u32, &list, 3, allocator);
184 var four = %%testCreateNode(u32, &list, 4, allocator);
185 var five = %%testCreateNode(u32, &list, 5, allocator);
201 defer {186 defer {
202 list.destroyNode(one);187 testDestroyNode(u32, &list, one, allocator);
203 list.destroyNode(two);188 testDestroyNode(u32, &list, two, allocator);
204 list.destroyNode(three);189 testDestroyNode(u32, &list, three, allocator);
205 list.destroyNode(four);190 testDestroyNode(u32, &list, four, allocator);
206 list.destroyNode(five);191 testDestroyNode(u32, &list, five, allocator);
207 }192 }
208193
209 list.append(two); // {2}194 list.append(two); // {2}
std/mem.zig+10-5
...@@ -49,11 +49,16 @@ pub const Allocator = struct {...@@ -49,11 +49,16 @@ pub const Allocator = struct {
49 }49 }
5050
51 fn free(self: &Allocator, memory: var) {51 fn free(self: &Allocator, memory: var) {
52 const const_slice = ([]const u8)(memory);52 const ptr = if (@typeId(@typeOf(memory)) == builtin.TypeId.Pointer) {
53 if (memory.len == 0)53 memory
54 return;54 } else {
55 const ptr = @intToPtr(&u8, @ptrToInt(const_slice.ptr));55 const const_slice = ([]const u8)(memory);
56 self.freeFn(self, ptr);56 if (memory.len == 0)
57 return;
58 const_slice.ptr
59 };
60 const non_const_ptr = @intToPtr(&u8, @ptrToInt(ptr));
61 self.freeFn(self, non_const_ptr);
57 }62 }
58};63};
5964
std/os/child_process.zig+189-61
...@@ -8,20 +8,31 @@ const assert = debug.assert;...@@ -8,20 +8,31 @@ const assert = debug.assert;
8const BufMap = @import("../buf_map.zig").BufMap;8const BufMap = @import("../buf_map.zig").BufMap;
9const builtin = @import("builtin");9const builtin = @import("builtin");
10const Os = builtin.Os;10const Os = builtin.Os;
11const LinkedList = @import("../linked_list.zig").LinkedList;
1112
12error PermissionDenied;13error PermissionDenied;
13error ProcessNotFound;14error ProcessNotFound;
1415
16var children_nodes = LinkedList(&ChildProcess).init();
17
15pub const ChildProcess = struct {18pub const ChildProcess = struct {
16 pid: i32,19 pid: i32,
20
17 err_pipe: [2]i32,21 err_pipe: [2]i32,
22 llnode: LinkedList(&ChildProcess).Node,
23 allocator: &mem.Allocator,
24
25 stdin: ?&io.OutStream,
26 stdout: ?&io.InStream,
27 stderr: ?&io.InStream,
1828
19 stdin: ?io.OutStream,29 term: ?%Term,
20 stdout: ?io.InStream,30
21 stderr: ?io.InStream,31 /// Possibly called from a signal handler.
32 onTerm: ?fn(&ChildProcess),
2233
23 pub const Term = enum {34 pub const Term = enum {
24 Clean: i32,35 Exited: i32,
25 Signal: i32,36 Signal: i32,
26 Stopped: i32,37 Stopped: i32,
27 Unknown: i32,38 Unknown: i32,
...@@ -34,13 +45,15 @@ pub const ChildProcess = struct {...@@ -34,13 +45,15 @@ pub const ChildProcess = struct {
34 Close,45 Close,
35 };46 };
3647
48 /// onTerm can be called before `spawn` returns.
37 pub fn spawn(exe_path: []const u8, args: []const []const u8,49 pub fn spawn(exe_path: []const u8, args: []const []const u8,
38 cwd: ?[]const u8, env_map: &const BufMap,50 cwd: ?[]const u8, env_map: &const BufMap,
39 stdin: StdIo, stdout: StdIo, stderr: StdIo, allocator: &Allocator) -> %ChildProcess51 stdin: StdIo, stdout: StdIo, stderr: StdIo,
52 onTerm: ?fn(&ChildProcess), allocator: &Allocator) -> %&ChildProcess
40 {53 {
41 switch (builtin.os) {54 switch (builtin.os) {
42 Os.linux, Os.macosx, Os.ios, Os.darwin => {55 Os.linux, Os.macosx, Os.ios, Os.darwin => {
43 return spawnPosix(exe_path, args, cwd, env_map, stdin, stdout, stderr, allocator);56 return spawnPosix(exe_path, args, cwd, env_map, stdin, stdout, stderr, onTerm, allocator);
44 },57 },
45 else => @compileError("Unsupported OS"),58 else => @compileError("Unsupported OS"),
46 }59 }
...@@ -48,6 +61,12 @@ pub const ChildProcess = struct {...@@ -48,6 +61,12 @@ pub const ChildProcess = struct {
4861
49 /// Forcibly terminates child process and then cleans up all resources.62 /// Forcibly terminates child process and then cleans up all resources.
50 pub fn kill(self: &ChildProcess) -> %Term {63 pub fn kill(self: &ChildProcess) -> %Term {
64 block_SIGCHLD();
65 defer restore_SIGCHLD();
66
67 if (self.term) |term| {
68 return term;
69 }
51 const ret = posix.kill(self.pid, posix.SIGTERM);70 const ret = posix.kill(self.pid, posix.SIGTERM);
52 const err = posix.getErrno(ret);71 const err = posix.getErrno(ret);
53 if (err > 0) {72 if (err > 0) {
...@@ -58,37 +77,60 @@ pub const ChildProcess = struct {...@@ -58,37 +77,60 @@ pub const ChildProcess = struct {
58 else => error.Unexpected,77 else => error.Unexpected,
59 };78 };
60 }79 }
61 return self.wait();80 self.waitUnwrapped();
81 return ??self.term;
62 }82 }
6383
64 /// Blocks until child process terminates and then cleans up all resources.84 /// Blocks until child process terminates and then cleans up all resources.
65 pub fn wait(self: &ChildProcess) -> %Term {85 pub fn wait(self: &ChildProcess) -> %Term {
66 defer {86 block_SIGCHLD();
67 os.posixClose(self.err_pipe[0]);87 defer restore_SIGCHLD();
68 os.posixClose(self.err_pipe[1]);
69 };
7088
89 if (self.term) |term| {
90 return term;
91 }
92
93 self.waitUnwrapped();
94 return ??self.term;
95 }
96
97 fn waitUnwrapped(self: &ChildProcess) {
71 var status: i32 = undefined;98 var status: i32 = undefined;
72 while (true) {99 while (true) {
73 const err = posix.getErrno(posix.waitpid(self.pid, &status, 0));100 const err = posix.getErrno(posix.waitpid(self.pid, &status, 0));
74 if (err > 0) {101 if (err > 0) {
75 switch (err) {102 switch (err) {
76 posix.EINVAL, posix.ECHILD => unreachable,
77 posix.EINTR => continue,103 posix.EINTR => continue,
78 else => {104 else => unreachable,
79 if (self.stdin) |*stdin| { stdin.close(); }
80 if (self.stdout) |*stdout| { stdout.close(); }
81 if (self.stderr) |*stderr| { stderr.close(); }
82 return error.Unexpected;
83 },
84 }105 }
85 }106 }
86 break;107 self.cleanupStreams();
108 self.handleWaitResult(status);
109 return;
87 }110 }
111 }
112
113 fn handleWaitResult(self: &ChildProcess, status: i32) {
114 self.term = self.cleanupAfterWait(status);
115
116 if (self.onTerm) |onTerm| {
117 onTerm(self);
118 }
119 }
88120
89 if (self.stdin) |*stdin| { stdin.close(); }121 fn cleanupStreams(self: &ChildProcess) {
90 if (self.stdout) |*stdout| { stdout.close(); }122 if (self.stdin) |stdin| { stdin.close(); self.allocator.free(stdin); }
91 if (self.stderr) |*stderr| { stderr.close(); }123 if (self.stdout) |stdout| { stdout.close(); self.allocator.free(stdout); }
124 if (self.stderr) |stderr| { stderr.close(); self.allocator.free(stderr); }
125 }
126
127 fn cleanupAfterWait(self: &ChildProcess, status: i32) -> %Term {
128 children_nodes.remove(&self.llnode);
129
130 defer {
131 os.posixClose(self.err_pipe[0]);
132 os.posixClose(self.err_pipe[1]);
133 };
92134
93 // Write @maxValue(ErrInt) to the write end of the err_pipe. This is after135 // Write @maxValue(ErrInt) to the write end of the err_pipe. This is after
94 // waitpid, so this write is guaranteed to be after the child136 // waitpid, so this write is guaranteed to be after the child
...@@ -108,7 +150,7 @@ pub const ChildProcess = struct {...@@ -108,7 +150,7 @@ pub const ChildProcess = struct {
108150
109 fn statusToTerm(status: i32) -> Term {151 fn statusToTerm(status: i32) -> Term {
110 return if (posix.WIFEXITED(status)) {152 return if (posix.WIFEXITED(status)) {
111 Term.Clean { posix.WEXITSTATUS(status) }153 Term.Exited { posix.WEXITSTATUS(status) }
112 } else if (posix.WIFSIGNALED(status)) {154 } else if (posix.WIFSIGNALED(status)) {
113 Term.Signal { posix.WTERMSIG(status) }155 Term.Signal { posix.WTERMSIG(status) }
114 } else if (posix.WIFSTOPPED(status)) {156 } else if (posix.WIFSTOPPED(status)) {
...@@ -120,8 +162,12 @@ pub const ChildProcess = struct {...@@ -120,8 +162,12 @@ pub const ChildProcess = struct {
120162
121 fn spawnPosix(exe_path: []const u8, args: []const []const u8,163 fn spawnPosix(exe_path: []const u8, args: []const []const u8,
122 maybe_cwd: ?[]const u8, env_map: &const BufMap,164 maybe_cwd: ?[]const u8, env_map: &const BufMap,
123 stdin: StdIo, stdout: StdIo, stderr: StdIo, allocator: &Allocator) -> %ChildProcess165 stdin: StdIo, stdout: StdIo, stderr: StdIo,
166 onTerm: ?fn(&ChildProcess), allocator: &Allocator) -> %&ChildProcess
124 {167 {
168 // TODO atomically set a flag saying that we already did this
169 install_SIGCHLD_handler();
170
125 const stdin_pipe = if (stdin == StdIo.Pipe) %return makePipe() else undefined;171 const stdin_pipe = if (stdin == StdIo.Pipe) %return makePipe() else undefined;
126 %defer if (stdin == StdIo.Pipe) { destroyPipe(stdin_pipe); };172 %defer if (stdin == StdIo.Pipe) { destroyPipe(stdin_pipe); };
127173
...@@ -143,16 +189,39 @@ pub const ChildProcess = struct {...@@ -143,16 +189,39 @@ pub const ChildProcess = struct {
143 const err_pipe = %return makePipe();189 const err_pipe = %return makePipe();
144 %defer destroyPipe(err_pipe);190 %defer destroyPipe(err_pipe);
145191
146 const pid = posix.fork();192 const child = %return allocator.create(ChildProcess);
147 const pid_err = posix.getErrno(pid);193 %defer allocator.destroy(child);
194
195 const stdin_ptr = if (stdin == StdIo.Pipe) {
196 %return allocator.create(io.OutStream)
197 } else {
198 null
199 };
200 const stdout_ptr = if (stdout == StdIo.Pipe) {
201 %return allocator.create(io.InStream)
202 } else {
203 null
204 };
205 const stderr_ptr = if (stderr == StdIo.Pipe) {
206 %return allocator.create(io.InStream)
207 } else {
208 null
209 };
210
211 block_SIGCHLD();
212 const pid_result = posix.fork();
213 const pid_err = posix.getErrno(pid_result);
148 if (pid_err > 0) {214 if (pid_err > 0) {
215 restore_SIGCHLD();
149 return switch (pid_err) {216 return switch (pid_err) {
150 posix.EAGAIN, posix.ENOMEM, posix.ENOSYS => error.SystemResources,217 posix.EAGAIN, posix.ENOMEM, posix.ENOSYS => error.SystemResources,
151 else => error.Unexpected,218 else => error.Unexpected,
152 };219 };
153 }220 }
154 if (pid == 0) {221 if (pid_result == 0) {
155 // we are the child222 // we are the child
223 restore_SIGCHLD();
224
156 setUpChildIo(stdin, stdin_pipe[0], posix.STDIN_FILENO, dev_null_fd) %%225 setUpChildIo(stdin, stdin_pipe[0], posix.STDIN_FILENO, dev_null_fd) %%
157 |err| forkChildErrReport(err_pipe[1], err);226 |err| forkChildErrReport(err_pipe[1], err);
158 setUpChildIo(stdout, stdout_pipe[1], posix.STDOUT_FILENO, dev_null_fd) %%227 setUpChildIo(stdout, stdout_pipe[1], posix.STDOUT_FILENO, dev_null_fd) %%
...@@ -170,45 +239,53 @@ pub const ChildProcess = struct {...@@ -170,45 +239,53 @@ pub const ChildProcess = struct {
170 }239 }
171240
172 // we are the parent241 // we are the parent
242 const pid = i32(pid_result);
243 if (stdin_ptr) |outstream| {
244 *outstream = io.OutStream {
245 .fd = stdin_pipe[1],
246 .handle = {},
247 .handle_id = {},
248 .buffer = undefined,
249 .index = 0,
250 };
251 }
252 if (stdout_ptr) |instream| {
253 *instream = io.InStream {
254 .fd = stdout_pipe[0],
255 .handle = {},
256 .handle_id = {},
257 };
258 }
259 if (stderr_ptr) |instream| {
260 *instream = io.InStream {
261 .fd = stderr_pipe[0],
262 .handle = {},
263 .handle_id = {},
264 };
265 }
266
267 *child = ChildProcess {
268 .allocator = allocator,
269 .pid = pid,
270 .err_pipe = err_pipe,
271 .llnode = LinkedList(&ChildProcess).Node.init(child),
272 .term = null,
273 .onTerm = onTerm,
274 .stdin = stdin_ptr,
275 .stdout = stdout_ptr,
276 .stderr = stderr_ptr,
277 };
278
279 children_nodes.prepend(&child.llnode);
280
281 restore_SIGCHLD();
282
173 if (stdin == StdIo.Pipe) { os.posixClose(stdin_pipe[0]); }283 if (stdin == StdIo.Pipe) { os.posixClose(stdin_pipe[0]); }
174 if (stdout == StdIo.Pipe) { os.posixClose(stdout_pipe[1]); }284 if (stdout == StdIo.Pipe) { os.posixClose(stdout_pipe[1]); }
175 if (stderr == StdIo.Pipe) { os.posixClose(stderr_pipe[1]); }285 if (stderr == StdIo.Pipe) { os.posixClose(stderr_pipe[1]); }
176 if (any_ignore) { os.posixClose(dev_null_fd); }286 if (any_ignore) { os.posixClose(dev_null_fd); }
177287
178 return ChildProcess {288 return child;
179 .pid = i32(pid),
180 .err_pipe = err_pipe,
181
182 .stdin = if (stdin == StdIo.Pipe) {
183 io.OutStream {
184 .fd = stdin_pipe[1],
185 .handle = {},
186 .handle_id = {},
187 .buffer = undefined,
188 .index = 0,
189 }
190 } else {
191 null
192 },
193 .stdout = if (stdout == StdIo.Pipe) {
194 io.InStream {
195 .fd = stdout_pipe[0],
196 .handle = {},
197 .handle_id = {},
198 }
199 } else {
200 null
201 },
202 .stderr = if (stderr == StdIo.Pipe) {
203 io.InStream {
204 .fd = stderr_pipe[0],
205 .handle = {},
206 .handle_id = {},
207 }
208 } else {
209 null
210 },
211 };
212 }289 }
213290
214 fn setUpChildIo(stdio: StdIo, pipe_fd: i32, std_fileno: i32, dev_null_fd: i32) -> %void {291 fn setUpChildIo(stdio: StdIo, pipe_fd: i32, std_fileno: i32, dev_null_fd: i32) -> %void {
...@@ -258,3 +335,54 @@ fn readIntFd(fd: i32) -> %ErrInt {...@@ -258,3 +335,54 @@ fn readIntFd(fd: i32) -> %ErrInt {
258 os.posixRead(fd, bytes[0..]) %% return error.SystemResources;335 os.posixRead(fd, bytes[0..]) %% return error.SystemResources;
259 return mem.readInt(bytes[0..], ErrInt, true);336 return mem.readInt(bytes[0..], ErrInt, true);
260}337}
338
339extern fn sigchld_handler(_: i32) {
340 while (true) {
341 var status: i32 = undefined;
342 const pid_result = posix.waitpid(-1, &status, posix.WNOHANG);
343 const err = posix.getErrno(pid_result);
344 if (err == posix.ECHILD) {
345 return;
346 }
347 handleTerm(i32(pid_result), status);
348 }
349}
350
351fn handleTerm(pid: i32, status: i32) {
352 var it = children_nodes.first;
353 while (it) |node| : (it = node.next) {
354 if (node.data.pid == pid) {
355 assert(node.data.term == null);
356 node.data.handleWaitResult(status);
357 return;
358 }
359 }
360 unreachable;
361}
362
363const sigchld_set = {
364 var signal_set = posix.empty_sigset;
365 posix.sigaddset(&signal_set, posix.SIGCHLD);
366 signal_set
367};
368
369fn block_SIGCHLD() {
370 const err = posix.getErrno(posix.sigprocmask(posix.SIG_BLOCK, &sigchld_set, null));
371 assert(err == 0);
372}
373
374fn restore_SIGCHLD() {
375 const err = posix.getErrno(posix.sigprocmask(posix.SIG_UNBLOCK, &sigchld_set, null));
376 assert(err == 0);
377}
378
379const sigchld_action = posix.Sigaction {
380 .handler = sigchld_handler,
381 .mask = posix.empty_sigset,
382 .flags = posix.SA_RESTART | posix.SA_NOCLDSTOP,
383};
384
385fn install_SIGCHLD_handler() {
386 const err = posix.getErrno(posix.sigaction(posix.SIGCHLD, &sigchld_action, null));
387 assert(err == 0);
388}
std/os/linux.zig+83-8
...@@ -1,3 +1,4 @@...@@ -1,3 +1,4 @@
1const assert = @import("../debug.zig").assert;
1const builtin = @import("builtin");2const builtin = @import("builtin");
2const arch = switch (builtin.arch) {3const arch = switch (builtin.arch) {
3 builtin.Arch.x86_64 => @import("linux_x86_64.zig"),4 builtin.Arch.x86_64 => @import("linux_x86_64.zig"),
...@@ -36,6 +37,22 @@ pub const MAP_STACK = 0x20000;...@@ -36,6 +37,22 @@ pub const MAP_STACK = 0x20000;
36pub const MAP_HUGETLB = 0x40000;37pub const MAP_HUGETLB = 0x40000;
37pub const MAP_FILE = 0;38pub const MAP_FILE = 0;
3839
40pub const WNOHANG = 1;
41pub const WUNTRACED = 2;
42pub const WSTOPPED = 2;
43pub const WEXITED = 4;
44pub const WCONTINUED = 8;
45pub const WNOWAIT = 0x1000000;
46
47pub const SA_NOCLDSTOP = 1;
48pub const SA_NOCLDWAIT = 2;
49pub const SA_SIGINFO = 4;
50pub const SA_ONSTACK = 0x08000000;
51pub const SA_RESTART = 0x10000000;
52pub const SA_NODEFER = 0x40000000;
53pub const SA_RESETHAND = 0x80000000;
54pub const SA_RESTORER = 0x04000000;
55
39pub const SIGHUP = 1;56pub const SIGHUP = 1;
40pub const SIGINT = 2;57pub const SIGINT = 2;
41pub const SIGQUIT = 3;58pub const SIGQUIT = 3;
...@@ -100,9 +117,9 @@ pub const SEEK_SET = 0;...@@ -100,9 +117,9 @@ pub const SEEK_SET = 0;
100pub const SEEK_CUR = 1;117pub const SEEK_CUR = 1;
101pub const SEEK_END = 2;118pub const SEEK_END = 2;
102119
103const SIG_BLOCK = 0;120pub const SIG_BLOCK = 0;
104const SIG_UNBLOCK = 1;121pub const SIG_UNBLOCK = 1;
105const SIG_SETMASK = 2;122pub const SIG_SETMASK = 2;
106123
107pub const SOCK_STREAM = 1;124pub const SOCK_STREAM = 1;
108pub const SOCK_DGRAM = 2;125pub const SOCK_DGRAM = 2;
...@@ -448,7 +465,7 @@ pub fn getrandom(buf: &u8, count: usize, flags: u32) -> usize {...@@ -448,7 +465,7 @@ pub fn getrandom(buf: &u8, count: usize, flags: u32) -> usize {
448}465}
449466
450pub fn kill(pid: i32, sig: i32) -> usize {467pub fn kill(pid: i32, sig: i32) -> usize {
451 arch.syscall2(arch.SYS_kill, usize(pid), usize(sig))468 arch.syscall2(arch.SYS_kill, @bitCast(usize, isize(pid)), usize(sig))
452}469}
453470
454pub fn unlink(path: &const u8) -> usize {471pub fn unlink(path: &const u8) -> usize {
...@@ -456,17 +473,65 @@ pub fn unlink(path: &const u8) -> usize {...@@ -456,17 +473,65 @@ pub fn unlink(path: &const u8) -> usize {
456}473}
457474
458pub fn waitpid(pid: i32, status: &i32, options: i32) -> usize {475pub fn waitpid(pid: i32, status: &i32, options: i32) -> usize {
459 arch.syscall4(arch.SYS_wait4, usize(pid), @ptrToInt(status), @bitCast(usize, isize(options)), 0)476 arch.syscall4(arch.SYS_wait4, @bitCast(usize, isize(pid)), @ptrToInt(status), @bitCast(usize, isize(options)), 0)
460}477}
461478
462pub fn nanosleep(req: &const timespec, rem: ?&timespec) -> usize {479pub fn nanosleep(req: &const timespec, rem: ?&timespec) -> usize {
463 arch.syscall2(arch.SYS_nanosleep, @ptrToInt(req), @ptrToInt(rem))480 arch.syscall2(arch.SYS_nanosleep, @ptrToInt(req), @ptrToInt(rem))
464}481}
465482
483pub fn sigprocmask(flags: u32, set: &const sigset_t, oldset: ?&sigset_t) -> usize {
484 arch.syscall4(arch.SYS_rt_sigprocmask, flags, @ptrToInt(set), @ptrToInt(oldset), NSIG/8)
485}
486
487pub fn sigaction(sig: u6, noalias act: &const Sigaction, noalias oact: ?&Sigaction) -> usize {
488 assert(sig >= 1);
489 assert(sig != SIGKILL);
490 assert(sig != SIGSTOP);
491 var ksa = k_sigaction {
492 .handler = act.handler,
493 .flags = act.flags | SA_RESTORER,
494 .mask = undefined,
495 .restorer = @ptrCast(extern fn(), arch.restore_rt),
496 };
497 var ksa_old: k_sigaction = undefined;
498 @memcpy(@ptrCast(&u8, &ksa.mask), @ptrCast(&const u8, &act.mask), 8);
499 const result = arch.syscall4(arch.SYS_rt_sigaction, sig, @ptrToInt(&ksa), @ptrToInt(&ksa_old), @sizeOf(@typeOf(ksa.mask)));
500 const err = getErrno(result);
501 if (err != 0) {
502 return result;
503 }
504 if (oact) |old| {
505 old.handler = ksa_old.handler;
506 old.flags = @truncate(u32, ksa_old.flags);
507 @memcpy(@ptrCast(&u8, &old.mask), @ptrCast(&const u8, &ksa_old.mask), @sizeOf(@typeOf(ksa_old.mask)));
508 }
509 return 0;
510}
511
466const NSIG = 65;512const NSIG = 65;
467const sigset_t = [128]u8;513const sigset_t = [128 / @sizeOf(usize)]usize;
468const all_mask = []u8 { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, };514const all_mask = []usize{@maxValue(usize)};
469const app_mask = []u8 { 0xff, 0xff, 0xff, 0xfc, 0x7f, 0xff, 0xff, 0xff, };515const app_mask = []usize{0xfffffffc7fffffff};
516
517const k_sigaction = extern struct {
518 handler: extern fn(i32),
519 flags: usize,
520 restorer: extern fn(),
521 mask: [2]u32,
522};
523
524/// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall.
525pub const Sigaction = struct {
526 handler: extern fn(i32),
527 mask: sigset_t,
528 flags: u32,
529};
530
531pub const SIG_ERR = @intToPtr(extern fn(i32), @maxValue(usize));
532pub const SIG_DFL = @intToPtr(extern fn(i32), 0);
533pub const SIG_IGN = @intToPtr(extern fn(i32), 1);
534pub const empty_sigset = []usize{0} ** sigset_t.len;
470535
471pub fn raise(sig: i32) -> usize {536pub fn raise(sig: i32) -> usize {
472 var set: sigset_t = undefined;537 var set: sigset_t = undefined;
...@@ -489,6 +554,16 @@ fn restoreSignals(set: &sigset_t) {...@@ -489,6 +554,16 @@ fn restoreSignals(set: &sigset_t) {
489 _ = arch.syscall4(arch.SYS_rt_sigprocmask, SIG_SETMASK, @ptrToInt(set), 0, NSIG/8);554 _ = arch.syscall4(arch.SYS_rt_sigprocmask, SIG_SETMASK, @ptrToInt(set), 0, NSIG/8);
490}555}
491556
557pub fn sigaddset(set: &sigset_t, sig: u6) {
558 const s = sig - 1;
559 (*set)[usize(s) / usize.bit_count] |= usize(1) << (s & (usize.bit_count - 1));
560}
561
562pub fn sigismember(set: &const sigset_t, sig: u6) -> bool {
563 const s = sig - 1;
564 return ((*set)[usize(s) / usize.bit_count] & (usize(1) << (s & (usize.bit_count - 1)))) != 0;
565}
566
492567
493pub const sa_family_t = u16;568pub const sa_family_t = u16;
494pub const socklen_t = u32;569pub const socklen_t = u32;
std/os/linux_i386.zig+17
...@@ -486,6 +486,23 @@ pub inline fn syscall6(number: usize, arg1: usize, arg2: usize, arg3: usize,...@@ -486,6 +486,23 @@ pub inline fn syscall6(number: usize, arg1: usize, arg2: usize, arg3: usize,
486 [arg6] "{ebp}" (arg6))486 [arg6] "{ebp}" (arg6))
487}487}
488488
489pub nakedcc fn restore() {
490 asm volatile (
491 \\popl %%eax
492 \\movl $119, %%eax
493 \\int $0x80
494 :
495 :
496 : "rcx", "r11")
497}
498
499pub nakedcc fn restore_rt() {
500 asm volatile ("int $0x80"
501 :
502 : [number] "{eax}" (usize(SYS_rt_sigreturn))
503 : "rcx", "r11")
504}
505
489export struct msghdr {506export struct msghdr {
490 msg_name: &u8,507 msg_name: &u8,
491 msg_namelen: socklen_t,508 msg_namelen: socklen_t,
std/os/linux_x86_64.zig+8
...@@ -442,6 +442,14 @@ pub fn syscall6(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz...@@ -442,6 +442,14 @@ pub fn syscall6(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz
442 : "rcx", "r11")442 : "rcx", "r11")
443}443}
444444
445pub nakedcc fn restore_rt() {
446 asm volatile ("syscall"
447 :
448 : [number] "{rax}" (usize(SYS_rt_sigreturn))
449 : "rcx", "r11")
450}
451
452
445pub const msghdr = extern struct {453pub const msghdr = extern struct {
446 msg_name: &u8,454 msg_name: &u8,
447 msg_namelen: socklen_t,455 msg_namelen: socklen_t,
test/cases/array.zig+10
...@@ -86,3 +86,13 @@ test "array literal with specified size" {...@@ -86,3 +86,13 @@ test "array literal with specified size" {
86 assert(array[0] == 1);86 assert(array[0] == 1);
87 assert(array[1] == 2);87 assert(array[1] == 2);
88}88}
89
90test "array child property" {
91 var x: [5]i32 = undefined;
92 assert(@typeOf(x).child == i32);
93}
94
95test "array len property" {
96 var x: [5]i32 = undefined;
97 assert(@typeOf(x).len == 5);
98}
test/tests.zig+8-8
...@@ -238,7 +238,7 @@ pub const CompareOutputContext = struct {...@@ -238,7 +238,7 @@ pub const CompareOutputContext = struct {
238 %%io.stderr.printf("Test {}/{} {}...", self.test_index+1, self.context.test_index, self.name);238 %%io.stderr.printf("Test {}/{} {}...", self.test_index+1, self.context.test_index, self.name);
239239
240 var child = os.ChildProcess.spawn(full_exe_path, [][]u8{}, null, &b.env_map,240 var child = os.ChildProcess.spawn(full_exe_path, [][]u8{}, null, &b.env_map,
241 StdIo.Ignore, StdIo.Pipe, StdIo.Pipe, b.allocator) %% |err|241 StdIo.Ignore, StdIo.Pipe, StdIo.Pipe, null, b.allocator) %% |err|
242 {242 {
243 debug.panic("Unable to spawn {}: {}\n", full_exe_path, @errorName(err));243 debug.panic("Unable to spawn {}: {}\n", full_exe_path, @errorName(err));
244 };244 };
...@@ -253,7 +253,7 @@ pub const CompareOutputContext = struct {...@@ -253,7 +253,7 @@ pub const CompareOutputContext = struct {
253 debug.panic("Unable to spawn {}: {}\n", full_exe_path, @errorName(err));253 debug.panic("Unable to spawn {}: {}\n", full_exe_path, @errorName(err));
254 };254 };
255 switch (term) {255 switch (term) {
256 Term.Clean => |code| {256 Term.Exited => |code| {
257 if (code != 0) {257 if (code != 0) {
258 %%io.stderr.printf("Process {} exited with error code {}\n", full_exe_path, code);258 %%io.stderr.printf("Process {} exited with error code {}\n", full_exe_path, code);
259 return error.TestFailed;259 return error.TestFailed;
...@@ -313,7 +313,7 @@ pub const CompareOutputContext = struct {...@@ -313,7 +313,7 @@ pub const CompareOutputContext = struct {
313 %%io.stderr.printf("Test {}/{} {}...", self.test_index+1, self.context.test_index, self.name);313 %%io.stderr.printf("Test {}/{} {}...", self.test_index+1, self.context.test_index, self.name);
314314
315 var child = os.ChildProcess.spawn(full_exe_path, [][]u8{}, null, &b.env_map,315 var child = os.ChildProcess.spawn(full_exe_path, [][]u8{}, null, &b.env_map,
316 StdIo.Ignore, StdIo.Pipe, StdIo.Pipe, b.allocator) %% |err|316 StdIo.Ignore, StdIo.Pipe, StdIo.Pipe, null, b.allocator) %% |err|
317 {317 {
318 debug.panic("Unable to spawn {}: {}\n", full_exe_path, @errorName(err));318 debug.panic("Unable to spawn {}: {}\n", full_exe_path, @errorName(err));
319 };319 };
...@@ -324,7 +324,7 @@ pub const CompareOutputContext = struct {...@@ -324,7 +324,7 @@ pub const CompareOutputContext = struct {
324324
325 const debug_trap_signal: i32 = 5;325 const debug_trap_signal: i32 = 5;
326 switch (term) {326 switch (term) {
327 Term.Clean => |code| {327 Term.Exited => |code| {
328 %%io.stderr.printf("\nProgram expected to hit debug trap (signal {}) " ++328 %%io.stderr.printf("\nProgram expected to hit debug trap (signal {}) " ++
329 "but exited with return code {}\n", debug_trap_signal, code);329 "but exited with return code {}\n", debug_trap_signal, code);
330 return error.TestFailed;330 return error.TestFailed;
...@@ -557,7 +557,7 @@ pub const CompileErrorContext = struct {...@@ -557,7 +557,7 @@ pub const CompileErrorContext = struct {
557 }557 }
558558
559 var child = os.ChildProcess.spawn(b.zig_exe, zig_args.toSliceConst(), null, &b.env_map,559 var child = os.ChildProcess.spawn(b.zig_exe, zig_args.toSliceConst(), null, &b.env_map,
560 StdIo.Ignore, StdIo.Pipe, StdIo.Pipe, b.allocator) %% |err|560 StdIo.Ignore, StdIo.Pipe, StdIo.Pipe, null, b.allocator) %% |err|
561 {561 {
562 debug.panic("Unable to spawn {}: {}\n", b.zig_exe, @errorName(err));562 debug.panic("Unable to spawn {}: {}\n", b.zig_exe, @errorName(err));
563 };563 };
...@@ -572,7 +572,7 @@ pub const CompileErrorContext = struct {...@@ -572,7 +572,7 @@ pub const CompileErrorContext = struct {
572 debug.panic("Unable to spawn {}: {}\n", b.zig_exe, @errorName(err));572 debug.panic("Unable to spawn {}: {}\n", b.zig_exe, @errorName(err));
573 };573 };
574 switch (term) {574 switch (term) {
575 Term.Clean => |code| {575 Term.Exited => |code| {
576 if (code == 0) {576 if (code == 0) {
577 %%io.stderr.printf("Compilation incorrectly succeeded\n");577 %%io.stderr.printf("Compilation incorrectly succeeded\n");
578 return error.TestFailed;578 return error.TestFailed;
...@@ -819,7 +819,7 @@ pub const ParseCContext = struct {...@@ -819,7 +819,7 @@ pub const ParseCContext = struct {
819 }819 }
820820
821 var child = os.ChildProcess.spawn(b.zig_exe, zig_args.toSliceConst(), null, &b.env_map,821 var child = os.ChildProcess.spawn(b.zig_exe, zig_args.toSliceConst(), null, &b.env_map,
822 StdIo.Ignore, StdIo.Pipe, StdIo.Pipe, b.allocator) %% |err|822 StdIo.Ignore, StdIo.Pipe, StdIo.Pipe, null, b.allocator) %% |err|
823 {823 {
824 debug.panic("Unable to spawn {}: {}\n", b.zig_exe, @errorName(err));824 debug.panic("Unable to spawn {}: {}\n", b.zig_exe, @errorName(err));
825 };825 };
...@@ -834,7 +834,7 @@ pub const ParseCContext = struct {...@@ -834,7 +834,7 @@ pub const ParseCContext = struct {
834 debug.panic("Unable to spawn {}: {}\n", b.zig_exe, @errorName(err));834 debug.panic("Unable to spawn {}: {}\n", b.zig_exe, @errorName(err));
835 };835 };
836 switch (term) {836 switch (term) {
837 Term.Clean => |code| {837 Term.Exited => |code| {
838 if (code != 0) {838 if (code != 0) {
839 %%io.stderr.printf("Compilation failed with exit code {}\n", code);839 %%io.stderr.printf("Compilation failed with exit code {}\n", code);
840 return error.TestFailed;840 return error.TestFailed;