1 /*
2  * Copyright (C) 2008 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 <cutils/ashmem.h>
18 
19 /*
20  * Implementation of the user-space ashmem API for devices, which have our
21  * ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
22  * used by the simulator.
23  */
24 #define LOG_TAG "ashmem"
25 
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <linux/ashmem.h>
29 #include <linux/memfd.h>
30 #include <log/log.h>
31 #include <pthread.h>
32 #include <stdio.h>
33 #include <string.h>
34 #include <sys/ioctl.h>
35 #include <sys/mman.h>
36 #include <sys/stat.h>
37 #include <sys/syscall.h>
38 #include <sys/sysmacros.h>
39 #include <sys/types.h>
40 #include <unistd.h>
41 
42 #include <android-base/file.h>
43 #include <android-base/properties.h>
44 #include <android-base/strings.h>
45 #include <android-base/unique_fd.h>
46 
47 /* Will be added to UAPI once upstream change is merged */
48 #define F_SEAL_FUTURE_WRITE 0x0010
49 
50 /*
51  * The minimum vendor API level at and after which it is safe to use memfd.
52  * This is to facilitate deprecation of ashmem.
53  */
54 #define MIN_MEMFD_VENDOR_API_LEVEL 29
55 #define MIN_MEMFD_VENDOR_API_LEVEL_CHAR 'Q'
56 
57 /* ashmem identity */
58 static dev_t __ashmem_rdev;
59 /*
60  * If we trigger a signal handler in the middle of locked activity and the
61  * signal handler calls ashmem, we could get into a deadlock state.
62  */
63 static pthread_mutex_t __ashmem_lock = PTHREAD_MUTEX_INITIALIZER;
64 
65 /*
66  * has_memfd_support() determines if the device can use memfd. memfd support
67  * has been there for long time, but certain things in it may be missing.  We
68  * check for needed support in it. Also we check if the VNDK version of
69  * libcutils being used is new enough, if its not, then we cannot use memfd
70  * since the older copies may be using ashmem so we just use ashmem. Once all
71  * Android devices that are getting updates are new enough (ex, they were
72  * originally shipped with Android release > P), then we can just use memfd and
73  * delete all ashmem code from libcutils (while preserving the interface).
74  *
75  * NOTE:
76  * The sys.use_memfd property is set by default to false in Android
77  * to temporarily disable memfd, till vendor and apps are ready for it.
78  * The main issue: either apps or vendor processes can directly make ashmem
79  * IOCTLs on FDs they receive by assuming they are ashmem, without going
80  * through libcutils. Such fds could have very well be originally created with
81  * libcutils hence they could be memfd. Thus the IOCTLs will break.
82  *
83  * Set default value of sys.use_memfd property to true once the issue is
84  * resolved, so that the code can then self-detect if kernel support is present
85  * on the device. The property can also set to true from adb shell, for
86  * debugging.
87  */
88 
89 static bool debug_log = false;            /* set to true for verbose logging and other debug  */
90 static bool pin_deprecation_warn = true; /* Log the pin deprecation warning only once */
91 
92 /* Determine if vendor processes would be ok with memfd in the system:
93  *
94  * If VNDK is using older libcutils, don't use memfd. This is so that the
95  * same shared memory mechanism is used across binder transactions between
96  * vendor partition processes and system partition processes.
97  */
check_vendor_memfd_allowed()98 static bool check_vendor_memfd_allowed() {
99     std::string vndk_version = android::base::GetProperty("ro.vndk.version", "");
100 
101     if (vndk_version == "") {
102         ALOGE("memfd: ro.vndk.version not defined or invalid (%s), this is mandated since P.\n",
103               vndk_version.c_str());
104         return false;
105     }
106 
107     /* No issues if vendor is targetting current Dessert */
108     if (vndk_version == "current") {
109         return false;
110     }
111 
112     /* Check if VNDK version is a number and act on it */
113     char* p;
114     long int vers = strtol(vndk_version.c_str(), &p, 10);
115     if (*p == 0) {
116         if (vers < MIN_MEMFD_VENDOR_API_LEVEL) {
117             ALOGI("memfd: device VNDK version (%s) is < Q so using ashmem.\n",
118                   vndk_version.c_str());
119             return false;
120         }
121 
122         return true;
123     }
124 
125     // Non-numeric should be a single ASCII character. Characters after the
126     // first are ignored.
127     if (tolower(vndk_version[0]) < 'a' || tolower(vndk_version[0]) > 'z') {
128         ALOGE("memfd: ro.vndk.version not defined or invalid (%s), this is mandated since P.\n",
129               vndk_version.c_str());
130         return false;
131     }
132 
133     if (tolower(vndk_version[0]) < tolower(MIN_MEMFD_VENDOR_API_LEVEL_CHAR)) {
134         ALOGI("memfd: device is using VNDK version (%s) which is less than Q. Use ashmem only.\n",
135               vndk_version.c_str());
136         return false;
137     }
138 
139     return true;
140 }
141 
142 
143 /* Determine if memfd can be supported. This is just one-time hardwork
144  * which will be cached by the caller.
145  */
__has_memfd_support()146 static bool __has_memfd_support() {
147     if (check_vendor_memfd_allowed() == false) {
148         return false;
149     }
150 
151     /* Used to turn on/off the detection at runtime, in the future this
152      * property will be removed once we switch everything over to ashmem.
153      * Currently it is used only for debugging to switch the system over.
154      */
155     if (!android::base::GetBoolProperty("sys.use_memfd", false)) {
156         if (debug_log) {
157             ALOGD("sys.use_memfd=false so memfd disabled\n");
158         }
159         return false;
160     }
161 
162     // Check if kernel support exists, otherwise fall back to ashmem.
163     // This code needs to build on old API levels, so we can't use the libc
164     // wrapper.
165     android::base::unique_fd fd(
166             syscall(__NR_memfd_create, "test_android_memfd", MFD_CLOEXEC | MFD_ALLOW_SEALING));
167     if (fd == -1) {
168         ALOGE("memfd_create failed: %s, no memfd support.\n", strerror(errno));
169         return false;
170     }
171 
172     if (fcntl(fd, F_ADD_SEALS, F_SEAL_FUTURE_WRITE) == -1) {
173         ALOGE("fcntl(F_ADD_SEALS) failed: %s, no memfd support.\n", strerror(errno));
174         return false;
175     }
176 
177     if (debug_log) {
178         ALOGD("memfd: device has memfd support, using it\n");
179     }
180     return true;
181 }
182 
has_memfd_support()183 static bool has_memfd_support() {
184     /* memfd_supported is the initial global per-process state of what is known
185      * about memfd.
186      */
187     static bool memfd_supported = __has_memfd_support();
188 
189     return memfd_supported;
190 }
191 
get_ashmem_device_path()192 static std::string get_ashmem_device_path() {
193     static const std::string boot_id_path = "/proc/sys/kernel/random/boot_id";
194     std::string boot_id;
195     if (!android::base::ReadFileToString(boot_id_path, &boot_id)) {
196         ALOGE("Failed to read %s: %s.\n", boot_id_path.c_str(), strerror(errno));
197         return "";
198     };
199     boot_id = android::base::Trim(boot_id);
200 
201     return "/dev/ashmem" + boot_id;
202 }
203 
204 /* logistics of getting file descriptor for ashmem */
__ashmem_open_locked()205 static int __ashmem_open_locked()
206 {
207     static const std::string ashmem_device_path = get_ashmem_device_path();
208 
209     if (ashmem_device_path.empty()) {
210         return -1;
211     }
212 
213     int fd = TEMP_FAILURE_RETRY(open(ashmem_device_path.c_str(), O_RDWR | O_CLOEXEC));
214 
215     // fallback for APEX w/ use_vendor on Q, which would have still used /dev/ashmem
216     if (fd < 0) {
217         int saved_errno = errno;
218         fd = TEMP_FAILURE_RETRY(open("/dev/ashmem", O_RDWR | O_CLOEXEC));
219         if (fd < 0) {
220             /* Q launching devices and newer must not reach here since they should have been
221              * able to open ashmem_device_path */
222             ALOGE("Unable to open ashmem device %s (error = %s) and /dev/ashmem(error = %s)",
223                   ashmem_device_path.c_str(), strerror(saved_errno), strerror(errno));
224             return fd;
225         }
226     }
227     struct stat st;
228     int ret = TEMP_FAILURE_RETRY(fstat(fd, &st));
229     if (ret < 0) {
230         int save_errno = errno;
231         close(fd);
232         errno = save_errno;
233         return ret;
234     }
235     if (!S_ISCHR(st.st_mode) || !st.st_rdev) {
236         close(fd);
237         errno = ENOTTY;
238         return -1;
239     }
240 
241     __ashmem_rdev = st.st_rdev;
242     return fd;
243 }
244 
__ashmem_open()245 static int __ashmem_open()
246 {
247     int fd;
248 
249     pthread_mutex_lock(&__ashmem_lock);
250     fd = __ashmem_open_locked();
251     pthread_mutex_unlock(&__ashmem_lock);
252 
253     return fd;
254 }
255 
256 /* Make sure file descriptor references ashmem, negative number means false */
__ashmem_is_ashmem(int fd,int fatal)257 static int __ashmem_is_ashmem(int fd, int fatal)
258 {
259     dev_t rdev;
260     struct stat st;
261 
262     if (fstat(fd, &st) < 0) {
263         return -1;
264     }
265 
266     rdev = 0; /* Too much complexity to sniff __ashmem_rdev */
267     if (S_ISCHR(st.st_mode) && st.st_rdev) {
268         pthread_mutex_lock(&__ashmem_lock);
269         rdev = __ashmem_rdev;
270         if (rdev) {
271             pthread_mutex_unlock(&__ashmem_lock);
272         } else {
273             int fd = __ashmem_open_locked();
274             if (fd < 0) {
275                 pthread_mutex_unlock(&__ashmem_lock);
276                 return -1;
277             }
278             rdev = __ashmem_rdev;
279             pthread_mutex_unlock(&__ashmem_lock);
280 
281             close(fd);
282         }
283 
284         if (st.st_rdev == rdev) {
285             return 0;
286         }
287     }
288 
289     if (fatal) {
290         if (rdev) {
291             LOG_ALWAYS_FATAL("illegal fd=%d mode=0%o rdev=%d:%d expected 0%o %d:%d",
292               fd, st.st_mode, major(st.st_rdev), minor(st.st_rdev),
293               S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IRGRP,
294               major(rdev), minor(rdev));
295         } else {
296             LOG_ALWAYS_FATAL("illegal fd=%d mode=0%o rdev=%d:%d expected 0%o",
297               fd, st.st_mode, major(st.st_rdev), minor(st.st_rdev),
298               S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IRGRP);
299         }
300         /* NOTREACHED */
301     }
302 
303     errno = ENOTTY;
304     return -1;
305 }
306 
__ashmem_check_failure(int fd,int result)307 static int __ashmem_check_failure(int fd, int result)
308 {
309     if (result == -1 && errno == ENOTTY) __ashmem_is_ashmem(fd, 1);
310     return result;
311 }
312 
memfd_is_ashmem(int fd)313 static bool memfd_is_ashmem(int fd) {
314     static bool fd_check_error_once = false;
315 
316     if (__ashmem_is_ashmem(fd, 0) == 0) {
317         if (!fd_check_error_once) {
318             ALOGE("memfd: memfd expected but ashmem fd used - please use libcutils.\n");
319             fd_check_error_once = true;
320         }
321 
322         return true;
323     }
324 
325     return false;
326 }
327 
ashmem_valid(int fd)328 int ashmem_valid(int fd)
329 {
330     if (has_memfd_support() && !memfd_is_ashmem(fd)) {
331         return 1;
332     }
333 
334     return __ashmem_is_ashmem(fd, 0) >= 0;
335 }
336 
memfd_create_region(const char * name,size_t size)337 static int memfd_create_region(const char* name, size_t size) {
338     // This code needs to build on old API levels, so we can't use the libc
339     // wrapper.
340     android::base::unique_fd fd(syscall(__NR_memfd_create, name, MFD_CLOEXEC | MFD_ALLOW_SEALING));
341 
342     if (fd == -1) {
343         ALOGE("memfd_create(%s, %zd) failed: %s\n", name, size, strerror(errno));
344         return -1;
345     }
346 
347     if (ftruncate(fd, size) == -1) {
348         ALOGE("ftruncate(%s, %zd) failed for memfd creation: %s\n", name, size, strerror(errno));
349         return -1;
350     }
351 
352     // forbid size changes to match ashmem behaviour
353     if (fcntl(fd, F_ADD_SEALS, F_SEAL_GROW | F_SEAL_SHRINK) == -1) {
354         ALOGE("memfd_create(%s, %zd) F_ADD_SEALS failed: %m", name, size);
355         return -1;
356     }
357 
358     if (debug_log) {
359         ALOGE("memfd_create(%s, %zd) success. fd=%d\n", name, size, fd.get());
360     }
361     return fd.release();
362 }
363 
364 /*
365  * ashmem_create_region - creates a new ashmem region and returns the file
366  * descriptor, or <0 on error
367  *
368  * `name' is an optional label to give the region (visible in /proc/pid/maps)
369  * `size' is the size of the region, in page-aligned bytes
370  */
ashmem_create_region(const char * name,size_t size)371 int ashmem_create_region(const char *name, size_t size)
372 {
373     int ret, save_errno;
374 
375     if (has_memfd_support()) {
376         return memfd_create_region(name ? name : "none", size);
377     }
378 
379     int fd = __ashmem_open();
380     if (fd < 0) {
381         return fd;
382     }
383 
384     if (name) {
385         char buf[ASHMEM_NAME_LEN] = {0};
386 
387         strlcpy(buf, name, sizeof(buf));
388         ret = TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_SET_NAME, buf));
389         if (ret < 0) {
390             goto error;
391         }
392     }
393 
394     ret = TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_SET_SIZE, size));
395     if (ret < 0) {
396         goto error;
397     }
398 
399     return fd;
400 
401 error:
402     save_errno = errno;
403     close(fd);
404     errno = save_errno;
405     return ret;
406 }
407 
memfd_set_prot_region(int fd,int prot)408 static int memfd_set_prot_region(int fd, int prot) {
409     int seals = fcntl(fd, F_GET_SEALS);
410     if (seals == -1) {
411         ALOGE("memfd_set_prot_region(%d, %d): F_GET_SEALS failed: %s\n", fd, prot, strerror(errno));
412         return -1;
413     }
414 
415     if (prot & PROT_WRITE) {
416         /* Now we want the buffer to be read-write, let's check if the buffer
417          * has been previously marked as read-only before, if so return error
418          */
419         if (seals & F_SEAL_FUTURE_WRITE) {
420             ALOGE("memfd_set_prot_region(%d, %d): region is write protected\n", fd, prot);
421             errno = EINVAL;  // inline with ashmem error code, if already in
422                              // read-only mode
423             return -1;
424         }
425         return 0;
426     }
427 
428     /* We would only allow read-only for any future file operations */
429     if (fcntl(fd, F_ADD_SEALS, F_SEAL_FUTURE_WRITE | F_SEAL_SEAL) == -1) {
430         ALOGE("memfd_set_prot_region(%d, %d): F_SEAL_FUTURE_WRITE | F_SEAL_SEAL seal failed: %s\n",
431               fd, prot, strerror(errno));
432         return -1;
433     }
434 
435     return 0;
436 }
437 
ashmem_set_prot_region(int fd,int prot)438 int ashmem_set_prot_region(int fd, int prot)
439 {
440     if (has_memfd_support() && !memfd_is_ashmem(fd)) {
441         return memfd_set_prot_region(fd, prot);
442     }
443 
444     return __ashmem_check_failure(fd, TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_SET_PROT_MASK, prot)));
445 }
446 
ashmem_pin_region(int fd,size_t offset,size_t len)447 int ashmem_pin_region(int fd, size_t offset, size_t len)
448 {
449     if (!pin_deprecation_warn || debug_log) {
450         ALOGE("Pinning is deprecated since Android Q. Please use trim or other methods.\n");
451         pin_deprecation_warn = true;
452     }
453 
454     if (has_memfd_support() && !memfd_is_ashmem(fd)) {
455         return 0;
456     }
457 
458     // TODO: should LP64 reject too-large offset/len?
459     ashmem_pin pin = { static_cast<uint32_t>(offset), static_cast<uint32_t>(len) };
460     return __ashmem_check_failure(fd, TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_PIN, &pin)));
461 }
462 
ashmem_unpin_region(int fd,size_t offset,size_t len)463 int ashmem_unpin_region(int fd, size_t offset, size_t len)
464 {
465     if (!pin_deprecation_warn || debug_log) {
466         ALOGE("Pinning is deprecated since Android Q. Please use trim or other methods.\n");
467         pin_deprecation_warn = true;
468     }
469 
470     if (has_memfd_support() && !memfd_is_ashmem(fd)) {
471         return 0;
472     }
473 
474     // TODO: should LP64 reject too-large offset/len?
475     ashmem_pin pin = { static_cast<uint32_t>(offset), static_cast<uint32_t>(len) };
476     return __ashmem_check_failure(fd, TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_UNPIN, &pin)));
477 }
478 
ashmem_get_size_region(int fd)479 int ashmem_get_size_region(int fd)
480 {
481     if (has_memfd_support() && !memfd_is_ashmem(fd)) {
482         struct stat sb;
483 
484         if (fstat(fd, &sb) == -1) {
485             ALOGE("ashmem_get_size_region(%d): fstat failed: %s\n", fd, strerror(errno));
486             return -1;
487         }
488 
489         if (debug_log) {
490             ALOGD("ashmem_get_size_region(%d): %d\n", fd, static_cast<int>(sb.st_size));
491         }
492 
493         return sb.st_size;
494     }
495 
496     return __ashmem_check_failure(fd, TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_GET_SIZE, NULL)));
497 }
498