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