Merge "rust: Visibility exports for bindgen"
diff --git a/.gitignore b/.gitignore
index 96ef6c0..5917dfb 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,5 @@
-/target
+apkdmverity/target/
+zipfuse/target/
+policy
+zipfuse/target/
 Cargo.lock
diff --git a/apkdmverity/Android.bp b/apkdmverity/Android.bp
index d7aa921..06d4500 100644
--- a/apkdmverity/Android.bp
+++ b/apkdmverity/Android.bp
@@ -11,7 +11,7 @@
     rustlibs: [
         "libanyhow",
         "libbitflags",
-        "libclap_deprecated",
+        "libclap",
         "libdata_model",
         "libidsig",
         "libitertools",
diff --git a/apkdmverity/src/main.rs b/apkdmverity/src/main.rs
index 16dd480..de7f5bb 100644
--- a/apkdmverity/src/main.rs
+++ b/apkdmverity/src/main.rs
@@ -45,7 +45,7 @@
                             block device is created at \"/dev/mapper/<name>\".' root_hash is \
                             optional; idsig file's root hash will be used if specified as \"none\"."
             ))
-        .arg(Arg::with_name("verbose").short("v").long("verbose").help("Shows verbose output"))
+        .arg(Arg::with_name("verbose").short('v').long("verbose").help("Shows verbose output"))
         .get_matches();
 
     let apks = matches.values_of("apk").unwrap();
diff --git a/authfs/Android.bp b/authfs/Android.bp
index 40643b8..cb7f119 100644
--- a/authfs/Android.bp
+++ b/authfs/Android.bp
@@ -14,7 +14,7 @@
         "libandroid_logger",
         "libanyhow",
         "libauthfs_fsverity_metadata",
-        "libbinder_rpc_unstable_bindgen",
+        "libbinder_common",
         "libbinder_rs",
         "libcfg_if",
         "libfsverity_digests_proto_rust",
diff --git a/authfs/fd_server/Android.bp b/authfs/fd_server/Android.bp
index c4aa1d8..943eec1 100644
--- a/authfs/fd_server/Android.bp
+++ b/authfs/fd_server/Android.bp
@@ -11,9 +11,8 @@
         "libanyhow",
         "libauthfs_fsverity_metadata",
         "libbinder_common",
-        "libbinder_rpc_unstable_bindgen",
         "libbinder_rs",
-        "libclap_deprecated",
+        "libclap",
         "liblibc",
         "liblog_rust",
         "libnix",
diff --git a/authfs/src/file.rs b/authfs/src/file.rs
index 44e60d8..d9f8964 100644
--- a/authfs/src/file.rs
+++ b/authfs/src/file.rs
@@ -6,15 +6,14 @@
 pub use dir::{InMemoryDir, RemoteDirEditor};
 pub use remote_file::{RemoteFileEditor, RemoteFileReader, RemoteMerkleTreeReader};
 
-use binder::unstable_api::{new_spibinder, AIBinder};
-use binder::FromIBinder;
-use std::convert::TryFrom;
-use std::io;
-use std::path::{Path, MAIN_SEPARATOR};
-
 use crate::common::{divide_roundup, CHUNK_SIZE};
 use authfs_aidl_interface::aidl::com::android::virt::fs::IVirtFdService::IVirtFdService;
 use authfs_aidl_interface::binder::{Status, Strong};
+use binder::StatusCode;
+use binder_common::rpc_client::connect_rpc_binder;
+use std::convert::TryFrom;
+use std::io;
+use std::path::{Path, MAIN_SEPARATOR};
 
 pub type VirtFdService = Strong<dyn IVirtFdService>;
 pub type VirtFdServiceStatus = Status;
