1use crate::ContainerStartInfo;
6use anyhow::{Context, Error, anyhow};
7use fidl_fuchsia_ui_composition as fuicomposition;
8use fidl_fuchsia_ui_input3 as fuiinput;
9use fidl_fuchsia_ui_policy as fuipolicy;
10use fidl_fuchsia_ui_views as fuiviews;
11use starnix_consent_sync::init as consent_sync_init;
12use starnix_container_structured_config::Config as ContainerStructuredConfig;
13use starnix_core::device::block::add_mmc_block_device;
14use starnix_core::mm::MlockPinFlavor;
15use starnix_core::task::{Kernel, KernelFeatures, SystemLimits, ThreadLockupDetector};
16use starnix_core::vfs::FsString;
17use starnix_features::Feature;
18use starnix_logging::log_error;
19use starnix_modules_android_usb::usb_device_init;
20use starnix_modules_ashmem::ashmem_device_init;
21use starnix_modules_boot::booted_device_init;
22use starnix_modules_fastrpc::fastrpc_device_init;
23use starnix_modules_framebuffer::{AspectRatio, Framebuffer};
24use starnix_modules_gpu::gpu_device_init;
25use starnix_modules_gralloc::gralloc_device_init;
26use starnix_modules_hvdcp_opti::hvdcp_opti_init;
27use starnix_modules_input::uinput::register_uinput_device;
28use starnix_modules_input::{
29 DEFAULT_KEYBOARD_DEVICE_ID, DEFAULT_MOUSE_DEVICE_ID, DEFAULT_TOUCH_DEVICE_ID, EventProxyMode,
30 InputDevice, new_input_relay,
31};
32use starnix_modules_kgsl::kgsl_device_init;
33use starnix_modules_magma::magma_device_init;
34use starnix_modules_nanohub::nanohub_device_init;
35use starnix_modules_nmfs::nmfs_init;
36use starnix_modules_perfetto_consumer::start_perfetto_consumer_thread;
37use starnix_modules_thermal::{cooling_device_init, thermal_device_init};
38use starnix_modules_touch_power_policy::TouchPowerPolicyDevice;
39use starnix_modules_wakeup_test::register_wakeup_test_device;
40use std::sync::Arc;
41
42use starnix_uapi::error;
43use starnix_uapi::errors::Errno;
44
45#[derive(Default, Debug)]
47pub struct Features {
48 pub kernel: KernelFeatures,
50
51 pub selinux: SELinuxFeature,
53
54 pub system_limits: SystemLimits,
56
57 pub ashmem: bool,
59
60 pub boot_notifier: bool,
62
63 pub data_collection_consent_sync: bool,
65
66 pub boot_notifier_cpu_boost: Option<zx::MonotonicDuration>,
68
69 pub framebuffer: bool,
71
72 pub aspect_ratio: Option<AspectRatio>,
74
75 pub enable_visual_debugging: bool,
78
79 pub initial_view_id_annotation: String,
81
82 pub gralloc: bool,
84
85 pub kgsl: bool,
87
88 pub magma_supported_vendors: Option<Vec<u16>>,
90
91 pub gfxstream: bool,
93
94 pub container: bool,
96
97 pub test_data: bool,
99
100 pub custom_artifacts: bool,
102
103 pub android_serialno: bool,
105
106 pub perfetto: Option<FsString>,
108
109 pub rootfs_rw: bool,
111
112 pub network_manager: bool,
114
115 pub nanohub: bool,
117
118 pub fastrpc: bool,
120
121 pub enable_utc_time_adjustment: bool,
122
123 pub thermal: bool,
124
125 pub cooling: Option<Vec<String>>,
128
129 pub android_bootreason: bool,
131
132 pub hvdcp_opti: bool,
133
134 pub additional_mounts: Option<Vec<String>>,
135
136 pub wakeup_test: bool,
138
139 pub mmcblk_stub: bool,
142
143 pub android_usb: bool,
145}
146
147#[derive(Default, Debug, PartialEq)]
148pub struct SELinuxFeature {
149 pub enabled: bool,
151
152 pub options: String,
154
155 pub exceptions: Vec<String>,
157}
158
159impl Features {
160 pub fn record_inspect(&self, parent_node: &fuchsia_inspect::Node) {
161 parent_node.record_child("features", |inspect_node| match self {
162 Features {
163 kernel:
164 KernelFeatures {
165 bpf_v2,
166 enable_suid,
167 io_uring,
168 error_on_failed_reboot,
169 default_uid,
170 default_seclabel,
171 selinux_test_suite,
172 default_ns_mount_options,
173 mlock_always_onfault,
174 mlock_pin_flavor,
175 crash_report_throttling,
176 wifi,
177 cached_zx_map_info_bytes,
178 dirent_cache_size,
179 fake_ion,
180 },
181 system_limits,
182 selinux,
183 ashmem,
184 boot_notifier,
185 boot_notifier_cpu_boost,
186 data_collection_consent_sync,
187 framebuffer,
188 aspect_ratio,
189 enable_visual_debugging,
190 gralloc,
191 kgsl,
192 magma_supported_vendors,
193 gfxstream,
194 container,
195 test_data,
196 custom_artifacts,
197 android_serialno,
198 perfetto,
199 rootfs_rw,
200 network_manager,
201 nanohub,
202 fastrpc,
203 enable_utc_time_adjustment,
204 thermal,
205 cooling,
206 android_bootreason,
207 hvdcp_opti,
208 additional_mounts,
209 wakeup_test,
210 mmcblk_stub,
211 android_usb,
212 initial_view_id_annotation,
213 } => {
214 inspect_node.record_bool("selinux", selinux.enabled);
215 inspect_node.record_bool("ashmem", *ashmem);
216 inspect_node.record_bool("boot_notifier", *boot_notifier);
217 inspect_node.record_string(
218 "initial_view_id_annotation",
219 initial_view_id_annotation.as_str(),
220 );
221 inspect_node
222 .record_bool("data_collection_consent_sync", *data_collection_consent_sync);
223 inspect_node.record_string(
224 "boot_notifier_cpu_boost",
225 boot_notifier_cpu_boost
226 .map(|d| format!("{}s", d.into_seconds()))
227 .unwrap_or_else(|| "none".to_string()),
228 );
229 inspect_node.record_bool("framebuffer", *framebuffer);
230 inspect_node.record_bool("gralloc", *gralloc);
231 inspect_node.record_bool("kgsl", *kgsl);
232 inspect_node.record_string(
233 "magma_supported_vendors",
234 match magma_supported_vendors {
235 Some(vendors) => vendors
236 .iter()
237 .map(|vendor| format!("0x{:x}", vendor))
238 .collect::<Vec<String>>()
239 .join(","),
240 None => "".to_string(),
241 },
242 );
243 inspect_node.record_bool("gfxstream", *gfxstream);
244 inspect_node.record_bool("container", *container);
245 inspect_node.record_bool("test_data", *test_data);
246 inspect_node.record_bool("custom_artifacts", *custom_artifacts);
247 inspect_node.record_bool("android_serialno", *android_serialno);
248 inspect_node.record_string(
249 "aspect_ratio",
250 aspect_ratio
251 .as_ref()
252 .map(|aspect_ratio| {
253 format!("width: {} height: {}", aspect_ratio.width, aspect_ratio.height)
254 })
255 .unwrap_or_default(),
256 );
257 inspect_node.record_string(
258 "perfetto",
259 perfetto.as_ref().map(|p| p.to_string()).unwrap_or_default(),
260 );
261 inspect_node.record_bool("rootfs_rw", *rootfs_rw);
262 inspect_node.record_bool("network_manager", *network_manager);
263 inspect_node.record_bool("nanohub", *nanohub);
264 inspect_node.record_bool("fastrpc", *fastrpc);
265 inspect_node.record_bool("thermal", *thermal);
266 inspect_node.record_string(
267 "cooling",
268 match cooling {
269 Some(devices) => devices.join(","),
270 None => "".to_string(),
271 },
272 );
273 inspect_node.record_bool("android_bootreason", *android_bootreason);
274 inspect_node.record_bool("hvdcp_opti", *hvdcp_opti);
275 inspect_node.record_string("ping_group_range", {
276 let range = system_limits.socket.icmp_ping_gids.lock();
277 std::format!("{},{}", range.start, range.end - 1)
278 });
279
280 inspect_node.record_child("kernel", |kernel_node| {
281 kernel_node.record_bool("bpf_v2", *bpf_v2);
282 kernel_node.record_bool("enable_suid", *enable_suid);
283 kernel_node.record_bool("io_uring", *io_uring);
284 kernel_node.record_bool("error_on_failed_reboot", *error_on_failed_reboot);
285 kernel_node.record_bool("enable_visual_debugging", *enable_visual_debugging);
286 kernel_node.record_int("default_uid", (*default_uid).into());
287 kernel_node.record_string(
288 "default_seclabel",
289 default_seclabel.as_deref().unwrap_or_default(),
290 );
291 kernel_node.record_bool("selinux_test_suite", *selinux_test_suite);
292 kernel_node.record_bool("crash_report_throttling", *crash_report_throttling);
293 kernel_node
294 .record_uint("cached_zx_map_info_bytes", *cached_zx_map_info_bytes as u64);
295 inspect_node.record_string(
296 "default_ns_mount_options",
297 format!("{:?}", default_ns_mount_options),
298 );
299 inspect_node
300 .record_bool("enable_utc_time_adjustment", *enable_utc_time_adjustment);
301 inspect_node.record_bool("mlock_always_onfault", *mlock_always_onfault);
302 inspect_node
303 .record_string("mlock_pin_flavor", format!("{:?}", mlock_pin_flavor));
304 inspect_node.record_bool("wifi", *wifi);
305 inspect_node
306 .record_string("additional_mounts", format!("{:?}", additional_mounts));
307 inspect_node.record_uint("dirent_cache_size", *dirent_cache_size as u64);
308 inspect_node.record_bool("wakeup_test", *wakeup_test);
309 inspect_node.record_bool("mmcblk_stub", *mmcblk_stub);
310 inspect_node.record_bool("android_usb", *android_usb);
311 inspect_node.record_bool("fake_ion", *fake_ion);
312 });
313 }
314 });
315 }
316}
317
318pub fn parse_features(
322 start_info: &ContainerStartInfo,
323 kernel_extra_features: &[String],
324) -> Result<Features, Error> {
325 let ContainerStructuredConfig {
326 crash_report_throttling,
327 enable_utc_time_adjustment,
328 extra_features,
329 cached_zx_map_info_bytes,
330 mlock_always_onfault,
331 mlock_pin_flavor,
332 selinux_exceptions,
333 ui_visual_debugging_level,
334 additional_mounts,
335 dirent_cache_size,
336 initial_view_id_annotation,
337 } = &start_info.config;
338
339 let mut features = Features::default();
340 for entry in start_info
341 .program
342 .features
343 .iter()
344 .chain(kernel_extra_features.iter())
345 .chain(extra_features.iter())
346 {
347 let (feature, raw_args) = Feature::try_parse_feature_and_args(entry)?;
348 match (feature, raw_args) {
349 (Feature::AndroidSerialno, _) => features.android_serialno = true,
350 (Feature::AndroidBootreason, _) => features.android_bootreason = true,
351 (Feature::AspectRatio, Some(args)) => {
352 let e = anyhow!("Invalid aspect_ratio: {:?}", args);
353 let components: Vec<_> = args.split(':').collect();
354 if components.len() != 2 {
355 return Err(e);
356 }
357 let width: u32 =
358 components[0].parse().map_err(|_| anyhow!("Invalid aspect ratio width"))?;
359 let height: u32 =
360 components[1].parse().map_err(|_| anyhow!("Invalid aspect ratio height"))?;
361 features.aspect_ratio = Some(AspectRatio { width, height });
362 }
363 (Feature::AspectRatio, None) => {
364 return Err(anyhow!(
365 "Aspect ratio feature must contain the aspect ratio in the format: aspect_ratio:w:h"
366 ));
367 }
368 (Feature::Container, _) => features.container = true,
369 (Feature::CustomArtifacts, _) => features.custom_artifacts = true,
370 (Feature::Ashmem, _) => features.ashmem = true,
371 (Feature::BootNotifier, _) => features.boot_notifier = true,
372 (Feature::DataCollectionConsentSync, _) => features.data_collection_consent_sync = true,
373 (Feature::BootNotifierCpuBoost, Some(arg)) => {
374 let duration = zx::MonotonicDuration::from_seconds(arg.parse::<i64>()?);
375 features.boot_notifier_cpu_boost = Some(duration);
376 }
377 (Feature::BootNotifierCpuBoost, None) => {
378 return Err(anyhow!(
379 "boot_notifier_cpu_boost feature must have an argument (e.g. \"boot_notifier_cpu_boost:60\")"
380 ));
381 }
382 (Feature::Framebuffer, _) => features.framebuffer = true,
383 (Feature::Gralloc, _) => features.gralloc = true,
384 (Feature::Kgsl, _) => features.kgsl = true,
385 (Feature::Magma, _) => {
386 if features.magma_supported_vendors.is_none() {
387 const VENDOR_ARM: u16 = 0x13B5;
388 const VENDOR_INTEL: u16 = 0x8086;
389 features.magma_supported_vendors = Some(vec![VENDOR_ARM, VENDOR_INTEL])
390 }
391 }
392 (Feature::MagmaSupportedVendors, Some(arg)) => {
393 features.magma_supported_vendors = Some(
394 arg.split(',')
395 .map(|s| {
396 let err = anyhow!(
397 "Feature format must be: magma_supported_vendors:0x1234[,0xabcd]"
398 );
399 let trimmed = s.trim_start_matches("0x");
400 u16::from_str_radix(trimmed, 16).map_err(|_| err)
401 })
402 .collect::<Result<Vec<u16>, Error>>()?,
403 );
404 }
405 (Feature::MagmaSupportedVendors, None) => {
406 return Err(anyhow!(
407 "Feature format must be: magma_supported_vendors:0x1234[,0xabcd]"
408 ));
409 }
410 (Feature::Nanohub, _) => features.nanohub = true,
411 (Feature::Fastrpc, _) => features.fastrpc = true,
412 (Feature::NetworkManager, _) => features.network_manager = true,
413 (Feature::Gfxstream, _) => features.gfxstream = true,
414 (Feature::Bpf, Some(version)) => features.kernel.bpf_v2 = version == "v2",
415 (Feature::Bpf, None) => {
416 return Err(anyhow!("bpf feature must have an argument (e.g. \"bpf:v2\")"));
417 }
418 (Feature::EnableSuid, _) => features.kernel.enable_suid = true,
419 (Feature::IoUring, _) => features.kernel.io_uring = true,
420 (Feature::ErrorOnFailedReboot, _) => features.kernel.error_on_failed_reboot = true,
421 (Feature::Perfetto, Some(socket_path)) => {
422 features.perfetto = Some(socket_path.into());
423 }
424 (Feature::Perfetto, None) => {
425 return Err(anyhow!("Perfetto feature must contain a socket path"));
426 }
427 (Feature::PingGroupRange, Some(arg)) => {
428 let mut args = arg.split(',');
429 let (min, max) = (|| {
430 let min = args.next()?.trim_ascii().parse::<u32>().ok()?;
431 let max = args.next()?.trim_ascii().parse::<u32>().ok()?.checked_add(1)?;
432 if args.next().is_some() {
433 return None;
434 }
435 Some((min, max))
436 })()
437 .ok_or_else(|| anyhow!("Feature format must be: ping_group_range:0,100"))?;
438 *features.system_limits.socket.icmp_ping_gids.lock() = min..max;
439 }
440 (Feature::PingGroupRange, None) => {
441 return Err(anyhow!("Feature format must be: ping_group_range:0,100"));
442 }
443 (Feature::RootfsRw, _) => features.rootfs_rw = true,
444 (Feature::Selinux, arg) => {
445 features.selinux = SELinuxFeature {
446 enabled: true,
447 options: arg.unwrap_or_default(),
448 exceptions: selinux_exceptions.clone(),
449 };
450 }
451 (Feature::SelinuxTestSuite, _) => features.kernel.selinux_test_suite = true,
452 (Feature::TestData, _) => features.test_data = true,
453 (Feature::Thermal, _) => features.thermal = true,
454 (Feature::Cooling, Some(arg)) => {
455 features.cooling = Some(arg.split(',').map(String::from).collect::<Vec<String>>())
456 }
457 (Feature::Cooling, None) => {
458 return Err(anyhow!("cooling feature must have an argument"));
459 }
460 (Feature::HvdcpOpti, _) => features.hvdcp_opti = true,
461 (Feature::Wifi, _) => features.kernel.wifi = true,
462 (Feature::AdditionalMounts, _) => {
463 features.additional_mounts = Some(additional_mounts.clone())
464 }
465 (Feature::WakeupTest, _) => features.wakeup_test = true,
466 (Feature::MmcblkStub, _) => features.mmcblk_stub = true,
467 (Feature::FakeIon, _) => features.kernel.fake_ion = true,
468 (Feature::AndroidUsb, _) => features.android_usb = true,
469 };
470 }
471
472 if features.boot_notifier_cpu_boost.is_some() && !features.boot_notifier {
473 return Err(anyhow!("boot_notifier_cpu_boost feature requires boot_notifier"));
474 }
475
476 if *ui_visual_debugging_level > 0 {
477 features.enable_visual_debugging = true;
478 }
479 features.enable_utc_time_adjustment = *enable_utc_time_adjustment;
480
481 features.kernel.default_uid = start_info.program.default_uid.0;
482 features.kernel.default_seclabel = start_info.program.default_seclabel.clone();
483 features.kernel.default_ns_mount_options =
484 if let Some(mount_options) = &start_info.program.default_ns_mount_options {
485 let options = mount_options
486 .iter()
487 .map(|item| {
488 let mut splitter = item.splitn(2, ":");
489 let key = splitter.next().expect("Failed to parse mount options");
490 let value = splitter.next().expect("Failed to parse mount options");
491 (key.to_string(), value.to_string())
492 })
493 .collect();
494 Some(options)
495 } else {
496 None
497 };
498
499 features.kernel.mlock_always_onfault = *mlock_always_onfault;
500 features.kernel.mlock_pin_flavor = MlockPinFlavor::parse(mlock_pin_flavor.as_str())?;
501 features.kernel.crash_report_throttling = *crash_report_throttling;
502 features.kernel.cached_zx_map_info_bytes = *cached_zx_map_info_bytes;
503 features.kernel.dirent_cache_size = *dirent_cache_size;
504 features.initial_view_id_annotation = initial_view_id_annotation.clone();
505
506 Ok(features)
507}
508
509pub fn run_container_features(kernel: &Arc<Kernel>, features: &Features) -> Result<(), Error> {
512 if features.framebuffer {
513 let framebuffer = Framebuffer::device_init(
514 kernel,
515 features.aspect_ratio,
516 features.enable_visual_debugging,
517 features.initial_view_id_annotation.clone(),
518 )
519 .context("initializing framebuffer")?;
520
521 let (touch_source_client, touch_source_server) = fidl::endpoints::create_endpoints();
522 let (mouse_source_client, mouse_source_server) = fidl::endpoints::create_endpoints();
523 let view_bound_protocols = fuicomposition::ViewBoundProtocols {
524 touch_source: Some(touch_source_server),
525 mouse_source: Some(mouse_source_server),
526 ..Default::default()
527 };
528 let view_identity = fuiviews::ViewIdentityOnCreation::from(
529 fuchsia_scenic::ViewRefPair::new().expect("Failed to create ViewRefPair"),
530 );
531 let view_ref = fuchsia_scenic::duplicate_view_ref(&view_identity.view_ref)
532 .expect("Failed to dup view ref.");
533 let keyboard =
534 fuchsia_component::client::connect_to_protocol_sync::<fuiinput::KeyboardMarker>()
535 .expect("Failed to connect to keyboard");
536 let registry_proxy = fuchsia_component::client::connect_to_protocol_sync::<
537 fuipolicy::DeviceListenerRegistryMarker,
538 >()
539 .expect("Failed to connect to device listener registry");
540
541 *framebuffer.view_identity.lock() = Some(view_identity);
550 *framebuffer.view_bound_protocols.lock() = Some(view_bound_protocols);
551
552 let (display_width, display_height) = {
553 let framebuffer_info = framebuffer.info.read();
554 (framebuffer_info.xres as i32, framebuffer_info.yres as i32)
555 };
556
557 let touch_device =
558 InputDevice::new_touch(display_width, display_height, &kernel.inspect_node);
559 let keyboard_device = InputDevice::new_keyboard(&kernel.inspect_node);
560 let mouse_device = InputDevice::new_mouse(&kernel.inspect_node);
561
562 touch_device.clone().register(kernel, DEFAULT_TOUCH_DEVICE_ID)?;
563 keyboard_device.clone().register(kernel, DEFAULT_KEYBOARD_DEVICE_ID)?;
564 mouse_device.clone().register(kernel, DEFAULT_MOUSE_DEVICE_ID)?;
565
566 let (input_events_relay, input_events_relay_handle) = new_input_relay();
567 input_events_relay.start_relays(
568 &kernel,
569 EventProxyMode::WakeContainer,
570 touch_source_client,
571 keyboard,
572 mouse_source_client,
573 view_ref,
574 registry_proxy,
575 touch_device.open_files.clone(),
576 keyboard_device.open_files.clone(),
577 mouse_device.open_files.clone(),
578 Some(touch_device.inspect_status),
579 Some(keyboard_device.inspect_status),
580 Some(mouse_device.inspect_status),
581 );
582
583 register_uinput_device(kernel, input_events_relay_handle)?;
584
585 let (touch_standby_sender, touch_standby_receiver) =
587 ThreadLockupDetector::tracked_channel::<bool>();
588 let touch_policy_device = TouchPowerPolicyDevice::new(touch_standby_sender);
589 touch_policy_device.clone().register(kernel);
590 touch_policy_device.start_relay(&kernel, touch_standby_receiver);
591
592 framebuffer.start_server(kernel, None);
593 }
594 if features.gralloc {
595 gralloc_device_init(kernel);
605 }
606 if features.kgsl {
607 kgsl_device_init(kernel);
608 }
609 if let Some(supported_vendors) = &features.magma_supported_vendors {
610 magma_device_init(kernel, supported_vendors.clone());
611 }
612 if features.gfxstream {
613 gpu_device_init(kernel);
614 }
615 if let Some(socket_path) = features.perfetto.clone() {
616 start_perfetto_consumer_thread(kernel, socket_path)
617 .context("Failed to start perfetto consumer thread")?;
618 }
619 if features.ashmem {
620 ashmem_device_init(kernel);
621 }
622 if features.boot_notifier {
623 booted_device_init(kernel, features.boot_notifier_cpu_boost);
624 }
625 if features.data_collection_consent_sync {
626 consent_sync_init(kernel);
627 }
628 if features.network_manager {
629 if let Err(e) = nmfs_init(kernel) {
630 log_error!("Network manager initialization failed: ({e:?})");
631 }
632 }
633 if features.nanohub {
634 nanohub_device_init(kernel);
635 }
636 if features.thermal {
637 thermal_device_init(kernel)?;
638 }
639 if let Some(devices) = &features.cooling {
640 cooling_device_init(kernel, devices.clone())?;
641 }
642 if features.hvdcp_opti {
643 hvdcp_opti_init(kernel)?;
644 }
645 if features.fastrpc {
646 fastrpc_device_init(kernel);
647 }
648 if features.wakeup_test {
649 register_wakeup_test_device(kernel)?;
650 }
651 if features.mmcblk_stub {
652 let _device = add_mmc_block_device(kernel).context("Failed to add stub mmcblk0 device")?;
653 }
654 if features.android_usb {
655 usb_device_init(kernel).context("Failed to add android usb device nodes")?;
656 }
657 Ok(())
658}
659
660pub fn run_component_features(
662 kernel: &Kernel,
663 entries: &Vec<String>,
664 mut incoming_dir: Option<fidl_fuchsia_io::DirectoryProxy>,
665) -> Result<(), Errno> {
666 for entry in entries {
667 match entry.as_str() {
668 "framebuffer" => {
669 Framebuffer::get(kernel)?.start_server(kernel, incoming_dir.take());
670 }
671 feature => {
672 return error!(ENOSYS, format!("Unsupported feature: {}", feature));
673 }
674 }
675 }
676 Ok(())
677}