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_android_bootreason;
12use bstr::{BString, ByteSlice};
13use devicetree::parser::parse_devicetree;
14use devicetree::types::Devicetree;
15use fidl::endpoints::{ControlHandle, RequestStream, ServerEnd};
16use fidl_fuchsia_component_runner::{TaskProviderRequest, TaskProviderRequestStream};
17use fidl_fuchsia_feedback::CrashReporterMarker;
18use fidl_fuchsia_time_external::AdjustMarker;
19use fuchsia_async::DurationExt;
20use fuchsia_component::client::{connect_to_protocol, connect_to_protocol_sync};
21use fuchsia_component::server::ServiceFs;
22use futures::channel::oneshot;
23use futures::{FutureExt, StreamExt, TryStreamExt};
24use serde::Deserialize;
25use starnix_container_structured_config::Config as ContainerStructuredConfig;
26use starnix_core::device::remote_block_device::remote_block_device_init;
27use starnix_core::execution::{
28 create_init_process, create_system_task, execute_task_with_prerun_result,
29};
30use starnix_core::fs::fuchsia::new_remotefs_in_root;
31use starnix_core::fs::tmpfs::TmpFs;
32use starnix_core::security;
33use starnix_core::task::container_namespace::ContainerNamespace;
34use starnix_core::task::{
35 CurrentTask, ExitStatus, Kernel, RoleOverrides, SchedulerManager, parse_cmdline,
36};
37use starnix_core::vfs::{FileSystemOptions, FsContext, LookupContext, Namespace, WhatToMount};
38use starnix_logging::{
39 CATEGORY_STARNIX, NAME_CREATE_CONTAINER, log_debug, log_error, log_info, log_warn,
40 trace_duration,
41};
42use starnix_modules::{init_common_devices, register_common_file_systems};
43use starnix_modules_layeredfs::LayeredFs;
44use starnix_modules_magma::get_magma_params;
45use starnix_modules_overlayfs::OverlayStack;
46use starnix_modules_rtc::rtc_device_init;
47use starnix_sync::{Locked, Unlocked};
48use starnix_task_command::TaskCommand;
49use starnix_uapi::errors::{ENOENT, SourceContext};
50use starnix_uapi::open_flags::OpenFlags;
51use starnix_uapi::resource_limits::Resource;
52use starnix_uapi::{errno, tid_t};
53use std::collections::BTreeMap;
54use std::ffi::CString;
55use std::ops::DerefMut;
56use std::sync::Arc;
57use zx::Task as _;
58use {
59 fidl_fuchsia_boot as fboot, fidl_fuchsia_component as fcomponent,
60 fidl_fuchsia_component_runner as frunner, fidl_fuchsia_element as felement,
61 fidl_fuchsia_io as fio, fidl_fuchsia_mem as fmem,
62 fidl_fuchsia_memory_attribution as fattribution, fidl_fuchsia_starnix_binder as fbinder,
63 fidl_fuchsia_starnix_container as fstarcontainer, fuchsia_async as fasync,
64 fuchsia_inspect as inspect, fuchsia_runtime as fruntime, fuchsia_zbi as zbi,
65};
66
67use std::sync::Weak;
68
69use crate::serve_memory_attribution_provider_container;
70use attribution_server::{AttributionServer, AttributionServerHandle};
71use fidl::HandleBased;
72
73struct ContainerMemoryAttributionManager {
75 memory_attribution_server: AttributionServerHandle,
77}
78
79impl ContainerMemoryAttributionManager {
80 pub fn new(kernel: Weak<Kernel>, component_instance: zx::Event) -> Self {
83 let memory_attribution_server = AttributionServer::new(Box::new(move || {
84 let kernel_ref = match kernel.upgrade() {
85 None => return vec![],
86 Some(k) => k,
87 };
88 attribution_info_for_kernel(kernel_ref.as_ref(), &component_instance)
89 }));
90
91 ContainerMemoryAttributionManager { memory_attribution_server }
92 }
93
94 pub fn new_observer(
96 &self,
97 control_handle: fattribution::ProviderControlHandle,
98 ) -> attribution_server::Observer {
99 self.memory_attribution_server.new_observer(control_handle)
100 }
101}
102
103fn attribution_info_for_kernel(
107 kernel: &Kernel,
108 component_instance: &zx::Event,
109) -> Vec<fattribution::AttributionUpdate> {
110 let (client_end, server_end) =
114 fidl::endpoints::create_request_stream::<fattribution::ProviderMarker>();
115 fuchsia_async::Task::spawn(serve_memory_attribution_provider_container(server_end, kernel))
116 .detach();
117
118 let starnix_kernel_id = Some(1);
119 let starnix_kernel_principal = fattribution::NewPrincipal {
120 identifier: starnix_kernel_id,
121 description: Some(fattribution::Description::Part("starnix_kernel".to_string())),
122 principal_type: Some(fattribution::PrincipalType::Part),
123 detailed_attribution: None,
127 ..Default::default()
128 };
129
130 let starnix_kernel_attribution = fattribution::UpdatedPrincipal {
131 identifier: starnix_kernel_id, resources: Some(fattribution::Resources::Data(fattribution::Data {
133 resources: vec![fattribution::Resource::ProcessMapped(fattribution::ProcessMapped {
134 process: fuchsia_runtime::process_self().koid().unwrap().raw_koid(),
135 base: 0, len: u64::max_value(),
137 hint_skip_handle_table: false,
138 })],
139 })),
140 ..Default::default()
141 };
142
143 let container_id = Some(2);
144 let new_principal = fattribution::NewPrincipal {
145 identifier: container_id,
146 description: Some(fattribution::Description::Component(
147 component_instance.duplicate_handle(zx::Rights::SAME_RIGHTS).unwrap(),
148 )),
149 principal_type: Some(fattribution::PrincipalType::Runnable),
150 detailed_attribution: Some(client_end),
151 ..Default::default()
152 };
153 let attribution = fattribution::UpdatedPrincipal {
154 identifier: container_id,
155 resources: Some(fattribution::Resources::Data(fattribution::Data {
156 resources: vec![fattribution::Resource::KernelObject(
157 fuchsia_runtime::job_default().koid().unwrap().raw_koid(),
158 )],
159 })),
160 ..Default::default()
161 };
162
163 vec![
164 fattribution::AttributionUpdate::Add(new_principal),
165 fattribution::AttributionUpdate::Add(starnix_kernel_principal),
166 fattribution::AttributionUpdate::Update(attribution),
167 fattribution::AttributionUpdate::Update(starnix_kernel_attribution),
168 ]
169}
170
171#[derive(Debug)]
172pub struct ContainerStartInfo {
173 pub program: ContainerProgram,
175
176 pub config: ContainerStructuredConfig,
177
178 outgoing_dir: Option<zx::Channel>,
182
183 pub container_namespace: ContainerNamespace,
186
187 runtime_dir: Option<ServerEnd<fio::DirectoryMarker>>,
189
190 break_on_start: Option<zx::EventPair>,
192
193 component_instance: Option<zx::Event>,
196}
197
198const MISSING_CONFIG_VMO_CONTEXT: &str = concat!(
199 "Retrieving container config VMO. ",
200 "If this fails, make sure your container CML includes ",
201 "//src/starnix/containers/container.shard.cml.",
202);
203
204impl ContainerStartInfo {
205 fn new(mut start_info: frunner::ComponentStartInfo) -> Result<Self, Error> {
206 let program = start_info.program.as_ref().context("retrieving program block")?;
207 let program: ContainerProgram =
208 runner::serde::deserialize_program(&program).context("parsing program block")?;
209
210 let encoded_config =
211 start_info.encoded_config.as_ref().context(MISSING_CONFIG_VMO_CONTEXT)?;
212 let config = match encoded_config {
213 fmem::Data::Bytes(b) => ContainerStructuredConfig::from_bytes(b),
214 fmem::Data::Buffer(b) => ContainerStructuredConfig::from_vmo(&b.vmo),
215 other => anyhow::bail!("unknown Data variant {other:?}"),
216 }
217 .context("parsing container structured config")?;
218
219 let ns = start_info.ns.take().context("retrieving container namespace")?;
220 let container_namespace = ContainerNamespace::from(ns);
221
222 let outgoing_dir = start_info.outgoing_dir.take().map(|dir| dir.into_channel());
223 let component_instance = start_info.component_instance;
224
225 Ok(Self {
226 program,
227 config,
228 outgoing_dir,
229 container_namespace,
230 component_instance,
231 break_on_start: start_info.break_on_start,
232 runtime_dir: start_info.runtime_dir,
233 })
234 }
235}
236
237#[derive(Debug, Default, Deserialize)]
238#[serde(deny_unknown_fields)]
239pub struct ContainerProgram {
240 name: String,
242
243 init: Vec<String>,
245
246 #[serde(default)]
248 kernel_cmdline: String,
249
250 #[serde(default)]
252 mounts: Vec<String>,
253
254 #[serde(default)]
256 pub features: Vec<String>,
257
258 #[serde(default)]
260 rlimits: Vec<String>,
261
262 #[serde(default)]
264 startup_file_path: String,
265
266 #[serde(default)]
270 pub default_seclabel: Option<String>,
271
272 #[serde(default = "default_uid")]
276 pub default_uid: runner::serde::StoreAsString<u32>,
277
278 pub default_ns_mount_options: Option<Vec<String>>,
282
283 #[serde(default)]
294 task_role_overrides: Vec<TaskSchedulerMapping>,
295}
296
297#[derive(Default, Deserialize)]
300struct TaskSchedulerMapping {
301 role: String,
303 process: String,
305 thread: String,
307}
308
309impl std::fmt::Debug for TaskSchedulerMapping {
310 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
311 write!(f, "process `{}` thread `{}` role `{}`", self.process, self.thread, self.role)
312 }
313}
314
315fn default_uid() -> runner::serde::StoreAsString<u32> {
316 runner::serde::StoreAsString(42)
317}
318
319fn to_cstr(str: &str) -> CString {
321 CString::new(str.to_string()).unwrap()
322}
323
324#[must_use = "The container must run serve on this config"]
325pub struct ContainerServiceConfig {
326 start_info: ContainerStartInfo,
327 request_stream: frunner::ComponentControllerRequestStream,
328 receiver: oneshot::Receiver<Result<ExitStatus, Error>>,
329}
330
331pub struct Container {
332 pub kernel: Arc<Kernel>,
334
335 memory_attribution_manager: ContainerMemoryAttributionManager,
336
337 _node: inspect::Node,
339
340 _thread_bound: std::marker::PhantomData<*mut u8>,
343}
344
345impl Container {
346 pub fn system_task(&self) -> &CurrentTask {
347 self.kernel.kthreads.system_task()
348 }
349
350 async fn serve_outgoing_directory(
351 &self,
352 outgoing_dir: Option<zx::Channel>,
353 ) -> Result<(), Error> {
354 if let Some(outgoing_dir) = outgoing_dir {
355 let mut fs = ServiceFs::new_local();
358 fs.dir("svc")
359 .add_fidl_service(ExposedServices::ComponentRunner)
360 .add_fidl_service(ExposedServices::ContainerController)
361 .add_fidl_service(ExposedServices::GraphicalPresenter)
362 .add_fidl_service(ExposedServices::LutexController);
363
364 let (fs_root, fs_root_server_end) = fidl::endpoints::create_proxy();
366 fs.add_remote("fs_root", fs_root);
367 expose_root(
368 self.kernel.kthreads.unlocked_for_async().deref_mut(),
369 self.system_task(),
370 fs_root_server_end,
371 )?;
372
373 fs.serve_connection(outgoing_dir.into()).map_err(|_| errno!(EINVAL))?;
374
375 fs.for_each_concurrent(None, |request_stream| async {
376 match request_stream {
377 ExposedServices::ComponentRunner(request_stream) => {
378 match serve_component_runner(request_stream, self.system_task()).await {
379 Ok(_) => {}
380 Err(e) => {
381 log_error!("Error serving component runner: {:?}", e);
382 }
383 }
384 }
385 ExposedServices::ContainerController(request_stream) => {
386 serve_container_controller(request_stream, self.system_task())
387 .await
388 .expect("failed to start container.")
389 }
390 ExposedServices::GraphicalPresenter(request_stream) => {
391 serve_graphical_presenter(request_stream, &self.kernel)
392 .await
393 .expect("failed to start GraphicalPresenter.")
394 }
395 ExposedServices::LutexController(request_stream) => {
396 serve_lutex_controller(request_stream, self.system_task())
397 .await
398 .expect("failed to start LutexController.")
399 }
400 }
401 })
402 .await
403 }
404 Ok(())
405 }
406
407 pub async fn serve(&self, service_config: ContainerServiceConfig) -> Result<(), Error> {
408 let (r, _) = futures::join!(
409 self.serve_outgoing_directory(service_config.start_info.outgoing_dir),
410 server_component_controller(
411 self.kernel.clone(),
412 service_config.request_stream,
413 service_config.receiver
414 )
415 );
416 r
417 }
418
419 pub fn new_memory_attribution_observer(
420 &self,
421 control_handle: fattribution::ProviderControlHandle,
422 ) -> attribution_server::Observer {
423 self.memory_attribution_manager.new_observer(control_handle)
424 }
425}
426
427enum ExposedServices {
429 ComponentRunner(frunner::ComponentRunnerRequestStream),
430 ContainerController(fstarcontainer::ControllerRequestStream),
431 GraphicalPresenter(felement::GraphicalPresenterRequestStream),
432 LutexController(fbinder::LutexControllerRequestStream),
433}
434
435type TaskResult = Result<ExitStatus, Error>;
436
437async fn server_component_controller(
438 kernel: Arc<Kernel>,
439 request_stream: frunner::ComponentControllerRequestStream,
440 task_complete: oneshot::Receiver<TaskResult>,
441) {
442 *kernel.container_control_handle.lock() = Some(request_stream.control_handle());
443
444 enum Event<T, U> {
445 Controller(T),
446 Completion(U),
447 }
448
449 let mut stream = futures::stream::select(
450 request_stream.map(Event::Controller),
451 task_complete.into_stream().map(Event::Completion),
452 );
453
454 while let Some(event) = stream.next().await {
455 match event {
456 Event::Controller(Ok(frunner::ComponentControllerRequest::Stop { .. })) => {
457 log_info!("Stopping the container.");
458 }
459 Event::Controller(Ok(frunner::ComponentControllerRequest::Kill { control_handle })) => {
460 log_info!("Killing the container's job.");
461 control_handle.shutdown_with_epitaph(zx::Status::from_raw(
462 fcomponent::Error::InstanceDied.into_primitive() as i32,
463 ));
464 fruntime::job_default().kill().expect("Failed to kill job");
465 }
466 Event::Controller(Ok(frunner::ComponentControllerRequest::_UnknownMethod {
467 ordinal,
468 method_type,
469 ..
470 })) => {
471 log_error!(ordinal, method_type:?; "Unknown component controller request received.");
472 }
473 Event::Controller(Err(e)) => {
474 log_warn!(e:?; "Container component controller channel encountered an error.");
475 }
476 Event::Completion(result) => {
477 log_info!(result:?; "init process exited.");
478 }
479 }
480
481 if !kernel.is_shutting_down() {
483 kernel.shut_down();
484 }
485 }
486
487 log_debug!("done listening for container-terminating events");
488
489 if !kernel.is_shutting_down() {
491 kernel.shut_down();
492 }
493}
494
495pub async fn create_component_from_stream(
496 mut request_stream: frunner::ComponentRunnerRequestStream,
497 kernel_extra_features: Vec<String>,
498) -> Result<(Container, ContainerServiceConfig), Error> {
499 if let Some(event) = request_stream.try_next().await? {
500 match event {
501 frunner::ComponentRunnerRequest::Start { start_info, controller, .. } => {
502 let request_stream = controller.into_stream();
503 let mut start_info = ContainerStartInfo::new(start_info)?;
504 let (sender, receiver) = oneshot::channel::<TaskResult>();
505 let container = create_container(&mut start_info, &kernel_extra_features, sender)
506 .await
507 .with_source_context(|| {
508 format!("creating container \"{}\"", start_info.program.name)
509 })?;
510 let service_config =
511 ContainerServiceConfig { start_info, request_stream, receiver };
512 return Ok((container, service_config));
513 }
514 frunner::ComponentRunnerRequest::_UnknownMethod { ordinal, .. } => {
515 log_warn!("Unknown ComponentRunner request: {ordinal}");
516 }
517 }
518 }
519 bail!("did not receive Start request");
520}
521
522async fn get_bootargs(device_tree: &Devicetree) -> Result<String, Error> {
523 device_tree
524 .root_node
525 .find("chosen")
526 .and_then(|n| {
527 n.get_property("bootargs").map(|p| {
528 let end =
529 if p.value.last() == Some(&0) { p.value.len() - 1 } else { p.value.len() };
530 match std::str::from_utf8(&p.value[..end]) {
531 Ok(s) => Ok(s.to_owned()),
532 Err(e) => {
533 log_warn!("Bootargs are not valid UTF-8: {e}");
534 Err(anyhow!("Bootargs are not valid UTF-8"))
535 }
536 }
537 })
538 })
539 .context("Couldn't find bootargs")?
540}
541
542async fn get_bootitems() -> Result<std::vec::Vec<u8>, Error> {
543 let items =
544 connect_to_protocol::<fboot::ItemsMarker>().context("Failed to connect to boot items")?;
545
546 let items_response = items
547 .get2(zbi::ZbiType::DeviceTree.into_raw(), None)
548 .await
549 .context("FIDL: Failed to get devicetree item")?
550 .map_err(|e| anyhow!("Failed to get devicetree item {:?}", e))?;
551
552 let Some(item) = items_response.last() else {
553 return Err(anyhow!("Failed to get items"));
554 };
555
556 let devicetree_vmo = &item.payload;
557 let bytes = devicetree_vmo
558 .read_to_vec(0, item.length as u64)
559 .context("Failed to read devicetree vmo")?;
560
561 Ok(bytes)
562}
563
564async fn create_container(
565 start_info: &mut ContainerStartInfo,
566 kernel_extra_features: &[String],
567 task_complete: oneshot::Sender<TaskResult>,
568) -> Result<Container, Error> {
569 trace_duration!(CATEGORY_STARNIX, NAME_CREATE_CONTAINER);
570 const DEFAULT_INIT: &str = "/container/init";
571
572 let pkg_channel = start_info.container_namespace.get_namespace_channel("/pkg").unwrap();
573 let pkg_dir_proxy = fio::DirectorySynchronousProxy::new(pkg_channel);
574
575 let device_tree: Option<Devicetree> = match get_bootitems().await {
576 Ok(items) => match parse_devicetree(&items) {
577 Ok(device_tree) => Some(device_tree),
578 Err(e) => {
579 log_warn!("Failed to parse devicetree: {e:?}");
580 None
581 }
582 },
583 Err(e) => {
584 log_warn!("Failed to get boot items for devicetree: {e:?}");
585 None
586 }
587 };
588 let mut features = parse_features(&start_info, kernel_extra_features)?;
589
590 log_debug!("Creating container with {:#?}", features);
591 let mut kernel_cmdline = BString::from(start_info.program.kernel_cmdline.as_bytes());
592 if features.android_serialno {
593 if let Some(device_tree) = &device_tree {
594 match get_bootargs(device_tree).await {
595 Ok(args) => {
596 for item in parse_cmdline(&args) {
597 if item.starts_with("androidboot.force_normal_boot") {
598 continue;
600 }
601 if item.starts_with("androidboot.bootreason") && features.android_bootreason
602 {
603 log_info!("Original devicetree bootarg {:?}", item);
607 continue;
608 }
609 kernel_cmdline.extend(b" ");
610 kernel_cmdline.extend(item.bytes());
611 }
612 }
613 Err(err) => log_warn!("could not get bootargs: {err:?}"),
614 }
615 } else {
616 log_warn!("No devicetree available to get bootargs for android.serialno");
617 }
618 }
619 if features.android_bootreason {
620 kernel_cmdline.extend(b" androidboot.bootreason=");
621
622 let tmp_channel = start_info.container_namespace.get_namespace_channel("/tmp_lifecycle");
623 let tmp_proxy = match tmp_channel {
624 Ok(channel) => {
625 Some(fio::DirectoryProxy::new(fidl::AsyncChannel::from_channel(channel)))
626 }
627 _ => None,
628 };
629
630 match get_android_bootreason(tmp_proxy).await {
631 Ok(reason) => {
632 kernel_cmdline.extend(reason.bytes());
633 }
634 Err(err) => {
635 log_warn!("could not get android bootreason: {err:?}. falling back to 'unknown'");
636 kernel_cmdline.extend(b"unknown");
637 }
638 }
639 }
640 if let Some(supported_vendors) = &features.magma_supported_vendors {
641 kernel_cmdline.extend(b" ");
642 let params = get_magma_params(supported_vendors);
643 kernel_cmdline.extend(&*params);
644 }
645
646 let mut task_mappings = RoleOverrides::new();
649 for m in &start_info.program.task_role_overrides {
650 task_mappings.add(m.process.clone(), m.thread.clone(), m.role.clone());
651 }
652 let task_mappings = task_mappings.build().context("adding custom task role")?;
653 let scheduler_manager = SchedulerManager::new(task_mappings);
654
655 let crash_reporter = connect_to_protocol::<CrashReporterMarker>().unwrap();
656
657 let node = inspect::component::inspector().root().create_child("container");
658 let kernel_node = node.create_child("kernel");
659 kernel_node.record_int("created_at", zx::MonotonicInstant::get().into_nanos());
660 features.record_inspect(&kernel_node);
661
662 let security_state = security::kernel_init_security(
663 features.selinux.enabled,
664 features.selinux.options.clone(),
665 features.selinux.exceptions.clone(),
666 &kernel_node,
667 );
668
669 let time_adjustment_proxy = if features.enable_utc_time_adjustment {
672 connect_to_protocol_sync::<AdjustMarker>()
673 .map_err(|e| log_error!("could not connect to fuchsia.time.external/Adjust: {:?}", e))
674 .ok()
675 } else {
676 log_info!("UTC adjustment is forbidden.");
678 None
679 };
680
681 log_info!("final kernel cmdline: {kernel_cmdline:?}");
682 kernel_node.record_string("cmdline", kernel_cmdline.to_str_lossy());
683
684 let kernel = Kernel::new(
685 kernel_cmdline,
686 features.kernel.clone(),
687 std::mem::take(&mut features.system_limits),
688 start_info.container_namespace.try_clone()?,
689 scheduler_manager,
690 Some(crash_reporter),
691 kernel_node,
692 security_state,
693 time_adjustment_proxy,
694 device_tree,
695 )
696 .with_source_context(|| format!("creating Kernel: {}", &start_info.program.name))?;
697 let fs_context = create_fs_context(
698 kernel.kthreads.unlocked_for_async().deref_mut(),
699 &kernel,
700 &features,
701 start_info,
702 &pkg_dir_proxy,
703 )
704 .source_context("creating FsContext")?;
705 let init_pid = kernel.pids.write().allocate_pid();
706 debug_assert_eq!(init_pid, 1);
708
709 let system_task = create_system_task(
710 kernel.kthreads.unlocked_for_async().deref_mut(),
711 &kernel,
712 Arc::clone(&fs_context),
713 )
714 .source_context("create system task")?;
715 debug_assert_eq!(system_task.tid, 2);
718
719 kernel.kthreads.init(system_task).source_context("initializing kthreads")?;
720 let system_task = kernel.kthreads.system_task();
721
722 kernel.syslog.init(&system_task).source_context("initializing syslog")?;
723
724 kernel.hrtimer_manager.init(system_task).source_context("initializing HrTimer manager")?;
725
726 log_info!("Initializing suspend resume manager.");
727 if let Err(e) = kernel.suspend_resume_manager.init(&system_task) {
728 log_warn!("Suspend/Resume manager initialization failed: ({e:?})");
729 }
730
731 log_info!("Initializing RTC device.");
733 rtc_device_init(kernel.kthreads.unlocked_for_async().deref_mut(), &system_task)
734 .context("in starnix_kernel_runner, while initializing RTC")?;
735
736 log_info!("Registering devices and filesystems.");
738 init_common_devices(kernel.kthreads.unlocked_for_async().deref_mut(), &kernel)?;
739 register_common_file_systems(kernel.kthreads.unlocked_for_async().deref_mut(), &kernel);
740
741 log_info!("Mounting filesystems.");
742 mount_filesystems(
743 kernel.kthreads.unlocked_for_async().deref_mut(),
744 &system_task,
745 start_info,
746 &pkg_dir_proxy,
747 )
748 .source_context("mounting filesystems")?;
749
750 {
752 log_info!("Running container features.");
753 run_container_features(
754 kernel.kthreads.unlocked_for_async().deref_mut(),
755 &system_task,
756 &features,
757 )?;
758 }
759
760 log_info!("Initializing remote block devices.");
761 init_remote_block_devices(kernel.kthreads.unlocked_for_async().deref_mut(), &system_task)
762 .source_context("initalizing remote block devices")?;
763
764 let argv = if start_info.program.init.is_empty() {
769 vec![DEFAULT_INIT.to_string()]
770 } else {
771 start_info.program.init.clone()
772 }
773 .iter()
774 .map(|s| to_cstr(s))
775 .collect::<Vec<_>>();
776
777 log_info!("Opening start_info file.");
778 let executable = system_task
779 .open_file(
780 kernel.kthreads.unlocked_for_async().deref_mut(),
781 argv[0].as_bytes().into(),
782 OpenFlags::RDONLY,
783 )
784 .with_source_context(|| format!("opening init: {:?}", &argv[0]))?;
785
786 let initial_name = if start_info.program.init.is_empty() {
787 TaskCommand::default()
788 } else {
789 TaskCommand::new(start_info.program.init[0].as_bytes())
790 };
791
792 let rlimits = parse_rlimits(&start_info.program.rlimits)?;
793
794 log_info!("Starting runtime directory.");
796 if let Some(runtime_dir) = start_info.runtime_dir.take() {
797 kernel.kthreads.spawn_future(
798 move || async move { serve_runtime_dir(runtime_dir).await },
799 "serve_runtime_dir",
800 );
801 }
802
803 if let Some(break_on_start) = start_info.break_on_start.take() {
806 log_info!("Waiting for signal from debugger before spawning init process...");
807 if let Err(e) =
808 fuchsia_async::OnSignals::new(break_on_start, zx::Signals::EVENTPAIR_PEER_CLOSED).await
809 {
810 log_warn!(e:%; "Received break_on_start eventpair but couldn't wait for PEER_CLOSED.");
811 }
812 }
813
814 log_info!("Creating init process.");
815 let init_task = create_init_process(
816 kernel.kthreads.unlocked_for_async().deref_mut(),
817 &kernel,
818 init_pid,
819 initial_name,
820 Arc::clone(&fs_context),
821 &rlimits,
822 )
823 .with_source_context(|| format!("creating init task: {:?}", &start_info.program.init))?;
824
825 execute_task_with_prerun_result(
826 kernel.kthreads.unlocked_for_async().deref_mut(),
827 init_task,
828 move |locked, init_task| {
829 parse_numbered_handles(locked, init_task, None, &init_task.files).expect("");
830 init_task.exec(locked, executable, argv[0].clone(), argv.clone(), vec![])
831 },
832 move |result| {
833 log_info!("Finished running init process: {:?}", result);
834 let _ = task_complete.send(result);
835 },
836 None,
837 )?;
838
839 if !start_info.program.startup_file_path.is_empty() {
840 wait_for_init_file(&start_info.program.startup_file_path, &system_task, init_pid).await?;
841 };
842
843 let memory_attribution_manager = ContainerMemoryAttributionManager::new(
844 Arc::downgrade(&kernel),
845 start_info.component_instance.take().ok_or_else(|| Error::msg("No component instance"))?,
846 );
847
848 Ok(Container {
849 kernel,
850 memory_attribution_manager,
851 _node: node,
852 _thread_bound: Default::default(),
853 })
854}
855
856fn create_fs_context(
857 locked: &mut Locked<Unlocked>,
858 kernel: &Kernel,
859 features: &Features,
860 start_info: &ContainerStartInfo,
861 pkg_dir_proxy: &fio::DirectorySynchronousProxy,
862) -> Result<Arc<FsContext>, Error> {
863 let mut mounts_iter =
867 start_info.program.mounts.iter().chain(start_info.config.additional_mounts.iter());
868 let mut root = MountAction::new_for_root(
869 locked,
870 kernel,
871 pkg_dir_proxy,
872 mounts_iter.next().ok_or_else(|| anyhow!("Mounts list is empty"))?,
873 )?;
874 if root.path != "/" {
875 anyhow::bail!("First mount in mounts list is not the root");
876 }
877
878 let mut mappings = vec![];
880 if features.container {
881 let component_tmpfs_options = FileSystemOptions {
884 params: kernel
885 .features
886 .ns_mount_options("#component_tmpfs")
887 .context("#component_tmpfs options")?,
888 ..Default::default()
889 };
890 let component_tmpfs = TmpFs::new_fs_with_options(locked, kernel, component_tmpfs_options)?;
891
892 let container_remotefs_options = FileSystemOptions {
894 source: "data".into(),
895 params: kernel.features.ns_mount_options("#container").context("#container options")?,
896 ..Default::default()
897 };
898 let container_remotefs = new_remotefs_in_root(
899 locked,
900 kernel,
901 pkg_dir_proxy,
902 container_remotefs_options,
903 fio::PERM_READABLE | fio::PERM_EXECUTABLE,
904 )?;
905
906 let container_fs = LayeredFs::new_fs(
907 locked,
908 kernel,
909 container_remotefs,
910 BTreeMap::from([("component".into(), component_tmpfs)]),
911 );
912 mappings.push(("container".into(), container_fs));
913 }
914 if features.custom_artifacts {
915 let mount_options = FileSystemOptions {
916 params: kernel
917 .features
918 .ns_mount_options("#custom_artifacts")
919 .context("#custom_artifacts options")?,
920 ..Default::default()
921 };
922 mappings.push((
923 "custom_artifacts".into(),
924 TmpFs::new_fs_with_options(locked, kernel, mount_options)?,
925 ));
926 }
927 if features.test_data {
928 let mount_options = FileSystemOptions {
929 params: kernel.features.ns_mount_options("#test_data").context("#test_data options")?,
930 ..Default::default()
931 };
932 mappings
933 .push(("test_data".into(), TmpFs::new_fs_with_options(locked, kernel, mount_options)?));
934 }
935
936 if !mappings.is_empty() {
937 root.fs = LayeredFs::new_fs(locked, kernel, root.fs, mappings.into_iter().collect());
940 }
941 if features.rootfs_rw {
942 root.fs = OverlayStack::wrap_fs_in_writable_layer(locked, kernel, root.fs)?;
943 }
944 Ok(FsContext::new(Namespace::new_with_flags(root.fs, root.flags)))
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 locked: &mut Locked<Unlocked>,
967 system_task: &CurrentTask,
968 start_info: &ContainerStartInfo,
969 pkg_dir_proxy: &fio::DirectorySynchronousProxy,
970) -> Result<(), Error> {
971 let mut mounts_iter =
973 start_info.program.mounts.iter().chain(start_info.config.additional_mounts.iter());
974 let _ = mounts_iter.next();
975 for mount_spec in mounts_iter {
976 let action = MountAction::from_spec(locked, system_task, pkg_dir_proxy, mount_spec)
977 .with_source_context(|| format!("creating filesystem from spec: {}", &mount_spec))?;
978 let mount_point = system_task
979 .lookup_path_from_root(locked, action.path.as_ref())
980 .with_source_context(|| format!("lookup path from root: {}", action.path))?;
981 mount_point.mount(WhatToMount::Fs(action.fs), action.flags)?;
982 }
983 Ok(())
984}
985
986fn init_remote_block_devices(
987 locked: &mut Locked<Unlocked>,
988 system_task: &CurrentTask,
989) -> Result<(), Error> {
990 remote_block_device_init(locked, system_task);
991 let entries = match std::fs::read_dir("/block") {
992 Ok(entries) => entries,
993 Err(e) => {
994 log_warn!("Failed to read block directory: {}", e);
995 return Ok(());
996 }
997 };
998 for entry in entries {
999 let entry = entry?;
1000 let path_buf = entry.path();
1001 let path = path_buf.to_str().ok_or_else(|| anyhow!("Invalid block device path"))?;
1002 let (client_end, server_end) = fidl::endpoints::create_endpoints();
1003 match fdio::service_connect(
1004 &format!("{}/fuchsia.storage.block.Block", path),
1005 server_end.into(),
1006 ) {
1007 Ok(()) => (),
1008 Err(e) => {
1009 log_warn!("Failed to connect to block device at {}: {}", path, e);
1010 continue;
1011 }
1012 }
1013 system_task.kernel().remote_block_device_registry.create_remote_block_device(
1014 locked,
1015 system_task,
1016 entry.file_name().to_str().unwrap(),
1017 client_end,
1018 )?;
1019 }
1020 Ok(())
1021}
1022
1023async fn wait_for_init_file(
1024 startup_file_path: &str,
1025 current_task: &CurrentTask,
1026 init_tid: tid_t,
1027) -> Result<(), Error> {
1028 loop {
1030 fasync::Timer::new(fasync::MonotonicDuration::from_millis(100).after_now()).await;
1031
1032 let creds = security::creds_start_internal_operation(current_task);
1033 if let Some(result) = current_task.override_creds(creds, || {
1034 let root = current_task.fs().root();
1035 let mut context = LookupContext::default();
1036
1037 match current_task.lookup_path(
1038 current_task.kernel().kthreads.unlocked_for_async().deref_mut(),
1039 &mut context,
1040 root,
1041 startup_file_path.into(),
1042 ) {
1043 Ok(_) => return Some(Ok(())),
1044 Err(error) if error == ENOENT => {}
1045 Err(error) => return Some(Err(anyhow::Error::from(error))),
1046 };
1047
1048 if current_task.get_task(init_tid).upgrade().is_none() {
1049 return Some(Err(anyhow!(
1050 "Init task terminated before startup_file_path was ready"
1051 )));
1052 }
1053
1054 None
1055 }) {
1056 return result;
1057 }
1058 }
1059}
1060
1061async fn serve_runtime_dir(runtime_dir: ServerEnd<fio::DirectoryMarker>) {
1062 let mut fs = fuchsia_component::server::ServiceFs::new();
1063 match create_job_id_vmo() {
1064 Ok(vmo) => {
1065 fs.dir("elf").add_vmo_file_at("job_id", vmo);
1066 }
1067 Err(e) => log_error!(e:%; "failed to create vmo with job id for debuggers"),
1068 }
1069 match fs.serve_connection(runtime_dir) {
1070 Ok(_) => {
1071 fs.add_fidl_service(|job_requests: TaskProviderRequestStream| {
1072 fuchsia_async::Task::local(async move {
1073 if let Err(e) = serve_task_provider(job_requests).await {
1074 log_warn!(e:?; "Error serving TaskProvider");
1075 }
1076 })
1077 .detach();
1078 });
1079 fs.collect::<()>().await;
1080 }
1081 Err(e) => log_error!("Couldn't serve runtime directory: {e:?}"),
1082 }
1083}
1084
1085fn create_job_id_vmo() -> Result<zx::Vmo, Error> {
1086 let job_id = fuchsia_runtime::job_default().koid().context("reading own job koid")?;
1087 let job_id_str = job_id.raw_koid().to_string();
1088 let job_id_vmo = zx::Vmo::create(job_id_str.len() as u64).context("creating job id vmo")?;
1089 job_id_vmo.write(job_id_str.as_bytes(), 0).context("write job id to vmo")?;
1090 Ok(job_id_vmo)
1091}
1092
1093async fn serve_task_provider(mut job_requests: TaskProviderRequestStream) -> Result<(), Error> {
1094 while let Some(request) = job_requests.next().await {
1095 match request.context("getting next TaskProvider request")? {
1096 TaskProviderRequest::GetJob { responder } => {
1097 responder
1098 .send(
1099 fuchsia_runtime::job_default()
1100 .duplicate_handle(zx::Rights::SAME_RIGHTS)
1101 .map_err(|s| s.into_raw()),
1102 )
1103 .context("sending job for runtime dir")?;
1104 }
1105 unknown => bail!("Unknown TaskProvider method {unknown:?}"),
1106 }
1107 }
1108 Ok(())
1109}
1110
1111#[cfg(test)]
1112mod test {
1113 use super::wait_for_init_file;
1114 use fuchsia_async as fasync;
1115 use futures::{SinkExt, StreamExt};
1116 #[allow(deprecated, reason = "pre-existing usage")]
1117 use starnix_core::testing::create_kernel_task_and_unlocked;
1118 use starnix_core::vfs::FdNumber;
1119 use starnix_uapi::CLONE_FS;
1120 use starnix_uapi::file_mode::{AccessCheck, FileMode};
1121 use starnix_uapi::open_flags::OpenFlags;
1122 use starnix_uapi::signals::SIGCHLD;
1123 use starnix_uapi::vfs::ResolveFlags;
1124
1125 #[fuchsia::test]
1126 async fn test_init_file_already_exists() {
1127 #[allow(deprecated, reason = "pre-existing usage")]
1128 let (_kernel, current_task, locked) = create_kernel_task_and_unlocked();
1129 let (mut sender, mut receiver) = futures::channel::mpsc::unbounded();
1130
1131 let path = "/path";
1132 current_task
1133 .open_file_at(
1134 locked,
1135 FdNumber::AT_FDCWD,
1136 path.into(),
1137 OpenFlags::CREAT,
1138 FileMode::default(),
1139 ResolveFlags::empty(),
1140 AccessCheck::default(),
1141 )
1142 .expect("Failed to create file");
1143
1144 fasync::Task::local(async move {
1145 wait_for_init_file(path, ¤t_task, current_task.get_tid())
1146 .await
1147 .expect("failed to wait for file");
1148 sender.send(()).await.expect("failed to send message");
1149 })
1150 .detach();
1151
1152 assert!(receiver.next().await.is_some());
1154 }
1155
1156 #[fuchsia::test]
1157 async fn test_init_file_wait_required() {
1158 #[allow(deprecated, reason = "pre-existing usage")]
1159 let (_kernel, current_task, locked) = create_kernel_task_and_unlocked();
1160 let (mut sender, mut receiver) = futures::channel::mpsc::unbounded();
1161
1162 let init_task = current_task.clone_task_for_test(locked, CLONE_FS as u64, Some(SIGCHLD));
1163 let path = "/path";
1164
1165 let test_init_tid = current_task.get_tid();
1166 fasync::Task::local(async move {
1167 sender.send(()).await.expect("failed to send message");
1168 wait_for_init_file(path, &init_task, test_init_tid)
1169 .await
1170 .expect("failed to wait for file");
1171 sender.send(()).await.expect("failed to send message");
1172 })
1173 .detach();
1174
1175 assert!(receiver.next().await.is_some());
1177
1178 current_task
1180 .open_file_at(
1181 locked,
1182 FdNumber::AT_FDCWD,
1183 path.into(),
1184 OpenFlags::CREAT,
1185 FileMode::default(),
1186 ResolveFlags::empty(),
1187 AccessCheck::default(),
1188 )
1189 .expect("Failed to create file");
1190
1191 assert!(receiver.next().await.is_some());
1193 }
1194
1195 #[fuchsia::test]
1196 async fn test_init_exits_before_file_exists() {
1197 #[allow(deprecated, reason = "pre-existing usage")]
1198 let (_kernel, current_task, locked) = create_kernel_task_and_unlocked();
1199 let (mut sender, mut receiver) = futures::channel::mpsc::unbounded();
1200
1201 let init_task = current_task.clone_task_for_test(locked, CLONE_FS as u64, Some(SIGCHLD));
1202 const STARTUP_FILE_PATH: &str = "/path";
1203
1204 let test_init_tid = init_task.get_tid();
1205 fasync::Task::local(async move {
1206 sender.send(()).await.expect("failed to send message");
1207 wait_for_init_file(STARTUP_FILE_PATH, ¤t_task, test_init_tid)
1208 .await
1209 .expect_err("Did not detect init exit");
1210 sender.send(()).await.expect("failed to send message");
1211 })
1212 .detach();
1213
1214 assert!(receiver.next().await.is_some());
1216
1217 std::mem::drop(init_task);
1219
1220 assert!(receiver.next().await.is_some());
1222 }
1223}