Merge changes Ib353f1eb,Iddb694e1

* changes:
  Use context()? instead of directly unwrap()-ing.
  Fix OOM in createOrUpdateIdsigFile when a directory is passed
diff --git a/authfs/fd_server/src/main.rs b/authfs/fd_server/src/main.rs
index 21d0e64..9d97423 100644
--- a/authfs/fd_server/src/main.rs
+++ b/authfs/fd_server/src/main.rs
@@ -37,7 +37,8 @@
 use aidl::{FdConfig, FdService};
 use authfs_fsverity_metadata::parse_fsverity_metadata;
 
-const RPC_SERVICE_PORT: u32 = 3264; // TODO: support dynamic port for multiple fd_server instances
+// TODO(b/259920193): support dynamic port for multiple fd_server instances
+const RPC_SERVICE_PORT: u32 = 3264;
 
 fn is_fd_valid(fd: i32) -> bool {
     // SAFETY: a query-only syscall
@@ -137,7 +138,8 @@
 
     debug!("fd_server is starting as a rpc service.");
     let service = FdService::new_binder(fd_pool).as_binder();
-    let server = RpcServer::new_vsock(service, RPC_SERVICE_PORT)?;
+    // TODO(b/259920193): Only accept connections from the intended guest VM.
+    let server = RpcServer::new_vsock(service, libc::VMADDR_CID_ANY, RPC_SERVICE_PORT)?;
     debug!("fd_server is ready");
 
     // Close the ready-fd if we were given one to signal our readiness.
diff --git a/compos/common/lib.rs b/compos/common/lib.rs
index c9555d5..8d49ff0 100644
--- a/compos/common/lib.rs
+++ b/compos/common/lib.rs
@@ -21,9 +21,6 @@
 pub mod odrefresh;
 pub mod timeouts;
 
-/// Special CID indicating "any".
-pub const VMADDR_CID_ANY: u32 = -1i32 as u32;
-
 /// VSock port that the CompOS server listens on for RPC binder connections. This should be out of
 /// future port range (if happens) that microdroid may reserve for system components.
 pub const COMPOS_VSOCK_PORT: u32 = 6432;
diff --git a/demo/java/com/android/microdroid/demo/MainActivity.java b/demo/java/com/android/microdroid/demo/MainActivity.java
index 77f2ee7..54d7420 100644
--- a/demo/java/com/android/microdroid/demo/MainActivity.java
+++ b/demo/java/com/android/microdroid/demo/MainActivity.java
@@ -238,13 +238,6 @@
                             mService.shutdownNow();
                             mStatus.postValue(VirtualMachine.STATUS_STOPPED);
                         }
-
-                        @Override
-                        public void onRamdump(VirtualMachine vm, ParcelFileDescriptor ramdump) {
-                            if (!mService.isShutdown()) {
-                                mPayloadOutput.postValue("(Kernel panic. Ramdump created)");
-                            }
-                        }
                     };
 
             try {
diff --git a/docs/debug/ramdump.md b/docs/debug/ramdump.md
index a0d9bf2..771c608 100644
--- a/docs/debug/ramdump.md
+++ b/docs/debug/ramdump.md
@@ -1,6 +1,6 @@
 # Doing RAM dump of a Microdroid VM and analyzing it
 
-A Microdroid VM creates a RAM dump of itself when the kernel panics. This
+A debuggable Microdroid VM creates a RAM dump of itself when the kernel panics. This
 document explains how the dump can be obtained and analyzed.
 
 ## Force triggering a RAM dump
@@ -49,7 +49,7 @@
 
 ## Obtaining the RAM dump
 
-By default, RAM dumps are sent to tombstone. To see which tombstone file is for
+RAM dumps are sent to tombstone. To see which tombstone file is for
 the RAM dump, look into the log.
 
 ```shell
@@ -64,15 +64,6 @@
 $ adb root && adb pull /data/tombstones/tombstone_47 ramdump && adb unroot
 ```
 
-Alternatively, you can specify the path to where RAM dump is stored when
-launching the VM using the `--ramdump` option of the `vm` tool.
-
-```shell
-$ adb shelll /apex/com.android.virt/bin/vm run-app --ramdump /data/local/tmp/virt/ramdump ...
-```
-
-In the above example, the RAM dump is saved to `/data/local/tmp/virt/ramdump`.
-
 ## Analyzing the RAM dump
 
 ### Building the crash(8) tool
@@ -151,9 +142,3 @@
 actually triggered a crash in the kernel.
 
 For more commands of crash(8), refer to the man page, or embedded `help` command.
-
-
-
-
-
-
diff --git a/javalib/api/system-current.txt b/javalib/api/system-current.txt
index c98c62e..821c47e 100644
--- a/javalib/api/system-current.txt
+++ b/javalib/api/system-current.txt
@@ -6,7 +6,6 @@
     method public void close();
     method @NonNull public android.os.IBinder connectToVsockServer(int) throws android.system.virtualmachine.VirtualMachineException;
     method @NonNull public android.os.ParcelFileDescriptor connectVsock(int) throws android.system.virtualmachine.VirtualMachineException;
-    method public int getCid() throws android.system.virtualmachine.VirtualMachineException;
     method @NonNull public android.system.virtualmachine.VirtualMachineConfig getConfig();
     method @NonNull public java.io.InputStream getConsoleOutput() throws android.system.virtualmachine.VirtualMachineException;
     method @NonNull public java.io.InputStream getLogOutput() throws android.system.virtualmachine.VirtualMachineException;
@@ -29,7 +28,6 @@
     method public void onPayloadFinished(@NonNull android.system.virtualmachine.VirtualMachine, int);
     method public void onPayloadReady(@NonNull android.system.virtualmachine.VirtualMachine);
     method public void onPayloadStarted(@NonNull android.system.virtualmachine.VirtualMachine);
-    method public void onRamdump(@NonNull android.system.virtualmachine.VirtualMachine, @NonNull android.os.ParcelFileDescriptor);
     method public void onStopped(@NonNull android.system.virtualmachine.VirtualMachine, int);
     field public static final int ERROR_PAYLOAD_CHANGED = 2; // 0x2
     field public static final int ERROR_PAYLOAD_INVALID_CONFIG = 3; // 0x3
@@ -74,8 +72,8 @@
     method @NonNull public android.system.virtualmachine.VirtualMachineConfig build();
     method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setApkPath(@NonNull String);
     method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setDebugLevel(int);
-    method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setEncryptedStorageKib(@IntRange(from=0) long);
-    method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setMemoryMib(@IntRange(from=0) int);
+    method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setEncryptedStorageKib(@IntRange(from=1) long);
+    method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setMemoryMib(@IntRange(from=1) int);
     method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setNumCpus(@IntRange(from=1) int);
     method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setPayloadBinaryPath(@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 504d3c7..49465aa 100644
--- a/javalib/src/android/system/virtualmachine/VirtualMachine.java
+++ b/javalib/src/android/system/virtualmachine/VirtualMachine.java
@@ -610,9 +610,22 @@
         } catch (RemoteException e) {
             throw e.rethrowAsRuntimeException();
         }
+        // It's stopped, but we still have a reference to it - we can fix that.
+        dropVm();
     }
 
