blob: f7df217c7d5088ed2962f6cccee75af3253383eb [file] [log] [blame]
David Brazdil66fc1202022-07-04 21:48:45 +01001// 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 Rialto.
16
17use android_system_virtualizationservice::{
18 aidl::android::system::virtualizationservice::{
Alice Wang9a8b39f2023-04-12 15:31:48 +000019 CpuTopology::CpuTopology, DiskImage::DiskImage, Partition::Partition,
20 PartitionType::PartitionType, VirtualMachineConfig::VirtualMachineConfig,
David Brazdil66fc1202022-07-04 21:48:45 +010021 VirtualMachineRawConfig::VirtualMachineRawConfig,
22 },
23 binder::{ParcelFileDescriptor, ProcessState},
24};
Alice Wang748b0322023-07-24 12:51:18 +000025use anyhow::{anyhow, bail, Context, Result};
David Brazdil66fc1202022-07-04 21:48:45 +010026use log::info;
Alice Wang1d9a5872023-09-06 14:32:36 +000027use service_vm_comm::{Request, Response, VmType};
David Brazdil66fc1202022-07-04 21:48:45 +010028use std::fs::File;
Alice Wang748b0322023-07-24 12:51:18 +000029use std::io::{self, BufRead, BufReader, BufWriter, Write};
David Brazdil66fc1202022-07-04 21:48:45 +010030use std::os::unix::io::FromRawFd;
31use std::panic;
32use std::thread;
Alan Stokesdfca76c2022-08-03 13:31:47 +010033use std::time::Duration;
David Brazdil66fc1202022-07-04 21:48:45 +010034use vmclient::{DeathReason, VmInstance};
Alice Wang4e082c32023-07-11 07:41:50 +000035use vsock::{VsockListener, VMADDR_CID_HOST};
36
Alice Wang9a8b39f2023-04-12 15:31:48 +000037const SIGNED_RIALTO_PATH: &str = "/data/local/tmp/rialto_test/arm64/rialto.bin";
38const UNSIGNED_RIALTO_PATH: &str = "/data/local/tmp/rialto_test/arm64/rialto_unsigned.bin";
39const INSTANCE_IMG_PATH: &str = "/data/local/tmp/rialto_test/arm64/instance.img";
40const INSTANCE_IMG_SIZE: i64 = 1024 * 1024; // 1MB
David Brazdil66fc1202022-07-04 21:48:45 +010041
David Brazdil66fc1202022-07-04 21:48:45 +010042#[test]
Alice Wang748b0322023-07-24 12:51:18 +000043fn boot_rialto_in_protected_vm_successfully() -> Result<()> {
Alice Wang1d9a5872023-09-06 14:32:36 +000044 boot_rialto_successfully(SIGNED_RIALTO_PATH, VmType::ProtectedVm)
Alice Wang9a8b39f2023-04-12 15:31:48 +000045}
46
47#[test]
Alice Wang748b0322023-07-24 12:51:18 +000048fn boot_rialto_in_unprotected_vm_successfully() -> Result<()> {
Alice Wang1d9a5872023-09-06 14:32:36 +000049 boot_rialto_successfully(UNSIGNED_RIALTO_PATH, VmType::NonProtectedVm)
Alice Wang9a8b39f2023-04-12 15:31:48 +000050}
51
Alice Wang1d9a5872023-09-06 14:32:36 +000052fn boot_rialto_successfully(rialto_path: &str, vm_type: VmType) -> Result<()> {
David Brazdil66fc1202022-07-04 21:48:45 +010053 android_logger::init_once(
54 android_logger::Config::default().with_tag("rialto").with_min_level(log::Level::Debug),
55 );
56
57 // Redirect panic messages to logcat.
58 panic::set_hook(Box::new(|panic_info| {
59 log::error!("{}", panic_info);
60 }));
61
62 // We need to start the thread pool for Binder to work properly, especially link_to_death.
63 ProcessState::start_thread_pool();
64
David Brazdil4b4c5102022-12-19 22:56:20 +000065 let virtmgr =
66 vmclient::VirtualizationService::new().context("Failed to spawn VirtualizationService")?;
67 let service = virtmgr.connect().context("Failed to connect to VirtualizationService")?;
68
Alice Wang9a8b39f2023-04-12 15:31:48 +000069 let rialto = File::open(rialto_path).context("Failed to open Rialto kernel binary")?;
David Brazdil66fc1202022-07-04 21:48:45 +010070 let console = android_log_fd()?;
71 let log = android_log_fd()?;
72
Alice Wang1d9a5872023-09-06 14:32:36 +000073 let disks = match vm_type {
74 VmType::ProtectedVm => {
75 let instance_img = File::options()
76 .create(true)
77 .read(true)
78 .write(true)
79 .truncate(true)
80 .open(INSTANCE_IMG_PATH)?;
81 let instance_img = ParcelFileDescriptor::new(instance_img);
Alice Wang9a8b39f2023-04-12 15:31:48 +000082
Alice Wang1d9a5872023-09-06 14:32:36 +000083 service
84 .initializeWritablePartition(
85 &instance_img,
86 INSTANCE_IMG_SIZE,
87 PartitionType::ANDROID_VM_INSTANCE,
88 )
89 .context("Failed to initialize instange.img")?;
90 let writable_partitions = vec![Partition {
91 label: "vm-instance".to_owned(),
92 image: Some(instance_img),
93 writable: true,
94 }];
95 vec![DiskImage { image: None, partitions: writable_partitions, writable: true }]
96 }
97 VmType::NonProtectedVm => vec![],
Alice Wang9a8b39f2023-04-12 15:31:48 +000098 };
99
David Brazdil66fc1202022-07-04 21:48:45 +0100100 let config = VirtualMachineConfig::RawConfig(VirtualMachineRawConfig {
Seungjae Yoo62085c02022-08-12 04:44:52 +0000101 name: String::from("RialtoTest"),
David Brazdil66fc1202022-07-04 21:48:45 +0100102 kernel: None,
103 initrd: None,
104 params: None,
105 bootloader: Some(ParcelFileDescriptor::new(rialto)),
Alice Wang9a8b39f2023-04-12 15:31:48 +0000106 disks,
Alice Wang1d9a5872023-09-06 14:32:36 +0000107 protectedVm: vm_type.is_protected(),
David Brazdil66fc1202022-07-04 21:48:45 +0100108 memoryMib: 300,
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000109 cpuTopology: CpuTopology::ONE_CPU,
David Brazdil66fc1202022-07-04 21:48:45 +0100110 platformVersion: "~1.0".to_string(),
Nikita Ioffe5776f082023-02-10 21:38:26 +0000111 gdbPort: 0, // No gdb
Inseob Kim6ef80972023-07-20 17:23:36 +0900112 ..Default::default()
David Brazdil66fc1202022-07-04 21:48:45 +0100113 });
Jiyong Parke6fb1672023-06-26 16:45:55 +0900114 let vm = VmInstance::create(
115 service.as_ref(),
116 &config,
117 Some(console),
118 /* consoleIn */ None,
119 Some(log),
120 None,
121 )
122 .context("Failed to create VM")?;
David Brazdil66fc1202022-07-04 21:48:45 +0100123
Alice Wang1d9a5872023-09-06 14:32:36 +0000124 let check_socket_handle =
125 thread::spawn(move || try_check_socket_connection(vm_type.port()).unwrap());
Alice Wang4e082c32023-07-11 07:41:50 +0000126
David Brazdil66fc1202022-07-04 21:48:45 +0100127 vm.start().context("Failed to start VM")?;
128
129 // Wait for VM to finish, and check that it shut down cleanly.
Alan Stokesdfca76c2022-08-03 13:31:47 +0100130 let death_reason = vm
131 .wait_for_death_with_timeout(Duration::from_secs(10))
132 .ok_or_else(|| anyhow!("Timed out waiting for VM exit"))?;
David Brazdil66fc1202022-07-04 21:48:45 +0100133 assert_eq!(death_reason, DeathReason::Shutdown);
134
Alice Wang4e082c32023-07-11 07:41:50 +0000135 match check_socket_handle.join() {
136 Ok(_) => {
137 info!(
138 "Received the echoed message. \
139 The socket connection between the host and the service VM works correctly."
140 )
141 }
142 Err(_) => bail!("The socket connection check failed."),
143 }
David Brazdil66fc1202022-07-04 21:48:45 +0100144 Ok(())
145}
146
147fn android_log_fd() -> io::Result<File> {
148 let (reader_fd, writer_fd) = nix::unistd::pipe()?;
149
150 // SAFETY: These are new FDs with no previous owner.
151 let reader = unsafe { File::from_raw_fd(reader_fd) };
Andrew Walbranae3350d2023-07-21 19:01:18 +0100152 // SAFETY: These are new FDs with no previous owner.
David Brazdil66fc1202022-07-04 21:48:45 +0100153 let writer = unsafe { File::from_raw_fd(writer_fd) };
154
155 thread::spawn(|| {
156 for line in BufReader::new(reader).lines() {
157 info!("{}", line.unwrap());
158 }
159 });
160 Ok(writer)
161}
Alice Wang4e082c32023-07-11 07:41:50 +0000162
Alice Wang748b0322023-07-24 12:51:18 +0000163fn try_check_socket_connection(port: u32) -> Result<()> {
Alice Wang4e082c32023-07-11 07:41:50 +0000164 info!("Setting up the listening socket on port {port}...");
165 let listener = VsockListener::bind_with_cid_port(VMADDR_CID_HOST, port)?;
166 info!("Listening on port {port}...");
167
Alice Wang748b0322023-07-24 12:51:18 +0000168 let mut vsock_stream =
169 listener.incoming().next().ok_or_else(|| anyhow!("Failed to get vsock_stream"))??;
Alice Wang4e082c32023-07-11 07:41:50 +0000170 info!("Accepted connection {:?}", vsock_stream);
Alice Wang4e082c32023-07-11 07:41:50 +0000171 vsock_stream.set_read_timeout(Some(Duration::from_millis(1_000)))?;
Alice Wang4e082c32023-07-11 07:41:50 +0000172
Alice Wang748b0322023-07-24 12:51:18 +0000173 const WRITE_BUFFER_CAPACITY: usize = 512;
174 let mut buffer = BufWriter::with_capacity(WRITE_BUFFER_CAPACITY, vsock_stream.clone());
175
176 // TODO(b/292080257): Test with message longer than the receiver's buffer capacity
177 // 1024 bytes once the guest virtio-vsock driver fixes the credit update in recv().
178 let message = "abc".repeat(166);
179 let request = Request::Reverse(message.as_bytes().to_vec());
180 ciborium::into_writer(&request, &mut buffer)?;
181 buffer.flush()?;
182 info!("Sent request: {request:?}.");
183
184 let response: Response = ciborium::from_reader(&mut vsock_stream)?;
185 info!("Received response: {response:?}.");
186
187 let expected_response: Vec<u8> = message.as_bytes().iter().rev().cloned().collect();
188 assert_eq!(Response::Reverse(expected_response), response);
Alice Wang4e082c32023-07-11 07:41:50 +0000189 Ok(())
190}