Coverage Report

Created: 2026-05-30 06:26

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openvswitch/lib/process.c
Line
Count
Source
1
/*
2
 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
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 <errno.h>
20
#include <fcntl.h>
21
#include <signal.h>
22
#include <stdlib.h>
23
#include <string.h>
24
#include <sys/resource.h>
25
#include <sys/stat.h>
26
#include <sys/wait.h>
27
#include <unistd.h>
28
#include "coverage.h"
29
#include "openvswitch/dynamic-string.h"
30
#include "fatal-signal.h"
31
#include "openvswitch/list.h"
32
#include "ovs-thread.h"
33
#include "openvswitch/poll-loop.h"
34
#include "signals.h"
35
#include "socket-util.h"
36
#include "timeval.h"
37
#include "util.h"
38
#include "openvswitch/vlog.h"
39
40
VLOG_DEFINE_THIS_MODULE(process);
41
42
COVERAGE_DEFINE(process_start);
43
44
#ifdef __linux__
45
0
#define LINUX 1
46
#include <asm/param.h>
47
#else
48
#define LINUX 0
49
#endif
50
51
struct process {
52
    struct ovs_list node;
53
    char *name;
54
    pid_t pid;
55
56
    /* State. */
57
    bool exited;
58
    int status;
59
};
60
61
struct raw_process_info {
62
    unsigned long int vsz;      /* Virtual size, in kB. */
63
    unsigned long int rss;      /* Resident set size, in kB. */
64
    long long int uptime;       /* ms since started. */
65
    long long int cputime;      /* ms of CPU used during 'uptime'. */
66
    pid_t ppid;                 /* Parent. */
67
    int core_id;                /* Core id last executed on. */
68
    char name[18];              /* Name. */
69
};
70
71
/* Pipe used to signal child termination. */
72
static int fds[2];
73
74
/* All processes. */
75
static struct ovs_list all_processes = OVS_LIST_INITIALIZER(&all_processes);
76
77
static void sigchld_handler(int signr OVS_UNUSED);
78
79
/* Initializes the process subsystem (if it is not already initialized).  Calls
80
 * exit() if initialization fails.
81
 *
82
 * This function may not be called after creating any additional threads.
83
 *
84
 * Calling this function is optional; it will be called automatically by
85
 * process_start() if necessary.  Calling it explicitly allows the client to
86
 * prevent the process from exiting at an unexpected time. */
87
void
88
process_init(void)
89
0
{
90
0
    static bool inited;
91
0
    struct sigaction sa;
92
93
0
    assert_single_threaded();
94
0
    if (inited) {
95
0
        return;
96
0
    }
97
0
    inited = true;
98
99
    /* Create notification pipe. */
100
0
    xpipe_nonblocking(fds);
101
102
    /* Set up child termination signal handler. */
103
0
    memset(&sa, 0, sizeof sa);
104
0
    sa.sa_handler = sigchld_handler;
105
0
    sigemptyset(&sa.sa_mask);
106
0
    sa.sa_flags = SA_NOCLDSTOP | SA_RESTART;
107
0
    xsigaction(SIGCHLD, &sa, NULL);
108
0
}
109
110
char *
111
process_escape_args(char **argv)
112
0
{
113
0
    struct ds ds = DS_EMPTY_INITIALIZER;
114
0
    char **argp;
115
0
    for (argp = argv; *argp; argp++) {
116
0
        const char *arg = *argp;
117
0
        const char *p;
118
0
        if (argp != argv) {
119
0
            ds_put_char(&ds, ' ');
120
0
        }
121
0
        if (arg[strcspn(arg, " \t\r\n\v\\\'\"")]) {
122
0
            ds_put_char(&ds, '"');
123
0
            for (p = arg; *p; p++) {
124
0
                if (*p == '\\' || *p == '\"') {
125
0
                    ds_put_char(&ds, '\\');
126
0
                }
127
0
                ds_put_char(&ds, *p);
128
0
            }
129
0
            ds_put_char(&ds, '"');
130
0
        } else {
131
0
            ds_put_cstr(&ds, arg);
132
0
        }
133
0
    }
134
0
    return ds_cstr(&ds);
135
0
}
136
137
/* Prepare to start a process whose command-line arguments are given by the
138
 * null-terminated 'argv' array.  Returns 0 if successful, otherwise a
139
 * positive errno value. */
