1 // Copyright 2018 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 #include <cutils/properties.h>
15
16 #include "AndroidHostCommon.h"
17
18 #include "base/Lock.h"
19
20 #include <string>
21 #include <unordered_map>
22
23 #include <string.h>
24
25 using android::base::AutoLock;
26 using android::base::Lock;
27
28 class AndroidSystemProperties {
29 public:
30 AndroidSystemProperties() = default;
31 ~AndroidSystemProperties() = default;
32
get(const char * key,char * value,const char * default_value)33 int get(const char* key, char* value, const char* default_value) {
34 AutoLock lock(mLock);
35 auto it = mProps.find(key);
36 if (it == mProps.end()) {
37 if (!default_value) return 0;
38 return getPropertyWithValueLimit(value, default_value);
39 }
40 const char* storedValue = it->second.data();
41 return getPropertyWithValueLimit(value, storedValue);
42 }
43
set(const char * key,const char * value)44 int set(const char *key, const char *value) {
45 AutoLock lock(mLock);
46 mProps[key] = value;
47 return 0;
48 }
49
50 private:
getPropertyWithValueLimit(char * dst,const char * src)51 int getPropertyWithValueLimit(char* dst, const char* src) {
52 size_t totalStrlen = strlen(src);
53 size_t maxPropStrlen = PROPERTY_VALUE_MAX - 1;
54 size_t copyStrlen =
55 maxPropStrlen < totalStrlen ? maxPropStrlen : totalStrlen;
56 memcpy(dst, src, copyStrlen);
57 dst[copyStrlen] = '\0';
58 return (int)copyStrlen;
59 }
60
61 Lock mLock;
62 std::unordered_map<std::string, std::string> mProps;
63 };
64
sProps()65 static AndroidSystemProperties* sProps() {
66 static AndroidSystemProperties* p = new AndroidSystemProperties;
67 return p;
68 }
69
70 extern "C" {
71
property_get(const char * key,char * value,const char * default_value)72 EXPORT int property_get(const char* key, char* value, const char* default_value) {
73 return sProps()->get(key, value, default_value);
74 }
75
property_set(const char * key,const char * value)76 EXPORT int property_set(const char *key, const char *value) {
77 return sProps()->set(key, value);
78 }
79
80 } // extern "C"
81