1use 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::{ControlHandle, 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
77struct ContainerMemoryAttributionManager {
79 memory_attribution_server: AttributionServerHandle,
81}
82
83impl ContainerMemoryAttributionManager {
84 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 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
107fn attribution_info_for_kernel(
111 kernel: &Kernel,
112 component_instance: &zx::Event,
113) -> Vec<fattribution::AttributionUpdate> {
114 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 detailed_attribution: None,
131 ..Default::default()
132 };
133
134 let starnix_kernel_attribution = fattribution::UpdatedPrincipal {
135 identifier: starnix_kernel_id, 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, 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 pub program: ContainerProgram,
179
180 pub config: ContainerStructuredConfig,
181
182 outgoing_dir: Option<zx::Channel>,
186
187 pub container_namespace: ContainerNamespace,
190
191 runtime_dir: Option<ServerEnd<fio::DirectoryMarker>>,
193
194 break_on_start: Option<zx::EventPair>,
196
197 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 name: String,
246
247 init: Vec<String>,
249
250 #[serde(default)]
252 kernel_cmdline: String,
253
254 #[serde(default)]
256 mounts: Vec<String>,
257
258 #[serde(default)]
260 pub features: Vec<String>,
261
262 #[serde(default)]
264 rlimits: Vec<String>,
265
266 #[serde(default)]
268 startup_file_path: String,
269
270 #[serde(default)]
274 pub default_seclabel: Option<String>,
275
276 #[serde(default = "default_uid")]
280 pub default_uid: runner::serde::StoreAsString<u32>,
281
282 pub default_ns_mount_options: Option<Vec<String>>,
286
287 #[serde(default)]
298 task_role_overrides: Vec<TaskSchedulerMapping>,
299}
300
301#[derive(Default, Deserialize)]
304struct TaskSchedulerMapping {
305 role: String,
307 process: String,
309 thread: String,
311 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
329fn 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 pub kernel: Arc<Kernel>,
344
345 memory_attribution_manager: ContainerMemoryAttributionManager,
346
347 _node: inspect::Node,
349
350 _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 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 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
433enum 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 if !kernel.is_shutting_down() {
489 kernel.shut_down();
490 }
491 }
492
493 log_debug!("done listening for container-terminating events");
494
495 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 if features.android_serialno {
615 if let Some(device_tree) = &device_tree {
616 match get_bootargs(device_tree).await {
617 Ok(args) => {
618 for item in parse_cmdline(&args) {
619 if item.starts_with("androidboot.force_normal_boot") {
620 continue;
622 }
623 if item.starts_with("androidboot.serialno") {
624 bootargs_has_serialno = true;
625 }
626 if item.starts_with("androidboot.bootreason") && features.android_bootreason
627 {
628 log_info!("Original devicetree bootarg {:?}", item);
632 if let Some((_, v)) = item.split_once('=') {
633 android_provided_bootreason = Some(v.to_string());
634 }
635 continue;
636 }
637 kernel_cmdline.extend(b" ");
638 kernel_cmdline.extend(item.bytes());
639 }
640 }
641 Err(err) => log_warn!("could not get bootargs: {err:?}"),
642 }
643 } else {
644 log_warn!("No devicetree available to get bootargs for android.serialno");
645 }
646
647 if !bootargs_has_serialno {
648 match get_serial_number().await {
649 Ok(serial) => {
650 log_info!("Fell back to sysinfo serial number: {}", serial);
651 kernel_cmdline.extend(b" androidboot.serialno=");
652 kernel_cmdline.extend(serial.bytes());
653 }
654 Err(err) => {
655 log_warn!("Could not get serial number from sysinfo: {err:?}");
656 }
657 }
658 }
659 }
660 if features.android_bootreason {
661 kernel_cmdline.extend(b" androidboot.bootreason=");
662
663 let tmp_channel = start_info.container_namespace.get_namespace_channel("/tmp_lifecycle");
664 let tmp_proxy = match tmp_channel {
665 Ok(channel) => {
666 Some(fio::DirectoryProxy::new(fidl::AsyncChannel::from_channel(channel)))
667 }
668 _ => None,
669 };
670
671 match get_or_init_android_bootreason(tmp_proxy, android_provided_bootreason).await {
672 Ok(reason) => {
673 kernel_cmdline.extend(reason.bytes());
674 }
675 Err(err) => {
676 log_warn!("could not get android bootreason: {err:?}. falling back to 'unknown'");
677 kernel_cmdline.extend(b"unknown");
678 }
679 }
680 }
681 if let Some(supported_vendors) = &features.magma_supported_vendors {
682 kernel_cmdline.extend(b" ");
683 let params = get_magma_params(supported_vendors);
684 kernel_cmdline.extend(&*params);
685 }
686
687 let mut task_mappings = RoleOverrides::new();
690 for m in &start_info.program.task_role_overrides {
691 task_mappings.add(m.process.clone(), m.thread.clone(), m.cgroup.clone(), m.role.clone());
692 }
693 let task_mappings = task_mappings.build().context("adding custom task role")?;
694 let scheduler_manager = SchedulerManager::new(task_mappings);
695
696 let crash_reporter = connect_to_protocol::<CrashReporterMarker>().unwrap();
697
698 let node = inspect::component::inspector().root().create_child("container");
699 let kernel_node = node.create_child("kernel");
700 kernel_node.record_int("created_at", zx::MonotonicInstant::get().into_nanos());
701 features.record_inspect(&kernel_node);
702
703 let security_state = security::kernel_init_security(
704 features.selinux.enabled,
705 features.selinux.options.clone(),
706 features.selinux.exceptions.clone(),
707 &kernel_node,
708 );
709
710 let time_adjustment_proxy = if features.enable_utc_time_adjustment {
713 connect_to_protocol_sync::<AdjustMarker>()
714 .map_err(|e| log_error!("could not connect to fuchsia.time.external/Adjust: {:?}", e))
715 .ok()
716 } else {
717 log_info!("UTC adjustment is forbidden.");
719 None
720 };
721
722 log_info!("final kernel cmdline: {kernel_cmdline:?}");
723 kernel_node.record_string("cmdline", kernel_cmdline.to_str_lossy());
724
725 let kernel = Kernel::new(
726 kernel_cmdline,
727 features.kernel.clone(),
728 std::mem::take(&mut features.system_limits),
729 start_info.container_namespace.try_clone()?,
730 scheduler_manager,
731 Some(crash_reporter),
732 kernel_node,
733 security_state,
734 time_adjustment_proxy,
735 device_tree,
736 )
737 .with_source_context(|| format!("creating Kernel: {}", start_info.program.name))?;
738 let (fs_context, feature_mounts) =
739 create_fs_context(&kernel, &features, start_info, &pkg_dir_proxy)
740 .source_context("creating FsContext")?;
741 let init_pid = kernel.pids.write().allocate_pid();
742 debug_assert_eq!(init_pid, 1);
744
745 let system_task = create_system_task(&kernel, Arc::clone(&fs_context))
746 .source_context("create system task")?;
747 debug_assert_eq!(system_task.tid, 2);
750
751 feature_mounts(&system_task).source_context("mounting feature filesystems")?;
752
753 kernel.kthreads.init(system_task).source_context("initializing kthreads")?;
754 let system_task = kernel.kthreads.system_task();
755
756 kernel.syslog.init(&kernel).source_context("initializing syslog")?;
757
758 kernel.hrtimer_manager.init(system_task).source_context("initializing HrTimer manager")?;
759
760 log_info!("Initializing suspend resume manager.");
761 if let Err(e) = kernel.suspend_resume_manager.init(&system_task) {
762 log_warn!("Suspend/Resume manager initialization failed: ({e:?})");
763 }
764
765 log_info!("Initializing RTC device.");
767 rtc_device_init(&system_task).context("in starnix_kernel_runner, while initializing RTC")?;
768
769 log_info!("Registering devices and filesystems.");
771 init_common_devices(&kernel)?;
772 register_common_file_systems(&kernel);
773
774 register_common_syscalls(&kernel);
775
776 log_info!("Mounting filesystems.");
777 mount_filesystems(&system_task, start_info, &pkg_dir_proxy)
778 .source_context("mounting filesystems")?;
779
780 {
782 log_info!("Running container features.");
783 run_container_features(&kernel, &features)?;
784 }
785
786 log_info!("Initializing remote block devices.");
787 init_remote_block_devices(&kernel).source_context("initalizing remote block devices")?;
788
789 let argv = if start_info.program.init.is_empty() {
794 vec![DEFAULT_INIT.to_string()]
795 } else {
796 start_info.program.init.clone()
797 }
798 .iter()
799 .map(|s| to_cstr(s))
800 .collect::<Vec<_>>();
801
802 log_info!("Opening start_info file.");
803 let executable = system_task
804 .open_file(argv[0].as_bytes().into(), OpenFlags::RDONLY)
805 .with_source_context(|| format!("opening init: {:?}", argv[0]))?;
806
807 let initial_name = if start_info.program.init.is_empty() {
808 TaskCommand::default()
809 } else {
810 TaskCommand::new(start_info.program.init[0].as_bytes())
811 };
812
813 let rlimits = parse_rlimits(&start_info.program.rlimits)?;
814
815 log_info!("Starting runtime directory.");
817 if let Some(runtime_dir) = start_info.runtime_dir.take() {
818 kernel.kthreads.spawn_future(
819 move || async move { serve_runtime_dir(runtime_dir).await },
820 "serve_runtime_dir",
821 );
822 }
823
824 if let Some(break_on_start) = start_info.break_on_start.take() {
827 log_info!("Waiting for signal from debugger before spawning init process...");
828 if let Err(e) =
829 fuchsia_async::OnSignals::new(break_on_start, zx::Signals::EVENTPAIR_PEER_CLOSED).await
830 {
831 log_warn!(e:%; "Received break_on_start eventpair but couldn't wait for PEER_CLOSED.");
832 }
833 }
834
835 log_info!("Creating init process.");
836 let init_task =
837 create_init_process(&kernel, init_pid, initial_name, Arc::clone(&fs_context), &rlimits)
838 .with_source_context(|| format!("creating init task: {:?}", start_info.program.init))?;
839
840 execute_task_with_prerun_result(
841 init_task,
842 move |init_task| {
843 parse_numbered_handles(init_task, None, &init_task.files()).expect("");
844 init_task.exec(executable, argv[0].clone(), argv.clone(), vec![])
845 },
846 move |result| {
847 log_info!("Finished running init process: {:?}", result);
848 let _ = task_complete.send(result);
849 },
850 None,
851 )?;
852
853 if !start_info.program.startup_file_path.is_empty() {
854 wait_for_init_file(&start_info.program.startup_file_path, &system_task, init_pid).await?;
855 };
856
857 let memory_attribution_manager = ContainerMemoryAttributionManager::new(
858 Arc::downgrade(&kernel),
859 start_info.component_instance.take().ok_or_else(|| Error::msg("No component instance"))?,
860 );
861
862 Ok(Container {
863 kernel,
864 memory_attribution_manager,
865 _node: node,
866 _thread_bound: Default::default(),
867 })
868}
869
870fn create_fs_context(
871 kernel: &Kernel,
872 features: &Features,
873 start_info: &ContainerStartInfo,
874 pkg_dir_proxy: &fio::DirectorySynchronousProxy,
875) -> Result<(Arc<FsContext>, LayeredFsMounts), Error> {
876 let mut mounts_iter =
880 start_info.program.mounts.iter().chain(start_info.config.additional_mounts.iter());
881 let root = MountAction::new_for_root(
882 kernel,
883 pkg_dir_proxy,
884 mounts_iter.next().ok_or_else(|| anyhow!("Mounts list is empty"))?,
885 )?;
886 if root.path != "/" {
887 anyhow::bail!("First mount in mounts list is not the root");
888 }
889
890 let mut builder = LayeredFsBuilder::new(root.fs);
891 if features.container {
892 let component_tmpfs_options = FileSystemOptions {
895 params: kernel
896 .features
897 .ns_mount_options("#component_tmpfs")
898 .context("#component_tmpfs options")?,
899 ..Default::default()
900 };
901 let component_tmpfs = TmpFs::new_fs_with_options(kernel, component_tmpfs_options)?;
902
903 let container_remotefs_options = FileSystemOptions {
905 source: "data".into(),
906 params: kernel.features.ns_mount_options("#container").context("#container options")?,
907 ..Default::default()
908 };
909 let container_remotefs = new_remotefs_in_root(
910 kernel,
911 pkg_dir_proxy,
912 container_remotefs_options,
913 fio::PERM_READABLE | fio::PERM_EXECUTABLE,
914 )?;
915
916 builder.add("/container", container_remotefs);
917 builder.add("/container/component", component_tmpfs);
918 }
919 if features.custom_artifacts {
920 let mount_options = FileSystemOptions {
921 params: kernel
922 .features
923 .ns_mount_options("#custom_artifacts")
924 .context("#custom_artifacts options")?,
925 ..Default::default()
926 };
927 let fs = TmpFs::new_fs_with_options(kernel, mount_options)?;
928 builder.add("/custom_artifacts", fs);
929 }
930 if features.test_data {
931 let mount_options = FileSystemOptions {
932 params: kernel.features.ns_mount_options("#test_data").context("#test_data options")?,
933 ..Default::default()
934 };
935 let fs = TmpFs::new_fs_with_options(kernel, mount_options)?;
936 builder.add("/test_data", fs);
937 }
938
939 let (mut root_fs, feature_mounts) = builder.build(kernel);
940 if features.rootfs_rw {
941 root_fs = OverlayStack::wrap_fs_in_writable_layer(kernel, root_fs)?;
942 }
943
944 Ok((FsContext::new(Namespace::new_with_flags(root_fs, root.flags)), feature_mounts))
945}
946
947fn parse_rlimits(rlimits: &[String]) -> Result<Vec<(Resource, u64)>, Error> {
948 let mut res = Vec::new();
949
950 for rlimit in rlimits {
951 let (key, value) =
952 rlimit.split_once('=').ok_or_else(|| anyhow!("Invalid rlimit: {rlimit}"))?;
953 let value = value.parse::<u64>()?;
954 let kv = match key {
955 "RLIMIT_NOFILE" => (Resource::NOFILE, value),
956 "RLIMIT_RTPRIO" => (Resource::RTPRIO, value),
957 _ => bail!("Unknown rlimit: {key}"),
958 };
959 res.push(kv);
960 }
961
962 Ok(res)
963}
964
965fn mount_filesystems(
966 system_task: &CurrentTask,
967 start_info: &ContainerStartInfo,
968 pkg_dir_proxy: &fio::DirectorySynchronousProxy,
969) -> Result<(), Error> {
970 let mut mounts_iter =
972 start_info.program.mounts.iter().chain(start_info.config.additional_mounts.iter());
973 let _ = mounts_iter.next();
974 for mount_spec in mounts_iter {
975 let action = MountAction::from_spec(system_task, pkg_dir_proxy, mount_spec)
976 .with_source_context(|| format!("creating filesystem from spec: {}", mount_spec))?;
977 let mount_point = system_task
978 .lookup_path_from_root(action.path.as_ref())
979 .with_source_context(|| format!("lookup path from root: {}", action.path))?;
980 mount_point.mount(WhatToMount::Fs(action.fs), action.flags)?;
981 }
982 Ok(())
983}
984
985fn init_remote_block_devices(kernel: &Kernel) -> Result<(), Error> {
986 remote_block_device_init(kernel);
987 let entries = match std::fs::read_dir("/block") {
988 Ok(entries) => entries,
989 Err(e) => {
990 log_warn!("Failed to read block directory: {}", e);
991 return Ok(());
992 }
993 };
994 for entry in entries {
995 let entry = entry?;
996 let path_buf = entry.path();
997 let path = path_buf.to_str().ok_or_else(|| anyhow!("Invalid block device path"))?;
998 let (client_end, server_end) = fidl::endpoints::create_endpoints();
999 match fdio::service_connect(
1000 &format!("{}/fuchsia.storage.block.Block", path),
1001 server_end.into(),
1002 ) {
1003 Ok(()) => (),
1004 Err(e) => {
1005 log_warn!("Failed to connect to block device at {}: {}", path, e);
1006 continue;
1007 }
1008 }
1009 let name = entry.file_name();
1010 let name_str = name.to_str().unwrap();
1011 kernel
1012 .remote_block_device_registry
1013 .create_remote_block_device(kernel, &name_str, client_end)
1014 .with_source_context(|| format!("creating remote block device: {name_str}"))?;
1015 }
1016 Ok(())
1017}
1018
1019async fn wait_for_init_file(
1020 startup_file_path: &str,
1021 current_task: &CurrentTask,
1022 init_tid: tid_t,
1023) -> Result<(), Error> {
1024 loop {
1026 fasync::Timer::new(fasync::MonotonicDuration::from_millis(100).after_now()).await;
1027
1028 let creds = security::creds_start_internal_operation(current_task);
1029 if let Some(result) = current_task.override_creds(creds, || {
1030 let root = current_task.fs().root();
1031 let mut context = LookupContext::default();
1032
1033 match current_task.lookup_path(&mut context, root, startup_file_path.into()) {
1034 Ok(_) => return Some(Ok(())),
1035 Err(error) if error == ENOENT => {}
1036 Err(error) => return Some(Err(anyhow::Error::from(error))),
1037 };
1038
1039 if current_task.get_task(init_tid).is_err() {
1040 return Some(Err(anyhow!(
1041 "Init task terminated before startup_file_path was ready"
1042 )));
1043 }
1044
1045 None
1046 }) {
1047 return result;
1048 }
1049 }
1050}
1051
1052async fn serve_runtime_dir(runtime_dir: ServerEnd<fio::DirectoryMarker>) {
1053 let mut fs = fuchsia_component::server::ServiceFs::new();
1054 match create_job_id_vmo() {
1055 Ok(vmo) => {
1056 fs.dir("elf").add_vmo_file_at("job_id", vmo);
1057 }
1058 Err(e) => log_error!(e:%; "failed to create vmo with job id for debuggers"),
1059 }
1060 match fs.serve_connection(runtime_dir) {
1061 Ok(_) => {
1062 fs.add_fidl_service(|job_requests: TaskProviderRequestStream| {
1063 fuchsia_async::Task::local(async move {
1064 if let Err(e) = serve_task_provider(job_requests).await {
1065 log_warn!(e:?; "Error serving TaskProvider");
1066 }
1067 })
1068 .detach();
1069 });
1070 fs.collect::<()>().await;
1071 }
1072 Err(e) => log_error!("Couldn't serve runtime directory: {e:?}"),
1073 }
1074}
1075
1076fn create_job_id_vmo() -> Result<zx::Vmo, Error> {
1077 let job_id = fuchsia_runtime::job_default().koid().context("reading own job koid")?;
1078 let job_id_str = job_id.raw_koid().to_string();
1079 let job_id_vmo = zx::Vmo::create(job_id_str.len() as u64).context("creating job id vmo")?;
1080 job_id_vmo.write(job_id_str.as_bytes(), 0).context("write job id to vmo")?;
1081 Ok(job_id_vmo)
1082}
1083
1084async fn serve_task_provider(mut job_requests: TaskProviderRequestStream) -> Result<(), Error> {
1085 while let Some(request) = job_requests.next().await {
1086 match request.context("getting next TaskProvider request")? {
1087 TaskProviderRequest::GetJob { responder } => {
1088 responder
1089 .send(
1090 fuchsia_runtime::job_default()
1091 .duplicate_handle(zx::Rights::SAME_RIGHTS)
1092 .map_err(|s| s.into_raw()),
1093 )
1094 .context("sending job for runtime dir")?;
1095 }
1096 unknown => bail!("Unknown TaskProvider method {unknown:?}"),
1097 }
1098 }
1099 Ok(())
1100}
1101
1102#[cfg(test)]
1103mod test {
1104 use super::wait_for_init_file;
1105
1106 use futures::{SinkExt, StreamExt};
1107 use starnix_core::testing::spawn_kernel_and_run;
1108 use starnix_core::vfs::FdNumber;
1109 use starnix_uapi::CLONE_FS;
1110 use starnix_uapi::file_mode::{AccessCheck, FileMode};
1111 use starnix_uapi::open_flags::OpenFlags;
1112 use starnix_uapi::signals::SIGCHLD;
1113 use starnix_uapi::vfs::ResolveFlags;
1114
1115 #[fuchsia::test]
1116 async fn test_init_file_already_exists() {
1117 spawn_kernel_and_run(async move |current_task| {
1118 let path = "/path";
1119 current_task
1120 .open_file_at(
1121 FdNumber::AT_FDCWD,
1122 path.into(),
1123 OpenFlags::CREAT,
1124 FileMode::default(),
1125 ResolveFlags::empty(),
1126 AccessCheck::default(),
1127 )
1128 .expect("Failed to create file");
1129
1130 wait_for_init_file(path, current_task, current_task.get_tid())
1131 .await
1132 .expect("failed to wait for file");
1133 })
1134 .await;
1135 }
1136 #[fuchsia::test]
1137 async fn test_init_file_wait_required() {
1138 spawn_kernel_and_run(async move |current_task| {
1139 let (mut sender, mut receiver) = futures::channel::mpsc::unbounded();
1140
1141 let init_task = current_task.clone_task_for_test(CLONE_FS as u64, Some(SIGCHLD));
1142 let path = "/path";
1143
1144 let test_init_tid = current_task.get_tid();
1145
1146 let wait_fut = async {
1147 sender.send(()).await.expect("failed to send message");
1148 wait_for_init_file(path, &init_task, test_init_tid)
1149 .await
1150 .expect("failed to wait for file");
1151 sender.send(()).await.expect("failed to send message");
1152 };
1153
1154 let create_fut = async {
1155 assert!(receiver.next().await.is_some());
1156 current_task
1157 .open_file_at(
1158 FdNumber::AT_FDCWD,
1159 path.into(),
1160 OpenFlags::CREAT,
1161 FileMode::default(),
1162 ResolveFlags::empty(),
1163 AccessCheck::default(),
1164 )
1165 .expect("Failed to create file");
1166 assert!(receiver.next().await.is_some());
1167 };
1168
1169 futures::join!(wait_fut, create_fut);
1170 })
1171 .await;
1172 }
1173 #[fuchsia::test]
1174 async fn test_init_exits_before_file_exists() {
1175 spawn_kernel_and_run(async move |current_task| {
1176 let (mut sender, mut receiver) = futures::channel::mpsc::unbounded();
1177
1178 let init_task = current_task.clone_task_for_test(CLONE_FS as u64, Some(SIGCHLD));
1179 const STARTUP_FILE_PATH: &str = "/path";
1180
1181 let test_init_tid = init_task.get_tid();
1182
1183 let wait_fut = async {
1184 sender.send(()).await.expect("failed to send message");
1185 wait_for_init_file(STARTUP_FILE_PATH, current_task, test_init_tid)
1186 .await
1187 .expect_err("Did not detect init exit");
1188 sender.send(()).await.expect("failed to send message");
1189 };
1190
1191 let exit_fut = async {
1192 assert!(receiver.next().await.is_some());
1193 std::mem::drop(init_task);
1194 assert!(receiver.next().await.is_some());
1195 };
1196
1197 futures::join!(wait_fut, exit_fut);
1198 })
1199 .await;
1200 }
1201}