Merge "compsvc_worker: refactor authfs into another module"
diff --git a/compos/Android.bp b/compos/Android.bp
index 1854291..ec3f67f 100644
--- a/compos/Android.bp
+++ b/compos/Android.bp
@@ -28,7 +28,7 @@
 
 rust_binary {
     name: "compsvc",
-    srcs: ["src/compsvc.rs"],
+    srcs: ["src/compsvc_main.rs"],
     rustlibs: [
         "compos_aidl_interface-rust",
         "libandroid_logger",
@@ -79,6 +79,7 @@
         "libbinder_rpc_unstable_bindgen",
         "libclap",
         "liblog_rust",
+        "libminijail_rust",
         "libring",
         "libscopeguard",
     ],
diff --git a/compos/aidl/com/android/compos/ICompOsKeyService.aidl b/compos/aidl/com/android/compos/ICompOsKeyService.aidl
index a2ff917..eb2caa7 100644
--- a/compos/aidl/com/android/compos/ICompOsKeyService.aidl
+++ b/compos/aidl/com/android/compos/ICompOsKeyService.aidl
@@ -17,6 +17,7 @@
 package com.android.compos;
 
 import com.android.compos.CompOsKeyData;
+import com.android.compos.ICompService;
 
 /** {@hide} */
 interface ICompOsKeyService {
@@ -48,4 +49,13 @@
      */
     // STOPSHIP(b/193241041): We must not expose this from the PVM.
     byte[] sign(in byte[] keyBlob, in byte[] data);
+
+    /**
+     * Return an instance of ICompService that will sign output files with a given encrypted
+     * private key.
+     *
+     * @param keyBlob The encrypted blob containing the private key, as returned by
+     *                generateSigningKey().
+     */
+    ICompService getCompService(in byte[] keyBlob);
 }
diff --git a/compos/apk/AndroidManifest.xml b/compos/apk/AndroidManifest.xml
index 1e9352b..2f8cbcf 100644
--- a/compos/apk/AndroidManifest.xml
+++ b/compos/apk/AndroidManifest.xml
@@ -14,5 +14,5 @@
 -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
       package="com.android.compos.payload">
-    <application android:label="CompOS" />
+    <application android:label="CompOS" android:hasCode="false"/>
 </manifest>
diff --git a/compos/src/compos_key_main.rs b/compos/src/compos_key_main.rs
index 9135c18..9d57e4d 100644
--- a/compos/src/compos_key_main.rs
+++ b/compos/src/compos_key_main.rs
@@ -16,12 +16,13 @@
 //! VM using RPC Binder.
 
 mod compos_key_service;
+mod compsvc;
+mod signer;
 
-use crate::compos_key_service::{CompOsKeyService, KeystoreNamespace};
+use crate::compos_key_service::KeystoreNamespace;
 use anyhow::{bail, Context, Result};
 use binder::unstable_api::AsNative;
-use compos_aidl_interface::aidl::com::android::compos::ICompOsKeyService::BnCompOsKeyService;
-use compos_aidl_interface::binder::{add_service, BinderFeatures, ProcessState};
+use compos_aidl_interface::binder::{add_service, ProcessState};
 use log::{info, Level};
 
 const LOG_TAG: &str = "CompOsKeyService";
@@ -41,9 +42,7 @@
 
     let key_namespace =
         if rpc_binder { KeystoreNamespace::VmPayload } else { KeystoreNamespace::Odsign };
-    let service = CompOsKeyService::new(key_namespace)?;
-    let mut service =
-        BnCompOsKeyService::new_binder(service, BinderFeatures::default()).as_binder();
+    let mut service = compos_key_service::new(key_namespace)?.as_binder();
 
     if rpc_binder {
         info!("Starting RPC service");
diff --git a/compos/src/compos_key_service.rs b/compos/src/compos_key_service.rs
index 66451b3..40d0f48 100644
--- a/compos/src/compos_key_service.rs
+++ b/compos/src/compos_key_service.rs
@@ -16,6 +16,8 @@
 //! access to Keystore in the VM, but not persistent storage; instead the host stores the key
 //! on our behalf via this service.
 
+use crate::compsvc;
+use crate::signer::Signer;
 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
     Algorithm::Algorithm, Digest::Digest, KeyParameter::KeyParameter,
     KeyParameterValue::KeyParameterValue, KeyPurpose::KeyPurpose, PaddingMode::PaddingMode,
@@ -27,10 +29,12 @@
 };
 use anyhow::{anyhow, Context, Result};
 use compos_aidl_interface::aidl::com::android::compos::{
-    CompOsKeyData::CompOsKeyData, ICompOsKeyService::ICompOsKeyService,
+    CompOsKeyData::CompOsKeyData,
+    ICompOsKeyService::{BnCompOsKeyService, ICompOsKeyService},
+    ICompService::ICompService,
 };
 use compos_aidl_interface::binder::{
-    self, wait_for_interface, ExceptionCode, Interface, Status, Strong,
+    self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, Status, Strong,
 };
 use log::warn;
 use ring::rand::{SecureRandom, SystemRandom};
@@ -48,6 +52,23 @@
     VmPayload = 140,
 }
 
