Skip to main content

starnix_kernel_runner/
container.rs

1// Copyright 2028 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::{
6    Features, MountAction, expose_root, parse_features, parse_numbered_handles,
7    run_container_features, serve_component_runner, serve_container_controller,
8    serve_graphical_presenter, serve_lutex_controller,
9};
10use anyhow::{Context, Error, anyhow, bail};
11use bootreason::get_or_init_android_bootreason;
12use bstr::{BString, ByteSlice};
13use devicetree::parser::parse_devicetree;
14use devicetree::types::Devicetree;
15use fidl::endpoints::{RequestStream, ServerEnd};
16use fidl_fuchsia_boot as fboot;
17use fidl_fuchsia_component as fcomponent;
18use fidl_fuchsia_component_runner as frunner;
19use fidl_fuchsia_component_runner::{TaskProviderRequest, TaskProviderRequestStream};
20use fidl_fuchsia_element as felement;
21use fidl_fuchsia_feedback::CrashReporterMarker;
22use fidl_fuchsia_io as fio;
23use fidl_fuchsia_mem as fmem;
24use fidl_fuchsia_memory_attribution as fattribution;
25use fidl_fuchsia_starnix_binder as fbinder;
26use fidl_fuchsia_starnix_container as fstarcontainer;
27use fidl_fuchsia_sysinfo as fsysinfo;
28use fidl_fuchsia_time_external::AdjustMarker;
29use fuchsia_async as fasync;
30use fuchsia_async::DurationExt;
31use fuchsia_component::client::{connect_to_protocol, connect_to_protocol_sync};
32use fuchsia_component::server::ServiceFs;
33use fuchsia_inspect as inspect;
34use fuchsia_runtime as fruntime;
35use futures::channel::oneshot;
36use futures::{FutureExt, StreamExt, TryStreamExt};
37use serde::Deserialize;
38use starnix_container_structured_config::Config as ContainerStructuredConfig;
39use starnix_core::device::remote_block_device::remote_block_device_init;
40use starnix_core::execution::{
41    create_init_process, create_system_task, execute_task_with_prerun_result,
42};
43use starnix_core::fs::fuchsia::new_remotefs_in_root;
44use starnix_core::fs::tmpfs::TmpFs;
45use starnix_core::security;
46use starnix_core::task::container_namespace::ContainerNamespace;
47use starnix_core::task::{
48    CurrentTask, ExitStatus, Kernel, RoleOverrides, SchedulerManager, parse_cmdline,
49};
50use starnix_core::vfs::{FileSystemOptions, FsContext, LookupContext, Namespace, WhatToMount};
51use starnix_logging::{
52    CATEGORY_STARNIX, NAME_CREATE_CONTAINER, log_debug, log_error, log_info, log_warn,
53};
54use starnix_modules::{
55    init_common_devices, register_common_file_systems, register_common_syscalls,
56};
57use starnix_modules_layeredfs::{LayeredFsBuilder, LayeredFsMounts};
58use starnix_modules_magma::get_magma_params;
59use starnix_modules_overlayfs::OverlayStack;
60use starnix_modules_rtc::rtc_device_init;
61
62use starnix_task_command::TaskCommand;
63use starnix_uapi::errors::{ENOENT, SourceContext};
64use starnix_uapi::open_flags::OpenFlags;
65use starnix_uapi::resource_limits::Resource;
66use starnix_uapi::{errno, tid_t};
67use std::ffi::CString;
68
69use std::sync::Arc;
70use zx::Task as _;
71
72use std::sync::Weak;
73
74use crate::serve_memory_attribution_provider_container;
75use attribution_server::{AttributionServer, AttributionServerHandle};
76
77/// Manages the memory attribution protocol for a Starnix container.
78struct ContainerMemoryAttributionManager {
79    /// Holds state for the hanging-get attribution protocol.
80    memory_attribution_server: AttributionServerHandle,
81}
82
83impl ContainerMemoryAttributionManager {
84    /// Creates a new [ContainerMemoryAttributionManager] from a Starnix kernel and the moniker
85    /// token of the container component.
86    pub fn new(kernel: Weak<Kernel>, component_instance: zx::Event) -> Self {
87        let memory_attribution_server = AttributionServer::new(Box::new(move || {
88            let kernel_ref = match kernel.upgrade() {
89                None => return vec![],
90                Some(k) => k,
91            };
92            attribution_info_for_kernel(kernel_ref.as_ref(), &component_instance)
93        }));
94
95        ContainerMemoryAttributionManager { memory_attribution_server }
96    }
97
98    /// Creates a new observer for the attribution information from this container.
99    pub fn new_observer(
100        &self,
101        control_handle: fattribution::ProviderControlHandle,
102    ) -> attribution_server::Observer {
103        self.memory_attribution_server.new_observer(control_handle)
104    }
105}
106
107/// Generates the attribution information for the Starnix kernel ELF component. The attribution
108/// information for the container is handled by the container component, not the kernel
109/// component itself, even if both are hosted within the same kernel process.
110fn attribution_info_for_kernel(
111    kernel: &Kernel,
112    component_instance: &zx::Event,
113) -> Vec<fattribution::AttributionUpdate> {
114    // Start the server to handle the memory attribution requests for the container, and provide
115    // a handle to get detailed attribution. We start a new task as each incoming connection is
116    // independent.
117    let (client_end, server_end) =
118        fidl::endpoints::create_request_stream::<fattribution::ProviderMarker>();
119    fuchsia_async::Task::spawn(serve_memory_attribution_provider_container(server_end, kernel))
120        .detach();
121
122    let starnix_kernel_id = Some(1);
123    let starnix_kernel_principal = fattribution::NewPrincipal {
124        identifier: starnix_kernel_id,
125        description: Some(fattribution::Description::Part("starnix_kernel".to_string())),
126        principal_type: Some(fattribution::PrincipalType::Part),
127        // This part is created for accounting. It holds the resource used for starnix
128        // kernel operation. It neither has sub-principals, nor publishes attribution,
129        // hence it does not need to be tied to a provider server end.
130        detailed_attribution: None,
131        ..Default::default()
132    };
133
134    let starnix_kernel_attribution = fattribution::UpdatedPrincipal {
135        identifier: starnix_kernel_id, // Recipient.
136        resources: Some(fattribution::Resources::Data(fattribution::Data {
137            resources: vec![fattribution::Resource::ProcessMapped(fattribution::ProcessMapped {
138                process: fuchsia_runtime::process_self().koid().unwrap().raw_koid(),
139                base: 0, // Attribute all the range.
140                len: u64::max_value(),
141                hint_skip_handle_table: false,
142            })],
143        })),
144        ..Default::default()
145    };
146
147    let container_id = Some(2);
148    let new_principal = fattribution::NewPrincipal {
149        identifier: container_id,
150        description: Some(fattribution::Description::Component(
151            component_instance.duplicate_handle(zx::Rights::SAME_RIGHTS).unwrap(),
152        )),
153        principal_type: Some(fattribution::PrincipalType::Runnable),
154        detailed_attribution: Some(client_end),
155        ..Default::default()
156    };
157    let attribution = fattribution::UpdatedPrincipal {
158        identifier: container_id,
159        resources: Some(fattribution::Resources::Data(fattribution::Data {
160            resources: vec![fattribution::Resource::KernelObject(
161                fuchsia_runtime::job_default().koid().unwrap().raw_koid(),
162            )],
163        })),
164        ..Default::default()
165    };
166
167    vec![
168        fattribution::AttributionUpdate::Add(new_principal),
169        fattribution::AttributionUpdate::Add(starnix_kernel_principal),
170        fattribution::AttributionUpdate::Update(attribution),
171        fattribution::AttributionUpdate::Update(starnix_kernel_attribution),
172    ]
173}
174
175#[derive(Debug)]
176pub struct ContainerStartInfo {
177    /// Configuration specified by the component's `program` block.
178    pub program: ContainerProgram,
179
180    pub config: ContainerStructuredConfig,
181
182    /// The outgoing directory of the container, used to serve protocols on behalf of the container.
183    /// For example, the starnix_kernel serves a component runner in the containers' outgoing
184    /// directory.
185    outgoing_dir: Option<zx::Channel>,
186
187    /// Mapping of top-level namespace entries to an associated channel.
188    /// For example, "/svc" to the respective channel.
189    pub container_namespace: ContainerNamespace,
190
191    /// The runtime directory of the container, used to provide CF introspection.
192    runtime_dir: Option<ServerEnd<fio::DirectoryMarker>>,
193
194    /// An eventpair that debuggers can use to defer the launch of the container.
195    break_on_start: Option<zx::EventPair>,
196
197    /// Component moniker token for the container component. This token is used in various protocols
198    /// to uniquely identify a component.
199    component_instance: Option<zx::Event>,
200}
201
202const MISSING_CONFIG_VMO_CONTEXT: &str = concat!(
203    "Retrieving container config VMO. ",
204    "If this fails, make sure your container CML includes ",
205    "//src/starnix/containers/container.shard.cml.",
206);
207
208impl ContainerStartInfo {
209    fn new(mut start_info: frunner::ComponentStartInfo) -> Result<Self, Error> {
210        let program = start_info.program.as_ref().context("retrieving program block")?;
211        let program: ContainerProgram =
212            runner::serde::deserialize_program(&program).context("parsing program block")?;
213
214        let encoded_config =
215            start_info.encoded_config.as_ref().context(MISSING_CONFIG_VMO_CONTEXT)?;
216        let config = match encoded_config {
217            fmem::Data::Bytes(b) => ContainerStructuredConfig::from_bytes(b),
218            fmem::Data::Buffer(b) => ContainerStructuredConfig::from_vmo(&b.vmo),
219            other => anyhow::bail!("unknown Data variant {other:?}"),
220        }
221        .context("parsing container structured config")?;
222
223        let ns = start_info.ns.take().context("retrieving container namespace")?;
224        let container_namespace = ContainerNamespace::from(ns);
225
226        let outgoing_dir = start_info.outgoing_dir.take().map(|dir| dir.into_channel());
227        let component_instance = start_info.component_instance;
228
229        Ok(Self {
230            program,
231            config,
232            outgoing_dir,
233            container_namespace,
234            component_instance,
235            break_on_start: start_info.break_on_start,
236            runtime_dir: start_info.runtime_dir,
237        })
238    }
239}
240
241#[derive(Debug, Default, Deserialize)]
242#[serde(deny_unknown_fields)]
243pub struct ContainerProgram {
244    /// The name of this container.
245    name: String,
246
247    /// The command line for the initial process for this container.
248    init: Vec<String>,
249
250    /// The command line for the kernel.
251    #[serde(default)]
252    kernel_cmdline: String,
253
254    /// The specifications for the file system mounts for this container.
255    #[serde(default)]
256    mounts: Vec<String>,
257
258    /// The features enabled for this container.
259    #[serde(default)]
260    pub features: Vec<String>,
261
262    /// The resource limits to apply to this container.
263    #[serde(default)]
264    rlimits: Vec<String>,
265
266    /// The path that the container will wait until exists before considering itself to have started.
267    #[serde(default)]
268    startup_file_path: String,
269
270    /// The default seclabel that is applied to components that are instantiated in this container.
271    ///
272    /// Components can override this by setting the `seclabel` field in their program block.
273    #[serde(default)]
274    pub default_seclabel: Option<String>,
275
276    /// The default uid that is applied to components that are instantiated in this container.
277    ///
278    /// Components can override this by setting the `uid` field in their program block.
279    #[serde(default = "default_uid")]
280    pub default_uid: runner::serde::StoreAsString<u32>,
281
282    /// The default mount options to use when mounting directories from a component's namespace.
283    ///
284    /// Each string is expected to follow the format: "<namespace_path>:<mount_options>".
285    pub default_ns_mount_options: Option<Vec<String>>,
286
287    /// Specifies role names to use for "realtime" tasks based on their process & thread names.
288    ///
289    /// Zircon's scheduler doesn't support configuring tasks to always preempt non-"realtime"
290    /// tasks without specifying a constant bandwidth profile. These profiles specify the period and
291    /// expected runtime of a "realtime" task, bounding the amount of work it is allowed to perform
292    /// at an elevated "realtime" priority.
293    ///
294    /// Because constant bandwidth profiles require workload-specific tuning, we can't uniformly
295    /// apply a single profile for all "realtime" tasks. Instead, this container configuration
296    /// allows us to specify different constant bandwidth profiles for different workloads.
297    #[serde(default)]
298    task_role_overrides: Vec<TaskSchedulerMapping>,
299}
300
301/// Specifies a role override for a class of tasks whose process and thread names match provided
302/// patterns.
303#[derive(Default, Deserialize)]
304struct TaskSchedulerMapping {
305    /// The role name to use for tasks matching the provided patterns.
306    role: String,
307    /// A regular expression that will be matched against the process' command.
308    process: String,
309    /// A regular expression that will be matched against the thread's command.
310    thread: String,
311    /// An optional regular expression that will be matched against the task's cgroup path.
312    cgroup: Option<String>,
313}
314
315impl std::fmt::Debug for TaskSchedulerMapping {
316    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
317        write!(
318            f,
319            "process `{}` thread `{}` cgroup `{:?}` role `{}`",
320            self.process, self.thread, self.cgroup, self.role
321        )
322    }
323}
324
325fn default_uid() -> runner::serde::StoreAsString<u32> {
326    runner::serde::StoreAsString(42)
327}
328
329// Creates a CString from a String. Calling this with an invalid CString will panic.
330fn to_cstr(str: &str) -> CString {
331    CString::new(str.to_string()).unwrap()
332}
333
334#[must_use = "The container must run serve on this config"]
335pub struct ContainerServiceConfig {
336    start_info: ContainerStartInfo,
337    request_stream: frunner::ComponentControllerRequestStream,
338    receiver: oneshot::Receiver<Result<ExitStatus, Error>>,
339}
340
341pub struct Container {
342    /// The `Kernel` object that is associated with the container.
343    pub kernel: Arc<Kernel>,
344
345    memory_attribution_manager: ContainerMemoryAttributionManager,
346
347    /// Inspect node holding information about the state of the container.
348    _node: inspect::Node,
349
350    /// Until negative trait bound are implemented, using `*mut u8` to prevent transferring
351    /// Container across threads.
352    _thread_bound: std::marker::PhantomData<*mut u8>,
353}
354
355impl Container {
356    pub fn system_task(&self) -> &CurrentTask {
357        self.kernel.kthreads.system_task()
358    }
359
360    async fn serve_outgoing_directory(
361        &self,
362        outgoing_dir: Option<zx::Channel>,
363    ) -> Result<(), Error> {
364        if let Some(outgoing_dir) = outgoing_dir {
365            // Add `ComponentRunner` to the exposed services of the container, and then serve the
366            // outgoing directory.
367            let mut fs = ServiceFs::new_local();
368            fs.dir("svc")
369                .add_fidl_service(ExposedServices::ComponentRunner)
370                .add_fidl_service(ExposedServices::ContainerController)
371                .add_fidl_service(ExposedServices::GraphicalPresenter)
372                .add_fidl_service(ExposedServices::LutexController);
373
374            // Expose the root of the container's filesystem.
375            let (fs_root, fs_root_server_end) = fidl::endpoints::create_proxy();
376            fs.add_remote("fs_root", fs_root);
377            expose_root(self.system_task(), fs_root_server_end)?;
378
379            fs.serve_connection(outgoing_dir.into()).map_err(|_| errno!(EINVAL))?;
380
381            fs.for_each_concurrent(None, |request_stream| async {
382                match request_stream {
383                    ExposedServices::ComponentRunner(request_stream) => {
384                        match serve_component_runner(request_stream, self.system_task()).await {
385                            Ok(_) => {}
386                            Err(e) => {
387                                log_error!("Error serving component runner: {:?}", e);
388                            }
389                        }
390                    }
391                    ExposedServices::ContainerController(request_stream) => {
392                        serve_container_controller(request_stream, self.system_task())
393                            .await
394                            .expect("failed to start container.")
395                    }
396                    ExposedServices::GraphicalPresenter(request_stream) => {
397                        serve_graphical_presenter(request_stream, &self.kernel)
398                            .await
399                            .expect("failed to start GraphicalPresenter.")
400                    }
401                    ExposedServices::LutexController(request_stream) => {
402                        serve_lutex_controller(request_stream, self.system_task())
403                            .await
404                            .expect("failed to start LutexController.")
405                    }
406                }
407            })
408            .await
409        }
410        Ok(())
411    }
412
413    pub async fn serve(&self, service_config: ContainerServiceConfig) -> Result<(), Error> {
414        let (r, _) = futures::join!(
415            self.serve_outgoing_directory(service_config.start_info.outgoing_dir),
416            server_component_controller(
417                self.kernel.clone(),
418                service_config.request_stream,
419                service_config.receiver
420            )
421        );
422        r
423    }
424
425    pub fn new_memory_attribution_observer(
426        &self,
427        control_handle: fattribution::ProviderControlHandle,
428    ) -> attribution_server::Observer {
429        self.memory_attribution_manager.new_observer(control_handle)
430    }
431}
432
433/// The services that are exposed in the container component's outgoing directory.
434enum ExposedServices {
435    ComponentRunner(frunner::ComponentRunnerRequestStream),
436    ContainerController(fstarcontainer::ControllerRequestStream),
437    GraphicalPresenter(felement::GraphicalPresenterRequestStream),
438    LutexController(fbinder::LutexControllerRequestStream),
439}
440
441type TaskResult = Result<ExitStatus, Error>;
442
443async fn server_component_controller(
444    kernel: Arc<Kernel>,
445    request_stream: frunner::ComponentControllerRequestStream,
446    task_complete: oneshot::Receiver<TaskResult>,
447) {
448    *kernel.container_control_handle.lock() = Some(request_stream.control_handle());
449
450    enum Event<T, U> {
451        Controller(T),
452        Completion(U),
453    }
454
455    let mut stream = futures::stream::select(
456        request_stream.map(Event::Controller),
457        task_complete.into_stream().map(Event::Completion),
458    );
459
460    while let Some(event) = stream.next().await {
461        match event {
462            Event::Controller(Ok(frunner::ComponentControllerRequest::Stop { .. })) => {
463                log_info!("Stopping the container.");
464            }
465            Event::Controller(Ok(frunner::ComponentControllerRequest::Kill { control_handle })) => {
466                log_info!("Killing the container's job.");
467                control_handle.shutdown_with_epitaph(zx::Status::from_raw(
468                    fcomponent::Error::InstanceDied.into_primitive() as i32,
469                ));
470                fruntime::job_default().kill().expect("Failed to kill job");
471            }
472            Event::Controller(Ok(frunner::ComponentControllerRequest::_UnknownMethod {
473                ordinal,
474                method_type,
475                ..
476            })) => {
477                log_error!(ordinal, method_type:?; "Unknown component controller request received.");
478            }
479            Event::Controller(Err(e)) => {
480                log_warn!(e:?; "Container component controller channel encountered an error.");
481            }
482            Event::Completion(result) => {
483                log_info!(result:?; "init process exited.");
484            }
485        }
486
487        // We treat any event in the stream as an invitation to shut down.
488        if !kernel.is_shutting_down() {
489            kernel.shut_down();
490        }
491    }
492
493    log_debug!("done listening for container-terminating events");
494
495    // In case the stream ended without an event, shut down the kernel here.
496    if !kernel.is_shutting_down() {
497        kernel.shut_down();
498    }
499}
500
501pub async fn create_component_from_stream(
502    mut request_stream: frunner::ComponentRunnerRequestStream,
503    kernel_extra_features: Vec<String>,
504) -> Result<(Container, ContainerServiceConfig), Error> {
505    if let Some(event) = request_stream.try_next().await? {
506        match event {
507            frunner::ComponentRunnerRequest::Start { start_info, controller, .. } => {
508                let request_stream = controller.into_stream();
509                let mut start_info = ContainerStartInfo::new(start_info)?;
510                let (sender, receiver) = oneshot::channel::<TaskResult>();
511                let container = create_container(&mut start_info, &kernel_extra_features, sender)
512                    .await
513                    .with_source_context(|| {
514                        format!("creating container \"{}\"", start_info.program.name)
515                    })?;
516                let service_config =
517                    ContainerServiceConfig { start_info, request_stream, receiver };
518                return Ok((container, service_config));
519            }
520            frunner::ComponentRunnerRequest::_UnknownMethod { ordinal, .. } => {
521                log_warn!("Unknown ComponentRunner request: {ordinal}");
522            }
523        }
524    }
525    bail!("did not receive Start request");
526}
527
528async fn get_bootargs(device_tree: &Devicetree) -> Result<String, Error> {
529    device_tree
530        .root_node
531        .find("chosen")
532        .and_then(|n| {
533            n.get_property("bootargs").map(|p| {
534                let end =
535                    if p.value.last() == Some(&0) { p.value.len() - 1 } else { p.value.len() };
536                match std::str::from_utf8(&p.value[..end]) {
537                    Ok(s) => Ok(s.to_owned()),
538                    Err(e) => {
539                        log_warn!("Bootargs are not valid UTF-8: {e}");
540                        Err(anyhow!("Bootargs are not valid UTF-8"))
541                    }
542                }
543            })
544        })
545        .context("Couldn't find bootargs")?
546}
547
548async fn get_bootitems() -> Result<std::vec::Vec<u8>, Error> {
549    let items =
550        connect_to_protocol::<fboot::ItemsMarker>().context("Failed to connect to boot items")?;
551
552    let items_response = items
553        .get2(zbi::Type::Devicetree.into(), None)
554        .await
555        .context("FIDL: Failed to get devicetree item")?
556        .map_err(|e| anyhow!("Failed to get devicetree item {:?}", e))?;
557
558    let Some(item) = items_response.last() else {
559        return Err(anyhow!("Failed to get items"));
560    };
561
562    let devicetree_vmo = &item.payload;
563    let bytes = devicetree_vmo
564        .read_to_vec(0, item.length as u64)
565        .context("Failed to read devicetree vmo")?;
566
567    Ok(bytes)
568}
569
570async fn get_serial_number() -> Result<String, Error> {
571    let sysinfo = connect_to_protocol::<fsysinfo::SysInfoMarker>()
572        .context("Failed to connect to fuchsia.sysinfo.SysInfo")?;
573    sysinfo
574        .get_serial_number()
575        .await
576        .context("FIDL: Failed to get serial number")?
577        .map_err(|status| anyhow!("Failed to get serial number: {:?}", status))
578}
579
580async fn create_container(
581    start_info: &mut ContainerStartInfo,
582    kernel_extra_features: &[String],
583    task_complete: oneshot::Sender<TaskResult>,
584) -> Result<Container, Error> {
585    fuchsia_trace::duration!(CATEGORY_STARNIX, NAME_CREATE_CONTAINER);
586    const DEFAULT_INIT: &str = "/container/init";
587
588    let pkg_channel = start_info.container_namespace.get_namespace_channel("/pkg").unwrap();
589    let pkg_dir_proxy = fio::DirectorySynchronousProxy::new(pkg_channel);
590
591    let device_tree: Option<Devicetree> = match get_bootitems().await {
592        Ok(items) => match parse_devicetree(&items) {
593            Ok(device_tree) => Some(device_tree),
594            Err(e) => {
595                log_warn!("Failed to parse devicetree: {e:?}");
596                None
597            }
598        },
599        Err(e) => {
600            log_warn!("Failed to get boot items for devicetree: {e:?}");
601            None
602        }
603    };
604    let mut features = parse_features(&start_info, kernel_extra_features)?;
605
606    log_debug!("Creating container with {:#?}", features);
607    let mut kernel_cmdline = BString::from(start_info.program.kernel_cmdline.as_bytes());
608    let mut android_provided_bootreason = None;
609
610    let mut bootargs_has_serialno = false;
611    let mut bootargs_has_verifiedbootstate = false;
612    // TODO(https://fxbug.dev/526770691): Newer versions of Android replace the 'androidboot.*'
613    // kernel parameters with 'bootconfig'. We should expose this to the container to avoid having
614    // to manage 'androidboot.*' parameters here.
615    if features.android_serialno {
616        if let Some(device_tree) = &device_tree {
617            match get_bootargs(device_tree).await {
618                Ok(args) => {
619                    for item in parse_cmdline(&args) {
620                        if item.starts_with("androidboot.force_normal_boot") {
621                            // TODO(https://fxbug.dev/424152964): Support force_normal_boot.
622                            continue;
623                        }
624                        if item.starts_with("androidboot.serialno") {
625                            bootargs_has_serialno = true;
626                        }
627                        if item.starts_with("androidboot.verifiedbootstate") {
628                            bootargs_has_verifiedbootstate = true;
629                        }
630                        if item.starts_with("androidboot.bootreason") && features.android_bootreason
631                        {
632                            // androidboot.bootreason is sourced from the Fuchsia reboot reason.
633                            // It is still useful to log it from userspace to learn what the
634                            // possible values are.
635                            log_info!("Original devicetree bootarg {:?}", item);
636                            if let Some((_, v)) = item.split_once('=') {
637                                android_provided_bootreason = Some(v.to_string());
638                            }
639                            continue;
640                        }
641                        kernel_cmdline.extend(b" ");
642                        kernel_cmdline.extend(item.bytes());
643                    }
644                }
645                Err(err) => log_warn!("could not get bootargs: {err:?}"),
646            }
647        } else {
648            log_warn!("No devicetree available to get bootargs for android.serialno");
649        }
650
651        if !bootargs_has_serialno {
652            match get_serial_number().await {
653                Ok(serial) => {
654                    log_info!("Fell back to sysinfo serial number: {}", serial);
655                    kernel_cmdline.extend(b" androidboot.serialno=");
656                    kernel_cmdline.extend(serial.bytes());
657                }
658                Err(err) => {
659                    log_warn!("Could not get serial number from sysinfo: {err:?}");
660                }
661            }
662        }
663        if !bootargs_has_verifiedbootstate {
664            kernel_cmdline.extend(b" androidboot.verifiedbootstate=orange");
665        }
666    }
667    if features.android_bootreason {
668        kernel_cmdline.extend(b" androidboot.bootreason=");
669
670        let tmp_channel = start_info.container_namespace.get_namespace_channel("/tmp_lifecycle");
671        let tmp_proxy = match tmp_channel {
672            Ok(channel) => {
673                Some(fio::DirectoryProxy::new(fidl::AsyncChannel::from_channel(channel)))
674            }
675            _ => None,
676        };
677
678        match get_or_init_android_bootreason(tmp_proxy, android_provided_bootreason).await {
679            Ok(reason) => {
680                kernel_cmdline.extend(reason.bytes());
681            }
682            Err(err) => {
683                log_warn!("could not get android bootreason: {err:?}. falling back to 'unknown'");
684                kernel_cmdline.extend(b"unknown");
685            }
686        }
687    }
688    if let Some(supported_vendors) = &features.magma_supported_vendors {
689        kernel_cmdline.extend(b" ");
690        let params = get_magma_params(supported_vendors);
691        kernel_cmdline.extend(&*params);
692    }
693
694    // Check whether we actually have access to a role manager by trying to set our own
695    // thread's role.
696    let mut task_mappings = RoleOverrides::new();
697    for m in &start_info.program.task_role_overrides {
698        task_mappings.add(m.process.clone(), m.thread.clone(), m.cgroup.clone(), m.role.clone());
699    }
700    let task_mappings = task_mappings.build().context("adding custom task role")?;
701    let scheduler_manager = SchedulerManager::new(task_mappings);
702
703    let crash_reporter = connect_to_protocol::<CrashReporterMarker>().unwrap();
704
705    let node = inspect::component::inspector().root().create_child("container");
706    let kernel_node = node.create_child("kernel");
707    kernel_node.record_int("created_at", zx::MonotonicInstant::get().into_nanos());
708    features.record_inspect(&kernel_node);
709
710    let security_state = security::kernel_init_security(
711        features.selinux.enabled,
712        features.selinux.options.clone(),
713        features.selinux.exceptions.clone(),
714        &kernel_node,
715    );
716
717    // `config.enable_utc_time_adjustment` is set through config capability
718    // `fuchsia.time.config.WritableUTCTime`.
719    let time_adjustment_proxy = if features.enable_utc_time_adjustment {
720        connect_to_protocol_sync::<AdjustMarker>()
721            .map_err(|e| log_error!("could not connect to fuchsia.time.external/Adjust: {:?}", e))
722            .ok()
723    } else {
724        // See the comment above. UTC adjustment is a per-product setting.
725        log_info!("UTC adjustment is forbidden.");
726        None
727    };
728
729    log_info!("final kernel cmdline: {kernel_cmdline:?}");
730    kernel_node.record_string("cmdline", kernel_cmdline.to_str_lossy());
731
732    let kernel = Kernel::new(
733        kernel_cmdline,
734        features.kernel.clone(),
735        std::mem::take(&mut features.system_limits),
736        start_info.container_namespace.try_clone()?,
737        scheduler_manager,
738        Some(crash_reporter),
739        kernel_node,
740        security_state,
741        time_adjustment_proxy,
742        device_tree,
743    )
744    .with_source_context(|| format!("creating Kernel: {}", start_info.program.name))?;
745    let (fs_context, feature_mounts) =
746        create_fs_context(&kernel, &features, start_info, &pkg_dir_proxy)
747            .source_context("creating FsContext")?;
748    let init_pid = kernel.pids.write().allocate_pid();
749    // Lots of software assumes that the pid for the init process is 1.
750    debug_assert_eq!(init_pid, 1);
751
752    let system_task = create_system_task(&kernel, Arc::clone(&fs_context))
753        .source_context("create system task")?;
754    // The system task gives pid 2. This value is less critical than giving
755    // pid 1 to init, but this value matches what is supposed to happen.
756    debug_assert_eq!(system_task.tid, 2);
757
758    feature_mounts(&system_task).source_context("mounting feature filesystems")?;
759
760    kernel.kthreads.init(system_task).source_context("initializing kthreads")?;
761    let system_task = kernel.kthreads.system_task();
762
763    kernel.syslog.init(&kernel).source_context("initializing syslog")?;
764
765    kernel.hrtimer_manager.init(system_task).source_context("initializing HrTimer manager")?;
766
767    log_info!("Initializing suspend resume manager.");
768    if let Err(e) = kernel.suspend_resume_manager.init(&system_task) {
769        log_warn!("Suspend/Resume manager initialization failed: ({e:?})");
770    }
771
772    // Real Time clock is present in all configuration.
773    log_info!("Initializing RTC device.");
774    rtc_device_init(&system_task).context("in starnix_kernel_runner, while initializing RTC")?;
775
776    // Register common devices and add them in sysfs and devtmpfs.
777    log_info!("Registering devices and filesystems.");
778    init_common_devices(&kernel)?;
779    register_common_file_systems(&kernel);
780
781    register_common_syscalls(&kernel);
782
783    log_info!("Mounting filesystems.");
784    mount_filesystems(&system_task, start_info, &pkg_dir_proxy)
785        .source_context("mounting filesystems")?;
786
787    // Run all common features that were specified in the .cml.
788    {
789        log_info!("Running container features.");
790        run_container_features(&kernel, &features)?;
791    }
792
793    log_info!("Initializing remote block devices.");
794    init_remote_block_devices(&kernel).source_context("initalizing remote block devices")?;
795
796    // If there is an init binary path, run it, optionally waiting for the
797    // startup_file_path to be created. The task struct is still used
798    // to initialize the system up until this point, regardless of whether
799    // or not there is an actual init to be run.
800    let argv = if start_info.program.init.is_empty() {
801        vec![DEFAULT_INIT.to_string()]
802    } else {
803        start_info.program.init.clone()
804    }
805    .iter()
806    .map(|s| to_cstr(s))
807    .collect::<Vec<_>>();
808
809    log_info!("Opening start_info file.");
810    let executable = system_task
811        .open_file(argv[0].as_bytes().into(), OpenFlags::RDONLY)
812        .with_source_context(|| format!("opening init: {:?}", argv[0]))?;
813
814    let initial_name = if start_info.program.init.is_empty() {
815        TaskCommand::default()
816    } else {
817        TaskCommand::new(start_info.program.init[0].as_bytes())
818    };
819
820    let rlimits = parse_rlimits(&start_info.program.rlimits)?;
821
822    // Serve the runtime directory.
823    log_info!("Starting runtime directory.");
824    if let Some(runtime_dir) = start_info.runtime_dir.take() {
825        kernel.kthreads.spawn_future(
826            move || async move { serve_runtime_dir(runtime_dir).await },
827            "serve_runtime_dir",
828        );
829    }
830
831    // At this point the runtime environment has been prepared but nothing is actually running yet.
832    // Pause here if a debugger needs time to attach to the job.
833    if let Some(break_on_start) = start_info.break_on_start.take() {
834        log_info!("Waiting for signal from debugger before spawning init process...");
835        if let Err(e) =
836            fuchsia_async::OnSignals::new(break_on_start, zx::Signals::EVENTPAIR_PEER_CLOSED).await
837        {
838            log_warn!(e:%; "Received break_on_start eventpair but couldn't wait for PEER_CLOSED.");
839        }
840    }
841
842    log_info!("Creating init process.");
843    let init_task =
844        create_init_process(&kernel, init_pid, initial_name, Arc::clone(&fs_context), &rlimits)
845            .with_source_context(|| format!("creating init task: {:?}", start_info.program.init))?;
846
847    execute_task_with_prerun_result(
848        init_task,
849        move |init_task| {
850            parse_numbered_handles(init_task, None, &init_task.files()).expect("");
851            init_task.exec(executable, argv[0].clone(), argv.clone(), vec![])
852        },
853        move |result| {
854            log_info!("Finished running init process: {:?}", result);
855            let _ = task_complete.send(result);
856        },
857        None,
858    )?;
859
860    if !start_info.program.startup_file_path.is_empty() {
861        wait_for_init_file(&start_info.program.startup_file_path, &system_task, init_pid).await?;
862    };
863
864    let memory_attribution_manager = ContainerMemoryAttributionManager::new(
865        Arc::downgrade(&kernel),
866        start_info.component_instance.take().ok_or_else(|| Error::msg("No component instance"))?,
867    );
868
869    Ok(Container {
870        kernel,
871        memory_attribution_manager,
872        _node: node,
873        _thread_bound: Default::default(),
874    })
875}
876
877fn create_fs_context(
878    kernel: &Kernel,
879    features: &Features,
880    start_info: &ContainerStartInfo,
881    pkg_dir_proxy: &fio::DirectorySynchronousProxy,
882) -> Result<(Arc<FsContext>, LayeredFsMounts), Error> {
883    // The mounts are applied in the order listed. Mounting will fail if the designated mount
884    // point doesn't exist in a previous mount. The root must be first so other mounts can be
885    // applied on top of it.
886    let mut mounts_iter =
887        start_info.program.mounts.iter().chain(start_info.config.additional_mounts.iter());
888    let root = MountAction::new_for_root(
889        kernel,
890        pkg_dir_proxy,
891        mounts_iter.next().ok_or_else(|| anyhow!("Mounts list is empty"))?,
892    )?;
893    if root.path != "/" {
894        anyhow::bail!("First mount in mounts list is not the root");
895    }
896
897    let mut builder = LayeredFsBuilder::new(root.fs);
898    if features.container {
899        // /container/component will be a tmpfs where component using the starnix kernel will have their
900        // package mounted.
901        let component_tmpfs_options = FileSystemOptions {
902            params: kernel
903                .features
904                .ns_mount_options("#component_tmpfs")
905                .context("#component_tmpfs options")?,
906            ..Default::default()
907        };
908        let component_tmpfs = TmpFs::new_fs_with_options(kernel, component_tmpfs_options)?;
909
910        // /container will mount the container pkg
911        let container_remotefs_options = FileSystemOptions {
912            source: "data".into(),
913            params: kernel.features.ns_mount_options("#container").context("#container options")?,
914            ..Default::default()
915        };
916        let container_remotefs = new_remotefs_in_root(
917            kernel,
918            pkg_dir_proxy,
919            container_remotefs_options,
920            fio::PERM_READABLE | fio::PERM_EXECUTABLE,
921        )?;
922
923        builder.add("/container", container_remotefs);
924        builder.add("/container/component", component_tmpfs);
925    }
926    if features.custom_artifacts {
927        let mount_options = FileSystemOptions {
928            params: kernel
929                .features
930                .ns_mount_options("#custom_artifacts")
931                .context("#custom_artifacts options")?,
932            ..Default::default()
933        };
934        let fs = TmpFs::new_fs_with_options(kernel, mount_options)?;
935        builder.add("/custom_artifacts", fs);
936    }
937    if features.test_data {
938        let mount_options = FileSystemOptions {
939            params: kernel.features.ns_mount_options("#test_data").context("#test_data options")?,
940            ..Default::default()
941        };
942        let fs = TmpFs::new_fs_with_options(kernel, mount_options)?;
943        builder.add("/test_data", fs);
944    }
945
946    let (mut root_fs, feature_mounts) = builder.build(kernel);
947    if features.rootfs_rw {
948        root_fs = OverlayStack::wrap_fs_in_writable_layer(kernel, root_fs)?;
949    }
950
951    Ok((FsContext::new(Namespace::new_with_flags(root_fs, root.flags)), feature_mounts))
952}
953
954fn parse_rlimits(rlimits: &[String]) -> Result<Vec<(Resource, u64)>, Error> {
955    let mut res = Vec::new();
956
957    for rlimit in rlimits {
958        let (key, value) =
959            rlimit.split_once('=').ok_or_else(|| anyhow!("Invalid rlimit: {rlimit}"))?;
960        let value = value.parse::<u64>()?;
961        let kv = match key {
962            "RLIMIT_NOFILE" => (Resource::NOFILE, value),
963            "RLIMIT_RTPRIO" => (Resource::RTPRIO, value),
964            _ => bail!("Unknown rlimit: {key}"),
965        };
966        res.push(kv);
967    }
968
969    Ok(res)
970}
971
972fn mount_filesystems(
973    system_task: &CurrentTask,
974    start_info: &ContainerStartInfo,
975    pkg_dir_proxy: &fio::DirectorySynchronousProxy,
976) -> Result<(), Error> {
977    // Skip the first mount, that was used to create the root filesystem.
978    let mut mounts_iter =
979        start_info.program.mounts.iter().chain(start_info.config.additional_mounts.iter());
980    let _ = mounts_iter.next();
981    for mount_spec in mounts_iter {
982        let action = MountAction::from_spec(system_task, pkg_dir_proxy, mount_spec)
983            .with_source_context(|| format!("creating filesystem from spec: {}", mount_spec))?;
984        let mount_point = system_task
985            .lookup_path_from_root(action.path.as_ref())
986            .with_source_context(|| format!("lookup path from root: {}", action.path))?;
987        mount_point.mount(WhatToMount::Fs(action.fs), action.flags)?;
988    }
989    Ok(())
990}
991
992fn init_remote_block_devices(kernel: &Kernel) -> Result<(), Error> {
993    remote_block_device_init(kernel);
994    let entries = match std::fs::read_dir("/block") {
995        Ok(entries) => entries,
996        Err(e) => {
997            log_warn!("Failed to read block directory: {}", e);
998            return Ok(());
999        }
1000    };
1001    for entry in entries {
1002        let entry = entry?;
1003        let path_buf = entry.path();
1004        let path = path_buf.to_str().ok_or_else(|| anyhow!("Invalid block device path"))?;
1005        let (client_end, server_end) = fidl::endpoints::create_endpoints();
1006        match fdio::service_connect(
1007            &format!("{}/fuchsia.storage.block.Block", path),
1008            server_end.into(),
1009        ) {
1010            Ok(()) => (),
1011            Err(e) => {
1012                log_warn!("Failed to connect to block device at {}: {}", path, e);
1013                continue;
1014            }
1015        }
1016        let name = entry.file_name();
1017        let name_str = name.to_str().unwrap();
1018        kernel
1019            .remote_block_device_registry
1020            .create_remote_block_device(kernel, &name_str, client_end)
1021            .with_source_context(|| format!("creating remote block device: {name_str}"))?;
1022    }
1023    Ok(())
1024}
1025
1026async fn wait_for_init_file(
1027    startup_file_path: &str,
1028    current_task: &CurrentTask,
1029    init_tid: tid_t,
1030) -> Result<(), Error> {
1031    // TODO(https://fxbug.dev/42178400): Use inotify machinery to wait for the file.
1032    loop {
1033        fasync::Timer::new(fasync::MonotonicDuration::from_millis(100).after_now()).await;
1034
1035        let creds = security::creds_start_internal_operation(current_task);
1036        if let Some(result) = current_task.override_creds(creds, || {
1037            let root = current_task.fs().root();
1038            let mut context = LookupContext::default();
1039
1040            match current_task.lookup_path(&mut context, root, startup_file_path.into()) {
1041                Ok(_) => return Some(Ok(())),
1042                Err(error) if error == ENOENT => {}
1043                Err(error) => return Some(Err(anyhow::Error::from(error))),
1044            };
1045
1046            if current_task.get_task(init_tid).is_err() {
1047                return Some(Err(anyhow!(
1048                    "Init task terminated before startup_file_path was ready"
1049                )));
1050            }
1051
1052            None
1053        }) {
1054            return result;
1055        }
1056    }
1057}
1058
1059async fn serve_runtime_dir(runtime_dir: ServerEnd<fio::DirectoryMarker>) {
1060    let mut fs = fuchsia_component::server::ServiceFs::new();
1061    match create_job_id_vmo() {
1062        Ok(vmo) => {
1063            fs.dir("elf").add_vmo_file_at("job_id", vmo);
1064        }
1065        Err(e) => log_error!(e:%; "failed to create vmo with job id for debuggers"),
1066    }
1067    match fs.serve_connection(runtime_dir) {
1068        Ok(_) => {
1069            fs.add_fidl_service(|job_requests: TaskProviderRequestStream| {
1070                fuchsia_async::Task::local(async move {
1071                    if let Err(e) = serve_task_provider(job_requests).await {
1072                        log_warn!(e:?; "Error serving TaskProvider");
1073                    }
1074                })
1075                .detach();
1076            });
1077            fs.collect::<()>().await;
1078        }
1079        Err(e) => log_error!("Couldn't serve runtime directory: {e:?}"),
1080    }
1081}
1082
1083fn create_job_id_vmo() -> Result<zx::Vmo, Error> {
1084    let job_id = fuchsia_runtime::job_default().koid().context("reading own job koid")?;
1085    let job_id_str = job_id.raw_koid().to_string();
1086    let job_id_vmo = zx::Vmo::create(job_id_str.len() as u64).context("creating job id vmo")?;
1087    job_id_vmo.write(job_id_str.as_bytes(), 0).context("write job id to vmo")?;
1088    Ok(job_id_vmo)
1089}
1090
1091async fn serve_task_provider(mut job_requests: TaskProviderRequestStream) -> Result<(), Error> {
1092    while let Some(request) = job_requests.next().await {
1093        match request.context("getting next TaskProvider request")? {
1094            TaskProviderRequest::GetJob { responder } => {
1095                responder
1096                    .send(
1097                        fuchsia_runtime::job_default()
1098                            .duplicate_handle(zx::Rights::SAME_RIGHTS)
1099                            .map_err(|s| s.into_raw()),
1100                    )
1101                    .context("sending job for runtime dir")?;
1102            }
1103            unknown => bail!("Unknown TaskProvider method {unknown:?}"),
1104        }
1105    }
1106    Ok(())
1107}
1108
1109#[cfg(test)]
1110mod test {
1111    use super::wait_for_init_file;
1112
1113    use futures::{SinkExt, StreamExt};
1114    use starnix_core::testing::spawn_kernel_and_run;
1115    use starnix_core::vfs::FdNumber;
1116    use starnix_uapi::CLONE_FS;
1117    use starnix_uapi::file_mode::{AccessCheck, FileMode};
1118    use starnix_uapi::open_flags::OpenFlags;
1119    use starnix_uapi::signals::SIGCHLD;
1120    use starnix_uapi::vfs::ResolveFlags;
1121
1122    #[fuchsia::test]
1123    async fn test_init_file_already_exists() {
1124        spawn_kernel_and_run(async move |current_task| {
1125            let path = "/path";
1126            current_task
1127                .open_file_at(
1128                    FdNumber::AT_FDCWD,
1129                    path.into(),
1130                    OpenFlags::CREAT,
1131                    FileMode::default(),
1132                    ResolveFlags::empty(),
1133                    AccessCheck::default(),
1134                )
1135                .expect("Failed to create file");
1136
1137            wait_for_init_file(path, current_task, current_task.get_tid())
1138                .await
1139                .expect("failed to wait for file");
1140        })
1141        .await;
1142    }
1143    #[fuchsia::test]
1144    async fn test_init_file_wait_required() {
1145        spawn_kernel_and_run(async move |current_task| {
1146            let (mut sender, mut receiver) = futures::channel::mpsc::unbounded();
1147
1148            let init_task = current_task.clone_task_for_test(CLONE_FS as u64, Some(SIGCHLD));
1149            let path = "/path";
1150
1151            let test_init_tid = current_task.get_tid();
1152
1153            let wait_fut = async {
1154                sender.send(()).await.expect("failed to send message");
1155                wait_for_init_file(path, &init_task, test_init_tid)
1156                    .await
1157                    .expect("failed to wait for file");
1158                sender.send(()).await.expect("failed to send message");
1159            };
1160
1161            let create_fut = async {
1162                assert!(receiver.next().await.is_some());
1163                current_task
1164                    .open_file_at(
1165                        FdNumber::AT_FDCWD,
1166                        path.into(),
1167                        OpenFlags::CREAT,
1168                        FileMode::default(),
1169                        ResolveFlags::empty(),
1170                        AccessCheck::default(),
1171                    )
1172                    .expect("Failed to create file");
1173                assert!(receiver.next().await.is_some());
1174            };
1175
1176            futures::join!(wait_fut, create_fut);
1177        })
1178        .await;
1179    }
1180    #[fuchsia::test]
1181    async fn test_init_exits_before_file_exists() {
1182        spawn_kernel_and_run(async move |current_task| {
1183            let (mut sender, mut receiver) = futures::channel::mpsc::unbounded();
1184
1185            let init_task = current_task.clone_task_for_test(CLONE_FS as u64, Some(SIGCHLD));
1186            const STARTUP_FILE_PATH: &str = "/path";
1187
1188            let test_init_tid = init_task.get_tid();
1189
1190            let wait_fut = async {
1191                sender.send(()).await.expect("failed to send message");
1192                wait_for_init_file(STARTUP_FILE_PATH, current_task, test_init_tid)
1193                    .await
1194                    .expect_err("Did not detect init exit");
1195                sender.send(()).await.expect("failed to send message");
1196            };
1197
1198            let exit_fut = async {
1199                assert!(receiver.next().await.is_some());
1200                std::mem::drop(init_task);
1201                assert!(receiver.next().await.is_some());
1202            };
1203
1204            futures::join!(wait_fut, exit_fut);
1205        })
1206        .await;
1207    }
1208}