@@ -24,21 +23,15 @@
 pub const RPC_SERVICE_PORT: u32 = 3264;
 
 pub fn get_rpc_binder_service(cid: u32) -> io::Result<VirtFdService> {
-    // SAFETY: AIBinder returned by RpcClient has correct reference count, and the ownership can be
-    // safely taken by new_spibinder.
-    let ibinder = unsafe {
-        new_spibinder(binder_rpc_unstable_bindgen::RpcClient(cid, RPC_SERVICE_PORT) as *mut AIBinder)
-    };
-    if let Some(ibinder) = ibinder {
-        Ok(<dyn IVirtFdService>::try_from(ibinder).map_err(|e| {
-            io::Error::new(
-                io::ErrorKind::AddrNotAvailable,
-                format!("Cannot connect to RPC service: {}", e),
-            )
-        })?)
-    } else {
-        Err(io::Error::new(io::ErrorKind::InvalidInput, "Invalid raw AIBinder"))
-    }
+    connect_rpc_binder(cid, RPC_SERVICE_PORT).map_err(|e| match e {
+        StatusCode::BAD_VALUE => {
+            io::Error::new(io::ErrorKind::InvalidInput, "Invalid raw AIBinder")
+        }
+        _ => io::Error::new(
+            io::ErrorKind::AddrNotAvailable,
+            format!("Cannot connect to RPC service: {}", e),
+        ),
+    })
 }
 
 /// A trait for reading data by chunks. Chunks can be read by specifying the chunk index. Only the
diff --git a/authfs/tests/Android.bp b/authfs/tests/Android.bp
index a886d10..ebc6dd4 100644
--- a/authfs/tests/Android.bp
+++ b/authfs/tests/Android.bp
@@ -31,7 +31,7 @@
     rustlibs: [
         "libandroid_logger",
         "libanyhow",
-        "libclap_deprecated",
+        "libclap",
         "libcommand_fds",
         "liblog_rust",
         "libnix",
diff --git a/avmd/Android.bp b/avmd/Android.bp
index e31e103..9f0b28b 100644
--- a/avmd/Android.bp
+++ b/avmd/Android.bp
@@ -30,7 +30,7 @@
         "libapexutil_rust",
         "libapkverify",
         "libavmd",
-        "libclap_deprecated",
+        "libclap",
         "libserde",
         "libserde_cbor",
         "libvbmeta_rust",
diff --git a/avmd/src/avmd.rs b/avmd/src/avmd.rs
index e3bc7a7..50cdfdf 100644
--- a/avmd/src/avmd.rs
+++ b/avmd/src/avmd.rs
@@ -12,9 +12,15 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+extern crate alloc;
+
+use alloc::{
+    string::{String, ToString},
+    vec::Vec,
+};
 use apexutil::to_hex_string;
+use core::fmt;
 use serde::{Deserialize, Serialize};
-use std::fmt;
 
 /// An Avmd struct contains
 /// - A header with version information that allows rollback when needed.
diff --git a/avmd/src/lib.rs b/avmd/src/lib.rs
index 9722518..7a06e6a 100644
--- a/avmd/src/lib.rs
+++ b/avmd/src/lib.rs
@@ -14,6 +14,8 @@
 
 //! Library for handling AVMD blobs.
 
+#![no_std]
+
 mod avmd;
 
 pub use avmd::{ApkDescriptor, Avmd, Descriptor, ResourceIdentifier, VbMetaDescriptor};
diff --git a/avmd/src/main.rs b/avmd/src/main.rs
index b156a66..ca28f42 100644
--- a/avmd/src/main.rs
+++ b/avmd/src/main.rs
@@ -149,8 +149,8 @@
 
     let args = app.get_matches();
     match args.subcommand() {
-        ("create", Some(sub_args)) => create(sub_args)?,
-        ("dump", Some(sub_args)) => dump(sub_args)?,
+        Some(("create", sub_args)) => create(sub_args)?,
+        Some(("dump", sub_args)) => dump(sub_args)?,
         _ => bail!("Invalid arguments"),
     }
     Ok(())
diff --git a/compos/Android.bp b/compos/Android.bp
index 7ef9e75..0f1675b 100644
--- a/compos/Android.bp
+++ b/compos/Android.bp
@@ -12,9 +12,8 @@
         "libandroid_logger",
         "libanyhow",
         "libbinder_common",
-        "libbinder_rpc_unstable_bindgen",
         "libbinder_rs",
-        "libclap_deprecated",
+        "libclap",
         "libcompos_common",
         "liblibc",
         "liblog_rust",
diff --git a/compos/common/Android.bp b/compos/common/Android.bp
index 1a69b1a..3c3397d 100644
--- a/compos/common/Android.bp
+++ b/compos/common/Android.bp
@@ -12,7 +12,6 @@
         "compos_aidl_interface-rust",
         "libanyhow",
         "libbinder_common",
-        "libbinder_rpc_unstable_bindgen",
         "liblazy_static",
         "liblog_rust",
         "libnested_virt",
diff --git a/compos/composd_cmd/Android.bp b/compos/composd_cmd/Android.bp
index 1ede0ba..c230e13 100644
--- a/compos/composd_cmd/Android.bp
+++ b/compos/composd_cmd/Android.bp
@@ -10,7 +10,7 @@
         "android.system.composd-rust",
         "libanyhow",
         "libbinder_rs",
-        "libclap_deprecated",
+        "libclap",
         "libcompos_common",
     ],
     prefer_rlib: true,
