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 namespace berberis {
31 
CreateMemfdOrDie(const char * name)32 inline int CreateMemfdOrDie(const char* name) {
33   // Use MFD_CLOEXEC to avoid leaking the file descriptor to child processes.
34   int fd = static_cast<int>(RawSyscall(__NR_memfd_create, bit_cast<long>(name), MFD_CLOEXEC));
35   CHECK(fd >= 0);
36   return fd;
37 }
38 
FtruncateOrDie(int fd,off64_t size)39 inline void FtruncateOrDie(int fd, off64_t size) {
40   // Call libc instead of syscall because we want 64 version and do not want to
41   // do ifdefs for 32/64/glibc/bionic in order to get the correct one.
42   CHECK_EQ(ftruncate64(fd, size), 0);
43 }
44 
WriteFullyOrDie(int fd,const void * data,size_t size)45 inline void WriteFullyOrDie(int fd, const void* data, size_t size) {
46   auto* curr = reinterpret_cast<const uint8_t*>(data);
47   auto* end = curr + size;
48   while (curr < end) {
49     auto written = RawSyscall(__NR_write, fd, bit_cast<long>(curr), end - curr);
50     // It is not clear if write syscall can return 0 when writing more than 0 bytes.
51     if (written >= 0) {
52       curr += written;
53     } else {
54       CHECK(written == -EINTR);
55     }
56   }
57 }
58 
CloseUnsafe(int fd)59 inline void CloseUnsafe(int fd) {
60   RawSyscall(__NR_close, fd);
61 }
62 
63 }  // namespace berberis
64 
65 #endif  // BERBERIS_BASE_FD_H_
66