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