Merge "Need to call set_requesting_sid for with_calling_sid to work."
diff --git a/apex/Android.bp b/apex/Android.bp
index 41d2f62..8af22ff 100644
--- a/apex/Android.bp
+++ b/apex/Android.bp
@@ -43,15 +43,20 @@
         },
     },
     binaries: [
-        "mk_cdisk",
         "fd_server",
         "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_payload.json",
         "microdroid_uboot_env",
         "microdroid_bootloader",
     ],
diff --git a/microdroid/Android.bp b/microdroid/Android.bp
index 2ce435b..249ddc7 100644
--- a/microdroid/Android.bp
+++ b/microdroid/Android.bp
@@ -30,9 +30,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",
@@ -41,6 +45,7 @@
     deps: [
         "init_second_stage",
         "microdroid_init_rc",
+        "microdroid_build_prop",
         "ueventd.rc",
         "libbinder",
         "libstdc++",
@@ -48,7 +53,11 @@
         "logd",
         "run-as",
         "secilc",
-        "adbd",
+
+        // "com.android.adbd" requires these,
+        "libadbd_auth",
+        "libadbd_fs",
+
         "apexd",
         "debuggerd",
         "linker",
@@ -56,6 +65,7 @@
         "servicemanager",
         "tombstoned",
         "cgroups.json",
+        "public.libraries.android.txt",
 
         "plat_sepolicy_and_mapping.sha256",
     ] + microdroid_shell_and_utilities,
@@ -73,6 +83,7 @@
             ],
         },
     },
+    linker_config_src: "linker.config.json",
     base_dir: "system",
     dirs: microdroid_rootdirs,
     symlinks: microdroid_symlinks,
@@ -87,6 +98,13 @@
     installable: false, // avoid collision with system partition's init.rc
 }
 
+prebuilt_root {
+    name: "microdroid_build_prop",
+    filename: "build.prop",
+    src: "build.prop",
+    installable: false,
+}
+
 android_filesystem {
     name: "microdroid_vendor",
     use_avb: true,
@@ -369,3 +387,8 @@
     name: "microdroid_cdisk_env.json",
     src: "microdroid_cdisk_env.json",
 }
