Debian Codegraph @

debian/missing-sources/jiff/src/tz/system/android.rs

raw
1 use std::{
2 ffi::{c_char, c_void},
3 sync::OnceLock,
4 };
5
6 use alloc::vec::Vec;
7
8 use core::{ffi::CStr, mem, ptr::NonNull};
9
10 use crate::tz::{TimeZone, TimeZoneDatabase};
11
12 /// Attempts to find the default "system" time zone.
13 pub(super) fn get(db: &TimeZoneDatabase) -> Option<TimeZone> {
14 static PROPERTY_NAME: &str = "persist.sys.timezone\0";
15
16 static GETTER: OnceLock<Option<PropertyGetter>> = OnceLock::new();
17 let Some(getter) = GETTER.get_or_init(|| PropertyGetter::new()) else {
18 // We don't emit any messages here because `PropertyGetter::new()` will
19 // have already done so.
20 return None;
21 };
22 let tzname = getter.get(cstr(PROPERTY_NAME))?;
23 let Some(tzname) = core::str::from_utf8(&tzname).ok() else {
24 warn!(
25 "found `{PROPERTY_NAME}` name `{name}` on Android, \
26 but it's not valid UTF-8",
27 name = crate::util::escape::Bytes(&tzname),
28 );
29 return None;
30 };
31 let tz = match db.get(tzname) {
32 Ok(tz) => tz,
33 Err(_err) => {
34 warn!(
35 "found `{PROPERTY_NAME}` name `{tzname}` on Android, \
36 but could not find it in time zone database {db:?}",
37 );
38 return None;
39 }
40 };
41 debug!(
42 "found system time zone `{tzname}` from Android property \
43 `{PROPERTY_NAME}` and found entry for it in time zone \
44 database {db:?}",
45 );
46 Some(tz)
47 }
48
49 /// Given a path to a system default TZif file, return its corresponding
50 /// time zone.
51 ///
52 /// This doesn't do any symlink shenanigans like in other Unix environments,
53 /// although we could consider doing that. I think probably this is very
54 /// unlikely to be used on Android, although it can be by setting `TZ`.
55 pub(super) fn read(_db: &TimeZoneDatabase, path: &str) -> Option<TimeZone> {
56 match super::read_unnamed_tzif_file(path) {
57 Ok(tz) => Some(tz),
58 Err(_err) => {
59 trace!("failed to read {path} as unnamed time zone: {_err}");
60 None
61 }
62 }
63 }
64
65 /// An abstraction for safely reading Android system properties.
66 ///
67 /// Initialization of this should only be done once. Initialization
68 /// dynamically loads `libc`. But it does not read any properties. Instead,
69 /// we permit the time zone property to be looked up repeatedly, in case it
70 /// changes. So, our `libc` library handle remains invariant, but the values
71 /// of properties can change over the lifetime of the process.
72 ///
73 /// This copies the technique used by the `android-system-properties` crate.
74 /// Namely, we use `dlopen` instead of hard-coding our linking requirements
75 /// since this is apparently more flexible. I guess in the past, the hard-coded
76 /// extern functions broke, but this technique doesn't. Or at least, it "fails
77 /// gracefully" since this won't result in build errors but just runtime
78 /// errors that result in no time zone being found (and thus will result in an
79 /// automatic fallback to UTC).
80 ///
81 /// Our implementation of this idea is perhaps a bit simpler than what
82 /// `android-system-properties` does though. We don't bother supporting >10
83 /// year old versions of Android. (Although support for that could be added
84 /// if there was a real need.) Also, when this fails, we give better error
85 /// messages via `dlerror()` in the logs.
86 struct PropertyGetter {
87 /// A `dlopen` handle to `libc.so`.
88 ///
89 /// Note that since this is a bespoke property getter and we only ever
90 /// create a single instance in a process global static, this never gets
91 /// dropped. So we don't bother writing a `Drop` impl that calls `dlclose`.
92 /// Because it never gets dropped and because we load the symbols right
93 /// away at construction time, we never actually end up using it after
94 /// construction. We keep it around in case we want to refactor to this
95 /// to actually drop it for some reason.
96 _libc: NonNull<c_void>,
97 system_property_find: SystemPropertyFind,
98 system_property_read: SystemPropertyRead,
99 }
100
101 // SAFETY: It is presumably safe to call functions derived from `dlsym`
102 // symbols from multiple threads simultaneously. And it is presumably safe
103 // to call Android's property getter APIs from multiple threads simultaneously.
104 // This isn't technically documented (as far as I can see), but it would be
105 // crazytown if this weren't true.
106 unsafe impl Send for PropertyGetter {}
107 // SAFETY: It is presumably safe to call functions derived from `dlsym`
108 // symbols from multiple threads simultaneously. And it is presumably safe
109 // to call Android's property getter APIs from multiple threads simultaneously.
110 // This isn't technically documented (as far as I can see), but it would be
111 // crazytown if this weren't true.
112 unsafe impl Sync for PropertyGetter {}
113
114 impl PropertyGetter {
115 /// Creates a new property getter by `dlopen`'ing `libc.so`.
116 ///
117 /// If this fails for whatever reason, `None` is returned and WARN-level
118 /// log messages are emitted stating the reason for failure if it is known.
119 fn new() -> Option<PropertyGetter> {
120 // SAFETY: OK because we provide a valid NUL terminated string.
121 let handle = unsafe { dlopen(cstr("libc.so\0").as_ptr(), 0) };
122 let Some(libc) = NonNull::new(handle) else {
123 let _msg = dlerror_message();
124 warn!(
125 "could not open libc.so via `dlopen`: {err}",
126 err = crate::util::escape::Bytes(&_msg),
127 );
128 return None;
129 };
130
131 // SAFETY: Our `SystemPropertyFind` type definition matches what is
132 // declared in `include/sys/system_properties.h` on Android.
133 let system_property_find: SystemPropertyFind =
134 unsafe { load_symbol(libc, cstr("__system_property_find\0"))? };
135
136 // SAFETY: Our `SystemPropertyRead` type definition matches what is
137 // declared in `include/sys/system_properties.h` on Android.
138 let system_property_read: SystemPropertyRead = unsafe {
139 load_symbol(libc, cstr("__system_property_read_callback\0"))?
140 };
141
142 Some(PropertyGetter {
143 _libc: libc,
144 system_property_find,
145 system_property_read,
146 })
147 }
148
149 /// Reads the given property name into the `Vec<u8>` returned.
150 ///
151 /// If the property doesn't exist, then `None` is returned and a WARN-level
152 /// log message is emitted explaining why.
153 fn get(&self, name: &CStr) -> Option<Vec<u8>> {
154 unsafe extern "C" fn callback(
155 buf: *mut c_void,
156 _name: *const c_char,
157 value: *const c_char,
158 _serial: u32,
159 ) {
160 let buf = buf.cast::<Vec<u8>>();
161 // SAFETY: The implied contract of `__system_property_read_callback`
162 // is that `value` is a valid NUL terminated C string.
163 let value = unsafe { CStr::from_ptr(value) };
164 // SAFETY: We passed a valid `*mut Vec<u8>` to the callback, so
165 // casting it back to it is safe.
166 unsafe {
167 (*buf).extend_from_slice(value.to_bytes());
168 }
169 }
170
171 // SAFETY: `name` is a valid NUL terminated string and
172 // `system_property_find` is a valid function read from `dlsym`
173 // according to the declaration in `include/sys/system_properties.h`.
174 let prop_info = unsafe { (self.system_property_find)(name.as_ptr()) };
175 if prop_info.is_null() {
176 warn!(
177 "Android property name `{name}` not found",
178 name = crate::util::escape::Bytes(name.to_bytes()),
179 );
180 return None;
181 }
182
183 // N.B. A `prop_info` is an opaque pointer[1]... which means the
184 // implementation is probably allocating something in order to create
185 // it... right? But there's no API to free the pointer returned. And
186 // no other indication as to its lifetime. Once again, C is awful.
187 //
188 // [1]: https://android.googlesource.com/platform/bionic/+/master/libc/include/sys/system_properties.h#44
189
190 let mut buf = Vec::new();
191 // SAFETY: `name` is a valid NUL terminated string and
192 // `system_property_find` is a valid function read from `dlsym`
193 // according to the declaration in `include/sys/system_properties.h`.
194 unsafe {
195 let buf: *mut Vec<u8> = &mut buf;
196 (self.system_property_read)(
197 prop_info,
198 callback,
199 buf.cast::<c_void>(),
200 );
201 }
202 if buf.is_empty() {
203 warn!(
204 "reading Android property `{name}` resulted in empty value",
205 name = crate::util::escape::Bytes(name.to_bytes()),
206 );
207 return None;
208 }
209 Some(buf)
210 }
211 }
212
213 /// Loads a function symbol, of type `F`, from the given `dlopen` handle.
214 ///
215 /// If this fails, then `handle` is closed and `None` is returned and a
216 /// WARN-level log message is emitted with an error message if possible.
217 ///
218 /// # Safety
219 ///
220 /// Callers must ensure that `F` is a function type that matches the ABI of
221 /// the `symbol` in `handle`.
222 unsafe fn load_symbol<F>(handle: NonNull<c_void>, symbol: &CStr) -> Option<F> {
223 let sym =
224 // SAFETY: We know `handle` is non-null.
225 unsafe { dlsym(handle.as_ptr(), symbol.as_ptr()) };
226 if sym.is_null() {
227 // SAFETY: We know `handle` is non-null.
228 let _ = unsafe { dlclose(handle.as_ptr()) };
229 let _msg = dlerror_message();
230 warn!(
231 "could not load `{symbol}` \
232 symbol from `libc.so: {err}",
233 symbol = crate::util::escape::Bytes(symbol.to_bytes()),
234 err = crate::util::escape::Bytes(&_msg),
235 );
236 return None;
237 }
238 // SAFETY: The safety obligation here is forwarded to the caller. They
239 // must guarantee that `F` is an appropriate type.
240 // declared in `include/sys/system_properties.h` on Android.
241 let function = unsafe { mem::transmute_copy::<*mut c_void, F>(&sym) };
242 Some(function)
243 }
244
245 /// Returns the error message given by `dlerror`.
246 ///
247 /// Callers should only use this when they expect an error to have occurred
248 /// with one of the `dl*` APIs. If `dlerror` returns a null pointer, then a
249 /// generic "unknown error" message is returned.
250 fn dlerror_message() -> Vec<u8> {
251 // SAFETY: I believe `dlerror()` is always safe to call.
252 let msg = unsafe { dlerror() };
253 if msg.is_null() {
254 return b"unknown error".to_vec();
255 }
256 // SAFETY: We've verified that `msg` is not null and the contract of
257 // `dlerror` says that it returns a NUL terminated C string. Moreover,
258 // we do not hold on to this string and instead copy it to the heap
259 // immediately.
260 //
261 // One wonders if `dlerror()` is actually sound in this context. While
262 // Jiff can guarantee that itself will call `dlerror()` in only one
263 // thread, Jiff can't prevent other parts of the process from calling
264 // `dlerror()`. In particular, `dlerror(3)` says:
265 //
266 // > The message returned by dlerror() may reside in a statically allocated
267 // > buffer that is overwritten by subsequent dlerror() calls.
268 //
269 // But no mention is made about whether this statically allocated buffer
270 // is written to in a thread safe way. Or whether the string returned to
271 // the caller can be unceremoniously overwritten by a simultaneously
272 // executing thread.
273 //
274 // However, in practice, this could be sound if the libc in use is doing
275 // something sensible like using a thread local. Then I believe this is
276 // fine.
277 //
278 // My goodness C is awful. If this turns out to be unsound, then since
279 // `dlerror()` isn't essential, we'll probably just have to stop using it.
280 // So dumb.
281 //
282 // Note that in theory the error path should never be exercised.
283 let cstr = unsafe { CStr::from_ptr(msg) };
284 cstr.to_bytes().to_vec()
285 }
286
287 /// Creates a C string "literal" and returns it as a raw pointer.
288 ///
289 /// This panics if the string given contains a NUL byte.
290 fn cstr(string: &'static str) -> &'static CStr {
291 CStr::from_bytes_with_nul(string.as_bytes()).unwrap()
292 }
293
294 // We just define the FFI bindings ourselves instead of bringing in libc for
295 // this. We're only doing it for one platform, so it doesn't seem like a huge
296 // deal. But if this turns out to be a problem in practice, I'm fine accepting
297 // a target specific dependency on `libc` for Android.
298 extern "C" {
299 fn dlopen(filename: *const c_char, flag: i32) -> *mut c_void;
300 fn dlclose(handle: *mut c_void) -> i32;
301 fn dlerror() -> *mut c_char;
302 fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
303 }
304
305 // These types come from:
306 // https://android.googlesource.com/platform/bionic/+/master/libc/include/sys/system_properties.h
307 type PropInfo = c_void;
308 type SystemPropertyFind =
309 unsafe extern "C" fn(*const c_char) -> *const PropInfo;
310 type SystemPropertyRead = unsafe extern "C" fn(
311 *const PropInfo,
312 SystemPropertyReadCallback,
313 *mut c_void,
314 );
315 type SystemPropertyReadCallback =
316 unsafe extern "C" fn(*mut c_void, *const c_char, *const c_char, u32);