blob: 355e193142fb841ebc1c2c713381b00dc0f98549 [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
Alan Stokesfda70842023-12-20 17:50:14 +000037#[derive(Args, Default)]
Jiyong Parkb1935ef2023-08-10 17:22:39 +090038/// 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
Jiyong Parkb1935ef2023-08-10 17:22:39 +090048 /// Memory size (in MiB) of the VM. If unspecified, defaults to the value of `memory_mib`
49 /// in the VM config file.
50 #[arg(short, long)]
51 mem: Option<u32>,
52
53 /// Run VM in protected mode.
54 #[arg(short, long)]
55 protected: bool,
56}
57
Alan Stokesfda70842023-12-20 17:50:14 +000058#[derive(Args, Default)]
Jiyong Parkb1935ef2023-08-10 17:22:39 +090059/// Collection of flags for debugging
60pub struct DebugConfig {
61 /// Debug level of the VM. Supported values: "full" (default), and "none".
62 #[arg(long, default_value = "full", value_parser = parse_debug_level)]
63 debug: DebugLevel,
64
65 /// Path to file for VM console output.
66 #[arg(long)]
67 console: Option<PathBuf>,
68
69 /// Path to file for VM console input.
70 #[arg(long)]
71 console_in: Option<PathBuf>,
72
73 /// Path to file for VM log output.
74 #[arg(long)]
75 log: Option<PathBuf>,
76
77 /// Port at which crosvm will start a gdb server to debug guest kernel.
78 /// Note: this is only supported on Android kernels android14-5.15 and higher.
79 #[arg(long)]
80 gdb: Option<NonZeroU16>,
81}
82
Alan Stokesfda70842023-12-20 17:50:14 +000083#[derive(Args, Default)]
Jiyong Parkb1935ef2023-08-10 17:22:39 +090084/// Collection of flags that are Microdroid specific
85pub struct MicrodroidConfig {
86 /// Path to the file backing the storage.
87 /// Created if the option is used but the path does not exist in the device.
88 #[arg(long)]
89 storage: Option<PathBuf>,
90
91 /// Size of the storage. Used only if --storage is supplied but path does not exist
92 /// Default size is 10*1024*1024
93 #[arg(long)]
94 storage_size: Option<u64>,
95
Jiyong Parkb1935ef2023-08-10 17:22:39 +090096 /// Path to disk image containing vendor-specific modules.
Nikita Ioffe631717e2023-09-05 13:38:07 +010097 #[cfg(vendor_modules)]
Jiyong Parkb1935ef2023-08-10 17:22:39 +090098 #[arg(long)]
99 vendor: Option<PathBuf>,
100
101 /// SysFS nodes of devices to assign to VM
Nikita Ioffe94a8a182023-11-16 16:37:48 +0000102 #[cfg(device_assignment)]
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900103 #[arg(long)]
104 devices: Vec<PathBuf>,
Inseob Kim172f9eb2023-11-06 17:02:08 +0900105
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900106 /// Version of GKI to use. If set, use instead of microdroid kernel
Inseob Kim172f9eb2023-11-06 17:02:08 +0900107 #[cfg(vendor_modules)]
108 #[arg(long)]
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900109 gki: Option<String>,
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900110}
111
Nikita Ioffe631717e2023-09-05 13:38:07 +0100112impl MicrodroidConfig {
113 #[cfg(vendor_modules)]
Nikita Ioffe631717e2023-09-05 13:38:07 +0100114 fn vendor(&self) -> &Option<PathBuf> {
115 &self.vendor
116 }
117
118 #[cfg(not(vendor_modules))]
Nikita Ioffe631717e2023-09-05 13:38:07 +0100119 fn vendor(&self) -> Option<PathBuf> {
120 None
121 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +0000122
Inseob Kim172f9eb2023-11-06 17:02:08 +0900123 #[cfg(vendor_modules)]
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900124 fn gki(&self) -> Option<&str> {
125 self.gki.as_deref()
Inseob Kim172f9eb2023-11-06 17:02:08 +0900126 }
127
128 #[cfg(not(vendor_modules))]
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900129 fn gki(&self) -> Option<&str> {
130 None
Inseob Kim172f9eb2023-11-06 17:02:08 +0900131 }
132
Nikita Ioffe94a8a182023-11-16 16:37:48 +0000133 #[cfg(device_assignment)]
134 fn devices(&self) -> &Vec<PathBuf> {
135 &self.devices
136 }
137
138 #[cfg(not(device_assignment))]
139 fn devices(&self) -> Vec<PathBuf> {
140 Vec::new()
141 }
Nikita Ioffe631717e2023-09-05 13:38:07 +0100142}
143
Alan Stokesfda70842023-12-20 17:50:14 +0000144#[derive(Args, Default)]
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900145/// Flags for the run_app subcommand
146pub struct RunAppConfig {
147 #[command(flatten)]
148 common: CommonConfig,
149
150 #[command(flatten)]
151 debug: DebugConfig,
152
153 #[command(flatten)]
154 microdroid: MicrodroidConfig,
155
156 /// Path to VM Payload APK
157 apk: PathBuf,
158
159 /// Path to idsig of the APK
160 idsig: PathBuf,
161
162 /// Path to the instance image. Created if not exists.
163 instance: PathBuf,
164
165 /// Path to VM config JSON within APK (e.g. assets/vm_config.json)
166 #[arg(long)]
167 config_path: Option<String>,
168
169 /// Name of VM payload binary within APK (e.g. MicrodroidTestNativeLib.so)
170 #[arg(long)]
171 #[arg(alias = "payload_path")]
172 payload_binary_name: Option<String>,
173
Alan Stokesfda70842023-12-20 17:50:14 +0000174 /// Paths to extra apk files.
175 #[cfg(multi_tenant)]
176 #[arg(long = "extra-apk")]
177 #[clap(conflicts_with = "config_path")]
178 extra_apks: Vec<PathBuf>,
179
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900180 /// Paths to extra idsig files.
181 #[arg(long = "extra-idsig")]
182 extra_idsigs: Vec<PathBuf>,
183}
184
Alan Stokesfda70842023-12-20 17:50:14 +0000185impl RunAppConfig {
186 #[cfg(multi_tenant)]
187 fn extra_apks(&self) -> &[PathBuf] {
188 &self.extra_apks
189 }
190
191 #[cfg(not(multi_tenant))]
192 fn extra_apks(&self) -> &[PathBuf] {
193 &[]
194 }
195}
196
197#[derive(Args, Default)]
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900198/// Flags for the run_microdroid subcommand
199pub struct RunMicrodroidConfig {
200 #[command(flatten)]
201 common: CommonConfig,
202
203 #[command(flatten)]
204 debug: DebugConfig,
205
206 #[command(flatten)]
207 microdroid: MicrodroidConfig,
208
209 /// Path to the directory where VM-related files (e.g. instance.img, apk.idsig, etc.) will
210 /// be stored. If not specified a random directory under /data/local/tmp/microdroid will be
211 /// created and used.
212 #[arg(long)]
213 work_dir: Option<PathBuf>,
214}
215
Alan Stokesfda70842023-12-20 17:50:14 +0000216#[derive(Args, Default)]
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900217/// Flags for the run subcommand
218pub struct RunCustomVmConfig {
219 #[command(flatten)]
220 common: CommonConfig,
221
222 #[command(flatten)]
223 debug: DebugConfig,
224
225 /// Path to VM config JSON
226 config: PathBuf,
227}
228
Victor Hsiehb5bcfab2022-09-12 13:06:26 -0700229#[derive(Parser)]
David Brazdil20412d92021-03-18 10:53:06 +0000230enum Opt {
Shikha Panwar6d306412024-02-17 21:37:49 +0000231 /// Check if the feature is enabled on device.
232 CheckFeatureEnabled { feature: String },
Jooyung Han21e9b922021-06-26 04:14:16 +0900233 /// Run a virtual machine with a config in APK
234 RunApp {
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900235 #[command(flatten)]
236 config: RunAppConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +0900237 },
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000238 /// Run a virtual machine with Microdroid inside
239 RunMicrodroid {
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900240 #[command(flatten)]
241 config: RunMicrodroidConfig,
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000242 },
David Brazdil20412d92021-03-18 10:53:06 +0000243 /// Run a virtual machine
244 Run {
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900245 #[command(flatten)]
246 config: RunCustomVmConfig,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000247 },
David Brazdil20412d92021-03-18 10:53:06 +0000248 /// List running virtual machines
249 List,
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000250 /// Print information about virtual machine support
251 Info,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000252 /// Create a new empty partition to be used as a writable partition for a VM
253 CreatePartition {
254 /// Path at which to create the image file
Andrew Walbrandff3b942021-06-09 15:20:36 +0000255 path: PathBuf,
256
257 /// The desired size of the partition, in bytes.
258 size: u64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900259
260 /// Type of the partition
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900261 #[arg(short = 't', long = "type", default_value = "raw",
Victor Hsiehb5bcfab2022-09-12 13:06:26 -0700262 value_parser = parse_partition_type)]
Jiyong Park9dd389e2021-08-23 20:42:59 +0900263 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000264 },
Jooyung Hanc221c052022-02-22 05:20:15 +0900265 /// Creates or update the idsig file by digesting the input APK file.
266 CreateIdsig {
267 /// Path to VM Payload APK
Jooyung Hanc221c052022-02-22 05:20:15 +0900268 apk: PathBuf,
Victor Hsiehb5bcfab2022-09-12 13:06:26 -0700269
Jooyung Hanc221c052022-02-22 05:20:15 +0900270 /// Path to idsig of the APK
Jooyung Hanc221c052022-02-22 05:20:15 +0900271 path: PathBuf,
272 },
David Brazdil20412d92021-03-18 10:53:06 +0000273}
274
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900275fn parse_debug_level(s: &str) -> Result<DebugLevel, String> {
276 match s {
277 "none" => Ok(DebugLevel::NONE),
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900278 "full" => Ok(DebugLevel::FULL),
279 _ => Err(format!("Invalid debug level {}", s)),
280 }
281}
282
Jiyong Park9dd389e2021-08-23 20:42:59 +0900283fn parse_partition_type(s: &str) -> Result<PartitionType, String> {
284 match s {
285 "raw" => Ok(PartitionType::RAW),
286 "instance" => Ok(PartitionType::ANDROID_VM_INSTANCE),
287 _ => Err(format!("Invalid partition type {}", s)),
288 }
289}
290
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000291fn parse_cpu_topology(s: &str) -> Result<CpuTopology, String> {
292 match s {
293 "one_cpu" => Ok(CpuTopology::ONE_CPU),
294 "match_host" => Ok(CpuTopology::MATCH_HOST),
295 _ => Err(format!("Invalid cpu topology {}", s)),
296 }
297}
298
Alan Stokesc4d5def2023-02-14 17:01:59 +0000299fn get_service() -> Result<Strong<dyn IVirtualizationService>, Error> {
300 let virtmgr =
301 vmclient::VirtualizationService::new().context("Failed to spawn VirtualizationService")?;
302 virtmgr.connect().context("Failed to connect to VirtualizationService")
303}
304
Shikha Panwar6d306412024-02-17 21:37:49 +0000305fn command_check_feature_enabled(feature: &str) {
306 println!(
307 "Feature {feature} is {}",
308 if avf_features::is_feature_enabled(feature) { "enabled" } else { "disabled" }
309 );
310}
311
Andrew Walbranea9fa482021-03-04 16:11:12 +0000312fn main() -> Result<(), Error> {
313 env_logger::init();
Victor Hsiehb5bcfab2022-09-12 13:06:26 -0700314 let opt = Opt::parse();
Andrew Walbranea9fa482021-03-04 16:11:12 +0000315
316 // We need to start the thread pool for Binder to work properly, especially link_to_death.
317 ProcessState::start_thread_pool();
318
David Brazdil20412d92021-03-18 10:53:06 +0000319 match opt {
Shikha Panwar6d306412024-02-17 21:37:49 +0000320 Opt::CheckFeatureEnabled { feature } => {
321 command_check_feature_enabled(&feature);
322 Ok(())
323 }
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900324 Opt::RunApp { config } => command_run_app(config),
325 Opt::RunMicrodroid { config } => command_run_microdroid(config),
326 Opt::Run { config } => command_run(config),
Alan Stokesc4d5def2023-02-14 17:01:59 +0000327 Opt::List => command_list(get_service()?.as_ref()),
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000328 Opt::Info => command_info(),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900329 Opt::CreatePartition { path, size, partition_type } => {
Alan Stokesc4d5def2023-02-14 17:01:59 +0000330 command_create_partition(get_service()?.as_ref(), &path, size, partition_type)
Jiyong Park9dd389e2021-08-23 20:42:59 +0900331 }
Alan Stokesc4d5def2023-02-14 17:01:59 +0000332 Opt::CreateIdsig { apk, path } => {
333 command_create_idsig(get_service()?.as_ref(), &apk, &path)
334 }
Andrew Walbranea9fa482021-03-04 16:11:12 +0000335 }
336}
337
Andrew Walbran320b5602021-03-04 16:11:12 +0000338/// List the VMs currently running.
Andrew Walbran616d13f2022-05-12 18:35:55 +0000339fn command_list(service: &dyn IVirtualizationService) -> Result<(), Error> {
Andrew Walbran17de24f2021-05-27 13:27:30 +0000340 let vms = service.debugListVms().context("Failed to get list of VMs")?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000341 println!("Running VMs: {:#?}", vms);
342 Ok(())
343}
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000344
345/// Print information about supported VM types.
346fn command_info() -> Result<(), Error> {
Alan Stokesc4d5def2023-02-14 17:01:59 +0000347 let non_protected_vm_supported = hypervisor_props::is_vm_supported()?;
348 let protected_vm_supported = hypervisor_props::is_protected_vm_supported()?;
Alan Stokes8d39a9b2023-01-10 15:01:00 +0000349 match (non_protected_vm_supported, protected_vm_supported) {
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000350 (false, false) => println!("VMs are not supported."),
351 (false, true) => println!("Only protected VMs are supported."),
Alan Stokes8d39a9b2023-01-10 15:01:00 +0000352 (true, false) => println!("Only non-protected VMs are supported."),
353 (true, true) => println!("Both protected and non-protected VMs are supported."),
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000354 }
355
Alan Stokesc4d5def2023-02-14 17:01:59 +0000356 if let Some(version) = hypervisor_props::version()? {
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000357 println!("Hypervisor version: {}", version);
358 } else {
359 println!("Hypervisor version not set.");
360 }
361
362 if Path::new("/dev/kvm").exists() {
363 println!("/dev/kvm exists.");
364 } else {
365 println!("/dev/kvm does not exist.");
366 }
367
Inseob Kim6ef80972023-07-20 17:23:36 +0900368 if Path::new("/dev/vfio/vfio").exists() {
369 println!("/dev/vfio/vfio exists.");
370 } else {
371 println!("/dev/vfio/vfio does not exist.");
372 }
373
374 if Path::new("/sys/bus/platform/drivers/vfio-platform").exists() {
375 println!("VFIO-platform is supported.");
376 } else {
377 println!("VFIO-platform is not supported.");
378 }
379
Inseob Kim75460b32023-08-09 13:41:31 +0900380 let devices = get_service()?.getAssignableDevices()?;
381 let devices = devices.into_iter().map(|x| x.node).collect::<Vec<_>>();
382 println!("Assignable devices: {}", serde_json::to_string(&devices)?);
383
Inseob Kim46257382024-01-03 15:41:22 +0900384 let os_list = get_service()?.getSupportedOSList()?;
385 println!("Available OS list: {}", serde_json::to_string(&os_list)?);
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900386
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000387 Ok(())
388}
Andrew Walbran1f810b62022-08-10 13:33:57 +0000389
390#[cfg(test)]
391mod tests {
392 use super::*;
Andrew Walbranaa1efc42022-08-10 13:33:57 +0000393 use clap::CommandFactory;
Andrew Walbran1f810b62022-08-10 13:33:57 +0000394
395 #[test]
396 fn verify_app() {
Andrew Walbranaa1efc42022-08-10 13:33:57 +0000397 // Check that the command parsing has been configured in a valid way.
398 Opt::command().debug_assert();
Andrew Walbran1f810b62022-08-10 13:33:57 +0000399 }
400}