blob: 67e7282f11e9deaf5ccee04c16056fd34df50535 [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;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +090028use anyhow::{bail, Context, Result};
David Brazdil4b4c5102022-12-19 22:56:20 +000029use binder::{BinderFeatures, ProcessState};
Jeff Vander Stoep57da1572024-01-31 10:52:16 +010030use log::{info, LevelFilter};
David Brazdil1f530702022-10-03 12:18:10 +010031use rpcbinder::{FileDescriptorTransportMode, RpcServer};
Jiyong Parkaf63d1c2024-09-04 16:15:42 +090032use std::os::unix::io::{AsFd, FromRawFd, OwnedFd, RawFd};
Andrew Walbran9c03a3a2024-09-03 12:12:59 +010033use std::sync::LazyLock;
David Brazdil1f530702022-10-03 12:18:10 +010034use clap::Parser;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +090035use 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
Andrew Walbran9c03a3a2024-09-03 12:12:59 +010041static PID_CURRENT: LazyLock<Pid> = LazyLock::new(Pid::this);
42static PID_PARENT: LazyLock<Pid> = LazyLock::new(Pid::parent);
43static UID_CURRENT: LazyLock<Uid> = LazyLock::new(Uid::current);
David Brazdil1f530702022-10-03 12:18:10 +010044
Seungjae Yoo13af0b62024-05-20 14:15:13 +090045fn get_this_pid() -> pid_t {
46 // Return the process ID of this process.
47 PID_CURRENT.as_raw()
48}
49
David Brazdil1f530702022-10-03 12:18:10 +010050fn get_calling_pid() -> pid_t {
51 // The caller is the parent of this process.
52 PID_PARENT.as_raw()
53}
54
55fn get_calling_uid() -> uid_t {
56 // The caller and this process share the same UID.
57 UID_CURRENT.as_raw()
58}
59
60#[derive(Parser)]
61struct Args {
62 /// File descriptor inherited from the caller to run RpcBinder server on.
63 /// This should be one end of a socketpair() compatible with RpcBinder's
64 /// UDS bootstrap transport.
65 #[clap(long)]
66 rpc_server_fd: RawFd,
67 /// File descriptor inherited from the caller to signal RpcBinder server
68 /// readiness. This should be one end of pipe() and the caller should be
69 /// waiting for HUP on the other end.
70 #[clap(long)]
71 ready_fd: RawFd,
72}
73
Jiyong Parkaf63d1c2024-09-04 16:15:42 +090074fn take_fd_ownership(raw_fd: RawFd, owned_fds: &mut Vec<RawFd>) -> Result<OwnedFd, anyhow::Error> {
75 // Basic check that the integer value does correspond to a file descriptor.
76 fcntl(raw_fd, F_GETFD).with_context(|| format!("Invalid file descriptor {raw_fd}"))?;
77
78 // The file descriptor had CLOEXEC disabled to be inherited from the parent.
79 // Re-enable it to make sure it is not accidentally inherited further.
80 fcntl(raw_fd, F_SETFD(FdFlag::FD_CLOEXEC))
81 .with_context(|| format!("Could not set CLOEXEC on file descriptor {raw_fd}"))?;
82
83 // Creating OwnedFd for stdio FDs is not safe.
84 if [libc::STDIN_FILENO, libc::STDOUT_FILENO, libc::STDERR_FILENO].contains(&raw_fd) {
85 bail!("File descriptor {raw_fd} is standard I/O descriptor");
86 }
87
88 // Reject RawFds that already have a corresponding OwnedFd.
89 if owned_fds.contains(&raw_fd) {
90 bail!("File descriptor {raw_fd} already owned");
91 }
92 owned_fds.push(raw_fd);
93
94 // SAFETY: Initializing OwnedFd for a RawFd provided in cmdline arguments.
95 // We checked that the integer value corresponds to a valid FD and that this
96 // is the first argument to claim its ownership.
97 Ok(unsafe { OwnedFd::from_raw_fd(raw_fd) })
98}
99
Alan Stokesc4d5def2023-02-14 17:01:59 +0000100fn check_vm_support() -> Result<()> {
101 if hypervisor_props::is_any_vm_supported()? {
102 Ok(())
103 } else {
104 // This should never happen, it indicates a misconfigured device where the virt APEX
105 // is present but VMs are not supported. If it does happen, fail fast to avoid wasting
106 // resources trying.
107 bail!("Device doesn't support protected or non-protected VMs")
108 }
Alan Stokes8d39a9b2023-01-10 15:01:00 +0000109}
110
David Brazdil1f530702022-10-03 12:18:10 +0100111fn main() {
112 android_logger::init_once(
113 android_logger::Config::default()
114 .with_tag(LOG_TAG)
Jeff Vander Stoep57da1572024-01-31 10:52:16 +0100115 .with_max_level(LevelFilter::Info)
116 .with_log_buffer(android_logger::LogId::System),
David Brazdil1f530702022-10-03 12:18:10 +0100117 );
118
Alan Stokesc4d5def2023-02-14 17:01:59 +0000119 check_vm_support().unwrap();
Alan Stokes8d39a9b2023-01-10 15:01:00 +0000120
David Brazdil1f530702022-10-03 12:18:10 +0100121 let args = Args::parse();
122
Jiyong Parkaf63d1c2024-09-04 16:15:42 +0900123 let mut owned_fds = vec![];
124 let rpc_server_fd = take_fd_ownership(args.rpc_server_fd, &mut owned_fds)
125 .expect("Failed to take ownership of rpc_server_fd");
126 let ready_fd = take_fd_ownership(args.ready_fd, &mut owned_fds)
127 .expect("Failed to take ownership of ready_fd");
David Brazdil1f530702022-10-03 12:18:10 +0100128
David Brazdil4b4c5102022-12-19 22:56:20 +0000129 // Start thread pool for kernel Binder connection to VirtualizationServiceInternal.
130 ProcessState::start_thread_pool();
131
Inseob Kimb198f6e2024-07-22 18:06:15 +0900132 if cfg!(early) {
Inseob Kimecde8c02024-09-03 13:11:08 +0900133 // we can't access VirtualizationServiceInternal, so directly call rlimit
134 let pid = i32::from(*PID_CURRENT);
135 let lim = libc::rlimit { rlim_cur: libc::RLIM_INFINITY, rlim_max: libc::RLIM_INFINITY };
136
137 // SAFETY: borrowing the new limit struct only. prlimit doesn't use lim outside its lifetime
138 let ret = unsafe { libc::prlimit(pid, libc::RLIMIT_MEMLOCK, &lim, std::ptr::null_mut()) };
139 if ret == -1 {
140 panic!("rlimit error: {}", std::io::Error::last_os_error());
141 } else if ret != 0 {
142 panic!("Unexpected return value from prlimit(): {ret}");
143 }
Inseob Kimb198f6e2024-07-22 18:06:15 +0900144 } else {
145 GLOBAL_SERVICE.removeMemlockRlimit().expect("Failed to remove memlock rlimit");
146 }
David Brazdil4b4c5102022-12-19 22:56:20 +0000147
David Brazdil1f530702022-10-03 12:18:10 +0100148 let service = VirtualizationService::init();
149 let service =
150 BnVirtualizationService::new_binder(service, BinderFeatures::default()).as_binder();
151
152 let server = RpcServer::new_unix_domain_bootstrap(service, rpc_server_fd)
153 .expect("Failed to start RpcServer");
154 server.set_supported_file_descriptor_transport_modes(&[FileDescriptorTransportMode::Unix]);
155
156 info!("Started VirtualizationService RpcServer. Ready to accept connections");
157
158 // Signal readiness to the caller by closing our end of the pipe.
Seungjae Yoodaf396a2024-04-15 12:58:07 +0900159 write(ready_fd.as_fd(), "o".as_bytes())
160 .expect("Failed to write a single character through ready_fd");
David Brazdil1f530702022-10-03 12:18:10 +0100161 drop(ready_fd);
162
163 server.join();
164 info!("Shutting down VirtualizationService RpcServer");
165}