]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/main.c
Merge pull request #24799 from poettering/initrd-ftw
[thirdparty/systemd.git] / src / core / main.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <getopt.h>
6 #include <linux/oom.h>
7 #include <sys/mount.h>
8 #include <sys/prctl.h>
9 #include <sys/utsname.h>
10 #include <unistd.h>
11 #if HAVE_SECCOMP
12 #include <seccomp.h>
13 #endif
14 #if HAVE_VALGRIND_VALGRIND_H
15 #include <valgrind/valgrind.h>
16 #endif
17
18 #include "sd-bus.h"
19 #include "sd-daemon.h"
20 #include "sd-messages.h"
21
22 #include "alloc-util.h"
23 #include "apparmor-setup.h"
24 #include "architecture.h"
25 #if HAVE_LIBBPF
26 #include "bpf-lsm.h"
27 #endif
28 #include "build.h"
29 #include "bus-error.h"
30 #include "bus-util.h"
31 #include "capability-util.h"
32 #include "cgroup-util.h"
33 #include "clock-util.h"
34 #include "conf-parser.h"
35 #include "cpu-set-util.h"
36 #include "crash-handler.h"
37 #include "dbus-manager.h"
38 #include "dbus.h"
39 #include "def.h"
40 #include "dev-setup.h"
41 #include "efi-random.h"
42 #include "efivars.h"
43 #include "emergency-action.h"
44 #include "env-util.h"
45 #include "exit-status.h"
46 #include "fd-util.h"
47 #include "fdset.h"
48 #include "fileio.h"
49 #include "format-util.h"
50 #include "fs-util.h"
51 #include "hexdecoct.h"
52 #include "hostname-setup.h"
53 #include "ima-setup.h"
54 #include "import-creds.h"
55 #include "killall.h"
56 #include "kmod-setup.h"
57 #include "limits-util.h"
58 #include "load-fragment.h"
59 #include "log.h"
60 #include "loopback-setup.h"
61 #include "machine-id-setup.h"
62 #include "main.h"
63 #include "manager.h"
64 #include "manager-dump.h"
65 #include "manager-serialize.h"
66 #include "mkdir-label.h"
67 #include "mount-setup.h"
68 #include "os-util.h"
69 #include "pager.h"
70 #include "parse-argument.h"
71 #include "parse-util.h"
72 #include "path-util.h"
73 #include "pretty-print.h"
74 #include "proc-cmdline.h"
75 #include "process-util.h"
76 #include "random-util.h"
77 #include "rlimit-util.h"
78 #if HAVE_SECCOMP
79 #include "seccomp-util.h"
80 #endif
81 #include "selinux-setup.h"
82 #include "selinux-util.h"
83 #include "signal-util.h"
84 #include "smack-setup.h"
85 #include "special.h"
86 #include "stat-util.h"
87 #include "stdio-util.h"
88 #include "strv.h"
89 #include "switch-root.h"
90 #include "sysctl-util.h"
91 #include "terminal-util.h"
92 #include "time-util.h"
93 #include "umask-util.h"
94 #include "user-util.h"
95 #include "util.h"
96 #include "virt.h"
97 #include "watchdog.h"
98
99 #if HAS_FEATURE_ADDRESS_SANITIZER
100 #include <sanitizer/lsan_interface.h>
101 #endif
102
103 #define DEFAULT_TASKS_MAX ((TasksMax) { 15U, 100U }) /* 15% */
104
105 static enum {
106 ACTION_RUN,
107 ACTION_HELP,
108 ACTION_VERSION,
109 ACTION_TEST,
110 ACTION_DUMP_CONFIGURATION_ITEMS,
111 ACTION_DUMP_BUS_PROPERTIES,
112 ACTION_BUS_INTROSPECT,
113 } arg_action = ACTION_RUN;
114
115 static const char *arg_bus_introspect = NULL;
116
117 /* Those variables are initialized to 0 automatically, so we avoid uninitialized memory access. Real
118 * defaults are assigned in reset_arguments() below. */
119 static char *arg_default_unit;
120 static bool arg_system;
121 bool arg_dump_core;
122 int arg_crash_chvt;
123 bool arg_crash_shell;
124 bool arg_crash_reboot;
125 static char *arg_confirm_spawn;
126 static ShowStatus arg_show_status;
127 static StatusUnitFormat arg_status_unit_format;
128 static bool arg_switched_root;
129 static PagerFlags arg_pager_flags;
130 static bool arg_service_watchdogs;
131 static ExecOutput arg_default_std_output;
132 static ExecOutput arg_default_std_error;
133 static usec_t arg_default_restart_usec;
134 static usec_t arg_default_timeout_start_usec;
135 static usec_t arg_default_timeout_stop_usec;
136 static usec_t arg_default_timeout_abort_usec;
137 static usec_t arg_default_device_timeout_usec;
138 static bool arg_default_timeout_abort_set;
139 static usec_t arg_default_start_limit_interval;
140 static unsigned arg_default_start_limit_burst;
141 static usec_t arg_runtime_watchdog;
142 static usec_t arg_reboot_watchdog;
143 static usec_t arg_kexec_watchdog;
144 static usec_t arg_pretimeout_watchdog;
145 static char *arg_early_core_pattern;
146 static char *arg_watchdog_pretimeout_governor;
147 static char *arg_watchdog_device;
148 static char **arg_default_environment;
149 static char **arg_manager_environment;
150 static struct rlimit *arg_default_rlimit[_RLIMIT_MAX];
151 static uint64_t arg_capability_bounding_set;
152 static bool arg_no_new_privs;
153 static nsec_t arg_timer_slack_nsec;
154 static usec_t arg_default_timer_accuracy_usec;
155 static Set* arg_syscall_archs;
156 static FILE* arg_serialization;
157 static int arg_default_cpu_accounting;
158 static bool arg_default_io_accounting;
159 static bool arg_default_ip_accounting;
160 static bool arg_default_blockio_accounting;
161 static bool arg_default_memory_accounting;
162 static bool arg_default_tasks_accounting;
163 static TasksMax arg_default_tasks_max;
164 static sd_id128_t arg_machine_id;
165 static EmergencyAction arg_cad_burst_action;
166 static OOMPolicy arg_default_oom_policy;
167 static CPUSet arg_cpu_affinity;
168 static NUMAPolicy arg_numa_policy;
169 static usec_t arg_clock_usec;
170 static void *arg_random_seed;
171 static size_t arg_random_seed_size;
172 static int arg_default_oom_score_adjust;
173 static bool arg_default_oom_score_adjust_set;
174 static char *arg_default_smack_process_label;
175
176 /* A copy of the original environment block */
177 static char **saved_env = NULL;
178
179 static int parse_configuration(const struct rlimit *saved_rlimit_nofile,
180 const struct rlimit *saved_rlimit_memlock);
181
182 static 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
212 static int console_setup(void) {
213 _cleanup_close_ int tty_fd = -1;
214 int r;
215
216 tty_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
217 if (tty_fd < 0)
218 return log_error_errno(tty_fd, "Failed to open /dev/console: %m");
219
220 /* We don't want to force text mode. plymouth may be showing
221 * pictures already from initrd. */
222 r = reset_terminal_fd(tty_fd, false);
223 if (r < 0)
224 return log_error_errno(r, "Failed to reset /dev/console: %m");
225
226 return 0;
227 }
228
229 static int set_machine_id(const char *m) {
230 sd_id128_t t;
231 assert(m);
232
233 if (sd_id128_from_string(m, &t) < 0)
234 return -EINVAL;
235
236 if (sd_id128_is_null(t))
237 return -EINVAL;
238
239 arg_machine_id = t;
240 return 0;
241 }
242
243 static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
244 int r;
245
246 assert(key);
247
248 if (STR_IN_SET(key, "systemd.unit", "rd.systemd.unit")) {
249
250 if (proc_cmdline_value_missing(key, value))
251 return 0;
252
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);
255 else if (in_initrd() == !!startswith(key, "rd."))
256 return free_and_strdup_warn(&arg_default_unit, value);
257
258 } else if (proc_cmdline_key_streq(key, "systemd.dump_core")) {
259
260 r = value ? parse_boolean(value) : true;
261 if (r < 0)
262 log_warning_errno(r, "Failed to parse dump core switch %s, ignoring: %m", value);
263 else
264 arg_dump_core = r;
265
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))
272 (void) parse_path_argument(value, false, &arg_early_core_pattern);
273 else
274 log_warning("Specified core pattern '%s' is not an absolute path, ignoring.", value);
275
276 } else if (proc_cmdline_key_streq(key, "systemd.crash_chvt")) {
277
278 if (!value)
279 arg_crash_chvt = 0; /* turn on */
280 else {
281 r = parse_crash_chvt(value, &arg_crash_chvt);
282 if (r < 0)
283 log_warning_errno(r, "Failed to parse crash chvt switch %s, ignoring: %m", value);
284 }
285
286 } else if (proc_cmdline_key_streq(key, "systemd.crash_shell")) {
287
288 r = value ? parse_boolean(value) : true;
289 if (r < 0)
290 log_warning_errno(r, "Failed to parse crash shell switch %s, ignoring: %m", value);
291 else
292 arg_crash_shell = r;
293
294 } else if (proc_cmdline_key_streq(key, "systemd.crash_reboot")) {
295
296 r = value ? parse_boolean(value) : true;
297 if (r < 0)
298 log_warning_errno(r, "Failed to parse crash reboot switch %s, ignoring: %m", value);
299 else
300 arg_crash_reboot = r;
301
302 } else if (proc_cmdline_key_streq(key, "systemd.confirm_spawn")) {
303 char *s;
304
305 r = parse_confirm_spawn(value, &s);
306 if (r < 0)
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);
310
311 } else if (proc_cmdline_key_streq(key, "systemd.service_watchdogs")) {
312
313 r = value ? parse_boolean(value) : true;
314 if (r < 0)
315 log_warning_errno(r, "Failed to parse service watchdog switch %s, ignoring: %m", value);
316 else
317 arg_service_watchdogs = r;
318
319 } else if (proc_cmdline_key_streq(key, "systemd.show_status")) {
320
321 if (value) {
322 r = parse_show_status(value, &arg_show_status);
323 if (r < 0)
324 log_warning_errno(r, "Failed to parse show status switch %s, ignoring: %m", value);
325 } else
326 arg_show_status = SHOW_STATUS_YES;
327
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
339 } else if (proc_cmdline_key_streq(key, "systemd.default_standard_output")) {
340
341 if (proc_cmdline_value_missing(key, value))
342 return 0;
343
344 r = exec_output_from_string(value);
345 if (r < 0)
346 log_warning_errno(r, "Failed to parse default standard output switch %s, ignoring: %m", value);
347 else
348 arg_default_std_output = r;
349
350 } else if (proc_cmdline_key_streq(key, "systemd.default_standard_error")) {
351
352 if (proc_cmdline_value_missing(key, value))
353 return 0;
354
355 r = exec_output_from_string(value);
356 if (r < 0)
357 log_warning_errno(r, "Failed to parse default standard error switch %s, ignoring: %m", value);
358 else
359 arg_default_std_error = r;
360
361 } else if (streq(key, "systemd.setenv")) {
362
363 if (proc_cmdline_value_missing(key, value))
364 return 0;
365
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)
371 return log_oom();
372 }
373
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)
381 log_warning_errno(r, "MachineID '%s' is not valid, ignoring: %m", value);
382
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)
390 log_warning_errno(r, "Failed to parse default start timeout '%s', ignoring: %m", value);
391
392 if (arg_default_timeout_start_usec <= 0)
393 arg_default_timeout_start_usec = USEC_INFINITY;
394
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)
402 log_warning_errno(r, "Failed to parse CPU affinity mask '%s', ignoring: %m", value);
403
404 } else if (proc_cmdline_key_streq(key, "systemd.watchdog_device")) {
405
406 if (proc_cmdline_value_missing(key, value))
407 return 0;
408
409 (void) parse_path_argument(value, false, &arg_watchdog_device);
410
411 } else if (proc_cmdline_key_streq(key, "systemd.watchdog_sec")) {
412
413 if (proc_cmdline_value_missing(key, value))
414 return 0;
415
416 if (streq(value, "default"))
417 arg_runtime_watchdog = USEC_INFINITY;
418 else if (streq(value, "off"))
419 arg_runtime_watchdog = 0;
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;
429
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
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
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
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
477 r = unbase64mem(value, SIZE_MAX, &p, &sz);
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
485 } else if (streq(key, "quiet") && !value) {
486
487 if (arg_show_status == _SHOW_STATUS_INVALID)
488 arg_show_status = SHOW_STATUS_ERROR;
489
490 } else if (streq(key, "debug") && !value) {
491
492 /* Note that log_parse_environment() handles 'debug'
493 * too, and sets the log level to LOG_DEBUG. */
494
495 if (detect_container() > 0)
496 log_set_target(LOG_TARGET_CONSOLE);
497
498 } else if (!value) {
499 const char *target;
500
501 /* Compatible with SysV, but supported independently even if SysV compatibility is disabled. */
502 target = runlevel_to_target(key);
503 if (target)
504 return free_and_strdup_warn(&arg_default_unit, target);
505 }
506
507 return 0;
508 }
509
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, \
515 unsigned section_line, \
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) \
530 log_syntax(unit, LOG_ERR, filename, line, r, \
531 "Invalid " descr "'%s': %m", \
532 rvalue); \
533 \
534 return 0; \
535 }
536
537 DEFINE_SETTER(config_parse_level2, log_set_max_level_from_string, "log level");
538 DEFINE_SETTER(config_parse_target, log_set_target_from_string, "target");
539 DEFINE_SETTER(config_parse_color, log_show_color_from_string, "color");
540 DEFINE_SETTER(config_parse_location, log_show_location_from_string, "location");
541 DEFINE_SETTER(config_parse_time, log_show_time_from_string, "time");
542
543 static 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 }
562
563 static 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
594 static int parse_config_file(void) {
595 const ConfigTableItem items[] = {
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 },
621 #if HAVE_SECCOMP
622 { "Manager", "SystemCallArchitectures", config_parse_syscall_archs, 0, &arg_syscall_archs },
623 #endif
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 },
631 { "Manager", "DefaultDeviceTimeoutSec", config_parse_sec, 0, &arg_default_device_timeout_usec },
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 },
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
669 {}
670 };
671
672 _cleanup_strv_free_ char **files = NULL, **dirs = NULL;
673 const char *suffix;
674 int r;
675
676 if (arg_system)
677 suffix = "system.conf.d";
678 else {
679 r = manager_find_user_config_paths(&files, &dirs);
680 if (r < 0)
681 return log_error_errno(r, "Failed to determine config file paths: %m");
682
683 suffix = "user.conf.d";
684 }
685
686 (void) config_parse_many(
687 (const char* const*) (files ?: STRV_MAKE(PKGSYSCONFDIR "/system.conf")),
688 (const char* const*) (dirs ?: CONF_PATHS_STRV("systemd")),
689 suffix,
690 "Manager\0",
691 config_item_table_lookup, items,
692 CONFIG_PARSE_WARN,
693 NULL,
694 NULL,
695 NULL);
696
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. */
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;
703
704 return 0;
705 }
706
707 static void set_manager_defaults(Manager *m) {
708
709 assert(m);
710
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
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;
720 m->default_timeout_abort_usec = arg_default_timeout_abort_usec;
721 m->default_timeout_abort_set = arg_default_timeout_abort_set;
722 m->default_device_timeout_usec = arg_default_device_timeout_usec;
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;
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
734 m->default_io_accounting = arg_default_io_accounting;
735 m->default_ip_accounting = arg_default_ip_accounting;
736 m->default_blockio_accounting = arg_default_blockio_accounting;
737 m->default_memory_accounting = arg_default_memory_accounting;
738 m->default_tasks_accounting = arg_default_tasks_accounting;
739 m->default_tasks_max = arg_default_tasks_max;
740 m->default_oom_policy = arg_default_oom_policy;
741 m->default_oom_score_adjust_set = arg_default_oom_score_adjust_set;
742 m->default_oom_score_adjust = arg_default_oom_score_adjust;
743
744 (void) manager_set_default_smack_process_label(m, arg_default_smack_process_label);
745
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);
750 }
751
752 static void set_manager_settings(Manager *m) {
753 int r;
754
755 assert(m);
756
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). */
760
761 m->confirm_spawn = arg_confirm_spawn;
762 m->service_watchdogs = arg_service_watchdogs;
763 m->cad_burst_action = arg_cad_burst_action;
764
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);
768 manager_set_watchdog(m, WATCHDOG_PRETIMEOUT, arg_pretimeout_watchdog);
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);
772
773 manager_set_show_status(m, arg_show_status, "commandline");
774 m->status_unit_format = arg_status_unit_format;
775 }
776
777 static int parse_argv(int argc, char *argv[]) {
778 enum {
779 ARG_LOG_LEVEL = 0x100,
780 ARG_LOG_TARGET,
781 ARG_LOG_COLOR,
782 ARG_LOG_LOCATION,
783 ARG_LOG_TIME,
784 ARG_UNIT,
785 ARG_SYSTEM,
786 ARG_USER,
787 ARG_TEST,
788 ARG_NO_PAGER,
789 ARG_VERSION,
790 ARG_DUMP_CONFIGURATION_ITEMS,
791 ARG_DUMP_BUS_PROPERTIES,
792 ARG_BUS_INTROSPECT,
793 ARG_DUMP_CORE,
794 ARG_CRASH_CHVT,
795 ARG_CRASH_SHELL,
796 ARG_CRASH_REBOOT,
797 ARG_CONFIRM_SPAWN,
798 ARG_SHOW_STATUS,
799 ARG_DESERIALIZE,
800 ARG_SWITCHED_ROOT,
801 ARG_DEFAULT_STD_OUTPUT,
802 ARG_DEFAULT_STD_ERROR,
803 ARG_MACHINE_ID,
804 ARG_SERVICE_WATCHDOGS,
805 };
806
807 static const struct option options[] = {
808 { "log-level", required_argument, NULL, ARG_LOG_LEVEL },
809 { "log-target", required_argument, NULL, ARG_LOG_TARGET },
810 { "log-color", optional_argument, NULL, ARG_LOG_COLOR },
811 { "log-location", optional_argument, NULL, ARG_LOG_LOCATION },
812 { "log-time", optional_argument, NULL, ARG_LOG_TIME },
813 { "unit", required_argument, NULL, ARG_UNIT },
814 { "system", no_argument, NULL, ARG_SYSTEM },
815 { "user", no_argument, NULL, ARG_USER },
816 { "test", no_argument, NULL, ARG_TEST },
817 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
818 { "help", no_argument, NULL, 'h' },
819 { "version", no_argument, NULL, ARG_VERSION },
820 { "dump-configuration-items", no_argument, NULL, ARG_DUMP_CONFIGURATION_ITEMS },
821 { "dump-bus-properties", no_argument, NULL, ARG_DUMP_BUS_PROPERTIES },
822 { "bus-introspect", required_argument, NULL, ARG_BUS_INTROSPECT },
823 { "dump-core", optional_argument, NULL, ARG_DUMP_CORE },
824 { "crash-chvt", required_argument, NULL, ARG_CRASH_CHVT },
825 { "crash-shell", optional_argument, NULL, ARG_CRASH_SHELL },
826 { "crash-reboot", optional_argument, NULL, ARG_CRASH_REBOOT },
827 { "confirm-spawn", optional_argument, NULL, ARG_CONFIRM_SPAWN },
828 { "show-status", optional_argument, NULL, ARG_SHOW_STATUS },
829 { "deserialize", required_argument, NULL, ARG_DESERIALIZE },
830 { "switched-root", no_argument, NULL, ARG_SWITCHED_ROOT },
831 { "default-standard-output", required_argument, NULL, ARG_DEFAULT_STD_OUTPUT, },
832 { "default-standard-error", required_argument, NULL, ARG_DEFAULT_STD_ERROR, },
833 { "machine-id", required_argument, NULL, ARG_MACHINE_ID },
834 { "service-watchdogs", required_argument, NULL, ARG_SERVICE_WATCHDOGS },
835 {}
836 };
837
838 int c, r;
839 bool user_arg_seen = false;
840
841 assert(argc >= 1);
842 assert(argv);
843
844 if (getpid_cached() == 1)
845 opterr = 0;
846
847 while ((c = getopt_long(argc, argv, "hDbsz:", options, NULL)) >= 0)
848
849 switch (c) {
850
851 case ARG_LOG_LEVEL:
852 r = log_set_max_level_from_string(optarg);
853 if (r < 0)
854 return log_error_errno(r, "Failed to parse log level \"%s\": %m", optarg);
855
856 break;
857
858 case ARG_LOG_TARGET:
859 r = log_set_target_from_string(optarg);
860 if (r < 0)
861 return log_error_errno(r, "Failed to parse log target \"%s\": %m", optarg);
862
863 break;
864
865 case ARG_LOG_COLOR:
866
867 if (optarg) {
868 r = log_show_color_from_string(optarg);
869 if (r < 0)
870 return log_error_errno(r, "Failed to parse log color setting \"%s\": %m",
871 optarg);
872 } else
873 log_show_color(true);
874
875 break;
876
877 case ARG_LOG_LOCATION:
878 if (optarg) {
879 r = log_show_location_from_string(optarg);
880 if (r < 0)
881 return log_error_errno(r, "Failed to parse log location setting \"%s\": %m",
882 optarg);
883 } else
884 log_show_location(true);
885
886 break;
887
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
900 case ARG_DEFAULT_STD_OUTPUT:
901 r = exec_output_from_string(optarg);
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;
906 break;
907
908 case ARG_DEFAULT_STD_ERROR:
909 r = exec_output_from_string(optarg);
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;
914 break;
915
916 case ARG_UNIT:
917 r = free_and_strdup(&arg_default_unit, optarg);
918 if (r < 0)
919 return log_error_errno(r, "Failed to set default unit \"%s\": %m", optarg);
920
921 break;
922
923 case ARG_SYSTEM:
924 arg_system = true;
925 break;
926
927 case ARG_USER:
928 arg_system = false;
929 user_arg_seen = true;
930 break;
931
932 case ARG_TEST:
933 arg_action = ACTION_TEST;
934 break;
935
936 case ARG_NO_PAGER:
937 arg_pager_flags |= PAGER_DISABLE;
938 break;
939
940 case ARG_VERSION:
941 arg_action = ACTION_VERSION;
942 break;
943
944 case ARG_DUMP_CONFIGURATION_ITEMS:
945 arg_action = ACTION_DUMP_CONFIGURATION_ITEMS;
946 break;
947
948 case ARG_DUMP_BUS_PROPERTIES:
949 arg_action = ACTION_DUMP_BUS_PROPERTIES;
950 break;
951
952 case ARG_BUS_INTROSPECT:
953 arg_bus_introspect = optarg;
954 arg_action = ACTION_BUS_INTROSPECT;
955 break;
956
957 case ARG_DUMP_CORE:
958 r = parse_boolean_argument("--dump-core", optarg, &arg_dump_core);
959 if (r < 0)
960 return r;
961 break;
962
963 case ARG_CRASH_CHVT:
964 r = parse_crash_chvt(optarg, &arg_crash_chvt);
965 if (r < 0)
966 return log_error_errno(r, "Failed to parse crash virtual terminal index: \"%s\": %m",
967 optarg);
968 break;
969
970 case ARG_CRASH_SHELL:
971 r = parse_boolean_argument("--crash-shell", optarg, &arg_crash_shell);
972 if (r < 0)
973 return r;
974 break;
975
976 case ARG_CRASH_REBOOT:
977 r = parse_boolean_argument("--crash-reboot", optarg, &arg_crash_reboot);
978 if (r < 0)
979 return r;
980 break;
981
982 case ARG_CONFIRM_SPAWN:
983 arg_confirm_spawn = mfree(arg_confirm_spawn);
984
985 r = parse_confirm_spawn(optarg, &arg_confirm_spawn);
986 if (r < 0)
987 return log_error_errno(r, "Failed to parse confirm spawn option: \"%s\": %m",
988 optarg);
989 break;
990
991 case ARG_SERVICE_WATCHDOGS:
992 r = parse_boolean_argument("--service-watchdogs=", optarg, &arg_service_watchdogs);
993 if (r < 0)
994 return r;
995 break;
996
997 case ARG_SHOW_STATUS:
998 if (optarg) {
999 r = parse_show_status(optarg, &arg_show_status);
1000 if (r < 0)
1001 return log_error_errno(r, "Failed to parse show status boolean: \"%s\": %m",
1002 optarg);
1003 } else
1004 arg_show_status = SHOW_STATUS_YES;
1005 break;
1006
1007 case ARG_DESERIALIZE: {
1008 int fd;
1009 FILE *f;
1010
1011 r = safe_atoi(optarg, &fd);
1012 if (r < 0)
1013 log_error_errno(r, "Failed to parse deserialize option \"%s\": %m", optarg);
1014 if (fd < 0)
1015 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1016 "Invalid deserialize fd: %d",
1017 fd);
1018
1019 (void) fd_cloexec(fd, true);
1020
1021 f = fdopen(fd, "r");
1022 if (!f)
1023 return log_error_errno(errno, "Failed to open serialization fd %d: %m", fd);
1024
1025 safe_fclose(arg_serialization);
1026 arg_serialization = f;
1027
1028 break;
1029 }
1030
1031 case ARG_SWITCHED_ROOT:
1032 arg_switched_root = true;
1033 break;
1034
1035 case ARG_MACHINE_ID:
1036 r = set_machine_id(optarg);
1037 if (r < 0)
1038 return log_error_errno(r, "MachineID '%s' is not valid: %m", optarg);
1039 break;
1040
1041 case 'h':
1042 arg_action = ACTION_HELP;
1043 break;
1044
1045 case 'D':
1046 log_set_max_level(LOG_DEBUG);
1047 break;
1048
1049 case 'b':
1050 case 's':
1051 case 'z':
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 */
1055 case '?':
1056 if (getpid_cached() != 1)
1057 return -EINVAL;
1058 else
1059 return 0;
1060
1061 default:
1062 assert_not_reached();
1063 }
1064
1065 if (optind < argc && getpid_cached() != 1)
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)
1070 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1071 "Explicit --user argument required to run as user manager.");
1072
1073 return 0;
1074 }
1075
1076 static int help(void) {
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();
1083
1084 printf("%s [OPTIONS...]\n\n"
1085 "%sStarts and monitors system and user services.%s\n\n"
1086 "This program takes no positional arguments.\n\n"
1087 "%sOptions%s:\n"
1088 " -h --help Show this help\n"
1089 " --version Show version\n"
1090 " --test Determine initial transaction, dump it and exit\n"
1091 " --system Combined with --test: operate in system mode\n"
1092 " --user Combined with --test: operate in user mode\n"
1093 " --dump-configuration-items Dump understood unit configuration items\n"
1094 " --dump-bus-properties Dump exposed bus properties\n"
1095 " --bus-introspect=PATH Write XML introspection data\n"
1096 " --unit=UNIT Set default unit\n"
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"
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"
1107 " --log-color[=BOOL] Highlight important log messages\n"
1108 " --log-location[=BOOL] Include code location in log messages\n"
1109 " --log-time[=BOOL] Prefix log messages with current time\n"
1110 " --default-standard-output= Set default standard output for services\n"
1111 " --default-standard-error= Set default standard error output for services\n"
1112 " --no-pager Do not pipe output into a pager\n"
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);
1120
1121 return 0;
1122 }
1123
1124 static int prepare_reexecute(
1125 Manager *m,
1126 FILE **ret_f,
1127 FDSet **ret_fds,
1128 bool switching_root) {
1129
1130 _cleanup_fdset_free_ FDSet *fds = NULL;
1131 _cleanup_fclose_ FILE *f = NULL;
1132 int r;
1133
1134 assert(m);
1135 assert(ret_f);
1136 assert(ret_fds);
1137
1138 r = manager_open_serialization(m, &f);
1139 if (r < 0)
1140 return log_error_errno(r, "Failed to create serialization file: %m");
1141
1142 /* Make sure nothing is really destructed when we shut down */
1143 m->n_reloading++;
1144 bus_manager_send_reloading(m, true);
1145
1146 fds = fdset_new();
1147 if (!fds)
1148 return log_oom();
1149
1150 r = manager_serialize(m, f, fds, switching_root);
1151 if (r < 0)
1152 return r;
1153
1154 if (fseeko(f, 0, SEEK_SET) == (off_t) -1)
1155 return log_error_errno(errno, "Failed to rewind serialization fd: %m");
1156
1157 r = fd_cloexec(fileno(f), false);
1158 if (r < 0)
1159 return log_error_errno(r, "Failed to disable O_CLOEXEC for serialization: %m");
1160
1161 r = fdset_cloexec(fds, false);
1162 if (r < 0)
1163 return log_error_errno(r, "Failed to disable O_CLOEXEC for serialization fds: %m");
1164
1165 *ret_f = TAKE_PTR(f);
1166 *ret_fds = TAKE_PTR(fds);
1167
1168 return 0;
1169 }
1170
1171 static void bump_file_max_and_nr_open(void) {
1172
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. */
1178
1179 #if BUMP_PROC_SYS_FS_FILE_MAX || BUMP_PROC_SYS_FS_NR_OPEN
1180 int r;
1181 #endif
1182
1183 #if BUMP_PROC_SYS_FS_FILE_MAX
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.) */
1186 r = sysctl_writef("fs/file-max", "%li\n", LONG_MAX);
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
1191 #if BUMP_PROC_SYS_FS_NR_OPEN
1192 int v = INT_MAX;
1193
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... 🤯 */
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
1220 r = sysctl_writef("fs/nr_open", "%i\n", v);
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
1237 static int bump_rlimit_nofile(const struct rlimit *saved_rlimit) {
1238 struct rlimit new_rlimit;
1239 int r, nr;
1240
1241 /* Get the underlying absolute limit the kernel enforces */
1242 nr = read_nr_open();
1243
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
1257 /* Bump up the resource limit for ourselves substantially, all the way to the maximum the kernel allows, for
1258 * both hard and soft. */
1259 r = setrlimit_closest(RLIMIT_NOFILE, &new_rlimit);
1260 if (r < 0)
1261 return log_warning_errno(r, "Setting RLIMIT_NOFILE failed, ignoring: %m");
1262
1263 return 0;
1264 }
1265
1266 static int bump_rlimit_memlock(const struct rlimit *saved_rlimit) {
1267 struct rlimit new_rlimit;
1268 uint64_t mm;
1269 int r;
1270
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. */
1274
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
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. */
1282
1283 new_rlimit = (struct rlimit) {
1284 .rlim_cur = MAX3(HIGH_RLIMIT_MEMLOCK, saved_rlimit->rlim_cur, mm),
1285 .rlim_max = MAX3(HIGH_RLIMIT_MEMLOCK, saved_rlimit->rlim_max, mm),
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);
1295 if (r < 0)
1296 return log_warning_errno(r, "Setting RLIMIT_MEMLOCK failed, ignoring: %m");
1297
1298 return 0;
1299 }
1300
1301 static void test_usr(void) {
1302
1303 /* Check that /usr is either on the same file system as / or mounted already. */
1304
1305 if (dir_is_empty("/usr", /* ignore_hidden_or_backup= */ false) <= 0)
1306 return;
1307
1308 log_warning("/usr appears to be on its own filesystem and is not already mounted. This is not a supported setup. "
1309 "Some things will probably break (sometimes even silently) in mysterious ways. "
1310 "Consult https://www.freedesktop.org/wiki/Software/systemd/separate-usr-is-broken for more information.");
1311 }
1312
1313 static int enforce_syscall_archs(Set *archs) {
1314 #if HAVE_SECCOMP
1315 int r;
1316
1317 if (!is_seccomp_available())
1318 return 0;
1319
1320 r = seccomp_restrict_archs(arg_syscall_archs);
1321 if (r < 0)
1322 return log_error_errno(r, "Failed to enforce system call architecture restrication: %m");
1323 #endif
1324 return 0;
1325 }
1326
1327 static int os_release_status(void) {
1328 _cleanup_free_ char *pretty_name = NULL, *name = NULL, *version = NULL,
1329 *ansi_color = NULL, *support_end = NULL;
1330 int r;
1331
1332 r = parse_os_release(NULL,
1333 "PRETTY_NAME", &pretty_name,
1334 "NAME", &name,
1335 "VERSION", &version,
1336 "ANSI_COLOR", &ansi_color,
1337 "SUPPORT_END", &support_end);
1338 if (r < 0)
1339 return log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_WARNING, r,
1340 "Failed to read os-release file, ignoring: %m");
1341
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;
1367 }
1368
1369 static int write_container_id(void) {
1370 const char *c;
1371 int r = 0; /* avoid false maybe-uninitialized warning */
1372
1373 c = getenv("container");
1374 if (isempty(c))
1375 return 0;
1376
1377 RUN_WITH_UMASK(0022)
1378 r = write_string_file("/run/systemd/container", c, WRITE_STRING_FILE_CREATE);
1379 if (r < 0)
1380 return log_warning_errno(r, "Failed to write /run/systemd/container, ignoring: %m");
1381
1382 return 1;
1383 }
1384
1385 static int bump_unix_max_dgram_qlen(void) {
1386 _cleanup_free_ char *qlen = NULL;
1387 unsigned long v;
1388 int r;
1389
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. */
1393
1394 r = read_one_line_file("/proc/sys/net/unix/max_dgram_qlen", &qlen);
1395 if (r < 0)
1396 return log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_WARNING, r,
1397 "Failed to read AF_UNIX datagram queue length, ignoring: %m");
1398
1399 r = safe_atolu(qlen, &v);
1400 if (r < 0)
1401 return log_warning_errno(r, "Failed to parse AF_UNIX datagram queue length '%s', ignoring: %m", qlen);
1402
1403 if (v >= DEFAULT_UNIX_MAX_DGRAM_QLEN)
1404 return 0;
1405
1406 r = write_string_filef("/proc/sys/net/unix/max_dgram_qlen", WRITE_STRING_FILE_DISABLE_BUFFER,
1407 "%lu", DEFAULT_UNIX_MAX_DGRAM_QLEN);
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;
1413 }
1414
1415 static int fixup_environment(void) {
1416 _cleanup_free_ char *term = NULL;
1417 const char *t;
1418 int r;
1419
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. */
1425 if (detect_container() > 0)
1426 return 0;
1427
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.
1431 *
1432 * However if TERM was configured through the kernel command line then leave it alone. */
1433 r = proc_cmdline_get_key("TERM", 0, &term);
1434 if (r < 0)
1435 return r;
1436
1437 t = term ?: default_term_for_tty("/dev/console");
1438
1439 if (setenv("TERM", t, 1) < 0)
1440 return -errno;
1441
1442 /* The kernels sets HOME=/ for init. Let's undo this. */
1443 if (path_equal_ptr(getenv("HOME"), "/"))
1444 assert_se(unsetenv("HOME") == 0);
1445
1446 return 0;
1447 }
1448
1449 static 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
1457 if (!invoked_as(argv, "init"))
1458 return;
1459
1460 execv(SYSTEMCTL_BINARY_PATH, argv);
1461 log_error_errno(errno, "Failed to exec " SYSTEMCTL_BINARY_PATH ": %m");
1462 exit(EXIT_FAILURE);
1463 #endif
1464 }
1465
1466 static int become_shutdown(
1467 const char *shutdown_verb,
1468 int retval) {
1469
1470 char log_level[DECIMAL_STR_MAX(int) + 1],
1471 exit_code[DECIMAL_STR_MAX(uint8_t) + 1],
1472 timeout[DECIMAL_STR_MAX(usec_t) + 1];
1473
1474 const char* command_line[13] = {
1475 SYSTEMD_SHUTDOWN_BINARY_PATH,
1476 shutdown_verb,
1477 "--timeout", timeout,
1478 "--log-level", log_level,
1479 "--log-target",
1480 };
1481
1482 _cleanup_strv_free_ char **env_block = NULL;
1483 usec_t watchdog_timer = 0;
1484 size_t pos = 7;
1485 int r;
1486
1487 assert(shutdown_verb);
1488 assert(!command_line[pos]);
1489 env_block = strv_copy(environ);
1490
1491 xsprintf(log_level, "%d", log_get_max_level());
1492 xsprintf(timeout, "%" PRI_USEC "us", arg_default_timeout_stop_usec);
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
1518 if (log_get_show_time())
1519 command_line[pos++] = "--log-time";
1520
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
1529 if (streq(shutdown_verb, "reboot"))
1530 watchdog_timer = arg_reboot_watchdog;
1531 else if (streq(shutdown_verb, "kexec"))
1532 watchdog_timer = arg_kexec_watchdog;
1533
1534 /* If we reboot or kexec let's set the shutdown watchdog and tell the
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);
1538 (void) watchdog_setup_pretimeout_governor(NULL);
1539 r = watchdog_setup(watchdog_timer);
1540 watchdog_close(r < 0);
1541
1542 /* Tell the binary how often to ping, ignore failure */
1543 (void) strv_extendf(&env_block, "WATCHDOG_USEC="USEC_FMT, watchdog_timer);
1544
1545 if (arg_watchdog_device)
1546 (void) strv_extendf(&env_block, "WATCHDOG_DEVICE=%s", arg_watchdog_device);
1547
1548 /* Avoid the creation of new processes forked by the kernel; at this
1549 * point, we will not listen to the signals anyway */
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
1557 static void initialize_clock(void) {
1558 int r;
1559
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
1563 if (clock_is_localtime(NULL) > 0) {
1564 int min;
1565
1566 /* The very first call of settimeofday() also does a time warp in the kernel.
1567 *
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.
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
1578 } else if (!in_initrd())
1579 /*
1580 * Do a dummy very first call to seal the kernel's time warp magic.
1581 *
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.
1585 *
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.
1589 */
1590 (void) clock_reset_timewarp();
1591
1592 ClockChangeDirection change_dir;
1593 r = clock_apply_epoch(&change_dir);
1594 if (r > 0 && change_dir == CLOCK_CHANGE_FORWARD)
1595 log_info("System time before build time, advancing clock.");
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));
1604 }
1605
1606 static void apply_clock_update(void) {
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
1613 if (getpid_cached() != 1)
1614 return;
1615
1616 if (clock_settime(CLOCK_REALTIME, TIMESPEC_STORE(arg_clock_usec)) < 0)
1617 log_error_errno(errno, "Failed to set system clock to time specified on kernel command line: %m");
1618 else
1619 log_info("Set system clock to %s, as specified on the kernel command line.",
1620 FORMAT_TIMESTAMP(arg_clock_usec));
1621 }
1622
1623 static void cmdline_take_random_seed(void) {
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
1640 r = random_write_entropy(-1, arg_random_seed, arg_random_seed_size, true);
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"
1647 "Note that the seed provided this way is accessible to unprivileged programs. "
1648 "This functionality should not be used outside of testing environments.");
1649 }
1650
1651 static void initialize_coredump(bool skip_setup) {
1652 #if ENABLE_COREDUMP
1653 if (getpid_cached() != 1)
1654 return;
1655
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. */
1658 if (setrlimit(RLIMIT_CORE, &RLIMIT_MAKE_CONST(RLIM_INFINITY)) < 0)
1659 log_warning_errno(errno, "Failed to set RLIMIT_CORE: %m");
1660
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
1663 * command line later so core dumps can still be generated during early startup and in initrd. */
1664 if (!skip_setup)
1665 disable_coredumps();
1666 #endif
1667 }
1668
1669 static 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
1678 r = write_string_file("/proc/sys/kernel/core_pattern", arg_early_core_pattern, WRITE_STRING_FILE_DISABLE_BUFFER);
1679 if (r < 0)
1680 log_warning_errno(r, "Failed to write '%s' to /proc/sys/kernel/core_pattern, ignoring: %m",
1681 arg_early_core_pattern);
1682 }
1683
1684 static 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
1692 mask = cpu_set_to_range_string(&arg_cpu_affinity);
1693 log_debug("Setting CPU affinity to {%s}.", strnull(mask));
1694
1695 if (sched_setaffinity(0, arg_cpu_affinity.allocated, arg_cpu_affinity.set) < 0)
1696 log_warning_errno(errno, "Failed to set CPU affinity, ignoring: %m");
1697 }
1698
1699 static 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);
1710 log_debug("Setting NUMA policy to %s, with nodes {%s}.", strnull(policy), strnull(nodes));
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)
1717 log_warning_errno(r, "Failed to set NUMA memory policy, ignoring: %m");
1718 }
1719
1720 static void filter_args(
1721 const char* dst[],
1722 size_t *dst_index,
1723 char **src,
1724 int argc) {
1725
1726 assert(dst);
1727 assert(dst_index);
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
1753 /* Seems we have a good old option. Let's pass it over to the new instance. */
1754 dst[(*dst_index)++] = src[i];
1755 }
1756 }
1757
1758 static int do_reexecute(
1759 ManagerObjective objective,
1760 int argc,
1761 char* argv[],
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
1769 size_t i, args_size;
1770 const char **args;
1771 int r;
1772
1773 assert(IN_SET(objective, MANAGER_REEXECUTE, MANAGER_SWITCH_ROOT));
1774 assert(argc >= 0);
1775 assert(saved_rlimit_nofile);
1776 assert(saved_rlimit_memlock);
1777 assert(ret_error_message);
1778
1779 /* Close and disarm the watchdog, so that the new instance can reinitialize it, but doesn't get
1780 * rebooted while we do that */
1781 watchdog_close(true);
1782
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)
1786 (void) setrlimit(RLIMIT_NOFILE, saved_rlimit_nofile);
1787 if (saved_rlimit_memlock->rlim_cur != RLIM_INFINITY)
1788 (void) setrlimit(RLIMIT_MEMLOCK, saved_rlimit_memlock);
1789
1790 if (switch_root_dir) {
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. */
1793 broadcast_signal(SIGTERM, false, true, arg_default_timeout_stop_usec);
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
1801 args_size = argc + 6;
1802 args = newa(const char*, args_size);
1803
1804 if (!switch_root_init) {
1805 char sfd[DECIMAL_STR_MAX(int)];
1806
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. */
1809
1810 assert(arg_serialization);
1811 assert(fds);
1812
1813 xsprintf(sfd, "%i", fileno(arg_serialization));
1814
1815 i = 1; /* Leave args[0] empty for now. */
1816 filter_args(args, &i, argv, argc);
1817
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 /*
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().
1832 */
1833 valgrind_summary_hack();
1834
1835 args[0] = SYSTEMD_BINARY_PATH;
1836 (void) execv(args[0], (char* const*) args);
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
1843 log_debug_errno(errno, "Failed to execute our own binary %s, trying fallback: %m", args[0]);
1844 }
1845
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.) */
1849
1850 arg_serialization = safe_fclose(arg_serialization);
1851 fds = fdset_free(fds);
1852
1853 /* Reopen the console */
1854 (void) make_console_stdio();
1855
1856 i = 1; /* Leave args[0] empty for now. */
1857 for (int j = 1; j <= argc; j++)
1858 args[i++] = argv[j];
1859 assert(i <= args_size);
1860
1861 /* Re-enable any blocked signals, especially important if we switch from initrd to init=... */
1862 (void) reset_all_signal_handlers();
1863 (void) reset_signal_mask();
1864 (void) rlimit_nofile_safe();
1865
1866 if (switch_root_init) {
1867 args[0] = switch_root_init;
1868 (void) execve(args[0], (char* const*) args, saved_env);
1869 log_warning_errno(errno, "Failed to execute configured init %s, trying fallback: %m", args[0]);
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
1880 *ret_error_message = "Failed to execute fallback shell";
1881 if (r == -ENOENT) {
1882 log_warning("No /sbin/init, trying fallback");
1883
1884 args[0] = "/bin/sh";
1885 args[1] = NULL;
1886 (void) execve(args[0], (char* const*) args, saved_env);
1887 return log_error_errno(errno, "Failed to execute /bin/sh, giving up: %m");
1888 } else
1889 return log_error_errno(r, "Failed to execute /sbin/init, giving up: %m");
1890 }
1891
1892 static int invoke_main_loop(
1893 Manager *m,
1894 const struct rlimit *saved_rlimit_nofile,
1895 const struct rlimit *saved_rlimit_memlock,
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);
1906 assert(saved_rlimit_nofile);
1907 assert(saved_rlimit_memlock);
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 (;;) {
1916 int objective = manager_loop(m);
1917 if (objective < 0) {
1918 *ret_error_message = "Failed to run main loop";
1919 return log_emergency_errno(objective, "Failed to run main loop: %m");
1920 }
1921
1922 switch (objective) {
1923
1924 case MANAGER_RELOAD: {
1925 LogTarget saved_log_target;
1926 int saved_log_level;
1927
1928 log_info("Reloading.");
1929
1930 /* First, save any overridden log level/target, then parse the configuration file,
1931 * which might change the log level to new settings. */
1932
1933 saved_log_level = m->log_level_overridden ? log_get_max_level() : -1;
1934 saved_log_target = m->log_target_overridden ? log_get_target() : _LOG_TARGET_INVALID;
1935
1936 (void) parse_configuration(saved_rlimit_nofile, saved_rlimit_memlock);
1937
1938 set_manager_defaults(m);
1939 set_manager_settings(m);
1940
1941 update_cpu_affinity(false);
1942 update_numa_policy(false);
1943
1944 if (saved_log_level >= 0)
1945 manager_override_log_level(m, saved_log_level);
1946 if (saved_log_target >= 0)
1947 manager_override_log_target(m, saved_log_target);
1948
1949 if (manager_reload(m) < 0)
1950 /* Reloading failed before the point of no return.
1951 * Let's continue running as if nothing happened. */
1952 m->objective = MANAGER_OK;
1953
1954 continue;
1955 }
1956
1957 case MANAGER_REEXECUTE:
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
1966 *ret_retval = EXIT_SUCCESS;
1967 *ret_shutdown_verb = NULL;
1968 *ret_switch_root_dir = *ret_switch_root_init = NULL;
1969
1970 return objective;
1971
1972 case MANAGER_SWITCH_ROOT:
1973 manager_set_switching_root(m, true);
1974
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
1986 *ret_retval = EXIT_SUCCESS;
1987 *ret_shutdown_verb = NULL;
1988
1989 /* Steal the switch root parameters */
1990 *ret_switch_root_dir = TAKE_PTR(m->switch_root);
1991 *ret_switch_root_init = TAKE_PTR(m->switch_root_init);
1992
1993 return objective;
1994
1995 case MANAGER_EXIT:
1996 if (MANAGER_IS_USER(m)) {
1997 log_debug("Exit.");
1998
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
2004 return objective;
2005 }
2006
2007 _fallthrough_;
2008 case MANAGER_REBOOT:
2009 case MANAGER_POWEROFF:
2010 case MANAGER_HALT:
2011 case MANAGER_KEXEC: {
2012 static const char* const table[_MANAGER_OBJECTIVE_MAX] = {
2013 [MANAGER_EXIT] = "exit",
2014 [MANAGER_REBOOT] = "reboot",
2015 [MANAGER_POWEROFF] = "poweroff",
2016 [MANAGER_HALT] = "halt",
2017 [MANAGER_KEXEC] = "kexec",
2018 };
2019
2020 log_notice("Shutting down.");
2021
2022 *ret_retval = m->return_value;
2023 assert_se(*ret_shutdown_verb = table[m->objective]);
2024 *ret_fds = NULL;
2025 *ret_switch_root_dir = *ret_switch_root_init = NULL;
2026
2027 return objective;
2028 }
2029
2030 default:
2031 assert_not_reached();
2032 }
2033 }
2034 }
2035
2036 static void log_execution_mode(bool *ret_first_boot) {
2037 assert(ret_first_boot);
2038
2039 if (arg_system) {
2040 struct utsname uts;
2041 int v;
2042
2043 log_info("systemd " GIT_VERSION " running in %ssystem mode (%s)",
2044 arg_action == ACTION_TEST ? "test " : "",
2045 systemd_features);
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 initrd.");
2056 } else {
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 }
2077 }
2078
2079 assert_se(uname(&uts) >= 0);
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);
2086 } else {
2087 if (DEBUG_LOGGING) {
2088 _cleanup_free_ char *t = NULL;
2089
2090 t = uid_to_name(getuid());
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);
2094 }
2095
2096 *ret_first_boot = false;
2097 }
2098 }
2099
2100 static int initialize_runtime(
2101 bool skip_setup,
2102 bool first_boot,
2103 struct rlimit *saved_rlimit_nofile,
2104 struct rlimit *saved_rlimit_memlock,
2105 const char **ret_error_message) {
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
2117 if (arg_action != ACTION_RUN)
2118 return 0;
2119
2120 update_cpu_affinity(skip_setup);
2121 update_numa_policy(skip_setup);
2122
2123 if (arg_system) {
2124 /* Make sure we leave a core dump without panicking the kernel. */
2125 install_crash_handler();
2126
2127 if (!skip_setup) {
2128 r = mount_cgroup_controllers();
2129 if (r < 0) {
2130 *ret_error_message = "Failed to mount cgroup hierarchies";
2131 return r;
2132 }
2133
2134 (void) os_release_status();
2135 (void) hostname_setup(true);
2136 /* Force transient machine-id on first boot. */
2137 machine_id_setup(NULL, first_boot, arg_machine_id, NULL);
2138 (void) loopback_setup();
2139 bump_unix_max_dgram_qlen();
2140 bump_file_max_and_nr_open();
2141 test_usr();
2142 write_container_id();
2143 }
2144
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);
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
2160 (void) mkdir_p_label(p, 0755);
2161 (void) make_inaccessible_nodes(p, UID_INVALID, GID_INVALID);
2162 }
2163
2164 if (arg_timer_slack_nsec != NSEC_INFINITY)
2165 if (prctl(PR_SET_TIMERSLACK, arg_timer_slack_nsec) < 0)
2166 log_warning_errno(errno, "Failed to adjust timer slack, ignoring: %m");
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
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
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)
2200 log_warning_errno(errno, "Failed to make us a subreaper, ignoring: %m");
2201
2202 /* Bump up RLIMIT_NOFILE for systemd itself */
2203 (void) bump_rlimit_nofile(saved_rlimit_nofile);
2204 (void) bump_rlimit_memlock(saved_rlimit_memlock);
2205
2206 /* Pull credentials from various sources into a common credential directory */
2207 if (arg_system && !skip_setup)
2208 (void) import_credentials();
2209
2210 return 0;
2211 }
2212
2213 static 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;
2218 const char *unit;
2219 Job *job;
2220 Unit *target;
2221 int r;
2222
2223 if (arg_default_unit)
2224 unit = arg_default_unit;
2225 else if (in_initrd())
2226 unit = SPECIAL_INITRD_TARGET;
2227 else
2228 unit = SPECIAL_DEFAULT_TARGET;
2229
2230 log_debug("Activating default unit: %s", unit);
2231
2232 r = manager_load_startable_unit_or_warn(m, unit, NULL, &target);
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 ".");
2238
2239 r = manager_load_startable_unit_or_warn(m, SPECIAL_DEFAULT_TARGET, NULL, &target);
2240 }
2241 if (r < 0) {
2242 log_info("Falling back to " SPECIAL_RESCUE_TARGET ".");
2243
2244 r = manager_load_startable_unit_or_warn(m, SPECIAL_RESCUE_TARGET, NULL, &target);
2245 if (r < 0) {
2246 *ret_error_message = r == -ERFKILL ? SPECIAL_RESCUE_TARGET " masked"
2247 : "Failed to load " SPECIAL_RESCUE_TARGET;
2248 return r;
2249 }
2250 }
2251
2252 assert(target->load_state == UNIT_LOADED);
2253
2254 r = manager_add_job(m, JOB_START, target, JOB_ISOLATE, NULL, &error, &job);
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
2260 r = manager_add_job(m, JOB_START, target, JOB_REPLACE, NULL, &error, &job);
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));
2269 } else
2270 log_info("Queued %s job for default target %s.",
2271 job_type_to_string(job->type),
2272 unit_status_string(job->unit, NULL));
2273
2274 m->default_unit_job_id = job->id;
2275
2276 return 0;
2277 }
2278
2279 static 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
2292 static 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
2336 static 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
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
2357 arg_default_rlimit[RLIMIT_MEMLOCK] = rl;
2358 }
2359
2360 static void setenv_manager_environment(void) {
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
2372 static void reset_arguments(void) {
2373 /* Frees/resets arg_* variables, with a few exceptions commented below. */
2374
2375 arg_default_unit = mfree(arg_default_unit);
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;
2383 arg_confirm_spawn = mfree(arg_confirm_spawn);
2384 arg_show_status = _SHOW_STATUS_INVALID;
2385 arg_status_unit_format = STATUS_UNIT_FORMAT_DEFAULT;
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;
2396 arg_default_device_timeout_usec = DEFAULT_TIMEOUT_USEC;
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;
2400 arg_reboot_watchdog = 10 * USEC_PER_MINUTE;
2401 arg_kexec_watchdog = 0;
2402 arg_pretimeout_watchdog = 0;
2403 arg_early_core_pattern = mfree(arg_early_core_pattern);
2404 arg_watchdog_device = mfree(arg_watchdog_device);
2405 arg_watchdog_pretimeout_governor = mfree(arg_watchdog_pretimeout_governor);
2406
2407 arg_default_environment = strv_free(arg_default_environment);
2408 arg_manager_environment = strv_free(arg_manager_environment);
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
2416 arg_syscall_archs = set_free(arg_syscall_archs);
2417
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;
2426 arg_default_tasks_max = DEFAULT_TASKS_MAX;
2427 arg_machine_id = (sd_id128_t) {};
2428 arg_cad_burst_action = EMERGENCY_ACTION_REBOOT_FORCE;
2429 arg_default_oom_policy = OOM_STOP;
2430
2431 cpu_set_reset(&arg_cpu_affinity);
2432 numa_policy_reset(&arg_numa_policy);
2433
2434 arg_random_seed = mfree(arg_random_seed);
2435 arg_random_seed_size = 0;
2436 arg_clock_usec = 0;
2437
2438 arg_default_oom_score_adjust_set = false;
2439 arg_default_smack_process_label = mfree(arg_default_smack_process_label);
2440 }
2441
2442 static 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;
2467 }
2468
2469 static int parse_configuration(const struct rlimit *saved_rlimit_nofile,
2470 const struct rlimit *saved_rlimit_memlock) {
2471 int r;
2472
2473 assert(saved_rlimit_nofile);
2474 assert(saved_rlimit_memlock);
2475
2476 /* Assign configuration defaults */
2477 reset_arguments();
2478
2479 r = parse_config_file();
2480 if (r < 0)
2481 log_warning_errno(r, "Failed to parse config file, ignoring: %m");
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
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
2493 /* Note that this also parses bits from the kernel command line, including "debug". */
2494 log_parse_environment();
2495
2496 /* Initialize the show status setting if it hasn't been set explicitly yet */
2497 if (arg_show_status == _SHOW_STATUS_INVALID)
2498 arg_show_status = SHOW_STATUS_YES;
2499
2500 /* Slightly raise the OOM score for our services if we are running for unprivileged users. */
2501 determine_default_oom_score_adjust();
2502
2503 /* Push variables into the manager environment block */
2504 setenv_manager_environment();
2505
2506 /* Parse log environment variables again to take into account any new environment variables. */
2507 log_parse_environment();
2508
2509 return 0;
2510 }
2511
2512 static int safety_checks(void) {
2513
2514 if (getpid_cached() == 1 &&
2515 arg_action != ACTION_RUN)
2516 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2517 "Unsupported execution mode while PID 1.");
2518
2519 if (getpid_cached() == 1 &&
2520 !arg_system)
2521 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2522 "Can't run --user mode as PID 1.");
2523
2524 if (arg_action == ACTION_RUN &&
2525 arg_system &&
2526 getpid_cached() != 1)
2527 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2528 "Can't run system mode unless PID 1.");
2529
2530 if (arg_action == ACTION_TEST &&
2531 geteuid() == 0)
2532 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2533 "Don't run test mode as root.");
2534
2535 if (!arg_system &&
2536 arg_action == ACTION_RUN &&
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.");
2540
2541 if (!arg_system &&
2542 arg_action == ACTION_RUN &&
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.");
2546
2547 if (arg_system &&
2548 arg_action == ACTION_RUN &&
2549 running_in_chroot() > 0)
2550 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2551 "Cannot be run in a chroot() environment.");
2552
2553 return 0;
2554 }
2555
2556 static 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
2571 r = mac_selinux_setup(loaded_policy);
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
2583 r = mac_apparmor_setup();
2584 if (r < 0) {
2585 *ret_error_message = "Failed to load AppArmor policy";
2586 return r;
2587 }
2588
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
2599 static 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
2619 static 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
2627 /* If we are init, we connect stdin/stdout/stderr to /dev/null and make sure we don't have a
2628 * controlling tty. */
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
2636 static bool early_skip_setup_check(int argc, char *argv[]) {
2637 bool found_deserialize = false;
2638
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. */
2642
2643 for (int i = 1; i < argc; i++)
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;
2648
2649 return found_deserialize; /* When we are deserializing, then we are reexecuting, hence avoid the extensive setup */
2650 }
2651
2652 static 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
2663 int main(int argc, char *argv[]) {
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;
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! */
2675 bool skip_setup, loaded_policy = false, queue_default_job = false, first_boot = false;
2676 char *switch_root_dir = NULL, *switch_root_init = NULL;
2677 usec_t before_startup, after_startup;
2678 static char systemd[] = "systemd";
2679 const char *shutdown_verb = NULL, *error_message = NULL;
2680 int r, retval = EXIT_FAILURE;
2681 Manager *m = NULL;
2682 FDSet *fds = NULL;
2683
2684 assert_se(argc > 0 && !isempty(argv[0]));
2685
2686 /* SysV compatibility: redirect init → telinit */
2687 redirect_telinit(argc, argv);
2688
2689 /* Take timestamps early on */
2690 dual_timestamp_from_monotonic(&kernel_timestamp, 0);
2691 dual_timestamp_get(&userspace_timestamp);
2692
2693 /* Figure out whether we need to do initialize the system, or if we already did that because we are
2694 * reexecuting. */
2695 skip_setup = early_skip_setup_check(argc, argv);
2696
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. */
2700 program_invocation_short_name = systemd;
2701 (void) prctl(PR_SET_NAME, systemd);
2702
2703 /* Save the original command line */
2704 save_argc_argv(argc, argv);
2705
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 }
2713
2714 /* Make sure that if the user says "syslog" we actually log to the journal. */
2715 log_set_upgrade_syslog_to_journal(true);
2716
2717 if (getpid_cached() == 1) {
2718 /* When we run as PID 1 force system mode */
2719 arg_system = true;
2720
2721 /* Disable the umask logic */
2722 umask(0);
2723
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). */
2726 log_set_prohibit_ipc(true);
2727
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. */
2732 log_set_always_reopen_console(true);
2733
2734 if (detect_container() <= 0) {
2735
2736 /* Running outside of a container as PID 1 */
2737 log_set_target(LOG_TARGET_KMSG);
2738 log_open();
2739
2740 if (in_initrd())
2741 initrd_timestamp = userspace_timestamp;
2742
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
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
2755 disable_printk_ratelimit();
2756
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;
2764 }
2765
2766 if (mac_selinux_init() < 0) {
2767 error_message = "Failed to initialize SELinux support";
2768 goto finish;
2769 }
2770
2771 if (!skip_setup)
2772 initialize_clock();
2773
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. */
2778 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
2779
2780 } else {
2781 /* Running inside a container, as PID 1 */
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
2788 /* clear the kernel timestamp, because we are in a container */
2789 kernel_timestamp = DUAL_TIMESTAMP_NULL;
2790 }
2791
2792 initialize_coredump(skip_setup);
2793
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 }
2800
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. */
2803 log_show_color(colors_enabled());
2804
2805 r = make_null_stdio();
2806 if (r < 0)
2807 log_warning_errno(r, "Failed to redirect standard streams to /dev/null, ignoring: %m");
2808
2809 /* Load the kernel modules early. */
2810 if (!skip_setup)
2811 (void) kmod_setup();
2812
2813 /* Mount /proc, /sys and friends, so that /proc/cmdline and /proc/$PID/fd is available. */
2814 r = mount_setup(loaded_policy, skip_setup);
2815 if (r < 0) {
2816 error_message = "Failed to mount API filesystems";
2817 goto finish;
2818 }
2819
2820 /* The efivarfs is now mounted, let's read the random seed off it */
2821 (void) efi_take_random_seed();
2822
2823 /* Cache command-line options passed from EFI variables */
2824 if (!skip_setup)
2825 (void) cache_efi_options_variable();
2826 } else {
2827 /* Running as user instance */
2828 arg_system = false;
2829 log_set_always_reopen_console(true);
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
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
2841 if (mac_selinux_init() < 0) {
2842 error_message = "Failed to initialize SELinux support";
2843 goto finish;
2844 }
2845 }
2846
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
2851 /* Reset all signal handlers. */
2852 (void) reset_all_signal_handlers();
2853 (void) ignore_signals(SIGNALS_IGNORE);
2854
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";
2860 goto finish;
2861 }
2862
2863 r = safety_checks();
2864 if (r < 0)
2865 goto finish;
2866
2867 if (IN_SET(arg_action, ACTION_TEST, ACTION_HELP, ACTION_DUMP_CONFIGURATION_ITEMS, ACTION_DUMP_BUS_PROPERTIES, ACTION_BUS_INTROSPECT))
2868 pager_open(arg_pager_flags);
2869
2870 if (arg_action != ACTION_RUN)
2871 skip_setup = true;
2872
2873 if (arg_action == ACTION_HELP) {
2874 retval = help() < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
2875 goto finish;
2876 } else if (arg_action == ACTION_VERSION) {
2877 retval = version();
2878 goto finish;
2879 } else if (arg_action == ACTION_DUMP_CONFIGURATION_ITEMS) {
2880 unit_dump_config_items(stdout);
2881 retval = EXIT_SUCCESS;
2882 goto finish;
2883 } else if (arg_action == ACTION_DUMP_BUS_PROPERTIES) {
2884 dump_bus_properties(stdout);
2885 retval = EXIT_SUCCESS;
2886 goto finish;
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;
2891 }
2892
2893 assert_se(IN_SET(arg_action, ACTION_RUN, ACTION_TEST));
2894
2895 /* Move out of the way, so that we won't block unmounts */
2896 assert_se(chdir("/") == 0);
2897
2898 if (arg_action == ACTION_RUN) {
2899 if (!skip_setup) {
2900 /* Apply the systemd.clock_usec= kernel command line switch */
2901 apply_clock_update();
2902
2903 /* Apply random seed from kernel command line */
2904 cmdline_take_random_seed();
2905 }
2906
2907 /* A core pattern might have been specified via the cmdline. */
2908 initialize_core_pattern(skip_setup);
2909
2910 /* Close logging fds, in order not to confuse collecting passed fds and terminal logic below */
2911 log_close();
2912
2913 /* Remember open file descriptors for later deserialization */
2914 r = collect_fds(&fds, &error_message);
2915 if (r < 0)
2916 goto finish;
2917
2918 /* Give up any control of the console, but make sure its initialized. */
2919 setup_console_terminal(skip_setup);
2920
2921 /* Open the logging devices, if possible and necessary */
2922 log_open();
2923 }
2924
2925 log_execution_mode(&first_boot);
2926
2927 r = initialize_runtime(skip_setup,
2928 first_boot,
2929 &saved_rlimit_nofile,
2930 &saved_rlimit_memlock,
2931 &error_message);
2932 if (r < 0)
2933 goto finish;
2934
2935 r = manager_new(arg_system ? LOOKUP_SCOPE_SYSTEM : LOOKUP_SCOPE_USER,
2936 arg_action == ACTION_TEST ? MANAGER_TEST_FULL : 0,
2937 &m);
2938 if (r < 0) {
2939 log_emergency_errno(r, "Failed to allocate manager object: %m");
2940 error_message = "Failed to allocate manager object";
2941 goto finish;
2942 }
2943
2944 m->timestamps[MANAGER_TIMESTAMP_KERNEL] = kernel_timestamp;
2945 m->timestamps[MANAGER_TIMESTAMP_INITRD] = initrd_timestamp;
2946 m->timestamps[MANAGER_TIMESTAMP_USERSPACE] = userspace_timestamp;
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;
2949
2950 set_manager_defaults(m);
2951 set_manager_settings(m);
2952 manager_set_first_boot(m, first_boot);
2953 manager_set_switching_root(m, arg_switched_root);
2954
2955 /* Remember whether we should queue the default job */
2956 queue_default_job = !arg_serialization || arg_switched_root;
2957
2958 before_startup = now(CLOCK_MONOTONIC);
2959
2960 r = manager_startup(m, arg_serialization, fds, /* root= */ NULL);
2961 if (r < 0) {
2962 error_message = "Failed to start up manager";
2963 goto finish;
2964 }
2965
2966 /* This will close all file descriptors that were opened, but not claimed by any unit. */
2967 fds = fdset_free(fds);
2968 arg_serialization = safe_fclose(arg_serialization);
2969
2970 if (queue_default_job) {
2971 r = do_queue_default_job(m, &error_message);
2972 if (r < 0)
2973 goto finish;
2974 }
2975
2976 after_startup = now(CLOCK_MONOTONIC);
2977
2978 log_full(arg_action == ACTION_TEST ? LOG_INFO : LOG_DEBUG,
2979 "Loaded units and determined initial transaction in %s.",
2980 FORMAT_TIMESPAN(after_startup - before_startup, 100 * USEC_PER_MSEC));
2981
2982 if (arg_action == ACTION_TEST) {
2983 manager_test_summary(m);
2984 retval = EXIT_SUCCESS;
2985 goto finish;
2986 }
2987
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));
3005
3006 finish:
3007 pager_close();
3008
3009 if (m) {
3010 arg_reboot_watchdog = manager_get_watchdog(m, WATCHDOG_REBOOT);
3011 arg_kexec_watchdog = manager_get_watchdog(m, WATCHDOG_KEXEC);
3012 m = manager_free(m);
3013 }
3014
3015 mac_selinux_finish();
3016
3017 if (IN_SET(r, MANAGER_REEXECUTE, MANAGER_SWITCH_ROOT))
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 */
3026
3027 arg_serialization = safe_fclose(arg_serialization);
3028 fds = fdset_free(fds);
3029
3030 saved_env = strv_free(saved_env);
3031
3032 #if HAVE_VALGRIND_VALGRIND_H
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. */
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();
3041 reset_arguments();
3042 return retval;
3043 }
3044 #endif
3045
3046 #if HAS_FEATURE_ADDRESS_SANITIZER
3047 __lsan_do_leak_check();
3048 #endif
3049
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) {
3053 r = become_shutdown(shutdown_verb, retval);
3054 log_error_errno(r, "Failed to execute shutdown binary, %s: %m", getpid_cached() == 1 ? "freezing" : "quitting");
3055 error_message = "Failed to execute shutdown binary";
3056 }
3057
3058 watchdog_free_device();
3059 arg_watchdog_device = mfree(arg_watchdog_device);
3060
3061 if (getpid_cached() == 1) {
3062 if (error_message)
3063 manager_status_printf(NULL, STATUS_TYPE_EMERGENCY,
3064 ANSI_HIGHLIGHT_RED "!!!!!!" ANSI_NORMAL,
3065 "%s.", error_message);
3066 freeze_or_exit_or_reboot();
3067 }
3068
3069 reset_arguments();
3070 return retval;
3071 }