blob: 733add64f960bd2e774de72c88ea8b687562dd0d [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 {
Ludovic Barman93ee3082023-06-20 12:18:43 +0000197 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) => {
Ludovic Barman93ee3082023-06-20 12:18:43 +0000202 PayloadMetadata::ConfigPath(format!("/mnt/apk/{}", config_path))
Alan Stokes0d1ef782022-09-27 13:46:35 +0100203 }
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
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,
Jaewan Kim61f86142023-03-28 15:12:52 +0900440 debug_config: &DebugConfig,
Shikha Panwar22e70452022-10-10 18:32:55 +0000441 temporary_directory: &Path,
442 apk_file: File,
443 idsig_file: File,
444 vm_payload_config: &VmPayloadConfig,
445 vm_config: &mut VirtualMachineRawConfig,
446) -> Result<()> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000447 vm_config.disks.push(make_payload_disk(
Inseob Kima5a262f2021-11-17 19:41:03 +0900448 config,
Jaewan Kim61f86142023-03-28 15:12:52 +0900449 debug_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000450 apk_file,
451 idsig_file,
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900452 vm_payload_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000453 temporary_directory,
454 )?);
455
Andrew Walbrancc0db522021-07-12 17:03:42 +0000456 Ok(())
457}
Jooyung Han5e0f2062021-10-12 14:00:46 +0900458
459#[cfg(test)]
460mod tests {
461 use super::*;
Jooyung Han743e0d62022-11-07 20:57:48 +0900462 use tempfile::NamedTempFile;
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000463
Jooyung Han5e0f2062021-10-12 14:00:46 +0900464 #[test]
Alan Stokesbf20c6a2022-01-04 12:30:50 +0000465 fn test_find_apex_names_in_classpath() {
466 let vars = r#"
467export FOO /apex/unterminated
468export BAR /apex/valid.apex/something
469wrong
470export EMPTY
471export OTHER /foo/bar:/baz:/apex/second.valid.apex/:gibberish:"#;
472 let expected = vec!["valid.apex", "second.valid.apex"];
473 let expected: HashSet<_> = expected.into_iter().map(ToString::to_string).collect();
474
475 assert_eq!(find_apex_names_in_classpath(vars).unwrap(), expected);
Jooyung Han5e0f2062021-10-12 14:00:46 +0900476 }
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000477
478 #[test]
Jooyung Hanec788042022-01-27 22:28:37 +0900479 fn test_collect_apexes() {
480 let apex_info_list = ApexInfoList {
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000481 list: vec![
482 ApexInfo {
Jooyung Hanec788042022-01-27 22:28:37 +0900483 // 0
484 name: "com.android.adbd".to_string(),
485 path: PathBuf::from("adbd"),
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000486 has_classpath_jar: false,
Andrew Walbran40be9d52022-01-19 14:32:53 +0000487 last_update_seconds: 12345678,
Jiyong Parkd6502352022-01-27 01:07:30 +0900488 is_factory: true,
Jooyung Hanec788042022-01-27 22:28:37 +0900489 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900490 ..Default::default()
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000491 },
492 ApexInfo {
Jooyung Hanec788042022-01-27 22:28:37 +0900493 // 1
494 name: "com.android.os.statsd".to_string(),
495 path: PathBuf::from("statsd"),
496 has_classpath_jar: false,
497 last_update_seconds: 12345678,
498 is_factory: true,
499 is_active: false,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900500 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900501 },
502 ApexInfo {
503 // 2
504 name: "com.android.os.statsd".to_string(),
505 path: PathBuf::from("statsd/updated"),
506 has_classpath_jar: false,
507 last_update_seconds: 12345678 + 1,
508 is_factory: false,
509 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900510 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900511 },
512 ApexInfo {
513 // 3
514 name: "no_classpath".to_string(),
515 path: PathBuf::from("no_classpath"),
516 has_classpath_jar: false,
517 last_update_seconds: 12345678,
518 is_factory: true,
519 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900520 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900521 },
522 ApexInfo {
523 // 4
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000524 name: "has_classpath".to_string(),
Jooyung Hanec788042022-01-27 22:28:37 +0900525 path: PathBuf::from("has_classpath"),
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000526 has_classpath_jar: true,
Andrew Walbran40be9d52022-01-19 14:32:53 +0000527 last_update_seconds: 87654321,
Jooyung Hanec788042022-01-27 22:28:37 +0900528 is_factory: true,
529 is_active: false,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900530 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900531 },
532 ApexInfo {
533 // 5
534 name: "has_classpath".to_string(),
535 path: PathBuf::from("has_classpath/updated"),
536 has_classpath_jar: true,
537 last_update_seconds: 87654321 + 1,
Jiyong Parkd6502352022-01-27 01:07:30 +0900538 is_factory: false,
Jooyung Hanec788042022-01-27 22:28:37 +0900539 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900540 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900541 },
542 ApexInfo {
543 // 6
544 name: "apex-foo".to_string(),
545 path: PathBuf::from("apex-foo"),
546 has_classpath_jar: false,
547 last_update_seconds: 87654321,
548 is_factory: true,
549 is_active: false,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900550 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900551 },
552 ApexInfo {
553 // 7
554 name: "apex-foo".to_string(),
555 path: PathBuf::from("apex-foo/updated"),
556 has_classpath_jar: false,
557 last_update_seconds: 87654321 + 1,
558 is_factory: false,
559 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900560 ..Default::default()
561 },
562 ApexInfo {
563 // 8
564 name: "sharedlibs".to_string(),
565 path: PathBuf::from("apex-foo"),
566 last_update_seconds: 87654321,
567 is_factory: true,
568 provide_shared_apex_libs: true,
569 ..Default::default()
570 },
571 ApexInfo {
572 // 9
573 name: "sharedlibs".to_string(),
574 path: PathBuf::from("apex-foo/updated"),
575 last_update_seconds: 87654321 + 1,
576 is_active: true,
577 provide_shared_apex_libs: true,
578 ..Default::default()
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000579 },
580 ],
581 };
Jooyung Hanec788042022-01-27 22:28:37 +0900582 let apex_configs = vec![
583 ApexConfig { name: "apex-foo".to_string() },
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000584 ApexConfig { name: "{CLASSPATH}".to_string() },
585 ];
586 assert_eq!(
Jaewan Kim61f86142023-03-28 15:12:52 +0900587 collect_apex_infos(&apex_info_list, &apex_configs, &DebugConfig::new(DebugLevel::FULL)),
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000588 vec![
Jooyung Han5ce867a2022-01-28 03:18:38 +0900589 // Pass active/required APEXes
Jooyung Hanec788042022-01-27 22:28:37 +0900590 &apex_info_list.list[0],
591 &apex_info_list.list[2],
Jooyung Han5ce867a2022-01-28 03:18:38 +0900592 // Pass active APEXes specified in the config
Jooyung Hanec788042022-01-27 22:28:37 +0900593 &apex_info_list.list[5],
594 &apex_info_list.list[7],
Jooyung Han5ce867a2022-01-28 03:18:38 +0900595 // Pass both preinstalled(inactive) and updated(active) for "sharedlibs" APEXes
596 &apex_info_list.list[8],
597 &apex_info_list.list[9],
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000598 ]
599 );
600 }
Jooyung Han743e0d62022-11-07 20:57:48 +0900601
602 #[test]
603 fn test_prefer_staged_apex_with_factory_active_apex() {
604 let single_apex = ApexInfo {
605 name: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900606 version: 1,
Jooyung Han743e0d62022-11-07 20:57:48 +0900607 path: PathBuf::from("foo.apex"),
608 is_factory: true,
609 is_active: true,
610 ..Default::default()
611 };
612 let mut apex_info_list = ApexInfoList { list: vec![single_apex.clone()] };
613
614 let staged = NamedTempFile::new().unwrap();
615 apex_info_list
616 .override_staged_apex(&StagedApexInfo {
617 moduleName: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900618 versionCode: 2,
Jooyung Han743e0d62022-11-07 20:57:48 +0900619 diskImagePath: staged.path().to_string_lossy().to_string(),
620 ..Default::default()
621 })
622 .expect("should be ok");
623
624 assert_eq!(
625 apex_info_list,
626 ApexInfoList {
627 list: vec![
628 ApexInfo {
Jooyung Hancaa995c2022-11-08 16:35:50 +0900629 version: 2,
Jooyung Han743e0d62022-11-07 20:57:48 +0900630 is_factory: false,
631 path: staged.path().to_owned(),
632 last_update_seconds: last_updated(staged.path()).unwrap(),
633 ..single_apex.clone()
634 },
635 ApexInfo { is_active: false, ..single_apex },
636 ],
637 }
638 );
639 }
640
641 #[test]
642 fn test_prefer_staged_apex_with_factory_and_inactive_apex() {
643 let factory_apex = ApexInfo {
644 name: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900645 version: 1,
Jooyung Han743e0d62022-11-07 20:57:48 +0900646 path: PathBuf::from("foo.apex"),
647 is_factory: true,
648 ..Default::default()
649 };
650 let active_apex = ApexInfo {
651 name: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900652 version: 2,
Jooyung Han743e0d62022-11-07 20:57:48 +0900653 path: PathBuf::from("foo.downloaded.apex"),
654 is_active: true,
655 ..Default::default()
656 };
657 let mut apex_info_list =
658 ApexInfoList { list: vec![factory_apex.clone(), active_apex.clone()] };
659
660 let staged = NamedTempFile::new().unwrap();
661 apex_info_list
662 .override_staged_apex(&StagedApexInfo {
663 moduleName: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900664 versionCode: 3,
Jooyung Han743e0d62022-11-07 20:57:48 +0900665 diskImagePath: staged.path().to_string_lossy().to_string(),
666 ..Default::default()
667 })
668 .expect("should be ok");
669
670 assert_eq!(
671 apex_info_list,
672 ApexInfoList {
673 list: vec![
674 // factory apex isn't touched
675 factory_apex,
676 // update active one
677 ApexInfo {
Jooyung Hancaa995c2022-11-08 16:35:50 +0900678 version: 3,
Jooyung Han743e0d62022-11-07 20:57:48 +0900679 path: staged.path().to_owned(),
680 last_update_seconds: last_updated(staged.path()).unwrap(),
681 ..active_apex
682 },
683 ],
684 }
685 );
686 }
Jooyung Han5e0f2062021-10-12 14:00:46 +0900687}