diff --git a/compos/composd_cmd/composd_cmd.rs b/compos/composd_cmd/composd_cmd.rs
index c6a5479..d5feed8 100644
--- a/compos/composd_cmd/composd_cmd.rs
+++ b/compos/composd_cmd/composd_cmd.rs
@@ -49,8 +49,8 @@
     ProcessState::start_thread_pool();
 
     match args.subcommand() {
-        ("staged-apex-compile", _) => run_staged_apex_compile()?,
-        ("test-compile", Some(sub_matches)) => {
+        Some(("staged-apex-compile", _)) => run_staged_apex_compile()?,
+        Some(("test-compile", sub_matches)) => {
             let prefer_staged = sub_matches.is_present("prefer-staged");
             run_test_compile(prefer_staged)?;
         }
diff --git a/compos/src/compsvc_main.rs b/compos/src/compsvc_main.rs
index 4ecbfe9..186977e 100644
--- a/compos/src/compsvc_main.rs
+++ b/compos/src/compsvc_main.rs
@@ -28,12 +28,8 @@
     },
     binder::Strong,
 };
-use anyhow::{anyhow, bail, Context, Result};
-use binder::{
-    unstable_api::{new_spibinder, AIBinder},
-    FromIBinder,
-};
-use binder_common::rpc_server::run_rpc_server;
+use anyhow::{bail, Context, Result};
+use binder_common::{rpc_client::connect_rpc_binder, rpc_server::run_rpc_server};
 use compos_common::COMPOS_VSOCK_PORT;
 use log::{debug, error};
 use std::panic;
@@ -76,15 +72,6 @@
 }
 
 fn get_vm_service() -> Result<Strong<dyn IVirtualMachineService>> {
-    // SAFETY: AIBinder returned by RpcClient has correct reference count, and the ownership
-    // can be safely taken by new_spibinder.
-    let ibinder = unsafe {
-        new_spibinder(binder_rpc_unstable_bindgen::RpcClient(
-            VMADDR_CID_HOST,
-            VM_BINDER_SERVICE_PORT as u32,
-        ) as *mut AIBinder)
-    }
-    .ok_or_else(|| anyhow!("Failed to connect to IVirtualMachineService"))?;
-
-    FromIBinder::try_from(ibinder).context("Connecting to IVirtualMachineService")
+    connect_rpc_binder(VMADDR_CID_HOST, VM_BINDER_SERVICE_PORT as u32)
+        .context("Connecting to IVirtualMachineService")
 }
diff --git a/compos/verify/Android.bp b/compos/verify/Android.bp
index 38edf1c..5c74e4f 100644
--- a/compos/verify/Android.bp
+++ b/compos/verify/Android.bp
@@ -11,7 +11,7 @@
         "libandroid_logger",
         "libanyhow",
         "libbinder_rs",
-        "libclap_deprecated",
+        "libclap",
         "libcompos_common",
         "libcompos_verify_native_rust",
         "liblog_rust",
diff --git a/microdroid_manager/Android.bp b/microdroid_manager/Android.bp
index d1afc14..3ba2700 100644
--- a/microdroid_manager/Android.bp
+++ b/microdroid_manager/Android.bp
@@ -16,7 +16,7 @@
         "libanyhow",
         "libapexutil_rust",
         "libapkverify",
-        "libbinder_rpc_unstable_bindgen",
+        "libbinder_common",
         "libbinder_rs",
         "libbyteorder",
         "libdiced_utils",
diff --git a/microdroid_manager/src/main.rs b/microdroid_manager/src/main.rs
index e4694e8..fa064a7 100644
--- a/microdroid_manager/src/main.rs
+++ b/microdroid_manager/src/main.rs
@@ -25,8 +25,8 @@
 use android_security_dice::aidl::android::security::dice::IDiceMaintenance::IDiceMaintenance;
 use anyhow::{anyhow, bail, ensure, Context, Error, Result};
 use apkverify::{get_public_key_der, verify};
