blob: 250c56c16c9a38ddce48acdbeb7b3dc6526c0932 [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::{
David Brazdil7d1e5ec2023-02-06 17:56:29 +000019 CpuTopology::CpuTopology,
Alan Stokes0d1ef782022-09-27 13:46:35 +010020 IVirtualizationService::IVirtualizationService,
21 PartitionType::PartitionType,
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +010022 VirtualMachineAppConfig::{
23 CustomConfig::CustomConfig, DebugLevel::DebugLevel, Payload::Payload,
24 VirtualMachineAppConfig,
25 },
Alan Stokes0d1ef782022-09-27 13:46:35 +010026 VirtualMachineConfig::VirtualMachineConfig,
Inseob Kim7b5f65c2022-11-15 14:27:04 +090027 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Andrew Walbranf8d94112021-09-07 11:45:36 +000028 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090029};
Nikita Ioffeb0b67562022-11-22 15:48:06 +000030use anyhow::{anyhow, bail, Context, Error};
Alan Stokes0e82b502022-08-08 14:44:48 +010031use binder::ParcelFileDescriptor;
Nikita Ioffefc041962023-01-18 00:10:40 +000032use glob::glob;
Inseob Kima5a262f2021-11-17 19:41:03 +090033use microdroid_payload_config::VmPayloadConfig;
Nikita Ioffeb0b67562022-11-22 15:48:06 +000034use rand::{distributions::Alphanumeric, Rng};
35use std::fs;
Andrew Walbranf395b822021-05-05 10:38:59 +000036use std::fs::File;
Alan Stokesf30982b2022-11-18 11:50:32 +000037use std::io;
Nikita Ioffe5776f082023-02-10 21:38:26 +000038use std::num::NonZeroU16;
Andrew Walbranf395b822021-05-05 10:38:59 +000039use std::os::unix::io::{AsRawFd, FromRawFd};
Inseob Kima5a262f2021-11-17 19:41:03 +090040use std::path::{Path, PathBuf};
Alan Stokes2bead0d2022-09-05 16:58:34 +010041use vmclient::{ErrorCode, VmInstance};
Jiyong Park48b354d2021-07-15 15:04:38 +090042use vmconfig::{open_parcel_file, VmConfig};
Inseob Kima5a262f2021-11-17 19:41:03 +090043use zip::ZipArchive;
Andrew Walbranf395b822021-05-05 10:38:59 +000044
Jooyung Han21e9b922021-06-26 04:14:16 +090045/// Run a VM from the given APK, idsig, and config.
Jiyong Park48b354d2021-07-15 15:04:38 +090046#[allow(clippy::too_many_arguments)]
Jooyung Han21e9b922021-06-26 04:14:16 +090047pub fn command_run_app(
Seungjae Yoo62085c02022-08-12 04:44:52 +000048 name: Option<String>,
Andrew Walbran616d13f2022-05-12 18:35:55 +000049 service: &dyn IVirtualizationService,
Jooyung Han21e9b922021-06-26 04:14:16 +090050 apk: &Path,
51 idsig: &Path,
Jiyong Park48b354d2021-07-15 15:04:38 +090052 instance: &Path,
Shikha Panwar22e70452022-10-10 18:32:55 +000053 storage: Option<&Path>,
54 storage_size: Option<u64>,
Inseob Kim7b5f65c2022-11-15 14:27:04 +090055 config_path: Option<String>,
Alan Stokes8f12f2b2023-01-09 09:19:20 +000056 payload_binary_name: Option<String>,
Jiyong Parke6fb1672023-06-26 16:45:55 +090057 console_out_path: Option<&Path>,
58 console_in_path: Option<&Path>,
Jooyung Han21e9b922021-06-26 04:14:16 +090059 log_path: Option<&Path>,
Jiyong Parkc2a49cc2021-10-15 00:02:12 +090060 debug_level: DebugLevel,
Andrew Walbran3994f002022-01-27 17:33:45 +000061 protected: bool,
Jiyong Parkd63cfff2021-09-27 20:10:17 +090062 mem: Option<u32>,
David Brazdil7d1e5ec2023-02-06 17:56:29 +000063 cpu_topology: CpuTopology,
Jiyong Parkdfe16d62022-04-20 17:32:12 +090064 task_profiles: Vec<String>,
Inseob Kima5a262f2021-11-17 19:41:03 +090065 extra_idsigs: &[PathBuf],
Nikita Ioffe5776f082023-02-10 21:38:26 +000066 gdb: Option<NonZeroU16>,
Nikita Ioffe26c35ed2023-06-05 17:49:08 +010067 kernel: Option<&Path>,
Nikita Ioffe5dfddf22023-06-29 16:11:26 +010068 vendor: Option<&Path>,
Inseob Kim6ef80972023-07-20 17:23:36 +090069 devices: Vec<PathBuf>,
Jooyung Han21e9b922021-06-26 04:14:16 +090070) -> Result<(), Error> {
Steven Moreland6a55e2e2022-10-22 00:30:42 +000071 let apk_file = File::open(apk).context("Failed to open APK file")?;
72
Inseob Kim7b5f65c2022-11-15 14:27:04 +090073 let extra_apks = match config_path.as_deref() {
74 Some(path) => parse_extra_apk_list(apk, path)?,
75 None => vec![],
76 };
77
Inseob Kima5a262f2021-11-17 19:41:03 +090078 if extra_apks.len() != extra_idsigs.len() {
79 bail!(
80 "Found {} extra apks, but there are {} extra idsigs",
81 extra_apks.len(),
82 extra_idsigs.len()
83 )
84 }
85
86 for i in 0..extra_apks.len() {
87 let extra_apk_fd = ParcelFileDescriptor::new(File::open(&extra_apks[i])?);
88 let extra_idsig_fd = ParcelFileDescriptor::new(File::create(&extra_idsigs[i])?);
89 service.createOrUpdateIdsigFile(&extra_apk_fd, &extra_idsig_fd)?;
90 }
91
Jiyong Park0a248432021-08-20 23:32:39 +090092 let idsig_file = File::create(idsig).context("Failed to create idsig file")?;
93
94 let apk_fd = ParcelFileDescriptor::new(apk_file);
95 let idsig_fd = ParcelFileDescriptor::new(idsig_file);
96 service.createOrUpdateIdsigFile(&apk_fd, &idsig_fd)?;
97
Jooyung Han21e9b922021-06-26 04:14:16 +090098 let idsig_file = File::open(idsig).context("Failed to open idsig file")?;
Jiyong Park0a248432021-08-20 23:32:39 +090099 let idsig_fd = ParcelFileDescriptor::new(idsig_file);
Jiyong Park48b354d2021-07-15 15:04:38 +0900100
101 if !instance.exists() {
102 const INSTANCE_FILE_SIZE: u64 = 10 * 1024 * 1024;
Jiyong Park9dd389e2021-08-23 20:42:59 +0900103 command_create_partition(
Andrew Walbran616d13f2022-05-12 18:35:55 +0000104 service,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900105 instance,
106 INSTANCE_FILE_SIZE,
107 PartitionType::ANDROID_VM_INSTANCE,
108 )?;
Jiyong Park48b354d2021-07-15 15:04:38 +0900109 }
110
Shikha Panwar22e70452022-10-10 18:32:55 +0000111 let storage = if let Some(path) = storage {
112 if !path.exists() {
113 command_create_partition(
114 service,
115 path,
116 storage_size.unwrap_or(10 * 1024 * 1024),
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000117 PartitionType::ENCRYPTEDSTORE,
Shikha Panwar22e70452022-10-10 18:32:55 +0000118 )?;
119 }
120 Some(open_parcel_file(path, true)?)
121 } else {
122 None
123 };
124
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100125 let kernel = kernel.map(|p| open_parcel_file(p, false)).transpose()?;
126
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100127 let vendor = vendor.map(|p| open_parcel_file(p, false)).transpose()?;
128
Inseob Kima5a262f2021-11-17 19:41:03 +0900129 let extra_idsig_files: Result<Vec<File>, _> = extra_idsigs.iter().map(File::open).collect();
130 let extra_idsig_fds = extra_idsig_files?.into_iter().map(ParcelFileDescriptor::new).collect();
131
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900132 let payload = if let Some(config_path) = config_path {
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000133 if payload_binary_name.is_some() {
134 bail!("Only one of --config-path or --payload-binary-name can be defined")
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900135 }
136 Payload::ConfigPath(config_path)
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000137 } else if let Some(payload_binary_name) = payload_binary_name {
138 Payload::PayloadConfig(VirtualMachinePayloadConfig {
139 payloadBinaryName: payload_binary_name,
140 })
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900141 } else {
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000142 bail!("Either --config-path or --payload-binary-name must be defined")
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900143 };
144
145 let payload_config_str = format!("{:?}!{:?}", apk, payload);
146
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100147 let custom_config = CustomConfig {
148 customKernelImage: kernel,
149 gdbPort: gdb.map(u16::from).unwrap_or(0) as i32, // 0 means no gdb
150 taskProfiles: task_profiles,
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100151 vendorImage: vendor,
Inseob Kim6ef80972023-07-20 17:23:36 +0900152 devices: devices
153 .iter()
154 .map(|x| {
155 x.to_str().map(String::from).ok_or(anyhow!("Failed to convert {x:?} to String"))
156 })
157 .collect::<Result<_, _>>()?,
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100158 };
159
Jooyung Han21e9b922021-06-26 04:14:16 +0900160 let config = VirtualMachineConfig::AppConfig(VirtualMachineAppConfig {
Seungjae Yoo62085c02022-08-12 04:44:52 +0000161 name: name.unwrap_or_else(|| String::from("VmRunApp")),
Jiyong Park0a248432021-08-20 23:32:39 +0900162 apk: apk_fd.into(),
163 idsig: idsig_fd.into(),
Inseob Kima5a262f2021-11-17 19:41:03 +0900164 extraIdsigs: extra_idsig_fds,
Jiyong Park48b354d2021-07-15 15:04:38 +0900165 instanceImage: open_parcel_file(instance, true /* writable */)?.into(),
Shikha Panwar22e70452022-10-10 18:32:55 +0000166 encryptedStorageImage: storage,
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900167 payload,
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900168 debugLevel: debug_level,
Andrew Walbran3994f002022-01-27 17:33:45 +0000169 protectedVm: protected,
Jiyong Parkd63cfff2021-09-27 20:10:17 +0900170 memoryMib: mem.unwrap_or(0) as i32, // 0 means use the VM default
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000171 cpuTopology: cpu_topology,
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100172 customConfig: Some(custom_config),
Jooyung Han21e9b922021-06-26 04:14:16 +0900173 });
Jiyong Parke6fb1672023-06-26 16:45:55 +0900174 run(service, &config, &payload_config_str, console_out_path, console_in_path, log_path)
Jooyung Han21e9b922021-06-26 04:14:16 +0900175}
176
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000177fn find_empty_payload_apk_path() -> Result<PathBuf, Error> {
Cole Faust237ee3e2023-03-01 11:58:01 -0800178 const GLOB_PATTERN: &str = "/apex/com.android.virt/app/**/EmptyPayloadApp*.apk";
Nikita Ioffefc041962023-01-18 00:10:40 +0000179 let mut entries: Vec<PathBuf> =
180 glob(GLOB_PATTERN).context("failed to glob")?.filter_map(|e| e.ok()).collect();
181 if entries.len() > 1 {
182 return Err(anyhow!("Found more than one apk matching {}", GLOB_PATTERN));
183 }
184 match entries.pop() {
185 Some(path) => Ok(path),
186 None => Err(anyhow!("No apks match {}", GLOB_PATTERN)),
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000187 }
188}
189
190fn create_work_dir() -> Result<PathBuf, Error> {
191 let s: String =
192 rand::thread_rng().sample_iter(&Alphanumeric).take(17).map(char::from).collect();
193 let work_dir = PathBuf::from("/data/local/tmp/microdroid").join(s);
194 println!("creating work dir {}", work_dir.display());
195 fs::create_dir_all(&work_dir).context("failed to mkdir")?;
196 Ok(work_dir)
197}
198
199/// Run a VM with Microdroid
200#[allow(clippy::too_many_arguments)]
201pub fn command_run_microdroid(
202 name: Option<String>,
203 service: &dyn IVirtualizationService,
204 work_dir: Option<PathBuf>,
205 storage: Option<&Path>,
206 storage_size: Option<u64>,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900207 console_out_path: Option<&Path>,
208 console_in_path: Option<&Path>,
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000209 log_path: Option<&Path>,
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000210 debug_level: DebugLevel,
211 protected: bool,
212 mem: Option<u32>,
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000213 cpu_topology: CpuTopology,
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000214 task_profiles: Vec<String>,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000215 gdb: Option<NonZeroU16>,
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100216 kernel: Option<&Path>,
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100217 vendor: Option<&Path>,
Inseob Kim6ef80972023-07-20 17:23:36 +0900218 devices: Vec<PathBuf>,
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000219) -> Result<(), Error> {
Nikita Ioffefc041962023-01-18 00:10:40 +0000220 let apk = find_empty_payload_apk_path()?;
221 println!("found path {}", apk.display());
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000222
223 let work_dir = work_dir.unwrap_or(create_work_dir()?);
224 let idsig = work_dir.join("apk.idsig");
225 println!("apk.idsig path: {}", idsig.display());
226 let instance_img = work_dir.join("instance.img");
227 println!("instance.img path: {}", instance_img.display());
228
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000229 let payload_binary_name = "MicrodroidEmptyPayloadJniLib.so";
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000230 let extra_sig = [];
231 command_run_app(
232 name,
233 service,
234 &apk,
235 &idsig,
236 &instance_img,
237 storage,
238 storage_size,
239 /* config_path= */ None,
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000240 Some(payload_binary_name.to_owned()),
Jiyong Parke6fb1672023-06-26 16:45:55 +0900241 console_out_path,
242 console_in_path,
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000243 log_path,
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000244 debug_level,
245 protected,
246 mem,
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000247 cpu_topology,
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000248 task_profiles,
249 &extra_sig,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000250 gdb,
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100251 kernel,
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100252 vendor,
Inseob Kim6ef80972023-07-20 17:23:36 +0900253 devices,
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000254 )
255}
256
Andrew Walbranf395b822021-05-05 10:38:59 +0000257/// Run a VM from the given configuration file.
Jooyung Hanb7983a22022-02-22 05:21:27 +0900258#[allow(clippy::too_many_arguments)]
Andrew Walbranf395b822021-05-05 10:38:59 +0000259pub fn command_run(
Seungjae Yoo62085c02022-08-12 04:44:52 +0000260 name: Option<String>,
Andrew Walbran616d13f2022-05-12 18:35:55 +0000261 service: &dyn IVirtualizationService,
Andrew Walbranf395b822021-05-05 10:38:59 +0000262 config_path: &Path,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900263 console_out_path: Option<&Path>,
264 console_in_path: Option<&Path>,
Jooyung Hanb7983a22022-02-22 05:21:27 +0900265 log_path: Option<&Path>,
Jiyong Parkd63cfff2021-09-27 20:10:17 +0900266 mem: Option<u32>,
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000267 cpu_topology: CpuTopology,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900268 task_profiles: Vec<String>,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000269 gdb: Option<NonZeroU16>,
Andrew Walbranf395b822021-05-05 10:38:59 +0000270) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000271 let config_file = File::open(config_path).context("Failed to open config file")?;
Jiyong Parkd63cfff2021-09-27 20:10:17 +0900272 let mut config =
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000273 VmConfig::load(&config_file).context("Failed to parse config file")?.to_parcelable()?;
Jiyong Parkd63cfff2021-09-27 20:10:17 +0900274 if let Some(mem) = mem {
275 config.memoryMib = mem as i32;
276 }
Seungjae Yoo62085c02022-08-12 04:44:52 +0000277 if let Some(name) = name {
278 config.name = name;
279 } else {
280 config.name = String::from("VmRun");
281 }
Nikita Ioffe5776f082023-02-10 21:38:26 +0000282 if let Some(gdb) = gdb {
283 config.gdbPort = gdb.get() as i32;
284 }
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000285 config.cpuTopology = cpu_topology;
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900286 config.taskProfiles = task_profiles;
Jooyung Han21e9b922021-06-26 04:14:16 +0900287 run(
288 service,
289 &VirtualMachineConfig::RawConfig(config),
290 &format!("{:?}", config_path),
Jiyong Parke6fb1672023-06-26 16:45:55 +0900291 console_out_path,
292 console_in_path,
Jooyung Hanb7983a22022-02-22 05:21:27 +0900293 log_path,
Jooyung Han21e9b922021-06-26 04:14:16 +0900294 )
295}
296
Andrew Walbranf8d94112021-09-07 11:45:36 +0000297fn state_to_str(vm_state: VirtualMachineState) -> &'static str {
298 match vm_state {
299 VirtualMachineState::NOT_STARTED => "NOT_STARTED",
300 VirtualMachineState::STARTING => "STARTING",
301 VirtualMachineState::STARTED => "STARTED",
302 VirtualMachineState::READY => "READY",
303 VirtualMachineState::FINISHED => "FINISHED",
304 VirtualMachineState::DEAD => "DEAD",
305 _ => "(invalid state)",
306 }
307}
308
Jooyung Han21e9b922021-06-26 04:14:16 +0900309fn run(
Andrew Walbran616d13f2022-05-12 18:35:55 +0000310 service: &dyn IVirtualizationService,
Jooyung Han21e9b922021-06-26 04:14:16 +0900311 config: &VirtualMachineConfig,
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900312 payload_config: &str,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900313 console_out_path: Option<&Path>,
314 console_in_path: Option<&Path>,
Jooyung Han21e9b922021-06-26 04:14:16 +0900315 log_path: Option<&Path>,
316) -> Result<(), Error> {
Jiyong Parke6fb1672023-06-26 16:45:55 +0900317 let console_out = if let Some(console_out_path) = console_out_path {
318 Some(File::create(console_out_path).with_context(|| {
319 format!("Failed to open console output file {:?}", console_out_path)
320 })?)
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900321 } else {
Jiyong Parke6fb1672023-06-26 16:45:55 +0900322 Some(duplicate_fd(io::stdout())?)
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900323 };
Jiyong Parke6fb1672023-06-26 16:45:55 +0900324 let console_in =
325 if let Some(console_in_path) = console_in_path {
326 Some(File::create(console_in_path).with_context(|| {
327 format!("Failed to open console input file {:?}", console_in_path)
328 })?)
329 } else {
330 Some(duplicate_fd(io::stdin())?)
331 };
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900332 let log = if let Some(log_path) = log_path {
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000333 Some(
Andrew Walbranbe429242021-06-28 12:22:54 +0000334 File::create(log_path)
335 .with_context(|| format!("Failed to open log file {:?}", log_path))?,
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000336 )
Andrew Walbranbe429242021-06-28 12:22:54 +0000337 } else {
Jiyong Parke6fb1672023-06-26 16:45:55 +0900338 Some(duplicate_fd(io::stdout())?)
Andrew Walbranbe429242021-06-28 12:22:54 +0000339 };
Alan Stokes0e82b502022-08-08 14:44:48 +0100340 let callback = Box::new(Callback {});
Jiyong Parke6fb1672023-06-26 16:45:55 +0900341 let vm = VmInstance::create(service, config, console_out, console_in, log, Some(callback))
Alan Stokes0e82b502022-08-08 14:44:48 +0100342 .context("Failed to create VM")?;
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000343 vm.start().context("Failed to start VM")?;
Andrew Walbranf395b822021-05-05 10:38:59 +0000344
Pierre-Clément Tosi1b691cc2023-06-28 11:40:29 +0000345 let debug_level = match config {
346 VirtualMachineConfig::AppConfig(config) => config.debugLevel,
347 _ => DebugLevel::NONE,
348 };
Andrew Walbranf8d94112021-09-07 11:45:36 +0000349 println!(
Pierre-Clément Tosi1b691cc2023-06-28 11:40:29 +0000350 "Created {} from {} with CID {}, state is {}.",
351 if debug_level == DebugLevel::FULL { "debuggable VM" } else { "VM" },
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900352 payload_config,
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000353 vm.cid(),
354 state_to_str(vm.state()?)
Andrew Walbranf8d94112021-09-07 11:45:36 +0000355 );
Andrew Walbranf395b822021-05-05 10:38:59 +0000356
David Brazdil2b6352f2023-01-12 11:01:17 +0000357 // 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);
Andrew Walbranf395b822021-05-05 10:38:59 +0000361 Ok(())
362}
363
Inseob Kima5a262f2021-11-17 19:41:03 +0900364fn parse_extra_apk_list(apk: &Path, config_path: &str) -> Result<Vec<String>, 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).collect())
369}
370
Alan Stokes0e82b502022-08-08 14:44:48 +0100371struct Callback {}
Andrew Walbranf395b822021-05-05 10:38:59 +0000372
Alan Stokes0e82b502022-08-08 14:44:48 +0100373impl vmclient::VmCallback for Callback {
David Brazdil451cc962022-10-14 14:08:12 +0100374 fn on_payload_started(&self, _cid: i32) {
375 eprintln!("payload started");
376 }
377
Alan Stokes0e82b502022-08-08 14:44:48 +0100378 fn on_payload_ready(&self, _cid: i32) {
Inseob Kim8dbc3222021-09-01 21:50:23 +0900379 eprintln!("payload is ready");
Inseob Kim14cb8692021-08-31 21:50:39 +0900380 }
381
Alan Stokes0e82b502022-08-08 14:44:48 +0100382 fn on_payload_finished(&self, _cid: i32, exit_code: i32) {
Inseob Kim8dbc3222021-09-01 21:50:23 +0900383 eprintln!("payload finished with exit code {}", exit_code);
Inseob Kim2444af92021-08-31 01:22:50 +0900384 }
385
Alan Stokes2bead0d2022-09-05 16:58:34 +0100386 fn on_error(&self, _cid: i32, error_code: ErrorCode, message: &str) {
387 eprintln!("VM encountered an error: code={:?}, message={}", error_code, message);
Andrew Walbranf395b822021-05-05 10:38:59 +0000388 }
389}
390
Jiyong Parke6fb1672023-06-26 16:45:55 +0900391/// Safely duplicate the file descriptor.
392fn duplicate_fd<T: AsRawFd>(file: T) -> io::Result<File> {
393 let fd = file.as_raw_fd();
Andrew Walbranb58d1b42023-07-07 13:54:49 +0100394 // SAFETY: This just duplicates a file descriptor which we know to be valid, and we check for an
395 // an error.
Jiyong Parke6fb1672023-06-26 16:45:55 +0900396 let dup_fd = unsafe { libc::dup(fd) };
Andrew Walbranf395b822021-05-05 10:38:59 +0000397 if dup_fd < 0 {
398 Err(io::Error::last_os_error())
399 } else {
Andrew Walbranb58d1b42023-07-07 13:54:49 +0100400 // SAFETY: We have just duplicated the file descriptor so we own it, and `from_raw_fd` takes
401 // ownership of it.
Andrew Walbranf395b822021-05-05 10:38:59 +0000402 Ok(unsafe { File::from_raw_fd(dup_fd) })
403 }
404}