1 // Copyright 2021, The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 //! Command to run a VM.
16
17 use crate::create_partition::command_create_partition;
18 use crate::{get_service, RunAppConfig, RunCustomVmConfig, RunMicrodroidConfig};
19 use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
20 CpuOptions::CpuOptions,
21 IVirtualizationService::IVirtualizationService,
22 PartitionType::PartitionType,
23 VirtualMachineAppConfig::{
24 CustomConfig::CustomConfig, DebugLevel::DebugLevel, Payload::Payload,
25 VirtualMachineAppConfig,
26 },
27 VirtualMachineConfig::VirtualMachineConfig,
28 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
29 VirtualMachineState::VirtualMachineState,
30 };
31 use anyhow::{anyhow, bail, Context, Error};
32 use binder::ParcelFileDescriptor;
33 use glob::glob;
34 use microdroid_payload_config::VmPayloadConfig;
35 use rand::{distributions::Alphanumeric, Rng};
36 use std::fs;
37 use std::fs::File;
38 use std::fs::OpenOptions;
39 use std::io;
40 use std::io::{Read, Write};
41 use std::os::fd::AsFd;
42 use std::path::{Path, PathBuf};
43 use vmclient::{ErrorCode, VmInstance};
44 use vmconfig::{get_debug_level, open_parcel_file, VmConfig};
45 use zip::ZipArchive;
46
47 /// Run a VM from the given APK, idsig, and config.
command_run_app(config: RunAppConfig) -> Result<(), Error>48 pub fn command_run_app(config: RunAppConfig) -> Result<(), Error> {
49 let service = get_service()?;
50 let apk = File::open(&config.apk).context("Failed to open APK file")?;
51
52 let extra_apks = match config.config_path.as_deref() {
53 Some(path) => parse_extra_apk_list(&config.apk, path)?,
54 None => config.extra_apks().to_vec(),
55 };
56
57 if extra_apks.len() != config.extra_idsigs.len() {
58 bail!(
59 "Found {} extra apks, but there are {} extra idsigs",
60 extra_apks.len(),
61 config.extra_idsigs.len()
62 )
63 }
64
65 for (i, extra_apk) in extra_apks.iter().enumerate() {
66 let extra_apk_fd = ParcelFileDescriptor::new(File::open(extra_apk)?);
67 let extra_idsig_fd = ParcelFileDescriptor::new(File::create(&config.extra_idsigs[i])?);
68 service.createOrUpdateIdsigFile(&extra_apk_fd, &extra_idsig_fd)?;
69 }
70
71 let idsig = File::create(&config.idsig).context("Failed to create idsig file")?;
72
73 let apk_fd = ParcelFileDescriptor::new(apk);
74 let idsig_fd = ParcelFileDescriptor::new(idsig);
75 service.createOrUpdateIdsigFile(&apk_fd, &idsig_fd)?;
76
77 let idsig = File::open(&config.idsig).context("Failed to open idsig file")?;
78 let idsig_fd = ParcelFileDescriptor::new(idsig);
79
80 if !config.instance.exists() {
81 const INSTANCE_FILE_SIZE: u64 = 10 * 1024 * 1024;
82 command_create_partition(
83 service.as_ref(),
84 &config.instance,
85 INSTANCE_FILE_SIZE,
86 PartitionType::ANDROID_VM_INSTANCE,
87 )?;
88 }
89
90 let instance_id = {
91 let id_file = config.instance_id;
92 if id_file.exists() {
93 let mut id = [0u8; 64];
94 let mut instance_id_file = File::open(id_file)?;
95 instance_id_file.read_exact(&mut id)?;
96 id
97 } else {
98 let id = service.allocateInstanceId().context("Failed to allocate instance_id")?;
99 let mut instance_id_file = File::create(id_file)?;
100 instance_id_file.write_all(&id)?;
101 id
102 }
103 };
104
105 let storage = if let Some(ref path) = config.microdroid.storage {
106 if !path.exists() {
107 command_create_partition(
108 service.as_ref(),
109 path,
110 config.microdroid.storage_size.unwrap_or(10 * 1024 * 1024),
111 PartitionType::ENCRYPTEDSTORE,
112 )?;
113 } else if let Some(storage_size) = config.microdroid.storage_size {
114 set_encrypted_storage(service.as_ref(), path, storage_size)?;
115 }
116 Some(open_parcel_file(path, true)?)
117 } else {
118 None
119 };
120
121 let vendor =
122 config.microdroid.vendor().as_ref().map(|p| open_parcel_file(p, false)).transpose()?;
123
124 let extra_idsig_files: Result<Vec<_>, _> = config.extra_idsigs.iter().map(File::open).collect();
125 let extra_idsig_fds = extra_idsig_files?.into_iter().map(ParcelFileDescriptor::new).collect();
126
127 let payload = if let Some(config_path) = config.config_path {
128 if config.payload_binary_name.is_some() {
129 bail!("Only one of --config-path or --payload-binary-name can be defined")
130 }
131 Payload::ConfigPath(config_path)
132 } else if let Some(payload_binary_name) = config.payload_binary_name {
133 let extra_apk_files: Result<Vec<_>, _> = extra_apks.iter().map(File::open).collect();
134 let extra_apk_fds = extra_apk_files?.into_iter().map(ParcelFileDescriptor::new).collect();
135
136 Payload::PayloadConfig(VirtualMachinePayloadConfig {
137 payloadBinaryName: payload_binary_name,
138 extraApks: extra_apk_fds,
139 })
140 } else {
141 bail!("Either --config-path or --payload-binary-name must be defined")
142 };
143
144 let os_name = if let Some(ref os) = config.microdroid.os { os } else { "microdroid" };
145
146 let payload_config_str = format!("{:?}!{:?}", config.apk, payload);
147
148 let mut custom_config = CustomConfig {
149 gdbPort: config.debug.gdb.map(u16::from).unwrap_or(0) as i32, // 0 means no gdb
150 vendorImage: vendor,
151 devices: config
152 .microdroid
153 .devices()
154 .iter()
155 .map(|x| {
156 x.to_str().map(String::from).ok_or(anyhow!("Failed to convert {x:?} to String"))
157 })
158 .collect::<Result<_, _>>()?,
159 networkSupported: config.common.network_supported(),
160 teeServices: config.common.tee_services().to_vec(),
161 ..Default::default()
162 };
163
164 let cpu_options = CpuOptions { cpuTopology: config.common.cpu_topology };
165 if config.debug.enable_earlycon() {
166 if config.debug.debug != DebugLevel::FULL {
167 bail!("earlycon is only supported for debuggable VMs")
168 }
169 if cfg!(target_arch = "aarch64") {
170 custom_config
171 .extraKernelCmdlineParams
172 .push(String::from("earlycon=uart8250,mmio,0x3f8"));
173 } else if cfg!(target_arch = "x86_64") {
174 custom_config.extraKernelCmdlineParams.push(String::from("earlycon=uart8250,io,0x3f8"));
175 } else {
176 bail!("unexpected architecture!");
177 }
178 custom_config.extraKernelCmdlineParams.push(String::from("keep_bootcon"));
179 }
180
181 let vm_config = VirtualMachineConfig::AppConfig(VirtualMachineAppConfig {
182 name: config.common.name.unwrap_or_else(|| String::from("VmRunApp")),
183 apk: apk_fd.into(),
184 idsig: idsig_fd.into(),
185 extraIdsigs: extra_idsig_fds,
186 instanceImage: open_parcel_file(&config.instance, true /* writable */)?.into(),
187 instanceId: instance_id,
188 encryptedStorageImage: storage,
189 payload,
190 debugLevel: config.debug.debug,
191 protectedVm: config.common.protected,
192 memoryMib: config.common.mem.unwrap_or(0) as i32, // 0 means use the VM default
193 cpuOptions: cpu_options,
194 customConfig: Some(custom_config),
195 osName: os_name.to_string(),
196 hugePages: config.common.hugepages,
197 boostUclamp: config.common.boost_uclamp,
198 });
199 run(
200 service.as_ref(),
201 &vm_config,
202 &payload_config_str,
203 config.debug.console.as_ref().map(|p| p.as_ref()),
204 config.debug.console_in.as_ref().map(|p| p.as_ref()),
205 config.debug.log.as_ref().map(|p| p.as_ref()),
206 config.debug.dump_device_tree.as_ref().map(|p| p.as_ref()),
207 )
208 }
209
find_empty_payload_apk_path() -> Result<PathBuf, Error>210 fn find_empty_payload_apk_path() -> Result<PathBuf, Error> {
211 const GLOB_PATTERN: &str = "/apex/com.android.virt/app/**/EmptyPayloadApp*.apk";
212 let mut entries: Vec<PathBuf> =
213 glob(GLOB_PATTERN).context("failed to glob")?.filter_map(|e| e.ok()).collect();
214 if entries.len() > 1 {
215 return Err(anyhow!("Found more than one apk matching {}", GLOB_PATTERN));
216 }
217 match entries.pop() {
218 Some(path) => Ok(path),
219 None => Err(anyhow!("No apks match {}", GLOB_PATTERN)),
220 }
221 }
222
create_work_dir() -> Result<PathBuf, Error>223 fn create_work_dir() -> Result<PathBuf, Error> {
224 let s: String =
225 rand::thread_rng().sample_iter(&Alphanumeric).take(17).map(char::from).collect();
226 let work_dir = PathBuf::from("/data/local/tmp/microdroid").join(s);
227 println!("creating work dir {}", work_dir.display());
228 fs::create_dir_all(&work_dir).context("failed to mkdir")?;
229 Ok(work_dir)
230 }
231
232 /// Run a VM with Microdroid
command_run_microdroid(config: RunMicrodroidConfig) -> Result<(), Error>233 pub fn command_run_microdroid(config: RunMicrodroidConfig) -> Result<(), Error> {
234 let apk = find_empty_payload_apk_path()?;
235 println!("found path {}", apk.display());
236
237 let work_dir = config.work_dir.unwrap_or(create_work_dir()?);
238 let idsig = work_dir.join("apk.idsig");
239 println!("apk.idsig path: {}", idsig.display());
240 let instance_img = work_dir.join("instance.img");
241 println!("instance.img path: {}", instance_img.display());
242
243 let mut app_config = RunAppConfig {
244 common: config.common,
245 debug: config.debug,
246 microdroid: config.microdroid,
247 apk,
248 idsig,
249 instance: instance_img,
250 payload_binary_name: Some("MicrodroidEmptyPayloadJniLib.so".to_owned()),
251 ..Default::default()
252 };
253
254 app_config.set_instance_id(work_dir.join("instance_id"));
255 println!("instance_id file path: {}", app_config.instance_id.display());
256
257 command_run_app(app_config)
258 }
259
260 /// Run a VM from the given configuration file.
command_run(config: RunCustomVmConfig) -> Result<(), Error>261 pub fn command_run(config: RunCustomVmConfig) -> Result<(), Error> {
262 let config_file = File::open(&config.config).context("Failed to open config file")?;
263 let mut vm_config =
264 VmConfig::load(&config_file).context("Failed to parse config file")?.to_parcelable()?;
265 if let Some(mem) = config.common.mem {
266 vm_config.memoryMib = mem as i32;
267 }
268 if let Some(ref name) = config.common.name {
269 vm_config.name = name.to_string();
270 } else {
271 vm_config.name = String::from("VmRun");
272 }
273 if let Some(gdb) = config.debug.gdb {
274 vm_config.gdbPort = gdb.get() as i32;
275 }
276 vm_config.cpuOptions = CpuOptions { cpuTopology: config.common.cpu_topology.clone() };
277 vm_config.hugePages = config.common.hugepages;
278 vm_config.boostUclamp = config.common.boost_uclamp;
279 vm_config.teeServices = config.common.tee_services().to_vec();
280 run(
281 get_service()?.as_ref(),
282 &VirtualMachineConfig::RawConfig(vm_config),
283 &format!("{:?}", &config.config),
284 config.debug.console.as_ref().map(|p| p.as_ref()),
285 config.debug.console_in.as_ref().map(|p| p.as_ref()),
286 config.debug.log.as_ref().map(|p| p.as_ref()),
287 config.debug.dump_device_tree.as_ref().map(|p| p.as_ref()),
288 )
289 }
290
state_to_str(vm_state: VirtualMachineState) -> &'static str291 fn state_to_str(vm_state: VirtualMachineState) -> &'static str {
292 match vm_state {
293 VirtualMachineState::NOT_STARTED => "NOT_STARTED",
294 VirtualMachineState::STARTING => "STARTING",
295 VirtualMachineState::STARTED => "STARTED",
296 VirtualMachineState::READY => "READY",
297 VirtualMachineState::FINISHED => "FINISHED",
298 VirtualMachineState::DEAD => "DEAD",
299 _ => "(invalid state)",
300 }
301 }
302
run( service: &dyn IVirtualizationService, config: &VirtualMachineConfig, payload_config: &str, console_out_path: Option<&Path>, console_in_path: Option<&Path>, log_path: Option<&Path>, dump_device_tree: Option<&Path>, ) -> Result<(), Error>303 fn run(
304 service: &dyn IVirtualizationService,
305 config: &VirtualMachineConfig,
306 payload_config: &str,
307 console_out_path: Option<&Path>,
308 console_in_path: Option<&Path>,
309 log_path: Option<&Path>,
310 dump_device_tree: Option<&Path>,
311 ) -> Result<(), Error> {
312 let console_out = if let Some(console_out_path) = console_out_path {
313 Some(File::create(console_out_path).with_context(|| {
314 format!("Failed to open console output file {:?}", console_out_path)
315 })?)
316 } else {
317 Some(duplicate_fd(io::stdout())?)
318 };
319 let console_in =
320 if let Some(console_in_path) = console_in_path {
321 Some(File::open(console_in_path).with_context(|| {
322 format!("Failed to open console input file {:?}", console_in_path)
323 })?)
324 } else {
325 Some(duplicate_fd(io::stdin())?)
326 };
327 let log = if let Some(log_path) = log_path {
328 Some(
329 File::create(log_path)
330 .with_context(|| format!("Failed to open log file {:?}", log_path))?,
331 )
332 } else {
333 Some(duplicate_fd(io::stdout())?)
334 };
335 let dump_dt = if let Some(dump_device_tree) = dump_device_tree {
336 Some(File::create(dump_device_tree).with_context(|| {
337 format!("Failed to open file to dump device tree: {:?}", dump_device_tree)
338 })?)
339 } else {
340 None
341 };
342 let vm = VmInstance::create(service, config, console_out, console_in, log, dump_dt)
343 .context("Failed to create VM")?;
344 let callback = Box::new(Callback {});
345 vm.start(Some(callback)).context("Failed to start VM")?;
346
347 let debug_level = get_debug_level(config).unwrap_or(DebugLevel::NONE);
348
349 println!(
350 "Created {} from {} with CID {}, state is {}.",
351 if debug_level == DebugLevel::FULL { "debuggable VM" } else { "VM" },
352 payload_config,
353 vm.cid(),
354 state_to_str(vm.state()?)
355 );
356
357 // Wait until the VM or VirtualizationService dies. If we just returned immediately then the
358 // IVirtualMachine Binder object would be dropped and the VM would be killed.
359 let death_reason = vm.wait_for_death();
360 println!("VM ended: {:?}", death_reason);
361 Ok(())
362 }
363
parse_extra_apk_list(apk: &Path, config_path: &str) -> Result<Vec<PathBuf>, Error>364 fn parse_extra_apk_list(apk: &Path, config_path: &str) -> Result<Vec<PathBuf>, Error> {
365 let mut archive = ZipArchive::new(File::open(apk)?)?;
366 let config_file = archive.by_name(config_path)?;
367 let config: VmPayloadConfig = serde_json::from_reader(config_file)?;
368 Ok(config.extra_apks.into_iter().map(|x| x.path.into()).collect())
369 }
370
set_encrypted_storage( service: &dyn IVirtualizationService, image_path: &Path, size: u64, ) -> Result<(), Error>371 fn set_encrypted_storage(
372 service: &dyn IVirtualizationService,
373 image_path: &Path,
374 size: u64,
375 ) -> Result<(), Error> {
376 let image = OpenOptions::new()
377 .create_new(false)
378 .read(true)
379 .write(true)
380 .open(image_path)
381 .with_context(|| format!("Failed to open {:?}", image_path))?;
382
383 service.setEncryptedStorageSize(&ParcelFileDescriptor::new(image), size.try_into()?)?;
384 Ok(())
385 }
386
387 struct Callback {}
388
389 impl vmclient::VmCallback for Callback {
on_payload_started(&self, _cid: i32)390 fn on_payload_started(&self, _cid: i32) {
391 eprintln!("payload started");
392 }
393
on_payload_ready(&self, _cid: i32)394 fn on_payload_ready(&self, _cid: i32) {
395 eprintln!("payload is ready");
396 }
397
on_payload_finished(&self, _cid: i32, exit_code: i32)398 fn on_payload_finished(&self, _cid: i32, exit_code: i32) {
399 eprintln!("payload finished with exit code {}", exit_code);
400 }
401
on_error(&self, _cid: i32, error_code: ErrorCode, message: &str)402 fn on_error(&self, _cid: i32, error_code: ErrorCode, message: &str) {
403 eprintln!("VM encountered an error: code={:?}, message={}", error_code, message);
404 }
405 }
406
407 /// Safely duplicate the file descriptor.
duplicate_fd<T: AsFd>(file: T) -> io::Result<File>408 fn duplicate_fd<T: AsFd>(file: T) -> io::Result<File> {
409 Ok(file.as_fd().try_clone_to_owned()?.into())
410 }
411