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 = static_cast<int>(RawSyscall(__NR_memfd_create, bit_cast<long>(name), MFD_CLOEXEC));
45   CHECK(fd >= 0);
46   return fd;
47 }
48 
FtruncateOrDie(int fd,off64_t size)49 inline void FtruncateOrDie(int fd, off64_t size) {
50   // Call libc instead of syscall because we want 64 version and do not want to
51   // do ifdefs for 32/64/glibc/bionic in order to get the correct one.
52   CHECK_EQ(ftruncate64(fd, size), 0);
53 }
54 
WriteFullyOrDie(int fd,const void * data,size_t size)55 inline void WriteFullyOrDie(int fd, const void* data, size_t size) {
56   auto* curr = reinterpret_cast<const uint8_t*>(data);
57   auto* end = curr + size;
58   while (curr < end) {
59     auto written = RawSyscall(__NR_write, fd, bit_cast<long>(curr), end - curr);
60     // It is not clear if write syscall can return 0 when writing more than 0 bytes.
61     if (written >= 0) {
62       curr += written;
63     } else {
64       CHECK(written == -EINTR);
65     }
66   }
67 }
68 
CloseUnsafe(int fd)69 inline void CloseUnsafe(int fd) {
70   RawSyscall(__NR_close, fd);
71 }
72 
73 }  // namespace berberis
74 
75 #endif  // BERBERIS_BASE_FD_H_
76