1 /*
2 * Copyright (C) 2021 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 // File operations without libc. Most important is not touching thread-local errno.
18
19 #ifndef BERBERIS_BASE_FD_H_
20 #define BERBERIS_BASE_FD_H_
21
22 #include <linux/unistd.h>
23 #include <sys/mman.h>
24 #include <unistd.h>
25
26 #include "berberis/base/bit_util.h"
27 #include "berberis/base/logging.h"
28 #include "berberis/base/raw_syscall.h"
29
30 // glibc in prebuilts does not have memfd_create
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 #define MFD_CLOEXEC 0x0001U
38 #endif // defined(__linux__) && !defined(__NR_memfd_create)
39
40 namespace berberis {
41
CreateMemfdOrDie(const char * name)42 inline int CreateMemfdOrDie(const char* name) {
43 // Use MFD_CLOEXEC to avoid leaking the file descriptor to child processes.
44 int fd = RawSyscall(__NR_memfd_create, bit_cast<long>(name), MFD_CLOEXEC);
45 CHECK(fd >= 0);
46 return fd;
47 }
48
WriteFullyOrDie(int fd,const void * data,size_t size)49 inline void WriteFullyOrDie(int fd, const void* data, size_t size) {
50 auto* curr = reinterpret_cast<const uint8_t*>(data);
51 auto* end = curr + size;
52 while (curr < end) {
53 auto written = RawSyscall(__NR_write, fd, bit_cast<long>(curr), end - curr);
54 // It is not clear if write syscall can return 0 when writing more than 0 bytes.
55 if (written >= 0) {
56 curr += written;
57 } else {
58 CHECK(written == -EINTR);
59 }
60 }
61 }
62
63 } // namespace berberis
64
65 #endif // BERBERIS_BASE_FD_H_
66