1 /*
2  * Copyright (C) 2024 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 //! Responsible for starting an instance of the Microfuchsia VM.
18 
19 use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
20     CpuTopology::CpuTopology, IVirtualizationService::IVirtualizationService,
21     VirtualMachineConfig::VirtualMachineConfig, VirtualMachineRawConfig::VirtualMachineRawConfig,
22 };
23 use anyhow::{ensure, Context, Result};
24 use binder::{LazyServiceGuard, ParcelFileDescriptor};
25 use log::info;
26 use std::ffi::CStr;
27 use std::fs::File;
28 use std::os::fd::FromRawFd;
29 use vmclient::VmInstance;
30 
31 pub struct MicrofuchsiaInstance {
32     _vm_instance: VmInstance,
33     _lazy_service_guard: LazyServiceGuard,
34     _pty: Option<Pty>,
35 }
36 
37 pub struct InstanceStarter {
38     instance_name: String,
39     instance_id: u8,
40 }
41 
42 impl InstanceStarter {
new(instance_name: &str, instance_id: u8) -> Self43     pub fn new(instance_name: &str, instance_id: u8) -> Self {
44         Self { instance_name: instance_name.to_owned(), instance_id }
45     }
46 
start_new_instance( &self, virtualization_service: &dyn IVirtualizationService, ) -> Result<MicrofuchsiaInstance>47     pub fn start_new_instance(
48         &self,
49         virtualization_service: &dyn IVirtualizationService,
50     ) -> Result<MicrofuchsiaInstance> {
51         info!("Creating {} instance", self.instance_name);
52 
53         // Always use instance id 0, because we will only ever have one instance.
54         let mut instance_id = [0u8; 64];
55         instance_id[0] = self.instance_id;
56 
57         // Open the kernel and initrd files from the microfuchsia.images apex.
58         let kernel_fd =
59             File::open("/apex/com.android.microfuchsia.images/etc/linux-arm64-boot-shim.bin")
60                 .context("Failed to open the boot-shim")?;
61         let initrd_fd = File::open("/apex/com.android.microfuchsia.images/etc/fuchsia.zbi")
62             .context("Failed to open the fuchsia ZBI")?;
63         let kernel = Some(ParcelFileDescriptor::new(kernel_fd));
64         let initrd = Some(ParcelFileDescriptor::new(initrd_fd));
65 
66         // Prepare a pty for console input/output.
67         let (pty, console_in, console_out) = if cfg!(enable_console) {
68             let pty = openpty()?;
69             let console_in = Some(pty.leader.try_clone().context("cloning pty")?);
70             let console_out = Some(pty.leader.try_clone().context("cloning pty")?);
71             (Some(pty), console_in, console_out)
72         } else {
73             (None, None, None)
74         };
75         let config = VirtualMachineConfig::RawConfig(VirtualMachineRawConfig {
76             name: "Microfuchsia".into(),
77             instanceId: instance_id,
78             kernel,
79             initrd,
80             params: None,
81             bootloader: None,
82             disks: vec![],
83             protectedVm: false,
84             memoryMib: 256,
85             cpuTopology: CpuTopology::ONE_CPU,
86             platformVersion: "1.0.0".into(),
87             #[cfg(enable_console)]
88             consoleInputDevice: Some("ttyS0".into()),
89             ..Default::default()
90         });
91         let vm_instance = VmInstance::create(
92             virtualization_service,
93             &config,
94             console_out,
95             console_in,
96             /* log= */ None,
97             /* dump_dt= */ None,
98             None,
99         )
100         .context("Failed to create VM")?;
101         if let Some(pty) = &pty {
102             vm_instance
103                 .vm
104                 .setHostConsoleName(&pty.follower_name)
105                 .context("Setting host console name")?;
106         }
107         vm_instance.start().context("Starting VM")?;
108 
109         Ok(MicrofuchsiaInstance {
110             _vm_instance: vm_instance,
111             _lazy_service_guard: Default::default(),
112             _pty: pty,
113         })
114     }
115 }
116 
117 struct Pty {
118     leader: File,
119     follower_name: String,
120 }
121 
122 /// Opens a pseudoterminal (pty), configures it to be a raw terminal, and returns the file pair.
openpty() -> Result<Pty>123 fn openpty() -> Result<Pty> {
124     // Create a pty pair.
125     let mut leader: libc::c_int = -1;
126     let mut _follower: libc::c_int = -1;
127     let mut follower_name: Vec<libc::c_char> = vec![0; 32];
128 
129     // SAFETY: calling openpty with valid+initialized variables is safe.
130     // The two null pointers are valid inputs for openpty.
131     unsafe {
132         ensure!(
133             libc::openpty(
134                 &mut leader,
135                 &mut _follower,
136                 follower_name.as_mut_ptr(),
137                 std::ptr::null_mut(),
138                 std::ptr::null_mut(),
139             ) == 0,
140             "failed to openpty"
141         );
142     }
143 
144     // SAFETY: calling these libc functions with valid+initialized variables is safe.
145     unsafe {
146         // Fetch the termios attributes.
147         let mut attr = libc::termios {
148             c_iflag: 0,
149             c_oflag: 0,
150             c_cflag: 0,
151             c_lflag: 0,
152             c_line: 0,
153             c_cc: [0u8; 19],
154         };
155         ensure!(libc::tcgetattr(leader, &mut attr) == 0, "failed to get termios attributes");
156 
157         // Force it to be a raw pty and re-set it.
158         libc::cfmakeraw(&mut attr);
159         ensure!(
160             libc::tcsetattr(leader, libc::TCSANOW, &attr) == 0,
161             "failed to set termios attributes"
162         );
163     }
164 
165     // Construct the return value.
166     // SAFETY: The file descriptors are valid because openpty returned without error (above).
167     let leader = unsafe { File::from_raw_fd(leader) };
168     let follower_name: Vec<u8> = follower_name.iter_mut().map(|x| *x as _).collect();
169     let follower_name = CStr::from_bytes_until_nul(&follower_name)
170         .context("pty filename missing NUL")?
171         .to_str()
172         .context("pty filename invalid utf8")?
173         .to_string();
174     Ok(Pty { leader, follower_name })
175 }
176