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