Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 1 | // 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 Park | 48b354d | 2021-07-15 15:04:38 +0900 | [diff] [blame] | 17 | use crate::create_partition::command_create_partition; |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 18 | use crate::sync::AtomicFlag; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 19 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{ |
Jiyong Park | c2a49cc | 2021-10-15 00:02:12 +0900 | [diff] [blame] | 20 | IVirtualMachine::IVirtualMachine, IVirtualMachineCallback::BnVirtualMachineCallback, |
| 21 | IVirtualMachineCallback::IVirtualMachineCallback, |
| 22 | IVirtualizationService::IVirtualizationService, PartitionType::PartitionType, |
| 23 | VirtualMachineAppConfig::DebugLevel::DebugLevel, |
| 24 | VirtualMachineAppConfig::VirtualMachineAppConfig, VirtualMachineConfig::VirtualMachineConfig, |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 25 | VirtualMachineState::VirtualMachineState, |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 26 | }; |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 27 | use android_system_virtualizationservice::binder::{ |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 28 | BinderFeatures, DeathRecipient, IBinder, ParcelFileDescriptor, Strong, |
| 29 | }; |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 30 | use android_system_virtualizationservice::binder::{Interface, Result as BinderResult}; |
Inseob Kim | a5a262f | 2021-11-17 19:41:03 +0900 | [diff] [blame] | 31 | use anyhow::{bail, Context, Error}; |
| 32 | use microdroid_payload_config::VmPayloadConfig; |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 33 | use std::fs::File; |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 34 | use std::io::{self, BufRead, BufReader}; |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 35 | use std::os::unix::io::{AsRawFd, FromRawFd}; |
Inseob Kim | a5a262f | 2021-11-17 19:41:03 +0900 | [diff] [blame] | 36 | use std::path::{Path, PathBuf}; |
Jiyong Park | 48b354d | 2021-07-15 15:04:38 +0900 | [diff] [blame] | 37 | use vmconfig::{open_parcel_file, VmConfig}; |
Inseob Kim | a5a262f | 2021-11-17 19:41:03 +0900 | [diff] [blame] | 38 | use zip::ZipArchive; |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 39 | |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 40 | /// Run a VM from the given APK, idsig, and config. |
Jiyong Park | 48b354d | 2021-07-15 15:04:38 +0900 | [diff] [blame] | 41 | #[allow(clippy::too_many_arguments)] |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 42 | pub fn command_run_app( |
| 43 | service: Strong<dyn IVirtualizationService>, |
| 44 | apk: &Path, |
| 45 | idsig: &Path, |
Jiyong Park | 48b354d | 2021-07-15 15:04:38 +0900 | [diff] [blame] | 46 | instance: &Path, |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 47 | config_path: &str, |
| 48 | daemonize: bool, |
Jiyong Park | b8182bb | 2021-10-26 22:53:08 +0900 | [diff] [blame] | 49 | console_path: Option<&Path>, |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 50 | log_path: Option<&Path>, |
Jiyong Park | c2a49cc | 2021-10-15 00:02:12 +0900 | [diff] [blame] | 51 | debug_level: DebugLevel, |
Jiyong Park | d63cfff | 2021-09-27 20:10:17 +0900 | [diff] [blame] | 52 | mem: Option<u32>, |
Jiyong Park | 032615f | 2022-01-10 13:55:34 +0900 | [diff] [blame^] | 53 | cpus: Option<u32>, |
| 54 | cpu_affinity: Option<String>, |
Inseob Kim | a5a262f | 2021-11-17 19:41:03 +0900 | [diff] [blame] | 55 | extra_idsigs: &[PathBuf], |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 56 | ) -> Result<(), Error> { |
Inseob Kim | a5a262f | 2021-11-17 19:41:03 +0900 | [diff] [blame] | 57 | let extra_apks = parse_extra_apk_list(apk, config_path)?; |
| 58 | if extra_apks.len() != extra_idsigs.len() { |
| 59 | bail!( |
| 60 | "Found {} extra apks, but there are {} extra idsigs", |
| 61 | extra_apks.len(), |
| 62 | extra_idsigs.len() |
| 63 | ) |
| 64 | } |
| 65 | |
| 66 | for i in 0..extra_apks.len() { |
| 67 | let extra_apk_fd = ParcelFileDescriptor::new(File::open(&extra_apks[i])?); |
| 68 | let extra_idsig_fd = ParcelFileDescriptor::new(File::create(&extra_idsigs[i])?); |
| 69 | service.createOrUpdateIdsigFile(&extra_apk_fd, &extra_idsig_fd)?; |
| 70 | } |
| 71 | |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 72 | let apk_file = File::open(apk).context("Failed to open APK file")?; |
Jiyong Park | 0a24843 | 2021-08-20 23:32:39 +0900 | [diff] [blame] | 73 | let idsig_file = File::create(idsig).context("Failed to create idsig file")?; |
| 74 | |
| 75 | let apk_fd = ParcelFileDescriptor::new(apk_file); |
| 76 | let idsig_fd = ParcelFileDescriptor::new(idsig_file); |
| 77 | service.createOrUpdateIdsigFile(&apk_fd, &idsig_fd)?; |
| 78 | |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 79 | let idsig_file = File::open(idsig).context("Failed to open idsig file")?; |
Jiyong Park | 0a24843 | 2021-08-20 23:32:39 +0900 | [diff] [blame] | 80 | let idsig_fd = ParcelFileDescriptor::new(idsig_file); |
Jiyong Park | 48b354d | 2021-07-15 15:04:38 +0900 | [diff] [blame] | 81 | |
| 82 | if !instance.exists() { |
| 83 | const INSTANCE_FILE_SIZE: u64 = 10 * 1024 * 1024; |
Jiyong Park | 9dd389e | 2021-08-23 20:42:59 +0900 | [diff] [blame] | 84 | command_create_partition( |
| 85 | service.clone(), |
| 86 | instance, |
| 87 | INSTANCE_FILE_SIZE, |
| 88 | PartitionType::ANDROID_VM_INSTANCE, |
| 89 | )?; |
Jiyong Park | 48b354d | 2021-07-15 15:04:38 +0900 | [diff] [blame] | 90 | } |
| 91 | |
Inseob Kim | a5a262f | 2021-11-17 19:41:03 +0900 | [diff] [blame] | 92 | let extra_idsig_files: Result<Vec<File>, _> = extra_idsigs.iter().map(File::open).collect(); |
| 93 | let extra_idsig_fds = extra_idsig_files?.into_iter().map(ParcelFileDescriptor::new).collect(); |
| 94 | |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 95 | let config = VirtualMachineConfig::AppConfig(VirtualMachineAppConfig { |
Jiyong Park | 0a24843 | 2021-08-20 23:32:39 +0900 | [diff] [blame] | 96 | apk: apk_fd.into(), |
| 97 | idsig: idsig_fd.into(), |
Inseob Kim | a5a262f | 2021-11-17 19:41:03 +0900 | [diff] [blame] | 98 | extraIdsigs: extra_idsig_fds, |
Jiyong Park | 48b354d | 2021-07-15 15:04:38 +0900 | [diff] [blame] | 99 | instanceImage: open_parcel_file(instance, true /* writable */)?.into(), |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 100 | configPath: config_path.to_owned(), |
Jiyong Park | c2a49cc | 2021-10-15 00:02:12 +0900 | [diff] [blame] | 101 | debugLevel: debug_level, |
Jiyong Park | d63cfff | 2021-09-27 20:10:17 +0900 | [diff] [blame] | 102 | memoryMib: mem.unwrap_or(0) as i32, // 0 means use the VM default |
Jiyong Park | 032615f | 2022-01-10 13:55:34 +0900 | [diff] [blame^] | 103 | numCpus: cpus.unwrap_or(1) as i32, |
| 104 | cpuAffinity: cpu_affinity, |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 105 | }); |
Jiyong Park | b8182bb | 2021-10-26 22:53:08 +0900 | [diff] [blame] | 106 | run( |
| 107 | service, |
| 108 | &config, |
| 109 | &format!("{:?}!{:?}", apk, config_path), |
| 110 | daemonize, |
| 111 | console_path, |
| 112 | log_path, |
| 113 | ) |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 114 | } |
| 115 | |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 116 | /// Run a VM from the given configuration file. |
| 117 | pub fn command_run( |
Andrew Walbran | 17de24f | 2021-05-27 13:27:30 +0000 | [diff] [blame] | 118 | service: Strong<dyn IVirtualizationService>, |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 119 | config_path: &Path, |
| 120 | daemonize: bool, |
Jiyong Park | b8182bb | 2021-10-26 22:53:08 +0900 | [diff] [blame] | 121 | console_path: Option<&Path>, |
Jiyong Park | d63cfff | 2021-09-27 20:10:17 +0900 | [diff] [blame] | 122 | mem: Option<u32>, |
Jiyong Park | 032615f | 2022-01-10 13:55:34 +0900 | [diff] [blame^] | 123 | cpus: Option<u32>, |
| 124 | cpu_affinity: Option<String>, |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 125 | ) -> Result<(), Error> { |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 126 | let config_file = File::open(config_path).context("Failed to open config file")?; |
Jiyong Park | d63cfff | 2021-09-27 20:10:17 +0900 | [diff] [blame] | 127 | let mut config = |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 128 | VmConfig::load(&config_file).context("Failed to parse config file")?.to_parcelable()?; |
Jiyong Park | d63cfff | 2021-09-27 20:10:17 +0900 | [diff] [blame] | 129 | if let Some(mem) = mem { |
| 130 | config.memoryMib = mem as i32; |
| 131 | } |
Jiyong Park | 032615f | 2022-01-10 13:55:34 +0900 | [diff] [blame^] | 132 | if let Some(cpus) = cpus { |
| 133 | config.numCpus = cpus as i32; |
| 134 | } |
| 135 | config.cpuAffinity = cpu_affinity; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 136 | run( |
| 137 | service, |
| 138 | &VirtualMachineConfig::RawConfig(config), |
| 139 | &format!("{:?}", config_path), |
| 140 | daemonize, |
Jiyong Park | b8182bb | 2021-10-26 22:53:08 +0900 | [diff] [blame] | 141 | console_path, |
| 142 | None, |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 143 | ) |
| 144 | } |
| 145 | |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 146 | fn state_to_str(vm_state: VirtualMachineState) -> &'static str { |
| 147 | match vm_state { |
| 148 | VirtualMachineState::NOT_STARTED => "NOT_STARTED", |
| 149 | VirtualMachineState::STARTING => "STARTING", |
| 150 | VirtualMachineState::STARTED => "STARTED", |
| 151 | VirtualMachineState::READY => "READY", |
| 152 | VirtualMachineState::FINISHED => "FINISHED", |
| 153 | VirtualMachineState::DEAD => "DEAD", |
| 154 | _ => "(invalid state)", |
| 155 | } |
| 156 | } |
| 157 | |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 158 | fn run( |
| 159 | service: Strong<dyn IVirtualizationService>, |
| 160 | config: &VirtualMachineConfig, |
| 161 | config_path: &str, |
| 162 | daemonize: bool, |
Jiyong Park | b8182bb | 2021-10-26 22:53:08 +0900 | [diff] [blame] | 163 | console_path: Option<&Path>, |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 164 | log_path: Option<&Path>, |
| 165 | ) -> Result<(), Error> { |
Jiyong Park | b8182bb | 2021-10-26 22:53:08 +0900 | [diff] [blame] | 166 | let console = if let Some(console_path) = console_path { |
| 167 | Some(ParcelFileDescriptor::new( |
| 168 | File::create(console_path) |
| 169 | .with_context(|| format!("Failed to open console file {:?}", console_path))?, |
| 170 | )) |
| 171 | } else if daemonize { |
| 172 | None |
| 173 | } else { |
| 174 | Some(ParcelFileDescriptor::new(duplicate_stdout()?)) |
| 175 | }; |
| 176 | let log = if let Some(log_path) = log_path { |
Andrew Walbran | be42924 | 2021-06-28 12:22:54 +0000 | [diff] [blame] | 177 | Some(ParcelFileDescriptor::new( |
| 178 | File::create(log_path) |
| 179 | .with_context(|| format!("Failed to open log file {:?}", log_path))?, |
| 180 | )) |
| 181 | } else if daemonize { |
| 182 | None |
| 183 | } else { |
| 184 | Some(ParcelFileDescriptor::new(duplicate_stdout()?)) |
| 185 | }; |
Jiyong Park | b8182bb | 2021-10-26 22:53:08 +0900 | [diff] [blame] | 186 | |
| 187 | let vm = |
| 188 | service.createVm(config, console.as_ref(), log.as_ref()).context("Failed to create VM")?; |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 189 | |
| 190 | let cid = vm.getCid().context("Failed to get CID")?; |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 191 | println!( |
| 192 | "Created VM from {} with CID {}, state is {}.", |
| 193 | config_path, |
| 194 | cid, |
| 195 | state_to_str(vm.getState()?) |
| 196 | ); |
| 197 | vm.start()?; |
| 198 | println!("Started VM, state now {}.", state_to_str(vm.getState()?)); |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 199 | |
| 200 | if daemonize { |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 201 | // Pass the VM reference back to VirtualizationService and have it hold it in the |
| 202 | // background. |
Andrew Walbran | 17de24f | 2021-05-27 13:27:30 +0000 | [diff] [blame] | 203 | service.debugHoldVmRef(&vm).context("Failed to pass VM to VirtualizationService") |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 204 | } else { |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 205 | // Wait until the VM or VirtualizationService dies. If we just returned immediately then the |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 206 | // IVirtualMachine Binder object would be dropped and the VM would be killed. |
| 207 | wait_for_vm(vm) |
| 208 | } |
| 209 | } |
| 210 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 211 | /// Wait until the given VM or the VirtualizationService itself dies. |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 212 | fn wait_for_vm(vm: Strong<dyn IVirtualMachine>) -> Result<(), Error> { |
| 213 | let dead = AtomicFlag::default(); |
| 214 | let callback = BnVirtualMachineCallback::new_binder( |
| 215 | VirtualMachineCallback { dead: dead.clone() }, |
| 216 | BinderFeatures::default(), |
| 217 | ); |
| 218 | vm.registerCallback(&callback)?; |
| 219 | let death_recipient = wait_for_death(&mut vm.as_binder(), dead.clone())?; |
| 220 | dead.wait(); |
| 221 | // Ensure that death_recipient isn't dropped before we wait on the flag, as it is removed |
| 222 | // from the Binder when it's dropped. |
| 223 | drop(death_recipient); |
| 224 | Ok(()) |
| 225 | } |
| 226 | |
| 227 | /// Raise the given flag when the given Binder object dies. |
| 228 | /// |
| 229 | /// If the returned DeathRecipient is dropped then this will no longer do anything. |
| 230 | fn wait_for_death(binder: &mut impl IBinder, dead: AtomicFlag) -> Result<DeathRecipient, Error> { |
| 231 | let mut death_recipient = DeathRecipient::new(move || { |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 232 | eprintln!("VirtualizationService unexpectedly died"); |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 233 | dead.raise(); |
| 234 | }); |
| 235 | binder.link_to_death(&mut death_recipient)?; |
| 236 | Ok(death_recipient) |
| 237 | } |
| 238 | |
Inseob Kim | a5a262f | 2021-11-17 19:41:03 +0900 | [diff] [blame] | 239 | fn parse_extra_apk_list(apk: &Path, config_path: &str) -> Result<Vec<String>, Error> { |
| 240 | let mut archive = ZipArchive::new(File::open(apk)?)?; |
| 241 | let config_file = archive.by_name(config_path)?; |
| 242 | let config: VmPayloadConfig = serde_json::from_reader(config_file)?; |
| 243 | Ok(config.extra_apks.into_iter().map(|x| x.path).collect()) |
| 244 | } |
| 245 | |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 246 | #[derive(Debug)] |
| 247 | struct VirtualMachineCallback { |
| 248 | dead: AtomicFlag, |
| 249 | } |
| 250 | |
| 251 | impl Interface for VirtualMachineCallback {} |
| 252 | |
| 253 | impl IVirtualMachineCallback for VirtualMachineCallback { |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 254 | fn onPayloadStarted( |
| 255 | &self, |
| 256 | _cid: i32, |
| 257 | stream: Option<&ParcelFileDescriptor>, |
| 258 | ) -> BinderResult<()> { |
| 259 | // Show the output of the payload |
| 260 | if let Some(stream) = stream { |
| 261 | let mut reader = BufReader::new(stream.as_ref()); |
| 262 | loop { |
| 263 | let mut s = String::new(); |
| 264 | match reader.read_line(&mut s) { |
| 265 | Ok(0) => break, |
| 266 | Ok(_) => print!("{}", s), |
| 267 | Err(e) => eprintln!("error reading from virtual machine: {}", e), |
| 268 | }; |
| 269 | } |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 270 | } |
| 271 | Ok(()) |
| 272 | } |
| 273 | |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 274 | fn onPayloadReady(&self, _cid: i32) -> BinderResult<()> { |
Inseob Kim | 8dbc322 | 2021-09-01 21:50:23 +0900 | [diff] [blame] | 275 | eprintln!("payload is ready"); |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 276 | Ok(()) |
| 277 | } |
| 278 | |
Inseob Kim | 8dbc322 | 2021-09-01 21:50:23 +0900 | [diff] [blame] | 279 | fn onPayloadFinished(&self, _cid: i32, exit_code: i32) -> BinderResult<()> { |
| 280 | eprintln!("payload finished with exit code {}", exit_code); |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 281 | Ok(()) |
| 282 | } |
| 283 | |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 284 | fn onError(&self, _cid: i32, error_code: i32, message: &str) -> BinderResult<()> { |
| 285 | eprintln!("VM encountered an error: code={}, message={}", error_code, message); |
| 286 | Ok(()) |
| 287 | } |
| 288 | |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 289 | fn onDied(&self, _cid: i32) -> BinderResult<()> { |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 290 | // No need to explicitly report the event to the user (e.g. via println!) because this |
| 291 | // callback is registered only when the vm tool is invoked as interactive mode (e.g. not |
| 292 | // --daemonize) in which case the tool will exit to the shell prompt upon VM shutdown. |
| 293 | // Printing something will actually even confuse the user as the output from the app |
| 294 | // payload is printed. |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 295 | self.dead.raise(); |
| 296 | Ok(()) |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | /// Safely duplicate the standard output file descriptor. |
| 301 | fn duplicate_stdout() -> io::Result<File> { |
| 302 | let stdout_fd = io::stdout().as_raw_fd(); |
| 303 | // Safe because this just duplicates a file descriptor which we know to be valid, and we check |
| 304 | // for an error. |
| 305 | let dup_fd = unsafe { libc::dup(stdout_fd) }; |
| 306 | if dup_fd < 0 { |
| 307 | Err(io::Error::last_os_error()) |
| 308 | } else { |
| 309 | // Safe because we have just duplicated the file descriptor so we own it, and `from_raw_fd` |
| 310 | // takes ownership of it. |
| 311 | Ok(unsafe { File::from_raw_fd(dup_fd) }) |
| 312 | } |
| 313 | } |