blob: e35b91ae3fb3d30a942164e984a3c7dfea4ec854 [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
Tri Vo2891ba02019-01-28 17:56:43 -080026#ifndef __ANDROID_VNDK__
27#include <dlfcn.h>
28#endif
Mark Salyzync2d8aad2016-02-02 08:05:54 -080029#include <errno.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080030#include <fcntl.h>
Mark Salyzyn23ed4c22016-09-28 13:33:27 -070031#include <linux/ashmem.h>
Joel Fernandes51944042018-12-18 13:32:31 -080032#include <linux/memfd.h>
33#include <log/log.h>
Mark Salyzyn1186f3a2016-02-02 08:21:32 -080034#include <pthread.h>
Joel Fernandes51944042018-12-18 13:32:31 -080035#include <stdio.h>
Mark Salyzync2d8aad2016-02-02 08:05:54 -080036#include <string.h>
37#include <sys/ioctl.h>
Joel Fernandes51944042018-12-18 13:32:31 -080038#include <sys/mman.h>
Mark Salyzync2d8aad2016-02-02 08:05:54 -080039#include <sys/stat.h>
Joel Fernandes51944042018-12-18 13:32:31 -080040#include <sys/syscall.h>
Elliott Hughesd77b5372017-05-17 11:36:51 -070041#include <sys/sysmacros.h>
Mark Salyzync2d8aad2016-02-02 08:05:54 -080042#include <sys/types.h>
43#include <unistd.h>
Joel Fernandes51944042018-12-18 13:32:31 -080044
45#include <android-base/properties.h>
46#include <android-base/unique_fd.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080047
Mark Salyzync2d8aad2016-02-02 08:05:54 -080048#define ASHMEM_DEVICE "/dev/ashmem"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080049
Joel Fernandes51944042018-12-18 13:32:31 -080050/* Will be added to UAPI once upstream change is merged */
51#define F_SEAL_FUTURE_WRITE 0x0010
52
53/*
54 * The minimum vendor API level at and after which it is safe to use memfd.
55 * This is to facilitate deprecation of ashmem.
56 */
57#define MIN_MEMFD_VENDOR_API_LEVEL 29
58#define MIN_MEMFD_VENDOR_API_LEVEL_CHAR 'Q'
59
Mark Salyzyn1186f3a2016-02-02 08:21:32 -080060/* ashmem identity */
61static dev_t __ashmem_rdev;
62/*
63 * If we trigger a signal handler in the middle of locked activity and the
64 * signal handler calls ashmem, we could get into a deadlock state.
65 */
66static pthread_mutex_t __ashmem_lock = PTHREAD_MUTEX_INITIALIZER;
67
Tri Vo2891ba02019-01-28 17:56:43 -080068/*
69 * We use ashmemd to enforce that apps don't open /dev/ashmem directly. Vendor
70 * code can't access system aidl services per Treble requirements. So we limit
71 * ashmemd access to the system variant of libcutils.
72 */
73#ifndef __ANDROID_VNDK__
74using openFdType = int (*)();
75
76openFdType initOpenAshmemFd() {
77 openFdType openFd = nullptr;
78 void* handle = dlopen("libashmemd_client.so", RTLD_NOW);
79 if (!handle) {
80 ALOGE("Failed to dlopen() libashmemd_client.so: %s", dlerror());
81 return openFd;
82 }
83
84 openFd = reinterpret_cast<openFdType>(dlsym(handle, "openAshmemdFd"));
85 if (!openFd) {
86 ALOGE("Failed to dlsym() openAshmemdFd() function: %s", dlerror());
87 }
88 return openFd;
89}
90#endif
91
Joel Fernandes51944042018-12-18 13:32:31 -080092/*
93 * has_memfd_support() determines if the device can use memfd. memfd support
94 * has been there for long time, but certain things in it may be missing. We
95 * check for needed support in it. Also we check if the VNDK version of
96 * libcutils being used is new enough, if its not, then we cannot use memfd
97 * since the older copies may be using ashmem so we just use ashmem. Once all
98 * Android devices that are getting updates are new enough (ex, they were
99 * originally shipped with Android release > P), then we can just use memfd and
100 * delete all ashmem code from libcutils (while preserving the interface).
101 *
102 * NOTE:
103 * The sys.use_memfd property is set by default to false in Android
104 * to temporarily disable memfd, till vendor and apps are ready for it.
105 * The main issue: either apps or vendor processes can directly make ashmem
106 * IOCTLs on FDs they receive by assuming they are ashmem, without going
107 * through libcutils. Such fds could have very well be originally created with
108 * libcutils hence they could be memfd. Thus the IOCTLs will break.
109 *
110 * Set default value of sys.use_memfd property to true once the issue is
111 * resolved, so that the code can then self-detect if kernel support is present
112 * on the device. The property can also set to true from adb shell, for
113 * debugging.
114 */
115
116static bool debug_log = false; /* set to true for verbose logging and other debug */
117static bool pin_deprecation_warn = true; /* Log the pin deprecation warning only once */
118
119/* Determine if vendor processes would be ok with memfd in the system:
120 *
121 * If VNDK is using older libcutils, don't use memfd. This is so that the
122 * same shared memory mechanism is used across binder transactions between
123 * vendor partition processes and system partition processes.
124 */
125static bool check_vendor_memfd_allowed() {
126 std::string vndk_version = android::base::GetProperty("ro.vndk.version", "");
127
128 if (vndk_version == "") {
129 ALOGE("memfd: ro.vndk.version not defined or invalid (%s), this is mandated since P.\n",
130 vndk_version.c_str());
131 return false;
132 }
133
134 /* No issues if vendor is targetting current Dessert */
135 if (vndk_version == "current") {
136 return false;
137 }
138
139 /* Check if VNDK version is a number and act on it */
140 char* p;
141 long int vers = strtol(vndk_version.c_str(), &p, 10);
142 if (*p == 0) {
143 if (vers < MIN_MEMFD_VENDOR_API_LEVEL) {
144 ALOGI("memfd: device VNDK version (%s) is < Q so using ashmem.\n",
145 vndk_version.c_str());
146 return false;
147 }
148
149 return true;
150 }
151
152 /* If its not a number, assume string, but check if its a sane string */
153 if (tolower(vndk_version[0]) < 'a' || tolower(vndk_version[0]) > 'z') {
154 ALOGE("memfd: ro.vndk.version not defined or invalid (%s), this is mandated since P.\n",
155 vndk_version.c_str());
156 return false;
157 }
158
159 if (tolower(vndk_version[0]) < tolower(MIN_MEMFD_VENDOR_API_LEVEL_CHAR)) {
160 ALOGI("memfd: device is using VNDK version (%s) which is less than Q. Use ashmem only.\n",
161 vndk_version.c_str());
162 return false;
163 }
164
165 return true;
166}
167
168
169/* Determine if memfd can be supported. This is just one-time hardwork
170 * which will be cached by the caller.
171 */
172static bool __has_memfd_support() {
173 if (check_vendor_memfd_allowed() == false) {
174 return false;
175 }
176
177 /* Used to turn on/off the detection at runtime, in the future this
178 * property will be removed once we switch everything over to ashmem.
179 * Currently it is used only for debugging to switch the system over.
180 */
181 if (!android::base::GetBoolProperty("sys.use_memfd", false)) {
182 if (debug_log) {
183 ALOGD("sys.use_memfd=false so memfd disabled\n");
184 }
185 return false;
186 }
187
188 /* Check if kernel support exists, otherwise fall back to ashmem */
189 android::base::unique_fd fd(
190 syscall(__NR_memfd_create, "test_android_memfd", MFD_ALLOW_SEALING));
191 if (fd == -1) {
192 ALOGE("memfd_create failed: %s, no memfd support.\n", strerror(errno));
193 return false;
194 }
195
196 if (fcntl(fd, F_ADD_SEALS, F_SEAL_FUTURE_WRITE) == -1) {
197 ALOGE("fcntl(F_ADD_SEALS) failed: %s, no memfd support.\n", strerror(errno));
198 return false;
199 }
200
201 if (debug_log) {
202 ALOGD("memfd: device has memfd support, using it\n");
203 }
204 return true;
205}
206
207static bool has_memfd_support() {
208 /* memfd_supported is the initial global per-process state of what is known
209 * about memfd.
210 */
211 static bool memfd_supported = __has_memfd_support();
212
213 return memfd_supported;
214}
215
Mark Salyzyn1186f3a2016-02-02 08:21:32 -0800216/* logistics of getting file descriptor for ashmem */
217static int __ashmem_open_locked()
218{
219 int ret;
220 struct stat st;
221
Tri Vo2891ba02019-01-28 17:56:43 -0800222 int fd = -1;
223#ifndef __ANDROID_VNDK__
224 static auto openFd = initOpenAshmemFd();
225 if (openFd) {
226 fd = openFd();
227 }
228#endif
229 if (fd < 0) {
230 fd = TEMP_FAILURE_RETRY(open(ASHMEM_DEVICE, O_RDWR | O_CLOEXEC));
231 }
Mark Salyzyn1186f3a2016-02-02 08:21:32 -0800232 if (fd < 0) {
233 return fd;
234 }
235
236 ret = TEMP_FAILURE_RETRY(fstat(fd, &st));
237 if (ret < 0) {
238 int save_errno = errno;
239 close(fd);
240 errno = save_errno;
241 return ret;
242 }
243 if (!S_ISCHR(st.st_mode) || !st.st_rdev) {
244 close(fd);
245 errno = ENOTTY;
246 return -1;
247 }
248
249 __ashmem_rdev = st.st_rdev;
250 return fd;
251}
252
253static int __ashmem_open()
254{
255 int fd;
256
257 pthread_mutex_lock(&__ashmem_lock);
258 fd = __ashmem_open_locked();
259 pthread_mutex_unlock(&__ashmem_lock);
260
261 return fd;
262}
263
264/* Make sure file descriptor references ashmem, negative number means false */
Mark Salyzynee431112016-08-23 13:58:37 -0700265static int __ashmem_is_ashmem(int fd, int fatal)
Mark Salyzyn1186f3a2016-02-02 08:21:32 -0800266{
267 dev_t rdev;
268 struct stat st;
269
Joel Fernandes56cd6512018-07-17 13:00:17 -0700270 if (fstat(fd, &st) < 0) {
Mark Salyzyn1186f3a2016-02-02 08:21:32 -0800271 return -1;
272 }
273
Mark Salyzyne37111d2016-02-02 09:19:39 -0800274 rdev = 0; /* Too much complexity to sniff __ashmem_rdev */
Mark Salyzyn1186f3a2016-02-02 08:21:32 -0800275 if (S_ISCHR(st.st_mode) && st.st_rdev) {
276 pthread_mutex_lock(&__ashmem_lock);
277 rdev = __ashmem_rdev;
278 if (rdev) {
279 pthread_mutex_unlock(&__ashmem_lock);
280 } else {
281 int fd = __ashmem_open_locked();
282 if (fd < 0) {
283 pthread_mutex_unlock(&__ashmem_lock);
284 return -1;
285 }
286 rdev = __ashmem_rdev;
287 pthread_mutex_unlock(&__ashmem_lock);
288
289 close(fd);
290 }
291
292 if (st.st_rdev == rdev) {
293 return 0;
294 }
295 }
296
Mark Salyzynee431112016-08-23 13:58:37 -0700297 if (fatal) {
298 if (rdev) {
299 LOG_ALWAYS_FATAL("illegal fd=%d mode=0%o rdev=%d:%d expected 0%o %d:%d",
300 fd, st.st_mode, major(st.st_rdev), minor(st.st_rdev),
301 S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IRGRP,
302 major(rdev), minor(rdev));
303 } else {
304 LOG_ALWAYS_FATAL("illegal fd=%d mode=0%o rdev=%d:%d expected 0%o",
305 fd, st.st_mode, major(st.st_rdev), minor(st.st_rdev),
306 S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IRGRP);
307 }
308 /* NOTREACHED */
Mark Salyzyne37111d2016-02-02 09:19:39 -0800309 }
310
Mark Salyzyn1186f3a2016-02-02 08:21:32 -0800311 errno = ENOTTY;
312 return -1;
313}
314
Joel Fernandes56cd6512018-07-17 13:00:17 -0700315static int __ashmem_check_failure(int fd, int result)
316{
317 if (result == -1 && errno == ENOTTY) __ashmem_is_ashmem(fd, 1);
318 return result;
319}
320
Joel Fernandes51944042018-12-18 13:32:31 -0800321static bool memfd_is_ashmem(int fd) {
322 static bool fd_check_error_once = false;
323
324 if (__ashmem_is_ashmem(fd, 0) == 0) {
325 if (!fd_check_error_once) {
326 ALOGE("memfd: memfd expected but ashmem fd used - please use libcutils.\n");
327 fd_check_error_once = true;
328 }
329
330 return true;
331 }
332
333 return false;
334}
335
Mark Salyzynee431112016-08-23 13:58:37 -0700336int ashmem_valid(int fd)
337{
Joel Fernandes51944042018-12-18 13:32:31 -0800338 if (has_memfd_support() && !memfd_is_ashmem(fd)) {
339 return 1;
340 }
341
Mark Salyzynee431112016-08-23 13:58:37 -0700342 return __ashmem_is_ashmem(fd, 0) >= 0;
343}
344
Joel Fernandes51944042018-12-18 13:32:31 -0800345static int memfd_create_region(const char* name, size_t size) {
346 android::base::unique_fd fd(syscall(__NR_memfd_create, name, MFD_ALLOW_SEALING));
347
348 if (fd == -1) {
349 ALOGE("memfd_create(%s, %zd) failed: %s\n", name, size, strerror(errno));
350 return -1;
351 }
352
353 if (ftruncate(fd, size) == -1) {
354 ALOGE("ftruncate(%s, %zd) failed for memfd creation: %s\n", name, size, strerror(errno));
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
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800364/*
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 */
371int ashmem_create_region(const char *name, size_t size)
372{
Mark Salyzync2d8aad2016-02-02 08:05:54 -0800373 int ret, save_errno;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800374
Joel Fernandes51944042018-12-18 13:32:31 -0800375 if (has_memfd_support()) {
376 return memfd_create_region(name ? name : "none", size);
377 }
378
Mark Salyzyn1186f3a2016-02-02 08:21:32 -0800379 int fd = __ashmem_open();
Mark Salyzync2d8aad2016-02-02 08:05:54 -0800380 if (fd < 0) {
381 return fd;
382 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800383
Mark Salyzync2d8aad2016-02-02 08:05:54 -0800384 if (name) {
385 char buf[ASHMEM_NAME_LEN] = {0};
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800386
Mark Salyzync2d8aad2016-02-02 08:05:54 -0800387 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 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800393
Mark Salyzync2d8aad2016-02-02 08:05:54 -0800394 ret = TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_SET_SIZE, size));
395 if (ret < 0) {
396 goto error;
397 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800398
Mark Salyzync2d8aad2016-02-02 08:05:54 -0800399 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800400
401error:
Mark Salyzync2d8aad2016-02-02 08:05:54 -0800402 save_errno = errno;
403 close(fd);
404 errno = save_errno;
405 return ret;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800406}
407
Joel Fernandes51944042018-12-18 13:32:31 -0800408static int memfd_set_prot_region(int fd, int prot) {
409 /* Only proceed if an fd needs to be write-protected */
410 if (prot & PROT_WRITE) {
411 return 0;
412 }
413
414 if (fcntl(fd, F_ADD_SEALS, F_SEAL_FUTURE_WRITE) == -1) {
415 ALOGE("memfd_set_prot_region(%d, %d): F_SEAL_FUTURE_WRITE seal failed: %s\n", fd, prot,
416 strerror(errno));
417 return -1;
418 }
419
420 return 0;
421}
422
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800423int ashmem_set_prot_region(int fd, int prot)
424{
Joel Fernandes51944042018-12-18 13:32:31 -0800425 if (has_memfd_support() && !memfd_is_ashmem(fd)) {
426 return memfd_set_prot_region(fd, prot);
427 }
428
Joel Fernandes56cd6512018-07-17 13:00:17 -0700429 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 -0800430}
431
432int ashmem_pin_region(int fd, size_t offset, size_t len)
433{
Joel Fernandes51944042018-12-18 13:32:31 -0800434 if (!pin_deprecation_warn || debug_log) {
435 ALOGE("Pinning is deprecated since Android Q. Please use trim or other methods.\n");
436 pin_deprecation_warn = true;
437 }
438
439 if (has_memfd_support() && !memfd_is_ashmem(fd)) {
440 return 0;
441 }
442
Elliott Hughes8e9aeb92017-11-10 10:22:07 -0800443 // TODO: should LP64 reject too-large offset/len?
444 ashmem_pin pin = { static_cast<uint32_t>(offset), static_cast<uint32_t>(len) };
Joel Fernandes56cd6512018-07-17 13:00:17 -0700445 return __ashmem_check_failure(fd, TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_PIN, &pin)));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800446}
447
448int ashmem_unpin_region(int fd, size_t offset, size_t len)
449{
Joel Fernandes51944042018-12-18 13:32:31 -0800450 if (!pin_deprecation_warn || debug_log) {
451 ALOGE("Pinning is deprecated since Android Q. Please use trim or other methods.\n");
452 pin_deprecation_warn = true;
453 }
454
455 if (has_memfd_support() && !memfd_is_ashmem(fd)) {
456 return 0;
457 }
458
Elliott Hughes8e9aeb92017-11-10 10:22:07 -0800459 // TODO: should LP64 reject too-large offset/len?
460 ashmem_pin pin = { static_cast<uint32_t>(offset), static_cast<uint32_t>(len) };
Joel Fernandes56cd6512018-07-17 13:00:17 -0700461 return __ashmem_check_failure(fd, TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_UNPIN, &pin)));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800462}
Bjorn Bringert7be52b12009-06-02 00:41:09 +0100463
464int ashmem_get_size_region(int fd)
465{
Joel Fernandes51944042018-12-18 13:32:31 -0800466 if (has_memfd_support() && !memfd_is_ashmem(fd)) {
467 struct stat sb;
468
469 if (fstat(fd, &sb) == -1) {
470 ALOGE("ashmem_get_size_region(%d): fstat failed: %s\n", fd, strerror(errno));
471 return -1;
472 }
473
474 if (debug_log) {
475 ALOGD("ashmem_get_size_region(%d): %d\n", fd, static_cast<int>(sb.st_size));
476 }
477
478 return sb.st_size;
479 }
480
Joel Fernandes56cd6512018-07-17 13:00:17 -0700481 return __ashmem_check_failure(fd, TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_GET_SIZE, NULL)));
Bjorn Bringert7be52b12009-06-02 00:41:09 +0100482}