Merge "Detect Microdroid hangup during boot"
diff --git a/apex/Android.bp b/apex/Android.bp
index 4698088..923c378 100644
--- a/apex/Android.bp
+++ b/apex/Android.bp
@@ -3,12 +3,16 @@
 }
 
 microdroid_filesystem_images = [
-    "microdroid_super",
     "microdroid_boot",
+    "microdroid_bootconfig_app_debuggable",
+    "microdroid_bootconfig_full_debuggable",
+    "microdroid_bootconfig_normal",
     "microdroid_init_boot",
-    "microdroid_vendor_boot",
+    "microdroid_super",
+    "microdroid_uboot_env",
     "microdroid_vbmeta",
     "microdroid_vbmeta_bootconfig",
+    "microdroid_vendor_boot",
 ]
 
 apex {
@@ -60,12 +64,8 @@
     prebuilts: [
         "com.android.virt.init.rc",
         "microdroid.json",
-        "microdroid_uboot_env",
         "microdroid_bootloader",
         "microdroid_bootloader.avbpubkey",
-        "microdroid_bootconfig_normal",
-        "microdroid_bootconfig_app_debuggable",
-        "microdroid_bootconfig_full_debuggable",
     ],
     file_contexts: ":com.android.virt-file_contexts",
     canned_fs_config: "canned_fs_config",
diff --git a/apex/sign_virt_apex.py b/apex/sign_virt_apex.py
index e314b71..df95323 100644
--- a/apex/sign_virt_apex.py
+++ b/apex/sign_virt_apex.py
@@ -360,17 +360,17 @@
 # dict of (key, file) for re-sign/verification. keys are un-versioned for readability.
 virt_apex_files = {
     'bootloader.pubkey': 'etc/microdroid_bootloader.avbpubkey',
-    'bootloader': 'etc/microdroid_bootloader',
+    'bootloader': 'etc/fs/microdroid_bootloader',
     'boot.img': 'etc/fs/microdroid_boot.img',
     'vendor_boot.img': 'etc/fs/microdroid_vendor_boot.img',
     'init_boot.img': 'etc/fs/microdroid_init_boot.img',
     'super.img': 'etc/fs/microdroid_super.img',
     'vbmeta.img': 'etc/fs/microdroid_vbmeta.img',
     'vbmeta_bootconfig.img': 'etc/fs/microdroid_vbmeta_bootconfig.img',
-    'bootconfig.normal': 'etc/microdroid_bootconfig.normal',
-    'bootconfig.app_debuggable': 'etc/microdroid_bootconfig.app_debuggable',
-    'bootconfig.full_debuggable': 'etc/microdroid_bootconfig.full_debuggable',
-    'uboot_env.img': 'etc/uboot_env.img'
+    'bootconfig.normal': 'etc/fs/microdroid_bootconfig.normal',
+    'bootconfig.app_debuggable': 'etc/fs/microdroid_bootconfig.app_debuggable',
+    'bootconfig.full_debuggable': 'etc/fs/microdroid_bootconfig.full_debuggable',
+    'uboot_env.img': 'etc/fs/uboot_env.img'
 }
 
 
diff --git a/microdroid/Android.bp b/microdroid/Android.bp
index c6ea28d..ba3da08 100644
--- a/microdroid/Android.bp
+++ b/microdroid/Android.bp
@@ -389,84 +389,34 @@
     ],
 }
 
-// See external/avb/avbtool.py
-// MAX_VBMETA_SIZE=64KB, MAX_FOOTER_SIZE=4KB
-avb_hash_footer_kb = "68"
-
-prebuilt_etc {
-    name: "microdroid_bootconfig_normal",
-    src: ":microdroid_bootconfig_normal_gen",
-    filename: "microdroid_bootconfig.normal",
-}
-
-prebuilt_etc {
-    name: "microdroid_bootconfig_app_debuggable",
-    src: ":microdroid_bootconfig_app_debuggable_gen",
-    filename: "microdroid_bootconfig.app_debuggable",
-}
-
-prebuilt_etc {
-    name: "microdroid_bootconfig_full_debuggable",
-    src: ":microdroid_bootconfig_full_debuggable_gen",
-    filename: "microdroid_bootconfig.full_debuggable",
-}
-
 // python -c "import hashlib; print(hashlib.sha256(b'bootconfig').hexdigest())"
 bootconfig_salt = "e158851fbebb402e1f18ea9372ea2f76b4dea23eceb5c4b92e5b27ade8537f5b"
 
