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 #pragma once
18 
19 #include <sys/cdefs.h>
20 
21 #include <chrono>
22 #include <limits>
23 #include <mutex>
24 #include <optional>
25 #include <string>
26 
27 struct prop_info;
28 
29 namespace android {
30 namespace base {
31 
32 // Returns the current value of the system property `key`,
33 // or `default_value` if the property is empty or doesn't exist.
34 std::string GetProperty(const std::string& key, const std::string& default_value);
35 
36 // Returns true if the system property `key` has the value "1", "y", "yes", "on", or "true",
37 // false for "0", "n", "no", "off", or "false", or `default_value` otherwise.
38 bool GetBoolProperty(const std::string& key, bool default_value);
39 
40 // Returns the signed integer corresponding to the system property `key`.
41 // If the property is empty, doesn't exist, doesn't have an integer value, or is outside
42 // the optional bounds, returns `default_value`.
43 template <typename T> T GetIntProperty(const std::string& key,
44                                        T default_value,
45                                        T min = std::numeric_limits<T>::min(),
46                                        T max = std::numeric_limits<T>::max());
47 
48 // Returns the unsigned integer corresponding to the system property `key`.
49 // If the property is empty, doesn't exist, doesn't have an integer value, or is outside
50 // the optional bound, returns `default_value`.
51 template <typename T> T GetUintProperty(const std::string& key,
52                                         T default_value,
53                                         T max = std::numeric_limits<T>::max());
54 
55 // Sets the system property `key` to `value`.
56 bool SetProperty(const std::string& key, const std::string& value);
57 
58 // Waits for the system property `key` to have the value `expected_value`.
59 // Times out after `relative_timeout`.
60 // Returns true on success, false on timeout.
61 #if defined(__BIONIC__)
62 bool WaitForProperty(const std::string& key, const std::string& expected_value,
63                      std::chrono::milliseconds relative_timeout = std::chrono::milliseconds::max());
64 #endif
65 
66 // Waits for the system property `key` to be created.
67 // Times out after `relative_timeout`.
68 // Returns true on success, false on timeout.
69 #if defined(__BIONIC__)
70 bool WaitForPropertyCreation(const std::string& key, std::chrono::milliseconds relative_timeout =
71                                                          std::chrono::milliseconds::max());
72 #endif
73 
74 #if defined(__BIONIC__) && __cplusplus >= 201703L
75 // Cached system property lookup. For code that needs to read the same property multiple times,
76 // this class helps optimize those lookups.
77 class CachedProperty {
78  public:
79   explicit CachedProperty(std::string property_name);
80 
81   // Kept for ABI compatibility.
82   explicit CachedProperty(const char* property_name);
83 
84   // Returns the current value of the underlying system property as cheaply as possible.
85   // The returned pointer is valid until the next call to Get. Because most callers are going
86   // to want to parse the string returned here and cache that as well, this function performs
87   // no locking, and is completely thread unsafe. It is the caller's responsibility to provide a
88   // lock for thread-safety.
89   //
90   // Note: *changed can be set to true even if the contents of the property remain the same.
91   const char* Get(bool* changed = nullptr);
92 
93   // Waits for the property to be changed and then reads its value.
94   // Times out returning nullptr, after `relative_timeout`
95   //
96   // Note: this can return the same value multiple times in a row if the property was set to the
97   // same value or if multiple changes happened before the current thread was resumed.
98   const char* WaitForChange(
99       std::chrono::milliseconds relative_timeout = std::chrono::milliseconds::max());
100 
101  private:
102   std::string property_name_;
103   const prop_info* prop_info_;
104   std::optional<uint32_t> cached_area_serial_;
105   std::optional<uint32_t> cached_property_serial_;
106   char cached_value_[92];
107   bool is_read_only_;
108   const char* read_only_property_;
109 };
110 
111 // Helper class for passing the output of CachedProperty to a parser function, and then caching
112 // that as well.
113 template <typename Parser>
114 class CachedParsedProperty {
115  public:
116   using value_type = std::remove_reference_t<std::invoke_result_t<Parser, const char*>>;
117 
CachedParsedProperty(std::string property_name,Parser parser)118   CachedParsedProperty(std::string property_name, Parser parser)
119       : cached_property_(std::move(property_name)), parser_(std::move(parser)) {}
120 
121   // Returns the parsed value.
122   // This function is internally-synchronized, so use from multiple threads is safe (but ordering
123   // of course cannot be guaranteed without external synchronization).
124   value_type Get(bool* changed = nullptr) {
125     std::lock_guard<std::mutex> lock(mutex_);
126     bool local_changed = false;
127     const char* value = cached_property_.Get(&local_changed);
128     if (!cached_result_ || local_changed) {
129       cached_result_ = parser_(value);
130     }
131 
132     if (changed) *changed = local_changed;
133     return *cached_result_;
134   }
135 
136  private:
137   std::mutex mutex_;
138   CachedProperty cached_property_;
139   std::optional<value_type> cached_result_;
140 
141   Parser parser_;
142 };
143 
144 // Helper for CachedParsedProperty that uses android::base::ParseBool.
145 class CachedBoolProperty {
146  public:
147   explicit CachedBoolProperty(std::string property_name);
148 
149   // Returns the parsed bool, or std::nullopt if it wasn't set or couldn't be parsed.
150   std::optional<bool> GetOptional();
151 
152   // Returns the parsed bool, or default_value if it wasn't set or couldn't be parsed.
153   bool Get(bool default_value);
154 
155  private:
156   CachedParsedProperty<std::optional<bool> (*)(const char*)> cached_parsed_property_;
157 };
158 
159 #endif
160 
HwTimeoutMultiplier()161 static inline int HwTimeoutMultiplier() {
162   return android::base::GetIntProperty("ro.hw_timeout_multiplier", 1);
163 }
164 
165 } // namespace base
166 } // namespace android
167 
168 #if !defined(__BIONIC__)
169 /** Implementation detail. */
170 extern "C" int __system_property_set(const char*, const char*);
171 /** Implementation detail. */
172 extern "C" int __system_property_get(const char*, char*);
173 #endif
174