blob: 8385fb4e7c8e5158dd67fec86667cc49d7954092 [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;
Jiyong Parkb1935ef2023-08-10 17:22:39 +090018use crate::{get_service, RunAppConfig, RunCustomVmConfig, RunMicrodroidConfig};
Jooyung Han21e9b922021-06-26 04:14:16 +090019use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Elie Kheirallahb4b2f242025-01-23 03:38:07 +000020 CpuOptions::CpuOptions,
Alan Stokes0d1ef782022-09-27 13:46:35 +010021 IVirtualizationService::IVirtualizationService,
22 PartitionType::PartitionType,
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +010023 VirtualMachineAppConfig::{
24 CustomConfig::CustomConfig, DebugLevel::DebugLevel, Payload::Payload,
25 VirtualMachineAppConfig,
26 },
Alan Stokes0d1ef782022-09-27 13:46:35 +010027 VirtualMachineConfig::VirtualMachineConfig,
Inseob Kim7b5f65c2022-11-15 14:27:04 +090028 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Andrew Walbranf8d94112021-09-07 11:45:36 +000029 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090030};
Nikita Ioffeb0b67562022-11-22 15:48:06 +000031use anyhow::{anyhow, bail, Context, Error};
Alan Stokes0e82b502022-08-08 14:44:48 +010032use binder::ParcelFileDescriptor;
Nikita Ioffefc041962023-01-18 00:10:40 +000033use glob::glob;
Inseob Kima5a262f2021-11-17 19:41:03 +090034use microdroid_payload_config::VmPayloadConfig;
Nikita Ioffeb0b67562022-11-22 15:48:06 +000035use rand::{distributions::Alphanumeric, Rng};
36use std::fs;
Andrew Walbranf395b822021-05-05 10:38:59 +000037use std::fs::File;
Shraddha Basantwania9a9c4f2025-02-25 09:51:48 -080038use std::fs::OpenOptions;
Alan Stokesf30982b2022-11-18 11:50:32 +000039use std::io;
Shikha Panwar61a74b52024-02-16 13:17:01 +000040use std::io::{Read, Write};
Jiyong Park8ee38312024-08-20 18:00:29 +090041use std::os::fd::AsFd;
Inseob Kima5a262f2021-11-17 19:41:03 +090042use std::path::{Path, PathBuf};
Alan Stokes2bead0d2022-09-05 16:58:34 +010043use vmclient::{ErrorCode, VmInstance};
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +010044use vmconfig::{get_debug_level, open_parcel_file, VmConfig};
Inseob Kima5a262f2021-11-17 19:41:03 +090045use zip::ZipArchive;
Andrew Walbranf395b822021-05-05 10:38:59 +000046
Jooyung Han21e9b922021-06-26 04:14:16 +090047/// Run a VM from the given APK, idsig, and config.
Jiyong Parkb1935ef2023-08-10 17:22:39 +090048pub 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")?;
Steven Moreland6a55e2e2022-10-22 00:30:42 +000051
Jiyong Parkb1935ef2023-08-10 17:22:39 +090052 let extra_apks = match config.config_path.as_deref() {
53 Some(path) => parse_extra_apk_list(&config.apk, path)?,
Alan Stokesfda70842023-12-20 17:50:14 +000054 None => config.extra_apks().to_vec(),
Inseob Kim7b5f65c2022-11-15 14:27:04 +090055 };
56
Jiyong Parkb1935ef2023-08-10 17:22:39 +090057 if extra_apks.len() != config.extra_idsigs.len() {
Inseob Kima5a262f2021-11-17 19:41:03 +090058 bail!(
59 "Found {} extra apks, but there are {} extra idsigs",
60 extra_apks.len(),
Jiyong Parkb1935ef2023-08-10 17:22:39 +090061 config.extra_idsigs.len()
Inseob Kima5a262f2021-11-17 19:41:03 +090062 )
63 }
64
Jiyong Parkb1935ef2023-08-10 17:22:39 +090065 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])?);
Inseob Kima5a262f2021-11-17 19:41:03 +090068 service.createOrUpdateIdsigFile(&extra_apk_fd, &extra_idsig_fd)?;
69 }
70
Jiyong Parkb1935ef2023-08-10 17:22:39 +090071 let idsig = File::create(&config.idsig).context("Failed to create idsig file")?;
Jiyong Park0a248432021-08-20 23:32:39 +090072
Jiyong Parkb1935ef2023-08-10 17:22:39 +090073 let apk_fd = ParcelFileDescriptor::new(apk);
74 let idsig_fd = ParcelFileDescriptor::new(idsig);
Jiyong Park0a248432021-08-20 23:32:39 +090075 service.createOrUpdateIdsigFile(&apk_fd, &idsig_fd)?;
76
Jiyong Parkb1935ef2023-08-10 17:22:39 +090077 let idsig = File::open(&config.idsig).context("Failed to open idsig file")?;
78 let idsig_fd = ParcelFileDescriptor::new(idsig);
Jiyong Park48b354d2021-07-15 15:04:38 +090079
Jiyong Parkb1935ef2023-08-10 17:22:39 +090080 if !config.instance.exists() {
Jiyong Park48b354d2021-07-15 15:04:38 +090081 const INSTANCE_FILE_SIZE: u64 = 10 * 1024 * 1024;
Jiyong Park9dd389e2021-08-23 20:42:59 +090082 command_create_partition(
Jiyong Parkb1935ef2023-08-10 17:22:39 +090083 service.as_ref(),
84 &config.instance,
Jiyong Park9dd389e2021-08-23 20:42:59 +090085 INSTANCE_FILE_SIZE,
86 PartitionType::ANDROID_VM_INSTANCE,
87 )?;
Jiyong Park48b354d2021-07-15 15:04:38 +090088 }
89
Shikha Panwar61a74b52024-02-16 13:17:01 +000090 let instance_id = if cfg!(llpvm_changes) {
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 } else {
104 // if llpvm feature flag is disabled, instance_id is not used.
105 [0u8; 64]
106 };
107
Nikita Ioffe631717e2023-09-05 13:38:07 +0100108 let storage = if let Some(ref path) = config.microdroid.storage {
Shikha Panwar22e70452022-10-10 18:32:55 +0000109 if !path.exists() {
110 command_create_partition(
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900111 service.as_ref(),
Nikita Ioffe631717e2023-09-05 13:38:07 +0100112 path,
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900113 config.microdroid.storage_size.unwrap_or(10 * 1024 * 1024),
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000114 PartitionType::ENCRYPTEDSTORE,
Shikha Panwar22e70452022-10-10 18:32:55 +0000115 )?;
Shraddha Basantwania9a9c4f2025-02-25 09:51:48 -0800116 } else if let Some(storage_size) = config.microdroid.storage_size {
117 set_encrypted_storage(service.as_ref(), path, storage_size)?;
Shikha Panwar22e70452022-10-10 18:32:55 +0000118 }
Nikita Ioffe631717e2023-09-05 13:38:07 +0100119 Some(open_parcel_file(path, true)?)
Shikha Panwar22e70452022-10-10 18:32:55 +0000120 } else {
121 None
122 };
123
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900124 let vendor =
Nikita Ioffe631717e2023-09-05 13:38:07 +0100125 config.microdroid.vendor().as_ref().map(|p| open_parcel_file(p, false)).transpose()?;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100126
Alan Stokesfda70842023-12-20 17:50:14 +0000127 let extra_idsig_files: Result<Vec<_>, _> = config.extra_idsigs.iter().map(File::open).collect();
Inseob Kima5a262f2021-11-17 19:41:03 +0900128 let extra_idsig_fds = extra_idsig_files?.into_iter().map(ParcelFileDescriptor::new).collect();
129
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900130 let payload = if let Some(config_path) = config.config_path {
131 if config.payload_binary_name.is_some() {
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000132 bail!("Only one of --config-path or --payload-binary-name can be defined")
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900133 }
134 Payload::ConfigPath(config_path)
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900135 } else if let Some(payload_binary_name) = config.payload_binary_name {
Alan Stokesfda70842023-12-20 17:50:14 +0000136 let extra_apk_files: Result<Vec<_>, _> = extra_apks.iter().map(File::open).collect();
137 let extra_apk_fds = extra_apk_files?.into_iter().map(ParcelFileDescriptor::new).collect();
138
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000139 Payload::PayloadConfig(VirtualMachinePayloadConfig {
140 payloadBinaryName: payload_binary_name,
Alan Stokesfda70842023-12-20 17:50:14 +0000141 extraApks: extra_apk_fds,
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000142 })
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900143 } else {
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000144 bail!("Either --config-path or --payload-binary-name must be defined")
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900145 };
146
Nikita Ioffe43c93622024-10-30 20:33:58 +0000147 let os_name = if let Some(ref os) = config.microdroid.os { os } else { "microdroid" };
Inseob Kim89b24592024-02-23 18:59:43 +0900148
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900149 let payload_config_str = format!("{:?}!{:?}", config.apk, payload);
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900150
Nikita Ioffeb4268b32024-09-03 10:23:14 +0000151 let mut custom_config = CustomConfig {
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900152 gdbPort: config.debug.gdb.map(u16::from).unwrap_or(0) as i32, // 0 means no gdb
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100153 vendorImage: vendor,
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900154 devices: config
155 .microdroid
Nikita Ioffe94a8a182023-11-16 16:37:48 +0000156 .devices()
Inseob Kim6ef80972023-07-20 17:23:36 +0900157 .iter()
158 .map(|x| {
159 x.to_str().map(String::from).ok_or(anyhow!("Failed to convert {x:?} to String"))
160 })
161 .collect::<Result<_, _>>()?,
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900162 networkSupported: config.common.network_supported(),
Nikita Ioffe69521872024-10-22 14:46:07 +0000163 teeServices: config.common.tee_services().to_vec(),
Alan Stokesc96b35e2024-05-03 13:21:20 +0100164 ..Default::default()
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100165 };
166
Elie Kheirallahb4b2f242025-01-23 03:38:07 +0000167 let cpu_options = CpuOptions { cpuTopology: config.common.cpu_topology };
Nikita Ioffeb4268b32024-09-03 10:23:14 +0000168 if config.debug.enable_earlycon() {
169 if config.debug.debug != DebugLevel::FULL {
170 bail!("earlycon is only supported for debuggable VMs")
171 }
172 if cfg!(target_arch = "aarch64") {
173 custom_config
174 .extraKernelCmdlineParams
175 .push(String::from("earlycon=uart8250,mmio,0x3f8"));
176 } else if cfg!(target_arch = "x86_64") {
177 custom_config.extraKernelCmdlineParams.push(String::from("earlycon=uart8250,io,0x3f8"));
178 } else {
179 bail!("unexpected architecture!");
180 }
Nikita Ioffe37146742024-11-27 13:45:54 +0000181 custom_config.extraKernelCmdlineParams.push(String::from("keep_bootcon"));
Nikita Ioffeb4268b32024-09-03 10:23:14 +0000182 }
183
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900184 let vm_config = VirtualMachineConfig::AppConfig(VirtualMachineAppConfig {
185 name: config.common.name.unwrap_or_else(|| String::from("VmRunApp")),
Jiyong Park0a248432021-08-20 23:32:39 +0900186 apk: apk_fd.into(),
187 idsig: idsig_fd.into(),
Inseob Kima5a262f2021-11-17 19:41:03 +0900188 extraIdsigs: extra_idsig_fds,
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900189 instanceImage: open_parcel_file(&config.instance, true /* writable */)?.into(),
Shikha Panwar61a74b52024-02-16 13:17:01 +0000190 instanceId: instance_id,
Shikha Panwar22e70452022-10-10 18:32:55 +0000191 encryptedStorageImage: storage,
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900192 payload,
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900193 debugLevel: config.debug.debug,
194 protectedVm: config.common.protected,
195 memoryMib: config.common.mem.unwrap_or(0) as i32, // 0 means use the VM default
Elie Kheirallahb4b2f242025-01-23 03:38:07 +0000196 cpuOptions: cpu_options,
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100197 customConfig: Some(custom_config),
Nikita Ioffe43c93622024-10-30 20:33:58 +0000198 osName: os_name.to_string(),
Vincent Donnefort538a2c62024-03-20 16:01:10 +0000199 hugePages: config.common.hugepages,
David Dai23cff712024-06-13 19:23:45 +0000200 boostUclamp: config.common.boost_uclamp,
Jooyung Han21e9b922021-06-26 04:14:16 +0900201 });
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900202 run(
203 service.as_ref(),
204 &vm_config,
205 &payload_config_str,
206 config.debug.console.as_ref().map(|p| p.as_ref()),
207 config.debug.console_in.as_ref().map(|p| p.as_ref()),
208 config.debug.log.as_ref().map(|p| p.as_ref()),
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000209 config.debug.dump_device_tree.as_ref().map(|p| p.as_ref()),
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900210 )
Jooyung Han21e9b922021-06-26 04:14:16 +0900211}
212
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000213fn find_empty_payload_apk_path() -> Result<PathBuf, Error> {
Cole Faust237ee3e2023-03-01 11:58:01 -0800214 const GLOB_PATTERN: &str = "/apex/com.android.virt/app/**/EmptyPayloadApp*.apk";
Nikita Ioffefc041962023-01-18 00:10:40 +0000215 let mut entries: Vec<PathBuf> =
216 glob(GLOB_PATTERN).context("failed to glob")?.filter_map(|e| e.ok()).collect();
217 if entries.len() > 1 {
218 return Err(anyhow!("Found more than one apk matching {}", GLOB_PATTERN));
219 }
220 match entries.pop() {
221 Some(path) => Ok(path),
222 None => Err(anyhow!("No apks match {}", GLOB_PATTERN)),
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000223 }
224}
225
226fn create_work_dir() -> Result<PathBuf, Error> {
227 let s: String =
228 rand::thread_rng().sample_iter(&Alphanumeric).take(17).map(char::from).collect();
229 let work_dir = PathBuf::from("/data/local/tmp/microdroid").join(s);
230 println!("creating work dir {}", work_dir.display());
231 fs::create_dir_all(&work_dir).context("failed to mkdir")?;
232 Ok(work_dir)
233}
234
235/// Run a VM with Microdroid
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900236pub fn command_run_microdroid(config: RunMicrodroidConfig) -> Result<(), Error> {
Nikita Ioffefc041962023-01-18 00:10:40 +0000237 let apk = find_empty_payload_apk_path()?;
238 println!("found path {}", apk.display());
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000239
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900240 let work_dir = config.work_dir.unwrap_or(create_work_dir()?);
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000241 let idsig = work_dir.join("apk.idsig");
242 println!("apk.idsig path: {}", idsig.display());
243 let instance_img = work_dir.join("instance.img");
244 println!("instance.img path: {}", instance_img.display());
245
Shikha Panwar61a74b52024-02-16 13:17:01 +0000246 let mut app_config = RunAppConfig {
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900247 common: config.common,
248 debug: config.debug,
249 microdroid: config.microdroid,
250 apk,
251 idsig,
252 instance: instance_img,
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900253 payload_binary_name: Some("MicrodroidEmptyPayloadJniLib.so".to_owned()),
Alan Stokesfda70842023-12-20 17:50:14 +0000254 ..Default::default()
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900255 };
Shikha Panwar61a74b52024-02-16 13:17:01 +0000256
257 if cfg!(llpvm_changes) {
258 app_config.set_instance_id(work_dir.join("instance_id"))?;
259 println!("instance_id file path: {}", app_config.instance_id()?.display());
260 }
261
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900262 command_run_app(app_config)
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000263}
264
Andrew Walbranf395b822021-05-05 10:38:59 +0000265/// Run a VM from the given configuration file.
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900266pub fn command_run(config: RunCustomVmConfig) -> Result<(), Error> {
267 let config_file = File::open(&config.config).context("Failed to open config file")?;
268 let mut vm_config =
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000269 VmConfig::load(&config_file).context("Failed to parse config file")?.to_parcelable()?;
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900270 if let Some(mem) = config.common.mem {
271 vm_config.memoryMib = mem as i32;
Jiyong Parkd63cfff2021-09-27 20:10:17 +0900272 }
Nikita Ioffe69521872024-10-22 14:46:07 +0000273 if let Some(ref name) = config.common.name {
274 vm_config.name = name.to_string();
Seungjae Yoo62085c02022-08-12 04:44:52 +0000275 } else {
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900276 vm_config.name = String::from("VmRun");
Seungjae Yoo62085c02022-08-12 04:44:52 +0000277 }
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900278 if let Some(gdb) = config.debug.gdb {
279 vm_config.gdbPort = gdb.get() as i32;
Nikita Ioffe5776f082023-02-10 21:38:26 +0000280 }
Elie Kheirallahb4b2f242025-01-23 03:38:07 +0000281 vm_config.cpuOptions = CpuOptions { cpuTopology: config.common.cpu_topology.clone() };
Vincent Donnefort538a2c62024-03-20 16:01:10 +0000282 vm_config.hugePages = config.common.hugepages;
David Dai23cff712024-06-13 19:23:45 +0000283 vm_config.boostUclamp = config.common.boost_uclamp;
Nikita Ioffe69521872024-10-22 14:46:07 +0000284 vm_config.teeServices = config.common.tee_services().to_vec();
Jooyung Han21e9b922021-06-26 04:14:16 +0900285 run(
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900286 get_service()?.as_ref(),
287 &VirtualMachineConfig::RawConfig(vm_config),
288 &format!("{:?}", &config.config),
289 config.debug.console.as_ref().map(|p| p.as_ref()),
290 config.debug.console_in.as_ref().map(|p| p.as_ref()),
291 config.debug.log.as_ref().map(|p| p.as_ref()),
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000292 config.debug.dump_device_tree.as_ref().map(|p| p.as_ref()),
Jooyung Han21e9b922021-06-26 04:14:16 +0900293 )
294}
295
Andrew Walbranf8d94112021-09-07 11:45:36 +0000296fn state_to_str(vm_state: VirtualMachineState) -> &'static str {
297 match vm_state {
298 VirtualMachineState::NOT_STARTED => "NOT_STARTED",
299 VirtualMachineState::STARTING => "STARTING",
300 VirtualMachineState::STARTED => "STARTED",
301 VirtualMachineState::READY => "READY",
302 VirtualMachineState::FINISHED => "FINISHED",
303 VirtualMachineState::DEAD => "DEAD",
304 _ => "(invalid state)",
305 }
306}
307
Jooyung Han21e9b922021-06-26 04:14:16 +0900308fn run(
Andrew Walbran616d13f2022-05-12 18:35:55 +0000309 service: &dyn IVirtualizationService,
Jooyung Han21e9b922021-06-26 04:14:16 +0900310 config: &VirtualMachineConfig,
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900311 payload_config: &str,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900312 console_out_path: Option<&Path>,
313 console_in_path: Option<&Path>,
Jooyung Han21e9b922021-06-26 04:14:16 +0900314 log_path: Option<&Path>,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000315 dump_device_tree: Option<&Path>,
Jooyung Han21e9b922021-06-26 04:14:16 +0900316) -> 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 {
Inseob Kim6132d812024-01-03 15:47:42 +0900326 Some(File::open(console_in_path).with_context(|| {
Jiyong Parke6fb1672023-06-26 16:45:55 +0900327 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 };
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000340 let dump_dt = if let Some(dump_device_tree) = dump_device_tree {
341 Some(File::create(dump_device_tree).with_context(|| {
342 format!("Failed to open file to dump device tree: {:?}", dump_device_tree)
343 })?)
344 } else {
345 None
346 };
Jaewan Kimfcf98b22025-01-21 23:14:49 -0800347 let vm = VmInstance::create(service, config, console_out, console_in, log, dump_dt)
348 .context("Failed to create VM")?;
Alan Stokes0e82b502022-08-08 14:44:48 +0100349 let callback = Box::new(Callback {});
Jaewan Kimfcf98b22025-01-21 23:14:49 -0800350 vm.start(Some(callback)).context("Failed to start VM")?;
Andrew Walbranf395b822021-05-05 10:38:59 +0000351
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +0100352 let debug_level = get_debug_level(config).unwrap_or(DebugLevel::NONE);
353
Andrew Walbranf8d94112021-09-07 11:45:36 +0000354 println!(
Pierre-Clément Tosi1b691cc2023-06-28 11:40:29 +0000355 "Created {} from {} with CID {}, state is {}.",
356 if debug_level == DebugLevel::FULL { "debuggable VM" } else { "VM" },
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900357 payload_config,
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000358 vm.cid(),
359 state_to_str(vm.state()?)
Andrew Walbranf8d94112021-09-07 11:45:36 +0000360 );
Andrew Walbranf395b822021-05-05 10:38:59 +0000361
David Brazdil2b6352f2023-01-12 11:01:17 +0000362 // Wait until the VM or VirtualizationService dies. If we just returned immediately then the
363 // IVirtualMachine Binder object would be dropped and the VM would be killed.
364 let death_reason = vm.wait_for_death();
365 println!("VM ended: {:?}", death_reason);
Andrew Walbranf395b822021-05-05 10:38:59 +0000366 Ok(())
367}
368
Alan Stokesfda70842023-12-20 17:50:14 +0000369fn parse_extra_apk_list(apk: &Path, config_path: &str) -> Result<Vec<PathBuf>, Error> {
Inseob Kima5a262f2021-11-17 19:41:03 +0900370 let mut archive = ZipArchive::new(File::open(apk)?)?;
371 let config_file = archive.by_name(config_path)?;
372 let config: VmPayloadConfig = serde_json::from_reader(config_file)?;
Alan Stokesfda70842023-12-20 17:50:14 +0000373 Ok(config.extra_apks.into_iter().map(|x| x.path.into()).collect())
Inseob Kima5a262f2021-11-17 19:41:03 +0900374}
375
Shraddha Basantwania9a9c4f2025-02-25 09:51:48 -0800376fn set_encrypted_storage(
377 service: &dyn IVirtualizationService,
378 image_path: &Path,
379 size: u64,
380) -> Result<(), Error> {
381 let image = OpenOptions::new()
382 .create_new(false)
383 .read(true)
384 .write(true)
385 .open(image_path)
386 .with_context(|| format!("Failed to open {:?}", image_path))?;
387
388 service.setEncryptedStorageSize(&ParcelFileDescriptor::new(image), size.try_into()?)?;
389 Ok(())
390}
391
Alan Stokes0e82b502022-08-08 14:44:48 +0100392struct Callback {}
Andrew Walbranf395b822021-05-05 10:38:59 +0000393
Alan Stokes0e82b502022-08-08 14:44:48 +0100394impl vmclient::VmCallback for Callback {
David Brazdil451cc962022-10-14 14:08:12 +0100395 fn on_payload_started(&self, _cid: i32) {
396 eprintln!("payload started");
397 }
398
Alan Stokes0e82b502022-08-08 14:44:48 +0100399 fn on_payload_ready(&self, _cid: i32) {
Inseob Kim8dbc3222021-09-01 21:50:23 +0900400 eprintln!("payload is ready");
Inseob Kim14cb8692021-08-31 21:50:39 +0900401 }
402
Alan Stokes0e82b502022-08-08 14:44:48 +0100403 fn on_payload_finished(&self, _cid: i32, exit_code: i32) {
Inseob Kim8dbc3222021-09-01 21:50:23 +0900404 eprintln!("payload finished with exit code {}", exit_code);
Inseob Kim2444af92021-08-31 01:22:50 +0900405 }
406
Alan Stokes2bead0d2022-09-05 16:58:34 +0100407 fn on_error(&self, _cid: i32, error_code: ErrorCode, message: &str) {
408 eprintln!("VM encountered an error: code={:?}, message={}", error_code, message);
Andrew Walbranf395b822021-05-05 10:38:59 +0000409 }
410}
411
Jiyong Parke6fb1672023-06-26 16:45:55 +0900412/// Safely duplicate the file descriptor.
Jiyong Park8ee38312024-08-20 18:00:29 +0900413fn duplicate_fd<T: AsFd>(file: T) -> io::Result<File> {
414 Ok(file.as_fd().try_clone_to_owned()?.into())
Andrew Walbranf395b822021-05-05 10:38:59 +0000415}