-    // If we have an IVirtualMachine in the running state return it, otherwise throw.
+    /**
+     * This should only be called when we know our VM has stopped; we no longer need to hold a
+     * reference to it (this allows resources to be GC'd) and we no longer need to be informed of
+     * memory pressure.
+     */
+    @GuardedBy("mLock")
+    private void dropVm() {
+        mContext.unregisterComponentCallbacks(mMemoryManagementCallbacks);
+        mVirtualMachine = null;
+    }
+
+    /** If we have an IVirtualMachine in the running state return it, otherwise throw. */
     @GuardedBy("mLock")
     private IVirtualMachine getRunningVm() throws VirtualMachineException {
         try {
@@ -796,11 +809,6 @@
                                                             VirtualMachine.this, translatedReason));
                                 }
                             }
-
-                            @Override
-                            public void onRamdump(int cid, ParcelFileDescriptor ramdump) {
-                                executeCallback((cb) -> cb.onRamdump(VirtualMachine.this, ramdump));
-                            }
                         });
                 mContext.registerComponentCallbacks(mMemoryManagementCallbacks);
                 service.asBinder().linkToDeath(deathRecipient, 0);
@@ -879,8 +887,7 @@
             }
             try {
                 mVirtualMachine.stop();
-                mContext.unregisterComponentCallbacks(mMemoryManagementCallbacks);
-                mVirtualMachine = null;
+                dropVm();
             } catch (RemoteException e) {
                 throw e.rethrowAsRuntimeException();
             } catch (ServiceSpecificException e) {
@@ -905,8 +912,7 @@
             try {
                 if (stateToStatus(mVirtualMachine.getState()) == STATUS_RUNNING) {
                     mVirtualMachine.stop();
-                    mContext.unregisterComponentCallbacks(mMemoryManagementCallbacks);
-                    mVirtualMachine = null;
+                    dropVm();
                 }
             } catch (RemoteException e) {
                 throw e.rethrowAsRuntimeException();
@@ -940,23 +946,6 @@
     }
 
     /**
-     * Returns the CID of this virtual machine, if it is running.
-     *
-     * @throws VirtualMachineException if the virtual machine is not running.
-     * @hide
-     */
-    @SystemApi
-    public int getCid() throws VirtualMachineException {
-        synchronized (mLock) {
-            try {
-                return getRunningVm().getCid();
-            } catch (RemoteException e) {
-                throw e.rethrowAsRuntimeException();
-            }
-        }
-    }
-
-    /**
      * Changes the config of this virtual machine to a new one. This can be used to adjust things
      * like the number of CPU and size of the RAM, depending on the situation (e.g. the size of the
      * application to run on the virtual machine, etc.)
diff --git a/javalib/src/android/system/virtualmachine/VirtualMachineCallback.java b/javalib/src/android/system/virtualmachine/VirtualMachineCallback.java
index fad2fa9..9aaecf0 100644
--- a/javalib/src/android/system/virtualmachine/VirtualMachineCallback.java
+++ b/javalib/src/android/system/virtualmachine/VirtualMachineCallback.java
@@ -20,7 +20,6 @@
 import android.annotation.NonNull;
 import android.annotation.SuppressLint;
 import android.annotation.SystemApi;
-import android.os.ParcelFileDescriptor;
 
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
@@ -155,7 +154,4 @@
 
     /** Called when the VM has stopped. */
     void onStopped(@NonNull VirtualMachine vm, @StopReason int reason);
-
-    /** Called when kernel panic occurs and as a result ramdump is generated from the VM. */
-    void onRamdump(@NonNull VirtualMachine vm, @NonNull ParcelFileDescriptor ramdump);
 }
