blob: e2299339a9ca2bd24173f3346bae0b10fb3dd81a [file] [log] [blame]
Andrew Walbranf395b822021-05-05 10:38:59 +00001// 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
Jiyong Park48b354d2021-07-15 15:04:38 +090017use crate::create_partition::command_create_partition;
Jooyung Han21e9b922021-06-26 04:14:16 +090018use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Alan Stokes0d1ef782022-09-27 13:46:35 +010019 IVirtualizationService::IVirtualizationService,
20 PartitionType::PartitionType,
21 VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
22 VirtualMachineConfig::VirtualMachineConfig,
Inseob Kim7b5f65c2022-11-15 14:27:04 +090023 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Andrew Walbranf8d94112021-09-07 11:45:36 +000024 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090025};
Nikita Ioffeb0b67562022-11-22 15:48:06 +000026use anyhow::{anyhow, bail, Context, Error};
Alan Stokes0e82b502022-08-08 14:44:48 +010027use binder::ParcelFileDescriptor;
Nikita Ioffefc041962023-01-18 00:10:40 +000028use glob::glob;
Inseob Kima5a262f2021-11-17 19:41:03 +090029use microdroid_payload_config::VmPayloadConfig;
Nikita Ioffeb0b67562022-11-22 15:48:06 +000030use rand::{distributions::Alphanumeric, Rng};
31use std::fs;
Andrew Walbranf395b822021-05-05 10:38:59 +000032use std::fs::File;
Alan Stokesf30982b2022-11-18 11:50:32 +000033use std::io;
Andrew Walbranf395b822021-05-05 10:38:59 +000034use std::os::unix::io::{AsRawFd, FromRawFd};
Inseob Kima5a262f2021-11-17 19:41:03 +090035use std::path::{Path, PathBuf};
Alan Stokes2bead0d2022-09-05 16:58:34 +010036use vmclient::{ErrorCode, VmInstance};
Jiyong Park48b354d2021-07-15 15:04:38 +090037use vmconfig::{open_parcel_file, VmConfig};
Inseob Kima5a262f2021-11-17 19:41:03 +090038use zip::ZipArchive;
Andrew Walbranf395b822021-05-05 10:38:59 +000039
Jooyung Han21e9b922021-06-26 04:14:16 +090040/// Run a VM from the given APK, idsig, and config.
Jiyong Park48b354d2021-07-15 15:04:38 +090041#[allow(clippy::too_many_arguments)]
Jooyung Han21e9b922021-06-26 04:14:16 +090042pub fn command_run_app(
Seungjae Yoo62085c02022-08-12 04:44:52 +000043 name: Option<String>,
Andrew Walbran616d13f2022-05-12 18:35:55 +000044 service: &dyn IVirtualizationService,
Jooyung Han21e9b922021-06-26 04:14:16 +090045 apk: &Path,
46 idsig: &Path,
Jiyong Park48b354d2021-07-15 15:04:38 +090047 instance: &Path,
Shikha Panwar22e70452022-10-10 18:32:55 +000048 storage: Option<&Path>,
49 storage_size: Option<u64>,
Inseob Kim7b5f65c2022-11-15 14:27:04 +090050 config_path: Option<String>,
Alan Stokes8f12f2b2023-01-09 09:19:20 +000051 payload_binary_name: Option<String>,
Jiyong Parkb8182bb2021-10-26 22:53:08 +090052 console_path: Option<&Path>,
Jooyung Han21e9b922021-06-26 04:14:16 +090053 log_path: Option<&Path>,
Jiyong Parkc2a49cc2021-10-15 00:02:12 +090054 debug_level: DebugLevel,
Andrew Walbran3994f002022-01-27 17:33:45 +000055 protected: bool,
Jiyong Parkd63cfff2021-09-27 20:10:17 +090056 mem: Option<u32>,
Jiyong Park032615f2022-01-10 13:55:34 +090057 cpus: Option<u32>,
Jiyong Parkdfe16d62022-04-20 17:32:12 +090058 task_profiles: Vec<String>,
Inseob Kima5a262f2021-11-17 19:41:03 +090059 extra_idsigs: &[PathBuf],
Jooyung Han21e9b922021-06-26 04:14:16 +090060) -> Result<(), Error> {
Steven Moreland6a55e2e2022-10-22 00:30:42 +000061 let apk_file = File::open(apk).context("Failed to open APK file")?;
62
Inseob Kim7b5f65c2022-11-15 14:27:04 +090063 let extra_apks = match config_path.as_deref() {
64 Some(path) => parse_extra_apk_list(apk, path)?,
65 None => vec![],
66 };
67
Inseob Kima5a262f2021-11-17 19:41:03 +090068 if extra_apks.len() != extra_idsigs.len() {
69 bail!(
70 "Found {} extra apks, but there are {} extra idsigs",
71 extra_apks.len(),
72 extra_idsigs.len()
73 )
74 }
75
76 for i in 0..extra_apks.len() {
77 let extra_apk_fd = ParcelFileDescriptor::new(File::open(&extra_apks[i])?);
78 let extra_idsig_fd = ParcelFileDescriptor::new(File::create(&extra_idsigs[i])?);
79 service.createOrUpdateIdsigFile(&extra_apk_fd, &extra_idsig_fd)?;
80 }
81
Jiyong Park0a248432021-08-20 23:32:39 +090082 let idsig_file = File::create(idsig).context("Failed to create idsig file")?;
83
84 let apk_fd = ParcelFileDescriptor::new(apk_file);
85 let idsig_fd = ParcelFileDescriptor::new(idsig_file);
86 service.createOrUpdateIdsigFile(&apk_fd, &idsig_fd)?;
87
Jooyung Han21e9b922021-06-26 04:14:16 +090088 let idsig_file = File::open(idsig).context("Failed to open idsig file")?;
Jiyong Park0a248432021-08-20 23:32:39 +090089 let idsig_fd = ParcelFileDescriptor::new(idsig_file);
Jiyong Park48b354d2021-07-15 15:04:38 +090090
91 if !instance.exists() {
92 const INSTANCE_FILE_SIZE: u64 = 10 * 1024 * 1024;
Jiyong Park9dd389e2021-08-23 20:42:59 +090093 command_create_partition(
Andrew Walbran616d13f2022-05-12 18:35:55 +000094 service,
Jiyong Park9dd389e2021-08-23 20:42:59 +090095 instance,
96 INSTANCE_FILE_SIZE,
97 PartitionType::ANDROID_VM_INSTANCE,
98 )?;
Jiyong Park48b354d2021-07-15 15:04:38 +090099 }
100
Shikha Panwar22e70452022-10-10 18:32:55 +0000101 let storage = if let Some(path) = storage {
102 if !path.exists() {
103 command_create_partition(
104 service,
105 path,
106 storage_size.unwrap_or(10 * 1024 * 1024),
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000107 PartitionType::ENCRYPTEDSTORE,
Shikha Panwar22e70452022-10-10 18:32:55 +0000108 )?;
109 }
110 Some(open_parcel_file(path, true)?)
111 } else {
112 None
113 };
114
Inseob Kima5a262f2021-11-17 19:41:03 +0900115 let extra_idsig_files: Result<Vec<File>, _> = extra_idsigs.iter().map(File::open).collect();
116 let extra_idsig_fds = extra_idsig_files?.into_iter().map(ParcelFileDescriptor::new).collect();
117
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900118 let payload = if let Some(config_path) = config_path {
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000119 if payload_binary_name.is_some() {
120 bail!("Only one of --config-path or --payload-binary-name can be defined")
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900121 }
122 Payload::ConfigPath(config_path)
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000123 } else if let Some(payload_binary_name) = payload_binary_name {
124 Payload::PayloadConfig(VirtualMachinePayloadConfig {
125 payloadBinaryName: payload_binary_name,
126 })
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900127 } else {
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000128 bail!("Either --config-path or --payload-binary-name must be defined")
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900129 };
130
131 let payload_config_str = format!("{:?}!{:?}", apk, payload);
132
Jooyung Han21e9b922021-06-26 04:14:16 +0900133 let config = VirtualMachineConfig::AppConfig(VirtualMachineAppConfig {
Seungjae Yoo62085c02022-08-12 04:44:52 +0000134 name: name.unwrap_or_else(|| String::from("VmRunApp")),
Jiyong Park0a248432021-08-20 23:32:39 +0900135 apk: apk_fd.into(),
136 idsig: idsig_fd.into(),
Inseob Kima5a262f2021-11-17 19:41:03 +0900137 extraIdsigs: extra_idsig_fds,
Jiyong Park48b354d2021-07-15 15:04:38 +0900138 instanceImage: open_parcel_file(instance, true /* writable */)?.into(),
Shikha Panwar22e70452022-10-10 18:32:55 +0000139 encryptedStorageImage: storage,
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900140 payload,
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900141 debugLevel: debug_level,
Andrew Walbran3994f002022-01-27 17:33:45 +0000142 protectedVm: protected,
Jiyong Parkd63cfff2021-09-27 20:10:17 +0900143 memoryMib: mem.unwrap_or(0) as i32, // 0 means use the VM default
Jiyong Park032615f2022-01-10 13:55:34 +0900144 numCpus: cpus.unwrap_or(1) as i32,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900145 taskProfiles: task_profiles,
Jooyung Han21e9b922021-06-26 04:14:16 +0900146 });
David Brazdil2b6352f2023-01-12 11:01:17 +0000147 run(service, &config, &payload_config_str, console_path, log_path)
Jooyung Han21e9b922021-06-26 04:14:16 +0900148}
149
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000150fn find_empty_payload_apk_path() -> Result<PathBuf, Error> {
Nikita Ioffefc041962023-01-18 00:10:40 +0000151 const GLOB_PATTERN: &str = "/apex/com.android.virt/app/**/EmptyPayloadApp.apk";
152 let mut entries: Vec<PathBuf> =
153 glob(GLOB_PATTERN).context("failed to glob")?.filter_map(|e| e.ok()).collect();
154 if entries.len() > 1 {
155 return Err(anyhow!("Found more than one apk matching {}", GLOB_PATTERN));
156 }
157 match entries.pop() {
158 Some(path) => Ok(path),
159 None => Err(anyhow!("No apks match {}", GLOB_PATTERN)),
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000160 }
161}
162
163fn create_work_dir() -> Result<PathBuf, Error> {
164 let s: String =
165 rand::thread_rng().sample_iter(&Alphanumeric).take(17).map(char::from).collect();
166 let work_dir = PathBuf::from("/data/local/tmp/microdroid").join(s);
167 println!("creating work dir {}", work_dir.display());
168 fs::create_dir_all(&work_dir).context("failed to mkdir")?;
169 Ok(work_dir)
170}
171
172/// Run a VM with Microdroid
173#[allow(clippy::too_many_arguments)]
174pub fn command_run_microdroid(
175 name: Option<String>,
176 service: &dyn IVirtualizationService,
177 work_dir: Option<PathBuf>,
178 storage: Option<&Path>,
179 storage_size: Option<u64>,
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000180 console_path: Option<&Path>,
181 log_path: Option<&Path>,
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000182 debug_level: DebugLevel,
183 protected: bool,
184 mem: Option<u32>,
185 cpus: Option<u32>,
186 task_profiles: Vec<String>,
187) -> Result<(), Error> {
Nikita Ioffefc041962023-01-18 00:10:40 +0000188 let apk = find_empty_payload_apk_path()?;
189 println!("found path {}", apk.display());
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000190
191 let work_dir = work_dir.unwrap_or(create_work_dir()?);
192 let idsig = work_dir.join("apk.idsig");
193 println!("apk.idsig path: {}", idsig.display());
194 let instance_img = work_dir.join("instance.img");
195 println!("instance.img path: {}", instance_img.display());
196
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000197 let payload_binary_name = "MicrodroidEmptyPayloadJniLib.so";
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000198 let extra_sig = [];
199 command_run_app(
200 name,
201 service,
202 &apk,
203 &idsig,
204 &instance_img,
205 storage,
206 storage_size,
207 /* config_path= */ None,
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000208 Some(payload_binary_name.to_owned()),
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000209 console_path,
210 log_path,
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000211 debug_level,
212 protected,
213 mem,
214 cpus,
215 task_profiles,
216 &extra_sig,
217 )
218}
219
Andrew Walbranf395b822021-05-05 10:38:59 +0000220/// Run a VM from the given configuration file.
Jooyung Hanb7983a22022-02-22 05:21:27 +0900221#[allow(clippy::too_many_arguments)]
Andrew Walbranf395b822021-05-05 10:38:59 +0000222pub fn command_run(
Seungjae Yoo62085c02022-08-12 04:44:52 +0000223 name: Option<String>,
Andrew Walbran616d13f2022-05-12 18:35:55 +0000224 service: &dyn IVirtualizationService,
Andrew Walbranf395b822021-05-05 10:38:59 +0000225 config_path: &Path,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900226 console_path: Option<&Path>,
Jooyung Hanb7983a22022-02-22 05:21:27 +0900227 log_path: Option<&Path>,
Jiyong Parkd63cfff2021-09-27 20:10:17 +0900228 mem: Option<u32>,
Jiyong Park032615f2022-01-10 13:55:34 +0900229 cpus: Option<u32>,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900230 task_profiles: Vec<String>,
Andrew Walbranf395b822021-05-05 10:38:59 +0000231) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000232 let config_file = File::open(config_path).context("Failed to open config file")?;
Jiyong Parkd63cfff2021-09-27 20:10:17 +0900233 let mut config =
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000234 VmConfig::load(&config_file).context("Failed to parse config file")?.to_parcelable()?;
Jiyong Parkd63cfff2021-09-27 20:10:17 +0900235 if let Some(mem) = mem {
236 config.memoryMib = mem as i32;
237 }
Jiyong Park032615f2022-01-10 13:55:34 +0900238 if let Some(cpus) = cpus {
239 config.numCpus = cpus as i32;
240 }
Seungjae Yoo62085c02022-08-12 04:44:52 +0000241 if let Some(name) = name {
242 config.name = name;
243 } else {
244 config.name = String::from("VmRun");
245 }
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900246 config.taskProfiles = task_profiles;
Jooyung Han21e9b922021-06-26 04:14:16 +0900247 run(
248 service,
249 &VirtualMachineConfig::RawConfig(config),
250 &format!("{:?}", config_path),
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900251 console_path,
Jooyung Hanb7983a22022-02-22 05:21:27 +0900252 log_path,
Jooyung Han21e9b922021-06-26 04:14:16 +0900253 )
254}
255
Andrew Walbranf8d94112021-09-07 11:45:36 +0000256fn state_to_str(vm_state: VirtualMachineState) -> &'static str {
257 match vm_state {
258 VirtualMachineState::NOT_STARTED => "NOT_STARTED",
259 VirtualMachineState::STARTING => "STARTING",
260 VirtualMachineState::STARTED => "STARTED",
261 VirtualMachineState::READY => "READY",
262 VirtualMachineState::FINISHED => "FINISHED",
263 VirtualMachineState::DEAD => "DEAD",
264 _ => "(invalid state)",
265 }
266}
267
Jooyung Han21e9b922021-06-26 04:14:16 +0900268fn run(
Andrew Walbran616d13f2022-05-12 18:35:55 +0000269 service: &dyn IVirtualizationService,
Jooyung Han21e9b922021-06-26 04:14:16 +0900270 config: &VirtualMachineConfig,
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900271 payload_config: &str,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900272 console_path: Option<&Path>,
Jooyung Han21e9b922021-06-26 04:14:16 +0900273 log_path: Option<&Path>,
274) -> Result<(), Error> {
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900275 let console = if let Some(console_path) = console_path {
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000276 Some(
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900277 File::create(console_path)
278 .with_context(|| format!("Failed to open console file {:?}", console_path))?,
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000279 )
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900280 } else {
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000281 Some(duplicate_stdout()?)
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900282 };
283 let log = if let Some(log_path) = log_path {
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000284 Some(
Andrew Walbranbe429242021-06-28 12:22:54 +0000285 File::create(log_path)
286 .with_context(|| format!("Failed to open log file {:?}", log_path))?,
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000287 )
Andrew Walbranbe429242021-06-28 12:22:54 +0000288 } else {
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000289 Some(duplicate_stdout()?)
Andrew Walbranbe429242021-06-28 12:22:54 +0000290 };
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900291
Alan Stokes0e82b502022-08-08 14:44:48 +0100292 let callback = Box::new(Callback {});
293 let vm = VmInstance::create(service, config, console, log, Some(callback))
294 .context("Failed to create VM")?;
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000295 vm.start().context("Failed to start VM")?;
Andrew Walbranf395b822021-05-05 10:38:59 +0000296
Andrew Walbranf8d94112021-09-07 11:45:36 +0000297 println!(
298 "Created VM from {} with CID {}, state is {}.",
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900299 payload_config,
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000300 vm.cid(),
301 state_to_str(vm.state()?)
Andrew Walbranf8d94112021-09-07 11:45:36 +0000302 );
Andrew Walbranf395b822021-05-05 10:38:59 +0000303
David Brazdil2b6352f2023-01-12 11:01:17 +0000304 // Wait until the VM or VirtualizationService dies. If we just returned immediately then the
305 // IVirtualMachine Binder object would be dropped and the VM would be killed.
306 let death_reason = vm.wait_for_death();
307 println!("VM ended: {:?}", death_reason);
Andrew Walbranf395b822021-05-05 10:38:59 +0000308 Ok(())
309}
310
Inseob Kima5a262f2021-11-17 19:41:03 +0900311fn parse_extra_apk_list(apk: &Path, config_path: &str) -> Result<Vec<String>, Error> {
312 let mut archive = ZipArchive::new(File::open(apk)?)?;
313 let config_file = archive.by_name(config_path)?;
314 let config: VmPayloadConfig = serde_json::from_reader(config_file)?;
315 Ok(config.extra_apks.into_iter().map(|x| x.path).collect())
316}
317
Alan Stokes0e82b502022-08-08 14:44:48 +0100318struct Callback {}
Andrew Walbranf395b822021-05-05 10:38:59 +0000319
Alan Stokes0e82b502022-08-08 14:44:48 +0100320impl vmclient::VmCallback for Callback {
David Brazdil451cc962022-10-14 14:08:12 +0100321 fn on_payload_started(&self, _cid: i32) {
322 eprintln!("payload started");
323 }
324
Alan Stokes0e82b502022-08-08 14:44:48 +0100325 fn on_payload_ready(&self, _cid: i32) {
Inseob Kim8dbc3222021-09-01 21:50:23 +0900326 eprintln!("payload is ready");
Inseob Kim14cb8692021-08-31 21:50:39 +0900327 }
328
Alan Stokes0e82b502022-08-08 14:44:48 +0100329 fn on_payload_finished(&self, _cid: i32, exit_code: i32) {
Inseob Kim8dbc3222021-09-01 21:50:23 +0900330 eprintln!("payload finished with exit code {}", exit_code);
Inseob Kim2444af92021-08-31 01:22:50 +0900331 }
332
Alan Stokes2bead0d2022-09-05 16:58:34 +0100333 fn on_error(&self, _cid: i32, error_code: ErrorCode, message: &str) {
334 eprintln!("VM encountered an error: code={:?}, message={}", error_code, message);
Andrew Walbranf395b822021-05-05 10:38:59 +0000335 }
336}
337
338/// Safely duplicate the standard output file descriptor.
339fn duplicate_stdout() -> io::Result<File> {
340 let stdout_fd = io::stdout().as_raw_fd();
341 // Safe because this just duplicates a file descriptor which we know to be valid, and we check
342 // for an error.
343 let dup_fd = unsafe { libc::dup(stdout_fd) };
344 if dup_fd < 0 {
345 Err(io::Error::last_os_error())
346 } else {
347 // Safe because we have just duplicated the file descriptor so we own it, and `from_raw_fd`
348 // takes ownership of it.
349 Ok(unsafe { File::from_raw_fd(dup_fd) })
350 }
351}