blob: bbd7fec0d3b2e06d881455015052173b63edc075 [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
Andrew Walbrancc0db522021-07-12 17:03:42 +000017use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Jiyong Parkc2a49cc2021-10-15 00:02:12 +090018 DiskImage::DiskImage, Partition::Partition, VirtualMachineAppConfig::DebugLevel::DebugLevel,
19 VirtualMachineAppConfig::VirtualMachineAppConfig,
Andrew Walbrancc0db522021-07-12 17:03:42 +000020 VirtualMachineRawConfig::VirtualMachineRawConfig,
21};
22use android_system_virtualizationservice::binder::ParcelFileDescriptor;
Inseob Kima5a262f2021-11-17 19:41:03 +090023use anyhow::{anyhow, bail, Context, Result};
Jooyung Han53cf7992021-10-18 19:38:41 +090024use binder::wait_for_interface;
Jooyung Han5e0f2062021-10-12 14:00:46 +090025use log::{error, info};
Jooyung Han21e9b922021-06-26 04:14:16 +090026use microdroid_metadata::{ApexPayload, ApkPayload, Metadata};
Jooyung Han5dc42172021-10-05 16:43:47 +090027use microdroid_payload_config::{ApexConfig, VmPayloadConfig};
Jooyung Han9900f3d2021-07-06 10:27:54 +090028use once_cell::sync::OnceCell;
Jooyung Han5dc42172021-10-05 16:43:47 +090029use packagemanager_aidl::aidl::android::content::pm::IPackageManagerNative::IPackageManagerNative;
Jooyung Han44b02ab2021-07-16 03:19:13 +090030use serde::Deserialize;
31use serde_xml_rs::from_reader;
Jooyung Han5e0f2062021-10-12 14:00:46 +090032use std::env;
Jooyung Han44b02ab2021-07-16 03:19:13 +090033use std::fs::{File, OpenOptions};
Jooyung Han21e9b922021-06-26 04:14:16 +090034use std::path::{Path, PathBuf};
Andrew Walbrancc0db522021-07-12 17:03:42 +000035use vmconfig::open_parcel_file;
36
37/// The list of APEXes which microdroid requires.
38// TODO(b/192200378) move this to microdroid.json?
Inseob Kimb4868e62021-11-09 17:28:23 +090039const MICRODROID_REQUIRED_APEXES: [&str; 1] = ["com.android.os.statsd"];
40const MICRODROID_REQUIRED_APEXES_DEBUG: [&str; 1] = ["com.android.adbd"];
Jooyung Han21e9b922021-06-26 04:14:16 +090041
Jooyung Han44b02ab2021-07-16 03:19:13 +090042const APEX_INFO_LIST_PATH: &str = "/apex/apex-info-list.xml";
43
Jooyung Han5dc42172021-10-05 16:43:47 +090044const PACKAGE_MANAGER_NATIVE_SERVICE: &str = "package_native";
45
Jooyung Han73bac242021-07-02 10:25:49 +090046/// Represents the list of APEXes
Jooyung Han9d7cd7d2021-10-12 17:44:14 +090047#[derive(Clone, Debug, Deserialize)]
Jooyung Han9900f3d2021-07-06 10:27:54 +090048struct ApexInfoList {
Jooyung Han44b02ab2021-07-16 03:19:13 +090049 #[serde(rename = "apex-info")]
Jooyung Han73bac242021-07-02 10:25:49 +090050 list: Vec<ApexInfo>,
51}
52
Jooyung Han9d7cd7d2021-10-12 17:44:14 +090053#[derive(Clone, Debug, Deserialize)]
Jooyung Han73bac242021-07-02 10:25:49 +090054struct ApexInfo {
Jooyung Han44b02ab2021-07-16 03:19:13 +090055 #[serde(rename = "moduleName")]
Jooyung Han73bac242021-07-02 10:25:49 +090056 name: String,
Jooyung Han44b02ab2021-07-16 03:19:13 +090057 #[serde(rename = "modulePath")]
Jooyung Han73bac242021-07-02 10:25:49 +090058 path: PathBuf,
Jooyung Han9d7cd7d2021-10-12 17:44:14 +090059
60 #[serde(default)]
Alan Stokes46ac3862021-12-21 15:31:47 +000061 has_classpath_jar: bool,
Jooyung Han73bac242021-07-02 10:25:49 +090062}
63
64impl ApexInfoList {
65 /// Loads ApexInfoList
Jooyung Han9900f3d2021-07-06 10:27:54 +090066 fn load() -> Result<&'static ApexInfoList> {
67 static INSTANCE: OnceCell<ApexInfoList> = OnceCell::new();
68 INSTANCE.get_or_try_init(|| {
Jooyung Han44b02ab2021-07-16 03:19:13 +090069 let apex_info_list = File::open(APEX_INFO_LIST_PATH)
70 .context(format!("Failed to open {}", APEX_INFO_LIST_PATH))?;
Jooyung Han9d7cd7d2021-10-12 17:44:14 +090071 let mut apex_info_list: ApexInfoList = from_reader(apex_info_list)
Jooyung Han44b02ab2021-07-16 03:19:13 +090072 .context(format!("Failed to parse {}", APEX_INFO_LIST_PATH))?;
Jooyung Han9d7cd7d2021-10-12 17:44:14 +090073
74 // For active APEXes, we refer env variables to see if it contributes to classpath
Alan Stokes46ac3862021-12-21 15:31:47 +000075 // TODO(b/210472252): Don't hard code the env variable names
Jooyung Han9d7cd7d2021-10-12 17:44:14 +090076 let boot_classpath_apexes = find_apex_names_in_classpath_env("BOOTCLASSPATH");
77 let systemserver_classpath_apexes =
78 find_apex_names_in_classpath_env("SYSTEMSERVERCLASSPATH");
79 let dex2oatboot_classpath_apexes =
80 find_apex_names_in_classpath_env("DEX2OATBOOTCLASSPATH");
Alan Stokes46ac3862021-12-21 15:31:47 +000081 let standalone_jar_apexes =
82 find_apex_names_in_classpath_env("STANDALONE_SYSTEMSERVER_JARS");
Jooyung Han9d7cd7d2021-10-12 17:44:14 +090083 for apex_info in apex_info_list.list.iter_mut() {
Alan Stokes46ac3862021-12-21 15:31:47 +000084 apex_info.has_classpath_jar = boot_classpath_apexes.contains(&apex_info.name)
85 || systemserver_classpath_apexes.contains(&apex_info.name)
86 || dex2oatboot_classpath_apexes.contains(&apex_info.name)
87 || standalone_jar_apexes.contains(&apex_info.name);
Jooyung Han9d7cd7d2021-10-12 17:44:14 +090088 }
Jooyung Han44b02ab2021-07-16 03:19:13 +090089 Ok(apex_info_list)
Jooyung Han9900f3d2021-07-06 10:27:54 +090090 })
Jooyung Han73bac242021-07-02 10:25:49 +090091 }
92
Jooyung Han9d7cd7d2021-10-12 17:44:14 +090093 /// Returns the list of apex names matching with the predicate
94 fn get_matching(&self, predicate: fn(&ApexInfo) -> bool) -> Vec<String> {
95 self.list.iter().filter(|info| predicate(info)).map(|info| info.name.clone()).collect()
96 }
97
Jooyung Han73bac242021-07-02 10:25:49 +090098 fn get_path_for(&self, apex_name: &str) -> Result<PathBuf> {
99 Ok(self
100 .list
101 .iter()
102 .find(|apex| apex.name == apex_name)
103 .ok_or_else(|| anyhow!("{} not found.", apex_name))?
104 .path
105 .clone())
106 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900107}
108
Jooyung Han5dc42172021-10-05 16:43:47 +0900109struct PackageManager {
Jooyung Han5dc42172021-10-05 16:43:47 +0900110 // TODO(b/199146189) use IPackageManagerNative
111 apex_info_list: &'static ApexInfoList,
112}
113
114impl PackageManager {
115 fn new() -> Result<Self> {
Jooyung Han5dc42172021-10-05 16:43:47 +0900116 let apex_info_list = ApexInfoList::load()?;
Jooyung Han53cf7992021-10-18 19:38:41 +0900117 Ok(Self { apex_info_list })
Jooyung Han5dc42172021-10-05 16:43:47 +0900118 }
119
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900120 fn get_apex_list(&self, prefer_staged: bool) -> Result<ApexInfoList> {
Jooyung Han53cf7992021-10-18 19:38:41 +0900121 // get the list of active apexes
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900122 let mut list = self.apex_info_list.clone();
Jooyung Han53cf7992021-10-18 19:38:41 +0900123 // When prefer_staged, we override ApexInfo by consulting "package_native"
Jooyung Han5dc42172021-10-05 16:43:47 +0900124 if prefer_staged {
Jooyung Han53cf7992021-10-18 19:38:41 +0900125 let pm =
126 wait_for_interface::<dyn IPackageManagerNative>(PACKAGE_MANAGER_NATIVE_SERVICE)
127 .context("Failed to get service when prefer_staged is set.")?;
128 let staged = pm.getStagedApexModuleNames()?;
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900129 for apex_info in list.list.iter_mut() {
130 if staged.contains(&apex_info.name) {
Jooyung Han53cf7992021-10-18 19:38:41 +0900131 let staged_apex_info = pm.getStagedApexInfo(&apex_info.name)?;
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900132 if let Some(staged_apex_info) = staged_apex_info {
133 apex_info.path = PathBuf::from(staged_apex_info.diskImagePath);
Alan Stokes46ac3862021-12-21 15:31:47 +0000134 apex_info.has_classpath_jar = staged_apex_info.hasClassPathJars;
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900135 }
136 }
Jooyung Han5dc42172021-10-05 16:43:47 +0900137 }
138 }
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900139 Ok(list)
Jooyung Han5dc42172021-10-05 16:43:47 +0900140 }
141}
142
Andrew Walbrancc0db522021-07-12 17:03:42 +0000143fn make_metadata_file(
Jooyung Han21e9b922021-06-26 04:14:16 +0900144 config_path: &str,
Jooyung Han5e0f2062021-10-12 14:00:46 +0900145 apex_names: &[String],
Jooyung Han21e9b922021-06-26 04:14:16 +0900146 temporary_directory: &Path,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000147) -> Result<ParcelFileDescriptor> {
Jooyung Han21e9b922021-06-26 04:14:16 +0900148 let metadata_path = temporary_directory.join("metadata");
149 let metadata = Metadata {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000150 version: 1,
Jooyung Han5e0f2062021-10-12 14:00:46 +0900151 apexes: apex_names
Jooyung Han21e9b922021-06-26 04:14:16 +0900152 .iter()
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900153 .enumerate()
Jooyung Han5e0f2062021-10-12 14:00:46 +0900154 .map(|(i, apex_name)| ApexPayload {
155 name: apex_name.clone(),
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900156 partition_name: format!("microdroid-apex-{}", i),
157 ..Default::default()
158 })
Jooyung Han21e9b922021-06-26 04:14:16 +0900159 .collect(),
160 apk: Some(ApkPayload {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900161 name: "apk".to_owned(),
162 payload_partition_name: "microdroid-apk".to_owned(),
163 idsig_partition_name: "microdroid-apk-idsig".to_owned(),
Jooyung Han21e9b922021-06-26 04:14:16 +0900164 ..Default::default()
165 })
166 .into(),
167 payload_config_path: format!("/mnt/apk/{}", config_path),
168 ..Default::default()
169 };
Andrew Walbrancc0db522021-07-12 17:03:42 +0000170
171 // Write metadata to file.
172 let mut metadata_file = OpenOptions::new()
173 .create_new(true)
174 .read(true)
175 .write(true)
176 .open(&metadata_path)
177 .with_context(|| format!("Failed to open metadata file {:?}", metadata_path))?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900178 microdroid_metadata::write_metadata(&metadata, &mut metadata_file)?;
179
Andrew Walbrancc0db522021-07-12 17:03:42 +0000180 // Re-open the metadata file as read-only.
181 open_parcel_file(&metadata_path, false)
182}
183
184/// Creates a DiskImage with partitions:
185/// metadata: metadata
186/// microdroid-apex-0: apex 0
187/// microdroid-apex-1: apex 1
188/// ..
189/// microdroid-apk: apk
190/// microdroid-apk-idsig: idsig
Inseob Kima5a262f2021-11-17 19:41:03 +0900191/// extra-apk-0: additional apk 0
192/// extra-idsig-0: additional idsig 0
193/// extra-apk-1: additional apk 1
194/// extra-idsig-1: additional idsig 1
195/// ..
Andrew Walbrancc0db522021-07-12 17:03:42 +0000196fn make_payload_disk(
Inseob Kima5a262f2021-11-17 19:41:03 +0900197 app_config: &VirtualMachineAppConfig,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000198 apk_file: File,
199 idsig_file: File,
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900200 vm_payload_config: &VmPayloadConfig,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000201 temporary_directory: &Path,
202) -> Result<DiskImage> {
Inseob Kima5a262f2021-11-17 19:41:03 +0900203 if vm_payload_config.extra_apks.len() != app_config.extraIdsigs.len() {
204 bail!(
205 "payload config has {} apks, but app config has {} idsigs",
206 vm_payload_config.extra_apks.len(),
207 app_config.extraIdsigs.len()
208 );
209 }
210
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900211 let pm = PackageManager::new()?;
212 let apex_list = pm.get_apex_list(vm_payload_config.prefer_staged)?;
213
214 // collect APEX names from config
Inseob Kima5a262f2021-11-17 19:41:03 +0900215 let apexes = collect_apex_names(&apex_list, &vm_payload_config.apexes, app_config.debugLevel);
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900216 info!("Microdroid payload APEXes: {:?}", apexes);
217
Inseob Kima5a262f2021-11-17 19:41:03 +0900218 let metadata_file = make_metadata_file(&app_config.configPath, &apexes, temporary_directory)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900219 // put metadata at the first partition
220 let mut partitions = vec![Partition {
Jooyung Han14e5a8e2021-07-06 20:48:38 +0900221 label: "payload-metadata".to_owned(),
Jooyung Han631d5882021-07-29 06:34:05 +0900222 image: Some(metadata_file),
Jooyung Han21e9b922021-06-26 04:14:16 +0900223 writable: false,
224 }];
225
Jooyung Han21e9b922021-06-26 04:14:16 +0900226 for (i, apex) in apexes.iter().enumerate() {
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900227 let apex_path = apex_list.get_path_for(apex)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000228 let apex_file = open_parcel_file(&apex_path, false)?;
Jooyung Han95884632021-07-06 22:27:54 +0900229 partitions.push(Partition {
230 label: format!("microdroid-apex-{}", i),
Jooyung Han631d5882021-07-29 06:34:05 +0900231 image: Some(apex_file),
Jooyung Han95884632021-07-06 22:27:54 +0900232 writable: false,
233 });
Jooyung Han21e9b922021-06-26 04:14:16 +0900234 }
Jooyung Han95884632021-07-06 22:27:54 +0900235 partitions.push(Partition {
236 label: "microdroid-apk".to_owned(),
Jooyung Han631d5882021-07-29 06:34:05 +0900237 image: Some(ParcelFileDescriptor::new(apk_file)),
Jooyung Han95884632021-07-06 22:27:54 +0900238 writable: false,
239 });
240 partitions.push(Partition {
241 label: "microdroid-apk-idsig".to_owned(),
Jooyung Han631d5882021-07-29 06:34:05 +0900242 image: Some(ParcelFileDescriptor::new(idsig_file)),
Jooyung Han95884632021-07-06 22:27:54 +0900243 writable: false,
244 });
Jooyung Han21e9b922021-06-26 04:14:16 +0900245
Inseob Kima5a262f2021-11-17 19:41:03 +0900246 // we've already checked that extra_apks and extraIdsigs are in the same size.
247 let extra_apks = &vm_payload_config.extra_apks;
248 let extra_idsigs = &app_config.extraIdsigs;
249 for (i, (extra_apk, extra_idsig)) in extra_apks.iter().zip(extra_idsigs.iter()).enumerate() {
250 partitions.push(Partition {
251 label: format!("extra-apk-{}", i),
252 image: Some(ParcelFileDescriptor::new(File::open(PathBuf::from(&extra_apk.path))?)),
253 writable: false,
254 });
255
256 partitions.push(Partition {
257 label: format!("extra-idsig-{}", i),
258 image: Some(ParcelFileDescriptor::new(extra_idsig.as_ref().try_clone()?)),
259 writable: false,
260 });
261 }
262
Jooyung Han21e9b922021-06-26 04:14:16 +0900263 Ok(DiskImage { image: None, partitions, writable: false })
264}
Andrew Walbrancc0db522021-07-12 17:03:42 +0000265
Jooyung Han5e0f2062021-10-12 14:00:46 +0900266fn find_apex_names_in_classpath_env(classpath_env_var: &str) -> Vec<String> {
267 let val = env::var(classpath_env_var).unwrap_or_else(|e| {
268 error!("Reading {} failed: {}", classpath_env_var, e);
269 String::from("")
270 });
271 val.split(':')
272 .filter_map(|path| {
273 Path::new(path)
274 .strip_prefix("/apex/")
275 .map(|stripped| {
276 let first = stripped.iter().next().unwrap();
277 first.to_str().unwrap().to_string()
278 })
279 .ok()
280 })
281 .collect()
282}
283
284// Collect APEX names from config
Inseob Kimb4868e62021-11-09 17:28:23 +0900285fn collect_apex_names(
286 apex_list: &ApexInfoList,
287 apexes: &[ApexConfig],
288 debug_level: DebugLevel,
289) -> Vec<String> {
Alan Stokes46ac3862021-12-21 15:31:47 +0000290 // Process pseudo names like "{CLASSPATH}".
Jooyung Han5e0f2062021-10-12 14:00:46 +0900291 // For now we have following pseudo APEX names:
Alan Stokes46ac3862021-12-21 15:31:47 +0000292 // - {CLASSPATH}: represents APEXes contributing to any derive_classpath environment variable
Jooyung Han5e0f2062021-10-12 14:00:46 +0900293 let mut apex_names: Vec<String> = apexes
294 .iter()
295 .flat_map(|apex| match apex.name.as_str() {
Alan Stokes46ac3862021-12-21 15:31:47 +0000296 "{CLASSPATH}" => apex_list.get_matching(|apex| apex.has_classpath_jar),
Jooyung Han5e0f2062021-10-12 14:00:46 +0900297 _ => vec![apex.name.clone()],
298 })
299 .collect();
300 // Add required APEXes
301 apex_names.extend(MICRODROID_REQUIRED_APEXES.iter().map(|name| name.to_string()));
Inseob Kimb4868e62021-11-09 17:28:23 +0900302 if debug_level != DebugLevel::NONE {
303 apex_names.extend(MICRODROID_REQUIRED_APEXES_DEBUG.iter().map(|name| name.to_string()));
304 }
Jooyung Han5e0f2062021-10-12 14:00:46 +0900305 apex_names.sort();
306 apex_names.dedup();
307 apex_names
308}
309
Andrew Walbrancc0db522021-07-12 17:03:42 +0000310pub fn add_microdroid_images(
311 config: &VirtualMachineAppConfig,
312 temporary_directory: &Path,
313 apk_file: File,
314 idsig_file: File,
Jiyong Park8d081812021-07-23 17:45:04 +0900315 instance_file: File,
Jooyung Han5dc42172021-10-05 16:43:47 +0900316 vm_payload_config: &VmPayloadConfig,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000317 vm_config: &mut VirtualMachineRawConfig,
318) -> Result<()> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000319 vm_config.disks.push(make_payload_disk(
Inseob Kima5a262f2021-11-17 19:41:03 +0900320 config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000321 apk_file,
322 idsig_file,
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900323 vm_payload_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000324 temporary_directory,
325 )?);
326
Jiyong Parkacf31b02021-11-04 20:45:14 +0900327 vm_config.disks[1].partitions.push(Partition {
328 label: "vbmeta".to_owned(),
329 image: Some(open_parcel_file(
330 Path::new("/apex/com.android.virt/etc/fs/microdroid_vbmeta_bootconfig.img"),
331 false,
332 )?),
333 writable: false,
334 });
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900335 let bootconfig_image = "/apex/com.android.virt/etc/microdroid_bootconfig.".to_owned()
336 + match config.debugLevel {
337 DebugLevel::NONE => "normal",
338 DebugLevel::APP_ONLY => "app_debuggable",
339 DebugLevel::FULL => "full_debuggable",
340 _ => return Err(anyhow!("unsupported debug level: {:?}", config.debugLevel)),
341 };
342 vm_config.disks[1].partitions.push(Partition {
343 label: "bootconfig".to_owned(),
344 image: Some(open_parcel_file(Path::new(&bootconfig_image), false)?),
345 writable: false,
346 });
Andrew Walbrancc0db522021-07-12 17:03:42 +0000347
Jiyong Park8d081812021-07-23 17:45:04 +0900348 // instance image is at the second partition in the second disk.
349 vm_config.disks[1].partitions.push(Partition {
350 label: "vm-instance".to_owned(),
Jooyung Han631d5882021-07-29 06:34:05 +0900351 image: Some(ParcelFileDescriptor::new(instance_file)),
Jiyong Park8d081812021-07-23 17:45:04 +0900352 writable: true,
353 });
354
Andrew Walbrancc0db522021-07-12 17:03:42 +0000355 Ok(())
356}
Jooyung Han5e0f2062021-10-12 14:00:46 +0900357
358#[cfg(test)]
359mod tests {
360 use super::*;
361 #[test]
362 fn test_find_apex_names_in_classpath_env() {
363 let key = "TEST_BOOTCLASSPATH";
364 let classpath = "/apex/com.android.foo/javalib/foo.jar:/system/framework/framework.jar:/apex/com.android.bar/javalib/bar.jar";
365 env::set_var(key, classpath);
366 assert_eq!(
367 find_apex_names_in_classpath_env(key),
368 vec!["com.android.foo".to_owned(), "com.android.bar".to_owned()]
369 );
370 }
371}