blob: 3bfad33da458e5a8208a5b633da6a5879d000f3d [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 Stokes0d1ef782022-09-27 13:46:35 +0100197 ..Default::default()
198 }),
199 Payload::ConfigPath(config_path) => {
Ludovic Barman93ee3082023-06-20 12:18:43 +0000200 PayloadMetadata::ConfigPath(format!("/mnt/apk/{}", config_path))
Alan Stokes0d1ef782022-09-27 13:46:35 +0100201 }
202 };
203
Jooyung Han21e9b922021-06-26 04:14:16 +0900204 let metadata = Metadata {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000205 version: 1,
Jooyung Hanec788042022-01-27 22:28:37 +0900206 apexes: apex_infos
Jooyung Han21e9b922021-06-26 04:14:16 +0900207 .iter()
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900208 .enumerate()
Jooyung Hanec788042022-01-27 22:28:37 +0900209 .map(|(i, apex_info)| {
Andrew Walbran40be9d52022-01-19 14:32:53 +0000210 Ok(ApexPayload {
Jooyung Hanec788042022-01-27 22:28:37 +0900211 name: apex_info.name.clone(),
Andrew Walbran40be9d52022-01-19 14:32:53 +0000212 partition_name: format!("microdroid-apex-{}", i),
Jiyong Parkd6502352022-01-27 01:07:30 +0900213 last_update_seconds: apex_info.last_update_seconds,
214 is_factory: apex_info.is_factory,
Andrew Walbran40be9d52022-01-19 14:32:53 +0000215 ..Default::default()
216 })
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900217 })
Andrew Walbran40be9d52022-01-19 14:32:53 +0000218 .collect::<Result<_>>()?,
Jooyung Han21e9b922021-06-26 04:14:16 +0900219 apk: Some(ApkPayload {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900220 name: "apk".to_owned(),
221 payload_partition_name: "microdroid-apk".to_owned(),
222 idsig_partition_name: "microdroid-apk-idsig".to_owned(),
Jooyung Han21e9b922021-06-26 04:14:16 +0900223 ..Default::default()
224 })
225 .into(),
Alan Stokes0d1ef782022-09-27 13:46:35 +0100226 payload: Some(payload_metadata),
Jooyung Han21e9b922021-06-26 04:14:16 +0900227 ..Default::default()
228 };
Andrew Walbrancc0db522021-07-12 17:03:42 +0000229
230 // Write metadata to file.
Alan Stokes0d1ef782022-09-27 13:46:35 +0100231 let metadata_path = temporary_directory.join("metadata");
Andrew Walbrancc0db522021-07-12 17:03:42 +0000232 let mut metadata_file = OpenOptions::new()
233 .create_new(true)
234 .read(true)
235 .write(true)
236 .open(&metadata_path)
237 .with_context(|| format!("Failed to open metadata file {:?}", metadata_path))?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900238 microdroid_metadata::write_metadata(&metadata, &mut metadata_file)?;
239
Andrew Walbrancc0db522021-07-12 17:03:42 +0000240 // Re-open the metadata file as read-only.
241 open_parcel_file(&metadata_path, false)
242}
243
244/// Creates a DiskImage with partitions:
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100245/// payload-metadata: metadata
Andrew Walbrancc0db522021-07-12 17:03:42 +0000246/// microdroid-apex-0: apex 0
247/// microdroid-apex-1: apex 1
248/// ..
249/// microdroid-apk: apk
250/// microdroid-apk-idsig: idsig
Inseob Kima5a262f2021-11-17 19:41:03 +0900251/// extra-apk-0: additional apk 0
252/// extra-idsig-0: additional idsig 0
253/// extra-apk-1: additional apk 1
254/// extra-idsig-1: additional idsig 1
255/// ..
Andrew Walbrancc0db522021-07-12 17:03:42 +0000256fn make_payload_disk(
Inseob Kima5a262f2021-11-17 19:41:03 +0900257 app_config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +0900258 debug_config: &DebugConfig,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000259 apk_file: File,
260 idsig_file: File,
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900261 vm_payload_config: &VmPayloadConfig,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000262 temporary_directory: &Path,
263) -> Result<DiskImage> {
Inseob Kima5a262f2021-11-17 19:41:03 +0900264 if vm_payload_config.extra_apks.len() != app_config.extraIdsigs.len() {
265 bail!(
266 "payload config has {} apks, but app config has {} idsigs",
267 vm_payload_config.extra_apks.len(),
268 app_config.extraIdsigs.len()
269 );
270 }
271
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900272 let pm = PackageManager::new()?;
273 let apex_list = pm.get_apex_list(vm_payload_config.prefer_staged)?;
274
Jooyung Hanec788042022-01-27 22:28:37 +0900275 // collect APEXes from config
Nikita Ioffed4551e12023-07-14 16:01:03 +0100276 let mut apex_infos = collect_apex_infos(&apex_list, &vm_payload_config.apexes, debug_config)?;
Jooyung Hancaa995c2022-11-08 16:35:50 +0900277
278 // Pass sorted list of apexes. Sorting key shouldn't use `path` because it will change after
279 // reboot with prefer_staged. `last_update_seconds` is added to distinguish "samegrade"
280 // update.
281 apex_infos.sort_by_key(|info| (&info.name, &info.version, &info.last_update_seconds));
Jooyung Hanec788042022-01-27 22:28:37 +0900282 info!("Microdroid payload APEXes: {:?}", apex_infos.iter().map(|ai| &ai.name));
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900283
Alan Stokes0d1ef782022-09-27 13:46:35 +0100284 let metadata_file = make_metadata_file(app_config, &apex_infos, temporary_directory)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900285 // put metadata at the first partition
286 let mut partitions = vec![Partition {
Jooyung Han14e5a8e2021-07-06 20:48:38 +0900287 label: "payload-metadata".to_owned(),
Jooyung Han631d5882021-07-29 06:34:05 +0900288 image: Some(metadata_file),
Jooyung Han21e9b922021-06-26 04:14:16 +0900289 writable: false,
290 }];
291
Jooyung Hanec788042022-01-27 22:28:37 +0900292 for (i, apex_info) in apex_infos.iter().enumerate() {
293 let apex_file = open_parcel_file(&apex_info.path, false)?;
Jooyung Han95884632021-07-06 22:27:54 +0900294 partitions.push(Partition {
295 label: format!("microdroid-apex-{}", i),
Jooyung Han631d5882021-07-29 06:34:05 +0900296 image: Some(apex_file),
Jooyung Han95884632021-07-06 22:27:54 +0900297 writable: false,
298 });
Jooyung Han21e9b922021-06-26 04:14:16 +0900299 }
Jooyung Han95884632021-07-06 22:27:54 +0900300 partitions.push(Partition {
301 label: "microdroid-apk".to_owned(),
Jooyung Han631d5882021-07-29 06:34:05 +0900302 image: Some(ParcelFileDescriptor::new(apk_file)),
Jooyung Han95884632021-07-06 22:27:54 +0900303 writable: false,
304 });
305 partitions.push(Partition {
306 label: "microdroid-apk-idsig".to_owned(),
Jooyung Han631d5882021-07-29 06:34:05 +0900307 image: Some(ParcelFileDescriptor::new(idsig_file)),
Jooyung Han95884632021-07-06 22:27:54 +0900308 writable: false,
309 });
Jooyung Han21e9b922021-06-26 04:14:16 +0900310
Inseob Kima5a262f2021-11-17 19:41:03 +0900311 // we've already checked that extra_apks and extraIdsigs are in the same size.
312 let extra_apks = &vm_payload_config.extra_apks;
313 let extra_idsigs = &app_config.extraIdsigs;
314 for (i, (extra_apk, extra_idsig)) in extra_apks.iter().zip(extra_idsigs.iter()).enumerate() {
315 partitions.push(Partition {
316 label: format!("extra-apk-{}", i),
Victor Hsieh14497f02022-09-21 10:10:16 -0700317 image: Some(ParcelFileDescriptor::new(
318 File::open(PathBuf::from(&extra_apk.path)).with_context(|| {
319 format!("Failed to open the extra apk #{} {}", i, extra_apk.path)
320 })?,
321 )),
Inseob Kima5a262f2021-11-17 19:41:03 +0900322 writable: false,
323 });
324
325 partitions.push(Partition {
326 label: format!("extra-idsig-{}", i),
Victor Hsieh14497f02022-09-21 10:10:16 -0700327 image: Some(ParcelFileDescriptor::new(
328 extra_idsig
329 .as_ref()
330 .try_clone()
331 .with_context(|| format!("Failed to clone the extra idsig #{}", i))?,
332 )),
Inseob Kima5a262f2021-11-17 19:41:03 +0900333 writable: false,
334 });
335 }
336
Jooyung Han21e9b922021-06-26 04:14:16 +0900337 Ok(DiskImage { image: None, partitions, writable: false })
338}
Andrew Walbrancc0db522021-07-12 17:03:42 +0000339
Alan Stokesbf20c6a2022-01-04 12:30:50 +0000340fn run_derive_classpath() -> Result<String> {
341 let result = Command::new("/apex/com.android.sdkext/bin/derive_classpath")
342 .arg("/proc/self/fd/1")
343 .output()
344 .context("Failed to run derive_classpath")?;
345
346 if !result.status.success() {
347 bail!("derive_classpath returned {}", result.status);
348 }
349
350 String::from_utf8(result.stdout).context("Converting derive_classpath output")
351}
352
353fn find_apex_names_in_classpath(classpath_vars: &str) -> Result<HashSet<String>> {
354 // Each line should be in the format "export <var name> <paths>", where <paths> is a
355 // colon-separated list of paths to JARs. We don't care about the var names, and we're only
356 // interested in paths that look like "/apex/<apex name>/<anything>" so we know which APEXes
357 // contribute to at least one var.
358 let mut apexes = HashSet::new();
359
360 let pattern = Regex::new(r"^export [^ ]+ ([^ ]+)$").context("Failed to construct Regex")?;
361 for line in classpath_vars.lines() {
362 if let Some(captures) = pattern.captures(line) {
363 if let Some(paths) = captures.get(1) {
364 apexes.extend(paths.as_str().split(':').filter_map(|path| {
365 let path = path.strip_prefix("/apex/")?;
366 Some(path[..path.find('/')?].to_owned())
367 }));
368 continue;
369 }
370 }
371 warn!("Malformed line from derive_classpath: {}", line);
372 }
373
374 Ok(apexes)
Jooyung Han5e0f2062021-10-12 14:00:46 +0900375}
376
Nikita Ioffed4551e12023-07-14 16:01:03 +0100377fn check_apexes_are_from_allowed_partitions(requested_apexes: &Vec<&ApexInfo>) -> Result<()> {
378 const ALLOWED_PARTITIONS: [&str; 2] = ["/system", "/system_ext"];
379 for apex in requested_apexes {
380 if !ALLOWED_PARTITIONS.iter().any(|p| apex.preinstalled_path.starts_with(p)) {
381 bail!("Non-system APEX {} is not supported in Microdroid", apex.name);
382 }
383 }
384 Ok(())
385}
386
Jooyung Hanec788042022-01-27 22:28:37 +0900387// Collect ApexInfos from VM config
388fn collect_apex_infos<'a>(
389 apex_list: &'a ApexInfoList,
390 apex_configs: &[ApexConfig],
Jaewan Kim61f86142023-03-28 15:12:52 +0900391 debug_config: &DebugConfig,
Nikita Ioffed4551e12023-07-14 16:01:03 +0100392) -> Result<Vec<&'a ApexInfo>> {
Alan Stokesf7260f12023-08-30 17:25:21 +0100393 // APEXes which any Microdroid VM needs.
394 // TODO(b/192200378) move this to microdroid.json?
395 let required_apexes: &[_] =
396 if debug_config.should_include_debug_apexes() { &["com.android.adbd"] } else { &[] };
Jooyung Hanec788042022-01-27 22:28:37 +0900397
Nikita Ioffed4551e12023-07-14 16:01:03 +0100398 let apex_infos = apex_list
Jooyung Hanec788042022-01-27 22:28:37 +0900399 .list
400 .iter()
401 .filter(|ai| {
402 apex_configs.iter().any(|cfg| ai.matches(cfg) && ai.is_active)
Alan Stokesf7260f12023-08-30 17:25:21 +0100403 || required_apexes.iter().any(|name| name == &ai.name && ai.is_active)
Jooyung Han5ce867a2022-01-28 03:18:38 +0900404 || ai.provide_shared_apex_libs
Jooyung Hanec788042022-01-27 22:28:37 +0900405 })
Nikita Ioffed4551e12023-07-14 16:01:03 +0100406 .collect();
407
408 check_apexes_are_from_allowed_partitions(&apex_infos)?;
409 Ok(apex_infos)
Jooyung Han5e0f2062021-10-12 14:00:46 +0900410}
411
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100412pub fn add_microdroid_vendor_image(vendor_image: File, vm_config: &mut VirtualMachineRawConfig) {
413 vm_config.disks.push(DiskImage {
414 image: None,
415 writable: false,
416 partitions: vec![Partition {
417 label: "microdroid-vendor".to_owned(),
418 image: Some(ParcelFileDescriptor::new(vendor_image)),
419 writable: false,
420 }],
421 })
422}
423
Shikha Panwar22e70452022-10-10 18:32:55 +0000424pub fn add_microdroid_system_images(
Andrew Walbrancc0db522021-07-12 17:03:42 +0000425 config: &VirtualMachineAppConfig,
Jiyong Park8d081812021-07-23 17:45:04 +0900426 instance_file: File,
Shikha Panwar22e70452022-10-10 18:32:55 +0000427 storage_image: Option<File>,
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 };
435 let initrd = format!("/apex/com.android.virt/etc/microdroid_initrd_{}.img", debug_suffix);
436 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
461pub fn add_microdroid_payload_images(
462 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +0900463 debug_config: &DebugConfig,
Shikha Panwar22e70452022-10-10 18:32:55 +0000464 temporary_directory: &Path,
465 apk_file: File,
466 idsig_file: File,
467 vm_payload_config: &VmPayloadConfig,
468 vm_config: &mut VirtualMachineRawConfig,
469) -> Result<()> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000470 vm_config.disks.push(make_payload_disk(
Inseob Kima5a262f2021-11-17 19:41:03 +0900471 config,
Jaewan Kim61f86142023-03-28 15:12:52 +0900472 debug_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000473 apk_file,
474 idsig_file,
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900475 vm_payload_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000476 temporary_directory,
477 )?);
478
Andrew Walbrancc0db522021-07-12 17:03:42 +0000479 Ok(())
480}
Jooyung Han5e0f2062021-10-12 14:00:46 +0900481
482#[cfg(test)]
483mod tests {
484 use super::*;
Alan Stokesf7260f12023-08-30 17:25:21 +0100485 use std::collections::HashMap;
Jooyung Han743e0d62022-11-07 20:57:48 +0900486 use tempfile::NamedTempFile;
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000487
Jooyung Han5e0f2062021-10-12 14:00:46 +0900488 #[test]
Alan Stokesbf20c6a2022-01-04 12:30:50 +0000489 fn test_find_apex_names_in_classpath() {
490 let vars = r#"
491export FOO /apex/unterminated
492export BAR /apex/valid.apex/something
493wrong
494export EMPTY
495export OTHER /foo/bar:/baz:/apex/second.valid.apex/:gibberish:"#;
496 let expected = vec!["valid.apex", "second.valid.apex"];
497 let expected: HashSet<_> = expected.into_iter().map(ToString::to_string).collect();
498
499 assert_eq!(find_apex_names_in_classpath(vars).unwrap(), expected);
Jooyung Han5e0f2062021-10-12 14:00:46 +0900500 }
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000501
502 #[test]
Nikita Ioffed4551e12023-07-14 16:01:03 +0100503 fn test_collect_apexes() -> Result<()> {
Alan Stokesf7260f12023-08-30 17:25:21 +0100504 let apex_infos_for_test = [
505 (
506 "adbd",
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000507 ApexInfo {
Jooyung Hanec788042022-01-27 22:28:37 +0900508 name: "com.android.adbd".to_string(),
509 path: PathBuf::from("adbd"),
Nikita Ioffed4551e12023-07-14 16:01:03 +0100510 preinstalled_path: PathBuf::from("/system/adbd"),
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000511 has_classpath_jar: false,
Andrew Walbran40be9d52022-01-19 14:32:53 +0000512 last_update_seconds: 12345678,
Jiyong Parkd6502352022-01-27 01:07:30 +0900513 is_factory: true,
Jooyung Hanec788042022-01-27 22:28:37 +0900514 is_active: false,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900515 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900516 },
Alan Stokesf7260f12023-08-30 17:25:21 +0100517 ),
518 (
519 "adbd_updated",
Jooyung Hanec788042022-01-27 22:28:37 +0900520 ApexInfo {
Alan Stokesf7260f12023-08-30 17:25:21 +0100521 name: "com.android.adbd".to_string(),
522 path: PathBuf::from("adbd"),
523 preinstalled_path: PathBuf::from("/system/adbd"),
Jooyung Hanec788042022-01-27 22:28:37 +0900524 has_classpath_jar: false,
525 last_update_seconds: 12345678 + 1,
526 is_factory: false,
527 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900528 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900529 },
Alan Stokesf7260f12023-08-30 17:25:21 +0100530 ),
531 (
532 "no_classpath",
Jooyung Hanec788042022-01-27 22:28:37 +0900533 ApexInfo {
Jooyung Hanec788042022-01-27 22:28:37 +0900534 name: "no_classpath".to_string(),
535 path: PathBuf::from("no_classpath"),
536 has_classpath_jar: false,
537 last_update_seconds: 12345678,
538 is_factory: true,
539 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900540 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900541 },
Alan Stokesf7260f12023-08-30 17:25:21 +0100542 ),
543 (
544 "has_classpath",
Jooyung Hanec788042022-01-27 22:28:37 +0900545 ApexInfo {
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000546 name: "has_classpath".to_string(),
Jooyung Hanec788042022-01-27 22:28:37 +0900547 path: PathBuf::from("has_classpath"),
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000548 has_classpath_jar: true,
Andrew Walbran40be9d52022-01-19 14:32:53 +0000549 last_update_seconds: 87654321,
Jooyung Hanec788042022-01-27 22:28:37 +0900550 is_factory: true,
551 is_active: false,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900552 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900553 },
Alan Stokesf7260f12023-08-30 17:25:21 +0100554 ),
555 (
556 "has_classpath_updated",
Jooyung Hanec788042022-01-27 22:28:37 +0900557 ApexInfo {
Jooyung Hanec788042022-01-27 22:28:37 +0900558 name: "has_classpath".to_string(),
559 path: PathBuf::from("has_classpath/updated"),
Nikita Ioffed4551e12023-07-14 16:01:03 +0100560 preinstalled_path: PathBuf::from("/system/has_classpath"),
Jooyung Hanec788042022-01-27 22:28:37 +0900561 has_classpath_jar: true,
562 last_update_seconds: 87654321 + 1,
Jiyong Parkd6502352022-01-27 01:07:30 +0900563 is_factory: false,
Jooyung Hanec788042022-01-27 22:28:37 +0900564 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900565 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900566 },
Alan Stokesf7260f12023-08-30 17:25:21 +0100567 ),
568 (
569 "apex-foo",
Jooyung Hanec788042022-01-27 22:28:37 +0900570 ApexInfo {
Jooyung Hanec788042022-01-27 22:28:37 +0900571 name: "apex-foo".to_string(),
572 path: PathBuf::from("apex-foo"),
Nikita Ioffed4551e12023-07-14 16:01:03 +0100573 preinstalled_path: PathBuf::from("/system/apex-foo"),
Jooyung Hanec788042022-01-27 22:28:37 +0900574 has_classpath_jar: false,
575 last_update_seconds: 87654321,
576 is_factory: true,
577 is_active: false,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900578 ..Default::default()
Jooyung Hanec788042022-01-27 22:28:37 +0900579 },
Alan Stokesf7260f12023-08-30 17:25:21 +0100580 ),
581 (
582 "apex-foo-updated",
Jooyung Hanec788042022-01-27 22:28:37 +0900583 ApexInfo {
Jooyung Hanec788042022-01-27 22:28:37 +0900584 name: "apex-foo".to_string(),
585 path: PathBuf::from("apex-foo/updated"),
Nikita Ioffed4551e12023-07-14 16:01:03 +0100586 preinstalled_path: PathBuf::from("/system/apex-foo"),
Jooyung Hanec788042022-01-27 22:28:37 +0900587 has_classpath_jar: false,
588 last_update_seconds: 87654321 + 1,
589 is_factory: false,
590 is_active: true,
Jooyung Han5ce867a2022-01-28 03:18:38 +0900591 ..Default::default()
592 },
Alan Stokesf7260f12023-08-30 17:25:21 +0100593 ),
594 (
595 "sharedlibs",
Jooyung Han5ce867a2022-01-28 03:18:38 +0900596 ApexInfo {
Jooyung Han5ce867a2022-01-28 03:18:38 +0900597 name: "sharedlibs".to_string(),
598 path: PathBuf::from("apex-foo"),
Nikita Ioffed4551e12023-07-14 16:01:03 +0100599 preinstalled_path: PathBuf::from("/system/apex-foo"),
Jooyung Han5ce867a2022-01-28 03:18:38 +0900600 last_update_seconds: 87654321,
601 is_factory: true,
602 provide_shared_apex_libs: true,
603 ..Default::default()
604 },
Alan Stokesf7260f12023-08-30 17:25:21 +0100605 ),
606 (
607 "sharedlibs-updated",
Jooyung Han5ce867a2022-01-28 03:18:38 +0900608 ApexInfo {
Jooyung Han5ce867a2022-01-28 03:18:38 +0900609 name: "sharedlibs".to_string(),
610 path: PathBuf::from("apex-foo/updated"),
Nikita Ioffed4551e12023-07-14 16:01:03 +0100611 preinstalled_path: PathBuf::from("/system/apex-foo"),
Jooyung Han5ce867a2022-01-28 03:18:38 +0900612 last_update_seconds: 87654321 + 1,
613 is_active: true,
614 provide_shared_apex_libs: true,
615 ..Default::default()
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000616 },
Alan Stokesf7260f12023-08-30 17:25:21 +0100617 ),
618 ];
619 let apex_info_list = ApexInfoList {
620 list: apex_infos_for_test.iter().map(|(_, info)| info).cloned().collect(),
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000621 };
Alan Stokesf7260f12023-08-30 17:25:21 +0100622 let apex_info_map = HashMap::from(apex_infos_for_test);
Jooyung Hanec788042022-01-27 22:28:37 +0900623 let apex_configs = vec![
624 ApexConfig { name: "apex-foo".to_string() },
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000625 ApexConfig { name: "{CLASSPATH}".to_string() },
626 ];
627 assert_eq!(
Nikita Ioffed4551e12023-07-14 16:01:03 +0100628 collect_apex_infos(
629 &apex_info_list,
630 &apex_configs,
631 &DebugConfig::new(DebugLevel::FULL)
632 )?,
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000633 vec![
Jooyung Han5ce867a2022-01-28 03:18:38 +0900634 // Pass active/required APEXes
Alan Stokesf7260f12023-08-30 17:25:21 +0100635 &apex_info_map["adbd_updated"],
Jooyung Han5ce867a2022-01-28 03:18:38 +0900636 // Pass active APEXes specified in the config
Alan Stokesf7260f12023-08-30 17:25:21 +0100637 &apex_info_map["has_classpath_updated"],
638 &apex_info_map["apex-foo-updated"],
Jooyung Han5ce867a2022-01-28 03:18:38 +0900639 // Pass both preinstalled(inactive) and updated(active) for "sharedlibs" APEXes
Alan Stokesf7260f12023-08-30 17:25:21 +0100640 &apex_info_map["sharedlibs"],
641 &apex_info_map["sharedlibs-updated"],
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000642 ]
643 );
Nikita Ioffed4551e12023-07-14 16:01:03 +0100644 Ok(())
645 }
646
647 #[test]
648 fn test_check_allowed_partitions_vendor_not_allowed() -> Result<()> {
649 let apex_info_list = ApexInfoList {
650 list: vec![ApexInfo {
651 name: "apex-vendor".to_string(),
652 path: PathBuf::from("apex-vendor"),
653 preinstalled_path: PathBuf::from("/vendor/apex-vendor"),
654 is_active: true,
655 ..Default::default()
656 }],
657 };
658 let apex_configs = vec![ApexConfig { name: "apex-vendor".to_string() }];
659
660 let ret =
661 collect_apex_infos(&apex_info_list, &apex_configs, &DebugConfig::new(DebugLevel::NONE));
662 assert!(ret
663 .is_err_and(|ret| ret.to_string()
664 == "Non-system APEX apex-vendor is not supported in Microdroid"));
665
666 Ok(())
667 }
668
669 #[test]
670 fn test_check_allowed_partitions_system_ext_allowed() -> Result<()> {
671 let apex_info_list = ApexInfoList {
672 list: vec![ApexInfo {
673 name: "apex-system_ext".to_string(),
674 path: PathBuf::from("apex-system_ext"),
675 preinstalled_path: PathBuf::from("/system_ext/apex-system_ext"),
676 is_active: true,
677 ..Default::default()
678 }],
679 };
680
681 let apex_configs = vec![ApexConfig { name: "apex-system_ext".to_string() }];
682
683 assert_eq!(
684 collect_apex_infos(
685 &apex_info_list,
686 &apex_configs,
687 &DebugConfig::new(DebugLevel::NONE)
688 )?,
689 vec![&apex_info_list.list[0]]
690 );
691
692 Ok(())
Andrew Walbranc1a5f5a2022-01-19 13:38:13 +0000693 }
Jooyung Han743e0d62022-11-07 20:57:48 +0900694
695 #[test]
696 fn test_prefer_staged_apex_with_factory_active_apex() {
697 let single_apex = ApexInfo {
698 name: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900699 version: 1,
Jooyung Han743e0d62022-11-07 20:57:48 +0900700 path: PathBuf::from("foo.apex"),
701 is_factory: true,
702 is_active: true,
703 ..Default::default()
704 };
705 let mut apex_info_list = ApexInfoList { list: vec![single_apex.clone()] };
706
707 let staged = NamedTempFile::new().unwrap();
708 apex_info_list
709 .override_staged_apex(&StagedApexInfo {
710 moduleName: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900711 versionCode: 2,
Jooyung Han743e0d62022-11-07 20:57:48 +0900712 diskImagePath: staged.path().to_string_lossy().to_string(),
713 ..Default::default()
714 })
715 .expect("should be ok");
716
717 assert_eq!(
718 apex_info_list,
719 ApexInfoList {
720 list: vec![
721 ApexInfo {
Jooyung Hancaa995c2022-11-08 16:35:50 +0900722 version: 2,
Jooyung Han743e0d62022-11-07 20:57:48 +0900723 is_factory: false,
724 path: staged.path().to_owned(),
725 last_update_seconds: last_updated(staged.path()).unwrap(),
726 ..single_apex.clone()
727 },
728 ApexInfo { is_active: false, ..single_apex },
729 ],
730 }
731 );
732 }
733
734 #[test]
735 fn test_prefer_staged_apex_with_factory_and_inactive_apex() {
736 let factory_apex = ApexInfo {
737 name: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900738 version: 1,
Jooyung Han743e0d62022-11-07 20:57:48 +0900739 path: PathBuf::from("foo.apex"),
740 is_factory: true,
741 ..Default::default()
742 };
743 let active_apex = ApexInfo {
744 name: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900745 version: 2,
Jooyung Han743e0d62022-11-07 20:57:48 +0900746 path: PathBuf::from("foo.downloaded.apex"),
747 is_active: true,
748 ..Default::default()
749 };
750 let mut apex_info_list =
751 ApexInfoList { list: vec![factory_apex.clone(), active_apex.clone()] };
752
753 let staged = NamedTempFile::new().unwrap();
754 apex_info_list
755 .override_staged_apex(&StagedApexInfo {
756 moduleName: "foo".to_string(),
Jooyung Hancaa995c2022-11-08 16:35:50 +0900757 versionCode: 3,
Jooyung Han743e0d62022-11-07 20:57:48 +0900758 diskImagePath: staged.path().to_string_lossy().to_string(),
759 ..Default::default()
760 })
761 .expect("should be ok");
762
763 assert_eq!(
764 apex_info_list,
765 ApexInfoList {
766 list: vec![
767 // factory apex isn't touched
768 factory_apex,
769 // update active one
770 ApexInfo {
Jooyung Hancaa995c2022-11-08 16:35:50 +0900771 version: 3,
Jooyung Han743e0d62022-11-07 20:57:48 +0900772 path: staged.path().to_owned(),
773 last_update_seconds: last_updated(staged.path()).unwrap(),
774 ..active_apex
775 },
776 ],
777 }
778 );
779 }
Jooyung Han5e0f2062021-10-12 14:00:46 +0900780}