1 // Copyright 2022, 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 //! Integration test for VM bootloader.
16 
17 use android_system_virtualizationservice::{
18     aidl::android::system::virtualizationservice::{
19         CpuTopology::CpuTopology, DiskImage::DiskImage, VirtualMachineConfig::VirtualMachineConfig,
20         VirtualMachineRawConfig::VirtualMachineRawConfig,
21     },
22     binder::{ParcelFileDescriptor, ProcessState},
23 };
24 use anyhow::{Context, Error};
25 use log::info;
26 use std::{
27     collections::{HashSet, VecDeque},
28     fs::File,
29     io::{self, BufRead, BufReader, Read, Write},
30     panic, thread,
31 };
32 use vmclient::{DeathReason, VmInstance};
33 
34 const VMBASE_EXAMPLE_KERNEL_PATH: &str = "vmbase_example_kernel.bin";
35 const VMBASE_EXAMPLE_BIOS_PATH: &str = "vmbase_example_bios.bin";
36 const TEST_DISK_IMAGE_PATH: &str = "test_disk.img";
37 const EMPTY_DISK_IMAGE_PATH: &str = "empty_disk.img";
38 
39 /// Runs the vmbase_example VM as an unprotected VM kernel via VirtualizationService.
40 #[test]
test_run_example_kernel_vm() -> Result<(), Error>41 fn test_run_example_kernel_vm() -> Result<(), Error> {
42     run_test(Some(open_payload(VMBASE_EXAMPLE_KERNEL_PATH)?), None)
43 }
44 
45 /// Runs the vmbase_example VM as an unprotected VM BIOS via VirtualizationService.
46 #[test]
test_run_example_bios_vm() -> Result<(), Error>47 fn test_run_example_bios_vm() -> Result<(), Error> {
48     run_test(None, Some(open_payload(VMBASE_EXAMPLE_BIOS_PATH)?))
49 }
50 
run_test( kernel: Option<ParcelFileDescriptor>, bootloader: Option<ParcelFileDescriptor>, ) -> Result<(), Error>51 fn run_test(
52     kernel: Option<ParcelFileDescriptor>,
53     bootloader: Option<ParcelFileDescriptor>,
54 ) -> Result<(), Error> {
55     android_logger::init_once(
56         android_logger::Config::default()
57             .with_tag("vmbase")
58             .with_max_level(log::LevelFilter::Debug),
59     );
60 
61     // Redirect panic messages to logcat.
62     panic::set_hook(Box::new(|panic_info| {
63         log::error!("{}", panic_info);
64     }));
65 
66     // We need to start the thread pool for Binder to work properly, especially link_to_death.
67     ProcessState::start_thread_pool();
68 
69     let virtmgr =
70         vmclient::VirtualizationService::new().context("Failed to spawn VirtualizationService")?;
71     let service = virtmgr.connect().context("Failed to connect to VirtualizationService")?;
72 
73     // Make file for test disk image.
74     let mut test_image = File::options()
75         .create(true)
76         .read(true)
77         .write(true)
78         .truncate(true)
79         .open(TEST_DISK_IMAGE_PATH)
80         .with_context(|| format!("Failed to open test disk image {}", TEST_DISK_IMAGE_PATH))?;
81     // Write 4 sectors worth of 4-byte numbers counting up.
82     for i in 0u32..512 {
83         test_image.write_all(&i.to_le_bytes())?;
84     }
85     let test_image = ParcelFileDescriptor::new(test_image);
86     let disk_image = DiskImage { image: Some(test_image), writable: false, partitions: vec![] };
87 
88     // Make file for empty test disk image.
89     let empty_image = File::options()
90         .create(true)
91         .read(true)
92         .write(true)
93         .truncate(true)
94         .open(EMPTY_DISK_IMAGE_PATH)
95         .with_context(|| format!("Failed to open empty disk image {}", EMPTY_DISK_IMAGE_PATH))?;
96     let empty_image = ParcelFileDescriptor::new(empty_image);
97     let empty_disk_image =
98         DiskImage { image: Some(empty_image), writable: false, partitions: vec![] };
99 
100     let config = VirtualMachineConfig::RawConfig(VirtualMachineRawConfig {
101         name: String::from("VmBaseTest"),
102         kernel,
103         initrd: None,
104         params: None,
105         bootloader,
106         disks: vec![disk_image, empty_disk_image],
107         protectedVm: false,
108         memoryMib: 300,
109         cpuTopology: CpuTopology::ONE_CPU,
110         platformVersion: "~1.0".to_string(),
111         gdbPort: 0, // no gdb
112         ..Default::default()
113     });
114     let (handle, console) = android_log_fd()?;
115     let (mut log_reader, log_writer) = pipe()?;
116     let vm = VmInstance::create(
117         service.as_ref(),
118         &config,
119         Some(console),
120         /* consoleIn */ None,
121         Some(log_writer),
122         /* dump_dt */ None,
123         None,
124     )
125     .context("Failed to create VM")?;
126     vm.start().context("Failed to start VM")?;
127     info!("Started example VM.");
128 
129     // Wait for VM to finish, and check that it shut down cleanly.
130     let death_reason = vm.wait_for_death();
131     assert_eq!(death_reason, DeathReason::Shutdown);
132     handle.join().unwrap();
133 
134     // Check that the expected string was written to the log VirtIO console device.
135     let expected = "Hello VirtIO console\n";
136     let mut log_output = String::new();
137     assert_eq!(log_reader.read_to_string(&mut log_output)?, expected.len());
138     assert_eq!(log_output, expected);
139 
140     Ok(())
141 }
142 
android_log_fd() -> Result<(thread::JoinHandle<()>, File), io::Error>143 fn android_log_fd() -> Result<(thread::JoinHandle<()>, File), io::Error> {
144     let (reader, writer) = pipe()?;
145     let handle = thread::spawn(|| VmLogProcessor::new(reader).run().unwrap());
146     Ok((handle, writer))
147 }
148 
pipe() -> io::Result<(File, File)>149 fn pipe() -> io::Result<(File, File)> {
150     let (reader_fd, writer_fd) = nix::unistd::pipe()?;
151     Ok((reader_fd.into(), writer_fd.into()))
152 }
153 
open_payload(path: &str) -> Result<ParcelFileDescriptor, Error>154 fn open_payload(path: &str) -> Result<ParcelFileDescriptor, Error> {
155     let file = File::open(path).with_context(|| format!("Failed to open VM image {path}"))?;
156     Ok(ParcelFileDescriptor::new(file))
157 }
158 
159 struct VmLogProcessor {
160     reader: Option<File>,
161     expected: VecDeque<String>,
162     unexpected: HashSet<String>,
163     had_unexpected: bool,
164 }
165 
166 impl VmLogProcessor {
messages() -> (VecDeque<String>, HashSet<String>)167     fn messages() -> (VecDeque<String>, HashSet<String>) {
168         let mut expected = VecDeque::new();
169         let mut unexpected = HashSet::new();
170         for log_lvl in ["[ERROR]", "[WARN]", "[INFO]", "[DEBUG]"] {
171             expected.push_back(format!("{log_lvl} Unsuppressed message"));
172             unexpected.insert(format!("{log_lvl} Suppressed message"));
173         }
174         (expected, unexpected)
175     }
176 
new(reader: File) -> Self177     fn new(reader: File) -> Self {
178         let (expected, unexpected) = Self::messages();
179         Self { reader: Some(reader), expected, unexpected, had_unexpected: false }
180     }
181 
verify(&mut self, msg: &str)182     fn verify(&mut self, msg: &str) {
183         if self.expected.front() == Some(&msg.to_owned()) {
184             self.expected.pop_front();
185         }
186         if !self.had_unexpected && self.unexpected.contains(msg) {
187             self.had_unexpected = true;
188         }
189     }
190 
run(mut self) -> Result<(), &'static str>191     fn run(mut self) -> Result<(), &'static str> {
192         for line in BufReader::new(self.reader.take().unwrap()).lines() {
193             let msg = line.unwrap();
194             info!("{msg}");
195             self.verify(&msg);
196         }
197         if !self.expected.is_empty() {
198             Err("missing expected log message")
199         } else if self.had_unexpected {
200             Err("unexpected log message")
201         } else {
202             Ok(())
203         }
204     }
205 }
206