140
static int
141
process_prestart(char **argv)
142
0
{
143
0
    char *binary;
144
145
0
    process_init();
146
147
    /* Log the process to be started. */
148
0
    if (VLOG_IS_DBG_ENABLED()) {
149
0
        char *args = process_escape_args(argv);
150
0
        VLOG_DBG("starting subprocess: %s", args);
151
0
        free(args);
152
0
    }
153
154
    /* execvp() will search PATH too, but the error in that case is more
155
     * obscure, since it is only reported post-fork. */
156
0
    binary = process_search_path(argv[0]);
157
0
    if (!binary) {
158
0
        VLOG_ERR("%s not found in PATH", argv[0]);
159
0
        return ENOENT;
160
0
    }
161
0
    free(binary);
162
163
0
    return 0;
164
0
}
165
166
/* Creates and returns a new struct process with the specified 'name' and
167
 * 'pid'. */
168
static struct process *
169
process_register(const char *name, pid_t pid)
170
0
{
171
0
    struct process *p;
172
0
    const char *slash;
173
174
0
    p = xzalloc(sizeof *p);
175
0
    p->pid = pid;
176
0
    slash = strrchr(name, '/');
177
0
    p->name = xstrdup(slash ? slash + 1 : name);
178
0
    p->exited = false;
179
180
0
    ovs_list_push_back(&all_processes, &p->node);
181
182
0
    return p;
183
0
}
184
185
static bool
186
rlim_is_finite(rlim_t limit)
187
0
{
188
0
    if (limit == RLIM_INFINITY) {
189
0
        return false;
190
0
    }
191
192
0
#ifdef RLIM_SAVED_CUR           /* FreeBSD 8.0 lacks RLIM_SAVED_CUR. */
193
0
    if (limit == RLIM_SAVED_CUR) {
194
0
        return false;
195
0
    }
196
0
#endif
197
198
0
#ifdef RLIM_SAVED_MAX           /* FreeBSD 8.0 lacks RLIM_SAVED_MAX. */
199
0
    if (limit == RLIM_SAVED_MAX) {
200
0
        return false;
201
0
    }
202
0
#endif
203
204
0
    return true;
205
0
}
206
207
/* Returns the maximum valid FD value, plus 1. */
208
static int
209
get_max_fds(void)
210
0
{
211
0
    static int max_fds;
212
213
0
    if (!max_fds) {
214
0
        struct rlimit r;
215
0
        if (!getrlimit(RLIMIT_NOFILE, &r) && rlim_is_finite(r.rlim_cur)) {
216
0
            max_fds = r.rlim_cur;
217
0
        } else {
218
0
            VLOG_WARN("failed to obtain fd limit, defaulting to 1024");
219
0
            max_fds = 1024;
220
0
        }
221
0
    }
222
223
0
    return max_fds;
224
0
}
225
226
/* Starts a subprocess with the arguments in the null-terminated argv[] array.
227
 * argv[0] is used as the name of the process.  Searches the PATH environment
228
 * variable to find the program to execute.
229
 *
230
 * This function may not be called after creating any additional threads.
231
 *
232
 * All file descriptors are closed before executing the subprocess, except for
233
 * fds 0, 1, and 2.
234
 *
235
 * Returns 0 if successful, otherwise a positive errno value indicating the
236
 * error.  If successful, '*pp' is assigned a new struct process that may be
237
 * used to query the process's status.  On failure, '*pp' is set to NULL. */
238
int
239
process_start(char **argv, struct process **pp)
240
0
{
241
0
    pid_t pid;
242
0
    int error;
243
0
    sigset_t prev_mask;
244
245
0
    assert_single_threaded();
246
247
0
    *pp = NULL;
248
0
    COVERAGE_INC(process_start);
249
0
    error = process_prestart(argv);
250
0
    if (error) {
251
0
        return error;
252
0
    }
253
254
0
    fatal_signal_block(&prev_mask);
255
0
    pid = fork();
256
0
    if (pid < 0) {
257
0
        VLOG_WARN("fork failed: %s", ovs_strerror(errno));
258
0
        error = errno;
259
0
    } else if (pid) {
260
        /* Running in parent process. */
261
0
        *pp = process_register(argv[0], pid);
262
0
        error = 0;
263
0
    } else {
264
        /* Running in child process. */
265
0
        int fd_max = get_max_fds();
266
0
        int fd;
267
268
0
        fatal_signal_fork();
269
0
        for (fd = 3; fd < fd_max; fd++) {
270
0
            close(fd);
271
0
        }
272
0
        xpthread_sigmask(SIG_SETMASK, &prev_mask, NULL);
273
0
        execvp(argv[0], argv);
274
0
        fprintf(stderr, "execvp(\"%s\") failed: %s\n",
275
0
                argv[0], ovs_strerror(errno));
276
0
        _exit(1);
277
0
    }
278
0
    xpthread_sigmask(SIG_SETMASK, &prev_mask, NULL);
279
0
    return error;
280
0
}
281
282
/* Destroys process 'p'. */
283
void
284
process_destroy(struct process *p)
285
0
{
286
0
    if (p) {
287
0
        ovs_list_remove(&p->node);
288
0
        free(p->name);
289
0
        free(p);
290
0
    }
291
0
}
292
293
/* Sends signal 'signr' to process 'p'.  Returns 0 if successful, otherwise a
294
 * positive errno value. */
