Merge changes I1ec20b6f,Id556f5ae

* changes:
  authfs: support resizing file
  authfs: Drop support of direct I/O
diff --git a/apex/Android.bp b/apex/Android.bp
index 9c201b4..91df00c 100644
--- a/apex/Android.bp
+++ b/apex/Android.bp
@@ -44,15 +44,20 @@
     },
     binaries: [
         "fd_server",
-        "mk_cdisk",
-        "mk_microdroid_signature",
         "virtmanager",
         "vm",
+
+        // tools to create composite images
+        "mk_cdisk",
+        "mk_microdroid_signature",
+        "mk_payload",
     ],
     prebuilts: [
         "com.android.virt.init.rc",
         "microdroid_cdisk.json",
         "microdroid_cdisk_env.json",
+        "microdroid_cdisk_userdata.json",
+        "microdroid_payload.json",
         "microdroid_uboot_env",
         "microdroid_bootloader",
     ],
diff --git a/authfs/fd_server/Android.bp b/authfs/fd_server/Android.bp
index f82b72f..7ac5eb4 100644
--- a/authfs/fd_server/Android.bp
+++ b/authfs/fd_server/Android.bp
@@ -9,7 +9,6 @@
         "authfs_aidl_interface-rust",
         "libandroid_logger",
         "libanyhow",
-        "libbinder_rs",
         "libclap",
         "liblibc",
         "liblog_rust",
diff --git a/authfs/fd_server/src/main.rs b/authfs/fd_server/src/main.rs
index d35feb1..204d1b1 100644
--- a/authfs/fd_server/src/main.rs
+++ b/authfs/fd_server/src/main.rs
@@ -37,15 +37,14 @@
 use std::os::unix::io::{AsRawFd, FromRawFd};
 
 use anyhow::{bail, Context, Result};
-use binder::IBinderInternal; // TODO(178852354): remove once set_requesting_sid is exposed in the API.
 use log::{debug, error};
 
 use authfs_aidl_interface::aidl::com::android::virt::fs::IVirtFdService::{
     BnVirtFdService, IVirtFdService, ERROR_IO, ERROR_UNKNOWN_FD, MAX_REQUESTING_DATA,
 };
 use authfs_aidl_interface::binder::{
-    add_service, ExceptionCode, Interface, ProcessState, Result as BinderResult, Status,
-    StatusCode, Strong,
+    add_service, BinderFeatures, ExceptionCode, Interface, ProcessState, Result as BinderResult,
+    Status, StatusCode, Strong,
 };
 
 const SERVICE_NAME: &str = "authfs_fd_server";
@@ -100,9 +99,7 @@
 
 impl FdService {
     pub fn new_binder(fd_pool: BTreeMap<i32, FdConfig>) -> Strong<dyn IVirtFdService> {
-        let result = BnVirtFdService::new_binder(FdService { fd_pool });
-        result.as_binder().set_requesting_sid(false);
-        result
+        BnVirtFdService::new_binder(FdService { fd_pool }, BinderFeatures::default())
     }
 
     fn get_file_config(&self, id: i32) -> BinderResult<&FdConfig> {
diff --git a/microdroid/Android.bp b/microdroid/Android.bp
index 564348b..e378f6c 100644
--- a/microdroid/Android.bp
+++ b/microdroid/Android.bp
@@ -18,6 +18,7 @@
     "vendor",
     "debug_ramdisk",
     "mnt",
+    "data",
 
     "apex",
     "linkerconfig",
@@ -30,9 +31,13 @@
         target: "/sys/kernel/debug",
         name: "d",
     },
+    {
+        target: "/system/etc",
+        name: "etc",
+    },
 ]
 
-android_filesystem {
+android_system_image {
     name: "microdroid",
     use_avb: true,
     avb_private_key: ":avb_testkey_rsa4096",
@@ -49,7 +54,11 @@
         "logd",
         "run-as",
         "secilc",
-        "adbd",
+
+        // "com.android.adbd" requires these,
+        "libadbd_auth",
+        "libadbd_fs",
+
         "apexd",
         "debuggerd",
         "linker",
@@ -58,7 +67,6 @@
         "tombstoned",
         "cgroups.json",
         "public.libraries.android.txt",
-        "microdroid_linker_config",
 
         "plat_sepolicy_and_mapping.sha256",
     ] + microdroid_shell_and_utilities,
@@ -76,6 +84,7 @@
             ],
         },
     },
+    linker_config_src: "linker.config.json",
     base_dir: "system",
     dirs: microdroid_rootdirs,
     symlinks: microdroid_symlinks,
@@ -101,6 +110,7 @@
     name: "microdroid_vendor",
     use_avb: true,
     deps: [
+        "microdroid_fstab",
         "microdroid_plat_sepolicy_vers.txt",
         "microdroid_precompiled_sepolicy",
         "microdroid_precompiled_sepolicy.plat_sepolicy_and_mapping.sha256",
@@ -380,27 +390,12 @@
     src: "microdroid_cdisk_env.json",
 }
 
