blob: ac8eec7894a810471480cfb574a6dff54e4d2c2b [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;
Jooyung Han44b02ab2021-07-16 03:19:13 +090023use anyhow::{anyhow, 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?
Jooyung Han1c2d7582021-09-08 22:46:42 +090039const MICRODROID_REQUIRED_APEXES: [&str; 2] = ["com.android.adbd", "com.android.os.statsd"];
Jooyung Han21e9b922021-06-26 04:14:16 +090040
Jooyung Han44b02ab2021-07-16 03:19:13 +090041const APEX_INFO_LIST_PATH: &str = "/apex/apex-info-list.xml";
42
Jooyung Han5dc42172021-10-05 16:43:47 +090043const PACKAGE_MANAGER_NATIVE_SERVICE: &str = "package_native";
44
Jooyung Han73bac242021-07-02 10:25:49 +090045/// Represents the list of APEXes
Jooyung Han9d7cd7d2021-10-12 17:44:14 +090046#[derive(Clone, Debug, Deserialize)]
Jooyung Han9900f3d2021-07-06 10:27:54 +090047struct ApexInfoList {
Jooyung Han44b02ab2021-07-16 03:19:13 +090048 #[serde(rename = "apex-info")]
Jooyung Han73bac242021-07-02 10:25:49 +090049 list: Vec<ApexInfo>,
50}
51
Jooyung Han9d7cd7d2021-10-12 17:44:14 +090052#[derive(Clone, Debug, Deserialize)]
Jooyung Han73bac242021-07-02 10:25:49 +090053struct ApexInfo {
Jooyung Han44b02ab2021-07-16 03:19:13 +090054 #[serde(rename = "moduleName")]
Jooyung Han73bac242021-07-02 10:25:49 +090055 name: String,
Jooyung Han44b02ab2021-07-16 03:19:13 +090056 #[serde(rename = "modulePath")]
Jooyung Han73bac242021-07-02 10:25:49 +090057 path: PathBuf,
Jooyung Han9d7cd7d2021-10-12 17:44:14 +090058
59 #[serde(default)]
60 boot_classpath: bool,
61 #[serde(default)]
62 systemserver_classpath: bool,
63 #[serde(default)]
64 dex2oatboot_classpath: bool,
Jooyung Han73bac242021-07-02 10:25:49 +090065}
66
67impl ApexInfoList {
68 /// Loads ApexInfoList
Jooyung Han9900f3d2021-07-06 10:27:54 +090069 fn load() -> Result<&'static ApexInfoList> {
70 static INSTANCE: OnceCell<ApexInfoList> = OnceCell::new();
71 INSTANCE.get_or_try_init(|| {
Jooyung Han44b02ab2021-07-16 03:19:13 +090072 let apex_info_list = File::open(APEX_INFO_LIST_PATH)
73 .context(format!("Failed to open {}", APEX_INFO_LIST_PATH))?;
Jooyung Han9d7cd7d2021-10-12 17:44:14 +090074 let mut apex_info_list: ApexInfoList = from_reader(apex_info_list)
Jooyung Han44b02ab2021-07-16 03:19:13 +090075 .context(format!("Failed to parse {}", APEX_INFO_LIST_PATH))?;
Jooyung Han9d7cd7d2021-10-12 17:44:14 +090076
77 // For active APEXes, we refer env variables to see if it contributes to classpath
78 let boot_classpath_apexes = find_apex_names_in_classpath_env("BOOTCLASSPATH");
79 let systemserver_classpath_apexes =
80 find_apex_names_in_classpath_env("SYSTEMSERVERCLASSPATH");
81 let dex2oatboot_classpath_apexes =
82 find_apex_names_in_classpath_env("DEX2OATBOOTCLASSPATH");
83 for apex_info in apex_info_list.list.iter_mut() {
84 apex_info.boot_classpath = boot_classpath_apexes.contains(&apex_info.name);
85 apex_info.systemserver_classpath =
86 systemserver_classpath_apexes.contains(&apex_info.name);
87 apex_info.dex2oatboot_classpath =
88 dex2oatboot_classpath_apexes.contains(&apex_info.name);
89 }
Jooyung Han44b02ab2021-07-16 03:19:13 +090090 Ok(apex_info_list)
Jooyung Han9900f3d2021-07-06 10:27:54 +090091 })
Jooyung Han73bac242021-07-02 10:25:49 +090092 }
93
Jooyung Han9d7cd7d2021-10-12 17:44:14 +090094 /// Returns the list of apex names matching with the predicate
95 fn get_matching(&self, predicate: fn(&ApexInfo) -> bool) -> Vec<String> {
96 self.list.iter().filter(|info| predicate(info)).map(|info| info.name.clone()).collect()
97 }
98
Jooyung Han73bac242021-07-02 10:25:49 +090099 fn get_path_for(&self, apex_name: &str) -> Result<PathBuf> {
100 Ok(self
101 .list
102 .iter()
103 .find(|apex| apex.name == apex_name)
104 .ok_or_else(|| anyhow!("{} not found.", apex_name))?
105 .path
106 .clone())
107 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900108}
109
Jooyung Han5dc42172021-10-05 16:43:47 +0900110struct PackageManager {
Jooyung Han5dc42172021-10-05 16:43:47 +0900111 // TODO(b/199146189) use IPackageManagerNative
112 apex_info_list: &'static ApexInfoList,
113}
114
115impl PackageManager {
116 fn new() -> Result<Self> {
Jooyung Han5dc42172021-10-05 16:43:47 +0900117 let apex_info_list = ApexInfoList::load()?;
Jooyung Han53cf7992021-10-18 19:38:41 +0900118 Ok(Self { apex_info_list })
Jooyung Han5dc42172021-10-05 16:43:47 +0900119 }
120
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900121 fn get_apex_list(&self, prefer_staged: bool) -> Result<ApexInfoList> {
Jooyung Han53cf7992021-10-18 19:38:41 +0900122 // get the list of active apexes
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900123 let mut list = self.apex_info_list.clone();
Jooyung Han53cf7992021-10-18 19:38:41 +0900124 // When prefer_staged, we override ApexInfo by consulting "package_native"
Jooyung Han5dc42172021-10-05 16:43:47 +0900125 if prefer_staged {
Jooyung Han53cf7992021-10-18 19:38:41 +0900126 let pm =
127 wait_for_interface::<dyn IPackageManagerNative>(PACKAGE_MANAGER_NATIVE_SERVICE)
128 .context("Failed to get service when prefer_staged is set.")?;
129 let staged = pm.getStagedApexModuleNames()?;
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900130 for apex_info in list.list.iter_mut() {
131 if staged.contains(&apex_info.name) {
Jooyung Han53cf7992021-10-18 19:38:41 +0900132 let staged_apex_info = pm.getStagedApexInfo(&apex_info.name)?;
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900133 if let Some(staged_apex_info) = staged_apex_info {
134 apex_info.path = PathBuf::from(staged_apex_info.diskImagePath);
Jooyung Han1e7b6032021-11-01 15:02:45 +0900135 apex_info.boot_classpath = staged_apex_info.hasBootClassPathJars;
136 apex_info.systemserver_classpath =
137 staged_apex_info.hasSystemServerClassPathJars;
138 apex_info.dex2oatboot_classpath =
139 staged_apex_info.hasDex2OatBootClassPathJars;
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900140 }
141 }
Jooyung Han5dc42172021-10-05 16:43:47 +0900142 }
143 }
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900144 Ok(list)
Jooyung Han5dc42172021-10-05 16:43:47 +0900145 }
146}
147
Andrew Walbrancc0db522021-07-12 17:03:42 +0000148fn make_metadata_file(
Jooyung Han21e9b922021-06-26 04:14:16 +0900149 config_path: &str,
Jooyung Han5e0f2062021-10-12 14:00:46 +0900150 apex_names: &[String],
Jooyung Han21e9b922021-06-26 04:14:16 +0900151 temporary_directory: &Path,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000152) -> Result<ParcelFileDescriptor> {
Jooyung Han21e9b922021-06-26 04:14:16 +0900153 let metadata_path = temporary_directory.join("metadata");
154 let metadata = Metadata {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000155 version: 1,
Jooyung Han5e0f2062021-10-12 14:00:46 +0900156 apexes: apex_names
Jooyung Han21e9b922021-06-26 04:14:16 +0900157 .iter()
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900158 .enumerate()
Jooyung Han5e0f2062021-10-12 14:00:46 +0900159 .map(|(i, apex_name)| ApexPayload {
160 name: apex_name.clone(),
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900161 partition_name: format!("microdroid-apex-{}", i),
162 ..Default::default()
163 })
Jooyung Han21e9b922021-06-26 04:14:16 +0900164 .collect(),
165 apk: Some(ApkPayload {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900166 name: "apk".to_owned(),
167 payload_partition_name: "microdroid-apk".to_owned(),
168 idsig_partition_name: "microdroid-apk-idsig".to_owned(),
Jooyung Han21e9b922021-06-26 04:14:16 +0900169 ..Default::default()
170 })
171 .into(),
172 payload_config_path: format!("/mnt/apk/{}", config_path),
173 ..Default::default()
174 };
Andrew Walbrancc0db522021-07-12 17:03:42 +0000175
176 // Write metadata to file.
177 let mut metadata_file = OpenOptions::new()
178 .create_new(true)
179 .read(true)
180 .write(true)
181 .open(&metadata_path)
182 .with_context(|| format!("Failed to open metadata file {:?}", metadata_path))?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900183 microdroid_metadata::write_metadata(&metadata, &mut metadata_file)?;
184
Andrew Walbrancc0db522021-07-12 17:03:42 +0000185 // Re-open the metadata file as read-only.
186 open_parcel_file(&metadata_path, false)
187}
188
189/// Creates a DiskImage with partitions:
190/// metadata: metadata
191/// microdroid-apex-0: apex 0
192/// microdroid-apex-1: apex 1
193/// ..
194/// microdroid-apk: apk
195/// microdroid-apk-idsig: idsig
196fn make_payload_disk(
197 apk_file: File,
198 idsig_file: File,
199 config_path: &str,
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> {
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900203 let pm = PackageManager::new()?;
204 let apex_list = pm.get_apex_list(vm_payload_config.prefer_staged)?;
205
206 // collect APEX names from config
207 let apexes = collect_apex_names(&apex_list, &vm_payload_config.apexes);
208 info!("Microdroid payload APEXes: {:?}", apexes);
209
210 let metadata_file = make_metadata_file(config_path, &apexes, temporary_directory)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900211 // put metadata at the first partition
212 let mut partitions = vec![Partition {
Jooyung Han14e5a8e2021-07-06 20:48:38 +0900213 label: "payload-metadata".to_owned(),
Jooyung Han631d5882021-07-29 06:34:05 +0900214 image: Some(metadata_file),
Jooyung Han21e9b922021-06-26 04:14:16 +0900215 writable: false,
216 }];
217
Jooyung Han21e9b922021-06-26 04:14:16 +0900218 for (i, apex) in apexes.iter().enumerate() {
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900219 let apex_path = apex_list.get_path_for(apex)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000220 let apex_file = open_parcel_file(&apex_path, false)?;
Jooyung Han95884632021-07-06 22:27:54 +0900221 partitions.push(Partition {
222 label: format!("microdroid-apex-{}", i),
Jooyung Han631d5882021-07-29 06:34:05 +0900223 image: Some(apex_file),
Jooyung Han95884632021-07-06 22:27:54 +0900224 writable: false,
225 });
Jooyung Han21e9b922021-06-26 04:14:16 +0900226 }
Jooyung Han95884632021-07-06 22:27:54 +0900227 partitions.push(Partition {
228 label: "microdroid-apk".to_owned(),
Jooyung Han631d5882021-07-29 06:34:05 +0900229 image: Some(ParcelFileDescriptor::new(apk_file)),
Jooyung Han95884632021-07-06 22:27:54 +0900230 writable: false,
231 });
232 partitions.push(Partition {
233 label: "microdroid-apk-idsig".to_owned(),
Jooyung Han631d5882021-07-29 06:34:05 +0900234 image: Some(ParcelFileDescriptor::new(idsig_file)),
Jooyung Han95884632021-07-06 22:27:54 +0900235 writable: false,
236 });
Jooyung Han21e9b922021-06-26 04:14:16 +0900237
238 Ok(DiskImage { image: None, partitions, writable: false })
239}
Andrew Walbrancc0db522021-07-12 17:03:42 +0000240
Jooyung Han5e0f2062021-10-12 14:00:46 +0900241fn find_apex_names_in_classpath_env(classpath_env_var: &str) -> Vec<String> {
242 let val = env::var(classpath_env_var).unwrap_or_else(|e| {
243 error!("Reading {} failed: {}", classpath_env_var, e);
244 String::from("")
245 });
246 val.split(':')
247 .filter_map(|path| {
248 Path::new(path)
249 .strip_prefix("/apex/")
250 .map(|stripped| {
251 let first = stripped.iter().next().unwrap();
252 first.to_str().unwrap().to_string()
253 })
254 .ok()
255 })
256 .collect()
257}
258
259// Collect APEX names from config
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900260fn collect_apex_names(apex_list: &ApexInfoList, apexes: &[ApexConfig]) -> Vec<String> {
Jooyung Han5e0f2062021-10-12 14:00:46 +0900261 // Process pseudo names like "{BOOTCLASSPATH}".
262 // For now we have following pseudo APEX names:
263 // - {BOOTCLASSPATH}: represents APEXes contributing "BOOTCLASSPATH" environment variable
264 // - {DEX2OATBOOTCLASSPATH}: represents APEXes contributing "DEX2OATBOOTCLASSPATH" environment variable
265 // - {SYSTEMSERVERCLASSPATH}: represents APEXes contributing "SYSTEMSERVERCLASSPATH" environment variable
266 let mut apex_names: Vec<String> = apexes
267 .iter()
268 .flat_map(|apex| match apex.name.as_str() {
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900269 "{BOOTCLASSPATH}" => apex_list.get_matching(|apex| apex.boot_classpath),
270 "{DEX2OATBOOTCLASSPATH}" => apex_list.get_matching(|apex| apex.dex2oatboot_classpath),
271 "{SYSTEMSERVERCLASSPATH}" => apex_list.get_matching(|apex| apex.systemserver_classpath),
Jooyung Han5e0f2062021-10-12 14:00:46 +0900272 _ => vec![apex.name.clone()],
273 })
274 .collect();
275 // Add required APEXes
276 apex_names.extend(MICRODROID_REQUIRED_APEXES.iter().map(|name| name.to_string()));
277 apex_names.sort();
278 apex_names.dedup();
279 apex_names
280}
281
Andrew Walbrancc0db522021-07-12 17:03:42 +0000282pub fn add_microdroid_images(
283 config: &VirtualMachineAppConfig,
284 temporary_directory: &Path,
285 apk_file: File,
286 idsig_file: File,
Jiyong Park8d081812021-07-23 17:45:04 +0900287 instance_file: File,
Jooyung Han5dc42172021-10-05 16:43:47 +0900288 vm_payload_config: &VmPayloadConfig,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000289 vm_config: &mut VirtualMachineRawConfig,
290) -> Result<()> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000291 vm_config.disks.push(make_payload_disk(
292 apk_file,
293 idsig_file,
294 &config.configPath,
Jooyung Han9d7cd7d2021-10-12 17:44:14 +0900295 vm_payload_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000296 temporary_directory,
297 )?);
298
Jiyong Parkacf31b02021-11-04 20:45:14 +0900299 vm_config.disks[1].partitions.push(Partition {
300 label: "vbmeta".to_owned(),
301 image: Some(open_parcel_file(
302 Path::new("/apex/com.android.virt/etc/fs/microdroid_vbmeta_bootconfig.img"),
303 false,
304 )?),
305 writable: false,
306 });
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900307 let bootconfig_image = "/apex/com.android.virt/etc/microdroid_bootconfig.".to_owned()
308 + match config.debugLevel {
309 DebugLevel::NONE => "normal",
310 DebugLevel::APP_ONLY => "app_debuggable",
311 DebugLevel::FULL => "full_debuggable",
312 _ => return Err(anyhow!("unsupported debug level: {:?}", config.debugLevel)),
313 };
314 vm_config.disks[1].partitions.push(Partition {
315 label: "bootconfig".to_owned(),
316 image: Some(open_parcel_file(Path::new(&bootconfig_image), false)?),
317 writable: false,
318 });
Andrew Walbrancc0db522021-07-12 17:03:42 +0000319
Jiyong Park8d081812021-07-23 17:45:04 +0900320 // instance image is at the second partition in the second disk.
321 vm_config.disks[1].partitions.push(Partition {
322 label: "vm-instance".to_owned(),
Jooyung Han631d5882021-07-29 06:34:05 +0900323 image: Some(ParcelFileDescriptor::new(instance_file)),
Jiyong Park8d081812021-07-23 17:45:04 +0900324 writable: true,
325 });
326
Andrew Walbrancc0db522021-07-12 17:03:42 +0000327 Ok(())
328}
Jooyung Han5e0f2062021-10-12 14:00:46 +0900329
330#[cfg(test)]
331mod tests {
332 use super::*;
333 #[test]
334 fn test_find_apex_names_in_classpath_env() {
335 let key = "TEST_BOOTCLASSPATH";
336 let classpath = "/apex/com.android.foo/javalib/foo.jar:/system/framework/framework.jar:/apex/com.android.bar/javalib/bar.jar";
337 env::set_var(key, classpath);
338 assert_eq!(
339 find_apex_names_in_classpath_env(key),
340 vec!["com.android.foo".to_owned(), "com.android.bar".to_owned()]
341 );
342 }
343}