Merge "Don't restart ueventd during shutdown"
diff --git a/TEST_MAPPING b/TEST_MAPPING
index c37fd19..4f879b4 100644
--- a/TEST_MAPPING
+++ b/TEST_MAPPING
@@ -43,6 +43,9 @@
       "path": "packages/modules/Virtualization/avmd"
     },
     {
+      "path": "packages/modules/Virtualization/encryptedstore"
+    },
+    {
       "path": "packages/modules/Virtualization/virtualizationservice"
     },
     {
diff --git a/apkdmverity/src/main.rs b/apkdmverity/src/main.rs
index 6e12e38..50b6069 100644
--- a/apkdmverity/src/main.rs
+++ b/apkdmverity/src/main.rs
@@ -23,7 +23,7 @@
 
 use anyhow::{bail, Context, Result};
 use apkverify::{HashAlgorithm, V4Signature};
-use clap::{App, Arg};
+use clap::{arg, Arg, ArgAction, Command};
 use dm::loopdevice;
 use dm::util;
 use dm::verity::{DmVerityHashAlgorithm, DmVerityTargetBuilder};
@@ -34,22 +34,12 @@
 use std::path::{Path, PathBuf};
 
 fn main() -> Result<()> {
-    let matches = App::new("apkdmverity")
-        .about("Creates a dm-verity block device out of APK signed with APK signature scheme V4.")
-        .arg(Arg::from_usage(
-            "--apk... <apk_path> <idsig_path> <name> <root_hash> \
-                            'Input APK file, idsig file, name of the block device, and root hash. \
-                            The APK file must be signed using the APK signature scheme 4. The \
-                            block device is created at \"/dev/mapper/<name>\".' root_hash is \
-                            optional; idsig file's root hash will be used if specified as \"none\"."
-            ))
-        .arg(Arg::with_name("verbose").short('v').long("verbose").help("Shows verbose output"))
-        .get_matches();
+    let matches = clap_command().get_matches();
 
-    let apks = matches.values_of("apk").unwrap();
+    let apks = matches.get_many::<String>("apk").unwrap();
     assert!(apks.len() % 4 == 0);
 
-    let verbose = matches.is_present("verbose");
+    let verbose = matches.get_flag("verbose");
 
     for (apk, idsig, name, roothash) in apks.tuples() {
         let roothash = if roothash != "none" {
@@ -68,6 +58,28 @@
     Ok(())
 }
 
+fn clap_command() -> Command {
+    Command::new("apkdmverity")
+        .about("Creates a dm-verity block device out of APK signed with APK signature scheme V4.")
+        .arg(
+            arg!(--apk ...
+                "Input APK file, idsig file, name of the block device, and root hash. \
+                The APK file must be signed using the APK signature scheme 4. The \
+                block device is created at \"/dev/mapper/<name>\".' root_hash is \
+                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"]),
+        )
+        .arg(
+            Arg::new("verbose")
+                .short('v')
+                .long("verbose")
+                .action(ArgAction::SetTrue)
+                .help("Shows verbose output"),
+        )
+}
+
 struct VerityResult {
     data_device: PathBuf,
     hash_device: PathBuf,
@@ -380,4 +392,10 @@
             },
         );
     }
+
+    #[test]
+    fn verify_command() {
+        // Check that the command parsing has been configured in a valid way.
+        clap_command().debug_assert();
+    }
 }
diff --git a/authfs/TEST_MAPPING b/authfs/TEST_MAPPING
index ab6111b..5e144c7 100644
--- a/authfs/TEST_MAPPING
+++ b/authfs/TEST_MAPPING
@@ -4,6 +4,9 @@
       "name": "authfs_device_test_src_lib"
     },
     {
+      "name": "open_then_run.test"
+    },
+    {
       "name": "AuthFsHostTest"
     }
   ],
diff --git a/authfs/tests/common/Android.bp b/authfs/tests/common/Android.bp
index ec426c7..01ebcfd 100644
--- a/authfs/tests/common/Android.bp
+++ b/authfs/tests/common/Android.bp
@@ -31,3 +31,19 @@
     test_suites: ["general-tests"],
     test_harness: false,
 }
+
+rust_test {
+    name: "open_then_run.test",
+    crate_name: "open_then_run",
+    srcs: ["src/open_then_run.rs"],
+    edition: "2021",
+    rustlibs: [
+        "libandroid_logger",
+        "libanyhow",
+        "libclap",
+        "libcommand_fds",
+        "liblibc",
+        "liblog_rust",
+    ],
+    test_suites: ["general-tests"],
+}
diff --git a/authfs/tests/common/src/open_then_run.rs b/authfs/tests/common/src/open_then_run.rs
index 110d838..6d828e4 100644
--- a/authfs/tests/common/src/open_then_run.rs
+++ b/authfs/tests/common/src/open_then_run.rs
@@ -19,7 +19,7 @@
 //! specified numbers in the child process.
 
 use anyhow::{bail, Context, Result};
-use clap::{App, Arg, Values};
+use clap::{parser::ValuesRef, Arg, ArgAction};
 use command_fds::{CommandFdExt, FdMapping};
 use log::{debug, error};
 use std::fs::OpenOptions;
@@ -51,7 +51,7 @@
 }
 
 fn parse_and_create_file_mapping<F>(
-    values: Option<Values<'_>>,
+    values: Option<ValuesRef<'_, String>>,
     opener: F,
 ) -> Result<Vec<OwnedFdMapping>>
 where
@@ -75,35 +75,35 @@
     }
 }
 
