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