blob: a31fd0acd133e75e43a1ed5a0bdff4979bd8f5e5 [file] [log] [blame]
David Brazdil1f530702022-10-03 12:18:10 +01001// Copyright 2022, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Android Virtualization Manager
16
17mod aidl;
18mod atom;
19mod composite;
20mod crosvm;
Jaewan Kimc03f6612023-02-20 00:06:26 +090021mod debug_config;
Shikha Panwar55e10ec2024-02-13 12:53:49 +000022mod dt_overlay;
David Brazdil1f530702022-10-03 12:18:10 +010023mod payload;
24mod selinux;
25
David Brazdil4b4c5102022-12-19 22:56:20 +000026use crate::aidl::{GLOBAL_SERVICE, VirtualizationService};
David Brazdil1f530702022-10-03 12:18:10 +010027use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualizationService::BnVirtualizationService;
Alan Stokesc4d5def2023-02-14 17:01:59 +000028use anyhow::{bail, Context, Result};
David Brazdil4b4c5102022-12-19 22:56:20 +000029use binder::{BinderFeatures, ProcessState};
David Brazdil1f530702022-10-03 12:18:10 +010030use lazy_static::lazy_static;
Jeff Vander Stoep57da1572024-01-31 10:52:16 +010031use log::{info, LevelFilter};
David Brazdil1f530702022-10-03 12:18:10 +010032use rpcbinder::{FileDescriptorTransportMode, RpcServer};
Seungjae Yoodaf396a2024-04-15 12:58:07 +090033use std::os::unix::io::{AsFd, FromRawFd, OwnedFd, RawFd};
David Brazdil1f530702022-10-03 12:18:10 +010034use clap::Parser;
David Brazdil161ddda2023-01-06 20:29:19 +000035use nix::fcntl::{fcntl, F_GETFD, F_SETFD, FdFlag};
Seungjae Yoodaf396a2024-04-15 12:58:07 +090036use nix::unistd::{write, Pid, Uid};
David Brazdil1f530702022-10-03 12:18:10 +010037use std::os::unix::raw::{pid_t, uid_t};
38
39const LOG_TAG: &str = "virtmgr";
40
41lazy_static! {
42 static ref PID_PARENT: Pid = Pid::parent();
43 static ref UID_CURRENT: Uid = Uid::current();
44}
45
46fn get_calling_pid() -> pid_t {
47 // The caller is the parent of this process.
48 PID_PARENT.as_raw()
49}
50
51fn get_calling_uid() -> uid_t {
52 // The caller and this process share the same UID.
53 UID_CURRENT.as_raw()
54}
55
56#[derive(Parser)]
57struct Args {
58 /// File descriptor inherited from the caller to run RpcBinder server on.
59 /// This should be one end of a socketpair() compatible with RpcBinder's
60 /// UDS bootstrap transport.
61 #[clap(long)]
62 rpc_server_fd: RawFd,
63 /// File descriptor inherited from the caller to signal RpcBinder server
64 /// readiness. This should be one end of pipe() and the caller should be
65 /// waiting for HUP on the other end.
66 #[clap(long)]
67 ready_fd: RawFd,
68}
69
70fn take_fd_ownership(raw_fd: RawFd, owned_fds: &mut Vec<RawFd>) -> Result<OwnedFd, anyhow::Error> {
71 // Basic check that the integer value does correspond to a file descriptor.
David Brazdil161ddda2023-01-06 20:29:19 +000072 fcntl(raw_fd, F_GETFD).with_context(|| format!("Invalid file descriptor {raw_fd}"))?;
73
74 // The file descriptor had CLOEXEC disabled to be inherited from the parent.
75 // Re-enable it to make sure it is not accidentally inherited further.
76 fcntl(raw_fd, F_SETFD(FdFlag::FD_CLOEXEC))
77 .with_context(|| format!("Could not set CLOEXEC on file descriptor {raw_fd}"))?;
David Brazdil1f530702022-10-03 12:18:10 +010078
79 // Creating OwnedFd for stdio FDs is not safe.
80 if [libc::STDIN_FILENO, libc::STDOUT_FILENO, libc::STDERR_FILENO].contains(&raw_fd) {
81 bail!("File descriptor {raw_fd} is standard I/O descriptor");
82 }
83
84 // Reject RawFds that already have a corresponding OwnedFd.
85 if owned_fds.contains(&raw_fd) {
86 bail!("File descriptor {raw_fd} already owned");
87 }
88 owned_fds.push(raw_fd);
89
Andrew Walbranb58d1b42023-07-07 13:54:49 +010090 // SAFETY: Initializing OwnedFd for a RawFd provided in cmdline arguments.
David Brazdil1f530702022-10-03 12:18:10 +010091 // We checked that the integer value corresponds to a valid FD and that this
92 // is the first argument to claim its ownership.
93 Ok(unsafe { OwnedFd::from_raw_fd(raw_fd) })
94}
95
Alan Stokesc4d5def2023-02-14 17:01:59 +000096fn check_vm_support() -> Result<()> {
97 if hypervisor_props::is_any_vm_supported()? {
98 Ok(())
99 } else {
100 // This should never happen, it indicates a misconfigured device where the virt APEX
101 // is present but VMs are not supported. If it does happen, fail fast to avoid wasting
102 // resources trying.
103 bail!("Device doesn't support protected or non-protected VMs")
104 }
Alan Stokes8d39a9b2023-01-10 15:01:00 +0000105}
106
David Brazdil1f530702022-10-03 12:18:10 +0100107fn main() {
108 android_logger::init_once(
109 android_logger::Config::default()
110 .with_tag(LOG_TAG)
Jeff Vander Stoep57da1572024-01-31 10:52:16 +0100111 .with_max_level(LevelFilter::Info)
112 .with_log_buffer(android_logger::LogId::System),
David Brazdil1f530702022-10-03 12:18:10 +0100113 );
114
Alan Stokesc4d5def2023-02-14 17:01:59 +0000115 check_vm_support().unwrap();
Alan Stokes8d39a9b2023-01-10 15:01:00 +0000116
David Brazdil1f530702022-10-03 12:18:10 +0100117 let args = Args::parse();
118
119 let mut owned_fds = vec![];
120 let rpc_server_fd = take_fd_ownership(args.rpc_server_fd, &mut owned_fds)
121 .expect("Failed to take ownership of rpc_server_fd");
122 let ready_fd = take_fd_ownership(args.ready_fd, &mut owned_fds)
123 .expect("Failed to take ownership of ready_fd");
124
David Brazdil4b4c5102022-12-19 22:56:20 +0000125 // Start thread pool for kernel Binder connection to VirtualizationServiceInternal.
126 ProcessState::start_thread_pool();
127
128 GLOBAL_SERVICE.removeMemlockRlimit().expect("Failed to remove memlock rlimit");
129
David Brazdil1f530702022-10-03 12:18:10 +0100130 let service = VirtualizationService::init();
131 let service =
132 BnVirtualizationService::new_binder(service, BinderFeatures::default()).as_binder();
133
134 let server = RpcServer::new_unix_domain_bootstrap(service, rpc_server_fd)
135 .expect("Failed to start RpcServer");
136 server.set_supported_file_descriptor_transport_modes(&[FileDescriptorTransportMode::Unix]);
137
138 info!("Started VirtualizationService RpcServer. Ready to accept connections");
139
140 // Signal readiness to the caller by closing our end of the pipe.
Seungjae Yoodaf396a2024-04-15 12:58:07 +0900141 write(ready_fd.as_fd(), "o".as_bytes())
142 .expect("Failed to write a single character through ready_fd");
David Brazdil1f530702022-10-03 12:18:10 +0100143 drop(ready_fd);
144
145 server.join();
146 info!("Shutting down VirtualizationService RpcServer");
147}