ashmem-dev.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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. #include <cutils/ashmem.h>
  17. /*
  18. * Implementation of the user-space ashmem API for devices, which have our
  19. * ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
  20. * used by the simulator.
  21. */
  22. #define LOG_TAG "ashmem"
  23. #ifndef __ANDROID_VNDK__
  24. #include <dlfcn.h>
  25. #endif
  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. #include <android-base/properties.h>
  42. #include <android-base/unique_fd.h>
  43. #define ASHMEM_DEVICE "/dev/ashmem"
  44. /* Will be added to UAPI once upstream change is merged */
  45. #define F_SEAL_FUTURE_WRITE 0x0010
  46. /*
  47. * The minimum vendor API level at and after which it is safe to use memfd.
  48. * This is to facilitate deprecation of ashmem.
  49. */
  50. #define MIN_MEMFD_VENDOR_API_LEVEL 29
  51. #define MIN_MEMFD_VENDOR_API_LEVEL_CHAR 'Q'
  52. /* ashmem identity */
  53. static dev_t __ashmem_rdev;
  54. /*
  55. * If we trigger a signal handler in the middle of locked activity and the
  56. * signal handler calls ashmem, we could get into a deadlock state.
  57. */
  58. static pthread_mutex_t __ashmem_lock = PTHREAD_MUTEX_INITIALIZER;
  59. /*
  60. * We use ashmemd to enforce that apps don't open /dev/ashmem directly. Vendor
  61. * code can't access system aidl services per Treble requirements. So we limit
  62. * ashmemd access to the system variant of libcutils.
  63. */
  64. #ifndef __ANDROID_VNDK__
  65. using openFdType = int (*)();
  66. static openFdType openFd;
  67. openFdType initOpenAshmemFd() {
  68. openFdType openFd = nullptr;
  69. void* handle = dlopen("libashmemd_client.so", RTLD_NOW);
  70. if (!handle) {
  71. ALOGE("Failed to dlopen() libashmemd_client.so: %s", dlerror());
  72. return openFd;
  73. }
  74. openFd = reinterpret_cast<openFdType>(dlsym(handle, "openAshmemdFd"));
  75. if (!openFd) {
  76. ALOGE("Failed to dlsym() openAshmemdFd() function: %s", dlerror());
  77. }
  78. return openFd;
  79. }
  80. #endif
  81. /*
  82. * has_memfd_support() determines if the device can use memfd. memfd support
  83. * has been there for long time, but certain things in it may be missing. We
  84. * check for needed support in it. Also we check if the VNDK version of
  85. * libcutils being used is new enough, if its not, then we cannot use memfd
  86. * since the older copies may be using ashmem so we just use ashmem. Once all
  87. * Android devices that are getting updates are new enough (ex, they were
  88. * originally shipped with Android release > P), then we can just use memfd and
  89. * delete all ashmem code from libcutils (while preserving the interface).
  90. *
  91. * NOTE:
  92. * The sys.use_memfd property is set by default to false in Android
  93. * to temporarily disable memfd, till vendor and apps are ready for it.
  94. * The main issue: either apps or vendor processes can directly make ashmem
  95. * IOCTLs on FDs they receive by assuming they are ashmem, without going
  96. * through libcutils. Such fds could have very well be originally created with
  97. * libcutils hence they could be memfd. Thus the IOCTLs will break.
  98. *
  99. * Set default value of sys.use_memfd property to true once the issue is
  100. * resolved, so that the code can then self-detect if kernel support is present
  101. * on the device. The property can also set to true from adb shell, for
  102. * debugging.
  103. */
  104. static bool debug_log = false; /* set to true for verbose logging and other debug */
  105. static bool pin_deprecation_warn = true; /* Log the pin deprecation warning only once */
  106. /* Determine if vendor processes would be ok with memfd in the system:
  107. *
  108. * If VNDK is using older libcutils, don't use memfd. This is so that the
  109. * same shared memory mechanism is used across binder transactions between
  110. * vendor partition processes and system partition processes.
  111. */
  112. static bool check_vendor_memfd_allowed() {
  113. std::string vndk_version = android::base::GetProperty("ro.vndk.version", "");
  114. if (vndk_version == "") {
  115. ALOGE("memfd: ro.vndk.version not defined or invalid (%s), this is mandated since P.\n",
  116. vndk_version.c_str());
  117. return false;
  118. }
  119. /* No issues if vendor is targetting current Dessert */
  120. if (vndk_version == "current") {
  121. return false;
  122. }
  123. /* Check if VNDK version is a number and act on it */
  124. char* p;
  125. long int vers = strtol(vndk_version.c_str(), &p, 10);
  126. if (*p == 0) {
  127. if (vers < MIN_MEMFD_VENDOR_API_LEVEL) {
  128. ALOGI("memfd: device VNDK version (%s) is < Q so using ashmem.\n",
  129. vndk_version.c_str());
  130. return false;
  131. }
  132. return true;
  133. }
  134. /* If its not a number, assume string, but check if its a sane string */
  135. if (tolower(vndk_version[0]) < 'a' || tolower(vndk_version[0]) > 'z') {
  136. ALOGE("memfd: ro.vndk.version not defined or invalid (%s), this is mandated since P.\n",
  137. vndk_version.c_str());
  138. return false;
  139. }
  140. if (tolower(vndk_version[0]) < tolower(MIN_MEMFD_VENDOR_API_LEVEL_CHAR)) {
  141. ALOGI("memfd: device is using VNDK version (%s) which is less than Q. Use ashmem only.\n",
  142. vndk_version.c_str());
  143. return false;
  144. }
  145. return true;
  146. }
  147. /* Determine if memfd can be supported. This is just one-time hardwork
  148. * which will be cached by the caller.
  149. */
  150. static bool __has_memfd_support() {
  151. if (check_vendor_memfd_allowed() == false) {
  152. return false;
  153. }
  154. /* Used to turn on/off the detection at runtime, in the future this
  155. * property will be removed once we switch everything over to ashmem.
  156. * Currently it is used only for debugging to switch the system over.
  157. */
  158. if (!android::base::GetBoolProperty("sys.use_memfd", false)) {
  159. if (debug_log) {
  160. ALOGD("sys.use_memfd=false so memfd disabled\n");
  161. }
  162. return false;
  163. }
  164. /* Check if kernel support exists, otherwise fall back to ashmem */
  165. android::base::unique_fd fd(
  166. syscall(__NR_memfd_create, "test_android_memfd", MFD_ALLOW_SEALING));
  167. if (fd == -1) {
  168. ALOGE("memfd_create failed: %s, no memfd support.\n", strerror(errno));
  169. return false;
  170. }
  171. if (fcntl(fd, F_ADD_SEALS, F_SEAL_FUTURE_WRITE) == -1) {
  172. ALOGE("fcntl(F_ADD_SEALS) failed: %s, no memfd support.\n", strerror(errno));
  173. return false;
  174. }
  175. if (debug_log) {
  176. ALOGD("memfd: device has memfd support, using it\n");
  177. }
  178. return true;
  179. }
  180. static 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. return memfd_supported;
  186. }
  187. /* logistics of getting file descriptor for ashmem */
  188. static int __ashmem_open_locked()
  189. {
  190. int ret;
  191. struct stat st;
  192. int fd = -1;
  193. #ifndef __ANDROID_VNDK__
  194. if (!openFd) {
  195. openFd = initOpenAshmemFd();
  196. }
  197. if (openFd) {
  198. fd = openFd();
  199. }
  200. #endif
  201. if (fd < 0) {
  202. fd = TEMP_FAILURE_RETRY(open(ASHMEM_DEVICE, O_RDWR | O_CLOEXEC));
  203. }
  204. if (fd < 0) {
  205. return fd;
  206. }
  207. ret = TEMP_FAILURE_RETRY(fstat(fd, &st));
  208. if (ret < 0) {
  209. int save_errno = errno;
  210. close(fd);
  211. errno = save_errno;
  212. return ret;
  213. }
  214. if (!S_ISCHR(st.st_mode) || !st.st_rdev) {
  215. close(fd);
  216. errno = ENOTTY;
  217. return -1;
  218. }
  219. __ashmem_rdev = st.st_rdev;
  220. return fd;
  221. }
  222. static int __ashmem_open()
  223. {
  224. int fd;
  225. pthread_mutex_lock(&__ashmem_lock);
  226. fd = __ashmem_open_locked();
  227. pthread_mutex_unlock(&__ashmem_lock);
  228. return fd;
  229. }
  230. /* Make sure file descriptor references ashmem, negative number means false */
  231. static int __ashmem_is_ashmem(int fd, int fatal)
  232. {
  233. dev_t rdev;
  234. struct stat st;
  235. if (fstat(fd, &st) < 0) {
  236. return -1;
  237. }
  238. rdev = 0; /* Too much complexity to sniff __ashmem_rdev */
  239. if (S_ISCHR(st.st_mode) && st.st_rdev) {
  240. pthread_mutex_lock(&__ashmem_lock);
  241. rdev = __ashmem_rdev;
  242. if (rdev) {
  243. pthread_mutex_unlock(&__ashmem_lock);
  244. } else {
  245. int fd = __ashmem_open_locked();
  246. if (fd < 0) {
  247. pthread_mutex_unlock(&__ashmem_lock);
  248. return -1;
  249. }
  250. rdev = __ashmem_rdev;
  251. pthread_mutex_unlock(&__ashmem_lock);
  252. close(fd);
  253. }
  254. if (st.st_rdev == rdev) {
  255. return 0;
  256. }
  257. }
  258. if (fatal) {
  259. if (rdev) {
  260. LOG_ALWAYS_FATAL("illegal fd=%d mode=0%o rdev=%d:%d expected 0%o %d:%d",
  261. fd, st.st_mode, major(st.st_rdev), minor(st.st_rdev),
  262. S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IRGRP,
  263. major(rdev), minor(rdev));
  264. } else {
  265. LOG_ALWAYS_FATAL("illegal fd=%d mode=0%o rdev=%d:%d expected 0%o",
  266. fd, st.st_mode, major(st.st_rdev), minor(st.st_rdev),
  267. S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IRGRP);
  268. }
  269. /* NOTREACHED */
  270. }
  271. errno = ENOTTY;
  272. return -1;
  273. }
  274. static int __ashmem_check_failure(int fd, int result)
  275. {
  276. if (result == -1 && errno == ENOTTY) __ashmem_is_ashmem(fd, 1);
  277. return result;
  278. }
  279. static bool memfd_is_ashmem(int fd) {
  280. static bool fd_check_error_once = false;
  281. if (__ashmem_is_ashmem(fd, 0) == 0) {
  282. if (!fd_check_error_once) {
  283. ALOGE("memfd: memfd expected but ashmem fd used - please use libcutils.\n");
  284. fd_check_error_once = true;
  285. }
  286. return true;
  287. }
  288. return false;
  289. }
  290. int ashmem_valid(int fd)
  291. {
  292. if (has_memfd_support() && !memfd_is_ashmem(fd)) {
  293. return 1;
  294. }
  295. return __ashmem_is_ashmem(fd, 0) >= 0;
  296. }
  297. static int memfd_create_region(const char* name, size_t size) {
  298. android::base::unique_fd fd(syscall(__NR_memfd_create, name, MFD_ALLOW_SEALING));
  299. if (fd == -1) {
  300. ALOGE("memfd_create(%s, %zd) failed: %s\n", name, size, strerror(errno));
  301. return -1;
  302. }
  303. if (ftruncate(fd, size) == -1) {
  304. ALOGE("ftruncate(%s, %zd) failed for memfd creation: %s\n", name, size, strerror(errno));
  305. return -1;
  306. }
  307. if (debug_log) {
  308. ALOGE("memfd_create(%s, %zd) success. fd=%d\n", name, size, fd.get());
  309. }
  310. return fd.release();
  311. }
  312. /*
  313. * ashmem_create_region - creates a new ashmem region and returns the file
  314. * descriptor, or <0 on error
  315. *
  316. * `name' is an optional label to give the region (visible in /proc/pid/maps)
  317. * `size' is the size of the region, in page-aligned bytes
  318. */
  319. int ashmem_create_region(const char *name, size_t size)
  320. {
  321. int ret, save_errno;
  322. if (has_memfd_support()) {
  323. return memfd_create_region(name ? name : "none", size);
  324. }
  325. int fd = __ashmem_open();
  326. if (fd < 0) {
  327. return fd;
  328. }
  329. if (name) {
  330. char buf[ASHMEM_NAME_LEN] = {0};
  331. strlcpy(buf, name, sizeof(buf));
  332. ret = TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_SET_NAME, buf));
  333. if (ret < 0) {
  334. goto error;
  335. }
  336. }
  337. ret = TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_SET_SIZE, size));
  338. if (ret < 0) {
  339. goto error;
  340. }
  341. return fd;
  342. error:
  343. save_errno = errno;
  344. close(fd);
  345. errno = save_errno;
  346. return ret;
  347. }
  348. static int memfd_set_prot_region(int fd, int prot) {
  349. /* Only proceed if an fd needs to be write-protected */
  350. if (prot & PROT_WRITE) {
  351. return 0;
  352. }
  353. if (fcntl(fd, F_ADD_SEALS, F_SEAL_FUTURE_WRITE) == -1) {
  354. ALOGE("memfd_set_prot_region(%d, %d): F_SEAL_FUTURE_WRITE seal failed: %s\n", fd, prot,
  355. strerror(errno));
  356. return -1;
  357. }
  358. return 0;
  359. }
  360. int ashmem_set_prot_region(int fd, int prot)
  361. {
  362. if (has_memfd_support() && !memfd_is_ashmem(fd)) {
  363. return memfd_set_prot_region(fd, prot);
  364. }
  365. return __ashmem_check_failure(fd, TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_SET_PROT_MASK, prot)));
  366. }
  367. int ashmem_pin_region(int fd, size_t offset, size_t len)
  368. {
  369. if (!pin_deprecation_warn || debug_log) {
  370. ALOGE("Pinning is deprecated since Android Q. Please use trim or other methods.\n");
  371. pin_deprecation_warn = true;
  372. }
  373. if (has_memfd_support() && !memfd_is_ashmem(fd)) {
  374. return 0;
  375. }
  376. // TODO: should LP64 reject too-large offset/len?
  377. ashmem_pin pin = { static_cast<uint32_t>(offset), static_cast<uint32_t>(len) };
  378. return __ashmem_check_failure(fd, TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_PIN, &pin)));
  379. }
  380. int ashmem_unpin_region(int fd, size_t offset, size_t len)
  381. {
  382. if (!pin_deprecation_warn || debug_log) {
  383. ALOGE("Pinning is deprecated since Android Q. Please use trim or other methods.\n");
  384. pin_deprecation_warn = true;
  385. }
  386. if (has_memfd_support() && !memfd_is_ashmem(fd)) {
  387. return 0;
  388. }
  389. // TODO: should LP64 reject too-large offset/len?
  390. ashmem_pin pin = { static_cast<uint32_t>(offset), static_cast<uint32_t>(len) };
  391. return __ashmem_check_failure(fd, TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_UNPIN, &pin)));
  392. }
  393. int ashmem_get_size_region(int fd)
  394. {
  395. if (has_memfd_support() && !memfd_is_ashmem(fd)) {
  396. struct stat sb;
  397. if (fstat(fd, &sb) == -1) {
  398. ALOGE("ashmem_get_size_region(%d): fstat failed: %s\n", fd, strerror(errno));
  399. return -1;
  400. }
  401. if (debug_log) {
  402. ALOGD("ashmem_get_size_region(%d): %d\n", fd, static_cast<int>(sb.st_size));
  403. }
  404. return sb.st_size;
  405. }
  406. return __ashmem_check_failure(fd, TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_GET_SIZE, NULL)));
  407. }
  408. void ashmem_init() {
  409. #ifndef __ANDROID_VNDK__
  410. pthread_mutex_lock(&__ashmem_lock);
  411. openFd = initOpenAshmemFd();
  412. pthread_mutex_unlock(&__ashmem_lock);
  413. #endif //__ANDROID_VNDK__
  414. }