blob: 5e01da9b890b3166b7c09c04cbdf908bbd8eb189 [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/*
48 * The minimum vendor API level at and after which it is safe to use memfd.
49 * This is to facilitate deprecation of ashmem.
50 */
51#define MIN_MEMFD_VENDOR_API_LEVEL 29
52#define MIN_MEMFD_VENDOR_API_LEVEL_CHAR 'Q'
53
Mark Salyzyn1186f3a2016-02-02 08:21:32 -080054/* ashmem identity */
55static dev_t __ashmem_rdev;
56/*
57 * If we trigger a signal handler in the middle of locked activity and the
58 * signal handler calls ashmem, we could get into a deadlock state.
59 */
60static pthread_mutex_t __ashmem_lock = PTHREAD_MUTEX_INITIALIZER;
61
Tri Vo2891ba02019-01-28 17:56:43 -080062/*
Joel Fernandes51944042018-12-18 13:32:31 -080063 * has_memfd_support() determines if the device can use memfd. memfd support
64 * has been there for long time, but certain things in it may be missing. We
65 * check for needed support in it. Also we check if the VNDK version of
66 * libcutils being used is new enough, if its not, then we cannot use memfd
67 * since the older copies may be using ashmem so we just use ashmem. Once all
68 * Android devices that are getting updates are new enough (ex, they were
69 * originally shipped with Android release > P), then we can just use memfd and
70 * delete all ashmem code from libcutils (while preserving the interface).
71 *
72 * NOTE:
73 * The sys.use_memfd property is set by default to false in Android
74 * to temporarily disable memfd, till vendor and apps are ready for it.
75 * The main issue: either apps or vendor processes can directly make ashmem
76 * IOCTLs on FDs they receive by assuming they are ashmem, without going
77 * through libcutils. Such fds could have very well be originally created with
78 * libcutils hence they could be memfd. Thus the IOCTLs will break.
79 *
80 * Set default value of sys.use_memfd property to true once the issue is
81 * resolved, so that the code can then self-detect if kernel support is present
82 * on the device. The property can also set to true from adb shell, for
83 * debugging.
84 */
85
86static bool debug_log = false; /* set to true for verbose logging and other debug */
87static bool pin_deprecation_warn = true; /* Log the pin deprecation warning only once */
88
89/* Determine if vendor processes would be ok with memfd in the system:
90 *
91 * If VNDK is using older libcutils, don't use memfd. This is so that the
92 * same shared memory mechanism is used across binder transactions between
93 * vendor partition processes and system partition processes.
94 */
95static bool check_vendor_memfd_allowed() {
96 std::string vndk_version = android::base::GetProperty("ro.vndk.version", "");
97
98 if (vndk_version == "") {
99 ALOGE("memfd: ro.vndk.version not defined or invalid (%s), this is mandated since P.\n",
100 vndk_version.c_str());
101 return false;
102 }
103
104 /* No issues if vendor is targetting current Dessert */
105 if (vndk_version == "current") {
106 return false;
107 }
108
109 /* Check if VNDK version is a number and act on it */
110 char* p;
111 long int vers = strtol(vndk_version.c_str(), &p, 10);
112 if (*p == 0) {
113 if (vers < MIN_MEMFD_VENDOR_API_LEVEL) {
114 ALOGI("memfd: device VNDK version (%s) is < Q so using ashmem.\n",
115 vndk_version.c_str());
116 return false;
117 }
118
119 return true;
120 }
121
Dan Albertac4500e2020-07-27 14:03:56 -0700122 // Non-numeric should be a single ASCII character. Characters after the
123 // first are ignored.
Joel Fernandes51944042018-12-18 13:32:31 -0800124 if (tolower(vndk_version[0]) < 'a' || tolower(vndk_version[0]) > 'z') {
125 ALOGE("memfd: ro.vndk.version not defined or invalid (%s), this is mandated since P.\n",
126 vndk_version.c_str());
127 return false;
128 }
129
130 if (tolower(vndk_version[0]) < tolower(MIN_MEMFD_VENDOR_API_LEVEL_CHAR)) {
131 ALOGI("memfd: device is using VNDK version (%s) which is less than Q. Use ashmem only.\n",
132 vndk_version.c_str());
133 return false;
134 }
135
136 return true;
137}
138
139
140/* Determine if memfd can be supported. This is just one-time hardwork
141 * which will be cached by the caller.
142 */
143static bool __has_memfd_support() {
144 if (check_vendor_memfd_allowed() == false) {
145 return false;
146 }
147
148 /* Used to turn on/off the detection at runtime, in the future this
149 * property will be removed once we switch everything over to ashmem.
150 * Currently it is used only for debugging to switch the system over.
151 */
152 if (!android::base::GetBoolProperty("sys.use_memfd", false)) {
153 if (debug_log) {
154 ALOGD("sys.use_memfd=false so memfd disabled\n");
155 }
156 return false;
157 }
158
Elliott Hughes790ef052020-09-03 10:53:16 -0700159 // Check if kernel support exists, otherwise fall back to ashmem.
160 // This code needs to build on old API levels, so we can't use the libc
161 // wrapper.
Joel Fernandes51944042018-12-18 13:32:31 -0800162 android::base::unique_fd fd(
Elliott Hughes790ef052020-09-03 10:53:16 -0700163 syscall(__NR_memfd_create, "test_android_memfd", MFD_CLOEXEC | MFD_ALLOW_SEALING));
Joel Fernandes51944042018-12-18 13:32:31 -0800164 if (fd == -1) {
165 ALOGE("memfd_create failed: %s, no memfd support.\n", strerror(errno));
166 return false;
167 }
168
169 if (fcntl(fd, F_ADD_SEALS, F_SEAL_FUTURE_WRITE) == -1) {
170 ALOGE("fcntl(F_ADD_SEALS) failed: %s, no memfd support.\n", strerror(errno));
171 return false;
172 }
173
174 if (debug_log) {
175 ALOGD("memfd: device has memfd support, using it\n");
176 }
177 return true;
178}
179
180static bool has_memfd_support() {
181 /* memfd_supported is the initial global per-process state of what is known
182 * about memfd.
183 */
184 static bool memfd_supported = __has_memfd_support();
185
186 return memfd_supported;
187}
188
Tri Vo92fd3ca2019-09-24 14:06:38 -0700189static std::string get_ashmem_device_path() {
190 static const std::string boot_id_path = "/proc/sys/kernel/random/boot_id";
191 std::string boot_id;
192 if (!android::base::ReadFileToString(boot_id_path, &boot_id)) {
193 ALOGE("Failed to read %s: %s.\n", boot_id_path.c_str(), strerror(errno));
194 return "";
195 };
196 boot_id = android::base::Trim(boot_id);
197
198 return "/dev/ashmem" + boot_id;
199}
200
Mark Salyzyn1186f3a2016-02-02 08:21:32 -0800201/* logistics of getting file descriptor for ashmem */
202static int __ashmem_open_locked()
203{
Tri Vo92fd3ca2019-09-24 14:06:38 -0700204 static const std::string ashmem_device_path = get_ashmem_device_path();
205
Tri Vo92fd3ca2019-09-24 14:06:38 -0700206 if (ashmem_device_path.empty()) {
207 return -1;
Tim Murray8879ed72019-04-04 09:16:32 -0700208 }
209
Tri Vo92fd3ca2019-09-24 14:06:38 -0700210 int fd = TEMP_FAILURE_RETRY(open(ashmem_device_path.c_str(), O_RDWR | O_CLOEXEC));
Steven Moreland4f99dd32020-01-09 14:42:32 -0800211
212 // fallback for APEX w/ use_vendor on Q, which would have still used /dev/ashmem
213 if (fd < 0) {
Hridya Valsaraju9a147032020-08-07 12:22:24 -0700214 int saved_errno = errno;
Steven Moreland4f99dd32020-01-09 14:42:32 -0800215 fd = TEMP_FAILURE_RETRY(open("/dev/ashmem", O_RDWR | O_CLOEXEC));
Hridya Valsaraju9a147032020-08-07 12:22:24 -0700216 if (fd < 0) {
217 /* Q launching devices and newer must not reach here since they should have been
218 * able to open ashmem_device_path */
219 ALOGE("Unable to open ashmem device %s (error = %s) and /dev/ashmem(error = %s)",
220 ashmem_device_path.c_str(), strerror(saved_errno), strerror(errno));
221 return fd;
222 }
Steven Moreland4f99dd32020-01-09 14:42:32 -0800223 }
Steven Moreland4f99dd32020-01-09 14:42:32 -0800224 struct stat st;
225 int ret = TEMP_FAILURE_RETRY(fstat(fd, &st));
Mark Salyzyn1186f3a2016-02-02 08:21:32 -0800226 if (ret < 0) {
227 int save_errno = errno;
228 close(fd);
229 errno = save_errno;
230 return ret;
231 }
232 if (!S_ISCHR(st.st_mode) || !st.st_rdev) {
233 close(fd);
234 errno = ENOTTY;
235 return -1;
236 }
237
238 __ashmem_rdev = st.st_rdev;
239 return fd;
240}
241
242static int __ashmem_open()
243{
244 int fd;
245
246 pthread_mutex_lock(&__ashmem_lock);
247 fd = __ashmem_open_locked();
248 pthread_mutex_unlock(&__ashmem_lock);
249
250 return fd;
251}
252
253/* Make sure file descriptor references ashmem, negative number means false */
Mark Salyzynee431112016-08-23 13:58:37 -0700254static int __ashmem_is_ashmem(int fd, int fatal)
Mark Salyzyn1186f3a2016-02-02 08:21:32 -0800255{
256 dev_t rdev;
257 struct stat st;
258
Joel Fernandes56cd6512018-07-17 13:00:17 -0700259 if (fstat(fd, &st) < 0) {
Mark Salyzyn1186f3a2016-02-02 08:21:32 -0800260 return -1;
261 }
262
Mark Salyzyne37111d2016-02-02 09:19:39 -0800263 rdev = 0; /* Too much complexity to sniff __ashmem_rdev */
Mark Salyzyn1186f3a2016-02-02 08:21:32 -0800264 if (S_ISCHR(st.st_mode) && st.st_rdev) {
265 pthread_mutex_lock(&__ashmem_lock);
266 rdev = __ashmem_rdev;
267 if (rdev) {
268 pthread_mutex_unlock(&__ashmem_lock);
269 } else {
270 int fd = __ashmem_open_locked();
271 if (fd < 0) {
272 pthread_mutex_unlock(&__ashmem_lock);
273 return -1;
274 }
275 rdev = __ashmem_rdev;
276 pthread_mutex_unlock(&__ashmem_lock);
277
278 close(fd);
279 }
280
281 if (st.st_rdev == rdev) {
282 return 0;
283 }
284 }
285
Mark Salyzynee431112016-08-23 13:58:37 -0700286 if (fatal) {
287 if (rdev) {
288 LOG_ALWAYS_FATAL("illegal fd=%d mode=0%o rdev=%d:%d expected 0%o %d:%d",
289 fd, st.st_mode, major(st.st_rdev), minor(st.st_rdev),
290 S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IRGRP,
291 major(rdev), minor(rdev));
292 } else {
293 LOG_ALWAYS_FATAL("illegal fd=%d mode=0%o rdev=%d:%d expected 0%o",
294 fd, st.st_mode, major(st.st_rdev), minor(st.st_rdev),
295 S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IRGRP);
296 }
297 /* NOTREACHED */
Mark Salyzyne37111d2016-02-02 09:19:39 -0800298 }
299
Mark Salyzyn1186f3a2016-02-02 08:21:32 -0800300 errno = ENOTTY;
301 return -1;
302}
303
Joel Fernandes56cd6512018-07-17 13:00:17 -0700304static int __ashmem_check_failure(int fd, int result)
305{
306 if (result == -1 && errno == ENOTTY) __ashmem_is_ashmem(fd, 1);
307 return result;
308}
309
Joel Fernandes51944042018-12-18 13:32:31 -0800310static bool memfd_is_ashmem(int fd) {
311 static bool fd_check_error_once = false;
312
313 if (__ashmem_is_ashmem(fd, 0) == 0) {
314 if (!fd_check_error_once) {
315 ALOGE("memfd: memfd expected but ashmem fd used - please use libcutils.\n");
316 fd_check_error_once = true;
317 }
318
319 return true;
320 }
321
322 return false;
323}
324
Mark Salyzynee431112016-08-23 13:58:37 -0700325int ashmem_valid(int fd)
326{
Joel Fernandes51944042018-12-18 13:32:31 -0800327 if (has_memfd_support() && !memfd_is_ashmem(fd)) {
328 return 1;
329 }
330
Mark Salyzynee431112016-08-23 13:58:37 -0700331 return __ashmem_is_ashmem(fd, 0) >= 0;
332}
333
Joel Fernandes51944042018-12-18 13:32:31 -0800334static int memfd_create_region(const char* name, size_t size) {
Elliott Hughes790ef052020-09-03 10:53:16 -0700335 // This code needs to build on old API levels, so we can't use the libc
336 // wrapper.
337 android::base::unique_fd fd(syscall(__NR_memfd_create, name, MFD_CLOEXEC | MFD_ALLOW_SEALING));
Joel Fernandes51944042018-12-18 13:32:31 -0800338
339 if (fd == -1) {
340 ALOGE("memfd_create(%s, %zd) failed: %s\n", name, size, strerror(errno));
341 return -1;
342 }
343
344 if (ftruncate(fd, size) == -1) {
345 ALOGE("ftruncate(%s, %zd) failed for memfd creation: %s\n", name, size, strerror(errno));
346 return -1;
347 }
348
349 if (debug_log) {
350 ALOGE("memfd_create(%s, %zd) success. fd=%d\n", name, size, fd.get());
351 }
352 return fd.release();
353}
354
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800355/*
356 * ashmem_create_region - creates a new ashmem region and returns the file
357 * descriptor, or <0 on error
358 *
359 * `name' is an optional label to give the region (visible in /proc/pid/maps)
360 * `size' is the size of the region, in page-aligned bytes
361 */
362int ashmem_create_region(const char *name, size_t size)
363{
Mark Salyzync2d8aad2016-02-02 08:05:54 -0800364 int ret, save_errno;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800365
Joel Fernandes51944042018-12-18 13:32:31 -0800366 if (has_memfd_support()) {
367 return memfd_create_region(name ? name : "none", size);
368 }
369
Mark Salyzyn1186f3a2016-02-02 08:21:32 -0800370 int fd = __ashmem_open();
Mark Salyzync2d8aad2016-02-02 08:05:54 -0800371 if (fd < 0) {
372 return fd;
373 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800374
Mark Salyzync2d8aad2016-02-02 08:05:54 -0800375 if (name) {
376 char buf[ASHMEM_NAME_LEN] = {0};
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800377
Mark Salyzync2d8aad2016-02-02 08:05:54 -0800378 strlcpy(buf, name, sizeof(buf));
379 ret = TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_SET_NAME, buf));
380 if (ret < 0) {
381 goto error;
382 }
383 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800384
Mark Salyzync2d8aad2016-02-02 08:05:54 -0800385 ret = TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_SET_SIZE, size));
386 if (ret < 0) {
387 goto error;
388 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800389
Mark Salyzync2d8aad2016-02-02 08:05:54 -0800390 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800391
392error:
Mark Salyzync2d8aad2016-02-02 08:05:54 -0800393 save_errno = errno;
394 close(fd);
395 errno = save_errno;
396 return ret;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800397}
398
Joel Fernandes51944042018-12-18 13:32:31 -0800399static int memfd_set_prot_region(int fd, int prot) {
400 /* Only proceed if an fd needs to be write-protected */
401 if (prot & PROT_WRITE) {
402 return 0;
403 }
404
405 if (fcntl(fd, F_ADD_SEALS, F_SEAL_FUTURE_WRITE) == -1) {
406 ALOGE("memfd_set_prot_region(%d, %d): F_SEAL_FUTURE_WRITE seal failed: %s\n", fd, prot,
407 strerror(errno));
408 return -1;
409 }
410
411 return 0;
412}
413
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800414int ashmem_set_prot_region(int fd, int prot)
415{
Joel Fernandes51944042018-12-18 13:32:31 -0800416 if (has_memfd_support() && !memfd_is_ashmem(fd)) {
417 return memfd_set_prot_region(fd, prot);
418 }
419
Joel Fernandes56cd6512018-07-17 13:00:17 -0700420 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 -0800421}
422
423int ashmem_pin_region(int fd, size_t offset, size_t len)
424{
Joel Fernandes51944042018-12-18 13:32:31 -0800425 if (!pin_deprecation_warn || debug_log) {
426 ALOGE("Pinning is deprecated since Android Q. Please use trim or other methods.\n");
427 pin_deprecation_warn = true;
428 }
429
430 if (has_memfd_support() && !memfd_is_ashmem(fd)) {
431 return 0;
432 }
433
Elliott Hughes8e9aeb92017-11-10 10:22:07 -0800434 // TODO: should LP64 reject too-large offset/len?
435 ashmem_pin pin = { static_cast<uint32_t>(offset), static_cast<uint32_t>(len) };
Joel Fernandes56cd6512018-07-17 13:00:17 -0700436 return __ashmem_check_failure(fd, TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_PIN, &pin)));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800437}
438
439int ashmem_unpin_region(int fd, size_t offset, size_t len)
440{
Joel Fernandes51944042018-12-18 13:32:31 -0800441 if (!pin_deprecation_warn || debug_log) {
442 ALOGE("Pinning is deprecated since Android Q. Please use trim or other methods.\n");
443 pin_deprecation_warn = true;
444 }
445
446 if (has_memfd_support() && !memfd_is_ashmem(fd)) {
447 return 0;
448 }
449
Elliott Hughes8e9aeb92017-11-10 10:22:07 -0800450 // TODO: should LP64 reject too-large offset/len?
451 ashmem_pin pin = { static_cast<uint32_t>(offset), static_cast<uint32_t>(len) };
Joel Fernandes56cd6512018-07-17 13:00:17 -0700452 return __ashmem_check_failure(fd, TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_UNPIN, &pin)));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800453}
Bjorn Bringert7be52b12009-06-02 00:41:09 +0100454
455int ashmem_get_size_region(int fd)
456{
Joel Fernandes51944042018-12-18 13:32:31 -0800457 if (has_memfd_support() && !memfd_is_ashmem(fd)) {
458 struct stat sb;
459
460 if (fstat(fd, &sb) == -1) {
461 ALOGE("ashmem_get_size_region(%d): fstat failed: %s\n", fd, strerror(errno));
462 return -1;
463 }
464
465 if (debug_log) {
466 ALOGD("ashmem_get_size_region(%d): %d\n", fd, static_cast<int>(sb.st_size));
467 }
468
469 return sb.st_size;
470 }
471
Joel Fernandes56cd6512018-07-17 13:00:17 -0700472 return __ashmem_check_failure(fd, TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_GET_SIZE, NULL)));
Bjorn Bringert7be52b12009-06-02 00:41:09 +0100473}