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