Merge "Remove the unused 'b' slot"
diff --git a/apex/Android.bp b/apex/Android.bp
index 5b6f0a9..146e4eb 100644
--- a/apex/Android.bp
+++ b/apex/Android.bp
@@ -13,12 +13,13 @@
     key: "com.android.virt.key",
     certificate: ":com.android.virt.certificate",
 
-    // crosvm is enabled for only 64-bit targets on device
+    // crosvm and virtualizationservice are only enabled for 64-bit targets on device
     arch: {
         arm64: {
             binaries: [
                 "authfs", // TODO(victorhsieh): move to microdroid once we can run the test in VM.
                 "crosvm",
+                "virtualizationservice",
             ],
             filesystems: [
                 "microdroid_super",
@@ -32,6 +33,7 @@
             binaries: [
                 "authfs", // TODO(victorhsieh): move to microdroid once we can run the test in VM.
                 "crosvm",
+                "virtualizationservice",
             ],
             filesystems: [
                 "microdroid_super",
@@ -44,7 +46,6 @@
     },
     binaries: [
         "fd_server",
-        "virtualizationservice",
         "vm",
 
         // tools to create composite images
diff --git a/compos/Android.bp b/compos/Android.bp
index fc0517f..1611b68 100644
--- a/compos/Android.bp
+++ b/compos/Android.bp
@@ -55,3 +55,10 @@
         "com.android.compos",
     ],
 }
+
+// TODO(b/190503456) Remove this when vm/virtualizationservice generates payload.img from vm_config
+prebuilt_etc {
+    name: "compos_payload_config",
+    src: "payload_config.json",
+    filename: "payload_config.json",
+}
diff --git a/compos/apex/Android.bp b/compos/apex/Android.bp
index 7ced384..3a8f601 100644
--- a/compos/apex/Android.bp
+++ b/compos/apex/Android.bp
@@ -40,4 +40,12 @@
         "compsvc_worker",
         "pvm_exec",
     ],
+
+    apps: [
+        "CompOSPayloadApp",
+    ],
+
+    prebuilts: [
+        "compos_payload_config",
+    ],
 }
diff --git a/compos/apk/Android.bp b/compos/apk/Android.bp
new file mode 100644
index 0000000..c6192b9
--- /dev/null
+++ b/compos/apk/Android.bp
@@ -0,0 +1,9 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_app {
+    name: "CompOSPayloadApp",
+    sdk_version: "current",
+    apex_available: ["com.android.compos"],
+}
diff --git a/compos/apk/AndroidManifest.xml b/compos/apk/AndroidManifest.xml
new file mode 100644
index 0000000..1e9352b
--- /dev/null
+++ b/compos/apk/AndroidManifest.xml
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 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.
+-->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+      package="com.android.compos.payload">
+    <application android:label="CompOS" />
+</manifest>
diff --git a/compos/apk/assets/vm_config.json b/compos/apk/assets/vm_config.json
new file mode 100644
index 0000000..a8dca71
--- /dev/null
+++ b/compos/apk/assets/vm_config.json
@@ -0,0 +1,34 @@
+{
+  "version": 1,
+  "os": {
+    "name": "microdroid"
+  },
+  "task": {
+    "type": "executable",
+    "command": "/apex/com.android.compos/bin/compsvc",
+    "args": [
+      "--rpc-binder",
+      "/apex/com.android.art/bin/dex2oat64"
+    ]
+  },
+  "apexes": [
+    {
+      "name": "com.android.adbd"
+    },
+    {
+      "name": "com.android.art"
+    },
+    {
+      "name": "com.android.compos"
+    },
+    {
+      "name": "com.android.i18n"
+    },
+    {
+      "name": "com.android.os.statsd"
+    },
+    {
+      "name": "com.android.sdkext"
+    }
+  ]
+}
\ No newline at end of file
diff --git a/compos/payload_config.json b/compos/payload_config.json
new file mode 100644
index 0000000..588ccca
--- /dev/null
+++ b/compos/payload_config.json
@@ -0,0 +1,15 @@
+{
+  "apk": {
+    "path": "/apex/com.android.compos/app/CompOSPayloadApp/CompOSPayloadApp.apk",
+    "name": "com.android.compos.payload"
+  },
+  "system_apexes": [
+    "com.android.adbd",
+    "com.android.art",
+    "com.android.compos",
+    "com.android.i18n",
+    "com.android.os.statsd",
+    "com.android.sdkext"
+  ],
+  "payload_config_path": "/mnt/apk/assets/vm_config.json"
+}
\ No newline at end of file
diff --git a/microdroid/README.md b/microdroid/README.md
index 7084773..aae6e66 100644
--- a/microdroid/README.md
+++ b/microdroid/README.md
@@ -99,7 +99,7 @@
     "com.android.i18n",
     "com.android.os.statsd",
     "com.android.sdkext"