-// TODO(jiyong): make a new module type that does the avb signing
-genrule {
-    name: "microdroid_bootconfig_normal_gen",
-    tools: ["avbtool"],
-    srcs: [
-        "bootconfig.normal",
-        ":microdroid_sign_key",
-    ],
-    out: ["microdroid_bootconfig.normal"],
-    cmd: "cp $(location bootconfig.normal) $(out) && " +
-        "$(location avbtool) add_hash_footer " +
-        "--algorithm SHA256_RSA4096 " +
-        "--salt " + bootconfig_salt + " " +
-        "--partition_name bootconfig " +
-        "--key $(location :microdroid_sign_key) " +
-        "--partition_size $$(( " + avb_hash_footer_kb + " * 1024 + ( $$(stat --format=%s $(out)) + 4096 - 1 ) / 4096 * 4096 )) " +
-        "--image $(out)",
+avb_add_hash_footer {
+    name: "microdroid_bootconfig_normal",
+    src: "bootconfig.normal",
+    filename: "microdroid_bootconfig.normal",
+    partition_name: "bootconfig",
+    private_key: ":microdroid_sign_key",
+    salt: bootconfig_salt,
 }
 
-genrule {
-    name: "microdroid_bootconfig_app_debuggable_gen",
-    tools: ["avbtool"],
-    srcs: [
-        "bootconfig.app_debuggable",
-        ":microdroid_sign_key",
-    ],
-    out: ["microdroid_bootconfig.app_debuggable"],
-    cmd: "cp $(location bootconfig.app_debuggable) $(out) && " +
-        "$(location avbtool) add_hash_footer " +
-        "--algorithm SHA256_RSA4096 " +
-        "--salt " + bootconfig_salt + " " +
-        "--partition_name bootconfig " +
-        "--key $(location :microdroid_sign_key) " +
-        "--partition_size $$(( " + avb_hash_footer_kb + " * 1024 + ( $$(stat --format=%s $(out)) + 4096 - 1 ) / 4096 * 4096 )) " +
-        "--image $(out)",
+avb_add_hash_footer {
+    name: "microdroid_bootconfig_app_debuggable",
+    src: "bootconfig.app_debuggable",
+    filename: "microdroid_bootconfig.app_debuggable",
+    partition_name: "bootconfig",
+    private_key: ":microdroid_sign_key",
+    salt: bootconfig_salt,
 }
 
-genrule {
-    name: "microdroid_bootconfig_full_debuggable_gen",
-    tools: ["avbtool"],
-    srcs: [
-        "bootconfig.full_debuggable",
-        ":microdroid_sign_key",
-    ],
-    out: ["microdroid_bootconfig.full_debuggable"],
-    cmd: "cp $(location bootconfig.full_debuggable) $(out) && " +
-        "$(location avbtool) add_hash_footer " +
-        "--algorithm SHA256_RSA4096 " +
-        "--salt " + bootconfig_salt + " " +
-        "--partition_name bootconfig " +
-        "--key $(location :microdroid_sign_key) " +
-        "--partition_size $$(( " + avb_hash_footer_kb + " * 1024 + ( $$(stat --format=%s $(out)) + 4096 - 1 ) / 4096 * 4096 )) " +
-        "--image $(out)",
+avb_add_hash_footer {
+    name: "microdroid_bootconfig_full_debuggable",
+    src: "bootconfig.full_debuggable",
+    filename: "microdroid_bootconfig.full_debuggable",
+    partition_name: "bootconfig",
+    private_key: ":microdroid_sign_key",
+    salt: bootconfig_salt,
 }
 
 prebuilt_etc {
@@ -478,7 +428,7 @@
 
 prebuilt_etc {
     name: "microdroid_bootloader",
-    src: ":microdroid_bootloader_gen",
+    src: ":microdroid_bootloader_signed",
     arch: {
         x86_64: {
             // For unknown reason, the signed bootloader doesn't work on x86_64. Until the problem
@@ -487,36 +437,20 @@
             src: ":microdroid_bootloader_pubkey_replaced",
         },
     },
+    relative_install_path: "fs",
     filename: "microdroid_bootloader",
 }
 
 // python -c "import hashlib; print(hashlib.sha256(b'bootloader').hexdigest())"
 bootloader_salt = "3b4a12881d11f33cff968a24d7c53723a8232cde9a8d91e29fdbd6a95ae6adf0"
 
-genrule {
-    name: "microdroid_bootloader_gen",
-    tools: ["avbtool"],
-    srcs: [
-        ":microdroid_bootloader_pubkey_replaced",
-        ":microdroid_sign_key",
-    ],
-    out: ["bootloader-signed"],
-    // 1. Copy the input to the output becaise avbtool modifies --image in
-    // place.
-    // 2. Check if the file is big enough. For arm and x86 we have fake
-    // bootloader file whose size is 1. It can't pass avbtool.
-    // 3. Add the hash footer. The partition size is set to (image size + 68KB)
-    // rounded up to 4KB boundary.
-    cmd: "cp $(location :microdroid_bootloader_pubkey_replaced) $(out) && " +
-        "if [ $$(stat --format=%s $(out)) -gt 4096 ]; then " +
-        "$(location avbtool) add_hash_footer " +
-        "--algorithm SHA256_RSA4096 " +
-        "--salt " + bootloader_salt + " " +
-        "--partition_name bootloader " +
-        "--key $(location :microdroid_sign_key) " +
-        "--partition_size $$(( " + avb_hash_footer_kb + " * 1024 + ( $$(stat --format=%s $(out)) + 4096 - 1 ) / 4096 * 4096 )) " +
-        "--image $(out)" +
-        "; fi",
+avb_add_hash_footer {
+    name: "microdroid_bootloader_signed",
+    src: ":microdroid_bootloader_pubkey_replaced",
+    filename: "microdroid_bootloader",
+    partition_name: "bootloader",
+    private_key: ":microdroid_sign_key",
+    salt: bootloader_salt,
 }
 
 // Replace avbpubkey of prebuilt bootloader with the avbpubkey of the signing key
@@ -530,15 +464,11 @@
     ],
     out: ["bootloader-pubkey-replaced"],
     // 1. Copy the input to the output (replace_bytes modifies the file in-place)
-    // 2. Check if the file is big enough. For arm and x86 we have fake
-    // bootloader file whose size is 1. (replace_bytes fails if key not found)
-    // 3. Replace embedded pubkey with new one.
+    // 2. Replace embedded pubkey with new one.
     cmd: "cp $(location :microdroid_crosvm_bootloader) $(out) && " +
-        "if [ $$(stat --format=%s $(out)) -gt 4096 ]; then " +
         "$(location replace_bytes) $(out) " +
         "$(location :microdroid_crosvm_bootloader.avbpubkey) " +
-        "$(location :microdroid_bootloader_avbpubkey_gen)" +
-        "; fi",
+        "$(location :microdroid_bootloader_avbpubkey_gen)",
 }
 
 // Apex keeps a copy of avbpubkey embedded in bootloader so that embedded avbpubkey can be replaced
@@ -559,34 +489,24 @@
         "--output $(out)",
 }
 
-prebuilt_etc {
-    name: "microdroid_uboot_env",
-    src: ":microdroid_uboot_env_gen",
-    filename: "uboot_env.img",
-}
-
 // python -c "import hashlib; print(hashlib.sha256(b'uboot_env').hexdigest())"
 uboot_env_salt = "cbf2d76827ece5ca8d176a40c94ac6355edcf6511b4b887364a8c0e05850df10"
 
+avb_add_hash_footer {
+    name: "microdroid_uboot_env",
+    src: ":microdroid_uboot_env_gen",
+    filename: "uboot_env.img",
+    partition_name: "uboot_env",
+    private_key: ":microdroid_sign_key",
+    salt: uboot_env_salt,
+}
+
 genrule {
     name: "microdroid_uboot_env_gen",
-    tools: [
-        "mkenvimage_slim",
-        "avbtool",
-    ],
-    srcs: [
-        "uboot-env.txt",
-        ":microdroid_sign_key",
-    ],
+    tools: ["mkenvimage_slim"],
+    srcs: ["uboot-env.txt"],
     out: ["output.img"],
-    cmd: "$(location mkenvimage_slim) -output_path $(out) -input_path $(location uboot-env.txt) && " +
-        "$(location avbtool) add_hash_footer " +
-        "--algorithm SHA256_RSA4096 " +
-        "--salt " + uboot_env_salt + " " +
-        "--partition_name uboot_env " +
-        "--key $(location :microdroid_sign_key) " +
-        "--partition_size $$(( " + avb_hash_footer_kb + " * 1024 + ( $$(stat --format=%s $(out)) + 4096 - 1 ) / 4096 * 4096 )) " +
-        "--image $(out)",
+    cmd: "$(location mkenvimage_slim) -output_path $(out) -input_path $(location uboot-env.txt)",
 }
 
 // Note that keys can be different for filesystem images even though we're using the same key
diff --git a/microdroid/README.md b/microdroid/README.md
index 681c23a..6e5d709 100644
--- a/microdroid/README.md
+++ b/microdroid/README.md
@@ -162,6 +162,8 @@
 ## ADB
 
 On userdebug builds, you can have an adb connection to microdroid. To do so,
+first, add the `--debug=full` flag to the `/apex/com.android.virt/bin/vm
+run-app` command, and then
 
 ```sh
 adb forward tcp:8000 vsock:$CID:5555
diff --git a/microdroid/microdroid.json b/microdroid/microdroid.json
index bf8d93e..f02dcbf 100644
--- a/microdroid/microdroid.json
+++ b/microdroid/microdroid.json
@@ -1,5 +1,5 @@
 {
-  "bootloader": "/apex/com.android.virt/etc/microdroid_bootloader",
+  "bootloader": "/apex/com.android.virt/etc/fs/microdroid_bootloader",
   "disks": [
     {
       "partitions": [
@@ -30,7 +30,7 @@
       "partitions": [
         {
           "label": "uboot_env",
-          "path": "/apex/com.android.virt/etc/uboot_env.img",
+          "path": "/apex/com.android.virt/etc/fs/uboot_env.img",
           "writable": false
         }
       ],
diff --git a/microdroid_manager/Android.bp b/microdroid_manager/Android.bp
index 8343691..d1afc14 100644
--- a/microdroid_manager/Android.bp
+++ b/microdroid_manager/Android.bp
@@ -34,6 +34,7 @@
         "libopenssl",
         "libprotobuf",
         "librustutils",
+        "libscopeguard",
         "libserde",
         "libserde_cbor",
         "libserde_json",
diff --git a/microdroid_manager/src/main.rs b/microdroid_manager/src/main.rs
index 998b94b..15d6663 100644
--- a/microdroid_manager/src/main.rs
+++ b/microdroid_manager/src/main.rs
@@ -155,17 +155,21 @@
     }
 }
 
-fn main() {
-    if let Err(e) = try_main() {
-        error!("Failed with {:?}. Shutting down...", e);
-        if let Err(e) = write_death_reason_to_serial(&e) {
-            error!("Failed to write death reason {:?}", e);
-        }
+fn main() -> Result<()> {
+    scopeguard::defer! {
+        info!("Shutting down...");
         if let Err(e) = system_properties::write("sys.powerctl", "shutdown") {
             error!("failed to shutdown {:?}", e);
         }
-        std::process::exit(1);
     }
+
+    try_main().map_err(|e| {
+        error!("Failed with {:?}.", e);
+        if let Err(e) = write_death_reason_to_serial(&e) {
+            error!("Failed to write death reason {:?}", e);
+        }
+        e
+    })
 }
 
 fn try_main() -> Result<()> {
diff --git a/tests/hostside/java/android/virt/test/MicrodroidTestCase.java b/tests/hostside/java/android/virt/test/MicrodroidTestCase.java
index ec2afaa..bb27913 100644
--- a/tests/hostside/java/android/virt/test/MicrodroidTestCase.java
+++ b/tests/hostside/java/android/virt/test/MicrodroidTestCase.java
@@ -254,7 +254,7 @@
 
         // Add partitions to the second disk
         final String vbmetaPath = TEST_ROOT + "etc/fs/microdroid_vbmeta_bootconfig.img";
-        final String bootconfigPath = TEST_ROOT + "etc/microdroid_bootconfig.full_debuggable";
+        final String bootconfigPath = TEST_ROOT + "etc/fs/microdroid_bootconfig.full_debuggable";
         disks.getJSONObject(1).getJSONArray("partitions")
                 .put(newPartition("vbmeta", vbmetaPath))
                 .put(newPartition("bootconfig", bootconfigPath))
diff --git a/virtualizationservice/src/payload.rs b/virtualizationservice/src/payload.rs
index 7b8cb7f..8378df3 100644
--- a/virtualizationservice/src/payload.rs
+++ b/virtualizationservice/src/payload.rs
@@ -365,7 +365,7 @@
         )?),
         writable: false,
     });
-    let bootconfig_image = "/apex/com.android.virt/etc/microdroid_bootconfig.".to_owned()
+    let bootconfig_image = "/apex/com.android.virt/etc/fs/microdroid_bootconfig.".to_owned()
         + match config.debugLevel {
             DebugLevel::NONE => "normal",
             DebugLevel::APP_ONLY => "app_debuggable",