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::fd::AsFd;
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(ref os) = config.microdroid.os { os } else { "microdroid" };
144 
145     let payload_config_str = format!("{:?}!{:?}", config.apk, payload);
146 
147     let mut custom_config = CustomConfig {
148         gdbPort: config.debug.gdb.map(u16::from).unwrap_or(0) as i32, // 0 means no gdb
149         vendorImage: vendor,
150         devices: config
151             .microdroid
152             .devices()
153             .iter()
154             .map(|x| {
155                 x.to_str().map(String::from).ok_or(anyhow!("Failed to convert {x:?} to String"))
156             })
157             .collect::<Result<_, _>>()?,
158         networkSupported: config.common.network_supported(),
159         teeServices: config.common.tee_services().to_vec(),
160         ..Default::default()
161     };
162 
163     if config.debug.enable_earlycon() {
164         if config.debug.debug != DebugLevel::FULL {
165             bail!("earlycon is only supported for debuggable VMs")
166         }
167         if cfg!(target_arch = "aarch64") {
168             custom_config
169                 .extraKernelCmdlineParams
170                 .push(String::from("earlycon=uart8250,mmio,0x3f8"));
171         } else if cfg!(target_arch = "x86_64") {
172             custom_config.extraKernelCmdlineParams.push(String::from("earlycon=uart8250,io,0x3f8"));
173         } else {
174             bail!("unexpected architecture!");
175         }
176         custom_config.extraKernelCmdlineParams.push(String::from("keep_bootcon"));
177     }
178 
179     let vm_config = VirtualMachineConfig::AppConfig(VirtualMachineAppConfig {
180         name: config.common.name.unwrap_or_else(|| String::from("VmRunApp")),
181         apk: apk_fd.into(),
182         idsig: idsig_fd.into(),
183         extraIdsigs: extra_idsig_fds,
184         instanceImage: open_parcel_file(&config.instance, true /* writable */)?.into(),
185         instanceId: instance_id,
186         encryptedStorageImage: storage,
187         payload,
188         debugLevel: config.debug.debug,
189         protectedVm: config.common.protected,
190         memoryMib: config.common.mem.unwrap_or(0) as i32, // 0 means use the VM default
191         cpuTopology: config.common.cpu_topology,
192         customConfig: Some(custom_config),
193         osName: os_name.to_string(),
194         hugePages: config.common.hugepages,
195         boostUclamp: config.common.boost_uclamp,
196     });
197     run(
198         service.as_ref(),
199         &vm_config,
200         &payload_config_str,
201         config.debug.console.as_ref().map(|p| p.as_ref()),
202         config.debug.console_in.as_ref().map(|p| p.as_ref()),
203         config.debug.log.as_ref().map(|p| p.as_ref()),
204         config.debug.dump_device_tree.as_ref().map(|p| p.as_ref()),
205     )
206 }
207 
find_empty_payload_apk_path() -> Result<PathBuf, Error>208 fn find_empty_payload_apk_path() -> Result<PathBuf, Error> {
209     const GLOB_PATTERN: &str = "/apex/com.android.virt/app/**/EmptyPayloadApp*.apk";
210     let mut entries: Vec<PathBuf> =
211         glob(GLOB_PATTERN).context("failed to glob")?.filter_map(|e| e.ok()).collect();
212     if entries.len() > 1 {
213         return Err(anyhow!("Found more than one apk matching {}", GLOB_PATTERN));
214     }
215     match entries.pop() {
216         Some(path) => Ok(path),
217         None => Err(anyhow!("No apks match {}", GLOB_PATTERN)),
218     }
219 }
220 
create_work_dir() -> Result<PathBuf, Error>221 fn create_work_dir() -> Result<PathBuf, Error> {
222     let s: String =
223         rand::thread_rng().sample_iter(&Alphanumeric).take(17).map(char::from).collect();
224     let work_dir = PathBuf::from("/data/local/tmp/microdroid").join(s);
225     println!("creating work dir {}", work_dir.display());
226     fs::create_dir_all(&work_dir).context("failed to mkdir")?;
227     Ok(work_dir)
228 }
229 
230 /// Run a VM with Microdroid
command_run_microdroid(config: RunMicrodroidConfig) -> Result<(), Error>231 pub fn command_run_microdroid(config: RunMicrodroidConfig) -> Result<(), Error> {
232     let apk = find_empty_payload_apk_path()?;
233     println!("found path {}", apk.display());
234 
235     let work_dir = config.work_dir.unwrap_or(create_work_dir()?);
236     let idsig = work_dir.join("apk.idsig");
237     println!("apk.idsig path: {}", idsig.display());
238     let instance_img = work_dir.join("instance.img");
239     println!("instance.img path: {}", instance_img.display());
240 
241     let mut app_config = RunAppConfig {
242         common: config.common,
243         debug: config.debug,
244         microdroid: config.microdroid,
245         apk,
246         idsig,
247         instance: instance_img,
248         payload_binary_name: Some("MicrodroidEmptyPayloadJniLib.so".to_owned()),
249         ..Default::default()
250     };
251 
252     if cfg!(llpvm_changes) {
253         app_config.set_instance_id(work_dir.join("instance_id"))?;
254         println!("instance_id file path: {}", app_config.instance_id()?.display());
255     }
256 
257     command_run_app(app_config)
258 }
259 
260 /// Run a VM from the given configuration file.
command_run(config: RunCustomVmConfig) -> Result<(), Error>261 pub fn command_run(config: RunCustomVmConfig) -> Result<(), Error> {
262     let config_file = File::open(&config.config).context("Failed to open config file")?;
263     let mut vm_config =
264         VmConfig::load(&config_file).context("Failed to parse config file")?.to_parcelable()?;
265     if let Some(mem) = config.common.mem {
266         vm_config.memoryMib = mem as i32;
267     }
268     if let Some(ref name) = config.common.name {
269         vm_config.name = name.to_string();
270     } else {
271         vm_config.name = String::from("VmRun");
272     }
273     if let Some(gdb) = config.debug.gdb {
274         vm_config.gdbPort = gdb.get() as i32;
275     }
276     vm_config.cpuTopology = config.common.cpu_topology;
277     vm_config.hugePages = config.common.hugepages;
278     vm_config.boostUclamp = config.common.boost_uclamp;
279     vm_config.teeServices = config.common.tee_services().to_vec();
280     run(
281         get_service()?.as_ref(),
282         &VirtualMachineConfig::RawConfig(vm_config),
283         &format!("{:?}", &config.config),
284         config.debug.console.as_ref().map(|p| p.as_ref()),
285         config.debug.console_in.as_ref().map(|p| p.as_ref()),
286         config.debug.log.as_ref().map(|p| p.as_ref()),
287         config.debug.dump_device_tree.as_ref().map(|p| p.as_ref()),
288     )
289 }
290 
state_to_str(vm_state: VirtualMachineState) -> &'static str291 fn state_to_str(vm_state: VirtualMachineState) -> &'static str {
292     match vm_state {
293         VirtualMachineState::NOT_STARTED => "NOT_STARTED",
294         VirtualMachineState::STARTING => "STARTING",
295         VirtualMachineState::STARTED => "STARTED",
296         VirtualMachineState::READY => "READY",
297         VirtualMachineState::FINISHED => "FINISHED",
298         VirtualMachineState::DEAD => "DEAD",
299         _ => "(invalid state)",
300     }
301 }
302 
run( service: &dyn IVirtualizationService, config: &VirtualMachineConfig, payload_config: &str, console_out_path: Option<&Path>, console_in_path: Option<&Path>, log_path: Option<&Path>, dump_device_tree: Option<&Path>, ) -> Result<(), Error>303 fn run(
304     service: &dyn IVirtualizationService,
305     config: &VirtualMachineConfig,
306     payload_config: &str,
307     console_out_path: Option<&Path>,
308     console_in_path: Option<&Path>,
309     log_path: Option<&Path>,
310     dump_device_tree: Option<&Path>,
311 ) -> Result<(), Error> {
312     let console_out = if let Some(console_out_path) = console_out_path {
313         Some(File::create(console_out_path).with_context(|| {
314             format!("Failed to open console output file {:?}", console_out_path)
315         })?)
316     } else {
317         Some(duplicate_fd(io::stdout())?)
318     };
319     let console_in =
320         if let Some(console_in_path) = console_in_path {
321             Some(File::open(console_in_path).with_context(|| {
322                 format!("Failed to open console input file {:?}", console_in_path)
323             })?)
324         } else {
325             Some(duplicate_fd(io::stdin())?)
326         };
327     let log = if let Some(log_path) = log_path {
328         Some(
329             File::create(log_path)
330                 .with_context(|| format!("Failed to open log file {:?}", log_path))?,
331         )
332     } else {
333         Some(duplicate_fd(io::stdout())?)
334     };
335     let dump_dt = if let Some(dump_device_tree) = dump_device_tree {
336         Some(File::create(dump_device_tree).with_context(|| {
337             format!("Failed to open file to dump device tree: {:?}", dump_device_tree)
338         })?)
339     } else {
340         None
341     };
342     let callback = Box::new(Callback {});
343     let vm =
344         VmInstance::create(service, config, console_out, console_in, log, dump_dt, Some(callback))
345             .context("Failed to create VM")?;
346     vm.start().context("Failed to start VM")?;
347 
348     let debug_level = get_debug_level(config).unwrap_or(DebugLevel::NONE);
349 
350     println!(
351         "Created {} from {} with CID {}, state is {}.",
352         if debug_level == DebugLevel::FULL { "debuggable VM" } else { "VM" },
353         payload_config,
354         vm.cid(),
355         state_to_str(vm.state()?)
356     );
357 
358     // Wait until the VM or VirtualizationService dies. If we just returned immediately then the
359     // IVirtualMachine Binder object would be dropped and the VM would be killed.
360     let death_reason = vm.wait_for_death();
361     println!("VM ended: {:?}", death_reason);
362     Ok(())
363 }
364 
parse_extra_apk_list(apk: &Path, config_path: &str) -> Result<Vec<PathBuf>, Error>365 fn parse_extra_apk_list(apk: &Path, config_path: &str) -> Result<Vec<PathBuf>, Error> {
366     let mut archive = ZipArchive::new(File::open(apk)?)?;
367     let config_file = archive.by_name(config_path)?;
368     let config: VmPayloadConfig = serde_json::from_reader(config_file)?;
369     Ok(config.extra_apks.into_iter().map(|x| x.path.into()).collect())
370 }
371 
372 struct Callback {}
373 
374 impl vmclient::VmCallback for Callback {
on_payload_started(&self, _cid: i32)375     fn on_payload_started(&self, _cid: i32) {
376         eprintln!("payload started");
377     }
378 
on_payload_ready(&self, _cid: i32)379     fn on_payload_ready(&self, _cid: i32) {
380         eprintln!("payload is ready");
381     }
382 
on_payload_finished(&self, _cid: i32, exit_code: i32)383     fn on_payload_finished(&self, _cid: i32, exit_code: i32) {
384         eprintln!("payload finished with exit code {}", exit_code);
385     }
386 
on_error(&self, _cid: i32, error_code: ErrorCode, message: &str)387     fn on_error(&self, _cid: i32, error_code: ErrorCode, message: &str) {
388         eprintln!("VM encountered an error: code={:?}, message={}", error_code, message);
389     }
390 }
391 
392 /// Safely duplicate the file descriptor.
duplicate_fd<T: AsFd>(file: T) -> io::Result<File>393 fn duplicate_fd<T: AsFd>(file: T) -> io::Result<File> {
394     Ok(file.as_fd().try_clone_to_owned()?.into())
395 }
396