• 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 <sys/syscall.h>
23 #include <sys/utsname.h>
24 #include <unistd.h>
25 #endif
26 
27 #include "macros.h"
28 
29 // When building for linux host, glibc in prebuilts does not include memfd_create system call
30 // number. As a temporary testing measure, we add the definition here.
31 #if defined(__linux__) && !defined(__NR_memfd_create)
32 #if defined(__x86_64__)
33 #define __NR_memfd_create 319
34 #elif defined(__i386__)
35 #define __NR_memfd_create 356
36 #endif  // defined(__i386__)
37 #endif  // defined(__linux__) && !defined(__NR_memfd_create)
38 
39 namespace art {
40 
41 #if defined(__NR_memfd_create)
42 
memfd_create(const char * name,unsigned int flags)43 int memfd_create(const char* name, unsigned int flags) {
44   // Check kernel version supports memfd_create(). Some older kernels segfault executing
45   // memfd_create() rather than returning ENOSYS (b/116769556).
46   static constexpr int kRequiredMajor = 3;
47   static constexpr int kRequiredMinor = 17;
48   struct utsname uts;
49   int major, minor;
50   if (uname(&uts) != 0 ||
51       strcmp(uts.sysname, "Linux") != 0 ||
52       sscanf(uts.release, "%d.%d", &major, &minor) != 2 ||
53       (major < kRequiredMajor || (major == kRequiredMajor && minor < kRequiredMinor))) {
54     errno = ENOSYS;
55     return -1;
56   }
57 
58   return syscall(__NR_memfd_create, name, flags);
59 }
60 
61 #else  // __NR_memfd_create
62 
63 int memfd_create(const char* name ATTRIBUTE_UNUSED, unsigned int flags ATTRIBUTE_UNUSED) {
64   errno = ENOSYS;
65   return -1;
66 }
67 
68 #endif  // __NR_memfd_create
69 
70 }  // namespace art
71