diff --git a/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java b/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
index 459b614..602f8b8 100644
--- a/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
+++ b/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
@@ -55,6 +55,8 @@
  */
 @SystemApi
 public final class VirtualMachineConfig {
+    private static final String[] EMPTY_STRING_ARRAY = {};
+
     // These define the schema of the config file persisted on disk.
     private static final int VERSION = 2;
     private static final String KEY_VERSION = "version";
@@ -133,49 +135,7 @@
             int memoryMib,
             int numCpus,
             long encryptedStorageKib) {
-        requireNonNull(apkPath);
-        if (!apkPath.startsWith("/")) {
-            throw new IllegalArgumentException("APK path must be an absolute path");
-        }
-
-        if (memoryMib < 0) {
-            throw new IllegalArgumentException("Memory size cannot be negative");
-        }
-
-        int availableCpus = Runtime.getRuntime().availableProcessors();
-        if (numCpus < 1 || numCpus > availableCpus) {
-            throw new IllegalArgumentException("Number of vCPUs (" + numCpus + ") is out of "
-                    + "range [1, " + availableCpus + "]");
-        }
-
-        if (debugLevel != DEBUG_LEVEL_NONE && debugLevel != DEBUG_LEVEL_FULL) {
-            throw new IllegalArgumentException("Invalid debugLevel: " + debugLevel);
-        }
-
-        if (payloadBinaryPath == null) {
-            if (payloadConfigPath == null) {
-                throw new IllegalStateException("setPayloadBinaryPath must be called");
-            }
-        } else {
-            if (payloadConfigPath != null) {
-                throw new IllegalStateException(
-                        "setPayloadBinaryPath and setPayloadConfigPath may not both be called");
-            }
-        }
-
-        if (protectedVm
-                && !HypervisorProperties.hypervisor_protected_vm_supported().orElse(false)) {
-            throw new UnsupportedOperationException(
-                    "Protected VMs are not supported on this device.");
-        }
-        if (!protectedVm && !HypervisorProperties.hypervisor_vm_supported().orElse(false)) {
-            throw new UnsupportedOperationException(
-                    "Unprotected VMs are not supported on this device.");
-        }
-        if (encryptedStorageKib < 0) {
-            throw new IllegalArgumentException("Encrypted Storage size cannot be negative");
-        }
-
+        // This is only called from Builder.build(); the builder handles parameter validation.
         mApkPath = apkPath;
         mPayloadConfigPath = payloadConfigPath;
         mPayloadBinaryPath = payloadBinaryPath;
@@ -212,40 +172,48 @@
     private static VirtualMachineConfig fromInputStream(@NonNull InputStream input)
             throws IOException, VirtualMachineException {
         PersistableBundle b = PersistableBundle.readFromStream(input);
+        try {
+            return fromPersistableBundle(b);
+        } catch (NullPointerException | IllegalArgumentException | IllegalStateException e) {
+            throw new VirtualMachineException("Persisted VM config is invalid", e);
+        }
+    }
+
+    @NonNull
+    private static VirtualMachineConfig fromPersistableBundle(PersistableBundle b) {
         int version = b.getInt(KEY_VERSION);
         if (version > VERSION) {
-            throw new VirtualMachineException("Version too high");
+            throw new IllegalArgumentException(
+                    "Version " + version + " too high; current is " + VERSION);
         }
-        String apkPath = b.getString(KEY_APKPATH);
-        if (apkPath == null) {
-            throw new VirtualMachineException("No apkPath");
+
+        Builder builder = new Builder();
+        builder.setApkPath(b.getString(KEY_APKPATH));
+
+        String payloadConfigPath = b.getString(KEY_PAYLOADCONFIGPATH);
+        if (payloadConfigPath == null) {
+            builder.setPayloadBinaryPath(b.getString(KEY_PAYLOADBINARYPATH));
+        } else {
+            builder.setPayloadConfigPath(payloadConfigPath);
         }
-        String payloadBinaryPath = b.getString(KEY_PAYLOADBINARYPATH);
-        String payloadConfigPath = null;
-        if (payloadBinaryPath == null) {
-            payloadConfigPath = b.getString(KEY_PAYLOADCONFIGPATH);
-            if (payloadConfigPath == null) {
-                throw new VirtualMachineException("No payloadBinaryPath");
-            }
-        }
+
         @DebugLevel int debugLevel = b.getInt(KEY_DEBUGLEVEL);
         if (debugLevel != DEBUG_LEVEL_NONE && debugLevel != DEBUG_LEVEL_FULL) {
-            throw new VirtualMachineException("Invalid debugLevel: " + debugLevel);
+            throw new IllegalArgumentException("Invalid debugLevel: " + debugLevel);
         }
-        boolean protectedVm = b.getBoolean(KEY_PROTECTED_VM);
+        builder.setDebugLevel(debugLevel);
+        builder.setProtectedVm(b.getBoolean(KEY_PROTECTED_VM));
         int memoryMib = b.getInt(KEY_MEMORY_MIB);
-        int numCpus = b.getInt(KEY_NUM_CPUS);
+        if (memoryMib != 0) {
+            builder.setMemoryMib(memoryMib);
+        }
+        builder.setNumCpus(b.getInt(KEY_NUM_CPUS));
         long encryptedStorageKib = b.getLong(KEY_ENCRYPTED_STORAGE_KIB);
+        if (encryptedStorageKib != 0) {
+            builder.setEncryptedStorageKib(encryptedStorageKib);
+        }
 
-        return new VirtualMachineConfig(
-                apkPath,
-                payloadConfigPath,
-                payloadBinaryPath,
-                debugLevel,
-                protectedVm,
-                memoryMib,
-                numCpus,
-                encryptedStorageKib);
+        return builder.build();
     }
 
     /** Persists this config to a file. */
@@ -335,7 +303,8 @@
     }
 
     /**
-     * Returns the amount of RAM that will be made available to the VM.
+     * Returns the amount of RAM that will be made available to the VM, or 0 if the default size
+     * will be used.
      *
      * @hide
      */
@@ -426,9 +395,8 @@
         vsConfig.protectedVm = mProtectedVm;
         vsConfig.memoryMib = mMemoryMib;
         vsConfig.numCpus = mNumCpus;
-        // Don't allow apps to set task profiles ... at last for now. Also, don't forget to
-        // validate the string because these are appended to the cmdline argument.
-        vsConfig.taskProfiles = new String[0];
+        // Don't allow apps to set task profiles ... at least for now.
+        vsConfig.taskProfiles = EMPTY_STRING_ARRAY;
         return vsConfig;
     }
 
