Merge "Allow VM memory to be specified in app config."
diff --git a/compos/Android.bp b/compos/Android.bp
index 2c864e7..ec3f67f 100644
--- a/compos/Android.bp
+++ b/compos/Android.bp
@@ -58,7 +58,6 @@
         "liblog_rust",
         "libminijail_rust",
         "libnix",
-        "libscopeguard",
     ],
     prefer_rlib: true,
     apex_available: [
diff --git a/compos/apex/Android.bp b/compos/apex/Android.bp
index 7638c41..061c362 100644
--- a/compos/apex/Android.bp
+++ b/compos/apex/Android.bp
@@ -31,6 +31,7 @@
     manifest: "manifest.json",
     file_contexts: ":com.android.compos-file_contexts",
     key: "com.android.compos.key",
+    certificate: ":com.android.compos.certificate",
 
     // TODO(victorhsieh): make it updatable
     updatable: false,
diff --git a/compos/apk/AndroidManifest.xml b/compos/apk/AndroidManifest.xml
index 1e9352b..2f8cbcf 100644
--- a/compos/apk/AndroidManifest.xml
+++ b/compos/apk/AndroidManifest.xml
@@ -14,5 +14,5 @@
 -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
       package="com.android.compos.payload">
-    <application android:label="CompOS" />
+    <application android:label="CompOS" android:hasCode="false"/>
 </manifest>
diff --git a/compos/src/authfs.rs b/compos/src/authfs.rs
new file mode 100644
index 0000000..ce9aaf8
--- /dev/null
+++ b/compos/src/authfs.rs
@@ -0,0 +1,144 @@
+/*
+ * 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.
+ */
+
+use anyhow::{bail, Context, Result};
+use log::warn;
+use minijail::Minijail;
+use nix::sys::statfs::{statfs, FsType};
+use std::fs::{File, OpenOptions};
+use std::path::Path;
+use std::thread::sleep;
+use std::time::{Duration, Instant};
+
+const AUTHFS_BIN: &str = "/system/bin/authfs";
+const AUTHFS_SETUP_POLL_INTERVAL_MS: Duration = Duration::from_millis(50);
+const AUTHFS_SETUP_TIMEOUT_SEC: Duration = Duration::from_secs(10);
+const FUSE_SUPER_MAGIC: FsType = FsType(0x65735546);
+
+/// The number that hints the future file descriptor. These are not really file descriptor, but
+/// represents the file descriptor number to pass to the task.
+pub type PseudoRawFd = i32;
+
+/// Annotation of input file descriptor.
+#[derive(Debug)]
+pub struct InFdAnnotation {
+    /// A number/file descriptor that is supposed to represent a remote file.
+    pub fd: PseudoRawFd,
+
+    /// The file size of the remote file. Remote input files are supposed to be immutable and
+    /// to be verified with fs-verity by authfs.
+    pub file_size: u64,
+}
+
+/// Annotation of output file descriptor.
+#[derive(Debug)]
+pub struct OutFdAnnotation {
+    /// A number/file descriptor that is supposed to represent a remote file.
+    pub fd: PseudoRawFd,
+}
+
+/// An `AuthFs` instance is supposed to be backed by the `authfs` process. When the lifetime of the
+/// instance is over, the process is terminated and the FUSE is unmounted.
+pub struct AuthFs {
+    mountpoint: String,
+    jail: Minijail,
+}
+
+impl AuthFs {
+    /// Mount an authfs at `mountpoint` with specified FD annotations.
+    pub fn mount_and_wait(
+        mountpoint: &str,
+        in_fds: &[InFdAnnotation],
+        out_fds: &[OutFdAnnotation],
+        debuggable: bool,
+    ) -> Result<AuthFs> {
+        let jail = jail_authfs(mountpoint, in_fds, out_fds, debuggable)?;
+        wait_until_authfs_ready(mountpoint)?;
+        Ok(AuthFs { mountpoint: mountpoint.to_string(), jail })
+    }
+
+    /// Open a file at authfs' root directory.
+    pub fn open_file(&self, basename: PseudoRawFd, writable: bool) -> Result<File> {
+        OpenOptions::new()
+            .read(true)
+            .write(writable)
+            .open(format!("{}/{}", self.mountpoint, basename))
+            .with_context(|| format!("open authfs file {}", basename))
+    }
+}
+
+impl Drop for AuthFs {
+    fn drop(&mut self) {
+        if let Err(e) = self.jail.kill() {
+            if !matches!(e, minijail::Error::Killed(_)) {
+                warn!("Failed to kill authfs: {}", e);
+            }
+        }
+    }
+}
+
+fn jail_authfs(
+    mountpoint: &str,
+    in_fds: &[InFdAnnotation],
+    out_fds: &[OutFdAnnotation],
+    debuggable: bool,
+) -> Result<Minijail> {
+    // TODO(b/185175567): Run in a more restricted sandbox.
+    let jail = Minijail::new()?;
+
+    let mut args = vec![
+        AUTHFS_BIN.to_string(),
+        mountpoint.to_string(),
+        "--cid=2".to_string(), // Always use host unless we need to support other cases
+    ];
+    for conf in in_fds {
+        // TODO(b/185178698): Many input files need to be signed and verified.
+        // or can we use debug cert for now, which is better than nothing?
+        args.push("--remote-ro-file-unverified".to_string());
+        args.push(format!("{}:{}:{}", conf.fd, conf.fd, conf.file_size));
+    }
+    for conf in out_fds {
+        args.push("--remote-new-rw-file".to_string());
+        args.push(format!("{}:{}", conf.fd, conf.fd));
+    }
+
+    let preserve_fds = if debuggable {
+        vec![1, 2] // inherit/redirect stdout/stderr for debugging
+    } else {
+        vec![]
+    };
+
+    let _pid = jail.run(Path::new(AUTHFS_BIN), &preserve_fds, &args)?;
+    Ok(jail)
+}
+
+fn wait_until_authfs_ready(mountpoint: &str) -> Result<()> {
+    let start_time = Instant::now();
+    loop {
+        if is_fuse(mountpoint)? {
+            break;
+        }
+        if start_time.elapsed() > AUTHFS_SETUP_TIMEOUT_SEC {
+            bail!("Time out mounting authfs");
+        }
+        sleep(AUTHFS_SETUP_POLL_INTERVAL_MS);
+    }
+    Ok(())
+}
+
+fn is_fuse(path: &str) -> Result<bool> {
+    Ok(statfs(path)?.filesystem_type() == FUSE_SUPER_MAGIC)
+}
diff --git a/compos/src/compsvc_worker.rs b/compos/src/compsvc_worker.rs
index 0456d58..f33659e 100644
--- a/compos/src/compsvc_worker.rs
+++ b/compos/src/compsvc_worker.rs
@@ -18,94 +18,29 @@
 //! responsible for setting up the execution environment, e.g. to create file descriptors for
 //! remote file access via an authfs mount.
 
+mod authfs;
+
 use anyhow::{bail, Result};
-use log::warn;
 use minijail::Minijail;
-use nix::sys::statfs::{statfs, FsType};
-use std::fs::{File, OpenOptions};
-use std::io;
+use std::fs::File;
 use std::os::unix::io::AsRawFd;
 use std::path::Path;
 use std::process::exit;
-use std::thread::sleep;
-use std::time::{Duration, Instant};
 
-const AUTHFS_BIN: &str = "/system/bin/authfs";
-const AUTHFS_SETUP_POLL_INTERVAL_MS: Duration = Duration::from_millis(50);
-const AUTHFS_SETUP_TIMEOUT_SEC: Duration = Duration::from_secs(10);
-const FUSE_SUPER_MAGIC: FsType = FsType(0x65735546);
+use crate::authfs::{AuthFs, InFdAnnotation, OutFdAnnotation, PseudoRawFd};
 
-/// The number that hints the future file descriptor. These are not really file descriptor, but
-/// represents the file descriptor number to pass to the task.
-type PseudoRawFd = i32;
-
-fn is_fuse(path: &str) -> Result<bool> {
-    Ok(statfs(path)?.filesystem_type() == FUSE_SUPER_MAGIC)
-}
-
-fn spawn_authfs(config: &Config) -> Result<Minijail> {
-    // TODO(b/185175567): Run in a more restricted sandbox.
-    let jail = Minijail::new()?;
-
-    let mut args = vec![
-        AUTHFS_BIN.to_string(),
-        config.authfs_root.clone(),
-        "--cid=2".to_string(), // Always use host unless we need to support other cases
-    ];
-    for conf in &config.in_fds {
-        // TODO(b/185178698): Many input files need to be signed and verified.
-        // or can we use debug cert for now, which is better than nothing?
-        args.push("--remote-ro-file-unverified".to_string());
-        args.push(format!("{}:{}:{}", conf.fd, conf.fd, conf.file_size));
-    }
-    for conf in &config.out_fds {
-        args.push("--remote-new-rw-file".to_string());
-        args.push(format!("{}:{}", conf.fd, conf.fd));
-    }
-
-    let preserve_fds = if config.debuggable {
-        vec![1, 2] // inherit/redirect stdout/stderr for debugging
-    } else {
-        vec![]
-    };
-
-    let _pid = jail.run(Path::new(AUTHFS_BIN), &preserve_fds, &args)?;
-    Ok(jail)
-}
-
-fn wait_until_authfs_ready(authfs_root: &str) -> Result<()> {
-    let start_time = Instant::now();
-    loop {
-        if is_fuse(authfs_root)? {
-            break;
-        }
-        if start_time.elapsed() > AUTHFS_SETUP_TIMEOUT_SEC {
-            bail!("Time out mounting authfs");
-        }
-        sleep(AUTHFS_SETUP_POLL_INTERVAL_MS);
-    }
-    Ok(())
-}
-
-fn open_authfs_file(authfs_root: &str, basename: PseudoRawFd, writable: bool) -> io::Result<File> {
-    OpenOptions::new().read(true).write(writable).open(format!("{}/{}", authfs_root, basename))
-}
-
-fn open_authfs_files_for_mapping(config: &Config) -> io::Result<Vec<(File, PseudoRawFd)>> {
+fn open_authfs_files_for_mapping(
+    authfs: &AuthFs,
+    config: &Config,
+) -> Result<Vec<(File, PseudoRawFd)>> {
     let mut fd_mapping = Vec::with_capacity(config.in_fds.len() + config.out_fds.len());
 
-    let results: io::Result<Vec<_>> = config
-        .in_fds
-        .iter()
-        .map(|conf| Ok((open_authfs_file(&config.authfs_root, conf.fd, false)?, conf.fd)))
-        .collect();
+    let results: Result<Vec<_>> =
+        config.in_fds.iter().map(|conf| Ok((authfs.open_file(conf.fd, false)?, conf.fd))).collect();
     fd_mapping.append(&mut results?);
 
-    let results: io::Result<Vec<_>> = config
-        .out_fds
-        .iter()
-        .map(|conf| Ok((open_authfs_file(&config.authfs_root, conf.fd, true)?, conf.fd)))
-        .collect();
+    let results: Result<Vec<_>> =
+        config.out_fds.iter().map(|conf| Ok((authfs.open_file(conf.fd, true)?, conf.fd))).collect();
     fd_mapping.append(&mut results?);
 
     Ok(fd_mapping)
@@ -125,15 +60,6 @@
     Ok(jail)
 }
 
-struct InFdAnnotation {
-    fd: PseudoRawFd,
-    file_size: u64,
-}
-
-struct OutFdAnnotation {
-    fd: PseudoRawFd,
-}
-
 struct Config {
     authfs_root: String,
     in_fds: Vec<InFdAnnotation>,
@@ -209,23 +135,19 @@
 
     let config = parse_args()?;
 
-    let authfs_jail = spawn_authfs(&config)?;
-    let authfs_lifetime = scopeguard::guard(authfs_jail, |authfs_jail| {
-        if let Err(e) = authfs_jail.kill() {
-            if !matches!(e, minijail::Error::Killed(_)) {
-                warn!("Failed to kill authfs: {}", e);
-            }
-        }
-    });
-
-    wait_until_authfs_ready(&config.authfs_root)?;
-    let fd_mapping = open_authfs_files_for_mapping(&config)?;
+    let authfs = AuthFs::mount_and_wait(
+        &config.authfs_root,
+        &config.in_fds,
+        &config.out_fds,
+        config.debuggable,
+    )?;
+    let fd_mapping = open_authfs_files_for_mapping(&authfs, &config)?;
 
     let jail = spawn_jailed_task(&config, fd_mapping)?;
     let jail_result = jail.wait();
 
     // Be explicit about the lifetime, which should last at least until the task is finished.
-    drop(authfs_lifetime);
+    drop(authfs);
 
     match jail_result {
         Ok(_) => Ok(()),
diff --git a/demo/README.md b/demo/README.md
index 8d0550a..113a14e 100644
--- a/demo/README.md
+++ b/demo/README.md
@@ -10,19 +10,12 @@
 
 ```
 adb install out/dist/MicrodroidDemoApp.apk
-adb push out/dist/MicrodroidDemoApp.apk.idsig /data/local/tmp/virt
+adb shell mkdir /data/local/tmp/virt
+adb push out/dist/MicrodroidDemoApp.apk.idsig /data/local/tmp/virt/
 ```
 
 ## Running
 
-Run these commands before running the app. Eventually, these won't be needed.
-
-```
-adb root
-adb setenforce 0
-adb start virtualizationservice
-```
-
 Run the app by touching the icon on the launcher. Press the `run` button to
 start a VM. You can see console output from the VM on the screen. You can stop
 the VM by pressing the `stop` button.
diff --git a/microdroid/README.md b/microdroid/README.md
index 96a2ef9..0578921 100644
--- a/microdroid/README.md
+++ b/microdroid/README.md
@@ -78,8 +78,9 @@
 ```
 
 The value of `task.command` should match with the name of the shared library
-defined above. If your app rquires APEXes to be imported, you can declare the list
-in `apexes` key like following.
+defined above. If your app rquires APEXes to be imported, you can declare the
+list in `apexes` key like following.
+
 ```json
 {
   "os": ...,
@@ -102,13 +103,13 @@
 }
 
 // The VM configuration file can be embedded by simply placing it at `./assets`
-directory.
+// directory.
 ```
 
 Finally, you build and sign the APK.
 
 ```sh
-TARGET_BUILD_APPS=MyApp m dist
+TARGET_BUILD_APPS=MyApp m apps_only dist
 m apksigner
 apksigner sign --ks path_to_keystore out/dist/MyApp.apk
 ```
@@ -147,7 +148,8 @@
 
 ```sh
 TEST_ROOT=/data/local/tmp/virt
-adb push out/dist/MyApp.apk.idsig $TEST_ROOT
+adb shell mkdir $TEST_ROOT
+adb push out/dist/MyApp.apk.idsig $TEST_ROOT/
 ```
 
 Execute the following commands to launch a VM. The VM will boot to microdroid
@@ -156,16 +158,18 @@
 
 ```sh
 TEST_ROOT=/data/local/tmp/virt
-adb root
-adb shell setenforce 0
-adb shell /apex/com.android.virt/bin/vm run-app --daemonize --log $TEST_ROOT/log.txt PATH_TO_YOUR_APP $TEST_ROOT/MyApp.apk.idsig assets/VM_CONFIG_FILE
+adb shell /apex/com.android.virt/bin/vm run-app \
+--log $TEST_ROOT/log.txt \
+PATH_TO_YOUR_APP \
+$TEST_ROOT/MyApp.apk.idsig \
+$TEST_ROOT/instance.img \
+assets/VM_CONFIG_FILE
 ```
 
 The last command lets you know the CID assigned to the VM. The console output
-from the VM is stored to `$TEST_ROOT/log.txt` file for debugging purpose.
-
-Note: the disabling of SELinux is a temporary step. The restriction will
-eventually be removed.
+from the VM is stored to `$TEST_ROOT/log.txt` file for debugging purpose. If you
+omit the `--log $TEST_ROOT/log.txt` option, it will be emitted to the current
+console.
 
 Stopping the VM can be done as follows:
 
@@ -174,7 +178,8 @@
 ```
 
 , where `CID` is the reported CID value. This works only when the `vm` was
-invoked with the `--daemonize` flag.
+invoked with the `--daemonize` flag. If the flag was not used, press Ctrl+C on
+the console where the `vm run-app` command was invoked.
 
 ## ADB
 
diff --git a/tests/hostside/helper/java/android/virt/test/VirtualizationTestCaseBase.java b/tests/hostside/helper/java/android/virt/test/VirtualizationTestCaseBase.java
index 40debba..a9e5040 100644
--- a/tests/hostside/helper/java/android/virt/test/VirtualizationTestCaseBase.java
+++ b/tests/hostside/helper/java/android/virt/test/VirtualizationTestCaseBase.java
@@ -70,6 +70,14 @@
         // disconnect from microdroid
         tryRunOnHost("adb", "disconnect", MICRODROID_SERIAL);
 
+        // Make sure we're connected to the host adb again (b/194219111)
+        for (int retry = 0; retry < 3; ++retry) {
+            if (android.tryRun("true") != null) {
+                break;
+            }
+            androidDevice.waitForDeviceOnline(1000);
+        }
+
         // kill stale VMs and directories
         android.tryRun("killall", "crosvm");
         android.tryRun("rm", "-rf", "/data/misc/virtualizationservice/*");