blob: 72f86c4a1ee5a22f4b9e09204692a36f369f3884 [file] [log] [blame]
Pierre-Clément Tosi6a42fdc2022-12-08 13:51:05 +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//! Low-level compatibility layer between baremetal Rust and Bionic C functions.
16
Pierre-Clément Tosi23c84c92023-07-14 16:50:56 +000017use crate::rand::fill_with_entropy;
Pierre-Clément Tosi67108c32023-06-30 11:04:02 +000018use crate::read_sysreg;
Charisee656095b2024-04-06 02:49:21 +000019use core::ffi::c_char;
20use core::ffi::c_int;
21use core::ffi::c_void;
22use core::ffi::CStr;
23use core::ptr::addr_of_mut;
24use core::slice;
25use core::str;
Pierre-Clément Tosi6a42fdc2022-12-08 13:51:05 +000026
Pierre-Clément Tosi1bf532b2023-11-13 11:06:20 +000027use cstr::cstr;
Pierre-Clément Tosi03939922024-06-06 12:44:49 +010028use log::error;
29use log::info;
Pierre-Clément Tosi1bf532b2023-11-13 11:06:20 +000030
Pierre-Clément Tosiba4af8a2022-12-20 17:32:37 +000031const EOF: c_int = -1;
Pierre-Clément Tosi23c84c92023-07-14 16:50:56 +000032const EIO: c_int = 5;
Pierre-Clément Tosiba4af8a2022-12-20 17:32:37 +000033
Pierre-Clément Tosi67108c32023-06-30 11:04:02 +000034/// Bionic thread-local storage.
35#[repr(C)]
36pub struct Tls {
37 /// Unused.
38 _unused: [u8; 40],
39 /// Use by the compiler as stack canary value.
40 pub stack_guard: u64,
41}
42
43/// Bionic TLS.
44///
45/// Provides the TLS used by Bionic code. This is unique as vmbase only supports one thread.
46///
47/// Note that the linker script re-exports __bionic_tls.stack_guard as __stack_chk_guard for
48/// compatibility with non-Bionic LLVM.
49#[link_section = ".data.stack_protector"]
50#[export_name = "__bionic_tls"]
51pub static mut TLS: Tls = Tls { _unused: [0; 40], stack_guard: 0 };
52
53/// Gets a reference to the TLS from the dedicated system register.
54pub fn __get_tls() -> &'static mut Tls {
55 let tpidr = read_sysreg!("tpidr_el0");
56 // SAFETY: The register is currently only written to once, from entry.S, with a valid value.
57 unsafe { &mut *(tpidr as *mut Tls) }
58}
59
Pierre-Clément Tosi6a42fdc2022-12-08 13:51:05 +000060#[no_mangle]
61extern "C" fn __stack_chk_fail() -> ! {
62 panic!("stack guard check failed");
63}
Pierre-Clément Tosia32c37c2022-12-08 13:54:03 +000064
65/// Called from C to cause abnormal program termination.
66#[no_mangle]
67extern "C" fn abort() -> ! {
68 panic!("C code called abort()")
69}
70
71/// Error number set and read by C functions.
72pub static mut ERRNO: c_int = 0;
73
74#[no_mangle]
75unsafe extern "C" fn __errno() -> *mut c_int {
Andrew Walbranc06e7342023-07-05 14:00:51 +000076 // SAFETY: C functions which call this are only called from the main thread, not from exception
77 // handlers.
Charisee656095b2024-04-06 02:49:21 +000078 unsafe { addr_of_mut!(ERRNO) as *mut _ }
Pierre-Clément Tosia32c37c2022-12-08 13:54:03 +000079}
80
Pierre-Clément Tosiba4af8a2022-12-20 17:32:37 +000081fn set_errno(value: c_int) {
Andrew Walbranc06e7342023-07-05 14:00:51 +000082 // SAFETY: vmbase is currently single-threaded.
Pierre-Clément Tosiba4af8a2022-12-20 17:32:37 +000083 unsafe { ERRNO = value };
84}
85
Pierre-Clément Tosi2c9d9372023-07-14 16:49:01 +000086fn get_errno() -> c_int {
87 // SAFETY: vmbase is currently single-threaded.
88 unsafe { ERRNO }
89}
90
Pierre-Clément Tosi23c84c92023-07-14 16:50:56 +000091#[no_mangle]
92extern "C" fn getentropy(buffer: *mut c_void, length: usize) -> c_int {
93 if length > 256 {
94 // The maximum permitted value for the length argument is 256.
95 set_errno(EIO);
96 return -1;
97 }
98
99 // SAFETY: Just like libc, we need to assume that `ptr` is valid.
100 let buffer = unsafe { slice::from_raw_parts_mut(buffer.cast::<u8>(), length) };
101 fill_with_entropy(buffer).unwrap();
102
103 0
104}
105
Pierre-Clément Tosia32c37c2022-12-08 13:54:03 +0000106/// Reports a fatal error detected by Bionic.
107///
108/// # Safety
109///
Andrew Walbranc06e7342023-07-05 14:00:51 +0000110/// Input strings `prefix` and `format` must be valid and properly NUL-terminated.
Pierre-Clément Tosia32c37c2022-12-08 13:54:03 +0000111///
112/// # Note
113///
114/// This Rust functions is missing the last argument of its C/C++ counterpart, a va_list.
115#[no_mangle]
116unsafe extern "C" fn async_safe_fatal_va_list(prefix: *const c_char, format: *const c_char) {
Andrew Walbranc06e7342023-07-05 14:00:51 +0000117 // SAFETY: The caller guaranteed that both strings were valid and NUL-terminated.
118 let (prefix, format) = unsafe { (CStr::from_ptr(prefix), CStr::from_ptr(format)) };
Pierre-Clément Tosia32c37c2022-12-08 13:54:03 +0000119
120 if let (Ok(prefix), Ok(format)) = (prefix.to_str(), format.to_str()) {
121 // We don't bother with printf formatting.
Pierre-Clément Tosi0bd98082024-06-06 12:44:49 +0100122 error!("FATAL BIONIC ERROR: {prefix}: \"{format}\" (unformatted)");
Pierre-Clément Tosia32c37c2022-12-08 13:54:03 +0000123 }
124}
Pierre-Clément Tosiba4af8a2022-12-20 17:32:37 +0000125
126#[repr(usize)]
127/// Arbitrary token FILE pseudo-pointers used by C to refer to the default streams.
128enum File {
129 Stdout = 0x7670cf00,
130 Stderr = 0x9d118200,
131}
132
Pierre-Clément Tosi03939922024-06-06 12:44:49 +0100133impl File {
134 fn write_lines(&self, s: &str) {
135 for line in s.split_inclusive('\n') {
136 let (line, ellipsis) = if let Some(stripped) = line.strip_suffix('\n') {
137 (stripped, "")
138 } else {
139 (line, " ...")
140 };
141
142 match self {
143 Self::Stdout => info!("{line}{ellipsis}"),
144 Self::Stderr => error!("{line}{ellipsis}"),
145 }
146 }
147 }
148}
149
Pierre-Clément Tosiba4af8a2022-12-20 17:32:37 +0000150impl TryFrom<usize> for File {
151 type Error = &'static str;
152
153 fn try_from(value: usize) -> Result<Self, Self::Error> {
154 match value {
155 x if x == File::Stdout as _ => Ok(File::Stdout),
156 x if x == File::Stderr as _ => Ok(File::Stderr),
157 _ => Err("Received Invalid FILE* from C"),
158 }
159 }
160}
161
162#[no_mangle]
163static stdout: File = File::Stdout;
164#[no_mangle]
165static stderr: File = File::Stderr;
166
167#[no_mangle]
168extern "C" fn fputs(c_str: *const c_char, stream: usize) -> c_int {
Andrew Walbranc06e7342023-07-05 14:00:51 +0000169 // SAFETY: Just like libc, we need to assume that `s` is a valid NULL-terminated string.
Pierre-Clément Tosiba4af8a2022-12-20 17:32:37 +0000170 let c_str = unsafe { CStr::from_ptr(c_str) };
171
Pierre-Clément Tosi03939922024-06-06 12:44:49 +0100172 if let (Ok(s), Ok(f)) = (c_str.to_str(), File::try_from(stream)) {
173 f.write_lines(s);
Pierre-Clément Tosiba4af8a2022-12-20 17:32:37 +0000174 0
175 } else {
176 set_errno(EOF);
177 EOF
178 }
179}
180
181#[no_mangle]
182extern "C" fn fwrite(ptr: *const c_void, size: usize, nmemb: usize, stream: usize) -> usize {
183 let length = size.saturating_mul(nmemb);
184
Andrew Walbranc06e7342023-07-05 14:00:51 +0000185 // SAFETY: Just like libc, we need to assume that `ptr` is valid.
Pierre-Clément Tosiba4af8a2022-12-20 17:32:37 +0000186 let bytes = unsafe { slice::from_raw_parts(ptr as *const u8, length) };
187
Pierre-Clément Tosi03939922024-06-06 12:44:49 +0100188 if let (Ok(s), Ok(f)) = (str::from_utf8(bytes), File::try_from(stream)) {
189 f.write_lines(s);
Pierre-Clément Tosiba4af8a2022-12-20 17:32:37 +0000190 length
191 } else {
192 0
193 }
194}
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +0000195
196#[no_mangle]
197extern "C" fn strerror(n: c_int) -> *mut c_char {
Pierre-Clément Tosi2c9d9372023-07-14 16:49:01 +0000198 cstr_error(n).as_ptr().cast_mut().cast()
199}
200
201#[no_mangle]
202extern "C" fn perror(s: *const c_char) {
203 let prefix = if s.is_null() {
204 None
205 } else {
206 // SAFETY: Just like libc, we need to assume that `s` is a valid NULL-terminated string.
207 let c_str = unsafe { CStr::from_ptr(s) };
Pierre-Clément Tosia6997512024-06-28 13:54:31 +0100208 if c_str.is_empty() {
Pierre-Clément Tosi2c9d9372023-07-14 16:49:01 +0000209 None
210 } else {
211 Some(c_str.to_str().unwrap())
212 }
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +0000213 };
214
Pierre-Clément Tosi2c9d9372023-07-14 16:49:01 +0000215 let error = cstr_error(get_errno()).to_str().unwrap();
216
217 if let Some(prefix) = prefix {
Pierre-Clément Tosi0bd98082024-06-06 12:44:49 +0100218 error!("{prefix}: {error}");
Pierre-Clément Tosi2c9d9372023-07-14 16:49:01 +0000219 } else {
Pierre-Clément Tosi0bd98082024-06-06 12:44:49 +0100220 error!("{error}");
Pierre-Clément Tosi2c9d9372023-07-14 16:49:01 +0000221 }
222}
223
224fn cstr_error(n: c_int) -> &'static CStr {
225 // Messages taken from errno(1).
226 match n {
227 0 => cstr!("Success"),
228 1 => cstr!("Operation not permitted"),
229 2 => cstr!("No such file or directory"),
230 3 => cstr!("No such process"),
231 4 => cstr!("Interrupted system call"),
232 5 => cstr!("Input/output error"),
233 6 => cstr!("No such device or address"),
234 7 => cstr!("Argument list too long"),
235 8 => cstr!("Exec format error"),
236 9 => cstr!("Bad file descriptor"),
237 10 => cstr!("No child processes"),
238 11 => cstr!("Resource temporarily unavailable"),
239 12 => cstr!("Cannot allocate memory"),
240 13 => cstr!("Permission denied"),
241 14 => cstr!("Bad address"),
242 15 => cstr!("Block device required"),
243 16 => cstr!("Device or resource busy"),
244 17 => cstr!("File exists"),
245 18 => cstr!("Invalid cross-device link"),
246 19 => cstr!("No such device"),
247 20 => cstr!("Not a directory"),
248 21 => cstr!("Is a directory"),
249 22 => cstr!("Invalid argument"),
250 23 => cstr!("Too many open files in system"),
251 24 => cstr!("Too many open files"),
252 25 => cstr!("Inappropriate ioctl for device"),
253 26 => cstr!("Text file busy"),
254 27 => cstr!("File too large"),
255 28 => cstr!("No space left on device"),
256 29 => cstr!("Illegal seek"),
257 30 => cstr!("Read-only file system"),
258 31 => cstr!("Too many links"),
259 32 => cstr!("Broken pipe"),
260 33 => cstr!("Numerical argument out of domain"),
261 34 => cstr!("Numerical result out of range"),
262 35 => cstr!("Resource deadlock avoided"),
263 36 => cstr!("File name too long"),
264 37 => cstr!("No locks available"),
265 38 => cstr!("Function not implemented"),
266 39 => cstr!("Directory not empty"),
267 40 => cstr!("Too many levels of symbolic links"),
268 42 => cstr!("No message of desired type"),
269 43 => cstr!("Identifier removed"),
270 44 => cstr!("Channel number out of range"),
271 45 => cstr!("Level 2 not synchronized"),
272 46 => cstr!("Level 3 halted"),
273 47 => cstr!("Level 3 reset"),
274 48 => cstr!("Link number out of range"),
275 49 => cstr!("Protocol driver not attached"),
276 50 => cstr!("No CSI structure available"),
277 51 => cstr!("Level 2 halted"),
278 52 => cstr!("Invalid exchange"),
279 53 => cstr!("Invalid request descriptor"),
280 54 => cstr!("Exchange full"),
281 55 => cstr!("No anode"),
282 56 => cstr!("Invalid request code"),
283 57 => cstr!("Invalid slot"),
284 59 => cstr!("Bad font file format"),
285 60 => cstr!("Device not a stream"),
286 61 => cstr!("No data available"),
287 62 => cstr!("Timer expired"),
288 63 => cstr!("Out of streams resources"),
289 64 => cstr!("Machine is not on the network"),
290 65 => cstr!("Package not installed"),
291 66 => cstr!("Object is remote"),
292 67 => cstr!("Link has been severed"),
293 68 => cstr!("Advertise error"),
294 69 => cstr!("Srmount error"),
295 70 => cstr!("Communication error on send"),
296 71 => cstr!("Protocol error"),
297 72 => cstr!("Multihop attempted"),
298 73 => cstr!("RFS specific error"),
299 74 => cstr!("Bad message"),
300 75 => cstr!("Value too large for defined data type"),
301 76 => cstr!("Name not unique on network"),
302 77 => cstr!("File descriptor in bad state"),
303 78 => cstr!("Remote address changed"),
304 79 => cstr!("Can not access a needed shared library"),
305 80 => cstr!("Accessing a corrupted shared library"),
306 81 => cstr!(".lib section in a.out corrupted"),
307 82 => cstr!("Attempting to link in too many shared libraries"),
308 83 => cstr!("Cannot exec a shared library directly"),
309 84 => cstr!("Invalid or incomplete multibyte or wide character"),
310 85 => cstr!("Interrupted system call should be restarted"),
311 86 => cstr!("Streams pipe error"),
312 87 => cstr!("Too many users"),
313 88 => cstr!("Socket operation on non-socket"),
314 89 => cstr!("Destination address required"),
315 90 => cstr!("Message too long"),
316 91 => cstr!("Protocol wrong type for socket"),
317 92 => cstr!("Protocol not available"),
318 93 => cstr!("Protocol not supported"),
319 94 => cstr!("Socket type not supported"),
320 95 => cstr!("Operation not supported"),
321 96 => cstr!("Protocol family not supported"),
322 97 => cstr!("Address family not supported by protocol"),
323 98 => cstr!("Address already in use"),
324 99 => cstr!("Cannot assign requested address"),
325 100 => cstr!("Network is down"),
326 101 => cstr!("Network is unreachable"),
327 102 => cstr!("Network dropped connection on reset"),
328 103 => cstr!("Software caused connection abort"),
329 104 => cstr!("Connection reset by peer"),
330 105 => cstr!("No buffer space available"),
331 106 => cstr!("Transport endpoint is already connected"),
332 107 => cstr!("Transport endpoint is not connected"),
333 108 => cstr!("Cannot send after transport endpoint shutdown"),
334 109 => cstr!("Too many references: cannot splice"),
335 110 => cstr!("Connection timed out"),
336 111 => cstr!("Connection refused"),
337 112 => cstr!("Host is down"),
338 113 => cstr!("No route to host"),
339 114 => cstr!("Operation already in progress"),
340 115 => cstr!("Operation now in progress"),
341 116 => cstr!("Stale file handle"),
342 117 => cstr!("Structure needs cleaning"),
343 118 => cstr!("Not a XENIX named type file"),
344 119 => cstr!("No XENIX semaphores available"),
345 120 => cstr!("Is a named type file"),
346 121 => cstr!("Remote I/O error"),
347 122 => cstr!("Disk quota exceeded"),
348 123 => cstr!("No medium found"),
349 124 => cstr!("Wrong medium type"),
350 125 => cstr!("Operation canceled"),
351 126 => cstr!("Required key not available"),
352 127 => cstr!("Key has expired"),
353 128 => cstr!("Key has been revoked"),
354 129 => cstr!("Key was rejected by service"),
355 130 => cstr!("Owner died"),
356 131 => cstr!("State not recoverable"),
357 132 => cstr!("Operation not possible due to RF-kill"),
358 133 => cstr!("Memory page has hardware error"),
359 _ => cstr!("Unknown errno value"),
360 }
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +0000361}