295
int
296
process_kill(const struct process *p, int signr)
297
0
{
298
0
    return (p->exited ? ESRCH
299
0
            : !kill(p->pid, signr) ? 0
300
0
            : errno);
301
0
}
302
303
/* Returns the pid of process 'p'. */
304
pid_t
305
process_pid(const struct process *p)
306
0
{
307
0
    return p->pid;
308
0
}
309
310
/* Returns the name of process 'p' (the name passed to process_start() with any
311
 * leading directories stripped). */
312
const char *
313
process_name(const struct process *p)
314
0
{
315
0
    return p->name;
316
0
}
317
318
/* Returns true if process 'p' has exited, false otherwise. */
319
bool
320
process_exited(struct process *p)
321
0
{
322
0
    return p->exited;
323
0
}
324
325
/* Returns process 'p''s exit status, as reported by waitpid(2).
326
 * process_status(p) may be called only after process_exited(p) has returned
327
 * true. */
328
int
329
process_status(const struct process *p)
330
0
{
331
0
    ovs_assert(p->exited);
332
0
    return p->status;
333
0
}
334
335
int
336
count_crashes(pid_t pid)
337
0
{
338
0
    char file_name[128];
339
0
    const char *paren;
340
0
    char line[128];
341
0
    int crashes = 0;
342
0
    FILE *stream;
343
344
0
    ovs_assert(LINUX);
345
346
0
    sprintf(file_name, "/proc/%lu/cmdline", (unsigned long int) pid);
347
0
    stream = fopen(file_name, "r");
348
0
    if (!stream) {
349
0
        VLOG_WARN_ONCE("%s: open failed (%s)", file_name, ovs_strerror(errno));
350
0
        goto exit;
351
0
    }
352
353
0
    if (!fgets(line, sizeof line, stream)) {
354
0
        VLOG_WARN_ONCE("%s: read failed (%s)", file_name,
355
0
                       feof(stream) ? "end of file" : ovs_strerror(errno));
356
0
        goto exit_close;
357
0
    }
358
359
0
    paren = strchr(line, '(');
360
0
    if (paren) {
361
0
        int x;
362
0
        if (ovs_scan(paren + 1, "%d", &x)) {
363
0
            crashes = x;
364
0
        }
365
0
    }
366
367
0
exit_close:
368
0
    fclose(stream);
369
0
exit:
370
0
    return crashes;
371
0
}
372
373
static unsigned long long int
374
ticks_to_ms(unsigned long long int ticks)
375
0
{
376
0
    ovs_assert(LINUX);
377
378
0
#ifndef USER_HZ
379
0
#define USER_HZ 100
380
0
#endif
381
382
0
#if USER_HZ == 100              /* Common case. */
383
0
    return ticks * (1000 / USER_HZ);
384
#else  /* Alpha and some other architectures.  */
385
    double factor = 1000.0 / USER_HZ;
386
    return ticks * factor + 0.5;
387
#endif
388
0
}
389
390
static bool
391
get_raw_process_info(pid_t pid, struct raw_process_info *raw)
392
0
{
393
0
    unsigned long long int vsize, rss, start_time, utime, stime;
394
0
    long long int start_msec;
395
0
    unsigned long ppid;
396
0
    char file_name[128];
397
0
    FILE *stream;
398
0
    int n;
399
400
0
    ovs_assert(LINUX);
401
402
0
    sprintf(file_name, "/proc/%lu/stat", (unsigned long int) pid);
403
0
    stream = fopen(file_name, "r");
404
0
    if (!stream) {
405
0
        VLOG_ERR_ONCE("%s: open failed (%s)",
406
0
                      file_name, ovs_strerror(errno));
407
0
        return false;
408
0
    }
409
410
0
    n = fscanf(stream,
411
0
               "%*d "           /* (1. pid) */
412
0
               "(%17[^)]) "     /* 2. process name */
413
0
               "%*c "           /* (3. state) */
414
0
               "%lu "           /* 4. ppid */
415
0
               "%*d "           /* (5. pgid) */
416
0
               "%*d "           /* (6. sid) */
417
0
               "%*d "           /* (7. tty_nr) */
418
0
               "%*d "           /* (8. tty_pgrp) */
419
0
               "%*u "           /* (9. flags) */
420
0
               "%*u "           /* (10. min_flt) */
421
0
               "%*u "           /* (11. cmin_flt) */
422
0
               "%*u "           /* (12. maj_flt) */
423
0
               "%*u "           /* (13. cmaj_flt) */
424
0
               "%llu "          /* 14. utime */
425
0
               "%llu "          /* 15. stime */
426
0
               "%*d "           /* (16. cutime) */
427
0
               "%*d "           /* (17. cstime) */
428
0
               "%*d "           /* (18. priority) */
429
0
               "%*d "           /* (19. nice) */
430
0
               "%*d "           /* (20. num_threads) */
431
0
               "%*d "           /* (21. always 0) */
432
0
               "%llu "          /* 22. start_time */
433
0
               "%llu "          /* 23. vsize */
434
0
               "%llu "          /* 24. rss */
435
0
               "%*u "           /* (25. rsslim) */
436
0
               "%*u "           /* (26. start_code) */
437
0
               "%*u "           /* (27. end_code) */
438
0
               "%*u "           /* (28. start_stack) */
439
0
               "%*u "           /* (29. esp) */
440
0
               "%*u "           /* (30. eip) */
441
0
               "%*u "           /* (31. pending signals) */
442
0
               "%*u "           /* (32. blocked signals) */
443
0
               "%*u "           /* (33. ignored signals) */
444
0
               "%*u "           /* (34. caught signals) */
445
0
               "%*u "           /* (35. whcan) */
446
0
               "%*u "           /* (36. always 0) */
447
0
               "%*u "           /* (37. always 0) */
448
0
               "%*d "           /* (38. exit_signal) */
449
0
               "%d "            /* 39. task_cpu */
450
#if 0
451
               /* These are here for documentation but #if'd out to save
452
                * actually parsing them from the stream for no benefit. */
453
               "%*u "           /* (40. rt_priority) */
454
               "%*u "           /* (41. policy) */
455
               "%*llu "         /* (42. blkio_ticks) */
456
               "%*lu "          /* (43. gtime) */
457
               "%*ld"           /* (44. cgtime) */
458
#endif
459
0
               , raw->name, &ppid, &utime, &stime, &start_time,
460
0
                  &vsize, &rss, &raw->core_id);
461
0
    fclose(stream);
462
0
    if (n != 8) {
463
0
        VLOG_ERR_ONCE("%s: fscanf failed", file_name);
464
0
        return false;
465
0
    }
466
467
0
    start_msec = get_boot_time() + ticks_to_ms(start_time);
468
469
0
    raw->vsz = vsize / 1024;
470
0
    raw->rss = rss * (get_page_size() / 1024);
471
0
    raw->uptime = time_wall_msec() - start_msec;
472
0
    raw->cputime = ticks_to_ms(utime + stime);
473
0
    raw->ppid = ppid;
474
475
0
    return true;
476
0
}
477
478
bool
479
get_process_info(pid_t pid, struct process_info *pinfo)
480
0
{
481
0
    struct raw_process_info child;
482
483
0
    ovs_assert(LINUX);
484
0
    if (!get_raw_process_info(pid, &child)) {
485
0
        return false;
486
0
    }
487
488
0
    ovs_strlcpy(pinfo->name, child.name, sizeof pinfo->name);
489
0
    pinfo->vsz = child.vsz;
490
0
    pinfo->rss = child.rss;
491
0
    pinfo->booted = child.uptime;
492
0
    pinfo->crashes = 0;
493
0
    pinfo->uptime = child.uptime;
494
0
    pinfo->cputime = child.cputime;
495
0
    pinfo->core_id = child.core_id;
496
497
0
    if (child.ppid) {
498
0
        struct raw_process_info parent;
499
500
0
        if (!get_raw_process_info(child.ppid, &parent)) {
501
0
            return false;
502
0
        }
503
0
        if (!strcmp(child.name, parent.name)) {
504
0
            pinfo->booted = parent.uptime;
505
0
            pinfo->crashes = count_crashes(child.ppid);
506
0
        }
507
0
    }
508
509
0
    return true;
510
0
}
511
512
/* Given 'status', which is a process status in the form reported by waitpid(2)
513
 * and returned by process_status(), returns a string describing how the
514
 * process terminated.  The caller is responsible for freeing the string when
515
 * it is no longer needed. */
