blob: 0c79f5f8f1ea5fc0aac4bdcb7bf3cbe20492a42d [file] [log] [blame]
Jooyung Han21e9b922021-06-26 04:14:16 +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//! Payload disk image
16
Andrew Walbrancc0db522021-07-12 17:03:42 +000017use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Alan Stokes0d1ef782022-09-27 13:46:35 +010018 DiskImage::DiskImage,
19 Partition::Partition,
20 VirtualMachineAppConfig::DebugLevel::DebugLevel,
21 VirtualMachineAppConfig::{Payload::Payload, VirtualMachineAppConfig},
Andrew Walbrancc0db522021-07-12 17:03:42 +000022 VirtualMachineRawConfig::VirtualMachineRawConfig,
23};
Inseob Kima5a262f2021-11-17 19:41:03 +090024use anyhow::{anyhow, bail, Context, Result};
Alan Stokes0e82b502022-08-08 14:44:48 +010025use binder::{wait_for_interface, ParcelFileDescriptor};
Alan Stokesbf20c6a2022-01-04 12:30:50 +000026use log::{info, warn};
Alan Stokes0d1ef782022-09-27 13:46:35 +010027use microdroid_metadata::{ApexPayload, ApkPayload, Metadata, PayloadConfig, PayloadMetadata};
Jooyung Han5dc42172021-10-05 16:43:47 +090028use microdroid_payload_config::{ApexConfig, VmPayloadConfig};
Jooyung Han9900f3d2021-07-06 10:27:54 +090029use once_cell::sync::OnceCell;
Jooyung Han743e0d62022-11-07 20:57:48 +090030use packagemanager_aidl::aidl::android::content::pm::{
31 IPackageManagerNative::IPackageManagerNative, StagedApexInfo::StagedApexInfo,
32};
Alan Stokesbf20c6a2022-01-04 12:30:50 +000033use regex::Regex;
Jooyung Han44b02ab2021-07-16 03:19:13 +090034use serde::Deserialize;
35use serde_xml_rs::from_reader;
Alan Stokesbf20c6a2022-01-04 12:30:50 +000036use std::collections::HashSet;
Andrew Walbran40be9d52022-01-19 14:32:53 +000037use std::fs::{metadata, File, OpenOptions};
Jooyung Han21e9b922021-06-26 04:14:16 +090038use std::path::{Path, PathBuf};
Alan Stokesbf20c6a2022-01-04 12:30:50 +000039use std::process::Command;
Andrew Walbran40be9d52022-01-19 14:32:53 +000040use std::time::SystemTime;
Andrew Walbrancc0db522021-07-12 17:03:42 +000041use vmconfig::open_parcel_file;
42
43/// The list of APEXes which microdroid requires.
44// TODO(b/192200378) move this to microdroid.json?
Inseob Kimb4868e62021-11-09 17:28:23 +090045const MICRODROID_REQUIRED_APEXES: [&str; 1] = ["com.android.os.statsd"];
46const MICRODROID_REQUIRED_APEXES_DEBUG: [&str; 1] = ["com.android.adbd"];
Jooyung Han21e9b922021-06-26 04:14:16 +090047
Jooyung Han44b02ab2021-07-16 03:19:13 +090048const APEX_INFO_LIST_PATH: &str = "/apex/apex-info-list.xml";
49
Jooyung Han5dc42172021-10-05 16:43:47 +090050const PACKAGE_MANAGER_NATIVE_SERVICE: &str = "package_native";
51
Jooyung Han73bac242021-07-02 10:25:49 +090052/// Represents the list of APEXes
Jooyung Han743e0d62022-11-07 20:57:48 +090053#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
Jooyung Han9900f3d2021-07-06 10:27:54 +090054struct ApexInfoList {
Jooyung Han44b02ab2021-07-16 03:19:13 +090055 #[serde(rename = "apex-info")]
Jooyung Han73bac242021-07-02 10:25:49 +090056 list: Vec<ApexInfo>,
57}
58
Jooyung Han5ce867a2022-01-28 03:18:38 +090059#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
Jooyung Han73bac242021-07-02 10:25:49 +090060struct ApexInfo {
Jooyung Han44b02ab2021-07-16 03:19:13 +090061 #[serde(rename = "moduleName")]
Jooyung Han73bac242021-07-02 10:25:49 +090062 name: String,
Jooyung Han44b02ab2021-07-16 03:19:13 +090063 #[serde(rename = "modulePath")]
Jooyung Han73bac242021-07-02 10:25:49 +090064 path: PathBuf,
Jooyung Han9d7cd7d2021-10-12 17:44:14 +090065
66 #[serde(default)]
Alan Stokes46ac3862021-12-21 15:31:47 +000067 has_classpath_jar: bool,
Andrew Walbran40be9d52022-01-19 14:32:53 +000068
69 // The field claims to be milliseconds but is actually seconds.
70 #[serde(rename = "lastUpdateMillis")]
71 last_update_seconds: u64,
Jiyong Parkd6502352022-01-27 01:07:30 +090072
73 #[serde(rename = "isFactory")]
74 is_factory: bool,
Jooyung Hanec788042022-01-27 22:28:37 +090075
76 #[serde(rename = "isActive")]
77 is_active: bool,
Jooyung Han5ce867a2022-01-28 03:18:38 +090078
79 #[serde(rename = "provideSharedApexLibs")]
80 provide_shared_apex_libs: bool,
Jooyung Han73bac242021-07-02 10:25:49 +090081}
82
83impl ApexInfoList {
84 /// Loads ApexInfoList
Jooyung Han9900f3d2021-07-06 10:27:54 +090085 fn load() -> Result<&'static ApexInfoList> {
86 static INSTANCE: OnceCell<ApexInfoList> = OnceCell::new();
87 INSTANCE.get_or_try_init(|| {
Jooyung Han44b02ab2021-07-16 03:19:13 +090088 let apex_info_list = File::open(APEX_INFO_LIST_PATH)
89 .context(format!("Failed to open {}", APEX_INFO_LIST_PATH))?;
Jooyung Han9d7cd7d2021-10-12 17:44:14 +090090 let mut apex_info_list: ApexInfoList = from_reader(apex_info_list)
Jooyung Han44b02ab2021-07-16 03:19:13 +090091 .context(format!("Failed to parse {}", APEX_INFO_LIST_PATH))?;
Jooyung Han9d7cd7d2021-10-12 17:44:14 +090092
Alan Stokesbf20c6a2022-01-04 12:30:50 +000093 // For active APEXes, we run derive_classpath and parse its output to see if it
94 // contributes to the classpath(s). (This allows us to handle any new classpath env
95 // vars seamlessly.)
96 let classpath_vars = run_derive_classpath()?;
97 let classpath_apexes = find_apex_names_in_classpath(&classpath_vars)?;
98
Jooyung Han9d7cd7d2021-10-12 17:44:14 +090099 for apex_info in apex_info_list.list.iter_mut() {
Alan Stokesbf20c6a2022-01-04 12:30:50 +0000100 apex_info.has_classpath_jar = classpath_apexes.contains(&apex_info.name);
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900101 }
Alan Stokesbf20c6a2022-01-04 12:30:50 +0000102
Jooyung Han44b02ab2021-07-16 03:19:13 +0900103 Ok(apex_info_list)
Jooyung Han9900f3d2021-07-06 10:27:54 +0900104 })
Jooyung Han73bac242021-07-02 10:25:49 +0900105 }
Jooyung Han743e0d62022-11-07 20:57:48 +0900106
107 // Override apex info with the staged one
108 fn override_staged_apex(&mut self, staged_apex_info: &StagedApexInfo) -> Result<()> {
109 let mut need_to_add: Option<ApexInfo> = None;
110 for apex_info in self.list.iter_mut() {
111 if staged_apex_info.moduleName == apex_info.name {
112 if apex_info.is_active && apex_info.is_factory {
113 // Copy the entry to the end as factory/non-active after the loop
114 // to keep the factory version. Typically this step is unncessary,
115 // but some apexes (like sharedlibs) need to be kept even if it's inactive.
116 need_to_add.replace(ApexInfo { is_active: false, ..apex_info.clone() });
117 // And make this one as non-factory. Note that this one is still active
118 // and overridden right below.
119 apex_info.is_factory = false;
120 }
121 // Active one is overridden with the staged one.
122 if apex_info.is_active {
123 apex_info.path = PathBuf::from(&staged_apex_info.diskImagePath);
124 apex_info.has_classpath_jar = staged_apex_info.hasClassPathJars;
125 apex_info.last_update_seconds = last_updated(&apex_info.path)?;
126 }
127 }
128 }
129 if let Some(info) = need_to_add {
130 self.list.push(info);
131 }
132 Ok(())
133 }
134}
135
136fn last_updated<P: AsRef<Path>>(path: P) -> Result<u64> {
137 let metadata = metadata(path)?;
138 Ok(metadata.modified()?.duration_since(SystemTime::UNIX_EPOCH)?.as_secs())
Jooyung Hanec788042022-01-27 22:28:37 +0900139}
Jooyung Han73bac242021-07-02 10:25:49 +0900140
Jooyung Hanec788042022-01-27 22:28:37 +0900141impl ApexInfo {
142 fn matches(&self, apex_config: &ApexConfig) -> bool {
143 // Match with pseudo name "{CLASSPATH}" which represents APEXes contributing
144 // to any derive_classpath environment variable
145 if apex_config.name == "{CLASSPATH}" && self.has_classpath_jar {
146 return true;
147 }
148 if apex_config.name == self.name {
149 return true;
150 }
151 false
Jooyung Han73bac242021-07-02 10:25:49 +0900152 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900153}
154
Jooyung Han5dc42172021-10-05 16:43:47 +0900155struct PackageManager {
Jooyung Han5dc42172021-10-05 16:43:47 +0900156 apex_info_list: &'static ApexInfoList,
157}
158
159impl PackageManager {
160 fn new() -> Result<Self> {
Jooyung Han5dc42172021-10-05 16:43:47 +0900161 let apex_info_list = ApexInfoList::load()?;
Jooyung Han53cf7992021-10-18 19:38:41 +0900162 Ok(Self { apex_info_list })
Jooyung Han5dc42172021-10-05 16:43:47 +0900163 }
164
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900165 fn get_apex_list(&self, prefer_staged: bool) -> Result<ApexInfoList> {
Jooyung Han53cf7992021-10-18 19:38:41 +0900166 // get the list of active apexes
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900167 let mut list = self.apex_info_list.clone();
Jooyung Han53cf7992021-10-18 19:38:41 +0900168 // When prefer_staged, we override ApexInfo by consulting "package_native"
Jooyung Han5dc42172021-10-05 16:43:47 +0900169 if prefer_staged {
Jooyung Han53cf7992021-10-18 19:38:41 +0900170 let pm =
171 wait_for_interface::<dyn IPackageManagerNative>(PACKAGE_MANAGER_NATIVE_SERVICE)
172 .context("Failed to get service when prefer_staged is set.")?;
Alan Stokes70ccf162022-07-08 11:05:03 +0100173 let staged =
174 pm.getStagedApexModuleNames().context("getStagedApexModuleNames failed")?;
Jooyung Han743e0d62022-11-07 20:57:48 +0900175 for name in staged {
176 if let Some(staged_apex_info) =
177 pm.getStagedApexInfo(&name).context("getStagedApexInfo failed")?
178 {
179 list.override_staged_apex(&staged_apex_info)?;
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900180 }
Jooyung Han5dc42172021-10-05 16:43:47 +0900181 }
182 }
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900183 Ok(list)
Jooyung Han5dc42172021-10-05 16:43:47 +0900184 }
185}
186
Andrew Walbrancc0db522021-07-12 17:03:42 +0000187fn make_metadata_file(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100188 app_config: &VirtualMachineAppConfig,
Jooyung Hanec788042022-01-27 22:28:37 +0900189 apex_infos: &[&ApexInfo],
Jooyung Han21e9b922021-06-26 04:14:16 +0900190 temporary_directory: &Path,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000191) -> Result<ParcelFileDescriptor> {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100192 let payload_metadata = match &app_config.payload {
193 Payload::PayloadConfig(payload_config) => PayloadMetadata::config(PayloadConfig {
194 payload_binary_path: payload_config.payloadPath.clone(),
Alan Stokes0d1ef782022-09-27 13:46:35 +0100195 ..Default::default()
196 }),
197 Payload::ConfigPath(config_path) => {
198 PayloadMetadata::config_path(format!("/mnt/apk/{}", config_path))
199 }
200 };
201
Jooyung Han21e9b922021-06-26 04:14:16 +0900202 let metadata = Metadata {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000203 version: 1,
Jooyung Hanec788042022-01-27 22:28:37 +0900204 apexes: apex_infos
Jooyung Han21e9b922021-06-26 04:14:16 +0900205 .iter()
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900206 .enumerate()
Jooyung Hanec788042022-01-27 22:28:37 +0900207 .map(|(i, apex_info)| {
Andrew Walbran40be9d52022-01-19 14:32:53 +0000208 Ok(ApexPayload {
Jooyung Hanec788042022-01-27 22:28:37 +0900209 name: apex_info.name.clone(),
Andrew Walbran40be9d52022-01-19 14:32:53 +0000210 partition_name: format!("microdroid-apex-{}", i),
Jiyong Parkd6502352022-01-27 01:07:30 +0900211 last_update_seconds: apex_info.last_update_seconds,
212 is_factory: apex_info.is_factory,
Andrew Walbran40be9d52022-01-19 14:32:53 +0000213 ..Default::default()
214 })
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900215 })
Andrew Walbran40be9d52022-01-19 14:32:53 +0000216 .collect::<Result<_>>()?,
Jooyung Han21e9b922021-06-26 04:14:16 +0900217 apk: Some(ApkPayload {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900218 name: "apk".to_owned(),
219 payload_partition_name: "microdroid-apk".to_owned(),
220 idsig_partition_name: "microdroid-apk-idsig".to_owned(),
Jooyung Han21e9b922021-06-26 04:14:16 +0900221 ..Default::default()
222 })
223 .into(),
Alan Stokes0d1ef782022-09-27 13:46:35 +0100224 payload: Some(payload_metadata),
Jooyung Han21e9b922021-06-26 04:14:16 +0900225 ..Default::default()
226 };
Andrew Walbrancc0db522021-07-12 17:03:42 +0000227
228 // Write metadata to file.
Alan Stokes0d1ef782022-09-27 13:46:35 +0100229 let metadata_path = temporary_directory.join("metadata");
Andrew Walbrancc0db522021-07-12 17:03:42 +0000230 let mut metadata_file = OpenOptions::new()
231 .create_new(true)
232 .read(true)
233 .write(true)
234 .open(&metadata_path)
235 .with_context(|| format!("Failed to open metadata file {:?}", metadata_path))?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900236 microdroid_metadata::write_metadata(&metadata, &mut metadata_file)?;
237
Andrew Walbrancc0db522021-07-12 17:03:42 +0000238 // Re-open the metadata file as read-only.
239 open_parcel_file(&metadata_path, false)
240}
241
242/// Creates a DiskImage with partitions:
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100243/// payload-metadata: metadata
Andrew Walbrancc0db522021-07-12 17:03:42 +0000244/// microdroid-apex-0: apex 0
245/// microdroid-apex-1: apex 1
246/// ..
247/// microdroid-apk: apk
248/// microdroid-apk-idsig: idsig
Inseob Kima5a262f2021-11-17 19:41:03 +0900249/// extra-apk-0: additional apk 0
250/// extra-idsig-0: additional idsig 0
251/// extra-apk-1: additional apk 1
252/// extra-idsig-1: additional idsig 1
253/// ..
Andrew Walbrancc0db522021-07-12 17:03:42 +0000254fn make_payload_disk(
Inseob Kima5a262f2021-11-17 19:41:03 +0900255 app_config: &VirtualMachineAppConfig,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000256 apk_file: File,
257 idsig_file: File,
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900258 vm_payload_config: &VmPayloadConfig,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000259 temporary_directory: &Path,
260) -> Result<DiskImage> {
Inseob Kima5a262f2021-11-17 19:41:03 +0900261 if vm_payload_config.extra_apks.len() != app_config.extraIdsigs.len() {
262 bail!(
263 "payload config has {} apks, but app config has {} idsigs",
264 vm_payload_config.extra_apks.len(),
265 app_config.extraIdsigs.len()
266 );
267 }
268
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900269 let pm = PackageManager::new()?;
270 let apex_list = pm.get_apex_list(vm_payload_config.prefer_staged)?;
271
Jooyung Hanec788042022-01-27 22:28:37 +0900272 // collect APEXes from config
273 let apex_infos =
274 collect_apex_infos(&apex_list, &vm_payload_config.apexes, app_config.debugLevel);
275 info!("Microdroid payload APEXes: {:?}", apex_infos.iter().map(|ai| &ai.name));
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900276
Alan Stokes0d1ef782022-09-27 13:46:35 +0100277 let metadata_file = make_metadata_file(app_config, &apex_infos, temporary_directory)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900278 // put metadata at the first partition
279 let mut partitions = vec![Partition {
Jooyung Han14e5a8e2021-07-06 20:48:38 +0900280 label: "payload-metadata".to_owned(),
Jooyung Han631d5882021-07-29 06:34:05 +0900281 image: Some(metadata_file),
Jooyung Han21e9b922021-06-26 04:14:16 +0900282 writable: false,
283 }];
284
Jooyung Hanec788042022-01-27 22:28:37 +0900285 for (i, apex_info) in apex_infos.iter().enumerate() {
286 let apex_file = open_parcel_file(&apex_info.path, false)?;
Jooyung Han95884632021-07-06 22:27:54 +0900287 partitions.push(Partition {
288 label: format!("microdroid-apex-{}", i),
Jooyung Han631d5882021-07-29 06:34:05 +0900289 image: Some(apex_file),
Jooyung Han95884632021-07-06 22:27:54 +0900290 writable: false,
291 });
Jooyung Han21e9b922021-06-26 04:14:16 +0900292 }
Jooyung Han95884632021-07-06 22:27:54 +0900293 partitions.push(Partition {
294 label: "microdroid-apk".to_owned(),
Jooyung Han631d5882021-07-29 06:34:05 +0900295 image: Some(ParcelFileDescriptor::new(apk_file)),
Jooyung Han95884632021-07-06 22:27:54 +0900296 writable: false,
297 });
298 partitions.push(Partition {
299 label: "microdroid-apk-idsig".to_owned(),
Jooyung Han631d5882021-07-29 06:34:05 +0900300 image: Some(ParcelFileDescriptor::new(idsig_file)),
Jooyung Han95884632021-07-06 22:27:54 +0900301 writable: false,
302 });
Jooyung Han21e9b922021-06-26 04:14:16 +0900303
Inseob Kima5a262f2021-11-17 19:41:03 +0900304 // we've already checked that extra_apks and extraIdsigs are in the same size.
305 let extra_apks = &vm_payload_config.extra_apks;
306 let extra_idsigs = &app_config.extraIdsigs;
307 for (i, (extra_apk, extra_idsig)) in extra_apks.iter().zip(extra_idsigs.iter()).enumerate() {
308 partitions.push(Partition {
309 label: format!("extra-apk-{}", i),
Victor Hsieh14497f02022-09-21 10:10:16 -0700310 image: Some(ParcelFileDescriptor::new(
311 File::open(PathBuf::from(&extra_apk.path)).with_context(|| {
312 format!("Failed to open the extra apk #{} {}", i, extra_apk.path)
313 })?,
314 )),
Inseob Kima5a262f2021-11-17 19:41:03 +0900315 writable: false,
316 });
317
318 partitions.push(Partition {
319 label: format!("extra-idsig-{}", i),
Victor Hsieh14497f02022-09-21 10:10:16 -0700320 image: Some(ParcelFileDescriptor::new(
321 extra_idsig
322 .as_ref()
323 .try_clone()
324 .with_context(|| format!("Failed to clone the extra idsig #{}", i))?,
325 )),
Inseob Kima5a262f2021-11-17 19:41:03 +0900326 writable: false,
327 });
328 }
329
Jooyung Han21e9b922021-06-26 04:14:16 +0900330 Ok(DiskImage { image: None, partitions, writable: false })
331}
Andrew Walbrancc0db522021-07-12 17:03:42 +0000332
Alan Stokesbf20c6a2022-01-04 12:30:50 +0000333fn run_derive_classpath() -> Result<String> {
334 let result = Command::new("/apex/com.android.sdkext/bin/derive_classpath")
335 .arg("/proc/self/fd/1")
336 .output()
337 .context("Failed to run derive_classpath")?;
338
339 if !result.status.success() {
340 bail!("derive_classpath returned {}", result.status);
341 }
342
343 String::from_utf8(result.stdout).context("Converting derive_classpath output")
344}
345
346fn find_apex_names_in_classpath(classpath_vars: &str) -> Result<HashSet<String>> {
347 // Each line should be in the format "export <var name> <paths>", where <paths> is a
348 // colon-separated list of paths to JARs. We don't care about the var names, and we're only
349 // interested in paths that look like "/apex/<apex name>/<anything>" so we know which APEXes
350 // contribute to at least one var.
351 let mut apexes = HashSet::new();
352
353 let pattern = Regex::new(r"^export [^ ]+ ([^ ]+)$").context("Failed to construct Regex")?;
354 for line in classpath_vars.lines() {
355 if let Some(captures) = pattern.captures(line) {
356 if let Some(paths) = captures.get(1) {
357 apexes.extend(paths.as_str().split(':').filter_map(|path| {
358 let path = path.strip_prefix("/apex/")?;
359 Some(path[..path.find('/')?].to_owned())
360 }));
361 continue;
362 }
363 }
364 warn!("Malformed line from derive_classpath: {}", line);
365 }
366
367 Ok(apexes)
Jooyung Han5e0f2062021-10-12 14:00:46 +0900368}
369
Jooyung Hanec788042022-01-27 22:28:37 +0900370// Collect ApexInfos from VM config
371fn collect_apex_infos<'a>(
372 apex_list: &'a ApexInfoList,
373 apex_configs: &[ApexConfig],
Inseob Kimb4868e62021-11-09 17:28:23 +0900374 debug_level: DebugLevel,
Jooyung Hanec788042022-01-27 22:28:37 +0900375) -> Vec<&'a ApexInfo> {
376 let mut additional_apexes: Vec<&str> = MICRODROID_REQUIRED_APEXES.to_vec();
Inseob Kimb4868e62021-11-09 17:28:23 +0900377 if debug_level != DebugLevel::NONE {
Jooyung Hanec788042022-01-27 22:28:37 +0900378 additional_apexes.extend(MICRODROID_REQUIRED_APEXES_DEBUG.to_vec());
Inseob Kimb4868e62021-11-09 17:28:23 +0900379 }
Jooyung Hanec788042022-01-27 22:28:37 +0900380
381 apex_list
382 .list
383 .iter()
384 .filter(|ai| {
385 apex_configs.iter().any(|cfg| ai.matches(cfg) && ai.is_active)
386 || additional_apexes.iter().any(|name| name == &ai.name && ai.is_active)
Jooyung Han5ce867a2022-01-28 03:18:38 +0900387 || ai.provide_shared_apex_libs
Jooyung Hanec788042022-01-27 22:28:37 +0900388 })
389 .collect()
Jooyung Han5e0f2062021-10-12 14:00:46 +0900390}
391
Shikha Panwar22e70452022-10-10 18:32:55 +0000392pub fn add_microdroid_system_images(
Andrew Walbrancc0db522021-07-12 17:03:42 +0000393 config: &VirtualMachineAppConfig,
Jiyong Park8d081812021-07-23 17:45:04 +0900394 instance_file: File,
Shikha Panwar22e70452022-10-10 18:32:55 +0000395 storage_image: Option<File>,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000396 vm_config: &mut VirtualMachineRawConfig,
397) -> Result<()> {
Shikha Panwared8ace42022-09-28 12:52:16 +0000398 let debug_suffix = match config.debugLevel {
399 DebugLevel::NONE => "normal",
400 DebugLevel::APP_ONLY => "app_debuggable",
401 DebugLevel::FULL => "full_debuggable",
402 _ => return Err(anyhow!("unsupported debug level: {:?}", config.debugLevel)),
403 };
404 let initrd = format!("/apex/com.android.virt/etc/microdroid_initrd_{}.img", debug_suffix);
405 vm_config.initrd = Some(open_parcel_file(Path::new(&initrd), false)?);
406
Shikha Panwar22e70452022-10-10 18:32:55 +0000407 let mut writable_partitions = vec![Partition {
Shikha Panwared8ace42022-09-28 12:52:16 +0000408 label: "vm-instance".to_owned(),
409 image: Some(ParcelFileDescriptor::new(instance_file)),
410 writable: true,
Shikha Panwar22e70452022-10-10 18:32:55 +0000411 }];
412
413 if let Some(file) = storage_image {
414 writable_partitions.push(Partition {
415 label: "encrypted-storage".to_owned(),
416 image: Some(ParcelFileDescriptor::new(file)),
417 writable: true,
418 });
419 }
420
421 vm_config.disks.push(DiskImage {
422 image: None,
423 partitions: writable_partitions,
424 writable: true,
425 });
426
427 Ok(())
428}
429
430pub fn add_microdroid_payload_images(
431 config: &VirtualMachineAppConfig,
432 temporary_directory: &Path,
433 apk_file: File,
434 idsig_file: File,
435 vm_payload_config: &VmPayloadConfig,
436 vm_config: &mut VirtualMachineRawConfig,
437) -> Result<()> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000438 vm_config.disks.push(make_payload_disk(
Inseob Kima5a262f2021-11-17 19:41:03 +0900439 config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000440 apk_file,
441 idsig_file,
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900442 vm_payload_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000443 temporary_directory,
444 )?);
445
Andrew Walbrancc0db522021-07-12 17:03:42 +0000446 Ok(())
447}
Jooyung Han5e0f2062021-10-12 14:00:46 +0900448
449#[cfg(test)]
450mod tests {
451 use super::*;
Jooyung Han743e0d62022-11-07 20:57:48 +0900452 use tempfile::NamedTempFile;
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000453
Jooyung Han5e0f2062021-10-12 14:00:46 +0900454 #[test]
Alan Stokesbf20c6a2022-01-04 12:30:50 +0000455 fn test_find_apex_names_in_classpath() {
456 let vars = r#"
457export FOO /apex/unterminated
458export BAR /apex/valid.apex/something
459wrong
460export EMPTY
461export OTHER /foo/bar:/baz:/apex/second.valid.apex/:gibberish:"#;
462 let expected = vec!["valid.apex", "second.valid.apex"];
463 let expected: HashSet<_> = expected.into_iter().map(ToString::to_string).collect();
464
465 assert_eq!(find_apex_names_in_classpath(vars).unwrap(), expected);
Jooyung Han5e0f2062021-10-12 14:00:46 +0900466 }
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000467
468 #[test]
Jooyung Hanec788042022-01-27 22:28:37 +0900469 fn test_collect_apexes() {
470 let apex_info_list = ApexInfoList {
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000471 list: vec![
472 ApexInfo {
Jooyung Hanec788042022-01-27 22:28:37 +0900473 // 0
474 name: "com.android.adbd".to_string(),
475 path: PathBuf::from("adbd"),
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000476 has_classpath_jar: false,
Andrew Walbran40be9d52022-01-19 14:32:53 +0000477 last_update_seconds: 12345678,
Jiyong Parkd6502352022-01-27 01:07:30 +0900478 is_factory: true,
Jooyung Hanec788042022-01-27 22:28:37 +0900479 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900480 ..Default::default()
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000481 },
482 ApexInfo {
Jooyung Hanec788042022-01-27 22:28:37 +0900483 // 1
484 name: "com.android.os.statsd".to_string(),
485 path: PathBuf::from("statsd"),
486 has_classpath_jar: false,
487 last_update_seconds: 12345678,
488 is_factory: true,
489 is_active: false,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900490 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900491 },
492 ApexInfo {
493 // 2
494 name: "com.android.os.statsd".to_string(),
495 path: PathBuf::from("statsd/updated"),
496 has_classpath_jar: false,
497 last_update_seconds: 12345678 + 1,
498 is_factory: false,
499 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900500 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900501 },
502 ApexInfo {
503 // 3
504 name: "no_classpath".to_string(),
505 path: PathBuf::from("no_classpath"),
506 has_classpath_jar: false,
507 last_update_seconds: 12345678,
508 is_factory: true,
509 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900510 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900511 },
512 ApexInfo {
513 // 4
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000514 name: "has_classpath".to_string(),
Jooyung Hanec788042022-01-27 22:28:37 +0900515 path: PathBuf::from("has_classpath"),
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000516 has_classpath_jar: true,
Andrew Walbran40be9d52022-01-19 14:32:53 +0000517 last_update_seconds: 87654321,
Jooyung Hanec788042022-01-27 22:28:37 +0900518 is_factory: true,
519 is_active: false,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900520 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900521 },
522 ApexInfo {
523 // 5
524 name: "has_classpath".to_string(),
525 path: PathBuf::from("has_classpath/updated"),
526 has_classpath_jar: true,
527 last_update_seconds: 87654321 + 1,
Jiyong Parkd6502352022-01-27 01:07:30 +0900528 is_factory: false,
Jooyung Hanec788042022-01-27 22:28:37 +0900529 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900530 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900531 },
532 ApexInfo {
533 // 6
534 name: "apex-foo".to_string(),
535 path: PathBuf::from("apex-foo"),
536 has_classpath_jar: false,
537 last_update_seconds: 87654321,
538 is_factory: true,
539 is_active: false,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900540 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900541 },
542 ApexInfo {
543 // 7
544 name: "apex-foo".to_string(),
545 path: PathBuf::from("apex-foo/updated"),
546 has_classpath_jar: false,
547 last_update_seconds: 87654321 + 1,
548 is_factory: false,
549 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900550 ..Default::default()
551 },
552 ApexInfo {
553 // 8
554 name: "sharedlibs".to_string(),
555 path: PathBuf::from("apex-foo"),
556 last_update_seconds: 87654321,
557 is_factory: true,
558 provide_shared_apex_libs: true,
559 ..Default::default()
560 },
561 ApexInfo {
562 // 9
563 name: "sharedlibs".to_string(),
564 path: PathBuf::from("apex-foo/updated"),
565 last_update_seconds: 87654321 + 1,
566 is_active: true,
567 provide_shared_apex_libs: true,
568 ..Default::default()
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000569 },
570 ],
571 };
Jooyung Hanec788042022-01-27 22:28:37 +0900572 let apex_configs = vec![
573 ApexConfig { name: "apex-foo".to_string() },
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000574 ApexConfig { name: "{CLASSPATH}".to_string() },
575 ];
576 assert_eq!(
Jooyung Hanec788042022-01-27 22:28:37 +0900577 collect_apex_infos(&apex_info_list, &apex_configs, DebugLevel::FULL),
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000578 vec![
Jooyung Han5ce867a2022-01-28 03:18:38 +0900579 // Pass active/required APEXes
Jooyung Hanec788042022-01-27 22:28:37 +0900580 &apex_info_list.list[0],
581 &apex_info_list.list[2],
Jooyung Han5ce867a2022-01-28 03:18:38 +0900582 // Pass active APEXes specified in the config
Jooyung Hanec788042022-01-27 22:28:37 +0900583 &apex_info_list.list[5],
584 &apex_info_list.list[7],
Jooyung Han5ce867a2022-01-28 03:18:38 +0900585 // Pass both preinstalled(inactive) and updated(active) for "sharedlibs" APEXes
586 &apex_info_list.list[8],
587 &apex_info_list.list[9],
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000588 ]
589 );
590 }
Jooyung Han743e0d62022-11-07 20:57:48 +0900591
592 #[test]
593 fn test_prefer_staged_apex_with_factory_active_apex() {
594 let single_apex = ApexInfo {
595 name: "foo".to_string(),
596 path: PathBuf::from("foo.apex"),
597 is_factory: true,
598 is_active: true,
599 ..Default::default()
600 };
601 let mut apex_info_list = ApexInfoList { list: vec![single_apex.clone()] };
602
603 let staged = NamedTempFile::new().unwrap();
604 apex_info_list
605 .override_staged_apex(&StagedApexInfo {
606 moduleName: "foo".to_string(),
607 diskImagePath: staged.path().to_string_lossy().to_string(),
608 ..Default::default()
609 })
610 .expect("should be ok");
611
612 assert_eq!(
613 apex_info_list,
614 ApexInfoList {
615 list: vec![
616 ApexInfo {
617 is_factory: false,
618 path: staged.path().to_owned(),
619 last_update_seconds: last_updated(staged.path()).unwrap(),
620 ..single_apex.clone()
621 },
622 ApexInfo { is_active: false, ..single_apex },
623 ],
624 }
625 );
626 }
627
628 #[test]
629 fn test_prefer_staged_apex_with_factory_and_inactive_apex() {
630 let factory_apex = ApexInfo {
631 name: "foo".to_string(),
632 path: PathBuf::from("foo.apex"),
633 is_factory: true,
634 ..Default::default()
635 };
636 let active_apex = ApexInfo {
637 name: "foo".to_string(),
638 path: PathBuf::from("foo.downloaded.apex"),
639 is_active: true,
640 ..Default::default()
641 };
642 let mut apex_info_list =
643 ApexInfoList { list: vec![factory_apex.clone(), active_apex.clone()] };
644
645 let staged = NamedTempFile::new().unwrap();
646 apex_info_list
647 .override_staged_apex(&StagedApexInfo {
648 moduleName: "foo".to_string(),
649 diskImagePath: staged.path().to_string_lossy().to_string(),
650 ..Default::default()
651 })
652 .expect("should be ok");
653
654 assert_eq!(
655 apex_info_list,
656 ApexInfoList {
657 list: vec![
658 // factory apex isn't touched
659 factory_apex,
660 // update active one
661 ApexInfo {
662 path: staged.path().to_owned(),
663 last_update_seconds: last_updated(staged.path()).unwrap(),
664 ..active_apex
665 },
666 ],
667 }
668 );
669 }
Jooyung Han5e0f2062021-10-12 14:00:46 +0900670}