@@ -439,15 +407,15 @@
      */
     @SystemApi
     public static final class Builder {
-        private final Context mContext;
+        @Nullable private final Context mContext;
         @Nullable private String mApkPath;
         @Nullable private String mPayloadConfigPath;
         @Nullable private String mPayloadBinaryPath;
-        @DebugLevel private int mDebugLevel;
+        @DebugLevel private int mDebugLevel = DEBUG_LEVEL_NONE;
         private boolean mProtectedVm;
         private boolean mProtectedVmSet;
         private int mMemoryMib;
-        private int mNumCpus;
+        private int mNumCpus = 1;
         private long mEncryptedStorageKib;
 
         /**
@@ -458,9 +426,14 @@
         @SystemApi
         public Builder(@NonNull Context context) {
             mContext = requireNonNull(context, "context must not be null");
-            mDebugLevel = DEBUG_LEVEL_NONE;
-            mNumCpus = 1;
-            mEncryptedStorageKib = 0;
+        }
+
+        /**
+         * Creates a builder with no associated context; {@link #setApkPath} must be called to
+         * specify which APK contains the payload.
+         */
+        private Builder() {
+            mContext = null;
         }
 
         /**
@@ -471,7 +444,26 @@
         @SystemApi
         @NonNull
         public VirtualMachineConfig build() {
-            String apkPath = (mApkPath == null) ? mContext.getPackageCodePath() : mApkPath;
+            String apkPath;
+            if (mApkPath == null) {
+                if (mContext == null) {
+                    throw new IllegalStateException("apkPath must be specified");
+                }
+                apkPath = mContext.getPackageCodePath();
+            } else {
+                apkPath = mApkPath;
+            }
+
+            if (mPayloadBinaryPath == null) {
+                if (mPayloadConfigPath == null) {
+                    throw new IllegalStateException("setPayloadBinaryPath must be called");
+                }
+            } else {
+                if (mPayloadConfigPath != null) {
+                    throw new IllegalStateException(
+                            "setPayloadBinaryPath and setPayloadConfigPath may not both be called");
+                }
+            }
 
             if (!mProtectedVmSet) {
                 throw new IllegalStateException("setProtectedVm must be called explicitly");
@@ -497,7 +489,11 @@
         @SystemApi
         @NonNull
         public Builder setApkPath(@NonNull String apkPath) {
-            mApkPath = requireNonNull(apkPath);
+            requireNonNull(apkPath, "apkPath must not be null");
+            if (!apkPath.startsWith("/")) {
+                throw new IllegalArgumentException("APK path must be an absolute path");
+            }
+            mApkPath = apkPath;
             return this;
         }
 
@@ -512,7 +508,8 @@
         @TestApi
         @NonNull
         public Builder setPayloadConfigPath(@NonNull String payloadConfigPath) {
-            mPayloadConfigPath = requireNonNull(payloadConfigPath);
+            mPayloadConfigPath =
+                    requireNonNull(payloadConfigPath, "payloadConfigPath must not be null");
             return this;
         }
 
@@ -525,7 +522,8 @@
         @SystemApi
         @NonNull
         public Builder setPayloadBinaryPath(@NonNull String payloadBinaryPath) {
-            mPayloadBinaryPath = requireNonNull(payloadBinaryPath);
+            mPayloadBinaryPath =
+                    requireNonNull(payloadBinaryPath, "payloadBinaryPath must not be null");
             return this;
         }
 
@@ -537,6 +535,9 @@
         @SystemApi
         @NonNull
         public Builder setDebugLevel(@DebugLevel int debugLevel) {
+            if (debugLevel != DEBUG_LEVEL_NONE && debugLevel != DEBUG_LEVEL_FULL) {
+                throw new IllegalArgumentException("Invalid debugLevel: " + debugLevel);
+            }
             mDebugLevel = debugLevel;
             return this;
         }
@@ -551,20 +552,34 @@
         @SystemApi
         @NonNull
         public Builder setProtectedVm(boolean protectedVm) {
+            if (protectedVm) {
+                if (!HypervisorProperties.hypervisor_protected_vm_supported().orElse(false)) {
+                    throw new UnsupportedOperationException(
+                            "Protected VMs are not supported on this device.");
+                }
+            } else {
+                if (!HypervisorProperties.hypervisor_vm_supported().orElse(false)) {
+                    throw new UnsupportedOperationException(
+                            "Unprotected VMs are not supported on this device.");
+                }
+            }
             mProtectedVm = protectedVm;
             mProtectedVmSet = true;
             return this;
         }
 
         /**
-         * Sets the amount of RAM to give the VM, in mebibytes. If zero or not explicitly set then a
-         * default size will be used.
+         * Sets the amount of RAM to give the VM, in mebibytes. If not explicitly set then a default
+         * size will be used.
          *
          * @hide
          */
         @SystemApi
         @NonNull
-        public Builder setMemoryMib(@IntRange(from = 0) int memoryMib) {
+        public Builder setMemoryMib(@IntRange(from = 1) int memoryMib) {
+            if (memoryMib <= 0) {
+                throw new IllegalArgumentException("Memory size must be positive");
+            }
             mMemoryMib = memoryMib;
             return this;
         }
@@ -577,13 +592,24 @@
          */
         @SystemApi
         @NonNull
-        public Builder setNumCpus(@IntRange(from = 1) int num) {
-            mNumCpus = num;
+        public Builder setNumCpus(@IntRange(from = 1) int numCpus) {
+            int availableCpus = Runtime.getRuntime().availableProcessors();
+            if (numCpus < 1 || numCpus > availableCpus) {
+                throw new IllegalArgumentException(
+                        "Number of vCPUs ("
+                                + numCpus
+                                + ") is out of "
+                                + "range [1, "
+                                + availableCpus
+                                + "]");
+            }
+            mNumCpus = numCpus;
             return this;
         }
 
         /**
-         * Sets the size (in KB) of encrypted storage available to the VM.
+         * Sets the size (in KB) of encrypted storage available to the VM. If not set, no encrypted
+         * storage is provided.
          *
          * <p>The storage is encrypted with a key deterministically derived from the VM identity
          *
@@ -599,7 +625,10 @@
          */
         @SystemApi
         @NonNull
-        public Builder setEncryptedStorageKib(@IntRange(from = 0) long encryptedStorageKib) {
+        public Builder setEncryptedStorageKib(@IntRange(from = 1) long encryptedStorageKib) {
+            if (encryptedStorageKib <= 0) {
+                throw new IllegalArgumentException("Encrypted Storage size must be positive");
+            }
             mEncryptedStorageKib = encryptedStorageKib;
             return this;
         }
diff --git a/libs/vbmeta/src/lib.rs b/libs/vbmeta/src/lib.rs
index 691b65c..c273973 100644
--- a/libs/vbmeta/src/lib.rs
+++ b/libs/vbmeta/src/lib.rs
@@ -95,14 +95,17 @@
     ) -> Result<Self, VbMetaImageVerificationError> {
         // Check for a footer in the image or assume it's an entire VBMeta image.
         image.seek(SeekFrom::Start(offset + size)).map_err(VbMetaImageParseError::Io)?;
-        let footer = read_avb_footer(&mut image).map_err(VbMetaImageParseError::Io)?;
-        let (vbmeta_offset, vbmeta_size) = if let Some(footer) = footer {
-            if footer.vbmeta_offset > size || footer.vbmeta_size > size - footer.vbmeta_offset {
-                return Err(VbMetaImageParseError::InvalidFooter.into());
+        let (vbmeta_offset, vbmeta_size) = match read_avb_footer(&mut image) {
+            Ok(footer) => {
+                if footer.vbmeta_offset > size || footer.vbmeta_size > size - footer.vbmeta_offset {
+                    return Err(VbMetaImageParseError::InvalidFooter.into());
+                }
+                (footer.vbmeta_offset, footer.vbmeta_size)
             }
-            (footer.vbmeta_offset, footer.vbmeta_size)
-        } else {
-            (0, size)
+            Err(VbMetaImageParseError::InvalidFooter) => (0, size),
+            Err(e) => {
+                return Err(e.into());
+            }
         };
         image.seek(SeekFrom::Start(offset + vbmeta_offset)).map_err(VbMetaImageParseError::Io)?;
         // Verify the image before examining it to check the size.
@@ -186,7 +189,7 @@
 }
 
 /// Read the AVB footer, if present, given a reader that's positioned at the end of the image.
-fn read_avb_footer<R: Read + Seek>(image: &mut R) -> io::Result<Option<AvbFooter>> {
+fn read_avb_footer<R: Read + Seek>(image: &mut R) -> Result<AvbFooter, VbMetaImageParseError> {
     image.seek(SeekFrom::Current(-(size_of::<AvbFooter>() as i64)))?;
     let mut raw_footer = [0u8; size_of::<AvbFooter>()];
     image.read_exact(&mut raw_footer)?;
@@ -194,9 +197,9 @@
     let mut footer = unsafe { transmute::<[u8; size_of::<AvbFooter>()], AvbFooter>(raw_footer) };
     // SAFETY: the function updates the struct in-place.
     if unsafe { avb_footer_validate_and_byteswap(&footer, &mut footer) } {
-        Ok(Some(footer))
+        Ok(footer)
     } else {
-        Ok(None)
+        Err(VbMetaImageParseError::InvalidFooter)
     }
 }
 
diff --git a/microdroid_manager/src/main.rs b/microdroid_manager/src/main.rs
index 3c490f4..6a37b88 100644
--- a/microdroid_manager/src/main.rs
+++ b/microdroid_manager/src/main.rs
@@ -77,7 +77,6 @@
 
 const APEX_CONFIG_DONE_PROP: &str = "apex_config.done";
 const DEBUGGABLE_PROP: &str = "ro.boot.microdroid.debuggable";
-const APK_MOUNT_DONE_PROP: &str = "microdroid_manager.apk.mounted";
 
 // SYNC WITH virtualizationservice/src/crosvm.rs
 const FAILURE_SERIAL_DEVICE: &str = "/dev/ttyS1";
@@ -383,15 +382,16 @@
         None
     };
 
+    let mut zipfuse = Zipfuse::default();
+
     // Before reading a file from the APK, start zipfuse
-    run_zipfuse(
+    zipfuse.mount(
         MountForExec::Allowed,
         "fscontext=u:object_r:zipfusefs:s0,context=u:object_r:system_file:s0",
         Path::new("/dev/block/mapper/microdroid-apk"),
         Path::new(VM_APK_CONTENTS_PATH),
-        Some(APK_MOUNT_DONE_PROP),
-    )
-    .context("Failed to run zipfuse")?;
+        "microdroid_manager.apk.mounted".to_owned(),
+    )?;
 
     // Restricted APIs are only allowed to be used by platform or test components. Infer this from
     // the use of a VM config file since those can only be used by platform and test components.
@@ -414,7 +414,7 @@
             verified_data.extra_apks_data.len()
         ));
     }
-    mount_extra_apks(&config)?;
+    mount_extra_apks(&config, &mut zipfuse)?;
 
     // Wait until apex config is done. (e.g. linker configuration for apexes)
     wait_for_apex_config_done()?;
@@ -428,8 +428,8 @@
         control_service("stop", "tombstoned")?;
     }
 
-    // Wait until zipfuse has mounted the APK so we can access the payload
-    wait_for_property_true(APK_MOUNT_DONE_PROP).context("Failed waiting for APK mount done")?;
+    // Wait until zipfuse has mounted the APKs so we can access the payload
+    zipfuse.wait_until_done()?;
 
     register_vm_payload_service(allow_restricted_apis, service.clone(), dice_context)?;
 
@@ -480,21 +480,40 @@
     Disallowed,
 }
 
