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