516
char *
517
process_status_msg(int status)
518
0
{
519
0
    struct ds ds = DS_EMPTY_INITIALIZER;
520
0
    if (WIFEXITED(status)) {
521
0
        ds_put_format(&ds, "exit status %d", WEXITSTATUS(status));
522
0
    } else if (WIFSIGNALED(status)) {
523
0
        char namebuf[SIGNAL_NAME_BUFSIZE];
524
525
0
        ds_put_format(&ds, "killed (%s)",
526
0
                      signal_name(WTERMSIG(status), namebuf, sizeof namebuf));
527
0
    } else if (WIFSTOPPED(status)) {
528
0
        char namebuf[SIGNAL_NAME_BUFSIZE];
529
530
0
        ds_put_format(&ds, "stopped (%s)",
531
0
                      signal_name(WSTOPSIG(status), namebuf, sizeof namebuf));
532
0
    } else {
533
0
        ds_put_format(&ds, "terminated abnormally (%x)", status);
534
0
    }
535
0
    if (WCOREDUMP(status)) {
536
0
        ds_put_cstr(&ds, ", core dumped");
537
0
    }
538
0
    return ds_cstr(&ds);
539
0
}
540
541
/* Executes periodic maintenance activities required by the process module. */
542
void
543
process_run(void)
544
0
{
545
0
    char buf[_POSIX_PIPE_BUF];
546
547
0
    if (!ovs_list_is_empty(&all_processes) && read(fds[0], buf, sizeof buf) > 0) {
548
0
        struct process *p;
549
550
0
        LIST_FOR_EACH (p, node, &all_processes) {
551
0
            if (!p->exited) {
552
0
                int retval, status;
553
0
                do {
554
0
                    retval = waitpid(p->pid, &status, WNOHANG);
555
0
                } while (retval == -1 && errno == EINTR);
556
0
                if (retval == p->pid) {
557
0
                    p->exited = true;
558
0
                    p->status = status;
559
0
                } else if (retval < 0) {
560
0
                    VLOG_WARN("waitpid: %s", ovs_strerror(errno));
561
0
                    p->exited = true;
562
0
                    p->status = -1;
563
0
                }
564
0
            }
565
0
        }
566
0
    }
567
0
}
568
569
/* Causes the next call to poll_block() to wake up when process 'p' has
570
 * exited. */
