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