+/// Constructs a binder object that implements ICompOsKeyService. namespace is the Keystore2 namespace to
+/// use for the keys.
+pub fn new(namespace: KeystoreNamespace) -> Result<Strong<dyn ICompOsKeyService>> {
+    let keystore_service = wait_for_interface::<dyn IKeystoreService>(KEYSTORE_SERVICE_NAME)
+        .context("No Keystore service")?;
+
+    let service = CompOsKeyService {
+        namespace,
+        random: SystemRandom::new(),
+        security_level: keystore_service
+            .getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT)
+            .context("Getting SecurityLevel failed")?,
+    };
+
+    Ok(BnCompOsKeyService::new_binder(service, BinderFeatures::default()))
+}
+
 const KEYSTORE_SERVICE_NAME: &str = "android.system.keystore2.IKeystoreService/default";
 const PURPOSE_SIGN: KeyParameter =
     KeyParameter { tag: Tag::PURPOSE, value: KeyParameterValue::KeyPurpose(KeyPurpose::SIGN) };
@@ -69,7 +90,8 @@
 const BLOB_KEY_DESCRIPTOR: KeyDescriptor =
     KeyDescriptor { domain: Domain::BLOB, nspace: 0, alias: None, blob: None };
 
-pub struct CompOsKeyService {
+#[derive(Clone)]
+struct CompOsKeyService {
     namespace: KeystoreNamespace,
     random: SystemRandom,
     security_level: Strong<dyn IKeystoreSecurityLevel>,
@@ -96,6 +118,17 @@
         self.do_sign(key_blob, data)
             .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))
     }
+
+    fn getCompService(&self, key_blob: &[u8]) -> binder::Result<Strong<dyn ICompService>> {
+        let signer =
+            Box::new(CompOsSigner { key_blob: key_blob.to_owned(), key_service: self.clone() });
+        let debuggable = true;
+        Ok(compsvc::new_binder(
+            "/apex/com.android.art/bin/dex2oat64".to_owned(),
+            debuggable,
+            Some(signer),
+        ))
+    }
 }
 
 /// Constructs a new Binder error `Status` with the given `ExceptionCode` and message.
@@ -103,20 +136,18 @@
     Status::new_exception(exception, CString::new(message.as_ref()).ok().as_deref())
 }
 