571
void
572
process_wait(struct process *p)
573
0
{
574
0
    if (p->exited) {
575
0
        poll_immediate_wake();
576
0
    } else {
577
0
        poll_fd_wait(fds[0], POLLIN);
578
0
    }
579
0
}
580
581
char *
582
process_search_path(const char *name)
583
0
{
584
0
    char *save_ptr = NULL;
585
0
    char *path, *dir;
586
0
    struct stat s;
587
588
0
    if (strchr(name, '/') || !getenv("PATH")) {
589
0
        return stat(name, &s) == 0 ? xstrdup(name) : NULL;
590
0
    }
591
592
0
    path = xstrdup(getenv("PATH"));
593
0
    for (dir = strtok_r(path, ":", &save_ptr); dir;
594
0
         dir = strtok_r(NULL, ":", &save_ptr)) {
595
0
        char *file = xasprintf("%s/%s", dir, name);
596
0
        if (stat(file, &s) == 0) {
597
0
            free(path);
598
0
            return file;
599
0
        }
600
0
        free(file);
601
0
    }
602
0
    free(path);
603
0
    return NULL;
604
0
}
605

606
static void
607
sigchld_handler(int signr OVS_UNUSED)
608
0
{
609
0
    ovs_ignore(write(fds[1], "", 1));
610
0
}