blob: 390a60d12376b4d380fa92dc121beab3d9a45c5c [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};
Shikha Panwar61a74b52024-02-16 13:17:01 +000025#[cfg(not(llpvm_changes))]
26use anyhow::anyhow;
David Brazdil20412d92021-03-18 10:53:06 +000027use anyhow::{Context, Error};
Alan Stokesc4d5def2023-02-14 17:01:59 +000028use binder::{ProcessState, Strong};
Jiyong Parkb1935ef2023-08-10 17:22:39 +090029use clap::{Args, Parser};
Jooyung Hanc221c052022-02-22 05:20:15 +090030use create_idsig::command_create_idsig;
Jiyong Park48b354d2021-07-15 15:04:38 +090031use create_partition::command_create_partition;
Nikita Ioffeb0b67562022-11-22 15:48:06 +000032use run::{command_run, command_run_app, command_run_microdroid};
Jaewan Kim0c99c612024-03-23 00:44:14 +090033use serde::Serialize;
Nikita Ioffe5776f082023-02-10 21:38:26 +000034use std::num::NonZeroU16;
Andrew Walbranc4b1bde2022-02-03 15:26:02 +000035use std::path::{Path, PathBuf};
Andrew Walbranea9fa482021-03-04 16:11:12 +000036
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,
Vincent Donnefort538a2c62024-03-20 16:01:10 +000056
57 /// Ask the kernel for transparent huge-pages (THP). This is only a hint and
58 /// the kernel will allocate THP-backed memory only if globally enabled by
59 /// the system and if any can be found. See
60 /// https://docs.kernel.org/admin-guide/mm/transhuge.html
61 #[arg(short, long)]
62 hugepages: bool,
Seungjae Yoo13af0b62024-05-20 14:15:13 +090063
64 /// Run VM with network feature.
65 #[cfg(network)]
66 #[arg(short, long)]
67 network_supported: bool,
68}
69
70impl CommonConfig {
71 #[cfg(network)]
72 fn network_supported(&self) -> bool {
73 self.network_supported
74 }
75
76 #[cfg(not(network))]
77 fn network_supported(&self) -> bool {
78 false
79 }
Jiyong Parkb1935ef2023-08-10 17:22:39 +090080}
81
Alan Stokesfda70842023-12-20 17:50:14 +000082#[derive(Args, Default)]
Jiyong Parkb1935ef2023-08-10 17:22:39 +090083/// Collection of flags for debugging
84pub struct DebugConfig {
85 /// Debug level of the VM. Supported values: "full" (default), and "none".
86 #[arg(long, default_value = "full", value_parser = parse_debug_level)]
87 debug: DebugLevel,
88
89 /// Path to file for VM console output.
90 #[arg(long)]
91 console: Option<PathBuf>,
92
93 /// Path to file for VM console input.
94 #[arg(long)]
95 console_in: Option<PathBuf>,
96
97 /// Path to file for VM log output.
98 #[arg(long)]
99 log: Option<PathBuf>,
100
101 /// Port at which crosvm will start a gdb server to debug guest kernel.
102 /// Note: this is only supported on Android kernels android14-5.15 and higher.
103 #[arg(long)]
104 gdb: Option<NonZeroU16>,
105}
106
Alan Stokesfda70842023-12-20 17:50:14 +0000107#[derive(Args, Default)]
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900108/// Collection of flags that are Microdroid specific
109pub struct MicrodroidConfig {
110 /// Path to the file backing the storage.
111 /// Created if the option is used but the path does not exist in the device.
112 #[arg(long)]
113 storage: Option<PathBuf>,
114
115 /// Size of the storage. Used only if --storage is supplied but path does not exist
116 /// Default size is 10*1024*1024
117 #[arg(long)]
118 storage_size: Option<u64>,
119
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900120 /// Path to disk image containing vendor-specific modules.
Nikita Ioffe631717e2023-09-05 13:38:07 +0100121 #[cfg(vendor_modules)]
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900122 #[arg(long)]
123 vendor: Option<PathBuf>,
124
125 /// SysFS nodes of devices to assign to VM
Nikita Ioffe94a8a182023-11-16 16:37:48 +0000126 #[cfg(device_assignment)]
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900127 #[arg(long)]
128 devices: Vec<PathBuf>,
Inseob Kim172f9eb2023-11-06 17:02:08 +0900129
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900130 /// Version of GKI to use. If set, use instead of microdroid kernel
Inseob Kim172f9eb2023-11-06 17:02:08 +0900131 #[cfg(vendor_modules)]
132 #[arg(long)]
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900133 gki: Option<String>,
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900134}
135
Nikita Ioffe631717e2023-09-05 13:38:07 +0100136impl MicrodroidConfig {
137 #[cfg(vendor_modules)]
Nikita Ioffe631717e2023-09-05 13:38:07 +0100138 fn vendor(&self) -> &Option<PathBuf> {
139 &self.vendor
140 }
141
142 #[cfg(not(vendor_modules))]
Nikita Ioffe631717e2023-09-05 13:38:07 +0100143 fn vendor(&self) -> Option<PathBuf> {
144 None
145 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +0000146
Inseob Kim172f9eb2023-11-06 17:02:08 +0900147 #[cfg(vendor_modules)]
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900148 fn gki(&self) -> Option<&str> {
149 self.gki.as_deref()
Inseob Kim172f9eb2023-11-06 17:02:08 +0900150 }
151
152 #[cfg(not(vendor_modules))]
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900153 fn gki(&self) -> Option<&str> {
154 None
Inseob Kim172f9eb2023-11-06 17:02:08 +0900155 }
156
Nikita Ioffe94a8a182023-11-16 16:37:48 +0000157 #[cfg(device_assignment)]
158 fn devices(&self) -> &Vec<PathBuf> {
159 &self.devices
160 }
161
162 #[cfg(not(device_assignment))]
163 fn devices(&self) -> Vec<PathBuf> {
164 Vec::new()
165 }
Nikita Ioffe631717e2023-09-05 13:38:07 +0100166}
167
Alan Stokesfda70842023-12-20 17:50:14 +0000168#[derive(Args, Default)]
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900169/// Flags for the run_app subcommand
170pub struct RunAppConfig {
171 #[command(flatten)]
172 common: CommonConfig,
173
174 #[command(flatten)]
175 debug: DebugConfig,
176
177 #[command(flatten)]
178 microdroid: MicrodroidConfig,
179
180 /// Path to VM Payload APK
181 apk: PathBuf,
182
183 /// Path to idsig of the APK
184 idsig: PathBuf,
185
186 /// Path to the instance image. Created if not exists.
187 instance: PathBuf,
188
Shikha Panwar61a74b52024-02-16 13:17:01 +0000189 /// Path to file containing instance_id. Required iff llpvm feature is enabled.
190 #[cfg(llpvm_changes)]
191 #[arg(long = "instance-id-file")]
192 instance_id: PathBuf,
193
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900194 /// Path to VM config JSON within APK (e.g. assets/vm_config.json)
195 #[arg(long)]
196 config_path: Option<String>,
197
198 /// Name of VM payload binary within APK (e.g. MicrodroidTestNativeLib.so)
199 #[arg(long)]
200 #[arg(alias = "payload_path")]
201 payload_binary_name: Option<String>,
202
Alan Stokesfda70842023-12-20 17:50:14 +0000203 /// Paths to extra apk files.
204 #[cfg(multi_tenant)]
205 #[arg(long = "extra-apk")]
206 #[clap(conflicts_with = "config_path")]
207 extra_apks: Vec<PathBuf>,
208
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900209 /// Paths to extra idsig files.
210 #[arg(long = "extra-idsig")]
211 extra_idsigs: Vec<PathBuf>,
212}
213
Alan Stokesfda70842023-12-20 17:50:14 +0000214impl RunAppConfig {
215 #[cfg(multi_tenant)]
216 fn extra_apks(&self) -> &[PathBuf] {
217 &self.extra_apks
218 }
219
220 #[cfg(not(multi_tenant))]
221 fn extra_apks(&self) -> &[PathBuf] {
222 &[]
223 }
Shikha Panwar61a74b52024-02-16 13:17:01 +0000224
225 #[cfg(llpvm_changes)]
226 fn instance_id(&self) -> Result<PathBuf, Error> {
227 Ok(self.instance_id.clone())
228 }
229
230 #[cfg(not(llpvm_changes))]
231 fn instance_id(&self) -> Result<PathBuf, Error> {
232 Err(anyhow!("LLPVM feature is disabled, --instance_id flag not supported"))
233 }
234
235 #[cfg(llpvm_changes)]
236 fn set_instance_id(&mut self, instance_id_file: PathBuf) -> Result<(), Error> {
237 self.instance_id = instance_id_file;
238 Ok(())
239 }
240
241 #[cfg(not(llpvm_changes))]
242 fn set_instance_id(&mut self, _: PathBuf) -> Result<(), Error> {
243 Err(anyhow!("LLPVM feature is disabled, --instance_id flag not supported"))
244 }
Alan Stokesfda70842023-12-20 17:50:14 +0000245}
246
247#[derive(Args, Default)]
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900248/// Flags for the run_microdroid subcommand
249pub struct RunMicrodroidConfig {
250 #[command(flatten)]
251 common: CommonConfig,
252
253 #[command(flatten)]
254 debug: DebugConfig,
255
256 #[command(flatten)]
257 microdroid: MicrodroidConfig,
258
259 /// Path to the directory where VM-related files (e.g. instance.img, apk.idsig, etc.) will
260 /// be stored. If not specified a random directory under /data/local/tmp/microdroid will be
261 /// created and used.
262 #[arg(long)]
263 work_dir: Option<PathBuf>,
264}
265
Alan Stokesfda70842023-12-20 17:50:14 +0000266#[derive(Args, Default)]
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900267/// Flags for the run subcommand
268pub struct RunCustomVmConfig {
269 #[command(flatten)]
270 common: CommonConfig,
271
272 #[command(flatten)]
273 debug: DebugConfig,
274
275 /// Path to VM config JSON
276 config: PathBuf,
277}
278
Victor Hsiehb5bcfab2022-09-12 13:06:26 -0700279#[derive(Parser)]
David Brazdil20412d92021-03-18 10:53:06 +0000280enum Opt {
Shikha Panwar6d306412024-02-17 21:37:49 +0000281 /// Check if the feature is enabled on device.
282 CheckFeatureEnabled { feature: String },
Jooyung Han21e9b922021-06-26 04:14:16 +0900283 /// Run a virtual machine with a config in APK
284 RunApp {
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900285 #[command(flatten)]
286 config: RunAppConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +0900287 },
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000288 /// Run a virtual machine with Microdroid inside
289 RunMicrodroid {
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900290 #[command(flatten)]
291 config: RunMicrodroidConfig,
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000292 },
David Brazdil20412d92021-03-18 10:53:06 +0000293 /// Run a virtual machine
294 Run {
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900295 #[command(flatten)]
296 config: RunCustomVmConfig,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000297 },
David Brazdil20412d92021-03-18 10:53:06 +0000298 /// List running virtual machines
299 List,
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000300 /// Print information about virtual machine support
301 Info,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000302 /// Create a new empty partition to be used as a writable partition for a VM
303 CreatePartition {
304 /// Path at which to create the image file
Andrew Walbrandff3b942021-06-09 15:20:36 +0000305 path: PathBuf,
306
307 /// The desired size of the partition, in bytes.
308 size: u64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900309
310 /// Type of the partition
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900311 #[arg(short = 't', long = "type", default_value = "raw",
Victor Hsiehb5bcfab2022-09-12 13:06:26 -0700312 value_parser = parse_partition_type)]
Jiyong Park9dd389e2021-08-23 20:42:59 +0900313 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000314 },
Jooyung Hanc221c052022-02-22 05:20:15 +0900315 /// Creates or update the idsig file by digesting the input APK file.
316 CreateIdsig {
317 /// Path to VM Payload APK
Jooyung Hanc221c052022-02-22 05:20:15 +0900318 apk: PathBuf,
Victor Hsiehb5bcfab2022-09-12 13:06:26 -0700319
Jooyung Hanc221c052022-02-22 05:20:15 +0900320 /// Path to idsig of the APK
Jooyung Hanc221c052022-02-22 05:20:15 +0900321 path: PathBuf,
322 },
David Brazdil20412d92021-03-18 10:53:06 +0000323}
324
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900325fn parse_debug_level(s: &str) -> Result<DebugLevel, String> {
326 match s {
327 "none" => Ok(DebugLevel::NONE),
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900328 "full" => Ok(DebugLevel::FULL),
329 _ => Err(format!("Invalid debug level {}", s)),
330 }
331}
332
Jiyong Park9dd389e2021-08-23 20:42:59 +0900333fn parse_partition_type(s: &str) -> Result<PartitionType, String> {
334 match s {
335 "raw" => Ok(PartitionType::RAW),
336 "instance" => Ok(PartitionType::ANDROID_VM_INSTANCE),
337 _ => Err(format!("Invalid partition type {}", s)),
338 }
339}
340
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000341fn parse_cpu_topology(s: &str) -> Result<CpuTopology, String> {
342 match s {
343 "one_cpu" => Ok(CpuTopology::ONE_CPU),
344 "match_host" => Ok(CpuTopology::MATCH_HOST),
345 _ => Err(format!("Invalid cpu topology {}", s)),
346 }
347}
348
Alan Stokesc4d5def2023-02-14 17:01:59 +0000349fn get_service() -> Result<Strong<dyn IVirtualizationService>, Error> {
350 let virtmgr =
351 vmclient::VirtualizationService::new().context("Failed to spawn VirtualizationService")?;
352 virtmgr.connect().context("Failed to connect to VirtualizationService")
353}
354
Shikha Panwar6d306412024-02-17 21:37:49 +0000355fn command_check_feature_enabled(feature: &str) {
356 println!(
357 "Feature {feature} is {}",
358 if avf_features::is_feature_enabled(feature) { "enabled" } else { "disabled" }
359 );
360}
361
Andrew Walbranea9fa482021-03-04 16:11:12 +0000362fn main() -> Result<(), Error> {
363 env_logger::init();
Victor Hsiehb5bcfab2022-09-12 13:06:26 -0700364 let opt = Opt::parse();
Andrew Walbranea9fa482021-03-04 16:11:12 +0000365
366 // We need to start the thread pool for Binder to work properly, especially link_to_death.
367 ProcessState::start_thread_pool();
368
David Brazdil20412d92021-03-18 10:53:06 +0000369 match opt {
Shikha Panwar6d306412024-02-17 21:37:49 +0000370 Opt::CheckFeatureEnabled { feature } => {
371 command_check_feature_enabled(&feature);
372 Ok(())
373 }
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900374 Opt::RunApp { config } => command_run_app(config),
375 Opt::RunMicrodroid { config } => command_run_microdroid(config),
376 Opt::Run { config } => command_run(config),
Alan Stokesc4d5def2023-02-14 17:01:59 +0000377 Opt::List => command_list(get_service()?.as_ref()),
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000378 Opt::Info => command_info(),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900379 Opt::CreatePartition { path, size, partition_type } => {
Alan Stokesc4d5def2023-02-14 17:01:59 +0000380 command_create_partition(get_service()?.as_ref(), &path, size, partition_type)
Jiyong Park9dd389e2021-08-23 20:42:59 +0900381 }
Alan Stokesc4d5def2023-02-14 17:01:59 +0000382 Opt::CreateIdsig { apk, path } => {
383 command_create_idsig(get_service()?.as_ref(), &apk, &path)
384 }
Andrew Walbranea9fa482021-03-04 16:11:12 +0000385 }
386}
387
Andrew Walbran320b5602021-03-04 16:11:12 +0000388/// List the VMs currently running.
Andrew Walbran616d13f2022-05-12 18:35:55 +0000389fn command_list(service: &dyn IVirtualizationService) -> Result<(), Error> {
Andrew Walbran17de24f2021-05-27 13:27:30 +0000390 let vms = service.debugListVms().context("Failed to get list of VMs")?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000391 println!("Running VMs: {:#?}", vms);
392 Ok(())
393}
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000394
395/// Print information about supported VM types.
396fn command_info() -> Result<(), Error> {
Alan Stokesc4d5def2023-02-14 17:01:59 +0000397 let non_protected_vm_supported = hypervisor_props::is_vm_supported()?;
398 let protected_vm_supported = hypervisor_props::is_protected_vm_supported()?;
Alan Stokes8d39a9b2023-01-10 15:01:00 +0000399 match (non_protected_vm_supported, protected_vm_supported) {
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000400 (false, false) => println!("VMs are not supported."),
401 (false, true) => println!("Only protected VMs are supported."),
Alan Stokes8d39a9b2023-01-10 15:01:00 +0000402 (true, false) => println!("Only non-protected VMs are supported."),
403 (true, true) => println!("Both protected and non-protected VMs are supported."),
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000404 }
405
Alan Stokesc4d5def2023-02-14 17:01:59 +0000406 if let Some(version) = hypervisor_props::version()? {
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000407 println!("Hypervisor version: {}", version);
408 } else {
409 println!("Hypervisor version not set.");
410 }
411
412 if Path::new("/dev/kvm").exists() {
413 println!("/dev/kvm exists.");
414 } else {
415 println!("/dev/kvm does not exist.");
416 }
417
Inseob Kim6ef80972023-07-20 17:23:36 +0900418 if Path::new("/dev/vfio/vfio").exists() {
419 println!("/dev/vfio/vfio exists.");
420 } else {
421 println!("/dev/vfio/vfio does not exist.");
422 }
423
424 if Path::new("/sys/bus/platform/drivers/vfio-platform").exists() {
425 println!("VFIO-platform is supported.");
426 } else {
427 println!("VFIO-platform is not supported.");
428 }
429
Jaewan Kim0c99c612024-03-23 00:44:14 +0900430 #[derive(Serialize)]
431 struct AssignableDevice {
432 node: String,
433 dtbo_label: String,
434 }
435
Inseob Kim75460b32023-08-09 13:41:31 +0900436 let devices = get_service()?.getAssignableDevices()?;
Jaewan Kim0c99c612024-03-23 00:44:14 +0900437 let devices: Vec<_> = devices
438 .into_iter()
439 .map(|device| AssignableDevice { node: device.node, dtbo_label: device.dtbo_label })
440 .collect();
Inseob Kim75460b32023-08-09 13:41:31 +0900441 println!("Assignable devices: {}", serde_json::to_string(&devices)?);
442
Inseob Kim46257382024-01-03 15:41:22 +0900443 let os_list = get_service()?.getSupportedOSList()?;
444 println!("Available OS list: {}", serde_json::to_string(&os_list)?);
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900445
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000446 Ok(())
447}
Andrew Walbran1f810b62022-08-10 13:33:57 +0000448
449#[cfg(test)]
450mod tests {
451 use super::*;
Andrew Walbranaa1efc42022-08-10 13:33:57 +0000452 use clap::CommandFactory;
Andrew Walbran1f810b62022-08-10 13:33:57 +0000453
454 #[test]
455 fn verify_app() {
Andrew Walbranaa1efc42022-08-10 13:33:57 +0000456 // Check that the command parsing has been configured in a valid way.
457 Opt::command().debug_assert();
Andrew Walbran1f810b62022-08-10 13:33:57 +0000458 }
459}