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