blob: d6ee3a5cbda2a7ba858759e6d56e2874f3af3451 [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,
Jiyong Parkb1935ef2023-08-10 17:22:39 +090063}
64
Alan Stokesfda70842023-12-20 17:50:14 +000065#[derive(Args, Default)]
Jiyong Parkb1935ef2023-08-10 17:22:39 +090066/// Collection of flags for debugging
67pub struct DebugConfig {
68 /// Debug level of the VM. Supported values: "full" (default), and "none".
69 #[arg(long, default_value = "full", value_parser = parse_debug_level)]
70 debug: DebugLevel,
71
72 /// Path to file for VM console output.
73 #[arg(long)]
74 console: Option<PathBuf>,
75
76 /// Path to file for VM console input.
77 #[arg(long)]
78 console_in: Option<PathBuf>,
79
80 /// Path to file for VM log output.
81 #[arg(long)]
82 log: Option<PathBuf>,
83
84 /// Port at which crosvm will start a gdb server to debug guest kernel.
85 /// Note: this is only supported on Android kernels android14-5.15 and higher.
86 #[arg(long)]
87 gdb: Option<NonZeroU16>,
88}
89
Alan Stokesfda70842023-12-20 17:50:14 +000090#[derive(Args, Default)]
Jiyong Parkb1935ef2023-08-10 17:22:39 +090091/// Collection of flags that are Microdroid specific
92pub struct MicrodroidConfig {
93 /// Path to the file backing the storage.
94 /// Created if the option is used but the path does not exist in the device.
95 #[arg(long)]
96 storage: Option<PathBuf>,
97
98 /// Size of the storage. Used only if --storage is supplied but path does not exist
99 /// Default size is 10*1024*1024
100 #[arg(long)]
101 storage_size: Option<u64>,
102
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900103 /// Path to disk image containing vendor-specific modules.
Nikita Ioffe631717e2023-09-05 13:38:07 +0100104 #[cfg(vendor_modules)]
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900105 #[arg(long)]
106 vendor: Option<PathBuf>,
107
108 /// SysFS nodes of devices to assign to VM
Nikita Ioffe94a8a182023-11-16 16:37:48 +0000109 #[cfg(device_assignment)]
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900110 #[arg(long)]
111 devices: Vec<PathBuf>,
Inseob Kim172f9eb2023-11-06 17:02:08 +0900112
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900113 /// Version of GKI to use. If set, use instead of microdroid kernel
Inseob Kim172f9eb2023-11-06 17:02:08 +0900114 #[cfg(vendor_modules)]
115 #[arg(long)]
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900116 gki: Option<String>,
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900117}
118
Nikita Ioffe631717e2023-09-05 13:38:07 +0100119impl MicrodroidConfig {
120 #[cfg(vendor_modules)]
Nikita Ioffe631717e2023-09-05 13:38:07 +0100121 fn vendor(&self) -> &Option<PathBuf> {
122 &self.vendor
123 }
124
125 #[cfg(not(vendor_modules))]
Nikita Ioffe631717e2023-09-05 13:38:07 +0100126 fn vendor(&self) -> Option<PathBuf> {
127 None
128 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +0000129
Inseob Kim172f9eb2023-11-06 17:02:08 +0900130 #[cfg(vendor_modules)]
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900131 fn gki(&self) -> Option<&str> {
132 self.gki.as_deref()
Inseob Kim172f9eb2023-11-06 17:02:08 +0900133 }
134
135 #[cfg(not(vendor_modules))]
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900136 fn gki(&self) -> Option<&str> {
137 None
Inseob Kim172f9eb2023-11-06 17:02:08 +0900138 }
139
Nikita Ioffe94a8a182023-11-16 16:37:48 +0000140 #[cfg(device_assignment)]
141 fn devices(&self) -> &Vec<PathBuf> {
142 &self.devices
143 }
144
145 #[cfg(not(device_assignment))]
146 fn devices(&self) -> Vec<PathBuf> {
147 Vec::new()
148 }
Nikita Ioffe631717e2023-09-05 13:38:07 +0100149}
150
Alan Stokesfda70842023-12-20 17:50:14 +0000151#[derive(Args, Default)]
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900152/// Flags for the run_app subcommand
153pub struct RunAppConfig {
154 #[command(flatten)]
155 common: CommonConfig,
156
157 #[command(flatten)]
158 debug: DebugConfig,
159
160 #[command(flatten)]
161 microdroid: MicrodroidConfig,
162
163 /// Path to VM Payload APK
164 apk: PathBuf,
165
166 /// Path to idsig of the APK
167 idsig: PathBuf,
168
169 /// Path to the instance image. Created if not exists.
170 instance: PathBuf,
171
Shikha Panwar61a74b52024-02-16 13:17:01 +0000172 /// Path to file containing instance_id. Required iff llpvm feature is enabled.
173 #[cfg(llpvm_changes)]
174 #[arg(long = "instance-id-file")]
175 instance_id: PathBuf,
176
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900177 /// Path to VM config JSON within APK (e.g. assets/vm_config.json)
178 #[arg(long)]
179 config_path: Option<String>,
180
181 /// Name of VM payload binary within APK (e.g. MicrodroidTestNativeLib.so)
182 #[arg(long)]
183 #[arg(alias = "payload_path")]
184 payload_binary_name: Option<String>,
185
Alan Stokesfda70842023-12-20 17:50:14 +0000186 /// Paths to extra apk files.
187 #[cfg(multi_tenant)]
188 #[arg(long = "extra-apk")]
189 #[clap(conflicts_with = "config_path")]
190 extra_apks: Vec<PathBuf>,
191
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900192 /// Paths to extra idsig files.
193 #[arg(long = "extra-idsig")]
194 extra_idsigs: Vec<PathBuf>,
195}
196
Alan Stokesfda70842023-12-20 17:50:14 +0000197impl RunAppConfig {
198 #[cfg(multi_tenant)]
199 fn extra_apks(&self) -> &[PathBuf] {
200 &self.extra_apks
201 }
202
203 #[cfg(not(multi_tenant))]
204 fn extra_apks(&self) -> &[PathBuf] {
205 &[]
206 }
Shikha Panwar61a74b52024-02-16 13:17:01 +0000207
208 #[cfg(llpvm_changes)]
209 fn instance_id(&self) -> Result<PathBuf, Error> {
210 Ok(self.instance_id.clone())
211 }
212
213 #[cfg(not(llpvm_changes))]
214 fn instance_id(&self) -> Result<PathBuf, Error> {
215 Err(anyhow!("LLPVM feature is disabled, --instance_id flag not supported"))
216 }
217
218 #[cfg(llpvm_changes)]
219 fn set_instance_id(&mut self, instance_id_file: PathBuf) -> Result<(), Error> {
220 self.instance_id = instance_id_file;
221 Ok(())
222 }
223
224 #[cfg(not(llpvm_changes))]
225 fn set_instance_id(&mut self, _: PathBuf) -> Result<(), Error> {
226 Err(anyhow!("LLPVM feature is disabled, --instance_id flag not supported"))
227 }
Alan Stokesfda70842023-12-20 17:50:14 +0000228}
229
230#[derive(Args, Default)]
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900231/// Flags for the run_microdroid subcommand
232pub struct RunMicrodroidConfig {
233 #[command(flatten)]
234 common: CommonConfig,
235
236 #[command(flatten)]
237 debug: DebugConfig,
238
239 #[command(flatten)]
240 microdroid: MicrodroidConfig,
241
242 /// Path to the directory where VM-related files (e.g. instance.img, apk.idsig, etc.) will
243 /// be stored. If not specified a random directory under /data/local/tmp/microdroid will be
244 /// created and used.
245 #[arg(long)]
246 work_dir: Option<PathBuf>,
247}
248
Alan Stokesfda70842023-12-20 17:50:14 +0000249#[derive(Args, Default)]
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900250/// Flags for the run subcommand
251pub struct RunCustomVmConfig {
252 #[command(flatten)]
253 common: CommonConfig,
254
255 #[command(flatten)]
256 debug: DebugConfig,
257
258 /// Path to VM config JSON
259 config: PathBuf,
260}
261
Victor Hsiehb5bcfab2022-09-12 13:06:26 -0700262#[derive(Parser)]
David Brazdil20412d92021-03-18 10:53:06 +0000263enum Opt {
Shikha Panwar6d306412024-02-17 21:37:49 +0000264 /// Check if the feature is enabled on device.
265 CheckFeatureEnabled { feature: String },
Jooyung Han21e9b922021-06-26 04:14:16 +0900266 /// Run a virtual machine with a config in APK
267 RunApp {
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900268 #[command(flatten)]
269 config: RunAppConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +0900270 },
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000271 /// Run a virtual machine with Microdroid inside
272 RunMicrodroid {
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900273 #[command(flatten)]
274 config: RunMicrodroidConfig,
Nikita Ioffeb0b67562022-11-22 15:48:06 +0000275 },
David Brazdil20412d92021-03-18 10:53:06 +0000276 /// Run a virtual machine
277 Run {
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900278 #[command(flatten)]
279 config: RunCustomVmConfig,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000280 },
David Brazdil20412d92021-03-18 10:53:06 +0000281 /// List running virtual machines
282 List,
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000283 /// Print information about virtual machine support
284 Info,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000285 /// Create a new empty partition to be used as a writable partition for a VM
286 CreatePartition {
287 /// Path at which to create the image file
Andrew Walbrandff3b942021-06-09 15:20:36 +0000288 path: PathBuf,
289
290 /// The desired size of the partition, in bytes.
291 size: u64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900292
293 /// Type of the partition
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900294 #[arg(short = 't', long = "type", default_value = "raw",
Victor Hsiehb5bcfab2022-09-12 13:06:26 -0700295 value_parser = parse_partition_type)]
Jiyong Park9dd389e2021-08-23 20:42:59 +0900296 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000297 },
Jooyung Hanc221c052022-02-22 05:20:15 +0900298 /// Creates or update the idsig file by digesting the input APK file.
299 CreateIdsig {
300 /// Path to VM Payload APK
Jooyung Hanc221c052022-02-22 05:20:15 +0900301 apk: PathBuf,
Victor Hsiehb5bcfab2022-09-12 13:06:26 -0700302
Jooyung Hanc221c052022-02-22 05:20:15 +0900303 /// Path to idsig of the APK
Jooyung Hanc221c052022-02-22 05:20:15 +0900304 path: PathBuf,
305 },
David Brazdil20412d92021-03-18 10:53:06 +0000306}
307
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900308fn parse_debug_level(s: &str) -> Result<DebugLevel, String> {
309 match s {
310 "none" => Ok(DebugLevel::NONE),
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900311 "full" => Ok(DebugLevel::FULL),
312 _ => Err(format!("Invalid debug level {}", s)),
313 }
314}
315
Jiyong Park9dd389e2021-08-23 20:42:59 +0900316fn parse_partition_type(s: &str) -> Result<PartitionType, String> {
317 match s {
318 "raw" => Ok(PartitionType::RAW),
319 "instance" => Ok(PartitionType::ANDROID_VM_INSTANCE),
320 _ => Err(format!("Invalid partition type {}", s)),
321 }
322}
323
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000324fn parse_cpu_topology(s: &str) -> Result<CpuTopology, String> {
325 match s {
326 "one_cpu" => Ok(CpuTopology::ONE_CPU),
327 "match_host" => Ok(CpuTopology::MATCH_HOST),
328 _ => Err(format!("Invalid cpu topology {}", s)),
329 }
330}
331
Alan Stokesc4d5def2023-02-14 17:01:59 +0000332fn get_service() -> Result<Strong<dyn IVirtualizationService>, Error> {
333 let virtmgr =
334 vmclient::VirtualizationService::new().context("Failed to spawn VirtualizationService")?;
335 virtmgr.connect().context("Failed to connect to VirtualizationService")
336}
337
Shikha Panwar6d306412024-02-17 21:37:49 +0000338fn command_check_feature_enabled(feature: &str) {
339 println!(
340 "Feature {feature} is {}",
341 if avf_features::is_feature_enabled(feature) { "enabled" } else { "disabled" }
342 );
343}
344
Andrew Walbranea9fa482021-03-04 16:11:12 +0000345fn main() -> Result<(), Error> {
346 env_logger::init();
Victor Hsiehb5bcfab2022-09-12 13:06:26 -0700347 let opt = Opt::parse();
Andrew Walbranea9fa482021-03-04 16:11:12 +0000348
349 // We need to start the thread pool for Binder to work properly, especially link_to_death.
350 ProcessState::start_thread_pool();
351
David Brazdil20412d92021-03-18 10:53:06 +0000352 match opt {
Shikha Panwar6d306412024-02-17 21:37:49 +0000353 Opt::CheckFeatureEnabled { feature } => {
354 command_check_feature_enabled(&feature);
355 Ok(())
356 }
Jiyong Parkb1935ef2023-08-10 17:22:39 +0900357 Opt::RunApp { config } => command_run_app(config),
358 Opt::RunMicrodroid { config } => command_run_microdroid(config),
359 Opt::Run { config } => command_run(config),
Alan Stokesc4d5def2023-02-14 17:01:59 +0000360 Opt::List => command_list(get_service()?.as_ref()),
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000361 Opt::Info => command_info(),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900362 Opt::CreatePartition { path, size, partition_type } => {
Alan Stokesc4d5def2023-02-14 17:01:59 +0000363 command_create_partition(get_service()?.as_ref(), &path, size, partition_type)
Jiyong Park9dd389e2021-08-23 20:42:59 +0900364 }
Alan Stokesc4d5def2023-02-14 17:01:59 +0000365 Opt::CreateIdsig { apk, path } => {
366 command_create_idsig(get_service()?.as_ref(), &apk, &path)
367 }
Andrew Walbranea9fa482021-03-04 16:11:12 +0000368 }
369}
370
Andrew Walbran320b5602021-03-04 16:11:12 +0000371/// List the VMs currently running.
Andrew Walbran616d13f2022-05-12 18:35:55 +0000372fn command_list(service: &dyn IVirtualizationService) -> Result<(), Error> {
Andrew Walbran17de24f2021-05-27 13:27:30 +0000373 let vms = service.debugListVms().context("Failed to get list of VMs")?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000374 println!("Running VMs: {:#?}", vms);
375 Ok(())
376}
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000377
378/// Print information about supported VM types.
379fn command_info() -> Result<(), Error> {
Alan Stokesc4d5def2023-02-14 17:01:59 +0000380 let non_protected_vm_supported = hypervisor_props::is_vm_supported()?;
381 let protected_vm_supported = hypervisor_props::is_protected_vm_supported()?;
Alan Stokes8d39a9b2023-01-10 15:01:00 +0000382 match (non_protected_vm_supported, protected_vm_supported) {
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000383 (false, false) => println!("VMs are not supported."),
384 (false, true) => println!("Only protected VMs are supported."),
Alan Stokes8d39a9b2023-01-10 15:01:00 +0000385 (true, false) => println!("Only non-protected VMs are supported."),
386 (true, true) => println!("Both protected and non-protected VMs are supported."),
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000387 }
388
Alan Stokesc4d5def2023-02-14 17:01:59 +0000389 if let Some(version) = hypervisor_props::version()? {
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000390 println!("Hypervisor version: {}", version);
391 } else {
392 println!("Hypervisor version not set.");
393 }
394
395 if Path::new("/dev/kvm").exists() {
396 println!("/dev/kvm exists.");
397 } else {
398 println!("/dev/kvm does not exist.");
399 }
400
Inseob Kim6ef80972023-07-20 17:23:36 +0900401 if Path::new("/dev/vfio/vfio").exists() {
402 println!("/dev/vfio/vfio exists.");
403 } else {
404 println!("/dev/vfio/vfio does not exist.");
405 }
406
407 if Path::new("/sys/bus/platform/drivers/vfio-platform").exists() {
408 println!("VFIO-platform is supported.");
409 } else {
410 println!("VFIO-platform is not supported.");
411 }
412
Jaewan Kim0c99c612024-03-23 00:44:14 +0900413 #[derive(Serialize)]
414 struct AssignableDevice {
415 node: String,
416 dtbo_label: String,
417 }
418
Inseob Kim75460b32023-08-09 13:41:31 +0900419 let devices = get_service()?.getAssignableDevices()?;
Jaewan Kim0c99c612024-03-23 00:44:14 +0900420 let devices: Vec<_> = devices
421 .into_iter()
422 .map(|device| AssignableDevice { node: device.node, dtbo_label: device.dtbo_label })
423 .collect();
Inseob Kim75460b32023-08-09 13:41:31 +0900424 println!("Assignable devices: {}", serde_json::to_string(&devices)?);
425
Inseob Kim46257382024-01-03 15:41:22 +0900426 let os_list = get_service()?.getSupportedOSList()?;
427 println!("Available OS list: {}", serde_json::to_string(&os_list)?);
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900428
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000429 Ok(())
430}
Andrew Walbran1f810b62022-08-10 13:33:57 +0000431
432#[cfg(test)]
433mod tests {
434 use super::*;
Andrew Walbranaa1efc42022-08-10 13:33:57 +0000435 use clap::CommandFactory;
Andrew Walbran1f810b62022-08-10 13:33:57 +0000436
437 #[test]
438 fn verify_app() {
Andrew Walbranaa1efc42022-08-10 13:33:57 +0000439 // Check that the command parsing has been configured in a valid way.
440 Opt::command().debug_assert();
Andrew Walbran1f810b62022-08-10 13:33:57 +0000441 }
442}