compsvc: Remove local binder support

Bug: 190851176
Test: atest ComposHostTestCases
Change-Id: I75e39ce4d44bb2188a4fe000a2a30b5a55e1ab8d
diff --git a/compos/apk/assets/vm_config.json b/compos/apk/assets/vm_config.json
index 3be8a8a..9be60d0 100644
--- a/compos/apk/assets/vm_config.json
+++ b/compos/apk/assets/vm_config.json
@@ -5,10 +5,7 @@
   },
   "task": {
     "type": "executable",
-    "command": "/apex/com.android.compos/bin/compsvc",
-    "args": [
-      "--rpc-binder"
-    ]
+    "command": "/apex/com.android.compos/bin/compsvc"
   },
   "apexes": [
     {
diff --git a/compos/src/common.rs b/compos/src/common.rs
index 6cad63a..ca831bb 100644
--- a/compos/src/common.rs
+++ b/compos/src/common.rs
@@ -17,6 +17,3 @@
 /// Port to listen. This should be out of future port range (if happens) that microdroid may
 /// reserve for system components.
 pub const VSOCK_PORT: u32 = 6432;
-
-/// Service name of local binder. Used only for debugging purpose.
-pub const SERVICE_NAME: &str = "compsvc";
diff --git a/compos/src/compos_key_service.rs b/compos/src/compos_key_service.rs
index 92b04f2..4a1566d 100644
--- a/compos/src/compos_key_service.rs
+++ b/compos/src/compos_key_service.rs
@@ -32,15 +32,9 @@
 use ring::signature;
 use scopeguard::ScopeGuard;
 
-/// Keystore2 namespace IDs, used for access control to keys.
-#[derive(Copy, Clone, Debug, PartialEq, Eq)]
-pub enum KeystoreNamespace {
-    /// In the host we re-use the ID assigned to odsign. See system/sepolicy/private/keystore2_key_contexts.
-    // TODO(alanstokes): Remove this.
-    Odsign = 101,
-    /// In a VM we can use the generic ID allocated for payloads. See microdroid's keystore2_key_contexts.
-    VmPayload = 140,
-}
+/// Keystore2 namespace ID, used for access control to keys. In a VM we can use the generic ID
+/// allocated for payloads. See microdroid's keystore2_key_contexts.
+const KEYSTORE_NAMESPACE: i64 = 140;
 
 const KEYSTORE_SERVICE_NAME: &str = "android.system.keystore2.IKeystoreService/default";
 const PURPOSE_SIGN: KeyParameter =
@@ -61,25 +55,21 @@
     KeyParameter { tag: Tag::NO_AUTH_REQUIRED, value: KeyParameterValue::BoolValue(true) };
 
 const BLOB_KEY_DESCRIPTOR: KeyDescriptor =
-    KeyDescriptor { domain: Domain::BLOB, nspace: 0, alias: None, blob: None };
+    KeyDescriptor { domain: Domain::BLOB, nspace: KEYSTORE_NAMESPACE, alias: None, blob: None };
 
 /// An internal service for CompOS key management.
 #[derive(Clone)]
 pub struct CompOsKeyService {
-    namespace: KeystoreNamespace,
     random: SystemRandom,
     security_level: Strong<dyn IKeystoreSecurityLevel>,
 }
 
 impl CompOsKeyService {
-    pub fn new(rpc_binder: bool) -> Result<Self> {
+    pub fn new() -> Result<Self> {
         let keystore_service = wait_for_interface::<dyn IKeystoreService>(KEYSTORE_SERVICE_NAME)
             .context("No Keystore service")?;
 
-        let namespace =
-            if rpc_binder { KeystoreNamespace::VmPayload } else { KeystoreNamespace::Odsign };
         Ok(CompOsKeyService {
-            namespace,
             random: SystemRandom::new(),
             security_level: keystore_service
                 .getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT)
@@ -88,7 +78,7 @@
     }
 
     pub fn do_generate(&self) -> Result<CompOsKeyData> {
-        let key_descriptor = KeyDescriptor { nspace: self.namespace as i64, ..BLOB_KEY_DESCRIPTOR };
+        let key_descriptor = BLOB_KEY_DESCRIPTOR;
         let key_parameters =
             [PURPOSE_SIGN, ALGORITHM, PADDING, DIGEST, KEY_SIZE, EXPONENT, NO_AUTH_REQUIRED];
         let attestation_key = None;
@@ -121,11 +111,7 @@
     }
 
     pub fn do_sign(&self, key_blob: &[u8], data: &[u8]) -> Result<Vec<u8>> {
-        let key_descriptor = KeyDescriptor {
-            nspace: self.namespace as i64,
-            blob: Some(key_blob.to_vec()),
-            ..BLOB_KEY_DESCRIPTOR
-        };
+        let key_descriptor = KeyDescriptor { blob: Some(key_blob.to_vec()), ..BLOB_KEY_DESCRIPTOR };
         let operation_parameters = [PURPOSE_SIGN, ALGORITHM, PADDING, DIGEST];
         let forced = false;
 
diff --git a/compos/src/compsvc.rs b/compos/src/compsvc.rs
index ed5534e..55d9d64 100644
--- a/compos/src/compsvc.rs
+++ b/compos/src/compsvc.rs
@@ -43,10 +43,10 @@
 const DEX2OAT_PATH: &str = "/apex/com.android.art/bin/dex2oat64";
 
 /// Constructs a binder object that implements ICompOsService.
-pub fn new_binder(rpc_binder: bool) -> Result<Strong<dyn ICompOsService>> {
+pub fn new_binder() -> Result<Strong<dyn ICompOsService>> {
     let service = CompOsService {
         dex2oat_path: PathBuf::from(DEX2OAT_PATH),
-        key_service: CompOsKeyService::new(rpc_binder)?,
+        key_service: CompOsKeyService::new()?,
         key_blob: Arc::new(RwLock::new(Vec::new())),
     };
     Ok(BnCompOsService::new_binder(service, BinderFeatures::default()))
diff --git a/compos/src/compsvc_main.rs b/compos/src/compsvc_main.rs
index 6396556..46c8f8c 100644
--- a/compos/src/compsvc_main.rs
+++ b/compos/src/compsvc_main.rs
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-//! A tool to start a standalone compsvc server, either in the host using Binder or in a VM using
-//! RPC binder over vsock.
+//! A tool to start a standalone compsvc server that serves over RPC binder.
 
 mod common;
 mod compilation;
@@ -24,55 +23,30 @@
 mod fsverity;
 mod signer;
 
-use crate::common::{SERVICE_NAME, VSOCK_PORT};
-use anyhow::{bail, Context, Result};
+use crate::common::VSOCK_PORT;
+use anyhow::{bail, Result};
 use binder::unstable_api::AsNative;
-use compos_aidl_interface::binder::{add_service, ProcessState};
 use log::debug;
 
-struct Config {
-    rpc_binder: bool,
-}
-
-fn parse_args() -> Result<Config> {
-    #[rustfmt::skip]
-    let matches = clap::App::new("compsvc")
-        .arg(clap::Arg::with_name("rpc_binder")
-             .long("rpc-binder"))
-        .get_matches();
-
-    Ok(Config { rpc_binder: matches.is_present("rpc_binder") })
-}
-
 fn main() -> Result<()> {
     android_logger::init_once(
         android_logger::Config::default().with_tag("compsvc").with_min_level(log::Level::Debug),
     );
 
-    let config = parse_args()?;
-    let mut service = compsvc::new_binder(config.rpc_binder)?.as_binder();
-    if config.rpc_binder {
-        debug!("compsvc is starting as a rpc service.");
-        // SAFETY: Service ownership is transferring to the server and won't be valid afterward.
-        // Plus the binder objects are threadsafe.
-        let retval = unsafe {
-            binder_rpc_unstable_bindgen::RunRpcServer(
-                service.as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder,
-                VSOCK_PORT,
-            )
-        };
-        if retval {
-            debug!("RPC server has shut down gracefully");
-            Ok(())
-        } else {
-            bail!("Premature termination of RPC server");
-        }
+    let mut service = compsvc::new_binder()?.as_binder();
+    debug!("compsvc is starting as a rpc service.");
+    // SAFETY: Service ownership is transferring to the server and won't be valid afterward.
+    // Plus the binder objects are threadsafe.
+    let retval = unsafe {
+        binder_rpc_unstable_bindgen::RunRpcServer(
+            service.as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder,
+            VSOCK_PORT,
+        )
+    };
+    if retval {
+        debug!("RPC server has shut down gracefully");
+        Ok(())
     } else {
-        ProcessState::start_thread_pool();
-        debug!("compsvc is starting as a local service.");
-        add_service(SERVICE_NAME, service)
-            .with_context(|| format!("Failed to register service {}", SERVICE_NAME))?;
-        ProcessState::join_thread_pool();
-        bail!("Unexpected exit after join_thread_pool")
+        bail!("Premature termination of RPC server");
     }
 }
diff --git a/compos/src/pvm_exec.rs b/compos/src/pvm_exec.rs
index 27802e3..cbcae8f 100644
--- a/compos/src/pvm_exec.rs
+++ b/compos/src/pvm_exec.rs
@@ -29,6 +29,7 @@
 use anyhow::{bail, Context, Result};
 use binder::unstable_api::{new_spibinder, AIBinder};
 use binder::FromIBinder;
+use clap::{value_t, App, Arg};
 use log::{debug, error, warn};
 use minijail::Minijail;
 use nix::fcntl::{fcntl, FcntlArg::F_GETFD};
@@ -42,14 +43,10 @@
 use compos_aidl_interface::binder::Strong;
 
 mod common;
-use common::{SERVICE_NAME, VSOCK_PORT};
+use common::VSOCK_PORT;
 
 const FD_SERVER_BIN: &str = "/apex/com.android.virt/bin/fd_server";
 
-fn get_local_service() -> Result<Strong<dyn ICompOsService>> {
-    compos_aidl_interface::binder::get_interface(SERVICE_NAME).context("get local binder")
-}
-
 fn get_rpc_binder(cid: u32) -> Result<Strong<dyn ICompOsService>> {
     // SAFETY: AIBinder returned by RpcClient has correct reference count, and the ownership can be
     // safely taken by new_spibinder.
@@ -103,29 +100,30 @@
 struct Config {
     args: Vec<String>,
     fd_annotation: FdAnnotation,
-    cid: Option<u32>,
+    cid: u32,
     debuggable: bool,
 }
 
 fn parse_args() -> Result<Config> {
     #[rustfmt::skip]
-    let matches = clap::App::new("pvm_exec")
-        .arg(clap::Arg::with_name("in-fd")
+    let matches = App::new("pvm_exec")
+        .arg(Arg::with_name("in-fd")
              .long("in-fd")
              .takes_value(true)
              .multiple(true)
              .use_delimiter(true))
-        .arg(clap::Arg::with_name("out-fd")
+        .arg(Arg::with_name("out-fd")
              .long("out-fd")
              .takes_value(true)
              .multiple(true)
              .use_delimiter(true))
-        .arg(clap::Arg::with_name("cid")
+        .arg(Arg::with_name("cid")
              .takes_value(true)
+             .required(true)
              .long("cid"))
-        .arg(clap::Arg::with_name("debug")
+        .arg(Arg::with_name("debug")
              .long("debug"))
-        .arg(clap::Arg::with_name("args")
+        .arg(Arg::with_name("args")
              .last(true)
              .required(true)
              .multiple(true))
@@ -140,8 +138,7 @@
     let output_fds = results?;
 
     let args: Vec<_> = matches.values_of("args").unwrap().map(|s| s.to_string()).collect();
-    let cid =
-        if let Some(arg) = matches.value_of("cid") { Some(arg.parse::<u32>()?) } else { None };
+    let cid = value_t!(matches, "cid", u32)?;
     let debuggable = matches.is_present("debug");
 
     Ok(Config { args, fd_annotation: FdAnnotation { input_fds, output_fds }, cid, debuggable })
@@ -168,7 +165,7 @@
     });
 
     // 3. Send the command line args to the remote to execute.
-    let service = if let Some(cid) = cid { get_rpc_binder(cid) } else { get_local_service() }?;
+    let service = get_rpc_binder(cid)?;
     let result = service.compile(&args, &fd_annotation).context("Binder call failed")?;
 
     // TODO: store/use the signature