Debian Codegraph @

debian/rust-vendor/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. UPDATE: We don't give better error
86 /// messages any more because `dlerror()` isn't sound to use for all possible
87 /// libc implementations in a multi-threaded environment.
88 struct PropertyGetter {
89 /// A `dlopen` handle to `libc.so`.
90 ///
91 /// Note that since this is a bespoke property getter and we only ever
92 /// create a single instance in a process global static, this never gets
93 /// dropped. So we don't bother writing a `Drop` impl that calls `dlclose`.
94 /// Because it never gets dropped and because we load the symbols right
95 /// away at construction time, we never actually end up using it after
96 /// construction. We keep it around in case we want to refactor to this
97 /// to actually drop it for some reason.
98 _libc: NonNull<c_void>,
99 system_property_find: SystemPropertyFind,
100 system_property_read: SystemPropertyRead,
101 }
102
103 // SAFETY: It is presumably safe to call functions derived from `dlsym`
104 // symbols from multiple threads simultaneously. And it is presumably safe
105 // to call Android's property getter APIs from multiple threads simultaneously.
106 // This isn't technically documented (as far as I can see), but it would be
107 // crazytown if this weren't true.
108 unsafe impl Send for PropertyGetter {}
109 // SAFETY: It is presumably safe to call functions derived from `dlsym`
110 // symbols from multiple threads simultaneously. And it is presumably safe
111 // to call Android's property getter APIs from multiple threads simultaneously.
112 // This isn't technically documented (as far as I can see), but it would be
113 // crazytown if this weren't true.
114 unsafe impl Sync for PropertyGetter {}
115
116 impl PropertyGetter {
117 /// Creates a new property getter by `dlopen`'ing `libc.so`.
118 ///
119 /// If this fails for whatever reason, `None` is returned and WARN-level
120 /// log messages are emitted stating the reason for failure if it is known.
121 fn new() -> Option<PropertyGetter> {
122 // SAFETY: OK because we provide a valid NUL terminated string.
123 let handle = unsafe { dlopen(cstr("libc.so\0").as_ptr(), 0) };
124 let Some(libc) = NonNull::new(handle) else {
125 warn!("could not open libc.so via `dlopen`:");
126 return None;
127 };
128
129 // SAFETY: Our `SystemPropertyFind` type definition matches what is
130 // declared in `include/sys/system_properties.h` on Android.
131 let system_property_find: SystemPropertyFind =
132 unsafe { load_symbol(libc, cstr("__system_property_find\0"))? };
133
134 // SAFETY: Our `SystemPropertyRead` type definition matches what is
135 // declared in `include/sys/system_properties.h` on Android.
136 let system_property_read: SystemPropertyRead = unsafe {
137 load_symbol(libc, cstr("__system_property_read_callback\0"))?
138 };
139
140 Some(PropertyGetter {
141 _libc: libc,
142 system_property_find,
143 system_property_read,
144 })
145 }
146
147 /// Reads the given property name into the `Vec<u8>` returned.
148 ///
149 /// If the property doesn't exist, then `None` is returned and a WARN-level
150 /// log message is emitted explaining why.
151 fn get(&self, name: &CStr) -> Option<Vec<u8>> {
152 unsafe extern "C" fn callback(
153 buf: *mut c_void,
154 _name: *const c_char,
155 value: *const c_char,
156 _serial: u32,
157 ) {
158 let buf = buf.cast::<Vec<u8>>();
159 // SAFETY: The implied contract of `__system_property_read_callback`
160 // is that `value` is a valid NUL terminated C string.
161 let value = unsafe { CStr::from_ptr(value) };
162 // SAFETY: We passed a valid `*mut Vec<u8>` to the callback, so
163 // casting it back to it is safe.
164 unsafe {
165 (*buf).extend_from_slice(value.to_bytes());
166 }
167 }
168
169 // SAFETY: `name` is a valid NUL terminated string and
170 // `system_property_find` is a valid function read from `dlsym`
171 // according to the declaration in `include/sys/system_properties.h`.
172 let prop_info = unsafe { (self.system_property_find)(name.as_ptr()) };
173 if prop_info.is_null() {
174 warn!(
175 "Android property name `{name}` not found",
176 name = crate::util::escape::Bytes(name.to_bytes()),
177 );
178 return None;
179 }
180
181 // N.B. A `prop_info` is an opaque pointer[1]... which means the
182 // implementation is probably allocating something in order to create
183 // it... right? But there's no API to free the pointer returned. And
184 // no other indication as to its lifetime. Once again, C is awful.
185 //
186 // [1]: https://android.googlesource.com/platform/bionic/+/master/libc/include/sys/system_properties.h#44
187
188 let mut buf = Vec::new();
189 // SAFETY: `name` is a valid NUL terminated string and
190 // `system_property_find` is a valid function read from `dlsym`
191 // according to the declaration in `include/sys/system_properties.h`.
192 unsafe {
193 let buf: *mut Vec<u8> = &mut buf;
194 (self.system_property_read)(
195 prop_info,
196 callback,
197 buf.cast::<c_void>(),
198 );
199 }
200 if buf.is_empty() {
201 warn!(
202 "reading Android property `{name}` resulted in empty value",
203 name = crate::util::escape::Bytes(name.to_bytes()),
204 );
205 return None;
206 }
207 Some(buf)
208 }
209 }
210
211 /// Loads a function symbol, of type `F`, from the given `dlopen` handle.
212 ///
213 /// If this fails, then `handle` is closed and `None` is returned and a
214 /// WARN-level log message is emitted with an error message if possible.
215 ///
216 /// # Safety
217 ///
218 /// Callers must ensure that `F` is a function type that matches the ABI of
219 /// the `symbol` in `handle`.
220 unsafe fn load_symbol<F>(handle: NonNull<c_void>, symbol: &CStr) -> Option<F> {
221 let sym =
222 // SAFETY: We know `handle` is non-null.
223 unsafe { dlsym(handle.as_ptr(), symbol.as_ptr()) };
224 if sym.is_null() {
225 // SAFETY: We know `handle` is non-null.
226 let _ = unsafe { dlclose(handle.as_ptr()) };
227 warn!(
228 "could not load `{symbol}` symbol from `libc.so",
229 symbol = crate::util::escape::Bytes(symbol.to_bytes()),
230 );
231 return None;
232 }
233 // SAFETY: The safety obligation here is forwarded to the caller. They
234 // must guarantee that `F` is an appropriate type.
235 // declared in `include/sys/system_properties.h` on Android.
236 let function = unsafe { mem::transmute_copy::<*mut c_void, F>(&sym) };
237 Some(function)
238 }
239
240 /// Creates a C string "literal" and returns it as a raw pointer.
241 ///
242 /// This panics if the string given contains a NUL byte.
243 fn cstr(string: &'static str) -> &'static CStr {
244 CStr::from_bytes_with_nul(string.as_bytes()).unwrap()
245 }
246
247 // We just define the FFI bindings ourselves instead of bringing in libc for
248 // this. We're only doing it for one platform, so it doesn't seem like a huge
249 // deal. But if this turns out to be a problem in practice, I'm fine accepting
250 // a target specific dependency on `libc` for Android.
251 extern "C" {
252 fn dlopen(filename: *const c_char, flag: i32) -> *mut c_void;
253 fn dlclose(handle: *mut c_void) -> i32;
254 fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
255 }
256
257 // These types come from:
258 // https://android.googlesource.com/platform/bionic/+/master/libc/include/sys/system_properties.h
259 type PropInfo = c_void;
260 type SystemPropertyFind =
261 unsafe extern "C" fn(*const c_char) -> *const PropInfo;
262 type SystemPropertyRead = unsafe extern "C" fn(
263 *const PropInfo,
264 SystemPropertyReadCallback,
265 *mut c_void,
266 );
267 type SystemPropertyReadCallback =
268 unsafe extern "C" fn(*mut c_void, *const c_char, *const c_char, u32);