xref: /libuv/src/unix/signal.c (revision 10f31363)
1 /* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
2  * Permission is hereby granted, free of charge, to any person obtaining a copy
3  * of this software and associated documentation files (the "Software"), to
4  * deal in the Software without restriction, including without limitation the
5  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
6  * sell copies of the Software, and to permit persons to whom the Software is
7  * furnished to do so, subject to the following conditions:
8  *
9  * The above copyright notice and this permission notice shall be included in
10  * all copies or substantial portions of the Software.
11  *
12  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
13  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
15  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
16  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
17  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
18  * IN THE SOFTWARE.
19  */
20 
21 #include "uv.h"
22 #include "internal.h"
23 
24 #include <assert.h>
25 #include <errno.h>
26 #include <signal.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <unistd.h>
30 
31 #ifndef SA_RESTART
32 # define SA_RESTART 0
33 #endif
34 
35 typedef struct {
36   uv_signal_t* handle;
37   int signum;
38 } uv__signal_msg_t;
39 
40 RB_HEAD(uv__signal_tree_s, uv_signal_s);
41 
42 
43 static int uv__signal_unlock(void);
44 static int uv__signal_start(uv_signal_t* handle,
45                             uv_signal_cb signal_cb,
46                             int signum,
47                             int oneshot);
48 static void uv__signal_event(uv_loop_t* loop, uv__io_t* w, unsigned int events);
49 static int uv__signal_compare(uv_signal_t* w1, uv_signal_t* w2);
50 static void uv__signal_stop(uv_signal_t* handle);
51 static void uv__signal_unregister_handler(int signum);
52 
53 
54 static uv_once_t uv__signal_global_init_guard = UV_ONCE_INIT;
55 static struct uv__signal_tree_s uv__signal_tree =
56     RB_INITIALIZER(uv__signal_tree);
57 static int uv__signal_lock_pipefd[2] = { -1, -1 };
58 
59 RB_GENERATE_STATIC(uv__signal_tree_s,
60                    uv_signal_s, tree_entry,
61                    uv__signal_compare)
62 
63 static void uv__signal_global_reinit(void);
64 
uv__signal_global_init(void)65 static void uv__signal_global_init(void) {
66   if (uv__signal_lock_pipefd[0] == -1)
67     /* pthread_atfork can register before and after handlers, one
68      * for each child. This only registers one for the child. That
69      * state is both persistent and cumulative, so if we keep doing
70      * it the handler functions will be called multiple times. Thus
71      * we only want to do it once.
72      */
73     if (pthread_atfork(NULL, NULL, &uv__signal_global_reinit))
74       abort();
75 
76   uv__signal_global_reinit();
77 }
78 
79 
uv__signal_cleanup(void)80 void uv__signal_cleanup(void) {
81   /* We can only use signal-safe functions here.
82    * That includes read/write and close, fortunately.
83    * We do all of this directly here instead of resetting
84    * uv__signal_global_init_guard because
85    * uv__signal_global_once_init is only called from uv_loop_init
86    * and this needs to function in existing loops.
87    */
88   if (uv__signal_lock_pipefd[0] != -1) {
89     uv__close(uv__signal_lock_pipefd[0]);
90     uv__signal_lock_pipefd[0] = -1;
91   }
92 
93   if (uv__signal_lock_pipefd[1] != -1) {
94     uv__close(uv__signal_lock_pipefd[1]);
95     uv__signal_lock_pipefd[1] = -1;
96   }
97 }
98 
99 
uv__signal_global_reinit(void)100 static void uv__signal_global_reinit(void) {
101   uv__signal_cleanup();
102 
103   if (uv__make_pipe(uv__signal_lock_pipefd, 0))
104     abort();
105 
106   if (uv__signal_unlock())
107     abort();
108 }
109 
110 
uv__signal_global_once_init(void)111 void uv__signal_global_once_init(void) {
112   uv_once(&uv__signal_global_init_guard, uv__signal_global_init);
113 }
114 
115 
uv__signal_lock(void)116 static int uv__signal_lock(void) {
117   int r;
118   char data;
119 
120   do {
121     r = read(uv__signal_lock_pipefd[0], &data, sizeof data);
122   } while (r < 0 && errno == EINTR);
123 
124   return (r < 0) ? -1 : 0;
125 }
126 
127 
uv__signal_unlock(void)128 static int uv__signal_unlock(void) {
129   int r;
130   char data = 42;
131 
132   do {
133     r = write(uv__signal_lock_pipefd[1], &data, sizeof data);
134   } while (r < 0 && errno == EINTR);
135 
136   return (r < 0) ? -1 : 0;
137 }
138 
139 
uv__signal_block_and_lock(sigset_t * saved_sigmask)140 static void uv__signal_block_and_lock(sigset_t* saved_sigmask) {
141   sigset_t new_mask;
142 
143   if (sigfillset(&new_mask))
144     abort();
145 
146   /* to shut up valgrind */
147   sigemptyset(saved_sigmask);
148   if (pthread_sigmask(SIG_SETMASK, &new_mask, saved_sigmask))
149     abort();
150 
151   if (uv__signal_lock())
152     abort();
153 }
154 
155 
uv__signal_unlock_and_unblock(sigset_t * saved_sigmask)156 static void uv__signal_unlock_and_unblock(sigset_t* saved_sigmask) {
157   if (uv__signal_unlock())
158     abort();
159 
160   if (pthread_sigmask(SIG_SETMASK, saved_sigmask, NULL))
161     abort();
162 }
163 
164 
uv__signal_first_handle(int signum)165 static uv_signal_t* uv__signal_first_handle(int signum) {
166   /* This function must be called with the signal lock held. */
167   uv_signal_t lookup;
168   uv_signal_t* handle;
169 
170   lookup.signum = signum;
171   lookup.flags = 0;
172   lookup.loop = NULL;
173 
174   handle = RB_NFIND(uv__signal_tree_s, &uv__signal_tree, &lookup);
175 
176   if (handle != NULL && handle->signum == signum)
177     return handle;
178 
179   return NULL;
180 }
181 
182 
uv__signal_handler(int signum)183 static void uv__signal_handler(int signum) {
184   uv__signal_msg_t msg;
185   uv_signal_t* handle;
186   int saved_errno;
187 
188   saved_errno = errno;
189   memset(&msg, 0, sizeof msg);
190 
191   if (uv__signal_lock()) {
192     errno = saved_errno;
193     return;
194   }
195 
196   for (handle = uv__signal_first_handle(signum);
197        handle != NULL && handle->signum == signum;
198        handle = RB_NEXT(uv__signal_tree_s, &uv__signal_tree, handle)) {
199     int r;
200 
201     msg.signum = signum;
202     msg.handle = handle;
203 
204     /* write() should be atomic for small data chunks, so the entire message
205      * should be written at once. In theory the pipe could become full, in
206      * which case the user is out of luck.
207      */
208     do {
209       r = write(handle->loop->signal_pipefd[1], &msg, sizeof msg);
210     } while (r == -1 && errno == EINTR);
211 
212     assert(r == sizeof msg ||
213            (r == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)));
214 
215     if (r != -1)
216       handle->caught_signals++;
217   }
218 
219   uv__signal_unlock();
220   errno = saved_errno;
221 }
222 
223 
uv__signal_register_handler(int signum,int oneshot)224 static int uv__signal_register_handler(int signum, int oneshot) {
225   /* When this function is called, the signal lock must be held. */
226   struct sigaction sa;
227 
228   /* XXX use a separate signal stack? */
229   memset(&sa, 0, sizeof(sa));
230   if (sigfillset(&sa.sa_mask))
231     abort();
232   sa.sa_handler = uv__signal_handler;
233   sa.sa_flags = SA_RESTART;
234   if (oneshot)
235     sa.sa_flags |= SA_RESETHAND;
236 
237   /* XXX save old action so we can restore it later on? */
238   if (sigaction(signum, &sa, NULL))
239     return UV__ERR(errno);
240 
241   return 0;
242 }
243 
244 
uv__signal_unregister_handler(int signum)245 static void uv__signal_unregister_handler(int signum) {
246   /* When this function is called, the signal lock must be held. */
247   struct sigaction sa;
248 
249   memset(&sa, 0, sizeof(sa));
250   sa.sa_handler = SIG_DFL;
251 
252   /* sigaction can only fail with EINVAL or EFAULT; an attempt to deregister a
253    * signal implies that it was successfully registered earlier, so EINVAL
254    * should never happen.
255    */
256   if (sigaction(signum, &sa, NULL))
257     abort();
258 }
259 
260 
uv__signal_loop_once_init(uv_loop_t * loop)261 static int uv__signal_loop_once_init(uv_loop_t* loop) {
262   int err;
263 
264   /* Return if already initialized. */
265   if (loop->signal_pipefd[0] != -1)
266     return 0;
267 
268   err = uv__make_pipe(loop->signal_pipefd, UV_NONBLOCK_PIPE);
269   if (err)
270     return err;
271 
272   uv__io_init(&loop->signal_io_watcher,
273               uv__signal_event,
274               loop->signal_pipefd[0]);
275   uv__io_start(loop, &loop->signal_io_watcher, POLLIN);
276 
277   return 0;
278 }
279 
280 
uv__signal_loop_fork(uv_loop_t * loop)281 int uv__signal_loop_fork(uv_loop_t* loop) {
282   struct uv__queue* q;
283 
284   if (loop->signal_pipefd[0] == -1)
285     return 0;
286   uv__io_stop(loop, &loop->signal_io_watcher, POLLIN);
287   uv__close(loop->signal_pipefd[0]);
288   uv__close(loop->signal_pipefd[1]);
289   loop->signal_pipefd[0] = -1;
290   loop->signal_pipefd[1] = -1;
291 
292   uv__queue_foreach(q, &loop->handle_queue) {
293     uv_handle_t* handle = uv__queue_data(q, uv_handle_t, handle_queue);
294     uv_signal_t* sh;
295 
296     if (handle->type != UV_SIGNAL)
297       continue;
298 
299     sh = (uv_signal_t*) handle;
300     sh->caught_signals = 0;
301     sh->dispatched_signals = 0;
302   }
303 
304   return uv__signal_loop_once_init(loop);
305 }
306 
307 
uv__signal_loop_cleanup(uv_loop_t * loop)308 void uv__signal_loop_cleanup(uv_loop_t* loop) {
309   struct uv__queue* q;
310 
311   /* Stop all the signal watchers that are still attached to this loop. This
312    * ensures that the (shared) signal tree doesn't contain any invalid entries
313    * entries, and that signal handlers are removed when appropriate.
314    * It's safe to use uv__queue_foreach here because the handles and the handle
315    * queue are not modified by uv__signal_stop().
316    */
317   uv__queue_foreach(q, &loop->handle_queue) {
318     uv_handle_t* handle = uv__queue_data(q, uv_handle_t, handle_queue);
319 
320     if (handle->type == UV_SIGNAL)
321       uv__signal_stop((uv_signal_t*) handle);
322   }
323 
324   if (loop->signal_pipefd[0] != -1) {
325     uv__close(loop->signal_pipefd[0]);
326     loop->signal_pipefd[0] = -1;
327   }
328 
329   if (loop->signal_pipefd[1] != -1) {
330     uv__close(loop->signal_pipefd[1]);
331     loop->signal_pipefd[1] = -1;
332   }
333 }
334 
335 
uv_signal_init(uv_loop_t * loop,uv_signal_t * handle)336 int uv_signal_init(uv_loop_t* loop, uv_signal_t* handle) {
337   int err;
338 
339   err = uv__signal_loop_once_init(loop);
340   if (err)
341     return err;
342 
343   uv__handle_init(loop, (uv_handle_t*) handle, UV_SIGNAL);
344   handle->signum = 0;
345   handle->caught_signals = 0;
346   handle->dispatched_signals = 0;
347 
348   return 0;
349 }
350 
351 
uv__signal_close(uv_signal_t * handle)352 void uv__signal_close(uv_signal_t* handle) {
353   uv__signal_stop(handle);
354 }
355 
356 
uv_signal_start(uv_signal_t * handle,uv_signal_cb signal_cb,int signum)357 int uv_signal_start(uv_signal_t* handle, uv_signal_cb signal_cb, int signum) {
358   return uv__signal_start(handle, signal_cb, signum, 0);
359 }
360 
361 
uv_signal_start_oneshot(uv_signal_t * handle,uv_signal_cb signal_cb,int signum)362 int uv_signal_start_oneshot(uv_signal_t* handle,
363                             uv_signal_cb signal_cb,
364                             int signum) {
365   return uv__signal_start(handle, signal_cb, signum, 1);
366 }
367 
368 
uv__signal_start(uv_signal_t * handle,uv_signal_cb signal_cb,int signum,int oneshot)369 static int uv__signal_start(uv_signal_t* handle,
370                             uv_signal_cb signal_cb,
371                             int signum,
372                             int oneshot) {
373   sigset_t saved_sigmask;
374   int err;
375   uv_signal_t* first_handle;
376 
377   assert(!uv__is_closing(handle));
378 
379   /* If the user supplies signum == 0, then return an error already. If the
380    * signum is otherwise invalid then uv__signal_register will find out
381    * eventually.
382    */
383   if (signum == 0)
384     return UV_EINVAL;
385 
386   /* Short circuit: if the signal watcher is already watching {signum} don't
387    * go through the process of deregistering and registering the handler.
388    * Additionally, this avoids pending signals getting lost in the small
389    * time frame that handle->signum == 0.
390    */
391   if (signum == handle->signum) {
392     handle->signal_cb = signal_cb;
393     return 0;
394   }
395 
396   /* If the signal handler was already active, stop it first. */
397   if (handle->signum != 0) {
398     uv__signal_stop(handle);
399   }
400 
401   uv__signal_block_and_lock(&saved_sigmask);
402 
403   /* If at this point there are no active signal watchers for this signum (in
404    * any of the loops), it's time to try and register a handler for it here.
405    * Also in case there's only one-shot handlers and a regular handler comes in.
406    */
407   first_handle = uv__signal_first_handle(signum);
408   if (first_handle == NULL ||
409       (!oneshot && (first_handle->flags & UV_SIGNAL_ONE_SHOT))) {
410     err = uv__signal_register_handler(signum, oneshot);
411     if (err) {
412       /* Registering the signal handler failed. Must be an invalid signal. */
413       uv__signal_unlock_and_unblock(&saved_sigmask);
414       return err;
415     }
416   }
417 
418   handle->signum = signum;
419   if (oneshot)
420     handle->flags |= UV_SIGNAL_ONE_SHOT;
421 
422   RB_INSERT(uv__signal_tree_s, &uv__signal_tree, handle);
423 
424   uv__signal_unlock_and_unblock(&saved_sigmask);
425 
426   handle->signal_cb = signal_cb;
427   uv__handle_start(handle);
428 
429   return 0;
430 }
431 
432 
uv__signal_event(uv_loop_t * loop,uv__io_t * w,unsigned int events)433 static void uv__signal_event(uv_loop_t* loop,
434                              uv__io_t* w,
435                              unsigned int events) {
436   uv__signal_msg_t* msg;
437   uv_signal_t* handle;
438   char buf[sizeof(uv__signal_msg_t) * 32];
439   size_t bytes, end, i;
440   int r;
441 
442   bytes = 0;
443   end = 0;
444 
445   do {
446     r = read(loop->signal_pipefd[0], buf + bytes, sizeof(buf) - bytes);
447 
448     if (r == -1 && errno == EINTR)
449       continue;
450 
451     if (r == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
452       /* If there are bytes in the buffer already (which really is extremely
453        * unlikely if possible at all) we can't exit the function here. We'll
454        * spin until more bytes are read instead.
455        */
456       if (bytes > 0)
457         continue;
458 
459       /* Otherwise, there was nothing there. */
460       return;
461     }
462 
463     /* Other errors really should never happen. */
464     if (r == -1)
465       abort();
466 
467     bytes += r;
468 
469     /* `end` is rounded down to a multiple of sizeof(uv__signal_msg_t). */
470     end = (bytes / sizeof(uv__signal_msg_t)) * sizeof(uv__signal_msg_t);
471 
472     for (i = 0; i < end; i += sizeof(uv__signal_msg_t)) {
473       msg = (uv__signal_msg_t*) (buf + i);
474       handle = msg->handle;
475 
476       if (msg->signum == handle->signum) {
477         assert(!(handle->flags & UV_HANDLE_CLOSING));
478         handle->signal_cb(handle, handle->signum);
479       }
480 
481       handle->dispatched_signals++;
482 
483       if (handle->flags & UV_SIGNAL_ONE_SHOT)
484         uv__signal_stop(handle);
485     }
486 
487     bytes -= end;
488 
489     /* If there are any "partial" messages left, move them to the start of the
490      * the buffer, and spin. This should not happen.
491      */
492     if (bytes) {
493       memmove(buf, buf + end, bytes);
494       continue;
495     }
496   } while (end == sizeof buf);
497 }
498 
499 
uv__signal_compare(uv_signal_t * w1,uv_signal_t * w2)500 static int uv__signal_compare(uv_signal_t* w1, uv_signal_t* w2) {
501   int f1;
502   int f2;
503   /* Compare signums first so all watchers with the same signnum end up
504    * adjacent.
505    */
506   if (w1->signum < w2->signum) return -1;
507   if (w1->signum > w2->signum) return 1;
508 
509   /* Handlers without UV_SIGNAL_ONE_SHOT set will come first, so if the first
510    * handler returned is a one-shot handler, the rest will be too.
511    */
512   f1 = w1->flags & UV_SIGNAL_ONE_SHOT;
513   f2 = w2->flags & UV_SIGNAL_ONE_SHOT;
514   if (f1 < f2) return -1;
515   if (f1 > f2) return 1;
516 
517   /* Sort by loop pointer, so we can easily look up the first item after
518    * { .signum = x, .loop = NULL }.
519    */
520   if (w1->loop < w2->loop) return -1;
521   if (w1->loop > w2->loop) return 1;
522 
523   if (w1 < w2) return -1;
524   if (w1 > w2) return 1;
525 
526   return 0;
527 }
528 
529 
uv_signal_stop(uv_signal_t * handle)530 int uv_signal_stop(uv_signal_t* handle) {
531   assert(!uv__is_closing(handle));
532   uv__signal_stop(handle);
533   return 0;
534 }
535 
536 
uv__signal_stop(uv_signal_t * handle)537 static void uv__signal_stop(uv_signal_t* handle) {
538   uv_signal_t* removed_handle;
539   sigset_t saved_sigmask;
540   uv_signal_t* first_handle;
541   int rem_oneshot;
542   int first_oneshot;
543   int ret;
544 
545   /* If the watcher wasn't started, this is a no-op. */
546   if (handle->signum == 0)
547     return;
548 
549   uv__signal_block_and_lock(&saved_sigmask);
550 
551   removed_handle = RB_REMOVE(uv__signal_tree_s, &uv__signal_tree, handle);
552   assert(removed_handle == handle);
553   (void) removed_handle;
554 
555   /* Check if there are other active signal watchers observing this signal. If
556    * not, unregister the signal handler.
557    */
558   first_handle = uv__signal_first_handle(handle->signum);
559   if (first_handle == NULL) {
560     uv__signal_unregister_handler(handle->signum);
561   } else {
562     rem_oneshot = handle->flags & UV_SIGNAL_ONE_SHOT;
563     first_oneshot = first_handle->flags & UV_SIGNAL_ONE_SHOT;
564     if (first_oneshot && !rem_oneshot) {
565       ret = uv__signal_register_handler(handle->signum, 1);
566       assert(ret == 0);
567       (void)ret;
568     }
569   }
570 
571   uv__signal_unlock_and_unblock(&saved_sigmask);
572 
573   handle->signum = 0;
574   uv__handle_stop(handle);
575 }
576