chiark / gitweb /
build-sys: use #if Y instead of #ifdef Y everywhere
[elogind.git] / src / basic / process-util.c
1 /***
2   This file is part of systemd.
3
4   Copyright 2010 Lennart Poettering
5
6   systemd is free software; you can redistribute it and/or modify it
7   under the terms of the GNU Lesser General Public License as published by
8   the Free Software Foundation; either version 2.1 of the License, or
9   (at your option) any later version.
10
11   systemd is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   Lesser General Public License for more details.
15
16   You should have received a copy of the GNU Lesser General Public License
17   along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <ctype.h>
21 #include <errno.h>
22 #include <limits.h>
23 #include <linux/oom.h>
24 #include <sched.h>
25 #include <signal.h>
26 #include <stdbool.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <sys/mman.h>
31 #include <sys/personality.h>
32 #include <sys/prctl.h>
33 #include <sys/types.h>
34 #include <sys/wait.h>
35 #include <syslog.h>
36 #include <unistd.h>
37 #if HAVE_VALGRIND_VALGRIND_H
38 #include <valgrind/valgrind.h>
39 #endif
40
41 #include "alloc-util.h"
42 //#include "architecture.h"
43 #include "escape.h"
44 #include "fd-util.h"
45 #include "fileio.h"
46 #include "fs-util.h"
47 //#include "ioprio.h"
48 #include "log.h"
49 #include "macro.h"
50 #include "missing.h"
51 #include "process-util.h"
52 //#include "raw-clone.h"
53 #include "signal-util.h"
54 //#include "stat-util.h"
55 #include "string-table.h"
56 #include "string-util.h"
57 #include "user-util.h"
58 #include "util.h"
59
60 int get_process_state(pid_t pid) {
61         const char *p;
62         char state;
63         int r;
64         _cleanup_free_ char *line = NULL;
65
66         assert(pid >= 0);
67
68         p = procfs_file_alloca(pid, "stat");
69
70         r = read_one_line_file(p, &line);
71         if (r == -ENOENT)
72                 return -ESRCH;
73         if (r < 0)
74                 return r;
75
76         p = strrchr(line, ')');
77         if (!p)
78                 return -EIO;
79
80         p++;
81
82         if (sscanf(p, " %c", &state) != 1)
83                 return -EIO;
84
85         return (unsigned char) state;
86 }
87
88 int get_process_comm(pid_t pid, char **name) {
89         const char *p;
90         int r;
91
92         assert(name);
93         assert(pid >= 0);
94
95         p = procfs_file_alloca(pid, "comm");
96
97         r = read_one_line_file(p, name);
98         if (r == -ENOENT)
99                 return -ESRCH;
100
101         return r;
102 }
103
104 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
105         _cleanup_fclose_ FILE *f = NULL;
106         bool space = false;
107         char *k, *ans = NULL;
108         const char *p;
109         int c;
110
111         assert(line);
112         assert(pid >= 0);
113
114         /* Retrieves a process' command line. Replaces unprintable characters while doing so by whitespace (coalescing
115          * multiple sequential ones into one). If max_length is != 0 will return a string of the specified size at most
116          * (the trailing NUL byte does count towards the length here!), abbreviated with a "..." ellipsis. If
117          * comm_fallback is true and the process has no command line set (the case for kernel threads), or has a
118          * command line that resolves to the empty string will return the "comm" name of the process instead.
119          *
120          * Returns -ESRCH if the process doesn't exist, and -ENOENT if the process has no command line (and
121          * comm_fallback is false). Returns 0 and sets *line otherwise. */
122
123         p = procfs_file_alloca(pid, "cmdline");
124
125         f = fopen(p, "re");
126         if (!f) {
127                 if (errno == ENOENT)
128                         return -ESRCH;
129                 return -errno;
130         }
131
132         if (max_length == 1) {
133
134                 /* If there's only room for one byte, return the empty string */
135                 ans = new0(char, 1);
136                 if (!ans)
137                         return -ENOMEM;
138
139                 *line = ans;
140                 return 0;
141
142         } else if (max_length == 0) {
143                 size_t len = 0, allocated = 0;
144
145                 while ((c = getc(f)) != EOF) {
146
147                         if (!GREEDY_REALLOC(ans, allocated, len+3)) {
148                                 free(ans);
149                                 return -ENOMEM;
150                         }
151
152                         if (isprint(c)) {
153                                 if (space) {
154                                         ans[len++] = ' ';
155                                         space = false;
156                                 }
157
158                                 ans[len++] = c;
159                         } else if (len > 0)
160                                 space = true;
161                }
162
163                 if (len > 0)
164                         ans[len] = '\0';
165                 else
166                         ans = mfree(ans);
167
168         } else {
169                 bool dotdotdot = false;
170                 size_t left;
171
172                 ans = new(char, max_length);
173                 if (!ans)
174                         return -ENOMEM;
175
176                 k = ans;
177                 left = max_length;
178                 while ((c = getc(f)) != EOF) {
179
180                         if (isprint(c)) {
181
182                                 if (space) {
183                                         if (left <= 2) {
184                                                 dotdotdot = true;
185                                                 break;
186                                         }
187
188                                         *(k++) = ' ';
189                                         left--;
190                                         space = false;
191                                 }
192
193                                 if (left <= 1) {
194                                         dotdotdot = true;
195                                         break;
196                                 }
197
198                                 *(k++) = (char) c;
199                                 left--;
200                         } else if (k > ans)
201                                 space = true;
202                 }
203
204                 if (dotdotdot) {
205                         if (max_length <= 4) {
206                                 k = ans;
207                                 left = max_length;
208                         } else {
209                                 k = ans + max_length - 4;
210                                 left = 4;
211
212                                 /* Eat up final spaces */
213                                 while (k > ans && isspace(k[-1])) {
214                                         k--;
215                                         left++;
216                                 }
217                         }
218
219                         strncpy(k, "...", left-1);
220                         k[left-1] = 0;
221                 } else
222                         *k = 0;
223         }
224
225         /* Kernel threads have no argv[] */
226         if (isempty(ans)) {
227                 _cleanup_free_ char *t = NULL;
228                 int h;
229
230                 free(ans);
231
232                 if (!comm_fallback)
233                         return -ENOENT;
234
235                 h = get_process_comm(pid, &t);
236                 if (h < 0)
237                         return h;
238
239                 if (max_length == 0)
240                         ans = strjoin("[", t, "]");
241                 else {
242                         size_t l;
243
244                         l = strlen(t);
245
246                         if (l + 3 <= max_length)
247                                 ans = strjoin("[", t, "]");
248                         else if (max_length <= 6) {
249
250                                 ans = new(char, max_length);
251                                 if (!ans)
252                                         return -ENOMEM;
253
254                                 memcpy(ans, "[...]", max_length-1);
255                                 ans[max_length-1] = 0;
256                         } else {
257                                 char *e;
258
259                                 t[max_length - 6] = 0;
260
261                                 /* Chop off final spaces */
262                                 e = strchr(t, 0);
263                                 while (e > t && isspace(e[-1]))
264                                         e--;
265                                 *e = 0;
266
267                                 ans = strjoin("[", t, "...]");
268                         }
269                 }
270                 if (!ans)
271                         return -ENOMEM;
272         }
273
274         *line = ans;
275         return 0;
276 }
277
278 #if 0 /// UNNEEDED by elogind
279 int rename_process(const char name[]) {
280         static size_t mm_size = 0;
281         static char *mm = NULL;
282         bool truncated = false;
283         size_t l;
284
285         /* This is a like a poor man's setproctitle(). It changes the comm field, argv[0], and also the glibc's
286          * internally used name of the process. For the first one a limit of 16 chars applies; to the second one in
287          * many cases one of 10 (i.e. length of "/sbin/init") — however if we have CAP_SYS_RESOURCES it is unbounded;
288          * to the third one 7 (i.e. the length of "systemd". If you pass a longer string it will likely be
289          * truncated.
290          *
291          * Returns 0 if a name was set but truncated, > 0 if it was set but not truncated. */
292
293         if (isempty(name))
294                 return -EINVAL; /* let's not confuse users unnecessarily with an empty name */
295
296         l = strlen(name);
297
298         /* First step, change the comm field. */
299         (void) prctl(PR_SET_NAME, name);
300         if (l > 15) /* Linux process names can be 15 chars at max */
301                 truncated = true;
302
303         /* Second step, change glibc's ID of the process name. */
304         if (program_invocation_name) {
305                 size_t k;
306
307                 k = strlen(program_invocation_name);
308                 strncpy(program_invocation_name, name, k);
309                 if (l > k)
310                         truncated = true;
311         }
312
313         /* Third step, completely replace the argv[] array the kernel maintains for us. This requires privileges, but
314          * has the advantage that the argv[] array is exactly what we want it to be, and not filled up with zeros at
315          * the end. This is the best option for changing /proc/self/cmdline. */
316
317         /* Let's not bother with this if we don't have euid == 0. Strictly speaking we should check for the
318          * CAP_SYS_RESOURCE capability which is independent of the euid. In our own code the capability generally is
319          * present only for euid == 0, hence let's use this as quick bypass check, to avoid calling mmap() if
320          * PR_SET_MM_ARG_{START,END} fails with EPERM later on anyway. After all geteuid() is dead cheap to call, but
321          * mmap() is not. */
322         if (geteuid() != 0)
323                 log_debug("Skipping PR_SET_MM, as we don't have privileges.");
324         else if (mm_size < l+1) {
325                 size_t nn_size;
326                 char *nn;
327
328                 nn_size = PAGE_ALIGN(l+1);
329                 nn = mmap(NULL, nn_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
330                 if (nn == MAP_FAILED) {
331                         log_debug_errno(errno, "mmap() failed: %m");
332                         goto use_saved_argv;
333                 }
334
335                 strncpy(nn, name, nn_size);
336
337                 /* Now, let's tell the kernel about this new memory */
338                 if (prctl(PR_SET_MM, PR_SET_MM_ARG_START, (unsigned long) nn, 0, 0) < 0) {
339                         log_debug_errno(errno, "PR_SET_MM_ARG_START failed, proceeding without: %m");
340                         (void) munmap(nn, nn_size);
341                         goto use_saved_argv;
342                 }
343
344                 /* And update the end pointer to the new end, too. If this fails, we don't really know what to do, it's
345                  * pretty unlikely that we can rollback, hence we'll just accept the failure, and continue. */
346                 if (prctl(PR_SET_MM, PR_SET_MM_ARG_END, (unsigned long) nn + l + 1, 0, 0) < 0)
347                         log_debug_errno(errno, "PR_SET_MM_ARG_END failed, proceeding without: %m");
348
349                 if (mm)
350                         (void) munmap(mm, mm_size);
351
352                 mm = nn;
353                 mm_size = nn_size;
354         } else {
355                 strncpy(mm, name, mm_size);
356
357                 /* Update the end pointer, continuing regardless of any failure. */
358                 if (prctl(PR_SET_MM, PR_SET_MM_ARG_END, (unsigned long) mm + l + 1, 0, 0) < 0)
359                         log_debug_errno(errno, "PR_SET_MM_ARG_END failed, proceeding without: %m");
360         }
361
362 use_saved_argv:
363         /* Fourth step: in all cases we'll also update the original argv[], so that our own code gets it right too if
364          * it still looks here */
365
366         if (saved_argc > 0) {
367                 int i;
368
369                 if (saved_argv[0]) {
370                         size_t k;
371
372                         k = strlen(saved_argv[0]);
373                         strncpy(saved_argv[0], name, k);
374                         if (l > k)
375                                 truncated = true;
376                 }
377
378                 for (i = 1; i < saved_argc; i++) {
379                         if (!saved_argv[i])
380                                 break;
381
382                         memzero(saved_argv[i], strlen(saved_argv[i]));
383                 }
384         }
385
386         return !truncated;
387 }
388 #endif // 0
389
390 int is_kernel_thread(pid_t pid) {
391         const char *p;
392         size_t count;
393         char c;
394         bool eof;
395         FILE *f;
396
397         if (pid == 0 || pid == 1 || pid == getpid_cached()) /* pid 1, and we ourselves certainly aren't a kernel thread */
398                 return 0;
399
400         assert(pid > 1);
401
402         p = procfs_file_alloca(pid, "cmdline");
403         f = fopen(p, "re");
404         if (!f) {
405                 if (errno == ENOENT)
406                         return -ESRCH;
407                 return -errno;
408         }
409
410         count = fread(&c, 1, 1, f);
411         eof = feof(f);
412         fclose(f);
413
414         /* Kernel threads have an empty cmdline */
415
416         if (count <= 0)
417                 return eof ? 1 : -errno;
418
419         return 0;
420 }
421
422 #if 0 /// UNNEEDED by elogind
423 int get_process_capeff(pid_t pid, char **capeff) {
424         const char *p;
425         int r;
426
427         assert(capeff);
428         assert(pid >= 0);
429
430         p = procfs_file_alloca(pid, "status");
431
432         r = get_proc_field(p, "CapEff", WHITESPACE, capeff);
433         if (r == -ENOENT)
434                 return -ESRCH;
435
436         return r;
437 }
438 #endif // 0
439
440 static int get_process_link_contents(const char *proc_file, char **name) {
441         int r;
442
443         assert(proc_file);
444         assert(name);
445
446         r = readlink_malloc(proc_file, name);
447         if (r == -ENOENT)
448                 return -ESRCH;
449         if (r < 0)
450                 return r;
451
452         return 0;
453 }
454
455 int get_process_exe(pid_t pid, char **name) {
456         const char *p;
457         char *d;
458         int r;
459
460         assert(pid >= 0);
461
462         p = procfs_file_alloca(pid, "exe");
463         r = get_process_link_contents(p, name);
464         if (r < 0)
465                 return r;
466
467         d = endswith(*name, " (deleted)");
468         if (d)
469                 *d = '\0';
470
471         return 0;
472 }
473
474 #if 0 /// UNNEEDED by elogind
475 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
476         _cleanup_fclose_ FILE *f = NULL;
477         char line[LINE_MAX];
478         const char *p;
479
480         assert(field);
481         assert(uid);
482
483         if (!pid_is_valid(pid))
484                 return -EINVAL;
485
486         p = procfs_file_alloca(pid, "status");
487         f = fopen(p, "re");
488         if (!f) {
489                 if (errno == ENOENT)
490                         return -ESRCH;
491                 return -errno;
492         }
493
494         FOREACH_LINE(line, f, return -errno) {
495                 char *l;
496
497                 l = strstrip(line);
498
499                 if (startswith(l, field)) {
500                         l += strlen(field);
501                         l += strspn(l, WHITESPACE);
502
503                         l[strcspn(l, WHITESPACE)] = 0;
504
505                         return parse_uid(l, uid);
506                 }
507         }
508
509         return -EIO;
510 }
511
512 int get_process_uid(pid_t pid, uid_t *uid) {
513
514         if (pid == 0 || pid == getpid_cached()) {
515                 *uid = getuid();
516                 return 0;
517         }
518
519         return get_process_id(pid, "Uid:", uid);
520 }
521
522 int get_process_gid(pid_t pid, gid_t *gid) {
523
524         if (pid == 0 || pid == getpid_cached()) {
525                 *gid = getgid();
526                 return 0;
527         }
528
529         assert_cc(sizeof(uid_t) == sizeof(gid_t));
530         return get_process_id(pid, "Gid:", gid);
531 }
532
533 int get_process_cwd(pid_t pid, char **cwd) {
534         const char *p;
535
536         assert(pid >= 0);
537
538         p = procfs_file_alloca(pid, "cwd");
539
540         return get_process_link_contents(p, cwd);
541 }
542
543 int get_process_root(pid_t pid, char **root) {
544         const char *p;
545
546         assert(pid >= 0);
547
548         p = procfs_file_alloca(pid, "root");
549
550         return get_process_link_contents(p, root);
551 }
552
553 int get_process_environ(pid_t pid, char **env) {
554         _cleanup_fclose_ FILE *f = NULL;
555         _cleanup_free_ char *outcome = NULL;
556         int c;
557         const char *p;
558         size_t allocated = 0, sz = 0;
559
560         assert(pid >= 0);
561         assert(env);
562
563         p = procfs_file_alloca(pid, "environ");
564
565         f = fopen(p, "re");
566         if (!f) {
567                 if (errno == ENOENT)
568                         return -ESRCH;
569                 return -errno;
570         }
571
572         while ((c = fgetc(f)) != EOF) {
573                 if (!GREEDY_REALLOC(outcome, allocated, sz + 5))
574                         return -ENOMEM;
575
576                 if (c == '\0')
577                         outcome[sz++] = '\n';
578                 else
579                         sz += cescape_char(c, outcome + sz);
580         }
581
582         if (!outcome) {
583                 outcome = strdup("");
584                 if (!outcome)
585                         return -ENOMEM;
586         } else
587                 outcome[sz] = '\0';
588
589         *env = outcome;
590         outcome = NULL;
591
592         return 0;
593 }
594
595 int get_process_ppid(pid_t pid, pid_t *_ppid) {
596         int r;
597         _cleanup_free_ char *line = NULL;
598         long unsigned ppid;
599         const char *p;
600
601         assert(pid >= 0);
602         assert(_ppid);
603
604         if (pid == 0 || pid == getpid_cached()) {
605                 *_ppid = getppid();
606                 return 0;
607         }
608
609         p = procfs_file_alloca(pid, "stat");
610         r = read_one_line_file(p, &line);
611         if (r == -ENOENT)
612                 return -ESRCH;
613         if (r < 0)
614                 return r;
615
616         /* Let's skip the pid and comm fields. The latter is enclosed
617          * in () but does not escape any () in its value, so let's
618          * skip over it manually */
619
620         p = strrchr(line, ')');
621         if (!p)
622                 return -EIO;
623
624         p++;
625
626         if (sscanf(p, " "
627                    "%*c "  /* state */
628                    "%lu ", /* ppid */
629                    &ppid) != 1)
630                 return -EIO;
631
632         if ((long unsigned) (pid_t) ppid != ppid)
633                 return -ERANGE;
634
635         *_ppid = (pid_t) ppid;
636
637         return 0;
638 }
639 #endif // 0
640
641 int wait_for_terminate(pid_t pid, siginfo_t *status) {
642         siginfo_t dummy;
643
644         assert(pid >= 1);
645
646         if (!status)
647                 status = &dummy;
648
649         for (;;) {
650                 zero(*status);
651
652                 if (waitid(P_PID, pid, status, WEXITED) < 0) {
653
654                         if (errno == EINTR)
655                                 continue;
656
657                         return negative_errno();
658                 }
659
660                 return 0;
661         }
662 }
663
664 /*
665  * Return values:
666  * < 0 : wait_for_terminate() failed to get the state of the
667  *       process, the process was terminated by a signal, or
668  *       failed for an unknown reason.
669  * >=0 : The process terminated normally, and its exit code is
670  *       returned.
671  *
672  * That is, success is indicated by a return value of zero, and an
673  * error is indicated by a non-zero value.
674  *
675  * A warning is emitted if the process terminates abnormally,
676  * and also if it returns non-zero unless check_exit_code is true.
677  */
678 int wait_for_terminate_and_warn(const char *name, pid_t pid, bool check_exit_code) {
679         int r;
680         siginfo_t status;
681
682         assert(name);
683         assert(pid > 1);
684
685         r = wait_for_terminate(pid, &status);
686         if (r < 0)
687                 return log_warning_errno(r, "Failed to wait for %s: %m", name);
688
689         if (status.si_code == CLD_EXITED) {
690                 if (status.si_status != 0)
691                         log_full(check_exit_code ? LOG_WARNING : LOG_DEBUG,
692                                  "%s failed with error code %i.", name, status.si_status);
693                 else
694                         log_debug("%s succeeded.", name);
695
696                 return status.si_status;
697         } else if (IN_SET(status.si_code, CLD_KILLED, CLD_DUMPED)) {
698
699                 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
700                 return -EPROTO;
701         }
702
703         log_warning("%s failed due to unknown reason.", name);
704         return -EPROTO;
705 }
706
707 #if 0 /// UNNEEDED by elogind
708 void sigkill_wait(pid_t pid) {
709         assert(pid > 1);
710
711         if (kill(pid, SIGKILL) > 0)
712                 (void) wait_for_terminate(pid, NULL);
713 }
714
715 void sigkill_waitp(pid_t *pid) {
716         if (!pid)
717                 return;
718         if (*pid <= 1)
719                 return;
720
721         sigkill_wait(*pid);
722 }
723
724 int kill_and_sigcont(pid_t pid, int sig) {
725         int r;
726
727         r = kill(pid, sig) < 0 ? -errno : 0;
728
729         /* If this worked, also send SIGCONT, unless we already just sent a SIGCONT, or SIGKILL was sent which isn't
730          * affected by a process being suspended anyway. */
731         if (r >= 0 && !IN_SET(sig, SIGCONT, SIGKILL))
732                 (void) kill(pid, SIGCONT);
733
734         return r;
735 }
736 #endif // 0
737
738 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
739         _cleanup_fclose_ FILE *f = NULL;
740         char *value = NULL;
741         int r;
742         bool done = false;
743         size_t l;
744         const char *path;
745
746         assert(pid >= 0);
747         assert(field);
748         assert(_value);
749
750         path = procfs_file_alloca(pid, "environ");
751
752         f = fopen(path, "re");
753         if (!f) {
754                 if (errno == ENOENT)
755                         return -ESRCH;
756                 return -errno;
757         }
758
759         l = strlen(field);
760         r = 0;
761
762         do {
763                 char line[LINE_MAX];
764                 unsigned i;
765
766                 for (i = 0; i < sizeof(line)-1; i++) {
767                         int c;
768
769                         c = getc(f);
770                         if (_unlikely_(c == EOF)) {
771                                 done = true;
772                                 break;
773                         } else if (c == 0)
774                                 break;
775
776                         line[i] = c;
777                 }
778                 line[i] = 0;
779
780                 if (strneq(line, field, l) && line[l] == '=') {
781                         value = strdup(line + l + 1);
782                         if (!value)
783                                 return -ENOMEM;
784
785                         r = 1;
786                         break;
787                 }
788
789         } while (!done);
790
791         *_value = value;
792         return r;
793 }
794
795 bool pid_is_unwaited(pid_t pid) {
796         /* Checks whether a PID is still valid at all, including a zombie */
797
798         if (!pid_is_valid(pid))
799                 return false;
800
801         if (pid <= 1) /* If we or PID 1 would be dead and have been waited for, this code would not be running */
802                 return true;
803
804         if (pid == getpid_cached())
805                 return true;
806
807         if (kill(pid, 0) >= 0)
808                 return true;
809
810         return errno != ESRCH;
811 }
812
813 bool pid_is_alive(pid_t pid) {
814         int r;
815
816         /* Checks whether a PID is still valid and not a zombie */
817
818         if (!pid_is_valid(pid))
819                 return false;
820
821         if (pid <= 1) /* If we or PID 1 would be a zombie, this code would not be running */
822                 return true;
823
824         if (pid == getpid_cached())
825                 return true;
826
827         r = get_process_state(pid);
828         if (r == -ESRCH || r == 'Z')
829                 return false;
830
831         return true;
832 }
833
834 #if 0 /// UNNEEDED by elogind
835 int pid_from_same_root_fs(pid_t pid) {
836         const char *root;
837
838         if (!pid_is_valid(pid))
839                 return false;
840
841         if (pid == 0 || pid == getpid_cached())
842                 return true;
843
844         root = procfs_file_alloca(pid, "root");
845
846         return files_same(root, "/proc/1/root", 0);
847 }
848 #endif // 0
849
850 bool is_main_thread(void) {
851         static thread_local int cached = 0;
852
853         if (_unlikely_(cached == 0))
854                 cached = getpid_cached() == gettid() ? 1 : -1;
855
856         return cached > 0;
857 }
858
859 #if 0 /// UNNEEDED by elogind
860 noreturn void freeze(void) {
861
862         log_close();
863
864         /* Make sure nobody waits for us on a socket anymore */
865         close_all_fds(NULL, 0);
866
867         sync();
868
869         for (;;)
870                 pause();
871 }
872
873 bool oom_score_adjust_is_valid(int oa) {
874         return oa >= OOM_SCORE_ADJ_MIN && oa <= OOM_SCORE_ADJ_MAX;
875 }
876
877 unsigned long personality_from_string(const char *p) {
878         int architecture;
879
880         if (!p)
881                 return PERSONALITY_INVALID;
882
883         /* Parse a personality specifier. We use our own identifiers that indicate specific ABIs, rather than just
884          * hints regarding the register size, since we want to keep things open for multiple locally supported ABIs for
885          * the same register size. */
886
887         architecture = architecture_from_string(p);
888         if (architecture < 0)
889                 return PERSONALITY_INVALID;
890
891         if (architecture == native_architecture())
892                 return PER_LINUX;
893 #ifdef SECONDARY_ARCHITECTURE
894         if (architecture == SECONDARY_ARCHITECTURE)
895                 return PER_LINUX32;
896 #endif
897
898         return PERSONALITY_INVALID;
899 }
900
901 const char* personality_to_string(unsigned long p) {
902         int architecture = _ARCHITECTURE_INVALID;
903
904         if (p == PER_LINUX)
905                 architecture = native_architecture();
906 #ifdef SECONDARY_ARCHITECTURE
907         else if (p == PER_LINUX32)
908                 architecture = SECONDARY_ARCHITECTURE;
909 #endif
910
911         if (architecture < 0)
912                 return NULL;
913
914         return architecture_to_string(architecture);
915 }
916
917 int safe_personality(unsigned long p) {
918         int ret;
919
920         /* So here's the deal, personality() is weirdly defined by glibc. In some cases it returns a failure via errno,
921          * and in others as negative return value containing an errno-like value. Let's work around this: this is a
922          * wrapper that uses errno if it is set, and uses the return value otherwise. And then it sets both errno and
923          * the return value indicating the same issue, so that we are definitely on the safe side.
924          *
925          * See https://github.com/elogind/elogind/issues/6737 */
926
927         errno = 0;
928         ret = personality(p);
929         if (ret < 0) {
930                 if (errno != 0)
931                         return -errno;
932
933                 errno = -ret;
934         }
935
936         return ret;
937 }
938
939 int opinionated_personality(unsigned long *ret) {
940         int current;
941
942         /* Returns the current personality, or PERSONALITY_INVALID if we can't determine it. This function is a bit
943          * opinionated though, and ignores all the finer-grained bits and exotic personalities, only distinguishing the
944          * two most relevant personalities: PER_LINUX and PER_LINUX32. */
945
946         current = safe_personality(PERSONALITY_INVALID);
947         if (current < 0)
948                 return current;
949
950         if (((unsigned long) current & 0xffff) == PER_LINUX32)
951                 *ret = PER_LINUX32;
952         else
953                 *ret = PER_LINUX;
954
955         return 0;
956 }
957
958 void valgrind_summary_hack(void) {
959 #if HAVE_VALGRIND_VALGRIND_H
960         if (getpid_cached() == 1 && RUNNING_ON_VALGRIND) {
961                 pid_t pid;
962                 pid = raw_clone(SIGCHLD);
963                 if (pid < 0)
964                         log_emergency_errno(errno, "Failed to fork off valgrind helper: %m");
965                 else if (pid == 0)
966                         exit(EXIT_SUCCESS);
967                 else {
968                         log_info("Spawned valgrind helper as PID "PID_FMT".", pid);
969                         (void) wait_for_terminate(pid, NULL);
970                 }
971         }
972 #endif
973 }
974
975 int pid_compare_func(const void *a, const void *b) {
976         const pid_t *p = a, *q = b;
977
978         /* Suitable for usage in qsort() */
979
980         if (*p < *q)
981                 return -1;
982         if (*p > *q)
983                 return 1;
984         return 0;
985 }
986
987 int ioprio_parse_priority(const char *s, int *ret) {
988         int i, r;
989
990         assert(s);
991         assert(ret);
992
993         r = safe_atoi(s, &i);
994         if (r < 0)
995                 return r;
996
997         if (!ioprio_priority_is_valid(i))
998                 return -EINVAL;
999
1000         *ret = i;
1001         return 0;
1002 }
1003 #endif // 0
1004
1005 /* The cached PID, possible values:
1006  *
1007  *     == UNSET [0]  → cache not initialized yet
1008  *     == BUSY [-1]  → some thread is initializing it at the moment
1009  *     any other     → the cached PID
1010  */
1011
1012 #define CACHED_PID_UNSET ((pid_t) 0)
1013 #define CACHED_PID_BUSY ((pid_t) -1)
1014
1015 static pid_t cached_pid = CACHED_PID_UNSET;
1016
1017 static void reset_cached_pid(void) {
1018         /* Invoked in the child after a fork(), i.e. at the first moment the PID changed */
1019         cached_pid = CACHED_PID_UNSET;
1020 }
1021
1022 /* We use glibc __register_atfork() + __dso_handle directly here, as they are not included in the glibc
1023  * headers. __register_atfork() is mostly equivalent to pthread_atfork(), but doesn't require us to link against
1024  * libpthread, as it is part of glibc anyway. */
1025 extern int __register_atfork(void (*prepare) (void), void (*parent) (void), void (*child) (void), void * __dso_handle);
1026 extern void* __dso_handle __attribute__ ((__weak__));
1027
1028 pid_t getpid_cached(void) {
1029         pid_t current_value;
1030
1031         /* getpid_cached() is much like getpid(), but caches the value in local memory, to avoid having to invoke a
1032          * system call each time. This restores glibc behaviour from before 2.24, when getpid() was unconditionally
1033          * cached. Starting with 2.24 getpid() started to become prohibitively expensive when used for detecting when
1034          * objects were used across fork()s. With this caching the old behaviour is somewhat restored.
1035          *
1036          * https://bugzilla.redhat.com/show_bug.cgi?id=1443976
1037          * https://sourceware.org/git/gitweb.cgi?p=glibc.git;h=c579f48edba88380635ab98cb612030e3ed8691e
1038          */
1039
1040         current_value = __sync_val_compare_and_swap(&cached_pid, CACHED_PID_UNSET, CACHED_PID_BUSY);
1041
1042         switch (current_value) {
1043
1044         case CACHED_PID_UNSET: { /* Not initialized yet, then do so now */
1045                 pid_t new_pid;
1046
1047                 new_pid = getpid();
1048
1049                 if (__register_atfork(NULL, NULL, reset_cached_pid, __dso_handle) != 0) {
1050                         /* OOM? Let's try again later */
1051                         cached_pid = CACHED_PID_UNSET;
1052                         return new_pid;
1053                 }
1054
1055                 cached_pid = new_pid;
1056                 return new_pid;
1057         }
1058
1059         case CACHED_PID_BUSY: /* Somebody else is currently initializing */
1060                 return getpid();
1061
1062         default: /* Properly initialized */
1063                 return current_value;
1064         }
1065 }
1066
1067 #if 0 /// UNNEEDED by elogind
1068 static const char *const ioprio_class_table[] = {
1069         [IOPRIO_CLASS_NONE] = "none",
1070         [IOPRIO_CLASS_RT] = "realtime",
1071         [IOPRIO_CLASS_BE] = "best-effort",
1072         [IOPRIO_CLASS_IDLE] = "idle"
1073 };
1074
1075 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
1076
1077 static const char *const sigchld_code_table[] = {
1078         [CLD_EXITED] = "exited",
1079         [CLD_KILLED] = "killed",
1080         [CLD_DUMPED] = "dumped",
1081         [CLD_TRAPPED] = "trapped",
1082         [CLD_STOPPED] = "stopped",
1083         [CLD_CONTINUED] = "continued",
1084 };
1085
1086 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
1087
1088 static const char* const sched_policy_table[] = {
1089         [SCHED_OTHER] = "other",
1090         [SCHED_BATCH] = "batch",
1091         [SCHED_IDLE] = "idle",
1092         [SCHED_FIFO] = "fifo",
1093         [SCHED_RR] = "rr"
1094 };
1095
1096 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
1097 #endif // 0