1 /*
2  * Copyright (C) 2008 The Android Open Source Project
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *  * Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  *  * Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in
12  *    the documentation and/or other materials provided with the
13  *    distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 #include <new>
29 #include <stdatomic.h>
30 #include <stdio.h>
31 #include <stdint.h>
32 #include <stdlib.h>
33 #include <unistd.h>
34 #include <stddef.h>
35 #include <errno.h>
36 #include <poll.h>
37 #include <fcntl.h>
38 #include <stdbool.h>
39 #include <string.h>
40 
41 #include <sys/mman.h>
42 
43 #include <sys/socket.h>
44 #include <sys/un.h>
45 #include <sys/select.h>
46 #include <sys/stat.h>
47 #include <sys/types.h>
48 #include <netinet/in.h>
49 
50 #define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
51 #include <sys/_system_properties.h>
52 #include <sys/system_properties.h>
53 
54 #include "private/bionic_futex.h"
55 #include "private/bionic_macros.h"
56 
57 static const char property_service_socket[] = "/dev/socket/" PROP_SERVICE_NAME;
58 
59 
60 /*
61  * Properties are stored in a hybrid trie/binary tree structure.
62  * Each property's name is delimited at '.' characters, and the tokens are put
63  * into a trie structure.  Siblings at each level of the trie are stored in a
64  * binary tree.  For instance, "ro.secure"="1" could be stored as follows:
65  *
66  * +-----+   children    +----+   children    +--------+
67  * |     |-------------->| ro |-------------->| secure |
68  * +-----+               +----+               +--------+
69  *                       /    \                /   |
70  *                 left /      \ right   left /    |  prop   +===========+
71  *                     v        v            v     +-------->| ro.secure |
72  *                  +-----+   +-----+     +-----+            +-----------+
73  *                  | net |   | sys |     | com |            |     1     |
74  *                  +-----+   +-----+     +-----+            +===========+
75  */
76 
77 // Represents a node in the trie.
78 struct prop_bt {
79     uint8_t namelen;
80     uint8_t reserved[3];
81 
82     // The property trie is updated only by the init process (single threaded) which provides
83     // property service. And it can be read by multiple threads at the same time.
84     // As the property trie is not protected by locks, we use atomic_uint_least32_t types for the
85     // left, right, children "pointers" in the trie node. To make sure readers who see the
86     // change of "pointers" can also notice the change of prop_bt structure contents pointed by
87     // the "pointers", we always use release-consume ordering pair when accessing these "pointers".
88 
89     // prop "points" to prop_info structure if there is a propery associated with the trie node.
90     // Its situation is similar to the left, right, children "pointers". So we use
91     // atomic_uint_least32_t and release-consume ordering to protect it as well.
92 
93     // We should also avoid rereading these fields redundantly, since not
94     // all processor implementations ensure that multiple loads from the
95     // same field are carried out in the right order.
96     atomic_uint_least32_t prop;
97 
98     atomic_uint_least32_t left;
99     atomic_uint_least32_t right;
100 
101     atomic_uint_least32_t children;
102 
103     char name[0];
104 
prop_btprop_bt105     prop_bt(const char *name, const uint8_t name_length) {
106         this->namelen = name_length;
107         memcpy(this->name, name, name_length);
108         this->name[name_length] = '\0';
109     }
110 
111 private:
112     DISALLOW_COPY_AND_ASSIGN(prop_bt);
113 };
114 
115 struct prop_area {
116     uint32_t bytes_used;
117     atomic_uint_least32_t serial;
118     uint32_t magic;
119     uint32_t version;
120     uint32_t reserved[28];
121     char data[0];
122 
prop_areaprop_area123     prop_area(const uint32_t magic, const uint32_t version) :
124         magic(magic), version(version) {
125         atomic_init(&serial, 0);
126         memset(reserved, 0, sizeof(reserved));
127         // Allocate enough space for the root node.
128         bytes_used = sizeof(prop_bt);
129     }
130 
131 private:
132     DISALLOW_COPY_AND_ASSIGN(prop_area);
133 };
134 
135 struct prop_info {
136     atomic_uint_least32_t serial;
137     char value[PROP_VALUE_MAX];
138     char name[0];
139 
prop_infoprop_info140     prop_info(const char *name, const uint8_t namelen, const char *value,
141               const uint8_t valuelen) {
142         memcpy(this->name, name, namelen);
143         this->name[namelen] = '\0';
144         atomic_init(&this->serial, valuelen << 24);
145         memcpy(this->value, value, valuelen);
146         this->value[valuelen] = '\0';
147     }
148 private:
149     DISALLOW_COPY_AND_ASSIGN(prop_info);
150 };
151 
152 struct find_nth_cookie {
153     uint32_t count;
154     const uint32_t n;
155     const prop_info *pi;
156 
find_nth_cookiefind_nth_cookie157     find_nth_cookie(uint32_t n) : count(0), n(n), pi(NULL) {
158     }
159 };
160 
161 static char property_filename[PATH_MAX] = PROP_FILENAME;
162 static bool compat_mode = false;
163 static size_t pa_data_size;
164 static size_t pa_size;
165 
166 // NOTE: This isn't static because system_properties_compat.c
167 // requires it.
168 prop_area *__system_property_area__ = NULL;
169 
get_fd_from_env(void)170 static int get_fd_from_env(void)
171 {
172     // This environment variable consistes of two decimal integer
173     // values separated by a ",". The first value is a file descriptor
174     // and the second is the size of the system properties area. The
175     // size is currently unused.
176     char *env = getenv("ANDROID_PROPERTY_WORKSPACE");
177 
178     if (!env) {
179         return -1;
180     }
181 
182     return atoi(env);
183 }
184 
map_prop_area_rw()185 static int map_prop_area_rw()
186 {
187     /* dev is a tmpfs that we can use to carve a shared workspace
188      * out of, so let's do that...
189      */
190     const int fd = open(property_filename,
191                         O_RDWR | O_CREAT | O_NOFOLLOW | O_CLOEXEC | O_EXCL, 0444);
192 
193     if (fd < 0) {
194         if (errno == EACCES) {
195             /* for consistency with the case where the process has already
196              * mapped the page in and segfaults when trying to write to it
197              */
198             abort();
199         }
200         return -1;
201     }
202 
203     if (ftruncate(fd, PA_SIZE) < 0) {
204         close(fd);
205         return -1;
206     }
207 
208     pa_size = PA_SIZE;
209     pa_data_size = pa_size - sizeof(prop_area);
210     compat_mode = false;
211 
212     void *const memory_area = mmap(NULL, pa_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
213     if (memory_area == MAP_FAILED) {
214         close(fd);
215         return -1;
216     }
217 
218     prop_area *pa = new(memory_area) prop_area(PROP_AREA_MAGIC, PROP_AREA_VERSION);
219 
220     /* plug into the lib property services */
221     __system_property_area__ = pa;
222 
223     close(fd);
224     return 0;
225 }
226 
map_fd_ro(const int fd)227 static int map_fd_ro(const int fd) {
228     struct stat fd_stat;
229     if (fstat(fd, &fd_stat) < 0) {
230         return -1;
231     }
232 
233     if ((fd_stat.st_uid != 0)
234             || (fd_stat.st_gid != 0)
235             || ((fd_stat.st_mode & (S_IWGRP | S_IWOTH)) != 0)
236             || (fd_stat.st_size < static_cast<off_t>(sizeof(prop_area))) ) {
237         return -1;
238     }
239 
240     pa_size = fd_stat.st_size;
241     pa_data_size = pa_size - sizeof(prop_area);
242 
243     void* const map_result = mmap(NULL, pa_size, PROT_READ, MAP_SHARED, fd, 0);
244     if (map_result == MAP_FAILED) {
245         return -1;
246     }
247 
248     prop_area* pa = reinterpret_cast<prop_area*>(map_result);
249     if ((pa->magic != PROP_AREA_MAGIC) || (pa->version != PROP_AREA_VERSION &&
250                 pa->version != PROP_AREA_VERSION_COMPAT)) {
251         munmap(pa, pa_size);
252         return -1;
253     }
254 
255     if (pa->version == PROP_AREA_VERSION_COMPAT) {
256         compat_mode = true;
257     }
258 
259     __system_property_area__ = pa;
260     return 0;
261 }
262 
map_prop_area()263 static int map_prop_area()
264 {
265     int fd = open(property_filename, O_CLOEXEC | O_NOFOLLOW | O_RDONLY);
266     bool close_fd = true;
267     if (fd == -1 && errno == ENOENT) {
268         /*
269          * For backwards compatibility, if the file doesn't
270          * exist, we use the environment to get the file descriptor.
271          * For security reasons, we only use this backup if the kernel
272          * returns ENOENT. We don't want to use the backup if the kernel
273          * returns other errors such as ENOMEM or ENFILE, since it
274          * might be possible for an external program to trigger this
275          * condition.
276          */
277         fd = get_fd_from_env();
278         close_fd = false;
279     }
280 
281     if (fd < 0) {
282         return -1;
283     }
284 
285     const int map_result = map_fd_ro(fd);
286     if (close_fd) {
287         close(fd);
288     }
289 
290     return map_result;
291 }
292 
allocate_obj(const size_t size,uint_least32_t * const off)293 static void *allocate_obj(const size_t size, uint_least32_t *const off)
294 {
295     prop_area *pa = __system_property_area__;
296     const size_t aligned = BIONIC_ALIGN(size, sizeof(uint_least32_t));
297     if (pa->bytes_used + aligned > pa_data_size) {
298         return NULL;
299     }
300 
301     *off = pa->bytes_used;
302     pa->bytes_used += aligned;
303     return pa->data + *off;
304 }
305 
new_prop_bt(const char * name,uint8_t namelen,uint_least32_t * const off)306 static prop_bt *new_prop_bt(const char *name, uint8_t namelen, uint_least32_t *const off)
307 {
308     uint_least32_t new_offset;
309     void *const p = allocate_obj(sizeof(prop_bt) + namelen + 1, &new_offset);
310     if (p != NULL) {
311         prop_bt* bt = new(p) prop_bt(name, namelen);
312         *off = new_offset;
313         return bt;
314     }
315 
316     return NULL;
317 }
318 
new_prop_info(const char * name,uint8_t namelen,const char * value,uint8_t valuelen,uint_least32_t * const off)319 static prop_info *new_prop_info(const char *name, uint8_t namelen,
320         const char *value, uint8_t valuelen, uint_least32_t *const off)
321 {
322     uint_least32_t new_offset;
323     void* const p = allocate_obj(sizeof(prop_info) + namelen + 1, &new_offset);
324     if (p != NULL) {
325         prop_info* info = new(p) prop_info(name, namelen, value, valuelen);
326         *off = new_offset;
327         return info;
328     }
329 
330     return NULL;
331 }
332 
to_prop_obj(uint_least32_t off)333 static void *to_prop_obj(uint_least32_t off)
334 {
335     if (off > pa_data_size)
336         return NULL;
337     if (!__system_property_area__)
338         return NULL;
339 
340     return (__system_property_area__->data + off);
341 }
342 
to_prop_bt(atomic_uint_least32_t * off_p)343 static inline prop_bt *to_prop_bt(atomic_uint_least32_t* off_p) {
344   uint_least32_t off = atomic_load_explicit(off_p, memory_order_consume);
345   return reinterpret_cast<prop_bt*>(to_prop_obj(off));
346 }
347 
to_prop_info(atomic_uint_least32_t * off_p)348 static inline prop_info *to_prop_info(atomic_uint_least32_t* off_p) {
349   uint_least32_t off = atomic_load_explicit(off_p, memory_order_consume);
350   return reinterpret_cast<prop_info*>(to_prop_obj(off));
351 }
352 
root_node()353 static inline prop_bt *root_node()
354 {
355     return reinterpret_cast<prop_bt*>(to_prop_obj(0));
356 }
357 
cmp_prop_name(const char * one,uint8_t one_len,const char * two,uint8_t two_len)358 static int cmp_prop_name(const char *one, uint8_t one_len, const char *two,
359         uint8_t two_len)
360 {
361     if (one_len < two_len)
362         return -1;
363     else if (one_len > two_len)
364         return 1;
365     else
366         return strncmp(one, two, one_len);
367 }
368 
find_prop_bt(prop_bt * const bt,const char * name,uint8_t namelen,bool alloc_if_needed)369 static prop_bt *find_prop_bt(prop_bt *const bt, const char *name,
370                              uint8_t namelen, bool alloc_if_needed)
371 {
372 
373     prop_bt* current = bt;
374     while (true) {
375         if (!current) {
376             return NULL;
377         }
378 
379         const int ret = cmp_prop_name(name, namelen, current->name, current->namelen);
380         if (ret == 0) {
381             return current;
382         }
383 
384         if (ret < 0) {
385             uint_least32_t left_offset = atomic_load_explicit(&current->left, memory_order_relaxed);
386             if (left_offset != 0) {
387                 current = to_prop_bt(&current->left);
388             } else {
389                 if (!alloc_if_needed) {
390                    return NULL;
391                 }
392 
393                 uint_least32_t new_offset;
394                 prop_bt* new_bt = new_prop_bt(name, namelen, &new_offset);
395                 if (new_bt) {
396                     atomic_store_explicit(&current->left, new_offset, memory_order_release);
397                 }
398                 return new_bt;
399             }
400         } else {
401             uint_least32_t right_offset = atomic_load_explicit(&current->right, memory_order_relaxed);
402             if (right_offset != 0) {
403                 current = to_prop_bt(&current->right);
404             } else {
405                 if (!alloc_if_needed) {
406                    return NULL;
407                 }
408 
409                 uint_least32_t new_offset;
410                 prop_bt* new_bt = new_prop_bt(name, namelen, &new_offset);
411                 if (new_bt) {
412                     atomic_store_explicit(&current->right, new_offset, memory_order_release);
413                 }
414                 return new_bt;
415             }
416         }
417     }
418 }
419 
find_property(prop_bt * const trie,const char * name,uint8_t namelen,const char * value,uint8_t valuelen,bool alloc_if_needed)420 static const prop_info *find_property(prop_bt *const trie, const char *name,
421         uint8_t namelen, const char *value, uint8_t valuelen,
422         bool alloc_if_needed)
423 {
424     if (!trie) return NULL;
425 
426     const char *remaining_name = name;
427     prop_bt* current = trie;
428     while (true) {
429         const char *sep = strchr(remaining_name, '.');
430         const bool want_subtree = (sep != NULL);
431         const uint8_t substr_size = (want_subtree) ?
432             sep - remaining_name : strlen(remaining_name);
433 
434         if (!substr_size) {
435             return NULL;
436         }
437 
438         prop_bt* root = NULL;
439         uint_least32_t children_offset = atomic_load_explicit(&current->children, memory_order_relaxed);
440         if (children_offset != 0) {
441             root = to_prop_bt(&current->children);
442         } else if (alloc_if_needed) {
443             uint_least32_t new_offset;
444             root = new_prop_bt(remaining_name, substr_size, &new_offset);
445             if (root) {
446                 atomic_store_explicit(&current->children, new_offset, memory_order_release);
447             }
448         }
449 
450         if (!root) {
451             return NULL;
452         }
453 
454         current = find_prop_bt(root, remaining_name, substr_size, alloc_if_needed);
455         if (!current) {
456             return NULL;
457         }
458 
459         if (!want_subtree)
460             break;
461 
462         remaining_name = sep + 1;
463     }
464 
465     uint_least32_t prop_offset = atomic_load_explicit(&current->prop, memory_order_relaxed);
466     if (prop_offset != 0) {
467         return to_prop_info(&current->prop);
468     } else if (alloc_if_needed) {
469         uint_least32_t new_offset;
470         prop_info* new_info = new_prop_info(name, namelen, value, valuelen, &new_offset);
471         if (new_info) {
472             atomic_store_explicit(&current->prop, new_offset, memory_order_release);
473         }
474 
475         return new_info;
476     } else {
477         return NULL;
478     }
479 }
480 
send_prop_msg(const prop_msg * msg)481 static int send_prop_msg(const prop_msg *msg)
482 {
483     const int fd = socket(AF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0);
484     if (fd == -1) {
485         return -1;
486     }
487 
488     const size_t namelen = strlen(property_service_socket);
489 
490     sockaddr_un addr;
491     memset(&addr, 0, sizeof(addr));
492     strlcpy(addr.sun_path, property_service_socket, sizeof(addr.sun_path));
493     addr.sun_family = AF_LOCAL;
494     socklen_t alen = namelen + offsetof(sockaddr_un, sun_path) + 1;
495     if (TEMP_FAILURE_RETRY(connect(fd, reinterpret_cast<sockaddr*>(&addr), alen)) < 0) {
496         close(fd);
497         return -1;
498     }
499 
500     const int num_bytes = TEMP_FAILURE_RETRY(send(fd, msg, sizeof(prop_msg), 0));
501 
502     int result = -1;
503     if (num_bytes == sizeof(prop_msg)) {
504         // We successfully wrote to the property server but now we
505         // wait for the property server to finish its work.  It
506         // acknowledges its completion by closing the socket so we
507         // poll here (on nothing), waiting for the socket to close.
508         // If you 'adb shell setprop foo bar' you'll see the POLLHUP
509         // once the socket closes.  Out of paranoia we cap our poll
510         // at 250 ms.
511         pollfd pollfds[1];
512         pollfds[0].fd = fd;
513         pollfds[0].events = 0;
514         const int poll_result = TEMP_FAILURE_RETRY(poll(pollfds, 1, 250 /* ms */));
515         if (poll_result == 1 && (pollfds[0].revents & POLLHUP) != 0) {
516             result = 0;
517         } else {
518             // Ignore the timeout and treat it like a success anyway.
519             // The init process is single-threaded and its property
520             // service is sometimes slow to respond (perhaps it's off
521             // starting a child process or something) and thus this
522             // times out and the caller thinks it failed, even though
523             // it's still getting around to it.  So we fake it here,
524             // mostly for ctl.* properties, but we do try and wait 250
525             // ms so callers who do read-after-write can reliably see
526             // what they've written.  Most of the time.
527             // TODO: fix the system properties design.
528             result = 0;
529         }
530     }
531 
532     close(fd);
533     return result;
534 }
535 
find_nth_fn(const prop_info * pi,void * ptr)536 static void find_nth_fn(const prop_info *pi, void *ptr)
537 {
538     find_nth_cookie *cookie = reinterpret_cast<find_nth_cookie*>(ptr);
539 
540     if (cookie->n == cookie->count)
541         cookie->pi = pi;
542 
543     cookie->count++;
544 }
545 
foreach_property(prop_bt * const trie,void (* propfn)(const prop_info * pi,void * cookie),void * cookie)546 static int foreach_property(prop_bt *const trie,
547         void (*propfn)(const prop_info *pi, void *cookie), void *cookie)
548 {
549     if (!trie)
550         return -1;
551 
552     uint_least32_t left_offset = atomic_load_explicit(&trie->left, memory_order_relaxed);
553     if (left_offset != 0) {
554         const int err = foreach_property(to_prop_bt(&trie->left), propfn, cookie);
555         if (err < 0)
556             return -1;
557     }
558     uint_least32_t prop_offset = atomic_load_explicit(&trie->prop, memory_order_relaxed);
559     if (prop_offset != 0) {
560         prop_info *info = to_prop_info(&trie->prop);
561         if (!info)
562             return -1;
563         propfn(info, cookie);
564     }
565     uint_least32_t children_offset = atomic_load_explicit(&trie->children, memory_order_relaxed);
566     if (children_offset != 0) {
567         const int err = foreach_property(to_prop_bt(&trie->children), propfn, cookie);
568         if (err < 0)
569             return -1;
570     }
571     uint_least32_t right_offset = atomic_load_explicit(&trie->right, memory_order_relaxed);
572     if (right_offset != 0) {
573         const int err = foreach_property(to_prop_bt(&trie->right), propfn, cookie);
574         if (err < 0)
575             return -1;
576     }
577 
578     return 0;
579 }
580 
__system_properties_init()581 int __system_properties_init()
582 {
583     return map_prop_area();
584 }
585 
__system_property_set_filename(const char * filename)586 int __system_property_set_filename(const char *filename)
587 {
588     size_t len = strlen(filename);
589     if (len >= sizeof(property_filename))
590         return -1;
591 
592     strcpy(property_filename, filename);
593     return 0;
594 }
595 
__system_property_area_init()596 int __system_property_area_init()
597 {
598     return map_prop_area_rw();
599 }
600 
__system_property_area_serial()601 unsigned int __system_property_area_serial()
602 {
603     prop_area *pa = __system_property_area__;
604     if (!pa) {
605         return -1;
606     }
607     // Make sure this read fulfilled before __system_property_serial
608     return atomic_load_explicit(&(pa->serial), memory_order_acquire);
609 }
610 
__system_property_find(const char * name)611 const prop_info *__system_property_find(const char *name)
612 {
613     if (__predict_false(compat_mode)) {
614         return __system_property_find_compat(name);
615     }
616     return find_property(root_node(), name, strlen(name), NULL, 0, false);
617 }
618 
619 // The C11 standard doesn't allow atomic loads from const fields,
620 // though C++11 does.  Fudge it until standards get straightened out.
load_const_atomic(const atomic_uint_least32_t * s,memory_order mo)621 static inline uint_least32_t load_const_atomic(const atomic_uint_least32_t* s,
622                                                memory_order mo) {
623     atomic_uint_least32_t* non_const_s = const_cast<atomic_uint_least32_t*>(s);
624     return atomic_load_explicit(non_const_s, mo);
625 }
626 
__system_property_read(const prop_info * pi,char * name,char * value)627 int __system_property_read(const prop_info *pi, char *name, char *value)
628 {
629     if (__predict_false(compat_mode)) {
630         return __system_property_read_compat(pi, name, value);
631     }
632 
633     while (true) {
634         uint32_t serial = __system_property_serial(pi); // acquire semantics
635         size_t len = SERIAL_VALUE_LEN(serial);
636         memcpy(value, pi->value, len + 1);
637         // TODO: Fix the synchronization scheme here.
638         // There is no fully supported way to implement this kind
639         // of synchronization in C++11, since the memcpy races with
640         // updates to pi, and the data being accessed is not atomic.
641         // The following fence is unintuitive, but would be the
642         // correct one if memcpy used memory_order_relaxed atomic accesses.
643         // In practice it seems unlikely that the generated code would
644         // would be any different, so this should be OK.
645         atomic_thread_fence(memory_order_acquire);
646         if (serial ==
647                 load_const_atomic(&(pi->serial), memory_order_relaxed)) {
648             if (name != 0) {
649                 strcpy(name, pi->name);
650             }
651             return len;
652         }
653     }
654 }
655 
__system_property_get(const char * name,char * value)656 int __system_property_get(const char *name, char *value)
657 {
658     const prop_info *pi = __system_property_find(name);
659 
660     if (pi != 0) {
661         return __system_property_read(pi, 0, value);
662     } else {
663         value[0] = 0;
664         return 0;
665     }
666 }
667 
__system_property_set(const char * key,const char * value)668 int __system_property_set(const char *key, const char *value)
669 {
670     if (key == 0) return -1;
671     if (value == 0) value = "";
672     if (strlen(key) >= PROP_NAME_MAX) return -1;
673     if (strlen(value) >= PROP_VALUE_MAX) return -1;
674 
675     prop_msg msg;
676     memset(&msg, 0, sizeof msg);
677     msg.cmd = PROP_MSG_SETPROP;
678     strlcpy(msg.name, key, sizeof msg.name);
679     strlcpy(msg.value, value, sizeof msg.value);
680 
681     const int err = send_prop_msg(&msg);
682     if (err < 0) {
683         return err;
684     }
685 
686     return 0;
687 }
688 
__system_property_update(prop_info * pi,const char * value,unsigned int len)689 int __system_property_update(prop_info *pi, const char *value, unsigned int len)
690 {
691     prop_area *pa = __system_property_area__;
692 
693     if (len >= PROP_VALUE_MAX)
694         return -1;
695 
696     uint32_t serial = atomic_load_explicit(&pi->serial, memory_order_relaxed);
697     serial |= 1;
698     atomic_store_explicit(&pi->serial, serial, memory_order_relaxed);
699     // The memcpy call here also races.  Again pretend it
700     // used memory_order_relaxed atomics, and use the analogous
701     // counterintuitive fence.
702     atomic_thread_fence(memory_order_release);
703     memcpy(pi->value, value, len + 1);
704     atomic_store_explicit(
705         &pi->serial,
706         (len << 24) | ((serial + 1) & 0xffffff),
707         memory_order_release);
708     __futex_wake(&pi->serial, INT32_MAX);
709 
710     atomic_store_explicit(
711         &pa->serial,
712         atomic_load_explicit(&pa->serial, memory_order_relaxed) + 1,
713         memory_order_release);
714     __futex_wake(&pa->serial, INT32_MAX);
715 
716     return 0;
717 }
718 
__system_property_add(const char * name,unsigned int namelen,const char * value,unsigned int valuelen)719 int __system_property_add(const char *name, unsigned int namelen,
720             const char *value, unsigned int valuelen)
721 {
722     prop_area *pa = __system_property_area__;
723     const prop_info *pi;
724 
725     if (namelen >= PROP_NAME_MAX)
726         return -1;
727     if (valuelen >= PROP_VALUE_MAX)
728         return -1;
729     if (namelen < 1)
730         return -1;
731 
732     pi = find_property(root_node(), name, namelen, value, valuelen, true);
733     if (!pi)
734         return -1;
735 
736     // There is only a single mutator, but we want to make sure that
737     // updates are visible to a reader waiting for the update.
738     atomic_store_explicit(
739         &pa->serial,
740         atomic_load_explicit(&pa->serial, memory_order_relaxed) + 1,
741         memory_order_release);
742     __futex_wake(&pa->serial, INT32_MAX);
743     return 0;
744 }
745 
746 // Wait for non-locked serial, and retrieve it with acquire semantics.
__system_property_serial(const prop_info * pi)747 unsigned int __system_property_serial(const prop_info *pi)
748 {
749     uint32_t serial = load_const_atomic(&pi->serial, memory_order_acquire);
750     while (SERIAL_DIRTY(serial)) {
751         __futex_wait(const_cast<volatile void *>(
752                         reinterpret_cast<const void *>(&pi->serial)),
753                      serial, NULL);
754         serial = load_const_atomic(&pi->serial, memory_order_acquire);
755     }
756     return serial;
757 }
758 
__system_property_wait_any(unsigned int serial)759 unsigned int __system_property_wait_any(unsigned int serial)
760 {
761     prop_area *pa = __system_property_area__;
762     uint32_t my_serial;
763 
764     do {
765         __futex_wait(&pa->serial, serial, NULL);
766         my_serial = atomic_load_explicit(&pa->serial, memory_order_acquire);
767     } while (my_serial == serial);
768 
769     return my_serial;
770 }
771 
__system_property_find_nth(unsigned n)772 const prop_info *__system_property_find_nth(unsigned n)
773 {
774     find_nth_cookie cookie(n);
775 
776     const int err = __system_property_foreach(find_nth_fn, &cookie);
777     if (err < 0) {
778         return NULL;
779     }
780 
781     return cookie.pi;
782 }
783 
__system_property_foreach(void (* propfn)(const prop_info * pi,void * cookie),void * cookie)784 int __system_property_foreach(void (*propfn)(const prop_info *pi, void *cookie),
785         void *cookie)
786 {
787     if (__predict_false(compat_mode)) {
788         return __system_property_foreach_compat(propfn, cookie);
789     }
790 
791     return foreach_property(root_node(), propfn, cookie);
792 }
793