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