-  ],
+  ]
 }
 ```
 
diff --git a/microdroid/sepolicy/system/private/microdroid_manager.te b/microdroid/sepolicy/system/private/microdroid_manager.te
index f2feca2..deb969c 100644
--- a/microdroid/sepolicy/system/private/microdroid_manager.te
+++ b/microdroid/sepolicy/system/private/microdroid_manager.te
@@ -21,6 +21,12 @@
 # Until then, allow microdroid_manager to execute the shell or other system executables.
 allow microdroid_manager {shell_exec toolbox_exec}:file rx_file_perms;
 
+# Let microdroid_manager kernel-log.
+# TODO(b/189805435) when ready this should be kmsg_device rather than kmsg_debug_device
+userdebug_or_eng(`
+  allow microdroid_manager kmsg_debug_device:chr_file write;
+')
+
 # Let microdroid_manager read a config file from /mnt/apk (fusefs)
 # TODO(b/188400186) remove the below two rules
 userdebug_or_eng(`
diff --git a/microdroid_manager/Android.bp b/microdroid_manager/Android.bp
index cb628b1..30f8481 100644
--- a/microdroid_manager/Android.bp
+++ b/microdroid_manager/Android.bp
@@ -9,7 +9,7 @@
     edition: "2018",
     prefer_rlib: true,
     rustlibs: [
-        "libandroid_logger",
+        "libenv_logger",
         "libanyhow",
         "libkeystore2_system_property-rust",
         "liblog_rust",
diff --git a/microdroid_manager/microdroid_manager.rc b/microdroid_manager/microdroid_manager.rc
index c800002..4f194a3 100644
--- a/microdroid_manager/microdroid_manager.rc
+++ b/microdroid_manager/microdroid_manager.rc
@@ -1,4 +1,7 @@
 service microdroid_manager /system/bin/microdroid_manager
     disabled
+    # TODO(b/189805435) for now redirect stdio to kmsg
+    stdio_to_kmsg
+    setenv RUST_LOG info
     # TODO(jooyung) remove this when microdroid_manager becomes a daemon
     oneshot
\ No newline at end of file
diff --git a/microdroid_manager/src/main.rs b/microdroid_manager/src/main.rs
index b71daa8..10731c5 100644
--- a/microdroid_manager/src/main.rs
+++ b/microdroid_manager/src/main.rs
@@ -17,10 +17,9 @@
 mod ioutil;
 mod metadata;
 
-use android_logger::Config;
 use anyhow::{anyhow, bail, Result};
 use keystore2_system_property::PropertyWatcher;
-use log::{info, Level};
+use log::info;
 use microdroid_payload_config::{Task, TaskType, VmPayloadConfig};
 use std::fs;
 use std::path::Path;
@@ -29,10 +28,9 @@
 
 const WAIT_TIMEOUT: Duration = Duration::from_secs(10);
 
-const LOG_TAG: &str = "MicrodroidManager";
-
 fn main() -> Result<()> {
-    android_logger::init_once(Config::default().with_tag(LOG_TAG).with_min_level(Level::Debug));
+    // TODO(b/189805435) use kernlog
+    env_logger::init();
 
     info!("started.");
 
diff --git a/tests/hostside/java/android/virt/test/MicrodroidTestCase.java b/tests/hostside/java/android/virt/test/MicrodroidTestCase.java
index 907858d..7f9b8de 100644
--- a/tests/hostside/java/android/virt/test/MicrodroidTestCase.java
+++ b/tests/hostside/java/android/virt/test/MicrodroidTestCase.java
@@ -138,7 +138,7 @@
 
     // Run a shell command on Microdroid
     private String runOnMicrodroid(String... cmd) {
-        final long timeout = 3000; // 3 sec. Microdroid is extremely slow on GCE-on-CF.
+        final long timeout = 30000; // 30 sec. Microdroid is extremely slow on GCE-on-CF.
         CommandResult result =
                 RunUtil.getDefault()
                         .runTimedCmd(timeout, "adb", "-s", MICRODROID_SERIAL, "shell", join(cmd));
diff --git a/virtualizationservice/Android.bp b/virtualizationservice/Android.bp
index bad7f46..f5ad1f8 100644
--- a/virtualizationservice/Android.bp
+++ b/virtualizationservice/Android.bp
@@ -7,6 +7,17 @@
     crate_name: "virtualizationservice",
     srcs: ["src/main.rs"],
     edition: "2018",
+    // Only build on targets which crosvm builds on.
+    enabled: false,
+    target: {
+        android64: {
+            compile_multilib: "64",
+            enabled: true,
+        },
+        linux_bionic_arm64: {
+            enabled: true,
+        },
+    },
     prefer_rlib: true,
     rustlibs: [
         "android.system.virtualizationservice-rust",
@@ -14,6 +25,7 @@
         "libanyhow",
         "libcommand_fds",
         "libcompositediskconfig",
+        "libdisk",
         "liblog_rust",
         "libserde_json",
         "libserde",
diff --git a/virtualizationservice/aidl/android/system/virtualizationservice/IVirtualizationService.aidl b/virtualizationservice/aidl/android/system/virtualizationservice/IVirtualizationService.aidl
index 311c2e0..8affaad 100644
--- a/virtualizationservice/aidl/android/system/virtualizationservice/IVirtualizationService.aidl
+++ b/virtualizationservice/aidl/android/system/virtualizationservice/IVirtualizationService.aidl
@@ -27,7 +27,11 @@
     IVirtualMachine startVm(
             in VirtualMachineConfig config, in @nullable ParcelFileDescriptor logFd);
 
-    /** Initialise an empty partition image of the given size to be used as a writable partition. */
+    /**
+     * Initialise an empty partition image of the given size to be used as a writable partition.
+     *
+     * The file must be open with both read and write permissions, and should be a new empty file.
+     */
     void initializeWritablePartition(in ParcelFileDescriptor imageFd, long size);
 
     /**
diff --git a/virtualizationservice/src/aidl.rs b/virtualizationservice/src/aidl.rs
index 7b63917..bc8df9d 100644
--- a/virtualizationservice/src/aidl.rs
+++ b/virtualizationservice/src/aidl.rs
@@ -29,10 +29,10 @@
     self, BinderFeatures, Interface, ParcelFileDescriptor, StatusCode, Strong, ThreadState,
 };
 use command_fds::FdMapping;
+use disk::QcowFile;
 use log::{debug, error, warn};
 use std::convert::TryInto;
 use std::fs::{File, create_dir};
-use std::io::{Seek, SeekFrom, Write};
 use std::os::unix::io::AsRawFd;
 use std::path::{Path, PathBuf};
 use std::sync::{Arc, Mutex, Weak};
@@ -139,26 +139,16 @@
         image_fd: &ParcelFileDescriptor,
         size: i64,
     ) -> binder::Result<()> {
-        let size: u64 = size.try_into().map_err(|e| {
+        let size = size.try_into().map_err(|e| {
             error!("Invalid size {}: {}", size, e);
             StatusCode::BAD_VALUE
         })?;
-        let mut image = clone_file(image_fd)?;
+        let image = clone_file(image_fd)?;
 
-        // TODO: create a QCOW2 image instead, like `crosvm create_qcow2`, once `mk_cdisk` supports
-        // it (b/189211641).
-        if size > 0 {
-            // Extend the file to the given size by seeking to the size we want and writing a single
-            // 0 byte there.
-            image.seek(SeekFrom::Start(size - 1)).map_err(|e| {
-                error!("Failed to seek to desired size of image file ({}): {}.", size, e);
-                StatusCode::UNKNOWN_ERROR
-            })?;
-            image.write_all(&[0]).map_err(|e| {
-                error!("Failed to write 0 to image file: {}.", e);
-                StatusCode::UNKNOWN_ERROR
-            })?;
-        }
+        QcowFile::new(image, size).map_err(|e| {
+            error!("Failed to create QCOW2 image: {}", e);
+            StatusCode::UNKNOWN_ERROR
+        })?;
 
         Ok(())
     }
diff --git a/vm/src/main.rs b/vm/src/main.rs
index e2c11a8..2c93ec4 100644
--- a/vm/src/main.rs
+++ b/vm/src/main.rs
@@ -104,6 +104,7 @@
 ) -> Result<(), Error> {
     let image = OpenOptions::new()
         .create_new(true)
+        .read(true)
         .write(true)
         .open(image_path)
         .with_context(|| format!("Failed to create {:?}", image_path))?;