chiark / gitweb /
tree-wide: use IN_SET where possible
[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 (IN_SET(status.si_code, CLD_KILLED, CLD_DUMPED)) {
696
697                 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
698                 return -EPROTO;
699         }
700
701         log_warning("%s failed due to unknown reason.", name);
702         return -EPROTO;
703 }
704
705 #if 0 /// UNNEEDED by elogind
706 void sigkill_wait(pid_t pid) {
707         assert(pid > 1);
708
709         if (kill(pid, SIGKILL) > 0)
710                 (void) wait_for_terminate(pid, NULL);
711 }
712
713 void sigkill_waitp(pid_t *pid) {
714         if (!pid)
715                 return;
716         if (*pid <= 1)
717                 return;
718
719         sigkill_wait(*pid);
720 }
721
722 int kill_and_sigcont(pid_t pid, int sig) {
723         int r;
724
725         r = kill(pid, sig) < 0 ? -errno : 0;
726
727         /* If this worked, also send SIGCONT, unless we already just sent a SIGCONT, or SIGKILL was sent which isn't
728          * affected by a process being suspended anyway. */
729         if (r >= 0 && !IN_SET(sig, SIGCONT, SIGKILL))
730                 (void) kill(pid, SIGCONT);
731
732         return r;
733 }
734 #endif // 0
735
736 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
737         _cleanup_fclose_ FILE *f = NULL;
738         char *value = NULL;
739         int r;
740         bool done = false;
741         size_t l;
742         const char *path;
743
744         assert(pid >= 0);
745         assert(field);
746         assert(_value);
747
748         path = procfs_file_alloca(pid, "environ");
749
750         f = fopen(path, "re");
751         if (!f) {
752                 if (errno == ENOENT)
753                         return -ESRCH;
754                 return -errno;
755         }
756
757         l = strlen(field);
758         r = 0;
759
760         do {
761                 char line[LINE_MAX];
762                 unsigned i;
763
764                 for (i = 0; i < sizeof(line)-1; i++) {
765                         int c;
766
767                         c = getc(f);
768                         if (_unlikely_(c == EOF)) {
769                                 done = true;
770                                 break;
771                         } else if (c == 0)
772                                 break;
773
774                         line[i] = c;
775                 }
776                 line[i] = 0;
777
778                 if (strneq(line, field, l) && line[l] == '=') {
779                         value = strdup(line + l + 1);
780                         if (!value)
781                                 return -ENOMEM;
782
783                         r = 1;
784                         break;
785                 }
786
787         } while (!done);
788
789         *_value = value;
790         return r;
791 }
792
793 bool pid_is_unwaited(pid_t pid) {
794         /* Checks whether a PID is still valid at all, including a zombie */
795
796         if (!pid_is_valid(pid))
797                 return false;
798
799         if (pid <= 1) /* If we or PID 1 would be dead and have been waited for, this code would not be running */
800                 return true;
801
802         if (pid == getpid_cached())
803                 return true;
804
805         if (kill(pid, 0) >= 0)
806                 return true;
807
808         return errno != ESRCH;
809 }
810
811 bool pid_is_alive(pid_t pid) {
812         int r;
813
814         /* Checks whether a PID is still valid and not a zombie */
815
816         if (!pid_is_valid(pid))
817                 return false;
818
819         if (pid <= 1) /* If we or PID 1 would be a zombie, this code would not be running */
820                 return true;
821
822         if (pid == getpid_cached())
823                 return true;
824
825         r = get_process_state(pid);
826         if (r == -ESRCH || r == 'Z')
827                 return false;
828
829         return true;
830 }
831
832 #if 0 /// UNNEEDED by elogind
833 int pid_from_same_root_fs(pid_t pid) {
834         const char *root;
835
836         if (!pid_is_valid(pid))
837                 return false;
838
839         if (pid == 0 || pid == getpid_cached())
840                 return true;
841
842         root = procfs_file_alloca(pid, "root");
843
844         return files_same(root, "/proc/1/root", 0);
845 }
846 #endif // 0
847
848 bool is_main_thread(void) {
849         static thread_local int cached = 0;
850
851         if (_unlikely_(cached == 0))
852                 cached = getpid_cached() == gettid() ? 1 : -1;
853
854         return cached > 0;
855 }
856
857 #if 0 /// UNNEEDED by elogind
858 noreturn void freeze(void) {
859
860         log_close();
861
862         /* Make sure nobody waits for us on a socket anymore */
863         close_all_fds(NULL, 0);
864
865         sync();
866
867         for (;;)
868                 pause();
869 }
870
871 bool oom_score_adjust_is_valid(int oa) {
872         return oa >= OOM_SCORE_ADJ_MIN && oa <= OOM_SCORE_ADJ_MAX;
873 }
874
875 unsigned long personality_from_string(const char *p) {
876         int architecture;
877
878         if (!p)
879                 return PERSONALITY_INVALID;
880
881         /* Parse a personality specifier. We use our own identifiers that indicate specific ABIs, rather than just
882          * hints regarding the register size, since we want to keep things open for multiple locally supported ABIs for
883          * the same register size. */
884
885         architecture = architecture_from_string(p);
886         if (architecture < 0)
887                 return PERSONALITY_INVALID;
888
889         if (architecture == native_architecture())
890                 return PER_LINUX;
891 #ifdef SECONDARY_ARCHITECTURE
892         if (architecture == SECONDARY_ARCHITECTURE)
893                 return PER_LINUX32;
894 #endif
895
896         return PERSONALITY_INVALID;
897 }
898
899 const char* personality_to_string(unsigned long p) {
900         int architecture = _ARCHITECTURE_INVALID;
901
902         if (p == PER_LINUX)
903                 architecture = native_architecture();
904 #ifdef SECONDARY_ARCHITECTURE
905         else if (p == PER_LINUX32)
906                 architecture = SECONDARY_ARCHITECTURE;
907 #endif
908
909         if (architecture < 0)
910                 return NULL;
911
912         return architecture_to_string(architecture);
913 }
914
915 int safe_personality(unsigned long p) {
916         int ret;
917
918         /* So here's the deal, personality() is weirdly defined by glibc. In some cases it returns a failure via errno,
919          * and in others as negative return value containing an errno-like value. Let's work around this: this is a
920          * wrapper that uses errno if it is set, and uses the return value otherwise. And then it sets both errno and
921          * the return value indicating the same issue, so that we are definitely on the safe side.
922          *
923          * See https://github.com/elogind/elogind/issues/6737 */
924
925         errno = 0;
926         ret = personality(p);
927         if (ret < 0) {
928                 if (errno != 0)
929                         return -errno;
930
931                 errno = -ret;
932         }
933
934         return ret;
935 }
936
937 int opinionated_personality(unsigned long *ret) {
938         int current;
939
940         /* Returns the current personality, or PERSONALITY_INVALID if we can't determine it. This function is a bit
941          * opinionated though, and ignores all the finer-grained bits and exotic personalities, only distinguishing the
942          * two most relevant personalities: PER_LINUX and PER_LINUX32. */
943
944         current = safe_personality(PERSONALITY_INVALID);
945         if (current < 0)
946                 return current;
947
948         if (((unsigned long) current & 0xffff) == PER_LINUX32)
949                 *ret = PER_LINUX32;
950         else
951                 *ret = PER_LINUX;
952
953         return 0;
954 }
955
956 void valgrind_summary_hack(void) {
957 #ifdef HAVE_VALGRIND_VALGRIND_H
958         if (getpid_cached() == 1 && RUNNING_ON_VALGRIND) {
959                 pid_t pid;
960                 pid = raw_clone(SIGCHLD);
961                 if (pid < 0)
962                         log_emergency_errno(errno, "Failed to fork off valgrind helper: %m");
963                 else if (pid == 0)
964                         exit(EXIT_SUCCESS);
965                 else {
966                         log_info("Spawned valgrind helper as PID "PID_FMT".", pid);
967                         (void) wait_for_terminate(pid, NULL);
968                 }
969         }
970 #endif
971 }
972
973 int pid_compare_func(const void *a, const void *b) {
974         const pid_t *p = a, *q = b;
975
976         /* Suitable for usage in qsort() */
977
978         if (*p < *q)
979                 return -1;
980         if (*p > *q)
981                 return 1;
982         return 0;
983 }
984
985 int ioprio_parse_priority(const char *s, int *ret) {
986         int i, r;
987
988         assert(s);
989         assert(ret);
990
991         r = safe_atoi(s, &i);
992         if (r < 0)
993                 return r;
994
995         if (!ioprio_priority_is_valid(i))
996                 return -EINVAL;
997
998         *ret = i;
999         return 0;
1000 }
1001 #endif // 0
1002
1003 /* The cached PID, possible values:
1004  *
1005  *     == UNSET [0]  → cache not initialized yet
1006  *     == BUSY [-1]  → some thread is initializing it at the moment
1007  *     any other     → the cached PID
1008  */
1009
1010 #define CACHED_PID_UNSET ((pid_t) 0)
1011 #define CACHED_PID_BUSY ((pid_t) -1)
1012
1013 static pid_t cached_pid = CACHED_PID_UNSET;
1014
1015 static void reset_cached_pid(void) {
1016         /* Invoked in the child after a fork(), i.e. at the first moment the PID changed */
1017         cached_pid = CACHED_PID_UNSET;
1018 }
1019
1020 /* We use glibc __register_atfork() + __dso_handle directly here, as they are not included in the glibc
1021  * headers. __register_atfork() is mostly equivalent to pthread_atfork(), but doesn't require us to link against
1022  * libpthread, as it is part of glibc anyway. */
1023 extern int __register_atfork(void (*prepare) (void), void (*parent) (void), void (*child) (void), void * __dso_handle);
1024 extern void* __dso_handle __attribute__ ((__weak__));
1025
1026 pid_t getpid_cached(void) {
1027         pid_t current_value;
1028
1029         /* getpid_cached() is much like getpid(), but caches the value in local memory, to avoid having to invoke a
1030          * system call each time. This restores glibc behaviour from before 2.24, when getpid() was unconditionally
1031          * cached. Starting with 2.24 getpid() started to become prohibitively expensive when used for detecting when
1032          * objects were used across fork()s. With this caching the old behaviour is somewhat restored.
1033          *
1034          * https://bugzilla.redhat.com/show_bug.cgi?id=1443976
1035          * https://sourceware.org/git/gitweb.cgi?p=glibc.git;h=c579f48edba88380635ab98cb612030e3ed8691e
1036          */
1037
1038         current_value = __sync_val_compare_and_swap(&cached_pid, CACHED_PID_UNSET, CACHED_PID_BUSY);
1039
1040         switch (current_value) {
1041
1042         case CACHED_PID_UNSET: { /* Not initialized yet, then do so now */
1043                 pid_t new_pid;
1044
1045                 new_pid = getpid();
1046
1047                 if (__register_atfork(NULL, NULL, reset_cached_pid, __dso_handle) != 0) {
1048                         /* OOM? Let's try again later */
1049                         cached_pid = CACHED_PID_UNSET;
1050                         return new_pid;
1051                 }
1052
1053                 cached_pid = new_pid;
1054                 return new_pid;
1055         }
1056
1057         case CACHED_PID_BUSY: /* Somebody else is currently initializing */
1058                 return getpid();
1059
1060         default: /* Properly initialized */
1061                 return current_value;
1062         }
1063 }
1064
1065 #if 0 /// UNNEEDED by elogind
1066 static const char *const ioprio_class_table[] = {
1067         [IOPRIO_CLASS_NONE] = "none",
1068         [IOPRIO_CLASS_RT] = "realtime",
1069         [IOPRIO_CLASS_BE] = "best-effort",
1070         [IOPRIO_CLASS_IDLE] = "idle"
1071 };
1072
1073 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
1074
1075 static const char *const sigchld_code_table[] = {
1076         [CLD_EXITED] = "exited",
1077         [CLD_KILLED] = "killed",
1078         [CLD_DUMPED] = "dumped",
1079         [CLD_TRAPPED] = "trapped",
1080         [CLD_STOPPED] = "stopped",
1081         [CLD_CONTINUED] = "continued",
1082 };
1083
1084 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
1085
1086 static const char* const sched_policy_table[] = {
1087         [SCHED_OTHER] = "other",
1088         [SCHED_BATCH] = "batch",
1089         [SCHED_IDLE] = "idle",
1090         [SCHED_FIFO] = "fifo",
1091         [SCHED_RR] = "rr"
1092 };
1093
1094 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
1095 #endif // 0