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