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