• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // 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 
17 use crate::debug_config::DebugConfig;
18 use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
19     DiskImage::DiskImage,
20     Partition::Partition,
21     VirtualMachineAppConfig::DebugLevel::DebugLevel,
22     VirtualMachineAppConfig::{Payload::Payload, VirtualMachineAppConfig},
23     VirtualMachineRawConfig::VirtualMachineRawConfig,
24 };
25 use anyhow::{anyhow, bail, Context, Result};
26 use binder::{wait_for_interface, ParcelFileDescriptor};
27 use log::{info, warn};
28 use microdroid_metadata::{ApexPayload, ApkPayload, Metadata, PayloadConfig, PayloadMetadata};
29 use microdroid_payload_config::{ApexConfig, VmPayloadConfig};
30 use once_cell::sync::OnceCell;
31 use packagemanager_aidl::aidl::android::content::pm::{
32     IPackageManagerNative::IPackageManagerNative, StagedApexInfo::StagedApexInfo,
33 };
34 use regex::Regex;
35 use serde::Deserialize;
36 use serde_xml_rs::from_reader;
37 use std::collections::HashSet;
38 use std::fs::{metadata, File, OpenOptions};
39 use std::path::{Path, PathBuf};
40 use std::process::Command;
41 use std::time::SystemTime;
42 use vmconfig::open_parcel_file;
43 
44 /// The list of APEXes which microdroid requires.
45 // TODO(b/192200378) move this to microdroid.json?
46 const MICRODROID_REQUIRED_APEXES: [&str; 1] = ["com.android.os.statsd"];
47 const MICRODROID_REQUIRED_APEXES_DEBUG: [&str; 1] = ["com.android.adbd"];
48 
49 const APEX_INFO_LIST_PATH: &str = "/apex/apex-info-list.xml";
50 
51 const PACKAGE_MANAGER_NATIVE_SERVICE: &str = "package_native";
52 
53 /// Represents the list of APEXes
54 #[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
55 struct ApexInfoList {
56     #[serde(rename = "apex-info")]
57     list: Vec<ApexInfo>,
58 }
59 
60 #[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
61 struct ApexInfo {
62     #[serde(rename = "moduleName")]
63     name: String,
64     #[serde(rename = "versionCode")]
65     version: u64,
66     #[serde(rename = "modulePath")]
67     path: PathBuf,
68 
69     #[serde(default)]
70     has_classpath_jar: bool,
71 
72     // The field claims to be milliseconds but is actually seconds.
73     #[serde(rename = "lastUpdateMillis")]
74     last_update_seconds: u64,
75 
76     #[serde(rename = "isFactory")]
77     is_factory: bool,
78 
79     #[serde(rename = "isActive")]
80     is_active: bool,
81 
82     #[serde(rename = "provideSharedApexLibs")]
83     provide_shared_apex_libs: bool,
84 }
85 
86 impl ApexInfoList {
87     /// Loads ApexInfoList
load() -> Result<&'static ApexInfoList>88     fn load() -> Result<&'static ApexInfoList> {
89         static INSTANCE: OnceCell<ApexInfoList> = OnceCell::new();
90         INSTANCE.get_or_try_init(|| {
91             let apex_info_list = File::open(APEX_INFO_LIST_PATH)
92                 .context(format!("Failed to open {}", APEX_INFO_LIST_PATH))?;
93             let mut apex_info_list: ApexInfoList = from_reader(apex_info_list)
94                 .context(format!("Failed to parse {}", APEX_INFO_LIST_PATH))?;
95 
96             // For active APEXes, we run derive_classpath and parse its output to see if it
97             // contributes to the classpath(s). (This allows us to handle any new classpath env
98             // vars seamlessly.)
99             let classpath_vars = run_derive_classpath()?;
100             let classpath_apexes = find_apex_names_in_classpath(&classpath_vars)?;
101 
102             for apex_info in apex_info_list.list.iter_mut() {
103                 apex_info.has_classpath_jar = classpath_apexes.contains(&apex_info.name);
104             }
105 
106             Ok(apex_info_list)
107         })
108     }
109 
110     // Override apex info with the staged one
override_staged_apex(&mut self, staged_apex_info: &StagedApexInfo) -> Result<()>111     fn override_staged_apex(&mut self, staged_apex_info: &StagedApexInfo) -> Result<()> {
112         let mut need_to_add: Option<ApexInfo> = None;
113         for apex_info in self.list.iter_mut() {
114             if staged_apex_info.moduleName == apex_info.name {
115                 if apex_info.is_active && apex_info.is_factory {
116                     // Copy the entry to the end as factory/non-active after the loop
117                     // to keep the factory version. Typically this step is unncessary,
118                     // but some apexes (like sharedlibs) need to be kept even if it's inactive.
119                     need_to_add.replace(ApexInfo { is_active: false, ..apex_info.clone() });
120                     // And make this one as non-factory. Note that this one is still active
121                     // and overridden right below.
122                     apex_info.is_factory = false;
123                 }
124                 // Active one is overridden with the staged one.
125                 if apex_info.is_active {
126                     apex_info.version = staged_apex_info.versionCode as u64;
127                     apex_info.path = PathBuf::from(&staged_apex_info.diskImagePath);
128                     apex_info.has_classpath_jar = staged_apex_info.hasClassPathJars;
129                     apex_info.last_update_seconds = last_updated(&apex_info.path)?;
130                 }
131             }
132         }
133         if let Some(info) = need_to_add {
134             self.list.push(info);
135         }
136         Ok(())
137     }
138 }
139 
last_updated<P: AsRef<Path>>(path: P) -> Result<u64>140 fn last_updated<P: AsRef<Path>>(path: P) -> Result<u64> {
141     let metadata = metadata(path)?;
142     Ok(metadata.modified()?.duration_since(SystemTime::UNIX_EPOCH)?.as_secs())
143 }
144 
145 impl ApexInfo {
matches(&self, apex_config: &ApexConfig) -> bool146     fn matches(&self, apex_config: &ApexConfig) -> bool {
147         // Match with pseudo name "{CLASSPATH}" which represents APEXes contributing
148         // to any derive_classpath environment variable
149         if apex_config.name == "{CLASSPATH}" && self.has_classpath_jar {
150             return true;
151         }
152         if apex_config.name == self.name {
153             return true;
154         }
155         false
156     }
157 }
158 
159 struct PackageManager {
160     apex_info_list: &'static ApexInfoList,
161 }
162 
163 impl PackageManager {
new() -> Result<Self>164     fn new() -> Result<Self> {
165         let apex_info_list = ApexInfoList::load()?;
166         Ok(Self { apex_info_list })
167     }
168 
get_apex_list(&self, prefer_staged: bool) -> Result<ApexInfoList>169     fn get_apex_list(&self, prefer_staged: bool) -> Result<ApexInfoList> {
170         // get the list of active apexes
171         let mut list = self.apex_info_list.clone();
172         // When prefer_staged, we override ApexInfo by consulting "package_native"
173         if prefer_staged {
174             let pm =
175                 wait_for_interface::<dyn IPackageManagerNative>(PACKAGE_MANAGER_NATIVE_SERVICE)
176                     .context("Failed to get service when prefer_staged is set.")?;
177             let staged =
178                 pm.getStagedApexModuleNames().context("getStagedApexModuleNames failed")?;
179             for name in staged {
180                 if let Some(staged_apex_info) =
181                     pm.getStagedApexInfo(&name).context("getStagedApexInfo failed")?
182                 {
183                     list.override_staged_apex(&staged_apex_info)?;
184                 }
185             }
186         }
187         Ok(list)
188     }
189 }
190 
make_metadata_file( app_config: &VirtualMachineAppConfig, apex_infos: &[&ApexInfo], temporary_directory: &Path, ) -> Result<ParcelFileDescriptor>191 fn make_metadata_file(
192     app_config: &VirtualMachineAppConfig,
193     apex_infos: &[&ApexInfo],
194     temporary_directory: &Path,
195 ) -> Result<ParcelFileDescriptor> {
196     let payload_metadata = match &app_config.payload {
197         Payload::PayloadConfig(payload_config) => PayloadMetadata::config(PayloadConfig {
198             payload_binary_name: payload_config.payloadBinaryName.clone(),
199             ..Default::default()
200         }),
201         Payload::ConfigPath(config_path) => {
202             PayloadMetadata::config_path(format!("/mnt/apk/{}", config_path))
203         }
204     };
205 
206     let metadata = Metadata {
207         version: 1,
208         apexes: apex_infos
209             .iter()
210             .enumerate()
211             .map(|(i, apex_info)| {
212                 Ok(ApexPayload {
213                     name: apex_info.name.clone(),
214                     partition_name: format!("microdroid-apex-{}", i),
215                     last_update_seconds: apex_info.last_update_seconds,
216                     is_factory: apex_info.is_factory,
217                     ..Default::default()
218                 })
219             })
220             .collect::<Result<_>>()?,
221         apk: Some(ApkPayload {
222             name: "apk".to_owned(),
223             payload_partition_name: "microdroid-apk".to_owned(),
224             idsig_partition_name: "microdroid-apk-idsig".to_owned(),
225             ..Default::default()
226         })
227         .into(),
228         payload: Some(payload_metadata),
229         ..Default::default()
230     };
231 
232     // Write metadata to file.
233     let metadata_path = temporary_directory.join("metadata");
234     let mut metadata_file = OpenOptions::new()
235         .create_new(true)
236         .read(true)
237         .write(true)
238         .open(&metadata_path)
239         .with_context(|| format!("Failed to open metadata file {:?}", metadata_path))?;
240     microdroid_metadata::write_metadata(&metadata, &mut metadata_file)?;
241 
242     // Re-open the metadata file as read-only.
243     open_parcel_file(&metadata_path, false)
244 }
245 
246 /// Creates a DiskImage with partitions:
247 ///   payload-metadata: metadata
248 ///   microdroid-apex-0: apex 0
249 ///   microdroid-apex-1: apex 1
250 ///   ..
251 ///   microdroid-apk: apk
252 ///   microdroid-apk-idsig: idsig
253 ///   extra-apk-0:   additional apk 0
254 ///   extra-idsig-0: additional idsig 0
255 ///   extra-apk-1:   additional apk 1
256 ///   extra-idsig-1: additional idsig 1
257 ///   ..
make_payload_disk( app_config: &VirtualMachineAppConfig, debug_config: &DebugConfig, apk_file: File, idsig_file: File, vm_payload_config: &VmPayloadConfig, temporary_directory: &Path, ) -> Result<DiskImage>258 fn make_payload_disk(
259     app_config: &VirtualMachineAppConfig,
260     debug_config: &DebugConfig,
261     apk_file: File,
262     idsig_file: File,
263     vm_payload_config: &VmPayloadConfig,
264     temporary_directory: &Path,
265 ) -> Result<DiskImage> {
266     if vm_payload_config.extra_apks.len() != app_config.extraIdsigs.len() {
267         bail!(
268             "payload config has {} apks, but app config has {} idsigs",
269             vm_payload_config.extra_apks.len(),
270             app_config.extraIdsigs.len()
271         );
272     }
273 
274     let pm = PackageManager::new()?;
275     let apex_list = pm.get_apex_list(vm_payload_config.prefer_staged)?;
276 
277     // collect APEXes from config
278     let mut apex_infos = collect_apex_infos(&apex_list, &vm_payload_config.apexes, debug_config);
279 
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));
284     info!("Microdroid payload APEXes: {:?}", apex_infos.iter().map(|ai| &ai.name));
285 
286     let metadata_file = make_metadata_file(app_config, &apex_infos, temporary_directory)?;
287     // put metadata at the first partition
288     let mut partitions = vec![Partition {
289         label: "payload-metadata".to_owned(),
290         image: Some(metadata_file),
291         writable: false,
292     }];
293 
294     for (i, apex_info) in apex_infos.iter().enumerate() {
295         let apex_file = open_parcel_file(&apex_info.path, false)?;
296         partitions.push(Partition {
297             label: format!("microdroid-apex-{}", i),
298             image: Some(apex_file),
299             writable: false,
300         });
301     }
302     partitions.push(Partition {
303         label: "microdroid-apk".to_owned(),
304         image: Some(ParcelFileDescriptor::new(apk_file)),
305         writable: false,
306     });
307     partitions.push(Partition {
308         label: "microdroid-apk-idsig".to_owned(),
309         image: Some(ParcelFileDescriptor::new(idsig_file)),
310         writable: false,
311     });
312 
313     // we've already checked that extra_apks and extraIdsigs are in the same size.
314     let extra_apks = &vm_payload_config.extra_apks;
315     let extra_idsigs = &app_config.extraIdsigs;
316     for (i, (extra_apk, extra_idsig)) in extra_apks.iter().zip(extra_idsigs.iter()).enumerate() {
317         partitions.push(Partition {
318             label: format!("extra-apk-{}", i),
319             image: Some(ParcelFileDescriptor::new(
320                 File::open(PathBuf::from(&extra_apk.path)).with_context(|| {
321                     format!("Failed to open the extra apk #{} {}", i, extra_apk.path)
322                 })?,
323             )),
324             writable: false,
325         });
326 
327         partitions.push(Partition {
328             label: format!("extra-idsig-{}", i),
329             image: Some(ParcelFileDescriptor::new(
330                 extra_idsig
331                     .as_ref()
332                     .try_clone()
333                     .with_context(|| format!("Failed to clone the extra idsig #{}", i))?,
334             )),
335             writable: false,
336         });
337     }
338 
339     Ok(DiskImage { image: None, partitions, writable: false })
340 }
341 
run_derive_classpath() -> Result<String>342 fn run_derive_classpath() -> Result<String> {
343     let result = Command::new("/apex/com.android.sdkext/bin/derive_classpath")
344         .arg("/proc/self/fd/1")
345         .output()
346         .context("Failed to run derive_classpath")?;
347 
348     if !result.status.success() {
349         bail!("derive_classpath returned {}", result.status);
350     }
351 
352     String::from_utf8(result.stdout).context("Converting derive_classpath output")
353 }
354 
find_apex_names_in_classpath(classpath_vars: &str) -> Result<HashSet<String>>355 fn find_apex_names_in_classpath(classpath_vars: &str) -> Result<HashSet<String>> {
356     // Each line should be in the format "export <var name> <paths>", where <paths> is a
357     // colon-separated list of paths to JARs. We don't care about the var names, and we're only
358     // interested in paths that look like "/apex/<apex name>/<anything>" so we know which APEXes
359     // contribute to at least one var.
360     let mut apexes = HashSet::new();
361 
362     let pattern = Regex::new(r"^export [^ ]+ ([^ ]+)$").context("Failed to construct Regex")?;
363     for line in classpath_vars.lines() {
364         if let Some(captures) = pattern.captures(line) {
365             if let Some(paths) = captures.get(1) {
366                 apexes.extend(paths.as_str().split(':').filter_map(|path| {
367                     let path = path.strip_prefix("/apex/")?;
368                     Some(path[..path.find('/')?].to_owned())
369                 }));
370                 continue;
371             }
372         }
373         warn!("Malformed line from derive_classpath: {}", line);
374     }
375 
376     Ok(apexes)
377 }
378 
379 // Collect ApexInfos from VM config
collect_apex_infos<'a>( apex_list: &'a ApexInfoList, apex_configs: &[ApexConfig], debug_config: &DebugConfig, ) -> Vec<&'a ApexInfo>380 fn collect_apex_infos<'a>(
381     apex_list: &'a ApexInfoList,
382     apex_configs: &[ApexConfig],
383     debug_config: &DebugConfig,
384 ) -> Vec<&'a ApexInfo> {
385     let mut additional_apexes: Vec<&str> = MICRODROID_REQUIRED_APEXES.to_vec();
386     if debug_config.should_include_debug_apexes() {
387         additional_apexes.extend(MICRODROID_REQUIRED_APEXES_DEBUG.to_vec());
388     }
389 
390     apex_list
391         .list
392         .iter()
393         .filter(|ai| {
394             apex_configs.iter().any(|cfg| ai.matches(cfg) && ai.is_active)
395                 || additional_apexes.iter().any(|name| name == &ai.name && ai.is_active)
396                 || ai.provide_shared_apex_libs
397         })
398         .collect()
399 }
400 
add_microdroid_system_images( config: &VirtualMachineAppConfig, instance_file: File, storage_image: Option<File>, vm_config: &mut VirtualMachineRawConfig, ) -> Result<()>401 pub fn add_microdroid_system_images(
402     config: &VirtualMachineAppConfig,
403     instance_file: File,
404     storage_image: Option<File>,
405     vm_config: &mut VirtualMachineRawConfig,
406 ) -> Result<()> {
407     let debug_suffix = match config.debugLevel {
408         DebugLevel::NONE => "normal",
409         DebugLevel::FULL => "debuggable",
410         _ => return Err(anyhow!("unsupported debug level: {:?}", config.debugLevel)),
411     };
412     let initrd = format!("/apex/com.android.virt/etc/microdroid_initrd_{}.img", debug_suffix);
413     vm_config.initrd = Some(open_parcel_file(Path::new(&initrd), false)?);
414 
415     let mut writable_partitions = vec![Partition {
416         label: "vm-instance".to_owned(),
417         image: Some(ParcelFileDescriptor::new(instance_file)),
418         writable: true,
419     }];
420 
421     if let Some(file) = storage_image {
422         writable_partitions.push(Partition {
423             label: "encryptedstore".to_owned(),
424             image: Some(ParcelFileDescriptor::new(file)),
425             writable: true,
426         });
427     }
428 
429     vm_config.disks.push(DiskImage {
430         image: None,
431         partitions: writable_partitions,
432         writable: true,
433     });
434 
435     Ok(())
436 }
437 
add_microdroid_payload_images( config: &VirtualMachineAppConfig, debug_config: &DebugConfig, temporary_directory: &Path, apk_file: File, idsig_file: File, vm_payload_config: &VmPayloadConfig, vm_config: &mut VirtualMachineRawConfig, ) -> Result<()>438 pub fn add_microdroid_payload_images(
439     config: &VirtualMachineAppConfig,
440     debug_config: &DebugConfig,
441     temporary_directory: &Path,
442     apk_file: File,
443     idsig_file: File,
444     vm_payload_config: &VmPayloadConfig,
445     vm_config: &mut VirtualMachineRawConfig,
446 ) -> Result<()> {
447     vm_config.disks.push(make_payload_disk(
448         config,
449         debug_config,
450         apk_file,
451         idsig_file,
452         vm_payload_config,
453         temporary_directory,
454     )?);
455 
456     Ok(())
457 }
458 
459 #[cfg(test)]
460 mod tests {
461     use super::*;
462     use tempfile::NamedTempFile;
463 
464     #[test]
test_find_apex_names_in_classpath()465     fn test_find_apex_names_in_classpath() {
466         let vars = r#"
467 export FOO /apex/unterminated
468 export BAR /apex/valid.apex/something
469 wrong
470 export EMPTY
471 export OTHER /foo/bar:/baz:/apex/second.valid.apex/:gibberish:"#;
472         let expected = vec!["valid.apex", "second.valid.apex"];
473         let expected: HashSet<_> = expected.into_iter().map(ToString::to_string).collect();
474 
475         assert_eq!(find_apex_names_in_classpath(vars).unwrap(), expected);
476     }
477 
478     #[test]
test_collect_apexes()479     fn test_collect_apexes() {
480         let apex_info_list = ApexInfoList {
481             list: vec![
482                 ApexInfo {
483                     // 0
484                     name: "com.android.adbd".to_string(),
485                     path: PathBuf::from("adbd"),
486                     has_classpath_jar: false,
487                     last_update_seconds: 12345678,
488                     is_factory: true,
489                     is_active: true,
490                     ..Default::default()
491                 },
492                 ApexInfo {
493                     // 1
494                     name: "com.android.os.statsd".to_string(),
495                     path: PathBuf::from("statsd"),
496                     has_classpath_jar: false,
497                     last_update_seconds: 12345678,
498                     is_factory: true,
499                     is_active: false,
500                     ..Default::default()
501                 },
502                 ApexInfo {
503                     // 2
504                     name: "com.android.os.statsd".to_string(),
505                     path: PathBuf::from("statsd/updated"),
506                     has_classpath_jar: false,
507                     last_update_seconds: 12345678 + 1,
508                     is_factory: false,
509                     is_active: true,
510                     ..Default::default()
511                 },
512                 ApexInfo {
513                     // 3
514                     name: "no_classpath".to_string(),
515                     path: PathBuf::from("no_classpath"),
516                     has_classpath_jar: false,
517                     last_update_seconds: 12345678,
518                     is_factory: true,
519                     is_active: true,
520                     ..Default::default()
521                 },
522                 ApexInfo {
523                     // 4
524                     name: "has_classpath".to_string(),
525                     path: PathBuf::from("has_classpath"),
526                     has_classpath_jar: true,
527                     last_update_seconds: 87654321,
528                     is_factory: true,
529                     is_active: false,
530                     ..Default::default()
531                 },
532                 ApexInfo {
533                     // 5
534                     name: "has_classpath".to_string(),
535                     path: PathBuf::from("has_classpath/updated"),
536                     has_classpath_jar: true,
537                     last_update_seconds: 87654321 + 1,
538                     is_factory: false,
539                     is_active: true,
540                     ..Default::default()
541                 },
542                 ApexInfo {
543                     // 6
544                     name: "apex-foo".to_string(),
545                     path: PathBuf::from("apex-foo"),
546                     has_classpath_jar: false,
547                     last_update_seconds: 87654321,
548                     is_factory: true,
549                     is_active: false,
550                     ..Default::default()
551                 },
552                 ApexInfo {
553                     // 7
554                     name: "apex-foo".to_string(),
555                     path: PathBuf::from("apex-foo/updated"),
556                     has_classpath_jar: false,
557                     last_update_seconds: 87654321 + 1,
558                     is_factory: false,
559                     is_active: true,
560                     ..Default::default()
561                 },
562                 ApexInfo {
563                     // 8
564                     name: "sharedlibs".to_string(),
565                     path: PathBuf::from("apex-foo"),
566                     last_update_seconds: 87654321,
567                     is_factory: true,
568                     provide_shared_apex_libs: true,
569                     ..Default::default()
570                 },
571                 ApexInfo {
572                     // 9
573                     name: "sharedlibs".to_string(),
574                     path: PathBuf::from("apex-foo/updated"),
575                     last_update_seconds: 87654321 + 1,
576                     is_active: true,
577                     provide_shared_apex_libs: true,
578                     ..Default::default()
579                 },
580             ],
581         };
582         let apex_configs = vec![
583             ApexConfig { name: "apex-foo".to_string() },
584             ApexConfig { name: "{CLASSPATH}".to_string() },
585         ];
586         assert_eq!(
587             collect_apex_infos(&apex_info_list, &apex_configs, &DebugConfig::new(DebugLevel::FULL)),
588             vec![
589                 // Pass active/required APEXes
590                 &apex_info_list.list[0],
591                 &apex_info_list.list[2],
592                 // Pass active APEXes specified in the config
593                 &apex_info_list.list[5],
594                 &apex_info_list.list[7],
595                 // Pass both preinstalled(inactive) and updated(active) for "sharedlibs" APEXes
596                 &apex_info_list.list[8],
597                 &apex_info_list.list[9],
598             ]
599         );
600     }
601 
602     #[test]
test_prefer_staged_apex_with_factory_active_apex()603     fn test_prefer_staged_apex_with_factory_active_apex() {
604         let single_apex = ApexInfo {
605             name: "foo".to_string(),
606             version: 1,
607             path: PathBuf::from("foo.apex"),
608             is_factory: true,
609             is_active: true,
610             ..Default::default()
611         };
612         let mut apex_info_list = ApexInfoList { list: vec![single_apex.clone()] };
613 
614         let staged = NamedTempFile::new().unwrap();
615         apex_info_list
616             .override_staged_apex(&StagedApexInfo {
617                 moduleName: "foo".to_string(),
618                 versionCode: 2,
619                 diskImagePath: staged.path().to_string_lossy().to_string(),
620                 ..Default::default()
621             })
622             .expect("should be ok");
623 
624         assert_eq!(
625             apex_info_list,
626             ApexInfoList {
627                 list: vec![
628                     ApexInfo {
629                         version: 2,
630                         is_factory: false,
631                         path: staged.path().to_owned(),
632                         last_update_seconds: last_updated(staged.path()).unwrap(),
633                         ..single_apex.clone()
634                     },
635                     ApexInfo { is_active: false, ..single_apex },
636                 ],
637             }
638         );
639     }
640 
641     #[test]
test_prefer_staged_apex_with_factory_and_inactive_apex()642     fn test_prefer_staged_apex_with_factory_and_inactive_apex() {
643         let factory_apex = ApexInfo {
644             name: "foo".to_string(),
645             version: 1,
646             path: PathBuf::from("foo.apex"),
647             is_factory: true,
648             ..Default::default()
649         };
650         let active_apex = ApexInfo {
651             name: "foo".to_string(),
652             version: 2,
653             path: PathBuf::from("foo.downloaded.apex"),
654             is_active: true,
655             ..Default::default()
656         };
657         let mut apex_info_list =
658             ApexInfoList { list: vec![factory_apex.clone(), active_apex.clone()] };
659 
660         let staged = NamedTempFile::new().unwrap();
661         apex_info_list
662             .override_staged_apex(&StagedApexInfo {
663                 moduleName: "foo".to_string(),
664                 versionCode: 3,
665                 diskImagePath: staged.path().to_string_lossy().to_string(),
666                 ..Default::default()
667             })
668             .expect("should be ok");
669 
670         assert_eq!(
671             apex_info_list,
672             ApexInfoList {
673                 list: vec![
674                     // factory apex isn't touched
675                     factory_apex,
676                     // update active one
677                     ApexInfo {
678                         version: 3,
679                         path: staged.path().to_owned(),
680                         last_update_seconds: last_updated(staged.path()).unwrap(),
681                         ..active_apex
682                     },
683                 ],
684             }
685         );
686     }
687 }
688