• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2015 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 #pragma once
18 
19 #include <dirent.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 
23 #if !defined(_WIN32)
24 #include <sys/socket.h>
25 #endif
26 
27 #include <stdio.h>
28 #include <sys/types.h>
29 #include <unistd.h>
30 
31 // DO NOT INCLUDE OTHER LIBBASE HEADERS!
32 // This file gets used in libbinder, and libbinder is used everywhere.
33 // Including other headers from libbase frequently results in inclusion of
34 // android-base/macros.h, which causes macro collisions.
35 
36 // Container for a file descriptor that automatically closes the descriptor as
37 // it goes out of scope.
38 //
39 //      unique_fd ufd(open("/some/path", "r"));
40 //      if (ufd.get() == -1) return error;
41 //
42 //      // Do something useful, possibly including 'return'.
43 //
44 //      return 0; // Descriptor is closed for you.
45 //
46 // unique_fd is also known as ScopedFd/ScopedFD/scoped_fd; mentioned here to help
47 // you find this class if you're searching for one of those names.
48 
49 #if defined(__BIONIC__)
50 #include <android/fdsan.h>
51 #endif
52 
53 namespace android {
54 namespace base {
55 
56 struct DefaultCloser {
57 #if defined(__BIONIC__)
TagDefaultCloser58   static void Tag(int fd, void* old_addr, void* new_addr) {
59     if (android_fdsan_exchange_owner_tag) {
60       uint64_t old_tag = android_fdsan_create_owner_tag(ANDROID_FDSAN_OWNER_TYPE_UNIQUE_FD,
61                                                         reinterpret_cast<uint64_t>(old_addr));
62       uint64_t new_tag = android_fdsan_create_owner_tag(ANDROID_FDSAN_OWNER_TYPE_UNIQUE_FD,
63                                                         reinterpret_cast<uint64_t>(new_addr));
64       android_fdsan_exchange_owner_tag(fd, old_tag, new_tag);
65     }
66   }
CloseDefaultCloser67   static void Close(int fd, void* addr) {
68     if (android_fdsan_close_with_tag) {
69       uint64_t tag = android_fdsan_create_owner_tag(ANDROID_FDSAN_OWNER_TYPE_UNIQUE_FD,
70                                                     reinterpret_cast<uint64_t>(addr));
71       android_fdsan_close_with_tag(fd, tag);
72     } else {
73       close(fd);
74     }
75   }
76 #else
77   static void Close(int fd) {
78     // Even if close(2) fails with EINTR, the fd will have been closed.
79     // Using TEMP_FAILURE_RETRY will either lead to EBADF or closing someone
80     // else's fd.
81     // http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
82     ::close(fd);
83   }
84 #endif
85 };
86 
87 template <typename Closer>
88 class unique_fd_impl final {
89  public:
unique_fd_impl()90   unique_fd_impl() {}
91 
unique_fd_impl(int fd)92   explicit unique_fd_impl(int fd) { reset(fd); }
~unique_fd_impl()93   ~unique_fd_impl() { reset(); }
94 
unique_fd_impl(unique_fd_impl && other)95   unique_fd_impl(unique_fd_impl&& other) noexcept { reset(other.release()); }
96   unique_fd_impl& operator=(unique_fd_impl&& s) noexcept {
97     int fd = s.fd_;
98     s.fd_ = -1;
99     reset(fd, &s);
100     return *this;
101   }
102 
103   void reset(int new_value = -1) { reset(new_value, nullptr); }
104 
get()105   int get() const { return fd_; }
106   operator int() const { return get(); }  // NOLINT
107 
108   // Catch bogus error checks (i.e.: "!fd" instead of "fd != -1").
109   bool operator!() const = delete;
110 
release()111   int release() __attribute__((warn_unused_result)) {
112     tag(fd_, this, nullptr);
113     int ret = fd_;
114     fd_ = -1;
115     return ret;
116   }
117 
118  private:
reset(int new_value,void * previous_tag)119   void reset(int new_value, void* previous_tag) {
120     int previous_errno = errno;
121 
122     if (fd_ != -1) {
123       close(fd_, this);
124     }
125 
126     fd_ = new_value;
127     if (new_value != -1) {
128       tag(new_value, previous_tag, this);
129     }
130 
131     errno = previous_errno;
132   }
133 
134   int fd_ = -1;
135 
136   // Template magic to use Closer::Tag if available, and do nothing if not.
137   // If Closer::Tag exists, this implementation is preferred, because int is a better match.
138   // If not, this implementation is SFINAEd away, and the no-op below is the only one that exists.
139   template <typename T = Closer>
140   static auto tag(int fd, void* old_tag, void* new_tag)
141       -> decltype(T::Tag(fd, old_tag, new_tag), void()) {
142     T::Tag(fd, old_tag, new_tag);
143   }
144 
145   template <typename T = Closer>
tag(long,void *,void *)146   static void tag(long, void*, void*) {
147     // No-op.
148   }
149 
150   // Same as above, to select between Closer::Close(int) and Closer::Close(int, void*).
151   template <typename T = Closer>
152   static auto close(int fd, void* tag_value) -> decltype(T::Close(fd, tag_value), void()) {
153     T::Close(fd, tag_value);
154   }
155 
156   template <typename T = Closer>
157   static auto close(int fd, void*) -> decltype(T::Close(fd), void()) {
158     T::Close(fd);
159   }
160 
161   unique_fd_impl(const unique_fd_impl&);
162   void operator=(const unique_fd_impl&);
163 };
164 
165 using unique_fd = unique_fd_impl<DefaultCloser>;
166 
167 #if !defined(_WIN32)
168 
169 // Inline functions, so that they can be used header-only.
170 template <typename Closer>
171 inline bool Pipe(unique_fd_impl<Closer>* read, unique_fd_impl<Closer>* write,
172                  int flags = O_CLOEXEC) {
173   int pipefd[2];
174 
175 #if defined(__linux__)
176   if (pipe2(pipefd, flags) != 0) {
177     return false;
178   }
179 #else  // defined(__APPLE__)
180   if (flags & ~(O_CLOEXEC | O_NONBLOCK)) {
181     return false;
182   }
183   if (pipe(pipefd) != 0) {
184     return false;
185   }
186 
187   if (flags & O_CLOEXEC) {
188     if (fcntl(pipefd[0], F_SETFD, FD_CLOEXEC) != 0 || fcntl(pipefd[1], F_SETFD, FD_CLOEXEC) != 0) {
189       close(pipefd[0]);
190       close(pipefd[1]);
191       return false;
192     }
193   }
194   if (flags & O_NONBLOCK) {
195     if (fcntl(pipefd[0], F_SETFL, O_NONBLOCK) != 0 || fcntl(pipefd[1], F_SETFL, O_NONBLOCK) != 0) {
196       close(pipefd[0]);
197       close(pipefd[1]);
198       return false;
199     }
200   }
201 #endif
202 
203   read->reset(pipefd[0]);
204   write->reset(pipefd[1]);
205   return true;
206 }
207 
208 template <typename Closer>
Socketpair(int domain,int type,int protocol,unique_fd_impl<Closer> * left,unique_fd_impl<Closer> * right)209 inline bool Socketpair(int domain, int type, int protocol, unique_fd_impl<Closer>* left,
210                        unique_fd_impl<Closer>* right) {
211   int sockfd[2];
212   if (socketpair(domain, type, protocol, sockfd) != 0) {
213     return false;
214   }
215   left->reset(sockfd[0]);
216   right->reset(sockfd[1]);
217   return true;
218 }
219 
220 template <typename Closer>
Socketpair(int type,unique_fd_impl<Closer> * left,unique_fd_impl<Closer> * right)221 inline bool Socketpair(int type, unique_fd_impl<Closer>* left, unique_fd_impl<Closer>* right) {
222   return Socketpair(AF_UNIX, type, 0, left, right);
223 }
224 
225 // Using fdopen with unique_fd correctly is more annoying than it should be,
226 // because fdopen doesn't close the file descriptor received upon failure.
Fdopen(unique_fd && ufd,const char * mode)227 inline FILE* Fdopen(unique_fd&& ufd, const char* mode) {
228   int fd = ufd.release();
229   FILE* file = fdopen(fd, mode);
230   if (!file) {
231     close(fd);
232   }
233   return file;
234 }
235 
236 // Using fdopendir with unique_fd correctly is more annoying than it should be,
237 // because fdopen doesn't close the file descriptor received upon failure.
Fdopendir(unique_fd && ufd)238 inline DIR* Fdopendir(unique_fd&& ufd) {
239   int fd = ufd.release();
240   DIR* dir = fdopendir(fd);
241   if (dir == nullptr) {
242     close(fd);
243   }
244   return dir;
245 }
246 
247 #endif  // !defined(_WIN32)
248 
249 }  // namespace base
250 }  // namespace android
251 
252 template <typename T>
253 int close(const android::base::unique_fd_impl<T>&)
254     __attribute__((__unavailable__("close called on unique_fd")));
255 
256 template <typename T>
257 FILE* fdopen(const android::base::unique_fd_impl<T>&, const char* mode)
258     __attribute__((__unavailable__("fdopen takes ownership of the fd passed in; either dup the "
259                                    "unique_fd, or use android::base::Fdopen to pass ownership")));
260 
261 template <typename T>
262 DIR* fdopendir(const android::base::unique_fd_impl<T>&) __attribute__((
263     __unavailable__("fdopendir takes ownership of the fd passed in; either dup the "
264                     "unique_fd, or use android::base::Fdopendir to pass ownership")));
265