blob: 02e8f8ef66a535f87f2cf10295ede97b073c6c60 [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 Hancaa995c2022-11-08 16:35:50 +090063 #[serde(rename = "versionCode")]
64 version: u64,
Jooyung Han44b02ab2021-07-16 03:19:13 +090065 #[serde(rename = "modulePath")]
Jooyung Han73bac242021-07-02 10:25:49 +090066 path: PathBuf,
Jooyung Han9d7cd7d2021-10-12 17:44:14 +090067
68 #[serde(default)]
Alan Stokes46ac3862021-12-21 15:31:47 +000069 has_classpath_jar: bool,
Andrew Walbran40be9d52022-01-19 14:32:53 +000070
71 // The field claims to be milliseconds but is actually seconds.
72 #[serde(rename = "lastUpdateMillis")]
73 last_update_seconds: u64,
Jiyong Parkd6502352022-01-27 01:07:30 +090074
75 #[serde(rename = "isFactory")]
76 is_factory: bool,
Jooyung Hanec788042022-01-27 22:28:37 +090077
78 #[serde(rename = "isActive")]
79 is_active: bool,
Jooyung Han5ce867a2022-01-28 03:18:38 +090080
81 #[serde(rename = "provideSharedApexLibs")]
82 provide_shared_apex_libs: bool,
Jooyung Han73bac242021-07-02 10:25:49 +090083}
84
85impl ApexInfoList {
86 /// Loads ApexInfoList
Jooyung Han9900f3d2021-07-06 10:27:54 +090087 fn load() -> Result<&'static ApexInfoList> {
88 static INSTANCE: OnceCell<ApexInfoList> = OnceCell::new();
89 INSTANCE.get_or_try_init(|| {
Jooyung Han44b02ab2021-07-16 03:19:13 +090090 let apex_info_list = File::open(APEX_INFO_LIST_PATH)
91 .context(format!("Failed to open {}", APEX_INFO_LIST_PATH))?;
Jooyung Han9d7cd7d2021-10-12 17:44:14 +090092 let mut apex_info_list: ApexInfoList = from_reader(apex_info_list)
Jooyung Han44b02ab2021-07-16 03:19:13 +090093 .context(format!("Failed to parse {}", APEX_INFO_LIST_PATH))?;
Jooyung Han9d7cd7d2021-10-12 17:44:14 +090094
Alan Stokesbf20c6a2022-01-04 12:30:50 +000095 // For active APEXes, we run derive_classpath and parse its output to see if it
96 // contributes to the classpath(s). (This allows us to handle any new classpath env
97 // vars seamlessly.)
98 let classpath_vars = run_derive_classpath()?;
99 let classpath_apexes = find_apex_names_in_classpath(&classpath_vars)?;
100
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900101 for apex_info in apex_info_list.list.iter_mut() {
Alan Stokesbf20c6a2022-01-04 12:30:50 +0000102 apex_info.has_classpath_jar = classpath_apexes.contains(&apex_info.name);
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900103 }
Alan Stokesbf20c6a2022-01-04 12:30:50 +0000104
Jooyung Han44b02ab2021-07-16 03:19:13 +0900105 Ok(apex_info_list)
Jooyung Han9900f3d2021-07-06 10:27:54 +0900106 })
Jooyung Han73bac242021-07-02 10:25:49 +0900107 }
Jooyung Han743e0d62022-11-07 20:57:48 +0900108
109 // Override apex info with the staged one
110 fn override_staged_apex(&mut self, staged_apex_info: &StagedApexInfo) -> Result<()> {
111 let mut need_to_add: Option<ApexInfo> = None;
112 for apex_info in self.list.iter_mut() {
113 if staged_apex_info.moduleName == apex_info.name {
114 if apex_info.is_active && apex_info.is_factory {
115 // Copy the entry to the end as factory/non-active after the loop
116 // to keep the factory version. Typically this step is unncessary,
117 // but some apexes (like sharedlibs) need to be kept even if it's inactive.
118 need_to_add.replace(ApexInfo { is_active: false, ..apex_info.clone() });
119 // And make this one as non-factory. Note that this one is still active
120 // and overridden right below.
121 apex_info.is_factory = false;
122 }
123 // Active one is overridden with the staged one.
124 if apex_info.is_active {
Jooyung Hancaa995c2022-11-08 16:35:50 +0900125 apex_info.version = staged_apex_info.versionCode as u64;
Jooyung Han743e0d62022-11-07 20:57:48 +0900126 apex_info.path = PathBuf::from(&staged_apex_info.diskImagePath);
127 apex_info.has_classpath_jar = staged_apex_info.hasClassPathJars;
128 apex_info.last_update_seconds = last_updated(&apex_info.path)?;
129 }
130 }
131 }
132 if let Some(info) = need_to_add {
133 self.list.push(info);
134 }
135 Ok(())
136 }
137}
138
139fn last_updated<P: AsRef<Path>>(path: P) -> Result<u64> {
140 let metadata = metadata(path)?;
141 Ok(metadata.modified()?.duration_since(SystemTime::UNIX_EPOCH)?.as_secs())
Jooyung Hanec788042022-01-27 22:28:37 +0900142}
Jooyung Han73bac242021-07-02 10:25:49 +0900143
Jooyung Hanec788042022-01-27 22:28:37 +0900144impl ApexInfo {
145 fn matches(&self, apex_config: &ApexConfig) -> bool {
146 // Match with pseudo name "{CLASSPATH}" which represents APEXes contributing
147 // to any derive_classpath environment variable
148 if apex_config.name == "{CLASSPATH}" && self.has_classpath_jar {
149 return true;
150 }
151 if apex_config.name == self.name {
152 return true;
153 }
154 false
Jooyung Han73bac242021-07-02 10:25:49 +0900155 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900156}
157
Jooyung Han5dc42172021-10-05 16:43:47 +0900158struct PackageManager {
Jooyung Han5dc42172021-10-05 16:43:47 +0900159 apex_info_list: &'static ApexInfoList,
160}
161
162impl PackageManager {
163 fn new() -> Result<Self> {
Jooyung Han5dc42172021-10-05 16:43:47 +0900164 let apex_info_list = ApexInfoList::load()?;
Jooyung Han53cf7992021-10-18 19:38:41 +0900165 Ok(Self { apex_info_list })
Jooyung Han5dc42172021-10-05 16:43:47 +0900166 }
167
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900168 fn get_apex_list(&self, prefer_staged: bool) -> Result<ApexInfoList> {
Jooyung Han53cf7992021-10-18 19:38:41 +0900169 // get the list of active apexes
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900170 let mut list = self.apex_info_list.clone();
Jooyung Han53cf7992021-10-18 19:38:41 +0900171 // When prefer_staged, we override ApexInfo by consulting "package_native"
Jooyung Han5dc42172021-10-05 16:43:47 +0900172 if prefer_staged {
Jooyung Han53cf7992021-10-18 19:38:41 +0900173 let pm =
174 wait_for_interface::<dyn IPackageManagerNative>(PACKAGE_MANAGER_NATIVE_SERVICE)
175 .context("Failed to get service when prefer_staged is set.")?;
Alan Stokes70ccf162022-07-08 11:05:03 +0100176 let staged =
177 pm.getStagedApexModuleNames().context("getStagedApexModuleNames failed")?;
Jooyung Han743e0d62022-11-07 20:57:48 +0900178 for name in staged {
179 if let Some(staged_apex_info) =
180 pm.getStagedApexInfo(&name).context("getStagedApexInfo failed")?
181 {
182 list.override_staged_apex(&staged_apex_info)?;
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900183 }
Jooyung Han5dc42172021-10-05 16:43:47 +0900184 }
185 }
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900186 Ok(list)
Jooyung Han5dc42172021-10-05 16:43:47 +0900187 }
188}
189
Andrew Walbrancc0db522021-07-12 17:03:42 +0000190fn make_metadata_file(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100191 app_config: &VirtualMachineAppConfig,
Jooyung Hanec788042022-01-27 22:28:37 +0900192 apex_infos: &[&ApexInfo],
Jooyung Han21e9b922021-06-26 04:14:16 +0900193 temporary_directory: &Path,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000194) -> Result<ParcelFileDescriptor> {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100195 let payload_metadata = match &app_config.payload {
196 Payload::PayloadConfig(payload_config) => PayloadMetadata::config(PayloadConfig {
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000197 payload_binary_name: payload_config.payloadBinaryName.clone(),
Alan Stokes0d1ef782022-09-27 13:46:35 +0100198 ..Default::default()
199 }),
200 Payload::ConfigPath(config_path) => {
201 PayloadMetadata::config_path(format!("/mnt/apk/{}", config_path))
202 }
203 };
204
Jooyung Han21e9b922021-06-26 04:14:16 +0900205 let metadata = Metadata {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000206 version: 1,
Jooyung Hanec788042022-01-27 22:28:37 +0900207 apexes: apex_infos
Jooyung Han21e9b922021-06-26 04:14:16 +0900208 .iter()
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900209 .enumerate()
Jooyung Hanec788042022-01-27 22:28:37 +0900210 .map(|(i, apex_info)| {
Andrew Walbran40be9d52022-01-19 14:32:53 +0000211 Ok(ApexPayload {
Jooyung Hanec788042022-01-27 22:28:37 +0900212 name: apex_info.name.clone(),
Andrew Walbran40be9d52022-01-19 14:32:53 +0000213 partition_name: format!("microdroid-apex-{}", i),
Jiyong Parkd6502352022-01-27 01:07:30 +0900214 last_update_seconds: apex_info.last_update_seconds,
215 is_factory: apex_info.is_factory,
Andrew Walbran40be9d52022-01-19 14:32:53 +0000216 ..Default::default()
217 })
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900218 })
Andrew Walbran40be9d52022-01-19 14:32:53 +0000219 .collect::<Result<_>>()?,
Jooyung Han21e9b922021-06-26 04:14:16 +0900220 apk: Some(ApkPayload {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900221 name: "apk".to_owned(),
222 payload_partition_name: "microdroid-apk".to_owned(),
223 idsig_partition_name: "microdroid-apk-idsig".to_owned(),
Jooyung Han21e9b922021-06-26 04:14:16 +0900224 ..Default::default()
225 })
226 .into(),
Alan Stokes0d1ef782022-09-27 13:46:35 +0100227 payload: Some(payload_metadata),
Jooyung Han21e9b922021-06-26 04:14:16 +0900228 ..Default::default()
229 };
Andrew Walbrancc0db522021-07-12 17:03:42 +0000230
231 // Write metadata to file.
Alan Stokes0d1ef782022-09-27 13:46:35 +0100232 let metadata_path = temporary_directory.join("metadata");
Andrew Walbrancc0db522021-07-12 17:03:42 +0000233 let mut metadata_file = OpenOptions::new()
234 .create_new(true)
235 .read(true)
236 .write(true)
237 .open(&metadata_path)
238 .with_context(|| format!("Failed to open metadata file {:?}", metadata_path))?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900239 microdroid_metadata::write_metadata(&metadata, &mut metadata_file)?;
240
Andrew Walbrancc0db522021-07-12 17:03:42 +0000241 // Re-open the metadata file as read-only.
242 open_parcel_file(&metadata_path, false)
243}
244
245/// Creates a DiskImage with partitions:
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100246/// payload-metadata: metadata
Andrew Walbrancc0db522021-07-12 17:03:42 +0000247/// microdroid-apex-0: apex 0
248/// microdroid-apex-1: apex 1
249/// ..
250/// microdroid-apk: apk
251/// microdroid-apk-idsig: idsig
Inseob Kima5a262f2021-11-17 19:41:03 +0900252/// extra-apk-0: additional apk 0
253/// extra-idsig-0: additional idsig 0
254/// extra-apk-1: additional apk 1
255/// extra-idsig-1: additional idsig 1
256/// ..
Andrew Walbrancc0db522021-07-12 17:03:42 +0000257fn make_payload_disk(
Inseob Kima5a262f2021-11-17 19:41:03 +0900258 app_config: &VirtualMachineAppConfig,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000259 apk_file: File,
260 idsig_file: File,
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900261 vm_payload_config: &VmPayloadConfig,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000262 temporary_directory: &Path,
263) -> Result<DiskImage> {
Inseob Kima5a262f2021-11-17 19:41:03 +0900264 if vm_payload_config.extra_apks.len() != app_config.extraIdsigs.len() {
265 bail!(
266 "payload config has {} apks, but app config has {} idsigs",
267 vm_payload_config.extra_apks.len(),
268 app_config.extraIdsigs.len()
269 );
270 }
271
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900272 let pm = PackageManager::new()?;
273 let apex_list = pm.get_apex_list(vm_payload_config.prefer_staged)?;
274
Jooyung Hanec788042022-01-27 22:28:37 +0900275 // collect APEXes from config
Jooyung Hancaa995c2022-11-08 16:35:50 +0900276 let mut apex_infos =
Jooyung Hanec788042022-01-27 22:28:37 +0900277 collect_apex_infos(&apex_list, &vm_payload_config.apexes, app_config.debugLevel);
Jooyung Hancaa995c2022-11-08 16:35:50 +0900278
279 // Pass sorted list of apexes. Sorting key shouldn't use `path` because it will change after
280 // reboot with prefer_staged. `last_update_seconds` is added to distinguish "samegrade"
281 // update.
282 apex_infos.sort_by_key(|info| (&info.name, &info.version, &info.last_update_seconds));
Jooyung Hanec788042022-01-27 22:28:37 +0900283 info!("Microdroid payload APEXes: {:?}", apex_infos.iter().map(|ai| &ai.name));
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900284
Alan Stokes0d1ef782022-09-27 13:46:35 +0100285 let metadata_file = make_metadata_file(app_config, &apex_infos, temporary_directory)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900286 // put metadata at the first partition
287 let mut partitions = vec![Partition {
Jooyung Han14e5a8e2021-07-06 20:48:38 +0900288 label: "payload-metadata".to_owned(),
Jooyung Han631d5882021-07-29 06:34:05 +0900289 image: Some(metadata_file),
Jooyung Han21e9b922021-06-26 04:14:16 +0900290 writable: false,
291 }];
292
Jooyung Hanec788042022-01-27 22:28:37 +0900293 for (i, apex_info) in apex_infos.iter().enumerate() {
294 let apex_file = open_parcel_file(&apex_info.path, false)?;
Jooyung Han95884632021-07-06 22:27:54 +0900295 partitions.push(Partition {
296 label: format!("microdroid-apex-{}", i),
Jooyung Han631d5882021-07-29 06:34:05 +0900297 image: Some(apex_file),
Jooyung Han95884632021-07-06 22:27:54 +0900298 writable: false,
299 });
Jooyung Han21e9b922021-06-26 04:14:16 +0900300 }
Jooyung Han95884632021-07-06 22:27:54 +0900301 partitions.push(Partition {
302 label: "microdroid-apk".to_owned(),
Jooyung Han631d5882021-07-29 06:34:05 +0900303 image: Some(ParcelFileDescriptor::new(apk_file)),
Jooyung Han95884632021-07-06 22:27:54 +0900304 writable: false,
305 });
306 partitions.push(Partition {
307 label: "microdroid-apk-idsig".to_owned(),
Jooyung Han631d5882021-07-29 06:34:05 +0900308 image: Some(ParcelFileDescriptor::new(idsig_file)),
Jooyung Han95884632021-07-06 22:27:54 +0900309 writable: false,
310 });
Jooyung Han21e9b922021-06-26 04:14:16 +0900311
Inseob Kima5a262f2021-11-17 19:41:03 +0900312 // we've already checked that extra_apks and extraIdsigs are in the same size.
313 let extra_apks = &vm_payload_config.extra_apks;
314 let extra_idsigs = &app_config.extraIdsigs;
315 for (i, (extra_apk, extra_idsig)) in extra_apks.iter().zip(extra_idsigs.iter()).enumerate() {
316 partitions.push(Partition {
317 label: format!("extra-apk-{}", i),
Victor Hsieh14497f02022-09-21 10:10:16 -0700318 image: Some(ParcelFileDescriptor::new(
319 File::open(PathBuf::from(&extra_apk.path)).with_context(|| {
320 format!("Failed to open the extra apk #{} {}", i, extra_apk.path)
321 })?,
322 )),
Inseob Kima5a262f2021-11-17 19:41:03 +0900323 writable: false,
324 });
325
326 partitions.push(Partition {
327 label: format!("extra-idsig-{}", i),
Victor Hsieh14497f02022-09-21 10:10:16 -0700328 image: Some(ParcelFileDescriptor::new(
329 extra_idsig
330 .as_ref()
331 .try_clone()
332 .with_context(|| format!("Failed to clone the extra idsig #{}", i))?,
333 )),
Inseob Kima5a262f2021-11-17 19:41:03 +0900334 writable: false,
335 });
336 }
337
Jooyung Han21e9b922021-06-26 04:14:16 +0900338 Ok(DiskImage { image: None, partitions, writable: false })
339}
Andrew Walbrancc0db522021-07-12 17:03:42 +0000340
Alan Stokesbf20c6a2022-01-04 12:30:50 +0000341fn run_derive_classpath() -> Result<String> {
342 let result = Command::new("/apex/com.android.sdkext/bin/derive_classpath")
343 .arg("/proc/self/fd/1")
344 .output()
345 .context("Failed to run derive_classpath")?;
346
347 if !result.status.success() {
348 bail!("derive_classpath returned {}", result.status);
349 }
350
351 String::from_utf8(result.stdout).context("Converting derive_classpath output")
352}
353
354fn find_apex_names_in_classpath(classpath_vars: &str) -> Result<HashSet<String>> {
355 // Each line should be in the format "export <var name> <paths>", where <paths> is a
356 // colon-separated list of paths to JARs. We don't care about the var names, and we're only
357 // interested in paths that look like "/apex/<apex name>/<anything>" so we know which APEXes
358 // contribute to at least one var.
359 let mut apexes = HashSet::new();
360
361 let pattern = Regex::new(r"^export [^ ]+ ([^ ]+)$").context("Failed to construct Regex")?;
362 for line in classpath_vars.lines() {
363 if let Some(captures) = pattern.captures(line) {
364 if let Some(paths) = captures.get(1) {
365 apexes.extend(paths.as_str().split(':').filter_map(|path| {
366 let path = path.strip_prefix("/apex/")?;
367 Some(path[..path.find('/')?].to_owned())
368 }));
369 continue;
370 }
371 }
372 warn!("Malformed line from derive_classpath: {}", line);
373 }
374
375 Ok(apexes)
Jooyung Han5e0f2062021-10-12 14:00:46 +0900376}
377
Jooyung Hanec788042022-01-27 22:28:37 +0900378// Collect ApexInfos from VM config
379fn collect_apex_infos<'a>(
380 apex_list: &'a ApexInfoList,
381 apex_configs: &[ApexConfig],
Inseob Kimb4868e62021-11-09 17:28:23 +0900382 debug_level: DebugLevel,
Jooyung Hanec788042022-01-27 22:28:37 +0900383) -> Vec<&'a ApexInfo> {
384 let mut additional_apexes: Vec<&str> = MICRODROID_REQUIRED_APEXES.to_vec();
Inseob Kimb4868e62021-11-09 17:28:23 +0900385 if debug_level != DebugLevel::NONE {
Jooyung Hanec788042022-01-27 22:28:37 +0900386 additional_apexes.extend(MICRODROID_REQUIRED_APEXES_DEBUG.to_vec());
Inseob Kimb4868e62021-11-09 17:28:23 +0900387 }
Jooyung Hanec788042022-01-27 22:28:37 +0900388
389 apex_list
390 .list
391 .iter()
392 .filter(|ai| {
393 apex_configs.iter().any(|cfg| ai.matches(cfg) && ai.is_active)
394 || additional_apexes.iter().any(|name| name == &ai.name && ai.is_active)
Jooyung Han5ce867a2022-01-28 03:18:38 +0900395 || ai.provide_shared_apex_libs
Jooyung Hanec788042022-01-27 22:28:37 +0900396 })
397 .collect()
Jooyung Han5e0f2062021-10-12 14:00:46 +0900398}
399
Shikha Panwar22e70452022-10-10 18:32:55 +0000400pub fn add_microdroid_system_images(
Andrew Walbrancc0db522021-07-12 17:03:42 +0000401 config: &VirtualMachineAppConfig,
Jiyong Park8d081812021-07-23 17:45:04 +0900402 instance_file: File,
Shikha Panwar22e70452022-10-10 18:32:55 +0000403 storage_image: Option<File>,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000404 vm_config: &mut VirtualMachineRawConfig,
405) -> Result<()> {
Shikha Panwared8ace42022-09-28 12:52:16 +0000406 let debug_suffix = match config.debugLevel {
407 DebugLevel::NONE => "normal",
Seungjae Yooe85831e2022-12-12 09:34:58 +0900408 DebugLevel::FULL => "debuggable",
Shikha Panwared8ace42022-09-28 12:52:16 +0000409 _ => return Err(anyhow!("unsupported debug level: {:?}", config.debugLevel)),
410 };
411 let initrd = format!("/apex/com.android.virt/etc/microdroid_initrd_{}.img", debug_suffix);
412 vm_config.initrd = Some(open_parcel_file(Path::new(&initrd), false)?);
413
Shikha Panwar22e70452022-10-10 18:32:55 +0000414 let mut writable_partitions = vec![Partition {
Shikha Panwared8ace42022-09-28 12:52:16 +0000415 label: "vm-instance".to_owned(),
416 image: Some(ParcelFileDescriptor::new(instance_file)),
417 writable: true,
Shikha Panwar22e70452022-10-10 18:32:55 +0000418 }];
419
420 if let Some(file) = storage_image {
421 writable_partitions.push(Partition {
Shikha Panwar566c9672022-11-15 14:39:58 +0000422 label: "encryptedstore".to_owned(),
Shikha Panwar22e70452022-10-10 18:32:55 +0000423 image: Some(ParcelFileDescriptor::new(file)),
424 writable: true,
425 });
426 }
427
428 vm_config.disks.push(DiskImage {
429 image: None,
430 partitions: writable_partitions,
431 writable: true,
432 });
433
434 Ok(())
435}
436
437pub fn add_microdroid_payload_images(
438 config: &VirtualMachineAppConfig,
439 temporary_directory: &Path,
440 apk_file: File,
441 idsig_file: File,
442 vm_payload_config: &VmPayloadConfig,
443 vm_config: &mut VirtualMachineRawConfig,
444) -> Result<()> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000445 vm_config.disks.push(make_payload_disk(
Inseob Kima5a262f2021-11-17 19:41:03 +0900446 config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000447 apk_file,
448 idsig_file,
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900449 vm_payload_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000450 temporary_directory,
451 )?);
452
Andrew Walbrancc0db522021-07-12 17:03:42 +0000453 Ok(())
454}
Jooyung Han5e0f2062021-10-12 14:00:46 +0900455
456#[cfg(test)]
457mod tests {
458 use super::*;
Jooyung Han743e0d62022-11-07 20:57:48 +0900459 use tempfile::NamedTempFile;
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000460
Jooyung Han5e0f2062021-10-12 14:00:46 +0900461 #[test]
Alan Stokesbf20c6a2022-01-04 12:30:50 +0000462 fn test_find_apex_names_in_classpath() {
463 let vars = r#"
464export FOO /apex/unterminated
465export BAR /apex/valid.apex/something
466wrong
467export EMPTY
468export OTHER /foo/bar:/baz:/apex/second.valid.apex/:gibberish:"#;
469 let expected = vec!["valid.apex", "second.valid.apex"];
470 let expected: HashSet<_> = expected.into_iter().map(ToString::to_string).collect();
471
472 assert_eq!(find_apex_names_in_classpath(vars).unwrap(), expected);
Jooyung Han5e0f2062021-10-12 14:00:46 +0900473 }
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000474
475 #[test]
Jooyung Hanec788042022-01-27 22:28:37 +0900476 fn test_collect_apexes() {
477 let apex_info_list = ApexInfoList {
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000478 list: vec![
479 ApexInfo {
Jooyung Hanec788042022-01-27 22:28:37 +0900480 // 0
481 name: "com.android.adbd".to_string(),
482 path: PathBuf::from("adbd"),
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000483 has_classpath_jar: false,
Andrew Walbran40be9d52022-01-19 14:32:53 +0000484 last_update_seconds: 12345678,
Jiyong Parkd6502352022-01-27 01:07:30 +0900485 is_factory: true,
Jooyung Hanec788042022-01-27 22:28:37 +0900486 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900487 ..Default::default()
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000488 },
489 ApexInfo {
Jooyung Hanec788042022-01-27 22:28:37 +0900490 // 1
491 name: "com.android.os.statsd".to_string(),
492 path: PathBuf::from("statsd"),
493 has_classpath_jar: false,
494 last_update_seconds: 12345678,
495 is_factory: true,
496 is_active: false,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900497 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900498 },
499 ApexInfo {
500 // 2
501 name: "com.android.os.statsd".to_string(),
502 path: PathBuf::from("statsd/updated"),
503 has_classpath_jar: false,
504 last_update_seconds: 12345678 + 1,
505 is_factory: false,
506 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900507 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900508 },
509 ApexInfo {
510 // 3
511 name: "no_classpath".to_string(),
512 path: PathBuf::from("no_classpath"),
513 has_classpath_jar: false,
514 last_update_seconds: 12345678,
515 is_factory: true,
516 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900517 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900518 },
519 ApexInfo {
520 // 4
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000521 name: "has_classpath".to_string(),
Jooyung Hanec788042022-01-27 22:28:37 +0900522 path: PathBuf::from("has_classpath"),
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000523 has_classpath_jar: true,
Andrew Walbran40be9d52022-01-19 14:32:53 +0000524 last_update_seconds: 87654321,
Jooyung Hanec788042022-01-27 22:28:37 +0900525 is_factory: true,
526 is_active: false,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900527 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900528 },
529 ApexInfo {
530 // 5
531 name: "has_classpath".to_string(),
532 path: PathBuf::from("has_classpath/updated"),
533 has_classpath_jar: true,
534 last_update_seconds: 87654321 + 1,
Jiyong Parkd6502352022-01-27 01:07:30 +0900535 is_factory: false,
Jooyung Hanec788042022-01-27 22:28:37 +0900536 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900537 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900538 },
539 ApexInfo {
540 // 6
541 name: "apex-foo".to_string(),
542 path: PathBuf::from("apex-foo"),
543 has_classpath_jar: false,
544 last_update_seconds: 87654321,
545 is_factory: true,
546 is_active: false,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900547 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900548 },
549 ApexInfo {
550 // 7
551 name: "apex-foo".to_string(),
552 path: PathBuf::from("apex-foo/updated"),
553 has_classpath_jar: false,
554 last_update_seconds: 87654321 + 1,
555 is_factory: false,
556 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900557 ..Default::default()
558 },
559 ApexInfo {
560 // 8
561 name: "sharedlibs".to_string(),
562 path: PathBuf::from("apex-foo"),
563 last_update_seconds: 87654321,
564 is_factory: true,
565 provide_shared_apex_libs: true,
566 ..Default::default()
567 },
568 ApexInfo {
569 // 9
570 name: "sharedlibs".to_string(),
571 path: PathBuf::from("apex-foo/updated"),
572 last_update_seconds: 87654321 + 1,
573 is_active: true,
574 provide_shared_apex_libs: true,
575 ..Default::default()
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000576 },
577 ],
578 };
Jooyung Hanec788042022-01-27 22:28:37 +0900579 let apex_configs = vec![
580 ApexConfig { name: "apex-foo".to_string() },
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000581 ApexConfig { name: "{CLASSPATH}".to_string() },
582 ];
583 assert_eq!(
Jooyung Hanec788042022-01-27 22:28:37 +0900584 collect_apex_infos(&apex_info_list, &apex_configs, DebugLevel::FULL),
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000585 vec![
Jooyung Han5ce867a2022-01-28 03:18:38 +0900586 // Pass active/required APEXes
Jooyung Hanec788042022-01-27 22:28:37 +0900587 &apex_info_list.list[0],
588 &apex_info_list.list[2],
Jooyung Han5ce867a2022-01-28 03:18:38 +0900589 // Pass active APEXes specified in the config
Jooyung Hanec788042022-01-27 22:28:37 +0900590 &apex_info_list.list[5],
591 &apex_info_list.list[7],
Jooyung Han5ce867a2022-01-28 03:18:38 +0900592 // Pass both preinstalled(inactive) and updated(active) for "sharedlibs" APEXes
593 &apex_info_list.list[8],
594 &apex_info_list.list[9],
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000595 ]
596 );
597 }
Jooyung Han743e0d62022-11-07 20:57:48 +0900598
599 #[test]
600 fn test_prefer_staged_apex_with_factory_active_apex() {
601 let single_apex = ApexInfo {
602 name: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900603 version: 1,
Jooyung Han743e0d62022-11-07 20:57:48 +0900604 path: PathBuf::from("foo.apex"),
605 is_factory: true,
606 is_active: true,
607 ..Default::default()
608 };
609 let mut apex_info_list = ApexInfoList { list: vec![single_apex.clone()] };
610
611 let staged = NamedTempFile::new().unwrap();
612 apex_info_list
613 .override_staged_apex(&StagedApexInfo {
614 moduleName: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900615 versionCode: 2,
Jooyung Han743e0d62022-11-07 20:57:48 +0900616 diskImagePath: staged.path().to_string_lossy().to_string(),
617 ..Default::default()
618 })
619 .expect("should be ok");
620
621 assert_eq!(
622 apex_info_list,
623 ApexInfoList {
624 list: vec![
625 ApexInfo {
Jooyung Hancaa995c2022-11-08 16:35:50 +0900626 version: 2,
Jooyung Han743e0d62022-11-07 20:57:48 +0900627 is_factory: false,
628 path: staged.path().to_owned(),
629 last_update_seconds: last_updated(staged.path()).unwrap(),
630 ..single_apex.clone()
631 },
632 ApexInfo { is_active: false, ..single_apex },
633 ],
634 }
635 );
636 }
637
638 #[test]
639 fn test_prefer_staged_apex_with_factory_and_inactive_apex() {
640 let factory_apex = ApexInfo {
641 name: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900642 version: 1,
Jooyung Han743e0d62022-11-07 20:57:48 +0900643 path: PathBuf::from("foo.apex"),
644 is_factory: true,
645 ..Default::default()
646 };
647 let active_apex = ApexInfo {
648 name: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900649 version: 2,
Jooyung Han743e0d62022-11-07 20:57:48 +0900650 path: PathBuf::from("foo.downloaded.apex"),
651 is_active: true,
652 ..Default::default()
653 };
654 let mut apex_info_list =
655 ApexInfoList { list: vec![factory_apex.clone(), active_apex.clone()] };
656
657 let staged = NamedTempFile::new().unwrap();
658 apex_info_list
659 .override_staged_apex(&StagedApexInfo {
660 moduleName: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900661 versionCode: 3,
Jooyung Han743e0d62022-11-07 20:57:48 +0900662 diskImagePath: staged.path().to_string_lossy().to_string(),
663 ..Default::default()
664 })
665 .expect("should be ok");
666
667 assert_eq!(
668 apex_info_list,
669 ApexInfoList {
670 list: vec![
671 // factory apex isn't touched
672 factory_apex,
673 // update active one
674 ApexInfo {
Jooyung Hancaa995c2022-11-08 16:35:50 +0900675 version: 3,
Jooyung Han743e0d62022-11-07 20:57:48 +0900676 path: staged.path().to_owned(),
677 last_update_seconds: last_updated(staged.path()).unwrap(),
678 ..active_apex
679 },
680 ],
681 }
682 );
683 }
Jooyung Han5e0f2062021-10-12 14:00:46 +0900684}