-fn parse_args() -> Result<Args> {
-    #[rustfmt::skip]
-    let matches = App::new("open_then_run")
-        .arg(Arg::with_name("open-ro")
+#[rustfmt::skip]
+fn args_command() -> clap::Command {
+    clap::Command::new("open_then_run")
+        .arg(Arg::new("open-ro")
              .long("open-ro")
              .value_name("FD:PATH")
              .help("Open <PATH> read-only to pass as fd <FD>")
-             .multiple(true)
-             .number_of_values(1))
-        .arg(Arg::with_name("open-rw")
+             .action(ArgAction::Append))
+        .arg(Arg::new("open-rw")
              .long("open-rw")
              .value_name("FD:PATH")
              .help("Open/create <PATH> read-write to pass as fd <FD>")
-             .multiple(true)
-             .number_of_values(1))
-        .arg(Arg::with_name("open-dir")
+             .action(ArgAction::Append))
+        .arg(Arg::new("open-dir")
              .long("open-dir")
              .value_name("FD:DIR")
              .help("Open <DIR> to pass as fd <FD>")
-             .multiple(true)
-             .number_of_values(1))
-        .arg(Arg::with_name("args")
+             .action(ArgAction::Append))
+        .arg(Arg::new("args")
              .help("Command line to execute with pre-opened FD inherited")
              .last(true)
              .required(true)
-             .multiple(true))
-        .get_matches();
+             .num_args(0..))
+}
 
-    let ro_file_fds = parse_and_create_file_mapping(matches.values_of("open-ro"), |path| {
+fn parse_args() -> Result<Args> {
+    let matches = args_command().get_matches();
+
+    let ro_file_fds = parse_and_create_file_mapping(matches.get_many("open-ro"), |path| {
         Ok(OwnedFd::from(
             OpenOptions::new()
                 .read(true)
@@ -112,7 +112,7 @@
         ))
     })?;
 
-    let rw_file_fds = parse_and_create_file_mapping(matches.values_of("open-rw"), |path| {
+    let rw_file_fds = parse_and_create_file_mapping(matches.get_many("open-rw"), |path| {
         Ok(OwnedFd::from(
             OpenOptions::new()
                 .read(true)
@@ -123,7 +123,7 @@
         ))
     })?;
 
-    let dir_fds = parse_and_create_file_mapping(matches.values_of("open-dir"), |path| {
+    let dir_fds = parse_and_create_file_mapping(matches.get_many("open-dir"), |path| {
         Ok(OwnedFd::from(
             OpenOptions::new()
                 .custom_flags(libc::O_DIRECTORY)
@@ -133,7 +133,8 @@
         ))
     })?;
 
-    let cmdline_args: Vec<_> = matches.values_of("args").unwrap().map(|s| s.to_string()).collect();
+    let cmdline_args: Vec<_> =
+        matches.get_many::<String>("args").unwrap().map(|s| s.to_string()).collect();
 
     Ok(Args { ro_file_fds, rw_file_fds, dir_fds, cmdline_args })
 }
@@ -168,3 +169,14 @@
         std::process::exit(1);
     }
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn verify_command() {
+        // Check that the command parsing has been configured in a valid way.
+        args_command().debug_assert();
+    }
+}
diff --git a/avmd/Android.bp b/avmd/Android.bp
index 0b87a7b..e5e0553 100644
--- a/avmd/Android.bp
+++ b/avmd/Android.bp
@@ -20,8 +20,8 @@
     defaults: ["libavmd_defaults"],
 }
 
-rust_binary {
-    name: "avmdtool",
+rust_defaults {
+    name: "avmdtool.defaults",
     srcs: ["src/main.rs"],
     host_supported: true,
     prefer_rlib: true,
@@ -37,6 +37,17 @@
     ],
 }
 
+rust_binary {
+    name: "avmdtool",
+    defaults: ["avmdtool.defaults"],
+}
+
+rust_test {
+    name: "avmdtool.test",
+    defaults: ["avmdtool.defaults"],
+    test_suites: ["general-tests"],
+}
+
 rust_test {
     name: "avmdtool_tests",
     srcs: ["tests/*_test.rs"],
diff --git a/avmd/TEST_MAPPING b/avmd/TEST_MAPPING
index ea58edb..892eb2c 100644
--- a/avmd/TEST_MAPPING
+++ b/avmd/TEST_MAPPING
@@ -1,7 +1,10 @@
 {
-  "avf-presubmit" : [
+  "avf-presubmit": [
     {
-      "name" : "avmdtool_tests"
+      "name": "avmdtool.test"
+    },
+    {
+      "name": "avmdtool_tests"
     }
   ]
 }
diff --git a/avmd/src/main.rs b/avmd/src/main.rs
index fc18225..740e9aa 100644
--- a/avmd/src/main.rs
+++ b/avmd/src/main.rs
@@ -18,9 +18,13 @@
 use apexutil::get_payload_vbmeta_image_hash;
 use apkverify::get_apk_digest;
 use avmd::{ApkDescriptor, Avmd, Descriptor, ResourceIdentifier, VbMetaDescriptor};
-use clap::{App, AppSettings, Arg, ArgMatches, SubCommand};
+use clap::{
+    builder::ValueParser,
+    parser::{Indices, ValuesRef},
+    Arg, ArgAction, ArgMatches, Command,
+};
 use serde::ser::Serialize;
-use std::fs::File;
+use std::{fs::File, path::PathBuf};
 use vbmeta::VbMetaImage;
 
 fn get_vbmeta_image_hash(file: &str) -> Result<Vec<u8>> {
@@ -31,13 +35,13 @@
 /// Iterate over a set of argument values, that could be empty or come in
 /// (<index>, <namespace>, <name>, <file>) tuple.
 struct NamespaceNameFileIterator<'a> {
-    indices: Option<clap::Indices<'a>>,
-    values: Option<clap::Values<'a>>,
+    indices: Option<Indices<'a>>,
+    values: Option<ValuesRef<'a, String>>,
 }
 
 impl<'a> NamespaceNameFileIterator<'a> {
     fn new(args: &'a ArgMatches, name: &'a str) -> Self {
-        NamespaceNameFileIterator { indices: args.indices_of(name), values: args.values_of(name) }
+        NamespaceNameFileIterator { indices: args.indices_of(name), values: args.get_many(name) }
     }
 }
 
@@ -100,54 +104,58 @@
             .packed_format()
             .legacy_enums(),
     )?;
-    std::fs::write(args.value_of("file").unwrap(), &bytes)?;
+    std::fs::write(args.get_one::<PathBuf>("file").unwrap(), &bytes)?;
     Ok(())
 }
 
 fn dump(args: &ArgMatches) -> Result<()> {
-    let file = std::fs::read(args.value_of("file").unwrap())?;
+    let file = std::fs::read(args.get_one::<PathBuf>("file").unwrap())?;
     let avmd: Avmd = serde_cbor::from_slice(&file)?;
     println!("{}", avmd);
     Ok(())
 }
 
-fn main() -> Result<()> {
+fn clap_command() -> Command {
     let namespace_name_file = ["namespace", "name", "file"];
-    let app = App::new("avmdtool")
-        .setting(AppSettings::SubcommandRequiredElseHelp)
+
+    Command::new("avmdtool")
+        .subcommand_required(true)
+        .arg_required_else_help(true)
         .subcommand(
-            SubCommand::with_name("create")
-                .setting(AppSettings::ArgRequiredElseHelp)
-                .arg(Arg::with_name("file").required(true).takes_value(true))
+            Command::new("create")
+                .arg_required_else_help(true)
+                .arg(Arg::new("file").value_parser(ValueParser::path_buf()).required(true))
                 .arg(
-                    Arg::with_name("vbmeta")
+                    Arg::new("vbmeta")
                         .long("vbmeta")
-                        .takes_value(true)
                         .value_names(&namespace_name_file)
-                        .multiple(true),
+                        .num_args(3)
+                        .action(ArgAction::Append),
                 )
                 .arg(
-                    Arg::with_name("apk")
+                    Arg::new("apk")
                         .long("apk")
-                        .takes_value(true)
                         .value_names(&namespace_name_file)
-                        .multiple(true),
+                        .num_args(3)
+                        .action(ArgAction::Append),
                 )
                 .arg(
-                    Arg::with_name("apex-payload")
+                    Arg::new("apex-payload")
                         .long("apex-payload")
-                        .takes_value(true)
                         .value_names(&namespace_name_file)
-                        .multiple(true),
+                        .num_args(3)
+                        .action(ArgAction::Append),
                 ),
         )
         .subcommand(
-            SubCommand::with_name("dump")
-                .setting(AppSettings::ArgRequiredElseHelp)
-                .arg(Arg::with_name("file").required(true).takes_value(true)),
-        );
+            Command::new("dump")
+                .arg_required_else_help(true)
+                .arg(Arg::new("file").value_parser(ValueParser::path_buf()).required(true)),
+        )
+}
 
-    let args = app.get_matches();
+fn main() -> Result<()> {
+    let args = clap_command().get_matches();
     match args.subcommand() {
         Some(("create", sub_args)) => create(sub_args)?,
         Some(("dump", sub_args)) => dump(sub_args)?,
@@ -155,3 +163,14 @@
     }
     Ok(())
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn verify_command() {
+        // Check that the command parsing has been configured in a valid way.
+        clap_command().debug_assert();
+    }
+}
diff --git a/compos/common/compos_client.rs b/compos/common/compos_client.rs
index 34be1d5..f6811cb 100644
--- a/compos/common/compos_client.rs
+++ b/compos/common/compos_client.rs
@@ -222,10 +222,10 @@
         bail!("Protected VM not supported, unable to start VM");
     }
 
-    let have_unprotected_vm =
+    let have_non_protected_vm =
         system_properties::read_bool("ro.boot.hypervisor.vm.supported", false)?;
-    if have_unprotected_vm {
-        warn!("Protected VM not supported, falling back to unprotected on debuggable build");
+    if have_non_protected_vm {
+        warn!("Protected VM not supported, falling back to non-protected on debuggable build");
         return Ok(false);
     }
 
diff --git a/demo/java/com/android/microdroid/demo/MainActivity.java b/demo/java/com/android/microdroid/demo/MainActivity.java
index 54d7420..c3fa55f 100644
--- a/demo/java/com/android/microdroid/demo/MainActivity.java
+++ b/demo/java/com/android/microdroid/demo/MainActivity.java
@@ -19,7 +19,6 @@
 import android.app.Application;
 import android.os.Bundle;
 import android.os.IBinder;
-import android.os.ParcelFileDescriptor;
 import android.os.RemoteException;
 import android.system.virtualmachine.VirtualMachine;
 import android.system.virtualmachine.VirtualMachineCallback;
@@ -243,7 +242,7 @@
             try {
                 VirtualMachineConfig.Builder builder =
                         new VirtualMachineConfig.Builder(getApplication());
-                builder.setPayloadBinaryPath("MicrodroidTestNativeLib.so");
+                builder.setPayloadBinaryName("MicrodroidTestNativeLib.so");
                 builder.setProtectedVm(true);
                 if (debug) {
                     builder.setDebugLevel(VirtualMachineConfig.DEBUG_LEVEL_FULL);
diff --git a/encryptedstore/Android.bp b/encryptedstore/Android.bp
index 13ef1b9..94ebcfc 100644
--- a/encryptedstore/Android.bp
+++ b/encryptedstore/Android.bp
@@ -29,3 +29,9 @@
     defaults: ["encryptedstore.defaults"],
     bootstrap: true,
 }
+
+rust_test {
+    name: "encryptedstore.test",
+    defaults: ["encryptedstore.defaults"],
+    test_suites: ["general-tests"],
+}
diff --git a/encryptedstore/TEST_MAPPING b/encryptedstore/TEST_MAPPING
new file mode 100644
index 0000000..a9e1d87
--- /dev/null
+++ b/encryptedstore/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+  "avf-presubmit": [
+    {
+      "name": "encryptedstore.test"
+    }
+  ]
+}
diff --git a/encryptedstore/src/main.rs b/encryptedstore/src/main.rs
index 7140ae2..888485b 100644
--- a/encryptedstore/src/main.rs
+++ b/encryptedstore/src/main.rs
@@ -19,9 +19,8 @@
 //! It uses dm_rust lib.
 
 use anyhow::{ensure, Context, Result};
-use clap::{arg, App};
-use dm::crypt::CipherType;
-use dm::util;
+use clap::arg;
+use dm::{crypt::CipherType, util};
 use log::info;
 use std::ffi::CString;
 use std::fs::{create_dir_all, OpenOptions};
@@ -42,18 +41,11 @@
     );
     info!("Starting encryptedstore binary");
 
-    let matches = App::new("encryptedstore")
-        .args(&[
-            arg!(--blkdevice <FILE> "the block device backing the encrypted storage")
-                .required(true),
-            arg!(--key <KEY> "key (in hex) equivalent to 32 bytes)").required(true),
-            arg!(--mountpoint <MOUNTPOINT> "mount point for the storage").required(true),
-        ])
-        .get_matches();
+    let matches = clap_command().get_matches();
 
-    let blkdevice = Path::new(matches.value_of("blkdevice").unwrap());
-    let key = matches.value_of("key").unwrap();
-    let mountpoint = Path::new(matches.value_of("mountpoint").unwrap());
+    let blkdevice = Path::new(matches.get_one::<String>("blkdevice").unwrap());
+    let key = matches.get_one::<String>("key").unwrap();
+    let mountpoint = Path::new(matches.get_one::<String>("mountpoint").unwrap());
     encryptedstore_init(blkdevice, key, mountpoint).context(format!(
         "Unable to initialize encryptedstore on {:?} & mount at {:?}",
         blkdevice, mountpoint
@@ -61,6 +53,14 @@
     Ok(())
 }
 
+fn clap_command() -> clap::Command {
+    clap::Command::new("encryptedstore").args(&[
+        arg!(--blkdevice <FILE> "the block device backing the encrypted storage").required(true),
+        arg!(--key <KEY> "key (in hex) equivalent to 32 bytes)").required(true),
+        arg!(--mountpoint <MOUNTPOINT> "mount point for the storage").required(true),
+    ])
+}
+
 fn encryptedstore_init(blkdevice: &Path, key: &str, mountpoint: &Path) -> Result<()> {
     ensure!(
         std::fs::metadata(&blkdevice)
@@ -160,3 +160,14 @@
         Ok(())
     }
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn verify_command() {
+        // Check that the command parsing has been configured in a valid way.
+        clap_command().debug_assert();
+    }
+}
diff --git a/javalib/api/system-current.txt b/javalib/api/system-current.txt
index 30e437b..71bdf13 100644
--- a/javalib/api/system-current.txt
+++ b/javalib/api/system-current.txt
@@ -61,7 +61,7 @@
     method @IntRange(from=0) public long getEncryptedStorageKib();
     method @IntRange(from=0) public int getMemoryMib();
     method @IntRange(from=1) public int getNumCpus();
-    method @Nullable public String getPayloadBinaryPath();
+    method @Nullable public String getPayloadBinaryName();
     method public boolean isCompatibleWith(@NonNull android.system.virtualmachine.VirtualMachineConfig);
     method public boolean isEncryptedStorageEnabled();
     method public boolean isProtectedVm();
@@ -77,7 +77,7 @@
     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 setNumCpus(@IntRange(from=1) int);
-    method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setPayloadBinaryPath(@NonNull String);
+    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 34851e4..b57cb5e 100644
--- a/javalib/src/android/system/virtualmachine/VirtualMachine.java
+++ b/javalib/src/android/system/virtualmachine/VirtualMachine.java
@@ -192,9 +192,6 @@
     /** Name of the idsig files for extra APKs. */
     private static final String EXTRA_IDSIG_FILE_PREFIX = "extra_idsig_";
 
-    /** Name of the virtualization service. */
-    private static final String SERVICE_NAME = "android.system.virtualizationservice";
-
     /** Size of the instance image. 10 MB. */
     private static final long INSTANCE_FILE_SIZE = 10 * 1024 * 1024;
 
@@ -1226,17 +1223,15 @@
     public String toString() {
         VirtualMachineConfig config = getConfig();
         String payloadConfigPath = config.getPayloadConfigPath();
-        String payloadBinaryPath = config.getPayloadBinaryPath();
+        String payloadBinaryName = config.getPayloadBinaryName();
 
         StringBuilder result = new StringBuilder();
         result.append("VirtualMachine(")
                 .append("name:")
                 .append(getName())
                 .append(", ");
-        if (payloadBinaryPath != null) {
-            result.append("payload:")
-                    .append(payloadBinaryPath)
-                    .append(", ");
+        if (payloadBinaryName != null) {
+            result.append("payload:").append(payloadBinaryName).append(", ");
         }
         if (payloadConfigPath != null) {
             result.append("config:")
diff --git a/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java b/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
index 7c16798..d9fc70c 100644
--- a/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
+++ b/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
@@ -62,7 +62,7 @@
     private static final String KEY_VERSION = "version";
     private static final String KEY_APKPATH = "apkPath";
     private static final String KEY_PAYLOADCONFIGPATH = "payloadConfigPath";
-    private static final String KEY_PAYLOADBINARYPATH = "payloadBinaryPath";
+    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";
@@ -118,10 +118,8 @@
      */
     @Nullable private final String mPayloadConfigPath;
 
-    /**
-     * Path within the APK to the payload binary file that will be executed within the VM.
-     */
-    @Nullable private final String mPayloadBinaryPath;
+    /** 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;
@@ -129,7 +127,7 @@
     private VirtualMachineConfig(
             @NonNull String apkPath,
             @Nullable String payloadConfigPath,
-            @Nullable String payloadBinaryPath,
+            @Nullable String payloadBinaryName,
             @DebugLevel int debugLevel,
             boolean protectedVm,
             int memoryMib,
@@ -138,7 +136,7 @@
         // This is only called from Builder.build(); the builder handles parameter validation.
         mApkPath = apkPath;
         mPayloadConfigPath = payloadConfigPath;
-        mPayloadBinaryPath = payloadBinaryPath;
+        mPayloadBinaryName = payloadBinaryName;
         mDebugLevel = debugLevel;
         mProtectedVm = protectedVm;
         mMemoryMib = memoryMib;
@@ -192,7 +190,7 @@
 
         String payloadConfigPath = b.getString(KEY_PAYLOADCONFIGPATH);
         if (payloadConfigPath == null) {
-            builder.setPayloadBinaryPath(b.getString(KEY_PAYLOADBINARYPATH));
+            builder.setPayloadBinaryName(b.getString(KEY_PAYLOADBINARYNAME));
         } else {
             builder.setPayloadConfigPath(payloadConfigPath);
         }
@@ -231,7 +229,7 @@
         b.putInt(KEY_VERSION, VERSION);
         b.putString(KEY_APKPATH, mApkPath);
         b.putString(KEY_PAYLOADCONFIGPATH, mPayloadConfigPath);
-        b.putString(KEY_PAYLOADBINARYPATH, mPayloadBinaryPath);
+        b.putString(KEY_PAYLOADBINARYNAME, mPayloadBinaryName);
         b.putInt(KEY_DEBUGLEVEL, mDebugLevel);
         b.putBoolean(KEY_PROTECTED_VM, mProtectedVm);
         b.putInt(KEY_NUM_CPUS, mNumCpus);
@@ -269,15 +267,15 @@
     }
 
     /**
-     * Returns the path within the {@code lib/<ABI>} directory of the APK to the payload binary file
+     * Returns the name of the payload binary file, in the {@code lib/<ABI>} directory of the APK,
      * that will be executed within the VM.
      *
      * @hide
      */
     @SystemApi
     @Nullable
-    public String getPayloadBinaryPath() {
-        return mPayloadBinaryPath;
+    public String getPayloadBinaryName() {
+        return mPayloadBinaryName;
     }
 
     /**
@@ -354,6 +352,7 @@
      * that would alter the identity of the VM (e.g. using a different payload or changing the debug
      * mode) are considered incompatible.
      *
+     * @see VirtualMachine#setConfig
      * @hide
      */
     @SystemApi
@@ -362,7 +361,7 @@
                 && this.mProtectedVm == other.mProtectedVm
                 && this.mEncryptedStorageKib == other.mEncryptedStorageKib
                 && Objects.equals(this.mPayloadConfigPath, other.mPayloadConfigPath)
-                && Objects.equals(this.mPayloadBinaryPath, other.mPayloadBinaryPath)
+                && Objects.equals(this.mPayloadBinaryName, other.mPayloadBinaryName)
                 && this.mApkPath.equals(other.mApkPath);
     }
 
@@ -376,9 +375,9 @@
     VirtualMachineAppConfig toVsConfig() throws FileNotFoundException {
         VirtualMachineAppConfig vsConfig = new VirtualMachineAppConfig();
         vsConfig.apk = ParcelFileDescriptor.open(new File(mApkPath), MODE_READ_ONLY);
-        if (mPayloadBinaryPath != null) {
+        if (mPayloadBinaryName != null) {
             VirtualMachinePayloadConfig payloadConfig = new VirtualMachinePayloadConfig();
-            payloadConfig.payloadPath = mPayloadBinaryPath;
+            payloadConfig.payloadBinaryName = mPayloadBinaryName;
             vsConfig.payload =
                     VirtualMachineAppConfig.Payload.payloadConfig(payloadConfig);
         } else {
@@ -411,7 +410,7 @@
         @Nullable private final Context mContext;
         @Nullable private String mApkPath;
         @Nullable private String mPayloadConfigPath;
-        @Nullable private String mPayloadBinaryPath;
+        @Nullable private String mPayloadBinaryName;
         @DebugLevel private int mDebugLevel = DEBUG_LEVEL_NONE;
         private boolean mProtectedVm;
         private boolean mProtectedVmSet;
@@ -455,14 +454,14 @@
                 apkPath = mApkPath;
             }
 
-            if (mPayloadBinaryPath == null) {
+            if (mPayloadBinaryName == null) {
                 if (mPayloadConfigPath == null) {
-                    throw new IllegalStateException("setPayloadBinaryPath must be called");
+                    throw new IllegalStateException("setPayloadBinaryName must be called");
                 }
             } else {
                 if (mPayloadConfigPath != null) {
                     throw new IllegalStateException(
-                            "setPayloadBinaryPath and setPayloadConfigPath may not both be called");
+                            "setPayloadBinaryName and setPayloadConfigPath may not both be called");
                 }
             }
 
@@ -473,7 +472,7 @@
             return new VirtualMachineConfig(
                     apkPath,
                     mPayloadConfigPath,
-                    mPayloadBinaryPath,
+                    mPayloadBinaryName,
                     mDebugLevel,
                     mProtectedVm,
                     mMemoryMib,
@@ -515,22 +514,37 @@
         }
 
         /**
-         * Sets the path within the {@code lib/<ABI>} directory of the APK to the payload binary
-         * file that will be executed within the VM.
+         * Sets the name of the payload binary file that will be executed within the VM, e.g.
+         * "payload.so". The file must reside in the {@code lib/<ABI>} directory of the APK.
+         *
+         * <p>Note that VMs only support 64-bit code, even if the owning app is running as a 32-bit
+         * process.
          *
          * @hide
          */
         @SystemApi
         @NonNull
-        public Builder setPayloadBinaryPath(@NonNull String payloadBinaryPath) {
-            mPayloadBinaryPath =
-                    requireNonNull(payloadBinaryPath, "payloadBinaryPath must not be null");
+        public Builder setPayloadBinaryName(@NonNull String payloadBinaryName) {
+            if (payloadBinaryName.contains(File.separator)) {
+                throw new IllegalArgumentException(
+                        "Invalid binary file name: " + payloadBinaryName);
+            }
+            mPayloadBinaryName =
+                    requireNonNull(payloadBinaryName, "payloadBinaryName must not be null");
             return this;
         }
 
         /**
          * Sets the debug level. Defaults to {@link #DEBUG_LEVEL_NONE}.
          *
+         * <p>If {@link #DEBUG_LEVEL_FULL} is set then logs from inside the VM are exported to the
+         * host and adb connections from the host are possible. This is convenient for debugging but
+         * may compromise the integrity of the VM - including bypassing the protections offered by a
+         * {@linkplain #setProtectedVm protected VM}.
+         *
+         * <p>Note that it isn't possible to {@linkplain #isCompatibleWith change} the debug level
+         * of a VM instance; debug and non-debug VMs always have different secrets.
+         *
          * @hide
          */
         @SystemApi
@@ -547,6 +561,13 @@
          * Sets whether to protect the VM memory from the host. No default is provided, this must be
          * set explicitly.
          *
+         * <p>Note that if debugging is {@linkplain #setDebugLevel enabled} for a protected VM, the
+         * VM is not truly protected - direct memory access by the host is prevented, but e.g. the
+         * debugger can be used to access the VM's internals.
+         *
+         * <p>It isn't possible to {@linkplain #isCompatibleWith change} the protected status of a
+         * VM instance; protected and non-protected VMs always have different secrets.
+         *
          * @see VirtualMachineManager#getCapabilities
          * @hide
          */
@@ -561,7 +582,7 @@
             } else {
                 if (!HypervisorProperties.hypervisor_vm_supported().orElse(false)) {
                     throw new UnsupportedOperationException(
-                            "Unprotected VMs are not supported on this device.");
+                            "Non-protected VMs are not supported on this device.");
                 }
             }
             mProtectedVm = protectedVm;
diff --git a/javalib/src/android/system/virtualmachine/VirtualizationService.java b/javalib/src/android/system/virtualmachine/VirtualizationService.java
index 75e359f..c3f2ba3 100644
--- a/javalib/src/android/system/virtualmachine/VirtualizationService.java
+++ b/javalib/src/android/system/virtualmachine/VirtualizationService.java
@@ -39,7 +39,7 @@
      * Client FD for UDS connection to virtmgr's RpcBinder server. Closing it
      * will make virtmgr shut down.
      */
-    private ParcelFileDescriptor mClientFd;
+    private final ParcelFileDescriptor mClientFd;
 
     private static native int nativeSpawn();
 
@@ -86,7 +86,7 @@
         VirtualizationService service = (sInstance == null) ? null : sInstance.get();
         if (service == null || !service.isOk()) {
             service = new VirtualizationService();
-            sInstance = new WeakReference(service);
+            sInstance = new WeakReference<>(service);
         }
         return service;
     }
diff --git a/microdroid/Android.bp b/microdroid/Android.bp
index ecaadf8..c62db2d 100644
--- a/microdroid/Android.bp
+++ b/microdroid/Android.bp
@@ -538,6 +538,46 @@
     srcs: ["bootconfig.normal"],
 }
 
+// python -c "import hashlib; print(hashlib.sha256(b'initrd_normal').hexdigest())"
+initrd_normal_salt = "8041a07d54ac82290f6d90bac1fa8d7fdbc4db974d101d60faf294749d1ebaf8"
+
+avb_gen_vbmeta_image {
+    name: "microdroid_initrd_normal_hashdesc",
+    src: ":microdroid_initrd_normal",
+    partition_name: "initrd_normal",
+    salt: initrd_normal_salt,
+    enabled: false,
+    arch: {
+        // Microdroid kernel is only available in these architectures.
+        arm64: {
+            enabled: true,
+        },
+        x86_64: {
+            enabled: true,
+        },
+    },
+}
+
+// python -c "import hashlib; print(hashlib.sha256(b'initrd_debug').hexdigest())"
+initrd_debug_salt = "8ab9dc9cb7e6456700ff6ef18c6b4c3acc24c5fa5381b829563f8d7a415d869a"
+
+avb_gen_vbmeta_image {
+    name: "microdroid_initrd_debug_hashdesc",
+    src: ":microdroid_initrd_debuggable",
+    partition_name: "initrd_debug",
+    salt: initrd_debug_salt,
+    enabled: false,
+    arch: {
+        // Microdroid kernel is only available in these architectures.
+        arm64: {
+            enabled: true,
+        },
+        x86_64: {
+            enabled: true,
+        },
+    },
+}
+
 avb_add_hash_footer {
     name: "microdroid_kernel_signed",
     src: "empty_kernel",
@@ -556,11 +596,9 @@
             enabled: true,
         },
     },
-    props: [
-        {
-            name: "trusted_ramdisk",
-            file: ":microdroid_initrd_hashes",
-        },
+    include_descriptors_from_images: [
+        ":microdroid_initrd_normal_hashdesc",
+        ":microdroid_initrd_debug_hashdesc",
     ],
 }
 
diff --git a/microdroid/initrd/Android.bp b/microdroid/initrd/Android.bp
index d05ea86..4531583 100644
--- a/microdroid/initrd/Android.bp
+++ b/microdroid/initrd/Android.bp
@@ -122,28 +122,3 @@
     },
     filename: "microdroid_initrd_normal.img",
 }
-
-genrule {
-    name: "microdroid_initrd_normal.sha256",
-    srcs: [":microdroid_initrd_normal"],
-    cmd: "cat $(in) | sha256sum | cut -d' ' -f1 > $(out)",
-    out: ["hash"],
-}
-
-genrule {
-    name: "microdroid_initrd_debuggable.sha256",
-    srcs: [":microdroid_initrd_debuggable"],
-    cmd: "cat $(in) | sha256sum | cut -d' ' -f1 > $(out)",
-    out: ["hash"],
-}
-
-genrule {
-    name: "microdroid_initrd_hashes",
-    srcs: [
-        ":microdroid_initrd_normal.sha256",
-        ":microdroid_initrd_debuggable.sha256",
-    ],
-    // join the hashes with commas
-    cmd: "cat $(in) | tr '\n' ',' > $(out) && truncate -s -1 $(out)",
-    out: ["output"],
-}
diff --git a/microdroid/payload/metadata.proto b/microdroid/payload/metadata.proto
index 1d8dd8c..c74c23b 100644
--- a/microdroid/payload/metadata.proto
+++ b/microdroid/payload/metadata.proto
@@ -65,6 +65,6 @@
 
 message PayloadConfig {
   // Required.
-  // Path to the payload binary file inside the APK.
-  string payload_binary_path = 1;
+  // Name of the payload binary file inside the APK.
+  string payload_binary_name = 1;
 }
diff --git a/microdroid_manager/src/main.rs b/microdroid_manager/src/main.rs
index 1ef41cb..f48611b 100644
--- a/microdroid_manager/src/main.rs
+++ b/microdroid_manager/src/main.rs
@@ -259,7 +259,7 @@
     //   ? -71001: PayloadConfig
     // }
     // PayloadConfig = {
-    //   1: tstr // payload_binary_path
+    //   1: tstr // payload_binary_name
     // }
 
     let mut config_desc = vec![
@@ -278,7 +278,7 @@
             encode_negative_number(-71001, &mut config_desc)?;
             encode_header(5, 1, &mut config_desc)?; // map(1)
             encode_number(1, &mut config_desc)?;
-            encode_tstr(&payload_config.payload_binary_path, &mut config_desc)?;
+            encode_tstr(&payload_config.payload_binary_name, &mut config_desc)?;
         }
     }
 
@@ -761,7 +761,7 @@
         PayloadMetadata::config(payload_config) => {
             let task = Task {
                 type_: TaskType::MicrodroidLauncher,
-                command: payload_config.payload_binary_path,
+                command: payload_config.payload_binary_name,
             };
             Ok(VmPayloadConfig {
                 os: OsConfig { name: "microdroid".to_owned() },
diff --git a/pvmfw/Android.bp b/pvmfw/Android.bp
index ed3ef8d..f5e214e 100644
--- a/pvmfw/Android.bp
+++ b/pvmfw/Android.bp
@@ -18,6 +18,7 @@
         "libfdtpci",
         "liblibfdt",
         "liblog_rust_nostd",
+        "libpvmfw_avb_nostd",
         "libpvmfw_embedded_key",
         "libtinyvec_nostd",
         "libvirtio_drivers",
diff --git a/pvmfw/avb/Android.bp b/pvmfw/avb/Android.bp
index 3026d20..cbec235 100644
--- a/pvmfw/avb/Android.bp
+++ b/pvmfw/avb/Android.bp
@@ -32,6 +32,8 @@
         ":avb_testkey_rsa2048_pub_bin",
         ":avb_testkey_rsa4096_pub_bin",
         ":microdroid_kernel_signed",
+        ":microdroid_initrd_normal",
+        ":test_image_with_one_hashdesc",
         ":unsigned_test_image",
     ],
     rustlibs: [
@@ -56,3 +58,11 @@
     out: ["unsigned_test.img"],
     cmd: "$(location avbtool) generate_test_image --image_size 16384 --output $(out)",
 }
+
+avb_add_hash_footer {
+    name: "test_image_with_one_hashdesc",
+    src: ":unsigned_test_image",
+    partition_name: "bootloader",
+    private_key: ":pvmfw_sign_key",
+    salt: "1111",
+}
diff --git a/pvmfw/avb/src/verify.rs b/pvmfw/avb/src/verify.rs
index b6db601..0bab960 100644
--- a/pvmfw/avb/src/verify.rs
+++ b/pvmfw/avb/src/verify.rs
@@ -25,6 +25,8 @@
     slice,
 };
 
+static NULL_BYTE: &[u8] = b"\0";
+
 /// Error code from AVB image verification.
 #[derive(Clone, Debug, PartialEq, Eq)]
 pub enum AvbImageVerifyError {
@@ -144,6 +146,45 @@
     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,
@@ -170,7 +211,7 @@
     buffer: *mut c_void,
     out_num_read: *mut usize,
 ) -> Result<(), AvbIOError> {
-    let ops = as_avbops_ref(ops)?;
+    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`
@@ -212,7 +253,7 @@
     partition: *const c_char,
     out_size_num_bytes: *mut u64,
 ) -> Result<(), AvbIOError> {
-    let ops = as_avbops_ref(ops)?;
+    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)?;
@@ -283,7 +324,7 @@
     // `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_avbops_ref(ops)?;
+    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;
@@ -295,14 +336,14 @@
     Ok(())
 }
 
-fn as_avbops_ref<'a>(ops: *mut AvbOps) -> Result<&'a AvbOps, AvbIOError> {
-    let ops = to_nonnull(ops)?;
-    // SAFETY: It is safe as the raw pointer `ops` is a nonnull pointer.
-    unsafe { Ok(ops.as_ref()) }
+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>(p: *mut T) -> Result<NonNull<T>, AvbIOError> {
-    NonNull::new(p).ok_or(AvbIOError::NoSuchValue)
+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> {
@@ -313,8 +354,44 @@
     }
 }
 
+#[derive(Clone, Debug, PartialEq, Eq)]
+enum PartitionName {
+    Kernel,
+    InitrdNormal,
+    InitrdDebug,
+}
+
+impl PartitionName {
+    const KERNEL_PARTITION_NAME: &[u8] = b"bootloader\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()
+    }
+}
+
+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),
+        }
+    }
+}
+
 struct Payload<'a> {
     kernel: &'a [u8],
