blob: 111a819ad67ac60ec2522aa5c68215d0cdbac4cd [file] [log] [blame]
Alan Stokes9e2c5d52021-07-21 11:29:10 +01001/*
2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//! A tool to start a standalone compsvc server, either in the host using Binder or in a VM using
18//! RPC binder over vsock.
19//!
20//! Example:
21//! $ compsvc /system/bin/sleep
22
23mod common;
24mod compsvc;
25
26use crate::common::{SERVICE_NAME, VSOCK_PORT};
27use anyhow::{bail, Context, Result};
28use binder::unstable_api::AsNative;
29use compos_aidl_interface::binder::{add_service, ProcessState};
30use log::debug;
31
32struct Config {
33 task_bin: String,
34 rpc_binder: bool,
35 debuggable: bool,
36}
37
38fn parse_args() -> Result<Config> {
39 #[rustfmt::skip]
40 let matches = clap::App::new("compsvc")
41 .arg(clap::Arg::with_name("debug")
42 .long("debug"))
43 .arg(clap::Arg::with_name("task_bin")
44 .required(true))
45 .arg(clap::Arg::with_name("rpc_binder")
46 .long("rpc-binder"))
47 .get_matches();
48
49 Ok(Config {
50 task_bin: matches.value_of("task_bin").unwrap().to_string(),
51 rpc_binder: matches.is_present("rpc_binder"),
52 debuggable: matches.is_present("debug"),
53 })
54}
55
56fn main() -> Result<()> {
57 android_logger::init_once(
58 android_logger::Config::default().with_tag("compsvc").with_min_level(log::Level::Debug),
59 );
60
61 let config = parse_args()?;
62 let mut service = compsvc::new_binder(config.task_bin, config.debuggable).as_binder();
63 if config.rpc_binder {
64 debug!("compsvc is starting as a rpc service.");
65 // SAFETY: Service ownership is transferring to the server and won't be valid afterward.
66 // Plus the binder objects are threadsafe.
67 let retval = unsafe {
68 binder_rpc_unstable_bindgen::RunRpcServer(
69 service.as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder,
70 VSOCK_PORT,
71 )
72 };
73 if retval {
74 debug!("RPC server has shut down gracefully");
75 Ok(())
76 } else {
77 bail!("Premature termination of RPC server");
78 }
79 } else {
80 ProcessState::start_thread_pool();
81 debug!("compsvc is starting as a local service.");
82 add_service(SERVICE_NAME, service)
83 .with_context(|| format!("Failed to register service {}", SERVICE_NAME))?;
84 ProcessState::join_thread_pool();
85 bail!("Unexpected exit after join_thread_pool")
86 }
87}