blob: 1bd38cac1ffdd3cc9dd7c6cfd631771b3560fe18 [file] [log] [blame]
Andrew Walbranb996b4a2022-04-22 15:15:41 +00001// 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//! Rust entry point.
16
Pierre-Clément Tosid3305482023-06-29 15:03:48 +000017use crate::{
Michał Mazurekf08509a2025-01-24 11:39:24 +000018 arch::layout::{UART_ADDRESSES, UART_PAGE_ADDR},
19 bionic, console, heap, logger,
Pierre-Clément Tosiae071612024-11-02 13:13:34 +000020 memory::{switch_to_dynamic_page_tables, PAGE_SIZE, SIZE_16KB, SIZE_4KB},
Pierre-Clément Tosid3305482023-06-29 15:03:48 +000021 power::{reboot, shutdown},
Pierre-Clément Tosi62ffc0d2023-06-30 09:31:56 +000022 rand,
Pierre-Clément Tosid3305482023-06-29 15:03:48 +000023};
Pierre-Clément Tosi62ffc0d2023-06-30 09:31:56 +000024use core::mem::size_of;
Per Larsen7ec45d32024-11-02 00:56:46 +000025use hypervisor_backends::{get_mmio_guard, Error};
Pierre-Clément Tosic08e63c2024-05-14 11:17:47 +010026use static_assertions::const_assert_eq;
Pierre-Clément Tosid3305482023-06-29 15:03:48 +000027
Per Larsen7ec45d32024-11-02 00:56:46 +000028fn try_console_init() -> Result<(), Error> {
29 if let Some(mmio_guard) = get_mmio_guard() {
Pierre-Clément Tosi15ae4a52023-07-11 13:31:31 +000030 mmio_guard.enroll()?;
Pierre-Clément Tosi32d96792024-04-29 01:19:37 +010031
32 // TODO(ptosi): Use MmioSharer::share() to properly track this MMIO_GUARD_MAP.
33 //
Pierre-Clément Tosic08e63c2024-05-14 11:17:47 +010034 // The following call shares the UART but also anything else present in 0..granule.
35 //
36 // For 4KiB, that's only the UARTs. For 16KiB, it also covers the RTC and watchdog but, as
37 // neither is used by vmbase clients (and as both are outside of the UART page), they
38 // will never have valid stage-1 mappings to those devices. As a result, this
39 // MMIO_GUARD_MAP isn't affected by the granule size in any visible way. Larger granule
40 // sizes will need to be checked separately, if needed.
41 assert!({
42 let granule = mmio_guard.granule()?;
43 granule == SIZE_4KB || granule == SIZE_16KB
44 });
45 // Validate the assumption above by ensuring that the UART is not moved to another page:
Pierre-Clément Tosi38a36212024-06-06 11:30:39 +010046 const_assert_eq!(UART_PAGE_ADDR, 0);
47 mmio_guard.map(UART_PAGE_ADDR)?;
Pierre-Clément Tosid3305482023-06-29 15:03:48 +000048 }
49
Pierre-Clément Tosi8e92d1a2024-06-18 16:15:14 +010050 // SAFETY: UART_PAGE is mapped at stage-1 (see entry.S) and was just MMIO-guarded.
Pierre-Clément Tosi075aade2024-06-18 20:08:13 +010051 unsafe { console::init(&UART_ADDRESSES) };
Pierre-Clément Tosi8e92d1a2024-06-18 16:15:14 +010052
Pierre-Clément Tosid3305482023-06-29 15:03:48 +000053 Ok(())
54}
Andrew Walbranb996b4a2022-04-22 15:15:41 +000055
56/// This is the entry point to the Rust code, called from the binary entry point in `entry.S`.
57#[no_mangle]
Andrew Walbrane03395a2022-04-29 15:15:49 +000058extern "C" fn rust_entry(x0: u64, x1: u64, x2: u64, x3: u64) -> ! {
Andrew Walbran2e059cc2024-10-15 18:22:05 +010059 heap::init();
Pierre-Clément Tosid3305482023-06-29 15:03:48 +000060
61 if try_console_init().is_err() {
62 // Don't panic (or log) here to avoid accessing the console.
63 reboot()
64 }
65
66 logger::init().expect("Failed to initialize the logger");
67 // We initialize the logger to Off (like the log crate) and clients should log::set_max_level.
68
Pierre-Clément Tosi62ffc0d2023-06-30 09:31:56 +000069 const SIZE_OF_STACK_GUARD: usize = size_of::<u64>();
70 let mut stack_guard = [0u8; SIZE_OF_STACK_GUARD];
71 // We keep a null byte at the top of the stack guard to act as a string terminator.
72 let random_guard = &mut stack_guard[..(SIZE_OF_STACK_GUARD - 1)];
73
Pierre-Clément Tosi20daaef2023-10-26 11:34:55 +010074 if let Err(e) = rand::init() {
75 panic!("Failed to initialize a source of entropy: {e}");
76 }
77
78 if let Err(e) = rand::fill_with_entropy(random_guard) {
79 panic!("Failed to get stack canary entropy: {e}");
80 }
81
Pierre-Clément Tosi62ffc0d2023-06-30 09:31:56 +000082 bionic::__get_tls().stack_guard = u64::from_ne_bytes(stack_guard);
83
Pierre-Clément Tosiae071612024-11-02 13:13:34 +000084 switch_to_dynamic_page_tables();
85
Pierre-Clément Tosi62ffc0d2023-06-30 09:31:56 +000086 // Note: If rust_entry ever returned (which it shouldn't by being -> !), the compiler-injected
87 // stack guard comparison would detect a mismatch and call __stack_chk_fail.
88
Andrew Walbranc06e7342023-07-05 14:00:51 +000089 // SAFETY: `main` is provided by the application using the `main!` macro, and we make sure it
90 // has the right type.
Andrew Walbranb996b4a2022-04-22 15:15:41 +000091 unsafe {
Andrew Walbrane03395a2022-04-29 15:15:49 +000092 main(x0, x1, x2, x3);
Andrew Walbranb996b4a2022-04-22 15:15:41 +000093 }
94 shutdown();
95}
96
97extern "Rust" {
98 /// Main function provided by the application using the `main!` macro.
Andrew Walbrane03395a2022-04-29 15:15:49 +000099 fn main(arg0: u64, arg1: u64, arg2: u64, arg3: u64);
Andrew Walbranb996b4a2022-04-22 15:15:41 +0000100}
101
102/// Marks the main function of the binary.
103///
Pierre-Clément Tosid3305482023-06-29 15:03:48 +0000104/// Once main is entered, it can assume that:
105/// - The panic_handler has been configured and panic!() and friends are available;
106/// - The global_allocator has been configured and heap memory is available;
107/// - The logger has been configured and the log::{info, warn, error, ...} macros are available.
108///
Andrew Walbranb996b4a2022-04-22 15:15:41 +0000109/// Example:
110///
111/// ```rust
Pierre-Clément Tosid3305482023-06-29 15:03:48 +0000112/// use vmbase::main;
Jakob Vukalovicef996292023-04-13 14:28:34 +0000113/// use log::{info, LevelFilter};
Andrew Walbranb996b4a2022-04-22 15:15:41 +0000114///
115/// main!(my_main);
116///
117/// fn my_main() {
Pierre-Clément Tosid3305482023-06-29 15:03:48 +0000118/// log::set_max_level(LevelFilter::Info);
Jakob Vukalovicef996292023-04-13 14:28:34 +0000119/// info!("Hello world");
Andrew Walbranb996b4a2022-04-22 15:15:41 +0000120/// }
121/// ```
122#[macro_export]
123macro_rules! main {
124 ($name:path) => {
125 // Export a symbol with a name matching the extern declaration above.
126 #[export_name = "main"]
Andrew Walbrane03395a2022-04-29 15:15:49 +0000127 fn __main(arg0: u64, arg1: u64, arg2: u64, arg3: u64) {
Andrew Walbranb996b4a2022-04-22 15:15:41 +0000128 // Ensure that the main function provided by the application has the correct type.
Andrew Walbrane03395a2022-04-29 15:15:49 +0000129 $name(arg0, arg1, arg2, arg3)
Andrew Walbranb996b4a2022-04-22 15:15:41 +0000130 }
131 };
132}
Pierre-Clément Tosi1f7c5232024-08-13 19:51:25 +0100133
134/// Prepends a Linux kernel header to the generated binary image.
135///
136/// See https://docs.kernel.org/arch/arm64/booting.html
137/// ```
138#[macro_export]
139macro_rules! generate_image_header {
140 () => {
141 #[cfg(not(target_endian = "little"))]
142 compile_error!("Image header uses wrong endianness: bootloaders expect LE!");
143
144 core::arch::global_asm!(
145 // This section gets linked at the start of the image.
146 ".section .init.head, \"ax\"",
147 // This prevents the macro from being called more than once.
148 ".global image_header",
149 "image_header:",
150 // Linux uses a special NOP to be ELF-compatible; we're not.
151 "nop", // code0
152 "b entry", // code1
153 ".quad 0", // text_offset
154 ".quad bin_end - image_header", // image_size
155 ".quad (1 << 1)", // flags (PAGE_SIZE=4KiB)
156 ".quad 0", // res2
157 ".quad 0", // res3
158 ".quad 0", // res4
159 ".ascii \"ARM\x64\"", // magic
160 ".long 0", // res5
161 );
162 };
163}
164
165// If this fails, the image header flags are out-of-sync with PAGE_SIZE!
166static_assertions::const_assert_eq!(PAGE_SIZE, SIZE_4KB);