-fn run_zipfuse(
-    noexec: MountForExec,
-    option: &str,
-    zip_path: &Path,
-    mount_dir: &Path,
-    ready_prop: Option<&str>,
-) -> Result<Child> {
-    let mut cmd = Command::new(ZIPFUSE_BIN);
-    if let MountForExec::Disallowed = noexec {
-        cmd.arg("--noexec");
+#[derive(Default)]
+struct Zipfuse {
+    ready_properties: Vec<String>,
+}
+
+impl Zipfuse {
+    fn mount(
+        &mut self,
+        noexec: MountForExec,
+        option: &str,
+        zip_path: &Path,
+        mount_dir: &Path,
+        ready_prop: String,
+    ) -> Result<Child> {
+        let mut cmd = Command::new(ZIPFUSE_BIN);
+        if let MountForExec::Disallowed = noexec {
+            cmd.arg("--noexec");
+        }
+        cmd.args(["-p", &ready_prop, "-o", option]);
+        cmd.arg(zip_path).arg(mount_dir);
+        self.ready_properties.push(ready_prop);
+        cmd.spawn().with_context(|| format!("Failed to run zipfuse for {mount_dir:?}"))
     }
-    if let Some(property_name) = ready_prop {
-        cmd.args(["-p", property_name]);
+
+    fn wait_until_done(self) -> Result<()> {
+        // We check the last-started check first in the hope that by the time it is done
+        // all or most of the others will also be done, minimising the number of times we
+        // block on a property.
+        for property in self.ready_properties.into_iter().rev() {
+            wait_for_property_true(&property)
+                .with_context(|| format!("Failed waiting for {property}"))?;
+        }
+        Ok(())
     }
-    cmd.arg("-o").arg(option).arg(zip_path).arg(mount_dir).spawn().context("Spawn zipfuse")
 }
 
 fn write_apex_payload_data(
@@ -664,21 +683,20 @@
     })
 }
 
-fn mount_extra_apks(config: &VmPayloadConfig) -> Result<()> {
+fn mount_extra_apks(config: &VmPayloadConfig, zipfuse: &mut Zipfuse) -> Result<()> {
     // For now, only the number of apks is important, as the mount point and dm-verity name is fixed
     for i in 0..config.extra_apks.len() {
-        let mount_dir = format!("/mnt/extra-apk/{}", i);
+        let mount_dir = format!("/mnt/extra-apk/{i}");
         create_dir(Path::new(&mount_dir)).context("Failed to create mount dir for extra apks")?;
 
         // don't wait, just detach
-        run_zipfuse(
+        zipfuse.mount(
             MountForExec::Disallowed,
             "fscontext=u:object_r:zipfusefs:s0,context=u:object_r:extra_apk_file:s0",
-            Path::new(&format!("/dev/block/mapper/extra-apk-{}", i)),
+            Path::new(&format!("/dev/block/mapper/extra-apk-{i}")),
             Path::new(&mount_dir),
-            None,
-        )
-        .context("Failed to zipfuse extra apks")?;
+            format!("microdroid_manager.extra_apk.mounted.{i}"),
+        )?;
     }
 
     Ok(())
diff --git a/pvmfw/src/config.rs b/pvmfw/src/config.rs
index 0f2a39c..b633745 100644
--- a/pvmfw/src/config.rs
+++ b/pvmfw/src/config.rs
@@ -17,8 +17,7 @@
 use crate::helpers;
 use core::fmt;
 use core::mem;
-use core::num::NonZeroUsize;
-use core::ops;
+use core::ops::Range;
 use core::result;
 
 #[repr(C, packed)]
@@ -43,8 +42,10 @@
     InvalidFlags(u32),
     /// Header describes configuration data that doesn't fit in the expected buffer.
     InvalidSize(usize),
+    /// Header entry is missing.
+    MissingEntry(Entry),
     /// Header entry is invalid.
-    InvalidEntry(Entry),
+    InvalidEntry(Entry, EntryError),
 }
 
 impl fmt::Display for Error {
@@ -55,13 +56,38 @@
             Self::UnsupportedVersion(x, y) => write!(f, "Version {x}.{y} not supported"),
             Self::InvalidFlags(v) => write!(f, "Flags value {v:#x} is incorrect or reserved"),
             Self::InvalidSize(sz) => write!(f, "Total size ({sz:#x}) overflows reserved region"),
-            Self::InvalidEntry(e) => write!(f, "Entry {e:?} is invalid"),
+            Self::MissingEntry(entry) => write!(f, "Mandatory {entry:?} entry is missing"),
+            Self::InvalidEntry(entry, e) => write!(f, "Invalid {entry:?} entry: {e}"),
         }
     }
 }
 
 pub type Result<T> = result::Result<T, Error>;
 