+    initrd: Option<&'a [u8]>,
     trusted_public_key: &'a [u8],
 }
 
@@ -330,63 +407,76 @@
 }
 
 impl<'a> Payload<'a> {
-    const KERNEL_PARTITION_NAME: &[u8] = b"bootloader\0";
-
-    fn kernel_partition_name(&self) -> &CStr {
-        CStr::from_bytes_with_nul(Self::KERNEL_PARTITION_NAME).unwrap()
-    }
+    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.to_bytes_with_nul() {
-            Self::KERNEL_PARTITION_NAME => Ok(self.kernel),
-            _ => Err(AvbIOError::NoSuchPartition),
+        match partition_name.try_into()? {
+            PartitionName::Kernel => Ok(self.kernel),
+            PartitionName::InitrdNormal | PartitionName::InitrdDebug => {
+                self.initrd.ok_or(AvbIOError::NoSuchPartition)
+            }
         }
     }
+
+    fn verify_partitions(&mut self, partition_names: &[&CStr]) -> Result<(), AvbImageVerifyError> {
+        if partition_names.len() > Self::MAX_NUM_OF_HASH_DESCRIPTORS {
+            return Err(AvbImageVerifyError::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,
+            )
+        };
+        to_avb_verify_result(result)
+    }
 }
 
 /// Verifies the payload (signed kernel + initrd) against the trusted public key.