-use binder::unstable_api::{new_spibinder, AIBinder};
-use binder::{wait_for_interface, FromIBinder, Strong};
+use binder::{wait_for_interface, Strong};
+use binder_common::rpc_client::connect_rpc_binder;
 use diced_utils::cbor::encode_header;
 use glob::glob;
 use idsig::V4Signature;
@@ -139,19 +139,8 @@
 }
 
 fn get_vms_rpc_binder() -> Result<Strong<dyn IVirtualMachineService>> {
-    // SAFETY: AIBinder returned by RpcClient has correct reference count, and the ownership can be
-    // safely taken by new_spibinder.
-    let ibinder = unsafe {
-        new_spibinder(binder_rpc_unstable_bindgen::RpcClient(
-            VMADDR_CID_HOST,
-            VM_BINDER_SERVICE_PORT as u32,
-        ) as *mut AIBinder)
-    };
-    if let Some(ibinder) = ibinder {
-        <dyn IVirtualMachineService>::try_from(ibinder).context("Cannot connect to RPC service")
-    } else {
-        bail!("Invalid raw AIBinder")
-    }
+    connect_rpc_binder(VMADDR_CID_HOST, VM_BINDER_SERVICE_PORT as u32)
+        .context("Cannot connect to RPC service")
 }
 
 fn main() -> Result<()> {
@@ -190,7 +179,6 @@
             Ok(())
         }
         Err(err) => {
-            error!("task terminated: {:?}", err);
             let (error_code, message) = translate_error(&err);
             service.notifyError(error_code, &message)?;
             Err(err)
diff --git a/tests/benchmark/src/native/benchmarkbinary.cpp b/tests/benchmark/src/native/benchmarkbinary.cpp
index 6a5b764..5523579 100644
--- a/tests/benchmark/src/native/benchmarkbinary.cpp
+++ b/tests/benchmark/src/native/benchmarkbinary.cpp
@@ -68,7 +68,7 @@
         char buf[kBlockSizeBytes];
 
         clock_t start = clock();
-        unique_fd fd(open(filename.c_str(), O_RDONLY));
+        unique_fd fd(open(filename.c_str(), O_RDONLY | O_CLOEXEC));
         if (fd.get() == -1) {
             return ErrnoError() << "Read: opening " << filename << " failed";
         }
diff --git a/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java b/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
index 1141106..b429e4d 100644
--- a/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
+++ b/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
@@ -157,6 +157,26 @@
     }
 
     @Test
+    public void bootFailsWhenLowMem() throws VirtualMachineException, InterruptedException {
+        VirtualMachineConfig lowMemConfig = mInner.newVmConfigBuilder("assets/vm_config.json")
+                .memoryMib(20)
+                .debugLevel(DebugLevel.NONE)
+                .build();
+        VirtualMachine vm = mInner.forceCreateNewVirtualMachine("low_mem", lowMemConfig);
+        final CompletableFuture<Integer> exception = new CompletableFuture<>();
+        VmEventListener listener =
+                new VmEventListener() {
+                    @Override
+                    public void onDied(VirtualMachine vm, @DeathReason int reason) {
+                        exception.complete(reason);
+                        super.onDied(vm, reason);
+                    }
+                };
+        listener.runToFinish(TAG, vm);
+        assertThat(exception.getNow(0)).isAnyOf(DeathReason.REBOOT, DeathReason.HANGUP);
+    }
+
+    @Test
     public void changingDebugLevelInvalidatesVmIdentity()
             throws VirtualMachineException, InterruptedException, IOException {
         assume()
diff --git a/zipfuse/Android.bp b/zipfuse/Android.bp
index d07a8e1..e10fc31 100644
--- a/zipfuse/Android.bp
+++ b/zipfuse/Android.bp
@@ -10,7 +10,7 @@
     prefer_rlib: true,
     rustlibs: [
         "libanyhow",
-        "libclap_deprecated",
+        "libclap",
         "libfuse_rust",
         "liblibc",
         "libzip",
diff --git a/zipfuse/src/main.rs b/zipfuse/src/main.rs
index 874056a..8400a72 100644
--- a/zipfuse/src/main.rs
+++ b/zipfuse/src/main.rs
@@ -41,7 +41,7 @@
     let matches = App::new("zipfuse")
         .arg(
             Arg::with_name("options")
-                .short("o")
+                .short('o')
                 .takes_value(true)
                 .required(false)
                 .help("Comma separated list of mount options"),