blob: 9d0c7d69d781cdcc4e44402147a0f6c8481f76ed [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
Jooyung Han44b02ab2021-07-16 03:19:13 +090044const APEX_INFO_LIST_PATH: &str = "/apex/apex-info-list.xml";
45
Jooyung Han5dc42172021-10-05 16:43:47 +090046const PACKAGE_MANAGER_NATIVE_SERVICE: &str = "package_native";
47
Jooyung Han73bac242021-07-02 10:25:49 +090048/// Represents the list of APEXes
Jooyung Han743e0d62022-11-07 20:57:48 +090049#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
Jooyung Han9900f3d2021-07-06 10:27:54 +090050struct ApexInfoList {
Jooyung Han44b02ab2021-07-16 03:19:13 +090051 #[serde(rename = "apex-info")]
Jooyung Han73bac242021-07-02 10:25:49 +090052 list: Vec<ApexInfo>,
53}
54
Jooyung Han5ce867a2022-01-28 03:18:38 +090055#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
Jooyung Han73bac242021-07-02 10:25:49 +090056struct ApexInfo {
Jooyung Han44b02ab2021-07-16 03:19:13 +090057 #[serde(rename = "moduleName")]
Jooyung Han73bac242021-07-02 10:25:49 +090058 name: String,
Jooyung Hancaa995c2022-11-08 16:35:50 +090059 #[serde(rename = "versionCode")]
60 version: u64,
Jooyung Han44b02ab2021-07-16 03:19:13 +090061 #[serde(rename = "modulePath")]
Jooyung Han73bac242021-07-02 10:25:49 +090062 path: PathBuf,
Jooyung Han9d7cd7d2021-10-12 17:44:14 +090063
64 #[serde(default)]
Alan Stokes46ac3862021-12-21 15:31:47 +000065 has_classpath_jar: bool,
Andrew Walbran40be9d52022-01-19 14:32:53 +000066
67 // The field claims to be milliseconds but is actually seconds.
68 #[serde(rename = "lastUpdateMillis")]
69 last_update_seconds: u64,
Jiyong Parkd6502352022-01-27 01:07:30 +090070
71 #[serde(rename = "isFactory")]
72 is_factory: bool,
Jooyung Hanec788042022-01-27 22:28:37 +090073
74 #[serde(rename = "isActive")]
75 is_active: bool,
Jooyung Han5ce867a2022-01-28 03:18:38 +090076
77 #[serde(rename = "provideSharedApexLibs")]
78 provide_shared_apex_libs: bool,
Nikita Ioffed4551e12023-07-14 16:01:03 +010079
80 #[serde(rename = "preinstalledModulePath")]
81 preinstalled_path: PathBuf,
Jooyung Han73bac242021-07-02 10:25:49 +090082}
83
84impl ApexInfoList {
85 /// Loads ApexInfoList
Jooyung Han9900f3d2021-07-06 10:27:54 +090086 fn load() -> Result<&'static ApexInfoList> {
87 static INSTANCE: OnceCell<ApexInfoList> = OnceCell::new();
88 INSTANCE.get_or_try_init(|| {
Jooyung Han44b02ab2021-07-16 03:19:13 +090089 let apex_info_list = File::open(APEX_INFO_LIST_PATH)
90 .context(format!("Failed to open {}", APEX_INFO_LIST_PATH))?;
Jooyung Han9d7cd7d2021-10-12 17:44:14 +090091 let mut apex_info_list: ApexInfoList = from_reader(apex_info_list)
Jooyung Han44b02ab2021-07-16 03:19:13 +090092 .context(format!("Failed to parse {}", APEX_INFO_LIST_PATH))?;
Jooyung Han9d7cd7d2021-10-12 17:44:14 +090093
Alan Stokesbf20c6a2022-01-04 12:30:50 +000094 // For active APEXes, we run derive_classpath and parse its output to see if it
95 // contributes to the classpath(s). (This allows us to handle any new classpath env
96 // vars seamlessly.)
97 let classpath_vars = run_derive_classpath()?;
98 let classpath_apexes = find_apex_names_in_classpath(&classpath_vars)?;
99
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900100 for apex_info in apex_info_list.list.iter_mut() {
Alan Stokesbf20c6a2022-01-04 12:30:50 +0000101 apex_info.has_classpath_jar = classpath_apexes.contains(&apex_info.name);
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900102 }
Alan Stokesbf20c6a2022-01-04 12:30:50 +0000103
Jooyung Han44b02ab2021-07-16 03:19:13 +0900104 Ok(apex_info_list)
Jooyung Han9900f3d2021-07-06 10:27:54 +0900105 })
Jooyung Han73bac242021-07-02 10:25:49 +0900106 }
Jooyung Han743e0d62022-11-07 20:57:48 +0900107
108 // Override apex info with the staged one
109 fn override_staged_apex(&mut self, staged_apex_info: &StagedApexInfo) -> Result<()> {
110 let mut need_to_add: Option<ApexInfo> = None;
111 for apex_info in self.list.iter_mut() {
112 if staged_apex_info.moduleName == apex_info.name {
113 if apex_info.is_active && apex_info.is_factory {
114 // Copy the entry to the end as factory/non-active after the loop
115 // to keep the factory version. Typically this step is unncessary,
116 // but some apexes (like sharedlibs) need to be kept even if it's inactive.
117 need_to_add.replace(ApexInfo { is_active: false, ..apex_info.clone() });
118 // And make this one as non-factory. Note that this one is still active
119 // and overridden right below.
120 apex_info.is_factory = false;
121 }
122 // Active one is overridden with the staged one.
123 if apex_info.is_active {
Jooyung Hancaa995c2022-11-08 16:35:50 +0900124 apex_info.version = staged_apex_info.versionCode as u64;
Jooyung Han743e0d62022-11-07 20:57:48 +0900125 apex_info.path = PathBuf::from(&staged_apex_info.diskImagePath);
126 apex_info.has_classpath_jar = staged_apex_info.hasClassPathJars;
127 apex_info.last_update_seconds = last_updated(&apex_info.path)?;
128 }
129 }
130 }
131 if let Some(info) = need_to_add {
132 self.list.push(info);
133 }
134 Ok(())
135 }
136}
137
138fn last_updated<P: AsRef<Path>>(path: P) -> Result<u64> {
139 let metadata = metadata(path)?;
140 Ok(metadata.modified()?.duration_since(SystemTime::UNIX_EPOCH)?.as_secs())
Jooyung Hanec788042022-01-27 22:28:37 +0900141}
Jooyung Han73bac242021-07-02 10:25:49 +0900142
Jooyung Hanec788042022-01-27 22:28:37 +0900143impl ApexInfo {
144 fn matches(&self, apex_config: &ApexConfig) -> bool {
145 // Match with pseudo name "{CLASSPATH}" which represents APEXes contributing
146 // to any derive_classpath environment variable
147 if apex_config.name == "{CLASSPATH}" && self.has_classpath_jar {
148 return true;
149 }
150 if apex_config.name == self.name {
151 return true;
152 }
153 false
Jooyung Han73bac242021-07-02 10:25:49 +0900154 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900155}
156
Jooyung Han5dc42172021-10-05 16:43:47 +0900157struct PackageManager {
Jooyung Han5dc42172021-10-05 16:43:47 +0900158 apex_info_list: &'static ApexInfoList,
159}
160
161impl PackageManager {
162 fn new() -> Result<Self> {
Jooyung Han5dc42172021-10-05 16:43:47 +0900163 let apex_info_list = ApexInfoList::load()?;
Jooyung Han53cf7992021-10-18 19:38:41 +0900164 Ok(Self { apex_info_list })
Jooyung Han5dc42172021-10-05 16:43:47 +0900165 }
166
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900167 fn get_apex_list(&self, prefer_staged: bool) -> Result<ApexInfoList> {
Jooyung Han53cf7992021-10-18 19:38:41 +0900168 // get the list of active apexes
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900169 let mut list = self.apex_info_list.clone();
Jooyung Han53cf7992021-10-18 19:38:41 +0900170 // When prefer_staged, we override ApexInfo by consulting "package_native"
Jooyung Han5dc42172021-10-05 16:43:47 +0900171 if prefer_staged {
Jooyung Han53cf7992021-10-18 19:38:41 +0900172 let pm =
173 wait_for_interface::<dyn IPackageManagerNative>(PACKAGE_MANAGER_NATIVE_SERVICE)
174 .context("Failed to get service when prefer_staged is set.")?;
Alan Stokes70ccf162022-07-08 11:05:03 +0100175 let staged =
176 pm.getStagedApexModuleNames().context("getStagedApexModuleNames failed")?;
Jooyung Han743e0d62022-11-07 20:57:48 +0900177 for name in staged {
178 if let Some(staged_apex_info) =
179 pm.getStagedApexInfo(&name).context("getStagedApexInfo failed")?
180 {
181 list.override_staged_apex(&staged_apex_info)?;
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900182 }
Jooyung Han5dc42172021-10-05 16:43:47 +0900183 }
184 }
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900185 Ok(list)
Jooyung Han5dc42172021-10-05 16:43:47 +0900186 }
187}
188
Andrew Walbrancc0db522021-07-12 17:03:42 +0000189fn make_metadata_file(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100190 app_config: &VirtualMachineAppConfig,
Jooyung Hanec788042022-01-27 22:28:37 +0900191 apex_infos: &[&ApexInfo],
Jooyung Han21e9b922021-06-26 04:14:16 +0900192 temporary_directory: &Path,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000193) -> Result<ParcelFileDescriptor> {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100194 let payload_metadata = match &app_config.payload {
Ludovic Barman93ee3082023-06-20 12:18:43 +0000195 Payload::PayloadConfig(payload_config) => PayloadMetadata::Config(PayloadConfig {
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000196 payload_binary_name: payload_config.payloadBinaryName.clone(),
Alan Stokesfda70842023-12-20 17:50:14 +0000197 extra_apk_count: payload_config.extraApks.len().try_into()?,
198 special_fields: Default::default(),
Alan Stokes0d1ef782022-09-27 13:46:35 +0100199 }),
200 Payload::ConfigPath(config_path) => {
Ludovic Barman93ee3082023-06-20 12:18:43 +0000201 PayloadMetadata::ConfigPath(format!("/mnt/apk/{}", config_path))
Alan Stokes0d1ef782022-09-27 13:46:35 +0100202 }
203 };
204
Jooyung Han21e9b922021-06-26 04:14:16 +0900205 let metadata = Metadata {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000206 version: 1,
Jooyung Hanec788042022-01-27 22:28:37 +0900207 apexes: apex_infos
Jooyung Han21e9b922021-06-26 04:14:16 +0900208 .iter()
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900209 .enumerate()
Jooyung Hanec788042022-01-27 22:28:37 +0900210 .map(|(i, apex_info)| {
Andrew Walbran40be9d52022-01-19 14:32:53 +0000211 Ok(ApexPayload {
Jooyung Hanec788042022-01-27 22:28:37 +0900212 name: apex_info.name.clone(),
Andrew Walbran40be9d52022-01-19 14:32:53 +0000213 partition_name: format!("microdroid-apex-{}", i),
Jiyong Parkd6502352022-01-27 01:07:30 +0900214 last_update_seconds: apex_info.last_update_seconds,
215 is_factory: apex_info.is_factory,
Andrew Walbran40be9d52022-01-19 14:32:53 +0000216 ..Default::default()
217 })
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900218 })
Andrew Walbran40be9d52022-01-19 14:32:53 +0000219 .collect::<Result<_>>()?,
Jooyung Han21e9b922021-06-26 04:14:16 +0900220 apk: Some(ApkPayload {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900221 name: "apk".to_owned(),
222 payload_partition_name: "microdroid-apk".to_owned(),
223 idsig_partition_name: "microdroid-apk-idsig".to_owned(),
Jooyung Han21e9b922021-06-26 04:14:16 +0900224 ..Default::default()
225 })
226 .into(),
Alan Stokes0d1ef782022-09-27 13:46:35 +0100227 payload: Some(payload_metadata),
Jooyung Han21e9b922021-06-26 04:14:16 +0900228 ..Default::default()
229 };
Andrew Walbrancc0db522021-07-12 17:03:42 +0000230
231 // Write metadata to file.
Alan Stokes0d1ef782022-09-27 13:46:35 +0100232 let metadata_path = temporary_directory.join("metadata");
Andrew Walbrancc0db522021-07-12 17:03:42 +0000233 let mut metadata_file = OpenOptions::new()
234 .create_new(true)
235 .read(true)
236 .write(true)
237 .open(&metadata_path)
238 .with_context(|| format!("Failed to open metadata file {:?}", metadata_path))?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900239 microdroid_metadata::write_metadata(&metadata, &mut metadata_file)?;
240
Andrew Walbrancc0db522021-07-12 17:03:42 +0000241 // Re-open the metadata file as read-only.
242 open_parcel_file(&metadata_path, false)
243}
244
245/// Creates a DiskImage with partitions:
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100246/// payload-metadata: metadata
Andrew Walbrancc0db522021-07-12 17:03:42 +0000247/// microdroid-apex-0: apex 0
248/// microdroid-apex-1: apex 1
249/// ..
250/// microdroid-apk: apk
251/// microdroid-apk-idsig: idsig
Inseob Kima5a262f2021-11-17 19:41:03 +0900252/// extra-apk-0: additional apk 0
253/// extra-idsig-0: additional idsig 0
254/// extra-apk-1: additional apk 1
255/// extra-idsig-1: additional idsig 1
256/// ..
Andrew Walbrancc0db522021-07-12 17:03:42 +0000257fn make_payload_disk(
Inseob Kima5a262f2021-11-17 19:41:03 +0900258 app_config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +0900259 debug_config: &DebugConfig,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000260 apk_file: File,
261 idsig_file: File,
Alan Stokesfda70842023-12-20 17:50:14 +0000262 extra_apk_files: Vec<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> {
Alan Stokesfda70842023-12-20 17:50:14 +0000266 if extra_apk_files.len() != app_config.extraIdsigs.len() {
Inseob Kima5a262f2021-11-17 19:41:03 +0900267 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
Nikita Ioffed4551e12023-07-14 16:01:03 +0100278 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.
Inseob Kima5a262f2021-11-17 19:41:03 +0900314 let extra_idsigs = &app_config.extraIdsigs;
Alan Stokesfda70842023-12-20 17:50:14 +0000315 for (i, (extra_apk_file, extra_idsig)) in
316 extra_apk_files.into_iter().zip(extra_idsigs.iter()).enumerate()
317 {
Inseob Kima5a262f2021-11-17 19:41:03 +0900318 partitions.push(Partition {
Alan Stokesfda70842023-12-20 17:50:14 +0000319 label: format!("extra-apk-{i}"),
320 image: Some(ParcelFileDescriptor::new(extra_apk_file)),
Inseob Kima5a262f2021-11-17 19:41:03 +0900321 writable: false,
322 });
323
324 partitions.push(Partition {
Alan Stokesfda70842023-12-20 17:50:14 +0000325 label: format!("extra-idsig-{i}"),
Victor Hsieh14497f02022-09-21 10:10:16 -0700326 image: Some(ParcelFileDescriptor::new(
327 extra_idsig
328 .as_ref()
329 .try_clone()
Alan Stokesfda70842023-12-20 17:50:14 +0000330 .with_context(|| format!("Failed to clone the extra idsig #{i}"))?,
Victor Hsieh14497f02022-09-21 10:10:16 -0700331 )),
Inseob Kima5a262f2021-11-17 19:41:03 +0900332 writable: false,
333 });
334 }
335
Jooyung Han21e9b922021-06-26 04:14:16 +0900336 Ok(DiskImage { image: None, partitions, writable: false })
337}
Andrew Walbrancc0db522021-07-12 17:03:42 +0000338
Alan Stokesbf20c6a2022-01-04 12:30:50 +0000339fn run_derive_classpath() -> Result<String> {
340 let result = Command::new("/apex/com.android.sdkext/bin/derive_classpath")
341 .arg("/proc/self/fd/1")
342 .output()
343 .context("Failed to run derive_classpath")?;
344
345 if !result.status.success() {
346 bail!("derive_classpath returned {}", result.status);
347 }
348
349 String::from_utf8(result.stdout).context("Converting derive_classpath output")
350}
351
352fn find_apex_names_in_classpath(classpath_vars: &str) -> Result<HashSet<String>> {
353 // Each line should be in the format "export <var name> <paths>", where <paths> is a
354 // colon-separated list of paths to JARs. We don't care about the var names, and we're only
355 // interested in paths that look like "/apex/<apex name>/<anything>" so we know which APEXes
356 // contribute to at least one var.
357 let mut apexes = HashSet::new();
358
359 let pattern = Regex::new(r"^export [^ ]+ ([^ ]+)$").context("Failed to construct Regex")?;
360 for line in classpath_vars.lines() {
361 if let Some(captures) = pattern.captures(line) {
362 if let Some(paths) = captures.get(1) {
363 apexes.extend(paths.as_str().split(':').filter_map(|path| {
364 let path = path.strip_prefix("/apex/")?;
365 Some(path[..path.find('/')?].to_owned())
366 }));
367 continue;
368 }
369 }
370 warn!("Malformed line from derive_classpath: {}", line);
371 }
372
373 Ok(apexes)
Jooyung Han5e0f2062021-10-12 14:00:46 +0900374}
375
Nikita Ioffed4551e12023-07-14 16:01:03 +0100376fn check_apexes_are_from_allowed_partitions(requested_apexes: &Vec<&ApexInfo>) -> Result<()> {
377 const ALLOWED_PARTITIONS: [&str; 2] = ["/system", "/system_ext"];
378 for apex in requested_apexes {
379 if !ALLOWED_PARTITIONS.iter().any(|p| apex.preinstalled_path.starts_with(p)) {
380 bail!("Non-system APEX {} is not supported in Microdroid", apex.name);
381 }
382 }
383 Ok(())
384}
385
Jooyung Hanec788042022-01-27 22:28:37 +0900386// Collect ApexInfos from VM config
387fn collect_apex_infos<'a>(
388 apex_list: &'a ApexInfoList,
389 apex_configs: &[ApexConfig],
Jaewan Kim61f86142023-03-28 15:12:52 +0900390 debug_config: &DebugConfig,
Nikita Ioffed4551e12023-07-14 16:01:03 +0100391) -> Result<Vec<&'a ApexInfo>> {
Alan Stokesf7260f12023-08-30 17:25:21 +0100392 // APEXes which any Microdroid VM needs.
393 // TODO(b/192200378) move this to microdroid.json?
394 let required_apexes: &[_] =
395 if debug_config.should_include_debug_apexes() { &["com.android.adbd"] } else { &[] };
Jooyung Hanec788042022-01-27 22:28:37 +0900396
Nikita Ioffed4551e12023-07-14 16:01:03 +0100397 let apex_infos = apex_list
Jooyung Hanec788042022-01-27 22:28:37 +0900398 .list
399 .iter()
400 .filter(|ai| {
401 apex_configs.iter().any(|cfg| ai.matches(cfg) && ai.is_active)
Alan Stokesf7260f12023-08-30 17:25:21 +0100402 || required_apexes.iter().any(|name| name == &ai.name && ai.is_active)
Jooyung Han5ce867a2022-01-28 03:18:38 +0900403 || ai.provide_shared_apex_libs
Jooyung Hanec788042022-01-27 22:28:37 +0900404 })
Nikita Ioffed4551e12023-07-14 16:01:03 +0100405 .collect();
406
407 check_apexes_are_from_allowed_partitions(&apex_infos)?;
408 Ok(apex_infos)
Jooyung Han5e0f2062021-10-12 14:00:46 +0900409}
410
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100411pub fn add_microdroid_vendor_image(vendor_image: File, vm_config: &mut VirtualMachineRawConfig) {
412 vm_config.disks.push(DiskImage {
413 image: None,
414 writable: false,
415 partitions: vec![Partition {
416 label: "microdroid-vendor".to_owned(),
417 image: Some(ParcelFileDescriptor::new(vendor_image)),
418 writable: false,
419 }],
420 })
421}
422
Shikha Panwar22e70452022-10-10 18:32:55 +0000423pub fn add_microdroid_system_images(
Andrew Walbrancc0db522021-07-12 17:03:42 +0000424 config: &VirtualMachineAppConfig,
Jiyong Park8d081812021-07-23 17:45:04 +0900425 instance_file: File,
Shikha Panwar22e70452022-10-10 18:32:55 +0000426 storage_image: Option<File>,
Inseob Kim172f9eb2023-11-06 17:02:08 +0900427 os_name: &str,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000428 vm_config: &mut VirtualMachineRawConfig,
429) -> Result<()> {
Shikha Panwared8ace42022-09-28 12:52:16 +0000430 let debug_suffix = match config.debugLevel {
431 DebugLevel::NONE => "normal",
Seungjae Yooe85831e2022-12-12 09:34:58 +0900432 DebugLevel::FULL => "debuggable",
Shikha Panwared8ace42022-09-28 12:52:16 +0000433 _ => return Err(anyhow!("unsupported debug level: {:?}", config.debugLevel)),
434 };
Inseob Kim172f9eb2023-11-06 17:02:08 +0900435 let initrd = format!("/apex/com.android.virt/etc/{os_name}_initrd_{debug_suffix}.img");
Shikha Panwared8ace42022-09-28 12:52:16 +0000436 vm_config.initrd = Some(open_parcel_file(Path::new(&initrd), false)?);
437
Shikha Panwar22e70452022-10-10 18:32:55 +0000438 let mut writable_partitions = vec![Partition {
Shikha Panwared8ace42022-09-28 12:52:16 +0000439 label: "vm-instance".to_owned(),
440 image: Some(ParcelFileDescriptor::new(instance_file)),
441 writable: true,
Shikha Panwar22e70452022-10-10 18:32:55 +0000442 }];
443
444 if let Some(file) = storage_image {
445 writable_partitions.push(Partition {
Shikha Panwar566c9672022-11-15 14:39:58 +0000446 label: "encryptedstore".to_owned(),
Shikha Panwar22e70452022-10-10 18:32:55 +0000447 image: Some(ParcelFileDescriptor::new(file)),
448 writable: true,
449 });
450 }
451
452 vm_config.disks.push(DiskImage {
453 image: None,
454 partitions: writable_partitions,
455 writable: true,
456 });
457
458 Ok(())
459}
460
Alan Stokesfda70842023-12-20 17:50:14 +0000461#[allow(clippy::too_many_arguments)] // TODO: Fewer arguments
Shikha Panwar22e70452022-10-10 18:32:55 +0000462pub fn add_microdroid_payload_images(
463 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +0900464 debug_config: &DebugConfig,
Shikha Panwar22e70452022-10-10 18:32:55 +0000465 temporary_directory: &Path,
466 apk_file: File,
467 idsig_file: File,
Alan Stokesfda70842023-12-20 17:50:14 +0000468 extra_apk_files: Vec<File>,
Shikha Panwar22e70452022-10-10 18:32:55 +0000469 vm_payload_config: &VmPayloadConfig,
470 vm_config: &mut VirtualMachineRawConfig,
471) -> Result<()> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000472 vm_config.disks.push(make_payload_disk(
Inseob Kima5a262f2021-11-17 19:41:03 +0900473 config,
Jaewan Kim61f86142023-03-28 15:12:52 +0900474 debug_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000475 apk_file,
476 idsig_file,
Alan Stokesfda70842023-12-20 17:50:14 +0000477 extra_apk_files,
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900478 vm_payload_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000479 temporary_directory,
480 )?);
481
Andrew Walbrancc0db522021-07-12 17:03:42 +0000482 Ok(())
483}
Jooyung Han5e0f2062021-10-12 14:00:46 +0900484
485#[cfg(test)]
486mod tests {
487 use super::*;
Alan Stokesf7260f12023-08-30 17:25:21 +0100488 use std::collections::HashMap;
Jooyung Han743e0d62022-11-07 20:57:48 +0900489 use tempfile::NamedTempFile;
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000490
Jooyung Han5e0f2062021-10-12 14:00:46 +0900491 #[test]
Alan Stokesbf20c6a2022-01-04 12:30:50 +0000492 fn test_find_apex_names_in_classpath() {
493 let vars = r#"
494export FOO /apex/unterminated
495export BAR /apex/valid.apex/something
496wrong
497export EMPTY
498export OTHER /foo/bar:/baz:/apex/second.valid.apex/:gibberish:"#;
499 let expected = vec!["valid.apex", "second.valid.apex"];
500 let expected: HashSet<_> = expected.into_iter().map(ToString::to_string).collect();
501
502 assert_eq!(find_apex_names_in_classpath(vars).unwrap(), expected);
Jooyung Han5e0f2062021-10-12 14:00:46 +0900503 }
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000504
505 #[test]
Nikita Ioffed4551e12023-07-14 16:01:03 +0100506 fn test_collect_apexes() -> Result<()> {
Alan Stokesf7260f12023-08-30 17:25:21 +0100507 let apex_infos_for_test = [
508 (
509 "adbd",
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000510 ApexInfo {
Jooyung Hanec788042022-01-27 22:28:37 +0900511 name: "com.android.adbd".to_string(),
512 path: PathBuf::from("adbd"),
Nikita Ioffed4551e12023-07-14 16:01:03 +0100513 preinstalled_path: PathBuf::from("/system/adbd"),
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000514 has_classpath_jar: false,
Andrew Walbran40be9d52022-01-19 14:32:53 +0000515 last_update_seconds: 12345678,
Jiyong Parkd6502352022-01-27 01:07:30 +0900516 is_factory: true,
Jooyung Hanec788042022-01-27 22:28:37 +0900517 is_active: false,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900518 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900519 },
Alan Stokesf7260f12023-08-30 17:25:21 +0100520 ),
521 (
522 "adbd_updated",
Jooyung Hanec788042022-01-27 22:28:37 +0900523 ApexInfo {
Alan Stokesf7260f12023-08-30 17:25:21 +0100524 name: "com.android.adbd".to_string(),
525 path: PathBuf::from("adbd"),
526 preinstalled_path: PathBuf::from("/system/adbd"),
Jooyung Hanec788042022-01-27 22:28:37 +0900527 has_classpath_jar: false,
528 last_update_seconds: 12345678 + 1,
529 is_factory: false,
530 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900531 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900532 },
Alan Stokesf7260f12023-08-30 17:25:21 +0100533 ),
534 (
535 "no_classpath",
Jooyung Hanec788042022-01-27 22:28:37 +0900536 ApexInfo {
Jooyung Hanec788042022-01-27 22:28:37 +0900537 name: "no_classpath".to_string(),
538 path: PathBuf::from("no_classpath"),
539 has_classpath_jar: false,
540 last_update_seconds: 12345678,
541 is_factory: true,
542 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900543 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900544 },
Alan Stokesf7260f12023-08-30 17:25:21 +0100545 ),
546 (
547 "has_classpath",
Jooyung Hanec788042022-01-27 22:28:37 +0900548 ApexInfo {
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000549 name: "has_classpath".to_string(),
Jooyung Hanec788042022-01-27 22:28:37 +0900550 path: PathBuf::from("has_classpath"),
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000551 has_classpath_jar: true,
Andrew Walbran40be9d52022-01-19 14:32:53 +0000552 last_update_seconds: 87654321,
Jooyung Hanec788042022-01-27 22:28:37 +0900553 is_factory: true,
554 is_active: false,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900555 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900556 },
Alan Stokesf7260f12023-08-30 17:25:21 +0100557 ),
558 (
559 "has_classpath_updated",
Jooyung Hanec788042022-01-27 22:28:37 +0900560 ApexInfo {
Jooyung Hanec788042022-01-27 22:28:37 +0900561 name: "has_classpath".to_string(),
562 path: PathBuf::from("has_classpath/updated"),
Nikita Ioffed4551e12023-07-14 16:01:03 +0100563 preinstalled_path: PathBuf::from("/system/has_classpath"),
Jooyung Hanec788042022-01-27 22:28:37 +0900564 has_classpath_jar: true,
565 last_update_seconds: 87654321 + 1,
Jiyong Parkd6502352022-01-27 01:07:30 +0900566 is_factory: false,
Jooyung Hanec788042022-01-27 22:28:37 +0900567 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900568 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900569 },
Alan Stokesf7260f12023-08-30 17:25:21 +0100570 ),
571 (
572 "apex-foo",
Jooyung Hanec788042022-01-27 22:28:37 +0900573 ApexInfo {
Jooyung Hanec788042022-01-27 22:28:37 +0900574 name: "apex-foo".to_string(),
575 path: PathBuf::from("apex-foo"),
Nikita Ioffed4551e12023-07-14 16:01:03 +0100576 preinstalled_path: PathBuf::from("/system/apex-foo"),
Jooyung Hanec788042022-01-27 22:28:37 +0900577 has_classpath_jar: false,
578 last_update_seconds: 87654321,
579 is_factory: true,
580 is_active: false,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900581 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900582 },
Alan Stokesf7260f12023-08-30 17:25:21 +0100583 ),
584 (
585 "apex-foo-updated",
Jooyung Hanec788042022-01-27 22:28:37 +0900586 ApexInfo {
Jooyung Hanec788042022-01-27 22:28:37 +0900587 name: "apex-foo".to_string(),
588 path: PathBuf::from("apex-foo/updated"),
Nikita Ioffed4551e12023-07-14 16:01:03 +0100589 preinstalled_path: PathBuf::from("/system/apex-foo"),
Jooyung Hanec788042022-01-27 22:28:37 +0900590 has_classpath_jar: false,
591 last_update_seconds: 87654321 + 1,
592 is_factory: false,
593 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900594 ..Default::default()
595 },
Alan Stokesf7260f12023-08-30 17:25:21 +0100596 ),
597 (
598 "sharedlibs",
Jooyung Han5ce867a2022-01-28 03:18:38 +0900599 ApexInfo {
Jooyung Han5ce867a2022-01-28 03:18:38 +0900600 name: "sharedlibs".to_string(),
601 path: PathBuf::from("apex-foo"),
Nikita Ioffed4551e12023-07-14 16:01:03 +0100602 preinstalled_path: PathBuf::from("/system/apex-foo"),
Jooyung Han5ce867a2022-01-28 03:18:38 +0900603 last_update_seconds: 87654321,
604 is_factory: true,
605 provide_shared_apex_libs: true,
606 ..Default::default()
607 },
Alan Stokesf7260f12023-08-30 17:25:21 +0100608 ),
609 (
610 "sharedlibs-updated",
Jooyung Han5ce867a2022-01-28 03:18:38 +0900611 ApexInfo {
Jooyung Han5ce867a2022-01-28 03:18:38 +0900612 name: "sharedlibs".to_string(),
613 path: PathBuf::from("apex-foo/updated"),
Nikita Ioffed4551e12023-07-14 16:01:03 +0100614 preinstalled_path: PathBuf::from("/system/apex-foo"),
Jooyung Han5ce867a2022-01-28 03:18:38 +0900615 last_update_seconds: 87654321 + 1,
616 is_active: true,
617 provide_shared_apex_libs: true,
618 ..Default::default()
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000619 },
Alan Stokesf7260f12023-08-30 17:25:21 +0100620 ),
621 ];
622 let apex_info_list = ApexInfoList {
623 list: apex_infos_for_test.iter().map(|(_, info)| info).cloned().collect(),
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000624 };
Alan Stokesf7260f12023-08-30 17:25:21 +0100625 let apex_info_map = HashMap::from(apex_infos_for_test);
Jooyung Hanec788042022-01-27 22:28:37 +0900626 let apex_configs = vec![
627 ApexConfig { name: "apex-foo".to_string() },
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000628 ApexConfig { name: "{CLASSPATH}".to_string() },
629 ];
630 assert_eq!(
Nikita Ioffed4551e12023-07-14 16:01:03 +0100631 collect_apex_infos(
632 &apex_info_list,
633 &apex_configs,
Jaewan Kimf3143242024-03-15 06:56:31 +0000634 &DebugConfig::new_with_debug_level(DebugLevel::FULL)
Nikita Ioffed4551e12023-07-14 16:01:03 +0100635 )?,
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000636 vec![
Jooyung Han5ce867a2022-01-28 03:18:38 +0900637 // Pass active/required APEXes
Alan Stokesf7260f12023-08-30 17:25:21 +0100638 &apex_info_map["adbd_updated"],
Jooyung Han5ce867a2022-01-28 03:18:38 +0900639 // Pass active APEXes specified in the config
Alan Stokesf7260f12023-08-30 17:25:21 +0100640 &apex_info_map["has_classpath_updated"],
641 &apex_info_map["apex-foo-updated"],
Jooyung Han5ce867a2022-01-28 03:18:38 +0900642 // Pass both preinstalled(inactive) and updated(active) for "sharedlibs" APEXes
Alan Stokesf7260f12023-08-30 17:25:21 +0100643 &apex_info_map["sharedlibs"],
644 &apex_info_map["sharedlibs-updated"],
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000645 ]
646 );
Nikita Ioffed4551e12023-07-14 16:01:03 +0100647 Ok(())
648 }
649
650 #[test]
651 fn test_check_allowed_partitions_vendor_not_allowed() -> Result<()> {
652 let apex_info_list = ApexInfoList {
653 list: vec![ApexInfo {
654 name: "apex-vendor".to_string(),
655 path: PathBuf::from("apex-vendor"),
656 preinstalled_path: PathBuf::from("/vendor/apex-vendor"),
657 is_active: true,
658 ..Default::default()
659 }],
660 };
661 let apex_configs = vec![ApexConfig { name: "apex-vendor".to_string() }];
662
Jaewan Kimf3143242024-03-15 06:56:31 +0000663 let ret = collect_apex_infos(
664 &apex_info_list,
665 &apex_configs,
666 &DebugConfig::new_with_debug_level(DebugLevel::NONE),
667 );
Nikita Ioffed4551e12023-07-14 16:01:03 +0100668 assert!(ret
669 .is_err_and(|ret| ret.to_string()
670 == "Non-system APEX apex-vendor is not supported in Microdroid"));
671
672 Ok(())
673 }
674
675 #[test]
676 fn test_check_allowed_partitions_system_ext_allowed() -> Result<()> {
677 let apex_info_list = ApexInfoList {
678 list: vec![ApexInfo {
679 name: "apex-system_ext".to_string(),
680 path: PathBuf::from("apex-system_ext"),
681 preinstalled_path: PathBuf::from("/system_ext/apex-system_ext"),
682 is_active: true,
683 ..Default::default()
684 }],
685 };
686
687 let apex_configs = vec![ApexConfig { name: "apex-system_ext".to_string() }];
688
689 assert_eq!(
690 collect_apex_infos(
691 &apex_info_list,
692 &apex_configs,
Jaewan Kimf3143242024-03-15 06:56:31 +0000693 &DebugConfig::new_with_debug_level(DebugLevel::NONE)
Nikita Ioffed4551e12023-07-14 16:01:03 +0100694 )?,
695 vec![&apex_info_list.list[0]]
696 );
697
698 Ok(())
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000699 }
Jooyung Han743e0d62022-11-07 20:57:48 +0900700
701 #[test]
702 fn test_prefer_staged_apex_with_factory_active_apex() {
703 let single_apex = ApexInfo {
704 name: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900705 version: 1,
Jooyung Han743e0d62022-11-07 20:57:48 +0900706 path: PathBuf::from("foo.apex"),
707 is_factory: true,
708 is_active: true,
709 ..Default::default()
710 };
711 let mut apex_info_list = ApexInfoList { list: vec![single_apex.clone()] };
712
713 let staged = NamedTempFile::new().unwrap();
714 apex_info_list
715 .override_staged_apex(&StagedApexInfo {
716 moduleName: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900717 versionCode: 2,
Jooyung Han743e0d62022-11-07 20:57:48 +0900718 diskImagePath: staged.path().to_string_lossy().to_string(),
719 ..Default::default()
720 })
721 .expect("should be ok");
722
723 assert_eq!(
724 apex_info_list,
725 ApexInfoList {
726 list: vec![
727 ApexInfo {
Jooyung Hancaa995c2022-11-08 16:35:50 +0900728 version: 2,
Jooyung Han743e0d62022-11-07 20:57:48 +0900729 is_factory: false,
730 path: staged.path().to_owned(),
731 last_update_seconds: last_updated(staged.path()).unwrap(),
732 ..single_apex.clone()
733 },
734 ApexInfo { is_active: false, ..single_apex },
735 ],
736 }
737 );
738 }
739
740 #[test]
741 fn test_prefer_staged_apex_with_factory_and_inactive_apex() {
742 let factory_apex = ApexInfo {
743 name: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900744 version: 1,
Jooyung Han743e0d62022-11-07 20:57:48 +0900745 path: PathBuf::from("foo.apex"),
746 is_factory: true,
747 ..Default::default()
748 };
749 let active_apex = ApexInfo {
750 name: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900751 version: 2,
Jooyung Han743e0d62022-11-07 20:57:48 +0900752 path: PathBuf::from("foo.downloaded.apex"),
753 is_active: true,
754 ..Default::default()
755 };
756 let mut apex_info_list =
757 ApexInfoList { list: vec![factory_apex.clone(), active_apex.clone()] };
758
759 let staged = NamedTempFile::new().unwrap();
760 apex_info_list
761 .override_staged_apex(&StagedApexInfo {
762 moduleName: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900763 versionCode: 3,
Jooyung Han743e0d62022-11-07 20:57:48 +0900764 diskImagePath: staged.path().to_string_lossy().to_string(),
765 ..Default::default()
766 })
767 .expect("should be ok");
768
769 assert_eq!(
770 apex_info_list,
771 ApexInfoList {
772 list: vec![
773 // factory apex isn't touched
774 factory_apex,
775 // update active one
776 ApexInfo {
Jooyung Hancaa995c2022-11-08 16:35:50 +0900777 version: 3,
Jooyung Han743e0d62022-11-07 20:57:48 +0900778 path: staged.path().to_owned(),
779 last_update_seconds: last_updated(staged.path()).unwrap(),
780 ..active_apex
781 },
782 ],
783 }
784 );
785 }
Jooyung Han5e0f2062021-10-12 14:00:46 +0900786}