blob: 64025bf410a81e5ccc49202b870c3a8d5a81d8c7 [file] [log] [blame]
Eric Seckler14a22db2020-02-03 13:47:08 +00001/*
2 * Copyright (C) 2020 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 "src/tracing/ipc/memfd.h"
18
19#include <errno.h>
20
21#define PERFETTO_MEMFD_ENABLED() \
22 PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) || \
23 PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX)
24
25#if PERFETTO_MEMFD_ENABLED()
26
27#include <stdio.h>
28#include <string.h>
29#include <sys/syscall.h>
30#include <sys/utsname.h>
31#include <unistd.h>
32
33// Some android build bots use a sysroot that doesn't support memfd when
34// compiling for the host, so we redefine it if necessary.
35#if !defined(__NR_memfd_create)
36#if defined(__x86_64__)
37#define __NR_memfd_create 319
38#elif defined(__i386__)
39#define __NR_memfd_create 356
40#elif defined(__aarch64__)
41#define __NR_memfd_create 279
42#elif defined(__arm__)
43#define __NR_memfd_create 385
44#else
45#error "unsupported sysroot without memfd support"
46#endif
47#endif // !defined(__NR_memfd_create)
48
49namespace perfetto {
50bool HasMemfdSupport() {
51 static bool kSupportsMemfd = [] {
52 // Check kernel version supports memfd_create(). Some older kernels segfault
53 // executing memfd_create() rather than returning ENOSYS (b/116769556).
54 static constexpr int kRequiredMajor = 3;
55 static constexpr int kRequiredMinor = 17;
56 struct utsname uts;
57 int major, minor;
58 if (uname(&uts) == 0 && strcmp(uts.sysname, "Linux") == 0 &&
59 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
60 ((major < kRequiredMajor ||
61 (major == kRequiredMajor && minor < kRequiredMinor)))) {
62 return false;
63 }
64
65 base::ScopedFile fd;
66 fd.reset(static_cast<int>(syscall(__NR_memfd_create, "perfetto_shmem",
67 MFD_CLOEXEC | MFD_ALLOW_SEALING)));
68 return !!fd;
69 }();
70 return kSupportsMemfd;
71}
72
73base::ScopedFile CreateMemfd(const char* name, unsigned int flags) {
74 if (!HasMemfdSupport()) {
75 errno = ENOSYS;
76 return base::ScopedFile();
77 }
78 return base::ScopedFile(
79 static_cast<int>(syscall(__NR_memfd_create, name, flags)));
80}
81} // namespace perfetto
82
83#else // PERFETTO_MEMFD_ENABLED()
84
85namespace perfetto {
86bool HasMemfdSupport() {
87 return false;
88}
89base::ScopedFile CreateMemfd(const char*, unsigned int) {
90 errno = ENOSYS;
91 return base::ScopedFile();
92}
93} // namespace perfetto
94
95#endif // PERFETTO_MEMFD_ENABLED()