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