• 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 
95   unique_fd_impl(const unique_fd_impl&) = delete;
96   void operator=(const unique_fd_impl&) = delete;
unique_fd_impl(unique_fd_impl && other)97   unique_fd_impl(unique_fd_impl&& other) noexcept { reset(other.release()); }
98   unique_fd_impl& operator=(unique_fd_impl&& s) noexcept {
99     int fd = s.fd_;
100     s.fd_ = -1;
101     reset(fd, &s);
102     return *this;
103   }
104 
105   [[clang::reinitializes]] void reset(int new_value = -1) { reset(new_value, nullptr); }
106 
get()107   int get() const { return fd_; }
108 
109 #if !defined(ANDROID_BASE_UNIQUE_FD_DISABLE_IMPLICIT_CONVERSION)
110   // unique_fd's operator int is dangerous, but we have way too much code that
111   // depends on it, so make this opt-in at first.
112   operator int() const { return get(); }  // NOLINT
113 #endif
114 
115   bool operator>=(int rhs) const { return get() >= rhs; }
116   bool operator<(int rhs) const { return get() < rhs; }
117   bool operator==(int rhs) const { return get() == rhs; }
118   bool operator!=(int rhs) const { return get() != rhs; }
119   bool operator==(const unique_fd_impl& rhs) const { return get() == rhs.get(); }
120   bool operator!=(const unique_fd_impl& rhs) const { return get() != rhs.get(); }
121 
122   // Catch bogus error checks (i.e.: "!fd" instead of "fd != -1").
123   bool operator!() const = delete;
124 
ok()125   bool ok() const { return get() >= 0; }
126 
release()127   int release() __attribute__((warn_unused_result)) {
128     tag(fd_, this, nullptr);
129     int ret = fd_;
130     fd_ = -1;
131     return ret;
132   }
133 
134  private:
reset(int new_value,void * previous_tag)135   void reset(int new_value, void* previous_tag) {
136     int previous_errno = errno;
137 
138     if (fd_ != -1) {
139       close(fd_, this);
140     }
141 
142     fd_ = new_value;
143     if (new_value != -1) {
144       tag(new_value, previous_tag, this);
145     }
146 
147     errno = previous_errno;
148   }
149 
150   int fd_ = -1;
151 
152   // Template magic to use Closer::Tag if available, and do nothing if not.
153   // If Closer::Tag exists, this implementation is preferred, because int is a better match.
154   // If not, this implementation is SFINAEd away, and the no-op below is the only one that exists.
155   template <typename T = Closer>
156   static auto tag(int fd, void* old_tag, void* new_tag)
157       -> decltype(T::Tag(fd, old_tag, new_tag), void()) {
158     T::Tag(fd, old_tag, new_tag);
159   }
160 
161   template <typename T = Closer>
tag(long,void *,void *)162   static void tag(long, void*, void*) {
163     // No-op.
164   }
165 
166   // Same as above, to select between Closer::Close(int) and Closer::Close(int, void*).
167   template <typename T = Closer>
168   static auto close(int fd, void* tag_value) -> decltype(T::Close(fd, tag_value), void()) {
169     T::Close(fd, tag_value);
170   }
171 
172   template <typename T = Closer>
173   static auto close(int fd, void*) -> decltype(T::Close(fd), void()) {
174     T::Close(fd);
175   }
176 };
177 
178 using unique_fd = unique_fd_impl<DefaultCloser>;
179 
180 #if !defined(_WIN32)
181 
182 // Inline functions, so that they can be used header-only.
183 template <typename Closer>
184 inline bool Pipe(unique_fd_impl<Closer>* read, unique_fd_impl<Closer>* write,
185                  int flags = O_CLOEXEC) {
186   int pipefd[2];
187 
188 #if defined(__linux__)
189   if (pipe2(pipefd, flags) != 0) {
190     return false;
191   }
192 #else  // defined(__APPLE__)
193   if (flags & ~(O_CLOEXEC | O_NONBLOCK)) {
194     return false;
195   }
196   if (pipe(pipefd) != 0) {
197     return false;
198   }
199 
200   if (flags & O_CLOEXEC) {
201     if (fcntl(pipefd[0], F_SETFD, FD_CLOEXEC) != 0 || fcntl(pipefd[1], F_SETFD, FD_CLOEXEC) != 0) {
202       close(pipefd[0]);
203       close(pipefd[1]);
204       return false;
205     }
206   }
207   if (flags & O_NONBLOCK) {
208     if (fcntl(pipefd[0], F_SETFL, O_NONBLOCK) != 0 || fcntl(pipefd[1], F_SETFL, O_NONBLOCK) != 0) {
209       close(pipefd[0]);
210       close(pipefd[1]);
211       return false;
212     }
213   }
214 #endif
215 
216   read->reset(pipefd[0]);
217   write->reset(pipefd[1]);
218   return true;
219 }
220 
221 template <typename Closer>
Socketpair(int domain,int type,int protocol,unique_fd_impl<Closer> * left,unique_fd_impl<Closer> * right)222 inline bool Socketpair(int domain, int type, int protocol, unique_fd_impl<Closer>* left,
223                        unique_fd_impl<Closer>* right) {
224   int sockfd[2];
225   if (socketpair(domain, type, protocol, sockfd) != 0) {
226     return false;
227   }
228   left->reset(sockfd[0]);
229   right->reset(sockfd[1]);
230   return true;
231 }
232 
233 template <typename Closer>
Socketpair(int type,unique_fd_impl<Closer> * left,unique_fd_impl<Closer> * right)234 inline bool Socketpair(int type, unique_fd_impl<Closer>* left, unique_fd_impl<Closer>* right) {
235   return Socketpair(AF_UNIX, type, 0, left, right);
236 }
237 
238 // Using fdopen with unique_fd correctly is more annoying than it should be,
239 // because fdopen doesn't close the file descriptor received upon failure.
Fdopen(unique_fd && ufd,const char * mode)240 inline FILE* Fdopen(unique_fd&& ufd, const char* mode) {
241   int fd = ufd.release();
242   FILE* file = fdopen(fd, mode);
243   if (!file) {
244     close(fd);
245   }
246   return file;
247 }
248 
249 // Using fdopendir with unique_fd correctly is more annoying than it should be,
250 // because fdopen doesn't close the file descriptor received upon failure.
Fdopendir(unique_fd && ufd)251 inline DIR* Fdopendir(unique_fd&& ufd) {
252   int fd = ufd.release();
253   DIR* dir = fdopendir(fd);
254   if (dir == nullptr) {
255     close(fd);
256   }
257   return dir;
258 }
259 
260 #endif  // !defined(_WIN32)
261 
262 // A wrapper type that can be implicitly constructed from either int or unique_fd.
263 struct borrowed_fd {
borrowed_fdborrowed_fd264   /* implicit */ borrowed_fd(int fd) : fd_(fd) {}  // NOLINT
265   template <typename T>
borrowed_fdborrowed_fd266   /* implicit */ borrowed_fd(const unique_fd_impl<T>& ufd) : fd_(ufd.get()) {}  // NOLINT
267 
getborrowed_fd268   int get() const { return fd_; }
269 
270   bool operator>=(int rhs) const { return get() >= rhs; }
271   bool operator<(int rhs) const { return get() < rhs; }
272   bool operator==(int rhs) const { return get() == rhs; }
273   bool operator!=(int rhs) const { return get() != rhs; }
274 
275  private:
276   int fd_ = -1;
277 };
278 }  // namespace base
279 }  // namespace android
280 
281 template <typename T>
282 int close(const android::base::unique_fd_impl<T>&)
283     __attribute__((__unavailable__("close called on unique_fd")));
284 
285 template <typename T>
286 FILE* fdopen(const android::base::unique_fd_impl<T>&, const char* mode)
287     __attribute__((__unavailable__("fdopen takes ownership of the fd passed in; either dup the "
288                                    "unique_fd, or use android::base::Fdopen to pass ownership")));
289 
290 template <typename T>
291 DIR* fdopendir(const android::base::unique_fd_impl<T>&) __attribute__((
292     __unavailable__("fdopendir takes ownership of the fd passed in; either dup the "
293                     "unique_fd, or use android::base::Fdopendir to pass ownership")));
294