blob: c11834d37a44ef224dad62d3e2a3e9f7fc2c8b83 [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 Kim61f86142023-03-28 15:12:52 +090017use crate::debug_config::DebugConfig;
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,
Jaewan Kim61f86142023-03-28 15:12:52 +0900260 debug_config: &DebugConfig,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000261 apk_file: File,
262 idsig_file: File,
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900263 vm_payload_config: &VmPayloadConfig,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000264 temporary_directory: &Path,
265) -> Result<DiskImage> {
Inseob Kima5a262f2021-11-17 19:41:03 +0900266 if vm_payload_config.extra_apks.len() != app_config.extraIdsigs.len() {
267 bail!(
268 "payload config has {} apks, but app config has {} idsigs",
269 vm_payload_config.extra_apks.len(),
270 app_config.extraIdsigs.len()
271 );
272 }
273
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900274 let pm = PackageManager::new()?;
275 let apex_list = pm.get_apex_list(vm_payload_config.prefer_staged)?;
276
Jooyung Hanec788042022-01-27 22:28:37 +0900277 // collect APEXes from config
Jaewan Kim61f86142023-03-28 15:12:52 +0900278 let mut apex_infos = collect_apex_infos(&apex_list, &vm_payload_config.apexes, debug_config);
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],
Jaewan Kim61f86142023-03-28 15:12:52 +0900383 debug_config: &DebugConfig,
Jooyung Hanec788042022-01-27 22:28:37 +0900384) -> Vec<&'a ApexInfo> {
385 let mut additional_apexes: Vec<&str> = MICRODROID_REQUIRED_APEXES.to_vec();
Jaewan Kim61f86142023-03-28 15:12:52 +0900386 if debug_config.should_include_debug_apexes() {
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
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100401pub fn add_microdroid_vendor_image(vendor_image: File, vm_config: &mut VirtualMachineRawConfig) {
402 vm_config.disks.push(DiskImage {
403 image: None,
404 writable: false,
405 partitions: vec![Partition {
406 label: "microdroid-vendor".to_owned(),
407 image: Some(ParcelFileDescriptor::new(vendor_image)),
408 writable: false,
409 }],
410 })
411}
412
Shikha Panwar22e70452022-10-10 18:32:55 +0000413pub fn add_microdroid_system_images(
Andrew Walbrancc0db522021-07-12 17:03:42 +0000414 config: &VirtualMachineAppConfig,
Jiyong Park8d081812021-07-23 17:45:04 +0900415 instance_file: File,
Shikha Panwar22e70452022-10-10 18:32:55 +0000416 storage_image: Option<File>,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000417 vm_config: &mut VirtualMachineRawConfig,
418) -> Result<()> {
Shikha Panwared8ace42022-09-28 12:52:16 +0000419 let debug_suffix = match config.debugLevel {
420 DebugLevel::NONE => "normal",
Seungjae Yooe85831e2022-12-12 09:34:58 +0900421 DebugLevel::FULL => "debuggable",
Shikha Panwared8ace42022-09-28 12:52:16 +0000422 _ => return Err(anyhow!("unsupported debug level: {:?}", config.debugLevel)),
423 };
424 let initrd = format!("/apex/com.android.virt/etc/microdroid_initrd_{}.img", debug_suffix);
425 vm_config.initrd = Some(open_parcel_file(Path::new(&initrd), false)?);
426
Shikha Panwar22e70452022-10-10 18:32:55 +0000427 let mut writable_partitions = vec![Partition {
Shikha Panwared8ace42022-09-28 12:52:16 +0000428 label: "vm-instance".to_owned(),
429 image: Some(ParcelFileDescriptor::new(instance_file)),
430 writable: true,
Shikha Panwar22e70452022-10-10 18:32:55 +0000431 }];
432
433 if let Some(file) = storage_image {
434 writable_partitions.push(Partition {
Shikha Panwar566c9672022-11-15 14:39:58 +0000435 label: "encryptedstore".to_owned(),
Shikha Panwar22e70452022-10-10 18:32:55 +0000436 image: Some(ParcelFileDescriptor::new(file)),
437 writable: true,
438 });
439 }
440
441 vm_config.disks.push(DiskImage {
442 image: None,
443 partitions: writable_partitions,
444 writable: true,
445 });
446
447 Ok(())
448}
449
450pub fn add_microdroid_payload_images(
451 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +0900452 debug_config: &DebugConfig,
Shikha Panwar22e70452022-10-10 18:32:55 +0000453 temporary_directory: &Path,
454 apk_file: File,
455 idsig_file: File,
456 vm_payload_config: &VmPayloadConfig,
457 vm_config: &mut VirtualMachineRawConfig,
458) -> Result<()> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000459 vm_config.disks.push(make_payload_disk(
Inseob Kima5a262f2021-11-17 19:41:03 +0900460 config,
Jaewan Kim61f86142023-03-28 15:12:52 +0900461 debug_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000462 apk_file,
463 idsig_file,
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900464 vm_payload_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000465 temporary_directory,
466 )?);
467
Andrew Walbrancc0db522021-07-12 17:03:42 +0000468 Ok(())
469}
Jooyung Han5e0f2062021-10-12 14:00:46 +0900470
471#[cfg(test)]
472mod tests {
473 use super::*;
Jooyung Han743e0d62022-11-07 20:57:48 +0900474 use tempfile::NamedTempFile;
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000475
Jooyung Han5e0f2062021-10-12 14:00:46 +0900476 #[test]
Alan Stokesbf20c6a2022-01-04 12:30:50 +0000477 fn test_find_apex_names_in_classpath() {
478 let vars = r#"
479export FOO /apex/unterminated
480export BAR /apex/valid.apex/something
481wrong
482export EMPTY
483export OTHER /foo/bar:/baz:/apex/second.valid.apex/:gibberish:"#;
484 let expected = vec!["valid.apex", "second.valid.apex"];
485 let expected: HashSet<_> = expected.into_iter().map(ToString::to_string).collect();
486
487 assert_eq!(find_apex_names_in_classpath(vars).unwrap(), expected);
Jooyung Han5e0f2062021-10-12 14:00:46 +0900488 }
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000489
490 #[test]
Jooyung Hanec788042022-01-27 22:28:37 +0900491 fn test_collect_apexes() {
492 let apex_info_list = ApexInfoList {
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000493 list: vec![
494 ApexInfo {
Jooyung Hanec788042022-01-27 22:28:37 +0900495 // 0
496 name: "com.android.adbd".to_string(),
497 path: PathBuf::from("adbd"),
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000498 has_classpath_jar: false,
Andrew Walbran40be9d52022-01-19 14:32:53 +0000499 last_update_seconds: 12345678,
Jiyong Parkd6502352022-01-27 01:07:30 +0900500 is_factory: true,
Jooyung Hanec788042022-01-27 22:28:37 +0900501 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900502 ..Default::default()
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000503 },
504 ApexInfo {
Jooyung Hanec788042022-01-27 22:28:37 +0900505 // 1
506 name: "com.android.os.statsd".to_string(),
507 path: PathBuf::from("statsd"),
508 has_classpath_jar: false,
509 last_update_seconds: 12345678,
510 is_factory: true,
511 is_active: false,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900512 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900513 },
514 ApexInfo {
515 // 2
516 name: "com.android.os.statsd".to_string(),
517 path: PathBuf::from("statsd/updated"),
518 has_classpath_jar: false,
519 last_update_seconds: 12345678 + 1,
520 is_factory: false,
521 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900522 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900523 },
524 ApexInfo {
525 // 3
526 name: "no_classpath".to_string(),
527 path: PathBuf::from("no_classpath"),
528 has_classpath_jar: false,
529 last_update_seconds: 12345678,
530 is_factory: true,
531 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900532 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900533 },
534 ApexInfo {
535 // 4
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000536 name: "has_classpath".to_string(),
Jooyung Hanec788042022-01-27 22:28:37 +0900537 path: PathBuf::from("has_classpath"),
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000538 has_classpath_jar: true,
Andrew Walbran40be9d52022-01-19 14:32:53 +0000539 last_update_seconds: 87654321,
Jooyung Hanec788042022-01-27 22:28:37 +0900540 is_factory: true,
541 is_active: false,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900542 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900543 },
544 ApexInfo {
545 // 5
546 name: "has_classpath".to_string(),
547 path: PathBuf::from("has_classpath/updated"),
548 has_classpath_jar: true,
549 last_update_seconds: 87654321 + 1,
Jiyong Parkd6502352022-01-27 01:07:30 +0900550 is_factory: false,
Jooyung Hanec788042022-01-27 22:28:37 +0900551 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900552 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900553 },
554 ApexInfo {
555 // 6
556 name: "apex-foo".to_string(),
557 path: PathBuf::from("apex-foo"),
558 has_classpath_jar: false,
559 last_update_seconds: 87654321,
560 is_factory: true,
561 is_active: false,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900562 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900563 },
564 ApexInfo {
565 // 7
566 name: "apex-foo".to_string(),
567 path: PathBuf::from("apex-foo/updated"),
568 has_classpath_jar: false,
569 last_update_seconds: 87654321 + 1,
570 is_factory: false,
571 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900572 ..Default::default()
573 },
574 ApexInfo {
575 // 8
576 name: "sharedlibs".to_string(),
577 path: PathBuf::from("apex-foo"),
578 last_update_seconds: 87654321,
579 is_factory: true,
580 provide_shared_apex_libs: true,
581 ..Default::default()
582 },
583 ApexInfo {
584 // 9
585 name: "sharedlibs".to_string(),
586 path: PathBuf::from("apex-foo/updated"),
587 last_update_seconds: 87654321 + 1,
588 is_active: true,
589 provide_shared_apex_libs: true,
590 ..Default::default()
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000591 },
592 ],
593 };
Jooyung Hanec788042022-01-27 22:28:37 +0900594 let apex_configs = vec![
595 ApexConfig { name: "apex-foo".to_string() },
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000596 ApexConfig { name: "{CLASSPATH}".to_string() },
597 ];
598 assert_eq!(
Jaewan Kim61f86142023-03-28 15:12:52 +0900599 collect_apex_infos(&apex_info_list, &apex_configs, &DebugConfig::new(DebugLevel::FULL)),
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000600 vec![
Jooyung Han5ce867a2022-01-28 03:18:38 +0900601 // Pass active/required APEXes
Jooyung Hanec788042022-01-27 22:28:37 +0900602 &apex_info_list.list[0],
603 &apex_info_list.list[2],
Jooyung Han5ce867a2022-01-28 03:18:38 +0900604 // Pass active APEXes specified in the config
Jooyung Hanec788042022-01-27 22:28:37 +0900605 &apex_info_list.list[5],
606 &apex_info_list.list[7],
Jooyung Han5ce867a2022-01-28 03:18:38 +0900607 // Pass both preinstalled(inactive) and updated(active) for "sharedlibs" APEXes
608 &apex_info_list.list[8],
609 &apex_info_list.list[9],
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000610 ]
611 );
612 }
Jooyung Han743e0d62022-11-07 20:57:48 +0900613
614 #[test]
615 fn test_prefer_staged_apex_with_factory_active_apex() {
616 let single_apex = ApexInfo {
617 name: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900618 version: 1,
Jooyung Han743e0d62022-11-07 20:57:48 +0900619 path: PathBuf::from("foo.apex"),
620 is_factory: true,
621 is_active: true,
622 ..Default::default()
623 };
624 let mut apex_info_list = ApexInfoList { list: vec![single_apex.clone()] };
625
626 let staged = NamedTempFile::new().unwrap();
627 apex_info_list
628 .override_staged_apex(&StagedApexInfo {
629 moduleName: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900630 versionCode: 2,
Jooyung Han743e0d62022-11-07 20:57:48 +0900631 diskImagePath: staged.path().to_string_lossy().to_string(),
632 ..Default::default()
633 })
634 .expect("should be ok");
635
636 assert_eq!(
637 apex_info_list,
638 ApexInfoList {
639 list: vec![
640 ApexInfo {
Jooyung Hancaa995c2022-11-08 16:35:50 +0900641 version: 2,
Jooyung Han743e0d62022-11-07 20:57:48 +0900642 is_factory: false,
643 path: staged.path().to_owned(),
644 last_update_seconds: last_updated(staged.path()).unwrap(),
645 ..single_apex.clone()
646 },
647 ApexInfo { is_active: false, ..single_apex },
648 ],
649 }
650 );
651 }
652
653 #[test]
654 fn test_prefer_staged_apex_with_factory_and_inactive_apex() {
655 let factory_apex = ApexInfo {
656 name: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900657 version: 1,
Jooyung Han743e0d62022-11-07 20:57:48 +0900658 path: PathBuf::from("foo.apex"),
659 is_factory: true,
660 ..Default::default()
661 };
662 let active_apex = ApexInfo {
663 name: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900664 version: 2,
Jooyung Han743e0d62022-11-07 20:57:48 +0900665 path: PathBuf::from("foo.downloaded.apex"),
666 is_active: true,
667 ..Default::default()
668 };
669 let mut apex_info_list =
670 ApexInfoList { list: vec![factory_apex.clone(), active_apex.clone()] };
671
672 let staged = NamedTempFile::new().unwrap();
673 apex_info_list
674 .override_staged_apex(&StagedApexInfo {
675 moduleName: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900676 versionCode: 3,
Jooyung Han743e0d62022-11-07 20:57:48 +0900677 diskImagePath: staged.path().to_string_lossy().to_string(),
678 ..Default::default()
679 })
680 .expect("should be ok");
681
682 assert_eq!(
683 apex_info_list,
684 ApexInfoList {
685 list: vec![
686 // factory apex isn't touched
687 factory_apex,
688 // update active one
689 ApexInfo {
Jooyung Hancaa995c2022-11-08 16:35:50 +0900690 version: 3,
Jooyung Han743e0d62022-11-07 20:57:48 +0900691 path: staged.path().to_owned(),
692 last_update_seconds: last_updated(staged.path()).unwrap(),
693 ..active_apex
694 },
695 ],
696 }
697 );
698 }
Jooyung Han5e0f2062021-10-12 14:00:46 +0900699}