HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/core/main.c
Git blob: 7887e0f02d9696e736ccfb06986d5d50dcb1cfc6
Lines 3001–4000 of 4,044
arg_reboot_watchdog = 10 * USEC_PER_MINUTE;
arg_kexec_watchdog = 0;
arg_pretimeout_watchdog = 0;
arg_early_core_pattern = mfree(arg_early_core_pattern);
arg_watchdog_device = mfree(arg_watchdog_device);
arg_watchdog_pretimeout_governor = mfree(arg_watchdog_pretimeout_governor);
arg_default_environment = strv_free(arg_default_environment);
arg_manager_environment = strv_free(arg_manager_environment);
arg_capability_bounding_set = CAP_MASK_ALL;
arg_no_new_privs = false;
arg_protect_system = -1;
arg_restrict_filesystem_access = RESTRICT_FILESYSTEM_ACCESS_NO;
arg_timer_slack_nsec = NSEC_INFINITY;
arg_syscall_archs = set_free(arg_syscall_archs);
/* arg_serialization — ignore */
arg_machine_id = (sd_id128_t) {};
arg_cad_burst_action = EMERGENCY_ACTION_REBOOT_FORCE;
cpu_set_done(&arg_cpu_affinity);
numa_policy_reset(&arg_numa_policy);
arg_random_seed = mfree(arg_random_seed);
arg_random_seed_size = 0;
arg_clock_usec = 0;
arg_reload_limit_interval_sec = 0;
arg_reload_limit_burst = 0;
arg_event_loop_ratelimit_interval_sec = 1 * USEC_PER_SEC;
arg_event_loop_ratelimit_burst = 50000;
arg_minimum_uptime_usec = USEC_INFINITY;
}
static void determine_default_oom_score_adjust(void) {
int r, a, b;
/* Run our services at slightly higher OOM score than ourselves. But let's be conservative here, and
* do this only if we don't run as root (i.e. only if we are run in user mode, for an unprivileged
* user). */
if (arg_defaults.oom_score_adjust_set)
return;
if (getuid() == 0)
return;
r = get_oom_score_adjust(&a);
if (r < 0)
return (void) log_warning_errno(r, "Failed to determine current OOM score adjustment value, ignoring: %m");
assert_cc(100 <= OOM_SCORE_ADJ_MAX);
b = saturate_add(a, 100, OOM_SCORE_ADJ_MAX);
if (a == b)
return;
arg_defaults.oom_score_adjust = b;
arg_defaults.oom_score_adjust_set = true;
}
static int parse_configuration(const struct rlimit *saved_rlimit_nofile,
const struct rlimit *saved_rlimit_memlock) {
int r;
assert(saved_rlimit_nofile);
assert(saved_rlimit_memlock);
/* Assign configuration defaults */
reset_arguments();
r = parse_config_file();
if (r < 0)
log_warning_errno(r, "Failed to parse config file, ignoring: %m");
if (arg_runtime_scope == RUNTIME_SCOPE_SYSTEM) {
r = proc_cmdline_parse(parse_proc_cmdline_item, NULL, 0);
if (r < 0)
log_warning_errno(r, "Failed to parse kernel command line, ignoring: %m");
}
/* Initialize the show status setting if it hasn't been explicitly set yet */
if (arg_show_status == _SHOW_STATUS_INVALID)
arg_show_status = SHOW_STATUS_YES;
/* Push variables into the manager environment block */
setenv_manager_environment();
/* Parse log environment variables to take into account any new environment variables.
* Note that this also parses bits from the kernel command line, including "debug". */
log_parse_environment();
/* Initialize some default rlimits for services if they haven't been configured */
fallback_rlimit_nofile(saved_rlimit_nofile);
fallback_rlimit_memlock(saved_rlimit_memlock);
/* Slightly raise the OOM score for our services if we are running for unprivileged users. */
determine_default_oom_score_adjust();
return 0;
}
static int safety_checks(void) {
if (getpid_cached() == 1 &&
arg_action != ACTION_RUN)
return log_error_errno(SYNTHETIC_ERRNO(EPERM),
"Unsupported execution mode while PID 1.");
if (getpid_cached() == 1 &&
arg_runtime_scope == RUNTIME_SCOPE_USER)
return log_error_errno(SYNTHETIC_ERRNO(EPERM),
"Can't run --user mode as PID 1.");
if (arg_action == ACTION_RUN &&
arg_runtime_scope == RUNTIME_SCOPE_SYSTEM &&
getpid_cached() != 1)
return log_error_errno(SYNTHETIC_ERRNO(EPERM),
"Can't run system mode unless PID 1.");
if (arg_action == ACTION_TEST &&
geteuid() == 0)
return log_error_errno(SYNTHETIC_ERRNO(EPERM),
"Don't run test mode as root.");
switch (arg_runtime_scope) {
case RUNTIME_SCOPE_USER:
if (arg_action == ACTION_RUN &&
sd_booted() <= 0)
return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
"Trying to run as user instance, but the system has not been booted with systemd.");
if (arg_action == ACTION_RUN &&
!getenv("XDG_RUNTIME_DIR"))
return log_error_errno(SYNTHETIC_ERRNO(EUNATCH),
"Trying to run as user instance, but $XDG_RUNTIME_DIR is not set.");
break;
case RUNTIME_SCOPE_SYSTEM:
if (arg_action == ACTION_RUN &&
running_in_chroot() > 0)
return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
"Cannot be run in a chroot() environment.");
break;
default:
assert_not_reached();
}
return 0;
}
static int initialize_security(
bool *loaded_policy,
dual_timestamp *security_start_timestamp,
dual_timestamp *security_finish_timestamp,
const char **ret_error_message) {
int r;
assert(loaded_policy);
assert(security_start_timestamp);
assert(security_finish_timestamp);
assert(ret_error_message);
dual_timestamp_now(security_start_timestamp);
r = mac_selinux_setup(loaded_policy);
if (r < 0) {
*ret_error_message = "Failed to load SELinux policy";
return r;
}
r = mac_smack_setup(loaded_policy);
if (r < 0) {
*ret_error_message = "Failed to load SMACK policy";
return r;
}
r = mac_apparmor_setup();
if (r < 0) {
*ret_error_message = "Failed to load AppArmor policy";
return r;
}
r = ima_setup();
if (r < 0) {
*ret_error_message = "Failed to load IMA policy";
return r;
}
r = ipe_setup();
if (r < 0) {
*ret_error_message = "Failed to load IPE policy";
return r;
}
dual_timestamp_now(security_finish_timestamp);
return 0;
}
static int parse_listen_fds_env(unsigned *ret_n_fds, char ***ret_names) {
_cleanup_strv_free_ char **names = NULL;
const char *e;
unsigned n_fds;
int r;
assert(ret_n_fds);
assert(ret_names);
/* Parse and validate the LISTEN_PID=/LISTEN_PIDFDID=/LISTEN_FDS=/LISTEN_FDNAMES= environment
* variables. */
e = secure_getenv("LISTEN_PID");
if (!e)
return -ENXIO;
pid_t pid;
r = parse_pid(e, &pid);
if (r < 0)
return log_debug_errno(r, "Failed to parse LISTEN_PID=%s: %m", e);
if (pid != getpid_cached())
return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
"LISTEN_PID=%s does not match our own PID " PID_FMT ", ignoring.",
e,
getpid_cached());
e = secure_getenv("LISTEN_PIDFDID");
if (e) {
uint64_t own_pidfdid, pidfdid;
r = safe_atou64(e, &pidfdid);
if (r < 0)
return log_debug_errno(r, "Failed to parse LISTEN_PIDFDID=%s: %m", e);
if (pidfd_get_inode_id_self_cached(&own_pidfdid) >= 0 && pidfdid != own_pidfdid)
return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
"LISTEN_PIDFDID=%s does not match our own pidfdid %" PRIu64 ", ignoring.",
e,
own_pidfdid);
}
e = secure_getenv("LISTEN_FDS");
if (!e)
return -ENXIO;
r = safe_atou(e, &n_fds);
if (r < 0)
return log_debug_errno(r, "Failed to parse LISTEN_FDS= value '%s': %m", e);
if (n_fds == 0)
return -ENXIO;
if (n_fds > INT_MAX - SD_LISTEN_FDS_START)
return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid number of fds in LISTEN_FDS= value '%s'", e);
e = secure_getenv("LISTEN_FDNAMES");
if (!e)
return -ENXIO;
r = strv_split_full(&names, e, ":", EXTRACT_DONT_COALESCE_SEPARATORS);
if (r < 0)
return log_debug_errno(r, "Failed to parse LISTEN_FDNAMES=%s: %m", e);
if (strv_length(names) != (size_t) n_fds)
return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
"Mismatch between number of LISTEN_FDS= and LISTEN_FDNAMES= entries: %u vs %zu",
n_fds, strv_length(names));
*ret_n_fds = n_fds;
*ret_names = TAKE_PTR(names);
return 0;
}
DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(
index_to_tag_hash_ops,
uint64_t, uint64_hash_func, uint64_compare_func,
ListenFDsTag, listen_fds_tag_free);
static int parse_listen_fds_mapping(int mapping_fd, Hashmap **ret_index_to_tag) {
int r;
assert(mapping_fd >= 0);
assert(ret_index_to_tag);
/* Parse the JSON mapping memfd that the downstream manager pushed alongside the indexed fds:
* { "unit-name.service": [ { "name": "fdname1", "index": 1 }, ... ], ... }
* Returns a hashmap keyed by stringified index ("1", "2", ...) with ListenFDsTag* values
* carrying the resolved (unit_id, original fdname, upstream index). */
_cleanup_(sd_json_variant_unrefp) sd_json_variant *root = NULL;
r = sd_json_parse_fd(
"fdstore-mapping",
mapping_fd,
SD_JSON_PARSE_MUST_BE_OBJECT|SD_JSON_PARSE_REOPEN_FD,
&root,
/* reterr_line= */ NULL,
/* reterr_column= */ NULL);
if (r < 0)
return log_warning_errno(r, "Failed to parse fdstore-mapping JSON: %m");
_cleanup_hashmap_free_ Hashmap *index_to_tag = NULL;
sd_json_variant *fds_json;
const char *unit_id;
JSON_VARIANT_OBJECT_FOREACH(unit_id, fds_json, root) {
sd_json_variant *entry;
if (!unit_name_is_valid(unit_id, UNIT_NAME_ANY)) {
log_warning("fdstore-mapping has invalid unit name '%s', skipping.", unit_id);
continue;
}
JSON_VARIANT_ARRAY_FOREACH(entry, fds_json) {
struct {
const char *name;
uint64_t index;
} p = { };
static const sd_json_dispatch_field dispatch_table[] = {
{ "name", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, voffsetof(p, name), SD_JSON_MANDATORY },
{ "index", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint64, voffsetof(p, index), SD_JSON_MANDATORY },
{}
};
r = sd_json_dispatch(entry, dispatch_table, SD_JSON_ALLOW_EXTENSIONS|SD_JSON_LOG|SD_JSON_WARNING, &p);
if (r < 0)
continue;
if (p.index == 0) {
log_warning("fdstore-mapping entry for unit '%s' name '%s' has zero index, skipping.", unit_id, p.name);
continue;
}
_cleanup_(listen_fds_tag_freep) ListenFDsTag *t = new(ListenFDsTag, 1);
if (!t)
return log_oom();
*t = (ListenFDsTag) {
.index = p.index,
};
t->unit_id = strdup(unit_id);
t->fdname = strdup(p.name);
if (!t->unit_id || !t->fdname)
return log_oom();
/* Key points into the value struct, so freeing the value frees the key. */
r = hashmap_ensure_put(&index_to_tag, &index_to_tag_hash_ops, &t->index, t);
if (r < 0)
return log_warning_errno(r, "Failed to insert fdstore-mapping entry into hashmap: %m");
if (r > 0)
TAKE_PTR(t);
}
}
*ret_index_to_tag = TAKE_PTR(index_to_tag);
return 0;
}
static int collect_listen_fds_named(FDSet *fds, Hashmap **ret_named_fds) {
_cleanup_hashmap_free_ Hashmap *named_fds = NULL, *index_to_tag = NULL;
_cleanup_strv_free_ char **names = NULL;
unsigned n_fds;
int r;
assert(fds);
assert(ret_named_fds);
/* Pull entries from the LISTEN_FDS=/LISTEN_FDNAMES= protocol out of 'fds' into a hashmap
* keyed by fd. Two flavours of named entries are recognized:
*
* - A single mapping memfd whose fdname matches SERVICE_FDSTORE_MAPPING_FDNAME, which
* contains a JSON map pairing numeric indices to (unit-id, original-fdname).
* - Numeric indices (matching entries in the mapping document) for the actual fds.
*
* The hashmap owns the fds (closed via destructor on cleanup) so any entries the dispatcher
* does not consume are correctly cleaned up. */
r = parse_listen_fds_env(&n_fds, &names);
if (r < 0) {
/* Fail gracefully here, just warn and ignore but otherwise proceed on parsing failure */
if (r != -ENXIO)
log_warning_errno(r, "Failed to parse LISTEN_FDS environment, ignoring: %m");
*ret_named_fds = NULL;
return 0;
}
/* First pass: locate and parse the mapping memfd, if any. */
for (unsigned i = 0; i < n_fds; i++) {
int fd = SD_LISTEN_FDS_START + i;
if (!streq(names[i], SERVICE_FDSTORE_MAPPING_FDNAME))
continue;
if (!fdset_contains(fds, fd))
continue;
(void) parse_listen_fds_mapping(fd, &index_to_tag);
/* The mapping memfd itself is not routed to any unit; close it and remove from fds
* so it doesn't get redistributed */
assert_se(fdset_remove(fds, fd) == fd);
safe_close(fd);
break;
}
/* Second pass: route fds whose name matches an entry in the mapping. */
for (unsigned i = 0; i < n_fds; i++) {
int fd = SD_LISTEN_FDS_START + i;
const char *name = names[i], *suffix;
ListenFDsTag *t;
uint64_t idx;
if (!fdset_contains(fds, fd))
continue;
if (!index_to_tag)
continue;
suffix = startswith(name, SERVICE_FDSTORE_SUB_FDNAME_PREFIX);
if (!suffix || safe_atou64(suffix, &idx) < 0)
continue;
/* Steal the matching mapping entry — we transfer ownership of the parsed
* (unit_id, fdname, index) struct into the per-fd hashmap that the manager
* will consume. */
t = hashmap_remove(index_to_tag, &idx);
if (!t)
continue;
_cleanup_(listen_fds_tag_freep) ListenFDsTag *t_owned = t;
r = hashmap_ensure_put(&named_fds, &fd_to_listen_fds_tag_hash_ops, FD_TO_PTR(fd), t_owned);
if (r < 0)
return log_debug_errno(r, "Failed to insert named fd into hashmap: %m");
if (r == 0)
continue; /* fd already inserted, cannot really happen */
TAKE_PTR(t_owned);
assert_se(fdset_remove(fds, fd) == fd);
}
*ret_named_fds = TAKE_PTR(named_fds);
return 1;
}
static int collect_fds(FDSet **ret_fds, Hashmap **ret_named_fds, const char **ret_error_message) {
int r;
assert(ret_fds);
assert(ret_named_fds);
assert(ret_error_message);
/* Pick up all fds passed to us. We apply a filter here: we only take the fds that have O_CLOEXEC
* off. All fds passed via execve() to us must have O_CLOEXEC off, and our own code and dependencies
* should be clean enough to set O_CLOEXEC universally. Thus checking the bit should be a safe
* mechanism to distinguish passed in fds from our own.
*
* Why bother? Some subsystems we initialize early, specifically selinux might keep fds open in our
* process behind our back. We should not take possession of that (and then accidentally close
* it). SELinux thankfully sets O_CLOEXEC on its fds, so this test should work. */
r = fdset_new_fill(/* filter_cloexec= */ 0, ret_fds);
if (r < 0) {
*ret_error_message = "Failed to allocate fd set";
return log_struct_errno(LOG_EMERG, r,
LOG_MESSAGE("Failed to allocate fd set: %m"),
LOG_MESSAGE_ID(SD_MESSAGE_CORE_FD_SET_FAILED_STR));
}
/* The serialization fd should have O_CLOEXEC turned on already, let's verify that we didn't pick it up here */
assert_se(!arg_serialization || !fdset_contains(*ret_fds, fileno(arg_serialization)));
(void) collect_listen_fds_named(*ret_fds, ret_named_fds);
return 0;
}
static void setup_console_terminal(bool skip_setup) {
if (arg_runtime_scope != RUNTIME_SCOPE_SYSTEM)
return;
/* If we are init, we connect stdin/stdout/stderr to /dev/null and make sure we don't have a
* controlling tty. */
terminal_detach_session();
/* Reset the console, but only if this is really init and we are freshly booted */
if (!skip_setup)
(void) console_setup();
}
static bool early_skip_setup_check(int argc, char *argv[]) {
bool found_deserialize = false;
/* Determine if this is a reexecution or normal bootup. We do the full command line parsing much
* later, so let's just have a quick peek here. Note that if we have switched root, do all the
* special setup things anyway, even if in that case we also do deserialization. */
for (int i = 1; i < argc; i++)
if (streq(argv[i], "--switched-root"))
return false; /* If we switched root, don't skip the setup. */
else if (startswith(argv[i], "--deserialize=") || streq(argv[i], "--deserialize"))
found_deserialize = true;
return found_deserialize; /* When we are deserializing, then we are reexecuting, hence avoid the extensive setup */
}
static int save_env(void) {
char **l;
l = strv_copy(environ);
if (!l)
return log_oom();
strv_free_and_replace(saved_env, l);
return 0;
}
static int run_systemd(int argc, char *argv[]) {
dual_timestamp
initrd_timestamp = DUAL_TIMESTAMP_NULL,
userspace_timestamp = DUAL_TIMESTAMP_NULL,
kernel_timestamp = DUAL_TIMESTAMP_NULL,
security_start_timestamp = DUAL_TIMESTAMP_NULL,
security_finish_timestamp = DUAL_TIMESTAMP_NULL;
struct rlimit saved_rlimit_nofile = RLIMIT_MAKE_CONST(0),
saved_rlimit_memlock = RLIMIT_MAKE_CONST(RLIM_INFINITY); /* The original rlimits we passed
* in. Note we use different values
* for the two that indicate whether
* these fields are initialized! */
bool skip_setup, loaded_policy = false, queue_default_job = false, first_boot = false;
_cleanup_hashmap_free_ Hashmap *named_listen_fds = NULL;
char *switch_root_dir = NULL, *switch_root_init = NULL;
usec_t before_startup, after_startup;
static char systemd[] = "systemd";
const char *error_message = NULL;
uint64_t saved_ambient_set = 0;
int r, retval = EXIT_FAILURE;
Manager *m = NULL;
FDSet *fds = NULL;
assert_se(argc > 0 && !isempty(argv[0]));
/* Take timestamps early on */
dual_timestamp_from_monotonic(&kernel_timestamp, 0);
dual_timestamp_now(&userspace_timestamp);
/* Figure out whether we need to do initialize the system, or if we already did that because we are
* reexecuting. */
skip_setup = early_skip_setup_check(argc, argv);
/* If we get started via the /sbin/init symlink then we are called 'init'. After a subsequent
* reexecution we are then called 'systemd'. That is confusing, hence let's call us systemd
* right-away. */
program_invocation_short_name = systemd;
(void) proc_set_comm(systemd);
/* Save the original command line */
save_argc_argv(argc, argv);
/* Save the original environment as we might need to restore it if we're requested to execute another
* system manager later. */
r = save_env();
if (r < 0) {
error_message = "Failed to copy environment block";
goto finish;
}
/* Make sure that if the user says "syslog" we actually log to the journal. */
log_set_upgrade_syslog_to_journal(true);
if (getpid_cached() == 1) {
/* When we run as PID 1 force system mode */
arg_runtime_scope = RUNTIME_SCOPE_SYSTEM;
/* Disable the umask logic */
umask(0);
/* Make sure that at least initially we do not ever log to journald/syslogd, because it might
* not be activated yet (even though the log socket for it exists). */
log_set_prohibit_ipc(true);
/* Always reopen /dev/console when running as PID 1 or one of its pre-execve() children. This
* is important so that we never end up logging to any foreign stderr, for example if we have
* to log in a child process right before execve()'ing the actual binary, at a point in time
* where socket activation stderr/stdout area already set up. */
log_set_always_reopen_console(true);
if (detect_container() <= 0) {
/* Running outside of a container as PID 1 */
log_set_target_and_open(LOG_TARGET_KMSG);
if (in_initrd())
initrd_timestamp = userspace_timestamp;
if (!skip_setup) {
r = mount_setup_early();
if (r < 0) {
error_message = "Failed to mount early API filesystems";
goto finish;
}
}
/* We might have just mounted /proc, so let's try to parse the kernel
* command line log arguments immediately. */
log_parse_environment();
/* Let's open the log backend a second time, in case the first time didn't
* work. Quite possibly we have mounted /dev just now, so /dev/kmsg became
* available, and it previously wasn't. */
log_open();
if (!skip_setup) {
disable_printk_ratelimit();
r = initialize_security(
&loaded_policy,
&security_start_timestamp,
&security_finish_timestamp,
&error_message);
if (r < 0)
goto finish;
}
r = mac_init();
if (r < 0) {
error_message = "Failed to initialize MAC support";
goto finish;
}
if (!skip_setup)
initialize_clock_timewarp();
clock_apply_epoch(/* allow_backwards= */ !skip_setup);
/* Set the default for later on, but don't actually open the logs like this for
* now. Note that if we are transitioning from the initrd there might still be
* journal fd open, and we shouldn't attempt opening that before we parsed
* /proc/cmdline which might redirect output elsewhere. */
log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
} else {
/* Running inside a container, as PID 1 */
log_set_target_and_open(LOG_TARGET_CONSOLE);
/* For later on, see above... */
log_set_target(LOG_TARGET_JOURNAL);
/* clear the kernel timestamp, because we are in a container */
kernel_timestamp = DUAL_TIMESTAMP_NULL;
}
initialize_coredump(skip_setup);
r = fixup_environment();
if (r < 0) {
log_struct_errno(LOG_EMERG, r,
LOG_MESSAGE("Failed to fix up PID 1 environment: %m"),
LOG_MESSAGE_ID(SD_MESSAGE_CORE_PID1_ENVIRONMENT_STR));
error_message = "Failed to fix up PID1 environment";
goto finish;
}
/* Try to figure out if we can use colors with the console. No need to do that for user
* instances since they never log into the console. */
log_show_color(colors_enabled());
r = make_null_stdio();
if (r < 0)
log_warning_errno(r, "Failed to redirect standard streams to /dev/null, ignoring: %m");
/* Load the kernel modules early. */
if (!skip_setup)
(void) kmod_setup();
/* Mount /proc, /sys and friends, so that /proc/cmdline and /proc/$PID/fd is available. */
r = mount_setup(loaded_policy, skip_setup);
if (r < 0) {
error_message = "Failed to mount API filesystems";
goto finish;
}
/* The efivarfs is now mounted, let's lock down the system token. */
lock_down_efi_variables();
} else {
/* Running as user instance */
arg_runtime_scope = RUNTIME_SCOPE_USER;
/* clear the kernel timestamp, because we are not PID 1 */
kernel_timestamp = DUAL_TIMESTAMP_NULL;
if (invoked_by_systemd()) {
log_set_always_reopen_console(true);
log_set_target_and_open(LOG_TARGET_AUTO);
}
r = mac_init();
if (r < 0) {
error_message = "Failed to initialize MAC support";
goto finish;
}
}
/* Save the original RLIMIT_NOFILE/RLIMIT_MEMLOCK so that we can reset it later when
* transitioning from the initrd to the main systemd or suchlike. */
save_rlimits(&saved_rlimit_nofile, &saved_rlimit_memlock);
/* Reset all signal handlers to clean up after reexec. */
(void) reset_all_signal_handlers();
if (getpid_cached() == 1 || invoked_by_systemd())
(void) ignore_signals(SIGNALS_IGNORE);
(void) parse_configuration(&saved_rlimit_nofile, &saved_rlimit_memlock);
r = parse_argv(argc, argv);
if (r < 0) {
error_message = "Failed to parse command line arguments";
goto finish;
}
r = safety_checks();
if (r < 0)
goto finish;
if (IN_SET(arg_action, ACTION_TEST, ACTION_DUMP_CONFIGURATION_ITEMS, ACTION_DUMP_BUS_PROPERTIES, ACTION_BUS_INTROSPECT))
pager_open(arg_pager_flags);
if (arg_action != ACTION_RUN)
skip_setup = true;
if (arg_action == ACTION_HELP) {
r = command_print_help_name("systemd");
retval = r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
goto finish;
} else if (arg_action == ACTION_VERSION) {
retval = version();
goto finish;
} else if (arg_action == ACTION_INTROSPECT_CLI) {
r = introspect_cli(SD_JSON_FORMAT_OFF);
retval = r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
goto finish;
} else if (arg_action == ACTION_DUMP_CONFIGURATION_ITEMS) {
unit_dump_config_items(stdout);
retval = EXIT_SUCCESS;
goto finish;
} else if (arg_action == ACTION_DUMP_BUS_PROPERTIES) {
dump_bus_properties(stdout);
retval = EXIT_SUCCESS;
goto finish;
} else if (arg_action == ACTION_BUS_INTROSPECT) {
r = bus_manager_introspect_implementations(stdout, arg_bus_introspect);
retval = r >= 0 ? EXIT_SUCCESS : EXIT_FAILURE;
goto finish;
}
assert_se(IN_SET(arg_action, ACTION_RUN, ACTION_TEST));
/* Move out of the way, so that we won't block unmounts */
assert_se(chdir("/") == 0);
if (arg_action == ACTION_RUN) {
if (!skip_setup) {
/* Apply the systemd.clock_usec= kernel command line switch */
apply_clock_update();
/* Apply random seed from kernel command line */
cmdline_take_random_seed();
}
/* A core pattern might have been specified via the cmdline. */
initialize_core_pattern(skip_setup);
/* Make /usr/ read-only */
apply_protect_system(skip_setup);
/* Close logging fds, in order not to confuse collecting passed fds and terminal logic below */
log_close();
/* Remember open file descriptors for later deserialization */
r = collect_fds(&fds, &named_listen_fds, &error_message);
if (r < 0)
goto finish;
/* Give up any control of the console, but make sure its initialized. */
setup_console_terminal(skip_setup);
/* Open the logging devices, if possible and necessary */
log_open();
}
log_execution_mode(&first_boot);
r = cg_has_legacy();
if (r < 0) {
error_message = "Failed to check cgroup hierarchy";
goto finish;
}
if (r > 0) {
r = log_full_errno(LOG_EMERG, SYNTHETIC_ERRNO(EPROTO),
"Detected cgroup v1 hierarchy at /sys/fs/cgroup/, which is no longer supported by current version of systemd.\n"
"Please instruct your initrd to mount cgroup v2 (unified) hierarchy,\n"
"possibly by removing any stale kernel command line options, such as:\n"
" systemd.legacy_systemd_cgroup_controller=1\n"
" systemd.unified_cgroup_hierarchy=0");
error_message = "Detected unsupported legacy cgroup hierarchy, refusing execution";
goto finish;
}
/* Building without libmount is allowed, but if it is compiled in, then we must be able to load it */
r = dlopen_libmount(LOG_DEBUG);
if (r < 0 && !ERRNO_IS_NEG_NOT_SUPPORTED(r)) {
error_message = "Failed to load libmount.so";
goto finish;
}
r = initialize_runtime(skip_setup,
first_boot,
&saved_rlimit_nofile,
&saved_rlimit_memlock,
&saved_ambient_set,
&error_message);
if (r < 0)
goto finish;
r = manager_new(arg_runtime_scope,
arg_action == ACTION_TEST ? MANAGER_TEST_FULL : 0,
&m);
if (r < 0) {
log_struct_errno(LOG_EMERG, r,
LOG_MESSAGE("Failed to allocate manager object: %m"),
LOG_MESSAGE_ID(SD_MESSAGE_CORE_MANAGER_ALLOCATE_STR));
error_message = "Failed to allocate manager object";
goto finish;
}
m->timestamps[MANAGER_TIMESTAMP_KERNEL] = kernel_timestamp;
m->timestamps[MANAGER_TIMESTAMP_INITRD] = initrd_timestamp;
m->timestamps[MANAGER_TIMESTAMP_USERSPACE] = userspace_timestamp;
m->timestamps[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_START)] = security_start_timestamp;
m->timestamps[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_FINISH)] = security_finish_timestamp;
m->saved_ambient_set = saved_ambient_set;
set_manager_defaults(m);
set_manager_settings(m);
manager_set_first_boot(m, first_boot);
manager_set_switching_root(m, arg_switched_root);
/* Remember whether we should queue the default job */
queue_default_job = !arg_serialization || arg_switched_root;
before_startup = now(CLOCK_MONOTONIC);
r = manager_startup(m, arg_serialization, fds, named_listen_fds, /* root= */ NULL);
if (r < 0) {
error_message = "Failed to start up manager";
goto finish;
}
/* This will close all file descriptors that were opened, but not claimed by any unit. */
fds = fdset_free(fds);
arg_serialization = safe_fclose(arg_serialization);
if (queue_default_job) {
r = do_queue_default_job(m, &error_message);
if (r < 0)
goto finish;
}
after_startup = now(CLOCK_MONOTONIC);
log_full(arg_action == ACTION_TEST ? LOG_INFO : LOG_DEBUG,
"Loaded units and determined initial transaction in %s.",
FORMAT_TIMESPAN(after_startup - before_startup, 100 * USEC_PER_MSEC));
if (arg_action == ACTION_TEST) {
manager_test_summary(m);
retval = EXIT_SUCCESS;
goto finish;
}
r = invoke_main_loop(m,
&saved_rlimit_nofile,
&saved_rlimit_memlock,
&retval,
&fds,
&switch_root_dir,
&switch_root_init,
&error_message);
/* MANAGER_OK and MANAGER_RELOAD are not expected here. */
assert(r < 0 || IN_SET(r, MANAGER_REEXECUTE, MANAGER_EXIT) ||
(arg_runtime_scope == RUNTIME_SCOPE_SYSTEM &&
IN_SET(r, MANAGER_REBOOT,
MANAGER_SOFT_REBOOT,
MANAGER_POWEROFF,
MANAGER_HALT,
MANAGER_KEXEC,
MANAGER_SWITCH_ROOT)));
finish:
pager_close();
if (m) {
arg_reboot_watchdog = manager_get_watchdog(m, WATCHDOG_REBOOT);
arg_kexec_watchdog = manager_get_watchdog(m, WATCHDOG_KEXEC);
/* For kexec, serialize fd stores now. Services have stopped and sent
* their FDs to the store, but the manager (and its fd stores) is still alive. */
if (r == MANAGER_KEXEC)
(void) manager_luo_serialize_fd_stores(m, &arg_luo_serialization, &fds);
m = manager_free(m);
}
mac_selinux_finish();
if (IN_SET(r, MANAGER_REEXECUTE, MANAGER_SWITCH_ROOT, MANAGER_SOFT_REBOOT))
r = do_reexecute(r,
argc, argv,
&saved_rlimit_nofile,
&saved_rlimit_memlock,
TAKE_PTR(fds),
switch_root_dir,
switch_root_init,
saved_ambient_set,
&error_message); /* This only returns if reexecution failed */
arg_serialization = safe_fclose(arg_serialization);
/* For kexec, the FDSet and LUO serialization file must survive until become_shutdown() calls
* execve() (CLOEXEC is already cleared on these FDs). For all other paths, free them now. */
if (r != MANAGER_KEXEC) {
fds = fdset_free(fds);
arg_luo_serialization = safe_fclose(arg_luo_serialization);
}
saved_env = strv_free(saved_env);
#if HAVE_VALGRIND_VALGRIND_H
/* If we are PID 1 and running under valgrind, then let's exit
* here explicitly. valgrind will only generate nice output on
* exit(), not on exec(), hence let's do the former not the
* latter here. */
if (getpid_cached() == 1 && RUNNING_ON_VALGRIND) {
/* Cleanup watchdog_device strings for valgrind. We need them
* in become_shutdown() so normally we cannot free them yet. */
watchdog_free_device();
reset_arguments();
return retval;
}
#endif
#if HAS_FEATURE_ADDRESS_SANITIZER
/* At this stage we most likely don't have stdio/stderr open, so the following
* LSan check would not print any actionable information and would just crash
* PID 1. To make this a bit more helpful, let's try to open /dev/console,
* and if we succeed redirect LSan's report there. */
if (getpid_cached() == 1) {
_cleanup_close_ int tty_fd = -EBADF;
tty_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
if (tty_fd >= 0)
__sanitizer_set_report_fd((void*) (intptr_t) tty_fd);
__lsan_do_leak_check();
}
#endif
if (r < 0)
(void) sd_notifyf(/* unset_environment= */ false,
"ERRNO=%i", -r);
/* Try to invoke the shutdown binary unless we already failed.
* If we failed above, we want to freeze after finishing cleanup. */
if (arg_runtime_scope == RUNTIME_SCOPE_SYSTEM &&
IN_SET(r, MANAGER_EXIT, MANAGER_REBOOT, MANAGER_POWEROFF, MANAGER_HALT, MANAGER_KEXEC)) {
ManagerObjective objective = r;
r = become_shutdown(objective, retval);
assert(r < 0);
log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_WARNING, r,
"Failed to execute shutdown binary: %m");
/* As PID 1, carry out the requested operation ourselves rather than relying on the shutdown
* binary. This only returns if that didn't work, in which case we freeze/exit/reboot
* below. */
r = fallback_shutdown(objective, retval);
assert(r < 0);
log_error_errno(r, "Failed to perform shutdown: %m");
error_message = "Failed to perform shutdown";