blob: 27fd903f567c636c14cd649d93b85a39c876f8e7 [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,
22 VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
23 VirtualMachineConfig::VirtualMachineConfig,
Inseob Kim7b5f65c2022-11-15 14:27:04 +090024 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Andrew Walbranf8d94112021-09-07 11:45:36 +000025 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090026};
Nikita Ioffeb0b67562022-11-22 15:48:06 +000027use anyhow::{anyhow, bail, Context, Error};
Alan Stokes0e82b502022-08-08 14:44:48 +010028use binder::ParcelFileDescriptor;
Nikita Ioffefc041962023-01-18 00:10:40 +000029use glob::glob;
Inseob Kima5a262f2021-11-17 19:41:03 +090030use microdroid_payload_config::VmPayloadConfig;
Nikita Ioffeb0b67562022-11-22 15:48:06 +000031use rand::{distributions::Alphanumeric, Rng};
32use std::fs;
Andrew Walbranf395b822021-05-05 10:38:59 +000033use std::fs::File;
Alan Stokesf30982b2022-11-18 11:50:32 +000034use std::io;
Nikita Ioffe5776f082023-02-10 21:38:26 +000035use std::num::NonZeroU16;
Andrew Walbranf395b822021-05-05 10:38:59 +000036use std::os::unix::io::{AsRawFd, FromRawFd};
Inseob Kima5a262f2021-11-17 19:41:03 +090037use std::path::{Path, PathBuf};
Alan Stokes2bead0d2022-09-05 16:58:34 +010038use vmclient::{ErrorCode, VmInstance};
Jiyong Park48b354d2021-07-15 15:04:38 +090039use vmconfig::{open_parcel_file, VmConfig};
Inseob Kima5a262f2021-11-17 19:41:03 +090040use zip::ZipArchive;
Andrew Walbranf395b822021-05-05 10:38:59 +000041
Jooyung Han21e9b922021-06-26 04:14:16 +090042/// Run a VM from the given APK, idsig, and config.
Jiyong Park48b354d2021-07-15 15:04:38 +090043#[allow(clippy::too_many_arguments)]
Jooyung Han21e9b922021-06-26 04:14:16 +090044pub fn command_run_app(
Seungjae Yoo62085c02022-08-12 04:44:52 +000045 name: Option<String>,
Andrew Walbran616d13f2022-05-12 18:35:55 +000046 service: &dyn IVirtualizationService,
Jooyung Han21e9b922021-06-26 04:14:16 +090047 apk: &Path,
48 idsig: &Path,
Jiyong Park48b354d2021-07-15 15:04:38 +090049 instance: &Path,
Shikha Panwar22e70452022-10-10 18:32:55 +000050 storage: Option<&Path>,
51 storage_size: Option<u64>,
Inseob Kim7b5f65c2022-11-15 14:27:04 +090052 config_path: Option<String>,
Alan Stokes8f12f2b2023-01-09 09:19:20 +000053 payload_binary_name: Option<String>,
Jiyong Parke6fb1672023-06-26 16:45:55 +090054 console_out_path: Option<&Path>,
55 console_in_path: Option<&Path>,
Jooyung Han21e9b922021-06-26 04:14:16 +090056 log_path: Option<&Path>,
Jiyong Parkc2a49cc2021-10-15 00:02:12 +090057 debug_level: DebugLevel,
Andrew Walbran3994f002022-01-27 17:33:45 +000058 protected: bool,
Jiyong Parkd63cfff2021-09-27 20:10:17 +090059 mem: Option<u32>,
David Brazdil7d1e5ec2023-02-06 17:56:29 +000060 cpu_topology: CpuTopology,
Jiyong Parkdfe16d62022-04-20 17:32:12 +090061 task_profiles: Vec<String>,
Inseob Kima5a262f2021-11-17 19:41:03 +090062 extra_idsigs: &[PathBuf],
Nikita Ioffe5776f082023-02-10 21:38:26 +000063 gdb: Option<NonZeroU16>,
Nikita Ioffe26c35ed2023-06-05 17:49:08 +010064 kernel: Option<&Path>,
Jooyung Han21e9b922021-06-26 04:14:16 +090065) -> Result<(), Error> {
Steven Moreland6a55e2e2022-10-22 00:30:42 +000066 let apk_file = File::open(apk).context("Failed to open APK file")?;
67
Inseob Kim7b5f65c2022-11-15 14:27:04 +090068 let extra_apks = match config_path.as_deref() {
69 Some(path) => parse_extra_apk_list(apk, path)?,
70 None => vec![],
71 };
72
Inseob Kima5a262f2021-11-17 19:41:03 +090073 if extra_apks.len() != extra_idsigs.len() {
74 bail!(
75 "Found {} extra apks, but there are {} extra idsigs",
76 extra_apks.len(),
77 extra_idsigs.len()
78 )
79 }
80
81 for i in 0..extra_apks.len() {
82 let extra_apk_fd = ParcelFileDescriptor::new(File::open(&extra_apks[i])?);
83 let extra_idsig_fd = ParcelFileDescriptor::new(File::create(&extra_idsigs[i])?);
84 service.createOrUpdateIdsigFile(&extra_apk_fd, &extra_idsig_fd)?;
85 }
86
Jiyong Park0a248432021-08-20 23:32:39 +090087 let idsig_file = File::create(idsig).context("Failed to create idsig file")?;
88
89 let apk_fd = ParcelFileDescriptor::new(apk_file);
90 let idsig_fd = ParcelFileDescriptor::new(idsig_file);
91 service.createOrUpdateIdsigFile(&apk_fd, &idsig_fd)?;
92
Jooyung Han21e9b922021-06-26 04:14:16 +090093 let idsig_file = File::open(idsig).context("Failed to open idsig file")?;
Jiyong Park0a248432021-08-20 23:32:39 +090094 let idsig_fd = ParcelFileDescriptor::new(idsig_file);
Jiyong Park48b354d2021-07-15 15:04:38 +090095
96 if !instance.exists() {
97 const INSTANCE_FILE_SIZE: u64 = 10 * 1024 * 1024;
Jiyong Park9dd389e2021-08-23 20:42:59 +090098 command_create_partition(
Andrew Walbran616d13f2022-05-12 18:35:55 +000099 service,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900100 instance,
101 INSTANCE_FILE_SIZE,
102 PartitionType::ANDROID_VM_INSTANCE,
103 )?;
Jiyong Park48b354d2021-07-15 15:04:38 +0900104 }
105
Shikha Panwar22e70452022-10-10 18:32:55 +0000106 let storage = if let Some(path) = storage {
107 if !path.exists() {
108 command_create_partition(
109 service,
110 path,
111 storage_size.unwrap_or(10 * 1024 * 1024),
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000112 PartitionType::ENCRYPTEDSTORE,
Shikha Panwar22e70452022-10-10 18:32:55 +0000113 )?;
114 }
115 Some(open_parcel_file(path, true)?)
116 } else {
117 None
118 };
119
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100120 let kernel = kernel.map(|p| open_parcel_file(p, false)).transpose()?;
121
Inseob Kima5a262f2021-11-17 19:41:03 +0900122 let extra_idsig_files: Result<Vec<File>, _> = extra_idsigs.iter().map(File::open).collect();
123 let extra_idsig_fds = extra_idsig_files?.into_iter().map(ParcelFileDescriptor::new).collect();
124
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900125 let payload = if let Some(config_path) = config_path {
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000126 if payload_binary_name.is_some() {
127 bail!("Only one of --config-path or --payload-binary-name can be defined")
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900128 }
129 Payload::ConfigPath(config_path)
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000130 } else if let Some(payload_binary_name) = payload_binary_name {
131 Payload::PayloadConfig(VirtualMachinePayloadConfig {
132 payloadBinaryName: payload_binary_name,
133 })
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900134 } else {
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000135 bail!("Either --config-path or --payload-binary-name must be defined")
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900136 };
137
138 let payload_config_str = format!("{:?}!{:?}", apk, payload);
139
Jooyung Han21e9b922021-06-26 04:14:16 +0900140 let config = VirtualMachineConfig::AppConfig(VirtualMachineAppConfig {
Seungjae Yoo62085c02022-08-12 04:44:52 +0000141 name: name.unwrap_or_else(|| String::from("VmRunApp")),
Jiyong Park0a248432021-08-20 23:32:39 +0900142 apk: apk_fd.into(),
143 idsig: idsig_fd.into(),
Inseob Kima5a262f2021-11-17 19:41:03 +0900144 extraIdsigs: extra_idsig_fds,
Jiyong Park48b354d2021-07-15 15:04:38 +0900145 instanceImage: open_parcel_file(instance, true /* writable */)?.into(),
Shikha Panwar22e70452022-10-10 18:32:55 +0000146 encryptedStorageImage: storage,
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900147 payload,
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900148 debugLevel: debug_level,
Andrew Walbran3994f002022-01-27 17:33:45 +0000149 protectedVm: protected,
Jiyong Parkd63cfff2021-09-27 20:10:17 +0900150 memoryMib: mem.unwrap_or(0) as i32, // 0 means use the VM default
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000151 cpuTopology: cpu_topology,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900152 taskProfiles: task_profiles,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000153 gdbPort: gdb.map(u16::from).unwrap_or(0) as i32, // 0 means no gdb
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100154 customKernelImage: kernel,
Jooyung Han21e9b922021-06-26 04:14:16 +0900155 });
Jiyong Parke6fb1672023-06-26 16:45:55 +0900156 run(service, &config, &payload_config_str, console_out_path, console_in_path, log_path)
Jooyung Han21e9b922021-06-26 04:14:16 +0900157}
158
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000159fn find_empty_payload_apk_path() -> Result<PathBuf, Error> {
Cole Faust237ee3e2023-03-01 11:58:01 -0800160 const GLOB_PATTERN: &str = "/apex/com.android.virt/app/**/EmptyPayloadApp*.apk";
Nikita Ioffefc041962023-01-18 00:10:40 +0000161 let mut entries: Vec<PathBuf> =
162 glob(GLOB_PATTERN).context("failed to glob")?.filter_map(|e| e.ok()).collect();
163 if entries.len() > 1 {
164 return Err(anyhow!("Found more than one apk matching {}", GLOB_PATTERN));
165 }
166 match entries.pop() {
167 Some(path) => Ok(path),
168 None => Err(anyhow!("No apks match {}", GLOB_PATTERN)),
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000169 }
170}
171
172fn create_work_dir() -> Result<PathBuf, Error> {
173 let s: String =
174 rand::thread_rng().sample_iter(&Alphanumeric).take(17).map(char::from).collect();
175 let work_dir = PathBuf::from("/data/local/tmp/microdroid").join(s);
176 println!("creating work dir {}", work_dir.display());
177 fs::create_dir_all(&work_dir).context("failed to mkdir")?;
178 Ok(work_dir)
179}
180
181/// Run a VM with Microdroid
182#[allow(clippy::too_many_arguments)]
183pub fn command_run_microdroid(
184 name: Option<String>,
185 service: &dyn IVirtualizationService,
186 work_dir: Option<PathBuf>,
187 storage: Option<&Path>,
188 storage_size: Option<u64>,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900189 console_out_path: Option<&Path>,
190 console_in_path: Option<&Path>,
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000191 log_path: Option<&Path>,
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000192 debug_level: DebugLevel,
193 protected: bool,
194 mem: Option<u32>,
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000195 cpu_topology: CpuTopology,
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000196 task_profiles: Vec<String>,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000197 gdb: Option<NonZeroU16>,
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100198 kernel: Option<&Path>,
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000199) -> Result<(), Error> {
Nikita Ioffefc041962023-01-18 00:10:40 +0000200 let apk = find_empty_payload_apk_path()?;
201 println!("found path {}", apk.display());
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000202
203 let work_dir = work_dir.unwrap_or(create_work_dir()?);
204 let idsig = work_dir.join("apk.idsig");
205 println!("apk.idsig path: {}", idsig.display());
206 let instance_img = work_dir.join("instance.img");
207 println!("instance.img path: {}", instance_img.display());
208
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000209 let payload_binary_name = "MicrodroidEmptyPayloadJniLib.so";
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000210 let extra_sig = [];
211 command_run_app(
212 name,
213 service,
214 &apk,
215 &idsig,
216 &instance_img,
217 storage,
218 storage_size,
219 /* config_path= */ None,
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000220 Some(payload_binary_name.to_owned()),
Jiyong Parke6fb1672023-06-26 16:45:55 +0900221 console_out_path,
222 console_in_path,
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000223 log_path,
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000224 debug_level,
225 protected,
226 mem,
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000227 cpu_topology,
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000228 task_profiles,
229 &extra_sig,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000230 gdb,
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100231 kernel,
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000232 )
233}
234
Andrew Walbranf395b822021-05-05 10:38:59 +0000235/// Run a VM from the given configuration file.
Jooyung Hanb7983a22022-02-22 05:21:27 +0900236#[allow(clippy::too_many_arguments)]
Andrew Walbranf395b822021-05-05 10:38:59 +0000237pub fn command_run(
Seungjae Yoo62085c02022-08-12 04:44:52 +0000238 name: Option<String>,
Andrew Walbran616d13f2022-05-12 18:35:55 +0000239 service: &dyn IVirtualizationService,
Andrew Walbranf395b822021-05-05 10:38:59 +0000240 config_path: &Path,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900241 console_out_path: Option<&Path>,
242 console_in_path: Option<&Path>,
Jooyung Hanb7983a22022-02-22 05:21:27 +0900243 log_path: Option<&Path>,
Jiyong Parkd63cfff2021-09-27 20:10:17 +0900244 mem: Option<u32>,
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000245 cpu_topology: CpuTopology,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900246 task_profiles: Vec<String>,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000247 gdb: Option<NonZeroU16>,
Andrew Walbranf395b822021-05-05 10:38:59 +0000248) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000249 let config_file = File::open(config_path).context("Failed to open config file")?;
Jiyong Parkd63cfff2021-09-27 20:10:17 +0900250 let mut config =
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000251 VmConfig::load(&config_file).context("Failed to parse config file")?.to_parcelable()?;
Jiyong Parkd63cfff2021-09-27 20:10:17 +0900252 if let Some(mem) = mem {
253 config.memoryMib = mem as i32;
254 }
Seungjae Yoo62085c02022-08-12 04:44:52 +0000255 if let Some(name) = name {
256 config.name = name;
257 } else {
258 config.name = String::from("VmRun");
259 }
Nikita Ioffe5776f082023-02-10 21:38:26 +0000260 if let Some(gdb) = gdb {
261 config.gdbPort = gdb.get() as i32;
262 }
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000263 config.cpuTopology = cpu_topology;
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900264 config.taskProfiles = task_profiles;
Jooyung Han21e9b922021-06-26 04:14:16 +0900265 run(
266 service,
267 &VirtualMachineConfig::RawConfig(config),
268 &format!("{:?}", config_path),
Jiyong Parke6fb1672023-06-26 16:45:55 +0900269 console_out_path,
270 console_in_path,
Jooyung Hanb7983a22022-02-22 05:21:27 +0900271 log_path,
Jooyung Han21e9b922021-06-26 04:14:16 +0900272 )
273}
274
Andrew Walbranf8d94112021-09-07 11:45:36 +0000275fn state_to_str(vm_state: VirtualMachineState) -> &'static str {
276 match vm_state {
277 VirtualMachineState::NOT_STARTED => "NOT_STARTED",
278 VirtualMachineState::STARTING => "STARTING",
279 VirtualMachineState::STARTED => "STARTED",
280 VirtualMachineState::READY => "READY",
281 VirtualMachineState::FINISHED => "FINISHED",
282 VirtualMachineState::DEAD => "DEAD",
283 _ => "(invalid state)",
284 }
285}
286
Jooyung Han21e9b922021-06-26 04:14:16 +0900287fn run(
Andrew Walbran616d13f2022-05-12 18:35:55 +0000288 service: &dyn IVirtualizationService,
Jooyung Han21e9b922021-06-26 04:14:16 +0900289 config: &VirtualMachineConfig,
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900290 payload_config: &str,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900291 console_out_path: Option<&Path>,
292 console_in_path: Option<&Path>,
Jooyung Han21e9b922021-06-26 04:14:16 +0900293 log_path: Option<&Path>,
294) -> Result<(), Error> {
Jiyong Parke6fb1672023-06-26 16:45:55 +0900295 let console_out = if let Some(console_out_path) = console_out_path {
296 Some(File::create(console_out_path).with_context(|| {
297 format!("Failed to open console output file {:?}", console_out_path)
298 })?)
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900299 } else {
Jiyong Parke6fb1672023-06-26 16:45:55 +0900300 Some(duplicate_fd(io::stdout())?)
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900301 };
Jiyong Parke6fb1672023-06-26 16:45:55 +0900302 let console_in =
303 if let Some(console_in_path) = console_in_path {
304 Some(File::create(console_in_path).with_context(|| {
305 format!("Failed to open console input file {:?}", console_in_path)
306 })?)
307 } else {
308 Some(duplicate_fd(io::stdin())?)
309 };
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900310 let log = if let Some(log_path) = log_path {
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000311 Some(
Andrew Walbranbe429242021-06-28 12:22:54 +0000312 File::create(log_path)
313 .with_context(|| format!("Failed to open log file {:?}", log_path))?,
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000314 )
Andrew Walbranbe429242021-06-28 12:22:54 +0000315 } else {
Jiyong Parke6fb1672023-06-26 16:45:55 +0900316 Some(duplicate_fd(io::stdout())?)
Andrew Walbranbe429242021-06-28 12:22:54 +0000317 };
Alan Stokes0e82b502022-08-08 14:44:48 +0100318 let callback = Box::new(Callback {});
Jiyong Parke6fb1672023-06-26 16:45:55 +0900319 let vm = VmInstance::create(service, config, console_out, console_in, log, Some(callback))
Alan Stokes0e82b502022-08-08 14:44:48 +0100320 .context("Failed to create VM")?;
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000321 vm.start().context("Failed to start VM")?;
Andrew Walbranf395b822021-05-05 10:38:59 +0000322
Andrew Walbranf8d94112021-09-07 11:45:36 +0000323 println!(
324 "Created VM from {} with CID {}, state is {}.",
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900325 payload_config,
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000326 vm.cid(),
327 state_to_str(vm.state()?)
Andrew Walbranf8d94112021-09-07 11:45:36 +0000328 );
Andrew Walbranf395b822021-05-05 10:38:59 +0000329
David Brazdil2b6352f2023-01-12 11:01:17 +0000330 // Wait until the VM or VirtualizationService dies. If we just returned immediately then the
331 // IVirtualMachine Binder object would be dropped and the VM would be killed.
332 let death_reason = vm.wait_for_death();
333 println!("VM ended: {:?}", death_reason);
Andrew Walbranf395b822021-05-05 10:38:59 +0000334 Ok(())
335}
336
Inseob Kima5a262f2021-11-17 19:41:03 +0900337fn parse_extra_apk_list(apk: &Path, config_path: &str) -> Result<Vec<String>, Error> {
338 let mut archive = ZipArchive::new(File::open(apk)?)?;
339 let config_file = archive.by_name(config_path)?;
340 let config: VmPayloadConfig = serde_json::from_reader(config_file)?;
341 Ok(config.extra_apks.into_iter().map(|x| x.path).collect())
342}
343
Alan Stokes0e82b502022-08-08 14:44:48 +0100344struct Callback {}
Andrew Walbranf395b822021-05-05 10:38:59 +0000345
Alan Stokes0e82b502022-08-08 14:44:48 +0100346impl vmclient::VmCallback for Callback {
David Brazdil451cc962022-10-14 14:08:12 +0100347 fn on_payload_started(&self, _cid: i32) {
348 eprintln!("payload started");
349 }
350
Alan Stokes0e82b502022-08-08 14:44:48 +0100351 fn on_payload_ready(&self, _cid: i32) {
Inseob Kim8dbc3222021-09-01 21:50:23 +0900352 eprintln!("payload is ready");
Inseob Kim14cb8692021-08-31 21:50:39 +0900353 }
354
Alan Stokes0e82b502022-08-08 14:44:48 +0100355 fn on_payload_finished(&self, _cid: i32, exit_code: i32) {
Inseob Kim8dbc3222021-09-01 21:50:23 +0900356 eprintln!("payload finished with exit code {}", exit_code);
Inseob Kim2444af92021-08-31 01:22:50 +0900357 }
358
Alan Stokes2bead0d2022-09-05 16:58:34 +0100359 fn on_error(&self, _cid: i32, error_code: ErrorCode, message: &str) {
360 eprintln!("VM encountered an error: code={:?}, message={}", error_code, message);
Andrew Walbranf395b822021-05-05 10:38:59 +0000361 }
362}
363
Jiyong Parke6fb1672023-06-26 16:45:55 +0900364/// Safely duplicate the file descriptor.
365fn duplicate_fd<T: AsRawFd>(file: T) -> io::Result<File> {
366 let fd = file.as_raw_fd();
Andrew Walbranf395b822021-05-05 10:38:59 +0000367 // Safe because this just duplicates a file descriptor which we know to be valid, and we check
368 // for an error.
Jiyong Parke6fb1672023-06-26 16:45:55 +0900369 let dup_fd = unsafe { libc::dup(fd) };
Andrew Walbranf395b822021-05-05 10:38:59 +0000370 if dup_fd < 0 {
371 Err(io::Error::last_os_error())
372 } else {
373 // Safe because we have just duplicated the file descriptor so we own it, and `from_raw_fd`
374 // takes ownership of it.
375 Ok(unsafe { File::from_raw_fd(dup_fd) })
376 }
377}