]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/main.c
service: beautify debug log message a bit
[thirdparty/systemd.git] / src / core / main.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
a7334b09 2
60918275 3#include <errno.h>
3dfc9763 4#include <fcntl.h>
f170852a 5#include <getopt.h>
97c4f35c 6#include <signal.h>
3dfc9763
LP
7#include <stdio.h>
8#include <string.h>
664f88a7 9#include <sys/mount.h>
3dfc9763 10#include <sys/prctl.h>
b9e74c39 11#include <sys/reboot.h>
3dfc9763
LP
12#include <sys/stat.h>
13#include <unistd.h>
349cc4a5 14#if HAVE_SECCOMP
b64a3d86
LP
15#include <seccomp.h>
16#endif
349cc4a5 17#if HAVE_VALGRIND_VALGRIND_H
3dfc9763
LP
18#include <valgrind/valgrind.h>
19#endif
54b434b1 20
718db961 21#include "sd-bus.h"
cf0fbc49 22#include "sd-daemon.h"
b2e7486c 23#include "sd-messages.h"
3dfc9763 24
b5efdb8a 25#include "alloc-util.h"
d9d93745 26#include "architecture.h"
3dfc9763
LP
27#include "build.h"
28#include "bus-error.h"
29#include "bus-util.h"
430f0182 30#include "capability-util.h"
a88c5b8a 31#include "cgroup-util.h"
24efb112 32#include "clock-util.h"
3dfc9763 33#include "conf-parser.h"
618234a5 34#include "cpu-set-util.h"
bbc1acab 35#include "dbus.h"
3dfc9763
LP
36#include "dbus-manager.h"
37#include "def.h"
eee8b7ab 38#include "emergency-action.h"
3dfc9763 39#include "env-util.h"
57b7a260 40#include "exit-status.h"
3ffd4af2 41#include "fd-util.h"
3dfc9763 42#include "fdset.h"
718db961 43#include "fileio.h"
f97b34a6 44#include "format-util.h"
f4f15635 45#include "fs-util.h"
3dfc9763
LP
46#include "hostname-setup.h"
47#include "ima-setup.h"
48#include "killall.h"
49#include "kmod-setup.h"
eefc66aa 50#include "limits-util.h"
d7b8eec7 51#include "load-fragment.h"
3dfc9763 52#include "log.h"
b6e66135 53#include "loopback-setup.h"
b6e66135 54#include "machine-id-setup.h"
3dfc9763
LP
55#include "manager.h"
56#include "missing.h"
57#include "mount-setup.h"
d58ad743 58#include "os-util.h"
3dfc9763 59#include "pager.h"
6bedfcbb 60#include "parse-util.h"
7d5ceb64 61#include "path-util.h"
294bf0c3 62#include "pretty-print.h"
4e731273 63#include "proc-cmdline.h"
3dfc9763 64#include "process-util.h"
8869a0b4 65#include "raw-clone.h"
78f22b97 66#include "rlimit-util.h"
349cc4a5 67#if HAVE_SECCOMP
83f12b27
FS
68#include "seccomp-util.h"
69#endif
b6e66135 70#include "selinux-setup.h"
3dfc9763
LP
71#include "selinux-util.h"
72#include "signal-util.h"
ffbd2c4d 73#include "smack-setup.h"
3dfc9763 74#include "special.h"
8fcde012 75#include "stat-util.h"
15a5e950 76#include "stdio-util.h"
3dfc9763
LP
77#include "strv.h"
78#include "switch-root.h"
a8b627aa 79#include "sysctl-util.h"
3dfc9763 80#include "terminal-util.h"
8612da97 81#include "umask-util.h"
b1d4f8e1 82#include "user-util.h"
9ce17593 83#include "util.h"
3dfc9763
LP
84#include "virt.h"
85#include "watchdog.h"
b6e66135 86
7e11a95e
EV
87#if HAS_FEATURE_ADDRESS_SANITIZER
88#include <sanitizer/lsan_interface.h>
89#endif
90
f170852a
LP
91static enum {
92 ACTION_RUN,
e965d56d 93 ACTION_HELP,
9ba0bc4e 94 ACTION_VERSION,
e537352b 95 ACTION_TEST,
bbc1acab
YW
96 ACTION_DUMP_CONFIGURATION_ITEMS,
97 ACTION_DUMP_BUS_PROPERTIES,
fa0f4d8a 98} arg_action = ACTION_RUN;
fa0f4d8a 99static char *arg_default_unit = NULL;
463d0d15 100static bool arg_system = false;
fa0f4d8a 101static bool arg_dump_core = true;
fa0f4d8a 102static int arg_crash_chvt = -1;
b9e74c39
LP
103static bool arg_crash_shell = false;
104static bool arg_crash_reboot = false;
7d5ceb64 105static char *arg_confirm_spawn = NULL;
7a293242 106static ShowStatus arg_show_status = _SHOW_STATUS_INVALID;
bf4df7c3 107static bool arg_switched_root = false;
0221d68a 108static PagerFlags arg_pager_flags = 0;
2a12e32e 109static bool arg_service_watchdogs = true;
706343f4 110static ExecOutput arg_default_std_output = EXEC_OUTPUT_JOURNAL;
0a494f1f 111static ExecOutput arg_default_std_error = EXEC_OUTPUT_INHERIT;
1f19a534
OS
112static usec_t arg_default_restart_usec = DEFAULT_RESTART_USEC;
113static usec_t arg_default_timeout_start_usec = DEFAULT_TIMEOUT_USEC;
114static usec_t arg_default_timeout_stop_usec = DEFAULT_TIMEOUT_USEC;
3f41e1e5
LN
115static usec_t arg_default_start_limit_interval = DEFAULT_START_LIMIT_INTERVAL;
116static unsigned arg_default_start_limit_burst = DEFAULT_START_LIMIT_BURST;
e96d6be7
LP
117static usec_t arg_runtime_watchdog = 0;
118static usec_t arg_shutdown_watchdog = 10 * USEC_PER_MINUTE;
c6885f5f 119static char *arg_early_core_pattern = NULL;
8a2c1fbf 120static char *arg_watchdog_device = NULL;
97d0e5f8 121static char **arg_default_environment = NULL;
517d56b1 122static struct rlimit *arg_default_rlimit[_RLIMIT_MAX] = {};
a103496c 123static uint64_t arg_capability_bounding_set = CAP_ALL;
39362f6f 124static bool arg_no_new_privs = false;
3a43da28 125static nsec_t arg_timer_slack_nsec = NSEC_INFINITY;
bd8f585b 126static usec_t arg_default_timer_accuracy_usec = 1 * USEC_PER_MINUTE;
d3b1c508
LP
127static Set* arg_syscall_archs = NULL;
128static FILE* arg_serialization = NULL;
a88c5b8a 129static int arg_default_cpu_accounting = -1;
13c31542 130static bool arg_default_io_accounting = false;
377bfd2d 131static bool arg_default_ip_accounting = false;
085afe36 132static bool arg_default_blockio_accounting = false;
444d5863 133static bool arg_default_memory_accounting = MEMORY_ACCOUNTING_DEFAULT;
9ded9cd1 134static bool arg_default_tasks_accounting = true;
79baeeb9 135static uint64_t arg_default_tasks_max = UINT64_MAX;
ee48dbd5 136static sd_id128_t arg_machine_id = {};
ae8c7939 137static EmergencyAction arg_cad_burst_action = EMERGENCY_ACTION_REBOOT_FORCE;
4fc935ca 138
bb259772
LP
139_noreturn_ static void freeze_or_exit_or_reboot(void) {
140
c3b6a348
LP
141 /* If we are running in a container, let's prefer exiting, after all we can propagate an exit code to
142 * the container manager, and thus inform it that something went wrong. */
bb259772
LP
143 if (detect_container() > 0) {
144 log_emergency("Exiting PID 1...");
c3b6a348 145 _exit(EXIT_EXCEPTION);
bb259772 146 }
b9e74c39
LP
147
148 if (arg_crash_reboot) {
149 log_notice("Rebooting in 10s...");
150 (void) sleep(10);
151
152 log_notice("Rebooting now...");
153 (void) reboot(RB_AUTOBOOT);
154 log_emergency_errno(errno, "Failed to reboot: %m");
155 }
156
157 log_emergency("Freezing execution.");
158 freeze();
159}
160
848e863a 161_noreturn_ static void crash(int sig) {
7d06dad9
MS
162 struct sigaction sa;
163 pid_t pid;
97c4f35c 164
df0ff127 165 if (getpid_cached() != 1)
abb26902 166 /* Pass this on immediately, if this is not PID 1 */
92ca4cac 167 (void) raise(sig);
abb26902 168 else if (!arg_dump_core)
4104970e 169 log_emergency("Caught <%s>, not dumping core.", signal_to_string(sig));
97c4f35c 170 else {
7d06dad9 171 sa = (struct sigaction) {
189d5bac 172 .sa_handler = nop_signal_handler,
b92bea5d
ZJS
173 .sa_flags = SA_NOCLDSTOP|SA_RESTART,
174 };
97c4f35c 175
6f5e3f35 176 /* We want to wait for the core process, hence let's enable SIGCHLD */
92ca4cac 177 (void) sigaction(SIGCHLD, &sa, NULL);
6f5e3f35 178
8869a0b4 179 pid = raw_clone(SIGCHLD);
e62d8c39 180 if (pid < 0)
56f64d95 181 log_emergency_errno(errno, "Caught <%s>, cannot fork for core dump: %m", signal_to_string(sig));
97c4f35c 182 else if (pid == 0) {
97c4f35c 183 /* Enable default signal handler for core dump */
15a90032 184
92ca4cac
LP
185 sa = (struct sigaction) {
186 .sa_handler = SIG_DFL,
187 };
188 (void) sigaction(sig, &sa, NULL);
97c4f35c 189
15a90032
LP
190 /* Don't limit the coredump size */
191 (void) setrlimit(RLIMIT_CORE, &RLIMIT_MAKE_CONST(RLIM_INFINITY));
97c4f35c
LP
192
193 /* Just to be sure... */
e62d9b81 194 (void) chdir("/");
97c4f35c
LP
195
196 /* Raise the signal again */
ee05e779 197 pid = raw_getpid();
92ca4cac 198 (void) kill(pid, sig); /* raise() would kill the parent */
97c4f35c
LP
199
200 assert_not_reached("We shouldn't be here...");
bb85a582 201 _exit(EXIT_EXCEPTION);
4fc935ca 202 } else {
8e12a6ae
LP
203 siginfo_t status;
204 int r;
4fc935ca
LP
205
206 /* Order things nicely. */
e62d8c39
ZJS
207 r = wait_for_terminate(pid, &status);
208 if (r < 0)
da927ba9 209 log_emergency_errno(r, "Caught <%s>, waitpid() failed: %m", signal_to_string(sig));
8e12a6ae 210 else if (status.si_code != CLD_DUMPED)
ee05e779
ZJS
211 log_emergency("Caught <%s>, core dump failed (child "PID_FMT", code=%s, status=%i/%s).",
212 signal_to_string(sig),
213 pid, sigchld_code_to_string(status.si_code),
214 status.si_status,
215 strna(status.si_code == CLD_EXITED
38107f5a 216 ? exit_status_to_string(status.si_status, EXIT_STATUS_MINIMAL)
ee05e779 217 : signal_to_string(status.si_status)));
4fc935ca 218 else
4104970e 219 log_emergency("Caught <%s>, dumped core as pid "PID_FMT".", signal_to_string(sig), pid);
97c4f35c
LP
220 }
221 }
222
b9e74c39 223 if (arg_crash_chvt >= 0)
92ca4cac 224 (void) chvt(arg_crash_chvt);
601f6a1e 225
7d06dad9
MS
226 sa = (struct sigaction) {
227 .sa_handler = SIG_IGN,
228 .sa_flags = SA_NOCLDSTOP|SA_NOCLDWAIT|SA_RESTART,
229 };
230
231 /* Let the kernel reap children for us */
232 (void) sigaction(SIGCHLD, &sa, NULL);
8c43883a 233
7d06dad9 234 if (arg_crash_shell) {
b9e74c39 235 log_notice("Executing crash shell in 10s...");
92ca4cac 236 (void) sleep(10);
4fc935ca 237
8869a0b4 238 pid = raw_clone(SIGCHLD);
cd3bd60a 239 if (pid < 0)
56f64d95 240 log_emergency_errno(errno, "Failed to fork off crash shell: %m");
6f5e3f35 241 else if (pid == 0) {
b9e74c39 242 (void) setsid();
92ca4cac 243 (void) make_console_stdio();
595225af 244 (void) rlimit_nofile_safe();
92ca4cac 245 (void) execle("/bin/sh", "/bin/sh", NULL, environ);
6f5e3f35 246
ee05e779 247 log_emergency_errno(errno, "execle() failed: %m");
bb85a582 248 _exit(EXIT_EXCEPTION);
b9e74c39
LP
249 } else {
250 log_info("Spawned crash shell as PID "PID_FMT".", pid);
4cf0b03b 251 (void) wait_for_terminate(pid, NULL);
b9e74c39 252 }
4fc935ca
LP
253 }
254
bb259772 255 freeze_or_exit_or_reboot();
97c4f35c
LP
256}
257
258static void install_crash_handler(void) {
297d563d 259 static const struct sigaction sa = {
b92bea5d 260 .sa_handler = crash,
297d563d 261 .sa_flags = SA_NODEFER, /* So that we can raise the signal again from the signal handler */
b92bea5d 262 };
297d563d 263 int r;
97c4f35c 264
297d563d
LP
265 /* We ignore the return value here, since, we don't mind if we
266 * cannot set up a crash handler */
267 r = sigaction_many(&sa, SIGNALS_CRASH_HANDLER, -1);
268 if (r < 0)
269 log_debug_errno(r, "I had trouble setting up the crash handler, ignoring: %m");
97c4f35c 270}
f170852a 271
56d96fc0
LP
272static int console_setup(void) {
273 _cleanup_close_ int tty_fd = -1;
274 int r;
80876c20 275
512947d4 276 tty_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
23bbb0de
MS
277 if (tty_fd < 0)
278 return log_error_errno(tty_fd, "Failed to open /dev/console: %m");
80876c20 279
56d96fc0
LP
280 /* We don't want to force text mode. plymouth may be showing
281 * pictures already from initrd. */
512947d4 282 r = reset_terminal_fd(tty_fd, false);
23bbb0de
MS
283 if (r < 0)
284 return log_error_errno(r, "Failed to reset /dev/console: %m");
843d2643 285
56d96fc0 286 return 0;
80876c20
LP
287}
288
b9e74c39
LP
289static int parse_crash_chvt(const char *value) {
290 int b;
291
292 if (safe_atoi(value, &arg_crash_chvt) >= 0)
293 return 0;
294
295 b = parse_boolean(value);
296 if (b < 0)
297 return b;
298
299 if (b > 0)
300 arg_crash_chvt = 0; /* switch to where kmsg goes */
301 else
302 arg_crash_chvt = -1; /* turn off switching */
303
304 return 0;
305}
306
7d5ceb64
FB
307static int parse_confirm_spawn(const char *value, char **console) {
308 char *s;
309 int r;
310
311 r = value ? parse_boolean(value) : 1;
312 if (r == 0) {
313 *console = NULL;
314 return 0;
315 }
316
317 if (r > 0) /* on with default tty */
318 s = strdup("/dev/console");
319 else if (is_path(value)) /* on with fully qualified path */
320 s = strdup(value);
321 else /* on with only a tty file name, not a fully qualified path */
322 s = strjoin("/dev/", value);
323 if (!s)
324 return -ENOMEM;
5b65ae15 325
7d5ceb64
FB
326 *console = s;
327 return 0;
328}
329
ee48dbd5 330static int set_machine_id(const char *m) {
e042eab7 331 sd_id128_t t;
8b26cdbd 332 assert(m);
ee48dbd5 333
e042eab7 334 if (sd_id128_from_string(m, &t) < 0)
ee48dbd5
NC
335 return -EINVAL;
336
e042eab7 337 if (sd_id128_is_null(t))
ee48dbd5
NC
338 return -EINVAL;
339
e042eab7 340 arg_machine_id = t;
ee48dbd5
NC
341 return 0;
342}
343
96287a49 344static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
f170852a 345
059cb385 346 int r;
f170852a 347
059cb385 348 assert(key);
5192bd19 349
1d84ad94 350 if (STR_IN_SET(key, "systemd.unit", "rd.systemd.unit")) {
bf4df7c3 351
1d84ad94
LP
352 if (proc_cmdline_value_missing(key, value))
353 return 0;
bf4df7c3 354
1d84ad94
LP
355 if (!unit_name_is_valid(value, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
356 log_warning("Unit name specified on %s= is not valid, ignoring: %s", key, value);
357 else if (in_initrd() == !!startswith(key, "rd.")) {
358 if (free_and_strdup(&arg_default_unit, value) < 0)
359 return log_oom();
360 }
f170852a 361
1d84ad94 362 } else if (proc_cmdline_key_streq(key, "systemd.dump_core")) {
4fc935ca 363
1d84ad94 364 r = value ? parse_boolean(value) : true;
fb472900 365 if (r < 0)
5e1ee764 366 log_warning_errno(r, "Failed to parse dump core switch %s, ignoring: %m", value);
4fc935ca 367 else
fa0f4d8a 368 arg_dump_core = r;
4fc935ca 369
c6885f5f
FB
370 } else if (proc_cmdline_key_streq(key, "systemd.early_core_pattern")) {
371
372 if (proc_cmdline_value_missing(key, value))
373 return 0;
374
375 if (path_is_absolute(value))
376 (void) parse_path_argument_and_warn(value, false, &arg_early_core_pattern);
377 else
378 log_warning("Specified core pattern '%s' is not an absolute path, ignoring.", value);
379
1d84ad94 380 } else if (proc_cmdline_key_streq(key, "systemd.crash_chvt")) {
b9e74c39 381
1d84ad94
LP
382 if (!value)
383 arg_crash_chvt = 0; /* turn on */
5e1ee764
YW
384 else {
385 r = parse_crash_chvt(value);
386 if (r < 0)
387 log_warning_errno(r, "Failed to parse crash chvt switch %s, ignoring: %m", value);
388 }
b9e74c39 389
1d84ad94 390 } else if (proc_cmdline_key_streq(key, "systemd.crash_shell")) {
4fc935ca 391
1d84ad94 392 r = value ? parse_boolean(value) : true;
fb472900 393 if (r < 0)
5e1ee764 394 log_warning_errno(r, "Failed to parse crash shell switch %s, ignoring: %m", value);
4fc935ca 395 else
fa0f4d8a 396 arg_crash_shell = r;
5e7ee61c 397
1d84ad94 398 } else if (proc_cmdline_key_streq(key, "systemd.crash_reboot")) {
5e7ee61c 399
1d84ad94 400 r = value ? parse_boolean(value) : true;
b9e74c39 401 if (r < 0)
5e1ee764 402 log_warning_errno(r, "Failed to parse crash reboot switch %s, ignoring: %m", value);
5e7ee61c 403 else
b9e74c39 404 arg_crash_reboot = r;
5e7ee61c 405
1d84ad94
LP
406 } else if (proc_cmdline_key_streq(key, "systemd.confirm_spawn")) {
407 char *s;
7d5ceb64 408
1d84ad94 409 r = parse_confirm_spawn(value, &s);
059cb385 410 if (r < 0)
5e1ee764
YW
411 log_warning_errno(r, "Failed to parse confirm_spawn switch %s, ignoring: %m", value);
412 else
413 free_and_replace(arg_confirm_spawn, s);
601f6a1e 414
2a12e32e
JK
415 } else if (proc_cmdline_key_streq(key, "systemd.service_watchdogs")) {
416
417 r = value ? parse_boolean(value) : true;
418 if (r < 0)
5e1ee764 419 log_warning_errno(r, "Failed to parse service watchdog switch %s, ignoring: %m", value);
2a12e32e
JK
420 else
421 arg_service_watchdogs = r;
422
1d84ad94 423 } else if (proc_cmdline_key_streq(key, "systemd.show_status")) {
9e58ff9c 424
1d84ad94
LP
425 if (value) {
426 r = parse_show_status(value, &arg_show_status);
427 if (r < 0)
5e1ee764 428 log_warning_errno(r, "Failed to parse show status switch %s, ignoring: %m", value);
1d84ad94
LP
429 } else
430 arg_show_status = SHOW_STATUS_YES;
059cb385 431
1d84ad94
LP
432 } else if (proc_cmdline_key_streq(key, "systemd.default_standard_output")) {
433
434 if (proc_cmdline_value_missing(key, value))
435 return 0;
0a494f1f 436
059cb385 437 r = exec_output_from_string(value);
fb472900 438 if (r < 0)
5e1ee764 439 log_warning_errno(r, "Failed to parse default standard output switch %s, ignoring: %m", value);
0a494f1f
LP
440 else
441 arg_default_std_output = r;
0a494f1f 442
1d84ad94
LP
443 } else if (proc_cmdline_key_streq(key, "systemd.default_standard_error")) {
444
445 if (proc_cmdline_value_missing(key, value))
446 return 0;
059cb385
LP
447
448 r = exec_output_from_string(value);
fb472900 449 if (r < 0)
5e1ee764 450 log_warning_errno(r, "Failed to parse default standard error switch %s, ignoring: %m", value);
0a494f1f
LP
451 else
452 arg_default_std_error = r;
9e7c5357 453
1d84ad94
LP
454 } else if (streq(key, "systemd.setenv")) {
455
456 if (proc_cmdline_value_missing(key, value))
457 return 0;
059cb385
LP
458
459 if (env_assignment_is_valid(value)) {
e21fea24
KS
460 char **env;
461
059cb385 462 env = strv_env_set(arg_default_environment, value);
1d84ad94
LP
463 if (!env)
464 return log_oom();
465
466 arg_default_environment = env;
e21fea24 467 } else
059cb385 468 log_warning("Environment variable name '%s' is not valid. Ignoring.", value);
9e58ff9c 469
1d84ad94
LP
470 } else if (proc_cmdline_key_streq(key, "systemd.machine_id")) {
471
472 if (proc_cmdline_value_missing(key, value))
473 return 0;
474
475 r = set_machine_id(value);
476 if (r < 0)
5e1ee764 477 log_warning_errno(r, "MachineID '%s' is not valid, ignoring: %m", value);
ee48dbd5 478
1d84ad94
LP
479 } else if (proc_cmdline_key_streq(key, "systemd.default_timeout_start_sec")) {
480
481 if (proc_cmdline_value_missing(key, value))
482 return 0;
483
484 r = parse_sec(value, &arg_default_timeout_start_usec);
485 if (r < 0)
5e1ee764 486 log_warning_errno(r, "Failed to parse default start timeout '%s', ignoring: %m", value);
1d84ad94
LP
487
488 if (arg_default_timeout_start_usec <= 0)
489 arg_default_timeout_start_usec = USEC_INFINITY;
ee48dbd5 490
8a2c1fbf
EJ
491 } else if (proc_cmdline_key_streq(key, "systemd.watchdog_device")) {
492
493 if (proc_cmdline_value_missing(key, value))
494 return 0;
495
c6885f5f 496 (void) parse_path_argument_and_warn(value, false, &arg_watchdog_device);
8a2c1fbf 497
059cb385 498 } else if (streq(key, "quiet") && !value) {
d7b15e0a 499
7a293242 500 if (arg_show_status == _SHOW_STATUS_INVALID)
d450b6f2 501 arg_show_status = SHOW_STATUS_AUTO;
059cb385
LP
502
503 } else if (streq(key, "debug") && !value) {
d7b15e0a 504
1de1c9c3
LP
505 /* Note that log_parse_environment() handles 'debug'
506 * too, and sets the log level to LOG_DEBUG. */
d7b15e0a 507
75f86906 508 if (detect_container() > 0)
b2103dcc 509 log_set_target(LOG_TARGET_CONSOLE);
059cb385 510
dcd61450 511 } else if (!value) {
e2c9a131 512 const char *target;
f170852a
LP
513
514 /* SysV compatibility */
e2c9a131
EV
515 target = runlevel_to_target(key);
516 if (target)
517 return free_and_strdup(&arg_default_unit, target);
f170852a
LP
518 }
519
520 return 0;
521}
522
e8e581bf
ZJS
523#define DEFINE_SETTER(name, func, descr) \
524 static int name(const char *unit, \
525 const char *filename, \
526 unsigned line, \
527 const char *section, \
71a61510 528 unsigned section_line, \
e8e581bf
ZJS
529 const char *lvalue, \
530 int ltype, \
531 const char *rvalue, \
532 void *data, \
533 void *userdata) { \
534 \
535 int r; \
536 \
537 assert(filename); \
538 assert(lvalue); \
539 assert(rvalue); \
540 \
541 r = func(rvalue); \
542 if (r < 0) \
d1cefe0a
LP
543 log_syntax(unit, LOG_ERR, filename, line, r, \
544 "Invalid " descr "'%s': %m", \
545 rvalue); \
e8e581bf
ZJS
546 \
547 return 0; \
548 }
487393e9 549
a6ecbf83
FB
550DEFINE_SETTER(config_parse_level2, log_set_max_level_from_string, "log level");
551DEFINE_SETTER(config_parse_target, log_set_target_from_string, "target");
552DEFINE_SETTER(config_parse_color, log_show_color_from_string, "color" );
553DEFINE_SETTER(config_parse_location, log_show_location_from_string, "location");
487393e9 554
4d7213b2
LP
555static int config_parse_cpu_affinity2(
556 const char *unit,
557 const char *filename,
558 unsigned line,
559 const char *section,
560 unsigned section_line,
561 const char *lvalue,
562 int ltype,
563 const char *rvalue,
564 void *data,
565 void *userdata) {
487393e9 566
4b40bc38 567 _cleanup_cpu_free_ cpu_set_t *c = NULL;
f5c72b73 568 int ncpus;
487393e9 569
765d143b 570 ncpus = parse_cpu_set_and_warn(rvalue, &c, unit, filename, line, lvalue);
f5c72b73
FB
571 if (ncpus < 0)
572 return ncpus;
487393e9 573
f5c72b73 574 if (sched_setaffinity(0, CPU_ALLOC_SIZE(ncpus), c) < 0)
25f027c5 575 log_warning_errno(errno, "Failed to set CPU affinity: %m");
487393e9 576
487393e9
LP
577 return 0;
578}
579
4d7213b2
LP
580static int config_parse_show_status(
581 const char* unit,
582 const char *filename,
583 unsigned line,
584 const char *section,
585 unsigned section_line,
586 const char *lvalue,
587 int ltype,
588 const char *rvalue,
589 void *data,
590 void *userdata) {
591
592 int k;
593 ShowStatus *b = data;
594
595 assert(filename);
596 assert(lvalue);
597 assert(rvalue);
598 assert(data);
599
600 k = parse_show_status(rvalue, b);
601 if (k < 0) {
12ca818f 602 log_syntax(unit, LOG_ERR, filename, line, k, "Failed to parse show status setting, ignoring: %s", rvalue);
4d7213b2
LP
603 return 0;
604 }
605
606 return 0;
607}
608
5db98187
LP
609static int config_parse_output_restricted(
610 const char* unit,
611 const char *filename,
612 unsigned line,
613 const char *section,
614 unsigned section_line,
615 const char *lvalue,
616 int ltype,
617 const char *rvalue,
618 void *data,
619 void *userdata) {
620
621 ExecOutput t, *eo = data;
622
623 assert(filename);
624 assert(lvalue);
625 assert(rvalue);
626 assert(data);
627
628 t = exec_output_from_string(rvalue);
629 if (t < 0) {
630 log_syntax(unit, LOG_ERR, filename, line, 0, "Failed to parse output type, ignoring: %s", rvalue);
631 return 0;
632 }
633
566b7d23
ZD
634 if (IN_SET(t, EXEC_OUTPUT_SOCKET, EXEC_OUTPUT_NAMED_FD, EXEC_OUTPUT_FILE, EXEC_OUTPUT_FILE_APPEND)) {
635 log_syntax(unit, LOG_ERR, filename, line, 0, "Standard output types socket, fd:, file:, append: are not supported as defaults, ignoring: %s", rvalue);
5db98187
LP
636 return 0;
637 }
638
639 *eo = t;
640 return 0;
641}
642
b9e74c39
LP
643static int config_parse_crash_chvt(
644 const char* unit,
645 const char *filename,
646 unsigned line,
647 const char *section,
648 unsigned section_line,
649 const char *lvalue,
650 int ltype,
651 const char *rvalue,
652 void *data,
653 void *userdata) {
654
655 int r;
656
657 assert(filename);
658 assert(lvalue);
659 assert(rvalue);
b9e74c39
LP
660
661 r = parse_crash_chvt(rvalue);
662 if (r < 0) {
663 log_syntax(unit, LOG_ERR, filename, line, r, "Failed to parse CrashChangeVT= setting, ignoring: %s", rvalue);
664 return 0;
665 }
666
667 return 0;
668}
669
487393e9
LP
670static int parse_config_file(void) {
671
f975e971 672 const ConfigTableItem items[] = {
d3b1c508
LP
673 { "Manager", "LogLevel", config_parse_level2, 0, NULL },
674 { "Manager", "LogTarget", config_parse_target, 0, NULL },
675 { "Manager", "LogColor", config_parse_color, 0, NULL },
676 { "Manager", "LogLocation", config_parse_location, 0, NULL },
677 { "Manager", "DumpCore", config_parse_bool, 0, &arg_dump_core },
b9e74c39
LP
678 { "Manager", "CrashChVT", /* legacy */ config_parse_crash_chvt, 0, NULL },
679 { "Manager", "CrashChangeVT", config_parse_crash_chvt, 0, NULL },
d3b1c508 680 { "Manager", "CrashShell", config_parse_bool, 0, &arg_crash_shell },
b9e74c39 681 { "Manager", "CrashReboot", config_parse_bool, 0, &arg_crash_reboot },
d3b1c508 682 { "Manager", "ShowStatus", config_parse_show_status, 0, &arg_show_status },
d3b1c508 683 { "Manager", "CPUAffinity", config_parse_cpu_affinity2, 0, NULL },
143fadf3 684 { "Manager", "JoinControllers", config_parse_warn_compat, DISABLED_CONFIGURATION, NULL },
d3b1c508
LP
685 { "Manager", "RuntimeWatchdogSec", config_parse_sec, 0, &arg_runtime_watchdog },
686 { "Manager", "ShutdownWatchdogSec", config_parse_sec, 0, &arg_shutdown_watchdog },
8a2c1fbf 687 { "Manager", "WatchdogDevice", config_parse_path, 0, &arg_watchdog_device },
a103496c 688 { "Manager", "CapabilityBoundingSet", config_parse_capability_set, 0, &arg_capability_bounding_set },
39362f6f 689 { "Manager", "NoNewPrivileges", config_parse_bool, 0, &arg_no_new_privs },
349cc4a5 690#if HAVE_SECCOMP
d3b1c508 691 { "Manager", "SystemCallArchitectures", config_parse_syscall_archs, 0, &arg_syscall_archs },
89fffa27 692#endif
d3b1c508 693 { "Manager", "TimerSlackNSec", config_parse_nsec, 0, &arg_timer_slack_nsec },
bd8f585b 694 { "Manager", "DefaultTimerAccuracySec", config_parse_sec, 0, &arg_default_timer_accuracy_usec },
5db98187
LP
695 { "Manager", "DefaultStandardOutput", config_parse_output_restricted,0, &arg_default_std_output },
696 { "Manager", "DefaultStandardError", config_parse_output_restricted,0, &arg_default_std_error },
d3b1c508
LP
697 { "Manager", "DefaultTimeoutStartSec", config_parse_sec, 0, &arg_default_timeout_start_usec },
698 { "Manager", "DefaultTimeoutStopSec", config_parse_sec, 0, &arg_default_timeout_stop_usec },
699 { "Manager", "DefaultRestartSec", config_parse_sec, 0, &arg_default_restart_usec },
f0367da7
LP
700 { "Manager", "DefaultStartLimitInterval", config_parse_sec, 0, &arg_default_start_limit_interval }, /* obsolete alias */
701 { "Manager", "DefaultStartLimitIntervalSec",config_parse_sec, 0, &arg_default_start_limit_interval },
d3b1c508
LP
702 { "Manager", "DefaultStartLimitBurst", config_parse_unsigned, 0, &arg_default_start_limit_burst },
703 { "Manager", "DefaultEnvironment", config_parse_environ, 0, &arg_default_environment },
4f424df7
LP
704 { "Manager", "DefaultLimitCPU", config_parse_rlimit, RLIMIT_CPU, arg_default_rlimit },
705 { "Manager", "DefaultLimitFSIZE", config_parse_rlimit, RLIMIT_FSIZE, arg_default_rlimit },
706 { "Manager", "DefaultLimitDATA", config_parse_rlimit, RLIMIT_DATA, arg_default_rlimit },
707 { "Manager", "DefaultLimitSTACK", config_parse_rlimit, RLIMIT_STACK, arg_default_rlimit },
708 { "Manager", "DefaultLimitCORE", config_parse_rlimit, RLIMIT_CORE, arg_default_rlimit },
709 { "Manager", "DefaultLimitRSS", config_parse_rlimit, RLIMIT_RSS, arg_default_rlimit },
710 { "Manager", "DefaultLimitNOFILE", config_parse_rlimit, RLIMIT_NOFILE, arg_default_rlimit },
711 { "Manager", "DefaultLimitAS", config_parse_rlimit, RLIMIT_AS, arg_default_rlimit },
712 { "Manager", "DefaultLimitNPROC", config_parse_rlimit, RLIMIT_NPROC, arg_default_rlimit },
713 { "Manager", "DefaultLimitMEMLOCK", config_parse_rlimit, RLIMIT_MEMLOCK, arg_default_rlimit },
714 { "Manager", "DefaultLimitLOCKS", config_parse_rlimit, RLIMIT_LOCKS, arg_default_rlimit },
715 { "Manager", "DefaultLimitSIGPENDING", config_parse_rlimit, RLIMIT_SIGPENDING, arg_default_rlimit },
716 { "Manager", "DefaultLimitMSGQUEUE", config_parse_rlimit, RLIMIT_MSGQUEUE, arg_default_rlimit },
717 { "Manager", "DefaultLimitNICE", config_parse_rlimit, RLIMIT_NICE, arg_default_rlimit },
718 { "Manager", "DefaultLimitRTPRIO", config_parse_rlimit, RLIMIT_RTPRIO, arg_default_rlimit },
719 { "Manager", "DefaultLimitRTTIME", config_parse_rlimit, RLIMIT_RTTIME, arg_default_rlimit },
a88c5b8a 720 { "Manager", "DefaultCPUAccounting", config_parse_tristate, 0, &arg_default_cpu_accounting },
13c31542 721 { "Manager", "DefaultIOAccounting", config_parse_bool, 0, &arg_default_io_accounting },
377bfd2d 722 { "Manager", "DefaultIPAccounting", config_parse_bool, 0, &arg_default_ip_accounting },
085afe36
LP
723 { "Manager", "DefaultBlockIOAccounting", config_parse_bool, 0, &arg_default_blockio_accounting },
724 { "Manager", "DefaultMemoryAccounting", config_parse_bool, 0, &arg_default_memory_accounting },
03a7b521 725 { "Manager", "DefaultTasksAccounting", config_parse_bool, 0, &arg_default_tasks_accounting },
0af20ea2 726 { "Manager", "DefaultTasksMax", config_parse_tasks_max, 0, &arg_default_tasks_max },
ae8c7939 727 { "Manager", "CtrlAltDelBurstAction", config_parse_emergency_action, 0, &arg_cad_burst_action },
d3b1c508 728 {}
487393e9
LP
729 };
730
1b907b5c 731 const char *fn, *conf_dirs_nulstr;
487393e9 732
463d0d15 733 fn = arg_system ?
75eb6154
LP
734 PKGSYSCONFDIR "/system.conf" :
735 PKGSYSCONFDIR "/user.conf";
736
463d0d15 737 conf_dirs_nulstr = arg_system ?
75eb6154
LP
738 CONF_PATHS_NULSTR("systemd/system.conf.d") :
739 CONF_PATHS_NULSTR("systemd/user.conf.d");
740
bcde742e 741 (void) config_parse_many_nulstr(fn, conf_dirs_nulstr, "Manager\0", config_item_table_lookup, items, CONFIG_PARSE_WARN, NULL);
36c16a7c
LP
742
743 /* Traditionally "0" was used to turn off the default unit timeouts. Fix this up so that we used USEC_INFINITY
744 * like everywhere else. */
745 if (arg_default_timeout_start_usec <= 0)
746 arg_default_timeout_start_usec = USEC_INFINITY;
747 if (arg_default_timeout_stop_usec <= 0)
748 arg_default_timeout_stop_usec = USEC_INFINITY;
487393e9 749
487393e9
LP
750 return 0;
751}
752
85cb4151 753static void set_manager_defaults(Manager *m) {
06af2a04
TB
754
755 assert(m);
756
5b65ae15
LP
757 /* Propagates the various default unit property settings into the manager object, i.e. properties that do not
758 * affect the manager itself, but are just what newly allocated units will have set if they haven't set
759 * anything else. (Also see set_manager_settings() for the settings that affect the manager's own behaviour) */
760
06af2a04
TB
761 m->default_timer_accuracy_usec = arg_default_timer_accuracy_usec;
762 m->default_std_output = arg_default_std_output;
763 m->default_std_error = arg_default_std_error;
764 m->default_timeout_start_usec = arg_default_timeout_start_usec;
765 m->default_timeout_stop_usec = arg_default_timeout_stop_usec;
766 m->default_restart_usec = arg_default_restart_usec;
767 m->default_start_limit_interval = arg_default_start_limit_interval;
768 m->default_start_limit_burst = arg_default_start_limit_burst;
a88c5b8a
CD
769
770 /* On 4.15+ with unified hierarchy, CPU accounting is essentially free as it doesn't require the CPU
771 * controller to be enabled, so the default is to enable it unless we got told otherwise. */
772 if (arg_default_cpu_accounting >= 0)
773 m->default_cpu_accounting = arg_default_cpu_accounting;
774 else
775 m->default_cpu_accounting = cpu_accounting_is_cheap();
776
13c31542 777 m->default_io_accounting = arg_default_io_accounting;
377bfd2d 778 m->default_ip_accounting = arg_default_ip_accounting;
06af2a04
TB
779 m->default_blockio_accounting = arg_default_blockio_accounting;
780 m->default_memory_accounting = arg_default_memory_accounting;
03a7b521 781 m->default_tasks_accounting = arg_default_tasks_accounting;
0af20ea2 782 m->default_tasks_max = arg_default_tasks_max;
06af2a04 783
79a224c4
LP
784 (void) manager_set_default_rlimits(m, arg_default_rlimit);
785
786 (void) manager_default_environment(m);
787 (void) manager_transient_environment_add(m, arg_default_environment);
06af2a04
TB
788}
789
7b46fc6a
LP
790static void set_manager_settings(Manager *m) {
791
792 assert(m);
793
5b65ae15
LP
794 /* Propagates the various manager settings into the manager object, i.e. properties that effect the manager
795 * itself (as opposed to just being inherited into newly allocated units, see set_manager_defaults() above). */
796
7b46fc6a 797 m->confirm_spawn = arg_confirm_spawn;
2a12e32e 798 m->service_watchdogs = arg_service_watchdogs;
7b46fc6a
LP
799 m->runtime_watchdog = arg_runtime_watchdog;
800 m->shutdown_watchdog = arg_shutdown_watchdog;
801 m->cad_burst_action = arg_cad_burst_action;
802
803 manager_set_show_status(m, arg_show_status);
804}
805
f170852a 806static int parse_argv(int argc, char *argv[]) {
f170852a
LP
807 enum {
808 ARG_LOG_LEVEL = 0x100,
809 ARG_LOG_TARGET,
bbe63281
LP
810 ARG_LOG_COLOR,
811 ARG_LOG_LOCATION,
2f198e2f 812 ARG_UNIT,
edb9aaa8 813 ARG_SYSTEM,
af2d49f7 814 ARG_USER,
e537352b 815 ARG_TEST,
b87c2aa6 816 ARG_NO_PAGER,
9ba0bc4e 817 ARG_VERSION,
80876c20 818 ARG_DUMP_CONFIGURATION_ITEMS,
bbc1acab 819 ARG_DUMP_BUS_PROPERTIES,
9e58ff9c 820 ARG_DUMP_CORE,
b9e74c39 821 ARG_CRASH_CHVT,
9e58ff9c 822 ARG_CRASH_SHELL,
b9e74c39 823 ARG_CRASH_REBOOT,
a16e1123 824 ARG_CONFIRM_SPAWN,
9e58ff9c 825 ARG_SHOW_STATUS,
4288f619 826 ARG_DESERIALIZE,
2660882b 827 ARG_SWITCHED_ROOT,
0a494f1f 828 ARG_DEFAULT_STD_OUTPUT,
ee48dbd5 829 ARG_DEFAULT_STD_ERROR,
2a12e32e
JK
830 ARG_MACHINE_ID,
831 ARG_SERVICE_WATCHDOGS,
f170852a
LP
832 };
833
834 static const struct option options[] = {
a16e1123
LP
835 { "log-level", required_argument, NULL, ARG_LOG_LEVEL },
836 { "log-target", required_argument, NULL, ARG_LOG_TARGET },
bbe63281
LP
837 { "log-color", optional_argument, NULL, ARG_LOG_COLOR },
838 { "log-location", optional_argument, NULL, ARG_LOG_LOCATION },
2f198e2f 839 { "unit", required_argument, NULL, ARG_UNIT },
edb9aaa8 840 { "system", no_argument, NULL, ARG_SYSTEM },
af2d49f7 841 { "user", no_argument, NULL, ARG_USER },
a16e1123 842 { "test", no_argument, NULL, ARG_TEST },
b87c2aa6 843 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
a16e1123 844 { "help", no_argument, NULL, 'h' },
9ba0bc4e 845 { "version", no_argument, NULL, ARG_VERSION },
a16e1123 846 { "dump-configuration-items", no_argument, NULL, ARG_DUMP_CONFIGURATION_ITEMS },
bbc1acab 847 { "dump-bus-properties", no_argument, NULL, ARG_DUMP_BUS_PROPERTIES },
a5d87bf0 848 { "dump-core", optional_argument, NULL, ARG_DUMP_CORE },
b9e74c39 849 { "crash-chvt", required_argument, NULL, ARG_CRASH_CHVT },
a5d87bf0 850 { "crash-shell", optional_argument, NULL, ARG_CRASH_SHELL },
b9e74c39 851 { "crash-reboot", optional_argument, NULL, ARG_CRASH_REBOOT },
a5d87bf0 852 { "confirm-spawn", optional_argument, NULL, ARG_CONFIRM_SPAWN },
6e98720f 853 { "show-status", optional_argument, NULL, ARG_SHOW_STATUS },
a16e1123 854 { "deserialize", required_argument, NULL, ARG_DESERIALIZE },
2660882b 855 { "switched-root", no_argument, NULL, ARG_SWITCHED_ROOT },
0a494f1f
LP
856 { "default-standard-output", required_argument, NULL, ARG_DEFAULT_STD_OUTPUT, },
857 { "default-standard-error", required_argument, NULL, ARG_DEFAULT_STD_ERROR, },
ee48dbd5 858 { "machine-id", required_argument, NULL, ARG_MACHINE_ID },
2a12e32e 859 { "service-watchdogs", required_argument, NULL, ARG_SERVICE_WATCHDOGS },
fb472900 860 {}
f170852a
LP
861 };
862
863 int c, r;
864
865 assert(argc >= 1);
866 assert(argv);
867
df0ff127 868 if (getpid_cached() == 1)
b770165a
LP
869 opterr = 0;
870
099663ff 871 while ((c = getopt_long(argc, argv, "hDbsz:", options, NULL)) >= 0)
f170852a
LP
872
873 switch (c) {
874
875 case ARG_LOG_LEVEL:
fb472900 876 r = log_set_max_level_from_string(optarg);
2b5107e1
ZJS
877 if (r < 0)
878 return log_error_errno(r, "Failed to parse log level \"%s\": %m", optarg);
f170852a
LP
879
880 break;
881
882 case ARG_LOG_TARGET:
fb472900 883 r = log_set_target_from_string(optarg);
2b5107e1
ZJS
884 if (r < 0)
885 return log_error_errno(r, "Failed to parse log target \"%s\": %m", optarg);
f170852a
LP
886
887 break;
888
bbe63281
LP
889 case ARG_LOG_COLOR:
890
d0b170c8 891 if (optarg) {
fb472900 892 r = log_show_color_from_string(optarg);
2b5107e1
ZJS
893 if (r < 0)
894 return log_error_errno(r, "Failed to parse log color setting \"%s\": %m",
895 optarg);
d0b170c8
LP
896 } else
897 log_show_color(true);
bbe63281
LP
898
899 break;
900
901 case ARG_LOG_LOCATION:
d0b170c8 902 if (optarg) {
fb472900 903 r = log_show_location_from_string(optarg);
2b5107e1
ZJS
904 if (r < 0)
905 return log_error_errno(r, "Failed to parse log location setting \"%s\": %m",
906 optarg);
d0b170c8
LP
907 } else
908 log_show_location(true);
bbe63281
LP
909
910 break;
911
0a494f1f 912 case ARG_DEFAULT_STD_OUTPUT:
fb472900 913 r = exec_output_from_string(optarg);
2b5107e1
ZJS
914 if (r < 0)
915 return log_error_errno(r, "Failed to parse default standard output setting \"%s\": %m",
916 optarg);
917 arg_default_std_output = r;
0a494f1f
LP
918 break;
919
920 case ARG_DEFAULT_STD_ERROR:
fb472900 921 r = exec_output_from_string(optarg);
2b5107e1
ZJS
922 if (r < 0)
923 return log_error_errno(r, "Failed to parse default standard error output setting \"%s\": %m",
924 optarg);
925 arg_default_std_error = r;
0a494f1f
LP
926 break;
927
2f198e2f 928 case ARG_UNIT:
e6e242ad 929 r = free_and_strdup(&arg_default_unit, optarg);
23bbb0de 930 if (r < 0)
2b5107e1 931 return log_error_errno(r, "Failed to set default unit \"%s\": %m", optarg);
f170852a
LP
932
933 break;
934
edb9aaa8 935 case ARG_SYSTEM:
463d0d15 936 arg_system = true;
edb9aaa8 937 break;
a5dab5ce 938
af2d49f7 939 case ARG_USER:
463d0d15 940 arg_system = false;
a5dab5ce 941 break;
a5dab5ce 942
e965d56d 943 case ARG_TEST:
fa0f4d8a 944 arg_action = ACTION_TEST;
b87c2aa6
ZJS
945 break;
946
947 case ARG_NO_PAGER:
0221d68a 948 arg_pager_flags |= PAGER_DISABLE;
e965d56d
LP
949 break;
950
9ba0bc4e
ZJS
951 case ARG_VERSION:
952 arg_action = ACTION_VERSION;
953 break;
954
e537352b 955 case ARG_DUMP_CONFIGURATION_ITEMS:
fa0f4d8a 956 arg_action = ACTION_DUMP_CONFIGURATION_ITEMS;
e537352b
LP
957 break;
958
bbc1acab
YW
959 case ARG_DUMP_BUS_PROPERTIES:
960 arg_action = ACTION_DUMP_BUS_PROPERTIES;
961 break;
962
9e58ff9c 963 case ARG_DUMP_CORE:
b9e74c39
LP
964 if (!optarg)
965 arg_dump_core = true;
966 else {
967 r = parse_boolean(optarg);
968 if (r < 0)
2b5107e1
ZJS
969 return log_error_errno(r, "Failed to parse dump core boolean: \"%s\": %m",
970 optarg);
b9e74c39 971 arg_dump_core = r;
a5d87bf0 972 }
b9e74c39
LP
973 break;
974
975 case ARG_CRASH_CHVT:
976 r = parse_crash_chvt(optarg);
977 if (r < 0)
2b5107e1
ZJS
978 return log_error_errno(r, "Failed to parse crash virtual terminal index: \"%s\": %m",
979 optarg);
9e58ff9c
LP
980 break;
981
982 case ARG_CRASH_SHELL:
b9e74c39
LP
983 if (!optarg)
984 arg_crash_shell = true;
985 else {
986 r = parse_boolean(optarg);
987 if (r < 0)
2b5107e1
ZJS
988 return log_error_errno(r, "Failed to parse crash shell boolean: \"%s\": %m",
989 optarg);
b9e74c39
LP
990 arg_crash_shell = r;
991 }
992 break;
993
994 case ARG_CRASH_REBOOT:
995 if (!optarg)
996 arg_crash_reboot = true;
997 else {
998 r = parse_boolean(optarg);
999 if (r < 0)
2b5107e1
ZJS
1000 return log_error_errno(r, "Failed to parse crash shell boolean: \"%s\": %m",
1001 optarg);
b9e74c39 1002 arg_crash_reboot = r;
a5d87bf0 1003 }
9e58ff9c
LP
1004 break;
1005
80876c20 1006 case ARG_CONFIRM_SPAWN:
7d5ceb64
FB
1007 arg_confirm_spawn = mfree(arg_confirm_spawn);
1008
1009 r = parse_confirm_spawn(optarg, &arg_confirm_spawn);
1010 if (r < 0)
2b5107e1
ZJS
1011 return log_error_errno(r, "Failed to parse confirm spawn option: \"%s\": %m",
1012 optarg);
80876c20
LP
1013 break;
1014
2a12e32e
JK
1015 case ARG_SERVICE_WATCHDOGS:
1016 r = parse_boolean(optarg);
1017 if (r < 0)
2b5107e1
ZJS
1018 return log_error_errno(r, "Failed to parse service watchdogs boolean: \"%s\": %m",
1019 optarg);
2a12e32e
JK
1020 arg_service_watchdogs = r;
1021 break;
1022
9e58ff9c 1023 case ARG_SHOW_STATUS:
d450b6f2
ZJS
1024 if (optarg) {
1025 r = parse_show_status(optarg, &arg_show_status);
ac7ec288 1026 if (r < 0)
2b5107e1
ZJS
1027 return log_error_errno(r, "Failed to parse show status boolean: \"%s\": %m",
1028 optarg);
d450b6f2
ZJS
1029 } else
1030 arg_show_status = SHOW_STATUS_YES;
6e98720f 1031 break;
a5d87bf0 1032
a16e1123
LP
1033 case ARG_DESERIALIZE: {
1034 int fd;
1035 FILE *f;
1036
01e10de3 1037 r = safe_atoi(optarg, &fd);
2b5107e1
ZJS
1038 if (r < 0)
1039 log_error_errno(r, "Failed to parse deserialize option \"%s\": %m", optarg);
baaa35ad
ZJS
1040 if (fd < 0)
1041 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1042 "Invalid deserialize fd: %d",
1043 fd);
a16e1123 1044
b9e74c39 1045 (void) fd_cloexec(fd, true);
01e10de3
LP
1046
1047 f = fdopen(fd, "r");
4a62c710 1048 if (!f)
2b5107e1 1049 return log_error_errno(errno, "Failed to open serialization fd %d: %m", fd);
a16e1123 1050
74ca738f 1051 safe_fclose(arg_serialization);
d3b1c508 1052 arg_serialization = f;
a16e1123
LP
1053
1054 break;
1055 }
1056
2660882b 1057 case ARG_SWITCHED_ROOT:
bf4df7c3 1058 arg_switched_root = true;
d03bc1b8
HH
1059 break;
1060
ee48dbd5
NC
1061 case ARG_MACHINE_ID:
1062 r = set_machine_id(optarg);
54500613 1063 if (r < 0)
2b5107e1 1064 return log_error_errno(r, "MachineID '%s' is not valid: %m", optarg);
ee48dbd5
NC
1065 break;
1066
f170852a 1067 case 'h':
fa0f4d8a 1068 arg_action = ACTION_HELP;
f170852a
LP
1069 break;
1070
1d2e23ab
LP
1071 case 'D':
1072 log_set_max_level(LOG_DEBUG);
1073 break;
1074
099663ff
LP
1075 case 'b':
1076 case 's':
1077 case 'z':
1078 /* Just to eat away the sysvinit kernel
1079 * cmdline args without getopt() error
1080 * messages that we'll parse in
1081 * parse_proc_cmdline_word() or ignore. */
f170852a 1082
099663ff 1083 case '?':
df0ff127 1084 if (getpid_cached() != 1)
099663ff 1085 return -EINVAL;
601185b4
ZJS
1086 else
1087 return 0;
099663ff 1088
601185b4
ZJS
1089 default:
1090 assert_not_reached("Unhandled option code.");
f170852a
LP
1091 }
1092
df0ff127 1093 if (optind < argc && getpid_cached() != 1) {
d821e6d6
LP
1094 /* Hmm, when we aren't run as init system
1095 * let's complain about excess arguments */
1096
baaa35ad
ZJS
1097 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1098 "Excess arguments.");
d821e6d6
LP
1099 }
1100
f170852a
LP
1101 return 0;
1102}
1103
1104static int help(void) {
37ec0fdd
LP
1105 _cleanup_free_ char *link = NULL;
1106 int r;
1107
1108 r = terminal_urlify_man("systemd", "1", &link);
1109 if (r < 0)
1110 return log_oom();
f170852a 1111
2e33c433 1112 printf("%s [OPTIONS...]\n\n"
af2d49f7 1113 "Starts up and maintains the system or user services.\n\n"
e537352b 1114 " -h --help Show this help\n"
cb4069d9 1115 " --version Show version\n"
e537352b 1116 " --test Determine startup sequence, dump it and exit\n"
b87c2aa6 1117 " --no-pager Do not pipe output into a pager\n"
80876c20 1118 " --dump-configuration-items Dump understood unit configuration items\n"
bbc1acab 1119 " --dump-bus-properties Dump exposed bus properties\n"
9e58ff9c 1120 " --unit=UNIT Set default unit\n"
edb9aaa8 1121 " --system Run a system instance, even if PID != 1\n"
af2d49f7 1122 " --user Run a user instance\n"
b9e74c39
LP
1123 " --dump-core[=BOOL] Dump core on crash\n"
1124 " --crash-vt=NR Change to specified VT on crash\n"
1125 " --crash-reboot[=BOOL] Reboot on crash\n"
1126 " --crash-shell[=BOOL] Run shell on crash\n"
1127 " --confirm-spawn[=BOOL] Ask for confirmation when spawning processes\n"
1128 " --show-status[=BOOL] Show status updates on the console during bootup\n"
c1dc6153 1129 " --log-target=TARGET Set log target (console, journal, kmsg, journal-or-kmsg, null)\n"
9e58ff9c 1130 " --log-level=LEVEL Set log level (debug, info, notice, warning, err, crit, alert, emerg)\n"
b9e74c39
LP
1131 " --log-color[=BOOL] Highlight important log messages\n"
1132 " --log-location[=BOOL] Include code location in log messages\n"
0a494f1f 1133 " --default-standard-output= Set default standard output for services\n"
37ec0fdd
LP
1134 " --default-standard-error= Set default standard error output for services\n"
1135 "\nSee the %s for details.\n"
1136 , program_invocation_short_name
1137 , link
1138 );
f170852a
LP
1139
1140 return 0;
1141}
1142
2cc856ac
LP
1143static int prepare_reexecute(
1144 Manager *m,
1145 FILE **ret_f,
1146 FDSet **ret_fds,
1147 bool switching_root) {
1148
48b90859
LP
1149 _cleanup_fdset_free_ FDSet *fds = NULL;
1150 _cleanup_fclose_ FILE *f = NULL;
a16e1123
LP
1151 int r;
1152
1153 assert(m);
2cc856ac
LP
1154 assert(ret_f);
1155 assert(ret_fds);
a16e1123 1156
6b78f9b4 1157 r = manager_open_serialization(m, &f);
48b90859
LP
1158 if (r < 0)
1159 return log_error_errno(r, "Failed to create serialization file: %m");
a16e1123 1160
71445ae7 1161 /* Make sure nothing is really destructed when we shut down */
313cefa1 1162 m->n_reloading++;
718db961 1163 bus_manager_send_reloading(m, true);
71445ae7 1164
6b78f9b4 1165 fds = fdset_new();
48b90859
LP
1166 if (!fds)
1167 return log_oom();
a16e1123 1168
b3680f49 1169 r = manager_serialize(m, f, fds, switching_root);
48b90859 1170 if (r < 0)
d68c645b 1171 return r;
a16e1123 1172
48b90859
LP
1173 if (fseeko(f, 0, SEEK_SET) == (off_t) -1)
1174 return log_error_errno(errno, "Failed to rewind serialization fd: %m");
a16e1123 1175
6b78f9b4 1176 r = fd_cloexec(fileno(f), false);
48b90859
LP
1177 if (r < 0)
1178 return log_error_errno(r, "Failed to disable O_CLOEXEC for serialization: %m");
a16e1123 1179
6b78f9b4 1180 r = fdset_cloexec(fds, false);
48b90859
LP
1181 if (r < 0)
1182 return log_error_errno(r, "Failed to disable O_CLOEXEC for serialization fds: %m");
a16e1123 1183
2cc856ac
LP
1184 *ret_f = TAKE_PTR(f);
1185 *ret_fds = TAKE_PTR(fds);
a16e1123 1186
48b90859 1187 return 0;
a16e1123
LP
1188}
1189
a8b627aa
LP
1190static void bump_file_max_and_nr_open(void) {
1191
1192 /* Let's bump fs.file-max and fs.nr_open to their respective maximums. On current kernels large numbers of file
1193 * descriptors are no longer a performance problem and their memory is properly tracked by memcg, thus counting
1194 * them and limiting them in another two layers of limits is unnecessary and just complicates things. This
1195 * function hence turns off 2 of the 4 levels of limits on file descriptors, and makes RLIMIT_NOLIMIT (soft +
1196 * hard) the only ones that really matter. */
1197
1198#if BUMP_PROC_SYS_FS_FILE_MAX || BUMP_PROC_SYS_FS_NR_OPEN
1199 _cleanup_free_ char *t = NULL;
1200 int r;
1201#endif
1202
1203#if BUMP_PROC_SYS_FS_FILE_MAX
1204 /* I so wanted to use STRINGIFY(ULONG_MAX) here, but alas we can't as glibc/gcc define that as
1205 * "(0x7fffffffffffffffL * 2UL + 1UL)". Seriously. 😢 */
1206 if (asprintf(&t, "%lu\n", ULONG_MAX) < 0) {
1207 log_oom();
1208 return;
1209 }
1210
1211 r = sysctl_write("fs/file-max", t);
1212 if (r < 0)
1213 log_full_errno(IN_SET(r, -EROFS, -EPERM, -EACCES) ? LOG_DEBUG : LOG_WARNING, r, "Failed to bump fs.file-max, ignoring: %m");
1214#endif
1215
1216#if BUMP_PROC_SYS_FS_FILE_MAX && BUMP_PROC_SYS_FS_NR_OPEN
1217 t = mfree(t);
1218#endif
1219
1220#if BUMP_PROC_SYS_FS_NR_OPEN
1221 int v = INT_MAX;
1222
1223 /* Arg! The kernel enforces maximum and minimum values on the fs.nr_open, but we don't really know what they
1224 * are. The expression by which the maximum is determined is dependent on the architecture, and is something we
1225 * don't really want to copy to userspace, as it is dependent on implementation details of the kernel. Since
1226 * the kernel doesn't expose the maximum value to us, we can only try and hope. Hence, let's start with
1227 * INT_MAX, and then keep halving the value until we find one that works. Ugly? Yes, absolutely, but kernel
1228 * APIs are kernel APIs, so what do can we do... 🤯 */
1229
1230 for (;;) {
1231 int k;
1232
1233 v &= ~(__SIZEOF_POINTER__ - 1); /* Round down to next multiple of the pointer size */
1234 if (v < 1024) {
1235 log_warning("Can't bump fs.nr_open, value too small.");
1236 break;
1237 }
1238
1239 k = read_nr_open();
1240 if (k < 0) {
1241 log_error_errno(k, "Failed to read fs.nr_open: %m");
1242 break;
1243 }
1244 if (k >= v) { /* Already larger */
1245 log_debug("Skipping bump, value is already larger.");
1246 break;
1247 }
1248
1249 if (asprintf(&t, "%i\n", v) < 0) {
1250 log_oom();
1251 return;
1252 }
1253
1254 r = sysctl_write("fs/nr_open", t);
1255 t = mfree(t);
1256 if (r == -EINVAL) {
1257 log_debug("Couldn't write fs.nr_open as %i, halving it.", v);
1258 v /= 2;
1259 continue;
1260 }
1261 if (r < 0) {
1262 log_full_errno(IN_SET(r, -EROFS, -EPERM, -EACCES) ? LOG_DEBUG : LOG_WARNING, r, "Failed to bump fs.nr_open, ignoring: %m");
1263 break;
1264 }
1265
1266 log_debug("Successfully bumped fs.nr_open to %i", v);
1267 break;
1268 }
1269#endif
1270}
1271
4096d6f5 1272static int bump_rlimit_nofile(struct rlimit *saved_rlimit) {
cda7faa9 1273 struct rlimit new_rlimit;
9264cc39 1274 int r, nr;
4096d6f5
LP
1275
1276 assert(saved_rlimit);
1277
52d62075 1278 /* Save the original RLIMIT_NOFILE so that we can reset it later when transitioning from the initrd to the main
4096d6f5 1279 * systemd or suchlike. */
4a62c710 1280 if (getrlimit(RLIMIT_NOFILE, saved_rlimit) < 0)
3ce40911 1281 return log_warning_errno(errno, "Reading RLIMIT_NOFILE failed, ignoring: %m");
4096d6f5 1282
52d62075
LP
1283 /* Get the underlying absolute limit the kernel enforces */
1284 nr = read_nr_open();
1285
1286 /* Make sure forked processes get limits based on the original kernel setting */
4096d6f5
LP
1287 if (!arg_default_rlimit[RLIMIT_NOFILE]) {
1288 struct rlimit *rl;
1289
1290 rl = newdup(struct rlimit, saved_rlimit, 1);
1291 if (!rl)
1292 return log_oom();
1293
52d62075
LP
1294 /* Bump the hard limit for system services to a substantially higher value. The default hard limit
1295 * current kernels set is pretty low (4K), mostly for historical reasons. According to kernel
1296 * developers, the fd handling in recent kernels has been optimized substantially enough, so that we
1297 * can bump the limit now, without paying too high a price in memory or performance. Note however that
1298 * we only bump the hard limit, not the soft limit. That's because select() works the way it works, and
1299 * chokes on fds >= 1024. If we'd bump the soft limit globally, it might accidentally happen to
1300 * unexpecting programs that they get fds higher than what they can process using select(). By only
1301 * bumping the hard limit but leaving the low limit as it is we avoid this pitfall: programs that are
1302 * written by folks aware of the select() problem in mind (and thus use poll()/epoll instead of
1303 * select(), the way everybody should) can explicitly opt into high fds by bumping their soft limit
1304 * beyond 1024, to the hard limit we pass. */
1305 if (arg_system)
1306 rl->rlim_max = MIN((rlim_t) nr, MAX(rl->rlim_max, (rlim_t) HIGH_RLIMIT_NOFILE));
1307
99a2fd3b
LP
1308 /* If for some reason we were invoked with a soft limit above 1024 (which should never
1309 * happen!, but who knows what we get passed in from pam_limit when invoked as --user
1310 * instance), then lower what we pass on to not confuse our children */
1311 rl->rlim_cur = MIN(rl->rlim_cur, (rlim_t) FD_SETSIZE);
1312
4096d6f5
LP
1313 arg_default_rlimit[RLIMIT_NOFILE] = rl;
1314 }
1315
cda7faa9
LP
1316 /* Calculate the new limits to use for us. Never lower from what we inherited. */
1317 new_rlimit = (struct rlimit) {
1318 .rlim_cur = MAX((rlim_t) nr, saved_rlimit->rlim_cur),
1319 .rlim_max = MAX((rlim_t) nr, saved_rlimit->rlim_max),
1320 };
1321
1322 /* Shortcut if nothing changes. */
1323 if (saved_rlimit->rlim_max >= new_rlimit.rlim_max &&
1324 saved_rlimit->rlim_cur >= new_rlimit.rlim_cur) {
1325 log_debug("RLIMIT_NOFILE is already as high or higher than we need it, not bumping.");
1326 return 0;
1327 }
1328
52d62075
LP
1329 /* Bump up the resource limit for ourselves substantially, all the way to the maximum the kernel allows, for
1330 * both hard and soft. */
cda7faa9 1331 r = setrlimit_closest(RLIMIT_NOFILE, &new_rlimit);
23bbb0de 1332 if (r < 0)
3ce40911 1333 return log_warning_errno(r, "Setting RLIMIT_NOFILE failed, ignoring: %m");
4096d6f5
LP
1334
1335 return 0;
1336}
1337
fb3ae275 1338static int bump_rlimit_memlock(struct rlimit *saved_rlimit) {
cda7faa9 1339 struct rlimit new_rlimit;
fb3ae275
LP
1340 int r;
1341
1342 assert(saved_rlimit);
fb3ae275 1343
a17c1712
LP
1344 /* BPF_MAP_TYPE_LPM_TRIE bpf maps are charged against RLIMIT_MEMLOCK, even if we have CAP_IPC_LOCK which should
1345 * normally disable such checks. We need them to implement IPAccessAllow= and IPAccessDeny=, hence let's bump
1346 * the value high enough for our user. */
fb3ae275
LP
1347
1348 if (getrlimit(RLIMIT_MEMLOCK, saved_rlimit) < 0)
1349 return log_warning_errno(errno, "Reading RLIMIT_MEMLOCK failed, ignoring: %m");
1350
c0d76959
LP
1351 /* Pass the original value down to invoked processes */
1352 if (!arg_default_rlimit[RLIMIT_MEMLOCK]) {
1353 struct rlimit *rl;
1354
1355 rl = newdup(struct rlimit, saved_rlimit, 1);
1356 if (!rl)
1357 return log_oom();
1358
1359 arg_default_rlimit[RLIMIT_MEMLOCK] = rl;
1360 }
1361
cda7faa9
LP
1362 /* Using MAX() on resource limits only is safe if RLIM_INFINITY is > 0. POSIX declares that rlim_t
1363 * must be unsigned, hence this is a given, but let's make this clear here. */
1364 assert_cc(RLIM_INFINITY > 0);
1365
1366 new_rlimit = (struct rlimit) {
1367 .rlim_cur = MAX(HIGH_RLIMIT_MEMLOCK, saved_rlimit->rlim_cur),
1368 .rlim_max = MAX(HIGH_RLIMIT_MEMLOCK, saved_rlimit->rlim_max),
1369 };
1370
1371 if (saved_rlimit->rlim_max >= new_rlimit.rlim_cur &&
1372 saved_rlimit->rlim_cur >= new_rlimit.rlim_max) {
1373 log_debug("RLIMIT_MEMLOCK is already as high or higher than we need it, not bumping.");
1374 return 0;
1375 }
1376
1377 r = setrlimit_closest(RLIMIT_MEMLOCK, &new_rlimit);
fb3ae275
LP
1378 if (r < 0)
1379 return log_warning_errno(r, "Setting RLIMIT_MEMLOCK failed, ignoring: %m");
1380
1381 return 0;
1382}
1383
80758717 1384static void test_usr(void) {
80758717 1385
796ac4c1 1386 /* Check that /usr is either on the same file system as / or mounted already. */
80758717 1387
871c44a7
LP
1388 if (dir_is_empty("/usr") <= 0)
1389 return;
1390
8b173b5e 1391 log_warning("/usr appears to be on its own filesystem and is not already mounted. This is not a supported setup. "
871c44a7
LP
1392 "Some things will probably break (sometimes even silently) in mysterious ways. "
1393 "Consult http://freedesktop.org/wiki/Software/systemd/separate-usr-is-broken for more information.");
1394}
1395
d3b1c508 1396static int enforce_syscall_archs(Set *archs) {
349cc4a5 1397#if HAVE_SECCOMP
d3b1c508
LP
1398 int r;
1399
83f12b27
FS
1400 if (!is_seccomp_available())
1401 return 0;
1402
469830d1 1403 r = seccomp_restrict_archs(arg_syscall_archs);
d3b1c508 1404 if (r < 0)
469830d1 1405 return log_error_errno(r, "Failed to enforce system call architecture restrication: %m");
d3b1c508 1406#endif
469830d1 1407 return 0;
d3b1c508
LP
1408}
1409
b6e2f329
LP
1410static int status_welcome(void) {
1411 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
1412 int r;
1413
7a293242 1414 if (IN_SET(arg_show_status, SHOW_STATUS_NO, SHOW_STATUS_AUTO))
fd8c85c6
LP
1415 return 0;
1416
d58ad743
LP
1417 r = parse_os_release(NULL,
1418 "PRETTY_NAME", &pretty_name,
1419 "ANSI_COLOR", &ansi_color,
1420 NULL);
1421 if (r < 0)
1422 log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_WARNING, r,
1423 "Failed to read os-release file, ignoring: %m");
b6e2f329 1424
dc9b5816 1425 if (log_get_show_color())
a885727a 1426 return status_printf(NULL, 0,
dc9b5816
ZJS
1427 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
1428 isempty(ansi_color) ? "1" : ansi_color,
1429 isempty(pretty_name) ? "Linux" : pretty_name);
1430 else
a885727a 1431 return status_printf(NULL, 0,
dc9b5816
ZJS
1432 "\nWelcome to %s!\n",
1433 isempty(pretty_name) ? "Linux" : pretty_name);
b6e2f329
LP
1434}
1435
fdd25311
LP
1436static int write_container_id(void) {
1437 const char *c;
19854865 1438 int r;
fdd25311
LP
1439
1440 c = getenv("container");
1441 if (isempty(c))
1442 return 0;
1443
8612da97
LP
1444 RUN_WITH_UMASK(0022)
1445 r = write_string_file("/run/systemd/container", c, WRITE_STRING_FILE_CREATE);
19854865 1446 if (r < 0)
f1f849b0 1447 return log_warning_errno(r, "Failed to write /run/systemd/container, ignoring: %m");
19854865
LP
1448
1449 return 1;
1450}
1451
1452static int bump_unix_max_dgram_qlen(void) {
1453 _cleanup_free_ char *qlen = NULL;
1454 unsigned long v;
1455 int r;
1456
3130fca5
LP
1457 /* Let's bump the net.unix.max_dgram_qlen sysctl. The kernel default of 16 is simply too low. We set the value
1458 * really really early during boot, so that it is actually applied to all our sockets, including the
1459 * $NOTIFY_SOCKET one. */
19854865
LP
1460
1461 r = read_one_line_file("/proc/sys/net/unix/max_dgram_qlen", &qlen);
1462 if (r < 0)
875622c3 1463 return log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_WARNING, r, "Failed to read AF_UNIX datagram queue length, ignoring: %m");
19854865
LP
1464
1465 r = safe_atolu(qlen, &v);
1466 if (r < 0)
3130fca5 1467 return log_warning_errno(r, "Failed to parse AF_UNIX datagram queue length '%s', ignoring: %m", qlen);
19854865
LP
1468
1469 if (v >= DEFAULT_UNIX_MAX_DGRAM_QLEN)
1470 return 0;
1471
57512c89 1472 r = write_string_filef("/proc/sys/net/unix/max_dgram_qlen", WRITE_STRING_FILE_DISABLE_BUFFER, "%lu", DEFAULT_UNIX_MAX_DGRAM_QLEN);
19854865
LP
1473 if (r < 0)
1474 return log_full_errno(IN_SET(r, -EROFS, -EPERM, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
1475 "Failed to bump AF_UNIX datagram queue length, ignoring: %m");
1476
1477 return 1;
fdd25311
LP
1478}
1479
32391275
FB
1480static int fixup_environment(void) {
1481 _cleanup_free_ char *term = NULL;
4dc63c4b 1482 const char *t;
32391275
FB
1483 int r;
1484
43db615b
LP
1485 /* Only fix up the environment when we are started as PID 1 */
1486 if (getpid_cached() != 1)
1487 return 0;
1488
1489 /* We expect the environment to be set correctly if run inside a container. */
84af7821
LP
1490 if (detect_container() > 0)
1491 return 0;
1492
43db615b
LP
1493 /* When started as PID1, the kernel uses /dev/console for our stdios and uses TERM=linux whatever the backend
1494 * device used by the console. We try to make a better guess here since some consoles might not have support
1495 * for color mode for example.
32391275 1496 *
43db615b 1497 * However if TERM was configured through the kernel command line then leave it alone. */
1d84ad94 1498 r = proc_cmdline_get_key("TERM", 0, &term);
32391275
FB
1499 if (r < 0)
1500 return r;
32391275 1501
4dc63c4b
LP
1502 t = term ?: default_term_for_tty("/dev/console");
1503
1504 if (setenv("TERM", t, 1) < 0)
32391275
FB
1505 return -errno;
1506
1507 return 0;
1508}
1509
6808a0bc
LP
1510static void redirect_telinit(int argc, char *argv[]) {
1511
1512 /* This is compatibility support for SysV, where calling init as a user is identical to telinit. */
1513
1514#if HAVE_SYSV_COMPAT
1515 if (getpid_cached() == 1)
1516 return;
1517
1518 if (!strstr(program_invocation_short_name, "init"))
1519 return;
1520
1521 execv(SYSTEMCTL_BINARY_PATH, argv);
1522 log_error_errno(errno, "Failed to exec " SYSTEMCTL_BINARY_PATH ": %m");
a45d7127 1523 exit(EXIT_FAILURE);
6808a0bc
LP
1524#endif
1525}
1526
4a36297c
LP
1527static int become_shutdown(
1528 const char *shutdown_verb,
7eb35049 1529 int retval) {
4a36297c
LP
1530
1531 char log_level[DECIMAL_STR_MAX(int) + 1],
e73c54b8
JK
1532 exit_code[DECIMAL_STR_MAX(uint8_t) + 1],
1533 timeout[DECIMAL_STR_MAX(usec_t) + 1];
4a36297c 1534
e73c54b8 1535 const char* command_line[13] = {
4a36297c
LP
1536 SYSTEMD_SHUTDOWN_BINARY_PATH,
1537 shutdown_verb,
e73c54b8 1538 "--timeout", timeout,
4a36297c
LP
1539 "--log-level", log_level,
1540 "--log-target",
1541 };
1542
1543 _cleanup_strv_free_ char **env_block = NULL;
e73c54b8 1544 size_t pos = 7;
4a36297c
LP
1545 int r;
1546
7eb35049 1547 assert(shutdown_verb);
234519ae 1548 assert(!command_line[pos]);
4a36297c
LP
1549 env_block = strv_copy(environ);
1550
1551 xsprintf(log_level, "%d", log_get_max_level());
e73c54b8 1552 xsprintf(timeout, "%" PRI_USEC "us", arg_default_timeout_stop_usec);
4a36297c
LP
1553
1554 switch (log_get_target()) {
1555
1556 case LOG_TARGET_KMSG:
1557 case LOG_TARGET_JOURNAL_OR_KMSG:
1558 case LOG_TARGET_SYSLOG_OR_KMSG:
1559 command_line[pos++] = "kmsg";
1560 break;
1561
1562 case LOG_TARGET_NULL:
1563 command_line[pos++] = "null";
1564 break;
1565
1566 case LOG_TARGET_CONSOLE:
1567 default:
1568 command_line[pos++] = "console";
1569 break;
1570 };
1571
1572 if (log_get_show_color())
1573 command_line[pos++] = "--log-color";
1574
1575 if (log_get_show_location())
1576 command_line[pos++] = "--log-location";
1577
1578 if (streq(shutdown_verb, "exit")) {
1579 command_line[pos++] = "--exit-code";
1580 command_line[pos++] = exit_code;
1581 xsprintf(exit_code, "%d", retval);
1582 }
1583
1584 assert(pos < ELEMENTSOF(command_line));
1585
7eb35049
LP
1586 if (streq(shutdown_verb, "reboot") &&
1587 arg_shutdown_watchdog > 0 &&
1588 arg_shutdown_watchdog != USEC_INFINITY) {
1589
4a36297c
LP
1590 char *e;
1591
1592 /* If we reboot let's set the shutdown
1593 * watchdog and tell the shutdown binary to
1594 * repeatedly ping it */
1595 r = watchdog_set_timeout(&arg_shutdown_watchdog);
1596 watchdog_close(r < 0);
1597
1598 /* Tell the binary how often to ping, ignore failure */
1599 if (asprintf(&e, "WATCHDOG_USEC="USEC_FMT, arg_shutdown_watchdog) > 0)
8a2c1fbf
EJ
1600 (void) strv_consume(&env_block, e);
1601
1602 if (arg_watchdog_device &&
1603 asprintf(&e, "WATCHDOG_DEVICE=%s", arg_watchdog_device) > 0)
1604 (void) strv_consume(&env_block, e);
4a36297c
LP
1605 } else
1606 watchdog_close(true);
1607
1608 /* Avoid the creation of new processes forked by the
1609 * kernel; at this point, we will not listen to the
1610 * signals anyway */
1611 if (detect_container() <= 0)
1612 (void) cg_uninstall_release_agent(SYSTEMD_CGROUP_CONTROLLER);
1613
1614 execve(SYSTEMD_SHUTDOWN_BINARY_PATH, (char **) command_line, env_block);
1615 return -errno;
1616}
1617
e839bafd
LP
1618static void initialize_clock(void) {
1619 int r;
1620
1621 if (clock_is_localtime(NULL) > 0) {
1622 int min;
1623
1624 /*
1625 * The very first call of settimeofday() also does a time warp in the kernel.
1626 *
1627 * In the rtc-in-local time mode, we set the kernel's timezone, and rely on external tools to take care
1628 * of maintaining the RTC and do all adjustments. This matches the behavior of Windows, which leaves
1629 * the RTC alone if the registry tells that the RTC runs in UTC.
1630 */
1631 r = clock_set_timezone(&min);
1632 if (r < 0)
1633 log_error_errno(r, "Failed to apply local time delta, ignoring: %m");
1634 else
1635 log_info("RTC configured in localtime, applying delta of %i minutes to system time.", min);
1636
1637 } else if (!in_initrd()) {
1638 /*
1639 * Do a dummy very first call to seal the kernel's time warp magic.
1640 *
1641 * Do not call this from inside the initrd. The initrd might not carry /etc/adjtime with LOCAL, but the
1642 * real system could be set up that way. In such case, we need to delay the time-warp or the sealing
1643 * until we reach the real system.
1644 *
1645 * Do no set the kernel's timezone. The concept of local time cannot be supported reliably, the time
1646 * will jump or be incorrect at every daylight saving time change. All kernel local time concepts will
1647 * be treated as UTC that way.
1648 */
1649 (void) clock_reset_timewarp();
1650 }
1651
1652 r = clock_apply_epoch();
1653 if (r < 0)
1654 log_error_errno(r, "Current system time is before build time, but cannot correct: %m");
1655 else if (r > 0)
1656 log_info("System time before build time, advancing clock.");
1657}
1658
1e41242e 1659static void initialize_coredump(bool skip_setup) {
752bcb77 1660#if ENABLE_COREDUMP
1e41242e
LP
1661 if (getpid_cached() != 1)
1662 return;
1663
1664 /* Don't limit the core dump size, so that coredump handlers such as systemd-coredump (which honour the limit)
1665 * will process core dumps for system services by default. */
1666 if (setrlimit(RLIMIT_CORE, &RLIMIT_MAKE_CONST(RLIM_INFINITY)) < 0)
1667 log_warning_errno(errno, "Failed to set RLIMIT_CORE: %m");
1668
c6885f5f
FB
1669 /* But at the same time, turn off the core_pattern logic by default, so that no
1670 * coredumps are stored until the systemd-coredump tool is enabled via
1671 * sysctl. However it can be changed via the kernel command line later so core
1672 * dumps can still be generated during early startup and in initramfs. */
1e41242e 1673 if (!skip_setup)
e557b1a6 1674 disable_coredumps();
752bcb77 1675#endif
1e41242e
LP
1676}
1677
c6885f5f
FB
1678static void initialize_core_pattern(bool skip_setup) {
1679 int r;
1680
1681 if (skip_setup || !arg_early_core_pattern)
1682 return;
1683
1684 if (getpid_cached() != 1)
1685 return;
1686
57512c89 1687 r = write_string_file("/proc/sys/kernel/core_pattern", arg_early_core_pattern, WRITE_STRING_FILE_DISABLE_BUFFER);
c6885f5f
FB
1688 if (r < 0)
1689 log_warning_errno(r, "Failed to write '%s' to /proc/sys/kernel/core_pattern, ignoring: %m", arg_early_core_pattern);
1690}
1691
3c7878f9
LP
1692static void do_reexecute(
1693 int argc,
1694 char *argv[],
1695 const struct rlimit *saved_rlimit_nofile,
1696 const struct rlimit *saved_rlimit_memlock,
1697 FDSet *fds,
1698 const char *switch_root_dir,
1699 const char *switch_root_init,
1700 const char **ret_error_message) {
1701
1702 unsigned i, j, args_size;
1703 const char **args;
1704 int r;
1705
1706 assert(saved_rlimit_nofile);
1707 assert(saved_rlimit_memlock);
1708 assert(ret_error_message);
1709
1710 /* Close and disarm the watchdog, so that the new instance can reinitialize it, but doesn't get rebooted while
1711 * we do that */
1712 watchdog_close(true);
1713
ddfa8b0b
LP
1714 /* Reset RLIMIT_NOFILE + RLIMIT_MEMLOCK back to the kernel defaults, so that the new systemd can pass
1715 * the kernel default to its child processes */
1716 if (saved_rlimit_nofile->rlim_cur != 0)
3c7878f9 1717 (void) setrlimit(RLIMIT_NOFILE, saved_rlimit_nofile);
ddfa8b0b 1718 if (saved_rlimit_memlock->rlim_cur != RLIM_INFINITY)
3c7878f9
LP
1719 (void) setrlimit(RLIMIT_MEMLOCK, saved_rlimit_memlock);
1720
1721 if (switch_root_dir) {
1722 /* Kill all remaining processes from the initrd, but don't wait for them, so that we can handle the
1723 * SIGCHLD for them after deserializing. */
e73c54b8 1724 broadcast_signal(SIGTERM, false, true, arg_default_timeout_stop_usec);
3c7878f9
LP
1725
1726 /* And switch root with MS_MOVE, because we remove the old directory afterwards and detach it. */
1727 r = switch_root(switch_root_dir, "/mnt", true, MS_MOVE);
1728 if (r < 0)
1729 log_error_errno(r, "Failed to switch root, trying to continue: %m");
1730 }
1731
1732 args_size = MAX(6, argc+1);
1733 args = newa(const char*, args_size);
1734
1735 if (!switch_root_init) {
1736 char sfd[DECIMAL_STR_MAX(int) + 1];
1737
1738 /* First try to spawn ourselves with the right path, and with full serialization. We do this only if
1739 * the user didn't specify an explicit init to spawn. */
1740
1741 assert(arg_serialization);
1742 assert(fds);
1743
1744 xsprintf(sfd, "%i", fileno(arg_serialization));
1745
1746 i = 0;
1747 args[i++] = SYSTEMD_BINARY_PATH;
1748 if (switch_root_dir)
1749 args[i++] = "--switched-root";
1750 args[i++] = arg_system ? "--system" : "--user";
1751 args[i++] = "--deserialize";
1752 args[i++] = sfd;
1753 args[i++] = NULL;
1754
1755 assert(i <= args_size);
1756
1757 /*
1758 * We want valgrind to print its memory usage summary before reexecution. Valgrind won't do this is on
1759 * its own on exec(), but it will do it on exit(). Hence, to ensure we get a summary here, fork() off
1760 * a child, let it exit() cleanly, so that it prints the summary, and wait() for it in the parent,
1761 * before proceeding into the exec().
1762 */
1763 valgrind_summary_hack();
1764
1765 (void) execv(args[0], (char* const*) args);
1766 log_debug_errno(errno, "Failed to execute our own binary, trying fallback: %m");
1767 }
1768
1769 /* Try the fallback, if there is any, without any serialization. We pass the original argv[] and envp[]. (Well,
1770 * modulo the ordering changes due to getopt() in argv[], and some cleanups in envp[], but let's hope that
1771 * doesn't matter.) */
1772
1773 arg_serialization = safe_fclose(arg_serialization);
1774 fds = fdset_free(fds);
1775
1776 /* Reopen the console */
1777 (void) make_console_stdio();
1778
1779 for (j = 1, i = 1; j < (unsigned) argc; j++)
1780 args[i++] = argv[j];
1781 args[i++] = NULL;
1782 assert(i <= args_size);
1783
1784 /* Reenable any blocked signals, especially important if we switch from initial ramdisk to init=... */
1785 (void) reset_all_signal_handlers();
1786 (void) reset_signal_mask();
595225af 1787 (void) rlimit_nofile_safe();
3c7878f9
LP
1788
1789 if (switch_root_init) {
1790 args[0] = switch_root_init;
1791 (void) execv(args[0], (char* const*) args);
1792 log_warning_errno(errno, "Failed to execute configured init, trying fallback: %m");
1793 }
1794
1795 args[0] = "/sbin/init";
1796 (void) execv(args[0], (char* const*) args);
1797 r = -errno;
1798
1799 manager_status_printf(NULL, STATUS_TYPE_EMERGENCY,
1800 ANSI_HIGHLIGHT_RED " !! " ANSI_NORMAL,
1801 "Failed to execute /sbin/init");
1802
1803 if (r == -ENOENT) {
1804 log_warning("No /sbin/init, trying fallback");
1805
1806 args[0] = "/bin/sh";
1807 args[1] = NULL;
1808 (void) execv(args[0], (char* const*) args);
1809 log_error_errno(errno, "Failed to execute /bin/sh, giving up: %m");
1810 } else
1811 log_warning_errno(r, "Failed to execute /sbin/init, giving up: %m");
1812
1813 *ret_error_message = "Failed to execute fallback shell";
1814}
1815
7eb35049
LP
1816static int invoke_main_loop(
1817 Manager *m,
1818 bool *ret_reexecute,
1819 int *ret_retval, /* Return parameters relevant for shutting down */
1820 const char **ret_shutdown_verb, /* … */
1821 FDSet **ret_fds, /* Return parameters for reexecuting */
1822 char **ret_switch_root_dir, /* … */
1823 char **ret_switch_root_init, /* … */
1824 const char **ret_error_message) {
1825
1826 int r;
1827
1828 assert(m);
1829 assert(ret_reexecute);
1830 assert(ret_retval);
1831 assert(ret_shutdown_verb);
1832 assert(ret_fds);
1833 assert(ret_switch_root_dir);
1834 assert(ret_switch_root_init);
1835 assert(ret_error_message);
1836
1837 for (;;) {
1838 r = manager_loop(m);
1839 if (r < 0) {
1840 *ret_error_message = "Failed to run main loop";
1841 return log_emergency_errno(r, "Failed to run main loop: %m");
1842 }
1843
3ca4d0b3 1844 switch ((ManagerObjective) r) {
7eb35049 1845
a6ecbf83 1846 case MANAGER_RELOAD: {
bda7d78b 1847 LogTarget saved_log_target;
a6ecbf83
FB
1848 int saved_log_level;
1849
7eb35049
LP
1850 log_info("Reloading.");
1851
3fe91079 1852 /* First, save any overridden log level/target, then parse the configuration file, which might
bda7d78b
FB
1853 * change the log level to new settings. */
1854
a6ecbf83 1855 saved_log_level = m->log_level_overridden ? log_get_max_level() : -1;
bda7d78b 1856 saved_log_target = m->log_target_overridden ? log_get_target() : _LOG_TARGET_INVALID;
a6ecbf83 1857
7eb35049
LP
1858 r = parse_config_file();
1859 if (r < 0)
1860 log_warning_errno(r, "Failed to parse config file, ignoring: %m");
1861
1862 set_manager_defaults(m);
1863
a6ecbf83
FB
1864 if (saved_log_level >= 0)
1865 manager_override_log_level(m, saved_log_level);
bda7d78b
FB
1866 if (saved_log_target >= 0)
1867 manager_override_log_target(m, saved_log_target);
a6ecbf83 1868
7eb35049
LP
1869 r = manager_reload(m);
1870 if (r < 0)
7a35fa24
LP
1871 /* Reloading failed before the point of no return. Let's continue running as if nothing happened. */
1872 m->objective = MANAGER_OK;
7eb35049
LP
1873
1874 break;
a6ecbf83 1875 }
7eb35049
LP
1876
1877 case MANAGER_REEXECUTE:
1878
1879 r = prepare_reexecute(m, &arg_serialization, ret_fds, false);
1880 if (r < 0) {
1881 *ret_error_message = "Failed to prepare for reexecution";
1882 return r;
1883 }
1884
1885 log_notice("Reexecuting.");
1886
1887 *ret_reexecute = true;
1888 *ret_retval = EXIT_SUCCESS;
1889 *ret_shutdown_verb = NULL;
1890 *ret_switch_root_dir = *ret_switch_root_init = NULL;
1891
1892 return 0;
1893
1894 case MANAGER_SWITCH_ROOT:
1895 if (!m->switch_root_init) {
1896 r = prepare_reexecute(m, &arg_serialization, ret_fds, true);
1897 if (r < 0) {
1898 *ret_error_message = "Failed to prepare for reexecution";
1899 return r;
1900 }
1901 } else
1902 *ret_fds = NULL;
1903
1904 log_notice("Switching root.");
1905
1906 *ret_reexecute = true;
1907 *ret_retval = EXIT_SUCCESS;
1908 *ret_shutdown_verb = NULL;
1909
1910 /* Steal the switch root parameters */
49052946
YW
1911 *ret_switch_root_dir = TAKE_PTR(m->switch_root);
1912 *ret_switch_root_init = TAKE_PTR(m->switch_root_init);
7eb35049
LP
1913
1914 return 0;
1915
1916 case MANAGER_EXIT:
1917
1918 if (MANAGER_IS_USER(m)) {
1919 log_debug("Exit.");
1920
1921 *ret_reexecute = false;
1922 *ret_retval = m->return_value;
1923 *ret_shutdown_verb = NULL;
1924 *ret_fds = NULL;
1925 *ret_switch_root_dir = *ret_switch_root_init = NULL;
1926
1927 return 0;
1928 }
1929
1930 _fallthrough_;
1931 case MANAGER_REBOOT:
1932 case MANAGER_POWEROFF:
1933 case MANAGER_HALT:
1934 case MANAGER_KEXEC: {
af41e508
LP
1935 static const char * const table[_MANAGER_OBJECTIVE_MAX] = {
1936 [MANAGER_EXIT] = "exit",
1937 [MANAGER_REBOOT] = "reboot",
7eb35049 1938 [MANAGER_POWEROFF] = "poweroff",
af41e508
LP
1939 [MANAGER_HALT] = "halt",
1940 [MANAGER_KEXEC] = "kexec",
7eb35049
LP
1941 };
1942
1943 log_notice("Shutting down.");
1944
1945 *ret_reexecute = false;
1946 *ret_retval = m->return_value;
af41e508 1947 assert_se(*ret_shutdown_verb = table[m->objective]);
7eb35049
LP
1948 *ret_fds = NULL;
1949 *ret_switch_root_dir = *ret_switch_root_init = NULL;
1950
1951 return 0;
1952 }
1953
1954 default:
af41e508 1955 assert_not_reached("Unknown or unexpected manager objective.");
7eb35049
LP
1956 }
1957 }
1958}
1959
31aef7ff
LP
1960static void log_execution_mode(bool *ret_first_boot) {
1961 assert(ret_first_boot);
1962
1963 if (arg_system) {
1964 int v;
1965
681bd2c5 1966 log_info("systemd " GIT_VERSION " running in %ssystem mode. (" SYSTEMD_FEATURES ")",
31aef7ff
LP
1967 arg_action == ACTION_TEST ? "test " : "" );
1968
1969 v = detect_virtualization();
1970 if (v > 0)
1971 log_info("Detected virtualization %s.", virtualization_to_string(v));
1972
1973 log_info("Detected architecture %s.", architecture_to_string(uname_architecture()));
1974
1975 if (in_initrd()) {
1976 *ret_first_boot = false;
1977 log_info("Running in initial RAM disk.");
1978 } else {
1979 /* Let's check whether we are in first boot, i.e. whether /etc is still unpopulated. We use
1980 * /etc/machine-id as flag file, for this: if it exists we assume /etc is populated, if it
1981 * doesn't it's unpopulated. This allows container managers and installers to provision a
1982 * couple of files already. If the container manager wants to provision the machine ID itself
1983 * it should pass $container_uuid to PID 1. */
1984
1985 *ret_first_boot = access("/etc/machine-id", F_OK) < 0;
1986 if (*ret_first_boot)
1987 log_info("Running with unpopulated /etc.");
1988 }
1989 } else {
b9e90f3a
LP
1990 if (DEBUG_LOGGING) {
1991 _cleanup_free_ char *t;
31aef7ff 1992
b9e90f3a 1993 t = uid_to_name(getuid());
681bd2c5 1994 log_debug("systemd " GIT_VERSION " running in %suser mode for user " UID_FMT "/%s. (" SYSTEMD_FEATURES ")",
b9e90f3a
LP
1995 arg_action == ACTION_TEST ? " test" : "", getuid(), strna(t));
1996 }
31aef7ff
LP
1997
1998 *ret_first_boot = false;
1999 }
2000}
2001
5afbaa36
LP
2002static int initialize_runtime(
2003 bool skip_setup,
2004 struct rlimit *saved_rlimit_nofile,
2005 struct rlimit *saved_rlimit_memlock,
2006 const char **ret_error_message) {
2007
2008 int r;
2009
2010 assert(ret_error_message);
2011
2012 /* Sets up various runtime parameters. Many of these initializations are conditionalized:
2013 *
2014 * - Some only apply to --system instances
2015 * - Some only apply to --user instances
2016 * - Some only apply when we first start up, but not when we reexecute
2017 */
2018
2d776038
LP
2019 if (arg_action != ACTION_RUN)
2020 return 0;
2021
3c3c6cb9
LP
2022 if (arg_system) {
2023 /* Make sure we leave a core dump without panicing the kernel. */
2024 install_crash_handler();
5afbaa36 2025
3c3c6cb9 2026 if (!skip_setup) {
143fadf3 2027 r = mount_cgroup_controllers();
3c3c6cb9
LP
2028 if (r < 0) {
2029 *ret_error_message = "Failed to mount cgroup hierarchies";
2030 return r;
2031 }
2032
2033 status_welcome();
2034 hostname_setup();
2035 machine_id_setup(NULL, arg_machine_id, NULL);
2036 loopback_setup();
2037 bump_unix_max_dgram_qlen();
a8b627aa 2038 bump_file_max_and_nr_open();
3c3c6cb9
LP
2039 test_usr();
2040 write_container_id();
2041 }
8a2c1fbf 2042
3c3c6cb9
LP
2043 if (arg_watchdog_device) {
2044 r = watchdog_set_device(arg_watchdog_device);
2045 if (r < 0)
2046 log_warning_errno(r, "Failed to set watchdog device to %s, ignoring: %m", arg_watchdog_device);
2047 }
2048
2049 if (arg_runtime_watchdog > 0 && arg_runtime_watchdog != USEC_INFINITY)
2050 watchdog_set_timeout(&arg_runtime_watchdog);
2051 }
5afbaa36
LP
2052
2053 if (arg_timer_slack_nsec != NSEC_INFINITY)
2054 if (prctl(PR_SET_TIMERSLACK, arg_timer_slack_nsec) < 0)
3a671cd1 2055 log_warning_errno(errno, "Failed to adjust timer slack, ignoring: %m");
5afbaa36
LP
2056
2057 if (arg_system && !cap_test_all(arg_capability_bounding_set)) {
2058 r = capability_bounding_set_drop_usermode(arg_capability_bounding_set);
2059 if (r < 0) {
2060 *ret_error_message = "Failed to drop capability bounding set of usermode helpers";
2061 return log_emergency_errno(r, "Failed to drop capability bounding set of usermode helpers: %m");
2062 }
2063
2064 r = capability_bounding_set_drop(arg_capability_bounding_set, true);
2065 if (r < 0) {
2066 *ret_error_message = "Failed to drop capability bounding set";
2067 return log_emergency_errno(r, "Failed to drop capability bounding set: %m");
2068 }
2069 }
2070
39362f6f
JB
2071 if (arg_system && arg_no_new_privs) {
2072 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
2073 *ret_error_message = "Failed to disable new privileges";
2074 return log_emergency_errno(errno, "Failed to disable new privileges: %m");
2075 }
2076 }
2077
5afbaa36
LP
2078 if (arg_syscall_archs) {
2079 r = enforce_syscall_archs(arg_syscall_archs);
2080 if (r < 0) {
2081 *ret_error_message = "Failed to set syscall architectures";
2082 return r;
2083 }
2084 }
2085
2086 if (!arg_system)
2087 /* Become reaper of our children */
2088 if (prctl(PR_SET_CHILD_SUBREAPER, 1) < 0)
2089 log_warning_errno(errno, "Failed to make us a subreaper: %m");
2090
a17c1712
LP
2091 /* Bump up RLIMIT_NOFILE for systemd itself */
2092 (void) bump_rlimit_nofile(saved_rlimit_nofile);
2093 (void) bump_rlimit_memlock(saved_rlimit_memlock);
5afbaa36
LP
2094
2095 return 0;
2096}
2097
6acca5fc
LP
2098static int do_queue_default_job(
2099 Manager *m,
2100 const char **ret_error_message) {
2101
2102 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2103 Job *default_unit_job;
2104 Unit *target = NULL;
2105 int r;
2106
2107 log_debug("Activating default unit: %s", arg_default_unit);
2108
4109ede7
ZJS
2109 r = manager_load_startable_unit_or_warn(m, arg_default_unit, NULL, &target);
2110 if (r < 0) {
2111 log_info("Falling back to rescue target: " SPECIAL_RESCUE_TARGET);
6acca5fc 2112
4109ede7 2113 r = manager_load_startable_unit_or_warn(m, SPECIAL_RESCUE_TARGET, NULL, &target);
6acca5fc 2114 if (r < 0) {
4109ede7
ZJS
2115 *ret_error_message = r == -ERFKILL ? "Rescue target masked"
2116 : "Failed to load rescue target";
2117 return r;
6acca5fc
LP
2118 }
2119 }
2120
2121 assert(target->load_state == UNIT_LOADED);
2122
50cbaba4 2123 r = manager_add_job(m, JOB_START, target, JOB_ISOLATE, NULL, &error, &default_unit_job);
6acca5fc
LP
2124 if (r == -EPERM) {
2125 log_debug_errno(r, "Default target could not be isolated, starting instead: %s", bus_error_message(&error, r));
2126
2127 sd_bus_error_free(&error);
2128
50cbaba4 2129 r = manager_add_job(m, JOB_START, target, JOB_REPLACE, NULL, &error, &default_unit_job);
6acca5fc
LP
2130 if (r < 0) {
2131 *ret_error_message = "Failed to start default target";
2132 return log_emergency_errno(r, "Failed to start default target: %s", bus_error_message(&error, r));
2133 }
2134
2135 } else if (r < 0) {
2136 *ret_error_message = "Failed to isolate default target";
2137 return log_emergency_errno(r, "Failed to isolate default target: %s", bus_error_message(&error, r));
2138 }
2139
2140 m->default_unit_job_id = default_unit_job->id;
2141
2142 return 0;
2143}
2144
970777b5 2145static void free_arguments(void) {
970777b5
LP
2146
2147 /* Frees all arg_* variables, with the exception of arg_serialization */
ef59409f 2148 rlimit_free_all(arg_default_rlimit);
970777b5
LP
2149
2150 arg_default_unit = mfree(arg_default_unit);
2151 arg_confirm_spawn = mfree(arg_confirm_spawn);
970777b5
LP
2152 arg_default_environment = strv_free(arg_default_environment);
2153 arg_syscall_archs = set_free(arg_syscall_archs);
2154}
2155
97d1fb94
LP
2156static int load_configuration(int argc, char **argv, const char **ret_error_message) {
2157 int r;
2158
2159 assert(ret_error_message);
2160
2161 arg_default_tasks_max = system_tasks_max_scale(DEFAULT_TASKS_MAX_PERCENTAGE, 100U);
2162
2163 r = parse_config_file();
2164 if (r < 0) {
2165 *ret_error_message = "Failed to parse config file";
2166 return r;
2167 }
2168
2169 if (arg_system) {
2170 r = proc_cmdline_parse(parse_proc_cmdline_item, NULL, 0);
2171 if (r < 0)
2172 log_warning_errno(r, "Failed to parse kernel command line, ignoring: %m");
2173 }
2174
2175 /* Note that this also parses bits from the kernel command line, including "debug". */
2176 log_parse_environment();
2177
2178 r = parse_argv(argc, argv);
2179 if (r < 0) {
2180 *ret_error_message = "Failed to parse commandline arguments";
2181 return r;
2182 }
2183
2184 /* Initialize default unit */
2185 if (!arg_default_unit) {
2186 arg_default_unit = strdup(SPECIAL_DEFAULT_TARGET);
2187 if (!arg_default_unit) {
2188 *ret_error_message = "Failed to set default unit";
2189 return log_oom();
2190 }
2191 }
2192
db33214b 2193 /* Initialize the show status setting if it hasn't been set explicitly yet */
7a293242 2194 if (arg_show_status == _SHOW_STATUS_INVALID)
db33214b
LP
2195 arg_show_status = SHOW_STATUS_YES;
2196
97d1fb94
LP
2197 return 0;
2198}
2199
b0d7c989
LP
2200static int safety_checks(void) {
2201
febf46a4 2202 if (getpid_cached() == 1 &&
baaa35ad
ZJS
2203 arg_action != ACTION_RUN)
2204 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2205 "Unsupported execution mode while PID 1.");
febf46a4
LP
2206
2207 if (getpid_cached() == 1 &&
baaa35ad
ZJS
2208 !arg_system)
2209 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2210 "Can't run --user mode as PID 1.");
febf46a4
LP
2211
2212 if (arg_action == ACTION_RUN &&
2213 arg_system &&
baaa35ad
ZJS
2214 getpid_cached() != 1)
2215 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2216 "Can't run system mode unless PID 1.");
febf46a4 2217
b0d7c989 2218 if (arg_action == ACTION_TEST &&
baaa35ad
ZJS
2219 geteuid() == 0)
2220 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2221 "Don't run test mode as root.");
b0d7c989
LP
2222
2223 if (!arg_system &&
2224 arg_action == ACTION_RUN &&
baaa35ad
ZJS
2225 sd_booted() <= 0)
2226 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2227 "Trying to run as user instance, but the system has not been booted with systemd.");
b0d7c989
LP
2228
2229 if (!arg_system &&
2230 arg_action == ACTION_RUN &&
baaa35ad
ZJS
2231 !getenv("XDG_RUNTIME_DIR"))
2232 return log_error_errno(SYNTHETIC_ERRNO(EUNATCH),
2233 "Trying to run as user instance, but $XDG_RUNTIME_DIR is not set.");
b0d7c989
LP
2234
2235 if (arg_system &&
2236 arg_action == ACTION_RUN &&
baaa35ad
ZJS
2237 running_in_chroot() > 0)
2238 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2239 "Cannot be run in a chroot() environment.");
b0d7c989
LP
2240
2241 return 0;
2242}
2243
74da609f
LP
2244static int initialize_security(
2245 bool *loaded_policy,
2246 dual_timestamp *security_start_timestamp,
2247 dual_timestamp *security_finish_timestamp,
2248 const char **ret_error_message) {
2249
2250 int r;
2251
2252 assert(loaded_policy);
2253 assert(security_start_timestamp);
2254 assert(security_finish_timestamp);
2255 assert(ret_error_message);
2256
2257 dual_timestamp_get(security_start_timestamp);
2258
97149f40 2259 r = mac_selinux_setup(loaded_policy);
74da609f
LP
2260 if (r < 0) {
2261 *ret_error_message = "Failed to load SELinux policy";
2262 return r;
2263 }
2264
2265 r = mac_smack_setup(loaded_policy);
2266 if (r < 0) {
2267 *ret_error_message = "Failed to load SMACK policy";
2268 return r;
2269 }
2270
2271 r = ima_setup();
2272 if (r < 0) {
2273 *ret_error_message = "Failed to load IMA policy";
2274 return r;
2275 }
2276
2277 dual_timestamp_get(security_finish_timestamp);
2278 return 0;
2279}
2280
263162da
LP
2281static void test_summary(Manager *m) {
2282 assert(m);
2283
2284 printf("-> By units:\n");
2285 manager_dump_units(m, stdout, "\t");
2286
2287 printf("-> By jobs:\n");
2288 manager_dump_jobs(m, stdout, "\t");
2289}
2290
efeb853f
LP
2291static int collect_fds(FDSet **ret_fds, const char **ret_error_message) {
2292 int r;
2293
2294 assert(ret_fds);
2295 assert(ret_error_message);
2296
2297 r = fdset_new_fill(ret_fds);
2298 if (r < 0) {
2299 *ret_error_message = "Failed to allocate fd set";
2300 return log_emergency_errno(r, "Failed to allocate fd set: %m");
2301 }
2302
2303 fdset_cloexec(*ret_fds, true);
2304
2305 if (arg_serialization)
2306 assert_se(fdset_remove(*ret_fds, fileno(arg_serialization)) >= 0);
2307
2308 return 0;
2309}
2310
2e51b31c
LP
2311static void setup_console_terminal(bool skip_setup) {
2312
2313 if (!arg_system)
2314 return;
2315
2316 /* Become a session leader if we aren't one yet. */
2317 (void) setsid();
2318
2319 /* If we are init, we connect stdin/stdout/stderr to /dev/null and make sure we don't have a controlling
2320 * tty. */
2321 (void) release_terminal();
2322
2323 /* Reset the console, but only if this is really init and we are freshly booted */
2324 if (getpid_cached() == 1 && !skip_setup)
2325 (void) console_setup();
2326}
2327
aa40ff07
LP
2328static bool early_skip_setup_check(int argc, char *argv[]) {
2329 bool found_deserialize = false;
2330 int i;
2331
2332 /* Determine if this is a reexecution or normal bootup. We do the full command line parsing much later, so
2333 * let's just have a quick peek here. Note that if we have switched root, do all the special setup things
2334 * anyway, even if in that case we also do deserialization. */
2335
2336 for (i = 1; i < argc; i++) {
aa40ff07
LP
2337 if (streq(argv[i], "--switched-root"))
2338 return false; /* If we switched root, don't skip the setup. */
2339 else if (streq(argv[i], "--deserialize"))
2340 found_deserialize = true;
2341 }
2342
2343 return found_deserialize; /* When we are deserializing, then we are reexecuting, hence avoid the extensive setup */
2344}
2345
60918275 2346int main(int argc, char *argv[]) {
625e8690
LP
2347
2348 dual_timestamp initrd_timestamp = DUAL_TIMESTAMP_NULL, userspace_timestamp = DUAL_TIMESTAMP_NULL, kernel_timestamp = DUAL_TIMESTAMP_NULL,
2349 security_start_timestamp = DUAL_TIMESTAMP_NULL, security_finish_timestamp = DUAL_TIMESTAMP_NULL;
ddfa8b0b
LP
2350 struct rlimit saved_rlimit_nofile = RLIMIT_MAKE_CONST(0),
2351 saved_rlimit_memlock = RLIMIT_MAKE_CONST(RLIM_INFINITY); /* The original rlimits we passed
2352 * in. Note we use different values
2353 * for the two that indicate whether
2354 * these fields are initialized! */
625e8690
LP
2355 bool skip_setup, loaded_policy = false, queue_default_job = false, first_boot = false, reexecute = false;
2356 char *switch_root_dir = NULL, *switch_root_init = NULL;
9d76d730 2357 usec_t before_startup, after_startup;
625e8690 2358 static char systemd[] = "systemd";
9d76d730 2359 char timespan[FORMAT_TIMESPAN_MAX];
625e8690
LP
2360 const char *shutdown_verb = NULL, *error_message = NULL;
2361 int r, retval = EXIT_FAILURE;
2362 Manager *m = NULL;
a16e1123 2363 FDSet *fds = NULL;
27b14a22 2364
d72a8f10 2365 /* SysV compatibility: redirect init → telinit */
6808a0bc 2366 redirect_telinit(argc, argv);
2cb1a60d 2367
d72a8f10 2368 /* Take timestamps early on */
c3a170f3
HH
2369 dual_timestamp_from_monotonic(&kernel_timestamp, 0);
2370 dual_timestamp_get(&userspace_timestamp);
2371
d72a8f10
LP
2372 /* Figure out whether we need to do initialize the system, or if we already did that because we are
2373 * reexecuting */
aa40ff07 2374 skip_setup = early_skip_setup_check(argc, argv);
d03bc1b8 2375
d72a8f10
LP
2376 /* If we get started via the /sbin/init symlink then we are called 'init'. After a subsequent reexecution we
2377 * are then called 'systemd'. That is confusing, hence let's call us systemd right-away. */
f3b6a3ed 2378 program_invocation_short_name = systemd;
eee8b7ab 2379 (void) prctl(PR_SET_NAME, systemd);
5d6b1584 2380
d72a8f10 2381 /* Save the original command line */
36fea155 2382 save_argc_argv(argc, argv);
f3b6a3ed 2383
6fdb8de4 2384 /* Make sure that if the user says "syslog" we actually log to the journal. */
c1dc6153 2385 log_set_upgrade_syslog_to_journal(true);
bbe63281 2386
df0ff127 2387 if (getpid_cached() == 1) {
b5752d23
LP
2388 /* When we run as PID 1 force system mode */
2389 arg_system = true;
2390
48a601fe 2391 /* Disable the umask logic */
90dc8c2e
MG
2392 umask(0);
2393
92890452
LP
2394 /* Make sure that at least initially we do not ever log to journald/syslogd, because it might not be
2395 * activated yet (even though the log socket for it exists). */
d075092f
LP
2396 log_set_prohibit_ipc(true);
2397
48a601fe
LP
2398 /* Always reopen /dev/console when running as PID 1 or one of its pre-execve() children. This is
2399 * important so that we never end up logging to any foreign stderr, for example if we have to log in a
2400 * child process right before execve()'ing the actual binary, at a point in time where socket
2401 * activation stderr/stdout area already set up. */
2402 log_set_always_reopen_console(true);
48a601fe 2403
92890452 2404 if (detect_container() <= 0) {
4f8d551f 2405
92890452 2406 /* Running outside of a container as PID 1 */
92890452
LP
2407 log_set_target(LOG_TARGET_KMSG);
2408 log_open();
a866073d 2409
92890452
LP
2410 if (in_initrd())
2411 initrd_timestamp = userspace_timestamp;
c3ba6250 2412
92890452
LP
2413 if (!skip_setup) {
2414 r = mount_setup_early();
2415 if (r < 0) {
2416 error_message = "Failed to mount early API filesystems";
2417 goto finish;
2418 }
2419
2420 r = initialize_security(
2421 &loaded_policy,
2422 &security_start_timestamp,
2423 &security_finish_timestamp,
2424 &error_message);
2425 if (r < 0)
2426 goto finish;
d723cd65 2427 }
eee8b7ab 2428
92890452
LP
2429 if (mac_selinux_init() < 0) {
2430 error_message = "Failed to initialize SELinux policy";
96694e99 2431 goto finish;
92890452 2432 }
0b3325e7 2433
92890452
LP
2434 if (!skip_setup)
2435 initialize_clock();
2436
2437 /* Set the default for later on, but don't actually open the logs like this for now. Note that
2438 * if we are transitioning from the initrd there might still be journal fd open, and we
2439 * shouldn't attempt opening that before we parsed /proc/cmdline which might redirect output
2440 * elsewhere. */
2441 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
2442
2443 } else {
2444 /* Running inside a container, as PID 1 */
92890452
LP
2445 log_set_target(LOG_TARGET_CONSOLE);
2446 log_open();
2447
2448 /* For later on, see above... */
2449 log_set_target(LOG_TARGET_JOURNAL);
2450
2451 /* clear the kernel timestamp,
2452 * because we are in a container */
2453 kernel_timestamp = DUAL_TIMESTAMP_NULL;
cb6531be 2454 }
7948c4df 2455
92890452 2456 initialize_coredump(skip_setup);
a866073d 2457
92890452
LP
2458 r = fixup_environment();
2459 if (r < 0) {
2460 log_emergency_errno(r, "Failed to fix up PID 1 environment: %m");
2461 error_message = "Failed to fix up PID1 environment";
2462 goto finish;
2463 }
a866073d 2464
c3a170f3 2465 } else {
a866073d 2466 /* Running as user instance */
463d0d15 2467 arg_system = false;
eeecf6e6 2468 log_set_target(LOG_TARGET_AUTO);
871e5809 2469 log_open();
c3a170f3
HH
2470
2471 /* clear the kernel timestamp,
2472 * because we are not PID 1 */
6513d561 2473 kernel_timestamp = DUAL_TIMESTAMP_NULL;
bbe63281 2474 }
a5dab5ce 2475
6edefe0b 2476 if (arg_system) {
92890452
LP
2477 /* Try to figure out if we can use colors with the console. No need to do that for user instances since
2478 * they never log into the console. */
3a18b604 2479 log_show_color(colors_enabled());
92890452 2480
c76cf844
AK
2481 r = make_null_stdio();
2482 if (r < 0)
92890452 2483 log_warning_errno(r, "Failed to redirect standard streams to /dev/null, ignoring: %m");
3a18b604
FB
2484 }
2485
f170852a
LP
2486 /* Mount /proc, /sys and friends, so that /proc/cmdline and
2487 * /proc/$PID/fd is available. */
df0ff127 2488 if (getpid_cached() == 1) {
f84f9974 2489
a132bef0 2490 /* Load the kernel modules early. */
2e75e2a8
DM
2491 if (!skip_setup)
2492 kmod_setup();
2e75e2a8 2493
0c85a4f3 2494 r = mount_setup(loaded_policy);
cb6531be
ZJS
2495 if (r < 0) {
2496 error_message = "Failed to mount API filesystems";
8efe3c01 2497 goto finish;
cb6531be 2498 }
0c85a4f3 2499 }
4ade7963
LP
2500
2501 /* Reset all signal handlers. */
ce30c8dc
LP
2502 (void) reset_all_signal_handlers();
2503 (void) ignore_signals(SIGNALS_IGNORE, -1);
078e4539 2504
97d1fb94
LP
2505 r = load_configuration(argc, argv, &error_message);
2506 if (r < 0)
f170852a 2507 goto finish;
10c961b9 2508
b0d7c989
LP
2509 r = safety_checks();
2510 if (r < 0)
fe783b03 2511 goto finish;
fe783b03 2512
bbc1acab 2513 if (IN_SET(arg_action, ACTION_TEST, ACTION_HELP, ACTION_DUMP_CONFIGURATION_ITEMS, ACTION_DUMP_BUS_PROPERTIES))
0221d68a 2514 (void) pager_open(arg_pager_flags);
b0d7c989
LP
2515
2516 if (arg_action != ACTION_RUN)
74e7579c 2517 skip_setup = true;
b87c2aa6 2518
fa0f4d8a 2519 if (arg_action == ACTION_HELP) {
37ec0fdd 2520 retval = help() < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
f170852a 2521 goto finish;
9ba0bc4e
ZJS
2522 } else if (arg_action == ACTION_VERSION) {
2523 retval = version();
2524 goto finish;
fa0f4d8a 2525 } else if (arg_action == ACTION_DUMP_CONFIGURATION_ITEMS) {
e537352b 2526 unit_dump_config_items(stdout);
22f4096c 2527 retval = EXIT_SUCCESS;
e537352b 2528 goto finish;
bbc1acab
YW
2529 } else if (arg_action == ACTION_DUMP_BUS_PROPERTIES) {
2530 dump_bus_properties(stdout);
2531 retval = EXIT_SUCCESS;
2532 goto finish;
f170852a
LP
2533 }
2534
4c701096 2535 assert_se(IN_SET(arg_action, ACTION_RUN, ACTION_TEST));
f170852a 2536
5a2e0c62
LP
2537 /* Move out of the way, so that we won't block unmounts */
2538 assert_se(chdir("/") == 0);
2539
dea374e8 2540 if (arg_action == ACTION_RUN) {
a70c72a0 2541
c6885f5f
FB
2542 /* A core pattern might have been specified via the cmdline. */
2543 initialize_core_pattern(skip_setup);
2544
efeb853f 2545 /* Close logging fds, in order not to confuse collecting passed fds and terminal logic below */
a70c72a0
LP
2546 log_close();
2547
2548 /* Remember open file descriptors for later deserialization */
efeb853f
LP
2549 r = collect_fds(&fds, &error_message);
2550 if (r < 0)
dea374e8 2551 goto finish;
a16e1123 2552
2e51b31c
LP
2553 /* Give up any control of the console, but make sure its initialized. */
2554 setup_console_terminal(skip_setup);
56d96fc0 2555
a70c72a0
LP
2556 /* Open the logging devices, if possible and necessary */
2557 log_open();
56d96fc0 2558 }
4ade7963 2559
31aef7ff 2560 log_execution_mode(&first_boot);
a5dab5ce 2561
2d776038
LP
2562 r = initialize_runtime(skip_setup,
2563 &saved_rlimit_nofile,
2564 &saved_rlimit_memlock,
2565 &error_message);
2566 if (r < 0)
2567 goto finish;
4096d6f5 2568
e0a3da1f
ZJS
2569 r = manager_new(arg_system ? UNIT_FILE_SYSTEM : UNIT_FILE_USER,
2570 arg_action == ACTION_TEST ? MANAGER_TEST_FULL : 0,
2571 &m);
e96d6be7 2572 if (r < 0) {
da927ba9 2573 log_emergency_errno(r, "Failed to allocate manager object: %m");
cb6531be 2574 error_message = "Failed to allocate manager object";
60918275
LP
2575 goto finish;
2576 }
2577
9f9f0342
LP
2578 m->timestamps[MANAGER_TIMESTAMP_KERNEL] = kernel_timestamp;
2579 m->timestamps[MANAGER_TIMESTAMP_INITRD] = initrd_timestamp;
2580 m->timestamps[MANAGER_TIMESTAMP_USERSPACE] = userspace_timestamp;
d4ee7bd8
YW
2581 m->timestamps[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_START)] = security_start_timestamp;
2582 m->timestamps[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_FINISH)] = security_finish_timestamp;
9e58ff9c 2583
85cb4151 2584 set_manager_defaults(m);
7b46fc6a 2585 set_manager_settings(m);
fd130612 2586 manager_set_first_boot(m, first_boot);
27d340c7 2587
bf4df7c3 2588 /* Remember whether we should queue the default job */
d3b1c508 2589 queue_default_job = !arg_serialization || arg_switched_root;
bf4df7c3 2590
9d76d730
LP
2591 before_startup = now(CLOCK_MONOTONIC);
2592
d3b1c508 2593 r = manager_startup(m, arg_serialization, fds);
58f88d92 2594 if (r < 0) {
cefb3eda 2595 error_message = "Failed to start up manager";
58f88d92
ZJS
2596 goto finish;
2597 }
a16e1123 2598
6acca5fc 2599 /* This will close all file descriptors that were opened, but not claimed by any unit. */
2feceb5e 2600 fds = fdset_free(fds);
74ca738f 2601 arg_serialization = safe_fclose(arg_serialization);
bf4df7c3
LP
2602
2603 if (queue_default_job) {
6acca5fc 2604 r = do_queue_default_job(m, &error_message);
718db961 2605 if (r < 0)
37d88da7 2606 goto finish;
6acca5fc 2607 }
ab17a050 2608
6acca5fc 2609 after_startup = now(CLOCK_MONOTONIC);
60918275 2610
6acca5fc
LP
2611 log_full(arg_action == ACTION_TEST ? LOG_INFO : LOG_DEBUG,
2612 "Loaded units and determined initial transaction in %s.",
2613 format_timespan(timespan, sizeof(timespan), after_startup - before_startup, 100 * USEC_PER_MSEC));
07672f49 2614
6acca5fc 2615 if (arg_action == ACTION_TEST) {
263162da 2616 test_summary(m);
6acca5fc
LP
2617 retval = EXIT_SUCCESS;
2618 goto finish;
e965d56d 2619 }
d46de8a1 2620
3046b6db
LP
2621 (void) invoke_main_loop(m,
2622 &reexecute,
2623 &retval,
2624 &shutdown_verb,
2625 &fds,
2626 &switch_root_dir,
2627 &switch_root_init,
2628 &error_message);
f170852a 2629
60918275 2630finish:
b87c2aa6
ZJS
2631 pager_close();
2632
92890452 2633 if (m) {
81f5fc2d 2634 arg_shutdown_watchdog = m->shutdown_watchdog;
92890452
LP
2635 m = manager_free(m);
2636 }
60918275 2637
970777b5 2638 free_arguments();
cc56fafe 2639 mac_selinux_finish();
b2bb3dbe 2640
3c7878f9
LP
2641 if (reexecute)
2642 do_reexecute(argc, argv,
2643 &saved_rlimit_nofile,
2644 &saved_rlimit_memlock,
2645 fds,
2646 switch_root_dir,
2647 switch_root_init,
2648 &error_message); /* This only returns if reexecution failed */
a16e1123 2649
74ca738f 2650 arg_serialization = safe_fclose(arg_serialization);
2feceb5e 2651 fds = fdset_free(fds);
a16e1123 2652
349cc4a5 2653#if HAVE_VALGRIND_VALGRIND_H
54b434b1
LP
2654 /* If we are PID 1 and running under valgrind, then let's exit
2655 * here explicitly. valgrind will only generate nice output on
2656 * exit(), not on exec(), hence let's do the former not the
2657 * latter here. */
8a2c1fbf
EJ
2658 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND) {
2659 /* Cleanup watchdog_device strings for valgrind. We need them
2660 * in become_shutdown() so normally we cannot free them yet. */
2661 watchdog_free_device();
2662 arg_watchdog_device = mfree(arg_watchdog_device);
27fe58b7 2663 return retval;
8a2c1fbf 2664 }
54b434b1
LP
2665#endif
2666
7e11a95e
EV
2667#if HAS_FEATURE_ADDRESS_SANITIZER
2668 __lsan_do_leak_check();
2669#endif
2670
b9080b03 2671 if (shutdown_verb) {
7eb35049 2672 r = become_shutdown(shutdown_verb, retval);
4a36297c 2673 log_error_errno(r, "Failed to execute shutdown binary, %s: %m", getpid_cached() == 1 ? "freezing" : "quitting");
9b9881d7 2674 error_message = "Failed to execute shutdown binary";
b9080b03
FF
2675 }
2676
8a2c1fbf
EJ
2677 watchdog_free_device();
2678 arg_watchdog_device = mfree(arg_watchdog_device);
2679
df0ff127 2680 if (getpid_cached() == 1) {
cb6531be
ZJS
2681 if (error_message)
2682 manager_status_printf(NULL, STATUS_TYPE_EMERGENCY,
1fc464f6 2683 ANSI_HIGHLIGHT_RED "!!!!!!" ANSI_NORMAL,
bb259772
LP
2684 "%s.", error_message);
2685 freeze_or_exit_or_reboot();
cb6531be 2686 }
c3b3c274 2687
60918275
LP
2688 return retval;
2689}