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