blob: e9bdab6a6c482b9ec61691a4332e7a66dbd3a245 [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 Wangd158e392023-08-30 12:51:12 +000027use service_vm_comm::{host_port, Request, Response};
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 Wang9a8b39f2023-04-12 15:31:48 +000044 boot_rialto_successfully(
45 SIGNED_RIALTO_PATH,
46 true, // protected_vm
47 )
48}
49
50#[test]
Alice Wang748b0322023-07-24 12:51:18 +000051fn boot_rialto_in_unprotected_vm_successfully() -> Result<()> {
Alice Wang9a8b39f2023-04-12 15:31:48 +000052 boot_rialto_successfully(
53 UNSIGNED_RIALTO_PATH,
54 false, // protected_vm
55 )
56}
57
Alice Wang748b0322023-07-24 12:51:18 +000058fn boot_rialto_successfully(rialto_path: &str, protected_vm: bool) -> Result<()> {
David Brazdil66fc1202022-07-04 21:48:45 +010059 android_logger::init_once(
60 android_logger::Config::default().with_tag("rialto").with_min_level(log::Level::Debug),
61 );
62
63 // Redirect panic messages to logcat.
64 panic::set_hook(Box::new(|panic_info| {
65 log::error!("{}", panic_info);
66 }));
67
68 // We need to start the thread pool for Binder to work properly, especially link_to_death.
69 ProcessState::start_thread_pool();
70
David Brazdil4b4c5102022-12-19 22:56:20 +000071 let virtmgr =
72 vmclient::VirtualizationService::new().context("Failed to spawn VirtualizationService")?;
73 let service = virtmgr.connect().context("Failed to connect to VirtualizationService")?;
74
Alice Wang9a8b39f2023-04-12 15:31:48 +000075 let rialto = File::open(rialto_path).context("Failed to open Rialto kernel binary")?;
David Brazdil66fc1202022-07-04 21:48:45 +010076 let console = android_log_fd()?;
77 let log = android_log_fd()?;
78
Alice Wang9a8b39f2023-04-12 15:31:48 +000079 let disks = if protected_vm {
80 let instance_img = File::options()
81 .create(true)
82 .read(true)
83 .write(true)
84 .truncate(true)
85 .open(INSTANCE_IMG_PATH)?;
86 let instance_img = ParcelFileDescriptor::new(instance_img);
87
88 service
89 .initializeWritablePartition(
90 &instance_img,
91 INSTANCE_IMG_SIZE,
92 PartitionType::ANDROID_VM_INSTANCE,
93 )
94 .context("Failed to initialize instange.img")?;
95 let writable_partitions = vec![Partition {
96 label: "vm-instance".to_owned(),
97 image: Some(instance_img),
98 writable: true,
99 }];
100 vec![DiskImage { image: None, partitions: writable_partitions, writable: true }]
101 } else {
102 vec![]
103 };
104
David Brazdil66fc1202022-07-04 21:48:45 +0100105 let config = VirtualMachineConfig::RawConfig(VirtualMachineRawConfig {
Seungjae Yoo62085c02022-08-12 04:44:52 +0000106 name: String::from("RialtoTest"),
David Brazdil66fc1202022-07-04 21:48:45 +0100107 kernel: None,
108 initrd: None,
109 params: None,
110 bootloader: Some(ParcelFileDescriptor::new(rialto)),
Alice Wang9a8b39f2023-04-12 15:31:48 +0000111 disks,
112 protectedVm: protected_vm,
David Brazdil66fc1202022-07-04 21:48:45 +0100113 memoryMib: 300,
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000114 cpuTopology: CpuTopology::ONE_CPU,
David Brazdil66fc1202022-07-04 21:48:45 +0100115 platformVersion: "~1.0".to_string(),
Nikita Ioffe5776f082023-02-10 21:38:26 +0000116 gdbPort: 0, // No gdb
Inseob Kim6ef80972023-07-20 17:23:36 +0900117 ..Default::default()
David Brazdil66fc1202022-07-04 21:48:45 +0100118 });
Jiyong Parke6fb1672023-06-26 16:45:55 +0900119 let vm = VmInstance::create(
120 service.as_ref(),
121 &config,
122 Some(console),
123 /* consoleIn */ None,
124 Some(log),
125 None,
126 )
127 .context("Failed to create VM")?;
David Brazdil66fc1202022-07-04 21:48:45 +0100128
Alice Wangd158e392023-08-30 12:51:12 +0000129 let port = host_port(protected_vm);
Alice Wang4e082c32023-07-11 07:41:50 +0000130 let check_socket_handle = thread::spawn(move || try_check_socket_connection(port).unwrap());
131
David Brazdil66fc1202022-07-04 21:48:45 +0100132 vm.start().context("Failed to start VM")?;
133
134 // Wait for VM to finish, and check that it shut down cleanly.
Alan Stokesdfca76c2022-08-03 13:31:47 +0100135 let death_reason = vm
136 .wait_for_death_with_timeout(Duration::from_secs(10))
137 .ok_or_else(|| anyhow!("Timed out waiting for VM exit"))?;
David Brazdil66fc1202022-07-04 21:48:45 +0100138 assert_eq!(death_reason, DeathReason::Shutdown);
139
Alice Wang4e082c32023-07-11 07:41:50 +0000140 match check_socket_handle.join() {
141 Ok(_) => {
142 info!(
143 "Received the echoed message. \
144 The socket connection between the host and the service VM works correctly."
145 )
146 }
147 Err(_) => bail!("The socket connection check failed."),
148 }
David Brazdil66fc1202022-07-04 21:48:45 +0100149 Ok(())
150}
151
152fn android_log_fd() -> io::Result<File> {
153 let (reader_fd, writer_fd) = nix::unistd::pipe()?;
154
155 // SAFETY: These are new FDs with no previous owner.
156 let reader = unsafe { File::from_raw_fd(reader_fd) };
Andrew Walbranae3350d2023-07-21 19:01:18 +0100157 // SAFETY: These are new FDs with no previous owner.
David Brazdil66fc1202022-07-04 21:48:45 +0100158 let writer = unsafe { File::from_raw_fd(writer_fd) };
159
160 thread::spawn(|| {
161 for line in BufReader::new(reader).lines() {
162 info!("{}", line.unwrap());
163 }
164 });
165 Ok(writer)
166}
Alice Wang4e082c32023-07-11 07:41:50 +0000167
Alice Wang748b0322023-07-24 12:51:18 +0000168fn try_check_socket_connection(port: u32) -> Result<()> {
Alice Wang4e082c32023-07-11 07:41:50 +0000169 info!("Setting up the listening socket on port {port}...");
170 let listener = VsockListener::bind_with_cid_port(VMADDR_CID_HOST, port)?;
171 info!("Listening on port {port}...");
172
Alice Wang748b0322023-07-24 12:51:18 +0000173 let mut vsock_stream =
174 listener.incoming().next().ok_or_else(|| anyhow!("Failed to get vsock_stream"))??;
Alice Wang4e082c32023-07-11 07:41:50 +0000175 info!("Accepted connection {:?}", vsock_stream);
Alice Wang4e082c32023-07-11 07:41:50 +0000176 vsock_stream.set_read_timeout(Some(Duration::from_millis(1_000)))?;
Alice Wang4e082c32023-07-11 07:41:50 +0000177
Alice Wang748b0322023-07-24 12:51:18 +0000178 const WRITE_BUFFER_CAPACITY: usize = 512;
179 let mut buffer = BufWriter::with_capacity(WRITE_BUFFER_CAPACITY, vsock_stream.clone());
180
181 // TODO(b/292080257): Test with message longer than the receiver's buffer capacity
182 // 1024 bytes once the guest virtio-vsock driver fixes the credit update in recv().
183 let message = "abc".repeat(166);
184 let request = Request::Reverse(message.as_bytes().to_vec());
185 ciborium::into_writer(&request, &mut buffer)?;
186 buffer.flush()?;
187 info!("Sent request: {request:?}.");
188
189 let response: Response = ciborium::from_reader(&mut vsock_stream)?;
190 info!("Received response: {response:?}.");
191
192 let expected_response: Vec<u8> = message.as_bytes().iter().rev().cloned().collect();
193 assert_eq!(Response::Reverse(expected_response), response);
Alice Wang4e082c32023-07-11 07:41:50 +0000194 Ok(())
195}