-impl CompOsKeyService {
-    pub fn new(namespace: KeystoreNamespace) -> Result<Self> {
-        let keystore_service = wait_for_interface::<dyn IKeystoreService>(KEYSTORE_SERVICE_NAME)
-            .context("No Keystore service")?;
+struct CompOsSigner {
+    key_blob: Vec<u8>,
+    key_service: CompOsKeyService,
+}
 
-        Ok(Self {
-            namespace,
-            random: SystemRandom::new(),
-            security_level: keystore_service
-                .getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT)
-                .context("Getting SecurityLevel failed")?,
-        })
+impl Signer for CompOsSigner {
+    fn sign(&self, data: &[u8]) -> Result<Vec<u8>> {
+        self.key_service.do_sign(&self.key_blob, data)
     }
+}
 
+impl CompOsKeyService {
     fn do_generate(&self) -> Result<CompOsKeyData> {
         let key_descriptor = KeyDescriptor { nspace: self.namespace as i64, ..BLOB_KEY_DESCRIPTOR };
         let key_parameters =
diff --git a/compos/src/compsvc.rs b/compos/src/compsvc.rs
index 4ad2e03..24e52f5 100644
--- a/compos/src/compsvc.rs
+++ b/compos/src/compsvc.rs
@@ -19,49 +19,57 @@
 //! read/write. The service also attempts to sandbox the execution so that one task cannot leak or
 //! impact future tasks.
 //!
-//! Example:
-//! $ compsvc /system/bin/sleep
-//!
 //! The current architecture / process hierarchy looks like:
 //! - compsvc (handle requests)
 //!   - compsvc_worker (for environment setup)
 //!     - authfs (fd translation)
 //!     - actual task
 
-use anyhow::{bail, Context, Result};
-use binder::unstable_api::AsNative;
-use log::{debug, error};
+use anyhow::Result;
+use log::error;
 use minijail::{self, Minijail};
 use std::path::PathBuf;
 
+use crate::signer::Signer;
 use compos_aidl_interface::aidl::com::android::compos::ICompService::{
     BnCompService, ICompService,
 };
 use compos_aidl_interface::aidl::com::android::compos::Metadata::Metadata;
 use compos_aidl_interface::binder::{
-    add_service, BinderFeatures, Interface, ProcessState, Result as BinderResult, Status,
-    StatusCode, Strong,
+    BinderFeatures, Interface, Result as BinderResult, Status, StatusCode, Strong,
 };
 
-mod common;
-use common::{SERVICE_NAME, VSOCK_PORT};
-
 const WORKER_BIN: &str = "/apex/com.android.compos/bin/compsvc_worker";
+
 // TODO: Replace with a valid directory setup in the VM.
 const AUTHFS_MOUNTPOINT: &str = "/data/local/tmp";
 
-struct CompService {
-    worker_bin: PathBuf,
+/// Constructs a binder object that implements ICompService. task_bin is the path to the binary that will
+/// be run when execute() is called. If debuggable is true then stdout/stderr from the binary will be
+/// available for debugging.
+pub fn new_binder(
     task_bin: String,
-    rpc_binder: bool,
     debuggable: bool,
+    signer: Option<Box<dyn Signer>>,
+) -> Strong<dyn ICompService> {
+    let service = CompService {
+        worker_bin: PathBuf::from(WORKER_BIN.to_owned()),
+        task_bin,
+        debuggable,
+        signer,
+    };
+    BnCompService::new_binder(service, BinderFeatures::default())
+}
+
+struct CompService {
+    task_bin: String,
+    worker_bin: PathBuf,
+    debuggable: bool,
+    #[allow(dead_code)] // TODO: Make use of this
+    signer: Option<Box<dyn Signer>>,
 }
 
 impl CompService {
-    pub fn new_binder(service: CompService) -> Strong<dyn ICompService> {
-        BnCompService::new_binder(service, BinderFeatures::default())
-    }
-
     fn run_worker_in_jail_and_wait(&self, args: &[String]) -> Result<(), minijail::Error> {
         let mut jail = Minijail::new()?;
 
@@ -124,56 +132,3 @@
         }
     }
 }
-
-fn parse_args() -> Result<CompService> {
-    #[rustfmt::skip]
-    let matches = clap::App::new("compsvc")
-        .arg(clap::Arg::with_name("debug")
-             .long("debug"))
-        .arg(clap::Arg::with_name("task_bin")
-             .required(true))
-        .arg(clap::Arg::with_name("rpc_binder")
-             .long("rpc-binder"))
-        .get_matches();
-
-    Ok(CompService {
-        task_bin: matches.value_of("task_bin").unwrap().to_string(),
-        worker_bin: PathBuf::from(WORKER_BIN),
-        rpc_binder: matches.is_present("rpc_binder"),
-        debuggable: matches.is_present("debug"),
-    })
-}
-
-fn main() -> Result<()> {
-    android_logger::init_once(
-        android_logger::Config::default().with_tag("compsvc").with_min_level(log::Level::Debug),
-    );
-
-    let service = parse_args()?;
-
-    if service.rpc_binder {
-        let mut service = CompService::new_binder(service).as_binder();
-        debug!("compsvc is starting as a rpc service.");
-        // SAFETY: Service ownership is transferring to the server and won't be valid afterward.
-        // Plus the binder objects are threadsafe.
-        let retval = unsafe {
-            binder_rpc_unstable_bindgen::RunRpcServer(
-                service.as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder,
-                VSOCK_PORT,
-            )
-        };
-        if retval {
-            debug!("RPC server has shut down gracefully");
-            Ok(())
-        } else {
-            bail!("Premature termination of RPC server");
-        }
-    } else {
-        ProcessState::start_thread_pool();
-        debug!("compsvc is starting as a local service.");
-        add_service(SERVICE_NAME, CompService::new_binder(service).as_binder())
-            .with_context(|| format!("Failed to register service {}", SERVICE_NAME))?;
-        ProcessState::join_thread_pool();
-        bail!("Unexpected exit after join_thread_pool")
-    }
-}
diff --git a/compos/src/compsvc_main.rs b/compos/src/compsvc_main.rs
new file mode 100644
index 0000000..9f12132
--- /dev/null
+++ b/compos/src/compsvc_main.rs
@@ -0,0 +1,88 @@
+/*
+ * Copyright (C) 2021 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+//! A tool to start a standalone compsvc server, either in the host using Binder or in a VM using
+//! RPC binder over vsock.
+//!
+//! Example:
+//! $ compsvc /system/bin/sleep
+
+mod common;
+mod compsvc;
+mod signer;
+
+use crate::common::{SERVICE_NAME, VSOCK_PORT};
+use anyhow::{bail, Context, Result};
+use binder::unstable_api::AsNative;
+use compos_aidl_interface::binder::{add_service, ProcessState};
+use log::debug;
+
+struct Config {
+    task_bin: String,
+    rpc_binder: bool,
+    debuggable: bool,
+}
+
+fn parse_args() -> Result<Config> {
+    #[rustfmt::skip]
+    let matches = clap::App::new("compsvc")
+        .arg(clap::Arg::with_name("debug")
+             .long("debug"))
+        .arg(clap::Arg::with_name("task_bin")
+             .required(true))
+        .arg(clap::Arg::with_name("rpc_binder")
+             .long("rpc-binder"))
+        .get_matches();
+
+    Ok(Config {
+        task_bin: matches.value_of("task_bin").unwrap().to_string(),
+        rpc_binder: matches.is_present("rpc_binder"),
+        debuggable: matches.is_present("debug"),
+    })
+}
+
+fn main() -> Result<()> {
+    android_logger::init_once(
+        android_logger::Config::default().with_tag("compsvc").with_min_level(log::Level::Debug),
+    );
+
+    let config = parse_args()?;
+    let mut service = compsvc::new_binder(config.task_bin, config.debuggable, None).as_binder();
+    if config.rpc_binder {
+        debug!("compsvc is starting as a rpc service.");
+        // SAFETY: Service ownership is transferring to the server and won't be valid afterward.
+        // Plus the binder objects are threadsafe.
+        let retval = unsafe {
+            binder_rpc_unstable_bindgen::RunRpcServer(
+                service.as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder,
+                VSOCK_PORT,
+            )
+        };
+        if retval {
+            debug!("RPC server has shut down gracefully");
+            Ok(())
+        } else {
+            bail!("Premature termination of RPC server");
+        }
+    } else {
+        ProcessState::start_thread_pool();
+        debug!("compsvc is starting as a local service.");
+        add_service(SERVICE_NAME, service)
+            .with_context(|| format!("Failed to register service {}", SERVICE_NAME))?;
+        ProcessState::join_thread_pool();
+        bail!("Unexpected exit after join_thread_pool")
+    }
+}
diff --git a/compos/src/signer.rs b/compos/src/signer.rs
new file mode 100644
index 0000000..9ff1477
--- /dev/null
+++ b/compos/src/signer.rs
@@ -0,0 +1,23 @@
+/*
+ * Copyright (C) 2021 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+use anyhow::Result;
+
+/// Provides the ability to cryptographically sign messages.
+pub trait Signer: Send + Sync {
+    /// Sign the supplied data. The result is a raw signature over the input data.
+    fn sign(&self, data: &[u8]) -> Result<Vec<u8>>;
+}
diff --git a/tests/hostside/AndroidTest.xml b/tests/hostside/AndroidTest.xml
index eda733a..e8aced6 100644
--- a/tests/hostside/AndroidTest.xml
+++ b/tests/hostside/AndroidTest.xml
@@ -14,14 +14,6 @@
      limitations under the License.
 -->
 <configuration description="Tests for microdroid">
-    <target_preparer class="com.android.tradefed.targetprep.RootTargetPreparer">
-        <option name="force-root" value="true" />
-    </target_preparer>
-
-    <!-- virtualizationservice doesn't have access to shell_data_file. Instead of giving it
-      a test-only permission, run it without selinux -->
-    <target_preparer class="com.android.tradefed.targetprep.DisableSELinuxTargetPreparer"/>
-
     <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
         <option name="jar" value="MicrodroidHostTestCases.jar" />
     </test>
diff --git a/tests/hostside/helper/java/android/virt/test/VirtualizationTestCaseBase.java b/tests/hostside/helper/java/android/virt/test/VirtualizationTestCaseBase.java
index 988b1ad..40debba 100644
--- a/tests/hostside/helper/java/android/virt/test/VirtualizationTestCaseBase.java
+++ b/tests/hostside/helper/java/android/virt/test/VirtualizationTestCaseBase.java
@@ -84,7 +84,7 @@
         // don't run the test (instead of failing)
         android.assumeSuccess("ls /dev/kvm");
         android.assumeSuccess("ls /dev/vhost-vsock");
-        android.assumeSuccess("ls /apex/com.android.virt/bin/crosvm");
+        android.assumeSuccess("ls /apex/com.android.virt");
     }
 
     // Run an arbitrary command in the host side and returns the result
@@ -181,7 +181,6 @@
         final String debugFlag = debug ? "--debug " : "";
 
         // Run the VM
-        android.run("start", "virtualizationservice");
         String ret =
                 android.run(
                         VIRT_APEX + "bin/vm",
diff --git a/virtualizationservice/src/aidl.rs b/virtualizationservice/src/aidl.rs
index 12c46ee..1d99c2d 100644
--- a/virtualizationservice/src/aidl.rs
+++ b/virtualizationservice/src/aidl.rs
@@ -16,7 +16,7 @@
 
 use crate::composite::make_composite_image;
 use crate::crosvm::{CrosvmConfig, DiskFile, VmInstance};
-use crate::payload::make_payload_disk;
+use crate::payload::add_microdroid_images;
 use crate::{Cid, FIRST_GUEST_CID};
 
 use android_os_permissions_aidl::aidl::android::os::IPermissionController;
@@ -38,7 +38,7 @@
 use anyhow::{bail, Context, Result};
 use disk::QcowFile;
 use log::{debug, error, warn, info};
-use microdroid_payload_config::{ApexConfig, VmPayloadConfig};
+use microdroid_payload_config::VmPayloadConfig;
 use std::convert::TryInto;
 use std::ffi::CString;
 use std::fs::{File, OpenOptions, create_dir};
@@ -46,7 +46,7 @@
 use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
 use std::path::{Path, PathBuf};
 use std::sync::{Arc, Mutex, Weak};
-use vmconfig::{VmConfig, Partition};
+use vmconfig::VmConfig;
 use vsock::{VsockListener, SockAddr, VsockStream};
 use zip::ZipArchive;
 
@@ -55,11 +55,6 @@
 /// Directory in which to write disk image files used while running VMs.
 pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
 
-/// The list of APEXes which microdroid requires.
-/// TODO(b/192200378) move this to microdroid.json?
-const MICRODROID_REQUIRED_APEXES: [&str; 3] =
-    ["com.android.adbd", "com.android.i18n", "com.android.os.statsd"];
-
 /// The CID representing the host VM
 const VMADDR_CID_HOST: u32 = 2;
 
@@ -365,53 +360,43 @@
     config: &VirtualMachineAppConfig,
     temporary_directory: &Path,
 ) -> Result<VirtualMachineRawConfig> {
-    let apk_file = config.apk.as_ref().unwrap().as_ref();
-    let idsig_file = config.idsig.as_ref().unwrap().as_ref();
+    let apk_file = clone_file(config.apk.as_ref().unwrap())?;
+    let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
     // TODO(b/193504400) pass this to crosvm
-    let _instance_file = config.instanceImage.as_ref().unwrap().as_ref();
+    let _instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
     let config_path = &config.configPath;
 
-    let mut apk_zip = ZipArchive::new(apk_file)?;
+    let mut apk_zip = ZipArchive::new(&apk_file)?;
     let config_file = apk_zip.by_name(config_path)?;
     let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
 
     let os_name = &vm_payload_config.os.name;
+
     // For now, the only supported "os" value is "microdroid"
     if os_name != "microdroid" {
-        bail!("unknown os: {}", os_name);
+        bail!("Unknown OS \"{}\"", os_name);
     }
+
+    // It is safe to construct a filename based on the os_name because we've already checked that it
+    // is one of the allowed values.
     let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
     let vm_config_file = File::open(vm_config_path)?;
-    let mut vm_config = VmConfig::load(&vm_config_file)?;
+    let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
 
-    // Microdroid requires additional payload disk image and the bootconfig partition
+    // Microdroid requires an additional payload disk image and the bootconfig partition.
     if os_name == "microdroid" {
-        let mut apexes = vm_payload_config.apexes.clone();
-        apexes.extend(
-            MICRODROID_REQUIRED_APEXES.iter().map(|name| ApexConfig { name: name.to_string() }),
-        );
-        apexes.dedup_by(|a, b| a.name == b.name);
-
-        vm_config.disks.push(make_payload_disk(
-            format!("/proc/self/fd/{}", apk_file.as_raw_fd()).into(),
-            format!("/proc/self/fd/{}", idsig_file.as_raw_fd()).into(),
-            config_path,
-            &apexes,
+        let apexes = vm_payload_config.apexes.clone();
+        add_microdroid_images(
+            config,
             temporary_directory,
-        )?);
-
-        if config.debug {
-            vm_config.disks[1].partitions.push(Partition {
-                label: "bootconfig".to_owned(),
-                paths: vec![PathBuf::from(
-                    "/apex/com.android.virt/etc/microdroid_bootconfig.debug",
-                )],
-                writable: false,
-            });
-        }
+            apk_file,
+            idsig_file,
+            apexes,
+            &mut vm_config,
+        )?;
     }
 
-    vm_config.to_parcelable()
+    Ok(vm_config)
 }
 
 /// Generates a unique filename to use for a composite disk image.
diff --git a/virtualizationservice/src/payload.rs b/virtualizationservice/src/payload.rs
index 9c6deae..28ef502 100644
--- a/virtualizationservice/src/payload.rs
+++ b/virtualizationservice/src/payload.rs
@@ -14,6 +14,11 @@
 
 //! Payload disk image
 
+use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
+    DiskImage::DiskImage, Partition::Partition, VirtualMachineAppConfig::VirtualMachineAppConfig,
+    VirtualMachineRawConfig::VirtualMachineRawConfig,
+};
+use android_system_virtualizationservice::binder::ParcelFileDescriptor;
 use anyhow::{anyhow, Context, Result};
 use microdroid_metadata::{ApexPayload, ApkPayload, Metadata};
 use microdroid_payload_config::ApexConfig;
@@ -22,7 +27,12 @@
 use serde_xml_rs::from_reader;
 use std::fs::{File, OpenOptions};
 use std::path::{Path, PathBuf};
-use vmconfig::{DiskImage, Partition};
+use vmconfig::open_parcel_file;
+
+/// The list of APEXes which microdroid requires.
+// TODO(b/192200378) move this to microdroid.json?
+const MICRODROID_REQUIRED_APEXES: [&str; 3] =
+    ["com.android.adbd", "com.android.i18n", "com.android.os.statsd"];
 
 const APEX_INFO_LIST_PATH: &str = "/apex/apex-info-list.xml";
 
@@ -65,23 +75,14 @@
     }
 }
 
-/// Creates a DiskImage with partitions:
-///   metadata: metadata
-///   microdroid-apex-0: apex 0
-///   microdroid-apex-1: apex 1
-///   ..
-///   microdroid-apk: apk
-///   microdroid-apk-idsig: idsig
-pub fn make_payload_disk(
-    apk_file: PathBuf,
-    idsig_file: PathBuf,
+fn make_metadata_file(
     config_path: &str,
     apexes: &[ApexConfig],
     temporary_directory: &Path,
-) -> Result<DiskImage> {
+) -> Result<ParcelFileDescriptor> {
     let metadata_path = temporary_directory.join("metadata");
     let metadata = Metadata {
-        version: 1u32,
+        version: 1,
         apexes: apexes
             .iter()
             .map(|apex| ApexPayload { name: apex.name.clone(), ..Default::default() })
@@ -96,35 +97,97 @@
         payload_config_path: format!("/mnt/apk/{}", config_path),
         ..Default::default()
     };
-    let mut metadata_file =
-        OpenOptions::new().create_new(true).read(true).write(true).open(&metadata_path)?;
+
+    // Write metadata to file.
+    let mut metadata_file = OpenOptions::new()
+        .create_new(true)
+        .read(true)
+        .write(true)
+        .open(&metadata_path)
+        .with_context(|| format!("Failed to open metadata file {:?}", metadata_path))?;
     microdroid_metadata::write_metadata(&metadata, &mut metadata_file)?;
 
+    // Re-open the metadata file as read-only.
+    open_parcel_file(&metadata_path, false)
+}
+
+/// Creates a DiskImage with partitions:
+///   metadata: metadata
+///   microdroid-apex-0: apex 0
+///   microdroid-apex-1: apex 1
+///   ..
+///   microdroid-apk: apk
+///   microdroid-apk-idsig: idsig
+fn make_payload_disk(
+    apk_file: File,
+    idsig_file: File,
+    config_path: &str,
+    apexes: &[ApexConfig],
+    temporary_directory: &Path,
+) -> Result<DiskImage> {
+    let metadata_file = make_metadata_file(config_path, apexes, temporary_directory)?;
     // put metadata at the first partition
     let mut partitions = vec![Partition {
         label: "payload-metadata".to_owned(),
-        paths: vec![metadata_path],
+        images: vec![metadata_file],
         writable: false,
     }];
 
     let apex_info_list = ApexInfoList::load()?;
     for (i, apex) in apexes.iter().enumerate() {
+        let apex_path = apex_info_list.get_path_for(&apex.name)?;
+        let apex_file = open_parcel_file(&apex_path, false)?;
         partitions.push(Partition {
             label: format!("microdroid-apex-{}", i),
-            paths: vec![apex_info_list.get_path_for(&apex.name)?],
+            images: vec![apex_file],
             writable: false,
         });
     }
     partitions.push(Partition {
         label: "microdroid-apk".to_owned(),
-        paths: vec![apk_file],
+        images: vec![ParcelFileDescriptor::new(apk_file)],
         writable: false,
     });
     partitions.push(Partition {
         label: "microdroid-apk-idsig".to_owned(),
-        paths: vec![idsig_file],
+        images: vec![ParcelFileDescriptor::new(idsig_file)],
         writable: false,
     });
 
     Ok(DiskImage { image: None, partitions, writable: false })
 }
+
+pub fn add_microdroid_images(
+    config: &VirtualMachineAppConfig,
+    temporary_directory: &Path,
+    apk_file: File,
+    idsig_file: File,
+    mut apexes: Vec<ApexConfig>,
+    vm_config: &mut VirtualMachineRawConfig,
+) -> Result<()> {
+    apexes.extend(
+        MICRODROID_REQUIRED_APEXES.iter().map(|name| ApexConfig { name: name.to_string() }),
+    );
+    apexes.dedup_by(|a, b| a.name == b.name);
+
+    vm_config.disks.push(make_payload_disk(
+        apk_file,
+        idsig_file,
+        &config.configPath,
+        &apexes,
+        temporary_directory,
+    )?);
+
+    if config.debug {
+        vm_config.disks[1].partitions.push(Partition {
+            label: "bootconfig".to_owned(),
+            images: vec![open_parcel_file(
+                Path::new("/apex/com.android.virt/etc/microdroid_bootconfig.debug"),
+                false,
+            )?],
+            writable: false,
+        });
+    }
+
+    Ok(())
+}