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