+
+prebuilt_etc {
+    name: "microdroid_payload.json",
+    src: "microdroid_payload.json",
+}
diff --git a/microdroid/README.md b/microdroid/README.md
index a4bfb6e..4ce74a5 100644
--- a/microdroid/README.md
+++ b/microdroid/README.md
@@ -36,7 +36,8 @@
 $ adb shell 'dd if=/dev/zero of=/data/local/tmp/misc.img bs=4k count=256'
 $ 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_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'
 ```
 
 The CID in `--cid` parameter can be anything greater than 2 (`VMADDR_CID_HOST`).
diff --git a/microdroid/build.prop b/microdroid/build.prop
new file mode 100644
index 0000000..52d073f
--- /dev/null
+++ b/microdroid/build.prop
@@ -0,0 +1,4 @@
+# build.prop for microdroid
+ro.apex.updatable=true
+ro.debuggable=1
+ro.adb.secure=0
diff --git a/microdroid/init.rc b/microdroid/init.rc
index e70fb77..61f9ae5 100644
--- a/microdroid/init.rc
+++ b/microdroid/init.rc
@@ -12,14 +12,22 @@
 
 # Cgroups are mounted right before early-init using list from /etc/cgroups.json
 on early-init
-    start ueventd
-    setprop ro.apex.updatable true
-    setprop ro.debuggable 1
-    setprop ro.adb.secure 0
 
-    # 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
@@ -90,11 +98,14 @@
     # 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
 
@@ -113,13 +124,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
new file mode 100644
index 0000000..fd90821
--- /dev/null
+++ b/microdroid/linker.config.json
@@ -0,0 +1,20 @@
+{
+  "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"
+  ]
+}
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
new file mode 100644
index 0000000..b993e4e
--- /dev/null
+++ b/microdroid/signature/Android.bp
@@ -0,0 +1,86 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_defaults {
+    name: "microdroid_signature_default",
+    host_supported: true,
+    srcs: [
+        "microdroid_signature.proto",
+        "signature.cc",
+    ],
+    shared_libs: [
+        "libbase",
+        "liblog",
+    ],
+    export_include_dirs: ["include"],
+}
+
+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: {
+        export_proto_headers: true,
+        type: "lite",
+    },
+    defaults: ["microdroid_signature_default"],
+    apex_available: [
+        "com.android.virt",
+    ],
+}
+
+cc_binary {
+    name: "mk_microdroid_signature",
+    srcs: [
+        "mk_microdroid_signature.cc",
+    ],
+    shared_libs: [
+        "libbase",
+        "liblog",
+    ],
+    static_libs: [
+        "lib_microdroid_signature_proto_lite",
+        "libjsoncpp",
+        "libprotobuf-cpp-lite",
+    ],
+    apex_available: [
+        "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
new file mode 100644
index 0000000..0a39c31
--- /dev/null
+++ b/microdroid/signature/README.md
@@ -0,0 +1,85 @@
+# Microdroid Signature
+
+Microdroid Signature contains the signatures of the payloads so that the payloads are
+verified inside the Guest OS.
+
+* APEX packages that are passed to microdroid should be listed in the Microroid Signature.
+
+## Format
+
+Microdroid Signature is composed of header and body.
+
+| offset | size | description                                                    |
+|--------|------|----------------------------------------------------------------|
+| 0      | 4    | Header. unsigned int32: body length(L) in big endian           |
+| 4      | L    | Body. A protobuf message. [schema](microdroid_signature.proto) |
+
+## How to Create
+
+### `mk_microdroid_signature` and `mk_cdisk`
+
+For testing purpose, use `mk_microdroid_signature` to create a Microdroid Signature.
+
+```
+$ cat signature_config.json
+{
+  "apexes": [
+    {
+      "name": "com.my.hello",
+      "path": "hello.apex"
+    }
+  ]
+}
+$ adb push signature_config.json hello.apex /data/local/tmp/
+$ adb shell 'cd /data/local/tmp; /apex/com.android.virt/bin/mk_microdroid_signature signature_config.json signature
+```
+
+Then, pass the signature as the first partition of the payload disk image.
+
+```
+$ cat payload_cdisk.json
+{
+  "partitions": [
+    {
+      "label": "signature",
+      "path": "signature"
+    },
+    {
+      "label": "com.my.hello",
+      "path": "hello.apex"
+    }
+  ]
+}
+$ adb push payload_cdisk.json /data/local/tmp/
+$ adb shell 'cd /data/local/tmp; /apex/com.android.virt/bin/mk_cdisk payload_cdisk.json payload.img
+$ 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/include/microdroid/signature.h b/microdroid/signature/include/microdroid/signature.h
new file mode 100644
index 0000000..abacd6e
--- /dev/null
+++ b/microdroid/signature/include/microdroid/signature.h
@@ -0,0 +1,34 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+#include <android-base/result.h>
+#include <microdroid_signature.pb.h>
+
+#include <iostream>
+#include <string>
+
+namespace android {
+namespace microdroid {
+
+base::Result<MicrodroidSignature> ReadMicrodroidSignature(const std::string& path);
+
+base::Result<void> WriteMicrodroidSignature(const MicrodroidSignature& signature,
+                                            std::ostream& out);
+
+} // namespace microdroid
+} // namespace android
diff --git a/microdroid/signature/microdroid_signature.proto b/microdroid/signature/microdroid_signature.proto
new file mode 100644
index 0000000..8335ff5
--- /dev/null
+++ b/microdroid/signature/microdroid_signature.proto
@@ -0,0 +1,46 @@
+/*
+ * 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.
+ */
+
+syntax = "proto3";
+
+package android.microdroid;
+
+// Microdroid Signature is the body of the signature partition.
+message MicrodroidSignature {
+  uint32 version = 1;
+
+  // Lists the signature information of the payload apexes.
+  // The payload apexes are mapped to the partitions following the signature partition.
+  repeated ApexSignature apexes = 2;
+}
+
+message ApexSignature {
+  // Required.
+  // The apex name.
+  string name = 1;
+
+  // Required.
+  // The original size of the apex file.
+  uint32 size = 2;
+
+  // Optional.
+  // When specified, the public key used to sign the apex should match with it.
+  string publicKey = 3;
+
+  // Optional.
+  // When specified, the root digest of the apex should match with it.
+  string rootDigest = 4;
+}
diff --git a/microdroid/signature/mk_microdroid_signature.cc b/microdroid/signature/mk_microdroid_signature.cc
new file mode 100644
index 0000000..d5cb1a5
--- /dev/null
+++ b/microdroid/signature/mk_microdroid_signature.cc
@@ -0,0 +1,141 @@
+/*
+ * 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 <string>
+
+#include <android-base/file.h>
+#include <android-base/result.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::MicrodroidSignature;
+using android::microdroid::WriteMicrodroidSignature;
+
+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);
+}
+
+// config JSON schema:
+// {
+//   "apexes": [
+//     {
+//       "name": string,       // the apex name
+//       "path": string,       // the path to the apex file
+//                             // absolute or relative to the config file
+//       "publicKey": string,  // optional
+//       "rootDigest": string, // optional
+//     }
+//   ]
+// }
+
+Result<MicrodroidSignature> LoadConfig(const std::string& config_file) {
+    MicrodroidSignature signature;
+    signature.set_version(1);
+
+    const std::string dirname = Dirname(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;
+    }
+
+    for (const Json::Value& apex : root["apexes"]) {
+        auto apex_signature = signature.add_apexes();
+
+        Json::Value name = apex["name"];
+        Json::Value path = apex["path"];
+        Json::Value publicKey = apex["publicKey"];
+        Json::Value rootDigest = apex["rootDigest"];
+
+        if (name.isString()) {
+            apex_signature->set_name(name.asString());
+        } else {
+            return Error() << "bad config: apexes.name should be a string: " << path;
+        }
+
+        if (path.isString()) {
+            std::string apex_path = path.asString();
+
+            // resolve path with the config_file's dirname if not absolute
+            bool is_absolute = !apex_path.empty() && apex_path[0] == '/';
+            if (!is_absolute) {
+                apex_path = dirname + "/" + apex_path;
+            }
+
+            auto file_size = GetFileSize(apex_path);
+            if (!file_size.ok()) {
+                return Error() << "I/O error: " << file_size.error();
+            }
+            apex_signature->set_size(file_size.value());
+        } else {
+            return Error() << "bad config: apexes.path should be a string: " << path;
+        }
+
+        if (publicKey.isString()) {
+            apex_signature->set_publickey(publicKey.asString());
+        } else if (!publicKey.isNull()) {
+            return Error() << "bad config: apexes.publicKey should be a string or null: "
+                           << publicKey;
+        }
+
+        if (rootDigest.isString()) {
+            apex_signature->set_rootdigest(rootDigest.asString());
+        } else if (!rootDigest.isNull()) {
+            return Error() << "bad config: apexes.rootDigest should be a string or null: "
+                           << rootDigest;
+        }
+    }
+
+    return signature;
+}
+
+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;
+    }
+
+    std::ofstream out(argv[2]);
+    auto result = WriteMicrodroidSignature(*config, out);
+    if (!result.ok()) {
+        std::cerr << result.error() << '\n';
+        return 1;
+    }
+    return 0;
+}
\ 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/microdroid/signature/signature.cc b/microdroid/signature/signature.cc
new file mode 100644
index 0000000..446159e
--- /dev/null
+++ b/microdroid/signature/signature.cc
@@ -0,0 +1,74 @@
+/*
+ * 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 "microdroid/signature.h"
+
+#include <android-base/endian.h>
+#include <android-base/file.h>
+
+using android::base::ErrnoError;
+using android::base::Error;
+using android::base::Result;
+
+namespace android {
+namespace microdroid {
+
+Result<MicrodroidSignature> ReadMicrodroidSignature(const std::string& path) {
+    std::string content;
+    if (!base::ReadFileToString(path, &content)) {
+        return ErrnoError() << "Failed to read " << path;
+    }
+
+    // read length prefix (4-byte, big-endian)
+    uint32_t size;
+    const size_t length_prefix_bytes = sizeof(size);
+    if (content.size() < length_prefix_bytes) {
+        return Error() << "Invalid signature: size == " << content.size();
+    }
+    size = be32toh(*reinterpret_cast<uint32_t*>(content.data()));
+    if (content.size() < length_prefix_bytes + size) {
+        return Error() << "Invalid signature: size(" << size << ") mimatches to the content size("
+                       << content.size() - length_prefix_bytes << ")";
+    }
+    content = content.substr(length_prefix_bytes, size);
+
+    // parse content
+    MicrodroidSignature signature;
+    if (!signature.ParseFromString(content)) {
+        return Error() << "Can't parse MicrodroidSignature from " << path;
+    }
+    return signature;
+}
+
+Result<void> WriteMicrodroidSignature(const MicrodroidSignature& signature, std::ostream& out) {
+    // prepare content
+    std::string content;
+    if (!signature.SerializeToString(&content)) {
+        return Error() << "Failed to write protobuf.";
+    }
+
+    // write length prefix (4-byte, big-endian)
+    uint32_t size = htobe32(static_cast<uint32_t>(content.size()));
+    out.write(reinterpret_cast<const char*>(&size), sizeof(size));
+
+    // write content
+    out << content;
+
+    return {};
+}
+
+} // namespace microdroid
+} // namespace android
\ No newline at end of file
diff --git a/microdroid/uboot-env-x86_64.txt b/microdroid/uboot-env-x86_64.txt
index ab0fc26..ffc0462 100644
--- a/microdroid/uboot-env-x86_64.txt
+++ b/microdroid/uboot-env-x86_64.txt
@@ -1,7 +1,7 @@
 # Static u-boot environment variables for microdroid. See b/180481192
 
 # Boot the device following the Android boot procedure
-bootcmd=boot_android virtio 0#misc
+bootcmd=avb init virtio 0 && avb verify _a && boot_android virtio 0#misc
 
 bootdelay=0
 
diff --git a/microdroid/uboot-env.txt b/microdroid/uboot-env.txt
index b7940e5..0bdc591 100644
--- a/microdroid/uboot-env.txt
+++ b/microdroid/uboot-env.txt
@@ -1,7 +1,7 @@
 # Static u-boot environment variables for microdroid. See b/180481192
 
 # Boot the device following the Android boot procedure
-bootcmd=boot_android virtio 0#misc
+bootcmd=avb init virtio 0 && avb verify _a && boot_android virtio 0#misc
 
 bootdelay=0
 fdtaddr=0x80000000
diff --git a/tests/hostside/java/android/virt/test/MicrodroidTestCase.java b/tests/hostside/java/android/virt/test/MicrodroidTestCase.java
index 57c7b17..aaa0457 100644
--- a/tests/hostside/java/android/virt/test/MicrodroidTestCase.java
+++ b/tests/hostside/java/android/virt/test/MicrodroidTestCase.java
@@ -65,7 +65,7 @@
                         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, and payload.img
         String makeOsCompositeCmd =
                 String.format(
                         "cd %s; %sbin/mk_cdisk %setc/microdroid_cdisk.json os_composite.img",
@@ -76,12 +76,21 @@
                         "cd %s; %sbin/mk_cdisk %setc/microdroid_cdisk_env.json env_composite.img",
                         TEST_ROOT, VIRT_APEX, VIRT_APEX);
         getDevice().executeShellCommand(makeEnvCompositeCmd);
+        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 osCompositeImg = TEST_ROOT + "/os_composite.img";
         final String envCompositeImg = TEST_ROOT + "/env_composite.img";
+        final String payloadCompositeImg = TEST_ROOT + "/payload.img";
         CommandResult result =
-                getDevice().executeShellV2Command("du -b " + compositeImg + " " + envCompositeImg);
+                getDevice().executeShellV2Command(
+                        "du -b " + osCompositeImg + " "
+                                 + envCompositeImg + " "
+                                 + payloadCompositeImg);
         assertThat(result.getExitCode(), is(0));
         assertThat(result.getStdout(), is(not("")));
 
@@ -91,7 +100,7 @@
                 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",
                         TEST_ROOT, VIRT_APEX, TEST_VM_CID);
         executor.execute(
                 () -> {