-// TODO(b/185391776) generate at build time
-linker_config {
-    name: "microdroid_system_provide",
-    src: "linker.config.json",
-    installable: false,
-}
-
-genrule {
-    name: "microdroid_linker_config_gen",
-    tools: ["conv_linker_config"],
-    srcs: [
-        ":system_linker_config",
-        ":microdroid_system_provide",
-    ],
-    out: ["linker.config.pb"],
-    cmd: "$(location conv_linker_config) merge -o $(out) -i $(location :system_linker_config) -i $(location :microdroid_system_provide)",
+prebuilt_etc {
+    name: "microdroid_cdisk_userdata.json",
+    src: "microdroid_cdisk_userdata.json",
 }
 
 prebuilt_etc {
-    name: "microdroid_linker_config",
-    src: ":microdroid_linker_config_gen",
-    filename: "linker.config.pb",
-    installable: false,
+    name: "microdroid_payload.json",
+    src: "microdroid_payload.json",
 }
diff --git a/microdroid/README.md b/microdroid/README.md
index a4bfb6e..a33e0cb 100644
--- a/microdroid/README.md
+++ b/microdroid/README.md
@@ -34,9 +34,14 @@
 $ adb shell 'cp /apex/com.android.virt/etc/fs/*.img /data/local/tmp'
 $ adb shell 'cp /apex/com.android.virt/etc/uboot_env.img /data/local/tmp'
 $ adb shell 'dd if=/dev/zero of=/data/local/tmp/misc.img bs=4k count=256'
+$ adb shell 'dd if=/dev/zero of=/data/local/tmp/userdata.img bs=1 count=0 seek=4G'
+$ adb shell 'mkfs.ext4 /data/local/tmp/userdata.img'
 $ adb shell 'cd /data/local/tmp; /apex/com.android.virt/bin/mk_cdisk /apex/com.android.virt/etc/microdroid_cdisk.json os_composite.img'
 $ adb shell 'cd /data/local/tmp; /apex/com.android.virt/bin/mk_cdisk /apex/com.android.virt/etc/microdroid_cdisk_env.json env_composite.img'
-$ adb shell 'cd /data/local/tmp; /apex/com.android.virt/bin/crosvm run --cid=5 --disable-sandbox --bios=bootloader --serial=type=stdout --disk=os_composite.img --disk=env_composite.img'
+$ adb shell 'cd /data/local/tmp; /apex/com.android.virt/bin/mk_cdisk /apex/com.android.virt/etc/microdroid_cdisk_userdata.json userdata_composite.img'
+$ adb shell 'cd /data/local/tmp; /apex/com.android.virt/bin/crosvm create_qcow2 --backing_file=userdata_composite.img userdata_composite.qcow2'
+$ adb shell 'cd /data/local/tmp; /apex/com.android.virt/bin/mk_payload /apex/com.android.virt/etc/microdroid_payload.json payload.img'
+$ adb shell 'cd /data/local/tmp; /apex/com.android.virt/bin/crosvm run --cid=5 --disable-sandbox --bios=bootloader --serial=type=stdout --disk=os_composite.img --disk=env_composite.img --disk=payload.img --rwdisk=userdata_composite.qcow2'
 ```
 
 The CID in `--cid` parameter can be anything greater than 2 (`VMADDR_CID_HOST`).
diff --git a/microdroid/fstab b/microdroid/fstab
index 129718e..2f4e45f 100644
--- a/microdroid/fstab
+++ b/microdroid/fstab
@@ -1,2 +1,5 @@
 system /system ext4 noatime,ro,errors=panic wait,first_stage_mount,logical
 vendor /vendor ext4 noatime,ro,errors=panic wait,first_stage_mount,logical
+
+# TODO(b/185767624): turn on encryption
+/dev/block/by-name/userdata /data ext4 noatime,nosuid,nodev,errors=panic latemount,wait,check
diff --git a/microdroid/init.rc b/microdroid/init.rc
index 14238a4..15f9a47 100644
--- a/microdroid/init.rc
+++ b/microdroid/init.rc
@@ -12,11 +12,22 @@
 
 # Cgroups are mounted right before early-init using list from /etc/cgroups.json
 on early-init
-    start ueventd
 
-    # Generate ld.config.txt
-    exec -- /system/bin/bootstrap/linkerconfig --target /linkerconfig
-    chmod 644 /linkerconfig/ld.config.txt
+    # TODO(b/185991357) eliminate bootstrap mount namespace
+    # Set up linker config subdirectories based on mount namespaces
+    mkdir /linkerconfig/bootstrap 0755
+    mkdir /linkerconfig/default 0755
+
+    # Generate ld.config.txt for early executed processes
+    exec -- /system/bin/bootstrap/linkerconfig --target /linkerconfig/bootstrap
+    chmod 644 /linkerconfig/bootstrap/ld.config.txt
+    copy /linkerconfig/bootstrap/ld.config.txt /linkerconfig/default/ld.config.txt
+    chmod 644 /linkerconfig/default/ld.config.txt
+
+    # Mount bootstrap linker configuration as current
+    mount none /linkerconfig/bootstrap /linkerconfig bind rec
+
+    start ueventd
 
     # Run apexd-bootstrap so that APEXes that provide critical libraries
     # become available. Note that this is executed as exec_start to ensure that
@@ -67,6 +78,8 @@
     # some services can be started.
     trigger late-fs
 
+    trigger post-fs-data
+
     # Load persist properties and override properties (if enabled) from /data.
     trigger load_persist_props_action
 
@@ -87,14 +100,39 @@
     # The bind+remount combination allows this to work in containers.
     mount rootfs rootfs / remount bind ro nodev
 
-    # Currently, exec_start apexd-bootstrap is enough to run adb.
-    # TODO(b/179342589): uncomment after turning off APEX session on microdroid
-    # start apexd
-    # Wait for apexd to finish activating APEXes before starting more processes.
-    # wait_for_prop apexd.status activated
+    enter_default_mount_ns
+
+    # Start apexd in the VM mode to avoid unnecessary overhead of session management.
+    exec - root system -- /system/bin/apexd --vm
+
+    perform_apex_config
+
+    exec_start derive_sdk
 
     start adbd
 
+on post-fs-data
+    mount_all /vendor/etc/fstab --late
+    restorecon /data
+
+    mkdir /data/vendor 0771 root root encryption=Require
+    mkdir /data/vendor_ce 0771 root root encryption=None
+    mkdir /data/vendor_de 0771 root root encryption=None
+    mkdir /data/vendor/hardware 0771 root root
+
+    # Start tombstoned early to be able to store tombstones.
+    mkdir /data/anr 0775 system system encryption=Require
+    mkdir /data/tombstones 0771 system system encryption=Require
+    mkdir /data/vendor/tombstones 0771 root root
+    mkdir /data/vendor/tombstones/wifi 0771 wifi wifi
+
+    start tombstoned
+
+    # For security reasons, /data/local/tmp should always be empty.
+    # Do not place files or directories in /data/local/tmp
+    mkdir /data/local 0751 root root encryption=Require
+    mkdir /data/local/tmp 0771 shell shell
+
 service ueventd /system/bin/ueventd
     class core
     critical
@@ -110,13 +148,6 @@
     seclabel u:r:shell:s0
     setenv HOSTNAME console
 
-# TODO(b/181093750): remove these after adding apex support
-service adbd /system/bin/adbd --root_seclabel=u:r:su:s0
-    class core
-    socket adbd seqpacket 660 system system
-    disabled
-    seclabel u:r:adbd:s0
-
 on fs
     write /dev/event-log-tags "# content owned by logd
 "
diff --git a/microdroid/linker.config.json b/microdroid/linker.config.json
index c9c5611..fd90821 100644
--- a/microdroid/linker.config.json
+++ b/microdroid/linker.config.json
@@ -1,17 +1,20 @@
 {
-  // TODO(b/185391776): Automate the list for microdroid
-  "provideLibs": [
-    "libadbd_auth.so",
-    "libadbd_fs.so",
-    "libc.so",
-    "libcgrouprc.so",
-    "libdl.so",
-    "libdl_android.so",
-    "liblog.so",
-    "libm.so",
-    "libselinux.so",
-    "libstdc++.so",
-    "libvndksupport.so",
-    "libz.so"
+  "requireLibs": [
+    "libdexfile.so",
+    "libdexfiled.so",
+    "libnativebridge.so",
+    "libnativehelper.so",
+    "libnativeloader.so",
+    "libsigchain.so",
+    "libandroidicu.so",
+    "libicu.so",
+    "libicui18n.so",
+    "libicuuc.so",
+    "libnetd_resolv.so",
+    "libstatspull.so",
+    "libstatssocket.so",
+    "libadb_pairing_auth.so",
+    "libadb_pairing_connection.so",
+    "libadb_pairing_server.so"
   ]
-}
\ No newline at end of file
+}
diff --git a/microdroid/microdroid_cdisk_userdata.json b/microdroid/microdroid_cdisk_userdata.json
new file mode 100644
index 0000000..04af3f2
--- /dev/null
+++ b/microdroid/microdroid_cdisk_userdata.json
@@ -0,0 +1,9 @@
+{
+  "partitions": [
+    {
+      "label": "userdata",
+      "path": "userdata.img",
+      "writable": true
+    }
+  ]
+}
diff --git a/microdroid/microdroid_payload.json b/microdroid/microdroid_payload.json
new file mode 100644
index 0000000..c5c49d0
--- /dev/null
+++ b/microdroid/microdroid_payload.json
@@ -0,0 +1,6 @@
+{
+  "system_apexes": [
+    "com.android.adbd",
+    "com.android.sdkext"
+  ]
+}
\ No newline at end of file
diff --git a/microdroid/signature/Android.bp b/microdroid/signature/Android.bp
index 63c2128..b993e4e 100644
--- a/microdroid/signature/Android.bp
+++ b/microdroid/signature/Android.bp
@@ -17,6 +17,15 @@
 }
 
 cc_library_static {
+    name: "lib_microdroid_signature_proto",
+    proto: {
+        export_proto_headers: true,
+        type: "full",
+    },
+    defaults: ["microdroid_signature_default"],
+}
+
+cc_library_static {
     name: "lib_microdroid_signature_proto_lite",
     recovery_available: true,
     proto: {
@@ -47,3 +56,31 @@
         "com.android.virt",
     ],
 }
+
+cc_binary {
+    name: "mk_payload",
+    srcs: [
+        "mk_payload.cc",
+    ],
+    shared_libs: [
+        "libbase",
+        "libcuttlefish_fs",
+        "libcuttlefish_utils",
+        "liblog",
+        "libz",
+    ],
+    static_libs: [
+        "lib_microdroid_signature_proto_lite",
+        "libcdisk_spec",
+        "libext2_uuid",
+        "libimage_aggregator",
+        "libjsoncpp",
+        "libprotobuf-cpp-lite",
+        "libsparse",
+        "libxml2",
+    ],
+    generated_sources: ["apex-info-list"],
+    apex_available: [
+        "com.android.virt",
+    ],
+}
diff --git a/microdroid/signature/README.md b/microdroid/signature/README.md
index 4f434ee..0a39c31 100644
--- a/microdroid/signature/README.md
+++ b/microdroid/signature/README.md
@@ -16,6 +16,8 @@
 
 ## How to Create
 
+### `mk_microdroid_signature` and `mk_cdisk`
+
 For testing purpose, use `mk_microdroid_signature` to create a Microdroid Signature.
 
 ```
@@ -53,4 +55,31 @@
 $ adb shell 'cd /data/local/tmp; /apex/com.android.virt/bin/crosvm .... --disk=payload.img'
 ```
 
+### `mk_payload`
+
+`mk_payload` combines these two steps into a single step. Additionally, `mk_payload` can search system APEXes as well.
+This will generate the output composite image as well as three more component images. (See below)
+
+```
+$ cat payload_config.json
+{
+  "system_apexes": [
+    "com.android.adbd",
+  ],
+  "apexes": [
+    {
+      "name": "com.my.hello",
+      "path": "hello.apex"
+    }
+  ]
+}
+$ adb push payload_config.json hello.apex /data/local/tmp/
+$ adb shell 'cd /data/local/tmp; /apex/com.android.virt/bin/mk_payload payload_config.json payload.img
+$ adb shell ls /data/local/tmp/*.img
+payload-footer.img
+payload-header.img
+payload-signature.img
+payload.img
+```
+
 In the future, [VirtManager](../../virtmanager) will handle these stuffs.
\ No newline at end of file
diff --git a/microdroid/signature/mk_payload.cc b/microdroid/signature/mk_payload.cc
new file mode 100644
index 0000000..8046b5e
--- /dev/null
+++ b/microdroid/signature/mk_payload.cc
@@ -0,0 +1,273 @@
+/*
+ * Copyright (C) 2021 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <fstream>
+#include <iostream>
+#include <optional>
+#include <string>
+#include <vector>
+
+#include <android-base/file.h>
+#include <android-base/result.h>
+#include <com_android_apex.h>
+#include <image_aggregator.h>
+#include <json/json.h>
+
+#include "microdroid/signature.h"
+
+using android::base::Dirname;
+using android::base::ErrnoError;
+using android::base::Error;
+using android::base::Result;
+using android::microdroid::ApexSignature;
+using android::microdroid::MicrodroidSignature;
+using android::microdroid::WriteMicrodroidSignature;
+
+using com::android::apex::ApexInfoList;
+using com::android::apex::readApexInfoList;
+
+using cuttlefish::CreateCompositeDisk;
+using cuttlefish::ImagePartition;
+using cuttlefish::kLinuxFilesystem;
+
+Result<uint32_t> GetFileSize(const std::string& path) {
+    struct stat st;
+    if (lstat(path.c_str(), &st) == -1) {
+        return ErrnoError() << "Can't lstat " << path;
+    }
+    return static_cast<uint32_t>(st.st_size);
+}
+
+std::string ToAbsolute(const std::string& path, const std::string& dirname) {
+    bool is_absolute = !path.empty() && path[0] == '/';
+    if (is_absolute) {
+        return path;
+    } else {
+        return dirname + "/" + path;
+    }
+}
+
+// Returns `append` is appended to the end of filename preserving the extension.
+std::string AppendFileName(const std::string& filename, const std::string& append) {
+    size_t pos = filename.find_last_of('.');
+    if (pos == std::string::npos) {
+        return filename + append;
+    } else {
+        return filename.substr(0, pos) + append + filename.substr(pos);
+    }
+}
+
+struct ApexConfig {
+    std::string name; // the apex name
+    std::string path; // the path to the apex file
+                      // absolute or relative to the config file
+    std::optional<std::string> public_key;
+    std::optional<std::string> root_digest;
+};
+
+struct Config {
+    std::string dirname; // config file's direname to resolve relative paths in the config
+
+    std::vector<std::string> system_apexes;
+    std::vector<ApexConfig> apexes;
+};
+
+#define DO(expr) \
+    if (auto res = (expr); !res.ok()) return res.error()
+
+Result<void> ParseJson(const Json::Value& value, std::string& s) {
+    if (!value.isString()) {
+        return Error() << "should be a string: " << value;
+    }
+    s = value.asString();
+    return {};
+}
+
+Result<void> ParseJson(const Json::Value& value, std::optional<std::string>& s) {
+    if (value.isNull()) {
+        s.reset();
+        return {};
+    }
+    s.emplace();
+    return ParseJson(value, *s);
+}
+
+Result<void> ParseJson(const Json::Value& value, ApexConfig& apex_config) {
+    DO(ParseJson(value["name"], apex_config.name));
+    DO(ParseJson(value["path"], apex_config.path));
+    DO(ParseJson(value["publicKey"], apex_config.public_key));
+    DO(ParseJson(value["rootDigest"], apex_config.root_digest));
+    return {};
+}
+
+template <typename T>
+Result<void> ParseJson(const Json::Value& values, std::vector<T>& parsed) {
+    for (const Json::Value& value : values) {
+        T t;
+        DO(ParseJson(value, t));
+        parsed.push_back(std::move(t));
+    }
+    return {};
+}
+
+Result<void> ParseJson(const Json::Value& value, Config& config) {
+    DO(ParseJson(value["system_apexes"], config.system_apexes));
+    DO(ParseJson(value["apexes"], config.apexes));
+    return {};
+}
+
+Result<Config> LoadConfig(const std::string& config_file) {
+    std::ifstream in(config_file);
+    Json::CharReaderBuilder builder;
+    Json::Value root;
+    Json::String errs;
+    if (!parseFromStream(builder, in, &root, &errs)) {
+        return Error() << "bad config: " << errs;
+    }
+
+    Config config;
+    config.dirname = Dirname(config_file);
+    DO(ParseJson(root, config));
+    return config;
+}
+
+#undef DO
+
+Result<void> LoadSystemApexes(Config& config) {
+    static const char* kApexInfoListFile = "/apex/apex-info-list.xml";
+    std::optional<ApexInfoList> apex_info_list = readApexInfoList(kApexInfoListFile);
+    if (!apex_info_list.has_value()) {
+        return Error() << "Failed to read " << kApexInfoListFile;
+    }
+    auto get_apex_path = [&](const std::string& apex_name) -> std::optional<std::string> {
+        for (const auto& apex_info : apex_info_list->getApexInfo()) {
+            if (apex_info.getIsActive() && apex_info.getModuleName() == apex_name) {
+                return apex_info.getModulePath();
+            }
+        }
+        return std::nullopt;
+    };
+    for (const auto& apex_name : config.system_apexes) {
+        const auto& apex_path = get_apex_path(apex_name);
+        if (!apex_path.has_value()) {
+            return Error() << "Can't find the system apex: " << apex_name;
+        }
+        config.apexes.push_back(ApexConfig{
+                .name = apex_name,
+                .path = *apex_path,
+                .public_key = std::nullopt,
+                .root_digest = std::nullopt,
+        });
+    }
+    return {};
+}
+
+Result<void> MakeSignature(const Config& config, const std::string& filename) {
+    MicrodroidSignature signature;
+    signature.set_version(1);
+
+    for (const auto& apex_config : config.apexes) {
+        ApexSignature* apex_signature = signature.add_apexes();
+
+        // name
+        apex_signature->set_name(apex_config.name);
+
+        // size
+        auto file_size = GetFileSize(ToAbsolute(apex_config.path, config.dirname));
+        if (!file_size.ok()) {
+            return Error() << "I/O error: " << file_size.error();
+        }
+        apex_signature->set_size(file_size.value());
+
+        // publicKey
+        if (apex_config.public_key.has_value()) {
+            apex_signature->set_publickey(apex_config.public_key.value());
+        }
+
+        // rootDigest
+        if (apex_config.root_digest.has_value()) {
+            apex_signature->set_rootdigest(apex_config.root_digest.value());
+        }
+    }
+
+    std::ofstream out(filename);
+    return WriteMicrodroidSignature(signature, out);
+}
+
+Result<void> MakePayload(const Config& config, const std::string& signature_file,
+                         const std::string& output_file) {
+    std::vector<ImagePartition> partitions;
+
+    // put signature at the first partition
+    partitions.push_back(ImagePartition{
+            .label = "signature",
+            .image_file_path = signature_file,
+            .type = kLinuxFilesystem,
+            .read_only = true,
+    });
+
+    // put apexes at the subsequent partitions
+    for (size_t i = 0; i < config.apexes.size(); i++) {
+        const auto& apex_config = config.apexes[i];
+        partitions.push_back(ImagePartition{
+                .label = "payload_apex_" + std::to_string(i),
+                .image_file_path = apex_config.path,
+                .type = kLinuxFilesystem,
+                .read_only = true,
+        });
+    }
+
+    const std::string gpt_header = AppendFileName(output_file, "-header");
+    const std::string gpt_footer = AppendFileName(output_file, "-footer");
+    CreateCompositeDisk(partitions, gpt_header, gpt_footer, output_file);
+    return {};
+}
+
+int main(int argc, char** argv) {
+    if (argc != 3) {
+        std::cerr << "Usage: " << argv[0] << " <config> <output>\n";
+        return 1;
+    }
+
+    auto config = LoadConfig(argv[1]);
+    if (!config.ok()) {
+        std::cerr << config.error() << '\n';
+        return 1;
+    }
+
+    if (const auto res = LoadSystemApexes(*config); !res.ok()) {
+        std::cerr << res.error() << '\n';
+        return 1;
+    }
+
+    const std::string output_file(argv[2]);
+    const std::string signature_file = AppendFileName(output_file, "-signature");
+
+    if (const auto res = MakeSignature(*config, signature_file); !res.ok()) {
+        std::cerr << res.error() << '\n';
+        return 1;
+    }
+    if (const auto res = MakePayload(*config, signature_file, output_file); !res.ok()) {
+        std::cerr << res.error() << '\n';
+        return 1;
+    }
+
+    return 0;
+}
\ No newline at end of file
diff --git a/tests/hostside/java/android/virt/test/MicrodroidTestCase.java b/tests/hostside/java/android/virt/test/MicrodroidTestCase.java
index 57c7b17..6dedb49 100644
--- a/tests/hostside/java/android/virt/test/MicrodroidTestCase.java
+++ b/tests/hostside/java/android/virt/test/MicrodroidTestCase.java
@@ -23,6 +23,7 @@
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
 import com.android.tradefed.util.CommandResult;
+import com.android.tradefed.util.FileUtil;
 import com.android.tradefed.util.RunUtil;
 
 import org.junit.After;
@@ -30,6 +31,11 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
+import java.io.File;
+import java.io.FileWriter;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 
@@ -61,11 +67,13 @@
                                 + "cp %setc/microdroid_bootloader bootloader && "
                                 + "cp %setc/fs/*.img . && "
                                 + "cp %setc/uboot_env.img . && "
-                                + "dd if=/dev/zero of=misc.img bs=4k count=256",
+                                + "dd if=/dev/zero of=misc.img bs=4k count=256 && "
+                                + "dd if=/dev/zero of=userdata.img bs=1 count=0 seek=4G && "
+                                + "mkfs.ext4 userdata.img",
                         TEST_ROOT, TEST_ROOT, VIRT_APEX, VIRT_APEX, VIRT_APEX);
         getDevice().executeShellCommand(prepareImagesCmd);
 
-        // Create os_composite.img and env_composite.img
+        // Create os_composite.img, env_composite.img, userdata.img, and payload.img
         String makeOsCompositeCmd =
                 String.format(
                         "cd %s; %sbin/mk_cdisk %setc/microdroid_cdisk.json os_composite.img",
@@ -76,12 +84,34 @@
                         "cd %s; %sbin/mk_cdisk %setc/microdroid_cdisk_env.json env_composite.img",
                         TEST_ROOT, VIRT_APEX, VIRT_APEX);
         getDevice().executeShellCommand(makeEnvCompositeCmd);
+        String makeDataCompositeCmd =
+                String.format(
+                        "cd %s; %sbin/mk_cdisk %setc/microdroid_cdisk_userdata.json"
+                                + " userdata_composite.img",
+                        TEST_ROOT, VIRT_APEX, VIRT_APEX);
+        getDevice().executeShellCommand(makeDataCompositeCmd);
+        String makeDataCompositeQcow2Cmd =
+                String.format(
+                        "cd %s; %sbin/crosvm create_qcow2 --backing_file=userdata_composite.img"
+                                + " userdata_composite.qcow2",
+                        TEST_ROOT, VIRT_APEX);
+        getDevice().executeShellCommand(makeDataCompositeQcow2Cmd);
+        String makePayloadCompositeCmd =
+                String.format(
+                        "cd %s; %sbin/mk_payload %setc/microdroid_payload.json payload.img",
+                        TEST_ROOT, VIRT_APEX, VIRT_APEX);
+        getDevice().executeShellCommand(makePayloadCompositeCmd);
 
         // Make sure that the composite images are created
-        final String compositeImg = TEST_ROOT + "/os_composite.img";
-        final String envCompositeImg = TEST_ROOT + "/env_composite.img";
+        final List<String> compositeImages =
+                new ArrayList<>(
+                        Arrays.asList(
+                                TEST_ROOT + "/os_composite.img",
+                                TEST_ROOT + "/env_composite.img",
+                                TEST_ROOT + "/userdata_composite.qcow2",
+                                TEST_ROOT + "/payload.img"));
         CommandResult result =
-                getDevice().executeShellV2Command("du -b " + compositeImg + " " + envCompositeImg);
+                getDevice().executeShellV2Command("du -b " + String.join(" ", compositeImages));
         assertThat(result.getExitCode(), is(0));
         assertThat(result.getStdout(), is(not("")));
 
@@ -91,7 +121,8 @@
                 String.format(
                         "cd %s; %sbin/crosvm run --cid=%d --disable-sandbox --bios=bootloader"
                                 + " --serial=type=syslog --disk=os_composite.img"
-                                + " --disk=env_composite.img",
+                                + " --disk=env_composite.img --disk=payload.img"
+                                + " --rwdisk=userdata_composite.qcow2",
                         TEST_ROOT, VIRT_APEX, TEST_VM_CID);
         executor.execute(
                 () -> {
@@ -118,6 +149,24 @@
         String prop = executeCommand("adb -s " + MICRODROID_SERIAL + " shell getprop ro.hardware");
         assertThat(prop, is("microdroid"));
 
+        // Test writing to /data partition
+        File tmpFile = FileUtil.createTempFile("test", ".txt");
+        tmpFile.deleteOnExit();
+        FileWriter writer = new FileWriter(tmpFile);
+        writer.write("MicrodroidTest");
+        writer.close();
+
+        executeCommand(
+                "adb -s "
+                        + MICRODROID_SERIAL
+                        + " push "
+                        + tmpFile.getPath()
+                        + " /data/local/tmp/test.txt");
+        String catResult =
+                executeCommand(
+                        "adb -s " + MICRODROID_SERIAL + " shell cat /data/local/tmp/test.txt");
+        assertThat(catResult, is("MicrodroidTest"));
+
         // Shutdown microdroid
         executeCommand("adb -s localhost:" + TEST_VM_ADB_PORT + " shell reboot");
     }
diff --git a/virtmanager/aidl/android/system/virtmanager/VirtualMachineDebugInfo.aidl b/virtmanager/aidl/android/system/virtmanager/VirtualMachineDebugInfo.aidl
index 7bb77ce..967db04 100644
--- a/virtmanager/aidl/android/system/virtmanager/VirtualMachineDebugInfo.aidl
+++ b/virtmanager/aidl/android/system/virtmanager/VirtualMachineDebugInfo.aidl
@@ -24,7 +24,7 @@
     int requesterUid;
 
     /** The SID of the process which requested the VM. */
-    @nullable String requesterSid;
+    String requesterSid;
 
     /**
      * The PID of the process which requested the VM. Note that this process may no longer exist and
diff --git a/virtmanager/src/aidl.rs b/virtmanager/src/aidl.rs
index 5a4eedc..2f96f9d 100644
--- a/virtmanager/src/aidl.rs
+++ b/virtmanager/src/aidl.rs
@@ -24,10 +24,9 @@
 use android_system_virtmanager::aidl::android::system::virtmanager::IVirtualMachineCallback::IVirtualMachineCallback;
 use android_system_virtmanager::aidl::android::system::virtmanager::VirtualMachineDebugInfo::VirtualMachineDebugInfo;
 use android_system_virtmanager::binder::{
-    self, Interface, ParcelFileDescriptor, StatusCode, Strong, ThreadState,
+    self, BinderFeatures, Interface, ParcelFileDescriptor, StatusCode, Strong, ThreadState,
 };
 use log::{debug, error};
-use std::ffi::CStr;
 use std::fs::File;
 use std::sync::{Arc, Mutex, Weak};
 
@@ -60,18 +59,29 @@
             .transpose()?;
         let requester_uid = ThreadState::get_calling_uid();
         let requester_sid = ThreadState::with_calling_sid(|sid| {
-            sid.and_then(|sid: &CStr| match sid.to_str() {
-                Ok(s) => Some(s.to_owned()),
-                Err(e) => {
-                    error!("SID was not valid UTF-8: {:?}", e);
-                    None
+            if let Some(sid) = sid {
+                match sid.to_str() {
+                    Ok(sid) => Ok(sid.to_owned()),
+                    Err(e) => {
+                        error!("SID was not valid UTF-8: {:?}", e);
+                        Err(StatusCode::BAD_VALUE)
+                    }
                 }
-            })
-        });
-        let requester_pid = ThreadState::get_calling_pid();
+            } else {
+                error!("Missing SID on startVm");
+                Err(StatusCode::UNKNOWN_ERROR)
+            }
+        })?;
+        let requester_debug_pid = ThreadState::get_calling_pid();
         let cid = state.allocate_cid()?;
-        let instance =
-            start_vm(config_fd.as_ref(), cid, log_fd, requester_uid, requester_sid, requester_pid)?;
+        let instance = start_vm(
+            config_fd.as_ref(),
+            cid,
+            log_fd,
+            requester_uid,
+            requester_sid,
+            requester_debug_pid,
+        )?;
         state.add_vm(Arc::downgrade(&instance));
         Ok(VirtualMachine::create(instance))
     }
@@ -91,7 +101,7 @@
                 cid: vm.cid as i32,
                 requesterUid: vm.requester_uid as i32,
                 requesterSid: vm.requester_sid.clone(),
-                requesterPid: vm.requester_pid,
+                requesterPid: vm.requester_debug_pid,
                 running: vm.running(),
             })
             .collect();
@@ -139,7 +149,7 @@
 impl VirtualMachine {
     fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
         let binder = VirtualMachine { instance };
-        BnVirtualMachine::new_binder(binder)
+        BnVirtualMachine::new_binder(binder, BinderFeatures::default())
     }
 }
 
@@ -259,16 +269,16 @@
     cid: Cid,
     log_fd: Option<File>,
     requester_uid: u32,
-    requester_sid: Option<String>,
-    requester_pid: i32,
+    requester_sid: String,
+    requester_debug_pid: i32,
 ) -> binder::Result<Arc<VmInstance>> {
     let config = VmConfig::load(config_file).map_err(|e| {
         error!("Failed to load VM config from {:?}: {:?}", config_file, e);
         StatusCode::BAD_VALUE
     })?;
-    Ok(VmInstance::start(&config, cid, log_fd, requester_uid, requester_sid, requester_pid)
+    Ok(VmInstance::start(&config, cid, log_fd, requester_uid, requester_sid, requester_debug_pid)
         .map_err(|e| {
-            error!("Failed to start VM from {:?}: {:?}", config_file, e);
-            StatusCode::UNKNOWN_ERROR
-        })?)
+        error!("Failed to start VM from {:?}: {:?}", config_file, e);
+        StatusCode::UNKNOWN_ERROR
+    })?)
 }
diff --git a/virtmanager/src/crosvm.rs b/virtmanager/src/crosvm.rs
index 5e6f658..60e063c 100644
--- a/virtmanager/src/crosvm.rs
+++ b/virtmanager/src/crosvm.rs
@@ -38,10 +38,10 @@
     /// The UID of the process which requested the VM.
     pub requester_uid: u32,
     /// The SID of the process which requested the VM.
-    pub requester_sid: Option<String>,
+    pub requester_sid: String,
     /// The PID of the process which requested the VM. Note that this process may no longer exist
     /// and the PID may have been reused for a different process, so this should not be trusted.
-    pub requester_pid: i32,
+    pub requester_debug_pid: i32,
     /// Whether the VM is still running.
     running: AtomicBool,
     /// Callbacks to clients of the VM.
@@ -54,15 +54,15 @@
         child: SharedChild,
         cid: Cid,
         requester_uid: u32,
-        requester_sid: Option<String>,
-        requester_pid: i32,
+        requester_sid: String,
+        requester_debug_pid: i32,
     ) -> VmInstance {
         VmInstance {
             child,
             cid,
             requester_uid,
             requester_sid,
-            requester_pid,
+            requester_debug_pid,
             running: AtomicBool::new(true),
             callbacks: Default::default(),
         }
@@ -75,12 +75,17 @@
         cid: Cid,
         log_fd: Option<File>,
         requester_uid: u32,
-        requester_sid: Option<String>,
-        requester_pid: i32,
+        requester_sid: String,
+        requester_debug_pid: i32,
     ) -> Result<Arc<VmInstance>, Error> {
         let child = run_vm(config, cid, log_fd)?;
-        let instance =
-            Arc::new(VmInstance::new(child, cid, requester_uid, requester_sid, requester_pid));
+        let instance = Arc::new(VmInstance::new(
+            child,
+            cid,
+            requester_uid,
+            requester_sid,
+            requester_debug_pid,
+        ));
 
         let instance_clone = instance.clone();
         thread::spawn(move || {
diff --git a/virtmanager/src/main.rs b/virtmanager/src/main.rs
index 486efeb..4c98c41 100644
--- a/virtmanager/src/main.rs
+++ b/virtmanager/src/main.rs
@@ -20,7 +20,7 @@
 
 use crate::aidl::{VirtManager, BINDER_SERVICE_IDENTIFIER};
 use android_system_virtmanager::aidl::android::system::virtmanager::IVirtManager::BnVirtManager;
-use android_system_virtmanager::binder::{add_service, ProcessState};
+use android_system_virtmanager::binder::{add_service, BinderFeatures, ProcessState};
 use log::{info, Level};
 
 /// The first CID to assign to a guest VM managed by the Virt Manager. CIDs lower than this are
@@ -38,7 +38,10 @@
     );
 
     let virt_manager = VirtManager::default();
-    let virt_manager = BnVirtManager::new_binder(virt_manager);
+    let virt_manager = BnVirtManager::new_binder(
+        virt_manager,
+        BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
+    );
     add_service(BINDER_SERVICE_IDENTIFIER, virt_manager.as_binder()).unwrap();
     info!("Registered Binder service, joining threadpool.");
     ProcessState::join_thread_pool();
diff --git a/vm/src/main.rs b/vm/src/main.rs
index 061cfd7..8045817 100644
--- a/vm/src/main.rs
+++ b/vm/src/main.rs
@@ -22,7 +22,8 @@
     BnVirtualMachineCallback, IVirtualMachineCallback,
 };
 use android_system_virtmanager::binder::{
-    get_interface, DeathRecipient, IBinder, ParcelFileDescriptor, ProcessState, Strong,
+    get_interface, BinderFeatures, DeathRecipient, IBinder, ParcelFileDescriptor, ProcessState,
+    Strong,
 };
 use android_system_virtmanager::binder::{Interface, Result as BinderResult};
 use anyhow::{Context, Error};
@@ -105,8 +106,10 @@
 /// Wait until the given VM or the VirtManager itself dies.
 fn wait_for_vm(vm: Strong<dyn IVirtualMachine>) -> Result<(), Error> {
     let dead = AtomicFlag::default();
-    let callback =
-        BnVirtualMachineCallback::new_binder(VirtualMachineCallback { dead: dead.clone() });
+    let callback = BnVirtualMachineCallback::new_binder(
+        VirtualMachineCallback { dead: dead.clone() },
+        BinderFeatures::default(),
+    );
     vm.registerCallback(&callback)?;
     let death_recipient = wait_for_death(&mut vm.as_binder(), dead.clone())?;
     dead.wait();