+#[derive(Debug)]
+pub enum EntryError {
+    /// Offset isn't between the fixed minimum value and size of configuration data.
+    InvalidOffset(usize),
+    /// Size must be zero when offset is and not be when it isn't.
+    InvalidSize(usize),
+    /// Entry isn't fully within the configuration data structure.
+    OutOfBounds { offset: usize, size: usize, limit: usize },
+}
+
+impl fmt::Display for EntryError {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        match self {
+            Self::InvalidOffset(offset) => write!(f, "Invalid offset: {offset:#x?}"),
+            Self::InvalidSize(sz) => write!(f, "Invalid size: {sz:#x?}"),
+            Self::OutOfBounds { offset, size, limit } => {
+                let range = Header::PADDED_SIZE..*limit;
+                let entry = *offset..(*offset + *size);
+                write!(f, "Out of bounds: {entry:#x?} must be within range {range:#x?}")
+            }
+        }
+    }
+}
+
 impl Header {
     const MAGIC: u32 = u32::from_ne_bytes(*b"pvmf");
     const PADDED_SIZE: usize =
@@ -83,8 +109,43 @@
         self.total_size() - Self::PADDED_SIZE
     }
 
-    fn get(&self, entry: Entry) -> HeaderEntry {
-        self.entries[entry as usize]
+    fn get_body_range(&self, entry: Entry) -> Result<Option<Range<usize>>> {
+        let e = self.entries[entry as usize];
+        let offset = e.offset as usize;
+        let size = e.size as usize;
+
+        match self._get_body_range(offset, size) {
+            Ok(r) => Ok(r),
+            Err(EntryError::InvalidSize(0)) => {
+                // As our bootloader currently uses this (non-compliant) case, permit it for now.
+                log::warn!("Config entry {entry:?} uses non-zero offset with zero size");
+                // TODO(b/262181812): Either make this case valid or fix the bootloader.
+                Ok(None)
+            }
+            Err(e) => Err(Error::InvalidEntry(entry, e)),
+        }
+    }
+
+    fn _get_body_range(
+        &self,
+        offset: usize,
+        size: usize,
+    ) -> result::Result<Option<Range<usize>>, EntryError> {
+        match (offset, size) {
+            (0, 0) => Ok(None),
+            (0, size) | (_, size @ 0) => Err(EntryError::InvalidSize(size)),
+            _ => {
+                let start = offset
+                    .checked_sub(Header::PADDED_SIZE)
+                    .ok_or(EntryError::InvalidOffset(offset))?;
+                let end = start
+                    .checked_add(size)
+                    .filter(|x| *x <= self.body_size())
+                    .ok_or(EntryError::OutOfBounds { offset, size, limit: self.total_size() })?;
+
+                Ok(Some(start..end))
+            }
+        }
     }
 }
 
@@ -105,38 +166,11 @@
     size: u32,
 }
 
-impl HeaderEntry {
-    pub fn is_empty(&self) -> bool {
-        self.offset() == 0 && self.size() == 0
-    }
-
-    pub fn fits_in(&self, max_size: usize) -> bool {
-        (Header::PADDED_SIZE..max_size).contains(&self.offset())
-            && NonZeroUsize::new(self.size())
-                .and_then(|s| s.checked_add(self.offset()))
-                .filter(|&x| x.get() <= max_size)
-                .is_some()
-    }
-
-    pub fn as_body_range(&self) -> ops::Range<usize> {
-        let start = self.offset() - Header::PADDED_SIZE;
-
-        start..(start + self.size())
-    }
-
-    pub fn offset(&self) -> usize {
-        self.offset as usize
-    }
-
-    pub fn size(&self) -> usize {
-        self.size as usize
-    }
-}
-
 #[derive(Debug)]
 pub struct Config<'a> {
-    header: &'a Header,
     body: &'a mut [u8],
+    bcc_range: Range<usize>,
+    dp_range: Option<Range<usize>>,
 }
 
 impl<'a> Config<'a> {
@@ -161,40 +195,26 @@
             return Err(Error::InvalidFlags(header.flags));
         }
 
-        let total_size = header.total_size();
-
-        // BCC is a mandatory entry of the configuration data.
-        if !header.get(Entry::Bcc).fits_in(total_size) {
-            return Err(Error::InvalidEntry(Entry::Bcc));
-        }
-
-        // Debug policy is optional.
-        let dp = header.get(Entry::DebugPolicy);
-        if !dp.is_empty() && !dp.fits_in(total_size) {
-            return Err(Error::InvalidEntry(Entry::DebugPolicy));
-        }
+        let bcc_range =
+            header.get_body_range(Entry::Bcc)?.ok_or(Error::MissingEntry(Entry::Bcc))?;
+        let dp_range = header.get_body_range(Entry::DebugPolicy)?;
 
         let body = data
             .get_mut(Header::PADDED_SIZE..)
             .ok_or(Error::BufferTooSmall)?
             .get_mut(..header.body_size())
-            .ok_or(Error::InvalidSize(total_size))?;
+            .ok_or_else(|| Error::InvalidSize(header.total_size()))?;
 
