• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 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 "memfd.h"
18 
19 #include <errno.h>
20 #include <stdio.h>
21 #if !defined(_WIN32)
22 #include <fcntl.h>
23 #include <sys/mman.h>
24 #include <sys/syscall.h>
25 #include <sys/utsname.h>
26 #include <unistd.h>
27 #endif
28 
29 #include <android-base/logging.h>
30 #include <android-base/unique_fd.h>
31 
32 #include "macros.h"
33 
34 namespace art {
35 
36 #if defined(__linux__)
37 
memfd_create(const char * name,unsigned int flags)38 int memfd_create(const char* name, unsigned int flags) {
39   // Check kernel version supports memfd_create(). Some older kernels segfault executing
40   // memfd_create() rather than returning ENOSYS (b/116769556).
41   static constexpr int kRequiredMajor = 3;
42   static constexpr int kRequiredMinor = 17;
43   struct utsname uts;
44   int major, minor;
45   if (uname(&uts) != 0 ||
46       strcmp(uts.sysname, "Linux") != 0 ||
47       sscanf(uts.release, "%d.%d", &major, &minor) != 2 ||
48       (major < kRequiredMajor || (major == kRequiredMajor && minor < kRequiredMinor))) {
49     errno = ENOSYS;
50     return -1;
51   }
52 
53   return syscall(__NR_memfd_create, name, flags);
54 }
55 
IsSealFutureWriteSupportedInternal()56 static bool IsSealFutureWriteSupportedInternal() {
57   android::base::unique_fd fd(art::memfd_create("test_android_memfd", MFD_ALLOW_SEALING));
58   if (fd == -1) {
59     LOG(INFO) << "memfd_create failed: " << strerror(errno) << ", no memfd support.";
60     return false;
61   }
62 
63   if (fcntl(fd, F_ADD_SEALS, F_SEAL_FUTURE_WRITE) == -1) {
64     LOG(INFO) << "fcntl(F_ADD_SEALS) failed: " << strerror(errno) << ", no memfd support.";
65     return false;
66   }
67 
68   LOG(INFO) << "Using memfd for future sealing";
69   return true;
70 }
71 
IsSealFutureWriteSupported()72 bool IsSealFutureWriteSupported() {
73   static bool is_seal_future_write_supported = IsSealFutureWriteSupportedInternal();
74   return is_seal_future_write_supported;
75 }
76 
77 #else  // __linux__
78 
79 int memfd_create([[maybe_unused]] const char* name, [[maybe_unused]] unsigned int flags) {
80   errno = ENOSYS;
81   return -1;
82 }
83 
84 bool IsSealFutureWriteSupported() {
85   return false;
86 }
87 
88 #endif  // __linux__
89 
90 }  // namespace art
91