Merge "Fix log string checked to test vbmeta verification"
diff --git a/TEST_MAPPING b/TEST_MAPPING
index 5a422df..14452a3 100644
--- a/TEST_MAPPING
+++ b/TEST_MAPPING
@@ -19,7 +19,7 @@
       "name": "compos_key_tests"
     },
     {
-      "name": "composd_verify.test"
+      "name": "compos_verify.test"
     },
     {
       "name": "initrd_bootconfig.test"
@@ -55,7 +55,7 @@
       "path": "packages/modules/Virtualization/encryptedstore"
     },
     {
-      "path": "packages/modules/Virtualization/virtualizationservice"
+      "path": "packages/modules/Virtualization/virtualizationmanager"
     },
     {
       "path": "packages/modules/Virtualization/libs/apexutil"
diff --git a/apex/Android.bp b/apex/Android.bp
index dce8edd..bdea039 100644
--- a/apex/Android.bp
+++ b/apex/Android.bp
@@ -3,15 +3,8 @@
 }
 
 microdroid_filesystem_images = [
-    "microdroid_boot",
-    "microdroid_bootconfig_debuggable",
-    "microdroid_bootconfig_normal",
-    "microdroid_init_boot",
     "microdroid_super",
-    "microdroid_uboot_env",
     "microdroid_vbmeta",
-    "microdroid_vbmeta_bootconfig",
-    "microdroid_vendor_boot",
 ]
 
 soong_config_module_type {
@@ -98,8 +91,6 @@
         "microdroid_initrd_debuggable",
         "microdroid_initrd_normal",
         "microdroid.json",
-        "microdroid_bootloader",
-        "microdroid_bootloader.avbpubkey",
         "microdroid_kernel",
     ],
     host_required: [
@@ -146,7 +137,10 @@
         },
     },
     required: [
+        // sign_virt_apex should be runnable from outside the source tree,
+        // therefore, any required tool should be listed in build/make/core/Makefile as well.
         "img2simg",
+        "initrd_bootconfig",
         "lpmake",
         "lpunpack",
         "simg2img",
@@ -167,6 +161,7 @@
         // sign_virt_apex
         "avbtool",
         "img2simg",
+        "initrd_bootconfig",
         "lpmake",
         "lpunpack",
         "sign_virt_apex",
diff --git a/apex/sign_virt_apex.py b/apex/sign_virt_apex.py
index 557c8aa..3f3600d 100644
--- a/apex/sign_virt_apex.py
+++ b/apex/sign_virt_apex.py
@@ -24,7 +24,7 @@
 
 sign_virt_apex uses external tools which are assumed to be available via PATH.
 - avbtool (--avbtool can override the tool)
-- lpmake, lpunpack, simg2img, img2simg
+- lpmake, lpunpack, simg2img, img2simg, initrd_bootconfig
 """
 import argparse
 import hashlib
@@ -102,6 +102,11 @@
     parser.add_argument(
         'input_dir',
         help='the directory having files to be packaged')
+    parser.add_argument(
+        '--do_not_update_bootconfigs',
+        action='store_true',
+        help='This will NOT update the vbmeta related bootconfigs while signing the apex.\
+            Used for testing only!!')
     args = parser.parse_args(argv)
     # preprocess --key_override into a map
     args.key_overrides = {}
@@ -200,23 +205,19 @@
     return info, descriptors
 
 
-# Look up a list of (key, value) with a key. Returns the value of the first matching pair.
+# Look up a list of (key, value) with a key. Returns the list of value(s) with the matching key.
+# The order of those values is maintained.
 def LookUp(pairs, key):
-    for k, v in pairs:
-        if key == k:
-            return v
-    return None
+    return [v for (k, v) in pairs if k == key]
 
 
-def AddHashFooter(args, key, image_path):
+def AddHashFooter(args, key, image_path, partition_name, additional_descriptors=None):
     if os.path.basename(image_path) in args.key_overrides:
         key = args.key_overrides[os.path.basename(image_path)]
-    info, descriptors = AvbInfo(args, image_path)
+    info, _ = AvbInfo(args, image_path)
     if info:
-        descriptor = LookUp(descriptors, 'Hash descriptor')
         image_size = ReadBytesSize(info['Image size'])
         algorithm = info['Algorithm']
-        partition_name = descriptor['Partition Name']
         partition_size = str(image_size)
 
         cmd = ['avbtool', 'add_hash_footer',
@@ -227,6 +228,9 @@
                '--image', image_path]
         if args.signing_args:
             cmd.extend(shlex.split(args.signing_args))
+        if additional_descriptors:
+            for image in additional_descriptors:
+                cmd.extend(['--include_descriptors_from_image', image])
         RunCommand(args, cmd)
 
 
@@ -235,7 +239,7 @@
         key = args.key_overrides[os.path.basename(image_path)]
     info, descriptors = AvbInfo(args, image_path)
     if info:
-        descriptor = LookUp(descriptors, 'Hashtree descriptor')
+        descriptor = LookUp(descriptors, 'Hashtree descriptor')[0]
         image_size = ReadBytesSize(info['Image size'])
         algorithm = info['Algorithm']
         partition_name = descriptor['Partition Name']
@@ -254,6 +258,82 @@
         RunCommand(args, cmd)
 
 
+def UpdateVbmetaBootconfig(args, initrds, vbmeta_img):
+    # Update the bootconfigs in ramdisk
+    def detach_bootconfigs(initrd_bc, initrd, bc):
+        cmd = ['initrd_bootconfig', 'detach', initrd_bc, initrd, bc]
+        RunCommand(args, cmd)
+
+    def attach_bootconfigs(initrd_bc, initrd, bc):
+        cmd = ['initrd_bootconfig', 'attach',
+               initrd, bc, '--output', initrd_bc]
+        RunCommand(args, cmd)
+
+    # Validate that avb version used while signing the apex is the same as used by build server
+    def validate_avb_version(bootconfigs):
+        cmd = ['avbtool', 'version']
+        stdout, _ = RunCommand(args, cmd)
+        avb_version_curr = stdout.split(" ")[1].strip()
+        avb_version_curr = avb_version_curr[0:avb_version_curr.rfind('.')]
+
+        avb_version_bc = re.search(
+            r"androidboot.vbmeta.avb_version = \"([^\"]*)\"", bootconfigs).group(1)
+        if avb_version_curr != avb_version_bc:
+            raise Exception(f'AVB version mismatch between current & one & \
+                used to build bootconfigs:{avb_version_curr}&{avb_version_bc}')
+
+    def calc_vbmeta_digest():
+        cmd = ['avbtool', 'calculate_vbmeta_digest', '--image',
+               vbmeta_img, '--hash_algorithm', 'sha256']
+        stdout, _ = RunCommand(args, cmd)
+        return stdout.strip()
+
+    def calc_vbmeta_size():
+        cmd = ['avbtool', 'info_image', '--image', vbmeta_img]
+        stdout, _ = RunCommand(args, cmd)
+        size = 0
+        for line in stdout.split("\n"):
+            line = line.split(":")
+            if line[0] in ['Header Block', 'Authentication Block', 'Auxiliary Block']:
+                size += int(line[1].strip()[0:-6])
+        return size
+
+    def update_vbmeta_digest(bootconfigs):
+        # Update androidboot.vbmeta.digest in bootconfigs
+        result = re.search(
+            r"androidboot.vbmeta.digest = \"[^\"]*\"", bootconfigs)
+        if not result:
+            raise ValueError("Failed to find androidboot.vbmeta.digest")
+
+        return bootconfigs.replace(result.group(),
+                                   f'androidboot.vbmeta.digest = "{calc_vbmeta_digest()}"')
+
+    def update_vbmeta_size(bootconfigs):
+        # Update androidboot.vbmeta.size in bootconfigs
+        result = re.search(r"androidboot.vbmeta.size = [0-9]+", bootconfigs)
+        if not result:
+            raise ValueError("Failed to find androidboot.vbmeta.size")
+        return bootconfigs.replace(result.group(),
+                                   f'androidboot.vbmeta.size = {calc_vbmeta_size()}')
+
+    with tempfile.TemporaryDirectory() as work_dir:
+        tmp_initrd = os.path.join(work_dir, 'initrd')
+        tmp_bc = os.path.join(work_dir, 'bc')
+
+        for initrd in initrds:
+            detach_bootconfigs(initrd, tmp_initrd, tmp_bc)
+            bc_file = open(tmp_bc, "rt", encoding="utf-8")
+            bc_data = bc_file.read()
+            validate_avb_version(bc_data)
+            bc_data = update_vbmeta_digest(bc_data)
+            bc_data = update_vbmeta_size(bc_data)
+            bc_file.close()
+            bc_file = open(tmp_bc, "wt", encoding="utf-8")
+            bc_file.write(bc_data)
+            bc_file.flush()
+            attach_bootconfigs(initrd, tmp_initrd, tmp_bc)
+
+
 def MakeVbmetaImage(args, key, vbmeta_img, images=None, chained_partitions=None):
     if os.path.basename(vbmeta_img) in args.key_overrides:
         key = args.key_overrides[os.path.basename(vbmeta_img)]
@@ -318,43 +398,21 @@
         RunCommand(args, cmd)
 
 
-def ReplaceBootloaderPubkey(args, key, bootloader, bootloader_pubkey):
-    if os.path.basename(bootloader) in args.key_overrides:
-        key = args.key_overrides[os.path.basename(bootloader)]
-    # read old pubkey before replacement
-    with open(bootloader_pubkey, 'rb') as f:
-        old_pubkey = f.read()
-
-    # replace bootloader pubkey (overwrite the old one with the new one)
-    ExtractAvbPubkey(args, key, bootloader_pubkey)
-
-    # read new pubkey
-    with open(bootloader_pubkey, 'rb') as f:
-        new_pubkey = f.read()
-
-    assert len(old_pubkey) == len(new_pubkey)
-
-    # replace pubkey embedded in bootloader
-    with open(bootloader, 'r+b') as bl_f:
-        pos = bl_f.read().find(old_pubkey)
-        assert pos != -1
-        bl_f.seek(pos)
-        bl_f.write(new_pubkey)
-
+def GenVbmetaImage(args, image, output, partition_name):
+    cmd = ['avbtool', 'add_hash_footer', '--dynamic_partition_size',
+           '--do_not_append_vbmeta_image',
+           '--partition_name', partition_name,
+           '--image', image,
+           '--output_vbmeta_image', output]
+    RunCommand(args, cmd)
 
 # dict of (key, file) for re-sign/verification. keys are un-versioned for readability.
 virt_apex_files = {
-    'bootloader.pubkey': 'etc/microdroid_bootloader.avbpubkey',
-    'bootloader': 'etc/fs/microdroid_bootloader',
-    'boot.img': 'etc/fs/microdroid_boot.img',
-    'vendor_boot.img': 'etc/fs/microdroid_vendor_boot.img',
-    'init_boot.img': 'etc/fs/microdroid_init_boot.img',
-    'super.img': 'etc/fs/microdroid_super.img',
+    'kernel': 'etc/fs/microdroid_kernel',
     'vbmeta.img': 'etc/fs/microdroid_vbmeta.img',
-    'vbmeta_bootconfig.img': 'etc/fs/microdroid_vbmeta_bootconfig.img',
-    'bootconfig.normal': 'etc/fs/microdroid_bootconfig.normal',
-    'bootconfig.debuggable': 'etc/fs/microdroid_bootconfig.debuggable',
-    'uboot_env.img': 'etc/fs/uboot_env.img'
+    'super.img': 'etc/fs/microdroid_super.img',
+    'initrd_normal.img': 'etc/microdroid_initrd_normal.img',
+    'initrd_debuggable.img': 'etc/microdroid_initrd_debuggable.img',
 }
 
 
@@ -371,17 +429,6 @@
     system_a_img = os.path.join(unpack_dir.name, 'system_a.img')
     vendor_a_img = os.path.join(unpack_dir.name, 'vendor_a.img')
 
-    # Key(pubkey) embedded in bootloader should match with the one used to make VBmeta below
-    # while it's okay to use different keys for other image files.
-    replace_f = Async(ReplaceBootloaderPubkey, args,
-                      key, files['bootloader'], files['bootloader.pubkey'])
-
-    # re-sign bootloader, boot.img, vendor_boot.img, and init_boot.img
-    Async(AddHashFooter, args, key, files['bootloader'], wait=[replace_f])
-    Async(AddHashFooter, args, key, files['boot.img'])
-    Async(AddHashFooter, args, key, files['vendor_boot.img'])
-    Async(AddHashFooter, args, key, files['init_boot.img'])
-
     # re-sign super.img
     # 1. unpack super.img
     # 2. resign system and vendor
@@ -390,27 +437,34 @@
     system_a_f = Async(AddHashTreeFooter, args, key, system_a_img)
     vendor_a_f = Async(AddHashTreeFooter, args, key, vendor_a_img)
     partitions = {"system_a": system_a_img, "vendor_a": vendor_a_img}
-    Async(MakeSuperImage, args, partitions, files['super.img'], wait=[system_a_f, vendor_a_f])
+    Async(MakeSuperImage, args, partitions,
+          files['super.img'], wait=[system_a_f, vendor_a_f])
 
     # re-generate vbmeta from re-signed {system_a, vendor_a}.img
-    Async(MakeVbmetaImage, args, key, files['vbmeta.img'],
-          images=[system_a_img, vendor_a_img],
-          wait=[system_a_f, vendor_a_f])
+    vbmeta_f = Async(MakeVbmetaImage, args, key, files['vbmeta.img'],
+                     images=[system_a_img, vendor_a_img],
+                     wait=[system_a_f, vendor_a_f])
 
-    # Re-sign bootconfigs and the uboot_env with the same key
-    bootconfig_sign_key = key
-    Async(AddHashFooter, args, bootconfig_sign_key, files['bootconfig.normal'])
-    Async(AddHashFooter, args, bootconfig_sign_key, files['bootconfig.debuggable'])
-    Async(AddHashFooter, args, bootconfig_sign_key, files['uboot_env.img'])
+    vbmeta_bc_f = None
+    if not args.do_not_update_bootconfigs:
+        vbmeta_bc_f = Async(UpdateVbmetaBootconfig, args,
+                            [files['initrd_normal.img'],
+                                files['initrd_debuggable.img']], files['vbmeta.img'],
+                            wait=[vbmeta_f])
 
-    # Re-sign vbmeta_bootconfig with chained_partitions to "bootconfig" and
-    # "uboot_env". Note that, for now, `key` and `bootconfig_sign_key` are the
-    # same, but technically they can be different. Vbmeta records pubkeys which
-    # signed chained partitions.
-    Async(MakeVbmetaImage, args, key, files['vbmeta_bootconfig.img'], chained_partitions={
-        'bootconfig': bootconfig_sign_key,
-        'uboot_env': bootconfig_sign_key,
-    })
+    # Re-sign kernel. Note kernel's vbmeta contain addition descriptor from ramdisk(s)
+    initrd_normal_hashdesc = tempfile.NamedTemporaryFile(delete=False).name
+    initrd_debug_hashdesc = tempfile.NamedTemporaryFile(delete=False).name
+    initrd_n_f = Async(GenVbmetaImage, args, files['initrd_normal.img'],
+                       initrd_normal_hashdesc, "initrd_normal",
+                       wait=[vbmeta_bc_f] if vbmeta_bc_f is not None else [])
+    initrd_d_f = Async(GenVbmetaImage, args, files['initrd_debuggable.img'],
+                       initrd_debug_hashdesc, "initrd_debug",
+                       wait=[vbmeta_bc_f] if vbmeta_bc_f is not None else [])
+    Async(AddHashFooter, args, key, files['kernel'], partition_name="boot",
+          additional_descriptors=[
+              initrd_normal_hashdesc, initrd_debug_hashdesc],
+          wait=[initrd_n_f, initrd_d_f])
 
 
 def VerifyVirtApex(args):
@@ -430,27 +484,16 @@
             pubkey = f.read()
             pubkey_digest = hashlib.sha1(pubkey).hexdigest()
 
-    def contents(file):
-        with open(file, 'rb') as f:
-            return f.read()
-
-    def check_equals_pubkey(file):
-        assert contents(file) == pubkey, f'pubkey mismatch: {file}'
-
-    def check_contains_pubkey(file):
-        assert contents(file).find(pubkey) != -1, f'pubkey missing: {file}'
-
     def check_avb_pubkey(file):
         info, _ = AvbInfo(args, file)
         assert info is not None, f'no avbinfo: {file}'
         assert info['Public key (sha1)'] == pubkey_digest, f'pubkey mismatch: {file}'
 
     for f in files.values():
-        if f == files['bootloader.pubkey']:
-            Async(check_equals_pubkey, f)
-        elif f == files['bootloader']:
-            Async(check_contains_pubkey, f)
-        elif f == files['super.img']:
+        if f in (files['initrd_normal.img'], files['initrd_debuggable.img']):
+            # TODO(b/245277660): Verify that ramdisks contain the correct vbmeta digest
+            continue
+        if f == files['super.img']:
             Async(check_avb_pubkey, system_a_img)
             Async(check_avb_pubkey, vendor_a_img)
         else:
@@ -467,7 +510,7 @@
             SignVirtApex(args)
         # ensure all tasks are completed without exceptions
         AwaitAll(tasks)
-    except: # pylint: disable=bare-except
+    except:  # pylint: disable=bare-except
         traceback.print_exc()
         sys.exit(1)
 
diff --git a/apkdmverity/src/main.rs b/apkdmverity/src/main.rs
index 50b6069..b9b88d4 100644
--- a/apkdmverity/src/main.rs
+++ b/apkdmverity/src/main.rs
@@ -69,7 +69,7 @@
                 optional; idsig file's root hash will be used if specified as \"none\"."
             )
             .action(ArgAction::Append)
-            .value_names(&["apk_path", "idsig_path", "name", "root_hash"]),
+            .value_names(["apk_path", "idsig_path", "name", "root_hash"]),
         )
         .arg(
             Arg::new("verbose")
diff --git a/authfs/src/fsverity/editor.rs b/authfs/src/fsverity/editor.rs
index 1e298be..4af6e80 100644
--- a/authfs/src/fsverity/editor.rs
+++ b/authfs/src/fsverity/editor.rs
@@ -204,7 +204,7 @@
             let mut merkle_tree = self.merkle_tree.write().unwrap();
 
             let offset_in_buf = (output_offset - offset) as usize;
-            let source = &buf[offset_in_buf as usize..offset_in_buf as usize + current_size];
+            let source = &buf[offset_in_buf..offset_in_buf + current_size];
             let output_chunk_index = (output_offset / CHUNK_SIZE) as usize;
             let offset_from_alignment = (output_offset % CHUNK_SIZE) as usize;
 
diff --git a/authfs/testdata/README.md b/authfs/testdata/README.md
index cf641a9..2df6753 100644
--- a/authfs/testdata/README.md
+++ b/authfs/testdata/README.md
@@ -2,7 +2,7 @@
 =================
 With a key pair, fs-verity signature can be generated by simply running
 `fsverity_metadata_generator` command line tool, which uses
-[fsverity-util](https://git.kernel.org/pub/scm/linux/kernel/git/ebiggers/fsverity-utils.git).
+[fsverity-utils](https://git.kernel.org/pub/scm/fs/fsverity/fsverity-utils.git)
 
 ```
 fsverity_metadata_generator --fsverity-path {fsverity_path} --key key.pem --key-format pem \
diff --git a/avmd/src/main.rs b/avmd/src/main.rs
index 740e9aa..8d7cb57 100644
--- a/avmd/src/main.rs
+++ b/avmd/src/main.rs
@@ -128,21 +128,21 @@
                 .arg(
                     Arg::new("vbmeta")
                         .long("vbmeta")
-                        .value_names(&namespace_name_file)
+                        .value_names(namespace_name_file)
                         .num_args(3)
                         .action(ArgAction::Append),
                 )
                 .arg(
                     Arg::new("apk")
                         .long("apk")
-                        .value_names(&namespace_name_file)
+                        .value_names(namespace_name_file)
                         .num_args(3)
                         .action(ArgAction::Append),
                 )
                 .arg(
                     Arg::new("apex-payload")
                         .long("apex-payload")
-                        .value_names(&namespace_name_file)
+                        .value_names(namespace_name_file)
                         .num_args(3)
                         .action(ArgAction::Append),
                 ),
diff --git a/compos/benchmark/src/java/com/android/compos/benchmark/ComposBenchmark.java b/compos/benchmark/src/java/com/android/compos/benchmark/ComposBenchmark.java
index c25de71..b884b9e 100644
--- a/compos/benchmark/src/java/com/android/compos/benchmark/ComposBenchmark.java
+++ b/compos/benchmark/src/java/com/android/compos/benchmark/ComposBenchmark.java
@@ -17,6 +17,7 @@
 
 import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
 
+import static com.google.common.truth.Truth.assertThat;
 import static com.google.common.truth.TruthJUnit.assume;
 
 import static org.junit.Assert.assertTrue;
@@ -136,9 +137,7 @@
             Long compileStartTime = System.nanoTime();
             String output = executeCommand(command);
             Long compileEndTime = System.nanoTime();
-            Pattern pattern = Pattern.compile("All Ok");
-            Matcher matcher = pattern.matcher(output);
-            assertTrue(matcher.find());
+            assertThat(output).containsMatch("All Ok");
             double elapsedSec = (compileEndTime - compileStartTime) / NANOS_IN_SEC;
             Log.i(TAG, "Compile time in guest took " + elapsedSec + "s");
             getMetricsRunnable.stop();
diff --git a/compos/tests/Android.bp b/compos/tests/Android.bp
index 41958ca..511ecd0 100644
--- a/compos/tests/Android.bp
+++ b/compos/tests/Android.bp
@@ -19,7 +19,7 @@
     // java_test_host doesn't have data_native_libs but jni_libs can be used to put
     // native modules under ./lib directory.
     // This works because host tools have rpath (../lib and ./lib).
-    data_native_bins: ["bcc_validator"],
+    data_native_bins: ["hwtrust"],
     jni_libs: [
         "libcrypto",
         "libc++",
diff --git a/compos/tests/java/android/compos/test/ComposTestCase.java b/compos/tests/java/android/compos/test/ComposTestCase.java
index d8504f7..fe1c4f0 100644
--- a/compos/tests/java/android/compos/test/ComposTestCase.java
+++ b/compos/tests/java/android/compos/test/ComposTestCase.java
@@ -186,13 +186,16 @@
                 new FileInputStreamSource(bcc_file));
 
         // Find the validator binary - note that it's specified as a dependency in our Android.bp.
-        File validator = getTestInformation().getDependencyFile("bcc_validator", /*targetFirst=*/
-                false);
+        File validator = getTestInformation().getDependencyFile("hwtrust", /*targetFirst=*/ false);
 
-        CommandResult result = new RunUtil().runTimedCmd(10000,
-                validator.getAbsolutePath(), "verify-chain", bcc_file.getAbsolutePath());
-        assertWithMessage("bcc_validator failed").about(command_results())
-                .that(result).isSuccess();
+        CommandResult result =
+                new RunUtil()
+                        .runTimedCmd(
+                                10000,
+                                validator.getAbsolutePath(),
+                                "verify-dice-chain",
+                                bcc_file.getAbsolutePath());
+        assertWithMessage("hwtrust failed").about(command_results()).that(result).isSuccess();
     }
 
     private CommandResult runOdrefresh(CommandRunner android, String command) throws Exception {
diff --git a/encryptedstore/src/main.rs b/encryptedstore/src/main.rs
index 888485b..2f54534 100644
--- a/encryptedstore/src/main.rs
+++ b/encryptedstore/src/main.rs
@@ -63,7 +63,7 @@
 
 fn encryptedstore_init(blkdevice: &Path, key: &str, mountpoint: &Path) -> Result<()> {
     ensure!(
-        std::fs::metadata(&blkdevice)
+        std::fs::metadata(blkdevice)
             .context(format!("Failed to get metadata of {:?}", blkdevice))?
             .file_type()
             .is_block_device(),
diff --git a/javalib/32/public/api/android.system.virtualmachine-removed.txt b/javalib/32/public/api/android.system.virtualmachine-removed.txt
deleted file mode 100644
index d802177..0000000
--- a/javalib/32/public/api/android.system.virtualmachine-removed.txt
+++ /dev/null
@@ -1 +0,0 @@
-// Signature format: 2.0
diff --git a/javalib/32/public/api/android.system.virtualmachine.txt b/javalib/32/public/api/android.system.virtualmachine.txt
deleted file mode 100644
index d802177..0000000
--- a/javalib/32/public/api/android.system.virtualmachine.txt
+++ /dev/null
@@ -1 +0,0 @@
-// Signature format: 2.0
diff --git a/javalib/32/system/api/android.system.virtualmachine-removed.txt b/javalib/32/system/api/android.system.virtualmachine-removed.txt
deleted file mode 100644
index d802177..0000000
--- a/javalib/32/system/api/android.system.virtualmachine-removed.txt
+++ /dev/null
@@ -1 +0,0 @@
-// Signature format: 2.0
diff --git a/javalib/32/system/api/android.system.virtualmachine.txt b/javalib/32/system/api/android.system.virtualmachine.txt
deleted file mode 100644
index d802177..0000000
--- a/javalib/32/system/api/android.system.virtualmachine.txt
+++ /dev/null
@@ -1 +0,0 @@
-// Signature format: 2.0
diff --git a/javalib/Android.bp b/javalib/Android.bp
index 118b648..a124af7 100644
--- a/javalib/Android.bp
+++ b/javalib/Android.bp
@@ -52,11 +52,6 @@
     ],
 }
 
-prebuilt_apis {
-    name: "android-virtualization-framework-sdk",
-    api_dirs: ["32"],
-}
-
 java_api_contribution {
     name: "framework-virtualization-public-stubs",
     api_surface: "public",
@@ -65,3 +60,30 @@
         "//build/orchestrator/apis",
     ],
 }
+
+java_api_contribution {
+    name: "framework-virtualization-system-stubs",
+    api_surface: "system",
+    api_file: "api/system-current.txt",
+    visibility: [
+        "//build/orchestrator/apis",
+    ],
+}
+
+java_api_contribution {
+    name: "framework-virtualization-test-stubs",
+    api_surface: "test",
+    api_file: "api/test-current.txt",
+    visibility: [
+        "//build/orchestrator/apis",
+    ],
+}
+
+java_api_contribution {
+    name: "framework-virtualization-module-lib-stubs",
+    api_surface: "module-lib",
+    api_file: "api/module-lib-current.txt",
+    visibility: [
+        "//build/orchestrator/apis",
+    ],
+}
diff --git a/javalib/api/system-current.txt b/javalib/api/system-current.txt
index 1977321..b455c85 100644
--- a/javalib/api/system-current.txt
+++ b/javalib/api/system-current.txt
@@ -56,10 +56,10 @@
   }
 
   public final class VirtualMachineConfig {
-    method @NonNull public String getApkPath();
+    method @Nullable public String getApkPath();
     method @NonNull public int getDebugLevel();
-    method @IntRange(from=0) public long getEncryptedStorageKib();
-    method @IntRange(from=0) public int getMemoryMib();
+    method @IntRange(from=0) public long getEncryptedStorageBytes();
+    method @IntRange(from=0) public long getMemoryBytes();
     method @IntRange(from=1) public int getNumCpus();
     method @Nullable public String getPayloadBinaryName();
     method public boolean isCompatibleWith(@NonNull android.system.virtualmachine.VirtualMachineConfig);
@@ -75,8 +75,8 @@
     method @NonNull public android.system.virtualmachine.VirtualMachineConfig build();
     method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setApkPath(@NonNull String);
     method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setDebugLevel(int);
-    method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setEncryptedStorageKib(@IntRange(from=1) long);
-    method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setMemoryMib(@IntRange(from=1) int);
+    method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setEncryptedStorageBytes(@IntRange(from=1) long);
+    method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setMemoryBytes(@IntRange(from=1) long);
     method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setNumCpus(@IntRange(from=1) int);
     method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setPayloadBinaryName(@NonNull String);
     method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setProtectedVm(boolean);
diff --git a/javalib/src/android/system/virtualmachine/VirtualMachine.java b/javalib/src/android/system/virtualmachine/VirtualMachine.java
index 1f0c8ea..ba7174e 100644
--- a/javalib/src/android/system/virtualmachine/VirtualMachine.java
+++ b/javalib/src/android/system/virtualmachine/VirtualMachine.java
@@ -40,6 +40,7 @@
 import static android.system.virtualmachine.VirtualMachineCallback.STOP_REASON_SHUTDOWN;
 import static android.system.virtualmachine.VirtualMachineCallback.STOP_REASON_START_FAILED;
 import static android.system.virtualmachine.VirtualMachineCallback.STOP_REASON_UNKNOWN;
+import static android.system.virtualmachine.VirtualMachineCallback.STOP_REASON_VIRTUALIZATION_SERVICE_DIED;
 
 import static java.util.Objects.requireNonNull;
 
@@ -475,7 +476,7 @@
                 try {
                     service.initializeWritablePartition(
                             ParcelFileDescriptor.open(vm.mEncryptedStoreFilePath, MODE_READ_WRITE),
-                            config.getEncryptedStorageKib() * 1024L,
+                            config.getEncryptedStorageBytes(),
                             PartitionType.ENCRYPTEDSTORE);
                 } catch (FileNotFoundException e) {
                     throw new VirtualMachineException("encrypted storage image missing", e);
@@ -620,15 +621,26 @@
             }
             virtualMachine = mVirtualMachine;
         }
+
+        int status;
         if (virtualMachine == null) {
-            return mVmRootPath.exists() ? STATUS_STOPPED : STATUS_DELETED;
+            status = STATUS_STOPPED;
         } else {
             try {
-                return stateToStatus(virtualMachine.getState());
+                status = stateToStatus(virtualMachine.getState());
             } catch (RemoteException e) {
                 throw e.rethrowAsRuntimeException();
             }
         }
+        if (status == STATUS_STOPPED && !mVmRootPath.exists()) {
+            // A VM can quite happily keep running if its backing files have been deleted.
+            // But once it stops, it's gone forever.
+            synchronized (mLock) {
+                dropVm();
+            }
+            return STATUS_DELETED;
+        }
+        return status;
     }
 
     private int stateToStatus(@VirtualMachineState int state) {
@@ -768,7 +780,7 @@
                 }
             } catch (IOException e) {
                 // If the file already exists, exception is not thrown.
-                throw new VirtualMachineException("failed to create idsig file", e);
+                throw new VirtualMachineException("Failed to create APK signature file", e);
             }
 
             IVirtualizationService service = mVirtualizationService.connect();
@@ -778,95 +790,25 @@
                     createVmPipes();
                 }
 
-                VirtualMachineAppConfig appConfig = getConfig().toVsConfig();
+                VirtualMachineAppConfig appConfig =
+                        getConfig().toVsConfig(mContext.getPackageManager());
                 appConfig.name = mName;
 
-                // Fill the idsig file by hashing the apk
-                service.createOrUpdateIdsigFile(
-                        appConfig.apk, ParcelFileDescriptor.open(mIdsigFilePath, MODE_READ_WRITE));
-
-                for (ExtraApkSpec extraApk : mExtraApks) {
-                    service.createOrUpdateIdsigFile(
-                            ParcelFileDescriptor.open(extraApk.apk, MODE_READ_ONLY),
-                            ParcelFileDescriptor.open(extraApk.idsig, MODE_READ_WRITE));
+                try {
+                    createIdSigs(service, appConfig);
+                } catch (FileNotFoundException e) {
+                    throw new VirtualMachineException("Failed to generate APK signature", e);
                 }
 
-                // Re-open idsig file in read-only mode
-                appConfig.idsig = ParcelFileDescriptor.open(mIdsigFilePath, MODE_READ_ONLY);
-                appConfig.instanceImage =
-                        ParcelFileDescriptor.open(mInstanceFilePath, MODE_READ_WRITE);
-                if (mEncryptedStoreFilePath != null) {
-                    appConfig.encryptedStorageImage =
-                            ParcelFileDescriptor.open(mEncryptedStoreFilePath, MODE_READ_WRITE);
-                }
-                List<ParcelFileDescriptor> extraIdsigs = new ArrayList<>();
-                for (ExtraApkSpec extraApk : mExtraApks) {
-                    extraIdsigs.add(ParcelFileDescriptor.open(extraApk.idsig, MODE_READ_ONLY));
-                }
-                appConfig.extraIdsigs = extraIdsigs;
-
                 android.system.virtualizationservice.VirtualMachineConfig vmConfigParcel =
                         android.system.virtualizationservice.VirtualMachineConfig.appConfig(
                                 appConfig);
 
-                // The VM should only be observed to die once
-                AtomicBoolean onDiedCalled = new AtomicBoolean(false);
-
-                IBinder.DeathRecipient deathRecipient = () -> {
-                    if (onDiedCalled.compareAndSet(false, true)) {
-                        executeCallback((cb) -> cb.onStopped(VirtualMachine.this,
-                                VirtualMachineCallback.STOP_REASON_VIRTUALIZATION_SERVICE_DIED));
-                    }
-                };
-
                 mVirtualMachine = service.createVm(vmConfigParcel, mConsoleWriter, mLogWriter);
-                mVirtualMachine.registerCallback(
-                        new IVirtualMachineCallback.Stub() {
-                            @Override
-                            public void onPayloadStarted(int cid) {
-                                executeCallback((cb) -> cb.onPayloadStarted(VirtualMachine.this));
-                            }
-
-                            @Override
-                            public void onPayloadReady(int cid) {
-                                executeCallback((cb) -> cb.onPayloadReady(VirtualMachine.this));
-                            }
-
-                            @Override
-                            public void onPayloadFinished(int cid, int exitCode) {
-                                executeCallback(
-                                        (cb) ->
-                                                cb.onPayloadFinished(
-                                                        VirtualMachine.this, exitCode));
-                            }
-
-                            @Override
-                            public void onError(int cid, int errorCode, String message) {
-                                int translatedError = getTranslatedError(errorCode);
-                                executeCallback(
-                                        (cb) ->
-                                                cb.onError(
-                                                        VirtualMachine.this,
-                                                        translatedError,
-                                                        message));
-                            }
-
-                            @Override
-                            public void onDied(int cid, int reason) {
-                                service.asBinder().unlinkToDeath(deathRecipient, 0);
-                                int translatedReason = getTranslatedReason(reason);
-                                if (onDiedCalled.compareAndSet(false, true)) {
-                                    executeCallback(
-                                            (cb) ->
-                                                    cb.onStopped(
-                                                            VirtualMachine.this, translatedReason));
-                                }
-                            }
-                        });
+                mVirtualMachine.registerCallback(new CallbackTranslator(service));
                 mContext.registerComponentCallbacks(mMemoryManagementCallbacks);
-                service.asBinder().linkToDeath(deathRecipient, 0);
                 mVirtualMachine.start();
-            } catch (IOException | IllegalStateException | ServiceSpecificException e) {
+            } catch (IllegalStateException | ServiceSpecificException e) {
                 throw new VirtualMachineException(e);
             } catch (RemoteException e) {
                 throw e.rethrowAsRuntimeException();
@@ -874,6 +816,32 @@
         }
     }
 
+    private void createIdSigs(IVirtualizationService service, VirtualMachineAppConfig appConfig)
+            throws RemoteException, FileNotFoundException {
+        // Fill the idsig file by hashing the apk
+        service.createOrUpdateIdsigFile(
+                appConfig.apk, ParcelFileDescriptor.open(mIdsigFilePath, MODE_READ_WRITE));
+
+        for (ExtraApkSpec extraApk : mExtraApks) {
+            service.createOrUpdateIdsigFile(
+                    ParcelFileDescriptor.open(extraApk.apk, MODE_READ_ONLY),
+                    ParcelFileDescriptor.open(extraApk.idsig, MODE_READ_WRITE));
+        }
+
+        // Re-open idsig files in read-only mode
+        appConfig.idsig = ParcelFileDescriptor.open(mIdsigFilePath, MODE_READ_ONLY);
+        appConfig.instanceImage = ParcelFileDescriptor.open(mInstanceFilePath, MODE_READ_WRITE);
+        if (mEncryptedStoreFilePath != null) {
+            appConfig.encryptedStorageImage =
+                    ParcelFileDescriptor.open(mEncryptedStoreFilePath, MODE_READ_WRITE);
+        }
+        List<ParcelFileDescriptor> extraIdsigs = new ArrayList<>();
+        for (ExtraApkSpec extraApk : mExtraApks) {
+            extraIdsigs.add(ParcelFileDescriptor.open(extraApk.idsig, MODE_READ_ONLY));
+        }
+        appConfig.extraIdsigs = extraIdsigs;
+    }
+
     @GuardedBy("mLock")
     private void createVmPipes() throws VirtualMachineException {
         try {
@@ -951,7 +919,7 @@
      * Stops this virtual machine. Stopping a virtual machine is like pulling the plug on a real
      * computer; the machine halts immediately. Software running on the virtual machine is not
      * notified of the event. Writes to {@linkplain
-     * VirtualMachineConfig.Builder#setEncryptedStorageKib encrypted storage} might not be
+     * VirtualMachineConfig.Builder#setEncryptedStorageBytes encrypted storage} might not be
      * persisted, and the instance might be left in an inconsistent state.
      *
      * <p>For a graceful shutdown, you could request the payload to call {@code exit()}, e.g. via a
@@ -1187,60 +1155,6 @@
         }
     }
 
-    @VirtualMachineCallback.ErrorCode
-    private int getTranslatedError(int reason) {
-        switch (reason) {
-            case ErrorCode.PAYLOAD_VERIFICATION_FAILED:
-                return ERROR_PAYLOAD_VERIFICATION_FAILED;
-            case ErrorCode.PAYLOAD_CHANGED:
-                return ERROR_PAYLOAD_CHANGED;
-            case ErrorCode.PAYLOAD_CONFIG_INVALID:
-                return ERROR_PAYLOAD_INVALID_CONFIG;
-            default:
-                return ERROR_UNKNOWN;
-        }
-    }
-
-    @VirtualMachineCallback.StopReason
-    private int getTranslatedReason(int reason) {
-        switch (reason) {
-            case DeathReason.INFRASTRUCTURE_ERROR:
-                return STOP_REASON_INFRASTRUCTURE_ERROR;
-            case DeathReason.KILLED:
-                return STOP_REASON_KILLED;
-            case DeathReason.SHUTDOWN:
-                return STOP_REASON_SHUTDOWN;
-            case DeathReason.START_FAILED:
-                return STOP_REASON_START_FAILED;
-            case DeathReason.REBOOT:
-                return STOP_REASON_REBOOT;
-            case DeathReason.CRASH:
-                return STOP_REASON_CRASH;
-            case DeathReason.PVM_FIRMWARE_PUBLIC_KEY_MISMATCH:
-                return STOP_REASON_PVM_FIRMWARE_PUBLIC_KEY_MISMATCH;
-            case DeathReason.PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED:
-                return STOP_REASON_PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED;
-            case DeathReason.BOOTLOADER_PUBLIC_KEY_MISMATCH:
-                return STOP_REASON_BOOTLOADER_PUBLIC_KEY_MISMATCH;
-            case DeathReason.BOOTLOADER_INSTANCE_IMAGE_CHANGED:
-                return STOP_REASON_BOOTLOADER_INSTANCE_IMAGE_CHANGED;
-            case DeathReason.MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE:
-                return STOP_REASON_MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE;
-            case DeathReason.MICRODROID_PAYLOAD_HAS_CHANGED:
-                return STOP_REASON_MICRODROID_PAYLOAD_HAS_CHANGED;
-            case DeathReason.MICRODROID_PAYLOAD_VERIFICATION_FAILED:
-                return STOP_REASON_MICRODROID_PAYLOAD_VERIFICATION_FAILED;
-            case DeathReason.MICRODROID_INVALID_PAYLOAD_CONFIG:
-                return STOP_REASON_MICRODROID_INVALID_PAYLOAD_CONFIG;
-            case DeathReason.MICRODROID_UNKNOWN_RUNTIME_ERROR:
-                return STOP_REASON_MICRODROID_UNKNOWN_RUNTIME_ERROR;
-            case DeathReason.HANGUP:
-                return STOP_REASON_HANGUP;
-            default:
-                return STOP_REASON_UNKNOWN;
-        }
-    }
-
     @Override
     public String toString() {
         VirtualMachineConfig config = getConfig();
@@ -1354,4 +1268,107 @@
             throw new VirtualMachineException("failed to transfer encryptedstore image", e);
         }
     }
+
+    /** Map the raw AIDL (& binder) callbacks to what the client expects. */
+    private class CallbackTranslator extends IVirtualMachineCallback.Stub {
+        private final IVirtualizationService mService;
+        private final DeathRecipient mDeathRecipient;
+
+        // The VM should only be observed to die once
+        private final AtomicBoolean mOnDiedCalled = new AtomicBoolean(false);
+
+        public CallbackTranslator(IVirtualizationService service) throws RemoteException {
+            this.mService = service;
+            this.mDeathRecipient = () -> reportStopped(STOP_REASON_VIRTUALIZATION_SERVICE_DIED);
+            service.asBinder().linkToDeath(mDeathRecipient, 0);
+        }
+
+        @Override
+        public void onPayloadStarted(int cid) {
+            executeCallback((cb) -> cb.onPayloadStarted(VirtualMachine.this));
+        }
+
+        @Override
+        public void onPayloadReady(int cid) {
+            executeCallback((cb) -> cb.onPayloadReady(VirtualMachine.this));
+        }
+
+        @Override
+        public void onPayloadFinished(int cid, int exitCode) {
+            executeCallback((cb) -> cb.onPayloadFinished(VirtualMachine.this, exitCode));
+        }
+
+        @Override
+        public void onError(int cid, int errorCode, String message) {
+            int translatedError = getTranslatedError(errorCode);
+            executeCallback((cb) -> cb.onError(VirtualMachine.this, translatedError, message));
+        }
+
+        @Override
+        public void onDied(int cid, int reason) {
+            int translatedReason = getTranslatedReason(reason);
+            reportStopped(translatedReason);
+            mService.asBinder().unlinkToDeath(mDeathRecipient, 0);
+        }
+
+        private void reportStopped(@VirtualMachineCallback.StopReason int reason) {
+            if (mOnDiedCalled.compareAndSet(false, true)) {
+                executeCallback((cb) -> cb.onStopped(VirtualMachine.this, reason));
+            }
+        }
+
+        @VirtualMachineCallback.ErrorCode
+        private int getTranslatedError(int reason) {
+            switch (reason) {
+                case ErrorCode.PAYLOAD_VERIFICATION_FAILED:
+                    return ERROR_PAYLOAD_VERIFICATION_FAILED;
+                case ErrorCode.PAYLOAD_CHANGED:
+                    return ERROR_PAYLOAD_CHANGED;
+                case ErrorCode.PAYLOAD_CONFIG_INVALID:
+                    return ERROR_PAYLOAD_INVALID_CONFIG;
+                default:
+                    return ERROR_UNKNOWN;
+            }
+        }
+
+        @VirtualMachineCallback.StopReason
+        private int getTranslatedReason(int reason) {
+            switch (reason) {
+                case DeathReason.INFRASTRUCTURE_ERROR:
+                    return STOP_REASON_INFRASTRUCTURE_ERROR;
+                case DeathReason.KILLED:
+                    return STOP_REASON_KILLED;
+                case DeathReason.SHUTDOWN:
+                    return STOP_REASON_SHUTDOWN;
+                case DeathReason.START_FAILED:
+                    return STOP_REASON_START_FAILED;
+                case DeathReason.REBOOT:
+                    return STOP_REASON_REBOOT;
+                case DeathReason.CRASH:
+                    return STOP_REASON_CRASH;
+                case DeathReason.PVM_FIRMWARE_PUBLIC_KEY_MISMATCH:
+                    return STOP_REASON_PVM_FIRMWARE_PUBLIC_KEY_MISMATCH;
+                case DeathReason.PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED:
+                    return STOP_REASON_PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED;
+                case DeathReason.BOOTLOADER_PUBLIC_KEY_MISMATCH:
+                    return STOP_REASON_BOOTLOADER_PUBLIC_KEY_MISMATCH;
+                case DeathReason.BOOTLOADER_INSTANCE_IMAGE_CHANGED:
+                    return STOP_REASON_BOOTLOADER_INSTANCE_IMAGE_CHANGED;
+                case DeathReason.MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE:
+                    return STOP_REASON_MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE;
+                case DeathReason.MICRODROID_PAYLOAD_HAS_CHANGED:
+                    return STOP_REASON_MICRODROID_PAYLOAD_HAS_CHANGED;
+                case DeathReason.MICRODROID_PAYLOAD_VERIFICATION_FAILED:
+                    return STOP_REASON_MICRODROID_PAYLOAD_VERIFICATION_FAILED;
+                case DeathReason.MICRODROID_INVALID_PAYLOAD_CONFIG:
+                    return STOP_REASON_MICRODROID_INVALID_PAYLOAD_CONFIG;
+                case DeathReason.MICRODROID_UNKNOWN_RUNTIME_ERROR:
+                    return STOP_REASON_MICRODROID_UNKNOWN_RUNTIME_ERROR;
+                case DeathReason.HANGUP:
+                    return STOP_REASON_HANGUP;
+                default:
+                    return STOP_REASON_UNKNOWN;
+            }
+        }
+    }
 }
diff --git a/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java b/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
index f5c3cd2..cb9bad0 100644
--- a/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
+++ b/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
@@ -29,6 +29,8 @@
 import android.annotation.SystemApi;
 import android.annotation.TestApi;
 import android.content.Context;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManager;
 import android.os.ParcelFileDescriptor;
 import android.os.PersistableBundle;
 import android.sysprop.HypervisorProperties;
@@ -58,16 +60,17 @@
     private static final String[] EMPTY_STRING_ARRAY = {};
 
     // These define the schema of the config file persisted on disk.
-    private static final int VERSION = 3;
+    private static final int VERSION = 5;
     private static final String KEY_VERSION = "version";
+    private static final String KEY_PACKAGENAME = "packageName";
     private static final String KEY_APKPATH = "apkPath";
     private static final String KEY_PAYLOADCONFIGPATH = "payloadConfigPath";
     private static final String KEY_PAYLOADBINARYNAME = "payloadBinaryPath";
     private static final String KEY_DEBUGLEVEL = "debugLevel";
     private static final String KEY_PROTECTED_VM = "protectedVm";
-    private static final String KEY_MEMORY_MIB = "memoryMib";
+    private static final String KEY_MEMORY_BYTES = "memoryBytes";
     private static final String KEY_NUM_CPUS = "numCpus";
-    private static final String KEY_ENCRYPTED_STORAGE_KIB = "encryptedStorageKib";
+    private static final String KEY_ENCRYPTED_STORAGE_BYTES = "encryptedStorageBytes";
     private static final String KEY_VM_OUTPUT_CAPTURED = "vmOutputCaptured";
 
     /** @hide */
@@ -94,8 +97,11 @@
      */
     @SystemApi public static final int DEBUG_LEVEL_FULL = 1;
 
+    /** Name of a package whose primary APK contains the VM payload. */
+    @Nullable private final String mPackageName;
+
     /** Absolute path to the APK file containing the VM payload. */
-    @NonNull private final String mApkPath;
+    @Nullable private final String mApkPath;
 
     @DebugLevel private final int mDebugLevel;
 
@@ -105,9 +111,10 @@
     private final boolean mProtectedVm;
 
     /**
-     * The amount of RAM to give the VM, in MiB. If this is 0 or negative the default will be used.
+     * The amount of RAM to give the VM, in bytes. If this is 0 or negative the default will be
+     * used.
      */
-    private final int mMemoryMib;
+    private final long mMemoryBytes;
 
     /**
      * Number of vCPUs in the VM. Defaults to 1 when not specified.
@@ -122,31 +129,33 @@
     /** Name of the payload binary file within the APK that will be executed within the VM. */
     @Nullable private final String mPayloadBinaryName;
 
-    /** The size of storage in KiB. 0 indicates that encryptedStorage is not required */
-    private final long mEncryptedStorageKib;
+    /** The size of storage in bytes. 0 indicates that encryptedStorage is not required */
+    private final long mEncryptedStorageBytes;
 
     /** Whether the app can read console and log output. */
     private final boolean mVmOutputCaptured;
 
     private VirtualMachineConfig(
-            @NonNull String apkPath,
+            @Nullable String packageName,
+            @Nullable String apkPath,
             @Nullable String payloadConfigPath,
             @Nullable String payloadBinaryName,
             @DebugLevel int debugLevel,
             boolean protectedVm,
-            int memoryMib,
+            long memoryBytes,
             int numCpus,
-            long encryptedStorageKib,
+            long encryptedStorageBytes,
             boolean vmOutputCaptured) {
         // This is only called from Builder.build(); the builder handles parameter validation.
+        mPackageName = packageName;
         mApkPath = apkPath;
         mPayloadConfigPath = payloadConfigPath;
         mPayloadBinaryName = payloadBinaryName;
         mDebugLevel = debugLevel;
         mProtectedVm = protectedVm;
-        mMemoryMib = memoryMib;
+        mMemoryBytes = memoryBytes;
         mNumCpus = numCpus;
-        mEncryptedStorageKib = encryptedStorageKib;
+        mEncryptedStorageBytes = encryptedStorageBytes;
         mVmOutputCaptured = vmOutputCaptured;
     }
 
@@ -191,8 +200,13 @@
                     "Version " + version + " too high; current is " + VERSION);
         }
 
-        Builder builder = new Builder();
-        builder.setApkPath(b.getString(KEY_APKPATH));
+        String packageName = b.getString(KEY_PACKAGENAME);
+        Builder builder = new Builder(packageName);
+
+        String apkPath = b.getString(KEY_APKPATH);
+        if (apkPath != null) {
+            builder.setApkPath(apkPath);
+        }
 
         String payloadConfigPath = b.getString(KEY_PAYLOADCONFIGPATH);
         if (payloadConfigPath == null) {
@@ -207,14 +221,14 @@
         }
         builder.setDebugLevel(debugLevel);
         builder.setProtectedVm(b.getBoolean(KEY_PROTECTED_VM));
-        int memoryMib = b.getInt(KEY_MEMORY_MIB);
-        if (memoryMib != 0) {
-            builder.setMemoryMib(memoryMib);
+        long memoryBytes = b.getLong(KEY_MEMORY_BYTES);
+        if (memoryBytes != 0) {
+            builder.setMemoryBytes(memoryBytes);
         }
         builder.setNumCpus(b.getInt(KEY_NUM_CPUS));
-        long encryptedStorageKib = b.getLong(KEY_ENCRYPTED_STORAGE_KIB);
-        if (encryptedStorageKib != 0) {
-            builder.setEncryptedStorageKib(encryptedStorageKib);
+        long encryptedStorageBytes = b.getLong(KEY_ENCRYPTED_STORAGE_BYTES);
+        if (encryptedStorageBytes != 0) {
+            builder.setEncryptedStorageBytes(encryptedStorageBytes);
         }
         builder.setVmOutputCaptured(b.getBoolean(KEY_VM_OUTPUT_CAPTURED));
 
@@ -234,17 +248,22 @@
     private void serializeOutputStream(@NonNull OutputStream output) throws IOException {
         PersistableBundle b = new PersistableBundle();
         b.putInt(KEY_VERSION, VERSION);
-        b.putString(KEY_APKPATH, mApkPath);
+        if (mPackageName != null) {
+            b.putString(KEY_PACKAGENAME, mPackageName);
+        }
+        if (mApkPath != null) {
+            b.putString(KEY_APKPATH, mApkPath);
+        }
         b.putString(KEY_PAYLOADCONFIGPATH, mPayloadConfigPath);
         b.putString(KEY_PAYLOADBINARYNAME, mPayloadBinaryName);
         b.putInt(KEY_DEBUGLEVEL, mDebugLevel);
         b.putBoolean(KEY_PROTECTED_VM, mProtectedVm);
         b.putInt(KEY_NUM_CPUS, mNumCpus);
-        if (mMemoryMib > 0) {
-            b.putInt(KEY_MEMORY_MIB, mMemoryMib);
+        if (mMemoryBytes > 0) {
+            b.putLong(KEY_MEMORY_BYTES, mMemoryBytes);
         }
-        if (mEncryptedStorageKib > 0) {
-            b.putLong(KEY_ENCRYPTED_STORAGE_KIB, mEncryptedStorageKib);
+        if (mEncryptedStorageBytes > 0) {
+            b.putLong(KEY_ENCRYPTED_STORAGE_BYTES, mEncryptedStorageBytes);
         }
         b.putBoolean(KEY_VM_OUTPUT_CAPTURED, mVmOutputCaptured);
         b.writeToStream(output);
@@ -252,12 +271,13 @@
 
     /**
      * Returns the absolute path of the APK which should contain the binary payload that will
-     * execute within the VM.
+     * execute within the VM. Returns null if no specific path has been set, so the primary APK will
+     * be used.
      *
      * @hide
      */
     @SystemApi
-    @NonNull
+    @Nullable
     public String getApkPath() {
         return mApkPath;
     }
@@ -316,8 +336,8 @@
      */
     @SystemApi
     @IntRange(from = 0)
-    public int getMemoryMib() {
-        return mMemoryMib;
+    public long getMemoryBytes() {
+        return mMemoryBytes;
     }
 
     /**
@@ -338,26 +358,26 @@
      */
     @SystemApi
     public boolean isEncryptedStorageEnabled() {
-        return mEncryptedStorageKib > 0;
+        return mEncryptedStorageBytes > 0;
     }
 
     /**
-     * Returns the size of encrypted storage (in KiB) available in the VM, or 0 if encrypted storage
-     * is not enabled
+     * Returns the size of encrypted storage (in bytes) available in the VM, or 0 if encrypted
+     * storage is not enabled
      *
      * @hide
      */
     @SystemApi
     @IntRange(from = 0)
-    public long getEncryptedStorageKib() {
-        return mEncryptedStorageKib;
+    public long getEncryptedStorageBytes() {
+        return mEncryptedStorageBytes;
     }
 
     /**
      * Returns whether the app can read the VM console or log output. If not, the VM output is
      * automatically forwarded to the host logcat.
      *
-     * @see #setVmOutputCaptured
+     * @see Builder#setVmOutputCaptured
      * @hide
      */
     @SystemApi
@@ -379,11 +399,12 @@
     public boolean isCompatibleWith(@NonNull VirtualMachineConfig other) {
         return this.mDebugLevel == other.mDebugLevel
                 && this.mProtectedVm == other.mProtectedVm
-                && this.mEncryptedStorageKib == other.mEncryptedStorageKib
+                && this.mEncryptedStorageBytes == other.mEncryptedStorageBytes
                 && this.mVmOutputCaptured == other.mVmOutputCaptured
                 && Objects.equals(this.mPayloadConfigPath, other.mPayloadConfigPath)
                 && Objects.equals(this.mPayloadBinaryName, other.mPayloadBinaryName)
-                && this.mApkPath.equals(other.mApkPath);
+                && Objects.equals(this.mPackageName, other.mPackageName)
+                && Objects.equals(this.mApkPath, other.mApkPath);
     }
 
     /**
@@ -393,9 +414,28 @@
      * app-owned files and that could be abused to run a VM with software that the calling
      * application doesn't own.
      */
-    VirtualMachineAppConfig toVsConfig() throws FileNotFoundException {
+    VirtualMachineAppConfig toVsConfig(@NonNull PackageManager packageManager)
+            throws VirtualMachineException {
         VirtualMachineAppConfig vsConfig = new VirtualMachineAppConfig();
-        vsConfig.apk = ParcelFileDescriptor.open(new File(mApkPath), MODE_READ_ONLY);
+
+        String apkPath = mApkPath;
+        if (apkPath == null) {
+            try {
+                ApplicationInfo appInfo =
+                        packageManager.getApplicationInfo(
+                                mPackageName, PackageManager.ApplicationInfoFlags.of(0));
+                // This really is the path to the APK, not a directory.
+                apkPath = appInfo.sourceDir;
+            } catch (PackageManager.NameNotFoundException e) {
+                throw new VirtualMachineException("Package not found", e);
+            }
+        }
+
+        try {
+            vsConfig.apk = ParcelFileDescriptor.open(new File(apkPath), MODE_READ_ONLY);
+        } catch (FileNotFoundException e) {
+            throw new VirtualMachineException("Failed to open APK", e);
+        }
         if (mPayloadBinaryName != null) {
             VirtualMachinePayloadConfig payloadConfig = new VirtualMachinePayloadConfig();
             payloadConfig.payloadBinaryName = mPayloadBinaryName;
@@ -414,13 +454,23 @@
                 break;
         }
         vsConfig.protectedVm = mProtectedVm;
-        vsConfig.memoryMib = mMemoryMib;
+        vsConfig.memoryMib = bytesToMebiBytes(mMemoryBytes);
         vsConfig.numCpus = mNumCpus;
         // Don't allow apps to set task profiles ... at least for now.
         vsConfig.taskProfiles = EMPTY_STRING_ARRAY;
         return vsConfig;
     }
 
+    private int bytesToMebiBytes(long mMemoryBytes) {
+        long oneMebi = 1024 * 1024;
+        // We can't express requests for more than 2 exabytes, but then they're not going to succeed
+        // anyway.
+        if (mMemoryBytes > (Integer.MAX_VALUE - 1) * oneMebi) {
+            return Integer.MAX_VALUE;
+        }
+        return (int) ((mMemoryBytes + oneMebi - 1) / oneMebi);
+    }
+
     /**
      * A builder used to create a {@link VirtualMachineConfig}.
      *
@@ -428,16 +478,16 @@
      */
     @SystemApi
     public static final class Builder {
-        @Nullable private final Context mContext;
+        @Nullable private final String mPackageName;
         @Nullable private String mApkPath;
         @Nullable private String mPayloadConfigPath;
         @Nullable private String mPayloadBinaryName;
         @DebugLevel private int mDebugLevel = DEBUG_LEVEL_NONE;
         private boolean mProtectedVm;
         private boolean mProtectedVmSet;
-        private int mMemoryMib;
+        private long mMemoryBytes;
         private int mNumCpus = 1;
-        private long mEncryptedStorageKib;
+        private long mEncryptedStorageBytes;
         private boolean mVmOutputCaptured = false;
 
         /**
@@ -447,15 +497,15 @@
          */
         @SystemApi
         public Builder(@NonNull Context context) {
-            mContext = requireNonNull(context, "context must not be null");
+            mPackageName = requireNonNull(context, "context must not be null").getPackageName();
         }
 
         /**
-         * Creates a builder with no associated context; {@link #setApkPath} must be called to
-         * specify which APK contains the payload.
+         * Creates a builder for a specific package. If packageName is null, {@link #setApkPath}
+         * must be called to specify the APK containing the payload.
          */
-        private Builder() {
-            mContext = null;
+        private Builder(@Nullable String packageName) {
+            mPackageName = packageName;
         }
 
         /**
@@ -466,14 +516,16 @@
         @SystemApi
         @NonNull
         public VirtualMachineConfig build() {
-            String apkPath;
-            if (mApkPath == null) {
-                if (mContext == null) {
-                    throw new IllegalStateException("apkPath must be specified");
-                }
-                apkPath = mContext.getPackageCodePath();
-            } else {
+            String apkPath = null;
+            String packageName = null;
+
+            if (mApkPath != null) {
                 apkPath = mApkPath;
+            } else if (mPackageName != null) {
+                packageName = mPackageName;
+            } else {
+                // This should never happen, unless we're deserializing a bad config
+                throw new IllegalStateException("apkPath or packageName must be specified");
             }
 
             if (mPayloadBinaryName == null) {
@@ -496,14 +548,15 @@
             }
 
             return new VirtualMachineConfig(
+                    packageName,
                     apkPath,
                     mPayloadConfigPath,
                     mPayloadBinaryName,
                     mDebugLevel,
                     mProtectedVm,
-                    mMemoryMib,
+                    mMemoryBytes,
                     mNumCpus,
-                    mEncryptedStorageKib,
+                    mEncryptedStorageBytes,
                     mVmOutputCaptured);
         }
 
@@ -618,18 +671,18 @@
         }
 
         /**
-         * Sets the amount of RAM to give the VM, in mebibytes. If not explicitly set then a default
+         * Sets the amount of RAM to give the VM, in bytes. If not explicitly set then a default
          * size will be used.
          *
          * @hide
          */
         @SystemApi
         @NonNull
-        public Builder setMemoryMib(@IntRange(from = 1) int memoryMib) {
-            if (memoryMib <= 0) {
+        public Builder setMemoryBytes(@IntRange(from = 1) long memoryBytes) {
+            if (memoryBytes <= 0) {
                 throw new IllegalArgumentException("Memory size must be positive");
             }
-            mMemoryMib = memoryMib;
+            mMemoryBytes = memoryBytes;
             return this;
         }
 
@@ -657,8 +710,8 @@
         }
 
         /**
-         * Sets the size (in KiB) of encrypted storage available to the VM. If not set, no encrypted
-         * storage is provided.
+         * Sets the size (in bytes) of encrypted storage available to the VM. If not set, no
+         * encrypted storage is provided.
          *
          * <p>The storage is encrypted with a key deterministically derived from the VM identity
          *
@@ -674,11 +727,11 @@
          */
         @SystemApi
         @NonNull
-        public Builder setEncryptedStorageKib(@IntRange(from = 1) long encryptedStorageKib) {
-            if (encryptedStorageKib <= 0) {
+        public Builder setEncryptedStorageBytes(@IntRange(from = 1) long encryptedStorageBytes) {
+            if (encryptedStorageBytes <= 0) {
                 throw new IllegalArgumentException("Encrypted Storage size must be positive");
             }
-            mEncryptedStorageKib = encryptedStorageKib;
+            mEncryptedStorageBytes = encryptedStorageBytes;
             return this;
         }
 
diff --git a/libs/apexutil/src/lib.rs b/libs/apexutil/src/lib.rs
index 698d93a..8a934e2 100644
--- a/libs/apexutil/src/lib.rs
+++ b/libs/apexutil/src/lib.rs
@@ -144,7 +144,7 @@
         let res = verify("tests/data/test.apex").unwrap();
         // The expected hex is generated when we ran the method the first time.
         assert_eq!(
-            hex::encode(&res.root_digest),
+            hex::encode(res.root_digest),
             "fe11ab17da0a3a738b54bdc3a13f6139cbdf91ec32f001f8d4bbbf8938e04e39"
         );
     }
@@ -153,7 +153,7 @@
     fn payload_vbmeta_has_valid_image_hash() {
         let result = get_payload_vbmeta_image_hash("tests/data/test.apex").unwrap();
         assert_eq!(
-            hex::encode(&result),
+            hex::encode(result),
             "296e32a76544de9da01713e471403ab4667705ad527bb4f1fac0cf61e7ce122d"
         );
     }
diff --git a/libs/apkverify/src/algorithms.rs b/libs/apkverify/src/algorithms.rs
index 6315606..442b47c 100644
--- a/libs/apkverify/src/algorithms.rs
+++ b/libs/apkverify/src/algorithms.rs
@@ -34,11 +34,14 @@
 /// [SignatureAlgorithm.java]: (tools/apksig/src/main/java/com/android/apksig/internal/apk/SignatureAlgorithm.java)
 ///
 /// Some of the algorithms are not implemented. See b/197052981.
-#[derive(Serialize, Deserialize, Clone, Copy, Debug, Eq, PartialEq, FromPrimitive, ToPrimitive)]
+#[derive(
+    Serialize, Deserialize, Clone, Copy, Debug, Default, Eq, PartialEq, FromPrimitive, ToPrimitive,
+)]
 #[repr(u32)]
 pub enum SignatureAlgorithmID {
     /// RSASSA-PSS with SHA2-256 digest, SHA2-256 MGF1, 32 bytes of salt, trailer: 0xbc, content
     /// digested using SHA2-256 in 1 MB chunks.
+    #[default]
     RsaPssWithSha256 = 0x0101,
 
     /// RSASSA-PSS with SHA2-512 digest, SHA2-512 MGF1, 64 bytes of salt, trailer: 0xbc, content
@@ -77,12 +80,6 @@
     VerityDsaWithSha256 = 0x0425,
 }
 
-impl Default for SignatureAlgorithmID {
-    fn default() -> Self {
-        SignatureAlgorithmID::RsaPssWithSha256
-    }
-}
-
 impl ReadFromBytes for Option<SignatureAlgorithmID> {
     fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
         Ok(SignatureAlgorithmID::from_u32(buf.get_u32_le()))
diff --git a/libs/apkverify/src/v3.rs b/libs/apkverify/src/v3.rs
index fcd966b..e1b728d 100644
--- a/libs/apkverify/src/v3.rs
+++ b/libs/apkverify/src/v3.rs
@@ -110,7 +110,7 @@
 ) -> Result<(Signer, ApkSections<R>)> {
     let mut sections = ApkSections::new(apk)?;
     let mut block = sections.find_signature(APK_SIGNATURE_SCHEME_V3_BLOCK_ID).context(
-        "Fallback to v2 when v3 block not found is not yet implemented. See b/197052981.",
+        "Fallback to v2 when v3 block not found is not yet implemented.", // b/197052981
     )?;
     let mut supported = block
         .read::<Signers>()?
@@ -135,7 +135,7 @@
             .iter()
             .filter(|sig| sig.signature_algorithm_id.map_or(false, |algo| algo.is_supported()))
             .max_by_key(|sig| sig.signature_algorithm_id.unwrap().content_digest_algorithm())
-            .context("No supported signatures found")?)
+            .context("No supported APK signatures found; DSA is not supported")?)
     }
 
     pub(crate) fn find_digest_by_algorithm(
diff --git a/libs/apkverify/src/ziputil.rs b/libs/apkverify/src/ziputil.rs
index eb2826a..cc8bc58 100644
--- a/libs/apkverify/src/ziputil.rs
+++ b/libs/apkverify/src/ziputil.rs
@@ -46,7 +46,7 @@
     reader = archive.into_inner();
     // the current position should point EOCD offset
     let eocd_offset = reader.seek(SeekFrom::Current(0))? as u32;
-    let mut eocd = vec![0u8; eocd_size as usize];
+    let mut eocd = vec![0u8; eocd_size];
     reader.read_exact(&mut eocd)?;
     ensure!(
         (&eocd[0..]).get_u32_le() == EOCD_SIGNATURE,
diff --git a/libs/apkverify/tests/apkverify_test.rs b/libs/apkverify/tests/apkverify_test.rs
index 047538c..baf7c42 100644
--- a/libs/apkverify/tests/apkverify_test.rs
+++ b/libs/apkverify/tests/apkverify_test.rs
@@ -44,7 +44,7 @@
     for key_name in KEY_NAMES_DSA.iter() {
         let res = verify(format!("tests/data/v3-only-with-dsa-sha256-{}.apk", key_name));
         assert!(res.is_err(), "DSA algorithm is not supported for verification. See b/197052981.");
-        assert_contains(&res.unwrap_err().to_string(), "No supported signatures found");
+        assert_contains(&res.unwrap_err().to_string(), "No supported APK signatures found");
     }
 }
 
@@ -151,7 +151,7 @@
 fn test_verify_v3_no_supported_sig_algs() {
     let res = verify("tests/data/v3-only-no-supported-sig-algs.apk");
     assert!(res.is_err());
-    assert_contains(&res.unwrap_err().to_string(), "No supported signatures found");
+    assert_contains(&res.unwrap_err().to_string(), "No supported APK signatures found");
 }
 
 #[test]
diff --git a/libs/avb/Android.bp b/libs/avb/Android.bp
index 436f672..1d257bc 100644
--- a/libs/avb/Android.bp
+++ b/libs/avb/Android.bp
@@ -14,6 +14,7 @@
         "--size_t-is-usize",
         "--default-enum-style rust",
         "--allowlist-function=.*",
+        "--allowlist-var=AVB.*",
         "--use-core",
         "--raw-line=#![no_std]",
         "--ctypes-prefix=core::ffi",
diff --git a/libs/devicemapper/src/lib.rs b/libs/devicemapper/src/lib.rs
index 9069eb2..4cf4e99 100644
--- a/libs/devicemapper/src/lib.rs
+++ b/libs/devicemapper/src/lib.rs
@@ -226,7 +226,7 @@
 
     let context = Context::new(0);
     let now = SystemTime::now().duration_since(UNIX_EPOCH)?;
-    let ts = Timestamp::from_unix(&context, now.as_secs(), now.subsec_nanos());
+    let ts = Timestamp::from_unix(context, now.as_secs(), now.subsec_nanos());
     let uuid = Uuid::new_v1(ts, node_id)?;
     Ok(String::from(uuid.to_hyphenated().encode_lower(&mut Uuid::encode_buffer())))
 }
diff --git a/libs/devicemapper/src/loopdevice.rs b/libs/devicemapper/src/loopdevice.rs
index 5533e17..16b5b65 100644
--- a/libs/devicemapper/src/loopdevice.rs
+++ b/libs/devicemapper/src/loopdevice.rs
@@ -172,13 +172,13 @@
 
     fn is_direct_io(dev: &Path) -> bool {
         let dio = Path::new("/sys/block").join(dev.file_name().unwrap()).join("loop/dio");
-        "1" == fs::read_to_string(&dio).unwrap().trim()
+        "1" == fs::read_to_string(dio).unwrap().trim()
     }
 
     // kernel exposes /sys/block/loop*/ro which gives the read-only value
     fn is_direct_io_writable(dev: &Path) -> bool {
         let ro = Path::new("/sys/block").join(dev.file_name().unwrap()).join("ro");
-        "0" == fs::read_to_string(&ro).unwrap().trim()
+        "0" == fs::read_to_string(ro).unwrap().trim()
     }
 
     #[test]
diff --git a/libs/fdtpci/src/lib.rs b/libs/fdtpci/src/lib.rs
index 1ddda9f..e32e16d 100644
--- a/libs/fdtpci/src/lib.rs
+++ b/libs/fdtpci/src/lib.rs
@@ -91,7 +91,7 @@
 }
 
 /// Information about the PCI bus parsed from the device tree.
-#[derive(Debug)]
+#[derive(Clone, Debug)]
 pub struct PciInfo {
     /// The MMIO range used by the memory-mapped PCI CAM.
     pub cam_range: Range<usize>,
diff --git a/libs/libfdt/src/lib.rs b/libs/libfdt/src/lib.rs
index 7c72fab..8fd1879 100644
--- a/libs/libfdt/src/lib.rs
+++ b/libs/libfdt/src/lib.rs
@@ -16,7 +16,6 @@
 //! to a bare-metal environment.
 
 #![no_std]
-#![feature(let_else)] // Stabilized in 1.65.0
 
 mod iterators;
 
@@ -508,6 +507,19 @@
         fdt_err_expect_zero(ret)
     }
 
+    /// Applies a DT overlay on the base DT.
+    ///
+    /// # Safety
+    ///
+    /// On failure, the library corrupts the DT and overlay so both must be discarded.
+    pub unsafe fn apply_overlay<'a>(&'a mut self, overlay: &'a mut Fdt) -> Result<&'a mut Self> {
+        fdt_err_expect_zero(libfdt_bindgen::fdt_overlay_apply(
+            self.as_mut_ptr(),
+            overlay.as_mut_ptr(),
+        ))?;
+        Ok(self)
+    }
+
     /// Return an iterator of memory banks specified the "/memory" node.
     ///
     /// NOTE: This does not support individual "/memory@XXXX" banks.
diff --git a/microdroid/Android.bp b/microdroid/Android.bp
index 529686d..9264692 100644
--- a/microdroid/Android.bp
+++ b/microdroid/Android.bp
@@ -240,37 +240,6 @@
     ],
 }
 
-bootimg {
-    name: "microdroid_boot",
-    // We don't have kernel for arm and x86. But Soong demands one when it builds for
-    // arm or x86 target. Satisfy that by providing an empty file as the kernel.
-    kernel_prebuilt: "empty_kernel",
-    arch: {
-        arm64: {
-            kernel_prebuilt: ":microdroid_kernel_prebuilts-6.1-arm64",
-        },
-        x86_64: {
-            kernel_prebuilt: ":microdroid_kernel_prebuilts-6.1-x86_64",
-        },
-    },
-
-    dtb_prebuilt: "dummy_dtb.img",
-    header_version: "4",
-    partition_name: "boot",
-    use_avb: true,
-    avb_private_key: ":microdroid_sign_key",
-}
-
-bootimg {
-    name: "microdroid_init_boot",
-    ramdisk_module: "microdroid_ramdisk",
-    kernel_prebuilt: "empty_kernel",
-    header_version: "4",
-    partition_name: "init_boot",
-    use_avb: true,
-    avb_private_key: ":microdroid_sign_key",
-}
-
 android_filesystem {
     name: "microdroid_ramdisk",
     deps: [
@@ -289,25 +258,6 @@
     type: "compressed_cpio",
 }
 
-bootimg {
-    name: "microdroid_vendor_boot",
-    ramdisk_module: "microdroid_vendor_ramdisk",
-    dtb_prebuilt: "dummy_dtb.img",
-    header_version: "4",
-    vendor_boot: true,
-    arch: {
-        arm64: {
-            bootconfig: ":microdroid_bootconfig_arm64_gen",
-        },
-        x86_64: {
-            bootconfig: ":microdroid_bootconfig_x86_64_gen",
-        },
-    },
-    partition_name: "vendor_boot",
-    use_avb: true,
-    avb_private_key: ":microdroid_sign_key",
-}
-
 android_filesystem {
     name: "microdroid_vendor_ramdisk",
     deps: [
@@ -347,43 +297,6 @@
     cmd: "cat $(in) > $(out)",
 }
 
-vbmeta {
-    name: "microdroid_vbmeta_bootconfig",
-    partition_name: "vbmeta",
-    private_key: ":microdroid_sign_key",
-    chained_partitions: [
-        {
-            name: "bootconfig",
-            private_key: ":microdroid_sign_key",
-        },
-        {
-            name: "uboot_env",
-            private_key: ":microdroid_sign_key",
-        },
-    ],
-}
-
-// python -c "import hashlib; print(hashlib.sha256(b'bootconfig').hexdigest())"
-bootconfig_salt = "e158851fbebb402e1f18ea9372ea2f76b4dea23eceb5c4b92e5b27ade8537f5b"
-
-avb_add_hash_footer {
-    name: "microdroid_bootconfig_normal",
-    src: "bootconfig.normal",
-    filename: "microdroid_bootconfig.normal",
-    partition_name: "bootconfig",
-    private_key: ":microdroid_sign_key",
-    salt: bootconfig_salt,
-}
-
-avb_add_hash_footer {
-    name: "microdroid_bootconfig_debuggable",
-    src: "bootconfig.debuggable",
-    filename: "microdroid_bootconfig.debuggable",
-    partition_name: "bootconfig",
-    private_key: ":microdroid_sign_key",
-    salt: bootconfig_salt,
-}
-
 prebuilt_etc {
     name: "microdroid_fstab",
     src: "fstab.microdroid",
@@ -391,89 +304,9 @@
     installable: false,
 }
 
-prebuilt_etc {
-    name: "microdroid_bootloader",
-    src: ":microdroid_bootloader_signed",
-    arch: {
-        x86_64: {
-            // For unknown reason, the signed bootloader doesn't work on x86_64. Until the problem
-            // is fixed, let's use the unsigned bootloader for the architecture.
-            // TODO(b/185115783): remove this
-            src: ":microdroid_bootloader_pubkey_replaced",
-        },
-    },
-    relative_install_path: "fs",
-    filename: "microdroid_bootloader",
-}
-
 // python -c "import hashlib; print(hashlib.sha256(b'bootloader').hexdigest())"
 bootloader_salt = "3b4a12881d11f33cff968a24d7c53723a8232cde9a8d91e29fdbd6a95ae6adf0"
 
-avb_add_hash_footer {
-    name: "microdroid_bootloader_signed",
-    src: ":microdroid_bootloader_pubkey_replaced",
-    filename: "microdroid_bootloader",
-    partition_name: "bootloader",
-    private_key: ":microdroid_sign_key",
-    salt: bootloader_salt,
-}
-
-// Replace avbpubkey of prebuilt bootloader with the avbpubkey of the signing key
-genrule {
-    name: "microdroid_bootloader_pubkey_replaced",
-    tools: ["replace_bytes"],
-    srcs: [
-        ":microdroid_crosvm_bootloader", // input (bootloader)
-        ":microdroid_crosvm_bootloader.avbpubkey", // old bytes (old pubkey)
-        ":microdroid_bootloader_avbpubkey_gen", // new bytes (new pubkey)
-    ],
-    out: ["bootloader-pubkey-replaced"],
-    // 1. Copy the input to the output (replace_bytes modifies the file in-place)
-    // 2. Replace embedded pubkey with new one.
-    cmd: "cp $(location :microdroid_crosvm_bootloader) $(out) && " +
-        "$(location replace_bytes) $(out) " +
-        "$(location :microdroid_crosvm_bootloader.avbpubkey) " +
-        "$(location :microdroid_bootloader_avbpubkey_gen)",
-}
-
-// Apex keeps a copy of avbpubkey embedded in bootloader so that embedded avbpubkey can be replaced
-// while re-signing bootloader.
-prebuilt_etc {
-    name: "microdroid_bootloader.avbpubkey",
-    src: ":microdroid_bootloader_avbpubkey_gen",
-}
-
-// Generate avbpukey from the signing key
-genrule {
-    name: "microdroid_bootloader_avbpubkey_gen",
-    tools: ["avbtool"],
-    srcs: [":microdroid_sign_key"],
-    out: ["bootloader.pubkey"],
-    cmd: "$(location avbtool) extract_public_key " +
-        "--key $(location :microdroid_sign_key) " +
-        "--output $(out)",
-}
-
-// python -c "import hashlib; print(hashlib.sha256(b'uboot_env').hexdigest())"
-uboot_env_salt = "cbf2d76827ece5ca8d176a40c94ac6355edcf6511b4b887364a8c0e05850df10"
-
-avb_add_hash_footer {
-    name: "microdroid_uboot_env",
-    src: ":microdroid_uboot_env_gen",
-    filename: "uboot_env.img",
-    partition_name: "uboot_env",
-    private_key: ":microdroid_sign_key",
-    salt: uboot_env_salt,
-}
-
-genrule {
-    name: "microdroid_uboot_env_gen",
-    tools: ["mkenvimage_slim"],
-    srcs: ["uboot-env.txt"],
-    out: ["output.img"],
-    cmd: "$(location mkenvimage_slim) -output_path $(out) -input_path $(location uboot-env.txt)",
-}
-
 // Note that keys can be different for filesystem images even though we're using the same key
 // for microdroid. However, the key signing VBmeta should match with the pubkey embedded in
 // bootloader.
diff --git a/microdroid/init.rc b/microdroid/init.rc
index bc42791..ce0cab4 100644
--- a/microdroid/init.rc
+++ b/microdroid/init.rc
@@ -149,6 +149,10 @@
     # Mark boot completed. This will notify microdroid_manager to run payload.
     setprop dev.bootcomplete 1
 
+on property:tombstone_transmit.start=1
+    mkdir /data/tombstones 0771 system system
+    start tombstone_transmit
+
 service tombstone_transmit /system/bin/tombstone_transmit.microdroid -cid 2 -port 2000 -remove_tombstones_after_transmitting
     user system
     group system
@@ -175,4 +179,3 @@
     group shell log readproc
     seclabel u:r:shell:s0
     setenv HOSTNAME console
-
diff --git a/microdroid/initrd/Android.bp b/microdroid/initrd/Android.bp
index 7a95ce6..ff6314b 100644
--- a/microdroid/initrd/Android.bp
+++ b/microdroid/initrd/Android.bp
@@ -68,7 +68,7 @@
         ":microdroid_bootconfig_debuggable_src",
     ] + bootconfigs_arm64,
     out: ["microdroid_initrd_debuggable_arm64"],
-    cmd: "$(location initrd_bootconfig) --output $(out) $(in)",
+    cmd: "$(location initrd_bootconfig) attach --output $(out) $(in)",
 }
 
 genrule {
@@ -79,7 +79,7 @@
         ":microdroid_bootconfig_debuggable_src",
     ] + bootconfigs_x86_64,
     out: ["microdroid_initrd_debuggable_x86_64"],
-    cmd: "$(location initrd_bootconfig) --output $(out) $(in)",
+    cmd: "$(location initrd_bootconfig) attach --output $(out) $(in)",
 }
 
 genrule {
@@ -90,7 +90,7 @@
         ":microdroid_bootconfig_normal_src",
     ] + bootconfigs_arm64,
     out: ["microdroid_initrd_normal_arm64"],
-    cmd: "$(location initrd_bootconfig) --output $(out) $(in)",
+    cmd: "$(location initrd_bootconfig) attach --output $(out) $(in)",
 }
 
 genrule {
@@ -101,7 +101,7 @@
         ":microdroid_bootconfig_normal_src",
     ] + bootconfigs_x86_64,
     out: ["microdroid_initrd_normal_x86_64"],
-    cmd: "$(location initrd_bootconfig) --output $(out) $(in)",
+    cmd: "$(location initrd_bootconfig) attach --output $(out) $(in)",
 }
 
 prebuilt_etc {
diff --git a/microdroid/initrd/src/main.rs b/microdroid/initrd/src/main.rs
index 74e4ba6..c5515af 100644
--- a/microdroid/initrd/src/main.rs
+++ b/microdroid/initrd/src/main.rs
@@ -12,36 +12,95 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-//! Append bootconfig to initrd image
-use anyhow::Result;
+//! Attach/Detach bootconfigs to initrd image
+use anyhow::{bail, Result};
 use clap::Parser;
+use std::cmp::min;
 use std::fs::File;
-use std::io::{Read, Write};
+use std::io::{Read, Seek, SeekFrom, Write};
+use std::mem::size_of;
 use std::path::PathBuf;
 
 const FOOTER_ALIGNMENT: usize = 4;
 const ZEROS: [u8; 4] = [0u8; 4_usize];
+const BOOTCONFIG_MAGIC: &str = "#BOOTCONFIG\n";
+// Footer includes [size(le32)][checksum(le32)][#BOOTCONFIG\n] at the end of bootconfigs.
+const INITRD_FOOTER_LEN: usize = 2 * std::mem::size_of::<u32>() + BOOTCONFIG_MAGIC.len();
 
 #[derive(Parser, Debug)]
-struct Args {
-    /// Initrd (without bootconfig)
-    initrd: PathBuf,
-    /// Bootconfig
-    bootconfigs: Vec<PathBuf>,
-    /// Output
-    #[clap(long = "output")]
-    output: PathBuf,
+enum Opt {
+    /// Append bootconfig(s) to initrd image
+    Attach {
+        /// Initrd (without bootconfigs) <- Input
+        initrd: PathBuf,
+        /// Bootconfigs <- Input
+        bootconfigs: Vec<PathBuf>,
+        /// Initrd (with bootconfigs) <- Output
+        #[clap(long = "output")]
+        output: PathBuf,
+    },
+
+    /// Detach the initrd & bootconfigs - this is required for cases when we update
+    /// bootconfigs in sign_virt_apex
+    Detach {
+        /// Initrd (with bootconfigs) <- Input
+        initrd_with_bootconfigs: PathBuf,
+        /// Initrd (without bootconfigs) <- Output
+        initrd: PathBuf,
+        /// Bootconfigs <- Output
+        bootconfigs: PathBuf,
+    },
 }
 
 fn get_checksum(file_path: &PathBuf) -> Result<u32> {
     File::open(file_path)?.bytes().map(|x| Ok(x? as u32)).sum()
 }
 
+// Copy n bytes of file_in to file_out. Note: copying starts from the current cursors of files.
+// On successful return, the files' cursors would have moved forward by k bytes.
+fn copyfile2file(file_in: &mut File, file_out: &mut File, n: usize) -> Result<()> {
+    let mut buf = vec![0; 1024];
+    let mut copied: usize = 0;
+    while copied < n {
+        let k = min(n - copied, buf.len());
+        file_in.read_exact(&mut buf[..k])?;
+        file_out.write_all(&buf[..k])?;
+        copied += k;
+    }
+    Ok(())
+}
+
+// Note: attaching & then detaching bootconfigs can lead to extra padding in bootconfigs
+fn detach_bootconfig(initrd_bc: PathBuf, initrd: PathBuf, bootconfig: PathBuf) -> Result<()> {
+    let mut initrd_bc = File::open(initrd_bc)?;
+    let mut bootconfig = File::create(bootconfig)?;
+    let mut initrd = File::create(initrd)?;
+    let initrd_bc_size: usize = initrd_bc.metadata()?.len().try_into()?;
+
+    initrd_bc.seek(SeekFrom::End(-(BOOTCONFIG_MAGIC.len() as i64)))?;
+    let mut magic_buf = [0; BOOTCONFIG_MAGIC.len()];
+    initrd_bc.read_exact(&mut magic_buf)?;
+    if magic_buf != BOOTCONFIG_MAGIC.as_bytes() {
+        bail!("BOOTCONFIG_MAGIC not found in initrd. Bootconfigs might not be attached correctly");
+    }
+    let mut size_buf = [0; size_of::<u32>()];
+    initrd_bc.seek(SeekFrom::End(-(INITRD_FOOTER_LEN as i64)))?;
+    initrd_bc.read_exact(&mut size_buf)?;
+    let bc_size: usize = u32::from_le_bytes(size_buf) as usize;
+
+    let initrd_size: usize = initrd_bc_size - bc_size - INITRD_FOOTER_LEN;
+
+    initrd_bc.seek(SeekFrom::Start(0))?;
+    copyfile2file(&mut initrd_bc, &mut initrd, initrd_size)?;
+    copyfile2file(&mut initrd_bc, &mut bootconfig, bc_size)?;
+    Ok(())
+}
+
 // Bootconfig is attached to the initrd in the following way:
 // [initrd][bootconfig][padding][size(le32)][checksum(le32)][#BOOTCONFIG\n]
 fn attach_bootconfig(initrd: PathBuf, bootconfigs: Vec<PathBuf>, output: PathBuf) -> Result<()> {
-    let mut output_file = File::create(&output)?;
-    let mut initrd_file = File::open(&initrd)?;
+    let mut output_file = File::create(output)?;
+    let mut initrd_file = File::open(initrd)?;
     let initrd_size: usize = initrd_file.metadata()?.len().try_into()?;
     let mut bootconfig_size: usize = 0;
     let mut checksum: u32 = 0;
@@ -59,14 +118,21 @@
     output_file.write_all(&ZEROS[..padding_size])?;
     output_file.write_all(&((padding_size + bootconfig_size) as u32).to_le_bytes())?;
     output_file.write_all(&checksum.to_le_bytes())?;
-    output_file.write_all(b"#BOOTCONFIG\n")?;
+    output_file.write_all(BOOTCONFIG_MAGIC.as_bytes())?;
     output_file.flush()?;
     Ok(())
 }
 
 fn try_main() -> Result<()> {
-    let args = Args::parse();
-    attach_bootconfig(args.initrd, args.bootconfigs, args.output)?;
+    let args = Opt::parse();
+    match args {
+        Opt::Attach { initrd, bootconfigs, output } => {
+            attach_bootconfig(initrd, bootconfigs, output)?
+        }
+        Opt::Detach { initrd_with_bootconfigs, initrd, bootconfigs } => {
+            detach_bootconfig(initrd_with_bootconfigs, initrd, bootconfigs)?
+        }
+    };
     Ok(())
 }
 
@@ -82,6 +148,6 @@
     #[test]
     fn verify_args() {
         // Check that the command parsing has been configured in a valid way.
-        Args::command().debug_assert();
+        Opt::command().debug_assert();
     }
 }
diff --git a/microdroid_manager/src/ioutil.rs b/microdroid_manager/src/ioutil.rs
index 8ac3712..d36e349 100644
--- a/microdroid_manager/src/ioutil.rs
+++ b/microdroid_manager/src/ioutil.rs
@@ -76,7 +76,7 @@
         });
 
         let test_file = test_dir.path().join("test.txt");
-        let mut file = wait_for_file(&test_file, Duration::from_secs(5))?;
+        let mut file = wait_for_file(test_file, Duration::from_secs(5))?;
         let mut buffer = String::new();
         file.read_to_string(&mut buffer)?;
         assert_eq!("test", buffer);
@@ -87,7 +87,7 @@
     fn test_wait_for_file_fails() {
         let test_dir = tempfile::TempDir::new().unwrap();
         let test_file = test_dir.path().join("test.txt");
-        let file = wait_for_file(&test_file, Duration::from_secs(1));
+        let file = wait_for_file(test_file, Duration::from_secs(1));
         assert!(file.is_err());
         assert_eq!(
             io::ErrorKind::NotFound,
diff --git a/microdroid_manager/src/main.rs b/microdroid_manager/src/main.rs
index f48611b..f1c41b9 100644
--- a/microdroid_manager/src/main.rs
+++ b/microdroid_manager/src/main.rs
@@ -77,6 +77,7 @@
     "/sys/firmware/devicetree/base/virtualization/guest/debug-microdroid,no-verified-boot";
 
 const APEX_CONFIG_DONE_PROP: &str = "apex_config.done";
+const TOMBSTONE_TRANSMIT_DONE_PROP: &str = "tombstone_transmit.init_done";
 const DEBUGGABLE_PROP: &str = "ro.boot.microdroid.debuggable";
 
 // SYNC WITH virtualizationservice/src/crosvm.rs
@@ -425,7 +426,8 @@
 
     // Start tombstone_transmit if enabled
     if config.export_tombstones {
-        control_service("start", "tombstone_transmit")?;
+        system_properties::write("tombstone_transmit.start", "1")
+            .context("set tombstone_transmit.start")?;
     } else {
         control_service("stop", "tombstoned")?;
     }
@@ -446,6 +448,12 @@
     wait_for_property_true("dev.bootcomplete").context("failed waiting for dev.bootcomplete")?;
     system_properties::write("microdroid_manager.init_done", "1")
         .context("set microdroid_manager.init_done")?;
+
+    // Wait for tombstone_transmit to init
+    if config.export_tombstones {
+        wait_for_tombstone_transmit_done()?;
+    }
+
     info!("boot completed, time to run payload");
     exec_task(task, service).context("Failed to run payload")
 }
@@ -723,6 +731,11 @@
     wait_for_property_true(APEX_CONFIG_DONE_PROP).context("Failed waiting for apex config done")
 }
 
+fn wait_for_tombstone_transmit_done() -> Result<()> {
+    wait_for_property_true(TOMBSTONE_TRANSMIT_DONE_PROP)
+        .context("Failed waiting for tombstone transmit done")
+}
+
 fn wait_for_property_true(property_name: &str) -> Result<()> {
     let mut prop = PropertyWatcher::new(property_name)?;
     loop {
diff --git a/microdroid_manager/src/swap.rs b/microdroid_manager/src/swap.rs
index d7916db..2f4d176 100644
--- a/microdroid_manager/src/swap.rs
+++ b/microdroid_manager/src/swap.rs
@@ -66,7 +66,7 @@
     f.write_all(Uuid::new_v4().as_bytes())?;
 
     // Write the magic signature string.
-    f.seek(SeekFrom::Start((pagesize - 10) as u64))?;
+    f.seek(SeekFrom::Start(pagesize - 10))?;
     f.write_all("SWAPSPACE2".as_bytes())?;
 
     Ok(())
diff --git a/pvmfw/Android.bp b/pvmfw/Android.bp
index f5e214e..21f84a5 100644
--- a/pvmfw/Android.bp
+++ b/pvmfw/Android.bp
@@ -18,6 +18,7 @@
         "libfdtpci",
         "liblibfdt",
         "liblog_rust_nostd",
+        "libonce_cell_nostd",
         "libpvmfw_avb_nostd",
         "libpvmfw_embedded_key",
         "libtinyvec_nostd",
diff --git a/pvmfw/README.md b/pvmfw/README.md
index e5ba88b..1e4b605 100644
--- a/pvmfw/README.md
+++ b/pvmfw/README.md
@@ -1,12 +1,107 @@
 # Protected Virtual Machine Firmware
 
-## Configuration Data Format
+In the context of the [Android Virtualization Framework][AVF], a hypervisor
+(_e.g._ [pKVM]) enforces full memory isolation between its virtual machines
+(VMs) and the host.  As a result, the host is only allowed to access memory that
+has been explicitly shared back by a VM. Such _protected VMs_ (“pVMs”) are
+therefore able to manipulate secrets without being at risk of an attacker
+stealing them by compromising the Android host.
 
-pvmfw will expect a [header] to have been appended to its loaded binary image
-at the next 4KiB boundary. It describes the configuration data entries that
-pvmfw will use and, being loaded by the pvmfw loader, is necessarily trusted.
+As pVMs are started dynamically by a _virtual machine manager_ (“VMM”) running
+as a host process and as pVMs must not trust the host (see [_Why
+AVF?_][why-avf]), the virtual machine it configures can't be trusted either.
+Furthermore, even though the isolation mentioned above allows pVMs to protect
+their secrets from the host, it does not help with provisioning them during
+boot. In particular, the threat model would prohibit the host from ever having
+access to those secrets, preventing the VMM from passing them to the pVM.
 
-The layout of the configuration data is as follows:
+To address these concerns the hypervisor securely loads the pVM firmware
+(“pvmfw”) in the pVM from a protected memory region (this prevents the host or
+any pVM from tampering with it), setting it as the entry point of the virtual
+machine. As a result, pvmfw becomes the very first code that gets executed in
+the pVM, allowing it to validate the environment and abort the boot sequence if
+necessary. This process takes place whenever the VMM places a VM in protected
+mode and can’t be prevented by the host.
+
+Given the threat model, pvmfw is not allowed to trust the devices or device
+layout provided by the virtual platform it is running on as those are configured
+by the VMM. Instead, it performs all the necessary checks to ensure that the pVM
+was set up as expected. For functional purposes, the interface with the
+hypervisor, although trusted, is also validated.
+
+Once it has been determined that the platform can be trusted, pvmfw derives
+unique secrets for the guest through the [_Boot Certificate Chain_][BCC]
+("BCC", see [Open Profile for DICE][open-dice]) that can be used to prove the
+identity of the pVM to local and remote actors. If any operation or check fails,
+or in case of a missing prerequisite, pvmfw will abort the boot process of the
+pVM, effectively preventing non-compliant pVMs and/or guests from running.
+Otherwise, it hands over the pVM to the guest kernel by jumping to its first
+instruction, similarly to a bootloader.
+
+pvmfw currently only supports AArch64.
+
+[AVF]: https://source.android.com/docs/core/virtualization
+[why-avf]: https://source.android.com/docs/core/virtualization/whyavf
+[BCC]: https://pigweed.googlesource.com/open-dice/+/master/src/android/README.md
+[pKVM]: https://source.android.com/docs/core/virtualization/architecture#hypervisor
+[open-dice]: https://pigweed.googlesource.com/open-dice/+/refs/heads/main/docs/specification.md
+
+## Integration
+
+### pvmfw Loading
+
+When running pKVM, the physical memory from which the hypervisor loads pvmfw
+into guest address space is not initially populated by the hypervisor itself.
+Instead, it receives a pre-loaded memory region from a trusted pvmfw loader and
+only then becomes responsible for protecting it. As a result, the hypervisor is
+kept generic (beyond AVF) and small as it is not expected (nor necessary) for it
+to know how to interpret or obtain the content of that region.
+
+#### Android Bootloader (ABL) Support
+
+Starting in Android T, the `PRODUCT_BUILD_PVMFW_IMAGE` build variable controls
+the generation of `pvmfw.img`, a new [ABL partition][ABL-part] containing the
+pvmfw binary and following the internal format of the [`boot`][boot-img]
+partition, intended to be verified and loaded by ABL on AVF-compatible devices.
+
+To support pKVM, ABL is expected to describe the region using a reserved memory
+device tree node where both address and size have been properly aligned to the
+page size used by the hypervisor. For example, the following node describes a
+region of size `0x40000` at address `0x80000000`:
+```
+reserved-memory {
+    ...
+    pkvm_guest_firmware {
+        compatible = "linux,pkvm-guest-firmware-memory";
+        reg = <0x0 0x80000000 0x40000>;
+        no-map;
+    }
+}
+```
+
+[ABL-part]: https://source.android.com/docs/core/architecture/bootloader/partitions
+[boot-img]: https://source.android.com/docs/core/architecture/bootloader/boot-image-header
+
+### Configuration Data
+
+As part of the process of loading pvmfw, the loader (typically the Android
+Bootloader, "ABL") is expected to pass device-specific pvmfw configuration data
+by appending it to the pvmfw binary and including it in the region passed to the
+hypervisor. As a result, the hypervisor will give the same protection to this
+data as it does to pvmfw and will transparently load it in guest memory, making
+it available to pvmfw at runtime. This enables pvmfw to be kept device-agnostic,
+simplifying its adoption and distribution as a centralized signed binary, while
+also being able to support device-specific details.
+
+The configuration data will be read by pvmfw at the next 4KiB boundary from the
+end of its loaded binary. Even if the pvmfw is position-independent, it will be
+expected for it to also have been loaded at a 4-KiB boundary. As a result, the
+location of the configuration data is implicitly passed to pvmfw and known to it
+at build time.
+
+#### Configuration Data Format
+
+The configuration data is described using the following [header]:
 
 ```
 +===============================+
@@ -64,9 +159,64 @@
 The header format itself is agnostic of the internal format of the individual
 blos it refers to. In version 1.0, it describes two blobs:
 
-- entry 0 must point to a valid [BCC Handover]
+- entry 0 must point to a valid BCC Handover (see below)
 - entry 1 may point to a [DTBO] to be applied to the pVM device tree
 
 [header]: src/config.rs
-[BCC Handover]: https://pigweed.googlesource.com/open-dice/+/825e3beb6c6efcd8c35506d818c18d1e73b9834a/src/android/bcc.c#260
 [DTBO]: https://android.googlesource.com/platform/external/dtc/+/refs/heads/master/Documentation/dt-object-internal.txt
+
+#### Virtual Platform Boot Certificate Chain Handover
+
+The format of the BCC entry mentioned above, compatible with the
+[`BccHandover`][BccHandover] defined by the Open Profile for DICE reference
+implementation, is described by the following [CDDL][CDDL]:
+```
+PvmfwBccHandover = {
+  1 : bstr .size 32,     ; CDI_Attest
+  2 : bstr .size 32,     ; CDI_Seal
+  3 : Bcc,               ; Certificate chain
+}
+```
+
+and contains the _Compound Device Identifiers_ ("CDIs"), used to derive the
+next-stage secret, and a certificate chain, intended for pVM attestation. Note
+that it differs from the `BccHandover` defined by the specification in that its
+`Bcc` field is mandatory (while optional in the original).
+
+The handover expected by pvmfw can be generated as follows:
+
+- by passing a `BccHandover` received from a previous boot stage (_e.g._ Trusted
+  Firmware, ROM bootloader, ...) to
+  [`BccHandoverMainFlow`][BccHandoverMainFlow];
+
+- by generating a `BccHandover` (as an example, see [Trusty][Trusty-BCC]) with
+  both CDIs set to an arbitrary constant value and no `Bcc`, and pass it to
+  `BccHandoverMainFlow`, which will both derive the pvmfw CDIs and start a
+  valid certificate chain, making the pvmfw loader the root of the BCC.
+
+The recommended DICE inputs at this stage are:
+
+- **Code**: hash of the pvmfw image, hypervisor (`boot.img`), and other target
+  code relevant to the secure execution of pvmfw (_e.g._ `vendor_boot.img`)
+- **Configuration Data**: any extra input relevant to pvmfw security
+- **Authority Data**: must cover all the public keys used to sign and verify the
+  code contributing to the **Code** input
+- **Mode Decision**: Set according to the [specification][dice-mode]. In
+  particular, should only be `Normal` if secure boot is being properly enforced
+  (_e.g._ locked device in [Android Verified Boot][AVB])
+- **Hidden Inputs**: Factory Reset Secret (FRS, stored in a tamper evident
+  storage and changes during every factory reset) or similar that changes as
+  part of the device lifecycle (_e.g._ reset)
+
+The resulting `BccHandover` is then used by pvmfw in a similar way to derive
+another [DICE layer][Layering], passed to the guest through a `/reserved-memory`
+device tree node marked as [`compatible=”google,open-dice”`][dice-dt].
+
+[AVB]: https://source.android.com/docs/security/features/verifiedboot/boot-flow
+[BccHandover]: https://pigweed.googlesource.com/open-dice/+/825e3beb6c/src/android/bcc.c#260
+[BccHandoverMainFlow]: https://pigweed.googlesource.com/open-dice/+/825e3beb6c/src/android/bcc.c#199
+[CDDL]: https://datatracker.ietf.org/doc/rfc8610
+[dice-mode]: https://pigweed.googlesource.com/open-dice/+/refs/heads/main/docs/specification.md#Mode-Value-Details
+[dice-dt]: https://www.kernel.org/doc/Documentation/devicetree/bindings/reserved-memory/google%2Copen-dice.yaml
+[Layering]: https://pigweed.googlesource.com/open-dice/+/refs/heads/main/docs/specification.md#layering-details
+[Trusty-BCC]: https://android.googlesource.com/trusty/lib/+/1696be0a8f3a7103/lib/hwbcc/common/swbcc.c#554
diff --git a/pvmfw/TEST_MAPPING b/pvmfw/TEST_MAPPING
index 8a2d352..5e58ebb 100644
--- a/pvmfw/TEST_MAPPING
+++ b/pvmfw/TEST_MAPPING
@@ -1,7 +1,7 @@
 {
   "avf-presubmit" : [
     {
-      "name" : "libpvmfw_avb.test"
+      "name" : "libpvmfw_avb.integration_test"
     }
   ]
 }
\ No newline at end of file
diff --git a/pvmfw/avb/Android.bp b/pvmfw/avb/Android.bp
index d3a5e4e..fb950b7 100644
--- a/pvmfw/avb/Android.bp
+++ b/pvmfw/avb/Android.bp
@@ -9,6 +9,7 @@
     prefer_rlib: true,
     rustlibs: [
         "libavb_bindgen",
+        "libtinyvec_nostd",
     ],
     whole_static_libs: [
         "libavb",
@@ -25,19 +26,27 @@
 }
 
 rust_test {
-    name: "libpvmfw_avb.test",
-    defaults: ["libpvmfw_avb_nostd_defaults"],
+    name: "libpvmfw_avb.integration_test",
+    crate_name: "pvmfw_avb_test",
+    srcs: ["tests/*.rs"],
     test_suites: ["general-tests"],
     data: [
         ":avb_testkey_rsa2048_pub_bin",
         ":avb_testkey_rsa4096_pub_bin",
         ":microdroid_kernel_signed",
         ":microdroid_initrd_normal",
+        ":microdroid_initrd_debuggable",
         ":test_image_with_one_hashdesc",
+        ":test_image_with_non_initrd_hashdesc",
+        ":test_image_with_initrd_and_non_initrd_desc",
+        ":test_image_with_prop_desc",
         ":unsigned_test_image",
     ],
+    prefer_rlib: true,
     rustlibs: [
         "libanyhow",
+        "libavb_bindgen",
+        "libpvmfw_avb_nostd",
     ],
     enabled: false,
     arch: {
@@ -59,6 +68,60 @@
     cmd: "$(location avbtool) generate_test_image --image_size 16384 --output $(out)",
 }
 
+avb_gen_vbmeta_image {
+    name: "test_non_initrd_hashdesc",
+    src: ":unsigned_test_image",
+    partition_name: "non_initrd11",
+    salt: "2222",
+}
+
+avb_add_hash_footer {
+    name: "test_image_with_non_initrd_hashdesc",
+    src: ":unsigned_test_image",
+    partition_name: "boot",
+    private_key: ":pvmfw_sign_key",
+    salt: "3322",
+    include_descriptors_from_images: [
+        ":test_non_initrd_hashdesc",
+    ],
+}
+
+avb_add_hash_footer {
+    name: "test_image_with_initrd_and_non_initrd_desc",
+    src: ":unsigned_test_image",
+    partition_name: "boot",
+    private_key: ":pvmfw_sign_key",
+    salt: "3241",
+    include_descriptors_from_images: [
+        ":microdroid_initrd_normal_hashdesc",
+        ":test_non_initrd_hashdesc",
+    ],
+    enabled: false,
+    arch: {
+        // microdroid_initrd_normal_hashdesc is only available in these architectures.
+        arm64: {
+            enabled: true,
+        },
+        x86_64: {
+            enabled: true,
+        },
+    },
+}
+
+avb_add_hash_footer {
+    name: "test_image_with_prop_desc",
+    src: ":unsigned_test_image",
+    partition_name: "boot",
+    private_key: ":pvmfw_sign_key",
+    salt: "2134",
+    props: [
+        {
+            name: "mock_prop",
+            value: "3333",
+        },
+    ],
+}
+
 avb_add_hash_footer {
     name: "test_image_with_one_hashdesc",
     src: ":unsigned_test_image",
diff --git a/pvmfw/avb/fuzz/Android.bp b/pvmfw/avb/fuzz/Android.bp
new file mode 100644
index 0000000..451fd8a
--- /dev/null
+++ b/pvmfw/avb/fuzz/Android.bp
@@ -0,0 +1,34 @@
+// Copyright 2023, 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.
+
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+rust_fuzz {
+    name: "avb_kernel_without_footer_verify_fuzzer",
+    srcs: ["without_footer_verify_fuzzer.rs"],
+    rustlibs: [
+        "libpvmfw_avb_nostd",
+    ],
+    fuzz_config: {
+        cc: [
+            "android-kvm@google.com",
+        ],
+        fuzz_on_haiku_device: true,
+        fuzz_on_haiku_host: true,
+    },
+}
+
+// TODO(b/260574387): Add avb_kernel_with_footer_verify_fuzzer
diff --git a/pvmfw/avb/fuzz/without_footer_verify_fuzzer.rs b/pvmfw/avb/fuzz/without_footer_verify_fuzzer.rs
new file mode 100644
index 0000000..fc8fa85
--- /dev/null
+++ b/pvmfw/avb/fuzz/without_footer_verify_fuzzer.rs
@@ -0,0 +1,28 @@
+// Copyright 2023, 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.
+
+#![allow(missing_docs)]
+#![no_main]
+
+use libfuzzer_sys::fuzz_target;
+use pvmfw_avb::verify_payload;
+
+fuzz_target!(|kernel: &[u8]| {
+    // This fuzzer is mostly supposed to catch the memory corruption in
+    // AVB footer parsing. It is unlikely that the randomly generated
+    // kernel can pass the kernel verification, so the value of `initrd`
+    // is not so important as we won't reach initrd verification with
+    // this fuzzer.
+    let _ = verify_payload(kernel, /*initrd=*/ None, &[0u8; 64]);
+});
diff --git a/pvmfw/avb/src/descriptor.rs b/pvmfw/avb/src/descriptor.rs
new file mode 100644
index 0000000..b0598de
--- /dev/null
+++ b/pvmfw/avb/src/descriptor.rs
@@ -0,0 +1,204 @@
+// Copyright 2023, 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.
+
+//! Structs and functions relating to the descriptors.
+
+#![warn(unsafe_op_in_unsafe_fn)]
+
+use crate::error::{AvbIOError, AvbSlotVerifyError};
+use crate::partition::PartitionName;
+use crate::utils::{self, is_not_null, to_nonnull, to_usize, usize_checked_add};
+use avb_bindgen::{
+    avb_descriptor_foreach, avb_hash_descriptor_validate_and_byteswap, AvbDescriptor,
+    AvbHashDescriptor, AvbVBMetaData, AVB_SHA256_DIGEST_SIZE,
+};
+use core::{
+    ffi::c_void,
+    mem::{size_of, MaybeUninit},
+    ops::Range,
+    slice,
+};
+use tinyvec::ArrayVec;
+
+const DIGEST_SIZE: usize = AVB_SHA256_DIGEST_SIZE as usize;
+
+/// `HashDescriptors` can have maximum one `HashDescriptor` per known partition.
+#[derive(Default)]
+pub(crate) struct HashDescriptors(
+    ArrayVec<[HashDescriptor; PartitionName::NUM_OF_KNOWN_PARTITIONS]>,
+);
+
+impl HashDescriptors {
+    /// Builds `HashDescriptors` from `AvbVBMetaData`.
+    /// Returns an error if the given `AvbVBMetaData` contains non-hash descriptor, hash
+    /// descriptor of unknown `PartitionName` or duplicated hash descriptors.
+    ///
+    /// # Safety
+    ///
+    /// Behavior is undefined if any of the following conditions are violated:
+    /// * `vbmeta.vbmeta_data` must be non-null and points to a valid VBMeta.
+    /// * `vbmeta.vbmeta_data` must be valid for reading `vbmeta.vbmeta_size` bytes.
+    pub(crate) unsafe fn from_vbmeta(vbmeta: AvbVBMetaData) -> Result<Self, AvbSlotVerifyError> {
+        is_not_null(vbmeta.vbmeta_data).map_err(|_| AvbSlotVerifyError::Io)?;
+        let mut descriptors = Self::default();
+        // SAFETY: It is safe as the raw pointer `vbmeta.vbmeta_data` is a non-null pointer and
+        // points to a valid VBMeta structure.
+        if !unsafe {
+            avb_descriptor_foreach(
+                vbmeta.vbmeta_data,
+                vbmeta.vbmeta_size,
+                Some(check_and_save_descriptor),
+                &mut descriptors as *mut _ as *mut c_void,
+            )
+        } {
+            return Err(AvbSlotVerifyError::InvalidMetadata);
+        }
+        Ok(descriptors)
+    }
+
+    fn push(&mut self, descriptor: HashDescriptor) -> utils::Result<()> {
+        if self.0.iter().any(|d| d.partition_name_eq(&descriptor)) {
+            return Err(AvbIOError::Io);
+        }
+        self.0.push(descriptor);
+        Ok(())
+    }
+
+    pub(crate) fn len(&self) -> usize {
+        self.0.len()
+    }
+
+    /// Finds the `HashDescriptor` for the given `PartitionName`.
+    /// Throws an error if no corresponding descriptor found.
+    pub(crate) fn find(
+        &self,
+        partition_name: PartitionName,
+    ) -> Result<&HashDescriptor, AvbSlotVerifyError> {
+        self.0
+            .iter()
+            .find(|d| d.partition_name == partition_name)
+            .ok_or(AvbSlotVerifyError::InvalidMetadata)
+    }
+}
+
+/// # Safety
+///
+/// Behavior is undefined if any of the following conditions are violated:
+/// * The `descriptor` pointer must be non-null and points to a valid `AvbDescriptor` struct.
+/// * The `user_data` pointer must be non-null and points to a valid `HashDescriptors` struct.
+unsafe extern "C" fn check_and_save_descriptor(
+    descriptor: *const AvbDescriptor,
+    user_data: *mut c_void,
+) -> bool {
+    // SAFETY: It is safe because the caller must ensure that the `descriptor` pointer and
+    // the `user_data` are non-null and valid.
+    unsafe { try_check_and_save_descriptor(descriptor, user_data).is_ok() }
+}
+
+/// # Safety
+///
+/// Behavior is undefined if any of the following conditions are violated:
+/// * The `descriptor` pointer must be non-null and points to a valid `AvbDescriptor` struct.
+/// * The `user_data` pointer must be non-null and points to a valid `HashDescriptors` struct.
+unsafe fn try_check_and_save_descriptor(
+    descriptor: *const AvbDescriptor,
+    user_data: *mut c_void,
+) -> utils::Result<()> {
+    is_not_null(descriptor)?;
+    // SAFETY: It is safe because the caller ensures that `descriptor` is a non-null pointer
+    // pointing to a valid struct.
+    let desc = unsafe { AvbHashDescriptorWrap::from_descriptor_ptr(descriptor)? };
+    // SAFETY: It is safe because the caller ensures that `descriptor` is a non-null pointer
+    // pointing to a valid struct.
+    let data = unsafe { slice::from_raw_parts(descriptor as *const u8, desc.len()?) };
+    let mut descriptors = to_nonnull(user_data as *mut HashDescriptors)?;
+    // SAFETY: It is safe because the caller ensures that `user_data` is a non-null pointer
+    // pointing to a valid struct.
+    let descriptors = unsafe { descriptors.as_mut() };
+    descriptors.push(HashDescriptor::new(&desc, data)?)
+}
+
+#[derive(Default)]
+pub(crate) struct HashDescriptor {
+    partition_name: PartitionName,
+    /// TODO(b/265897559): Pass this digest to DICE.
+    #[allow(dead_code)]
+    pub(crate) digest: [u8; DIGEST_SIZE],
+}
+
+impl HashDescriptor {
+    fn new(desc: &AvbHashDescriptorWrap, data: &[u8]) -> utils::Result<Self> {
+        let partition_name = data
+            .get(desc.partition_name_range()?)
+            .ok_or(AvbIOError::RangeOutsidePartition)?
+            .try_into()?;
+        let partition_digest =
+            data.get(desc.digest_range()?).ok_or(AvbIOError::RangeOutsidePartition)?;
+        let mut digest = [0u8; DIGEST_SIZE];
+        digest.copy_from_slice(partition_digest);
+        Ok(Self { partition_name, digest })
+    }
+
+    fn partition_name_eq(&self, other: &HashDescriptor) -> bool {
+        self.partition_name == other.partition_name
+    }
+}
+
+/// `AvbHashDescriptor` contains the metadata for the given descriptor.
+struct AvbHashDescriptorWrap(AvbHashDescriptor);
+
+impl AvbHashDescriptorWrap {
+    /// # Safety
+    ///
+    /// Behavior is undefined if any of the following conditions are violated:
+    /// * The `descriptor` pointer must be non-null and point to a valid `AvbDescriptor`.
+    unsafe fn from_descriptor_ptr(descriptor: *const AvbDescriptor) -> utils::Result<Self> {
+        is_not_null(descriptor)?;
+        // SAFETY: It is safe as the raw pointer `descriptor` is non-null and points to
+        // a valid `AvbDescriptor`.
+        let desc = unsafe {
+            let mut desc = MaybeUninit::uninit();
+            if !avb_hash_descriptor_validate_and_byteswap(
+                descriptor as *const AvbHashDescriptor,
+                desc.as_mut_ptr(),
+            ) {
+                return Err(AvbIOError::Io);
+            }
+            desc.assume_init()
+        };
+        Ok(Self(desc))
+    }
+
+    fn len(&self) -> utils::Result<usize> {
+        usize_checked_add(
+            size_of::<AvbDescriptor>(),
+            to_usize(self.0.parent_descriptor.num_bytes_following)?,
+        )
+    }
+
+    fn partition_name_end(&self) -> utils::Result<usize> {
+        usize_checked_add(size_of::<AvbHashDescriptor>(), to_usize(self.0.partition_name_len)?)
+    }
+
+    fn partition_name_range(&self) -> utils::Result<Range<usize>> {
+        let start = size_of::<AvbHashDescriptor>();
+        Ok(start..(self.partition_name_end()?))
+    }
+
+    fn digest_range(&self) -> utils::Result<Range<usize>> {
+        let start = usize_checked_add(self.partition_name_end()?, to_usize(self.0.salt_len)?)?;
+        let end = usize_checked_add(start, to_usize(self.0.digest_len)?)?;
+        Ok(start..end)
+    }
+}
diff --git a/pvmfw/avb/src/error.rs b/pvmfw/avb/src/error.rs
index 8b06150..674e5a7 100644
--- a/pvmfw/avb/src/error.rs
+++ b/pvmfw/avb/src/error.rs
@@ -12,9 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-//! This module contains the error thrown by the payload verification API.
+//! This module contains the error thrown by the payload verification API
+//! and other errors used in the library.
 
-use avb_bindgen::AvbSlotVerifyResult;
+use avb_bindgen::{AvbIOResult, AvbSlotVerifyResult};
 
 use core::fmt;
 
@@ -85,3 +86,44 @@
         }
     }
 }
+
+#[derive(Debug)]
+pub(crate) enum AvbIOError {
+    /// AVB_IO_RESULT_ERROR_OOM,
+    #[allow(dead_code)]
+    Oom,
+    /// AVB_IO_RESULT_ERROR_IO,
+    #[allow(dead_code)]
+    Io,
+    /// AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION,
+    NoSuchPartition,
+    /// AVB_IO_RESULT_ERROR_RANGE_OUTSIDE_PARTITION,
+    RangeOutsidePartition,
+    /// AVB_IO_RESULT_ERROR_NO_SUCH_VALUE,
+    NoSuchValue,
+    /// AVB_IO_RESULT_ERROR_INVALID_VALUE_SIZE,
+    InvalidValueSize,
+    /// AVB_IO_RESULT_ERROR_INSUFFICIENT_SPACE,
+    #[allow(dead_code)]
+    InsufficientSpace,
+}
+
+impl From<AvbIOError> for AvbIOResult {
+    fn from(error: AvbIOError) -> Self {
+        match error {
+            AvbIOError::Oom => AvbIOResult::AVB_IO_RESULT_ERROR_OOM,
+            AvbIOError::Io => AvbIOResult::AVB_IO_RESULT_ERROR_IO,
+            AvbIOError::NoSuchPartition => AvbIOResult::AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION,
+            AvbIOError::RangeOutsidePartition => {
+                AvbIOResult::AVB_IO_RESULT_ERROR_RANGE_OUTSIDE_PARTITION
+            }
+            AvbIOError::NoSuchValue => AvbIOResult::AVB_IO_RESULT_ERROR_NO_SUCH_VALUE,
+            AvbIOError::InvalidValueSize => AvbIOResult::AVB_IO_RESULT_ERROR_INVALID_VALUE_SIZE,
+            AvbIOError::InsufficientSpace => AvbIOResult::AVB_IO_RESULT_ERROR_INSUFFICIENT_SPACE,
+        }
+    }
+}
+
+pub(crate) fn to_avb_io_result(result: Result<(), AvbIOError>) -> AvbIOResult {
+    result.map_or_else(|e| e.into(), |_| AvbIOResult::AVB_IO_RESULT_OK)
+}
diff --git a/pvmfw/avb/src/lib.rs b/pvmfw/avb/src/lib.rs
index 6a5b16d..065eca5 100644
--- a/pvmfw/avb/src/lib.rs
+++ b/pvmfw/avb/src/lib.rs
@@ -18,8 +18,12 @@
 // For usize.checked_add_signed(isize), available in Rust 1.66.0
 #![feature(mixed_integer_ops)]
 
+mod descriptor;
 mod error;
+mod ops;
+mod partition;
+mod utils;
 mod verify;
 
 pub use error::AvbSlotVerifyError;
-pub use verify::verify_payload;
+pub use verify::{verify_payload, DebugLevel};
diff --git a/pvmfw/avb/src/ops.rs b/pvmfw/avb/src/ops.rs
new file mode 100644
index 0000000..e7f0ac7
--- /dev/null
+++ b/pvmfw/avb/src/ops.rs
@@ -0,0 +1,339 @@
+// Copyright 2023, 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.
+
+//! Structs and functions relating to `AvbOps`.
+
+use crate::error::{
+    slot_verify_result_to_verify_payload_result, to_avb_io_result, AvbIOError, AvbSlotVerifyError,
+};
+use crate::partition::PartitionName;
+use crate::utils::{self, as_ref, is_not_null, to_nonnull, write};
+use avb_bindgen::{
+    avb_slot_verify, avb_slot_verify_data_free, AvbHashtreeErrorMode, AvbIOResult, AvbOps,
+    AvbPartitionData, AvbSlotVerifyData, AvbSlotVerifyFlags, AvbVBMetaData,
+};
+use core::{
+    ffi::{c_char, c_void, CStr},
+    mem::MaybeUninit,
+    ptr, slice,
+};
+
+const NULL_BYTE: &[u8] = b"\0";
+
+pub(crate) struct Payload<'a> {
+    kernel: &'a [u8],
+    initrd: Option<&'a [u8]>,
+    trusted_public_key: &'a [u8],
+}
+
+impl<'a> AsRef<Payload<'a>> for AvbOps {
+    fn as_ref(&self) -> &Payload<'a> {
+        let payload = self.user_data as *const Payload;
+        // SAFETY: It is safe to cast the `AvbOps.user_data` to Payload as we have saved a
+        // pointer to a valid value of Payload in user_data when creating AvbOps.
+        unsafe { &*payload }
+    }
+}
+
+impl<'a> Payload<'a> {
+    pub(crate) fn new(
+        kernel: &'a [u8],
+        initrd: Option<&'a [u8]>,
+        trusted_public_key: &'a [u8],
+    ) -> Self {
+        Self { kernel, initrd, trusted_public_key }
+    }
+
+    fn get_partition(&self, partition_name: *const c_char) -> Result<&[u8], AvbIOError> {
+        match partition_name.try_into()? {
+            PartitionName::Kernel => Ok(self.kernel),
+            PartitionName::InitrdNormal | PartitionName::InitrdDebug => {
+                self.initrd.ok_or(AvbIOError::NoSuchPartition)
+            }
+        }
+    }
+}
+
+/// `Ops` wraps the class `AvbOps` in libavb. It provides pvmfw customized
+/// operations used in the verification.
+pub(crate) struct Ops(AvbOps);
+
+impl<'a> From<&mut Payload<'a>> for Ops {
+    fn from(payload: &mut Payload<'a>) -> Self {
+        let avb_ops = AvbOps {
+            user_data: payload as *mut _ as *mut c_void,
+            ab_ops: ptr::null_mut(),
+            atx_ops: ptr::null_mut(),
+            read_from_partition: Some(read_from_partition),
+            get_preloaded_partition: Some(get_preloaded_partition),
+            write_to_partition: None,
+            validate_vbmeta_public_key: Some(validate_vbmeta_public_key),
+            read_rollback_index: Some(read_rollback_index),
+            write_rollback_index: None,
+            read_is_device_unlocked: Some(read_is_device_unlocked),
+            get_unique_guid_for_partition: Some(get_unique_guid_for_partition),
+            get_size_of_partition: Some(get_size_of_partition),
+            read_persistent_value: None,
+            write_persistent_value: None,
+            validate_public_key_for_partition: None,
+        };
+        Self(avb_ops)
+    }
+}
+
+impl Ops {
+    pub(crate) fn verify_partition(
+        &mut self,
+        partition_name: &CStr,
+    ) -> Result<AvbSlotVerifyDataWrap, AvbSlotVerifyError> {
+        let requested_partitions = [partition_name.as_ptr(), ptr::null()];
+        let ab_suffix = CStr::from_bytes_with_nul(NULL_BYTE).unwrap();
+        let mut out_data = MaybeUninit::uninit();
+        // SAFETY: It is safe to call `avb_slot_verify()` as the pointer arguments (`ops`,
+        // `requested_partitions` and `ab_suffix`) passed to the method are all valid and
+        // initialized.
+        let result = unsafe {
+            avb_slot_verify(
+                &mut self.0,
+                requested_partitions.as_ptr(),
+                ab_suffix.as_ptr(),
+                AvbSlotVerifyFlags::AVB_SLOT_VERIFY_FLAGS_NONE,
+                AvbHashtreeErrorMode::AVB_HASHTREE_ERROR_MODE_RESTART_AND_INVALIDATE,
+                out_data.as_mut_ptr(),
+            )
+        };
+        slot_verify_result_to_verify_payload_result(result)?;
+        // SAFETY: This is safe because `out_data` has been properly initialized after
+        // calling `avb_slot_verify` and it returns OK.
+        let out_data = unsafe { out_data.assume_init() };
+        out_data.try_into()
+    }
+}
+
+extern "C" fn read_is_device_unlocked(
+    _ops: *mut AvbOps,
+    out_is_unlocked: *mut bool,
+) -> AvbIOResult {
+    to_avb_io_result(write(out_is_unlocked, false))
+}
+
+extern "C" fn get_preloaded_partition(
+    ops: *mut AvbOps,
+    partition: *const c_char,
+    num_bytes: usize,
+    out_pointer: *mut *mut u8,
+    out_num_bytes_preloaded: *mut usize,
+) -> AvbIOResult {
+    to_avb_io_result(try_get_preloaded_partition(
+        ops,
+        partition,
+        num_bytes,
+        out_pointer,
+        out_num_bytes_preloaded,
+    ))
+}
+
+fn try_get_preloaded_partition(
+    ops: *mut AvbOps,
+    partition: *const c_char,
+    num_bytes: usize,
+    out_pointer: *mut *mut u8,
+    out_num_bytes_preloaded: *mut usize,
+) -> utils::Result<()> {
+    let ops = as_ref(ops)?;
+    let partition = ops.as_ref().get_partition(partition)?;
+    write(out_pointer, partition.as_ptr() as *mut u8)?;
+    write(out_num_bytes_preloaded, partition.len().min(num_bytes))
+}
+
+extern "C" fn read_from_partition(
+    ops: *mut AvbOps,
+    partition: *const c_char,
+    offset: i64,
+    num_bytes: usize,
+    buffer: *mut c_void,
+    out_num_read: *mut usize,
+) -> AvbIOResult {
+    to_avb_io_result(try_read_from_partition(
+        ops,
+        partition,
+        offset,
+        num_bytes,
+        buffer,
+        out_num_read,
+    ))
+}
+
+fn try_read_from_partition(
+    ops: *mut AvbOps,
+    partition: *const c_char,
+    offset: i64,
+    num_bytes: usize,
+    buffer: *mut c_void,
+    out_num_read: *mut usize,
+) -> utils::Result<()> {
+    let ops = as_ref(ops)?;
+    let partition = ops.as_ref().get_partition(partition)?;
+    let buffer = to_nonnull(buffer)?;
+    // SAFETY: It is safe to copy the requested number of bytes to `buffer` as `buffer`
+    // is created to point to the `num_bytes` of bytes in memory.
+    let buffer_slice = unsafe { slice::from_raw_parts_mut(buffer.as_ptr() as *mut u8, num_bytes) };
+    copy_data_to_dst(partition, offset, buffer_slice)?;
+    write(out_num_read, buffer_slice.len())
+}
+
+fn copy_data_to_dst(src: &[u8], offset: i64, dst: &mut [u8]) -> utils::Result<()> {
+    let start = to_copy_start(offset, src.len()).ok_or(AvbIOError::InvalidValueSize)?;
+    let end = start.checked_add(dst.len()).ok_or(AvbIOError::InvalidValueSize)?;
+    dst.copy_from_slice(src.get(start..end).ok_or(AvbIOError::RangeOutsidePartition)?);
+    Ok(())
+}
+
+fn to_copy_start(offset: i64, len: usize) -> Option<usize> {
+    usize::try_from(offset)
+        .ok()
+        .or_else(|| isize::try_from(offset).ok().and_then(|v| len.checked_add_signed(v)))
+}
+
+extern "C" fn get_size_of_partition(
+    ops: *mut AvbOps,
+    partition: *const c_char,
+    out_size_num_bytes: *mut u64,
+) -> AvbIOResult {
+    to_avb_io_result(try_get_size_of_partition(ops, partition, out_size_num_bytes))
+}
+
+fn try_get_size_of_partition(
+    ops: *mut AvbOps,
+    partition: *const c_char,
+    out_size_num_bytes: *mut u64,
+) -> utils::Result<()> {
+    let ops = as_ref(ops)?;
+    let partition = ops.as_ref().get_partition(partition)?;
+    let partition_size =
+        u64::try_from(partition.len()).map_err(|_| AvbIOError::InvalidValueSize)?;
+    write(out_size_num_bytes, partition_size)
+}
+
+extern "C" fn read_rollback_index(
+    _ops: *mut AvbOps,
+    _rollback_index_location: usize,
+    out_rollback_index: *mut u64,
+) -> AvbIOResult {
+    // Rollback protection is not yet implemented, but this method is required by
+    // `avb_slot_verify()`.
+    // We set `out_rollback_index` to 0 to ensure that the default rollback index (0)
+    // is never smaller than it, thus the rollback index check will pass.
+    to_avb_io_result(write(out_rollback_index, 0))
+}
+
+extern "C" fn get_unique_guid_for_partition(
+    _ops: *mut AvbOps,
+    _partition: *const c_char,
+    _guid_buf: *mut c_char,
+    _guid_buf_size: usize,
+) -> AvbIOResult {
+    // TODO(b/256148034): Check if it's possible to throw an error here instead of having
+    // an empty method.
+    // This method is required by `avb_slot_verify()`.
+    AvbIOResult::AVB_IO_RESULT_OK
+}
+
+extern "C" fn validate_vbmeta_public_key(
+    ops: *mut AvbOps,
+    public_key_data: *const u8,
+    public_key_length: usize,
+    public_key_metadata: *const u8,
+    public_key_metadata_length: usize,
+    out_is_trusted: *mut bool,
+) -> AvbIOResult {
+    to_avb_io_result(try_validate_vbmeta_public_key(
+        ops,
+        public_key_data,
+        public_key_length,
+        public_key_metadata,
+        public_key_metadata_length,
+        out_is_trusted,
+    ))
+}
+
+fn try_validate_vbmeta_public_key(
+    ops: *mut AvbOps,
+    public_key_data: *const u8,
+    public_key_length: usize,
+    _public_key_metadata: *const u8,
+    _public_key_metadata_length: usize,
+    out_is_trusted: *mut bool,
+) -> utils::Result<()> {
+    // The public key metadata is not used when we build the VBMeta.
+    is_not_null(public_key_data)?;
+    // SAFETY: It is safe to create a slice with the given pointer and length as
+    // `public_key_data` is a valid pointer and it points to an array of length
+    // `public_key_length`.
+    let public_key = unsafe { slice::from_raw_parts(public_key_data, public_key_length) };
+    let ops = as_ref(ops)?;
+    let trusted_public_key = ops.as_ref().trusted_public_key;
+    write(out_is_trusted, public_key == trusted_public_key)
+}
+
+pub(crate) struct AvbSlotVerifyDataWrap(*mut AvbSlotVerifyData);
+
+impl TryFrom<*mut AvbSlotVerifyData> for AvbSlotVerifyDataWrap {
+    type Error = AvbSlotVerifyError;
+
+    fn try_from(data: *mut AvbSlotVerifyData) -> Result<Self, Self::Error> {
+        is_not_null(data).map_err(|_| AvbSlotVerifyError::Io)?;
+        Ok(Self(data))
+    }
+}
+
+impl Drop for AvbSlotVerifyDataWrap {
+    fn drop(&mut self) {
+        // SAFETY: This is safe because `self.0` is checked nonnull when the
+        // instance is created. We can free this pointer when the instance is
+        // no longer needed.
+        unsafe {
+            avb_slot_verify_data_free(self.0);
+        }
+    }
+}
+
+impl AsRef<AvbSlotVerifyData> for AvbSlotVerifyDataWrap {
+    fn as_ref(&self) -> &AvbSlotVerifyData {
+        // This is safe because `self.0` is checked nonnull when the instance is created.
+        as_ref(self.0).unwrap()
+    }
+}
+
+impl AvbSlotVerifyDataWrap {
+    pub(crate) fn vbmeta_images(&self) -> Result<&[AvbVBMetaData], AvbSlotVerifyError> {
+        let data = self.as_ref();
+        is_not_null(data.vbmeta_images).map_err(|_| AvbSlotVerifyError::Io)?;
+        // SAFETY: It is safe as the raw pointer `data.vbmeta_images` is a nonnull pointer.
+        let vbmeta_images =
+            unsafe { slice::from_raw_parts(data.vbmeta_images, data.num_vbmeta_images) };
+        Ok(vbmeta_images)
+    }
+
+    pub(crate) fn loaded_partitions(&self) -> Result<&[AvbPartitionData], AvbSlotVerifyError> {
+        let data = self.as_ref();
+        is_not_null(data.loaded_partitions).map_err(|_| AvbSlotVerifyError::Io)?;
+        // SAFETY: It is safe as the raw pointer `data.loaded_partitions` is a nonnull pointer and
+        // is guaranteed by libavb to point to a valid `AvbPartitionData` array as part of the
+        // `AvbSlotVerifyData` struct.
+        let loaded_partitions =
+            unsafe { slice::from_raw_parts(data.loaded_partitions, data.num_loaded_partitions) };
+        Ok(loaded_partitions)
+    }
+}
diff --git a/pvmfw/avb/src/partition.rs b/pvmfw/avb/src/partition.rs
new file mode 100644
index 0000000..636bfd3
--- /dev/null
+++ b/pvmfw/avb/src/partition.rs
@@ -0,0 +1,90 @@
+// Copyright 2023, 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.
+
+//! Struct and functions relating to well-known partition names.
+
+use crate::error::AvbIOError;
+use crate::utils::is_not_null;
+use core::ffi::{c_char, CStr};
+
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub(crate) enum PartitionName {
+    /// The default `PartitionName` is needed to build the default `HashDescriptor`.
+    #[default]
+    Kernel,
+    InitrdNormal,
+    InitrdDebug,
+}
+
+impl PartitionName {
+    pub(crate) const NUM_OF_KNOWN_PARTITIONS: usize = 3;
+
+    const KERNEL_PARTITION_NAME: &[u8] = b"boot\0";
+    const INITRD_NORMAL_PARTITION_NAME: &[u8] = b"initrd_normal\0";
+    const INITRD_DEBUG_PARTITION_NAME: &[u8] = b"initrd_debug\0";
+
+    pub(crate) fn as_cstr(&self) -> &CStr {
+        CStr::from_bytes_with_nul(self.as_bytes()).unwrap()
+    }
+
+    fn as_non_null_terminated_bytes(&self) -> &[u8] {
+        let partition_name = self.as_bytes();
+        &partition_name[..partition_name.len() - 1]
+    }
+
+    fn as_bytes(&self) -> &[u8] {
+        match self {
+            Self::Kernel => Self::KERNEL_PARTITION_NAME,
+            Self::InitrdNormal => Self::INITRD_NORMAL_PARTITION_NAME,
+            Self::InitrdDebug => Self::INITRD_DEBUG_PARTITION_NAME,
+        }
+    }
+}
+
+impl TryFrom<*const c_char> for PartitionName {
+    type Error = AvbIOError;
+
+    fn try_from(partition_name: *const c_char) -> Result<Self, Self::Error> {
+        is_not_null(partition_name)?;
+        // SAFETY: It is safe as the raw pointer `partition_name` is a nonnull pointer.
+        let partition_name = unsafe { CStr::from_ptr(partition_name) };
+        partition_name.try_into()
+    }
+}
+
+impl TryFrom<&CStr> for PartitionName {
+    type Error = AvbIOError;
+
+    fn try_from(partition_name: &CStr) -> Result<Self, Self::Error> {
+        match partition_name.to_bytes_with_nul() {
+            Self::KERNEL_PARTITION_NAME => Ok(Self::Kernel),
+            Self::INITRD_NORMAL_PARTITION_NAME => Ok(Self::InitrdNormal),
+            Self::INITRD_DEBUG_PARTITION_NAME => Ok(Self::InitrdDebug),
+            _ => Err(AvbIOError::NoSuchPartition),
+        }
+    }
+}
+
+impl TryFrom<&[u8]> for PartitionName {
+    type Error = AvbIOError;
+
+    fn try_from(non_null_terminated_name: &[u8]) -> Result<Self, Self::Error> {
+        match non_null_terminated_name {
+            x if x == Self::Kernel.as_non_null_terminated_bytes() => Ok(Self::Kernel),
+            x if x == Self::InitrdNormal.as_non_null_terminated_bytes() => Ok(Self::InitrdNormal),
+            x if x == Self::InitrdDebug.as_non_null_terminated_bytes() => Ok(Self::InitrdDebug),
+            _ => Err(AvbIOError::NoSuchPartition),
+        }
+    }
+}
diff --git a/pvmfw/avb/src/utils.rs b/pvmfw/avb/src/utils.rs
new file mode 100644
index 0000000..a24d61f
--- /dev/null
+++ b/pvmfw/avb/src/utils.rs
@@ -0,0 +1,56 @@
+// Copyright 2023, 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.
+
+//! Common utility functions.
+
+use crate::error::AvbIOError;
+use core::ptr::NonNull;
+use core::result;
+
+pub(crate) type Result<T> = result::Result<T, AvbIOError>;
+
+pub(crate) fn write<T>(ptr: *mut T, value: T) -> Result<()> {
+    let ptr = to_nonnull(ptr)?;
+    // SAFETY: It is safe as the raw pointer `ptr` is a non-null pointer.
+    unsafe {
+        *ptr.as_ptr() = value;
+    }
+    Ok(())
+}
+
+pub(crate) fn as_ref<'a, T>(ptr: *mut T) -> Result<&'a T> {
+    let ptr = to_nonnull(ptr)?;
+    // SAFETY: It is safe as the raw pointer `ptr` is a non-null pointer.
+    unsafe { Ok(ptr.as_ref()) }
+}
+
+pub(crate) fn to_nonnull<T>(ptr: *mut T) -> Result<NonNull<T>> {
+    NonNull::new(ptr).ok_or(AvbIOError::NoSuchValue)
+}
+
+pub(crate) fn is_not_null<T>(ptr: *const T) -> Result<()> {
+    if ptr.is_null() {
+        Err(AvbIOError::NoSuchValue)
+    } else {
+        Ok(())
+    }
+}
+
+pub(crate) fn to_usize<T: TryInto<usize>>(num: T) -> Result<usize> {
+    num.try_into().map_err(|_| AvbIOError::InvalidValueSize)
+}
+
+pub(crate) fn usize_checked_add(x: usize, y: usize) -> Result<usize> {
+    x.checked_add(y).ok_or(AvbIOError::InvalidValueSize)
+}
diff --git a/pvmfw/avb/src/verify.rs b/pvmfw/avb/src/verify.rs
index fb18626..14b0e7e 100644
--- a/pvmfw/avb/src/verify.rs
+++ b/pvmfw/avb/src/verify.rs
@@ -14,389 +14,71 @@
 
 //! This module handles the pvmfw payload verification.
 
-use crate::error::{slot_verify_result_to_verify_payload_result, AvbSlotVerifyError};
-use avb_bindgen::{avb_slot_verify, AvbHashtreeErrorMode, AvbIOResult, AvbOps, AvbSlotVerifyFlags};
-use core::{
-    ffi::{c_char, c_void, CStr},
-    ptr::{self, NonNull},
-    slice,
-};
+use crate::descriptor::HashDescriptors;
+use crate::error::AvbSlotVerifyError;
+use crate::ops::{Ops, Payload};
+use crate::partition::PartitionName;
+use avb_bindgen::{AvbPartitionData, AvbVBMetaData};
+use core::ffi::c_char;
 
-static NULL_BYTE: &[u8] = b"\0";
-
-enum AvbIOError {
-    /// AVB_IO_RESULT_ERROR_OOM,
-    #[allow(dead_code)]
-    Oom,
-    /// AVB_IO_RESULT_ERROR_IO,
-    #[allow(dead_code)]
-    Io,
-    /// AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION,
-    NoSuchPartition,
-    /// AVB_IO_RESULT_ERROR_RANGE_OUTSIDE_PARTITION,
-    RangeOutsidePartition,
-    /// AVB_IO_RESULT_ERROR_NO_SUCH_VALUE,
-    NoSuchValue,
-    /// AVB_IO_RESULT_ERROR_INVALID_VALUE_SIZE,
-    InvalidValueSize,
-    /// AVB_IO_RESULT_ERROR_INSUFFICIENT_SPACE,
-    #[allow(dead_code)]
-    InsufficientSpace,
-}
-
-impl From<AvbIOError> for AvbIOResult {
-    fn from(error: AvbIOError) -> Self {
-        match error {
-            AvbIOError::Oom => AvbIOResult::AVB_IO_RESULT_ERROR_OOM,
-            AvbIOError::Io => AvbIOResult::AVB_IO_RESULT_ERROR_IO,
-            AvbIOError::NoSuchPartition => AvbIOResult::AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION,
-            AvbIOError::RangeOutsidePartition => {
-                AvbIOResult::AVB_IO_RESULT_ERROR_RANGE_OUTSIDE_PARTITION
-            }
-            AvbIOError::NoSuchValue => AvbIOResult::AVB_IO_RESULT_ERROR_NO_SUCH_VALUE,
-            AvbIOError::InvalidValueSize => AvbIOResult::AVB_IO_RESULT_ERROR_INVALID_VALUE_SIZE,
-            AvbIOError::InsufficientSpace => AvbIOResult::AVB_IO_RESULT_ERROR_INSUFFICIENT_SPACE,
-        }
-    }
-}
-
-fn to_avb_io_result(result: Result<(), AvbIOError>) -> AvbIOResult {
-    result.map_or_else(|e| e.into(), |_| AvbIOResult::AVB_IO_RESULT_OK)
-}
-
-extern "C" fn read_is_device_unlocked(
-    _ops: *mut AvbOps,
-    out_is_unlocked: *mut bool,
-) -> AvbIOResult {
-    if let Err(e) = is_not_null(out_is_unlocked) {
-        return e.into();
-    }
-    // SAFETY: It is safe as the raw pointer `out_is_unlocked` is a valid pointer.
-    unsafe {
-        *out_is_unlocked = false;
-    }
-    AvbIOResult::AVB_IO_RESULT_OK
-}
-
-unsafe extern "C" fn get_preloaded_partition(
-    ops: *mut AvbOps,
-    partition: *const c_char,
-    num_bytes: usize,
-    out_pointer: *mut *mut u8,
-    out_num_bytes_preloaded: *mut usize,
-) -> AvbIOResult {
-    to_avb_io_result(try_get_preloaded_partition(
-        ops,
-        partition,
-        num_bytes,
-        out_pointer,
-        out_num_bytes_preloaded,
-    ))
-}
-
-fn try_get_preloaded_partition(
-    ops: *mut AvbOps,
-    partition: *const c_char,
-    num_bytes: usize,
-    out_pointer: *mut *mut u8,
-    out_num_bytes_preloaded: *mut usize,
-) -> Result<(), AvbIOError> {
-    let ops = as_ref(ops)?;
-    let partition = ops.as_ref().get_partition(partition)?;
-    let out_pointer = to_nonnull(out_pointer)?;
-    // SAFETY: It is safe as the raw pointer `out_pointer` is a nonnull pointer.
-    unsafe {
-        *out_pointer.as_ptr() = partition.as_ptr() as _;
-    }
-    let out_num_bytes_preloaded = to_nonnull(out_num_bytes_preloaded)?;
-    // SAFETY: The raw pointer `out_num_bytes_preloaded` was created to point to a valid a `usize`
-    // and we checked it is nonnull.
-    unsafe {
-        *out_num_bytes_preloaded.as_ptr() = partition.len().min(num_bytes);
-    }
-    Ok(())
-}
-
-extern "C" fn read_from_partition(
-    ops: *mut AvbOps,
-    partition: *const c_char,
-    offset: i64,
-    num_bytes: usize,
-    buffer: *mut c_void,
-    out_num_read: *mut usize,
-) -> AvbIOResult {
-    to_avb_io_result(try_read_from_partition(
-        ops,
-        partition,
-        offset,
-        num_bytes,
-        buffer,
-        out_num_read,
-    ))
-}
-
-fn try_read_from_partition(
-    ops: *mut AvbOps,
-    partition: *const c_char,
-    offset: i64,
-    num_bytes: usize,
-    buffer: *mut c_void,
-    out_num_read: *mut usize,
-) -> Result<(), AvbIOError> {
-    let ops = as_ref(ops)?;
-    let partition = ops.as_ref().get_partition(partition)?;
-    let buffer = to_nonnull(buffer)?;
-    // SAFETY: It is safe to copy the requested number of bytes to `buffer` as `buffer`
-    // is created to point to the `num_bytes` of bytes in memory.
-    let buffer_slice = unsafe { slice::from_raw_parts_mut(buffer.as_ptr() as *mut u8, num_bytes) };
-    copy_data_to_dst(partition, offset, buffer_slice)?;
-    let out_num_read = to_nonnull(out_num_read)?;
-    // SAFETY: The raw pointer `out_num_read` was created to point to a valid a `usize`
-    // and we checked it is nonnull.
-    unsafe {
-        *out_num_read.as_ptr() = buffer_slice.len();
-    }
-    Ok(())
-}
-
-fn copy_data_to_dst(src: &[u8], offset: i64, dst: &mut [u8]) -> Result<(), AvbIOError> {
-    let start = to_copy_start(offset, src.len()).ok_or(AvbIOError::InvalidValueSize)?;
-    let end = start.checked_add(dst.len()).ok_or(AvbIOError::InvalidValueSize)?;
-    dst.copy_from_slice(src.get(start..end).ok_or(AvbIOError::RangeOutsidePartition)?);
-    Ok(())
-}
-
-fn to_copy_start(offset: i64, len: usize) -> Option<usize> {
-    usize::try_from(offset)
-        .ok()
-        .or_else(|| isize::try_from(offset).ok().and_then(|v| len.checked_add_signed(v)))
-}
-
-extern "C" fn get_size_of_partition(
-    ops: *mut AvbOps,
-    partition: *const c_char,
-    out_size_num_bytes: *mut u64,
-) -> AvbIOResult {
-    to_avb_io_result(try_get_size_of_partition(ops, partition, out_size_num_bytes))
-}
-
-fn try_get_size_of_partition(
-    ops: *mut AvbOps,
-    partition: *const c_char,
-    out_size_num_bytes: *mut u64,
-) -> Result<(), AvbIOError> {
-    let ops = as_ref(ops)?;
-    let partition = ops.as_ref().get_partition(partition)?;
-    let partition_size =
-        u64::try_from(partition.len()).map_err(|_| AvbIOError::InvalidValueSize)?;
-    let out_size_num_bytes = to_nonnull(out_size_num_bytes)?;
-    // SAFETY: The raw pointer `out_size_num_bytes` was created to point to a valid a `u64`
-    // and we checked it is nonnull.
-    unsafe {
-        *out_size_num_bytes.as_ptr() = partition_size;
-    }
-    Ok(())
-}
-
-extern "C" fn read_rollback_index(
-    _ops: *mut AvbOps,
-    _rollback_index_location: usize,
-    _out_rollback_index: *mut u64,
-) -> AvbIOResult {
-    // Rollback protection is not yet implemented, but
-    // this method is required by `avb_slot_verify()`.
-    AvbIOResult::AVB_IO_RESULT_OK
-}
-
-extern "C" fn get_unique_guid_for_partition(
-    _ops: *mut AvbOps,
-    _partition: *const c_char,
-    _guid_buf: *mut c_char,
-    _guid_buf_size: usize,
-) -> AvbIOResult {
-    // This method is required by `avb_slot_verify()`.
-    AvbIOResult::AVB_IO_RESULT_OK
-}
-
-extern "C" fn validate_public_key_for_partition(
-    ops: *mut AvbOps,
-    partition: *const c_char,
-    public_key_data: *const u8,
-    public_key_length: usize,
-    public_key_metadata: *const u8,
-    public_key_metadata_length: usize,
-    out_is_trusted: *mut bool,
-    out_rollback_index_location: *mut u32,
-) -> AvbIOResult {
-    to_avb_io_result(try_validate_public_key_for_partition(
-        ops,
-        partition,
-        public_key_data,
-        public_key_length,
-        public_key_metadata,
-        public_key_metadata_length,
-        out_is_trusted,
-        out_rollback_index_location,
-    ))
-}
-
-#[allow(clippy::too_many_arguments)]
-fn try_validate_public_key_for_partition(
-    ops: *mut AvbOps,
-    partition: *const c_char,
-    public_key_data: *const u8,
-    public_key_length: usize,
-    _public_key_metadata: *const u8,
-    _public_key_metadata_length: usize,
-    out_is_trusted: *mut bool,
-    _out_rollback_index_location: *mut u32,
-) -> Result<(), AvbIOError> {
-    is_not_null(public_key_data)?;
-    // SAFETY: It is safe to create a slice with the given pointer and length as
-    // `public_key_data` is a valid pointer and it points to an array of length
-    // `public_key_length`.
-    let public_key = unsafe { slice::from_raw_parts(public_key_data, public_key_length) };
-    let ops = as_ref(ops)?;
-    // Verifies the public key for the known partitions only.
-    ops.as_ref().get_partition(partition)?;
-    let trusted_public_key = ops.as_ref().trusted_public_key;
-    let out_is_trusted = to_nonnull(out_is_trusted)?;
-    // SAFETY: It is safe as the raw pointer `out_is_trusted` is a nonnull pointer.
-    unsafe {
-        *out_is_trusted.as_ptr() = public_key == trusted_public_key;
-    }
-    Ok(())
-}
-
-fn as_ref<'a, T>(ptr: *mut T) -> Result<&'a T, AvbIOError> {
-    let ptr = to_nonnull(ptr)?;
-    // SAFETY: It is safe as the raw pointer `ptr` is a nonnull pointer.
-    unsafe { Ok(ptr.as_ref()) }
-}
-
-fn to_nonnull<T>(ptr: *mut T) -> Result<NonNull<T>, AvbIOError> {
-    NonNull::new(ptr).ok_or(AvbIOError::NoSuchValue)
-}
-
-fn is_not_null<T>(ptr: *const T) -> Result<(), AvbIOError> {
-    if ptr.is_null() {
-        Err(AvbIOError::NoSuchValue)
-    } else {
-        Ok(())
-    }
-}
-
+/// This enum corresponds to the `DebugLevel` in `VirtualMachineConfig`.
 #[derive(Clone, Debug, PartialEq, Eq)]
-enum PartitionName {
-    Kernel,
-    InitrdNormal,
-    InitrdDebug,
+pub enum DebugLevel {
+    /// Not debuggable at all.
+    None,
+    /// Fully debuggable.
+    Full,
 }
 
-impl PartitionName {
-    const KERNEL_PARTITION_NAME: &[u8] = b"boot\0";
-    const INITRD_NORMAL_PARTITION_NAME: &[u8] = b"initrd_normal\0";
-    const INITRD_DEBUG_PARTITION_NAME: &[u8] = b"initrd_debug\0";
-
-    fn as_cstr(&self) -> &CStr {
-        let partition_name = match self {
-            Self::Kernel => Self::KERNEL_PARTITION_NAME,
-            Self::InitrdNormal => Self::INITRD_NORMAL_PARTITION_NAME,
-            Self::InitrdDebug => Self::INITRD_DEBUG_PARTITION_NAME,
-        };
-        CStr::from_bytes_with_nul(partition_name).unwrap()
+fn verify_only_one_vbmeta_exists(
+    vbmeta_images: &[AvbVBMetaData],
+) -> Result<(), AvbSlotVerifyError> {
+    if vbmeta_images.len() == 1 {
+        Ok(())
+    } else {
+        Err(AvbSlotVerifyError::InvalidMetadata)
     }
 }
 
-impl TryFrom<&CStr> for PartitionName {
-    type Error = AvbIOError;
-
-    fn try_from(partition_name: &CStr) -> Result<Self, Self::Error> {
-        match partition_name.to_bytes_with_nul() {
-            Self::KERNEL_PARTITION_NAME => Ok(Self::Kernel),
-            Self::INITRD_NORMAL_PARTITION_NAME => Ok(Self::InitrdNormal),
-            Self::INITRD_DEBUG_PARTITION_NAME => Ok(Self::InitrdDebug),
-            _ => Err(AvbIOError::NoSuchPartition),
-        }
+fn verify_vbmeta_is_from_kernel_partition(
+    vbmeta_image: &AvbVBMetaData,
+) -> Result<(), AvbSlotVerifyError> {
+    match (vbmeta_image.partition_name as *const c_char).try_into() {
+        Ok(PartitionName::Kernel) => Ok(()),
+        _ => Err(AvbSlotVerifyError::InvalidMetadata),
     }
 }
 
-struct Payload<'a> {
-    kernel: &'a [u8],
-    initrd: Option<&'a [u8]>,
-    trusted_public_key: &'a [u8],
-}
-
-impl<'a> AsRef<Payload<'a>> for AvbOps {
-    fn as_ref(&self) -> &Payload<'a> {
-        let payload = self.user_data as *const Payload;
-        // SAFETY: It is safe to cast the `AvbOps.user_data` to Payload as we have saved a
-        // pointer to a valid value of Payload in user_data when creating AvbOps, and
-        // assume that the Payload isn't used beyond the lifetime of the AvbOps that it
-        // belongs to.
-        unsafe { &*payload }
+fn verify_vbmeta_has_only_one_hash_descriptor(
+    hash_descriptors: &HashDescriptors,
+) -> Result<(), AvbSlotVerifyError> {
+    if hash_descriptors.len() == 1 {
+        Ok(())
+    } else {
+        Err(AvbSlotVerifyError::InvalidMetadata)
     }
 }
 
-impl<'a> Payload<'a> {
-    const MAX_NUM_OF_HASH_DESCRIPTORS: usize = 3;
-
-    fn get_partition(&self, partition_name: *const c_char) -> Result<&[u8], AvbIOError> {
-        is_not_null(partition_name)?;
-        // SAFETY: It is safe as the raw pointer `partition_name` is a nonnull pointer.
-        let partition_name = unsafe { CStr::from_ptr(partition_name) };
-        match partition_name.try_into()? {
-            PartitionName::Kernel => Ok(self.kernel),
-            PartitionName::InitrdNormal | PartitionName::InitrdDebug => {
-                self.initrd.ok_or(AvbIOError::NoSuchPartition)
-            }
-        }
+fn verify_loaded_partition_has_expected_length(
+    loaded_partitions: &[AvbPartitionData],
+    partition_name: PartitionName,
+    expected_len: usize,
+) -> Result<(), AvbSlotVerifyError> {
+    if loaded_partitions.len() != 1 {
+        // Only one partition should be loaded in each verify result.
+        return Err(AvbSlotVerifyError::Io);
     }
-
-    fn verify_partitions(&mut self, partition_names: &[&CStr]) -> Result<(), AvbSlotVerifyError> {
-        if partition_names.len() > Self::MAX_NUM_OF_HASH_DESCRIPTORS {
-            return Err(AvbSlotVerifyError::InvalidArgument);
-        }
-        let mut requested_partitions = [ptr::null(); Self::MAX_NUM_OF_HASH_DESCRIPTORS + 1];
-        partition_names
-            .iter()
-            .enumerate()
-            .for_each(|(i, name)| requested_partitions[i] = name.as_ptr());
-
-        let mut avb_ops = AvbOps {
-            user_data: self as *mut _ as *mut c_void,
-            ab_ops: ptr::null_mut(),
-            atx_ops: ptr::null_mut(),
-            read_from_partition: Some(read_from_partition),
-            get_preloaded_partition: Some(get_preloaded_partition),
-            write_to_partition: None,
-            validate_vbmeta_public_key: None,
-            read_rollback_index: Some(read_rollback_index),
-            write_rollback_index: None,
-            read_is_device_unlocked: Some(read_is_device_unlocked),
-            get_unique_guid_for_partition: Some(get_unique_guid_for_partition),
-            get_size_of_partition: Some(get_size_of_partition),
-            read_persistent_value: None,
-            write_persistent_value: None,
-            validate_public_key_for_partition: Some(validate_public_key_for_partition),
-        };
-        let ab_suffix = CStr::from_bytes_with_nul(NULL_BYTE).unwrap();
-        let out_data = ptr::null_mut();
-        // SAFETY: It is safe to call `avb_slot_verify()` as the pointer arguments (`ops`,
-        // `requested_partitions` and `ab_suffix`) passed to the method are all valid and
-        // initialized. The last argument `out_data` is allowed to be null so that nothing
-        // will be written to it.
-        let result = unsafe {
-            avb_slot_verify(
-                &mut avb_ops,
-                requested_partitions.as_ptr(),
-                ab_suffix.as_ptr(),
-                AvbSlotVerifyFlags::AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION,
-                AvbHashtreeErrorMode::AVB_HASHTREE_ERROR_MODE_RESTART_AND_INVALIDATE,
-                out_data,
-            )
-        };
-        slot_verify_result_to_verify_payload_result(result)
+    let loaded_partition = loaded_partitions[0];
+    if !PartitionName::try_from(loaded_partition.partition_name as *const c_char)
+        .map_or(false, |p| p == partition_name)
+    {
+        // Only the requested partition should be loaded.
+        return Err(AvbSlotVerifyError::Io);
+    }
+    if loaded_partition.data_size == expected_len {
+        Ok(())
+    } else {
+        Err(AvbSlotVerifyError::Verification)
     }
 }
 
@@ -405,134 +87,41 @@
     kernel: &[u8],
     initrd: Option<&[u8]>,
     trusted_public_key: &[u8],
-) -> Result<(), AvbSlotVerifyError> {
-    let mut payload = Payload { kernel, initrd, trusted_public_key };
-    let requested_partitions = [PartitionName::Kernel.as_cstr()];
-    payload.verify_partitions(&requested_partitions)
-}
+) -> Result<DebugLevel, AvbSlotVerifyError> {
+    let mut payload = Payload::new(kernel, initrd, trusted_public_key);
+    let mut ops = Ops::from(&mut payload);
+    let kernel_verify_result = ops.verify_partition(PartitionName::Kernel.as_cstr())?;
 
-#[cfg(test)]
-mod tests {
-    use super::*;
-    use anyhow::Result;
-    use avb_bindgen::AvbFooter;
-    use std::{fs, mem::size_of};
+    let vbmeta_images = kernel_verify_result.vbmeta_images()?;
+    verify_only_one_vbmeta_exists(vbmeta_images)?;
+    let vbmeta_image = vbmeta_images[0];
+    verify_vbmeta_is_from_kernel_partition(&vbmeta_image)?;
+    // SAFETY: It is safe because the `vbmeta_image` is collected from `AvbSlotVerifyData`,
+    // which is returned by `avb_slot_verify()` when the verification succeeds. It is
+    // guaranteed by libavb to be non-null and to point to a valid VBMeta structure.
+    let hash_descriptors = unsafe { HashDescriptors::from_vbmeta(vbmeta_image)? };
+    // TODO(b/265897559): Pass the digest in kernel descriptor to DICE.
+    let _kernel_descriptor = hash_descriptors.find(PartitionName::Kernel)?;
 
-    const MICRODROID_KERNEL_IMG_PATH: &str = "microdroid_kernel";
-    const INITRD_NORMAL_IMG_PATH: &str = "microdroid_initrd_normal.img";
-    const TEST_IMG_WITH_ONE_HASHDESC_PATH: &str = "test_image_with_one_hashdesc.img";
-    const UNSIGNED_TEST_IMG_PATH: &str = "unsigned_test.img";
-
-    const PUBLIC_KEY_RSA2048_PATH: &str = "data/testkey_rsa2048_pub.bin";
-    const PUBLIC_KEY_RSA4096_PATH: &str = "data/testkey_rsa4096_pub.bin";
-    const RANDOM_FOOTER_POS: usize = 30;
-
-    /// This test uses the Microdroid payload compiled on the fly to check that
-    /// the latest payload can be verified successfully.
-    #[test]
-    fn latest_valid_payload_passes_verification() -> Result<()> {
-        let kernel = load_latest_signed_kernel()?;
-        let initrd_normal = fs::read(INITRD_NORMAL_IMG_PATH)?;
-        let public_key = fs::read(PUBLIC_KEY_RSA4096_PATH)?;
-
-        assert_eq!(Ok(()), verify_payload(&kernel, Some(&initrd_normal[..]), &public_key));
-        Ok(())
+    if initrd.is_none() {
+        verify_vbmeta_has_only_one_hash_descriptor(&hash_descriptors)?;
+        return Ok(DebugLevel::None);
     }
 
-    #[test]
-    fn payload_expecting_no_initrd_passes_verification_with_no_initrd() -> Result<()> {
-        let kernel = fs::read(TEST_IMG_WITH_ONE_HASHDESC_PATH)?;
-        let public_key = fs::read(PUBLIC_KEY_RSA4096_PATH)?;
-
-        assert_eq!(Ok(()), verify_payload(&kernel, None, &public_key));
-        Ok(())
-    }
-
-    // TODO(b/256148034): Test that kernel with two hashdesc and no initrd fails verification.
-    // e.g. payload_expecting_initrd_fails_verification_with_no_initrd
-
-    #[test]
-    fn payload_with_empty_public_key_fails_verification() -> Result<()> {
-        assert_payload_verification_fails(
-            &load_latest_signed_kernel()?,
-            &load_latest_initrd_normal()?,
-            /*trusted_public_key=*/ &[0u8; 0],
-            AvbSlotVerifyError::PublicKeyRejected,
-        )
-    }
-
-    #[test]
-    fn payload_with_an_invalid_public_key_fails_verification() -> Result<()> {
-        assert_payload_verification_fails(
-            &load_latest_signed_kernel()?,
-            &load_latest_initrd_normal()?,
-            /*trusted_public_key=*/ &[0u8; 512],
-            AvbSlotVerifyError::PublicKeyRejected,
-        )
-    }
-
-    #[test]
-    fn payload_with_a_different_valid_public_key_fails_verification() -> Result<()> {
-        assert_payload_verification_fails(
-            &load_latest_signed_kernel()?,
-            &load_latest_initrd_normal()?,
-            &fs::read(PUBLIC_KEY_RSA2048_PATH)?,
-            AvbSlotVerifyError::PublicKeyRejected,
-        )
-    }
-
-    #[test]
-    fn unsigned_kernel_fails_verification() -> Result<()> {
-        assert_payload_verification_fails(
-            &fs::read(UNSIGNED_TEST_IMG_PATH)?,
-            &load_latest_initrd_normal()?,
-            &fs::read(PUBLIC_KEY_RSA4096_PATH)?,
-            AvbSlotVerifyError::Io,
-        )
-    }
-
-    #[test]
-    fn tampered_kernel_fails_verification() -> Result<()> {
-        let mut kernel = load_latest_signed_kernel()?;
-        kernel[1] = !kernel[1]; // Flip the bits
-
-        assert_payload_verification_fails(
-            &kernel,
-            &load_latest_initrd_normal()?,
-            &fs::read(PUBLIC_KEY_RSA4096_PATH)?,
-            AvbSlotVerifyError::Verification,
-        )
-    }
-
-    #[test]
-    fn tampered_kernel_footer_fails_verification() -> Result<()> {
-        let mut kernel = load_latest_signed_kernel()?;
-        let avb_footer_index = kernel.len() - size_of::<AvbFooter>() + RANDOM_FOOTER_POS;
-        kernel[avb_footer_index] = !kernel[avb_footer_index];
-
-        assert_payload_verification_fails(
-            &kernel,
-            &load_latest_initrd_normal()?,
-            &fs::read(PUBLIC_KEY_RSA4096_PATH)?,
-            AvbSlotVerifyError::InvalidMetadata,
-        )
-    }
-
-    fn assert_payload_verification_fails(
-        kernel: &[u8],
-        initrd: &[u8],
-        trusted_public_key: &[u8],
-        expected_error: AvbSlotVerifyError,
-    ) -> Result<()> {
-        assert_eq!(Err(expected_error), verify_payload(kernel, Some(initrd), trusted_public_key));
-        Ok(())
-    }
-
-    fn load_latest_signed_kernel() -> Result<Vec<u8>> {
-        Ok(fs::read(MICRODROID_KERNEL_IMG_PATH)?)
-    }
-
-    fn load_latest_initrd_normal() -> Result<Vec<u8>> {
-        Ok(fs::read(INITRD_NORMAL_IMG_PATH)?)
-    }
+    let initrd = initrd.unwrap();
+    let (debug_level, initrd_verify_result, initrd_partition_name) =
+        if let Ok(result) = ops.verify_partition(PartitionName::InitrdNormal.as_cstr()) {
+            (DebugLevel::None, result, PartitionName::InitrdNormal)
+        } else if let Ok(result) = ops.verify_partition(PartitionName::InitrdDebug.as_cstr()) {
+            (DebugLevel::Full, result, PartitionName::InitrdDebug)
+        } else {
+            return Err(AvbSlotVerifyError::Verification);
+        };
+    let loaded_partitions = initrd_verify_result.loaded_partitions()?;
+    verify_loaded_partition_has_expected_length(
+        loaded_partitions,
+        initrd_partition_name,
+        initrd.len(),
+    )?;
+    Ok(debug_level)
 }
diff --git a/pvmfw/avb/tests/api_test.rs b/pvmfw/avb/tests/api_test.rs
new file mode 100644
index 0000000..4f00f1e
--- /dev/null
+++ b/pvmfw/avb/tests/api_test.rs
@@ -0,0 +1,312 @@
+/*
+ * Copyright (C) 2022 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.
+ */
+
+mod utils;
+
+use anyhow::Result;
+use avb_bindgen::{AvbFooter, AvbVBMetaImageHeader};
+use pvmfw_avb::{AvbSlotVerifyError, DebugLevel};
+use std::{fs, mem::size_of, ptr};
+use utils::*;
+
+const TEST_IMG_WITH_ONE_HASHDESC_PATH: &str = "test_image_with_one_hashdesc.img";
+const TEST_IMG_WITH_PROP_DESC_PATH: &str = "test_image_with_prop_desc.img";
+const TEST_IMG_WITH_NON_INITRD_HASHDESC_PATH: &str = "test_image_with_non_initrd_hashdesc.img";
+const TEST_IMG_WITH_INITRD_AND_NON_INITRD_DESC_PATH: &str =
+    "test_image_with_initrd_and_non_initrd_desc.img";
+const UNSIGNED_TEST_IMG_PATH: &str = "unsigned_test.img";
+
+const RANDOM_FOOTER_POS: usize = 30;
+
+/// This test uses the Microdroid payload compiled on the fly to check that
+/// the latest payload can be verified successfully.
+#[test]
+fn latest_normal_payload_passes_verification() -> Result<()> {
+    assert_payload_verification_with_initrd_eq(
+        &load_latest_signed_kernel()?,
+        &load_latest_initrd_normal()?,
+        &load_trusted_public_key()?,
+        Ok(DebugLevel::None),
+    )
+}
+
+#[test]
+fn latest_debug_payload_passes_verification() -> Result<()> {
+    assert_payload_verification_with_initrd_eq(
+        &load_latest_signed_kernel()?,
+        &load_latest_initrd_debug()?,
+        &load_trusted_public_key()?,
+        Ok(DebugLevel::Full),
+    )
+}
+
+#[test]
+fn payload_expecting_no_initrd_passes_verification_with_no_initrd() -> Result<()> {
+    assert_payload_verification_eq(
+        &fs::read(TEST_IMG_WITH_ONE_HASHDESC_PATH)?,
+        /*initrd=*/ None,
+        &load_trusted_public_key()?,
+        Ok(DebugLevel::None),
+    )
+}
+
+#[test]
+fn payload_with_non_initrd_descriptor_fails_verification_with_no_initrd() -> Result<()> {
+    assert_payload_verification_eq(
+        &fs::read(TEST_IMG_WITH_NON_INITRD_HASHDESC_PATH)?,
+        /*initrd=*/ None,
+        &load_trusted_public_key()?,
+        Err(AvbSlotVerifyError::InvalidMetadata),
+    )
+}
+
+#[test]
+fn payload_with_non_initrd_descriptor_fails_verification_with_initrd() -> Result<()> {
+    assert_payload_verification_with_initrd_eq(
+        &fs::read(TEST_IMG_WITH_INITRD_AND_NON_INITRD_DESC_PATH)?,
+        &load_latest_initrd_normal()?,
+        &load_trusted_public_key()?,
+        Err(AvbSlotVerifyError::InvalidMetadata),
+    )
+}
+
+#[test]
+fn payload_with_prop_descriptor_fails_verification_with_no_initrd() -> Result<()> {
+    assert_payload_verification_eq(
+        &fs::read(TEST_IMG_WITH_PROP_DESC_PATH)?,
+        /*initrd=*/ None,
+        &load_trusted_public_key()?,
+        Err(AvbSlotVerifyError::InvalidMetadata),
+    )
+}
+
+#[test]
+fn payload_expecting_initrd_fails_verification_with_no_initrd() -> Result<()> {
+    assert_payload_verification_eq(
+        &load_latest_signed_kernel()?,
+        /*initrd=*/ None,
+        &load_trusted_public_key()?,
+        Err(AvbSlotVerifyError::InvalidMetadata),
+    )
+}
+
+#[test]
+fn payload_with_empty_public_key_fails_verification() -> Result<()> {
+    assert_payload_verification_with_initrd_eq(
+        &load_latest_signed_kernel()?,
+        &load_latest_initrd_normal()?,
+        /*trusted_public_key=*/ &[0u8; 0],
+        Err(AvbSlotVerifyError::PublicKeyRejected),
+    )
+}
+
+#[test]
+fn payload_with_an_invalid_public_key_fails_verification() -> Result<()> {
+    assert_payload_verification_with_initrd_eq(
+        &load_latest_signed_kernel()?,
+        &load_latest_initrd_normal()?,
+        /*trusted_public_key=*/ &[0u8; 512],
+        Err(AvbSlotVerifyError::PublicKeyRejected),
+    )
+}
+
+#[test]
+fn payload_with_a_different_valid_public_key_fails_verification() -> Result<()> {
+    assert_payload_verification_with_initrd_eq(
+        &load_latest_signed_kernel()?,
+        &load_latest_initrd_normal()?,
+        &fs::read(PUBLIC_KEY_RSA2048_PATH)?,
+        Err(AvbSlotVerifyError::PublicKeyRejected),
+    )
+}
+
+#[test]
+fn payload_with_an_invalid_initrd_fails_verification() -> Result<()> {
+    assert_payload_verification_with_initrd_eq(
+        &load_latest_signed_kernel()?,
+        /*initrd=*/ &fs::read(UNSIGNED_TEST_IMG_PATH)?,
+        &load_trusted_public_key()?,
+        Err(AvbSlotVerifyError::Verification),
+    )
+}
+
+#[test]
+fn unsigned_kernel_fails_verification() -> Result<()> {
+    assert_payload_verification_with_initrd_eq(
+        &fs::read(UNSIGNED_TEST_IMG_PATH)?,
+        &load_latest_initrd_normal()?,
+        &load_trusted_public_key()?,
+        Err(AvbSlotVerifyError::Io),
+    )
+}
+
+#[test]
+fn tampered_kernel_fails_verification() -> Result<()> {
+    let mut kernel = load_latest_signed_kernel()?;
+    kernel[1] = !kernel[1]; // Flip the bits
+
+    assert_payload_verification_with_initrd_eq(
+        &kernel,
+        &load_latest_initrd_normal()?,
+        &load_trusted_public_key()?,
+        Err(AvbSlotVerifyError::Verification),
+    )
+}
+
+#[test]
+fn kernel_footer_with_vbmeta_offset_overwritten_fails_verification() -> Result<()> {
+    // Arrange.
+    let mut kernel = load_latest_signed_kernel()?;
+    let total_len = kernel.len() as u64;
+    let footer = extract_avb_footer(&kernel)?;
+    assert!(footer.vbmeta_offset < total_len);
+    let vbmeta_offset_addr = ptr::addr_of!(footer.vbmeta_offset) as *const u8;
+    // SAFETY: It is safe as both raw pointers `vbmeta_offset_addr` and `footer` are not null.
+    let vbmeta_offset_start =
+        unsafe { vbmeta_offset_addr.offset_from(ptr::addr_of!(footer) as *const u8) };
+    let footer_start = kernel.len() - size_of::<AvbFooter>();
+    let vbmeta_offset_start = footer_start + usize::try_from(vbmeta_offset_start)?;
+
+    let wrong_offsets = [total_len, u64::MAX];
+    for &wrong_offset in wrong_offsets.iter() {
+        // Act.
+        kernel[vbmeta_offset_start..(vbmeta_offset_start + size_of::<u64>())]
+            .copy_from_slice(&wrong_offset.to_be_bytes());
+
+        // Assert.
+        let footer = extract_avb_footer(&kernel)?;
+        // footer is unaligned; copy vbmeta_offset to local variable
+        let vbmeta_offset = footer.vbmeta_offset;
+        assert_eq!(wrong_offset, vbmeta_offset);
+        assert_payload_verification_with_initrd_eq(
+            &kernel,
+            &load_latest_initrd_normal()?,
+            &load_trusted_public_key()?,
+            Err(AvbSlotVerifyError::Io),
+        )?;
+    }
+    Ok(())
+}
+
+#[test]
+fn tampered_kernel_footer_fails_verification() -> Result<()> {
+    let mut kernel = load_latest_signed_kernel()?;
+    let avb_footer_index = kernel.len() - size_of::<AvbFooter>() + RANDOM_FOOTER_POS;
+    kernel[avb_footer_index] = !kernel[avb_footer_index];
+
+    assert_payload_verification_with_initrd_eq(
+        &kernel,
+        &load_latest_initrd_normal()?,
+        &load_trusted_public_key()?,
+        Err(AvbSlotVerifyError::InvalidMetadata),
+    )
+}
+
+#[test]
+fn extended_initrd_fails_verification() -> Result<()> {
+    let mut initrd = load_latest_initrd_normal()?;
+    initrd.extend(b"androidboot.vbmeta.digest=1111");
+
+    assert_payload_verification_with_initrd_eq(
+        &load_latest_signed_kernel()?,
+        &initrd,
+        &load_trusted_public_key()?,
+        Err(AvbSlotVerifyError::Verification),
+    )
+}
+
+#[test]
+fn tampered_vbmeta_fails_verification() -> Result<()> {
+    let mut kernel = load_latest_signed_kernel()?;
+    let footer = extract_avb_footer(&kernel)?;
+    let vbmeta_index: usize = (footer.vbmeta_offset + 1).try_into()?;
+
+    kernel[vbmeta_index] = !kernel[vbmeta_index]; // Flip the bits
+
+    assert_payload_verification_with_initrd_eq(
+        &kernel,
+        &load_latest_initrd_normal()?,
+        &load_trusted_public_key()?,
+        Err(AvbSlotVerifyError::InvalidMetadata),
+    )
+}
+
+#[test]
+fn vbmeta_with_public_key_overwritten_fails_verification() -> Result<()> {
+    let mut kernel = load_latest_signed_kernel()?;
+    let footer = extract_avb_footer(&kernel)?;
+    let vbmeta_header = extract_vbmeta_header(&kernel, &footer)?;
+    let public_key_offset = footer.vbmeta_offset as usize
+        + size_of::<AvbVBMetaImageHeader>()
+        + vbmeta_header.authentication_data_block_size as usize
+        + vbmeta_header.public_key_offset as usize;
+    let public_key_size: usize = vbmeta_header.public_key_size.try_into()?;
+    let empty_public_key = vec![0u8; public_key_size];
+
+    kernel[public_key_offset..(public_key_offset + public_key_size)]
+        .copy_from_slice(&empty_public_key);
+
+    assert_payload_verification_with_initrd_eq(
+        &kernel,
+        &load_latest_initrd_normal()?,
+        &empty_public_key,
+        Err(AvbSlotVerifyError::Verification),
+    )?;
+    assert_payload_verification_with_initrd_eq(
+        &kernel,
+        &load_latest_initrd_normal()?,
+        &load_trusted_public_key()?,
+        Err(AvbSlotVerifyError::Verification),
+    )
+}
+
+#[test]
+fn vbmeta_with_verification_flag_disabled_fails_verification() -> Result<()> {
+    // From external/avb/libavb/avb_vbmeta_image.h
+    const AVB_VBMETA_IMAGE_FLAGS_VERIFICATION_DISABLED: u32 = 2;
+
+    // Arrange.
+    let mut kernel = load_latest_signed_kernel()?;
+    let footer = extract_avb_footer(&kernel)?;
+    let vbmeta_header = extract_vbmeta_header(&kernel, &footer)?;
+
+    // vbmeta_header is unaligned; copy flags to local variable
+    let vbmeta_header_flags = vbmeta_header.flags;
+    assert_eq!(0, vbmeta_header_flags, "The disable flag should not be set in the latest kernel.");
+    let flags_addr = ptr::addr_of!(vbmeta_header.flags) as *const u8;
+    // SAFETY: It is safe as both raw pointers `flags_addr` and `vbmeta_header` are not null.
+    let flags_offset = unsafe { flags_addr.offset_from(ptr::addr_of!(vbmeta_header) as *const u8) };
+    let flags_offset = usize::try_from(footer.vbmeta_offset)? + usize::try_from(flags_offset)?;
+
+    // Act.
+    kernel[flags_offset..(flags_offset + size_of::<u32>())]
+        .copy_from_slice(&AVB_VBMETA_IMAGE_FLAGS_VERIFICATION_DISABLED.to_be_bytes());
+
+    // Assert.
+    let vbmeta_header = extract_vbmeta_header(&kernel, &footer)?;
+    // vbmeta_header is unaligned; copy flags to local variable
+    let vbmeta_header_flags = vbmeta_header.flags;
+    assert_eq!(
+        AVB_VBMETA_IMAGE_FLAGS_VERIFICATION_DISABLED, vbmeta_header_flags,
+        "VBMeta verification flag should be disabled now."
+    );
+    assert_payload_verification_with_initrd_eq(
+        &kernel,
+        &load_latest_initrd_normal()?,
+        &load_trusted_public_key()?,
+        Err(AvbSlotVerifyError::Verification),
+    )
+}
diff --git a/pvmfw/avb/tests/utils.rs b/pvmfw/avb/tests/utils.rs
new file mode 100644
index 0000000..0a2eac6
--- /dev/null
+++ b/pvmfw/avb/tests/utils.rs
@@ -0,0 +1,97 @@
+/*
+ * Copyright (C) 2023 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.
+ */
+
+//! Utility functions used by API tests.
+
+use anyhow::Result;
+use avb_bindgen::{
+    avb_footer_validate_and_byteswap, avb_vbmeta_image_header_to_host_byte_order, AvbFooter,
+    AvbVBMetaImageHeader,
+};
+use pvmfw_avb::{verify_payload, AvbSlotVerifyError, DebugLevel};
+use std::{
+    fs,
+    mem::{size_of, transmute, MaybeUninit},
+};
+
+const MICRODROID_KERNEL_IMG_PATH: &str = "microdroid_kernel";
+const INITRD_NORMAL_IMG_PATH: &str = "microdroid_initrd_normal.img";
+const INITRD_DEBUG_IMG_PATH: &str = "microdroid_initrd_debuggable.img";
+const PUBLIC_KEY_RSA4096_PATH: &str = "data/testkey_rsa4096_pub.bin";
+
+pub const PUBLIC_KEY_RSA2048_PATH: &str = "data/testkey_rsa2048_pub.bin";
+
+pub fn assert_payload_verification_with_initrd_eq(
+    kernel: &[u8],
+    initrd: &[u8],
+    trusted_public_key: &[u8],
+    expected_result: Result<DebugLevel, AvbSlotVerifyError>,
+) -> Result<()> {
+    assert_payload_verification_eq(kernel, Some(initrd), trusted_public_key, expected_result)
+}
+
+pub fn assert_payload_verification_eq(
+    kernel: &[u8],
+    initrd: Option<&[u8]>,
+    trusted_public_key: &[u8],
+    expected_result: Result<DebugLevel, AvbSlotVerifyError>,
+) -> Result<()> {
+    assert_eq!(expected_result, verify_payload(kernel, initrd, trusted_public_key));
+    Ok(())
+}
+
+pub fn load_latest_signed_kernel() -> Result<Vec<u8>> {
+    Ok(fs::read(MICRODROID_KERNEL_IMG_PATH)?)
+}
+
+pub fn load_latest_initrd_normal() -> Result<Vec<u8>> {
+    Ok(fs::read(INITRD_NORMAL_IMG_PATH)?)
+}
+
+pub fn load_latest_initrd_debug() -> Result<Vec<u8>> {
+    Ok(fs::read(INITRD_DEBUG_IMG_PATH)?)
+}
+
+pub fn load_trusted_public_key() -> Result<Vec<u8>> {
+    Ok(fs::read(PUBLIC_KEY_RSA4096_PATH)?)
+}
+
+pub fn extract_avb_footer(kernel: &[u8]) -> Result<AvbFooter> {
+    let footer_start = kernel.len() - size_of::<AvbFooter>();
+    // SAFETY: The slice is the same size as the struct which only contains simple data types.
+    let mut footer = unsafe {
+        transmute::<[u8; size_of::<AvbFooter>()], AvbFooter>(kernel[footer_start..].try_into()?)
+    };
+    // SAFETY: The function updates the struct in-place.
+    unsafe {
+        avb_footer_validate_and_byteswap(&footer, &mut footer);
+    }
+    Ok(footer)
+}
+
+pub fn extract_vbmeta_header(kernel: &[u8], footer: &AvbFooter) -> Result<AvbVBMetaImageHeader> {
+    let vbmeta_offset: usize = footer.vbmeta_offset.try_into()?;
+    let vbmeta_size: usize = footer.vbmeta_size.try_into()?;
+    let vbmeta_src = &kernel[vbmeta_offset..(vbmeta_offset + vbmeta_size)];
+    // SAFETY: The latest kernel has a valid VBMeta header at the position specified in footer.
+    let vbmeta_header = unsafe {
+        let mut header = MaybeUninit::uninit();
+        let src = vbmeta_src.as_ptr() as *const _ as *const AvbVBMetaImageHeader;
+        avb_vbmeta_image_header_to_host_byte_order(src, header.as_mut_ptr());
+        header.assume_init()
+    };
+    Ok(vbmeta_header)
+}
diff --git a/pvmfw/src/entry.rs b/pvmfw/src/entry.rs
index bfcb423..4f30902 100644
--- a/pvmfw/src/entry.rs
+++ b/pvmfw/src/entry.rs
@@ -178,6 +178,37 @@
     }
 }
 
+/// Applies the debug policy device tree overlay to the pVM DT.
+///
+/// # Safety
+///
+/// When an error is returned by this function, the input `Fdt` should be discarded as it may have
+/// have been partially corrupted during the overlay application process.
+unsafe fn apply_debug_policy(
+    fdt: &mut libfdt::Fdt,
+    debug_policy: &mut [u8],
+) -> Result<(), RebootReason> {
+    let overlay = libfdt::Fdt::from_mut_slice(debug_policy).map_err(|e| {
+        error!("Failed to load the debug policy overlay: {e}");
+        RebootReason::InvalidConfig
+    })?;
+
+    fdt.unpack().map_err(|e| {
+        error!("Failed to unpack DT for debug policy: {e}");
+        RebootReason::InternalError
+    })?;
+
+    let fdt = fdt.apply_overlay(overlay).map_err(|e| {
+        error!("Failed to apply the debug policy overlay: {e}");
+        RebootReason::InvalidConfig
+    })?;
+
+    fdt.pack().map_err(|e| {
+        error!("Failed to re-pack DT after debug policy: {e}");
+        RebootReason::InternalError
+    })
+}
+
 /// Sets up the environment for main() and wraps its result for start().
 ///
 /// Provide the abstractions necessary for start() to abort the pVM boot and for main() to run with
@@ -252,6 +283,11 @@
     helpers::flushed_zeroize(bcc_slice);
     helpers::flush(slices.fdt.as_slice());
 
+    if let Some(debug_policy) = appended.get_debug_policy() {
+        // SAFETY - As we `?` the result, there is no risk of re-using a bad `slices.fdt`.
+        unsafe { apply_debug_policy(slices.fdt, debug_policy) }?;
+    }
+
     info!("Expecting a bug making MMIO_GUARD_UNMAP return NOT_SUPPORTED on success");
     memory.mmio_unmap_all().map_err(|e| {
         error!("Failed to unshare MMIO ranges: {e}");
diff --git a/pvmfw/src/heap.rs b/pvmfw/src/heap.rs
index e412f69..435a6ff 100644
--- a/pvmfw/src/heap.rs
+++ b/pvmfw/src/heap.rs
@@ -30,7 +30,9 @@
 #[global_allocator]
 static HEAP_ALLOCATOR: LockedHeap<32> = LockedHeap::<32>::new();
 
-static mut HEAP: [u8; 65536] = [0; 65536];
+/// 128 KiB
+const HEAP_SIZE: usize = 0x20000;
+static mut HEAP: [u8; HEAP_SIZE] = [0; HEAP_SIZE];
 
 pub unsafe fn init() {
     HEAP_ALLOCATOR.lock().init(HEAP.as_mut_ptr() as usize, HEAP.len());
diff --git a/pvmfw/src/main.rs b/pvmfw/src/main.rs
index d0fdd5a..eabdfe8 100644
--- a/pvmfw/src/main.rs
+++ b/pvmfw/src/main.rs
@@ -17,11 +17,9 @@
 #![no_main]
 #![no_std]
 #![feature(default_alloc_error_handler)]
-#![feature(ptr_const_cast)] // Stabilized in 1.65.0
 
 extern crate alloc;
 
-mod avb;
 mod config;
 mod dice;
 mod entry;
@@ -33,26 +31,26 @@
 mod memory;
 mod mmio_guard;
 mod mmu;
-mod pci;
 mod smccc;
+mod virtio;
 
 use alloc::boxed::Box;
 
 use crate::{
-    avb::PUBLIC_KEY,
     dice::derive_next_bcc,
     entry::RebootReason,
     fdt::add_dice_node,
     helpers::flush,
     helpers::GUEST_PAGE_SIZE,
     memory::MemoryTracker,
-    pci::{find_virtio_devices, map_mmio},
+    virtio::pci::{self, find_virtio_devices},
 };
 use ::dice::bcc;
 use fdtpci::{PciError, PciInfo};
 use libfdt::Fdt;
 use log::{debug, error, info, trace};
 use pvmfw_avb::verify_payload;
+use pvmfw_embedded_key::PUBLIC_KEY;
 
 const NEXT_BCC_SIZE: usize = GUEST_PAGE_SIZE;
 
@@ -77,10 +75,7 @@
     // Set up PCI bus for VirtIO devices.
     let pci_info = PciInfo::from_fdt(fdt).map_err(handle_pci_error)?;
     debug!("PCI: {:#x?}", pci_info);
-    map_mmio(&pci_info, memory)?;
-    // Safety: This is the only place where we call make_pci_root, and this main function is only
-    // called once.
-    let mut pci_root = unsafe { pci_info.make_pci_root() };
+    let mut pci_root = pci::initialise(pci_info, memory)?;
     find_virtio_devices(&mut pci_root).map_err(handle_pci_error)?;
 
     verify_payload(signed_kernel, ramdisk, PUBLIC_KEY).map_err(|e| {
diff --git a/pvmfw/src/memory.rs b/pvmfw/src/memory.rs
index 5e4874f..7eecb97 100644
--- a/pvmfw/src/memory.rs
+++ b/pvmfw/src/memory.rs
@@ -14,16 +14,23 @@
 
 //! Low-level allocation and tracking of main memory.
 
-use crate::helpers::{self, align_down, page_4kb_of, SIZE_4KB};
+#![deny(unsafe_op_in_unsafe_fn)]
+
+use crate::helpers::{self, align_down, align_up, page_4kb_of, SIZE_4KB};
 use crate::hvc::{hyp_meminfo, mem_share, mem_unshare};
 use crate::mmio_guard;
 use crate::mmu;
 use crate::smccc;
+use alloc::alloc::alloc_zeroed;
+use alloc::alloc::dealloc;
+use alloc::alloc::handle_alloc_error;
+use core::alloc::Layout;
 use core::cmp::max;
 use core::cmp::min;
 use core::fmt;
 use core::num::NonZeroUsize;
 use core::ops::Range;
+use core::ptr::NonNull;
 use core::result;
 use log::error;
 use tinyvec::ArrayVec;
@@ -272,9 +279,7 @@
 /// Gives the KVM host read, write and execute permissions on the given memory range. If the range
 /// is not aligned with the memory protection granule then it will be extended on either end to
 /// align.
-#[allow(unused)]
-pub fn share_range(range: &MemoryRange) -> smccc::Result<()> {
-    let granule = hyp_meminfo()? as usize;
+fn share_range(range: &MemoryRange, granule: usize) -> smccc::Result<()> {
     for base in (align_down(range.start, granule)
         .expect("Memory protection granule was not a power of two")..range.end)
         .step_by(granule)
@@ -287,9 +292,7 @@
 /// Removes permission from the KVM host to access the given memory range which was previously
 /// shared. If the range is not aligned with the memory protection granule then it will be extended
 /// on either end to align.
-#[allow(unused)]
-pub fn unshare_range(range: &MemoryRange) -> smccc::Result<()> {
-    let granule = hyp_meminfo()? as usize;
+fn unshare_range(range: &MemoryRange, granule: usize) -> smccc::Result<()> {
     for base in (align_down(range.start, granule)
         .expect("Memory protection granule was not a power of two")..range.end)
         .step_by(granule)
@@ -299,7 +302,85 @@
     Ok(())
 }
 
+/// Allocates a memory range of at least the given size from the global allocator, and shares it
+/// with the host. Returns a pointer to the buffer.
+///
+/// It will be aligned to the memory sharing granule size supported by the hypervisor.
+pub fn alloc_shared(size: usize) -> smccc::Result<NonNull<u8>> {
+    let layout = shared_buffer_layout(size)?;
+    let granule = layout.align();
+
+    // Safe because `shared_buffer_layout` panics if the size is 0, so the layout must have a
+    // non-zero size.
+    let buffer = unsafe { alloc_zeroed(layout) };
+
+    // TODO: Use let-else once we have Rust 1.65 in AOSP.
+    let buffer = if let Some(buffer) = NonNull::new(buffer) {
+        buffer
+    } else {
+        handle_alloc_error(layout);
+    };
+
+    let paddr = virt_to_phys(buffer);
+    // If share_range fails then we will leak the allocation, but that seems better than having it
+    // be reused while maybe still partially shared with the host.
+    share_range(&(paddr..paddr + layout.size()), granule)?;
+
+    Ok(buffer)
+}
+
+/// Unshares and deallocates a memory range which was previously allocated by `alloc_shared`.
+///
+/// The size passed in must be the size passed to the original `alloc_shared` call.
+///
+/// # Safety
+///
+/// The memory must have been allocated by `alloc_shared` with the same size, and not yet
+/// deallocated.
+pub unsafe fn dealloc_shared(vaddr: NonNull<u8>, size: usize) -> smccc::Result<()> {
+    let layout = shared_buffer_layout(size)?;
+    let granule = layout.align();
+
+    let paddr = virt_to_phys(vaddr);
+    unshare_range(&(paddr..paddr + layout.size()), granule)?;
+    // Safe because the memory was allocated by `alloc_shared` above using the same allocator, and
+    // the layout is the same as was used then.
+    unsafe { dealloc(vaddr.as_ptr(), layout) };
+
+    Ok(())
+}
+
+/// Returns the layout to use for allocating a buffer of at least the given size shared with the
+/// host.
+///
+/// It will be aligned to the memory sharing granule size supported by the hypervisor.
+///
+/// Panics if `size` is 0.
+fn shared_buffer_layout(size: usize) -> smccc::Result<Layout> {
+    assert_ne!(size, 0);
+    let granule = hyp_meminfo()? as usize;
+    let allocated_size =
+        align_up(size, granule).expect("Memory protection granule was not a power of two");
+    Ok(Layout::from_size_align(allocated_size, granule).unwrap())
+}
+
 /// Returns an iterator which yields the base address of each 4 KiB page within the given range.
 fn page_iterator(range: &MemoryRange) -> impl Iterator<Item = usize> {
     (page_4kb_of(range.start)..range.end).step_by(SIZE_4KB)
 }
+
+/// Returns the intermediate physical address corresponding to the given virtual address.
+///
+/// As we use identity mapping for everything, this is just a cast, but it's useful to use it to be
+/// explicit about where we are converting from virtual to physical address.
+pub fn virt_to_phys(vaddr: NonNull<u8>) -> usize {
+    vaddr.as_ptr() as _
+}
+
+/// Returns a pointer for the virtual address corresponding to the given non-zero intermediate
+/// physical address.
+///
+/// Panics if `paddr` is 0.
+pub fn phys_to_virt(paddr: usize) -> NonNull<u8> {
+    NonNull::new(paddr as _).unwrap()
+}
diff --git a/pvmfw/src/pci.rs b/pvmfw/src/pci.rs
deleted file mode 100644
index 2b81772..0000000
--- a/pvmfw/src/pci.rs
+++ /dev/null
@@ -1,53 +0,0 @@
-// Copyright 2022, 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.
-
-//! Functions to scan the PCI bus for VirtIO devices.
-
-use crate::{entry::RebootReason, memory::MemoryTracker};
-use fdtpci::{PciError, PciInfo};
-use log::{debug, error};
-use virtio_drivers::transport::pci::{bus::PciRoot, virtio_device_type};
-
-/// Maps the CAM and BAR range in the page table and MMIO guard.
-pub fn map_mmio(pci_info: &PciInfo, memory: &mut MemoryTracker) -> Result<(), RebootReason> {
-    memory.map_mmio_range(pci_info.cam_range.clone()).map_err(|e| {
-        error!("Failed to map PCI CAM: {}", e);
-        RebootReason::InternalError
-    })?;
-
-    memory
-        .map_mmio_range(pci_info.bar_range.start as usize..pci_info.bar_range.end as usize)
-        .map_err(|e| {
-            error!("Failed to map PCI MMIO range: {}", e);
-            RebootReason::InternalError
-        })?;
-
-    Ok(())
-}
-
-/// Finds VirtIO PCI devices.
-pub fn find_virtio_devices(pci_root: &mut PciRoot) -> Result<(), PciError> {
-    for (device_function, info) in pci_root.enumerate_bus(0) {
-        let (status, command) = pci_root.get_status_command(device_function);
-        debug!(
-            "Found PCI device {} at {}, status {:?} command {:?}",
-            info, device_function, status, command
-        );
-        if let Some(virtio_type) = virtio_device_type(&info) {
-            debug!("  VirtIO {:?}", virtio_type);
-        }
-    }
-
-    Ok(())
-}
diff --git a/pvmfw/src/avb.rs b/pvmfw/src/virtio.rs
similarity index 89%
rename from pvmfw/src/avb.rs
rename to pvmfw/src/virtio.rs
index 1abe73f..df916bc 100644
--- a/pvmfw/src/avb.rs
+++ b/pvmfw/src/virtio.rs
@@ -12,6 +12,7 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-//! Image verification.
+//! Modules for working with VirtIO devices.
 
-pub use pvmfw_embedded_key::PUBLIC_KEY;
+mod hal;
+pub mod pci;
diff --git a/pvmfw/src/virtio/hal.rs b/pvmfw/src/virtio/hal.rs
new file mode 100644
index 0000000..5f70b33
--- /dev/null
+++ b/pvmfw/src/virtio/hal.rs
@@ -0,0 +1,93 @@
+use super::pci::PCI_INFO;
+use crate::memory::{alloc_shared, dealloc_shared, phys_to_virt, virt_to_phys};
+use core::{
+    ops::Range,
+    ptr::{copy_nonoverlapping, NonNull},
+};
+use log::debug;
+use virtio_drivers::{BufferDirection, Hal, PhysAddr, PAGE_SIZE};
+
+pub struct HalImpl;
+
+impl Hal for HalImpl {
+    fn dma_alloc(pages: usize, _direction: BufferDirection) -> (PhysAddr, NonNull<u8>) {
+        debug!("dma_alloc: pages={}", pages);
+        let size = pages * PAGE_SIZE;
+        let vaddr =
+            alloc_shared(size).expect("Failed to allocate and share VirtIO DMA range with host");
+        let paddr = virt_to_phys(vaddr);
+        (paddr, vaddr)
+    }
+
+    fn dma_dealloc(paddr: PhysAddr, vaddr: NonNull<u8>, pages: usize) -> i32 {
+        debug!("dma_dealloc: paddr={:#x}, pages={}", paddr, pages);
+        let size = pages * PAGE_SIZE;
+        // Safe because the memory was allocated by `dma_alloc` above using the same allocator, and
+        // the layout is the same as was used then.
+        unsafe {
+            dealloc_shared(vaddr, size).expect("Failed to unshare VirtIO DMA range with host");
+        }
+        0
+    }
+
+    fn mmio_phys_to_virt(paddr: PhysAddr, size: usize) -> NonNull<u8> {
+        let pci_info = PCI_INFO.get().expect("VirtIO HAL used before PCI_INFO was initialised");
+        // Check that the region is within the PCI MMIO range that we read from the device tree. If
+        // not, the host is probably trying to do something malicious.
+        if !contains_range(
+            &pci_info.bar_range,
+            &(paddr.try_into().expect("PCI MMIO region start was outside of 32-bit address space")
+                ..paddr
+                    .checked_add(size)
+                    .expect("PCI MMIO region end overflowed")
+                    .try_into()
+                    .expect("PCI MMIO region end was outside of 32-bit address space")),
+        ) {
+            panic!("PCI MMIO region was outside of expected BAR range.");
+        }
+        phys_to_virt(paddr)
+    }
+
+    fn share(buffer: NonNull<[u8]>, direction: BufferDirection) -> PhysAddr {
+        let size = buffer.len();
+
+        // TODO: Copy to a pre-shared region rather than allocating and sharing each time.
+        // Allocate a range of pages, copy the buffer if necessary, and share the new range instead.
+        let copy =
+            alloc_shared(size).expect("Failed to allocate and share VirtIO buffer with host");
+        if direction == BufferDirection::DriverToDevice {
+            unsafe {
+                copy_nonoverlapping(buffer.as_ptr() as *mut u8, copy.as_ptr(), size);
+            }
+        }
+        virt_to_phys(copy)
+    }
+
+    fn unshare(paddr: PhysAddr, buffer: NonNull<[u8]>, direction: BufferDirection) {
+        let vaddr = phys_to_virt(paddr);
+        let size = buffer.len();
+        if direction == BufferDirection::DeviceToDriver {
+            debug!(
+                "Copying VirtIO buffer back from {:#x} to {:#x}.",
+                paddr,
+                buffer.as_ptr() as *mut u8 as usize
+            );
+            unsafe {
+                copy_nonoverlapping(vaddr.as_ptr(), buffer.as_ptr() as *mut u8, size);
+            }
+        }
+
+        // Unshare and deallocate the shared copy of the buffer.
+        debug!("Unsharing VirtIO buffer {:#x}", paddr);
+        // Safe because the memory was allocated by `share` using `alloc_shared`, and the size is
+        // the same as was used then.
+        unsafe {
+            dealloc_shared(vaddr, size).expect("Failed to unshare VirtIO buffer with host");
+        }
+    }
+}
+
+/// Returns true if `inner` is entirely contained within `outer`.
+fn contains_range(outer: &Range<u32>, inner: &Range<u32>) -> bool {
+    inner.start >= outer.start && inner.end <= outer.end
+}
diff --git a/pvmfw/src/virtio/pci.rs b/pvmfw/src/virtio/pci.rs
new file mode 100644
index 0000000..d3b3124
--- /dev/null
+++ b/pvmfw/src/virtio/pci.rs
@@ -0,0 +1,96 @@
+// Copyright 2022, 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.
+
+//! Functions to scan the PCI bus for VirtIO devices.
+
+use super::hal::HalImpl;
+use crate::{entry::RebootReason, memory::MemoryTracker};
+use alloc::boxed::Box;
+use fdtpci::{PciError, PciInfo};
+use log::{debug, error, info};
+use once_cell::race::OnceBox;
+use virtio_drivers::{
+    device::blk::VirtIOBlk,
+    transport::{
+        pci::{bus::PciRoot, virtio_device_type, PciTransport},
+        DeviceType, Transport,
+    },
+};
+
+pub(super) static PCI_INFO: OnceBox<PciInfo> = OnceBox::new();
+
+/// Prepares to use VirtIO PCI devices.
+///
+/// In particular:
+///
+/// 1. Maps the PCI CAM and BAR range in the page table and MMIO guard.
+/// 2. Stores the `PciInfo` for the VirtIO HAL to use later.
+/// 3. Creates and returns a `PciRoot`.
+///
+/// This must only be called once; it will panic if it is called a second time.
+pub fn initialise(pci_info: PciInfo, memory: &mut MemoryTracker) -> Result<PciRoot, RebootReason> {
+    map_mmio(&pci_info, memory)?;
+
+    PCI_INFO.set(Box::new(pci_info.clone())).expect("Tried to set PCI_INFO a second time");
+
+    // Safety: This is the only place where we call make_pci_root, and `PCI_INFO.set` above will
+    // panic if it is called a second time.
+    Ok(unsafe { pci_info.make_pci_root() })
+}
+
+/// Maps the CAM and BAR range in the page table and MMIO guard.
+fn map_mmio(pci_info: &PciInfo, memory: &mut MemoryTracker) -> Result<(), RebootReason> {
+    memory.map_mmio_range(pci_info.cam_range.clone()).map_err(|e| {
+        error!("Failed to map PCI CAM: {}", e);
+        RebootReason::InternalError
+    })?;
+
+    memory
+        .map_mmio_range(pci_info.bar_range.start as usize..pci_info.bar_range.end as usize)
+        .map_err(|e| {
+            error!("Failed to map PCI MMIO range: {}", e);
+            RebootReason::InternalError
+        })?;
+
+    Ok(())
+}
+
+/// Finds VirtIO PCI devices.
+pub fn find_virtio_devices(pci_root: &mut PciRoot) -> Result<(), PciError> {
+    for (device_function, info) in pci_root.enumerate_bus(0) {
+        let (status, command) = pci_root.get_status_command(device_function);
+        debug!(
+            "Found PCI device {} at {}, status {:?} command {:?}",
+            info, device_function, status, command
+        );
+        if let Some(virtio_type) = virtio_device_type(&info) {
+            debug!("  VirtIO {:?}", virtio_type);
+            let mut transport = PciTransport::new::<HalImpl>(pci_root, device_function).unwrap();
+            info!(
+                "Detected virtio PCI device with device type {:?}, features {:#018x}",
+                transport.device_type(),
+                transport.read_device_features(),
+            );
+            if virtio_type == DeviceType::Block {
+                let mut blk =
+                    VirtIOBlk::<HalImpl, _>::new(transport).expect("failed to create blk driver");
+                info!("Found {} KiB block device.", blk.capacity() * 512 / 1024);
+                let mut data = [0; 512];
+                blk.read_block(0, &mut data).expect("Failed to read block device");
+            }
+        }
+    }
+
+    Ok(())
+}
diff --git a/tests/benchmark/src/java/com/android/microdroid/benchmark/MicrodroidBenchmarks.java b/tests/benchmark/src/java/com/android/microdroid/benchmark/MicrodroidBenchmarks.java
index 40114fd..f17000a 100644
--- a/tests/benchmark/src/java/com/android/microdroid/benchmark/MicrodroidBenchmarks.java
+++ b/tests/benchmark/src/java/com/android/microdroid/benchmark/MicrodroidBenchmarks.java
@@ -60,6 +60,7 @@
     private static final String TAG = "MicrodroidBenchmarks";
     private static final String METRIC_NAME_PREFIX = getMetricPrefix() + "microdroid/";
     private static final int IO_TEST_TRIAL_COUNT = 5;
+    private static final long ONE_MEBI = 1024 * 1024;
 
     @Rule public Timeout globalTimeout = Timeout.seconds(300);
 
@@ -95,7 +96,7 @@
                 newVmConfigBuilder()
                         .setPayloadBinaryName("MicrodroidIdleNativeLib.so")
                         .setDebugLevel(DEBUG_LEVEL_NONE)
-                        .setMemoryMib(mem)
+                        .setMemoryBytes(mem * ONE_MEBI)
                         .build();
 
         // returns true if succeeded at least once.
@@ -148,7 +149,7 @@
                     newVmConfigBuilder()
                             .setPayloadBinaryName("MicrodroidIdleNativeLib.so")
                             .setDebugLevel(DEBUG_LEVEL_NONE)
-                            .setMemoryMib(256)
+                            .setMemoryBytes(256 * ONE_MEBI)
                             .build();
             forceCreateNewVirtualMachine("test_vm_boot_time", normalConfig);
 
@@ -176,7 +177,7 @@
                         newVmConfigBuilder()
                                 .setPayloadBinaryName("MicrodroidIdleNativeLib.so")
                                 .setDebugLevel(DEBUG_LEVEL_NONE)
-                                .setMemoryMib(256)
+                                .setMemoryBytes(256 * ONE_MEBI)
                                 .setNumCpus(numCpus)
                                 .build();
                 forceCreateNewVirtualMachine("test_vm_boot_time_multicore", normalConfig);
@@ -212,7 +213,7 @@
                             .setPayloadBinaryName("MicrodroidIdleNativeLib.so")
                             .setDebugLevel(DEBUG_LEVEL_FULL)
                             .setVmOutputCaptured(true)
-                            .setMemoryMib(256)
+                            .setMemoryBytes(256 * ONE_MEBI)
                             .build();
             forceCreateNewVirtualMachine("test_vm_boot_time_debug", normalConfig);
 
@@ -397,7 +398,7 @@
                 newVmConfigBuilder()
                         .setPayloadConfigPath("assets/vm_config_io.json")
                         .setDebugLevel(DEBUG_LEVEL_NONE)
-                        .setMemoryMib(256)
+                        .setMemoryBytes(256 * ONE_MEBI)
                         .build();
         VirtualMachine vm = forceCreateNewVirtualMachine(vmName, config);
         MemoryUsageListener listener = new MemoryUsageListener(this::executeCommand);
@@ -469,7 +470,7 @@
                 newVmConfigBuilder()
                         .setPayloadConfigPath("assets/vm_config_io.json")
                         .setDebugLevel(DEBUG_LEVEL_NONE)
-                        .setMemoryMib(256)
+                        .setMemoryBytes(256 * ONE_MEBI)
                         .build();
         VirtualMachine vm = forceCreateNewVirtualMachine(vmName, config);
         MemoryReclaimListener listener = new MemoryReclaimListener(this::executeCommand);
diff --git a/tests/helper/src/java/com/android/microdroid/test/device/MicrodroidDeviceTestBase.java b/tests/helper/src/java/com/android/microdroid/test/device/MicrodroidDeviceTestBase.java
index e8a36ce..f1da43a 100644
--- a/tests/helper/src/java/com/android/microdroid/test/device/MicrodroidDeviceTestBase.java
+++ b/tests/helper/src/java/com/android/microdroid/test/device/MicrodroidDeviceTestBase.java
@@ -140,12 +140,6 @@
         }
     }
 
-    protected enum EncryptedStoreOperation {
-        NONE,
-        READ,
-        WRITE,
-    }
-
     public abstract static class VmEventListener implements VirtualMachineCallback {
         private ExecutorService mExecutorService = Executors.newSingleThreadExecutor();
         private OptionalLong mVcpuStartedNanoTime = OptionalLong.empty();
diff --git a/tests/hostside/Android.bp b/tests/hostside/Android.bp
index 7679c57..6e0cf5a 100644
--- a/tests/hostside/Android.bp
+++ b/tests/hostside/Android.bp
@@ -29,6 +29,7 @@
         // For re-sign test
         "avbtool",
         "img2simg",
+        "initrd_bootconfig",
         "lpmake",
         "lpunpack",
         "mk_payload",
diff --git a/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java b/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
index 730c7dd..0623ff2 100644
--- a/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
+++ b/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
@@ -55,7 +55,6 @@
 import org.json.JSONObject;
 import org.junit.After;
 import org.junit.Before;
-import org.junit.Ignore;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.rules.TestName;
@@ -75,6 +74,7 @@
 import java.util.Arrays;
 import java.util.List;
 import java.util.Map;
+import java.util.Optional;
 import java.util.concurrent.Callable;
 import java.util.concurrent.TimeUnit;
 import java.util.function.Function;
@@ -96,6 +96,8 @@
 
     private static final int BOOT_COMPLETE_TIMEOUT = 30000; // 30 seconds
 
+    private static final Pattern sCIDPattern = Pattern.compile("with CID (\\d+)");
+
     private static class VmInfo {
         final Process mProcess;
         final String mCid;
@@ -170,7 +172,11 @@
                 .isSuccess();
     }
 
-    private void resignVirtApex(File virtApexDir, File signingKey, Map<String, File> keyOverrides) {
+    private void resignVirtApex(
+            File virtApexDir,
+            File signingKey,
+            Map<String, File> keyOverrides,
+            boolean updateBootconfigs) {
         File signVirtApex = findTestFile("sign_virt_apex");
 
         RunUtil runUtil = new RunUtil();
@@ -181,6 +187,9 @@
 
         List<String> command = new ArrayList<>();
         command.add(signVirtApex.getAbsolutePath());
+        if (!updateBootconfigs) {
+            command.add("--do_not_update_bootconfigs");
+        }
         keyOverrides.forEach(
                 (filename, keyFile) ->
                         command.add("--key_override " + filename + "=" + keyFile.getPath()));
@@ -268,7 +277,11 @@
     }
 
     private VmInfo runMicrodroidWithResignedImages(
-            File key, Map<String, File> keyOverrides, boolean isProtected) throws Exception {
+            File key,
+            Map<String, File> keyOverrides,
+            boolean isProtected,
+            boolean updateBootconfigs)
+            throws Exception {
         CommandRunner android = new CommandRunner(getDevice());
 
         File virtApexDir = FileUtil.createTempDir("virt_apex");
@@ -281,7 +294,7 @@
         assertWithMessage("Failed to pull " + VIRT_APEX + "etc")
                 .that(getDevice().pullDir(VIRT_APEX + "etc", virtApexEtcDir)).isTrue();
 
-        resignVirtApex(virtApexDir, key, keyOverrides);
+        resignVirtApex(virtApexDir, key, keyOverrides, updateBootconfigs);
 
         // Push back re-signed virt APEX contents and updated microdroid.json
         getDevice().pushDir(virtApexDir, TEST_ROOT);
@@ -387,16 +400,23 @@
         return new VmInfo(process, extractCidFrom(pis));
     }
 
+    private static Optional<String> tryExtractCidFrom(String str) {
+        Matcher matcher = sCIDPattern.matcher(str);
+        if (matcher.find()) {
+            return Optional.of(matcher.group(1));
+        }
+        return Optional.empty();
+    }
+
     private static String extractCidFrom(InputStream input) throws IOException {
         String cid = null;
-        Pattern pattern = Pattern.compile("with CID (\\d+)");
         String line;
         try (BufferedReader out = new BufferedReader(new InputStreamReader(input))) {
             while ((line = out.readLine()) != null) {
                 CLog.i("VM output: " + line);
-                Matcher matcher = pattern.matcher(line);
-                if (matcher.find()) {
-                    cid = matcher.group(1);
+                Optional<String> result = tryExtractCidFrom(line);
+                if (result.isPresent()) {
+                    cid = result.get();
                     break;
                 }
             }
@@ -450,7 +470,8 @@
 
         // Act
         VmInfo vmInfo =
-                runMicrodroidWithResignedImages(key, /*keyOverrides=*/ Map.of(), protectedVm);
+                runMicrodroidWithResignedImages(
+                        key, /*keyOverrides=*/ Map.of(), protectedVm, /*updateBootconfigs=*/ true);
 
         // Assert
         vmInfo.mProcess.waitFor(5L, TimeUnit.SECONDS);
@@ -461,16 +482,15 @@
         vmInfo.mProcess.destroy();
     }
 
-    // TODO(b/245277660): Resigning the system/vendor image changes the vbmeta hash.
-    // So, unless vbmeta related bootconfigs are updated the following test will fail
     @Test
-    @Ignore("b/245277660")
     @CddTest(requirements = {"9.17/C-2-2", "9.17/C-2-6"})
     public void testBootSucceedsWhenNonProtectedVmStartsWithImagesSignedWithDifferentKey()
             throws Exception {
         File key = findTestFile("test.com.android.virt.pem");
         Map<String, File> keyOverrides = Map.of();
-        VmInfo vmInfo = runMicrodroidWithResignedImages(key, keyOverrides, /*isProtected=*/ false);
+        VmInfo vmInfo =
+                runMicrodroidWithResignedImages(
+                        key, keyOverrides, /*isProtected=*/ false, /*updateBootconfigs=*/ true);
         // Device online means that boot must have succeeded.
         adbConnectToMicrodroid(getDevice(), vmInfo.mCid);
         vmInfo.mProcess.destroy();
@@ -481,10 +501,10 @@
     public void testBootFailsWhenVbMetaDigestDoesNotMatchBootconfig() throws Exception {
         // Sign everything with key1 except vbmeta
         File key = findTestFile("test.com.android.virt.pem");
-        File key2 = findTestFile("test2.com.android.virt.pem");
-        Map<String, File> keyOverrides = Map.of("microdroid_vbmeta.img", key2);
         // To be able to stop it, it should be a daemon.
-        VmInfo vmInfo = runMicrodroidWithResignedImages(key, keyOverrides, /*isProtected=*/ false);
+        VmInfo vmInfo =
+                runMicrodroidWithResignedImages(
+                        key, Map.of(), /*isProtected=*/ false, /*updateBootconfigs=*/ false);
         // Wait so that init can print errors to console (time in cuttlefish >> in real device)
         assertThatEventually(
                 100000,
@@ -518,7 +538,7 @@
                 "-m",
                 "1",
                 "-e",
-                "'virtualizationservice::crosvm.*exited with status exit status:'");
+                "'virtualizationmanager::crosvm.*exited with status exit status:'");
 
         // Check that tombstone is received (from host logcat)
         String ramdumpRegex =
@@ -829,6 +849,64 @@
         assertThat(ret).contains("Payload binary name must not specify a path");
     }
 
+    @Test
+    @CddTest(requirements = {"9.17/C-2-2", "9.17/C-2-6"})
+    public void testAllVbmetaUseSHA256() throws Exception {
+        File virtApexDir = FileUtil.createTempDir("virt_apex");
+        // Pull the virt apex's etc/ directory (which contains images)
+        File virtApexEtcDir = new File(virtApexDir, "etc");
+        // We need only etc/ directory for images
+        assertWithMessage("Failed to mkdir " + virtApexEtcDir)
+                .that(virtApexEtcDir.mkdirs())
+                .isTrue();
+        assertWithMessage("Failed to pull " + VIRT_APEX + "etc")
+                .that(getDevice().pullDir(VIRT_APEX + "etc", virtApexEtcDir))
+                .isTrue();
+
+        checkHashAlgorithm(virtApexEtcDir);
+    }
+
+    private String avbInfo(String image_path) throws Exception {
+        File avbtool = findTestFile("avbtool");
+        List<String> command =
+                Arrays.asList(avbtool.getAbsolutePath(), "info_image", "--image", image_path);
+        CommandResult result =
+                new RunUtil().runTimedCmd(5000, "/bin/bash", "-c", String.join(" ", command));
+        String out = result.getStdout();
+        String err = result.getStderr();
+        assertWithMessage(
+                        "Command "
+                                + command
+                                + " failed."
+                                + ":\n\tout: "
+                                + out
+                                + "\n\terr: "
+                                + err
+                                + "\n")
+                .about(command_results())
+                .that(result)
+                .isSuccess();
+        return out;
+    }
+
+    private void checkHashAlgorithm(File virtApexEtcDir) throws Exception {
+        List<String> images =
+                Arrays.asList(
+                        // kernel image (contains descriptors from initrd(s) as well)
+                        "/fs/microdroid_kernel",
+                        // vbmeta partition (contains descriptors from vendor/system images)
+                        "/fs/microdroid_vbmeta.img");
+
+        for (String path : images) {
+            String info = avbInfo(virtApexEtcDir + path);
+            Pattern pattern = Pattern.compile("Hash Algorithm:[ ]*(sha1|sha256)");
+            Matcher m = pattern.matcher(info);
+            while (m.find()) {
+                assertThat(m.group(1)).isEqualTo("sha256");
+            }
+        }
+    }
+
     @Before
     public void setUp() throws Exception {
         testIfDeviceIsCapable(getDevice());
diff --git a/tests/testapk/Android.bp b/tests/testapk/Android.bp
index e3c9961..5f9b915 100644
--- a/tests/testapk/Android.bp
+++ b/tests/testapk/Android.bp
@@ -24,6 +24,7 @@
         "MicrodroidTestNativeLib",
         "MicrodroidIdleNativeLib",
         "MicrodroidEmptyNativeLib",
+        "MicrodroidExitNativeLib",
         "MicrodroidPrivateLinkingNativeLib",
     ],
     jni_uses_platform_apis: true,
@@ -73,6 +74,14 @@
     stl: "none",
 }
 
+// A payload that exits immediately on start
+cc_library_shared {
+    name: "MicrodroidExitNativeLib",
+    srcs: ["src/native/exitbinary.cpp"],
+    header_libs: ["vm_payload_headers"],
+    stl: "libc++_static",
+}
+
 // A payload which tries to link against libselinux, one of private libraries
 cc_library_shared {
     name: "MicrodroidPrivateLinkingNativeLib",
diff --git a/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java b/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
index 5c3be5f..c6915e5 100644
--- a/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
+++ b/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
@@ -31,6 +31,7 @@
 import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
 
 import android.content.Context;
+import android.content.ContextWrapper;
 import android.os.Build;
 import android.os.ParcelFileDescriptor;
 import android.os.ParcelFileDescriptor.AutoCloseInputStream;
@@ -50,6 +51,7 @@
 import com.android.microdroid.test.device.MicrodroidDeviceTestBase;
 import com.android.microdroid.testservice.ITestService;
 
+import com.google.common.base.Strings;
 import com.google.common.truth.BooleanSubject;
 
 import org.junit.After;
@@ -76,6 +78,8 @@
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.Paths;
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
 import java.util.Arrays;
 import java.util.List;
 import java.util.OptionalLong;
@@ -115,8 +119,10 @@
         revokePermission(VirtualMachine.USE_CUSTOM_VIRTUAL_MACHINE_PERMISSION);
     }
 
-    private static final int MIN_MEM_ARM64 = 150;
-    private static final int MIN_MEM_X86_64 = 196;
+    private static final long ONE_MEBI = 1024 * 1024;
+
+    private static final long MIN_MEM_ARM64 = 150 * ONE_MEBI;
+    private static final long MIN_MEM_X86_64 = 196 * ONE_MEBI;
     private static final String EXAMPLE_STRING = "Literally any string!! :)";
 
     @Test
@@ -127,12 +133,21 @@
         VirtualMachineConfig config =
                 newVmConfigBuilder()
                         .setPayloadBinaryName("MicrodroidTestNativeLib.so")
-                        .setMemoryMib(minMemoryRequired())
+                        .setMemoryBytes(minMemoryRequired())
                         .setDebugLevel(DEBUG_LEVEL_FULL)
                         .build();
         VirtualMachine vm = forceCreateNewVirtualMachine("test_vm", config);
 
-        TestResults testResults = runVmTestService(vm);
+        TestResults testResults =
+                runVmTestService(
+                        vm,
+                        (ts, tr) -> {
+                            tr.mAddInteger = ts.addInteger(123, 456);
+                            tr.mAppRunProp = ts.readProperty("debug.microdroid.app.run");
+                            tr.mSublibRunProp = ts.readProperty("debug.microdroid.app.sublib.run");
+                            tr.mApkContentsPath = ts.getApkContentsPath();
+                            tr.mEncryptedStoragePath = ts.getEncryptedStoragePath();
+                        });
         assertThat(testResults.mException).isNull();
         assertThat(testResults.mAddInteger).isEqualTo(123 + 456);
         assertThat(testResults.mAppRunProp).isEqualTo("true");
@@ -151,14 +166,20 @@
         VirtualMachineConfig config =
                 newVmConfigBuilder()
                         .setPayloadBinaryName("MicrodroidTestNativeLib.so")
-                        .setMemoryMib(minMemoryRequired())
+                        .setMemoryBytes(minMemoryRequired())
                         .setDebugLevel(DEBUG_LEVEL_NONE)
                         .setVmOutputCaptured(false)
                         .build();
         VirtualMachine vm = forceCreateNewVirtualMachine("test_vm", config);
 
-        TestResults testResults = runVmTestService(vm);
+        TestResults testResults =
+                runVmTestService(
+                        vm,
+                        (ts, tr) -> {
+                            tr.mAddInteger = ts.addInteger(37, 73);
+                        });
         assertThat(testResults.mException).isNull();
+        assertThat(testResults.mAddInteger).isEqualTo(37 + 73);
     }
 
     @Test
@@ -176,7 +197,7 @@
         VirtualMachineConfig config =
                 newVmConfigBuilder()
                         .setPayloadBinaryName("MicrodroidTestNativeLib.so")
-                        .setMemoryMib(minMemoryRequired())
+                        .setMemoryBytes(minMemoryRequired())
                         .build();
 
         SecurityException e =
@@ -195,7 +216,7 @@
         VirtualMachineConfig config =
                 newVmConfigBuilder()
                         .setPayloadBinaryName("MicrodroidTestNativeLib.so")
-                        .setMemoryMib(minMemoryRequired())
+                        .setMemoryBytes(minMemoryRequired())
                         .setDebugLevel(DEBUG_LEVEL_FULL)
                         .build();
 
@@ -226,7 +247,7 @@
         VirtualMachineConfig config =
                 newVmConfigBuilder()
                         .setPayloadBinaryName("MicrodroidTestNativeLib.so")
-                        .setMemoryMib(minMemoryRequired())
+                        .setMemoryBytes(minMemoryRequired())
                         .setDebugLevel(DEBUG_LEVEL_FULL)
                         .build();
 
@@ -275,7 +296,7 @@
         VirtualMachineConfig config =
                 newVmConfigBuilder()
                         .setPayloadBinaryName("MicrodroidTestNativeLib.so")
-                        .setMemoryMib(minMemoryRequired())
+                        .setMemoryBytes(minMemoryRequired())
                         .setDebugLevel(DEBUG_LEVEL_FULL)
                         .build();
         VirtualMachine vm = forceCreateNewVirtualMachine("test_vm_vsock", config);
@@ -324,15 +345,15 @@
         VirtualMachineConfig.Builder minimalBuilder = newVmConfigBuilder();
         VirtualMachineConfig minimal = minimalBuilder.setPayloadBinaryName("binary.so").build();
 
-        assertThat(minimal.getApkPath()).isEqualTo(getContext().getPackageCodePath());
+        assertThat(minimal.getApkPath()).isNull();
         assertThat(minimal.getDebugLevel()).isEqualTo(DEBUG_LEVEL_NONE);
-        assertThat(minimal.getMemoryMib()).isEqualTo(0);
+        assertThat(minimal.getMemoryBytes()).isEqualTo(0);
         assertThat(minimal.getNumCpus()).isEqualTo(1);
         assertThat(minimal.getPayloadBinaryName()).isEqualTo("binary.so");
         assertThat(minimal.getPayloadConfigPath()).isNull();
         assertThat(minimal.isProtectedVm()).isEqualTo(isProtectedVm());
         assertThat(minimal.isEncryptedStorageEnabled()).isFalse();
-        assertThat(minimal.getEncryptedStorageKib()).isEqualTo(0);
+        assertThat(minimal.getEncryptedStorageBytes()).isEqualTo(0);
         assertThat(minimal.isVmOutputCaptured()).isEqualTo(false);
 
         // Maximal has everything that can be set to some non-default value. (And has different
@@ -345,20 +366,20 @@
                         .setApkPath("/apk/path")
                         .setNumCpus(maxCpus)
                         .setDebugLevel(DEBUG_LEVEL_FULL)
-                        .setMemoryMib(42)
-                        .setEncryptedStorageKib(1024)
+                        .setMemoryBytes(42)
+                        .setEncryptedStorageBytes(1_000_000)
                         .setVmOutputCaptured(true);
         VirtualMachineConfig maximal = maximalBuilder.build();
 
         assertThat(maximal.getApkPath()).isEqualTo("/apk/path");
         assertThat(maximal.getDebugLevel()).isEqualTo(DEBUG_LEVEL_FULL);
-        assertThat(maximal.getMemoryMib()).isEqualTo(42);
+        assertThat(maximal.getMemoryBytes()).isEqualTo(42);
         assertThat(maximal.getNumCpus()).isEqualTo(maxCpus);
         assertThat(maximal.getPayloadBinaryName()).isNull();
         assertThat(maximal.getPayloadConfigPath()).isEqualTo("config/path");
         assertThat(maximal.isProtectedVm()).isEqualTo(isProtectedVm());
         assertThat(maximal.isEncryptedStorageEnabled()).isTrue();
-        assertThat(maximal.getEncryptedStorageKib()).isEqualTo(1024);
+        assertThat(maximal.getEncryptedStorageBytes()).isEqualTo(1_000_000);
         assertThat(maximal.isVmOutputCaptured()).isEqualTo(true);
 
         assertThat(minimal.isCompatibleWith(maximal)).isFalse();
@@ -384,9 +405,9 @@
         assertThrows(
                 IllegalArgumentException.class, () -> builder.setPayloadBinaryName("dir/file.so"));
         assertThrows(IllegalArgumentException.class, () -> builder.setDebugLevel(-1));
-        assertThrows(IllegalArgumentException.class, () -> builder.setMemoryMib(0));
+        assertThrows(IllegalArgumentException.class, () -> builder.setMemoryBytes(0));
         assertThrows(IllegalArgumentException.class, () -> builder.setNumCpus(0));
-        assertThrows(IllegalArgumentException.class, () -> builder.setEncryptedStorageKib(0));
+        assertThrows(IllegalArgumentException.class, () -> builder.setEncryptedStorageBytes(0));
 
         // Consistency checks enforced at build time.
         Exception e;
@@ -407,13 +428,9 @@
         assertThat(e).hasMessageThat().contains("debug level must be FULL to capture output");
     }
 
-    private VirtualMachineConfig.Builder newBaselineBuilder() {
-        return newVmConfigBuilder().setPayloadBinaryName("binary.so").setApkPath("/apk/path");
-    }
-
     @Test
     @CddTest(requirements = {"9.17/C-1-1"})
-    public void compatibleConfigTests() throws Exception {
+    public void compatibleConfigTests() {
         int maxCpus = Runtime.getRuntime().availableProcessors();
 
         VirtualMachineConfig baseline = newBaselineBuilder().build();
@@ -422,7 +439,7 @@
         assertConfigCompatible(baseline, newBaselineBuilder()).isTrue();
 
         // Changes that must always be compatible
-        assertConfigCompatible(baseline, newBaselineBuilder().setMemoryMib(99)).isTrue();
+        assertConfigCompatible(baseline, newBaselineBuilder().setMemoryBytes(99)).isTrue();
         if (maxCpus > 1) {
             assertConfigCompatible(baseline, newBaselineBuilder().setNumCpus(2)).isTrue();
         }
@@ -442,13 +459,38 @@
         // Changes that are currently incompatible for ease of implementation, but this might change
         // in the future.
         assertConfigCompatible(baseline, newBaselineBuilder().setApkPath("/different")).isFalse();
-        assertConfigCompatible(baseline, newBaselineBuilder().setEncryptedStorageKib(100))
+        assertConfigCompatible(baseline, newBaselineBuilder().setEncryptedStorageBytes(100_000))
                 .isFalse();
 
         VirtualMachineConfig.Builder debuggableBuilder =
                 newBaselineBuilder().setDebugLevel(DEBUG_LEVEL_FULL);
         VirtualMachineConfig debuggable = debuggableBuilder.build();
         assertConfigCompatible(debuggable, debuggableBuilder.setVmOutputCaptured(true)).isFalse();
+
+        VirtualMachineConfig currentContextConfig =
+                new VirtualMachineConfig.Builder(getContext())
+                        .setProtectedVm(isProtectedVm())
+                        .setPayloadBinaryName("binary.so")
+                        .build();
+
+        // packageName is not directly exposed by the config, so we have to be a bit creative
+        // to modify it.
+        Context otherContext =
+                new ContextWrapper(getContext()) {
+                    @Override
+                    public String getPackageName() {
+                        return "other.package.name";
+                    }
+                };
+        VirtualMachineConfig.Builder otherContextBuilder =
+                new VirtualMachineConfig.Builder(otherContext)
+                        .setProtectedVm(isProtectedVm())
+                        .setPayloadBinaryName("binary.so");
+        assertConfigCompatible(currentContextConfig, otherContextBuilder).isFalse();
+    }
+
+    private VirtualMachineConfig.Builder newBaselineBuilder() {
+        return newVmConfigBuilder().setPayloadBinaryName("binary.so").setApkPath("/apk/path");
     }
 
     private BooleanSubject assertConfigCompatible(
@@ -466,14 +508,14 @@
 
         assertThat(vm.getName()).isEqualTo("vm_name");
         assertThat(vm.getConfig().getPayloadBinaryName()).isEqualTo("binary.so");
-        assertThat(vm.getConfig().getMemoryMib()).isEqualTo(0);
+        assertThat(vm.getConfig().getMemoryBytes()).isEqualTo(0);
 
-        VirtualMachineConfig compatibleConfig = builder.setMemoryMib(42).build();
+        VirtualMachineConfig compatibleConfig = builder.setMemoryBytes(42).build();
         vm.setConfig(compatibleConfig);
 
         assertThat(vm.getName()).isEqualTo("vm_name");
         assertThat(vm.getConfig().getPayloadBinaryName()).isEqualTo("binary.so");
-        assertThat(vm.getConfig().getMemoryMib()).isEqualTo(42);
+        assertThat(vm.getConfig().getMemoryBytes()).isEqualTo(42);
 
         assertThat(getVirtualMachineManager().get("vm_name")).isSameInstanceAs(vm);
     }
@@ -486,7 +528,7 @@
         VirtualMachineConfig config =
                 newVmConfigBuilder()
                         .setPayloadBinaryName("MicrodroidTestNativeLib.so")
-                        .setMemoryMib(minMemoryRequired())
+                        .setMemoryBytes(minMemoryRequired())
                         .setDebugLevel(DEBUG_LEVEL_FULL)
                         .build();
 
@@ -584,13 +626,14 @@
         VirtualMachineConfig config =
                 newVmConfigBuilder()
                         .setPayloadConfigPath("assets/vm_config.json")
-                        .setMemoryMib(minMemoryRequired())
+                        .setMemoryBytes(minMemoryRequired())
                         .build();
 
         VirtualMachine vm =
                 forceCreateNewVirtualMachine("test_vm_config_requires_permission", config);
 
-        SecurityException e = assertThrows(SecurityException.class, () -> runVmTestService(vm));
+        SecurityException e =
+                assertThrows(SecurityException.class, () -> runVmTestService(vm, (ts, tr) -> {}));
         assertThat(e).hasMessageThat()
                 .contains("android.permission.USE_CUSTOM_VIRTUAL_MACHINE permission");
     }
@@ -605,7 +648,7 @@
         VirtualMachineConfig config =
                 newVmConfigBuilder()
                         .setPayloadBinaryName("MicrodroidTestNativeLib.so")
-                        .setMemoryMib(minMemoryRequired())
+                        .setMemoryBytes(minMemoryRequired())
                         .build();
 
         VirtualMachine vm = forceCreateNewVirtualMachine("test_vm_delete", config);
@@ -623,6 +666,40 @@
     }
 
     @Test
+    @CddTest(
+            requirements = {
+                "9.17/C-1-1",
+            })
+    public void deleteVmFiles() throws Exception {
+        assumeSupportedKernel();
+
+        VirtualMachineConfig config =
+                newVmConfigBuilder()
+                        .setPayloadBinaryName("MicrodroidExitNativeLib.so")
+                        .setMemoryBytes(minMemoryRequired())
+                        .build();
+
+        VirtualMachine vm = forceCreateNewVirtualMachine("test_vm_delete", config);
+        vm.run();
+        // If we explicitly stop a VM, that triggers some tidy up; so for this test we start a VM
+        // that immediately stops itself.
+        while (vm.getStatus() == STATUS_RUNNING) {
+            Thread.sleep(100);
+        }
+
+        // Delete the files without telling VMM. This isn't a good idea, but we can't stop an
+        // app doing it, and we should recover from it.
+        for (File f : vm.getRootDir().listFiles()) {
+            Files.delete(f.toPath());
+        }
+        vm.getRootDir().delete();
+
+        VirtualMachineManager vmm = getVirtualMachineManager();
+        assertThat(vmm.get("test_vm_delete")).isNull();
+        assertThat(vm.getStatus()).isEqualTo(STATUS_DELETED);
+    }
+
+    @Test
     @CddTest(requirements = {
             "9.17/C-1-1",
     })
@@ -633,14 +710,20 @@
                 newVmConfigBuilder()
                         .setPayloadBinaryName("MicrodroidTestNativeLib.so")
                         .setApkPath(getContext().getPackageCodePath())
-                        .setMemoryMib(minMemoryRequired())
+                        .setMemoryBytes(minMemoryRequired())
                         .setDebugLevel(DEBUG_LEVEL_FULL)
                         .build();
 
         VirtualMachine vm = forceCreateNewVirtualMachine("test_vm_explicit_apk_path", config);
 
-        TestResults testResults = runVmTestService(vm);
+        TestResults testResults =
+                runVmTestService(
+                        vm,
+                        (ts, tr) -> {
+                            tr.mApkContentsPath = ts.getApkContentsPath();
+                        });
         assertThat(testResults.mException).isNull();
+        assertThat(testResults.mApkContentsPath).isEqualTo("/mnt/apk");
     }
 
     @Test
@@ -663,12 +746,18 @@
         VirtualMachineConfig config =
                 newVmConfigBuilder()
                         .setPayloadConfigPath("assets/vm_config_extra_apk.json")
-                        .setMemoryMib(minMemoryRequired())
+                        .setMemoryBytes(minMemoryRequired())
                         .setDebugLevel(DEBUG_LEVEL_FULL)
                         .build();
         VirtualMachine vm = forceCreateNewVirtualMachine("test_vm_extra_apk", config);
 
-        TestResults testResults = runVmTestService(vm);
+        TestResults testResults =
+                runVmTestService(
+                        vm,
+                        (ts, tr) -> {
+                            tr.mExtraApkTestProp =
+                                    ts.readProperty("debug.microdroid.test.extra_apk");
+                        });
         assertThat(testResults.mExtraApkTestProp).isEqualTo("PASS");
     }
 
@@ -678,7 +767,7 @@
             VirtualMachineConfig lowMemConfig =
                     newVmConfigBuilder()
                             .setPayloadBinaryName("MicrodroidTestNativeLib.so")
-                            .setMemoryMib(memMib)
+                            .setMemoryBytes(memMib)
                             .setDebugLevel(DEBUG_LEVEL_NONE)
                             .setVmOutputCaptured(false)
                             .build();
@@ -1142,13 +1231,21 @@
                 newVmConfigBuilder()
                         .setPayloadBinaryName("MicrodroidTestNativeLib.so")
                         .setDebugLevel(DEBUG_LEVEL_FULL);
-        if (encryptedStoreEnabled) builder = builder.setEncryptedStorageKib(4096);
+        if (encryptedStoreEnabled) {
+            builder.setEncryptedStorageBytes(4_000_000);
+        }
         VirtualMachineConfig config = builder.build();
         String vmNameOrig = "test_vm_orig";
         String vmNameImport = "test_vm_import";
         VirtualMachine vmOrig = forceCreateNewVirtualMachine(vmNameOrig, config);
         // Run something to make the instance.img different with the initialized one.
-        TestResults origTestResults = runVmTestService(vmOrig);
+        TestResults origTestResults =
+                runVmTestService(
+                        vmOrig,
+                        (ts, tr) -> {
+                            tr.mAddInteger = ts.addInteger(123, 456);
+                            tr.mEncryptedStoragePath = ts.getEncryptedStoragePath();
+                        });
         assertThat(origTestResults.mException).isNull();
         assertThat(origTestResults.mAddInteger).isEqualTo(123 + 456);
         VirtualMachineDescriptor descriptor = vmOrig.toDescriptor();
@@ -1169,7 +1266,13 @@
         assertThat(vmImport).isNotEqualTo(vmOrig);
         vmm.delete(vmNameOrig);
         assertThat(vmImport).isEqualTo(vmm.get(vmNameImport));
-        TestResults testResults = runVmTestService(vmImport);
+        TestResults testResults =
+                runVmTestService(
+                        vmImport,
+                        (ts, tr) -> {
+                            tr.mAddInteger = ts.addInteger(123, 456);
+                            tr.mEncryptedStoragePath = ts.getEncryptedStoragePath();
+                        });
         assertThat(testResults.mException).isNull();
         assertThat(testResults.mAddInteger).isEqualTo(123 + 456);
         return testResults;
@@ -1183,13 +1286,18 @@
         VirtualMachineConfig config =
                 newVmConfigBuilder()
                         .setPayloadBinaryName("MicrodroidTestNativeLib.so")
-                        .setMemoryMib(minMemoryRequired())
-                        .setEncryptedStorageKib(4096)
+                        .setMemoryBytes(minMemoryRequired())
+                        .setEncryptedStorageBytes(4_000_000)
                         .setDebugLevel(DEBUG_LEVEL_FULL)
                         .build();
         VirtualMachine vm = forceCreateNewVirtualMachine("test_vm", config);
 
-        TestResults testResults = runVmTestService(vm);
+        TestResults testResults =
+                runVmTestService(
+                        vm,
+                        (ts, tr) -> {
+                            tr.mEncryptedStoragePath = ts.getEncryptedStoragePath();
+                        });
         assertThat(testResults.mEncryptedStoragePath).isEqualTo("/mnt/encryptedstore");
     }
 
@@ -1201,12 +1309,17 @@
         final VirtualMachineConfig vmConfig =
                 newVmConfigBuilder()
                         .setPayloadBinaryName("MicrodroidTestNativeLib.so")
-                        .setMemoryMib(minMemoryRequired())
+                        .setMemoryBytes(minMemoryRequired())
                         .setDebugLevel(DEBUG_LEVEL_FULL)
                         .build();
         final VirtualMachine vm = forceCreateNewVirtualMachine("test_vm_caps", vmConfig);
 
-        final TestResults testResults = runVmTestService(vm);
+        final TestResults testResults =
+                runVmTestService(
+                        vm,
+                        (ts, tr) -> {
+                            tr.mEffectiveCapabilities = ts.getEffectiveCapabilities();
+                        });
 
         assertThat(testResults.mException).isNull();
         assertThat(testResults.mEffectiveCapabilities).isEmpty();
@@ -1220,17 +1333,29 @@
         VirtualMachineConfig config =
                 newVmConfigBuilder()
                         .setPayloadBinaryName("MicrodroidTestNativeLib.so")
-                        .setMemoryMib(minMemoryRequired())
-                        .setEncryptedStorageKib(4096)
+                        .setMemoryBytes(minMemoryRequired())
+                        .setEncryptedStorageBytes(4_000_000)
                         .setDebugLevel(DEBUG_LEVEL_FULL)
                         .build();
         VirtualMachine vm = forceCreateNewVirtualMachine("test_vm_a", config);
-        TestResults testResults = runVmTestService(vm, EncryptedStoreOperation.WRITE);
+        TestResults testResults =
+                runVmTestService(
+                        vm,
+                        (ts, tr) -> {
+                            ts.writeToFile(
+                                    /* content= */ EXAMPLE_STRING,
+                                    /* path= */ "/mnt/encryptedstore/test_file");
+                        });
         assertThat(testResults.mException).isNull();
 
         // Re-run the same VM & verify the file persisted. Note, the previous `runVmTestService`
         // stopped the VM
-        testResults = runVmTestService(vm, EncryptedStoreOperation.READ);
+        testResults =
+                runVmTestService(
+                        vm,
+                        (ts, tr) -> {
+                            tr.mFileContent = ts.readFromFile("/mnt/encryptedstore/test_file");
+                        });
         assertThat(testResults.mException).isNull();
         assertThat(testResults.mFileContent).isEqualTo(EXAMPLE_STRING);
     }
@@ -1243,7 +1368,7 @@
         VirtualMachineConfig config =
                 newVmConfigBuilder()
                         .setPayloadBinaryName("MicrodroidTestNativeLib.so")
-                        .setMemoryMib(minMemoryRequired())
+                        .setMemoryBytes(minMemoryRequired())
                         .setDebugLevel(DEBUG_LEVEL_FULL)
                         .build();
         VirtualMachine vm = forceCreateNewVirtualMachine("test_vm_read_from_assets", config);
@@ -1260,7 +1385,7 @@
     }
 
     @Test
-    public void outputsShouldBeExplicitlyForwarded() throws Exception {
+    public void outputShouldBeExplicitlyCaptured() throws Exception {
         assumeSupportedKernel();
 
         final VirtualMachineConfig vmConfig =
@@ -1282,6 +1407,57 @@
         }
     }
 
+    private boolean checkVmOutputIsRedirectedToLogcat(boolean debuggable) throws Exception {
+        String time =
+                LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
+        final VirtualMachineConfig vmConfig =
+                new VirtualMachineConfig.Builder(ApplicationProvider.getApplicationContext())
+                        .setProtectedVm(mProtectedVm)
+                        .setPayloadBinaryName("MicrodroidTestNativeLib.so")
+                        .setDebugLevel(debuggable ? DEBUG_LEVEL_FULL : DEBUG_LEVEL_NONE)
+                        .setVmOutputCaptured(false)
+                        .build();
+        final VirtualMachine vm = forceCreateNewVirtualMachine("test_vm_logcat", vmConfig);
+
+        VmEventListener listener =
+                new VmEventListener() {
+                    @Override
+                    public void onPayloadStarted(VirtualMachine vm) {
+                        forceStop(vm);
+                    }
+                };
+        listener.runToFinish(TAG, vm);
+
+        // only check logs printed after this test
+        Process logcatProcess =
+                new ProcessBuilder()
+                        .command(
+                                "logcat",
+                                "-e",
+                                "virtualizationmanager::aidl: Console.*executing main task",
+                                "-t",
+                                time)
+                        .start();
+        logcatProcess.waitFor();
+        BufferedReader reader =
+                new BufferedReader(new InputStreamReader(logcatProcess.getInputStream()));
+        return !Strings.isNullOrEmpty(reader.readLine());
+    }
+
+    @Test
+    public void outputIsRedirectedToLogcatIfNotCaptured() throws Exception {
+        assumeSupportedKernel();
+
+        assertThat(checkVmOutputIsRedirectedToLogcat(true)).isTrue();
+    }
+
+    @Test
+    public void outputIsNotRedirectedToLogcatIfNotDebuggable() throws Exception {
+        assumeSupportedKernel();
+
+        assertThat(checkVmOutputIsRedirectedToLogcat(false)).isFalse();
+    }
+
     private void assertFileContentsAreEqualInTwoVms(String fileName, String vmName1, String vmName2)
             throws IOException {
         File file1 = getVmFile(vmName1, fileName);
@@ -1308,7 +1484,7 @@
         assertThat(e).hasMessageThat().contains(expectedContents);
     }
 
-    private int minMemoryRequired() {
+    private long minMemoryRequired() {
         if (Build.SUPPORTED_ABIS.length > 0) {
             String primaryAbi = Build.SUPPORTED_ABIS[0];
             switch (primaryAbi) {
@@ -1340,67 +1516,6 @@
         String mFileContent;
     }
 
-    private TestResults runVmTestService(VirtualMachine vm) throws Exception {
-        return runVmTestService(vm, EncryptedStoreOperation.NONE);
-    }
-
-    private TestResults runVmTestService(VirtualMachine vm, EncryptedStoreOperation mode)
-            throws Exception {
-        CompletableFuture<Boolean> payloadStarted = new CompletableFuture<>();
-        CompletableFuture<Boolean> payloadReady = new CompletableFuture<>();
-        TestResults testResults = new TestResults();
-        VmEventListener listener =
-                new VmEventListener() {
-                    private void testVMService(VirtualMachine vm) {
-                        try {
-                            ITestService testService =
-                                    ITestService.Stub.asInterface(
-                                            vm.connectToVsockServer(ITestService.SERVICE_PORT));
-                            testResults.mAddInteger = testService.addInteger(123, 456);
-                            testResults.mAppRunProp =
-                                    testService.readProperty("debug.microdroid.app.run");
-                            testResults.mSublibRunProp =
-                                    testService.readProperty("debug.microdroid.app.sublib.run");
-                            testResults.mExtraApkTestProp =
-                                    testService.readProperty("debug.microdroid.test.extra_apk");
-                            testResults.mApkContentsPath = testService.getApkContentsPath();
-                            testResults.mEncryptedStoragePath =
-                                    testService.getEncryptedStoragePath();
-                            testResults.mEffectiveCapabilities =
-                                    testService.getEffectiveCapabilities();
-                            if (mode == EncryptedStoreOperation.WRITE) {
-                                testService.writeToFile(
-                                        /*content*/ EXAMPLE_STRING,
-                                        /*path*/ "/mnt/encryptedstore/test_file");
-                            } else if (mode == EncryptedStoreOperation.READ) {
-                                testResults.mFileContent =
-                                        testService.readFromFile("/mnt/encryptedstore/test_file");
-                            }
-                        } catch (Exception e) {
-                            testResults.mException = e;
-                        }
-                    }
-
-                    @Override
-                    public void onPayloadReady(VirtualMachine vm) {
-                        Log.i(TAG, "onPayloadReady");
-                        payloadReady.complete(true);
-                        testVMService(vm);
-                        forceStop(vm);
-                    }
-
-                    @Override
-                    public void onPayloadStarted(VirtualMachine vm) {
-                        Log.i(TAG, "onPayloadStarted");
-                        payloadStarted.complete(true);
-                    }
-                };
-        listener.runToFinish(TAG, vm);
-        assertThat(payloadStarted.getNow(false)).isTrue();
-        assertThat(payloadReady.getNow(false)).isTrue();
-        return testResults;
-    }
-
     private TestResults runVmTestService(VirtualMachine vm, RunTestsAgainstTestService testsToRun)
             throws Exception {
         CompletableFuture<Boolean> payloadStarted = new CompletableFuture<>();
diff --git a/tests/testapk/src/native/exitbinary.cpp b/tests/testapk/src/native/exitbinary.cpp
new file mode 100644
index 0000000..4b70727
--- /dev/null
+++ b/tests/testapk/src/native/exitbinary.cpp
@@ -0,0 +1,21 @@
+/*
+ * Copyright 2023 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.
+ */
+
+#include <vm_main.h>
+
+extern "C" int AVmPayload_main() {
+    return 0;
+}
diff --git a/tests/testapk/src/native/idlebinary.cpp b/tests/testapk/src/native/idlebinary.cpp
index 9499d94..366120c 100644
--- a/tests/testapk/src/native/idlebinary.cpp
+++ b/tests/testapk/src/native/idlebinary.cpp
@@ -20,6 +20,6 @@
 extern "C" int AVmPayload_main() {
     // do nothing; just leave it alive. good night.
     for (;;) {
-        sleep(1000);
+        pause();
     }
 }
diff --git a/virtualizationmanager/Android.bp b/virtualizationmanager/Android.bp
new file mode 100644
index 0000000..a436cea
--- /dev/null
+++ b/virtualizationmanager/Android.bp
@@ -0,0 +1,82 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+rust_defaults {
+    name: "virtualizationmanager_defaults",
+    crate_name: "virtualizationmanager",
+    edition: "2021",
+    // Only build on targets which crosvm builds on.
+    enabled: false,
+    target: {
+        android64: {
+            compile_multilib: "64",
+            enabled: true,
+        },
+        linux_bionic_arm64: {
+            enabled: true,
+        },
+    },
+    prefer_rlib: true,
+    rustlibs: [
+        "android.system.virtualizationcommon-rust",
+        "android.system.virtualizationservice-rust",
+        "android.system.virtualizationservice_internal-rust",
+        "android.system.virtualmachineservice-rust",
+        "android.os.permissions_aidl-rust",
+        "libandroid_logger",
+        "libanyhow",
+        "libapkverify",
+        "libbase_rust",
+        "libbinder_rs",
+        "libclap",
+        "libcommand_fds",
+        "libdisk",
+        "liblazy_static",
+        "liblibc",
+        "liblog_rust",
+        "libmicrodroid_metadata",
+        "libmicrodroid_payload_config",
+        "libnested_virt",
+        "libnix",
+        "libonce_cell",
+        "libregex",
+        "librpcbinder_rs",
+        "librustutils",
+        "libsemver",
+        "libselinux_bindgen",
+        "libserde",
+        "libserde_json",
+        "libserde_xml_rs",
+        "libshared_child",
+        "libstatslog_virtualization_rust",
+        "libtombstoned_client_rust",
+        "libvm_control",
+        "libvmconfig",
+        "libzip",
+        "libvsock",
+        // TODO(b/202115393) stabilize the interface
+        "packagemanager_aidl-rust",
+    ],
+    shared_libs: [
+        "libbinder_rpc_unstable",
+        "libselinux",
+    ],
+}
+
+rust_binary {
+    name: "virtmgr",
+    defaults: ["virtualizationmanager_defaults"],
+    srcs: ["src/main.rs"],
+    apex_available: ["com.android.virt"],
+}
+
+rust_test {
+    name: "virtualizationmanager_device_test",
+    srcs: ["src/main.rs"],
+    defaults: ["virtualizationmanager_defaults"],
+    rustlibs: [
+        "libtempfile",
+    ],
+    test_suites: ["general-tests"],
+}
diff --git a/virtualizationmanager/TEST_MAPPING b/virtualizationmanager/TEST_MAPPING
new file mode 100644
index 0000000..a680f6d
--- /dev/null
+++ b/virtualizationmanager/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+  "avf-presubmit": [
+    {
+      "name": "virtualizationmanager_device_test"
+    }
+  ]
+}
diff --git a/virtualizationmanager/src/aidl.rs b/virtualizationmanager/src/aidl.rs
new file mode 100644
index 0000000..cab7c71
--- /dev/null
+++ b/virtualizationmanager/src/aidl.rs
@@ -0,0 +1,1191 @@
+// Copyright 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.
+
+//! Implementation of the AIDL interface of the VirtualizationService.
+
+use crate::{get_calling_pid, get_calling_uid};
+use crate::atom::{
+    write_vm_booted_stats, write_vm_creation_stats};
+use crate::composite::make_composite_image;
+use crate::crosvm::{CrosvmConfig, DiskFile, PayloadState, VmContext, VmInstance, VmState};
+use crate::payload::{add_microdroid_payload_images, add_microdroid_system_images};
+use crate::selinux::{getfilecon, SeContext};
+use android_os_permissions_aidl::aidl::android::os::IPermissionController;
+use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::{
+    DeathReason::DeathReason,
+    ErrorCode::ErrorCode,
+};
+use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
+    DiskImage::DiskImage,
+    IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
+    IVirtualMachineCallback::IVirtualMachineCallback,
+    IVirtualizationService::IVirtualizationService,
+    MemoryTrimLevel::MemoryTrimLevel,
+    Partition::Partition,
+    PartitionType::PartitionType,
+    VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
+    VirtualMachineConfig::VirtualMachineConfig,
+    VirtualMachineDebugInfo::VirtualMachineDebugInfo,
+    VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
+    VirtualMachineRawConfig::VirtualMachineRawConfig,
+    VirtualMachineState::VirtualMachineState,
+};
+use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::IVirtualizationServiceInternal;
+use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
+        BnVirtualMachineService, IVirtualMachineService,
+};
+use anyhow::{bail, Context, Result};
+use apkverify::{HashAlgorithm, V4Signature};
+use binder::{
+    self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor,
+    Status, StatusCode, Strong,
+};
+use disk::QcowFile;
+use lazy_static::lazy_static;
+use log::{debug, error, info, warn};
+use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
+use nix::unistd::pipe;
+use rpcbinder::RpcServer;
+use semver::VersionReq;
+use std::convert::TryInto;
+use std::ffi::CStr;
+use std::fs::{read_dir, remove_file, File, OpenOptions};
+use std::io::{BufRead, BufReader, Error, ErrorKind, Write};
+use std::num::NonZeroU32;
+use std::os::unix::io::{FromRawFd, IntoRawFd};
+use std::os::unix::raw::pid_t;
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, Mutex, Weak};
+use vmconfig::VmConfig;
+use vsock::VsockStream;
+use zip::ZipArchive;
+
+/// The unique ID of a VM used (together with a port number) for vsock communication.
+pub type Cid = u32;
+
+pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
+
+/// The size of zero.img.
+/// Gaps in composite disk images are filled with a shared zero.img.
+const ZERO_FILLER_SIZE: u64 = 4096;
+
+/// Magic string for the instance image
+const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
+
+/// Version of the instance image format
+const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
+
+const MICRODROID_OS_NAME: &str = "microdroid";
+
+const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
+
+/// crosvm requires all partitions to be a multiple of 4KiB.
+const PARTITION_GRANULARITY_BYTES: u64 = 4096;
+
+lazy_static! {
+    pub static ref GLOBAL_SERVICE: Strong<dyn IVirtualizationServiceInternal> =
+        wait_for_interface(BINDER_SERVICE_IDENTIFIER)
+            .expect("Could not connect to VirtualizationServiceInternal");
+}
+
+fn create_or_update_idsig_file(
+    input_fd: &ParcelFileDescriptor,
+    idsig_fd: &ParcelFileDescriptor,
+) -> Result<()> {
+    let mut input = clone_file(input_fd)?;
+    let metadata = input.metadata().context("failed to get input metadata")?;
+    if !metadata.is_file() {
+        bail!("input is not a regular file");
+    }
+    let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256)
+        .context("failed to create idsig")?;
+
+    let mut output = clone_file(idsig_fd)?;
+    output.set_len(0).context("failed to set_len on the idsig output")?;
+    sig.write_into(&mut output).context("failed to write idsig")?;
+    Ok(())
+}
+
+pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
+    for dir_entry in read_dir(path)? {
+        remove_file(dir_entry?.path())?;
+    }
+    Ok(())
+}
+
+/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
+#[derive(Debug, Default)]
+pub struct VirtualizationService {
+    state: Arc<Mutex<State>>,
+}
+
+impl Interface for VirtualizationService {
+    fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
+        check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
+        let state = &mut *self.state.lock().unwrap();
+        let vms = state.vms();
+        writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
+        for vm in vms {
+            writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
+            writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
+                .or(Err(StatusCode::UNKNOWN_ERROR))?;
+            writeln!(file, "\tPayload state {:?}", vm.payload_state())
+                .or(Err(StatusCode::UNKNOWN_ERROR))?;
+            writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
+            writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
+                .or(Err(StatusCode::UNKNOWN_ERROR))?;
+            writeln!(file, "\trequester_uid: {}", vm.requester_uid)
+                .or(Err(StatusCode::UNKNOWN_ERROR))?;
+            writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
+                .or(Err(StatusCode::UNKNOWN_ERROR))?;
+        }
+        Ok(())
+    }
+}
+
+impl IVirtualizationService for VirtualizationService {
+    /// Creates (but does not start) a new VM with the given configuration, assigning it the next
+    /// available CID.
+    ///
+    /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
+    fn createVm(
+        &self,
+        config: &VirtualMachineConfig,
+        console_fd: Option<&ParcelFileDescriptor>,
+        log_fd: Option<&ParcelFileDescriptor>,
+    ) -> binder::Result<Strong<dyn IVirtualMachine>> {
+        let mut is_protected = false;
+        let ret = self.create_vm_internal(config, console_fd, log_fd, &mut is_protected);
+        write_vm_creation_stats(config, is_protected, &ret);
+        ret
+    }
+
+    /// Initialise an empty partition image of the given size to be used as a writable partition.
+    fn initializeWritablePartition(
+        &self,
+        image_fd: &ParcelFileDescriptor,
+        size_bytes: i64,
+        partition_type: PartitionType,
+    ) -> binder::Result<()> {
+        check_manage_access()?;
+        let size_bytes = size_bytes.try_into().map_err(|e| {
+            Status::new_exception_str(
+                ExceptionCode::ILLEGAL_ARGUMENT,
+                Some(format!("Invalid size {}: {:?}", size_bytes, e)),
+            )
+        })?;
+        let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
+        let image = clone_file(image_fd)?;
+        // initialize the file. Any data in the file will be erased.
+        image.set_len(0).map_err(|e| {
+            Status::new_service_specific_error_str(
+                -1,
+                Some(format!("Failed to reset a file: {:?}", e)),
+            )
+        })?;
+        let mut part = QcowFile::new(image, size_bytes).map_err(|e| {
+            Status::new_service_specific_error_str(
+                -1,
+                Some(format!("Failed to create QCOW2 image: {:?}", e)),
+            )
+        })?;
+
+        match partition_type {
+            PartitionType::RAW => Ok(()),
+            PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
+            PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part),
+            _ => Err(Error::new(
+                ErrorKind::Unsupported,
+                format!("Unsupported partition type {:?}", partition_type),
+            )),
+        }
+        .map_err(|e| {
+            Status::new_service_specific_error_str(
+                -1,
+                Some(format!("Failed to initialize partition as {:?}: {:?}", partition_type, e)),
+            )
+        })?;
+
+        Ok(())
+    }
+
+    /// Creates or update the idsig file by digesting the input APK file.
+    fn createOrUpdateIdsigFile(
+        &self,
+        input_fd: &ParcelFileDescriptor,
+        idsig_fd: &ParcelFileDescriptor,
+    ) -> binder::Result<()> {
+        // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
+        // idsig_fd is different from APK digest in input_fd
+
+        check_manage_access()?;
+
+        create_or_update_idsig_file(input_fd, idsig_fd)
+            .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
+        Ok(())
+    }
+
+    /// Get a list of all currently running VMs. This method is only intended for debug purposes,
+    /// and as such is only permitted from the shell user.
+    fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
+        // Delegate to the global service, including checking the debug permission.
+        GLOBAL_SERVICE.debugListVms()
+    }
+}
+
+impl VirtualizationService {
+    pub fn init() -> VirtualizationService {
+        VirtualizationService::default()
+    }
+
+    fn create_vm_context(
+        &self,
+        requester_debug_pid: pid_t,
+    ) -> binder::Result<(VmContext, Cid, PathBuf)> {
+        const NUM_ATTEMPTS: usize = 5;
+
+        for _ in 0..NUM_ATTEMPTS {
+            let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
+            let cid = vm_context.getCid()? as Cid;
+            let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
+            let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
+
+            // Start VM service listening for connections from the new CID on port=CID.
+            let port = cid;
+            match RpcServer::new_vsock(service, cid, port) {
+                Ok(vm_server) => {
+                    vm_server.start();
+                    return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
+                }
+                Err(err) => {
+                    warn!("Could not start RpcServer on port {}: {}", port, err);
+                }
+            }
+        }
+        Err(Status::new_service_specific_error_str(
+            -1,
+            Some("Too many attempts to create VM context failed."),
+        ))
+    }
+
+    fn create_vm_internal(
+        &self,
+        config: &VirtualMachineConfig,
+        console_fd: Option<&ParcelFileDescriptor>,
+        log_fd: Option<&ParcelFileDescriptor>,
+        is_protected: &mut bool,
+    ) -> binder::Result<Strong<dyn IVirtualMachine>> {
+        let requester_uid = get_calling_uid();
+        let requester_debug_pid = get_calling_pid();
+
+        // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
+        let (vm_context, cid, temporary_directory) = self.create_vm_context(requester_debug_pid)?;
+
+        let is_custom = match config {
+            VirtualMachineConfig::RawConfig(_) => true,
+            VirtualMachineConfig::AppConfig(config) => {
+                // Some features are reserved for platform apps only, even when using
+                // VirtualMachineAppConfig:
+                // - controlling CPUs;
+                // - specifying a config file in the APK.
+                !config.taskProfiles.is_empty() || matches!(config.payload, Payload::ConfigPath(_))
+            }
+        };
+        if is_custom {
+            check_use_custom_virtual_machine()?;
+        }
+
+        let state = &mut *self.state.lock().unwrap();
+        let console_fd =
+            clone_or_prepare_logger_fd(config, console_fd, format!("Console({})", cid))?;
+        let log_fd = clone_or_prepare_logger_fd(config, log_fd, format!("Log({})", cid))?;
+
+        // Counter to generate unique IDs for temporary image files.
+        let mut next_temporary_image_id = 0;
+        // Files which are referred to from composite images. These must be mapped to the crosvm
+        // child process, and not closed before it is started.
+        let mut indirect_files = vec![];
+
+        let (is_app_config, config) = match config {
+            VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
+            VirtualMachineConfig::AppConfig(config) => {
+                let config = load_app_config(config, &temporary_directory).map_err(|e| {
+                    *is_protected = config.protectedVm;
+                    let message = format!("Failed to load app config: {:?}", e);
+                    error!("{}", message);
+                    Status::new_service_specific_error_str(-1, Some(message))
+                })?;
+                (true, BorrowedOrOwned::Owned(config))
+            }
+        };
+        let config = config.as_ref();
+        *is_protected = config.protectedVm;
+
+        // Check if partition images are labeled incorrectly. This is to prevent random images
+        // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
+        // being loaded in a pVM. This applies to everything in the raw config, and everything but
+        // the non-executable, generated partitions in the app config.
+        config
+            .disks
+            .iter()
+            .flat_map(|disk| disk.partitions.iter())
+            .filter(|partition| {
+                if is_app_config {
+                    !is_safe_app_partition(&partition.label)
+                } else {
+                    true // all partitions are checked
+                }
+            })
+            .try_for_each(check_label_for_partition)
+            .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
+
+        let kernel = maybe_clone_file(&config.kernel)?;
+        let initrd = maybe_clone_file(&config.initrd)?;
+
+        // In a protected VM, we require custom kernels to come from a trusted source (b/237054515).
+        if config.protectedVm {
+            check_label_for_kernel_files(&kernel, &initrd).map_err(|e| {
+                Status::new_service_specific_error_str(-1, Some(format!("{:?}", e)))
+            })?;
+        }
+
+        let zero_filler_path = temporary_directory.join("zero.img");
+        write_zero_filler(&zero_filler_path).map_err(|e| {
+            error!("Failed to make composite image: {:?}", e);
+            Status::new_service_specific_error_str(
+                -1,
+                Some(format!("Failed to make composite image: {:?}", e)),
+            )
+        })?;
+
+        // Assemble disk images if needed.
+        let disks = config
+            .disks
+            .iter()
+            .map(|disk| {
+                assemble_disk_image(
+                    disk,
+                    &zero_filler_path,
+                    &temporary_directory,
+                    &mut next_temporary_image_id,
+                    &mut indirect_files,
+                )
+            })
+            .collect::<Result<Vec<DiskFile>, _>>()?;
+
+        // Creating this ramdump file unconditionally is not harmful as ramdump will be created
+        // only when the VM is configured as such. `ramdump_write` is sent to crosvm and will
+        // be the backing store for the /dev/hvc1 where VM will emit ramdump to. `ramdump_read`
+        // will be sent back to the client (i.e. the VM owner) for readout.
+        let ramdump_path = temporary_directory.join("ramdump");
+        let ramdump = prepare_ramdump_file(&ramdump_path).map_err(|e| {
+            error!("Failed to prepare ramdump file: {:?}", e);
+            Status::new_service_specific_error_str(
+                -1,
+                Some(format!("Failed to prepare ramdump file: {:?}", e)),
+            )
+        })?;
+
+        // Actually start the VM.
+        let crosvm_config = CrosvmConfig {
+            cid,
+            name: config.name.clone(),
+            bootloader: maybe_clone_file(&config.bootloader)?,
+            kernel,
+            initrd,
+            disks,
+            params: config.params.to_owned(),
+            protected: *is_protected,
+            memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
+            cpus: config.numCpus.try_into().ok().and_then(NonZeroU32::new),
+            task_profiles: config.taskProfiles.clone(),
+            console_fd,
+            log_fd,
+            ramdump: Some(ramdump),
+            indirect_files,
+            platform_version: parse_platform_version_req(&config.platformVersion)?,
+            detect_hangup: is_app_config,
+        };
+        let instance = Arc::new(
+            VmInstance::new(
+                crosvm_config,
+                temporary_directory,
+                requester_uid,
+                requester_debug_pid,
+                vm_context,
+            )
+            .map_err(|e| {
+                error!("Failed to create VM with config {:?}: {:?}", config, e);
+                Status::new_service_specific_error_str(
+                    -1,
+                    Some(format!("Failed to create VM: {:?}", e)),
+                )
+            })?,
+        );
+        state.add_vm(Arc::downgrade(&instance));
+        Ok(VirtualMachine::create(instance))
+    }
+}
+
+fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
+    let file = OpenOptions::new()
+        .create_new(true)
+        .read(true)
+        .write(true)
+        .open(zero_filler_path)
+        .with_context(|| "Failed to create zero.img")?;
+    file.set_len(ZERO_FILLER_SIZE)?;
+    Ok(())
+}
+
+fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
+    part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
+    part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
+    part.flush()
+}
+
+fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
+    part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
+    part.flush()
+}
+
+fn prepare_ramdump_file(ramdump_path: &Path) -> Result<File> {
+    File::create(ramdump_path).context(format!("Failed to create ramdump file {:?}", &ramdump_path))
+}
+
+fn round_up(input: u64, granularity: u64) -> u64 {
+    if granularity == 0 {
+        return input;
+    }
+    // If the input is absurdly large we round down instead of up; it's going to fail anyway.
+    let result = input.checked_add(granularity - 1).unwrap_or(input);
+    (result / granularity) * granularity
+}
+
+/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
+///
+/// This may involve assembling a composite disk from a set of partition images.
+fn assemble_disk_image(
+    disk: &DiskImage,
+    zero_filler_path: &Path,
+    temporary_directory: &Path,
+    next_temporary_image_id: &mut u64,
+    indirect_files: &mut Vec<File>,
+) -> Result<DiskFile, Status> {
+    let image = if !disk.partitions.is_empty() {
+        if disk.image.is_some() {
+            warn!("DiskImage {:?} contains both image and partitions.", disk);
+            return Err(Status::new_exception_str(
+                ExceptionCode::ILLEGAL_ARGUMENT,
+                Some("DiskImage contains both image and partitions."),
+            ));
+        }
+
+        let composite_image_filenames =
+            make_composite_image_filenames(temporary_directory, next_temporary_image_id);
+        let (image, partition_files) = make_composite_image(
+            &disk.partitions,
+            zero_filler_path,
+            &composite_image_filenames.composite,
+            &composite_image_filenames.header,
+            &composite_image_filenames.footer,
+        )
+        .map_err(|e| {
+            error!("Failed to make composite image with config {:?}: {:?}", disk, e);
+            Status::new_service_specific_error_str(
+                -1,
+                Some(format!("Failed to make composite image: {:?}", e)),
+            )
+        })?;
+
+        // Pass the file descriptors for the various partition files to crosvm when it
+        // is run.
+        indirect_files.extend(partition_files);
+
+        image
+    } else if let Some(image) = &disk.image {
+        clone_file(image)?
+    } else {
+        warn!("DiskImage {:?} didn't contain image or partitions.", disk);
+        return Err(Status::new_exception_str(
+            ExceptionCode::ILLEGAL_ARGUMENT,
+            Some("DiskImage didn't contain image or partitions."),
+        ));
+    };
+
+    Ok(DiskFile { image, writable: disk.writable })
+}
+
+fn load_app_config(
+    config: &VirtualMachineAppConfig,
+    temporary_directory: &Path,
+) -> Result<VirtualMachineRawConfig> {
+    let apk_file = clone_file(config.apk.as_ref().unwrap())?;
+    let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
+    let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
+
+    let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
+        Some(clone_file(file)?)
+    } else {
+        None
+    };
+
+    let vm_payload_config = match &config.payload {
+        Payload::ConfigPath(config_path) => {
+            load_vm_payload_config_from_file(&apk_file, config_path.as_str())
+                .with_context(|| format!("Couldn't read config from {}", config_path))?
+        }
+        Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
+    };
+
+    // For now, the only supported OS is Microdroid
+    let os_name = vm_payload_config.os.name.as_str();
+    if os_name != MICRODROID_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)?.to_parcelable()?;
+
+    if config.memoryMib > 0 {
+        vm_config.memoryMib = config.memoryMib;
+    }
+
+    vm_config.name = config.name.clone();
+    vm_config.protectedVm = config.protectedVm;
+    vm_config.numCpus = config.numCpus;
+    vm_config.taskProfiles = config.taskProfiles.clone();
+
+    // Microdroid takes additional init ramdisk & (optionally) storage image
+    add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
+
+    // Include Microdroid payload disk (contains apks, idsigs) in vm config
+    add_microdroid_payload_images(
+        config,
+        temporary_directory,
+        apk_file,
+        idsig_file,
+        &vm_payload_config,
+        &mut vm_config,
+    )?;
+
+    Ok(vm_config)
+}
+
+fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
+    let mut apk_zip = ZipArchive::new(apk_file)?;
+    let config_file = apk_zip.by_name(config_path)?;
+    Ok(serde_json::from_reader(config_file)?)
+}
+
+fn create_vm_payload_config(
+    payload_config: &VirtualMachinePayloadConfig,
+) -> Result<VmPayloadConfig> {
+    // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
+    // parameters we've been given. Microdroid will do something equivalent inside the VM using the
+    // payload config that we send it via the metadata file.
+
+    let payload_binary_name = &payload_config.payloadBinaryName;
+    if payload_binary_name.contains('/') {
+        bail!("Payload binary name must not specify a path: {payload_binary_name}");
+    }
+
+    let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
+    Ok(VmPayloadConfig {
+        os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
+        task: Some(task),
+        apexes: vec![],
+        extra_apks: vec![],
+        prefer_staged: false,
+        export_tombstones: false,
+        enable_authfs: false,
+    })
+}
+
+/// Generates a unique filename to use for a composite disk image.
+fn make_composite_image_filenames(
+    temporary_directory: &Path,
+    next_temporary_image_id: &mut u64,
+) -> CompositeImageFilenames {
+    let id = *next_temporary_image_id;
+    *next_temporary_image_id += 1;
+    CompositeImageFilenames {
+        composite: temporary_directory.join(format!("composite-{}.img", id)),
+        header: temporary_directory.join(format!("composite-{}-header.img", id)),
+        footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
+    }
+}
+
+/// Filenames for a composite disk image, including header and footer partitions.
+#[derive(Clone, Debug, Eq, PartialEq)]
+struct CompositeImageFilenames {
+    /// The composite disk image itself.
+    composite: PathBuf,
+    /// The header partition image.
+    header: PathBuf,
+    /// The footer partition image.
+    footer: PathBuf,
+}
+
+/// Checks whether the caller has a specific permission
+fn check_permission(perm: &str) -> binder::Result<()> {
+    let calling_pid = get_calling_pid();
+    let calling_uid = get_calling_uid();
+    // Root can do anything
+    if calling_uid == 0 {
+        return Ok(());
+    }
+    let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
+        binder::get_interface("permission")?;
+    if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
+        Ok(())
+    } else {
+        Err(Status::new_exception_str(
+            ExceptionCode::SECURITY,
+            Some(format!("does not have the {} permission", perm)),
+        ))
+    }
+}
+
+/// Check whether the caller of the current Binder method is allowed to manage VMs
+fn check_manage_access() -> binder::Result<()> {
+    check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
+}
+
+/// Check whether the caller of the current Binder method is allowed to create custom VMs
+fn check_use_custom_virtual_machine() -> binder::Result<()> {
+    check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
+}
+
+/// Return whether a partition is exempt from selinux label checks, because we know that it does
+/// not contain code and is likely to be generated in an app-writable directory.
+fn is_safe_app_partition(label: &str) -> bool {
+    // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
+    label == "vm-instance"
+        || label == "encryptedstore"
+        || label == "microdroid-apk-idsig"
+        || label == "payload-metadata"
+        || label.starts_with("extra-idsig-")
+}
+
+/// Check that a file SELinux label is acceptable.
+///
+/// We only want to allow code in a VM to be sourced from places that apps, and the
+/// system, do not have write access to.
+///
+/// Note that sepolicy must also grant read access for these types to both virtualization
+/// service and crosvm.
+///
+/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
+/// user devices (W^X).
+fn check_label_is_allowed(context: &SeContext) -> Result<()> {
+    match context.selinux_type()? {
+        | "system_file" // immutable dm-verity protected partition
+        | "apk_data_file" // APKs of an installed app
+        | "staging_data_file" // updated/staged APEX images
+        | "shell_data_file" // test files created via adb shell
+         => Ok(()),
+        _ => bail!("Label {} is not allowed", context),
+    }
+}
+
+fn check_label_for_partition(partition: &Partition) -> Result<()> {
+    let file = partition.image.as_ref().unwrap().as_ref();
+    check_label_is_allowed(&getfilecon(file)?)
+        .with_context(|| format!("Partition {} invalid", &partition.label))
+}
+
+fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
+    if let Some(f) = kernel {
+        check_label_for_file(f, "kernel")?;
+    }
+    if let Some(f) = initrd {
+        check_label_for_file(f, "initrd")?;
+    }
+    Ok(())
+}
+fn check_label_for_file(file: &File, name: &str) -> Result<()> {
+    check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
+}
+
+/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
+#[derive(Debug)]
+struct VirtualMachine {
+    instance: Arc<VmInstance>,
+}
+
+impl VirtualMachine {
+    fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
+        BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
+    }
+}
+
+impl Interface for VirtualMachine {}
+
+impl IVirtualMachine for VirtualMachine {
+    fn getCid(&self) -> binder::Result<i32> {
+        // Don't check permission. The owner of the VM might have passed this binder object to
+        // others.
+        Ok(self.instance.cid as i32)
+    }
+
+    fn getState(&self) -> binder::Result<VirtualMachineState> {
+        // Don't check permission. The owner of the VM might have passed this binder object to
+        // others.
+        Ok(get_state(&self.instance))
+    }
+
+    fn registerCallback(
+        &self,
+        callback: &Strong<dyn IVirtualMachineCallback>,
+    ) -> binder::Result<()> {
+        // Don't check permission. The owner of the VM might have passed this binder object to
+        // others.
+        //
+        // TODO: Should this give an error if the VM is already dead?
+        self.instance.callbacks.add(callback.clone());
+        Ok(())
+    }
+
+    fn start(&self) -> binder::Result<()> {
+        self.instance.start().map_err(|e| {
+            error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
+            Status::new_service_specific_error_str(-1, Some(e.to_string()))
+        })
+    }
+
+    fn stop(&self) -> binder::Result<()> {
+        self.instance.kill().map_err(|e| {
+            error!("Error stopping VM with CID {}: {:?}", self.instance.cid, e);
+            Status::new_service_specific_error_str(-1, Some(e.to_string()))
+        })
+    }
+
+    fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> {
+        self.instance.trim_memory(level).map_err(|e| {
+            error!("Error trimming VM with CID {}: {:?}", self.instance.cid, e);
+            Status::new_service_specific_error_str(-1, Some(e.to_string()))
+        })
+    }
+
+    fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
+        if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
+            return Err(Status::new_service_specific_error_str(-1, Some("VM is not running")));
+        }
+        let port = port as u32;
+        if port < 1024 {
+            return Err(Status::new_service_specific_error_str(
+                -1,
+                Some(format!("Can't connect to privileged port {port}")),
+            ));
+        }
+        let stream = VsockStream::connect_with_cid_port(self.instance.cid, port).map_err(|e| {
+            Status::new_service_specific_error_str(-1, Some(format!("Failed to connect: {:?}", e)))
+        })?;
+        Ok(vsock_stream_to_pfd(stream))
+    }
+}
+
+impl Drop for VirtualMachine {
+    fn drop(&mut self) {
+        debug!("Dropping {:?}", self);
+        if let Err(e) = self.instance.kill() {
+            debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
+        }
+    }
+}
+
+/// A set of Binders to be called back in response to various events on the VM, such as when it
+/// dies.
+#[derive(Debug, Default)]
+pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
+
+impl VirtualMachineCallbacks {
+    /// Call all registered callbacks to notify that the payload has started.
+    pub fn notify_payload_started(&self, cid: Cid) {
+        let callbacks = &*self.0.lock().unwrap();
+        for callback in callbacks {
+            if let Err(e) = callback.onPayloadStarted(cid as i32) {
+                error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
+            }
+        }
+    }
+
+    /// Call all registered callbacks to notify that the payload is ready to serve.
+    pub fn notify_payload_ready(&self, cid: Cid) {
+        let callbacks = &*self.0.lock().unwrap();
+        for callback in callbacks {
+            if let Err(e) = callback.onPayloadReady(cid as i32) {
+                error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
+            }
+        }
+    }
+
+    /// Call all registered callbacks to notify that the payload has finished.
+    pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
+        let callbacks = &*self.0.lock().unwrap();
+        for callback in callbacks {
+            if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
+                error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
+            }
+        }
+    }
+
+    /// Call all registered callbacks to say that the VM encountered an error.
+    pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
+        let callbacks = &*self.0.lock().unwrap();
+        for callback in callbacks {
+            if let Err(e) = callback.onError(cid as i32, error_code, message) {
+                error!("Error notifying error event from VM CID {}: {:?}", cid, e);
+            }
+        }
+    }
+
+    /// Call all registered callbacks to say that the VM has died.
+    pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
+        let callbacks = &*self.0.lock().unwrap();
+        for callback in callbacks {
+            if let Err(e) = callback.onDied(cid as i32, reason) {
+                error!("Error notifying exit of VM CID {}: {:?}", cid, e);
+            }
+        }
+    }
+
+    /// Add a new callback to the set.
+    fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
+        self.0.lock().unwrap().push(callback);
+    }
+}
+
+/// The mutable state of the VirtualizationService. There should only be one instance of this
+/// struct.
+#[derive(Debug, Default)]
+struct State {
+    /// The VMs which have been started. When VMs are started a weak reference is added to this list
+    /// while a strong reference is returned to the caller over Binder. Once all copies of the
+    /// Binder client are dropped the weak reference here will become invalid, and will be removed
+    /// from the list opportunistically the next time `add_vm` is called.
+    vms: Vec<Weak<VmInstance>>,
+}
+
+impl State {
+    /// Get a list of VMs which still have Binder references to them.
+    fn vms(&self) -> Vec<Arc<VmInstance>> {
+        // Attempt to upgrade the weak pointers to strong pointers.
+        self.vms.iter().filter_map(Weak::upgrade).collect()
+    }
+
+    /// Add a new VM to the list.
+    fn add_vm(&mut self, vm: Weak<VmInstance>) {
+        // Garbage collect any entries from the stored list which no longer exist.
+        self.vms.retain(|vm| vm.strong_count() > 0);
+
+        // Actually add the new VM.
+        self.vms.push(vm);
+    }
+
+    /// Get a VM that corresponds to the given cid
+    fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
+        self.vms().into_iter().find(|vm| vm.cid == cid)
+    }
+}
+
+/// Gets the `VirtualMachineState` of the given `VmInstance`.
+fn get_state(instance: &VmInstance) -> VirtualMachineState {
+    match &*instance.vm_state.lock().unwrap() {
+        VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
+        VmState::Running { .. } => match instance.payload_state() {
+            PayloadState::Starting => VirtualMachineState::STARTING,
+            PayloadState::Started => VirtualMachineState::STARTED,
+            PayloadState::Ready => VirtualMachineState::READY,
+            PayloadState::Finished => VirtualMachineState::FINISHED,
+            PayloadState::Hangup => VirtualMachineState::DEAD,
+        },
+        VmState::Dead => VirtualMachineState::DEAD,
+        VmState::Failed => VirtualMachineState::DEAD,
+    }
+}
+
+/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
+pub fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
+    file.as_ref().try_clone().map_err(|e| {
+        Status::new_exception_str(
+            ExceptionCode::BAD_PARCELABLE,
+            Some(format!("Failed to clone File from ParcelFileDescriptor: {:?}", e)),
+        )
+    })
+}
+
+/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
+fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
+    file.as_ref().map(clone_file).transpose()
+}
+
+/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
+fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
+    // SAFETY: ownership is transferred from stream to f
+    let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
+    ParcelFileDescriptor::new(f)
+}
+
+/// Parses the platform version requirement string.
+fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
+    VersionReq::parse(s).map_err(|e| {
+        Status::new_exception_str(
+            ExceptionCode::BAD_PARCELABLE,
+            Some(format!("Invalid platform version requirement {}: {:?}", s, e)),
+        )
+    })
+}
+
+fn is_debuggable(config: &VirtualMachineConfig) -> bool {
+    match config {
+        VirtualMachineConfig::AppConfig(config) => config.debugLevel != DebugLevel::NONE,
+        _ => false,
+    }
+}
+
+fn clone_or_prepare_logger_fd(
+    config: &VirtualMachineConfig,
+    fd: Option<&ParcelFileDescriptor>,
+    tag: String,
+) -> Result<Option<File>, Status> {
+    if let Some(fd) = fd {
+        return Ok(Some(clone_file(fd)?));
+    }
+
+    if !is_debuggable(config) {
+        return Ok(None);
+    }
+
+    let (raw_read_fd, raw_write_fd) = pipe().map_err(|e| {
+        Status::new_service_specific_error_str(-1, Some(format!("Failed to create pipe: {:?}", e)))
+    })?;
+
+    // SAFETY: We are the sole owners of these fds as they were just created.
+    let mut reader = BufReader::new(unsafe { File::from_raw_fd(raw_read_fd) });
+    let write_fd = unsafe { File::from_raw_fd(raw_write_fd) };
+
+    std::thread::spawn(move || loop {
+        let mut buf = vec![];
+        match reader.read_until(b'\n', &mut buf) {
+            Ok(0) => {
+                // EOF
+                return;
+            }
+            Ok(size) => {
+                if buf[size - 1] == b'\n' {
+                    buf.pop();
+                }
+                info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
+            }
+            Err(e) => {
+                error!("Could not read console pipe: {:?}", e);
+                return;
+            }
+        };
+    });
+
+    Ok(Some(write_fd))
+}
+
+/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
+/// it doesn't require that T implements Clone.
+enum BorrowedOrOwned<'a, T> {
+    Borrowed(&'a T),
+    Owned(T),
+}
+
+impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
+    fn as_ref(&self) -> &T {
+        match self {
+            Self::Borrowed(b) => b,
+            Self::Owned(o) => o,
+        }
+    }
+}
+
+/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
+#[derive(Debug, Default)]
+struct VirtualMachineService {
+    state: Arc<Mutex<State>>,
+    cid: Cid,
+}
+
+impl Interface for VirtualMachineService {}
+
+impl IVirtualMachineService for VirtualMachineService {
+    fn notifyPayloadStarted(&self) -> binder::Result<()> {
+        let cid = self.cid;
+        if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
+            info!("VM with CID {} started payload", cid);
+            vm.update_payload_state(PayloadState::Started).map_err(|e| {
+                Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
+            })?;
+            vm.callbacks.notify_payload_started(cid);
+
+            let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
+            write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
+            Ok(())
+        } else {
+            error!("notifyPayloadStarted is called from an unknown CID {}", cid);
+            Err(Status::new_service_specific_error_str(
+                -1,
+                Some(format!("cannot find a VM with CID {}", cid)),
+            ))
+        }
+    }
+
+    fn notifyPayloadReady(&self) -> binder::Result<()> {
+        let cid = self.cid;
+        if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
+            info!("VM with CID {} reported payload is ready", cid);
+            vm.update_payload_state(PayloadState::Ready).map_err(|e| {
+                Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
+            })?;
+            vm.callbacks.notify_payload_ready(cid);
+            Ok(())
+        } else {
+            error!("notifyPayloadReady is called from an unknown CID {}", cid);
+            Err(Status::new_service_specific_error_str(
+                -1,
+                Some(format!("cannot find a VM with CID {}", cid)),
+            ))
+        }
+    }
+
+    fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
+        let cid = self.cid;
+        if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
+            info!("VM with CID {} finished payload", cid);
+            vm.update_payload_state(PayloadState::Finished).map_err(|e| {
+                Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
+            })?;
+            vm.callbacks.notify_payload_finished(cid, exit_code);
+            Ok(())
+        } else {
+            error!("notifyPayloadFinished is called from an unknown CID {}", cid);
+            Err(Status::new_service_specific_error_str(
+                -1,
+                Some(format!("cannot find a VM with CID {}", cid)),
+            ))
+        }
+    }
+
+    fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
+        let cid = self.cid;
+        if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
+            info!("VM with CID {} encountered an error", cid);
+            vm.update_payload_state(PayloadState::Finished).map_err(|e| {
+                Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
+            })?;
+            vm.callbacks.notify_error(cid, error_code, message);
+            Ok(())
+        } else {
+            error!("notifyError is called from an unknown CID {}", cid);
+            Err(Status::new_service_specific_error_str(
+                -1,
+                Some(format!("cannot find a VM with CID {}", cid)),
+            ))
+        }
+    }
+}
+
+impl VirtualMachineService {
+    fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
+        BnVirtualMachineService::new_binder(
+            VirtualMachineService { state, cid },
+            BinderFeatures::default(),
+        )
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_is_allowed_label_for_partition() -> Result<()> {
+        let expected_results = vec![
+            ("u:object_r:system_file:s0", true),
+            ("u:object_r:apk_data_file:s0", true),
+            ("u:object_r:app_data_file:s0", false),
+            ("u:object_r:app_data_file:s0:c512,c768", false),
+            ("u:object_r:privapp_data_file:s0:c512,c768", false),
+            ("invalid", false),
+            ("user:role:apk_data_file:severity:categories", true),
+            ("user:role:apk_data_file:severity:categories:extraneous", false),
+        ];
+
+        for (label, expected_valid) in expected_results {
+            let context = SeContext::new(label)?;
+            let result = check_label_is_allowed(&context);
+            if expected_valid {
+                assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
+            } else if result.is_ok() {
+                bail!("Expected label {} to be disallowed", label);
+            }
+        }
+        Ok(())
+    }
+
+    #[test]
+    fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
+        let apk = tempfile::tempfile().unwrap();
+        let idsig = tempfile::tempfile().unwrap();
+
+        let ret = create_or_update_idsig_file(
+            &ParcelFileDescriptor::new(apk),
+            &ParcelFileDescriptor::new(idsig),
+        );
+        assert!(ret.is_err(), "should fail");
+        Ok(())
+    }
+
+    #[test]
+    fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
+        let tmp_dir = tempfile::TempDir::new().unwrap();
+        let apk = File::open(tmp_dir.path()).unwrap();
+        let idsig = tempfile::tempfile().unwrap();
+
+        let ret = create_or_update_idsig_file(
+            &ParcelFileDescriptor::new(apk),
+            &ParcelFileDescriptor::new(idsig),
+        );
+        assert!(ret.is_err(), "should fail");
+        Ok(())
+    }
+
+    /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
+    /// on ext4 filesystem is passed.
+    /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
+    /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
+    /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
+    #[test]
+    fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
+        // APEXes are backed by the ext4.
+        let apk = File::open("/apex/com.android.virt/").unwrap();
+        let idsig = tempfile::tempfile().unwrap();
+
+        let ret = create_or_update_idsig_file(
+            &ParcelFileDescriptor::new(apk),
+            &ParcelFileDescriptor::new(idsig),
+        );
+        assert!(ret.is_err(), "should fail");
+        Ok(())
+    }
+}
diff --git a/virtualizationmanager/src/atom.rs b/virtualizationmanager/src/atom.rs
new file mode 100644
index 0000000..c33f262
--- /dev/null
+++ b/virtualizationmanager/src/atom.rs
@@ -0,0 +1,186 @@
+// Copyright 2022, 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.
+
+//! Functions for creating and collecting atoms.
+
+use crate::aidl::{clone_file, GLOBAL_SERVICE};
+use crate::crosvm::VmMetric;
+use crate::get_calling_uid;
+use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::DeathReason::DeathReason;
+use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
+    IVirtualMachine::IVirtualMachine,
+    VirtualMachineAppConfig::{Payload::Payload, VirtualMachineAppConfig},
+    VirtualMachineConfig::VirtualMachineConfig,
+};
+use android_system_virtualizationservice::binder::{Status, Strong};
+use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::{
+    AtomVmBooted::AtomVmBooted,
+    AtomVmCreationRequested::AtomVmCreationRequested,
+    AtomVmExited::AtomVmExited,
+};
+use anyhow::{anyhow, Result};
+use binder::ParcelFileDescriptor;
+use log::warn;
+use microdroid_payload_config::VmPayloadConfig;
+use statslog_virtualization_rust::vm_creation_requested;
+use std::thread;
+use std::time::{Duration, SystemTime};
+use zip::ZipArchive;
+
+fn get_apex_list(config: &VirtualMachineAppConfig) -> String {
+    match &config.payload {
+        Payload::PayloadConfig(_) => String::new(),
+        Payload::ConfigPath(config_path) => {
+            let vm_payload_config = get_vm_payload_config(&config.apk, config_path);
+            if let Ok(vm_payload_config) = vm_payload_config {
+                vm_payload_config
+                    .apexes
+                    .iter()
+                    .map(|x| x.name.clone())
+                    .collect::<Vec<String>>()
+                    .join(":")
+            } else {
+                "INFO: Can't get VmPayloadConfig".to_owned()
+            }
+        }
+    }
+}
+
+fn get_vm_payload_config(
+    apk_fd: &Option<ParcelFileDescriptor>,
+    config_path: &str,
+) -> Result<VmPayloadConfig> {
+    let apk = apk_fd.as_ref().ok_or_else(|| anyhow!("APK is none"))?;
+    let apk_file = clone_file(apk)?;
+    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)?;
+    Ok(vm_payload_config)
+}
+
+fn get_duration(vm_start_timestamp: Option<SystemTime>) -> Duration {
+    match vm_start_timestamp {
+        Some(vm_start_timestamp) => vm_start_timestamp.elapsed().unwrap_or_default(),
+        None => Duration::default(),
+    }
+}
+
+/// Write the stats of VMCreation to statsd
+pub fn write_vm_creation_stats(
+    config: &VirtualMachineConfig,
+    is_protected: bool,
+    ret: &binder::Result<Strong<dyn IVirtualMachine>>,
+) {
+    let creation_succeeded;
+    let binder_exception_code;
+    match ret {
+        Ok(_) => {
+            creation_succeeded = true;
+            binder_exception_code = Status::ok().exception_code() as i32;
+        }
+        Err(ref e) => {
+            creation_succeeded = false;
+            binder_exception_code = e.exception_code() as i32;
+        }
+    }
+    let (vm_identifier, config_type, num_cpus, memory_mib, apexes) = match config {
+        VirtualMachineConfig::AppConfig(config) => (
+            config.name.clone(),
+            vm_creation_requested::ConfigType::VirtualMachineAppConfig,
+            config.numCpus,
+            config.memoryMib,
+            get_apex_list(config),
+        ),
+        VirtualMachineConfig::RawConfig(config) => (
+            config.name.clone(),
+            vm_creation_requested::ConfigType::VirtualMachineRawConfig,
+            config.numCpus,
+            config.memoryMib,
+            String::new(),
+        ),
+    };
+
+    let atom = AtomVmCreationRequested {
+        uid: get_calling_uid() as i32,
+        vmIdentifier: vm_identifier,
+        isProtected: is_protected,
+        creationSucceeded: creation_succeeded,
+        binderExceptionCode: binder_exception_code,
+        configType: config_type as i32,
+        numCpus: num_cpus,
+        memoryMib: memory_mib,
+        apexes,
+    };
+
+    thread::spawn(move || {
+        GLOBAL_SERVICE.atomVmCreationRequested(&atom).unwrap_or_else(|e| {
+            warn!("Failed to write VmCreationRequested atom: {e}");
+        });
+    });
+}
+
+/// Write the stats of VM boot to statsd
+/// The function creates a separate thread which waits fro statsd to start to push atom
+pub fn write_vm_booted_stats(
+    uid: i32,
+    vm_identifier: &str,
+    vm_start_timestamp: Option<SystemTime>,
+) {
+    let vm_identifier = vm_identifier.to_owned();
+    let duration = get_duration(vm_start_timestamp);
+
+    let atom = AtomVmBooted {
+        uid,
+        vmIdentifier: vm_identifier,
+        elapsedTimeMillis: duration.as_millis() as i64,
+    };
+
+    thread::spawn(move || {
+        GLOBAL_SERVICE.atomVmBooted(&atom).unwrap_or_else(|e| {
+            warn!("Failed to write VmCreationRequested atom: {e}");
+        });
+    });
+}
+
+/// Write the stats of VM exit to statsd
+/// The function creates a separate thread which waits fro statsd to start to push atom
+pub fn write_vm_exited_stats(
+    uid: i32,
+    vm_identifier: &str,
+    reason: DeathReason,
+    exit_signal: Option<i32>,
+    vm_metric: &VmMetric,
+) {
+    let vm_identifier = vm_identifier.to_owned();
+    let elapsed_time_millis = get_duration(vm_metric.start_timestamp).as_millis() as i64;
+    let guest_time_millis = vm_metric.cpu_guest_time.unwrap_or_default();
+    let rss = vm_metric.rss.unwrap_or_default();
+
+    let atom = AtomVmExited {
+        uid,
+        vmIdentifier: vm_identifier,
+        elapsedTimeMillis: elapsed_time_millis,
+        deathReason: reason,
+        guestTimeMillis: guest_time_millis,
+        rssVmKb: rss.vm,
+        rssCrosvmKb: rss.crosvm,
+        exitSignal: exit_signal.unwrap_or_default(),
+    };
+
+    thread::spawn(move || {
+        GLOBAL_SERVICE.atomVmExited(&atom).unwrap_or_else(|e| {
+            warn!("Failed to write VmExited atom: {e}");
+        });
+    });
+}
diff --git a/virtualizationservice/src/composite.rs b/virtualizationmanager/src/composite.rs
similarity index 100%
rename from virtualizationservice/src/composite.rs
rename to virtualizationmanager/src/composite.rs
diff --git a/virtualizationservice/src/crosvm.rs b/virtualizationmanager/src/crosvm.rs
similarity index 99%
rename from virtualizationservice/src/crosvm.rs
rename to virtualizationmanager/src/crosvm.rs
index 98e7d99..8f88daf 100644
--- a/virtualizationservice/src/crosvm.rs
+++ b/virtualizationmanager/src/crosvm.rs
@@ -78,9 +78,9 @@
     /// triggered.
     static ref BOOT_HANGUP_TIMEOUT: Duration = if nested_virt::is_nested_virtualization().unwrap() {
         // Nested virtualization is slow, so we need a longer timeout.
-        Duration::from_secs(100)
+        Duration::from_secs(300)
     } else {
-        Duration::from_secs(10)
+        Duration::from_secs(30)
     };
 }
 
@@ -376,7 +376,7 @@
             &self.name,
             death_reason,
             exit_signal,
-            &*vm_metric,
+            &vm_metric,
         );
 
         // Delete temporary files. The folder itself is removed by VirtualizationServiceInternal.
@@ -575,7 +575,7 @@
 
     let guest_time_ticks = data_list[42].parse::<i64>()?;
     // SAFETY : It just returns an integer about CPU tick information.
-    let ticks_per_sec = unsafe { sysconf(_SC_CLK_TCK) } as i64;
+    let ticks_per_sec = unsafe { sysconf(_SC_CLK_TCK) };
     Ok(guest_time_ticks * MILLIS_PER_SEC / ticks_per_sec)
 }
 
@@ -678,7 +678,7 @@
         // Configure the logger for the crosvm process to silence logs from the disk crate which
         // don't provide much information to us (but do spamming us).
         .arg("--log-level")
-        .arg("info,disk=off")
+        .arg("info,disk=warn")
         .arg("run")
         .arg("--disable-sandbox")
         .arg("--cid")
diff --git a/virtualizationservice/src/virtmgr.rs b/virtualizationmanager/src/main.rs
similarity index 100%
rename from virtualizationservice/src/virtmgr.rs
rename to virtualizationmanager/src/main.rs
diff --git a/virtualizationservice/src/payload.rs b/virtualizationmanager/src/payload.rs
similarity index 100%
rename from virtualizationservice/src/payload.rs
rename to virtualizationmanager/src/payload.rs
diff --git a/virtualizationservice/src/selinux.rs b/virtualizationmanager/src/selinux.rs
similarity index 100%
rename from virtualizationservice/src/selinux.rs
rename to virtualizationmanager/src/selinux.rs
diff --git a/virtualizationservice/Android.bp b/virtualizationservice/Android.bp
index d0dde42..f7202da 100644
--- a/virtualizationservice/Android.bp
+++ b/virtualizationservice/Android.bp
@@ -2,10 +2,11 @@
     default_applicable_licenses: ["Android-Apache-2.0"],
 }
 
-rust_defaults {
-    name: "virtualizationservice_defaults",
+rust_binary {
+    name: "virtualizationservice",
     crate_name: "virtualizationservice",
     edition: "2021",
+    srcs: ["src/main.rs"],
     // Only build on targets which crosvm builds on.
     enabled: false,
     target: {
@@ -26,66 +27,14 @@
         "android.os.permissions_aidl-rust",
         "libandroid_logger",
         "libanyhow",
-        "libapkverify",
-        "libbase_rust",
         "libbinder_rs",
-        "libcommand_fds",
-        "libdisk",
-        "liblazy_static",
         "liblibc",
         "liblog_rust",
-        "libmicrodroid_metadata",
-        "libmicrodroid_payload_config",
-        "libnested_virt",
         "libnix",
-        "libonce_cell",
-        "libregex",
-        "librpcbinder_rs",
         "librustutils",
-        "libsemver",
-        "libselinux_bindgen",
-        "libserde",
-        "libserde_json",
-        "libserde_xml_rs",
-        "libshared_child",
         "libstatslog_virtualization_rust",
         "libtombstoned_client_rust",
-        "libvm_control",
-        "libvmconfig",
-        "libzip",
         "libvsock",
-        // TODO(b/202115393) stabilize the interface
-        "packagemanager_aidl-rust",
-    ],
-    shared_libs: [
-        "libbinder_rpc_unstable",
-        "libselinux",
-    ],
-}
-
-rust_binary {
-    name: "virtualizationservice",
-    defaults: ["virtualizationservice_defaults"],
-    srcs: ["src/main.rs"],
-    apex_available: ["com.android.virt"],
-}
-
-rust_binary {
-    name: "virtmgr",
-    defaults: ["virtualizationservice_defaults"],
-    srcs: ["src/virtmgr.rs"],
-    rustlibs: [
-        "libclap",
     ],
     apex_available: ["com.android.virt"],
 }
-
-rust_test {
-    name: "virtualizationservice_device_test",
-    srcs: ["src/main.rs"],
-    defaults: ["virtualizationservice_defaults"],
-    rustlibs: [
-        "libtempfile",
-    ],
-    test_suites: ["general-tests"],
-}
diff --git a/virtualizationservice/TEST_MAPPING b/virtualizationservice/TEST_MAPPING
deleted file mode 100644
index 8388ff2..0000000
--- a/virtualizationservice/TEST_MAPPING
+++ /dev/null
@@ -1,7 +0,0 @@
-{
-  "avf-presubmit": [
-    {
-      "name": "virtualizationservice_device_test"
-    }
-  ]
-}
diff --git a/virtualizationservice/aidl/android/system/virtualizationservice/IVirtualizationService.aidl b/virtualizationservice/aidl/android/system/virtualizationservice/IVirtualizationService.aidl
index fc4c9e7..d72d5ac 100644
--- a/virtualizationservice/aidl/android/system/virtualizationservice/IVirtualizationService.aidl
+++ b/virtualizationservice/aidl/android/system/virtualizationservice/IVirtualizationService.aidl
@@ -37,7 +37,7 @@
      * The file must be open with both read and write permissions, and should be a new empty file.
      */
     void initializeWritablePartition(
-            in ParcelFileDescriptor imageFd, long size, PartitionType type);
+            in ParcelFileDescriptor imageFd, long sizeBytes, PartitionType type);
 
     /**
      * Create or update an idsig file that digests the given APK file. The idsig file follows the
diff --git a/virtualizationservice/src/aidl.rs b/virtualizationservice/src/aidl.rs
index 374b90f..e0b78ba 100644
--- a/virtualizationservice/src/aidl.rs
+++ b/virtualizationservice/src/aidl.rs
@@ -15,33 +15,9 @@
 //! Implementation of the AIDL interface of the VirtualizationService.
 
 use crate::{get_calling_pid, get_calling_uid};
-use crate::atom::{
-    forward_vm_booted_atom, forward_vm_creation_atom, forward_vm_exited_atom,
-    write_vm_booted_stats, write_vm_creation_stats};
-use crate::composite::make_composite_image;
-use crate::crosvm::{CrosvmConfig, DiskFile, PayloadState, VmContext, VmInstance, VmState};
-use crate::payload::{add_microdroid_payload_images, add_microdroid_system_images};
-use crate::selinux::{getfilecon, SeContext};
+use crate::atom::{forward_vm_booted_atom, forward_vm_creation_atom, forward_vm_exited_atom};
 use android_os_permissions_aidl::aidl::android::os::IPermissionController;
-use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::{
-    DeathReason::DeathReason,
-    ErrorCode::ErrorCode,
-};
-use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
-    DiskImage::DiskImage,
-    IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
-    IVirtualMachineCallback::IVirtualMachineCallback,
-    IVirtualizationService::IVirtualizationService,
-    MemoryTrimLevel::MemoryTrimLevel,
-    Partition::Partition,
-    PartitionType::PartitionType,
-    VirtualMachineAppConfig::{Payload::Payload, VirtualMachineAppConfig},
-    VirtualMachineConfig::VirtualMachineConfig,
-    VirtualMachineDebugInfo::VirtualMachineDebugInfo,
-    VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
-    VirtualMachineRawConfig::VirtualMachineRawConfig,
-    VirtualMachineState::VirtualMachineState,
-};
+use android_system_virtualizationservice::aidl::android::system::virtualizationservice::VirtualMachineDebugInfo::VirtualMachineDebugInfo;
 use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::{
     AtomVmBooted::AtomVmBooted,
     AtomVmCreationRequested::AtomVmCreationRequested,
@@ -49,38 +25,21 @@
     IGlobalVmContext::{BnGlobalVmContext, IGlobalVmContext},
     IVirtualizationServiceInternal::IVirtualizationServiceInternal,
 };
-use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
-        BnVirtualMachineService, IVirtualMachineService, VM_TOMBSTONES_SERVICE_PORT,
-};
+use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::VM_TOMBSTONES_SERVICE_PORT;
 use anyhow::{anyhow, bail, Context, Result};
-use apkverify::{HashAlgorithm, V4Signature};
-use binder::{
-    self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, LazyServiceGuard,
-    ParcelFileDescriptor, Status, StatusCode, Strong,
-};
-use disk::QcowFile;
-use lazy_static::lazy_static;
+use binder::{self, BinderFeatures, ExceptionCode, Interface, LazyServiceGuard, Status, Strong};
 use libc::VMADDR_CID_HOST;
-use log::{debug, error, info, warn};
-use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
-use rpcbinder::RpcServer;
+use log::{error, info, warn};
 use rustutils::system_properties;
-use semver::VersionReq;
 use std::collections::HashMap;
-use std::convert::TryInto;
-use std::ffi::CStr;
-use std::fs::{create_dir, read_dir, remove_dir, remove_file, set_permissions, File, OpenOptions, Permissions};
-use std::io::{Error, ErrorKind, Read, Write};
-use std::num::NonZeroU32;
+use std::fs::{create_dir, read_dir, remove_dir, remove_file, set_permissions, Permissions};
+use std::io::{Read, Write};
 use std::os::unix::fs::PermissionsExt;
-use std::os::unix::io::{FromRawFd, IntoRawFd};
 use std::os::unix::raw::{pid_t, uid_t};
-use std::path::{Path, PathBuf};
+use std::path::PathBuf;
 use std::sync::{Arc, Mutex, Weak};
 use tombstoned_client::{DebuggerdDumpType, TombstonedConnection};
-use vmconfig::VmConfig;
 use vsock::{VsockListener, VsockStream};
-use zip::ZipArchive;
 use nix::unistd::{chown, Uid};
 
 /// The unique ID of a VM used (together with a port number) for vsock communication.
@@ -98,50 +57,12 @@
 
 const SYSPROP_LAST_CID: &str = "virtualizationservice.state.last_cid";
 
-/// The size of zero.img.
-/// Gaps in composite disk images are filled with a shared zero.img.
-const ZERO_FILLER_SIZE: u64 = 4096;
-
-/// Magic string for the instance image
-const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
-
-/// Version of the instance image format
-const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
-
 const CHUNK_RECV_MAX_LEN: usize = 1024;
 
-const MICRODROID_OS_NAME: &str = "microdroid";
-
-const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
-
-lazy_static! {
-    pub static ref GLOBAL_SERVICE: Strong<dyn IVirtualizationServiceInternal> =
-        wait_for_interface(BINDER_SERVICE_IDENTIFIER)
-            .expect("Could not connect to VirtualizationServiceInternal");
-}
-
 fn is_valid_guest_cid(cid: Cid) -> bool {
     (GUEST_CID_MIN..=GUEST_CID_MAX).contains(&cid)
 }
 
-fn create_or_update_idsig_file(
-    input_fd: &ParcelFileDescriptor,
-    idsig_fd: &ParcelFileDescriptor,
-) -> Result<()> {
-    let mut input = clone_file(input_fd)?;
-    let metadata = input.metadata().context("failed to get input metadata")?;
-    if !metadata.is_file() {
-        bail!("input is not a regular file");
-    }
-    let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256)
-        .context("failed to create idsig")?;
-
-    let mut output = clone_file(idsig_fd)?;
-    output.set_len(0).context("failed to set_len on the idsig output")?;
-    sig.write_into(&mut output).context("failed to write idsig")?;
-    Ok(())
-}
-
 /// Singleton service for allocating globally-unique VM resources, such as the CID, and running
 /// singleton servers, like tombstone receiver.
 #[derive(Debug, Default)]
@@ -150,9 +71,6 @@
 }
 
 impl VirtualizationServiceInternal {
-    // TODO(b/245727626): Remove after the source files for virtualizationservice
-    // and virtmgr binaries are split from each other.
-    #[allow(dead_code)]
     pub fn init() -> VirtualizationServiceInternal {
         let service = VirtualizationServiceInternal::default();
 
@@ -193,6 +111,8 @@
         &self,
         requester_debug_pid: i32,
     ) -> binder::Result<Strong<dyn IGlobalVmContext>> {
+        check_manage_access()?;
+
         let requester_uid = get_calling_uid();
         let requester_debug_pid = requester_debug_pid as pid_t;
         let state = &mut *self.state.lock().unwrap();
@@ -217,6 +137,8 @@
     }
 
     fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
+        check_debug_access()?;
+
         let state = &mut *self.state.lock().unwrap();
         let cids = state
             .held_contexts
@@ -226,7 +148,7 @@
                 cid: vm.cid as i32,
                 temporaryDirectory: vm.get_temp_dir().to_string_lossy().to_string(),
                 requesterUid: vm.requester_uid as i32,
-                requesterPid: vm.requester_debug_pid as i32,
+                requesterPid: vm.requester_debug_pid,
             })
             .collect();
         Ok(cids)
@@ -385,125 +307,6 @@
     }
 }
 
-/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
-#[derive(Debug, Default)]
-pub struct VirtualizationService {
-    state: Arc<Mutex<State>>,
-}
-
-impl Interface for VirtualizationService {
-    fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
-        check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
-        let state = &mut *self.state.lock().unwrap();
-        let vms = state.vms();
-        writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
-        for vm in vms {
-            writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
-            writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
-                .or(Err(StatusCode::UNKNOWN_ERROR))?;
-            writeln!(file, "\tPayload state {:?}", vm.payload_state())
-                .or(Err(StatusCode::UNKNOWN_ERROR))?;
-            writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
-            writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
-                .or(Err(StatusCode::UNKNOWN_ERROR))?;
-            writeln!(file, "\trequester_uid: {}", vm.requester_uid)
-                .or(Err(StatusCode::UNKNOWN_ERROR))?;
-            writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
-                .or(Err(StatusCode::UNKNOWN_ERROR))?;
-        }
-        Ok(())
-    }
-}
-
-impl IVirtualizationService for VirtualizationService {
-    /// Creates (but does not start) a new VM with the given configuration, assigning it the next
-    /// available CID.
-    ///
-    /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
-    fn createVm(
-        &self,
-        config: &VirtualMachineConfig,
-        console_fd: Option<&ParcelFileDescriptor>,
-        log_fd: Option<&ParcelFileDescriptor>,
-    ) -> binder::Result<Strong<dyn IVirtualMachine>> {
-        let mut is_protected = false;
-        let ret = self.create_vm_internal(config, console_fd, log_fd, &mut is_protected);
-        write_vm_creation_stats(config, is_protected, &ret);
-        ret
-    }
-
-    /// Initialise an empty partition image of the given size to be used as a writable partition.
-    fn initializeWritablePartition(
-        &self,
-        image_fd: &ParcelFileDescriptor,
-        size: i64,
-        partition_type: PartitionType,
-    ) -> binder::Result<()> {
-        check_manage_access()?;
-        let size = size.try_into().map_err(|e| {
-            Status::new_exception_str(
-                ExceptionCode::ILLEGAL_ARGUMENT,
-                Some(format!("Invalid size {}: {:?}", size, e)),
-            )
-        })?;
-        let image = clone_file(image_fd)?;
-        // initialize the file. Any data in the file will be erased.
-        image.set_len(0).map_err(|e| {
-            Status::new_service_specific_error_str(
-                -1,
-                Some(format!("Failed to reset a file: {:?}", e)),
-            )
-        })?;
-        let mut part = QcowFile::new(image, size).map_err(|e| {
-            Status::new_service_specific_error_str(
-                -1,
-                Some(format!("Failed to create QCOW2 image: {:?}", e)),
-            )
-        })?;
-
-        match partition_type {
-            PartitionType::RAW => Ok(()),
-            PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
-            PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part),
-            _ => Err(Error::new(
-                ErrorKind::Unsupported,
-                format!("Unsupported partition type {:?}", partition_type),
-            )),
-        }
-        .map_err(|e| {
-            Status::new_service_specific_error_str(
-                -1,
-                Some(format!("Failed to initialize partition as {:?}: {:?}", partition_type, e)),
-            )
-        })?;
-
-        Ok(())
-    }
-
-    /// Creates or update the idsig file by digesting the input APK file.
-    fn createOrUpdateIdsigFile(
-        &self,
-        input_fd: &ParcelFileDescriptor,
-        idsig_fd: &ParcelFileDescriptor,
-    ) -> binder::Result<()> {
-        // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
-        // idsig_fd is different from APK digest in input_fd
-
-        check_manage_access()?;
-
-        create_or_update_idsig_file(input_fd, idsig_fd)
-            .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
-        Ok(())
-    }
-
-    /// Get a list of all currently running VMs. This method is only intended for debug purposes,
-    /// and as such is only permitted from the shell user.
-    fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
-        check_debug_access()?;
-        GLOBAL_SERVICE.debugListVms()
-    }
-}
-
 fn handle_stream_connection_tombstoned() -> Result<()> {
     // Should not listen for tombstones on a guest VM's port.
     assert!(!is_valid_guest_cid(VM_TOMBSTONES_SERVICE_PORT as Cid));
@@ -554,398 +357,6 @@
     Ok(())
 }
 
-impl VirtualizationService {
-    // TODO(b/245727626): Remove after the source files for virtualizationservice
-    // and virtmgr binaries are split from each other.
-    #[allow(dead_code)]
-    pub fn init() -> VirtualizationService {
-        VirtualizationService::default()
-    }
-
-    fn create_vm_context(&self, requester_debug_pid: pid_t) -> Result<(VmContext, Cid, PathBuf)> {
-        const NUM_ATTEMPTS: usize = 5;
-
-        for _ in 0..NUM_ATTEMPTS {
-            let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid as i32)?;
-            let cid = vm_context.getCid()? as Cid;
-            let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
-            let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
-
-            // Start VM service listening for connections from the new CID on port=CID.
-            let port = cid;
-            match RpcServer::new_vsock(service, cid, port) {
-                Ok(vm_server) => {
-                    vm_server.start();
-                    return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
-                }
-                Err(err) => {
-                    warn!("Could not start RpcServer on port {}: {}", port, err);
-                }
-            }
-        }
-        bail!("Too many attempts to create VM context failed.");
-    }
-
-    fn create_vm_internal(
-        &self,
-        config: &VirtualMachineConfig,
-        console_fd: Option<&ParcelFileDescriptor>,
-        log_fd: Option<&ParcelFileDescriptor>,
-        is_protected: &mut bool,
-    ) -> binder::Result<Strong<dyn IVirtualMachine>> {
-        check_manage_access()?;
-
-        let is_custom = match config {
-            VirtualMachineConfig::RawConfig(_) => true,
-            VirtualMachineConfig::AppConfig(config) => {
-                // Some features are reserved for platform apps only, even when using
-                // VirtualMachineAppConfig:
-                // - controlling CPUs;
-                // - specifying a config file in the APK.
-                !config.taskProfiles.is_empty() || matches!(config.payload, Payload::ConfigPath(_))
-            }
-        };
-        if is_custom {
-            check_use_custom_virtual_machine()?;
-        }
-
-        let requester_uid = get_calling_uid();
-        let requester_debug_pid = get_calling_pid();
-
-        let (vm_context, cid, temporary_directory) =
-            self.create_vm_context(requester_debug_pid).map_err(|e| {
-                error!("Failed to create VmContext: {:?}", e);
-                Status::new_service_specific_error_str(
-                    -1,
-                    Some(format!("Failed to create VmContext: {:?}", e)),
-                )
-            })?;
-
-        let state = &mut *self.state.lock().unwrap();
-        let console_fd = console_fd.map(clone_file).transpose()?;
-        let log_fd = log_fd.map(clone_file).transpose()?;
-
-        // Counter to generate unique IDs for temporary image files.
-        let mut next_temporary_image_id = 0;
-        // Files which are referred to from composite images. These must be mapped to the crosvm
-        // child process, and not closed before it is started.
-        let mut indirect_files = vec![];
-
-        let (is_app_config, config) = match config {
-            VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
-            VirtualMachineConfig::AppConfig(config) => {
-                let config = load_app_config(config, &temporary_directory).map_err(|e| {
-                    *is_protected = config.protectedVm;
-                    let message = format!("Failed to load app config: {:?}", e);
-                    error!("{}", message);
-                    Status::new_service_specific_error_str(-1, Some(message))
-                })?;
-                (true, BorrowedOrOwned::Owned(config))
-            }
-        };
-        let config = config.as_ref();
-        *is_protected = config.protectedVm;
-
-        // Check if partition images are labeled incorrectly. This is to prevent random images
-        // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
-        // being loaded in a pVM. This applies to everything in the raw config, and everything but
-        // the non-executable, generated partitions in the app config.
-        config
-            .disks
-            .iter()
-            .flat_map(|disk| disk.partitions.iter())
-            .filter(|partition| {
-                if is_app_config {
-                    !is_safe_app_partition(&partition.label)
-                } else {
-                    true // all partitions are checked
-                }
-            })
-            .try_for_each(check_label_for_partition)
-            .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
-
-        let kernel = maybe_clone_file(&config.kernel)?;
-        let initrd = maybe_clone_file(&config.initrd)?;
-
-        // In a protected VM, we require custom kernels to come from a trusted source (b/237054515).
-        if config.protectedVm {
-            check_label_for_kernel_files(&kernel, &initrd).map_err(|e| {
-                Status::new_service_specific_error_str(-1, Some(format!("{:?}", e)))
-            })?;
-        }
-
-        let zero_filler_path = temporary_directory.join("zero.img");
-        write_zero_filler(&zero_filler_path).map_err(|e| {
-            error!("Failed to make composite image: {:?}", e);
-            Status::new_service_specific_error_str(
-                -1,
-                Some(format!("Failed to make composite image: {:?}", e)),
-            )
-        })?;
-
-        // Assemble disk images if needed.
-        let disks = config
-            .disks
-            .iter()
-            .map(|disk| {
-                assemble_disk_image(
-                    disk,
-                    &zero_filler_path,
-                    &temporary_directory,
-                    &mut next_temporary_image_id,
-                    &mut indirect_files,
-                )
-            })
-            .collect::<Result<Vec<DiskFile>, _>>()?;
-
-        // Creating this ramdump file unconditionally is not harmful as ramdump will be created
-        // only when the VM is configured as such. `ramdump_write` is sent to crosvm and will
-        // be the backing store for the /dev/hvc1 where VM will emit ramdump to. `ramdump_read`
-        // will be sent back to the client (i.e. the VM owner) for readout.
-        let ramdump_path = temporary_directory.join("ramdump");
-        let ramdump = prepare_ramdump_file(&ramdump_path).map_err(|e| {
-            error!("Failed to prepare ramdump file: {:?}", e);
-            Status::new_service_specific_error_str(
-                -1,
-                Some(format!("Failed to prepare ramdump file: {:?}", e)),
-            )
-        })?;
-
-        // Actually start the VM.
-        let crosvm_config = CrosvmConfig {
-            cid,
-            name: config.name.clone(),
-            bootloader: maybe_clone_file(&config.bootloader)?,
-            kernel,
-            initrd,
-            disks,
-            params: config.params.to_owned(),
-            protected: *is_protected,
-            memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
-            cpus: config.numCpus.try_into().ok().and_then(NonZeroU32::new),
-            task_profiles: config.taskProfiles.clone(),
-            console_fd,
-            log_fd,
-            ramdump: Some(ramdump),
-            indirect_files,
-            platform_version: parse_platform_version_req(&config.platformVersion)?,
-            detect_hangup: is_app_config,
-        };
-        let instance = Arc::new(
-            VmInstance::new(
-                crosvm_config,
-                temporary_directory,
-                requester_uid,
-                requester_debug_pid,
-                vm_context,
-            )
-            .map_err(|e| {
-                error!("Failed to create VM with config {:?}: {:?}", config, e);
-                Status::new_service_specific_error_str(
-                    -1,
-                    Some(format!("Failed to create VM: {:?}", e)),
-                )
-            })?,
-        );
-        state.add_vm(Arc::downgrade(&instance));
-        Ok(VirtualMachine::create(instance))
-    }
-}
-
-fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
-    let file = OpenOptions::new()
-        .create_new(true)
-        .read(true)
-        .write(true)
-        .open(zero_filler_path)
-        .with_context(|| "Failed to create zero.img")?;
-    file.set_len(ZERO_FILLER_SIZE)?;
-    Ok(())
-}
-
-fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
-    part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
-    part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
-    part.flush()
-}
-
-fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
-    part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
-    part.flush()
-}
-
-fn prepare_ramdump_file(ramdump_path: &Path) -> Result<File> {
-    File::create(ramdump_path).context(format!("Failed to create ramdump file {:?}", &ramdump_path))
-}
-
-/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
-///
-/// This may involve assembling a composite disk from a set of partition images.
-fn assemble_disk_image(
-    disk: &DiskImage,
-    zero_filler_path: &Path,
-    temporary_directory: &Path,
-    next_temporary_image_id: &mut u64,
-    indirect_files: &mut Vec<File>,
-) -> Result<DiskFile, Status> {
-    let image = if !disk.partitions.is_empty() {
-        if disk.image.is_some() {
-            warn!("DiskImage {:?} contains both image and partitions.", disk);
-            return Err(Status::new_exception_str(
-                ExceptionCode::ILLEGAL_ARGUMENT,
-                Some("DiskImage contains both image and partitions."),
-            ));
-        }
-
-        let composite_image_filenames =
-            make_composite_image_filenames(temporary_directory, next_temporary_image_id);
-        let (image, partition_files) = make_composite_image(
-            &disk.partitions,
-            zero_filler_path,
-            &composite_image_filenames.composite,
-            &composite_image_filenames.header,
-            &composite_image_filenames.footer,
-        )
-        .map_err(|e| {
-            error!("Failed to make composite image with config {:?}: {:?}", disk, e);
-            Status::new_service_specific_error_str(
-                -1,
-                Some(format!("Failed to make composite image: {:?}", e)),
-            )
-        })?;
-
-        // Pass the file descriptors for the various partition files to crosvm when it
-        // is run.
-        indirect_files.extend(partition_files);
-
-        image
-    } else if let Some(image) = &disk.image {
-        clone_file(image)?
-    } else {
-        warn!("DiskImage {:?} didn't contain image or partitions.", disk);
-        return Err(Status::new_exception_str(
-            ExceptionCode::ILLEGAL_ARGUMENT,
-            Some("DiskImage didn't contain image or partitions."),
-        ));
-    };
-
-    Ok(DiskFile { image, writable: disk.writable })
-}
-
-fn load_app_config(
-    config: &VirtualMachineAppConfig,
-    temporary_directory: &Path,
-) -> Result<VirtualMachineRawConfig> {
-    let apk_file = clone_file(config.apk.as_ref().unwrap())?;
-    let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
-    let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
-
-    let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
-        Some(clone_file(file)?)
-    } else {
-        None
-    };
-
-    let vm_payload_config = match &config.payload {
-        Payload::ConfigPath(config_path) => {
-            load_vm_payload_config_from_file(&apk_file, config_path.as_str())
-                .with_context(|| format!("Couldn't read config from {}", config_path))?
-        }
-        Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
-    };
-
-    // For now, the only supported OS is Microdroid
-    let os_name = vm_payload_config.os.name.as_str();
-    if os_name != MICRODROID_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)?.to_parcelable()?;
-
-    if config.memoryMib > 0 {
-        vm_config.memoryMib = config.memoryMib;
-    }
-
-    vm_config.name = config.name.clone();
-    vm_config.protectedVm = config.protectedVm;
-    vm_config.numCpus = config.numCpus;
-    vm_config.taskProfiles = config.taskProfiles.clone();
-
-    // Microdroid takes additional init ramdisk & (optionally) storage image
-    add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
-
-    // Include Microdroid payload disk (contains apks, idsigs) in vm config
-    add_microdroid_payload_images(
-        config,
-        temporary_directory,
-        apk_file,
-        idsig_file,
-        &vm_payload_config,
-        &mut vm_config,
-    )?;
-
-    Ok(vm_config)
-}
-
-fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
-    let mut apk_zip = ZipArchive::new(apk_file)?;
-    let config_file = apk_zip.by_name(config_path)?;
-    Ok(serde_json::from_reader(config_file)?)
-}
-
-fn create_vm_payload_config(
-    payload_config: &VirtualMachinePayloadConfig,
-) -> Result<VmPayloadConfig> {
-    // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
-    // parameters we've been given. Microdroid will do something equivalent inside the VM using the
-    // payload config that we send it via the metadata file.
-
-    let payload_binary_name = &payload_config.payloadBinaryName;
-    if payload_binary_name.contains('/') {
-        bail!("Payload binary name must not specify a path: {payload_binary_name}");
-    }
-
-    let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
-    Ok(VmPayloadConfig {
-        os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
-        task: Some(task),
-        apexes: vec![],
-        extra_apks: vec![],
-        prefer_staged: false,
-        export_tombstones: false,
-        enable_authfs: false,
-    })
-}
-
-/// Generates a unique filename to use for a composite disk image.
-fn make_composite_image_filenames(
-    temporary_directory: &Path,
-    next_temporary_image_id: &mut u64,
-) -> CompositeImageFilenames {
-    let id = *next_temporary_image_id;
-    *next_temporary_image_id += 1;
-    CompositeImageFilenames {
-        composite: temporary_directory.join(format!("composite-{}.img", id)),
-        header: temporary_directory.join(format!("composite-{}-header.img", id)),
-        footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
-    }
-}
-
-/// Filenames for a composite disk image, including header and footer partitions.
-#[derive(Clone, Debug, Eq, PartialEq)]
-struct CompositeImageFilenames {
-    /// The composite disk image itself.
-    composite: PathBuf,
-    /// The header partition image.
-    header: PathBuf,
-    /// The footer partition image.
-    footer: PathBuf,
-}
-
 /// Checks whether the caller has a specific permission
 fn check_permission(perm: &str) -> binder::Result<()> {
     let calling_pid = get_calling_pid();
@@ -975,476 +386,3 @@
 fn check_manage_access() -> binder::Result<()> {
     check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
 }
-
-/// Check whether the caller of the current Binder method is allowed to create custom VMs
-fn check_use_custom_virtual_machine() -> binder::Result<()> {
-    check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
-}
-
-/// Return whether a partition is exempt from selinux label checks, because we know that it does
-/// not contain code and is likely to be generated in an app-writable directory.
-fn is_safe_app_partition(label: &str) -> bool {
-    // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
-    label == "vm-instance"
-        || label == "encryptedstore"
-        || label == "microdroid-apk-idsig"
-        || label == "payload-metadata"
-        || label.starts_with("extra-idsig-")
-}
-
-/// Check that a file SELinux label is acceptable.
-///
-/// We only want to allow code in a VM to be sourced from places that apps, and the
-/// system, do not have write access to.
-///
-/// Note that sepolicy must also grant read access for these types to both virtualization
-/// service and crosvm.
-///
-/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
-/// user devices (W^X).
-fn check_label_is_allowed(context: &SeContext) -> Result<()> {
-    match context.selinux_type()? {
-        | "system_file" // immutable dm-verity protected partition
-        | "apk_data_file" // APKs of an installed app
-        | "staging_data_file" // updated/staged APEX images
-        | "shell_data_file" // test files created via adb shell
-         => Ok(()),
-        _ => bail!("Label {} is not allowed", context),
-    }
-}
-
-fn check_label_for_partition(partition: &Partition) -> Result<()> {
-    let file = partition.image.as_ref().unwrap().as_ref();
-    check_label_is_allowed(&getfilecon(file)?)
-        .with_context(|| format!("Partition {} invalid", &partition.label))
-}
-
-fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
-    if let Some(f) = kernel {
-        check_label_for_file(f, "kernel")?;
-    }
-    if let Some(f) = initrd {
-        check_label_for_file(f, "initrd")?;
-    }
-    Ok(())
-}
-fn check_label_for_file(file: &File, name: &str) -> Result<()> {
-    check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
-}
-
-/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
-#[derive(Debug)]
-struct VirtualMachine {
-    instance: Arc<VmInstance>,
-}
-
-impl VirtualMachine {
-    fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
-        BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
-    }
-}
-
-impl Interface for VirtualMachine {}
-
-impl IVirtualMachine for VirtualMachine {
-    fn getCid(&self) -> binder::Result<i32> {
-        // Don't check permission. The owner of the VM might have passed this binder object to
-        // others.
-        Ok(self.instance.cid as i32)
-    }
-
-    fn getState(&self) -> binder::Result<VirtualMachineState> {
-        // Don't check permission. The owner of the VM might have passed this binder object to
-        // others.
-        Ok(get_state(&self.instance))
-    }
-
-    fn registerCallback(
-        &self,
-        callback: &Strong<dyn IVirtualMachineCallback>,
-    ) -> binder::Result<()> {
-        // Don't check permission. The owner of the VM might have passed this binder object to
-        // others.
-        //
-        // TODO: Should this give an error if the VM is already dead?
-        self.instance.callbacks.add(callback.clone());
-        Ok(())
-    }
-
-    fn start(&self) -> binder::Result<()> {
-        self.instance.start().map_err(|e| {
-            error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
-            Status::new_service_specific_error_str(-1, Some(e.to_string()))
-        })
-    }
-
-    fn stop(&self) -> binder::Result<()> {
-        self.instance.kill().map_err(|e| {
-            error!("Error stopping VM with CID {}: {:?}", self.instance.cid, e);
-            Status::new_service_specific_error_str(-1, Some(e.to_string()))
-        })
-    }
-
-    fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> {
-        self.instance.trim_memory(level).map_err(|e| {
-            error!("Error trimming VM with CID {}: {:?}", self.instance.cid, e);
-            Status::new_service_specific_error_str(-1, Some(e.to_string()))
-        })
-    }
-
-    fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
-        if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
-            return Err(Status::new_service_specific_error_str(-1, Some("VM is not running")));
-        }
-        let port = port as u32;
-        if port < 1024 {
-            return Err(Status::new_service_specific_error_str(
-                -1,
-                Some(format!("Can't connect to privileged port {port}")),
-            ));
-        }
-        let stream = VsockStream::connect_with_cid_port(self.instance.cid, port).map_err(|e| {
-            Status::new_service_specific_error_str(-1, Some(format!("Failed to connect: {:?}", e)))
-        })?;
-        Ok(vsock_stream_to_pfd(stream))
-    }
-}
-
-impl Drop for VirtualMachine {
-    fn drop(&mut self) {
-        debug!("Dropping {:?}", self);
-        if let Err(e) = self.instance.kill() {
-            debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
-        }
-    }
-}
-
-/// A set of Binders to be called back in response to various events on the VM, such as when it
-/// dies.
-#[derive(Debug, Default)]
-pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
-
-impl VirtualMachineCallbacks {
-    /// Call all registered callbacks to notify that the payload has started.
-    pub fn notify_payload_started(&self, cid: Cid) {
-        let callbacks = &*self.0.lock().unwrap();
-        for callback in callbacks {
-            if let Err(e) = callback.onPayloadStarted(cid as i32) {
-                error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
-            }
-        }
-    }
-
-    /// Call all registered callbacks to notify that the payload is ready to serve.
-    pub fn notify_payload_ready(&self, cid: Cid) {
-        let callbacks = &*self.0.lock().unwrap();
-        for callback in callbacks {
-            if let Err(e) = callback.onPayloadReady(cid as i32) {
-                error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
-            }
-        }
-    }
-
-    /// Call all registered callbacks to notify that the payload has finished.
-    pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
-        let callbacks = &*self.0.lock().unwrap();
-        for callback in callbacks {
-            if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
-                error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
-            }
-        }
-    }
-
-    /// Call all registered callbacks to say that the VM encountered an error.
-    pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
-        let callbacks = &*self.0.lock().unwrap();
-        for callback in callbacks {
-            if let Err(e) = callback.onError(cid as i32, error_code, message) {
-                error!("Error notifying error event from VM CID {}: {:?}", cid, e);
-            }
-        }
-    }
-
-    /// Call all registered callbacks to say that the VM has died.
-    pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
-        let callbacks = &*self.0.lock().unwrap();
-        for callback in callbacks {
-            if let Err(e) = callback.onDied(cid as i32, reason) {
-                error!("Error notifying exit of VM CID {}: {:?}", cid, e);
-            }
-        }
-    }
-
-    /// Add a new callback to the set.
-    fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
-        self.0.lock().unwrap().push(callback);
-    }
-}
-
-/// The mutable state of the VirtualizationService. There should only be one instance of this
-/// struct.
-#[derive(Debug, Default)]
-struct State {
-    /// The VMs which have been started. When VMs are started a weak reference is added to this list
-    /// while a strong reference is returned to the caller over Binder. Once all copies of the
-    /// Binder client are dropped the weak reference here will become invalid, and will be removed
-    /// from the list opportunistically the next time `add_vm` is called.
-    vms: Vec<Weak<VmInstance>>,
-}
-
-impl State {
-    /// Get a list of VMs which still have Binder references to them.
-    fn vms(&self) -> Vec<Arc<VmInstance>> {
-        // Attempt to upgrade the weak pointers to strong pointers.
-        self.vms.iter().filter_map(Weak::upgrade).collect()
-    }
-
-    /// Add a new VM to the list.
-    fn add_vm(&mut self, vm: Weak<VmInstance>) {
-        // Garbage collect any entries from the stored list which no longer exist.
-        self.vms.retain(|vm| vm.strong_count() > 0);
-
-        // Actually add the new VM.
-        self.vms.push(vm);
-    }
-
-    /// Get a VM that corresponds to the given cid
-    fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
-        self.vms().into_iter().find(|vm| vm.cid == cid)
-    }
-}
-
-/// Gets the `VirtualMachineState` of the given `VmInstance`.
-fn get_state(instance: &VmInstance) -> VirtualMachineState {
-    match &*instance.vm_state.lock().unwrap() {
-        VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
-        VmState::Running { .. } => match instance.payload_state() {
-            PayloadState::Starting => VirtualMachineState::STARTING,
-            PayloadState::Started => VirtualMachineState::STARTED,
-            PayloadState::Ready => VirtualMachineState::READY,
-            PayloadState::Finished => VirtualMachineState::FINISHED,
-            PayloadState::Hangup => VirtualMachineState::DEAD,
-        },
-        VmState::Dead => VirtualMachineState::DEAD,
-        VmState::Failed => VirtualMachineState::DEAD,
-    }
-}
-
-/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
-pub fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
-    file.as_ref().try_clone().map_err(|e| {
-        Status::new_exception_str(
-            ExceptionCode::BAD_PARCELABLE,
-            Some(format!("Failed to clone File from ParcelFileDescriptor: {:?}", e)),
-        )
-    })
-}
-
-/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
-fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
-    file.as_ref().map(clone_file).transpose()
-}
-
-/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
-fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
-    // SAFETY: ownership is transferred from stream to f
-    let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
-    ParcelFileDescriptor::new(f)
-}
-
-/// Parses the platform version requirement string.
-fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
-    VersionReq::parse(s).map_err(|e| {
-        Status::new_exception_str(
-            ExceptionCode::BAD_PARCELABLE,
-            Some(format!("Invalid platform version requirement {}: {:?}", s, e)),
-        )
-    })
-}
-
-/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
-/// it doesn't require that T implements Clone.
-enum BorrowedOrOwned<'a, T> {
-    Borrowed(&'a T),
-    Owned(T),
-}
-
-impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
-    fn as_ref(&self) -> &T {
-        match self {
-            Self::Borrowed(b) => b,
-            Self::Owned(o) => o,
-        }
-    }
-}
-
-/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
-#[derive(Debug, Default)]
-struct VirtualMachineService {
-    state: Arc<Mutex<State>>,
-    cid: Cid,
-}
-
-impl Interface for VirtualMachineService {}
-
-impl IVirtualMachineService for VirtualMachineService {
-    fn notifyPayloadStarted(&self) -> binder::Result<()> {
-        let cid = self.cid;
-        if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
-            info!("VM with CID {} started payload", cid);
-            vm.update_payload_state(PayloadState::Started).map_err(|e| {
-                Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
-            })?;
-            vm.callbacks.notify_payload_started(cid);
-
-            let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
-            write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
-            Ok(())
-        } else {
-            error!("notifyPayloadStarted is called from an unknown CID {}", cid);
-            Err(Status::new_service_specific_error_str(
-                -1,
-                Some(format!("cannot find a VM with CID {}", cid)),
-            ))
-        }
-    }
-
-    fn notifyPayloadReady(&self) -> binder::Result<()> {
-        let cid = self.cid;
-        if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
-            info!("VM with CID {} reported payload is ready", cid);
-            vm.update_payload_state(PayloadState::Ready).map_err(|e| {
-                Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
-            })?;
-            vm.callbacks.notify_payload_ready(cid);
-            Ok(())
-        } else {
-            error!("notifyPayloadReady is called from an unknown CID {}", cid);
-            Err(Status::new_service_specific_error_str(
-                -1,
-                Some(format!("cannot find a VM with CID {}", cid)),
-            ))
-        }
-    }
-
-    fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
-        let cid = self.cid;
-        if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
-            info!("VM with CID {} finished payload", cid);
-            vm.update_payload_state(PayloadState::Finished).map_err(|e| {
-                Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
-            })?;
-            vm.callbacks.notify_payload_finished(cid, exit_code);
-            Ok(())
-        } else {
-            error!("notifyPayloadFinished is called from an unknown CID {}", cid);
-            Err(Status::new_service_specific_error_str(
-                -1,
-                Some(format!("cannot find a VM with CID {}", cid)),
-            ))
-        }
-    }
-
-    fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
-        let cid = self.cid;
-        if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
-            info!("VM with CID {} encountered an error", cid);
-            vm.update_payload_state(PayloadState::Finished).map_err(|e| {
-                Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
-            })?;
-            vm.callbacks.notify_error(cid, error_code, message);
-            Ok(())
-        } else {
-            error!("notifyError is called from an unknown CID {}", cid);
-            Err(Status::new_service_specific_error_str(
-                -1,
-                Some(format!("cannot find a VM with CID {}", cid)),
-            ))
-        }
-    }
-}
-
-impl VirtualMachineService {
-    fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
-        BnVirtualMachineService::new_binder(
-            VirtualMachineService { state, cid },
-            BinderFeatures::default(),
-        )
-    }
-}
-
-#[cfg(test)]
-mod tests {
-    use super::*;
-
-    #[test]
-    fn test_is_allowed_label_for_partition() -> Result<()> {
-        let expected_results = vec![
-            ("u:object_r:system_file:s0", true),
-            ("u:object_r:apk_data_file:s0", true),
-            ("u:object_r:app_data_file:s0", false),
-            ("u:object_r:app_data_file:s0:c512,c768", false),
-            ("u:object_r:privapp_data_file:s0:c512,c768", false),
-            ("invalid", false),
-            ("user:role:apk_data_file:severity:categories", true),
-            ("user:role:apk_data_file:severity:categories:extraneous", false),
-        ];
-
-        for (label, expected_valid) in expected_results {
-            let context = SeContext::new(label)?;
-            let result = check_label_is_allowed(&context);
-            if expected_valid {
-                assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
-            } else if result.is_ok() {
-                bail!("Expected label {} to be disallowed", label);
-            }
-        }
-        Ok(())
-    }
-
-    #[test]
-    fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
-        let apk = tempfile::tempfile().unwrap();
-        let idsig = tempfile::tempfile().unwrap();
-
-        let ret = create_or_update_idsig_file(
-            &ParcelFileDescriptor::new(apk),
-            &ParcelFileDescriptor::new(idsig),
-        );
-        assert!(ret.is_err(), "should fail");
-        Ok(())
-    }
-
-    #[test]
-    fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
-        let tmp_dir = tempfile::TempDir::new().unwrap();
-        let apk = File::open(tmp_dir.path()).unwrap();
-        let idsig = tempfile::tempfile().unwrap();
-
-        let ret = create_or_update_idsig_file(
-            &ParcelFileDescriptor::new(apk),
-            &ParcelFileDescriptor::new(idsig),
-        );
-        assert!(ret.is_err(), "should fail");
-        Ok(())
-    }
-
-    /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
-    /// on ext4 filesystem is passed.
-    /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
-    /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
-    /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
-    #[test]
-    fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
-        // APEXes are backed by the ext4.
-        let apk = File::open("/apex/com.android.virt/").unwrap();
-        let idsig = tempfile::tempfile().unwrap();
-
-        let ret = create_or_update_idsig_file(
-            &ParcelFileDescriptor::new(apk),
-            &ParcelFileDescriptor::new(idsig),
-        );
-        assert!(ret.is_err(), "should fail");
-        Ok(())
-    }
-}
diff --git a/virtualizationservice/src/atom.rs b/virtualizationservice/src/atom.rs
index e430c74..47a1603 100644
--- a/virtualizationservice/src/atom.rs
+++ b/virtualizationservice/src/atom.rs
@@ -14,122 +14,16 @@
 
 //! Functions for creating and collecting atoms.
 
-use crate::aidl::{clone_file, GLOBAL_SERVICE};
-use crate::crosvm::VmMetric;
-use crate::get_calling_uid;
 use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::DeathReason::DeathReason;
-use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
-    IVirtualMachine::IVirtualMachine,
-    VirtualMachineAppConfig::{Payload::Payload, VirtualMachineAppConfig},
-    VirtualMachineConfig::VirtualMachineConfig,
-};
-use android_system_virtualizationservice::binder::{Status, Strong};
 use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::{
     AtomVmBooted::AtomVmBooted,
     AtomVmCreationRequested::AtomVmCreationRequested,
     AtomVmExited::AtomVmExited,
 };
-use anyhow::{anyhow, Result};
-use binder::ParcelFileDescriptor;
+use anyhow::Result;
 use log::{trace, warn};
-use microdroid_payload_config::VmPayloadConfig;
 use rustutils::system_properties;
 use statslog_virtualization_rust::{vm_booted, vm_creation_requested, vm_exited};
-use std::thread;
-use std::time::{Duration, SystemTime};
-use zip::ZipArchive;
-
-fn get_apex_list(config: &VirtualMachineAppConfig) -> String {
-    match &config.payload {
-        Payload::PayloadConfig(_) => String::new(),
-        Payload::ConfigPath(config_path) => {
-            let vm_payload_config = get_vm_payload_config(&config.apk, config_path);
-            if let Ok(vm_payload_config) = vm_payload_config {
-                vm_payload_config
-                    .apexes
-                    .iter()
-                    .map(|x| x.name.clone())
-                    .collect::<Vec<String>>()
-                    .join(":")
-            } else {
-                "INFO: Can't get VmPayloadConfig".to_owned()
-            }
-        }
-    }
-}
-
-fn get_vm_payload_config(
-    apk_fd: &Option<ParcelFileDescriptor>,
-    config_path: &str,
-) -> Result<VmPayloadConfig> {
-    let apk = apk_fd.as_ref().ok_or_else(|| anyhow!("APK is none"))?;
-    let apk_file = clone_file(apk)?;
-    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)?;
-    Ok(vm_payload_config)
-}
-
-fn get_duration(vm_start_timestamp: Option<SystemTime>) -> Duration {
-    match vm_start_timestamp {
-        Some(vm_start_timestamp) => vm_start_timestamp.elapsed().unwrap_or_default(),
-        None => Duration::default(),
-    }
-}
-
-/// Write the stats of VMCreation to statsd
-pub fn write_vm_creation_stats(
-    config: &VirtualMachineConfig,
-    is_protected: bool,
-    ret: &binder::Result<Strong<dyn IVirtualMachine>>,
-) {
-    let creation_succeeded;
-    let binder_exception_code;
-    match ret {
-        Ok(_) => {
-            creation_succeeded = true;
-            binder_exception_code = Status::ok().exception_code() as i32;
-        }
-        Err(ref e) => {
-            creation_succeeded = false;
-            binder_exception_code = e.exception_code() as i32;
-        }
-    }
-    let (vm_identifier, config_type, num_cpus, memory_mib, apexes) = match config {
-        VirtualMachineConfig::AppConfig(config) => (
-            config.name.clone(),
-            vm_creation_requested::ConfigType::VirtualMachineAppConfig,
-            config.numCpus,
-            config.memoryMib,
-            get_apex_list(config),
-        ),
-        VirtualMachineConfig::RawConfig(config) => (
-            config.name.clone(),
-            vm_creation_requested::ConfigType::VirtualMachineRawConfig,
-            config.numCpus,
-            config.memoryMib,
-            String::new(),
-        ),
-    };
-
-    let atom = AtomVmCreationRequested {
-        uid: get_calling_uid() as i32,
-        vmIdentifier: vm_identifier,
-        isProtected: is_protected,
-        creationSucceeded: creation_succeeded,
-        binderExceptionCode: binder_exception_code,
-        configType: config_type as i32,
-        numCpus: num_cpus,
-        memoryMib: memory_mib,
-        apexes,
-    };
-
-    thread::spawn(move || {
-        GLOBAL_SERVICE.atomVmCreationRequested(&atom).unwrap_or_else(|e| {
-            warn!("Failed to write VmCreationRequested atom: {e}");
-        });
-    });
-}
 
 pub fn forward_vm_creation_atom(atom: &AtomVmCreationRequested) {
     let config_type = match atom.configType {
@@ -164,29 +58,6 @@
     }
 }
 
-/// Write the stats of VM boot to statsd
-/// The function creates a separate thread which waits fro statsd to start to push atom
-pub fn write_vm_booted_stats(
-    uid: i32,
-    vm_identifier: &str,
-    vm_start_timestamp: Option<SystemTime>,
-) {
-    let vm_identifier = vm_identifier.to_owned();
-    let duration = get_duration(vm_start_timestamp);
-
-    let atom = AtomVmBooted {
-        uid,
-        vmIdentifier: vm_identifier,
-        elapsedTimeMillis: duration.as_millis() as i64,
-    };
-
-    thread::spawn(move || {
-        GLOBAL_SERVICE.atomVmBooted(&atom).unwrap_or_else(|e| {
-            warn!("Failed to write VmCreationRequested atom: {e}");
-        });
-    });
-}
-
 pub fn forward_vm_booted_atom(atom: &AtomVmBooted) {
     let vm_booted = vm_booted::VmBooted {
         uid: atom.uid,
@@ -201,38 +72,6 @@
     }
 }
 
-/// Write the stats of VM exit to statsd
-/// The function creates a separate thread which waits fro statsd to start to push atom
-pub fn write_vm_exited_stats(
-    uid: i32,
-    vm_identifier: &str,
-    reason: DeathReason,
-    exit_signal: Option<i32>,
-    vm_metric: &VmMetric,
-) {
-    let vm_identifier = vm_identifier.to_owned();
-    let elapsed_time_millis = get_duration(vm_metric.start_timestamp).as_millis() as i64;
-    let guest_time_millis = vm_metric.cpu_guest_time.unwrap_or_default();
-    let rss = vm_metric.rss.unwrap_or_default();
-
-    let atom = AtomVmExited {
-        uid,
-        vmIdentifier: vm_identifier,
-        elapsedTimeMillis: elapsed_time_millis,
-        deathReason: reason,
-        guestTimeMillis: guest_time_millis,
-        rssVmKb: rss.vm,
-        rssCrosvmKb: rss.crosvm,
-        exitSignal: exit_signal.unwrap_or_default(),
-    };
-
-    thread::spawn(move || {
-        GLOBAL_SERVICE.atomVmExited(&atom).unwrap_or_else(|e| {
-            warn!("Failed to write VmExited atom: {e}");
-        });
-    });
-}
-
 pub fn forward_vm_exited_atom(atom: &AtomVmExited) {
     let death_reason = match atom.deathReason {
         DeathReason::INFRASTRUCTURE_ERROR => vm_exited::DeathReason::InfrastructureError,
diff --git a/virtualizationservice/src/main.rs b/virtualizationservice/src/main.rs
index 35eeff3..64ccb13 100644
--- a/virtualizationservice/src/main.rs
+++ b/virtualizationservice/src/main.rs
@@ -16,12 +16,11 @@
 
 mod aidl;
 mod atom;
-mod composite;
-mod crosvm;
-mod payload;
-mod selinux;
 
-use crate::aidl::{remove_temporary_dir, BINDER_SERVICE_IDENTIFIER, TEMPORARY_DIRECTORY, VirtualizationServiceInternal};
+use crate::aidl::{
+    remove_temporary_dir, BINDER_SERVICE_IDENTIFIER, TEMPORARY_DIRECTORY,
+    VirtualizationServiceInternal
+};
 use android_logger::{Config, FilterBuilder};
 use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::BnVirtualizationServiceInternal;
 use anyhow::Error;
diff --git a/vm/Android.bp b/vm/Android.bp
index b95dca3..e217786 100644
--- a/vm/Android.bp
+++ b/vm/Android.bp
@@ -14,6 +14,7 @@
         "libbinder_rs",
         "libclap",
         "libenv_logger",
+        "libglob",
         "liblibc",
         "liblog_rust",
         "libmicrodroid_payload_config",
diff --git a/vm/src/run.rs b/vm/src/run.rs
index 6c21dbc..e229933 100644
--- a/vm/src/run.rs
+++ b/vm/src/run.rs
@@ -25,6 +25,7 @@
 };
 use anyhow::{anyhow, bail, Context, Error};
 use binder::ParcelFileDescriptor;
+use glob::glob;
 use microdroid_payload_config::VmPayloadConfig;
 use rand::{distributions::Alphanumeric, Rng};
 use std::fs;
@@ -32,7 +33,6 @@
 use std::io;
 use std::os::unix::io::{AsRawFd, FromRawFd};
 use std::path::{Path, PathBuf};
-use std::process::Command;
 use vmclient::{ErrorCode, VmInstance};
 use vmconfig::{open_parcel_file, VmConfig};
 use zip::ZipArchive;
@@ -147,18 +147,16 @@
     run(service, &config, &payload_config_str, console_path, log_path)
 }
 
-const EMPTY_PAYLOAD_APK: &str = "com.android.microdroid.empty_payload";
-
 fn find_empty_payload_apk_path() -> Result<PathBuf, Error> {
-    let output = Command::new("/system/bin/pm")
-        .arg("path")
-        .arg(EMPTY_PAYLOAD_APK)
-        .output()
-        .context("failed to execute pm path")?;
-    let output_str = String::from_utf8(output.stdout).context("failed to parse output")?;
-    match output_str.strip_prefix("package:") {
-        None => Err(anyhow!("Unexpected output {}", output_str)),
-        Some(apk_path) => Ok(PathBuf::from(apk_path.trim())),
+    const GLOB_PATTERN: &str = "/apex/com.android.virt/app/**/EmptyPayloadApp.apk";
+    let mut entries: Vec<PathBuf> =
+        glob(GLOB_PATTERN).context("failed to glob")?.filter_map(|e| e.ok()).collect();
+    if entries.len() > 1 {
+        return Err(anyhow!("Found more than one apk matching {}", GLOB_PATTERN));
+    }
+    match entries.pop() {
+        Some(path) => Ok(path),
+        None => Err(anyhow!("No apks match {}", GLOB_PATTERN)),
     }
 }
 
@@ -187,9 +185,8 @@
     cpus: Option<u32>,
     task_profiles: Vec<String>,
 ) -> Result<(), Error> {
-    let apk = find_empty_payload_apk_path()
-        .context(anyhow!("failed to find path for {} apk", EMPTY_PAYLOAD_APK))?;
-    println!("found path for {} apk: {}", EMPTY_PAYLOAD_APK, apk.display());
+    let apk = find_empty_payload_apk_path()?;
+    println!("found path {}", apk.display());
 
     let work_dir = work_dir.unwrap_or(create_work_dir()?);
     let idsig = work_dir.join("apk.idsig");
diff --git a/vm/vm_shell.sh b/vm/vm_shell.sh
index 3db7003..b73a9dc 100755
--- a/vm/vm_shell.sh
+++ b/vm/vm_shell.sh
@@ -66,12 +66,16 @@
     fi
 
     if [ ! -n "${selected_cid}" ]; then
-        PS3="Select CID of VM to adb-shell into: "
-        select cid in ${available_cids}
-        do
-            selected_cid=${cid}
-            break
-        done
+        if [ ${#selected_cid[@]} -eq 1 ]; then
+            selected_cid=${available_cids[0]}
+        else
+            PS3="Select CID of VM to adb-shell into: "
+            select cid in ${available_cids}
+            do
+                selected_cid=${cid}
+                break
+            done
+        fi
     fi
 
     if [[ ! " ${available_cids[*]} " =~ " ${selected_cid} " ]]; then
diff --git a/vm_payload/README.md b/vm_payload/README.md
index bcba9be..d5f5331 100644
--- a/vm_payload/README.md
+++ b/vm_payload/README.md
@@ -2,13 +2,14 @@
 
 This directory contains the definition of the VM Payload API. This is a native
 API, exposed as a set of C functions, available to payload code running inside a
-[Microdroid](../microdroid/README.md) VM.
+[Microdroid](https://android.googlesource.com/platform/packages/modules/Virtualization/+/refs/heads/master/microdroid/README.md)
+VM.
 
 Note that only native code is supported in Microdroid, so no Java APIs are
 available in the VM, and only 64 bit code is supported.
 
 To create a VM and run the payload from Android, see
-[android.system.virtualmachine.VirtualMachineManager](../javalib/src/android/system/virtualmachine/VirtualMachineManager.java).
+[android.system.virtualmachine.VirtualMachineManager](https://android.googlesource.com/platform/packages/modules/Virtualization/+/refs/heads/master/javalib/src/android/system/virtualmachine/VirtualMachineManager.java).
 
 ## Entry point
 
@@ -16,7 +17,7 @@
 under the `lib/<ABI>` directory, like other JNI code.
 
 The primary .so, which is specified as part of the VM configuration via
-[VirtualMachineConfig.Builder#setPayloadBinaryPath](../javalib/src/android/system/virtualmachine/VirtualMachineConfig.java),
+[VirtualMachineConfig.Builder#setPayloadBinaryPath](https://android.googlesource.com/platform/packages/modules/Virtualization/+/refs/heads/master/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java),
 must define the entry point for the payload.
 
 This entry point is a C function called `AVmPayload_main()`, as declared in
@@ -34,11 +35,12 @@
 against a stub `libvm_payload.so`, where the dependencies will be satisfied at
 runtime from the real `libvm_payload.so` hosted within the Microdroid VM.
 
-See `MicrodroidTestNativeLib` in the [test APK](../tests/testapk/Android.bp) for
-an example.
+See `MicrodroidTestNativeLib` in the [test
+APK](https://android.googlesource.com/platform/packages/modules/Virtualization/+/refs/heads/master/tests/testapk/Android.bp)
+for an example.
 
 In other build systems a similar stub `libvm_payload.so` can be built using
-[stub.c](stub/stub.c).
+[stub.c](stub/stub.c) and the [linker script](libvm_payload.map.txt).
 
 ## Available NDK APIs
 
diff --git a/vmbase/example/src/pci.rs b/vmbase/example/src/pci.rs
index 438ff9e..c0a2d2b 100644
--- a/vmbase/example/src/pci.rs
+++ b/vmbase/example/src/pci.rs
@@ -15,7 +15,7 @@
 //! Functions to scan the PCI bus for VirtIO device.
 
 use aarch64_paging::paging::MemoryRegion;
-use alloc::alloc::{alloc, dealloc, Layout};
+use alloc::alloc::{alloc, dealloc, handle_alloc_error, Layout};
 use core::{mem::size_of, ptr::NonNull};
 use fdtpci::PciInfo;
 use log::{debug, info};
@@ -25,7 +25,7 @@
         pci::{bus::PciRoot, virtio_device_type, PciTransport},
         DeviceType, Transport,
     },
-    BufferDirection, Hal, PhysAddr, VirtAddr, PAGE_SIZE,
+    BufferDirection, Hal, PhysAddr, PAGE_SIZE,
 };
 
 /// The standard sector size of a VirtIO block device, in bytes.
@@ -87,32 +87,34 @@
 struct HalImpl;
 
 impl Hal for HalImpl {
-    fn dma_alloc(pages: usize) -> PhysAddr {
+    fn dma_alloc(pages: usize, _direction: BufferDirection) -> (PhysAddr, NonNull<u8>) {
         debug!("dma_alloc: pages={}", pages);
         let layout = Layout::from_size_align(pages * PAGE_SIZE, PAGE_SIZE).unwrap();
         // Safe because the layout has a non-zero size.
-        let vaddr = unsafe { alloc(layout) } as VirtAddr;
-        virt_to_phys(vaddr)
+        let vaddr = unsafe { alloc(layout) };
+        let vaddr =
+            if let Some(vaddr) = NonNull::new(vaddr) { vaddr } else { handle_alloc_error(layout) };
+        let paddr = virt_to_phys(vaddr);
+        (paddr, vaddr)
     }
 
-    fn dma_dealloc(paddr: PhysAddr, pages: usize) -> i32 {
+    fn dma_dealloc(paddr: PhysAddr, vaddr: NonNull<u8>, pages: usize) -> i32 {
         debug!("dma_dealloc: paddr={:#x}, pages={}", paddr, pages);
-        let vaddr = Self::phys_to_virt(paddr);
         let layout = Layout::from_size_align(pages * PAGE_SIZE, PAGE_SIZE).unwrap();
         // Safe because the memory was allocated by `dma_alloc` above using the same allocator, and
         // the layout is the same as was used then.
         unsafe {
-            dealloc(vaddr as *mut u8, layout);
+            dealloc(vaddr.as_ptr(), layout);
         }
         0
     }
 
-    fn phys_to_virt(paddr: PhysAddr) -> VirtAddr {
-        paddr
+    fn mmio_phys_to_virt(paddr: PhysAddr, _size: usize) -> NonNull<u8> {
+        NonNull::new(paddr as _).unwrap()
     }
 
     fn share(buffer: NonNull<[u8]>, _direction: BufferDirection) -> PhysAddr {
-        let vaddr = buffer.as_ptr() as *mut u8 as usize;
+        let vaddr = buffer.cast();
         // Nothing to do, as the host already has access to all memory.
         virt_to_phys(vaddr)
     }
@@ -123,6 +125,6 @@
     }
 }
 
-fn virt_to_phys(vaddr: VirtAddr) -> PhysAddr {
-    vaddr
+fn virt_to_phys(vaddr: NonNull<u8>) -> PhysAddr {
+    vaddr.as_ptr() as _
 }
diff --git a/zipfuse/src/main.rs b/zipfuse/src/main.rs
index 5e9e160..20d6fd6 100644
--- a/zipfuse/src/main.rs
+++ b/zipfuse/src/main.rs
@@ -673,7 +673,7 @@
             |root| {
                 let path = root.join("foo");
 
-                let metadata = fs::metadata(&path);
+                let metadata = fs::metadata(path);
                 assert!(metadata.is_ok());
                 let metadata = metadata.unwrap();