-pub fn verify_payload(kernel: &[u8], trusted_public_key: &[u8]) -> Result<(), AvbImageVerifyError> {
-    let mut payload = Payload { kernel, trusted_public_key };
-    let mut avb_ops = AvbOps {
-        user_data: &mut 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: None,
-        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),
-    };
-    // NULL is needed to mark the end of the array.
-    let requested_partitions: [*const c_char; 2] =
-        [payload.kernel_partition_name().as_ptr(), ptr::null()];
-    let ab_suffix = CStr::from_bytes_with_nul(b"\0").unwrap();
-
-    // 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=*/ ptr::null_mut(),
-        )
-    };
-    to_avb_verify_result(result)
+pub fn verify_payload(
+    kernel: &[u8],
+    initrd: Option<&[u8]>,
+    trusted_public_key: &[u8],
+) -> Result<(), AvbImageVerifyError> {
+    let mut payload = Payload { kernel, initrd, trusted_public_key };
+    let requested_partitions = [PartitionName::Kernel.as_cstr()];
+    payload.verify_partitions(&requested_partitions)
 }
 
 #[cfg(test)]
@@ -396,6 +486,11 @@
     use avb_bindgen::AvbFooter;
     use std::{fs, mem::size_of};
 
+    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;
@@ -403,18 +498,32 @@
     /// 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_is_verified_successfully() -> Result<()> {
+    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, &public_key));
+        assert_eq!(Ok(()), verify_payload(&kernel, Some(&initrd_normal[..]), &public_key));
         Ok(())
     }
 
     #[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],
             AvbImageVerifyError::PublicKeyRejected,
         )
@@ -424,6 +533,7 @@
     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],
             AvbImageVerifyError::PublicKeyRejected,
         )
@@ -433,6 +543,7 @@
     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)?,
             AvbImageVerifyError::PublicKeyRejected,
         )
@@ -441,7 +552,8 @@
     #[test]
     fn unsigned_kernel_fails_verification() -> Result<()> {
         assert_payload_verification_fails(
-            &fs::read("unsigned_test.img")?,
+            &fs::read(UNSIGNED_TEST_IMG_PATH)?,
+            &load_latest_initrd_normal()?,
             &fs::read(PUBLIC_KEY_RSA4096_PATH)?,
             AvbImageVerifyError::Io,
         )
@@ -454,6 +566,7 @@
 
         assert_payload_verification_fails(
             &kernel,
+            &load_latest_initrd_normal()?,
             &fs::read(PUBLIC_KEY_RSA4096_PATH)?,
             AvbImageVerifyError::Verification,
         )
@@ -467,6 +580,7 @@
 
         assert_payload_verification_fails(
             &kernel,
+            &load_latest_initrd_normal()?,
             &fs::read(PUBLIC_KEY_RSA4096_PATH)?,
             AvbImageVerifyError::InvalidMetadata,
         )
@@ -474,14 +588,19 @@
 
     fn assert_payload_verification_fails(
         kernel: &[u8],
+        initrd: &[u8],
         trusted_public_key: &[u8],
         expected_error: AvbImageVerifyError,
     ) -> Result<()> {
-        assert_eq!(Err(expected_error), verify_payload(kernel, trusted_public_key));
+        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")?)
+        Ok(fs::read(MICRODROID_KERNEL_IMG_PATH)?)
+    }
+
+    fn load_latest_initrd_normal() -> Result<Vec<u8>> {
+        Ok(fs::read(INITRD_NORMAL_IMG_PATH)?)
     }
 }
