1 /*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "android-base/properties.h"
18
19 #if defined(__BIONIC__)
20 #include <sys/system_properties.h>
21 #endif
22
23 #include <algorithm>
24 #include <chrono>
25 #include <limits>
26 #include <set>
27 #include <string>
28
29 #include <android-base/parsebool.h>
30 #include <android-base/parseint.h>
31 #include <android-base/strings.h>
32 #include <android-base/thread_annotations.h>
33
34 #if !defined(__BIONIC__)
35
36 // Here lies a rudimentary implementation of system properties for non-Bionic
37 // platforms. We are using weak symbols here because we want to allow
38 // downstream users of libbase to override with their own implementation.
39 // For example, on Ravenwood (host-side testing for platform development)
40 // we'd love to be able to fully control system properties exposed to tests,
41 // so we reimplement the entire system properties API there.
42
43 #if defined(__linux__)
44 // Weak symbols are not supported on Windows, and to prevent unnecessary
45 // complications, we strictly limit the use of weak symbols to Linux.
46 #define SYSPROP_WEAK __attribute__((weak))
47 #else
48 #define SYSPROP_WEAK
49 #endif
50
51 #define PROP_VALUE_MAX 92
52
53 struct prop_info {
54 std::string key;
55 mutable std::string value;
56 mutable uint32_t serial;
57
prop_infoprop_info58 prop_info(const char* key, const char* value) : key(key), value(value), serial(0) {}
59 };
60
61 struct prop_info_cmp {
62 using is_transparent = void;
operator ()prop_info_cmp63 bool operator()(const prop_info& lhs, const prop_info& rhs) { return lhs.key < rhs.key; }
operator ()prop_info_cmp64 bool operator()(std::string_view lhs, const prop_info& rhs) { return lhs < rhs.key; }
operator ()prop_info_cmp65 bool operator()(const prop_info& lhs, std::string_view rhs) { return lhs.key < rhs; }
66 };
67
68 static auto& g_properties_lock = *new std::mutex;
69 static auto& g_properties GUARDED_BY(g_properties_lock) = *new std::set<prop_info, prop_info_cmp>;
70
__system_property_set(const char * key,const char * value)71 SYSPROP_WEAK int __system_property_set(const char* key, const char* value) {
72 if (key == nullptr || *key == '\0') return -1;
73 if (value == nullptr) value = "";
74 bool read_only = !strncmp(key, "ro.", 3);
75 if (!read_only && strlen(value) >= PROP_VALUE_MAX) return -1;
76
77 std::lock_guard lock(g_properties_lock);
78 auto [it, success] = g_properties.emplace(key, value);
79 if (read_only) return success ? 0 : -1;
80 if (!success) {
81 it->value = value;
82 ++it->serial;
83 }
84 return 0;
85 }
86
__system_property_get(const char * key,char * value)87 SYSPROP_WEAK int __system_property_get(const char* key, char* value) {
88 std::lock_guard lock(g_properties_lock);
89 auto it = g_properties.find(key);
90 if (it == g_properties.end()) {
91 *value = '\0';
92 return 0;
93 }
94 snprintf(value, PROP_VALUE_MAX, "%s", it->value.c_str());
95 return strlen(value);
96 }
97
__system_property_find(const char * key)98 SYSPROP_WEAK const prop_info* __system_property_find(const char* key) {
99 std::lock_guard lock(g_properties_lock);
100 auto it = g_properties.find(key);
101 if (it == g_properties.end()) {
102 return nullptr;
103 } else {
104 return &*it;
105 }
106 }
107
__system_property_read_callback(const prop_info * pi,void (* callback)(void *,const char *,const char *,uint32_t),void * cookie)108 SYSPROP_WEAK void __system_property_read_callback(const prop_info* pi,
109 void (*callback)(void*, const char*, const char*,
110 uint32_t),
111 void* cookie) {
112 std::lock_guard lock(g_properties_lock);
113 callback(cookie, pi->key.c_str(), pi->value.c_str(), pi->serial);
114 }
115
116 #endif // __BIONIC__
117
118 namespace android {
119 namespace base {
120
GetBoolProperty(const std::string & key,bool default_value)121 bool GetBoolProperty(const std::string& key, bool default_value) {
122 switch (ParseBool(GetProperty(key, ""))) {
123 case ParseBoolResult::kError:
124 return default_value;
125 case ParseBoolResult::kFalse:
126 return false;
127 case ParseBoolResult::kTrue:
128 return true;
129 }
130 __builtin_unreachable();
131 }
132
133 template <typename T>
GetIntProperty(const std::string & key,T default_value,T min,T max)134 T GetIntProperty(const std::string& key, T default_value, T min, T max) {
135 T result;
136 std::string value = GetProperty(key, "");
137 if (!value.empty() && android::base::ParseInt(value, &result, min, max)) return result;
138 return default_value;
139 }
140
141 template <typename T>
GetUintProperty(const std::string & key,T default_value,T max)142 T GetUintProperty(const std::string& key, T default_value, T max) {
143 T result;
144 std::string value = GetProperty(key, "");
145 if (!value.empty() && android::base::ParseUint(value, &result, max)) return result;
146 return default_value;
147 }
148
149 template int8_t GetIntProperty(const std::string&, int8_t, int8_t, int8_t);
150 template int16_t GetIntProperty(const std::string&, int16_t, int16_t, int16_t);
151 template int32_t GetIntProperty(const std::string&, int32_t, int32_t, int32_t);
152 template int64_t GetIntProperty(const std::string&, int64_t, int64_t, int64_t);
153
154 template uint8_t GetUintProperty(const std::string&, uint8_t, uint8_t);
155 template uint16_t GetUintProperty(const std::string&, uint16_t, uint16_t);
156 template uint32_t GetUintProperty(const std::string&, uint32_t, uint32_t);
157 template uint64_t GetUintProperty(const std::string&, uint64_t, uint64_t);
158
GetProperty(const std::string & key,const std::string & default_value)159 std::string GetProperty(const std::string& key, const std::string& default_value) {
160 std::string property_value;
161 const prop_info* pi = __system_property_find(key.c_str());
162 if (pi == nullptr) return default_value;
163
164 __system_property_read_callback(
165 pi,
166 [](void* cookie, const char*, const char* value, unsigned) {
167 auto property_value = reinterpret_cast<std::string*>(cookie);
168 *property_value = value;
169 },
170 &property_value);
171 // If the property exists but is empty, also return the default value.
172 // Since we can't remove system properties, "empty" is traditionally
173 // the same as "missing" (this was true for cutils' property_get).
174 return property_value.empty() ? default_value : property_value;
175 }
176
SetProperty(const std::string & key,const std::string & value)177 bool SetProperty(const std::string& key, const std::string& value) {
178 return (__system_property_set(key.c_str(), value.c_str()) == 0);
179 }
180
181 #if defined(__BIONIC__)
182
183 struct WaitForPropertyData {
184 bool done;
185 const std::string* expected_value;
186 unsigned last_read_serial;
187 };
188
WaitForPropertyCallback(void * data_ptr,const char *,const char * value,unsigned serial)189 static void WaitForPropertyCallback(void* data_ptr, const char*, const char* value, unsigned serial) {
190 WaitForPropertyData* data = reinterpret_cast<WaitForPropertyData*>(data_ptr);
191 if (*data->expected_value == value) {
192 data->done = true;
193 } else {
194 data->last_read_serial = serial;
195 }
196 }
197
198 // TODO: chrono_utils?
DurationToTimeSpec(timespec & ts,const std::chrono::milliseconds d)199 static void DurationToTimeSpec(timespec& ts, const std::chrono::milliseconds d) {
200 auto s = std::chrono::duration_cast<std::chrono::seconds>(d);
201 auto ns = std::chrono::duration_cast<std::chrono::nanoseconds>(d - s);
202 ts.tv_sec = std::min<std::chrono::seconds::rep>(s.count(), std::numeric_limits<time_t>::max());
203 ts.tv_nsec = ns.count();
204 }
205
206 using AbsTime = std::chrono::time_point<std::chrono::steady_clock>;
207
UpdateTimeSpec(timespec & ts,std::chrono::milliseconds relative_timeout,const AbsTime & start_time)208 static void UpdateTimeSpec(timespec& ts, std::chrono::milliseconds relative_timeout,
209 const AbsTime& start_time) {
210 auto now = std::chrono::steady_clock::now();
211 auto time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - start_time);
212 if (time_elapsed >= relative_timeout) {
213 ts = { 0, 0 };
214 } else {
215 auto remaining_timeout = relative_timeout - time_elapsed;
216 DurationToTimeSpec(ts, remaining_timeout);
217 }
218 }
219
220 // Waits for the system property `key` to be created.
221 // Times out after `relative_timeout`.
222 // Sets absolute_timeout which represents absolute time for the timeout.
223 // Returns nullptr on timeout.
WaitForPropertyCreation(const std::string & key,const std::chrono::milliseconds & relative_timeout,const AbsTime & start_time)224 static const prop_info* WaitForPropertyCreation(const std::string& key,
225 const std::chrono::milliseconds& relative_timeout,
226 const AbsTime& start_time) {
227 // Find the property's prop_info*.
228 const prop_info* pi;
229 unsigned global_serial = 0;
230 while ((pi = __system_property_find(key.c_str())) == nullptr) {
231 // The property doesn't even exist yet.
232 // Wait for a global change and then look again.
233 timespec ts;
234 UpdateTimeSpec(ts, relative_timeout, start_time);
235 if (!__system_property_wait(nullptr, global_serial, &global_serial, &ts)) return nullptr;
236 }
237 return pi;
238 }
239
WaitForProperty(const std::string & key,const std::string & expected_value,std::chrono::milliseconds relative_timeout)240 bool WaitForProperty(const std::string& key, const std::string& expected_value,
241 std::chrono::milliseconds relative_timeout) {
242 auto start_time = std::chrono::steady_clock::now();
243 const prop_info* pi = WaitForPropertyCreation(key, relative_timeout, start_time);
244 if (pi == nullptr) return false;
245
246 WaitForPropertyData data;
247 data.expected_value = &expected_value;
248 data.done = false;
249 while (true) {
250 timespec ts;
251 // Check whether the property has the value we're looking for?
252 __system_property_read_callback(pi, WaitForPropertyCallback, &data);
253 if (data.done) return true;
254
255 // It didn't, so wait for the property to change before checking again.
256 UpdateTimeSpec(ts, relative_timeout, start_time);
257 uint32_t unused;
258 if (!__system_property_wait(pi, data.last_read_serial, &unused, &ts)) return false;
259 }
260 }
261
WaitForPropertyCreation(const std::string & key,std::chrono::milliseconds relative_timeout)262 bool WaitForPropertyCreation(const std::string& key,
263 std::chrono::milliseconds relative_timeout) {
264 auto start_time = std::chrono::steady_clock::now();
265 return (WaitForPropertyCreation(key, relative_timeout, start_time) != nullptr);
266 }
267
CachedProperty(std::string property_name)268 CachedProperty::CachedProperty(std::string property_name)
269 : property_name_(std::move(property_name)),
270 prop_info_(nullptr),
271 cached_area_serial_(0),
272 cached_property_serial_(0),
273 is_read_only_(android::base::StartsWith(property_name, "ro.")),
274 read_only_property_(nullptr) {
275 static_assert(sizeof(cached_value_) == PROP_VALUE_MAX);
276 }
277
CachedProperty(const char * property_name)278 CachedProperty::CachedProperty(const char* property_name)
279 : CachedProperty(std::string(property_name)) {}
280
Get(bool * changed)281 const char* CachedProperty::Get(bool* changed) {
282 std::optional<uint32_t> initial_property_serial = cached_property_serial_;
283
284 // Do we have a `struct prop_info` yet?
285 if (prop_info_ == nullptr) {
286 // `__system_property_find` is expensive, so only retry if a property
287 // has been created since last time we checked.
288 uint32_t property_area_serial = __system_property_area_serial();
289 if (property_area_serial != cached_area_serial_) {
290 prop_info_ = __system_property_find(property_name_.c_str());
291 cached_area_serial_ = property_area_serial;
292 }
293 }
294
295 if (prop_info_ != nullptr) {
296 // Only bother re-reading the property if it's actually changed since last time.
297 uint32_t property_serial = __system_property_serial(prop_info_);
298 if (property_serial != cached_property_serial_) {
299 __system_property_read_callback(
300 prop_info_,
301 [](void* data, const char*, const char* value, uint32_t serial) {
302 CachedProperty* instance = reinterpret_cast<CachedProperty*>(data);
303 instance->cached_property_serial_ = serial;
304 // Read only properties can be larger than PROP_VALUE_MAX, but also never change value
305 // or location, thus we return the pointer from the shared memory directly.
306 if (instance->is_read_only_) {
307 instance->read_only_property_ = value;
308 } else {
309 strlcpy(instance->cached_value_, value, PROP_VALUE_MAX);
310 }
311 },
312 this);
313 }
314 }
315
316 if (changed) {
317 *changed = cached_property_serial_ != initial_property_serial;
318 }
319
320 if (is_read_only_) {
321 return read_only_property_;
322 } else {
323 return cached_value_;
324 }
325 }
326
WaitForChange(std::chrono::milliseconds relative_timeout)327 const char* CachedProperty::WaitForChange(std::chrono::milliseconds relative_timeout) {
328 if (!prop_info_) {
329 auto start_time = std::chrono::steady_clock::now();
330 prop_info_ = WaitForPropertyCreation(property_name_, relative_timeout, start_time);
331 if (!prop_info_) {
332 return nullptr;
333 }
334 } else {
335 timespec ts;
336 DurationToTimeSpec(ts, relative_timeout);
337
338 uint32_t old_serial = cached_property_serial_.value_or(0);
339 uint32_t new_serial;
340 if (!__system_property_wait(prop_info_, old_serial, &new_serial, &ts)) return nullptr;
341 }
342
343 return Get(nullptr);
344 }
345
CachedBoolProperty(std::string property_name)346 CachedBoolProperty::CachedBoolProperty(std::string property_name)
347 : cached_parsed_property_(std::move(property_name),
348 [](const char* value) -> std::optional<bool> {
349 switch (ParseBool(value)) {
350 case ParseBoolResult::kError:
351 return std::nullopt;
352 case ParseBoolResult::kFalse:
353 return false;
354 case ParseBoolResult::kTrue:
355 return true;
356 }
357 }) {}
358
GetOptional()359 std::optional<bool> CachedBoolProperty::GetOptional() {
360 return cached_parsed_property_.Get();
361 }
362
Get(bool default_value)363 bool CachedBoolProperty::Get(bool default_value) {
364 return GetOptional().value_or(default_value);
365 }
366
367 #endif
368
369 } // namespace base
370 } // namespace android
371