Skip to main content

starnix_core/task/
kernel.rs

1// Copyright 2021 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use crate::bpf::EbpfState;
6use crate::device::remote_block_device::RemoteBlockDeviceRegistry;
7use crate::device::{DeviceMode, DeviceRegistry};
8use crate::execution::CrashReporter;
9use crate::mm::{FutexTable, MappingSummary, MlockPinFlavor, SharedFutexKey};
10use crate::power::SuspendResumeManagerHandle;
11use crate::ptrace::StopState;
12use crate::security::{self, AuditLogger};
13use crate::task::container_namespace::ContainerNamespace;
14use crate::task::limits::SystemLimits;
15use crate::task::memory_attribution::MemoryAttributionManager;
16use crate::task::net::NetstackDevices;
17use crate::task::tracing::PidToKoidMap;
18use crate::task::{
19    AbstractUnixSocketNamespace, AbstractVsockSocketNamespace, CurrentTask, DelayedReleaser,
20    IpTables, KernelCgroups, KernelStats, KernelThreads, PidTable, SchedulerManager, Syslog,
21    ThreadGroup, UtsNamespace, UtsNamespaceHandle,
22};
23use crate::time::{HrTimerManager, HrTimerManagerHandle};
24use crate::vdso::vdso_loader::Vdso;
25use crate::vfs::fs_args::MountParams;
26use crate::vfs::socket::{
27    GenericMessage, GenericNetlink, NetlinkAccessControl, NetlinkContextImpl,
28    NetlinkToClientSender, SocketAddress, SocketTokensStore,
29};
30use crate::vfs::{CacheConfig, FileOps, FsNodeHandle, FsString, Mounts, NamespaceNode};
31use bstr::{BString, ByteSlice};
32use devicetree::types::Devicetree;
33use expando::Expando;
34use fidl::endpoints::{
35    ClientEnd, ControlHandle, DiscoverableProtocolMarker, ProtocolMarker, create_endpoints,
36};
37use fidl_fuchsia_component_runner::{ComponentControllerControlHandle, ComponentStopInfo};
38use fidl_fuchsia_feedback::CrashReporterProxy;
39use fidl_fuchsia_io as fio;
40use fidl_fuchsia_memory_attribution as fattribution;
41use fidl_fuchsia_time_external::AdjustSynchronousProxy;
42use fuchsia_async as fasync;
43use fuchsia_inspect::ArrayProperty;
44use futures::FutureExt;
45use netlink::interfaces::InterfacesHandler;
46use netlink::{NETLINK_LOG_TAG, Netlink};
47use once_cell::sync::OnceCell;
48use starnix_lifecycle::{AtomicU32Counter, AtomicU64Counter};
49use starnix_logging::{SyscallLogFilter, log_debug, log_error, log_info, log_warn};
50use starnix_sync::{
51    FileOpsCore, KernelSwapFiles, LockEqualOrBefore, Locked, Mutex, OrderedMutex, RwLock,
52};
53use starnix_types::ownership::TempRef;
54use starnix_uapi::device_id::DeviceId;
55use starnix_uapi::errors::{Errno, errno};
56use starnix_uapi::open_flags::OpenFlags;
57use starnix_uapi::{VMADDR_CID_HOST, from_status_like_fdio};
58use std::borrow::Cow;
59use std::collections::{HashMap, HashSet};
60use std::num::NonZeroU64;
61use std::path::PathBuf;
62use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU16, Ordering};
63use std::sync::{Arc, OnceLock, Weak};
64use zx::CpuFeatureFlags;
65
66/// Kernel features are specified in the component manifest of the starnix container
67/// or explicitly provided to the kernel constructor in tests.
68#[derive(Debug, Default, Clone)]
69pub struct KernelFeatures {
70    pub bpf_v2: bool,
71
72    /// Whether the kernel supports the S_ISUID and S_ISGID bits.
73    ///
74    /// For example, these bits are used by `sudo`.
75    ///
76    /// Enabling this feature is potentially a security risk because they allow privilege
77    /// escalation.
78    pub enable_suid: bool,
79
80    /// Whether io_uring is enabled.
81    ///
82    /// TODO(https://fxbug.dev/297431387): Enabled by default once the feature is completed.
83    pub io_uring: bool,
84
85    /// Whether the kernel should return an error to userspace, rather than panicking, if `reboot()`
86    /// is requested but cannot be enacted because the kernel lacks the relevant capabilities.
87    pub error_on_failed_reboot: bool,
88
89    /// The default seclabel that is applied to components that are run in this kernel.
90    ///
91    /// Components can override this by setting the `seclabel` field in their program block.
92    pub default_seclabel: Option<String>,
93
94    /// Whether the kernel is being used to run the SELinux Test Suite.
95    ///
96    /// TODO: https://fxbug.dev/388077431 - remove this once we no longer need workarounds for the
97    /// SELinux Test Suite.
98    pub selinux_test_suite: bool,
99
100    /// The default mount options to use when mounting directories from a component's namespace.
101    ///
102    /// The key is the path in the component's namespace, and the value is the mount options
103    /// string.
104    pub default_ns_mount_options: Option<HashMap<String, String>>,
105
106    /// The default uid that is applied to components that are run in this kernel.
107    ///
108    /// Components can override this by setting the `uid` field in their program block.
109    pub default_uid: u32,
110
111    /// mlock() never prefaults pages.
112    pub mlock_always_onfault: bool,
113
114    /// Implementation of mlock() to use for this kernel instance.
115    pub mlock_pin_flavor: MlockPinFlavor,
116
117    /// Whether excessive crash reports should be throttled.
118    pub crash_report_throttling: bool,
119
120    /// Whether or not to serve wifi support to Android.
121    pub wifi: bool,
122
123    /// The number of bytes to cache in pages for reading zx::MapInfo from VMARs.
124    pub cached_zx_map_info_bytes: u32,
125
126    /// The size of the Dirent LRU cache.
127    pub dirent_cache_size: u32,
128
129    /// Whether to expose a stub '/dev/ion' node, as a temporary workaround for compatibility.
130    // TODO(https://fxbug.dev/485370648) remove when unnecessary
131    pub fake_ion: bool,
132}
133
134impl KernelFeatures {
135    /// Returns the `MountParams` to use when mounting the specified path from a component's
136    /// namespace.  This mechanism is also used to specified options for mounts created via
137    /// container features, by specifying a pseudo-path e.g. "#container".
138    pub fn ns_mount_options(&self, ns_path: &str) -> Result<MountParams, Errno> {
139        if let Some(all_options) = &self.default_ns_mount_options {
140            if let Some(options) = all_options.get(ns_path) {
141                return MountParams::parse(options.as_bytes().into());
142            }
143        }
144        Ok(MountParams::default())
145    }
146}
147
148/// Kernel command line argument structure
149pub struct ArgNameAndValue<'a> {
150    pub name: &'a str,
151    pub value: Option<&'a str>,
152}
153
154/// The shared, mutable state for the entire Starnix kernel.
155///
156/// The `Kernel` object holds all kernel threads, userspace tasks, and file system resources for a
157/// single instance of the Starnix kernel. In production, there is one instance of this object for
158/// the entire Starnix kernel. However, multiple instances of this object can be created in one
159/// process during unit testing.
160///
161/// The structure of this object will likely need to evolve as we implement more namespacing and
162/// isolation mechanisms, such as `namespaces(7)` and `pid_namespaces(7)`.
163pub struct Kernel {
164    /// Weak reference to self. Allows to not have to pass &Arc<Kernel> in apis.
165    pub weak_self: Weak<Kernel>,
166
167    /// The kernel threads running on behalf of this kernel.
168    pub kthreads: KernelThreads,
169
170    /// The features enabled for this kernel.
171    pub features: KernelFeatures,
172
173    /// The processes and threads running in this kernel, organized by pid_t.
174    pub pids: RwLock<PidTable>,
175
176    /// Used to record the pid/tid to Koid mappings. Set when collecting trace data.
177    pub pid_to_koid_mapping: Arc<RwLock<Option<PidToKoidMap>>>,
178
179    /// Subsystem-specific properties that hang off the Kernel object.
180    ///
181    /// Instead of adding yet another property to the Kernel object, consider storing the property
182    /// in an expando if that property is only used by one part of the system, such as a module.
183    pub expando: Expando,
184
185    /// The default namespace for abstract AF_UNIX sockets in this kernel.
186    ///
187    /// Rather than use this default namespace, abstract socket addresses
188    /// should be looked up in the AbstractSocketNamespace on each Task
189    /// object because some Task objects might have a non-default namespace.
190    pub default_abstract_socket_namespace: Arc<AbstractUnixSocketNamespace>,
191
192    /// The default namespace for abstract AF_VSOCK sockets in this kernel.
193    pub default_abstract_vsock_namespace: Arc<AbstractVsockSocketNamespace>,
194
195    /// The kernel command line. Shows up in /proc/cmdline.
196    pub cmdline: BString,
197
198    pub device_tree: Option<Devicetree>,
199
200    // Global state held by the Linux Security Modules subsystem.
201    pub security_state: security::KernelState,
202
203    /// The registry of device drivers.
204    pub device_registry: DeviceRegistry,
205
206    /// Mapping of top-level namespace entries to an associated proxy.
207    /// For example, "/svc" to the respective proxy. Only the namespace entries
208    /// which were known at component startup will be available by the kernel.
209    pub container_namespace: ContainerNamespace,
210
211    /// The registry of block devices backed by a remote fuchsia.io file.
212    pub remote_block_device_registry: Arc<RemoteBlockDeviceRegistry>,
213
214    /// The iptables used for filtering network packets.
215    iptables: OnceLock<IpTables>,
216
217    /// The futexes shared across processes.
218    pub shared_futexes: Arc<FutexTable<SharedFutexKey>>,
219
220    /// The default UTS namespace for all tasks.
221    ///
222    /// Because each task can have its own UTS namespace, you probably want to use
223    /// the UTS namespace handle of the task, which may/may not point to this one.
224    pub root_uts_ns: UtsNamespaceHandle,
225
226    /// A struct containing a VMO with a vDSO implementation, if implemented for a given architecture, and possibly an offset for a sigreturn function.
227    pub vdso: Vdso,
228
229    /// A struct containing a VMO with a arch32-vDSO implementation, if implemented for a given architecture.
230    // TODO(https://fxbug.dev/380431743) This could be made less clunky -- maybe a Vec<Vdso> above or
231    // something else
232    pub vdso_arch32: Option<Vdso>,
233
234    /// The table of devices installed on the netstack and their associated
235    /// state local to this `Kernel`.
236    pub netstack_devices: Arc<NetstackDevices>,
237
238    /// Files that are currently available for swapping.
239    /// Note: Starnix never actually swaps memory to these files. We just need to track them
240    /// to pass conformance tests.
241    pub swap_files: OrderedMutex<Vec<FsNodeHandle>, KernelSwapFiles>,
242
243    /// The implementation of generic Netlink protocol families.
244    generic_netlink: OnceLock<GenericNetlink<NetlinkToClientSender<GenericMessage>>>,
245
246    /// The implementation of networking-related Netlink protocol families.
247    network_netlink: OnceLock<Netlink<NetlinkContextImpl>>,
248
249    /// Inspect instrumentation for this kernel instance.
250    pub inspect_node: fuchsia_inspect::Node,
251
252    /// The kinds of seccomp action that gets logged, stored as a bit vector.
253    /// Each potential SeccompAction gets a bit in the vector, as specified by
254    /// SeccompAction::logged_bit_offset.  If the bit is set, that means the
255    /// action should be logged when it is taken, subject to the caveats
256    /// described in seccomp(2).  The value of the bit vector is exposed to users
257    /// in a text form in the file /proc/sys/kernel/seccomp/actions_logged.
258    pub actions_logged: AtomicU16,
259
260    /// The manager for suspend/resume.
261    pub suspend_resume_manager: SuspendResumeManagerHandle,
262
263    /// Unique IDs for new mounts and mount namespaces.
264    pub next_mount_id: AtomicU64Counter,
265    pub next_peer_group_id: AtomicU64Counter,
266    pub next_namespace_id: AtomicU64Counter,
267
268    /// Unique IDs for file objects.
269    pub next_file_object_id: AtomicU64Counter,
270
271    /// Unique cookie used to link two inotify events, usually an IN_MOVE_FROM/IN_MOVE_TO pair.
272    pub next_inotify_cookie: AtomicU32Counter,
273
274    /// Controls which processes a process is allowed to ptrace.  See Documentation/security/Yama.txt
275    pub ptrace_scope: AtomicU8,
276
277    // The Fuchsia build version returned by `fuchsia.buildinfo.Provider`.
278    pub build_version: OnceCell<String>,
279
280    pub stats: Arc<KernelStats>,
281
282    /// Resource limits that are exposed, for example, via sysctl.
283    pub system_limits: SystemLimits,
284
285    // The service to handle delayed releases. This is required for elements that requires to
286    // execute some code when released and requires a known context (both in term of lock context,
287    // as well as `CurrentTask`).
288    pub delayed_releaser: DelayedReleaser,
289
290    /// Manages task priorities.
291    pub scheduler: SchedulerManager,
292
293    /// The syslog manager.
294    pub syslog: Syslog,
295
296    /// All mounts.
297    pub mounts: Mounts,
298
299    /// The manager for creating and managing high-resolution timers.
300    pub hrtimer_manager: HrTimerManagerHandle,
301
302    /// The manager for monitoring and reporting resources used by the kernel.
303    pub memory_attribution_manager: MemoryAttributionManager,
304
305    /// Handler for crashing Linux processes.
306    pub crash_reporter: CrashReporter,
307
308    /// Whether this kernel is shutting down. When shutting down, new processes may not be spawned.
309    shutting_down: AtomicBool,
310
311    /// True to disable syslog access to unprivileged callers.  This also controls whether read
312    /// access to /dev/kmsg requires privileged capabilities.
313    pub restrict_dmesg: AtomicBool,
314
315    /// Determines whether unprivileged BPF is permitted, or can be re-enabled.
316    ///   0 - Unprivileged BPF is permitted.
317    ///   1 - Unprivileged BPF is not permitted, and cannot be enabled.
318    ///   2 - Unprivileged BPF is not permitted, but can be enabled by a privileged task.
319    pub disable_unprivileged_bpf: AtomicU8,
320
321    /// Control handle to the running container's ComponentController.
322    pub container_control_handle: Mutex<Option<ComponentControllerControlHandle>>,
323
324    /// eBPF state: loaded programs, eBPF maps, etc.
325    pub ebpf_state: EbpfState,
326
327    /// Cgroups of the kernel.
328    pub cgroups: KernelCgroups,
329
330    /// Used to communicate requests to adjust system time from within a Starnix
331    /// container. Used from syscalls.
332    pub time_adjustment_proxy: Option<AdjustSynchronousProxy>,
333
334    /// Used to store tokens for sockets, particularly per-uid sharing domain sockets.
335    pub socket_tokens_store: SocketTokensStore,
336
337    /// Hardware capabilities to push onto stack when loading an ELF binary.
338    pub hwcaps: HwCaps,
339
340    /// Filters for syscall logging. Processes with names matching these filters will have syscalls
341    /// logged at INFO level.
342    pub syscall_log_filters: Mutex<Vec<SyscallLogFilter>>,
343}
344
345/// Hardware capabilities.
346#[derive(Debug, Clone, Copy, Default)]
347pub struct HwCap {
348    /// The value for `AT_HWCAP`.
349    pub hwcap: u32,
350    /// The value for `AT_HWCAP2`.
351    pub hwcap2: u32,
352}
353
354/// Hardware capabilities for both 32-bit and 64-bit ELF binaries.
355#[derive(Debug, Clone, Copy, Default)]
356pub struct HwCaps {
357    /// For 32-bit binaries.
358    #[cfg(target_arch = "aarch64")]
359    pub arch32: HwCap,
360    /// For 64-bit binaries.
361    pub arch64: HwCap,
362}
363
364/// An implementation of [`InterfacesHandler`].
365///
366/// This holds a `Weak<Kernel>` because it is held within a [`Netlink`] which
367/// is itself held within an `Arc<Kernel>`. Holding an `Arc<T>` within an
368/// `Arc<T>` prevents the `Arc`'s ref count from ever reaching 0, causing a
369/// leak.
370struct InterfacesHandlerImpl(Weak<Kernel>);
371
372impl InterfacesHandlerImpl {
373    fn kernel(&self) -> Option<Arc<Kernel>> {
374        self.0.upgrade()
375    }
376}
377
378impl InterfacesHandler for InterfacesHandlerImpl {
379    fn handle_new_link(&mut self, name: &str, interface_id: NonZeroU64) {
380        if let Some(kernel) = self.kernel() {
381            kernel.netstack_devices.add_device(&kernel, name.into(), interface_id);
382        }
383    }
384
385    fn handle_deleted_link(&mut self, name: &str) {
386        if let Some(kernel) = self.kernel() {
387            kernel.netstack_devices.remove_device(&kernel, name.into());
388        }
389    }
390
391    fn handle_idle_event(&mut self) {
392        let Some(kernel) = self.kernel() else {
393            log_error!("kernel went away while netlink is initializing");
394            return;
395        };
396        let (initialized, wq) = &kernel.netstack_devices.initialized_and_wq;
397        if initialized.swap(true, Ordering::SeqCst) {
398            log_error!("netlink initial devices should only be reported once");
399            return;
400        }
401        wq.notify_all()
402    }
403}
404
405impl Kernel {
406    pub fn new(
407        cmdline: BString,
408        features: KernelFeatures,
409        system_limits: SystemLimits,
410        container_namespace: ContainerNamespace,
411        scheduler: SchedulerManager,
412        crash_reporter_proxy: Option<CrashReporterProxy>,
413        inspect_node: fuchsia_inspect::Node,
414        security_state: security::KernelState,
415        time_adjustment_proxy: Option<AdjustSynchronousProxy>,
416        device_tree: Option<Devicetree>,
417    ) -> Result<Arc<Kernel>, zx::Status> {
418        let unix_address_maker =
419            Box::new(|x: FsString| -> SocketAddress { SocketAddress::Unix(x) });
420        let vsock_address_maker = Box::new(|x: u32| -> SocketAddress {
421            SocketAddress::Vsock { port: x, cid: VMADDR_CID_HOST }
422        });
423
424        let crash_reporter = CrashReporter::new(
425            &inspect_node,
426            crash_reporter_proxy,
427            zx::Duration::from_minutes(8),
428            features.crash_report_throttling,
429        );
430        let hrtimer_manager = HrTimerManager::new(&inspect_node);
431
432        let cpu_feature_flags =
433            zx::system_get_feature_flags::<CpuFeatureFlags>().unwrap_or_else(|e| {
434                log_debug!("CPU feature flags are only supported on ARM64: {}, reporting 0", e);
435                CpuFeatureFlags::empty()
436            });
437        let hwcaps = HwCaps::from_cpu_feature_flags(cpu_feature_flags);
438
439        let this = Arc::new_cyclic(|kernel| Kernel {
440            weak_self: kernel.clone(),
441            kthreads: KernelThreads::new(kernel.clone()),
442            features,
443            pids: Default::default(),
444            pid_to_koid_mapping: Arc::new(RwLock::new(None)),
445            expando: Default::default(),
446            default_abstract_socket_namespace: AbstractUnixSocketNamespace::new(unix_address_maker),
447            default_abstract_vsock_namespace: AbstractVsockSocketNamespace::new(
448                vsock_address_maker,
449            ),
450            cmdline,
451            device_tree,
452            security_state,
453            device_registry: Default::default(),
454            container_namespace,
455            remote_block_device_registry: Default::default(),
456            iptables: OnceLock::new(),
457            shared_futexes: Arc::<FutexTable<SharedFutexKey>>::default(),
458            root_uts_ns: Arc::new(RwLock::new(UtsNamespace::default())),
459            vdso: Vdso::new(),
460            vdso_arch32: Vdso::new_arch32(),
461            netstack_devices: Arc::default(),
462            swap_files: Default::default(),
463            generic_netlink: OnceLock::new(),
464            network_netlink: OnceLock::new(),
465            inspect_node,
466            actions_logged: AtomicU16::new(0),
467            suspend_resume_manager: Default::default(),
468            next_mount_id: AtomicU64Counter::new(1),
469            next_peer_group_id: AtomicU64Counter::new(1),
470            next_namespace_id: AtomicU64Counter::new(1),
471            next_inotify_cookie: AtomicU32Counter::new(1),
472            next_file_object_id: Default::default(),
473            system_limits,
474            ptrace_scope: AtomicU8::new(0), // Disable YAMA checks by default.
475            restrict_dmesg: AtomicBool::new(false),
476            disable_unprivileged_bpf: AtomicU8::new(0), // Enable unprivileged BPF by default.
477            build_version: OnceCell::new(),
478            stats: Arc::new(KernelStats::default()),
479            delayed_releaser: Default::default(),
480            scheduler,
481            syslog: Default::default(),
482            mounts: Mounts::new(),
483            hrtimer_manager,
484            memory_attribution_manager: MemoryAttributionManager::new(kernel.clone()),
485            crash_reporter,
486            shutting_down: AtomicBool::new(false),
487            container_control_handle: Mutex::new(None),
488            ebpf_state: Default::default(),
489            cgroups: Default::default(),
490            time_adjustment_proxy,
491            socket_tokens_store: Default::default(),
492            hwcaps,
493            syscall_log_filters: Default::default(),
494        });
495
496        // Initialize the device registry before registering any devices.
497        //
498        // We will create sysfs recursively within this function.
499        this.device_registry.objects.init(&mut this.kthreads.unlocked_for_async(), &this);
500
501        // Make a copy of this Arc for the inspect lazy node to use but don't create an Arc cycle
502        // because the inspect node that owns this reference is owned by the kernel.
503        let kernel = Arc::downgrade(&this);
504        this.inspect_node.record_lazy_child("thread_groups", move || {
505            if let Some(kernel) = kernel.upgrade() {
506                let inspector = kernel.get_thread_groups_inspect();
507                async move { Ok(inspector) }.boxed()
508            } else {
509                async move { Err(anyhow::format_err!("kernel was dropped")) }.boxed()
510            }
511        });
512
513        let kernel = Arc::downgrade(&this);
514        this.inspect_node.record_lazy_child("cgroupv2", move || {
515            if let Some(kernel) = kernel.upgrade() {
516                async move { Ok(kernel.cgroups.cgroup2.get_cgroup_inspect()) }.boxed()
517            } else {
518                async move { Err(anyhow::format_err!("kernel was dropped")) }.boxed()
519            }
520        });
521
522        Ok(this)
523    }
524
525    /// Shuts down userspace and the kernel in an orderly fashion, eventually terminating the root
526    /// kernel process.
527    pub fn shut_down(self: &Arc<Self>) {
528        // Run shutdown code on a kthread in the main process so that it can be the last process
529        // alive.
530        self.kthreads.spawn_future(
531            {
532                let kernel = self.clone();
533                move || async move {
534                    kernel.run_shutdown().await;
535                }
536            },
537            "run_shutdown",
538        );
539    }
540
541    /// Starts shutting down the Starnix kernel and any running container. Only one thread can drive
542    /// shutdown at a time. This function will return immediately if shut down is already under way.
543    ///
544    /// Shutdown happens in several phases:
545    ///
546    /// 1. Disable launching new processes
547    /// 2. Shut down individual ThreadGroups until only the init and system tasks remain
548    /// 3. Repeat the above for the init task
549    /// 4. Clean up kernel-internal structures that can hold processes alive
550    /// 5. Ensure this process is the only one running in the kernel job.
551    /// 6. Unmounts the kernel's mounts' FileSystems.
552    /// 7. Tell CF the container component has stopped
553    /// 8. Exit this process
554    ///
555    /// If a ThreadGroup does not shut down on its own (including after SIGKILL), that phase of
556    /// shutdown will hang. To gracefully shut down any further we need the other kernel processes
557    /// to do controlled exits that properly release access to shared state. If our orderly shutdown
558    /// does hang, eventually CF will kill the container component which will lead to the job of
559    /// this process being killed and shutdown will still complete.
560    async fn run_shutdown(&self) {
561        const INIT_PID: i32 = 1;
562        const SYSTEM_TASK_PID: i32 = 2;
563
564        // Step 1: Prevent new processes from being created once they observe this update. We don't
565        // want the thread driving shutdown to be racing with other threads creating new processes.
566        if self
567            .shutting_down
568            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
569            .is_err()
570        {
571            log_info!("Additional thread tried to initiate shutdown while already in-progress.");
572            return;
573        }
574
575        log_info!("Shutting down Starnix kernel.");
576
577        // Step 2: Shut down thread groups in a loop until init and the system task are all that
578        // remain.
579        loop {
580            let tgs = {
581                // Exiting thread groups need to acquire a write lock for the pid table to
582                // successfully exit so we need to acquire that lock in a reduced scope.
583                self.pids
584                    .read()
585                    .get_thread_groups()
586                    .filter(|tg| tg.leader != SYSTEM_TASK_PID && tg.leader != INIT_PID)
587                    .collect::<Vec<_>>()
588            };
589            if tgs.is_empty() {
590                log_info!("pid table is empty except init and system task");
591                break;
592            }
593
594            log_info!(tgs:?; "shutting down thread groups");
595            let mut tasks = vec![];
596            for tg in tgs {
597                let task = fasync::Task::local(ThreadGroup::shut_down(Arc::downgrade(&tg)));
598                tasks.push(task);
599            }
600            futures::future::join_all(tasks).await;
601        }
602
603        // Step 3: Terminate the init process.
604        let maybe_init = {
605            // Exiting thread groups need to acquire a write lock for the pid table to successfully
606            // exit so we need to acquire that lock in a reduced scope.
607            self.pids.read().get_thread_group(1).map(|tg| Arc::downgrade(&tg))
608        };
609        if let Some(init) = maybe_init {
610            log_info!("shutting down init");
611            ThreadGroup::shut_down(init).await;
612        } else {
613            log_info!("init already terminated");
614        }
615
616        // Step 4: Clean up any structures that can keep non-Linux processes live in our job.
617        log_info!("cleaning up pinned memory");
618        self.expando.remove::<crate::mm::InfoCacheShadowProcess>();
619        self.expando.remove::<crate::mm::MlockShadowProcess>();
620
621        // Step 5: Make sure this is the only process running in the job. We already should have
622        // cleared up all processes other than the system task at this point, but wait on any that
623        // might be around for good measure.
624        //
625        // Use unwrap liberally since we're shutting down anyway and errors will still tear down the
626        // kernel.
627        let kernel_job = fuchsia_runtime::job_default();
628        assert_eq!(kernel_job.children().unwrap(), &[], "starnix does not create any child jobs");
629        let own_koid = fuchsia_runtime::process_self().koid().unwrap();
630
631        log_info!("waiting for this to be the only process in the job");
632        loop {
633            let mut remaining_processes = kernel_job
634                .processes()
635                .unwrap()
636                .into_iter()
637                // Don't wait for ourselves to exit.
638                .filter(|pid| pid != &own_koid)
639                .peekable();
640            if remaining_processes.peek().is_none() {
641                log_info!("No stray Zircon processes.");
642                break;
643            }
644
645            let mut terminated_signals = vec![];
646            for pid in remaining_processes {
647                let handle = match kernel_job
648                    .get_child(&pid, zx::Rights::BASIC | zx::Rights::PROPERTY | zx::Rights::DESTROY)
649                {
650                    Ok(h) => h,
651                    Err(e) => {
652                        log_info!(pid:?, e:?; "failed to get child process from job");
653                        continue;
654                    }
655                };
656                log_info!(
657                    pid:?,
658                    name:? = handle.get_name();
659                    "waiting on process terminated signal"
660                );
661                terminated_signals
662                    .push(fuchsia_async::OnSignals::new(handle, zx::Signals::PROCESS_TERMINATED));
663            }
664            log_info!("waiting on process terminated signals");
665            futures::future::join_all(terminated_signals).await;
666        }
667
668        // Step 6: Forcibly unmounts the mounts' FileSystems.
669        log_info!("clearing mounts");
670        self.mounts.clear();
671
672        // Step 7: Tell CF the container stopped.
673        log_info!("all non-root processes killed, notifying CF container is stopped");
674        if let Some(control_handle) = self.container_control_handle.lock().take() {
675            log_info!("Notifying CF that the container has stopped.");
676            control_handle
677                .send_on_stop(ComponentStopInfo {
678                    termination_status: Some(zx::Status::OK.into_raw()),
679                    exit_code: Some(0),
680                    ..ComponentStopInfo::default()
681                })
682                .unwrap();
683            control_handle.shutdown_with_epitaph(zx::Status::OK);
684        } else {
685            log_warn!("Shutdown invoked without a container controller control handle.");
686        }
687
688        // Step 8: exiting this process.
689        log_info!("All tasks killed, exiting Starnix kernel root process.");
690        // Normally a Rust program exits its process by calling `std::process::exit()` which goes
691        // through libc to exit the program. This runs drop impls on any thread-local variables
692        // which can cause issues during Starnix shutdown when we haven't yet integrated every
693        // subsystem with the shutdown flow. While those issues are indicative of underlying
694        // problems, we can't solve them without finishing the implementation of graceful shutdown.
695        // Instead, ask Zircon to exit our process directly, bypassing any libc atexit handlers.
696        // TODO(https://fxbug.dev/295073633) return from main instead of avoiding atexit handlers
697        zx::Process::exit(0);
698    }
699
700    pub fn is_shutting_down(&self) -> bool {
701        self.shutting_down.load(Ordering::Acquire)
702    }
703
704    /// Opens a device file (driver) identified by `dev`.
705    pub fn open_device<L>(
706        &self,
707        locked: &mut Locked<L>,
708        current_task: &CurrentTask,
709        node: &NamespaceNode,
710        flags: OpenFlags,
711        dev: DeviceId,
712        mode: DeviceMode,
713    ) -> Result<Box<dyn FileOps>, Errno>
714    where
715        L: LockEqualOrBefore<FileOpsCore>,
716    {
717        self.device_registry.open_device(locked, current_task, node, flags, dev, mode)
718    }
719
720    /// Return a reference to the Audit Framework
721    ///
722    /// This function follows the lazy initialization pattern.
723    pub fn audit_logger(&self) -> Arc<AuditLogger> {
724        self.expando.get_or_init(|| AuditLogger::new(self))
725    }
726
727    /// Return a reference to the GenericNetlink implementation.
728    ///
729    /// This function follows the lazy initialization pattern, where the first
730    /// call will instantiate the Generic Netlink server in a separate kthread.
731    pub fn generic_netlink(&self) -> &GenericNetlink<NetlinkToClientSender<GenericMessage>> {
732        self.generic_netlink.get_or_init(|| {
733            let (generic_netlink, worker_params) = GenericNetlink::new();
734            let enable_nl80211 = self.features.wifi;
735            self.kthreads.spawn_future(
736                move || async move {
737                    crate::vfs::socket::run_generic_netlink_worker(worker_params, enable_nl80211)
738                        .await;
739                    log_error!("Generic Netlink future unexpectedly exited");
740                },
741                "generic_netlink_worker",
742            );
743            generic_netlink
744        })
745    }
746
747    /// Return a reference to the [`netlink::Netlink`] implementation.
748    ///
749    /// This function follows the lazy initialization pattern, where the first
750    /// call will instantiate the Netlink implementation.
751    pub fn network_netlink(self: &Arc<Self>) -> &Netlink<NetlinkContextImpl> {
752        self.network_netlink.get_or_init(|| {
753            let (network_netlink, worker_params) =
754                Netlink::new(InterfacesHandlerImpl(self.weak_self.clone()));
755
756            let kernel = self.clone();
757            self.kthreads.spawn_future(
758                move || async move {
759                    netlink::run_netlink_worker(
760                        worker_params,
761                        NetlinkAccessControl::new(kernel.kthreads.system_task()),
762                    )
763                    .await;
764                    log_error!(tag = NETLINK_LOG_TAG; "Netlink async worker unexpectedly exited");
765                },
766                "network_netlink_worker",
767            );
768            network_netlink
769        })
770    }
771
772    pub fn iptables(&self) -> &IpTables {
773        self.iptables.get_or_init(|| IpTables::new())
774    }
775
776    /// Returns a Proxy to the service used by the container at `filename`.
777    #[allow(unused)]
778    pub fn connect_to_named_protocol_at_container_svc<P: ProtocolMarker>(
779        &self,
780        filename: &str,
781    ) -> Result<ClientEnd<P>, Errno> {
782        match self.container_namespace.get_namespace_channel("/svc") {
783            Ok(channel) => {
784                let (client_end, server_end) = create_endpoints::<P>();
785                fdio::service_connect_at(channel.as_ref(), filename, server_end.into_channel())
786                    .map_err(|status| from_status_like_fdio!(status))?;
787                Ok(client_end)
788            }
789            Err(err) => {
790                log_error!("Unable to get /svc namespace channel! {}", err);
791                Err(errno!(ENOENT))
792            }
793        }
794    }
795
796    /// Returns a Proxy to the service `P` used by the container.
797    pub fn connect_to_protocol_at_container_svc<P: DiscoverableProtocolMarker>(
798        &self,
799    ) -> Result<ClientEnd<P>, Errno> {
800        self.connect_to_named_protocol_at_container_svc::<P>(P::PROTOCOL_NAME)
801    }
802
803    pub fn add_syscall_log_filter(&self, name: &str) {
804        let filter = SyscallLogFilter::new(name.to_string());
805        {
806            let mut filters = self.syscall_log_filters.lock();
807            if filters.contains(&filter) {
808                return;
809            }
810            filters.push(filter);
811        }
812        for headers in self.pids.read().get_thread_groups() {
813            headers.sync_syscall_log_level();
814        }
815    }
816
817    pub fn clear_syscall_log_filters(&self) {
818        {
819            let mut filters = self.syscall_log_filters.lock();
820            if filters.is_empty() {
821                return;
822            }
823            filters.clear();
824        }
825        for headers in self.pids.read().get_thread_groups() {
826            headers.sync_syscall_log_level();
827        }
828    }
829
830    fn get_thread_groups_inspect(&self) -> fuchsia_inspect::Inspector {
831        let inspector = fuchsia_inspect::Inspector::default();
832
833        let thread_groups = inspector.root();
834        let mut mm_summary = MappingSummary::default();
835        let mut mms_summarized = HashSet::new();
836
837        // Avoid holding locks for the entire iteration.
838        let all_thread_groups = {
839            let pid_table = self.pids.read();
840            pid_table.get_thread_groups().collect::<Vec<_>>()
841        };
842        for thread_group in all_thread_groups {
843            // Avoid holding the state lock while summarizing.
844            let (ppid, tasks) = {
845                let tg = thread_group.read();
846                (tg.get_ppid() as i64, tg.tasks().map(TempRef::into_static).collect::<Vec<_>>())
847            };
848
849            let tg_node = thread_groups.create_child(format!("{}", thread_group.leader));
850            if let Ok(koid) = &thread_group.process.koid() {
851                tg_node.record_int("koid", koid.raw_koid() as i64);
852            }
853            tg_node.record_int("pid", thread_group.leader as i64);
854            tg_node.record_int("ppid", ppid);
855            tg_node.record_bool("stopped", thread_group.load_stopped() == StopState::GroupStopped);
856
857            let tasks_node = tg_node.create_child("tasks");
858            for task in tasks {
859                if let Ok(mm) = task.mm() {
860                    if mms_summarized.insert(Arc::as_ptr(&mm) as usize) {
861                        mm.summarize(&mut mm_summary);
862                    }
863                }
864                let set_properties = |node: &fuchsia_inspect::Node| {
865                    node.record_string("command", task.command().to_string());
866
867                    let scheduler_state = task.read().scheduler_state;
868                    if !scheduler_state.is_default() {
869                        node.record_child("sched", |node| {
870                            node.record_string(
871                                "role_name",
872                                self.scheduler
873                                    .role_name(&task)
874                                    .map(|n| Cow::Borrowed(n))
875                                    .unwrap_or_else(|e| Cow::Owned(e.to_string())),
876                            );
877                            node.record_string("state", format!("{scheduler_state:?}"));
878                        });
879                    }
880                };
881                if task.tid == thread_group.leader {
882                    let mut argv = task.read_argv(256).unwrap_or_default();
883
884                    // Any runtime that overwrites argv is likely to leave a lot of trailing
885                    // nulls, no need to print those in inspect.
886                    argv.retain(|arg| !arg.is_empty());
887
888                    let inspect_argv = tg_node.create_string_array("argv", argv.len());
889                    for (i, arg) in argv.iter().enumerate() {
890                        inspect_argv.set(i, arg.to_string());
891                    }
892                    tg_node.record(inspect_argv);
893
894                    set_properties(&tg_node);
895                } else {
896                    tasks_node.record_child(task.tid.to_string(), |task_node| {
897                        set_properties(task_node);
898                    });
899                };
900            }
901            tg_node.record(tasks_node);
902            thread_groups.record(tg_node);
903        }
904
905        thread_groups.record_child("memory_managers", |node| mm_summary.record(node));
906
907        inspector
908    }
909
910    pub fn new_memory_attribution_observer(
911        &self,
912        control_handle: fattribution::ProviderControlHandle,
913    ) -> attribution_server::Observer {
914        self.memory_attribution_manager.new_observer(control_handle)
915    }
916
917    /// Opens and returns a directory proxy from the container's namespace, at
918    /// the requested path, using the provided flags. This method will open the
919    /// closest existing path from the namespace hierarchy, and then attempt
920    /// initialize an open on the remaining subdirectory path, using the given open_flags.
921    ///
922    /// For example, given the parameter provided is `/path/to/foo/bar` and there
923    /// are namespace entries already for `/path/to/foo` and `/path/to`. The entry
924    /// for /path/to/foo will be opened, and then the /bar will attempt to be opened
925    /// underneath that directory with the given open_flags. The returned value
926    /// will be the proxy to the parent (/path/to/foo) and the string to the child
927    /// path (/bar). The caller of this method can expect /bar to be initialized.
928    pub fn open_ns_dir(
929        &self,
930        path: &str,
931        open_flags: fio::Flags,
932    ) -> Result<(fio::DirectorySynchronousProxy, String), Errno> {
933        let ns_path = PathBuf::from(path);
934        match self.container_namespace.find_closest_channel(&ns_path) {
935            Ok((root_channel, remaining_subdir)) => {
936                let (_, server_end) = create_endpoints::<fio::DirectoryMarker>();
937                fdio::open_at(
938                    &root_channel,
939                    &remaining_subdir,
940                    open_flags,
941                    server_end.into_channel(),
942                )
943                .map_err(|e| {
944                    log_error!("Failed to intialize the subdirs: {}", e);
945                    errno!(EIO)
946                })?;
947
948                Ok((fio::DirectorySynchronousProxy::new(root_channel), remaining_subdir))
949            }
950            Err(err) => {
951                log_error!(
952                    "Unable to find a channel for {}. Received error: {}",
953                    ns_path.display(),
954                    err
955                );
956                Err(errno!(ENOENT))
957            }
958        }
959    }
960
961    /// Returns an iterator of the command line arguments.
962    pub fn cmdline_args_iter(&self) -> impl Iterator<Item = ArgNameAndValue<'_>> {
963        parse_cmdline(self.cmdline.to_str().unwrap_or_default()).filter_map(|arg| {
964            arg.split_once('=')
965                .map(|(name, value)| ArgNameAndValue { name: name, value: Some(value) })
966                .or(Some(ArgNameAndValue { name: arg, value: None }))
967        })
968    }
969
970    /// Returns the container-configured CacheConfig.
971    pub fn fs_cache_config(&self) -> CacheConfig {
972        CacheConfig { capacity: self.features.dirent_cache_size as usize }
973    }
974}
975
976pub fn parse_cmdline(cmdline: &str) -> impl Iterator<Item = &str> {
977    let mut args = Vec::new();
978    let mut arg_start: Option<usize> = None;
979    let mut in_quotes = false;
980    let mut previous_char = ' ';
981
982    for (i, c) in cmdline.char_indices() {
983        if let Some(start) = arg_start {
984            match c {
985                ' ' if !in_quotes => {
986                    args.push(&cmdline[start..i]);
987                    arg_start = None;
988                }
989                '"' if previous_char != '\\' => {
990                    in_quotes = !in_quotes;
991                }
992                _ => {}
993            }
994        } else if c != ' ' {
995            arg_start = Some(i);
996            if c == '"' {
997                in_quotes = true;
998            }
999        }
1000        previous_char = c;
1001    }
1002    if let Some(start) = arg_start {
1003        args.push(&cmdline[start..]);
1004    }
1005    args.into_iter()
1006}
1007
1008impl std::fmt::Debug for Kernel {
1009    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1010        f.debug_struct("Kernel").finish()
1011    }
1012}
1013
1014// TODO(https://fxbug.dev/380427153): move arch dependent code to `kernel/core/arch/*`.
1015#[cfg(target_arch = "aarch64")]
1016fn arm32_hwcap(cpu_feature_flags: CpuFeatureFlags) -> HwCap {
1017    use starnix_uapi::arch32;
1018    const COMPAT_ARM32_ELF_HWCAP: u32 = arch32::HWCAP_HALF
1019        | arch32::HWCAP_THUMB
1020        | arch32::HWCAP_FAST_MULT
1021        | arch32::HWCAP_EDSP
1022        | arch32::HWCAP_TLS
1023        | arch32::HWCAP_IDIV // == IDIVA | IDIVT.
1024        | arch32::HWCAP_LPAE
1025        | arch32::HWCAP_EVTSTRM;
1026
1027    let mut hwcap = COMPAT_ARM32_ELF_HWCAP;
1028    let mut hwcap2 = 0;
1029    for feature in cpu_feature_flags.iter() {
1030        match feature {
1031            CpuFeatureFlags::ARM64_FEATURE_ISA_ASIMD => hwcap |= arch32::HWCAP_NEON,
1032            CpuFeatureFlags::ARM64_FEATURE_ISA_AES => hwcap2 |= arch32::HWCAP2_AES,
1033            CpuFeatureFlags::ARM64_FEATURE_ISA_PMULL => hwcap2 |= arch32::HWCAP2_PMULL,
1034            CpuFeatureFlags::ARM64_FEATURE_ISA_SHA1 => hwcap2 |= arch32::HWCAP2_SHA1,
1035            CpuFeatureFlags::ARM64_FEATURE_ISA_SHA256 => hwcap2 |= arch32::HWCAP2_SHA2,
1036            CpuFeatureFlags::ARM64_FEATURE_ISA_CRC32 => hwcap2 |= arch32::HWCAP2_CRC32,
1037            CpuFeatureFlags::ARM64_FEATURE_ISA_I8MM => hwcap |= arch32::HWCAP_I8MM,
1038            CpuFeatureFlags::ARM64_FEATURE_ISA_FHM => hwcap |= arch32::HWCAP_ASIMDFHM,
1039            CpuFeatureFlags::ARM64_FEATURE_ISA_DP => hwcap |= arch32::HWCAP_ASIMDDP,
1040            CpuFeatureFlags::ARM64_FEATURE_ISA_FP => {
1041                hwcap |= arch32::HWCAP_VFP | arch32::HWCAP_VFPv3 | arch32::HWCAP_VFPv4
1042            }
1043            _ => {}
1044        }
1045    }
1046    HwCap { hwcap, hwcap2 }
1047}
1048
1049#[cfg(target_arch = "aarch64")]
1050fn arm64_hwcap(cpu_feature_flags: CpuFeatureFlags) -> HwCap {
1051    // See https://docs.kernel.org/arch/arm64/elf_hwcaps.html for details.
1052    use starnix_uapi;
1053    let mut hwcap = 0;
1054    let mut hwcap2 = 0;
1055
1056    for feature in cpu_feature_flags.iter() {
1057        match feature {
1058            CpuFeatureFlags::ARM64_FEATURE_ISA_FP => hwcap |= starnix_uapi::HWCAP_FP,
1059            CpuFeatureFlags::ARM64_FEATURE_ISA_ASIMD => hwcap |= starnix_uapi::HWCAP_ASIMD,
1060            CpuFeatureFlags::ARM64_FEATURE_ISA_AES => hwcap |= starnix_uapi::HWCAP_AES,
1061            CpuFeatureFlags::ARM64_FEATURE_ISA_PMULL => hwcap |= starnix_uapi::HWCAP_PMULL,
1062            CpuFeatureFlags::ARM64_FEATURE_ISA_SHA1 => hwcap |= starnix_uapi::HWCAP_SHA1,
1063            CpuFeatureFlags::ARM64_FEATURE_ISA_SHA256 => hwcap |= starnix_uapi::HWCAP_SHA2,
1064            CpuFeatureFlags::ARM64_FEATURE_ISA_CRC32 => hwcap |= starnix_uapi::HWCAP_CRC32,
1065            CpuFeatureFlags::ARM64_FEATURE_ISA_I8MM => hwcap2 |= starnix_uapi::HWCAP2_I8MM,
1066            CpuFeatureFlags::ARM64_FEATURE_ISA_FHM => hwcap |= starnix_uapi::HWCAP_ASIMDFHM,
1067            CpuFeatureFlags::ARM64_FEATURE_ISA_DP => hwcap |= starnix_uapi::HWCAP_ASIMDDP,
1068            CpuFeatureFlags::ARM64_FEATURE_ISA_SM3 => hwcap |= starnix_uapi::HWCAP_SM3,
1069            CpuFeatureFlags::ARM64_FEATURE_ISA_SM4 => hwcap |= starnix_uapi::HWCAP_SM4,
1070            CpuFeatureFlags::ARM64_FEATURE_ISA_SHA3 => hwcap |= starnix_uapi::HWCAP_SHA3,
1071            CpuFeatureFlags::ARM64_FEATURE_ISA_SHA512 => hwcap |= starnix_uapi::HWCAP_SHA512,
1072            CpuFeatureFlags::ARM64_FEATURE_ISA_ATOMICS => hwcap |= starnix_uapi::HWCAP_ATOMICS,
1073            CpuFeatureFlags::ARM64_FEATURE_ISA_RDM => hwcap |= starnix_uapi::HWCAP_ASIMDRDM,
1074            CpuFeatureFlags::ARM64_FEATURE_ISA_TS => hwcap |= starnix_uapi::HWCAP_FLAGM,
1075            CpuFeatureFlags::ARM64_FEATURE_ISA_DPB => hwcap |= starnix_uapi::HWCAP_DCPOP,
1076            CpuFeatureFlags::ARM64_FEATURE_ISA_RNDR => hwcap2 |= starnix_uapi::HWCAP2_RNG,
1077            _ => {}
1078        }
1079    }
1080    HwCap { hwcap, hwcap2 }
1081}
1082
1083impl HwCaps {
1084    #[cfg(target_arch = "aarch64")]
1085    pub fn from_cpu_feature_flags(cpu_feature_flags: CpuFeatureFlags) -> Self {
1086        Self { arch32: arm32_hwcap(cpu_feature_flags), arch64: arm64_hwcap(cpu_feature_flags) }
1087    }
1088
1089    #[cfg(not(target_arch = "aarch64"))]
1090    pub fn from_cpu_feature_flags(_cpu_feature_flags: CpuFeatureFlags) -> Self {
1091        Self { arch64: HwCap::default() }
1092    }
1093}
1094
1095#[cfg(test)]
1096mod test {
1097    use super::parse_cmdline;
1098
1099    #[test]
1100    fn test_parse_cmdline() {
1101        let cmdline =
1102            r#"first second=third "fourth fifth" sixth="seventh eighth" "ninth\" tenth" eleventh"#;
1103        let expected = vec![
1104            "first",
1105            "second=third",
1106            "\"fourth fifth\"",
1107            "sixth=\"seventh eighth\"",
1108            "\"ninth\\\" tenth\"",
1109            "eleventh",
1110        ];
1111        assert_eq!(parse_cmdline(cmdline).collect::<Vec<_>>(), expected);
1112    }
1113}