blob: 14db27c241f9da4972f62639f50ef5ec53f4db92 [file] [log] [blame]
Andrew Walbranea9fa482021-03-04 16:11:12 +00001// Copyright 2021, 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 VM control tool.
16
Jooyung Hanc221c052022-02-22 05:20:15 +090017mod create_idsig;
Jiyong Park48b354d2021-07-15 15:04:38 +090018mod create_partition;
Andrew Walbranf395b822021-05-05 10:38:59 +000019mod run;
Andrew Walbranea9fa482021-03-04 16:11:12 +000020
Jiyong Parkc2a49cc2021-10-15 00:02:12 +090021use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
David Brazdil7d1e5ec2023-02-06 17:56:29 +000022 CpuTopology::CpuTopology, IVirtualizationService::IVirtualizationService,
23 PartitionType::PartitionType, VirtualMachineAppConfig::DebugLevel::DebugLevel,
Jiyong Parkc2a49cc2021-10-15 00:02:12 +090024};
David Brazdil20412d92021-03-18 10:53:06 +000025use anyhow::{Context, Error};
Alan Stokesc4d5def2023-02-14 17:01:59 +000026use binder::{ProcessState, Strong};
Jiyong Parkb1935ef2023-08-10 17:22:39 +090027use clap::{Args, Parser};
Jooyung Hanc221c052022-02-22 05:20:15 +090028use create_idsig::command_create_idsig;
Jiyong Park48b354d2021-07-15 15:04:38 +090029use create_partition::command_create_partition;
Nikita Ioffeb0b67562022-11-22 15:48:06 +000030use run::{command_run, command_run_app, command_run_microdroid};
Nikita Ioffe5776f082023-02-10 21:38:26 +000031use std::num::NonZeroU16;
Andrew Walbranc4b1bde2022-02-03 15:26:02 +000032use std::path::{Path, PathBuf};
Andrew Walbranea9fa482021-03-04 16:11:12 +000033
Inseob Kima5a262f2021-11-17 19:41:03 +090034#[derive(Debug)]
35struct Idsigs(Vec<PathBuf>);
36
Jiyong Parkb1935ef2023-08-10 17:22:39 +090037#[derive(Args)]
38/// Collection of flags that are at VM level and therefore applicable to all subcommands
39pub struct CommonConfig {
40 /// Name of VM
41 #[arg(long)]
42 name: Option<String>,
43
44 /// Run VM with vCPU topology matching that of the host. If unspecified, defaults to 1 vCPU.
45 #[arg(long, default_value = "one_cpu", value_parser = parse_cpu_topology)]
46 cpu_topology: CpuTopology,
47
48 /// Comma separated list of task profile names to apply to the VM
49 #[arg(long)]
50 task_profiles: Vec<String>,
51
52 /// Memory size (in MiB) of the VM. If unspecified, defaults to the value of `memory_mib`
53 /// in the VM config file.
54 #[arg(short, long)]
55 mem: Option<u32>,
56
57 /// Run VM in protected mode.
58 #[arg(short, long)]
59 protected: bool,
60}
61
62#[derive(Args)]
63/// Collection of flags for debugging
64pub struct DebugConfig {
65 /// Debug level of the VM. Supported values: "full" (default), and "none".
66 #[arg(long, default_value = "full", value_parser = parse_debug_level)]
67 debug: DebugLevel,
68
69 /// Path to file for VM console output.
70 #[arg(long)]
71 console: Option<PathBuf>,
72
73 /// Path to file for VM console input.
74 #[arg(long)]
75 console_in: Option<PathBuf>,
76
77 /// Path to file for VM log output.
78 #[arg(long)]
79 log: Option<PathBuf>,
80
81 /// Port at which crosvm will start a gdb server to debug guest kernel.
82 /// Note: this is only supported on Android kernels android14-5.15 and higher.
83 #[arg(long)]
84 gdb: Option<NonZeroU16>,
85}
86
87#[derive(Args)]
88/// Collection of flags that are Microdroid specific
89pub struct MicrodroidConfig {
90 /// Path to the file backing the storage.
91 /// Created if the option is used but the path does not exist in the device.
92 #[arg(long)]
93 storage: Option<PathBuf>,
94
95 /// Size of the storage. Used only if --storage is supplied but path does not exist
96 /// Default size is 10*1024*1024
97 #[arg(long)]
98 storage_size: Option<u64>,
99
100 /// Path to custom kernel image to use when booting Microdroid.
Nikita Ioffe631717e2023-09-05 13:38:07 +0100101 #[cfg(vendor_modules)]
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900102 #[arg(long)]
103 kernel: Option<PathBuf>,
104
105 /// Path to disk image containing vendor-specific modules.
Nikita Ioffe631717e2023-09-05 13:38:07 +0100106 #[cfg(vendor_modules)]
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900107 #[arg(long)]
108 vendor: Option<PathBuf>,
109
110 /// SysFS nodes of devices to assign to VM
Nikita Ioffe94a8a182023-11-16 16:37:48 +0000111 #[cfg(device_assignment)]
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900112 #[arg(long)]
113 devices: Vec<PathBuf>,
114}
115
Nikita Ioffe631717e2023-09-05 13:38:07 +0100116impl MicrodroidConfig {
117 #[cfg(vendor_modules)]
118 fn kernel(&self) -> &Option<PathBuf> {
119 &self.kernel
120 }
121
122 #[cfg(not(vendor_modules))]
123 fn kernel(&self) -> Option<PathBuf> {
124 None
125 }
126
127 #[cfg(vendor_modules)]
128 fn vendor(&self) -> &Option<PathBuf> {
129 &self.vendor
130 }
131
132 #[cfg(not(vendor_modules))]
Nikita Ioffe631717e2023-09-05 13:38:07 +0100133 fn vendor(&self) -> Option<PathBuf> {
134 None
135 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +0000136
137 #[cfg(device_assignment)]
138 fn devices(&self) -> &Vec<PathBuf> {
139 &self.devices
140 }
141
142 #[cfg(not(device_assignment))]
143 fn devices(&self) -> Vec<PathBuf> {
144 Vec::new()
145 }
Nikita Ioffe631717e2023-09-05 13:38:07 +0100146}
147
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900148#[derive(Args)]
149/// Flags for the run_app subcommand
150pub struct RunAppConfig {
151 #[command(flatten)]
152 common: CommonConfig,
153
154 #[command(flatten)]
155 debug: DebugConfig,
156
157 #[command(flatten)]
158 microdroid: MicrodroidConfig,
159
160 /// Path to VM Payload APK
161 apk: PathBuf,
162
163 /// Path to idsig of the APK
164 idsig: PathBuf,
165
166 /// Path to the instance image. Created if not exists.
167 instance: PathBuf,
168
169 /// Path to VM config JSON within APK (e.g. assets/vm_config.json)
170 #[arg(long)]
171 config_path: Option<String>,
172
173 /// Name of VM payload binary within APK (e.g. MicrodroidTestNativeLib.so)
174 #[arg(long)]
175 #[arg(alias = "payload_path")]
176 payload_binary_name: Option<String>,
177
178 /// Paths to extra idsig files.
179 #[arg(long = "extra-idsig")]
180 extra_idsigs: Vec<PathBuf>,
181}
182
183#[derive(Args)]
184/// Flags for the run_microdroid subcommand
185pub struct RunMicrodroidConfig {
186 #[command(flatten)]
187 common: CommonConfig,
188
189 #[command(flatten)]
190 debug: DebugConfig,
191
192 #[command(flatten)]
193 microdroid: MicrodroidConfig,
194
195 /// Path to the directory where VM-related files (e.g. instance.img, apk.idsig, etc.) will
196 /// be stored. If not specified a random directory under /data/local/tmp/microdroid will be
197 /// created and used.
198 #[arg(long)]
199 work_dir: Option<PathBuf>,
200}
201
202#[derive(Args)]
203/// Flags for the run subcommand
204pub struct RunCustomVmConfig {
205 #[command(flatten)]
206 common: CommonConfig,
207
208 #[command(flatten)]
209 debug: DebugConfig,
210
211 /// Path to VM config JSON
212 config: PathBuf,
213}
214
Victor Hsiehb5bcfab2022-09-12 13:06:26 -0700215#[derive(Parser)]
David Brazdil20412d92021-03-18 10:53:06 +0000216enum Opt {
Jooyung Han21e9b922021-06-26 04:14:16 +0900217 /// Run a virtual machine with a config in APK
218 RunApp {
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900219 #[command(flatten)]
220 config: RunAppConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +0900221 },
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000222 /// Run a virtual machine with Microdroid inside
223 RunMicrodroid {
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900224 #[command(flatten)]
225 config: RunMicrodroidConfig,
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000226 },
David Brazdil20412d92021-03-18 10:53:06 +0000227 /// Run a virtual machine
228 Run {
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900229 #[command(flatten)]
230 config: RunCustomVmConfig,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000231 },
David Brazdil20412d92021-03-18 10:53:06 +0000232 /// List running virtual machines
233 List,
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000234 /// Print information about virtual machine support
235 Info,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000236 /// Create a new empty partition to be used as a writable partition for a VM
237 CreatePartition {
238 /// Path at which to create the image file
Andrew Walbrandff3b942021-06-09 15:20:36 +0000239 path: PathBuf,
240
241 /// The desired size of the partition, in bytes.
242 size: u64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900243
244 /// Type of the partition
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900245 #[arg(short = 't', long = "type", default_value = "raw",
Victor Hsiehb5bcfab2022-09-12 13:06:26 -0700246 value_parser = parse_partition_type)]
Jiyong Park9dd389e2021-08-23 20:42:59 +0900247 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000248 },
Jooyung Hanc221c052022-02-22 05:20:15 +0900249 /// Creates or update the idsig file by digesting the input APK file.
250 CreateIdsig {
251 /// Path to VM Payload APK
Jooyung Hanc221c052022-02-22 05:20:15 +0900252 apk: PathBuf,
Victor Hsiehb5bcfab2022-09-12 13:06:26 -0700253
Jooyung Hanc221c052022-02-22 05:20:15 +0900254 /// Path to idsig of the APK
Jooyung Hanc221c052022-02-22 05:20:15 +0900255 path: PathBuf,
256 },
David Brazdil20412d92021-03-18 10:53:06 +0000257}
258
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900259fn parse_debug_level(s: &str) -> Result<DebugLevel, String> {
260 match s {
261 "none" => Ok(DebugLevel::NONE),
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900262 "full" => Ok(DebugLevel::FULL),
263 _ => Err(format!("Invalid debug level {}", s)),
264 }
265}
266
Jiyong Park9dd389e2021-08-23 20:42:59 +0900267fn parse_partition_type(s: &str) -> Result<PartitionType, String> {
268 match s {
269 "raw" => Ok(PartitionType::RAW),
270 "instance" => Ok(PartitionType::ANDROID_VM_INSTANCE),
271 _ => Err(format!("Invalid partition type {}", s)),
272 }
273}
274
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000275fn parse_cpu_topology(s: &str) -> Result<CpuTopology, String> {
276 match s {
277 "one_cpu" => Ok(CpuTopology::ONE_CPU),
278 "match_host" => Ok(CpuTopology::MATCH_HOST),
279 _ => Err(format!("Invalid cpu topology {}", s)),
280 }
281}
282
Alan Stokesc4d5def2023-02-14 17:01:59 +0000283fn get_service() -> Result<Strong<dyn IVirtualizationService>, Error> {
284 let virtmgr =
285 vmclient::VirtualizationService::new().context("Failed to spawn VirtualizationService")?;
286 virtmgr.connect().context("Failed to connect to VirtualizationService")
287}
288
Andrew Walbranea9fa482021-03-04 16:11:12 +0000289fn main() -> Result<(), Error> {
290 env_logger::init();
Victor Hsiehb5bcfab2022-09-12 13:06:26 -0700291 let opt = Opt::parse();
Andrew Walbranea9fa482021-03-04 16:11:12 +0000292
293 // We need to start the thread pool for Binder to work properly, especially link_to_death.
294 ProcessState::start_thread_pool();
295
David Brazdil20412d92021-03-18 10:53:06 +0000296 match opt {
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900297 Opt::RunApp { config } => command_run_app(config),
298 Opt::RunMicrodroid { config } => command_run_microdroid(config),
299 Opt::Run { config } => command_run(config),
Alan Stokesc4d5def2023-02-14 17:01:59 +0000300 Opt::List => command_list(get_service()?.as_ref()),
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000301 Opt::Info => command_info(),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900302 Opt::CreatePartition { path, size, partition_type } => {
Alan Stokesc4d5def2023-02-14 17:01:59 +0000303 command_create_partition(get_service()?.as_ref(), &path, size, partition_type)
Jiyong Park9dd389e2021-08-23 20:42:59 +0900304 }
Alan Stokesc4d5def2023-02-14 17:01:59 +0000305 Opt::CreateIdsig { apk, path } => {
306 command_create_idsig(get_service()?.as_ref(), &apk, &path)
307 }
Andrew Walbranea9fa482021-03-04 16:11:12 +0000308 }
309}
310
Andrew Walbran320b5602021-03-04 16:11:12 +0000311/// List the VMs currently running.
Andrew Walbran616d13f2022-05-12 18:35:55 +0000312fn command_list(service: &dyn IVirtualizationService) -> Result<(), Error> {
Andrew Walbran17de24f2021-05-27 13:27:30 +0000313 let vms = service.debugListVms().context("Failed to get list of VMs")?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000314 println!("Running VMs: {:#?}", vms);
315 Ok(())
316}
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000317
318/// Print information about supported VM types.
319fn command_info() -> Result<(), Error> {
Alan Stokesc4d5def2023-02-14 17:01:59 +0000320 let non_protected_vm_supported = hypervisor_props::is_vm_supported()?;
321 let protected_vm_supported = hypervisor_props::is_protected_vm_supported()?;
Alan Stokes8d39a9b2023-01-10 15:01:00 +0000322 match (non_protected_vm_supported, protected_vm_supported) {
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000323 (false, false) => println!("VMs are not supported."),
324 (false, true) => println!("Only protected VMs are supported."),
Alan Stokes8d39a9b2023-01-10 15:01:00 +0000325 (true, false) => println!("Only non-protected VMs are supported."),
326 (true, true) => println!("Both protected and non-protected VMs are supported."),
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000327 }
328
Alan Stokesc4d5def2023-02-14 17:01:59 +0000329 if let Some(version) = hypervisor_props::version()? {
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000330 println!("Hypervisor version: {}", version);
331 } else {
332 println!("Hypervisor version not set.");
333 }
334
335 if Path::new("/dev/kvm").exists() {
336 println!("/dev/kvm exists.");
337 } else {
338 println!("/dev/kvm does not exist.");
339 }
340
Inseob Kim6ef80972023-07-20 17:23:36 +0900341 if Path::new("/dev/vfio/vfio").exists() {
342 println!("/dev/vfio/vfio exists.");
343 } else {
344 println!("/dev/vfio/vfio does not exist.");
345 }
346
347 if Path::new("/sys/bus/platform/drivers/vfio-platform").exists() {
348 println!("VFIO-platform is supported.");
349 } else {
350 println!("VFIO-platform is not supported.");
351 }
352
Inseob Kim75460b32023-08-09 13:41:31 +0900353 let devices = get_service()?.getAssignableDevices()?;
354 let devices = devices.into_iter().map(|x| x.node).collect::<Vec<_>>();
355 println!("Assignable devices: {}", serde_json::to_string(&devices)?);
356
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000357 Ok(())
358}
Andrew Walbran1f810b62022-08-10 13:33:57 +0000359
360#[cfg(test)]
361mod tests {
362 use super::*;
Andrew Walbranaa1efc42022-08-10 13:33:57 +0000363 use clap::CommandFactory;
Andrew Walbran1f810b62022-08-10 13:33:57 +0000364
365 #[test]
366 fn verify_app() {
Andrew Walbranaa1efc42022-08-10 13:33:57 +0000367 // Check that the command parsing has been configured in a valid way.
368 Opt::command().debug_assert();
Andrew Walbran1f810b62022-08-10 13:33:57 +0000369 }
370}