blob: 283ecb9e8fae7ee1d60016cbd58e4460f76df181 [file] [log] [blame]
Jooyung Han347d9f22021-05-28 00:05:14 +09001// 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//! Microdroid Manager
16
Jiyong Park21ce2c52021-08-28 02:32:17 +090017mod instance;
Jooyung Hanf48ceb42021-06-01 18:00:04 +090018mod ioutil;
Jooyung Han7a343f92021-09-08 22:53:11 +090019mod payload;
Jooyung Han347d9f22021-05-28 00:05:14 +090020
Jiyong Parkf7dea252021-09-08 01:42:54 +090021use crate::instance::{ApkData, InstanceDisk, MicrodroidData, RootHash};
Jooyung Handd0a1732021-11-23 15:26:20 +090022use anyhow::{anyhow, bail, ensure, Context, Error, Result};
Jiyong Parka41535b2021-09-10 19:31:48 +090023use apkverify::{get_public_key_der, verify};
Inseob Kim1b95f2e2021-08-19 13:17:40 +090024use binder::unstable_api::{new_spibinder, AIBinder};
25use binder::{FromIBinder, Strong};
Jiyong Park21ce2c52021-08-28 02:32:17 +090026use idsig::V4Signature;
Jiyong Parkbb4a9872021-09-06 15:59:21 +090027use log::{error, info, warn};
Jooyung Han4a9b3bf2021-09-10 17:19:00 +090028use microdroid_metadata::{write_metadata, Metadata};
Jooyung Han634e2d72021-06-10 16:27:38 +090029use microdroid_payload_config::{Task, TaskType, VmPayloadConfig};
Jiyong Park9f72ea62021-12-06 21:18:38 +090030use once_cell::sync::OnceCell;
Jooyung Han4a9b3bf2021-09-10 17:19:00 +090031use payload::{get_apex_data_from_payload, load_metadata, to_metadata};
Jiyong Parkbb4a9872021-09-06 15:59:21 +090032use rustutils::system_properties;
Joel Galenson482704c2021-07-29 15:53:53 -070033use rustutils::system_properties::PropertyWatcher;
Inseob Kim7f61fe72021-08-20 20:50:47 +090034use std::fs::{self, File, OpenOptions};
Inseob Kimc7d28c72021-10-25 14:28:10 +000035use std::os::unix::io::{FromRawFd, IntoRawFd};
Jooyung Hanf48ceb42021-06-01 18:00:04 +090036use std::path::Path;
Inseob Kim217038e2021-11-25 11:15:06 +090037use std::process::{Child, Command, Stdio};
Jiyong Park8611a6c2021-07-09 18:17:44 +090038use std::str;
Jiyong Parkbb4a9872021-09-06 15:59:21 +090039use std::time::{Duration, SystemTime};
Jiyong Park8611a6c2021-07-09 18:17:44 +090040use vsock::VsockStream;
Jooyung Han634e2d72021-06-10 16:27:38 +090041
Inseob Kimd0587562021-09-01 21:27:32 +090042use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
Jooyung Handd0a1732021-11-23 15:26:20 +090043 ERROR_PAYLOAD_CHANGED, ERROR_PAYLOAD_VERIFICATION_FAILED, ERROR_UNKNOWN, VM_BINDER_SERVICE_PORT, VM_STREAM_SERVICE_PORT, IVirtualMachineService,
Inseob Kimd0587562021-09-01 21:27:32 +090044};
Inseob Kim1b95f2e2021-08-19 13:17:40 +090045
Jooyung Han634e2d72021-06-10 16:27:38 +090046const WAIT_TIMEOUT: Duration = Duration::from_secs(10);
Inseob Kim217038e2021-11-25 11:15:06 +090047const APK_DM_VERITY_ARGUMENT: ApkDmverityArgument = {
48 ApkDmverityArgument {
49 apk: "/dev/block/by-name/microdroid-apk",
50 idsig: "/dev/block/by-name/microdroid-apk-idsig",
51 name: "microdroid-apk",
52 }
53};
Jooyung Han19c1d6c2021-08-06 14:08:16 +090054const DM_MOUNTED_APK_PATH: &str = "/dev/block/mapper/microdroid-apk";
Inseob Kim217038e2021-11-25 11:15:06 +090055const APKDMVERITY_BIN: &str = "/system/bin/apkdmverity";
56const ZIPFUSE_BIN: &str = "/system/bin/zipfuse";
Jooyung Han347d9f22021-05-28 00:05:14 +090057
Inseob Kim1b95f2e2021-08-19 13:17:40 +090058/// The CID representing the host VM
59const VMADDR_CID_HOST: u32 = 2;
60
Jiyong Parkbb4a9872021-09-06 15:59:21 +090061const APEX_CONFIG_DONE_PROP: &str = "apex_config.done";
Jiyong Parkfa91d702021-10-18 23:51:39 +090062const LOGD_ENABLED_PROP: &str = "ro.boot.logd.enabled";
Jiyong Parkbb4a9872021-09-06 15:59:21 +090063
Jooyung Handd0a1732021-11-23 15:26:20 +090064#[derive(thiserror::Error, Debug)]
65enum MicrodroidError {
66 #[error("Payload has changed: {0}")]
67 PayloadChanged(String),
68 #[error("Payload verification has failed: {0}")]
69 PayloadVerificationFailed(String),
70}
71
72fn translate_error(err: &Error) -> (i32, String) {
73 if let Some(e) = err.downcast_ref::<MicrodroidError>() {
74 match e {
75 MicrodroidError::PayloadChanged(msg) => (ERROR_PAYLOAD_CHANGED, msg.to_string()),
76 MicrodroidError::PayloadVerificationFailed(msg) => {
77 (ERROR_PAYLOAD_VERIFICATION_FAILED, msg.to_string())
78 }
79 }
80 } else {
81 (ERROR_UNKNOWN, err.to_string())
82 }
83}
84
Inseob Kim1b95f2e2021-08-19 13:17:40 +090085fn get_vms_rpc_binder() -> Result<Strong<dyn IVirtualMachineService>> {
86 // SAFETY: AIBinder returned by RpcClient has correct reference count, and the ownership can be
87 // safely taken by new_spibinder.
88 let ibinder = unsafe {
89 new_spibinder(binder_rpc_unstable_bindgen::RpcClient(
90 VMADDR_CID_HOST,
Inseob Kimd0587562021-09-01 21:27:32 +090091 VM_BINDER_SERVICE_PORT as u32,
Inseob Kim1b95f2e2021-08-19 13:17:40 +090092 ) as *mut AIBinder)
93 };
94 if let Some(ibinder) = ibinder {
95 <dyn IVirtualMachineService>::try_from(ibinder).context("Cannot connect to RPC service")
96 } else {
97 bail!("Invalid raw AIBinder")
98 }
99}
100
Jooyung Han311b1202021-09-14 22:00:16 +0900101fn main() {
102 if let Err(e) = try_main() {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900103 error!("Failed with {:?}. Shutting down...", e);
104 if let Err(e) = system_properties::write("sys.powerctl", "shutdown") {
105 error!("failed to shutdown {:?}", e);
106 }
Jooyung Han311b1202021-09-14 22:00:16 +0900107 std::process::exit(1);
108 }
109}
110
111fn try_main() -> Result<()> {
Jiyong Park79b88012021-06-25 13:06:25 +0900112 kernlog::init()?;
Jooyung Han347d9f22021-05-28 00:05:14 +0900113 info!("started.");
114
Jooyung Handd0a1732021-11-23 15:26:20 +0900115 let service = get_vms_rpc_binder().context("cannot connect to VirtualMachineService")?;
116 if let Err(err) = try_start_payload(&service) {
117 let (error_code, message) = translate_error(&err);
118 service.notifyError(error_code, &message)?;
119 Err(err)
120 } else {
121 Ok(())
122 }
123}
124
125fn try_start_payload(service: &Strong<dyn IVirtualMachineService>) -> Result<()> {
Jooyung Han311b1202021-09-14 22:00:16 +0900126 let metadata = load_metadata().context("Failed to load payload metadata")?;
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900127
Jooyung Han311b1202021-09-14 22:00:16 +0900128 let mut instance = InstanceDisk::new().context("Failed to load instance.img")?;
Jooyung Han7a343f92021-09-08 22:53:11 +0900129 let saved_data = instance.read_microdroid_data().context("Failed to read identity data")?;
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900130
131 // Verify the payload before using it.
Jooyung Han7a343f92021-09-08 22:53:11 +0900132 let verified_data =
133 verify_payload(&metadata, saved_data.as_ref()).context("Payload verification failed")?;
134 if let Some(saved_data) = saved_data {
Jooyung Handd0a1732021-11-23 15:26:20 +0900135 ensure!(
136 saved_data == verified_data,
137 MicrodroidError::PayloadChanged(String::from(
138 "Detected an update of the payload which isn't supported yet."
139 ))
140 );
141 info!("Saved data is verified.");
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900142 } else {
Jooyung Han7a343f92021-09-08 22:53:11 +0900143 info!("Saving verified data.");
144 instance.write_microdroid_data(&verified_data).context("Failed to write identity data")?;
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900145 }
146
Jooyung Hana6d11eb2021-09-10 11:48:05 +0900147 // Before reading a file from the APK, start zipfuse
Inseob Kim217038e2021-11-25 11:15:06 +0900148 run_zipfuse(
149 "fscontext=u:object_r:zipfusefs:s0,context=u:object_r:system_file:s0",
150 Path::new("/dev/block/mapper/microdroid-apk"),
151 Path::new("/mnt/apk"),
152 )
153 .context("Failed to run zipfuse")?;
Jiyong Park21ce2c52021-08-28 02:32:17 +0900154
Jooyung Han74573482021-06-08 17:10:21 +0900155 if !metadata.payload_config_path.is_empty() {
Jooyung Han634e2d72021-06-10 16:27:38 +0900156 let config = load_config(Path::new(&metadata.payload_config_path))?;
157
Andrew Scull6f3e5fe2021-07-02 12:38:21 +0000158 let fake_secret = "This is a placeholder for a value that is derived from the images that are loaded in the VM.";
Joel Galenson482704c2021-07-29 15:53:53 -0700159 if let Err(err) = rustutils::system_properties::write("ro.vmsecret.keymint", fake_secret) {
Andrew Scull6f3e5fe2021-07-02 12:38:21 +0000160 warn!("failed to set ro.vmsecret.keymint: {}", err);
161 }
162
Jooyung Hana6d11eb2021-09-10 11:48:05 +0900163 // Wait until apex config is done. (e.g. linker configuration for apexes)
Jooyung Han634e2d72021-06-10 16:27:38 +0900164 // TODO(jooyung): wait until sys.boot_completed?
Jooyung Hana6d11eb2021-09-10 11:48:05 +0900165 wait_for_apex_config_done()?;
166
Jooyung Han347d9f22021-05-28 00:05:14 +0900167 if let Some(main_task) = &config.task {
Jooyung Handd0a1732021-11-23 15:26:20 +0900168 exec_task(main_task, service).map_err(|e| {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900169 error!("failed to execute task: {}", e);
170 e
171 })?;
Jooyung Han347d9f22021-05-28 00:05:14 +0900172 }
173 }
174
175 Ok(())
176}
177
Inseob Kim217038e2021-11-25 11:15:06 +0900178struct ApkDmverityArgument<'a> {
179 apk: &'a str,
180 idsig: &'a str,
181 name: &'a str,
182}
183
184fn run_apkdmverity(args: &[ApkDmverityArgument]) -> Result<Child> {
185 let mut cmd = Command::new(APKDMVERITY_BIN);
186
187 cmd.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
188
189 for argument in args {
190 cmd.arg("--apk").arg(argument.apk).arg(argument.idsig).arg(argument.name);
191 }
192
193 cmd.spawn().context("Spawn apkdmverity")
194}
195
196fn run_zipfuse(option: &str, zip_path: &Path, mount_dir: &Path) -> Result<Child> {
197 Command::new(ZIPFUSE_BIN)
198 .arg("-o")
199 .arg(option)
200 .arg(zip_path)
201 .arg(mount_dir)
202 .stdin(Stdio::null())
203 .stdout(Stdio::null())
204 .stderr(Stdio::null())
205 .spawn()
206 .context("Spawn zipfuse")
207}
208
Jooyung Han7a343f92021-09-08 22:53:11 +0900209// Verify payload before executing it. For APK payload, Full verification (which is slow) is done
210// when the root_hash values from the idsig file and the instance disk are different. This function
211// returns the verified root hash (for APK payload) and pubkeys (for APEX payloads) that can be
212// saved to the instance disk.
213fn verify_payload(
214 metadata: &Metadata,
215 saved_data: Option<&MicrodroidData>,
216) -> Result<MicrodroidData> {
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900217 let start_time = SystemTime::now();
218
Jiyong Park9f72ea62021-12-06 21:18:38 +0900219 if let Some(saved_bootconfig) = saved_data.map(|d| &d.bootconfig) {
220 ensure!(
221 saved_bootconfig.as_ref() == get_bootconfig()?.as_slice(),
222 MicrodroidError::PayloadChanged(String::from("Bootconfig has changed."))
223 );
224 }
225
Jooyung Han7a343f92021-09-08 22:53:11 +0900226 let root_hash = saved_data.map(|d| &d.apk_data.root_hash);
Jiyong Parkf7dea252021-09-08 01:42:54 +0900227 let root_hash_from_idsig = get_apk_root_hash_from_idsig()?;
228 let root_hash_trustful = root_hash == Some(&root_hash_from_idsig);
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900229
Jiyong Parkf7dea252021-09-08 01:42:54 +0900230 // If root_hash can be trusted, pass it to apkdmverity so that it uses the passed root_hash
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900231 // instead of the value read from the idsig file.
Jiyong Parkf7dea252021-09-08 01:42:54 +0900232 if root_hash_trustful {
233 let root_hash = to_hex_string(root_hash.unwrap());
234 system_properties::write("microdroid_manager.apk_root_hash", &root_hash)?;
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900235 }
236
237 // Start apkdmverity and wait for the dm-verify block
Inseob Kim217038e2021-11-25 11:15:06 +0900238 let mut apkdmverity_child = run_apkdmverity(&[APK_DM_VERITY_ARGUMENT])?;
Jooyung Han7a343f92021-09-08 22:53:11 +0900239
Jooyung Hanc8deb472021-09-13 13:48:25 +0900240 // While waiting for apkdmverity to mount APK, gathers public keys and root digests from
241 // APEX payload.
Jooyung Han7a343f92021-09-08 22:53:11 +0900242 let apex_data_from_payload = get_apex_data_from_payload(metadata)?;
Jooyung Han4a9b3bf2021-09-10 17:19:00 +0900243 if let Some(saved_data) = saved_data.map(|d| &d.apex_data) {
Jooyung Hanc8deb472021-09-13 13:48:25 +0900244 // We don't support APEX updates. (assuming that update will change root digest)
Jooyung Handd0a1732021-11-23 15:26:20 +0900245 ensure!(
246 saved_data == &apex_data_from_payload,
247 MicrodroidError::PayloadChanged(String::from("APEXes have changed."))
248 );
Jooyung Han4a9b3bf2021-09-10 17:19:00 +0900249 let apex_metadata = to_metadata(&apex_data_from_payload);
Jooyung Hanc8deb472021-09-13 13:48:25 +0900250 // Pass metadata(with public keys and root digests) to apexd so that it uses the passed
251 // metadata instead of the default one (/dev/block/by-name/payload-metadata)
Jooyung Han4a9b3bf2021-09-10 17:19:00 +0900252 OpenOptions::new()
253 .create_new(true)
254 .write(true)
255 .open("/apex/vm-payload-metadata")
256 .context("Failed to open /apex/vm-payload-metadata")
257 .and_then(|f| write_metadata(&apex_metadata, f))?;
258 }
259 // Start apexd to activate APEXes
260 system_properties::write("ctl.start", "apexd-vm")?;
Jooyung Han7a343f92021-09-08 22:53:11 +0900261
Inseob Kim217038e2021-11-25 11:15:06 +0900262 // TODO(inseob): add timeout
263 apkdmverity_child.wait()?;
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900264
Jiyong Parkf7dea252021-09-08 01:42:54 +0900265 // Do the full verification if the root_hash is un-trustful. This requires the full scanning of
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900266 // the APK file and therefore can be very slow if the APK is large. Note that this step is
Jiyong Parkf7dea252021-09-08 01:42:54 +0900267 // taken only when the root_hash is un-trustful which can be either when this is the first boot
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900268 // of the VM or APK was updated in the host.
269 // TODO(jooyung): consider multithreading to make this faster
Jiyong Parka41535b2021-09-10 19:31:48 +0900270 let apk_pubkey = if !root_hash_trustful {
Jooyung Handd0a1732021-11-23 15:26:20 +0900271 verify(DM_MOUNTED_APK_PATH).context(MicrodroidError::PayloadVerificationFailed(format!(
272 "failed to verify {}",
273 DM_MOUNTED_APK_PATH
274 )))?
Jiyong Parka41535b2021-09-10 19:31:48 +0900275 } else {
276 get_public_key_der(DM_MOUNTED_APK_PATH)?
277 };
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900278
279 info!("payload verification successful. took {:#?}", start_time.elapsed().unwrap());
280
Jiyong Parkf7dea252021-09-08 01:42:54 +0900281 // At this point, we can ensure that the root_hash from the idsig file is trusted, either by
282 // fully verifying the APK or by comparing it with the saved root_hash.
Jooyung Han7a343f92021-09-08 22:53:11 +0900283 Ok(MicrodroidData {
Jiyong Parka41535b2021-09-10 19:31:48 +0900284 apk_data: ApkData { root_hash: root_hash_from_idsig, pubkey: apk_pubkey },
Jooyung Han7a343f92021-09-08 22:53:11 +0900285 apex_data: apex_data_from_payload,
Jiyong Park9f72ea62021-12-06 21:18:38 +0900286 bootconfig: get_bootconfig()?.clone().into_boxed_slice(),
Jooyung Han7a343f92021-09-08 22:53:11 +0900287 })
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900288}
289
290// Waits until linker config is generated
291fn wait_for_apex_config_done() -> Result<()> {
292 let mut prop = PropertyWatcher::new(APEX_CONFIG_DONE_PROP)?;
293 loop {
294 prop.wait()?;
295 let val = system_properties::read(APEX_CONFIG_DONE_PROP)?;
296 if val == "true" {
297 break;
298 }
299 }
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900300 Ok(())
301}
302
Jiyong Parkf7dea252021-09-08 01:42:54 +0900303fn get_apk_root_hash_from_idsig() -> Result<Box<RootHash>> {
Jiyong Park21ce2c52021-08-28 02:32:17 +0900304 let mut idsig = File::open("/dev/block/by-name/microdroid-apk-idsig")?;
305 let idsig = V4Signature::from(&mut idsig)?;
306 Ok(idsig.hashing_info.raw_root_hash)
307}
308
Jiyong Park9f72ea62021-12-06 21:18:38 +0900309fn get_bootconfig() -> Result<&'static Vec<u8>> {
310 static VAL: OnceCell<Vec<u8>> = OnceCell::new();
311 VAL.get_or_try_init(|| {
312 fs::read("/proc/bootconfig").context("Failed to read bootconfig")
313 })
314}
315
Jooyung Han634e2d72021-06-10 16:27:38 +0900316fn load_config(path: &Path) -> Result<VmPayloadConfig> {
317 info!("loading config from {:?}...", path);
318 let file = ioutil::wait_for_file(path, WAIT_TIMEOUT)?;
319 Ok(serde_json::from_reader(file)?)
320}
321
Jiyong Park8611a6c2021-07-09 18:17:44 +0900322/// Executes the given task. Stdout of the task is piped into the vsock stream to the
323/// virtualizationservice in the host side.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900324fn exec_task(task: &Task, service: &Strong<dyn IVirtualMachineService>) -> Result<()> {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900325 info!("executing main task {:?}...", task);
Inseob Kim86ca0162021-10-20 02:21:02 +0000326 let mut command = build_command(task)?;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900327
328 info!("notifying payload started");
Inseob Kimc7d28c72021-10-25 14:28:10 +0000329 service.notifyPayloadStarted()?;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900330
Jiyong Parkfa91d702021-10-18 23:51:39 +0900331 // Start logging if enabled
332 // TODO(b/200914564) set filterspec if debug_level is app_only
333 if system_properties::read(LOGD_ENABLED_PROP)? == "1" {
334 system_properties::write("ctl.start", "seriallogging")?;
335 }
336
Inseob Kim86ca0162021-10-20 02:21:02 +0000337 let exit_status = command.spawn()?.wait()?;
Alan Stokes4eea5c72021-09-20 17:40:28 +0100338 if let Some(code) = exit_status.code() {
Inseob Kim2444af92021-08-31 01:22:50 +0900339 info!("notifying payload finished");
Inseob Kimc7d28c72021-10-25 14:28:10 +0000340 service.notifyPayloadFinished(code)?;
Inseob Kim2444af92021-08-31 01:22:50 +0900341
342 if code == 0 {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900343 info!("task successfully finished");
Inseob Kim2444af92021-08-31 01:22:50 +0900344 } else {
345 error!("task exited with exit code: {}", code);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900346 }
Inseob Kim2444af92021-08-31 01:22:50 +0900347 } else {
Alan Stokes4eea5c72021-09-20 17:40:28 +0100348 error!("task terminated: {}", exit_status);
Jiyong Park038b73e2021-06-16 01:57:02 +0900349 }
Inseob Kim2444af92021-08-31 01:22:50 +0900350 Ok(())
Jooyung Han347d9f22021-05-28 00:05:14 +0900351}
Jooyung Han634e2d72021-06-10 16:27:38 +0900352
353fn build_command(task: &Task) -> Result<Command> {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900354 const VMADDR_CID_HOST: u32 = 2;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900355
356 let mut command = match task.type_ {
Jooyung Han634e2d72021-06-10 16:27:38 +0900357 TaskType::Executable => {
358 let mut command = Command::new(&task.command);
359 command.args(&task.args);
360 command
361 }
362 TaskType::MicrodroidLauncher => {
363 let mut command = Command::new("/system/bin/microdroid_launcher");
364 command.arg(find_library_path(&task.command)?).args(&task.args);
365 command
366 }
Inseob Kim7f61fe72021-08-20 20:50:47 +0900367 };
368
Inseob Kimd0587562021-09-01 21:27:32 +0900369 match VsockStream::connect_with_cid_port(VMADDR_CID_HOST, VM_STREAM_SERVICE_PORT as u32) {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900370 Ok(stream) => {
371 // SAFETY: the ownership of the underlying file descriptor is transferred from stream
372 // to the file object, and then into the Command object. When the command is finished,
373 // the file descriptor is closed.
374 let file = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
375 command
376 .stdin(Stdio::from(file.try_clone()?))
377 .stdout(Stdio::from(file.try_clone()?))
378 .stderr(Stdio::from(file));
379 }
380 Err(e) => {
381 error!("failed to connect to virtualization service: {}", e);
382 // Don't fail hard here. Even if we failed to connect to the virtualizationservice,
383 // we keep executing the task. This can happen if the owner of the VM doesn't register
384 // callback to accept the stream. Use /dev/null as the stream so that the task can
385 // make progress without waiting for someone to consume the output.
386 command.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
387 }
388 }
389
390 Ok(command)
Jooyung Han634e2d72021-06-10 16:27:38 +0900391}
392
393fn find_library_path(name: &str) -> Result<String> {
394 let mut watcher = PropertyWatcher::new("ro.product.cpu.abilist")?;
395 let value = watcher.read(|_name, value| Ok(value.trim().to_string()))?;
396 let abi = value.split(',').next().ok_or_else(|| anyhow!("no abilist"))?;
397 let path = format!("/mnt/apk/lib/{}/{}", abi, name);
398
399 let metadata = fs::metadata(&path)?;
400 if !metadata.is_file() {
401 bail!("{} is not a file", &path);
402 }
403
404 Ok(path)
405}
Jiyong Park21ce2c52021-08-28 02:32:17 +0900406
407fn to_hex_string(buf: &[u8]) -> String {
408 buf.iter().map(|b| format!("{:02X}", b)).collect()
409}