-        Ok(Self { header, body })
+        Ok(Self { body, bcc_range, dp_range })
     }
 
     /// Get slice containing the platform BCC.
     pub fn get_bcc_mut(&mut self) -> &mut [u8] {
-        &mut self.body[self.header.get(Entry::Bcc).as_body_range()]
+        &mut self.body[self.bcc_range.clone()]
     }
 
     /// Get slice containing the platform debug policy.
     pub fn get_debug_policy(&mut self) -> Option<&mut [u8]> {
-        let entry = self.header.get(Entry::DebugPolicy);
-        if entry.is_empty() {
-            None
-        } else {
-            Some(&mut self.body[entry.as_body_range()])
-        }
+        self.dp_range.as_ref().map(|r| &mut self.body[r.clone()])
     }
 }
diff --git a/tests/helper/src/java/com/android/microdroid/test/device/MicrodroidDeviceTestBase.java b/tests/helper/src/java/com/android/microdroid/test/device/MicrodroidDeviceTestBase.java
index 72a0090..9aed34d 100644
--- a/tests/helper/src/java/com/android/microdroid/test/device/MicrodroidDeviceTestBase.java
+++ b/tests/helper/src/java/com/android/microdroid/test/device/MicrodroidDeviceTestBase.java
@@ -248,9 +248,6 @@
             vm.clearCallback();
             mExecutorService.shutdown();
         }
-
-        @Override
-        public void onRamdump(VirtualMachine vm, ParcelFileDescriptor ramdump) {}
     }
 
     public static class BootResult {
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 2cd4e51..25f2310 100644
--- a/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
+++ b/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
@@ -458,10 +458,10 @@
         VirtualMachineConfig.Builder builder =
                 newVmConfigBuilder()
                         .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
-                        .setApkPath("relative/path/to.apk")
                         .setDebugLevel(DEBUG_LEVEL_FULL)
                         .setMemoryMib(minMemoryRequired());
-        assertThrows(IllegalArgumentException.class, () -> builder.build());
+        assertThrows(
+                IllegalArgumentException.class, () -> builder.setApkPath("relative/path/to.apk"));
     }
 
     @Test
diff --git a/virtualizationservice/aidl/android/system/virtualizationservice/IVirtualMachineCallback.aidl b/virtualizationservice/aidl/android/system/virtualizationservice/IVirtualMachineCallback.aidl
index a329fa6..34b6fa5 100644
--- a/virtualizationservice/aidl/android/system/virtualizationservice/IVirtualMachineCallback.aidl
+++ b/virtualizationservice/aidl/android/system/virtualizationservice/IVirtualMachineCallback.aidl
@@ -50,9 +50,4 @@
      * also use `link_to_death` to handle that.
      */
     void onDied(int cid, in DeathReason reason);
-
-    /**
-     * Called when kernel panic occurs and as a result ramdump is generated from the VM.
-     */
-    void onRamdump(int cid, in ParcelFileDescriptor ramdump);
 }
diff --git a/virtualizationservice/src/aidl.rs b/virtualizationservice/src/aidl.rs
index 050b89c..4c6b961 100644
--- a/virtualizationservice/src/aidl.rs
+++ b/virtualizationservice/src/aidl.rs
@@ -477,9 +477,8 @@
             let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
 
             // Start VM service listening for connections from the new CID on port=CID.
-            // TODO(b/245727626): Only accept connections from the new VM.
             let port = cid;
-            match RpcServer::new_vsock(service, port) {
+            match RpcServer::new_vsock(service, cid, port) {
                 Ok(vm_server) => {
                     vm_server.start();
                     return Ok((VmContext::new(global_context, vm_server), cid));
@@ -1064,17 +1063,6 @@
         }
     }
 
-    /// Call all registered callbacks to say that there was a ramdump to download.
-    pub fn callback_on_ramdump(&self, cid: Cid, ramdump: File) {
-        let callbacks = &*self.0.lock().unwrap();
-        let pfd = ParcelFileDescriptor::new(ramdump);
-        for callback in callbacks {
-            if let Err(e) = callback.onRamdump(cid as i32, &pfd) {
-                error!("Error notifying ramdump of VM CID {}: {:?}", cid, e);
-            }
-        }
-    }
-
     /// Add a new callback to the set.
     fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
         self.0.lock().unwrap().push(callback);
diff --git a/virtualizationservice/src/crosvm.rs b/virtualizationservice/src/crosvm.rs
index fc85ca5..5125f19 100644
--- a/virtualizationservice/src/crosvm.rs
+++ b/virtualizationservice/src/crosvm.rs
@@ -520,15 +520,10 @@
         Ok(())
     }
 
-    /// Checks if ramdump has been created. If so, send a notification to the user with the handle
-    /// to read the ramdump.
+    /// Checks if ramdump has been created. If so, send it to tombstoned.
     fn handle_ramdump(&self) -> Result<(), Error> {
         let ramdump_path = self.temporary_directory.join("ramdump");
         if std::fs::metadata(&ramdump_path)?.len() > 0 {
-            let ramdump = File::open(&ramdump_path)
-                .context(format!("Failed to open ramdump {:?} for reading", &ramdump_path))?;
-            self.callbacks.callback_on_ramdump(self.cid, ramdump);
-
             Self::send_ramdump_to_tombstoned(&ramdump_path)?;
         }
         Ok(())
@@ -536,7 +531,7 @@
 
     fn send_ramdump_to_tombstoned(ramdump_path: &Path) -> Result<(), Error> {
         let mut input = File::open(ramdump_path)
-            .context(format!("Failed to open raudmp {:?} for reading", ramdump_path))?;
+            .context(format!("Failed to open ramdump {:?} for reading", ramdump_path))?;
 
         let pid = std::process::id() as i32;
         let conn = TombstonedConnection::connect(pid, DebuggerdDumpType::Tombstone)
diff --git a/vm/src/main.rs b/vm/src/main.rs
index 32b165b..3d2fc00 100644
--- a/vm/src/main.rs
+++ b/vm/src/main.rs
@@ -81,10 +81,6 @@
         #[clap(long)]
         log: Option<PathBuf>,
 
-        /// Path to file where ramdump is recorded on kernel panic
-        #[clap(long)]
-        ramdump: Option<PathBuf>,
-
         /// Debug level of the VM. Supported values: "none" (default), and "full".
         #[clap(long, default_value = "none", value_parser = parse_debug_level)]
         debug: DebugLevel,
@@ -144,10 +140,6 @@
         #[clap(long)]
         log: Option<PathBuf>,
 
-        /// Path to file where ramdump is recorded on kernel panic
-        #[clap(long)]
-        ramdump: Option<PathBuf>,
-
         /// Debug level of the VM. Supported values: "none" (default), and "full".
         #[clap(long, default_value = "full", value_parser = parse_debug_level)]
         debug: DebugLevel,
@@ -268,7 +260,6 @@
             daemonize,
             console,
             log,
-            ramdump,
             debug,
             protected,
             mem,
@@ -288,7 +279,6 @@
             daemonize,
             console.as_deref(),
             log.as_deref(),
-            ramdump.as_deref(),
             debug,
             protected,
             mem,
@@ -304,7 +294,6 @@
             daemonize,
             console,
             log,
-            ramdump,
             debug,
             protected,
             mem,
@@ -319,7 +308,6 @@
             daemonize,
             console.as_deref(),
             log.as_deref(),
-            ramdump.as_deref(),
             debug,
             protected,
             mem,
diff --git a/vm/src/run.rs b/vm/src/run.rs
index 3f25bba..6096913 100644
--- a/vm/src/run.rs
+++ b/vm/src/run.rs
@@ -52,7 +52,6 @@
     daemonize: bool,
     console_path: Option<&Path>,
     log_path: Option<&Path>,
-    ramdump_path: Option<&Path>,
     debug_level: DebugLevel,
     protected: bool,
     mem: Option<u32>,
@@ -144,7 +143,7 @@
         numCpus: cpus.unwrap_or(1) as i32,
         taskProfiles: task_profiles,
     });
