coverage: Make the coverage counters catalog program-specific.
[sliver-openvswitch.git] / lib / process.c
1 /*
2  * Copyright (c) 2008, 2009, 2010 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "process.h"
19 #include <assert.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <signal.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <sys/stat.h>
26 #include <sys/wait.h>
27 #include <unistd.h>
28 #include "coverage.h"
29 #include "dynamic-string.h"
30 #include "fatal-signal.h"
31 #include "list.h"
32 #include "poll-loop.h"
33 #include "socket-util.h"
34 #include "util.h"
35 #include "vlog.h"
36
37 VLOG_DEFINE_THIS_MODULE(process);
38
39 COVERAGE_DEFINE(process_run);
40 COVERAGE_DEFINE(process_run_capture);
41 COVERAGE_DEFINE(process_sigchld);
42 COVERAGE_DEFINE(process_start);
43
44 struct process {
45     struct list node;
46     char *name;
47     pid_t pid;
48
49     /* Modified by signal handler. */
50     volatile bool exited;
51     volatile int status;
52 };
53
54 /* Pipe used to signal child termination. */
55 static int fds[2];
56
57 /* All processes. */
58 static struct list all_processes = LIST_INITIALIZER(&all_processes);
59
60 static bool sigchld_is_blocked(void);
61 static void block_sigchld(sigset_t *);
62 static void unblock_sigchld(const sigset_t *);
63 static void sigchld_handler(int signr OVS_UNUSED);
64 static bool is_member(int x, const int *array, size_t);
65
66 /* Initializes the process subsystem (if it is not already initialized).  Calls
67  * exit() if initialization fails.
68  *
69  * Calling this function is optional; it will be called automatically by
70  * process_start() if necessary.  Calling it explicitly allows the client to
71  * prevent the process from exiting at an unexpected time. */
72 void
73 process_init(void)
74 {
75     static bool inited;
76     struct sigaction sa;
77
78     if (inited) {
79         return;
80     }
81     inited = true;
82
83     /* Create notification pipe. */
84     if (pipe(fds)) {
85         ovs_fatal(errno, "could not create pipe");
86     }
87     set_nonblocking(fds[0]);
88     set_nonblocking(fds[1]);
89
90     /* Set up child termination signal handler. */
91     memset(&sa, 0, sizeof sa);
92     sa.sa_handler = sigchld_handler;
93     sigemptyset(&sa.sa_mask);
94     sa.sa_flags = SA_NOCLDSTOP | SA_RESTART;
95     if (sigaction(SIGCHLD, &sa, NULL)) {
96         ovs_fatal(errno, "sigaction(SIGCHLD) failed");
97     }
98 }
99
100 char *
101 process_escape_args(char **argv)
102 {
103     struct ds ds = DS_EMPTY_INITIALIZER;
104     char **argp;
105     for (argp = argv; *argp; argp++) {
106         const char *arg = *argp;
107         const char *p;
108         if (argp != argv) {
109             ds_put_char(&ds, ' ');
110         }
111         if (arg[strcspn(arg, " \t\r\n\v\\\'\"")]) {
112             ds_put_char(&ds, '"');
113             for (p = arg; *p; p++) {
114                 if (*p == '\\' || *p == '\"') {
115                     ds_put_char(&ds, '\\');
116                 }
117                 ds_put_char(&ds, *p);
118             }
119             ds_put_char(&ds, '"');
120         } else {
121             ds_put_cstr(&ds, arg);
122         }
123     }
124     return ds_cstr(&ds);
125 }
126
127 /* Prepare to start a process whose command-line arguments are given by the
128  * null-terminated 'argv' array.  Returns 0 if successful, otherwise a
129  * positive errno value. */
130 static int
131 process_prestart(char **argv)
132 {
133     char *binary;
134
135     process_init();
136
137     /* Log the process to be started. */
138     if (VLOG_IS_DBG_ENABLED()) {
139         char *args = process_escape_args(argv);
140         VLOG_DBG("starting subprocess: %s", args);
141         free(args);
142     }
143
144     /* execvp() will search PATH too, but the error in that case is more
145      * obscure, since it is only reported post-fork. */
146     binary = process_search_path(argv[0]);
147     if (!binary) {
148         VLOG_ERR("%s not found in PATH", argv[0]);
149         return ENOENT;
150     }
151     free(binary);
152
153     return 0;
154 }
155
156 /* Creates and returns a new struct process with the specified 'name' and
157  * 'pid'.
158  *
159  * This is racy unless SIGCHLD is blocked (and has been blocked since before
160  * the fork()) that created the subprocess.  */
161 static struct process *
162 process_register(const char *name, pid_t pid)
163 {
164     struct process *p;
165     const char *slash;
166
167     assert(sigchld_is_blocked());
168
169     p = xzalloc(sizeof *p);
170     p->pid = pid;
171     slash = strrchr(name, '/');
172     p->name = xstrdup(slash ? slash + 1 : name);
173     p->exited = false;
174
175     list_push_back(&all_processes, &p->node);
176
177     return p;
178 }
179
180 /* Starts a subprocess with the arguments in the null-terminated argv[] array.
181  * argv[0] is used as the name of the process.  Searches the PATH environment
182  * variable to find the program to execute.
183  *
184  * All file descriptors are closed before executing the subprocess, except for
185  * fds 0, 1, and 2 and the 'n_keep_fds' fds listed in 'keep_fds'.  Also, any of
186  * the 'n_null_fds' fds listed in 'null_fds' are replaced by /dev/null.
187  *
188  * Returns 0 if successful, otherwise a positive errno value indicating the
189  * error.  If successful, '*pp' is assigned a new struct process that may be
190  * used to query the process's status.  On failure, '*pp' is set to NULL. */
191 int
192 process_start(char **argv,
193               const int keep_fds[], size_t n_keep_fds,
194               const int null_fds[], size_t n_null_fds,
195               struct process **pp)
196 {
197     sigset_t oldsigs;
198     pid_t pid;
199     int error;
200
201     *pp = NULL;
202     COVERAGE_INC(process_start);
203     error = process_prestart(argv);
204     if (error) {
205         return error;
206     }
207
208     block_sigchld(&oldsigs);
209     pid = fork();
210     if (pid < 0) {
211         unblock_sigchld(&oldsigs);
212         VLOG_WARN("fork failed: %s", strerror(errno));
213         return errno;
214     } else if (pid) {
215         /* Running in parent process. */
216         *pp = process_register(argv[0], pid);
217         unblock_sigchld(&oldsigs);
218         return 0;
219     } else {
220         /* Running in child process. */
221         int fd_max = get_max_fds();
222         int fd;
223
224         fatal_signal_fork();
225         unblock_sigchld(&oldsigs);
226         for (fd = 0; fd < fd_max; fd++) {
227             if (is_member(fd, null_fds, n_null_fds)) {
228                 /* We can't use get_null_fd() here because we might have
229                  * already closed its fd. */
230                 int nullfd = open("/dev/null", O_RDWR);
231                 dup2(nullfd, fd);
232                 close(nullfd);
233             } else if (fd >= 3 && !is_member(fd, keep_fds, n_keep_fds)) {
234                 close(fd);
235             }
236         }
237         execvp(argv[0], argv);
238         fprintf(stderr, "execvp(\"%s\") failed: %s\n",
239                 argv[0], strerror(errno));
240         _exit(1);
241     }
242 }
243
244 /* Destroys process 'p'. */
245 void
246 process_destroy(struct process *p)
247 {
248     if (p) {
249         sigset_t oldsigs;
250
251         block_sigchld(&oldsigs);
252         list_remove(&p->node);
253         unblock_sigchld(&oldsigs);
254
255         free(p->name);
256         free(p);
257     }
258 }
259
260 /* Sends signal 'signr' to process 'p'.  Returns 0 if successful, otherwise a
261  * positive errno value. */
262 int
263 process_kill(const struct process *p, int signr)
264 {
265     return (p->exited ? ESRCH
266             : !kill(p->pid, signr) ? 0
267             : errno);
268 }
269
270 /* Returns the pid of process 'p'. */
271 pid_t
272 process_pid(const struct process *p)
273 {
274     return p->pid;
275 }
276
277 /* Returns the name of process 'p' (the name passed to process_start() with any
278  * leading directories stripped). */
279 const char *
280 process_name(const struct process *p)
281 {
282     return p->name;
283 }
284
285 /* Returns true if process 'p' has exited, false otherwise. */
286 bool
287 process_exited(struct process *p)
288 {
289     if (p->exited) {
290         return true;
291     } else {
292         char buf[_POSIX_PIPE_BUF];
293         ignore(read(fds[0], buf, sizeof buf));
294         return false;
295     }
296 }
297
298 /* Returns process 'p''s exit status, as reported by waitpid(2).
299  * process_status(p) may be called only after process_exited(p) has returned
300  * true. */
301 int
302 process_status(const struct process *p)
303 {
304     assert(p->exited);
305     return p->status;
306 }
307
308 int
309 process_run(char **argv,
310             const int keep_fds[], size_t n_keep_fds,
311             const int null_fds[], size_t n_null_fds,
312             int *status)
313 {
314     struct process *p;
315     int retval;
316
317     COVERAGE_INC(process_run);
318     retval = process_start(argv, keep_fds, n_keep_fds, null_fds, n_null_fds,
319                            &p);
320     if (retval) {
321         *status = 0;
322         return retval;
323     }
324
325     while (!process_exited(p)) {
326         process_wait(p);
327         poll_block();
328     }
329     *status = process_status(p);
330     process_destroy(p);
331     return 0;
332 }
333
334 /* Given 'status', which is a process status in the form reported by waitpid(2)
335  * and returned by process_status(), returns a string describing how the
336  * process terminated.  The caller is responsible for freeing the string when
337  * it is no longer needed. */
338 char *
339 process_status_msg(int status)
340 {
341     struct ds ds = DS_EMPTY_INITIALIZER;
342     if (WIFEXITED(status)) {
343         ds_put_format(&ds, "exit status %d", WEXITSTATUS(status));
344     } else if (WIFSIGNALED(status) || WIFSTOPPED(status)) {
345         int signr = WIFSIGNALED(status) ? WTERMSIG(status) : WSTOPSIG(status);
346         const char *name = NULL;
347 #ifdef HAVE_STRSIGNAL
348         name = strsignal(signr);
349 #endif
350         ds_put_format(&ds, "%s by signal %d",
351                       WIFSIGNALED(status) ? "killed" : "stopped", signr);
352         if (name) {
353             ds_put_format(&ds, " (%s)", name);
354         }
355     } else {
356         ds_put_format(&ds, "terminated abnormally (%x)", status);
357     }
358     if (WCOREDUMP(status)) {
359         ds_put_cstr(&ds, ", core dumped");
360     }
361     return ds_cstr(&ds);
362 }
363
364 /* Causes the next call to poll_block() to wake up when process 'p' has
365  * exited. */
366 void
367 process_wait(struct process *p)
368 {
369     if (p->exited) {
370         poll_immediate_wake();
371     } else {
372         poll_fd_wait(fds[0], POLLIN);
373     }
374 }
375
376 char *
377 process_search_path(const char *name)
378 {
379     char *save_ptr = NULL;
380     char *path, *dir;
381     struct stat s;
382
383     if (strchr(name, '/') || !getenv("PATH")) {
384         return stat(name, &s) == 0 ? xstrdup(name) : NULL;
385     }
386
387     path = xstrdup(getenv("PATH"));
388     for (dir = strtok_r(path, ":", &save_ptr); dir;
389          dir = strtok_r(NULL, ":", &save_ptr)) {
390         char *file = xasprintf("%s/%s", dir, name);
391         if (stat(file, &s) == 0) {
392             free(path);
393             return file;
394         }
395         free(file);
396     }
397     free(path);
398     return NULL;
399 }
400 \f
401 /* process_run_capture() and supporting functions. */
402
403 struct stream {
404     struct ds log;
405     int fds[2];
406 };
407
408 static int
409 stream_open(struct stream *s)
410 {
411     ds_init(&s->log);
412     if (pipe(s->fds)) {
413         VLOG_WARN("failed to create pipe: %s", strerror(errno));
414         return errno;
415     }
416     set_nonblocking(s->fds[0]);
417     return 0;
418 }
419
420 static void
421 stream_read(struct stream *s)
422 {
423     if (s->fds[0] < 0) {
424         return;
425     }
426
427     for (;;) {
428         char buffer[512];
429         int error;
430         size_t n;
431
432         error = read_fully(s->fds[0], buffer, sizeof buffer, &n);
433         ds_put_buffer(&s->log, buffer, n);
434         if (error) {
435             if (error == EAGAIN || error == EWOULDBLOCK) {
436                 return;
437             } else {
438                 if (error != EOF) {
439                     VLOG_WARN("error reading subprocess pipe: %s",
440                               strerror(error));
441                 }
442                 break;
443             }
444         } else if (s->log.length > PROCESS_MAX_CAPTURE) {
445             VLOG_WARN("subprocess output overflowed %d-byte buffer",
446                       PROCESS_MAX_CAPTURE);
447             break;
448         }
449     }
450     close(s->fds[0]);
451     s->fds[0] = -1;
452 }
453
454 static void
455 stream_wait(struct stream *s)
456 {
457     if (s->fds[0] >= 0) {
458         poll_fd_wait(s->fds[0], POLLIN);
459     }
460 }
461
462 static void
463 stream_close(struct stream *s)
464 {
465     ds_destroy(&s->log);
466     if (s->fds[0] >= 0) {
467         close(s->fds[0]);
468     }
469     if (s->fds[1] >= 0) {
470         close(s->fds[1]);
471     }
472 }
473
474 /* Starts the process whose arguments are given in the null-terminated array
475  * 'argv' and waits for it to exit.  On success returns 0 and stores the
476  * process exit value (suitable for passing to process_status_msg()) in
477  * '*status'.  On failure, returns a positive errno value and stores 0 in
478  * '*status'.
479  *
480  * If 'stdout_log' is nonnull, then the subprocess's output to stdout (up to a
481  * limit of PROCESS_MAX_CAPTURE bytes) is captured in a memory buffer, which
482  * when this function returns 0 is stored as a null-terminated string in
483  * '*stdout_log'.  The caller is responsible for freeing '*stdout_log' (by
484  * passing it to free()).  When this function returns an error, '*stdout_log'
485  * is set to NULL.
486  *
487  * If 'stderr_log' is nonnull, then it is treated like 'stdout_log' except
488  * that it captures the subprocess's output to stderr. */
489 int
490 process_run_capture(char **argv, char **stdout_log, char **stderr_log,
491                     int *status)
492 {
493     struct stream s_stdout, s_stderr;
494     sigset_t oldsigs;
495     pid_t pid;
496     int error;
497
498     COVERAGE_INC(process_run_capture);
499     if (stdout_log) {
500         *stdout_log = NULL;
501     }
502     if (stderr_log) {
503         *stderr_log = NULL;
504     }
505     *status = 0;
506     error = process_prestart(argv);
507     if (error) {
508         return error;
509     }
510
511     error = stream_open(&s_stdout);
512     if (error) {
513         return error;
514     }
515
516     error = stream_open(&s_stderr);
517     if (error) {
518         stream_close(&s_stdout);
519         return error;
520     }
521
522     block_sigchld(&oldsigs);
523     pid = fork();
524     if (pid < 0) {
525         error = errno;
526
527         unblock_sigchld(&oldsigs);
528         VLOG_WARN("fork failed: %s", strerror(error));
529
530         stream_close(&s_stdout);
531         stream_close(&s_stderr);
532         *status = 0;
533         return error;
534     } else if (pid) {
535         /* Running in parent process. */
536         struct process *p;
537
538         p = process_register(argv[0], pid);
539         unblock_sigchld(&oldsigs);
540
541         close(s_stdout.fds[1]);
542         close(s_stderr.fds[1]);
543         while (!process_exited(p)) {
544             stream_read(&s_stdout);
545             stream_read(&s_stderr);
546
547             stream_wait(&s_stdout);
548             stream_wait(&s_stderr);
549             process_wait(p);
550             poll_block();
551         }
552         stream_read(&s_stdout);
553         stream_read(&s_stderr);
554
555         if (stdout_log) {
556             *stdout_log = ds_steal_cstr(&s_stdout.log);
557         }
558         if (stderr_log) {
559             *stderr_log = ds_steal_cstr(&s_stderr.log);
560         }
561
562         stream_close(&s_stdout);
563         stream_close(&s_stderr);
564
565         *status = process_status(p);
566         process_destroy(p);
567         return 0;
568     } else {
569         /* Running in child process. */
570         int max_fds;
571         int i;
572
573         fatal_signal_fork();
574         unblock_sigchld(&oldsigs);
575
576         dup2(get_null_fd(), 0);
577         dup2(s_stdout.fds[1], 1);
578         dup2(s_stderr.fds[1], 2);
579
580         max_fds = get_max_fds();
581         for (i = 3; i < max_fds; i++) {
582             close(i);
583         }
584
585         execvp(argv[0], argv);
586         fprintf(stderr, "execvp(\"%s\") failed: %s\n",
587                 argv[0], strerror(errno));
588         exit(EXIT_FAILURE);
589     }
590 }
591 \f
592 static void
593 sigchld_handler(int signr OVS_UNUSED)
594 {
595     struct process *p;
596
597     COVERAGE_INC(process_sigchld);
598     LIST_FOR_EACH (p, node, &all_processes) {
599         if (!p->exited) {
600             int retval, status;
601             do {
602                 retval = waitpid(p->pid, &status, WNOHANG);
603             } while (retval == -1 && errno == EINTR);
604             if (retval == p->pid) {
605                 p->exited = true;
606                 p->status = status;
607             } else if (retval < 0) {
608                 /* XXX We want to log something but we're in a signal
609                  * handler. */
610                 p->exited = true;
611                 p->status = -1;
612             }
613         }
614     }
615     ignore(write(fds[1], "", 1));
616 }
617
618 static bool
619 is_member(int x, const int *array, size_t n)
620 {
621     size_t i;
622
623     for (i = 0; i < n; i++) {
624         if (array[i] == x) {
625             return true;
626         }
627     }
628     return false;
629 }
630
631 static bool
632 sigchld_is_blocked(void)
633 {
634     sigset_t sigs;
635     if (sigprocmask(SIG_SETMASK, NULL, &sigs)) {
636         ovs_fatal(errno, "sigprocmask");
637     }
638     return sigismember(&sigs, SIGCHLD);
639 }
640
641 static void
642 block_sigchld(sigset_t *oldsigs)
643 {
644     sigset_t sigchld;
645     sigemptyset(&sigchld);
646     sigaddset(&sigchld, SIGCHLD);
647     if (sigprocmask(SIG_BLOCK, &sigchld, oldsigs)) {
648         ovs_fatal(errno, "sigprocmask");
649     }
650 }
651
652 static void
653 unblock_sigchld(const sigset_t *oldsigs)
654 {
655     if (sigprocmask(SIG_SETMASK, oldsigs, NULL)) {
656         ovs_fatal(errno, "sigprocmask");
657     }
658 }