blob: 99aea01952a7b9baa3310edb8da55be0e91c01f4 [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
Jaewan Kimb24d1dc2023-02-13 15:34:56 +090017use crate::debug_config::should_include_debug_apexes;
Andrew Walbrancc0db522021-07-12 17:03:42 +000018use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Alan Stokes0d1ef782022-09-27 13:46:35 +010019 DiskImage::DiskImage,
20 Partition::Partition,
21 VirtualMachineAppConfig::DebugLevel::DebugLevel,
22 VirtualMachineAppConfig::{Payload::Payload, VirtualMachineAppConfig},
Andrew Walbrancc0db522021-07-12 17:03:42 +000023 VirtualMachineRawConfig::VirtualMachineRawConfig,
24};
Inseob Kima5a262f2021-11-17 19:41:03 +090025use anyhow::{anyhow, bail, Context, Result};
Alan Stokes0e82b502022-08-08 14:44:48 +010026use binder::{wait_for_interface, ParcelFileDescriptor};
Alan Stokesbf20c6a2022-01-04 12:30:50 +000027use log::{info, warn};
Alan Stokes0d1ef782022-09-27 13:46:35 +010028use microdroid_metadata::{ApexPayload, ApkPayload, Metadata, PayloadConfig, PayloadMetadata};
Jooyung Han5dc42172021-10-05 16:43:47 +090029use microdroid_payload_config::{ApexConfig, VmPayloadConfig};
Jooyung Han9900f3d2021-07-06 10:27:54 +090030use once_cell::sync::OnceCell;
Jooyung Han743e0d62022-11-07 20:57:48 +090031use packagemanager_aidl::aidl::android::content::pm::{
32 IPackageManagerNative::IPackageManagerNative, StagedApexInfo::StagedApexInfo,
33};
Alan Stokesbf20c6a2022-01-04 12:30:50 +000034use regex::Regex;
Jooyung Han44b02ab2021-07-16 03:19:13 +090035use serde::Deserialize;
36use serde_xml_rs::from_reader;
Alan Stokesbf20c6a2022-01-04 12:30:50 +000037use std::collections::HashSet;
Andrew Walbran40be9d52022-01-19 14:32:53 +000038use std::fs::{metadata, File, OpenOptions};
Jooyung Han21e9b922021-06-26 04:14:16 +090039use std::path::{Path, PathBuf};
Alan Stokesbf20c6a2022-01-04 12:30:50 +000040use std::process::Command;
Andrew Walbran40be9d52022-01-19 14:32:53 +000041use std::time::SystemTime;
Andrew Walbrancc0db522021-07-12 17:03:42 +000042use vmconfig::open_parcel_file;
43
44/// The list of APEXes which microdroid requires.
45// TODO(b/192200378) move this to microdroid.json?
Inseob Kimb4868e62021-11-09 17:28:23 +090046const MICRODROID_REQUIRED_APEXES: [&str; 1] = ["com.android.os.statsd"];
47const MICRODROID_REQUIRED_APEXES_DEBUG: [&str; 1] = ["com.android.adbd"];
Jooyung Han21e9b922021-06-26 04:14:16 +090048
Jooyung Han44b02ab2021-07-16 03:19:13 +090049const APEX_INFO_LIST_PATH: &str = "/apex/apex-info-list.xml";
50
Jooyung Han5dc42172021-10-05 16:43:47 +090051const PACKAGE_MANAGER_NATIVE_SERVICE: &str = "package_native";
52
Jooyung Han73bac242021-07-02 10:25:49 +090053/// Represents the list of APEXes
Jooyung Han743e0d62022-11-07 20:57:48 +090054#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
Jooyung Han9900f3d2021-07-06 10:27:54 +090055struct ApexInfoList {
Jooyung Han44b02ab2021-07-16 03:19:13 +090056 #[serde(rename = "apex-info")]
Jooyung Han73bac242021-07-02 10:25:49 +090057 list: Vec<ApexInfo>,
58}
59
Jooyung Han5ce867a2022-01-28 03:18:38 +090060#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
Jooyung Han73bac242021-07-02 10:25:49 +090061struct ApexInfo {
Jooyung Han44b02ab2021-07-16 03:19:13 +090062 #[serde(rename = "moduleName")]
Jooyung Han73bac242021-07-02 10:25:49 +090063 name: String,
Jooyung Hancaa995c2022-11-08 16:35:50 +090064 #[serde(rename = "versionCode")]
65 version: u64,
Jooyung Han44b02ab2021-07-16 03:19:13 +090066 #[serde(rename = "modulePath")]
Jooyung Han73bac242021-07-02 10:25:49 +090067 path: PathBuf,
Jooyung Han9d7cd7d2021-10-12 17:44:14 +090068
69 #[serde(default)]
Alan Stokes46ac3862021-12-21 15:31:47 +000070 has_classpath_jar: bool,
Andrew Walbran40be9d52022-01-19 14:32:53 +000071
72 // The field claims to be milliseconds but is actually seconds.
73 #[serde(rename = "lastUpdateMillis")]
74 last_update_seconds: u64,
Jiyong Parkd6502352022-01-27 01:07:30 +090075
76 #[serde(rename = "isFactory")]
77 is_factory: bool,
Jooyung Hanec788042022-01-27 22:28:37 +090078
79 #[serde(rename = "isActive")]
80 is_active: bool,
Jooyung Han5ce867a2022-01-28 03:18:38 +090081
82 #[serde(rename = "provideSharedApexLibs")]
83 provide_shared_apex_libs: bool,
Jooyung Han73bac242021-07-02 10:25:49 +090084}
85
86impl ApexInfoList {
87 /// Loads ApexInfoList
Jooyung Han9900f3d2021-07-06 10:27:54 +090088 fn load() -> Result<&'static ApexInfoList> {
89 static INSTANCE: OnceCell<ApexInfoList> = OnceCell::new();
90 INSTANCE.get_or_try_init(|| {
Jooyung Han44b02ab2021-07-16 03:19:13 +090091 let apex_info_list = File::open(APEX_INFO_LIST_PATH)
92 .context(format!("Failed to open {}", APEX_INFO_LIST_PATH))?;
Jooyung Han9d7cd7d2021-10-12 17:44:14 +090093 let mut apex_info_list: ApexInfoList = from_reader(apex_info_list)
Jooyung Han44b02ab2021-07-16 03:19:13 +090094 .context(format!("Failed to parse {}", APEX_INFO_LIST_PATH))?;
Jooyung Han9d7cd7d2021-10-12 17:44:14 +090095
Alan Stokesbf20c6a2022-01-04 12:30:50 +000096 // For active APEXes, we run derive_classpath and parse its output to see if it
97 // contributes to the classpath(s). (This allows us to handle any new classpath env
98 // vars seamlessly.)
99 let classpath_vars = run_derive_classpath()?;
100 let classpath_apexes = find_apex_names_in_classpath(&classpath_vars)?;
101
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900102 for apex_info in apex_info_list.list.iter_mut() {
Alan Stokesbf20c6a2022-01-04 12:30:50 +0000103 apex_info.has_classpath_jar = classpath_apexes.contains(&apex_info.name);
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900104 }
Alan Stokesbf20c6a2022-01-04 12:30:50 +0000105
Jooyung Han44b02ab2021-07-16 03:19:13 +0900106 Ok(apex_info_list)
Jooyung Han9900f3d2021-07-06 10:27:54 +0900107 })
Jooyung Han73bac242021-07-02 10:25:49 +0900108 }
Jooyung Han743e0d62022-11-07 20:57:48 +0900109
110 // Override apex info with the staged one
111 fn override_staged_apex(&mut self, staged_apex_info: &StagedApexInfo) -> Result<()> {
112 let mut need_to_add: Option<ApexInfo> = None;
113 for apex_info in self.list.iter_mut() {
114 if staged_apex_info.moduleName == apex_info.name {
115 if apex_info.is_active && apex_info.is_factory {
116 // Copy the entry to the end as factory/non-active after the loop
117 // to keep the factory version. Typically this step is unncessary,
118 // but some apexes (like sharedlibs) need to be kept even if it's inactive.
119 need_to_add.replace(ApexInfo { is_active: false, ..apex_info.clone() });
120 // And make this one as non-factory. Note that this one is still active
121 // and overridden right below.
122 apex_info.is_factory = false;
123 }
124 // Active one is overridden with the staged one.
125 if apex_info.is_active {
Jooyung Hancaa995c2022-11-08 16:35:50 +0900126 apex_info.version = staged_apex_info.versionCode as u64;
Jooyung Han743e0d62022-11-07 20:57:48 +0900127 apex_info.path = PathBuf::from(&staged_apex_info.diskImagePath);
128 apex_info.has_classpath_jar = staged_apex_info.hasClassPathJars;
129 apex_info.last_update_seconds = last_updated(&apex_info.path)?;
130 }
131 }
132 }
133 if let Some(info) = need_to_add {
134 self.list.push(info);
135 }
136 Ok(())
137 }
138}
139
140fn last_updated<P: AsRef<Path>>(path: P) -> Result<u64> {
141 let metadata = metadata(path)?;
142 Ok(metadata.modified()?.duration_since(SystemTime::UNIX_EPOCH)?.as_secs())
Jooyung Hanec788042022-01-27 22:28:37 +0900143}
Jooyung Han73bac242021-07-02 10:25:49 +0900144
Jooyung Hanec788042022-01-27 22:28:37 +0900145impl ApexInfo {
146 fn matches(&self, apex_config: &ApexConfig) -> bool {
147 // Match with pseudo name "{CLASSPATH}" which represents APEXes contributing
148 // to any derive_classpath environment variable
149 if apex_config.name == "{CLASSPATH}" && self.has_classpath_jar {
150 return true;
151 }
152 if apex_config.name == self.name {
153 return true;
154 }
155 false
Jooyung Han73bac242021-07-02 10:25:49 +0900156 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900157}
158
Jooyung Han5dc42172021-10-05 16:43:47 +0900159struct PackageManager {
Jooyung Han5dc42172021-10-05 16:43:47 +0900160 apex_info_list: &'static ApexInfoList,
161}
162
163impl PackageManager {
164 fn new() -> Result<Self> {
Jooyung Han5dc42172021-10-05 16:43:47 +0900165 let apex_info_list = ApexInfoList::load()?;
Jooyung Han53cf7992021-10-18 19:38:41 +0900166 Ok(Self { apex_info_list })
Jooyung Han5dc42172021-10-05 16:43:47 +0900167 }
168
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900169 fn get_apex_list(&self, prefer_staged: bool) -> Result<ApexInfoList> {
Jooyung Han53cf7992021-10-18 19:38:41 +0900170 // get the list of active apexes
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900171 let mut list = self.apex_info_list.clone();
Jooyung Han53cf7992021-10-18 19:38:41 +0900172 // When prefer_staged, we override ApexInfo by consulting "package_native"
Jooyung Han5dc42172021-10-05 16:43:47 +0900173 if prefer_staged {
Jooyung Han53cf7992021-10-18 19:38:41 +0900174 let pm =
175 wait_for_interface::<dyn IPackageManagerNative>(PACKAGE_MANAGER_NATIVE_SERVICE)
176 .context("Failed to get service when prefer_staged is set.")?;
Alan Stokes70ccf162022-07-08 11:05:03 +0100177 let staged =
178 pm.getStagedApexModuleNames().context("getStagedApexModuleNames failed")?;
Jooyung Han743e0d62022-11-07 20:57:48 +0900179 for name in staged {
180 if let Some(staged_apex_info) =
181 pm.getStagedApexInfo(&name).context("getStagedApexInfo failed")?
182 {
183 list.override_staged_apex(&staged_apex_info)?;
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900184 }
Jooyung Han5dc42172021-10-05 16:43:47 +0900185 }
186 }
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900187 Ok(list)
Jooyung Han5dc42172021-10-05 16:43:47 +0900188 }
189}
190
Andrew Walbrancc0db522021-07-12 17:03:42 +0000191fn make_metadata_file(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100192 app_config: &VirtualMachineAppConfig,
Jooyung Hanec788042022-01-27 22:28:37 +0900193 apex_infos: &[&ApexInfo],
Jooyung Han21e9b922021-06-26 04:14:16 +0900194 temporary_directory: &Path,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000195) -> Result<ParcelFileDescriptor> {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100196 let payload_metadata = match &app_config.payload {
197 Payload::PayloadConfig(payload_config) => PayloadMetadata::config(PayloadConfig {
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000198 payload_binary_name: payload_config.payloadBinaryName.clone(),
Alan Stokes0d1ef782022-09-27 13:46:35 +0100199 ..Default::default()
200 }),
201 Payload::ConfigPath(config_path) => {
202 PayloadMetadata::config_path(format!("/mnt/apk/{}", config_path))
203 }
204 };
205
Jooyung Han21e9b922021-06-26 04:14:16 +0900206 let metadata = Metadata {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000207 version: 1,
Jooyung Hanec788042022-01-27 22:28:37 +0900208 apexes: apex_infos
Jooyung Han21e9b922021-06-26 04:14:16 +0900209 .iter()
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900210 .enumerate()
Jooyung Hanec788042022-01-27 22:28:37 +0900211 .map(|(i, apex_info)| {
Andrew Walbran40be9d52022-01-19 14:32:53 +0000212 Ok(ApexPayload {
Jooyung Hanec788042022-01-27 22:28:37 +0900213 name: apex_info.name.clone(),
Andrew Walbran40be9d52022-01-19 14:32:53 +0000214 partition_name: format!("microdroid-apex-{}", i),
Jiyong Parkd6502352022-01-27 01:07:30 +0900215 last_update_seconds: apex_info.last_update_seconds,
216 is_factory: apex_info.is_factory,
Andrew Walbran40be9d52022-01-19 14:32:53 +0000217 ..Default::default()
218 })
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900219 })
Andrew Walbran40be9d52022-01-19 14:32:53 +0000220 .collect::<Result<_>>()?,
Jooyung Han21e9b922021-06-26 04:14:16 +0900221 apk: Some(ApkPayload {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900222 name: "apk".to_owned(),
223 payload_partition_name: "microdroid-apk".to_owned(),
224 idsig_partition_name: "microdroid-apk-idsig".to_owned(),
Jooyung Han21e9b922021-06-26 04:14:16 +0900225 ..Default::default()
226 })
227 .into(),
Alan Stokes0d1ef782022-09-27 13:46:35 +0100228 payload: Some(payload_metadata),
Jooyung Han21e9b922021-06-26 04:14:16 +0900229 ..Default::default()
230 };
Andrew Walbrancc0db522021-07-12 17:03:42 +0000231
232 // Write metadata to file.
Alan Stokes0d1ef782022-09-27 13:46:35 +0100233 let metadata_path = temporary_directory.join("metadata");
Andrew Walbrancc0db522021-07-12 17:03:42 +0000234 let mut metadata_file = OpenOptions::new()
235 .create_new(true)
236 .read(true)
237 .write(true)
238 .open(&metadata_path)
239 .with_context(|| format!("Failed to open metadata file {:?}", metadata_path))?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900240 microdroid_metadata::write_metadata(&metadata, &mut metadata_file)?;
241
Andrew Walbrancc0db522021-07-12 17:03:42 +0000242 // Re-open the metadata file as read-only.
243 open_parcel_file(&metadata_path, false)
244}
245
246/// Creates a DiskImage with partitions:
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100247/// payload-metadata: metadata
Andrew Walbrancc0db522021-07-12 17:03:42 +0000248/// microdroid-apex-0: apex 0
249/// microdroid-apex-1: apex 1
250/// ..
251/// microdroid-apk: apk
252/// microdroid-apk-idsig: idsig
Inseob Kima5a262f2021-11-17 19:41:03 +0900253/// extra-apk-0: additional apk 0
254/// extra-idsig-0: additional idsig 0
255/// extra-apk-1: additional apk 1
256/// extra-idsig-1: additional idsig 1
257/// ..
Andrew Walbrancc0db522021-07-12 17:03:42 +0000258fn make_payload_disk(
Inseob Kima5a262f2021-11-17 19:41:03 +0900259 app_config: &VirtualMachineAppConfig,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000260 apk_file: File,
261 idsig_file: File,
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900262 vm_payload_config: &VmPayloadConfig,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000263 temporary_directory: &Path,
264) -> Result<DiskImage> {
Inseob Kima5a262f2021-11-17 19:41:03 +0900265 if vm_payload_config.extra_apks.len() != app_config.extraIdsigs.len() {
266 bail!(
267 "payload config has {} apks, but app config has {} idsigs",
268 vm_payload_config.extra_apks.len(),
269 app_config.extraIdsigs.len()
270 );
271 }
272
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900273 let pm = PackageManager::new()?;
274 let apex_list = pm.get_apex_list(vm_payload_config.prefer_staged)?;
275
Jooyung Hanec788042022-01-27 22:28:37 +0900276 // collect APEXes from config
Jooyung Hancaa995c2022-11-08 16:35:50 +0900277 let mut apex_infos =
Jooyung Hanec788042022-01-27 22:28:37 +0900278 collect_apex_infos(&apex_list, &vm_payload_config.apexes, app_config.debugLevel);
Jooyung Hancaa995c2022-11-08 16:35:50 +0900279
280 // Pass sorted list of apexes. Sorting key shouldn't use `path` because it will change after
281 // reboot with prefer_staged. `last_update_seconds` is added to distinguish "samegrade"
282 // update.
283 apex_infos.sort_by_key(|info| (&info.name, &info.version, &info.last_update_seconds));
Jooyung Hanec788042022-01-27 22:28:37 +0900284 info!("Microdroid payload APEXes: {:?}", apex_infos.iter().map(|ai| &ai.name));
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900285
Alan Stokes0d1ef782022-09-27 13:46:35 +0100286 let metadata_file = make_metadata_file(app_config, &apex_infos, temporary_directory)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900287 // put metadata at the first partition
288 let mut partitions = vec![Partition {
Jooyung Han14e5a8e2021-07-06 20:48:38 +0900289 label: "payload-metadata".to_owned(),
Jooyung Han631d5882021-07-29 06:34:05 +0900290 image: Some(metadata_file),
Jooyung Han21e9b922021-06-26 04:14:16 +0900291 writable: false,
292 }];
293
Jooyung Hanec788042022-01-27 22:28:37 +0900294 for (i, apex_info) in apex_infos.iter().enumerate() {
295 let apex_file = open_parcel_file(&apex_info.path, false)?;
Jooyung Han95884632021-07-06 22:27:54 +0900296 partitions.push(Partition {
297 label: format!("microdroid-apex-{}", i),
Jooyung Han631d5882021-07-29 06:34:05 +0900298 image: Some(apex_file),
Jooyung Han95884632021-07-06 22:27:54 +0900299 writable: false,
300 });
Jooyung Han21e9b922021-06-26 04:14:16 +0900301 }
Jooyung Han95884632021-07-06 22:27:54 +0900302 partitions.push(Partition {
303 label: "microdroid-apk".to_owned(),
Jooyung Han631d5882021-07-29 06:34:05 +0900304 image: Some(ParcelFileDescriptor::new(apk_file)),
Jooyung Han95884632021-07-06 22:27:54 +0900305 writable: false,
306 });
307 partitions.push(Partition {
308 label: "microdroid-apk-idsig".to_owned(),
Jooyung Han631d5882021-07-29 06:34:05 +0900309 image: Some(ParcelFileDescriptor::new(idsig_file)),
Jooyung Han95884632021-07-06 22:27:54 +0900310 writable: false,
311 });
Jooyung Han21e9b922021-06-26 04:14:16 +0900312
Inseob Kima5a262f2021-11-17 19:41:03 +0900313 // we've already checked that extra_apks and extraIdsigs are in the same size.
314 let extra_apks = &vm_payload_config.extra_apks;
315 let extra_idsigs = &app_config.extraIdsigs;
316 for (i, (extra_apk, extra_idsig)) in extra_apks.iter().zip(extra_idsigs.iter()).enumerate() {
317 partitions.push(Partition {
318 label: format!("extra-apk-{}", i),
Victor Hsieh14497f02022-09-21 10:10:16 -0700319 image: Some(ParcelFileDescriptor::new(
320 File::open(PathBuf::from(&extra_apk.path)).with_context(|| {
321 format!("Failed to open the extra apk #{} {}", i, extra_apk.path)
322 })?,
323 )),
Inseob Kima5a262f2021-11-17 19:41:03 +0900324 writable: false,
325 });
326
327 partitions.push(Partition {
328 label: format!("extra-idsig-{}", i),
Victor Hsieh14497f02022-09-21 10:10:16 -0700329 image: Some(ParcelFileDescriptor::new(
330 extra_idsig
331 .as_ref()
332 .try_clone()
333 .with_context(|| format!("Failed to clone the extra idsig #{}", i))?,
334 )),
Inseob Kima5a262f2021-11-17 19:41:03 +0900335 writable: false,
336 });
337 }
338
Jooyung Han21e9b922021-06-26 04:14:16 +0900339 Ok(DiskImage { image: None, partitions, writable: false })
340}
Andrew Walbrancc0db522021-07-12 17:03:42 +0000341
Alan Stokesbf20c6a2022-01-04 12:30:50 +0000342fn run_derive_classpath() -> Result<String> {
343 let result = Command::new("/apex/com.android.sdkext/bin/derive_classpath")
344 .arg("/proc/self/fd/1")
345 .output()
346 .context("Failed to run derive_classpath")?;
347
348 if !result.status.success() {
349 bail!("derive_classpath returned {}", result.status);
350 }
351
352 String::from_utf8(result.stdout).context("Converting derive_classpath output")
353}
354
355fn find_apex_names_in_classpath(classpath_vars: &str) -> Result<HashSet<String>> {
356 // Each line should be in the format "export <var name> <paths>", where <paths> is a
357 // colon-separated list of paths to JARs. We don't care about the var names, and we're only
358 // interested in paths that look like "/apex/<apex name>/<anything>" so we know which APEXes
359 // contribute to at least one var.
360 let mut apexes = HashSet::new();
361
362 let pattern = Regex::new(r"^export [^ ]+ ([^ ]+)$").context("Failed to construct Regex")?;
363 for line in classpath_vars.lines() {
364 if let Some(captures) = pattern.captures(line) {
365 if let Some(paths) = captures.get(1) {
366 apexes.extend(paths.as_str().split(':').filter_map(|path| {
367 let path = path.strip_prefix("/apex/")?;
368 Some(path[..path.find('/')?].to_owned())
369 }));
370 continue;
371 }
372 }
373 warn!("Malformed line from derive_classpath: {}", line);
374 }
375
376 Ok(apexes)
Jooyung Han5e0f2062021-10-12 14:00:46 +0900377}
378
Jooyung Hanec788042022-01-27 22:28:37 +0900379// Collect ApexInfos from VM config
380fn collect_apex_infos<'a>(
381 apex_list: &'a ApexInfoList,
382 apex_configs: &[ApexConfig],
Inseob Kimb4868e62021-11-09 17:28:23 +0900383 debug_level: DebugLevel,
Jooyung Hanec788042022-01-27 22:28:37 +0900384) -> Vec<&'a ApexInfo> {
385 let mut additional_apexes: Vec<&str> = MICRODROID_REQUIRED_APEXES.to_vec();
Jaewan Kimb24d1dc2023-02-13 15:34:56 +0900386 if should_include_debug_apexes(debug_level) {
Jooyung Hanec788042022-01-27 22:28:37 +0900387 additional_apexes.extend(MICRODROID_REQUIRED_APEXES_DEBUG.to_vec());
Inseob Kimb4868e62021-11-09 17:28:23 +0900388 }
Jooyung Hanec788042022-01-27 22:28:37 +0900389
390 apex_list
391 .list
392 .iter()
393 .filter(|ai| {
394 apex_configs.iter().any(|cfg| ai.matches(cfg) && ai.is_active)
395 || additional_apexes.iter().any(|name| name == &ai.name && ai.is_active)
Jooyung Han5ce867a2022-01-28 03:18:38 +0900396 || ai.provide_shared_apex_libs
Jooyung Hanec788042022-01-27 22:28:37 +0900397 })
398 .collect()
Jooyung Han5e0f2062021-10-12 14:00:46 +0900399}
400
Shikha Panwar22e70452022-10-10 18:32:55 +0000401pub fn add_microdroid_system_images(
Andrew Walbrancc0db522021-07-12 17:03:42 +0000402 config: &VirtualMachineAppConfig,
Jiyong Park8d081812021-07-23 17:45:04 +0900403 instance_file: File,
Shikha Panwar22e70452022-10-10 18:32:55 +0000404 storage_image: Option<File>,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000405 vm_config: &mut VirtualMachineRawConfig,
406) -> Result<()> {
Shikha Panwared8ace42022-09-28 12:52:16 +0000407 let debug_suffix = match config.debugLevel {
408 DebugLevel::NONE => "normal",
Seungjae Yooe85831e2022-12-12 09:34:58 +0900409 DebugLevel::FULL => "debuggable",
Shikha Panwared8ace42022-09-28 12:52:16 +0000410 _ => return Err(anyhow!("unsupported debug level: {:?}", config.debugLevel)),
411 };
412 let initrd = format!("/apex/com.android.virt/etc/microdroid_initrd_{}.img", debug_suffix);
413 vm_config.initrd = Some(open_parcel_file(Path::new(&initrd), false)?);
414
Shikha Panwar22e70452022-10-10 18:32:55 +0000415 let mut writable_partitions = vec![Partition {
Shikha Panwared8ace42022-09-28 12:52:16 +0000416 label: "vm-instance".to_owned(),
417 image: Some(ParcelFileDescriptor::new(instance_file)),
418 writable: true,
Shikha Panwar22e70452022-10-10 18:32:55 +0000419 }];
420
421 if let Some(file) = storage_image {
422 writable_partitions.push(Partition {
Shikha Panwar566c9672022-11-15 14:39:58 +0000423 label: "encryptedstore".to_owned(),
Shikha Panwar22e70452022-10-10 18:32:55 +0000424 image: Some(ParcelFileDescriptor::new(file)),
425 writable: true,
426 });
427 }
428
429 vm_config.disks.push(DiskImage {
430 image: None,
431 partitions: writable_partitions,
432 writable: true,
433 });
434
435 Ok(())
436}
437
438pub fn add_microdroid_payload_images(
439 config: &VirtualMachineAppConfig,
440 temporary_directory: &Path,
441 apk_file: File,
442 idsig_file: File,
443 vm_payload_config: &VmPayloadConfig,
444 vm_config: &mut VirtualMachineRawConfig,
445) -> Result<()> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000446 vm_config.disks.push(make_payload_disk(
Inseob Kima5a262f2021-11-17 19:41:03 +0900447 config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000448 apk_file,
449 idsig_file,
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900450 vm_payload_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000451 temporary_directory,
452 )?);
453
Andrew Walbrancc0db522021-07-12 17:03:42 +0000454 Ok(())
455}
Jooyung Han5e0f2062021-10-12 14:00:46 +0900456
457#[cfg(test)]
458mod tests {
459 use super::*;
Jooyung Han743e0d62022-11-07 20:57:48 +0900460 use tempfile::NamedTempFile;
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000461
Jooyung Han5e0f2062021-10-12 14:00:46 +0900462 #[test]
Alan Stokesbf20c6a2022-01-04 12:30:50 +0000463 fn test_find_apex_names_in_classpath() {
464 let vars = r#"
465export FOO /apex/unterminated
466export BAR /apex/valid.apex/something
467wrong
468export EMPTY
469export OTHER /foo/bar:/baz:/apex/second.valid.apex/:gibberish:"#;
470 let expected = vec!["valid.apex", "second.valid.apex"];
471 let expected: HashSet<_> = expected.into_iter().map(ToString::to_string).collect();
472
473 assert_eq!(find_apex_names_in_classpath(vars).unwrap(), expected);
Jooyung Han5e0f2062021-10-12 14:00:46 +0900474 }
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000475
476 #[test]
Jooyung Hanec788042022-01-27 22:28:37 +0900477 fn test_collect_apexes() {
478 let apex_info_list = ApexInfoList {
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000479 list: vec![
480 ApexInfo {
Jooyung Hanec788042022-01-27 22:28:37 +0900481 // 0
482 name: "com.android.adbd".to_string(),
483 path: PathBuf::from("adbd"),
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000484 has_classpath_jar: false,
Andrew Walbran40be9d52022-01-19 14:32:53 +0000485 last_update_seconds: 12345678,
Jiyong Parkd6502352022-01-27 01:07:30 +0900486 is_factory: true,
Jooyung Hanec788042022-01-27 22:28:37 +0900487 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900488 ..Default::default()
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000489 },
490 ApexInfo {
Jooyung Hanec788042022-01-27 22:28:37 +0900491 // 1
492 name: "com.android.os.statsd".to_string(),
493 path: PathBuf::from("statsd"),
494 has_classpath_jar: false,
495 last_update_seconds: 12345678,
496 is_factory: true,
497 is_active: false,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900498 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900499 },
500 ApexInfo {
501 // 2
502 name: "com.android.os.statsd".to_string(),
503 path: PathBuf::from("statsd/updated"),
504 has_classpath_jar: false,
505 last_update_seconds: 12345678 + 1,
506 is_factory: false,
507 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900508 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900509 },
510 ApexInfo {
511 // 3
512 name: "no_classpath".to_string(),
513 path: PathBuf::from("no_classpath"),
514 has_classpath_jar: false,
515 last_update_seconds: 12345678,
516 is_factory: true,
517 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900518 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900519 },
520 ApexInfo {
521 // 4
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000522 name: "has_classpath".to_string(),
Jooyung Hanec788042022-01-27 22:28:37 +0900523 path: PathBuf::from("has_classpath"),
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000524 has_classpath_jar: true,
Andrew Walbran40be9d52022-01-19 14:32:53 +0000525 last_update_seconds: 87654321,
Jooyung Hanec788042022-01-27 22:28:37 +0900526 is_factory: true,
527 is_active: false,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900528 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900529 },
530 ApexInfo {
531 // 5
532 name: "has_classpath".to_string(),
533 path: PathBuf::from("has_classpath/updated"),
534 has_classpath_jar: true,
535 last_update_seconds: 87654321 + 1,
Jiyong Parkd6502352022-01-27 01:07:30 +0900536 is_factory: false,
Jooyung Hanec788042022-01-27 22:28:37 +0900537 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900538 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900539 },
540 ApexInfo {
541 // 6
542 name: "apex-foo".to_string(),
543 path: PathBuf::from("apex-foo"),
544 has_classpath_jar: false,
545 last_update_seconds: 87654321,
546 is_factory: true,
547 is_active: false,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900548 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900549 },
550 ApexInfo {
551 // 7
552 name: "apex-foo".to_string(),
553 path: PathBuf::from("apex-foo/updated"),
554 has_classpath_jar: false,
555 last_update_seconds: 87654321 + 1,
556 is_factory: false,
557 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900558 ..Default::default()
559 },
560 ApexInfo {
561 // 8
562 name: "sharedlibs".to_string(),
563 path: PathBuf::from("apex-foo"),
564 last_update_seconds: 87654321,
565 is_factory: true,
566 provide_shared_apex_libs: true,
567 ..Default::default()
568 },
569 ApexInfo {
570 // 9
571 name: "sharedlibs".to_string(),
572 path: PathBuf::from("apex-foo/updated"),
573 last_update_seconds: 87654321 + 1,
574 is_active: true,
575 provide_shared_apex_libs: true,
576 ..Default::default()
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000577 },
578 ],
579 };
Jooyung Hanec788042022-01-27 22:28:37 +0900580 let apex_configs = vec![
581 ApexConfig { name: "apex-foo".to_string() },
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000582 ApexConfig { name: "{CLASSPATH}".to_string() },
583 ];
584 assert_eq!(
Jooyung Hanec788042022-01-27 22:28:37 +0900585 collect_apex_infos(&apex_info_list, &apex_configs, DebugLevel::FULL),
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000586 vec![
Jooyung Han5ce867a2022-01-28 03:18:38 +0900587 // Pass active/required APEXes
Jooyung Hanec788042022-01-27 22:28:37 +0900588 &apex_info_list.list[0],
589 &apex_info_list.list[2],
Jooyung Han5ce867a2022-01-28 03:18:38 +0900590 // Pass active APEXes specified in the config
Jooyung Hanec788042022-01-27 22:28:37 +0900591 &apex_info_list.list[5],
592 &apex_info_list.list[7],
Jooyung Han5ce867a2022-01-28 03:18:38 +0900593 // Pass both preinstalled(inactive) and updated(active) for "sharedlibs" APEXes
594 &apex_info_list.list[8],
595 &apex_info_list.list[9],
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000596 ]
597 );
598 }
Jooyung Han743e0d62022-11-07 20:57:48 +0900599
600 #[test]
601 fn test_prefer_staged_apex_with_factory_active_apex() {
602 let single_apex = ApexInfo {
603 name: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900604 version: 1,
Jooyung Han743e0d62022-11-07 20:57:48 +0900605 path: PathBuf::from("foo.apex"),
606 is_factory: true,
607 is_active: true,
608 ..Default::default()
609 };
610 let mut apex_info_list = ApexInfoList { list: vec![single_apex.clone()] };
611
612 let staged = NamedTempFile::new().unwrap();
613 apex_info_list
614 .override_staged_apex(&StagedApexInfo {
615 moduleName: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900616 versionCode: 2,
Jooyung Han743e0d62022-11-07 20:57:48 +0900617 diskImagePath: staged.path().to_string_lossy().to_string(),
618 ..Default::default()
619 })
620 .expect("should be ok");
621
622 assert_eq!(
623 apex_info_list,
624 ApexInfoList {
625 list: vec![
626 ApexInfo {
Jooyung Hancaa995c2022-11-08 16:35:50 +0900627 version: 2,
Jooyung Han743e0d62022-11-07 20:57:48 +0900628 is_factory: false,
629 path: staged.path().to_owned(),
630 last_update_seconds: last_updated(staged.path()).unwrap(),
631 ..single_apex.clone()
632 },
633 ApexInfo { is_active: false, ..single_apex },
634 ],
635 }
636 );
637 }
638
639 #[test]
640 fn test_prefer_staged_apex_with_factory_and_inactive_apex() {
641 let factory_apex = ApexInfo {
642 name: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900643 version: 1,
Jooyung Han743e0d62022-11-07 20:57:48 +0900644 path: PathBuf::from("foo.apex"),
645 is_factory: true,
646 ..Default::default()
647 };
648 let active_apex = ApexInfo {
649 name: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900650 version: 2,
Jooyung Han743e0d62022-11-07 20:57:48 +0900651 path: PathBuf::from("foo.downloaded.apex"),
652 is_active: true,
653 ..Default::default()
654 };
655 let mut apex_info_list =
656 ApexInfoList { list: vec![factory_apex.clone(), active_apex.clone()] };
657
658 let staged = NamedTempFile::new().unwrap();
659 apex_info_list
660 .override_staged_apex(&StagedApexInfo {
661 moduleName: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900662 versionCode: 3,
Jooyung Han743e0d62022-11-07 20:57:48 +0900663 diskImagePath: staged.path().to_string_lossy().to_string(),
664 ..Default::default()
665 })
666 .expect("should be ok");
667
668 assert_eq!(
669 apex_info_list,
670 ApexInfoList {
671 list: vec![
672 // factory apex isn't touched
673 factory_apex,
674 // update active one
675 ApexInfo {
Jooyung Hancaa995c2022-11-08 16:35:50 +0900676 version: 3,
Jooyung Han743e0d62022-11-07 20:57:48 +0900677 path: staged.path().to_owned(),
678 last_update_seconds: last_updated(staged.path()).unwrap(),
679 ..active_apex
680 },
681 ],
682 }
683 );
684 }
Jooyung Han5e0f2062021-10-12 14:00:46 +0900685}