1 // 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 //! Command to run a VM.
16
17 use crate::create_partition::command_create_partition;
18 use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
19 CpuTopology::CpuTopology,
20 IVirtualizationService::IVirtualizationService,
21 PartitionType::PartitionType,
22 VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
23 VirtualMachineConfig::VirtualMachineConfig,
24 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
25 VirtualMachineState::VirtualMachineState,
26 };
27 use anyhow::{anyhow, bail, Context, Error};
28 use binder::ParcelFileDescriptor;
29 use glob::glob;
30 use microdroid_payload_config::VmPayloadConfig;
31 use rand::{distributions::Alphanumeric, Rng};
32 use std::fs;
33 use std::fs::File;
34 use std::io;
35 use std::num::NonZeroU16;
36 use std::os::unix::io::{AsRawFd, FromRawFd};
37 use std::path::{Path, PathBuf};
38 use vmclient::{ErrorCode, VmInstance};
39 use vmconfig::{open_parcel_file, VmConfig};
40 use zip::ZipArchive;
41
42 /// Run a VM from the given APK, idsig, and config.
43 #[allow(clippy::too_many_arguments)]
command_run_app( name: Option<String>, service: &dyn IVirtualizationService, apk: &Path, idsig: &Path, instance: &Path, storage: Option<&Path>, storage_size: Option<u64>, config_path: Option<String>, payload_binary_name: Option<String>, console_path: Option<&Path>, log_path: Option<&Path>, debug_level: DebugLevel, protected: bool, mem: Option<u32>, cpu_topology: CpuTopology, task_profiles: Vec<String>, extra_idsigs: &[PathBuf], gdb: Option<NonZeroU16>, ) -> Result<(), Error>44 pub fn command_run_app(
45 name: Option<String>,
46 service: &dyn IVirtualizationService,
47 apk: &Path,
48 idsig: &Path,
49 instance: &Path,
50 storage: Option<&Path>,
51 storage_size: Option<u64>,
52 config_path: Option<String>,
53 payload_binary_name: Option<String>,
54 console_path: Option<&Path>,
55 log_path: Option<&Path>,
56 debug_level: DebugLevel,
57 protected: bool,
58 mem: Option<u32>,
59 cpu_topology: CpuTopology,
60 task_profiles: Vec<String>,
61 extra_idsigs: &[PathBuf],
62 gdb: Option<NonZeroU16>,
63 ) -> Result<(), Error> {
64 let apk_file = File::open(apk).context("Failed to open APK file")?;
65
66 let extra_apks = match config_path.as_deref() {
67 Some(path) => parse_extra_apk_list(apk, path)?,
68 None => vec![],
69 };
70
71 if extra_apks.len() != extra_idsigs.len() {
72 bail!(
73 "Found {} extra apks, but there are {} extra idsigs",
74 extra_apks.len(),
75 extra_idsigs.len()
76 )
77 }
78
79 for i in 0..extra_apks.len() {
80 let extra_apk_fd = ParcelFileDescriptor::new(File::open(&extra_apks[i])?);
81 let extra_idsig_fd = ParcelFileDescriptor::new(File::create(&extra_idsigs[i])?);
82 service.createOrUpdateIdsigFile(&extra_apk_fd, &extra_idsig_fd)?;
83 }
84
85 let idsig_file = File::create(idsig).context("Failed to create idsig file")?;
86
87 let apk_fd = ParcelFileDescriptor::new(apk_file);
88 let idsig_fd = ParcelFileDescriptor::new(idsig_file);
89 service.createOrUpdateIdsigFile(&apk_fd, &idsig_fd)?;
90
91 let idsig_file = File::open(idsig).context("Failed to open idsig file")?;
92 let idsig_fd = ParcelFileDescriptor::new(idsig_file);
93
94 if !instance.exists() {
95 const INSTANCE_FILE_SIZE: u64 = 10 * 1024 * 1024;
96 command_create_partition(
97 service,
98 instance,
99 INSTANCE_FILE_SIZE,
100 PartitionType::ANDROID_VM_INSTANCE,
101 )?;
102 }
103
104 let storage = if let Some(path) = storage {
105 if !path.exists() {
106 command_create_partition(
107 service,
108 path,
109 storage_size.unwrap_or(10 * 1024 * 1024),
110 PartitionType::ENCRYPTEDSTORE,
111 )?;
112 }
113 Some(open_parcel_file(path, true)?)
114 } else {
115 None
116 };
117
118 let extra_idsig_files: Result<Vec<File>, _> = extra_idsigs.iter().map(File::open).collect();
119 let extra_idsig_fds = extra_idsig_files?.into_iter().map(ParcelFileDescriptor::new).collect();
120
121 let payload = if let Some(config_path) = config_path {
122 if payload_binary_name.is_some() {
123 bail!("Only one of --config-path or --payload-binary-name can be defined")
124 }
125 Payload::ConfigPath(config_path)
126 } else if let Some(payload_binary_name) = payload_binary_name {
127 Payload::PayloadConfig(VirtualMachinePayloadConfig {
128 payloadBinaryName: payload_binary_name,
129 })
130 } else {
131 bail!("Either --config-path or --payload-binary-name must be defined")
132 };
133
134 let payload_config_str = format!("{:?}!{:?}", apk, payload);
135
136 let config = VirtualMachineConfig::AppConfig(VirtualMachineAppConfig {
137 name: name.unwrap_or_else(|| String::from("VmRunApp")),
138 apk: apk_fd.into(),
139 idsig: idsig_fd.into(),
140 extraIdsigs: extra_idsig_fds,
141 instanceImage: open_parcel_file(instance, true /* writable */)?.into(),
142 encryptedStorageImage: storage,
143 payload,
144 debugLevel: debug_level,
145 protectedVm: protected,
146 memoryMib: mem.unwrap_or(0) as i32, // 0 means use the VM default
147 cpuTopology: cpu_topology,
148 taskProfiles: task_profiles,
149 gdbPort: gdb.map(u16::from).unwrap_or(0) as i32, // 0 means no gdb
150 });
151 run(service, &config, &payload_config_str, console_path, log_path)
152 }
153
find_empty_payload_apk_path() -> Result<PathBuf, Error>154 fn find_empty_payload_apk_path() -> Result<PathBuf, Error> {
155 const GLOB_PATTERN: &str = "/apex/com.android.virt/app/**/EmptyPayloadApp*.apk";
156 let mut entries: Vec<PathBuf> =
157 glob(GLOB_PATTERN).context("failed to glob")?.filter_map(|e| e.ok()).collect();
158 if entries.len() > 1 {
159 return Err(anyhow!("Found more than one apk matching {}", GLOB_PATTERN));
160 }
161 match entries.pop() {
162 Some(path) => Ok(path),
163 None => Err(anyhow!("No apks match {}", GLOB_PATTERN)),
164 }
165 }
166
create_work_dir() -> Result<PathBuf, Error>167 fn create_work_dir() -> Result<PathBuf, Error> {
168 let s: String =
169 rand::thread_rng().sample_iter(&Alphanumeric).take(17).map(char::from).collect();
170 let work_dir = PathBuf::from("/data/local/tmp/microdroid").join(s);
171 println!("creating work dir {}", work_dir.display());
172 fs::create_dir_all(&work_dir).context("failed to mkdir")?;
173 Ok(work_dir)
174 }
175
176 /// Run a VM with Microdroid
177 #[allow(clippy::too_many_arguments)]
command_run_microdroid( name: Option<String>, service: &dyn IVirtualizationService, work_dir: Option<PathBuf>, storage: Option<&Path>, storage_size: Option<u64>, console_path: Option<&Path>, log_path: Option<&Path>, debug_level: DebugLevel, protected: bool, mem: Option<u32>, cpu_topology: CpuTopology, task_profiles: Vec<String>, gdb: Option<NonZeroU16>, ) -> Result<(), Error>178 pub fn command_run_microdroid(
179 name: Option<String>,
180 service: &dyn IVirtualizationService,
181 work_dir: Option<PathBuf>,
182 storage: Option<&Path>,
183 storage_size: Option<u64>,
184 console_path: Option<&Path>,
185 log_path: Option<&Path>,
186 debug_level: DebugLevel,
187 protected: bool,
188 mem: Option<u32>,
189 cpu_topology: CpuTopology,
190 task_profiles: Vec<String>,
191 gdb: Option<NonZeroU16>,
192 ) -> Result<(), Error> {
193 let apk = find_empty_payload_apk_path()?;
194 println!("found path {}", apk.display());
195
196 let work_dir = work_dir.unwrap_or(create_work_dir()?);
197 let idsig = work_dir.join("apk.idsig");
198 println!("apk.idsig path: {}", idsig.display());
199 let instance_img = work_dir.join("instance.img");
200 println!("instance.img path: {}", instance_img.display());
201
202 let payload_binary_name = "MicrodroidEmptyPayloadJniLib.so";
203 let extra_sig = [];
204 command_run_app(
205 name,
206 service,
207 &apk,
208 &idsig,
209 &instance_img,
210 storage,
211 storage_size,
212 /* config_path= */ None,
213 Some(payload_binary_name.to_owned()),
214 console_path,
215 log_path,
216 debug_level,
217 protected,
218 mem,
219 cpu_topology,
220 task_profiles,
221 &extra_sig,
222 gdb,
223 )
224 }
225
226 /// Run a VM from the given configuration file.
227 #[allow(clippy::too_many_arguments)]
command_run( name: Option<String>, service: &dyn IVirtualizationService, config_path: &Path, console_path: Option<&Path>, log_path: Option<&Path>, mem: Option<u32>, cpu_topology: CpuTopology, task_profiles: Vec<String>, gdb: Option<NonZeroU16>, ) -> Result<(), Error>228 pub fn command_run(
229 name: Option<String>,
230 service: &dyn IVirtualizationService,
231 config_path: &Path,
232 console_path: Option<&Path>,
233 log_path: Option<&Path>,
234 mem: Option<u32>,
235 cpu_topology: CpuTopology,
236 task_profiles: Vec<String>,
237 gdb: Option<NonZeroU16>,
238 ) -> Result<(), Error> {
239 let config_file = File::open(config_path).context("Failed to open config file")?;
240 let mut config =
241 VmConfig::load(&config_file).context("Failed to parse config file")?.to_parcelable()?;
242 if let Some(mem) = mem {
243 config.memoryMib = mem as i32;
244 }
245 if let Some(name) = name {
246 config.name = name;
247 } else {
248 config.name = String::from("VmRun");
249 }
250 if let Some(gdb) = gdb {
251 config.gdbPort = gdb.get() as i32;
252 }
253 config.cpuTopology = cpu_topology;
254 config.taskProfiles = task_profiles;
255 run(
256 service,
257 &VirtualMachineConfig::RawConfig(config),
258 &format!("{:?}", config_path),
259 console_path,
260 log_path,
261 )
262 }
263
state_to_str(vm_state: VirtualMachineState) -> &'static str264 fn state_to_str(vm_state: VirtualMachineState) -> &'static str {
265 match vm_state {
266 VirtualMachineState::NOT_STARTED => "NOT_STARTED",
267 VirtualMachineState::STARTING => "STARTING",
268 VirtualMachineState::STARTED => "STARTED",
269 VirtualMachineState::READY => "READY",
270 VirtualMachineState::FINISHED => "FINISHED",
271 VirtualMachineState::DEAD => "DEAD",
272 _ => "(invalid state)",
273 }
274 }
275
run( service: &dyn IVirtualizationService, config: &VirtualMachineConfig, payload_config: &str, console_path: Option<&Path>, log_path: Option<&Path>, ) -> Result<(), Error>276 fn run(
277 service: &dyn IVirtualizationService,
278 config: &VirtualMachineConfig,
279 payload_config: &str,
280 console_path: Option<&Path>,
281 log_path: Option<&Path>,
282 ) -> Result<(), Error> {
283 let console = if let Some(console_path) = console_path {
284 Some(
285 File::create(console_path)
286 .with_context(|| format!("Failed to open console file {:?}", console_path))?,
287 )
288 } else {
289 Some(duplicate_stdout()?)
290 };
291 let log = if let Some(log_path) = log_path {
292 Some(
293 File::create(log_path)
294 .with_context(|| format!("Failed to open log file {:?}", log_path))?,
295 )
296 } else {
297 Some(duplicate_stdout()?)
298 };
299
300 let callback = Box::new(Callback {});
301 let vm = VmInstance::create(service, config, console, log, Some(callback))
302 .context("Failed to create VM")?;
303 vm.start().context("Failed to start VM")?;
304
305 println!(
306 "Created VM from {} with CID {}, state is {}.",
307 payload_config,
308 vm.cid(),
309 state_to_str(vm.state()?)
310 );
311
312 // Wait until the VM or VirtualizationService dies. If we just returned immediately then the
313 // IVirtualMachine Binder object would be dropped and the VM would be killed.
314 let death_reason = vm.wait_for_death();
315 println!("VM ended: {:?}", death_reason);
316 Ok(())
317 }
318
parse_extra_apk_list(apk: &Path, config_path: &str) -> Result<Vec<String>, Error>319 fn parse_extra_apk_list(apk: &Path, config_path: &str) -> Result<Vec<String>, Error> {
320 let mut archive = ZipArchive::new(File::open(apk)?)?;
321 let config_file = archive.by_name(config_path)?;
322 let config: VmPayloadConfig = serde_json::from_reader(config_file)?;
323 Ok(config.extra_apks.into_iter().map(|x| x.path).collect())
324 }
325
326 struct Callback {}
327
328 impl vmclient::VmCallback for Callback {
on_payload_started(&self, _cid: i32)329 fn on_payload_started(&self, _cid: i32) {
330 eprintln!("payload started");
331 }
332
on_payload_ready(&self, _cid: i32)333 fn on_payload_ready(&self, _cid: i32) {
334 eprintln!("payload is ready");
335 }
336
on_payload_finished(&self, _cid: i32, exit_code: i32)337 fn on_payload_finished(&self, _cid: i32, exit_code: i32) {
338 eprintln!("payload finished with exit code {}", exit_code);
339 }
340
on_error(&self, _cid: i32, error_code: ErrorCode, message: &str)341 fn on_error(&self, _cid: i32, error_code: ErrorCode, message: &str) {
342 eprintln!("VM encountered an error: code={:?}, message={}", error_code, message);
343 }
344 }
345
346 /// Safely duplicate the standard output file descriptor.
duplicate_stdout() -> io::Result<File>347 fn duplicate_stdout() -> io::Result<File> {
348 let stdout_fd = io::stdout().as_raw_fd();
349 // Safe because this just duplicates a file descriptor which we know to be valid, and we check
350 // for an error.
351 let dup_fd = unsafe { libc::dup(stdout_fd) };
352 if dup_fd < 0 {
353 Err(io::Error::last_os_error())
354 } else {
355 // Safe because we have just duplicated the file descriptor so we own it, and `from_raw_fd`
356 // takes ownership of it.
357 Ok(unsafe { File::from_raw_fd(dup_fd) })
358 }
359 }
360