blob: 9a92f135de3c0dcb8a593ae0dfa0551bde186e17 [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;
Inseob Kim7a1fc8f2023-11-22 18:45:28 +090030use glob::glob;
Nikita Ioffeb0b67562022-11-22 15:48:06 +000031use run::{command_run, command_run_app, command_run_microdroid};
Nikita Ioffe5776f082023-02-10 21:38:26 +000032use std::num::NonZeroU16;
Andrew Walbranc4b1bde2022-02-03 15:26:02 +000033use std::path::{Path, PathBuf};
Andrew Walbranea9fa482021-03-04 16:11:12 +000034
Inseob Kima5a262f2021-11-17 19:41:03 +090035#[derive(Debug)]
36struct Idsigs(Vec<PathBuf>);
37
Jiyong Parkb1935ef2023-08-10 17:22:39 +090038#[derive(Args)]
39/// Collection of flags that are at VM level and therefore applicable to all subcommands
40pub struct CommonConfig {
41 /// Name of VM
42 #[arg(long)]
43 name: Option<String>,
44
45 /// Run VM with vCPU topology matching that of the host. If unspecified, defaults to 1 vCPU.
46 #[arg(long, default_value = "one_cpu", value_parser = parse_cpu_topology)]
47 cpu_topology: CpuTopology,
48
49 /// Comma separated list of task profile names to apply to the VM
50 #[arg(long)]
51 task_profiles: Vec<String>,
52
53 /// Memory size (in MiB) of the VM. If unspecified, defaults to the value of `memory_mib`
54 /// in the VM config file.
55 #[arg(short, long)]
56 mem: Option<u32>,
57
58 /// Run VM in protected mode.
59 #[arg(short, long)]
60 protected: bool,
61}
62
63#[derive(Args)]
64/// Collection of flags for debugging
65pub struct DebugConfig {
66 /// Debug level of the VM. Supported values: "full" (default), and "none".
67 #[arg(long, default_value = "full", value_parser = parse_debug_level)]
68 debug: DebugLevel,
69
70 /// Path to file for VM console output.
71 #[arg(long)]
72 console: Option<PathBuf>,
73
74 /// Path to file for VM console input.
75 #[arg(long)]
76 console_in: Option<PathBuf>,
77
78 /// Path to file for VM log output.
79 #[arg(long)]
80 log: Option<PathBuf>,
81
82 /// Port at which crosvm will start a gdb server to debug guest kernel.
83 /// Note: this is only supported on Android kernels android14-5.15 and higher.
84 #[arg(long)]
85 gdb: Option<NonZeroU16>,
86}
87
88#[derive(Args)]
89/// Collection of flags that are Microdroid specific
90pub struct MicrodroidConfig {
91 /// Path to the file backing the storage.
92 /// Created if the option is used but the path does not exist in the device.
93 #[arg(long)]
94 storage: Option<PathBuf>,
95
96 /// Size of the storage. Used only if --storage is supplied but path does not exist
97 /// Default size is 10*1024*1024
98 #[arg(long)]
99 storage_size: Option<u64>,
100
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900101 /// Path to disk image containing vendor-specific modules.
Nikita Ioffe631717e2023-09-05 13:38:07 +0100102 #[cfg(vendor_modules)]
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900103 #[arg(long)]
104 vendor: Option<PathBuf>,
105
106 /// SysFS nodes of devices to assign to VM
Nikita Ioffe94a8a182023-11-16 16:37:48 +0000107 #[cfg(device_assignment)]
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900108 #[arg(long)]
109 devices: Vec<PathBuf>,
Inseob Kim172f9eb2023-11-06 17:02:08 +0900110
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900111 /// Version of GKI to use. If set, use instead of microdroid kernel
Inseob Kim172f9eb2023-11-06 17:02:08 +0900112 #[cfg(vendor_modules)]
113 #[arg(long)]
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900114 gki: Option<String>,
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900115}
116
Nikita Ioffe631717e2023-09-05 13:38:07 +0100117impl MicrodroidConfig {
118 #[cfg(vendor_modules)]
Nikita Ioffe631717e2023-09-05 13:38:07 +0100119 fn vendor(&self) -> &Option<PathBuf> {
120 &self.vendor
121 }
122
123 #[cfg(not(vendor_modules))]
Nikita Ioffe631717e2023-09-05 13:38:07 +0100124 fn vendor(&self) -> Option<PathBuf> {
125 None
126 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +0000127
Inseob Kim172f9eb2023-11-06 17:02:08 +0900128 #[cfg(vendor_modules)]
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900129 fn gki(&self) -> Option<&str> {
130 self.gki.as_deref()
Inseob Kim172f9eb2023-11-06 17:02:08 +0900131 }
132
133 #[cfg(not(vendor_modules))]
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900134 fn gki(&self) -> Option<&str> {
135 None
Inseob Kim172f9eb2023-11-06 17:02:08 +0900136 }
137
Nikita Ioffe94a8a182023-11-16 16:37:48 +0000138 #[cfg(device_assignment)]
139 fn devices(&self) -> &Vec<PathBuf> {
140 &self.devices
141 }
142
143 #[cfg(not(device_assignment))]
144 fn devices(&self) -> Vec<PathBuf> {
145 Vec::new()
146 }
Nikita Ioffe631717e2023-09-05 13:38:07 +0100147}
148
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900149#[derive(Args)]
150/// Flags for the run_app subcommand
151pub struct RunAppConfig {
152 #[command(flatten)]
153 common: CommonConfig,
154
155 #[command(flatten)]
156 debug: DebugConfig,
157
158 #[command(flatten)]
159 microdroid: MicrodroidConfig,
160
161 /// Path to VM Payload APK
162 apk: PathBuf,
163
164 /// Path to idsig of the APK
165 idsig: PathBuf,
166
167 /// Path to the instance image. Created if not exists.
168 instance: PathBuf,
169
170 /// Path to VM config JSON within APK (e.g. assets/vm_config.json)
171 #[arg(long)]
172 config_path: Option<String>,
173
174 /// Name of VM payload binary within APK (e.g. MicrodroidTestNativeLib.so)
175 #[arg(long)]
176 #[arg(alias = "payload_path")]
177 payload_binary_name: Option<String>,
178
179 /// Paths to extra idsig files.
180 #[arg(long = "extra-idsig")]
181 extra_idsigs: Vec<PathBuf>,
182}
183
184#[derive(Args)]
185/// Flags for the run_microdroid subcommand
186pub struct RunMicrodroidConfig {
187 #[command(flatten)]
188 common: CommonConfig,
189
190 #[command(flatten)]
191 debug: DebugConfig,
192
193 #[command(flatten)]
194 microdroid: MicrodroidConfig,
195
196 /// Path to the directory where VM-related files (e.g. instance.img, apk.idsig, etc.) will
197 /// be stored. If not specified a random directory under /data/local/tmp/microdroid will be
198 /// created and used.
199 #[arg(long)]
200 work_dir: Option<PathBuf>,
201}
202
203#[derive(Args)]
204/// Flags for the run subcommand
205pub struct RunCustomVmConfig {
206 #[command(flatten)]
207 common: CommonConfig,
208
209 #[command(flatten)]
210 debug: DebugConfig,
211
212 /// Path to VM config JSON
213 config: PathBuf,
214}
215
Victor Hsiehb5bcfab2022-09-12 13:06:26 -0700216#[derive(Parser)]
David Brazdil20412d92021-03-18 10:53:06 +0000217enum Opt {
Jooyung Han21e9b922021-06-26 04:14:16 +0900218 /// Run a virtual machine with a config in APK
219 RunApp {
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900220 #[command(flatten)]
221 config: RunAppConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +0900222 },
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000223 /// Run a virtual machine with Microdroid inside
224 RunMicrodroid {
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900225 #[command(flatten)]
226 config: RunMicrodroidConfig,
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000227 },
David Brazdil20412d92021-03-18 10:53:06 +0000228 /// Run a virtual machine
229 Run {
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900230 #[command(flatten)]
231 config: RunCustomVmConfig,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000232 },
David Brazdil20412d92021-03-18 10:53:06 +0000233 /// List running virtual machines
234 List,
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000235 /// Print information about virtual machine support
236 Info,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000237 /// Create a new empty partition to be used as a writable partition for a VM
238 CreatePartition {
239 /// Path at which to create the image file
Andrew Walbrandff3b942021-06-09 15:20:36 +0000240 path: PathBuf,
241
242 /// The desired size of the partition, in bytes.
243 size: u64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900244
245 /// Type of the partition
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900246 #[arg(short = 't', long = "type", default_value = "raw",
Victor Hsiehb5bcfab2022-09-12 13:06:26 -0700247 value_parser = parse_partition_type)]
Jiyong Park9dd389e2021-08-23 20:42:59 +0900248 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000249 },
Jooyung Hanc221c052022-02-22 05:20:15 +0900250 /// Creates or update the idsig file by digesting the input APK file.
251 CreateIdsig {
252 /// Path to VM Payload APK
Jooyung Hanc221c052022-02-22 05:20:15 +0900253 apk: PathBuf,
Victor Hsiehb5bcfab2022-09-12 13:06:26 -0700254
Jooyung Hanc221c052022-02-22 05:20:15 +0900255 /// Path to idsig of the APK
Jooyung Hanc221c052022-02-22 05:20:15 +0900256 path: PathBuf,
257 },
David Brazdil20412d92021-03-18 10:53:06 +0000258}
259
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900260fn parse_debug_level(s: &str) -> Result<DebugLevel, String> {
261 match s {
262 "none" => Ok(DebugLevel::NONE),
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900263 "full" => Ok(DebugLevel::FULL),
264 _ => Err(format!("Invalid debug level {}", s)),
265 }
266}
267
Jiyong Park9dd389e2021-08-23 20:42:59 +0900268fn parse_partition_type(s: &str) -> Result<PartitionType, String> {
269 match s {
270 "raw" => Ok(PartitionType::RAW),
271 "instance" => Ok(PartitionType::ANDROID_VM_INSTANCE),
272 _ => Err(format!("Invalid partition type {}", s)),
273 }
274}
275
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000276fn parse_cpu_topology(s: &str) -> Result<CpuTopology, String> {
277 match s {
278 "one_cpu" => Ok(CpuTopology::ONE_CPU),
279 "match_host" => Ok(CpuTopology::MATCH_HOST),
280 _ => Err(format!("Invalid cpu topology {}", s)),
281 }
282}
283
Alan Stokesc4d5def2023-02-14 17:01:59 +0000284fn get_service() -> Result<Strong<dyn IVirtualizationService>, Error> {
285 let virtmgr =
286 vmclient::VirtualizationService::new().context("Failed to spawn VirtualizationService")?;
287 virtmgr.connect().context("Failed to connect to VirtualizationService")
288}
289
Andrew Walbranea9fa482021-03-04 16:11:12 +0000290fn main() -> Result<(), Error> {
291 env_logger::init();
Victor Hsiehb5bcfab2022-09-12 13:06:26 -0700292 let opt = Opt::parse();
Andrew Walbranea9fa482021-03-04 16:11:12 +0000293
294 // We need to start the thread pool for Binder to work properly, especially link_to_death.
295 ProcessState::start_thread_pool();
296
David Brazdil20412d92021-03-18 10:53:06 +0000297 match opt {
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900298 Opt::RunApp { config } => command_run_app(config),
299 Opt::RunMicrodroid { config } => command_run_microdroid(config),
300 Opt::Run { config } => command_run(config),
Alan Stokesc4d5def2023-02-14 17:01:59 +0000301 Opt::List => command_list(get_service()?.as_ref()),
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000302 Opt::Info => command_info(),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900303 Opt::CreatePartition { path, size, partition_type } => {
Alan Stokesc4d5def2023-02-14 17:01:59 +0000304 command_create_partition(get_service()?.as_ref(), &path, size, partition_type)
Jiyong Park9dd389e2021-08-23 20:42:59 +0900305 }
Alan Stokesc4d5def2023-02-14 17:01:59 +0000306 Opt::CreateIdsig { apk, path } => {
307 command_create_idsig(get_service()?.as_ref(), &apk, &path)
308 }
Andrew Walbranea9fa482021-03-04 16:11:12 +0000309 }
310}
311
Andrew Walbran320b5602021-03-04 16:11:12 +0000312/// List the VMs currently running.
Andrew Walbran616d13f2022-05-12 18:35:55 +0000313fn command_list(service: &dyn IVirtualizationService) -> Result<(), Error> {
Andrew Walbran17de24f2021-05-27 13:27:30 +0000314 let vms = service.debugListVms().context("Failed to get list of VMs")?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000315 println!("Running VMs: {:#?}", vms);
316 Ok(())
317}
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000318
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900319fn extract_gki_version(gki_config: &Path) -> Option<&str> {
320 let name = gki_config.file_name()?;
321 let name_str = name.to_str()?;
322 name_str.strip_prefix("microdroid_gki-")?.strip_suffix(".json")
323}
324
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000325/// Print information about supported VM types.
326fn command_info() -> Result<(), Error> {
Alan Stokesc4d5def2023-02-14 17:01:59 +0000327 let non_protected_vm_supported = hypervisor_props::is_vm_supported()?;
328 let protected_vm_supported = hypervisor_props::is_protected_vm_supported()?;
Alan Stokes8d39a9b2023-01-10 15:01:00 +0000329 match (non_protected_vm_supported, protected_vm_supported) {
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000330 (false, false) => println!("VMs are not supported."),
331 (false, true) => println!("Only protected VMs are supported."),
Alan Stokes8d39a9b2023-01-10 15:01:00 +0000332 (true, false) => println!("Only non-protected VMs are supported."),
333 (true, true) => println!("Both protected and non-protected VMs are supported."),
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000334 }
335
Alan Stokesc4d5def2023-02-14 17:01:59 +0000336 if let Some(version) = hypervisor_props::version()? {
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000337 println!("Hypervisor version: {}", version);
338 } else {
339 println!("Hypervisor version not set.");
340 }
341
342 if Path::new("/dev/kvm").exists() {
343 println!("/dev/kvm exists.");
344 } else {
345 println!("/dev/kvm does not exist.");
346 }
347
Inseob Kim6ef80972023-07-20 17:23:36 +0900348 if Path::new("/dev/vfio/vfio").exists() {
349 println!("/dev/vfio/vfio exists.");
350 } else {
351 println!("/dev/vfio/vfio does not exist.");
352 }
353
354 if Path::new("/sys/bus/platform/drivers/vfio-platform").exists() {
355 println!("VFIO-platform is supported.");
356 } else {
357 println!("VFIO-platform is not supported.");
358 }
359
Inseob Kim75460b32023-08-09 13:41:31 +0900360 let devices = get_service()?.getAssignableDevices()?;
361 let devices = devices.into_iter().map(|x| x.node).collect::<Vec<_>>();
362 println!("Assignable devices: {}", serde_json::to_string(&devices)?);
363
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900364 let gki_configs =
365 glob("/apex/com.android.virt/etc/microdroid_gki-*.json")?.collect::<Result<Vec<_>, _>>()?;
366 let gki_versions =
367 gki_configs.iter().filter_map(|x| extract_gki_version(x)).collect::<Vec<_>>();
368 println!("Available gki versions: {}", serde_json::to_string(&gki_versions)?);
369
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000370 Ok(())
371}
Andrew Walbran1f810b62022-08-10 13:33:57 +0000372
373#[cfg(test)]
374mod tests {
375 use super::*;
Andrew Walbranaa1efc42022-08-10 13:33:57 +0000376 use clap::CommandFactory;
Andrew Walbran1f810b62022-08-10 13:33:57 +0000377
378 #[test]
379 fn verify_app() {
Andrew Walbranaa1efc42022-08-10 13:33:57 +0000380 // Check that the command parsing has been configured in a valid way.
381 Opt::command().debug_assert();
Andrew Walbran1f810b62022-08-10 13:33:57 +0000382 }
383}