blob: 233d400e0ec26d22a0f789d2dc3e040be182ebfb [file] [log] [blame]
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001/*
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
Elliott Hughes8e9aeb92017-11-10 10:22:07 -080017#include <cutils/ashmem.h>
18
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080019/*
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 */
Mark Salyzyne37111d2016-02-02 09:19:39 -080024#define LOG_TAG "ashmem"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080025
Mark Salyzync2d8aad2016-02-02 08:05:54 -080026#include <errno.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080027#include <fcntl.h>
Mark Salyzyn23ed4c22016-09-28 13:33:27 -070028#include <linux/ashmem.h>
Joel Fernandes51944042018-12-18 13:32:31 -080029#include <linux/memfd.h>
30#include <log/log.h>
Mark Salyzyn1186f3a2016-02-02 08:21:32 -080031#include <pthread.h>
Joel Fernandes51944042018-12-18 13:32:31 -080032#include <stdio.h>
Mark Salyzync2d8aad2016-02-02 08:05:54 -080033#include <string.h>
34#include <sys/ioctl.h>
Joel Fernandes51944042018-12-18 13:32:31 -080035#include <sys/mman.h>
Mark Salyzync2d8aad2016-02-02 08:05:54 -080036#include <sys/stat.h>
Joel Fernandes51944042018-12-18 13:32:31 -080037#include <sys/syscall.h>
Elliott Hughesd77b5372017-05-17 11:36:51 -070038#include <sys/sysmacros.h>
Mark Salyzync2d8aad2016-02-02 08:05:54 -080039#include <sys/types.h>
40#include <unistd.h>
Joel Fernandes51944042018-12-18 13:32:31 -080041
Tri Vo92fd3ca2019-09-24 14:06:38 -070042#include <android-base/file.h>
Joel Fernandes51944042018-12-18 13:32:31 -080043#include <android-base/properties.h>
Tri Vo92fd3ca2019-09-24 14:06:38 -070044#include <android-base/strings.h>
Joel Fernandes51944042018-12-18 13:32:31 -080045#include <android-base/unique_fd.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080046
Joel Fernandes51944042018-12-18 13:32:31 -080047/* 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
Mark Salyzyn1186f3a2016-02-02 08:21:32 -080057/* ashmem identity */
58static 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 */
63static pthread_mutex_t __ashmem_lock = PTHREAD_MUTEX_INITIALIZER;
64
Tri Vo2891ba02019-01-28 17:56:43 -080065/*
Joel Fernandes51944042018-12-18 13:32:31 -080066 * 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
89static bool debug_log = false; /* set to true for verbose logging and other debug */
90static 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 */
98static 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
Dan Albertac4500e2020-07-27 14:03:56 -0700125 // Non-numeric should be a single ASCII character. Characters after the
126 // first are ignored.
Joel Fernandes51944042018-12-18 13:32:31 -0800127 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 */
146static 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 android::base::unique_fd fd(
164 syscall(__NR_memfd_create, "test_android_memfd", MFD_ALLOW_SEALING));
165 if (fd == -1) {
166 ALOGE("memfd_create failed: %s, no memfd support.\n", strerror(errno));
167 return false;
168 }
169
170 if (fcntl(fd, F_ADD_SEALS, F_SEAL_FUTURE_WRITE) == -1) {
171 ALOGE("fcntl(F_ADD_SEALS) failed: %s, no memfd support.\n", strerror(errno));
172 return false;
173 }
174
175 if (debug_log) {
176 ALOGD("memfd: device has memfd support, using it\n");
177 }
178 return true;
179}
180
181static bool has_memfd_support() {
182 /* memfd_supported is the initial global per-process state of what is known
183 * about memfd.
184 */
185 static bool memfd_supported = __has_memfd_support();
186
187 return memfd_supported;
188}
189
Tri Vo92fd3ca2019-09-24 14:06:38 -0700190static std::string get_ashmem_device_path() {
191 static const std::string boot_id_path = "/proc/sys/kernel/random/boot_id";
192 std::string boot_id;
193 if (!android::base::ReadFileToString(boot_id_path, &boot_id)) {
194 ALOGE("Failed to read %s: %s.\n", boot_id_path.c_str(), strerror(errno));
195 return "";
196 };
197 boot_id = android::base::Trim(boot_id);
198
199 return "/dev/ashmem" + boot_id;
200}
201
Mark Salyzyn1186f3a2016-02-02 08:21:32 -0800202/* logistics of getting file descriptor for ashmem */
203static int __ashmem_open_locked()
204{
Tri Vo92fd3ca2019-09-24 14:06:38 -0700205 static const std::string ashmem_device_path = get_ashmem_device_path();
206
Tri Vo92fd3ca2019-09-24 14:06:38 -0700207 if (ashmem_device_path.empty()) {
208 return -1;
Tim Murray8879ed72019-04-04 09:16:32 -0700209 }
210
Tri Vo92fd3ca2019-09-24 14:06:38 -0700211 int fd = TEMP_FAILURE_RETRY(open(ashmem_device_path.c_str(), O_RDWR | O_CLOEXEC));
Steven Moreland4f99dd32020-01-09 14:42:32 -0800212
213 // fallback for APEX w/ use_vendor on Q, which would have still used /dev/ashmem
214 if (fd < 0) {
Hridya Valsaraju9a147032020-08-07 12:22:24 -0700215 int saved_errno = errno;
Steven Moreland4f99dd32020-01-09 14:42:32 -0800216 fd = TEMP_FAILURE_RETRY(open("/dev/ashmem", O_RDWR | O_CLOEXEC));
Hridya Valsaraju9a147032020-08-07 12:22:24 -0700217 if (fd < 0) {
218 /* Q launching devices and newer must not reach here since they should have been
219 * able to open ashmem_device_path */
220 ALOGE("Unable to open ashmem device %s (error = %s) and /dev/ashmem(error = %s)",
221 ashmem_device_path.c_str(), strerror(saved_errno), strerror(errno));
222 return fd;
223 }
Steven Moreland4f99dd32020-01-09 14:42:32 -0800224 }
Steven Moreland4f99dd32020-01-09 14:42:32 -0800225 struct stat st;
226 int ret = TEMP_FAILURE_RETRY(fstat(fd, &st));
Mark Salyzyn1186f3a2016-02-02 08:21:32 -0800227 if (ret < 0) {
228 int save_errno = errno;
229 close(fd);
230 errno = save_errno;
231 return ret;
232 }
233 if (!S_ISCHR(st.st_mode) || !st.st_rdev) {
234 close(fd);
235 errno = ENOTTY;
236 return -1;
237 }
238
239 __ashmem_rdev = st.st_rdev;
240 return fd;
241}
242
243static int __ashmem_open()
244{
245 int fd;
246
247 pthread_mutex_lock(&__ashmem_lock);
248 fd = __ashmem_open_locked();
249 pthread_mutex_unlock(&__ashmem_lock);
250
251 return fd;
252}
253
254/* Make sure file descriptor references ashmem, negative number means false */
Mark Salyzynee431112016-08-23 13:58:37 -0700255static int __ashmem_is_ashmem(int fd, int fatal)
Mark Salyzyn1186f3a2016-02-02 08:21:32 -0800256{
257 dev_t rdev;
258 struct stat st;
259
Joel Fernandes56cd6512018-07-17 13:00:17 -0700260 if (fstat(fd, &st) < 0) {
Mark Salyzyn1186f3a2016-02-02 08:21:32 -0800261 return -1;
262 }
263
Mark Salyzyne37111d2016-02-02 09:19:39 -0800264 rdev = 0; /* Too much complexity to sniff __ashmem_rdev */
Mark Salyzyn1186f3a2016-02-02 08:21:32 -0800265 if (S_ISCHR(st.st_mode) && st.st_rdev) {
266 pthread_mutex_lock(&__ashmem_lock);
267 rdev = __ashmem_rdev;
268 if (rdev) {
269 pthread_mutex_unlock(&__ashmem_lock);
270 } else {
271 int fd = __ashmem_open_locked();
272 if (fd < 0) {
273 pthread_mutex_unlock(&__ashmem_lock);
274 return -1;
275 }
276 rdev = __ashmem_rdev;
277 pthread_mutex_unlock(&__ashmem_lock);
278
279 close(fd);
280 }
281
282 if (st.st_rdev == rdev) {
283 return 0;
284 }
285 }
286
Mark Salyzynee431112016-08-23 13:58:37 -0700287 if (fatal) {
288 if (rdev) {
289 LOG_ALWAYS_FATAL("illegal fd=%d mode=0%o rdev=%d:%d expected 0%o %d:%d",
290 fd, st.st_mode, major(st.st_rdev), minor(st.st_rdev),
291 S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IRGRP,
292 major(rdev), minor(rdev));
293 } else {
294 LOG_ALWAYS_FATAL("illegal fd=%d mode=0%o rdev=%d:%d expected 0%o",
295 fd, st.st_mode, major(st.st_rdev), minor(st.st_rdev),
296 S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IRGRP);
297 }
298 /* NOTREACHED */
Mark Salyzyne37111d2016-02-02 09:19:39 -0800299 }
300
Mark Salyzyn1186f3a2016-02-02 08:21:32 -0800301 errno = ENOTTY;
302 return -1;
303}
304
Joel Fernandes56cd6512018-07-17 13:00:17 -0700305static int __ashmem_check_failure(int fd, int result)
306{
307 if (result == -1 && errno == ENOTTY) __ashmem_is_ashmem(fd, 1);
308 return result;
309}
310
Joel Fernandes51944042018-12-18 13:32:31 -0800311static bool memfd_is_ashmem(int fd) {
312 static bool fd_check_error_once = false;
313
314 if (__ashmem_is_ashmem(fd, 0) == 0) {
315 if (!fd_check_error_once) {
316 ALOGE("memfd: memfd expected but ashmem fd used - please use libcutils.\n");
317 fd_check_error_once = true;
318 }
319
320 return true;
321 }
322
323 return false;
324}
325
Mark Salyzynee431112016-08-23 13:58:37 -0700326int ashmem_valid(int fd)
327{
Joel Fernandes51944042018-12-18 13:32:31 -0800328 if (has_memfd_support() && !memfd_is_ashmem(fd)) {
329 return 1;
330 }
331
Mark Salyzynee431112016-08-23 13:58:37 -0700332 return __ashmem_is_ashmem(fd, 0) >= 0;
333}
334
Joel Fernandes51944042018-12-18 13:32:31 -0800335static int memfd_create_region(const char* name, size_t size) {
336 android::base::unique_fd fd(syscall(__NR_memfd_create, name, MFD_ALLOW_SEALING));
337
338 if (fd == -1) {
339 ALOGE("memfd_create(%s, %zd) failed: %s\n", name, size, strerror(errno));
340 return -1;
341 }
342
343 if (ftruncate(fd, size) == -1) {
344 ALOGE("ftruncate(%s, %zd) failed for memfd creation: %s\n", name, size, strerror(errno));
345 return -1;
346 }
347
348 if (debug_log) {
349 ALOGE("memfd_create(%s, %zd) success. fd=%d\n", name, size, fd.get());
350 }
351 return fd.release();
352}
353
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800354/*
355 * ashmem_create_region - creates a new ashmem region and returns the file
356 * descriptor, or <0 on error
357 *
358 * `name' is an optional label to give the region (visible in /proc/pid/maps)
359 * `size' is the size of the region, in page-aligned bytes
360 */
361int ashmem_create_region(const char *name, size_t size)
362{
Mark Salyzync2d8aad2016-02-02 08:05:54 -0800363 int ret, save_errno;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800364
Joel Fernandes51944042018-12-18 13:32:31 -0800365 if (has_memfd_support()) {
366 return memfd_create_region(name ? name : "none", size);
367 }
368
Mark Salyzyn1186f3a2016-02-02 08:21:32 -0800369 int fd = __ashmem_open();
Mark Salyzync2d8aad2016-02-02 08:05:54 -0800370 if (fd < 0) {
371 return fd;
372 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800373
Mark Salyzync2d8aad2016-02-02 08:05:54 -0800374 if (name) {
375 char buf[ASHMEM_NAME_LEN] = {0};
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800376
Mark Salyzync2d8aad2016-02-02 08:05:54 -0800377 strlcpy(buf, name, sizeof(buf));
378 ret = TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_SET_NAME, buf));
379 if (ret < 0) {
380 goto error;
381 }
382 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800383
Mark Salyzync2d8aad2016-02-02 08:05:54 -0800384 ret = TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_SET_SIZE, size));
385 if (ret < 0) {
386 goto error;
387 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800388
Mark Salyzync2d8aad2016-02-02 08:05:54 -0800389 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800390
391error:
Mark Salyzync2d8aad2016-02-02 08:05:54 -0800392 save_errno = errno;
393 close(fd);
394 errno = save_errno;
395 return ret;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800396}
397
Joel Fernandes51944042018-12-18 13:32:31 -0800398static int memfd_set_prot_region(int fd, int prot) {
399 /* Only proceed if an fd needs to be write-protected */
400 if (prot & PROT_WRITE) {
401 return 0;
402 }
403
404 if (fcntl(fd, F_ADD_SEALS, F_SEAL_FUTURE_WRITE) == -1) {
405 ALOGE("memfd_set_prot_region(%d, %d): F_SEAL_FUTURE_WRITE seal failed: %s\n", fd, prot,
406 strerror(errno));
407 return -1;
408 }
409
410 return 0;
411}
412
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800413int ashmem_set_prot_region(int fd, int prot)
414{
Joel Fernandes51944042018-12-18 13:32:31 -0800415 if (has_memfd_support() && !memfd_is_ashmem(fd)) {
416 return memfd_set_prot_region(fd, prot);
417 }
418
Joel Fernandes56cd6512018-07-17 13:00:17 -0700419 return __ashmem_check_failure(fd, TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_SET_PROT_MASK, prot)));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800420}
421
422int ashmem_pin_region(int fd, size_t offset, size_t len)
423{
Joel Fernandes51944042018-12-18 13:32:31 -0800424 if (!pin_deprecation_warn || debug_log) {
425 ALOGE("Pinning is deprecated since Android Q. Please use trim or other methods.\n");
426 pin_deprecation_warn = true;
427 }
428
429 if (has_memfd_support() && !memfd_is_ashmem(fd)) {
430 return 0;
431 }
432
Elliott Hughes8e9aeb92017-11-10 10:22:07 -0800433 // TODO: should LP64 reject too-large offset/len?
434 ashmem_pin pin = { static_cast<uint32_t>(offset), static_cast<uint32_t>(len) };
Joel Fernandes56cd6512018-07-17 13:00:17 -0700435 return __ashmem_check_failure(fd, TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_PIN, &pin)));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800436}
437
438int ashmem_unpin_region(int fd, size_t offset, size_t len)
439{
Joel Fernandes51944042018-12-18 13:32:31 -0800440 if (!pin_deprecation_warn || debug_log) {
441 ALOGE("Pinning is deprecated since Android Q. Please use trim or other methods.\n");
442 pin_deprecation_warn = true;
443 }
444
445 if (has_memfd_support() && !memfd_is_ashmem(fd)) {
446 return 0;
447 }
448
Elliott Hughes8e9aeb92017-11-10 10:22:07 -0800449 // TODO: should LP64 reject too-large offset/len?
450 ashmem_pin pin = { static_cast<uint32_t>(offset), static_cast<uint32_t>(len) };
Joel Fernandes56cd6512018-07-17 13:00:17 -0700451 return __ashmem_check_failure(fd, TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_UNPIN, &pin)));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800452}
Bjorn Bringert7be52b12009-06-02 00:41:09 +0100453
454int ashmem_get_size_region(int fd)
455{
Joel Fernandes51944042018-12-18 13:32:31 -0800456 if (has_memfd_support() && !memfd_is_ashmem(fd)) {
457 struct stat sb;
458
459 if (fstat(fd, &sb) == -1) {
460 ALOGE("ashmem_get_size_region(%d): fstat failed: %s\n", fd, strerror(errno));
461 return -1;
462 }
463
464 if (debug_log) {
465 ALOGD("ashmem_get_size_region(%d): %d\n", fd, static_cast<int>(sb.st_size));
466 }
467
468 return sb.st_size;
469 }
470
Joel Fernandes56cd6512018-07-17 13:00:17 -0700471 return __ashmem_check_failure(fd, TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_GET_SIZE, NULL)));
Bjorn Bringert7be52b12009-06-02 00:41:09 +0100472}