blob: fc8d7e0afcda597d21f8c5d173b2f16a37272b9a [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::{
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;
Andrew Walbranf395b822021-05-05 10:38:59 +000038use std::os::unix::io::{AsRawFd, FromRawFd};
Inseob Kima5a262f2021-11-17 19:41:03 +090039use std::path::{Path, PathBuf};
Alan Stokes2bead0d2022-09-05 16:58:34 +010040use vmclient::{ErrorCode, VmInstance};
Jiyong Park48b354d2021-07-15 15:04:38 +090041use vmconfig::{open_parcel_file, VmConfig};
Inseob Kima5a262f2021-11-17 19:41:03 +090042use zip::ZipArchive;
Andrew Walbranf395b822021-05-05 10:38:59 +000043
Jooyung Han21e9b922021-06-26 04:14:16 +090044/// Run a VM from the given APK, idsig, and config.
Jiyong Parkb1935ef2023-08-10 17:22:39 +090045pub fn command_run_app(config: RunAppConfig) -> Result<(), Error> {
46 let service = get_service()?;
47 let apk = File::open(&config.apk).context("Failed to open APK file")?;
Steven Moreland6a55e2e2022-10-22 00:30:42 +000048
Jiyong Parkb1935ef2023-08-10 17:22:39 +090049 let extra_apks = match config.config_path.as_deref() {
50 Some(path) => parse_extra_apk_list(&config.apk, path)?,
Inseob Kim7b5f65c2022-11-15 14:27:04 +090051 None => vec![],
52 };
53
Jiyong Parkb1935ef2023-08-10 17:22:39 +090054 if extra_apks.len() != config.extra_idsigs.len() {
Inseob Kima5a262f2021-11-17 19:41:03 +090055 bail!(
56 "Found {} extra apks, but there are {} extra idsigs",
57 extra_apks.len(),
Jiyong Parkb1935ef2023-08-10 17:22:39 +090058 config.extra_idsigs.len()
Inseob Kima5a262f2021-11-17 19:41:03 +090059 )
60 }
61
Jiyong Parkb1935ef2023-08-10 17:22:39 +090062 for (i, extra_apk) in extra_apks.iter().enumerate() {
63 let extra_apk_fd = ParcelFileDescriptor::new(File::open(extra_apk)?);
64 let extra_idsig_fd = ParcelFileDescriptor::new(File::create(&config.extra_idsigs[i])?);
Inseob Kima5a262f2021-11-17 19:41:03 +090065 service.createOrUpdateIdsigFile(&extra_apk_fd, &extra_idsig_fd)?;
66 }
67
Jiyong Parkb1935ef2023-08-10 17:22:39 +090068 let idsig = File::create(&config.idsig).context("Failed to create idsig file")?;
Jiyong Park0a248432021-08-20 23:32:39 +090069
Jiyong Parkb1935ef2023-08-10 17:22:39 +090070 let apk_fd = ParcelFileDescriptor::new(apk);
71 let idsig_fd = ParcelFileDescriptor::new(idsig);
Jiyong Park0a248432021-08-20 23:32:39 +090072 service.createOrUpdateIdsigFile(&apk_fd, &idsig_fd)?;
73
Jiyong Parkb1935ef2023-08-10 17:22:39 +090074 let idsig = File::open(&config.idsig).context("Failed to open idsig file")?;
75 let idsig_fd = ParcelFileDescriptor::new(idsig);
Jiyong Park48b354d2021-07-15 15:04:38 +090076
Jiyong Parkb1935ef2023-08-10 17:22:39 +090077 if !config.instance.exists() {
Jiyong Park48b354d2021-07-15 15:04:38 +090078 const INSTANCE_FILE_SIZE: u64 = 10 * 1024 * 1024;
Jiyong Park9dd389e2021-08-23 20:42:59 +090079 command_create_partition(
Jiyong Parkb1935ef2023-08-10 17:22:39 +090080 service.as_ref(),
81 &config.instance,
Jiyong Park9dd389e2021-08-23 20:42:59 +090082 INSTANCE_FILE_SIZE,
83 PartitionType::ANDROID_VM_INSTANCE,
84 )?;
Jiyong Park48b354d2021-07-15 15:04:38 +090085 }
86
Jiyong Parkb1935ef2023-08-10 17:22:39 +090087 let storage = if let Some(path) = config.microdroid.storage {
Shikha Panwar22e70452022-10-10 18:32:55 +000088 if !path.exists() {
89 command_create_partition(
Jiyong Parkb1935ef2023-08-10 17:22:39 +090090 service.as_ref(),
91 &path,
92 config.microdroid.storage_size.unwrap_or(10 * 1024 * 1024),
Shikha Panwar9fd198f2022-11-18 17:43:43 +000093 PartitionType::ENCRYPTEDSTORE,
Shikha Panwar22e70452022-10-10 18:32:55 +000094 )?;
95 }
Jiyong Parkb1935ef2023-08-10 17:22:39 +090096 Some(open_parcel_file(&path, true)?)
Shikha Panwar22e70452022-10-10 18:32:55 +000097 } else {
98 None
99 };
100
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900101 let kernel =
102 config.microdroid.kernel.as_ref().map(|p| open_parcel_file(p, false)).transpose()?;
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100103
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900104 let vendor =
105 config.microdroid.vendor.as_ref().map(|p| open_parcel_file(p, false)).transpose()?;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100106
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900107 let extra_idsig_files: Result<Vec<File>, _> =
108 config.extra_idsigs.iter().map(File::open).collect();
Inseob Kima5a262f2021-11-17 19:41:03 +0900109 let extra_idsig_fds = extra_idsig_files?.into_iter().map(ParcelFileDescriptor::new).collect();
110
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900111 let payload = if let Some(config_path) = config.config_path {
112 if config.payload_binary_name.is_some() {
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000113 bail!("Only one of --config-path or --payload-binary-name can be defined")
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900114 }
115 Payload::ConfigPath(config_path)
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900116 } else if let Some(payload_binary_name) = config.payload_binary_name {
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000117 Payload::PayloadConfig(VirtualMachinePayloadConfig {
118 payloadBinaryName: payload_binary_name,
119 })
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900120 } else {
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000121 bail!("Either --config-path or --payload-binary-name must be defined")
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900122 };
123
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900124 let payload_config_str = format!("{:?}!{:?}", config.apk, payload);
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900125
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100126 let custom_config = CustomConfig {
127 customKernelImage: kernel,
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900128 gdbPort: config.debug.gdb.map(u16::from).unwrap_or(0) as i32, // 0 means no gdb
129 taskProfiles: config.common.task_profiles,
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100130 vendorImage: vendor,
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900131 devices: config
132 .microdroid
133 .devices
Inseob Kim6ef80972023-07-20 17:23:36 +0900134 .iter()
135 .map(|x| {
136 x.to_str().map(String::from).ok_or(anyhow!("Failed to convert {x:?} to String"))
137 })
138 .collect::<Result<_, _>>()?,
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100139 };
140
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900141 let vm_config = VirtualMachineConfig::AppConfig(VirtualMachineAppConfig {
142 name: config.common.name.unwrap_or_else(|| String::from("VmRunApp")),
Jiyong Park0a248432021-08-20 23:32:39 +0900143 apk: apk_fd.into(),
144 idsig: idsig_fd.into(),
Inseob Kima5a262f2021-11-17 19:41:03 +0900145 extraIdsigs: extra_idsig_fds,
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900146 instanceImage: open_parcel_file(&config.instance, true /* writable */)?.into(),
Shikha Panwar22e70452022-10-10 18:32:55 +0000147 encryptedStorageImage: storage,
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900148 payload,
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900149 debugLevel: config.debug.debug,
150 protectedVm: config.common.protected,
151 memoryMib: config.common.mem.unwrap_or(0) as i32, // 0 means use the VM default
152 cpuTopology: config.common.cpu_topology,
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100153 customConfig: Some(custom_config),
Jooyung Han21e9b922021-06-26 04:14:16 +0900154 });
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900155 run(
156 service.as_ref(),
157 &vm_config,
158 &payload_config_str,
159 config.debug.console.as_ref().map(|p| p.as_ref()),
160 config.debug.console_in.as_ref().map(|p| p.as_ref()),
161 config.debug.log.as_ref().map(|p| p.as_ref()),
162 )
Jooyung Han21e9b922021-06-26 04:14:16 +0900163}
164
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000165fn find_empty_payload_apk_path() -> Result<PathBuf, Error> {
Cole Faust237ee3e2023-03-01 11:58:01 -0800166 const GLOB_PATTERN: &str = "/apex/com.android.virt/app/**/EmptyPayloadApp*.apk";
Nikita Ioffefc041962023-01-18 00:10:40 +0000167 let mut entries: Vec<PathBuf> =
168 glob(GLOB_PATTERN).context("failed to glob")?.filter_map(|e| e.ok()).collect();
169 if entries.len() > 1 {
170 return Err(anyhow!("Found more than one apk matching {}", GLOB_PATTERN));
171 }
172 match entries.pop() {
173 Some(path) => Ok(path),
174 None => Err(anyhow!("No apks match {}", GLOB_PATTERN)),
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000175 }
176}
177
178fn create_work_dir() -> Result<PathBuf, Error> {
179 let s: String =
180 rand::thread_rng().sample_iter(&Alphanumeric).take(17).map(char::from).collect();
181 let work_dir = PathBuf::from("/data/local/tmp/microdroid").join(s);
182 println!("creating work dir {}", work_dir.display());
183 fs::create_dir_all(&work_dir).context("failed to mkdir")?;
184 Ok(work_dir)
185}
186
187/// Run a VM with Microdroid
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900188pub fn command_run_microdroid(config: RunMicrodroidConfig) -> Result<(), Error> {
Nikita Ioffefc041962023-01-18 00:10:40 +0000189 let apk = find_empty_payload_apk_path()?;
190 println!("found path {}", apk.display());
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000191
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900192 let work_dir = config.work_dir.unwrap_or(create_work_dir()?);
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000193 let idsig = work_dir.join("apk.idsig");
194 println!("apk.idsig path: {}", idsig.display());
195 let instance_img = work_dir.join("instance.img");
196 println!("instance.img path: {}", instance_img.display());
197
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900198 let app_config = RunAppConfig {
199 common: config.common,
200 debug: config.debug,
201 microdroid: config.microdroid,
202 apk,
203 idsig,
204 instance: instance_img,
205 config_path: None,
206 payload_binary_name: Some("MicrodroidEmptyPayloadJniLib.so".to_owned()),
207 extra_idsigs: [].to_vec(),
208 };
209 command_run_app(app_config)
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000210}
211
Andrew Walbranf395b822021-05-05 10:38:59 +0000212/// Run a VM from the given configuration file.
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900213pub fn command_run(config: RunCustomVmConfig) -> Result<(), Error> {
214 let config_file = File::open(&config.config).context("Failed to open config file")?;
215 let mut vm_config =
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000216 VmConfig::load(&config_file).context("Failed to parse config file")?.to_parcelable()?;
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900217 if let Some(mem) = config.common.mem {
218 vm_config.memoryMib = mem as i32;
Jiyong Parkd63cfff2021-09-27 20:10:17 +0900219 }
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900220 if let Some(name) = config.common.name {
221 vm_config.name = name;
Seungjae Yoo62085c02022-08-12 04:44:52 +0000222 } else {
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900223 vm_config.name = String::from("VmRun");
Seungjae Yoo62085c02022-08-12 04:44:52 +0000224 }
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900225 if let Some(gdb) = config.debug.gdb {
226 vm_config.gdbPort = gdb.get() as i32;
Nikita Ioffe5776f082023-02-10 21:38:26 +0000227 }
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900228 vm_config.cpuTopology = config.common.cpu_topology;
229 vm_config.taskProfiles = config.common.task_profiles;
Jooyung Han21e9b922021-06-26 04:14:16 +0900230 run(
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900231 get_service()?.as_ref(),
232 &VirtualMachineConfig::RawConfig(vm_config),
233 &format!("{:?}", &config.config),
234 config.debug.console.as_ref().map(|p| p.as_ref()),
235 config.debug.console_in.as_ref().map(|p| p.as_ref()),
236 config.debug.log.as_ref().map(|p| p.as_ref()),
Jooyung Han21e9b922021-06-26 04:14:16 +0900237 )
238}
239
Andrew Walbranf8d94112021-09-07 11:45:36 +0000240fn state_to_str(vm_state: VirtualMachineState) -> &'static str {
241 match vm_state {
242 VirtualMachineState::NOT_STARTED => "NOT_STARTED",
243 VirtualMachineState::STARTING => "STARTING",
244 VirtualMachineState::STARTED => "STARTED",
245 VirtualMachineState::READY => "READY",
246 VirtualMachineState::FINISHED => "FINISHED",
247 VirtualMachineState::DEAD => "DEAD",
248 _ => "(invalid state)",
249 }
250}
251
Jooyung Han21e9b922021-06-26 04:14:16 +0900252fn run(
Andrew Walbran616d13f2022-05-12 18:35:55 +0000253 service: &dyn IVirtualizationService,
Jooyung Han21e9b922021-06-26 04:14:16 +0900254 config: &VirtualMachineConfig,
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900255 payload_config: &str,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900256 console_out_path: Option<&Path>,
257 console_in_path: Option<&Path>,
Jooyung Han21e9b922021-06-26 04:14:16 +0900258 log_path: Option<&Path>,
259) -> Result<(), Error> {
Jiyong Parke6fb1672023-06-26 16:45:55 +0900260 let console_out = if let Some(console_out_path) = console_out_path {
261 Some(File::create(console_out_path).with_context(|| {
262 format!("Failed to open console output file {:?}", console_out_path)
263 })?)
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900264 } else {
Jiyong Parke6fb1672023-06-26 16:45:55 +0900265 Some(duplicate_fd(io::stdout())?)
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900266 };
Jiyong Parke6fb1672023-06-26 16:45:55 +0900267 let console_in =
268 if let Some(console_in_path) = console_in_path {
269 Some(File::create(console_in_path).with_context(|| {
270 format!("Failed to open console input file {:?}", console_in_path)
271 })?)
272 } else {
273 Some(duplicate_fd(io::stdin())?)
274 };
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900275 let log = if let Some(log_path) = log_path {
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000276 Some(
Andrew Walbranbe429242021-06-28 12:22:54 +0000277 File::create(log_path)
278 .with_context(|| format!("Failed to open log file {:?}", log_path))?,
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000279 )
Andrew Walbranbe429242021-06-28 12:22:54 +0000280 } else {
Jiyong Parke6fb1672023-06-26 16:45:55 +0900281 Some(duplicate_fd(io::stdout())?)
Andrew Walbranbe429242021-06-28 12:22:54 +0000282 };
Alan Stokes0e82b502022-08-08 14:44:48 +0100283 let callback = Box::new(Callback {});
Jiyong Parke6fb1672023-06-26 16:45:55 +0900284 let vm = VmInstance::create(service, config, console_out, console_in, log, Some(callback))
Alan Stokes0e82b502022-08-08 14:44:48 +0100285 .context("Failed to create VM")?;
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000286 vm.start().context("Failed to start VM")?;
Andrew Walbranf395b822021-05-05 10:38:59 +0000287
Pierre-Clément Tosi1b691cc2023-06-28 11:40:29 +0000288 let debug_level = match config {
289 VirtualMachineConfig::AppConfig(config) => config.debugLevel,
290 _ => DebugLevel::NONE,
291 };
Andrew Walbranf8d94112021-09-07 11:45:36 +0000292 println!(
Pierre-Clément Tosi1b691cc2023-06-28 11:40:29 +0000293 "Created {} from {} with CID {}, state is {}.",
294 if debug_level == DebugLevel::FULL { "debuggable VM" } else { "VM" },
Inseob Kim7b5f65c2022-11-15 14:27:04 +0900295 payload_config,
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000296 vm.cid(),
297 state_to_str(vm.state()?)
Andrew Walbranf8d94112021-09-07 11:45:36 +0000298 );
Andrew Walbranf395b822021-05-05 10:38:59 +0000299
David Brazdil2b6352f2023-01-12 11:01:17 +0000300 // Wait until the VM or VirtualizationService dies. If we just returned immediately then the
301 // IVirtualMachine Binder object would be dropped and the VM would be killed.
302 let death_reason = vm.wait_for_death();
303 println!("VM ended: {:?}", death_reason);
Andrew Walbranf395b822021-05-05 10:38:59 +0000304 Ok(())
305}
306
Inseob Kima5a262f2021-11-17 19:41:03 +0900307fn parse_extra_apk_list(apk: &Path, config_path: &str) -> Result<Vec<String>, Error> {
308 let mut archive = ZipArchive::new(File::open(apk)?)?;
309 let config_file = archive.by_name(config_path)?;
310 let config: VmPayloadConfig = serde_json::from_reader(config_file)?;
311 Ok(config.extra_apks.into_iter().map(|x| x.path).collect())
312}
313
Alan Stokes0e82b502022-08-08 14:44:48 +0100314struct Callback {}
Andrew Walbranf395b822021-05-05 10:38:59 +0000315
Alan Stokes0e82b502022-08-08 14:44:48 +0100316impl vmclient::VmCallback for Callback {
David Brazdil451cc962022-10-14 14:08:12 +0100317 fn on_payload_started(&self, _cid: i32) {
318 eprintln!("payload started");
319 }
320
Alan Stokes0e82b502022-08-08 14:44:48 +0100321 fn on_payload_ready(&self, _cid: i32) {
Inseob Kim8dbc3222021-09-01 21:50:23 +0900322 eprintln!("payload is ready");
Inseob Kim14cb8692021-08-31 21:50:39 +0900323 }
324
Alan Stokes0e82b502022-08-08 14:44:48 +0100325 fn on_payload_finished(&self, _cid: i32, exit_code: i32) {
Inseob Kim8dbc3222021-09-01 21:50:23 +0900326 eprintln!("payload finished with exit code {}", exit_code);
Inseob Kim2444af92021-08-31 01:22:50 +0900327 }
328
Alan Stokes2bead0d2022-09-05 16:58:34 +0100329 fn on_error(&self, _cid: i32, error_code: ErrorCode, message: &str) {
330 eprintln!("VM encountered an error: code={:?}, message={}", error_code, message);
Andrew Walbranf395b822021-05-05 10:38:59 +0000331 }
332}
333
Jiyong Parke6fb1672023-06-26 16:45:55 +0900334/// Safely duplicate the file descriptor.
335fn duplicate_fd<T: AsRawFd>(file: T) -> io::Result<File> {
336 let fd = file.as_raw_fd();
Andrew Walbranb58d1b42023-07-07 13:54:49 +0100337 // SAFETY: This just duplicates a file descriptor which we know to be valid, and we check for an
338 // an error.
Jiyong Parke6fb1672023-06-26 16:45:55 +0900339 let dup_fd = unsafe { libc::dup(fd) };
Andrew Walbranf395b822021-05-05 10:38:59 +0000340 if dup_fd < 0 {
341 Err(io::Error::last_os_error())
342 } else {
Andrew Walbranb58d1b42023-07-07 13:54:49 +0100343 // SAFETY: We have just duplicated the file descriptor so we own it, and `from_raw_fd` takes
344 // ownership of it.
Andrew Walbranf395b822021-05-05 10:38:59 +0000345 Ok(unsafe { File::from_raw_fd(dup_fd) })
346 }
347}