-    run(service, &config, &payload_config_str, daemonize, console_path, log_path, ramdump_path)
+    run(service, &config, &payload_config_str, daemonize, console_path, log_path)
 }
 
 const EMPTY_PAYLOAD_APK: &str = "com.android.microdroid.empty_payload";
@@ -182,7 +181,6 @@
     daemonize: bool,
     console_path: Option<&Path>,
     log_path: Option<&Path>,
-    ramdump_path: Option<&Path>,
     debug_level: DebugLevel,
     protected: bool,
     mem: Option<u32>,
@@ -214,7 +212,6 @@
         daemonize,
         console_path,
         log_path,
-        ramdump_path,
         debug_level,
         protected,
         mem,
@@ -259,7 +256,6 @@
         daemonize,
         console_path,
         log_path,
-        /* ramdump_path */ None,
     )
 }
 
@@ -282,7 +278,6 @@
     daemonize: bool,
     console_path: Option<&Path>,
     log_path: Option<&Path>,
-    ramdump_path: Option<&Path>,
 ) -> Result<(), Error> {
     let console = if let Some(console_path) = console_path {
         Some(
@@ -325,27 +320,12 @@
         // Wait until the VM or VirtualizationService dies. If we just returned immediately then the
         // IVirtualMachine Binder object would be dropped and the VM would be killed.
         let death_reason = vm.wait_for_death();
-
-        if let Some(path) = ramdump_path {
-            save_ramdump_if_available(path, &vm)?;
-        }
         println!("VM ended: {:?}", death_reason);
     }
 
     Ok(())
 }
 
-fn save_ramdump_if_available(path: &Path, vm: &VmInstance) -> Result<(), Error> {
-    if let Some(mut ramdump) = vm.get_ramdump() {
-        let mut file =
-            File::create(path).context(format!("Failed to create ramdump file {:?}", path))?;
-        let size = std::io::copy(&mut ramdump, &mut file)
-            .context(format!("Failed to save ramdump to file {:?}", path))?;
-        eprintln!("Ramdump ({} bytes) saved to {:?}", size, path);
-    }
-    Ok(())
-}
-
 fn parse_extra_apk_list(apk: &Path, config_path: &str) -> Result<Vec<String>, Error> {
     let mut archive = ZipArchive::new(File::open(apk)?)?;
     let config_file = archive.by_name(config_path)?;
diff --git a/vm_payload/src/api.rs b/vm_payload/src/api.rs
index 28b440e..66c8ef7 100644
--- a/vm_payload/src/api.rs
+++ b/vm_payload/src/api.rs
@@ -136,7 +136,7 @@
     // safely be taken by new_spibinder.
     let service = unsafe { new_spibinder(service) };
     if let Some(service) = service {
-        match RpcServer::new_vsock(service, port) {
+        match RpcServer::new_vsock(service, libc::VMADDR_CID_HOST, port) {
             Ok(server) => {
                 if let Some(on_ready) = on_ready {
                     // SAFETY: We're calling the callback with the parameter specified within the
diff --git a/vmbase/Android.bp b/vmbase/Android.bp
index 7a36a0a..5ed436c 100644
--- a/vmbase/Android.bp
+++ b/vmbase/Android.bp
@@ -68,7 +68,7 @@
         "libspin_nostd",
     ],
     whole_static_libs: [
-        "libarm-optimized-routines-mem",
+        "librust_baremetal",
     ],
     apex_available: ["com.android.virt"],
 }
diff --git a/vmclient/src/lib.rs b/vmclient/src/lib.rs
index 20b7f02..7c05545 100644
--- a/vmclient/src/lib.rs
+++ b/vmclient/src/lib.rs
@@ -190,11 +190,6 @@
             }
         })
     }
-
-    /// Get ramdump
-    pub fn get_ramdump(&self) -> Option<File> {
-        self.state.get_ramdump()
-    }
 }
 
 impl Debug for VmInstance {
@@ -222,7 +217,6 @@
 struct VmState {
     death_reason: Option<DeathReason>,
     reported_state: VirtualMachineState,
-    ramdump: Option<File>,
 }
 
 impl Monitor<VmState> {
@@ -239,14 +233,6 @@
         self.state.lock().unwrap().reported_state = state;
         self.cv.notify_all();
     }
-
-    fn set_ramdump(&self, ramdump: File) {
-        self.state.lock().unwrap().ramdump = Some(ramdump);
-    }
-
-    fn get_ramdump(&self) -> Option<File> {
-        self.state.lock().unwrap().ramdump.as_ref().and_then(|f| f.try_clone().ok())
-    }
 }
 
 struct VirtualMachineCallback {
@@ -302,12 +288,6 @@
         Ok(())
     }
 
-    fn onRamdump(&self, _cid: i32, ramdump: &ParcelFileDescriptor) -> BinderResult<()> {
-        let ramdump: File = ramdump.as_ref().try_clone().unwrap();
-        self.state.set_ramdump(ramdump);
-        Ok(())
-    }
-
     fn onDied(&self, cid: i32, reason: AidlDeathReason) -> BinderResult<()> {
         let reason = reason.into();
         self.state.notify_death(reason);