diff --git a/pvmfw/src/entry.rs b/pvmfw/src/entry.rs
index e979a95..1b35c79 100644
--- a/pvmfw/src/entry.rs
+++ b/pvmfw/src/entry.rs
@@ -47,7 +47,6 @@
     /// The provided ramdisk was invalid.
     InvalidRamdisk,
     /// Failed to verify the payload.
-    #[allow(dead_code)]
     PayloadVerificationError,
 }
 
diff --git a/pvmfw/src/main.rs b/pvmfw/src/main.rs
index 4d1ddfe..9b14644 100644
--- a/pvmfw/src/main.rs
+++ b/pvmfw/src/main.rs
@@ -34,7 +34,7 @@
 mod smccc;
 
 use crate::{
-    avb::PUBLIC_KEY, // Keep the public key here otherwise the signing script will be broken.
+    avb::PUBLIC_KEY,
     entry::RebootReason,
     memory::MemoryTracker,
     pci::{find_virtio_devices, map_mmio},
@@ -43,6 +43,7 @@
 use fdtpci::{PciError, PciInfo};
 use libfdt::Fdt;
 use log::{debug, error, info, trace};
+use pvmfw_avb::verify_payload;
 
 fn main(
     fdt: &Fdt,
@@ -71,6 +72,11 @@
     let mut pci_root = unsafe { pci_info.make_pci_root() };
     find_virtio_devices(&mut pci_root).map_err(handle_pci_error)?;
 
+    verify_payload(signed_kernel, ramdisk, PUBLIC_KEY).map_err(|e| {
+        error!("Failed to verify the payload: {e}");
+        RebootReason::PayloadVerificationError
+    })?;
+
     info!("Starting payload...");
     Ok(())
 }
diff --git a/rialto/tests/test.rs b/rialto/tests/test.rs
index 0447cd3..b25034f 100644
--- a/rialto/tests/test.rs
+++ b/rialto/tests/test.rs
@@ -33,7 +33,7 @@
 
 const RIALTO_PATH: &str = "/data/local/tmp/rialto_test/arm64/rialto.bin";
 
-/// Runs the Rialto VM as an unprotected VM via VirtualizationService.
+/// Runs the Rialto VM as a non-protected VM via VirtualizationService.
 #[test]
 fn test_boots() -> Result<(), Error> {
     android_logger::init_once(
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 9cfac4e..9e4b228 100644
--- a/tests/benchmark/src/java/com/android/microdroid/benchmark/MicrodroidBenchmarks.java
+++ b/tests/benchmark/src/java/com/android/microdroid/benchmark/MicrodroidBenchmarks.java
@@ -93,7 +93,7 @@
             throws VirtualMachineException, InterruptedException, IOException {
         VirtualMachineConfig normalConfig =
                 newVmConfigBuilder()
-                        .setPayloadBinaryPath("MicrodroidIdleNativeLib.so")
+                        .setPayloadBinaryName("MicrodroidIdleNativeLib.so")
                         .setDebugLevel(DEBUG_LEVEL_NONE)
                         .setMemoryMib(mem)
                         .build();
@@ -146,7 +146,7 @@
         for (int i = 0; i < trialCount; i++) {
             VirtualMachineConfig normalConfig =
                     newVmConfigBuilder()
-                            .setPayloadBinaryPath("MicrodroidIdleNativeLib.so")
+                            .setPayloadBinaryName("MicrodroidIdleNativeLib.so")
                             .setDebugLevel(DEBUG_LEVEL_NONE)
                             .setMemoryMib(256)
                             .build();
@@ -174,7 +174,7 @@
             for (int i = 0; i < trialCount; i++) {
                 VirtualMachineConfig normalConfig =
                         newVmConfigBuilder()
-                                .setPayloadBinaryPath("MicrodroidIdleNativeLib.so")
+                                .setPayloadBinaryName("MicrodroidIdleNativeLib.so")
                                 .setDebugLevel(DEBUG_LEVEL_NONE)
                                 .setMemoryMib(256)
                                 .setNumCpus(numCpus)
@@ -209,7 +209,7 @@
             // To grab boot events from log, set debug mode to FULL
             VirtualMachineConfig normalConfig =
                     newVmConfigBuilder()
-                            .setPayloadBinaryPath("MicrodroidIdleNativeLib.so")
+                            .setPayloadBinaryName("MicrodroidIdleNativeLib.so")
                             .setDebugLevel(DEBUG_LEVEL_FULL)
                             .setMemoryMib(256)
                             .build();
diff --git a/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java b/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
index 464e091..617c300 100644
--- a/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
+++ b/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
@@ -792,6 +792,39 @@
                                 + " permission");
     }
 
+    @Test
+    public void testPathToBinaryIsRejected() throws Exception {
+        CommandRunner android = new CommandRunner(getDevice());
+
+        // Create the idsig file for the APK
+        final String apkPath = getPathForPackage(PACKAGE_NAME);
+        final String idSigPath = TEST_ROOT + "idsig";
+        android.run(VIRT_APEX + "bin/vm", "create-idsig", apkPath, idSigPath);
+
+        // Create the instance image for the VM
+        final String instanceImgPath = TEST_ROOT + "instance.img";
+        android.run(
+                VIRT_APEX + "bin/vm",
+                "create-partition",
+                "--type instance",
+                instanceImgPath,
+                Integer.toString(10 * 1024 * 1024));
+
+        final String ret =
+                android.runForResult(
+                                VIRT_APEX + "bin/vm",
+                                "run-app",
+                                "--payload-binary-name",
+                                "./MicrodroidTestNativeLib.so",
+                                apkPath,
+                                idSigPath,
+                                instanceImgPath)
+                        .getStderr()
+                        .trim();
+
+        assertThat(ret).contains("Payload binary name must not specify a path");
+    }
+
     @Before
     public void setUp() throws Exception {
         testIfDeviceIsCapable(getDevice());
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 0e94ba2..d8e74f7 100644
--- a/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
+++ b/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
@@ -126,7 +126,7 @@
 
         VirtualMachineConfig config =
                 newVmConfigBuilder()
-                        .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+                        .setPayloadBinaryName("MicrodroidTestNativeLib.so")
                         .setMemoryMib(minMemoryRequired())
                         .setDebugLevel(DEBUG_LEVEL_FULL)
                         .build();
@@ -150,7 +150,7 @@
         // But we do need non-debug VMs to work, so run one.
         VirtualMachineConfig config =
                 newVmConfigBuilder()
-                        .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+                        .setPayloadBinaryName("MicrodroidTestNativeLib.so")
                         .setMemoryMib(minMemoryRequired())
                         .setDebugLevel(DEBUG_LEVEL_NONE)
                         .build();
@@ -174,7 +174,7 @@
 
         VirtualMachineConfig config =
                 newVmConfigBuilder()
-                        .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+                        .setPayloadBinaryName("MicrodroidTestNativeLib.so")
                         .setMemoryMib(minMemoryRequired())
                         .build();
 
@@ -193,7 +193,7 @@
 
         VirtualMachineConfig config =
                 newVmConfigBuilder()
-                        .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+                        .setPayloadBinaryName("MicrodroidTestNativeLib.so")
                         .setMemoryMib(minMemoryRequired())
                         .setDebugLevel(DEBUG_LEVEL_FULL)
                         .build();
@@ -224,7 +224,7 @@
 
         VirtualMachineConfig config =
                 newVmConfigBuilder()
-                        .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+                        .setPayloadBinaryName("MicrodroidTestNativeLib.so")
                         .setMemoryMib(minMemoryRequired())
                         .setDebugLevel(DEBUG_LEVEL_FULL)
                         .build();
@@ -273,7 +273,7 @@
 
         VirtualMachineConfig config =
                 newVmConfigBuilder()
-                        .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+                        .setPayloadBinaryName("MicrodroidTestNativeLib.so")
                         .setMemoryMib(minMemoryRequired())
                         .setDebugLevel(DEBUG_LEVEL_FULL)
                         .build();
@@ -321,13 +321,13 @@
     public void vmConfigGetAndSetTests() {
         // Minimal has as little as specified as possible; everything that can be is defaulted.
         VirtualMachineConfig.Builder minimalBuilder = newVmConfigBuilder();
-        VirtualMachineConfig minimal = minimalBuilder.setPayloadBinaryPath("binary/path").build();
+        VirtualMachineConfig minimal = minimalBuilder.setPayloadBinaryName("binary.so").build();
 
         assertThat(minimal.getApkPath()).isEqualTo(getContext().getPackageCodePath());
         assertThat(minimal.getDebugLevel()).isEqualTo(DEBUG_LEVEL_NONE);
         assertThat(minimal.getMemoryMib()).isEqualTo(0);
         assertThat(minimal.getNumCpus()).isEqualTo(1);
-        assertThat(minimal.getPayloadBinaryPath()).isEqualTo("binary/path");
+        assertThat(minimal.getPayloadBinaryName()).isEqualTo("binary.so");
         assertThat(minimal.getPayloadConfigPath()).isNull();
         assertThat(minimal.isProtectedVm()).isEqualTo(isProtectedVm());
         assertThat(minimal.isEncryptedStorageEnabled()).isFalse();
@@ -350,7 +350,7 @@
         assertThat(maximal.getDebugLevel()).isEqualTo(DEBUG_LEVEL_FULL);
         assertThat(maximal.getMemoryMib()).isEqualTo(42);
         assertThat(maximal.getNumCpus()).isEqualTo(maxCpus);
-        assertThat(maximal.getPayloadBinaryPath()).isNull();
+        assertThat(maximal.getPayloadBinaryName()).isNull();
         assertThat(maximal.getPayloadConfigPath()).isEqualTo("config/path");
         assertThat(maximal.isProtectedVm()).isEqualTo(isProtectedVm());
         assertThat(maximal.isEncryptedStorageEnabled()).isTrue();
@@ -370,12 +370,14 @@
         assertThrows(NullPointerException.class, () -> new VirtualMachineConfig.Builder(null));
         assertThrows(NullPointerException.class, () -> builder.setApkPath(null));
         assertThrows(NullPointerException.class, () -> builder.setPayloadConfigPath(null));
-        assertThrows(NullPointerException.class, () -> builder.setPayloadBinaryPath(null));
+        assertThrows(NullPointerException.class, () -> builder.setPayloadBinaryName(null));
         assertThrows(NullPointerException.class, () -> builder.setPayloadConfigPath(null));
 
         // Individual property checks.
         assertThrows(
                 IllegalArgumentException.class, () -> builder.setApkPath("relative/path/to.apk"));
+        assertThrows(
+                IllegalArgumentException.class, () -> builder.setPayloadBinaryName("dir/file.so"));
         assertThrows(IllegalArgumentException.class, () -> builder.setDebugLevel(-1));
         assertThrows(IllegalArgumentException.class, () -> builder.setMemoryMib(0));
         assertThrows(IllegalArgumentException.class, () -> builder.setNumCpus(0));
@@ -384,45 +386,51 @@
         // Consistency checks enforced at build time.
         Exception e;
         e = assertThrows(IllegalStateException.class, () -> builder.build());
-        assertThat(e).hasMessageThat().contains("setPayloadBinaryPath must be called");
+        assertThat(e).hasMessageThat().contains("setPayloadBinaryName must be called");
 
         VirtualMachineConfig.Builder protectedNotSet =
-                new VirtualMachineConfig.Builder(getContext()).setPayloadBinaryPath("binary/path");
+                new VirtualMachineConfig.Builder(getContext()).setPayloadBinaryName("binary.so");
         e = assertThrows(IllegalStateException.class, () -> protectedNotSet.build());
         assertThat(e).hasMessageThat().contains("setProtectedVm must be called");
     }
 
+    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 {
         int maxCpus = Runtime.getRuntime().availableProcessors();
 
-        VirtualMachineConfig.Builder builder =
-                newVmConfigBuilder().setPayloadBinaryPath("binary/path").setApkPath("/apk/path");
-        VirtualMachineConfig baseline = builder.build();
+        VirtualMachineConfig baseline = newBaselineBuilder().build();
 
         // A config must be compatible with itself
-        assertConfigCompatible(baseline, builder).isTrue();
+        assertConfigCompatible(baseline, newBaselineBuilder()).isTrue();
 
         // Changes that must always be compatible
-        assertConfigCompatible(baseline, builder.setMemoryMib(99)).isTrue();
+        assertConfigCompatible(baseline, newBaselineBuilder().setMemoryMib(99)).isTrue();
         if (maxCpus > 1) {
-            assertConfigCompatible(baseline, builder.setNumCpus(2)).isTrue();
+            assertConfigCompatible(baseline, newBaselineBuilder().setNumCpus(2)).isTrue();
         }
 
         // Changes that must be incompatible, since they must change the VM identity.
-        assertConfigCompatible(baseline, builder.setDebugLevel(DEBUG_LEVEL_FULL)).isFalse();
-        assertConfigCompatible(baseline, builder.setPayloadBinaryPath("different")).isFalse();
+        assertConfigCompatible(baseline, newBaselineBuilder().setDebugLevel(DEBUG_LEVEL_FULL))
+                .isFalse();
+        assertConfigCompatible(baseline, newBaselineBuilder().setPayloadBinaryName("different"))
+                .isFalse();
         int capabilities = getVirtualMachineManager().getCapabilities();
         if ((capabilities & CAPABILITY_PROTECTED_VM) != 0
                 && (capabilities & CAPABILITY_NON_PROTECTED_VM) != 0) {
-            assertConfigCompatible(baseline, builder.setProtectedVm(!isProtectedVm())).isFalse();
+            assertConfigCompatible(baseline, newBaselineBuilder().setProtectedVm(!isProtectedVm()))
+                    .isFalse();
         }
 
         // Changes that are currently incompatible for ease of implementation, but this might change
         // in the future.
-        assertConfigCompatible(baseline, builder.setApkPath("/different")).isFalse();
-        assertConfigCompatible(baseline, builder.setEncryptedStorageKib(100)).isFalse();
+        assertConfigCompatible(baseline, newBaselineBuilder().setApkPath("/different")).isFalse();
+        assertConfigCompatible(baseline, newBaselineBuilder().setEncryptedStorageKib(100))
+                .isFalse();
     }
 
     private BooleanSubject assertConfigCompatible(
@@ -434,19 +442,19 @@
     @CddTest(requirements = {"9.17/C-1-1"})
     public void vmUnitTests() throws Exception {
         VirtualMachineConfig.Builder builder =
-                newVmConfigBuilder().setPayloadBinaryPath("binary/path");
+                newVmConfigBuilder().setPayloadBinaryName("binary.so");
         VirtualMachineConfig config = builder.build();
         VirtualMachine vm = forceCreateNewVirtualMachine("vm_name", config);
 
         assertThat(vm.getName()).isEqualTo("vm_name");
-        assertThat(vm.getConfig().getPayloadBinaryPath()).isEqualTo("binary/path");
+        assertThat(vm.getConfig().getPayloadBinaryName()).isEqualTo("binary.so");
         assertThat(vm.getConfig().getMemoryMib()).isEqualTo(0);
 
         VirtualMachineConfig compatibleConfig = builder.setMemoryMib(42).build();
         vm.setConfig(compatibleConfig);
 
         assertThat(vm.getName()).isEqualTo("vm_name");
-        assertThat(vm.getConfig().getPayloadBinaryPath()).isEqualTo("binary/path");
+        assertThat(vm.getConfig().getPayloadBinaryName()).isEqualTo("binary.so");
         assertThat(vm.getConfig().getMemoryMib()).isEqualTo(42);
 
         assertThat(getVirtualMachineManager().get("vm_name")).isSameInstanceAs(vm);
@@ -459,7 +467,7 @@
 
         VirtualMachineConfig config =
                 newVmConfigBuilder()
-                        .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+                        .setPayloadBinaryName("MicrodroidTestNativeLib.so")
                         .setMemoryMib(minMemoryRequired())
                         .setDebugLevel(DEBUG_LEVEL_FULL)
                         .build();
@@ -507,7 +515,7 @@
         final int userId = ctx.getUserId();
         final VirtualMachineManager vmm = ctx.getSystemService(VirtualMachineManager.class);
         VirtualMachineConfig config =
-                newVmConfigBuilder().setPayloadBinaryPath("binary/path").build();
+                newVmConfigBuilder().setPayloadBinaryName("binary.so").build();
         try {
             VirtualMachine vm = vmm.create("vm-name", config);
             // TODO(b/261430346): what about non-primary user?
@@ -526,7 +534,7 @@
         final int userId = ctx.getUserId();
         final VirtualMachineManager vmm = ctx.getSystemService(VirtualMachineManager.class);
         VirtualMachineConfig config =
-                newVmConfigBuilder().setPayloadBinaryPath("binary/path").build();
+                newVmConfigBuilder().setPayloadBinaryName("binary.so").build();
         try {
             VirtualMachine vm = vmm.create("vm-name", config);
             // TODO(b/261430346): what about non-primary user?
@@ -578,7 +586,7 @@
 
         VirtualMachineConfig config =
                 newVmConfigBuilder()
-                        .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+                        .setPayloadBinaryName("MicrodroidTestNativeLib.so")
                         .setMemoryMib(minMemoryRequired())
                         .build();
 
@@ -605,7 +613,7 @@
 
         VirtualMachineConfig config =
                 newVmConfigBuilder()
-                        .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+                        .setPayloadBinaryName("MicrodroidTestNativeLib.so")
                         .setApkPath(getContext().getPackageCodePath())
                         .setMemoryMib(minMemoryRequired())
                         .setDebugLevel(DEBUG_LEVEL_FULL)
@@ -651,7 +659,7 @@
         for (int memMib : new int[]{ 10, 20, 40 }) {
             VirtualMachineConfig lowMemConfig =
                     newVmConfigBuilder()
-                            .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+                            .setPayloadBinaryName("MicrodroidTestNativeLib.so")
                             .setMemoryMib(memMib)
                             .setDebugLevel(DEBUG_LEVEL_NONE)
                             .build();
@@ -695,7 +703,7 @@
 
         VirtualMachineConfig.Builder builder =
                 newVmConfigBuilder()
-                        .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+                        .setPayloadBinaryName("MicrodroidTestNativeLib.so")
                         .setDebugLevel(fromLevel);
         VirtualMachineConfig normalConfig = builder.build();
         forceCreateNewVirtualMachine("test_vm", normalConfig);
@@ -865,7 +873,7 @@
 
         VirtualMachineConfig config =
                 newVmConfigBuilder()
-                        .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+                        .setPayloadBinaryName("MicrodroidTestNativeLib.so")
                         .setDebugLevel(DEBUG_LEVEL_FULL)
                         .build();
         forceCreateNewVirtualMachine("test_vm", config);
@@ -912,7 +920,7 @@
     private RandomAccessFile prepareInstanceImage(String vmName) throws Exception {
         VirtualMachineConfig config =
                 newVmConfigBuilder()
-                        .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+                        .setPayloadBinaryName("MicrodroidTestNativeLib.so")
                         .setDebugLevel(DEBUG_LEVEL_FULL)
                         .build();
 
@@ -985,9 +993,9 @@
     }
 
     @Test
-    public void bootFailsWhenBinaryPathIsInvalid() throws Exception {
+    public void bootFailsWhenBinaryNameIsInvalid() throws Exception {
         VirtualMachineConfig.Builder builder =
-                newVmConfigBuilder().setPayloadBinaryPath("DoesNotExist.so");
+                newVmConfigBuilder().setPayloadBinaryName("DoesNotExist.so");
         VirtualMachineConfig normalConfig = builder.setDebugLevel(DEBUG_LEVEL_FULL).build();
         forceCreateNewVirtualMachine("test_vm_invalid_binary_path", normalConfig);
 
@@ -1024,7 +1032,7 @@
     @Test
     public void bootFailsWhenBinaryIsMissingEntryFunction() throws Exception {
         VirtualMachineConfig.Builder builder =
-                newVmConfigBuilder().setPayloadBinaryPath("MicrodroidEmptyNativeLib.so");
+                newVmConfigBuilder().setPayloadBinaryName("MicrodroidEmptyNativeLib.so");
         VirtualMachineConfig normalConfig = builder.setDebugLevel(DEBUG_LEVEL_FULL).build();
         VirtualMachine vm = forceCreateNewVirtualMachine("test_vm_missing_entry", normalConfig);
 
@@ -1034,7 +1042,7 @@
     @Test
     public void bootFailsWhenBinaryTriesToLinkAgainstPrivateLibs() throws Exception {
         VirtualMachineConfig.Builder builder =
-                newVmConfigBuilder().setPayloadBinaryPath("MicrodroidPrivateLinkingNativeLib.so");
+                newVmConfigBuilder().setPayloadBinaryName("MicrodroidPrivateLinkingNativeLib.so");
         VirtualMachineConfig normalConfig = builder.setDebugLevel(DEBUG_LEVEL_FULL).build();
         VirtualMachine vm = forceCreateNewVirtualMachine("test_vm_private_linking", normalConfig);
 
@@ -1044,9 +1052,7 @@
     @Test
     public void sameInstancesShareTheSameVmObject() throws Exception {
         VirtualMachineConfig config =
-                newVmConfigBuilder()
-                        .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
-                        .build();
+                newVmConfigBuilder().setPayloadBinaryName("MicrodroidTestNativeLib.so").build();
 
         VirtualMachine vm = forceCreateNewVirtualMachine("test_vm", config);
         VirtualMachine vm2 = getVirtualMachineManager().get("test_vm");
@@ -1108,7 +1114,7 @@
         // Arrange
         VirtualMachineConfig.Builder builder =
                 newVmConfigBuilder()
-                        .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+                        .setPayloadBinaryName("MicrodroidTestNativeLib.so")
                         .setDebugLevel(DEBUG_LEVEL_FULL);
         if (encryptedStoreEnabled) builder = builder.setEncryptedStorageKib(4096);
         VirtualMachineConfig config = builder.build();
@@ -1150,7 +1156,7 @@
 
         VirtualMachineConfig config =
                 newVmConfigBuilder()
-                        .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+                        .setPayloadBinaryName("MicrodroidTestNativeLib.so")
                         .setMemoryMib(minMemoryRequired())
                         .setEncryptedStorageKib(4096)
                         .setDebugLevel(DEBUG_LEVEL_FULL)
@@ -1168,7 +1174,7 @@
 
         final VirtualMachineConfig vmConfig =
                 newVmConfigBuilder()
-                        .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+                        .setPayloadBinaryName("MicrodroidTestNativeLib.so")
                         .setMemoryMib(minMemoryRequired())
                         .setDebugLevel(DEBUG_LEVEL_FULL)
                         .build();
@@ -1187,7 +1193,7 @@
 
         VirtualMachineConfig config =
                 newVmConfigBuilder()
-                        .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+                        .setPayloadBinaryName("MicrodroidTestNativeLib.so")
                         .setMemoryMib(minMemoryRequired())
                         .setEncryptedStorageKib(4096)
                         .setDebugLevel(DEBUG_LEVEL_FULL)
@@ -1210,7 +1216,7 @@
 
         VirtualMachineConfig config =
                 newVmConfigBuilder()
-                        .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+                        .setPayloadBinaryName("MicrodroidTestNativeLib.so")
                         .setMemoryMib(minMemoryRequired())
                         .setDebugLevel(DEBUG_LEVEL_FULL)
                         .build();
diff --git a/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachinePayloadConfig.aidl b/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachinePayloadConfig.aidl
index ed3c512..55c2f5d 100644
--- a/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachinePayloadConfig.aidl
+++ b/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachinePayloadConfig.aidl
@@ -18,8 +18,9 @@
 
 parcelable VirtualMachinePayloadConfig {
     /**
-     * Path to the payload executable code in an APK. The code is in the form of a .so with a
-     * defined entry point; inside the VM this file is loaded and the entry function invoked.
+     * Name of the payload executable file in the lib/<ABI> folder of an APK. The payload is in the
+     * form of a .so with a defined entry point; inside the VM this file is loaded and the entry
+     * function invoked.
      */
-    @utf8InCpp String payloadPath;
+    @utf8InCpp String payloadBinaryName;
 }
diff --git a/virtualizationservice/src/aidl.rs b/virtualizationservice/src/aidl.rs
index 733d9c5..0859a76 100644
--- a/virtualizationservice/src/aidl.rs
+++ b/virtualizationservice/src/aidl.rs
@@ -841,7 +841,7 @@
             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),
+        Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
     };
 
     // For now, the only supported OS is Microdroid
@@ -887,13 +887,20 @@
     Ok(serde_json::from_reader(config_file)?)
 }
 
-fn create_vm_payload_config(payload_config: &VirtualMachinePayloadConfig) -> VmPayloadConfig {
+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 task =
-        Task { type_: TaskType::MicrodroidLauncher, command: payload_config.payloadPath.clone() };
-    VmPayloadConfig {
+
+    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![],
@@ -901,7 +908,7 @@
         prefer_staged: false,
         export_tombstones: false,
         enable_authfs: false,
-    }
+    })
 }
 
 /// Generates a unique filename to use for a composite disk image.
diff --git a/virtualizationservice/src/payload.rs b/virtualizationservice/src/payload.rs
index eb3e9eb..02e8f8e 100644
--- a/virtualizationservice/src/payload.rs
+++ b/virtualizationservice/src/payload.rs
@@ -194,7 +194,7 @@
 ) -> Result<ParcelFileDescriptor> {
     let payload_metadata = match &app_config.payload {
         Payload::PayloadConfig(payload_config) => PayloadMetadata::config(PayloadConfig {
-            payload_binary_path: payload_config.payloadPath.clone(),
+            payload_binary_name: payload_config.payloadBinaryName.clone(),
             ..Default::default()
         }),
         Payload::ConfigPath(config_path) => {
diff --git a/virtualizationservice/src/virtmgr.rs b/virtualizationservice/src/virtmgr.rs
index 5616097..dca64cb 100644
--- a/virtualizationservice/src/virtmgr.rs
+++ b/virtualizationservice/src/virtmgr.rs
@@ -33,6 +33,7 @@
 use nix::fcntl::{fcntl, F_GETFD, F_SETFD, FdFlag};
 use nix::unistd::{Pid, Uid};
 use std::os::unix::raw::{pid_t, uid_t};
+use rustutils::system_properties;
 
 const LOG_TAG: &str = "virtmgr";
 
@@ -91,6 +92,11 @@
     Ok(unsafe { OwnedFd::from_raw_fd(raw_fd) })
 }
 
+fn is_property_set(name: &str) -> bool {
+    system_properties::read_bool(name, false)
+        .unwrap_or_else(|e| panic!("Failed to read {name}: {e:?}"))
+}
+
 fn main() {
     android_logger::init_once(
         android_logger::Config::default()
@@ -99,6 +105,15 @@
             .with_log_id(android_logger::LogId::System),
     );
 
+    let non_protected_vm_supported = is_property_set("ro.boot.hypervisor.vm.supported");
+    let protected_vm_supported = is_property_set("ro.boot.hypervisor.protected_vm.supported");
+    if !non_protected_vm_supported && !protected_vm_supported {
+        // This should never happen, it indicates a misconfigured device where the virt APEX
+        // is present but VMs are not supported. If it does happen, fail fast to avoid wasting
+        // resources trying.
+        panic!("Device doesn't support protected or unprotected VMs");
+    }
+
     let args = Args::parse();
 
     let mut owned_fds = vec![];
diff --git a/vm/TEST_MAPPING b/vm/TEST_MAPPING
index a8d1fa6..485c3af 100644
--- a/vm/TEST_MAPPING
+++ b/vm/TEST_MAPPING
@@ -1,7 +1,7 @@
 {
-  "avf-presubmit" : [
+  "avf-presubmit": [
     {
-      "name" : "vm.test"
+      "name": "vm.test"
     }
   ]
 }
diff --git a/vm/src/main.rs b/vm/src/main.rs
index 002e505..bfc7920 100644
--- a/vm/src/main.rs
+++ b/vm/src/main.rs
@@ -51,9 +51,10 @@
         #[clap(long)]
         config_path: Option<String>,
 
-        /// Path to VM payload binary within APK (e.g. MicrodroidTestNativeLib.so)
+        /// Name of VM payload binary within APK (e.g. MicrodroidTestNativeLib.so)
         #[clap(long)]
-        payload_path: Option<String>,
+        #[clap(alias = "payload_path")]
+        payload_binary_name: Option<String>,
 
         /// Name of VM
         #[clap(long)]
@@ -258,7 +259,7 @@
             storage,
             storage_size,
             config_path,
-            payload_path,
+            payload_binary_name,
             daemonize,
             console,
             log,
@@ -277,7 +278,7 @@
             storage.as_deref(),
             storage_size,
             config_path,
-            payload_path,
+            payload_binary_name,
             daemonize,
             console.as_deref(),
             log.as_deref(),
@@ -357,15 +358,15 @@
 
 /// Print information about supported VM types.
 fn command_info() -> Result<(), Error> {
-    let unprotected_vm_supported =
+    let non_protected_vm_supported =
         system_properties::read_bool("ro.boot.hypervisor.vm.supported", false)?;
     let protected_vm_supported =
         system_properties::read_bool("ro.boot.hypervisor.protected_vm.supported", false)?;
-    match (unprotected_vm_supported, protected_vm_supported) {
+    match (non_protected_vm_supported, protected_vm_supported) {
         (false, false) => println!("VMs are not supported."),
         (false, true) => println!("Only protected VMs are supported."),
-        (true, false) => println!("Only unprotected VMs are supported."),
-        (true, true) => println!("Both protected and unprotected VMs are supported."),
+        (true, false) => println!("Only non-protected VMs are supported."),
+        (true, true) => println!("Both protected and non-protected VMs are supported."),
     }
 
     if let Some(version) = system_properties::read("ro.boot.hypervisor.version")? {
@@ -386,10 +387,11 @@
 #[cfg(test)]
 mod tests {
     use super::*;
-    use clap::IntoApp;
+    use clap::CommandFactory;
 
     #[test]
     fn verify_app() {
-        Opt::into_app().debug_assert();
+        // Check that the command parsing has been configured in a valid way.
+        Opt::command().debug_assert();
     }
 }
diff --git a/vm/src/run.rs b/vm/src/run.rs
index 6096913..b99328a 100644
--- a/vm/src/run.rs
+++ b/vm/src/run.rs
@@ -48,7 +48,7 @@
     storage: Option<&Path>,
     storage_size: Option<u64>,
     config_path: Option<String>,
-    payload_path: Option<String>,
+    payload_binary_name: Option<String>,
     daemonize: bool,
     console_path: Option<&Path>,
     log_path: Option<&Path>,
@@ -117,14 +117,16 @@
     let extra_idsig_fds = extra_idsig_files?.into_iter().map(ParcelFileDescriptor::new).collect();
 
     let payload = if let Some(config_path) = config_path {
-        if payload_path.is_some() {
-            bail!("Only one of --config-path or --payload-path can be defined")
+        if payload_binary_name.is_some() {
+            bail!("Only one of --config-path or --payload-binary-name can be defined")
         }
         Payload::ConfigPath(config_path)
-    } else if let Some(payload_path) = payload_path {
-        Payload::PayloadConfig(VirtualMachinePayloadConfig { payloadPath: payload_path })
+    } else if let Some(payload_binary_name) = payload_binary_name {
+        Payload::PayloadConfig(VirtualMachinePayloadConfig {
+            payloadBinaryName: payload_binary_name,
+        })
     } else {
-        bail!("Either --config-path or --payload-path must be defined")
+        bail!("Either --config-path or --payload-binary-name must be defined")
     };
 
     let payload_config_str = format!("{:?}!{:?}", apk, payload);
@@ -197,7 +199,7 @@
     let instance_img = work_dir.join("instance.img");
     println!("instance.img path: {}", instance_img.display());
 
-    let payload_path = "MicrodroidEmptyPayloadJniLib.so";
+    let payload_binary_name = "MicrodroidEmptyPayloadJniLib.so";
     let extra_sig = [];
     command_run_app(
         name,
@@ -208,7 +210,7 @@
         storage,
         storage_size,
         /* config_path= */ None,
-        Some(payload_path.to_owned()),
+        Some(payload_binary_name.to_owned()),
         daemonize,
         console_path,
         log_path,
diff --git a/vmbase/src/bionic.rs b/vmbase/src/bionic.rs
index b4a2f7b..6f88cf6 100644
--- a/vmbase/src/bionic.rs
+++ b/vmbase/src/bionic.rs
@@ -16,11 +16,17 @@
 
 use core::ffi::c_char;
 use core::ffi::c_int;
+use core::ffi::c_void;
 use core::ffi::CStr;
+use core::slice;
+use core::str;
 
+use crate::console;
 use crate::eprintln;
 use crate::linker;
 
+const EOF: c_int = -1;
+
 /// Reference to __stack_chk_guard.
 pub static STACK_CHK_GUARD: &u64 = unsafe { &linker::__stack_chk_guard };
 
@@ -43,6 +49,11 @@
     &mut ERRNO as *mut _
 }
 
+fn set_errno(value: c_int) {
+    // SAFETY - vmbase is currently single-threaded.
+    unsafe { ERRNO = value };
+}
+
 /// Reports a fatal error detected by Bionic.
 ///
 /// # Safety
@@ -62,3 +73,56 @@
         eprintln!("FATAL BIONIC ERROR: {prefix}: \"{format}\" (unformatted)");
     }
 }
+
+#[repr(usize)]
+/// Arbitrary token FILE pseudo-pointers used by C to refer to the default streams.
+enum File {
+    Stdout = 0x7670cf00,
+    Stderr = 0x9d118200,
+}
+
+impl TryFrom<usize> for File {
+    type Error = &'static str;
+
+    fn try_from(value: usize) -> Result<Self, Self::Error> {
+        match value {
+            x if x == File::Stdout as _ => Ok(File::Stdout),
+            x if x == File::Stderr as _ => Ok(File::Stderr),
+            _ => Err("Received Invalid FILE* from C"),
+        }
+    }
+}
+
+#[no_mangle]
+static stdout: File = File::Stdout;
+#[no_mangle]
+static stderr: File = File::Stderr;
+
+#[no_mangle]
+extern "C" fn fputs(c_str: *const c_char, stream: usize) -> c_int {
+    // SAFETY - Just like libc, we need to assume that `s` is a valid NULL-terminated string.
+    let c_str = unsafe { CStr::from_ptr(c_str) };
+
+    if let (Ok(s), Ok(_)) = (c_str.to_str(), File::try_from(stream)) {
+        console::write_str(s);
+        0
+    } else {
+        set_errno(EOF);
+        EOF
+    }
+}
+
+#[no_mangle]
+extern "C" fn fwrite(ptr: *const c_void, size: usize, nmemb: usize, stream: usize) -> usize {
+    let length = size.saturating_mul(nmemb);
+
+    // SAFETY - Just like libc, we need to assume that `ptr` is valid.
+    let bytes = unsafe { slice::from_raw_parts(ptr as *const u8, length) };
+
+    if let (Ok(s), Ok(_)) = (str::from_utf8(bytes), File::try_from(stream)) {
+        console::write_str(s);
+        length
+    } else {
+        0
+    }
+}
diff --git a/zipfuse/src/main.rs b/zipfuse/src/main.rs
index ffa0a4a..5e9e160 100644
--- a/zipfuse/src/main.rs
+++ b/zipfuse/src/main.rs
@@ -21,7 +21,7 @@
 mod inode;
 
 use anyhow::{Context as AnyhowContext, Result};
-use clap::{App, Arg};
+use clap::{builder::ValueParser, Arg, ArgAction, Command};
 use fuse::filesystem::*;
 use fuse::mount::*;
 use rustutils::system_properties;
@@ -34,65 +34,58 @@
 use std::mem::size_of;
 use std::os::unix::io::AsRawFd;
 use std::path::Path;
+use std::path::PathBuf;
 use std::sync::Mutex;
 
 use crate::inode::{DirectoryEntry, Inode, InodeData, InodeKind, InodeTable};
 
 fn main() -> Result<()> {
-    let matches = App::new("zipfuse")
+    let matches = clap_command().get_matches();
+
+    let zip_file = matches.get_one::<PathBuf>("ZIPFILE").unwrap();
+    let mount_point = matches.get_one::<PathBuf>("MOUNTPOINT").unwrap();
+    let options = matches.get_one::<String>("options");
+    let noexec = matches.get_flag("noexec");
+    let ready_prop = matches.get_one::<String>("readyprop");
+    let uid: u32 = matches.get_one::<String>("uid").map_or(0, |s| s.parse().unwrap());
+    let gid: u32 = matches.get_one::<String>("gid").map_or(0, |s| s.parse().unwrap());
+    run_fuse(zip_file, mount_point, options, noexec, ready_prop, uid, gid)?;
+
+    Ok(())
+}
+
+fn clap_command() -> Command {
+    Command::new("zipfuse")
         .arg(
-            Arg::with_name("options")
+            Arg::new("options")
                 .short('o')
-                .takes_value(true)
                 .required(false)
                 .help("Comma separated list of mount options"),
         )
         .arg(
-            Arg::with_name("noexec")
+            Arg::new("noexec")
                 .long("noexec")
-                .takes_value(false)
+                .action(ArgAction::SetTrue)
                 .help("Disallow the execution of binary files"),
         )
         .arg(
-            Arg::with_name("readyprop")
+            Arg::new("readyprop")
                 .short('p')
-                .takes_value(true)
                 .help("Specify a property to be set when mount is ready"),
         )
-        .arg(
-            Arg::with_name("uid")
-                .short('u')
-                .takes_value(true)
-                .help("numeric UID who's the owner of the files"),
-        )
-        .arg(
-            Arg::with_name("gid")
-                .short('g')
-                .takes_value(true)
-                .help("numeric GID who's the group of the files"),
-        )
-        .arg(Arg::with_name("ZIPFILE").required(true))
-        .arg(Arg::with_name("MOUNTPOINT").required(true))
-        .get_matches();
-
-    let zip_file = matches.value_of("ZIPFILE").unwrap().as_ref();
-    let mount_point = matches.value_of("MOUNTPOINT").unwrap().as_ref();
-    let options = matches.value_of("options");
-    let noexec = matches.is_present("noexec");
-    let ready_prop = matches.value_of("readyprop");
-    let uid: u32 = matches.value_of("uid").map_or(0, |s| s.parse().unwrap());
-    let gid: u32 = matches.value_of("gid").map_or(0, |s| s.parse().unwrap());
-    run_fuse(zip_file, mount_point, options, noexec, ready_prop, uid, gid)?;
-    Ok(())
+        .arg(Arg::new("uid").short('u').help("numeric UID who's the owner of the files"))
+        .arg(Arg::new("gid").short('g').help("numeric GID who's the group of the files"))
+        .arg(Arg::new("ZIPFILE").value_parser(ValueParser::path_buf()).required(true))
+        .arg(Arg::new("MOUNTPOINT").value_parser(ValueParser::path_buf()).required(true))
 }
 
 /// Runs a fuse filesystem by mounting `zip_file` on `mount_point`.
 pub fn run_fuse(
     zip_file: &Path,
     mount_point: &Path,
-    extra_options: Option<&str>,
+    extra_options: Option<&String>,
     noexec: bool,
-    ready_prop: Option<&str>,
+    ready_prop: Option<&String>,
     uid: u32,
     gid: u32,
 ) -> Result<()> {
@@ -471,36 +464,46 @@
 
 #[cfg(test)]
 mod tests {
-    use anyhow::{bail, Result};
+    use super::*;
+    use anyhow::bail;
     use nix::sys::statfs::{statfs, FsType};
     use std::collections::BTreeSet;
     use std::fs;
-    use std::fs::File;
     use std::io::Write;
+    use std::os::unix::fs::MetadataExt;
     use std::path::{Path, PathBuf};
     use std::time::{Duration, Instant};
     use zip::write::FileOptions;
 
+    #[derive(Default)]
+    struct Options {
+        noexec: bool,
+        uid: u32,
+        gid: u32,
+    }
+
     #[cfg(not(target_os = "android"))]
-    fn start_fuse(zip_path: &Path, mnt_path: &Path, noexec: bool) {
+    fn start_fuse(zip_path: &Path, mnt_path: &Path, opt: Options) {
         let zip_path = PathBuf::from(zip_path);
         let mnt_path = PathBuf::from(mnt_path);
         std::thread::spawn(move || {
-            crate::run_fuse(&zip_path, &mnt_path, None, noexec, 0, 0).unwrap();
+            crate::run_fuse(&zip_path, &mnt_path, None, opt.noexec, opt.uid, opt.gid).unwrap();
         });
     }
 
     #[cfg(target_os = "android")]
-    fn start_fuse(zip_path: &Path, mnt_path: &Path, noexec: bool) {
+    fn start_fuse(zip_path: &Path, mnt_path: &Path, opt: Options) {
         // Note: for some unknown reason, running a thread to serve fuse doesn't work on Android.
         // Explicitly spawn a zipfuse process instead.
         // TODO(jiyong): fix this
-        let noexec = if noexec { "--noexec" } else { "" };
+        let noexec = if opt.noexec { "--noexec" } else { "" };
         assert!(std::process::Command::new("sh")
             .arg("-c")
             .arg(format!(
-                "/data/local/tmp/zipfuse {} {} {}",
+                "/data/local/tmp/zipfuse {} -u {} -g {} {} {}",
                 noexec,
+                opt.uid,
+                opt.gid,
                 zip_path.display(),
                 mnt_path.display()
             ))
@@ -529,11 +532,11 @@
     // Creates a zip file, adds some files to the zip file, mounts it using zipfuse, runs the check
     // routine, and finally unmounts.
     fn run_test(add: fn(&mut zip::ZipWriter<File>), check: fn(&std::path::Path)) {
-        run_test_noexec(false, add, check);
+        run_test_with_options(Default::default(), add, check);
     }
 
-    fn run_test_noexec(
-        noexec: bool,
+    fn run_test_with_options(
+        opt: Options,
         add: fn(&mut zip::ZipWriter<File>),
         check: fn(&std::path::Path),
     ) {
@@ -553,7 +556,7 @@
         let mnt_path = test_dir.path().join("mnt");
         assert!(fs::create_dir(&mnt_path).is_ok());
 
-        start_fuse(&zip_path, &mnt_path, noexec);
+        start_fuse(&zip_path, &mnt_path, opt);
 
         let mnt_path = test_dir.path().join("mnt");
         // Give some time for the fuse to boot up
@@ -650,14 +653,37 @@
         });
 
         // Mounting with noexec results in permissions denial when running an executable.
-        let noexec = true;
-        run_test_noexec(noexec, add_executable, |root| {
+        let opt = Options { noexec: true, ..Default::default() };
+        run_test_with_options(opt, add_executable, |root| {
             let res = std::process::Command::new(root.join("executable")).status();
             assert!(matches!(res.unwrap_err().kind(), std::io::ErrorKind::PermissionDenied));
         });
     }
 
     #[test]
+    fn uid_gid() {
+        const UID: u32 = 100;
+        const GID: u32 = 200;
+        run_test_with_options(
+            Options { noexec: true, uid: UID, gid: GID },
+            |zip| {
+                zip.start_file("foo", FileOptions::default()).unwrap();
+                zip.write_all(b"0123456789").unwrap();
+            },
+            |root| {
+                let path = root.join("foo");
+
+                let metadata = fs::metadata(&path);
+                assert!(metadata.is_ok());
+                let metadata = metadata.unwrap();
+
+                assert_eq!(UID, metadata.uid());
+                assert_eq!(GID, metadata.gid());
+            },
+        );
+    }
+
+    #[test]
     fn single_dir() {
         run_test(
             |zip| {
@@ -769,8 +795,8 @@
         let mnt_path = test_dir.join("mnt");
         assert!(fs::create_dir(&mnt_path).is_ok());
 
-        let noexec = false;
-        start_fuse(zip_path, &mnt_path, noexec);
+        let opt = Options { noexec: false, ..Default::default() };
+        start_fuse(zip_path, &mnt_path, opt);
 
         // Give some time for the fuse to boot up
         assert!(wait_for_mount(&mnt_path).is_ok());
@@ -840,4 +866,10 @@
         // Start zipfuse over to the loop device (not the zip file)
         run_fuse_and_check_test_zip(&test_dir.path(), &ld.path().unwrap());
     }
+
+    #[test]
+    fn verify_command() {
+        // Check that the command parsing has been configured in a valid way.
+        clap_command().debug_assert();
+    }
 }