• 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 #include <stdio.h>
24 #include <sys/types.h>
25 #include <unistd.h>
26 
27 // DO NOT INCLUDE OTHER LIBBASE HEADERS HERE!
28 // This file gets used in libbinder, and libbinder is used everywhere.
29 // Including other headers from libbase frequently results in inclusion of
30 // android-base/macros.h, which causes macro collisions.
31 
32 #if defined(__BIONIC__)
33 #include <android/fdsan.h>
34 #endif
35 #if !defined(_WIN32) && !defined(__TRUSTY__)
36 #include <sys/socket.h>
37 #endif
38 
39 namespace android {
40 namespace base {
41 
42 // Container for a file descriptor that automatically closes the descriptor as
43 // it goes out of scope.
44 //
45 //      unique_fd ufd(open("/some/path", "r"));
46 //      if (ufd.get() == -1) return error;
47 //
48 //      // Do something useful, possibly including 'return'.
49 //
50 //      return 0; // Descriptor is closed for you.
51 //
52 // See also the Pipe()/Socketpair()/Fdopen()/Fdopendir() functions in this file
53 // that provide interoperability with the libc functions with the same (but
54 // lowercase) names.
55 //
56 // unique_fd is also known as ScopedFd/ScopedFD/scoped_fd; mentioned here to help
57 // you find this class if you're searching for one of those names.
58 //
59 // unique_fd itself is a specialization of unique_fd_impl with a default closer.
60 template <typename Closer>
61 class unique_fd_impl final {
62  public:
unique_fd_impl()63   unique_fd_impl() {}
64 
unique_fd_impl(int fd)65   explicit unique_fd_impl(int fd) { reset(fd); }
~unique_fd_impl()66   ~unique_fd_impl() { reset(); }
67 
68   unique_fd_impl(const unique_fd_impl&) = delete;
69   void operator=(const unique_fd_impl&) = delete;
unique_fd_impl(unique_fd_impl && other)70   unique_fd_impl(unique_fd_impl&& other) noexcept { reset(other.release()); }
71   unique_fd_impl& operator=(unique_fd_impl&& s) noexcept {
72     int fd = s.fd_;
73     s.fd_ = -1;
74     reset(fd, &s);
75     return *this;
76   }
77 
78   [[clang::reinitializes]] void reset(int new_value = -1) { reset(new_value, nullptr); }
79 
get()80   int get() const { return fd_; }
81 
82 #if !defined(ANDROID_BASE_UNIQUE_FD_DISABLE_IMPLICIT_CONVERSION)
83   // unique_fd's operator int is dangerous, but we have way too much code that
84   // depends on it, so make this opt-in at first.
85   operator int() const { return get(); }  // NOLINT
86 #endif
87 
88   bool operator>=(int rhs) const { return get() >= rhs; }
89   bool operator<(int rhs) const { return get() < rhs; }
90   bool operator==(int rhs) const { return get() == rhs; }
91   bool operator!=(int rhs) const { return get() != rhs; }
92   bool operator==(const unique_fd_impl& rhs) const { return get() == rhs.get(); }
93   bool operator!=(const unique_fd_impl& rhs) const { return get() != rhs.get(); }
94 
95   // Catch bogus error checks (i.e.: "!fd" instead of "fd != -1").
96   bool operator!() const = delete;
97 
ok()98   bool ok() const { return get() >= 0; }
99 
release()100   int release() __attribute__((warn_unused_result)) {
101     tag(fd_, this, nullptr);
102     int ret = fd_;
103     fd_ = -1;
104     return ret;
105   }
106 
107  private:
reset(int new_value,void * previous_tag)108   void reset(int new_value, void* previous_tag) {
109     int previous_errno = errno;
110 
111     if (fd_ != -1) {
112       close(fd_, this);
113     }
114 
115     fd_ = new_value;
116     if (new_value != -1) {
117       tag(new_value, previous_tag, this);
118     }
119 
120     errno = previous_errno;
121   }
122 
123   int fd_ = -1;
124 
125   // Template magic to use Closer::Tag if available, and do nothing if not.
126   // If Closer::Tag exists, this implementation is preferred, because int is a better match.
127   // If not, this implementation is SFINAEd away, and the no-op below is the only one that exists.
128   template <typename T = Closer>
129   static auto tag(int fd, void* old_tag, void* new_tag)
130       -> decltype(T::Tag(fd, old_tag, new_tag), void()) {
131     T::Tag(fd, old_tag, new_tag);
132   }
133 
134   template <typename T = Closer>
tag(long,void *,void *)135   static void tag(long, void*, void*) {
136     // No-op.
137   }
138 
139   // Same as above, to select between Closer::Close(int) and Closer::Close(int, void*).
140   template <typename T = Closer>
141   static auto close(int fd, void* tag_value) -> decltype(T::Close(fd, tag_value), void()) {
142     T::Close(fd, tag_value);
143   }
144 
145   template <typename T = Closer>
146   static auto close(int fd, void*) -> decltype(T::Close(fd), void()) {
147     T::Close(fd);
148   }
149 };
150 
151 // The actual details of closing are factored out to support unusual cases.
152 // Almost everyone will want this DefaultCloser, which handles fdsan on bionic.
153 struct DefaultCloser {
154 #if defined(__BIONIC__)
TagDefaultCloser155   static void Tag(int fd, void* old_addr, void* new_addr) {
156     if (android_fdsan_exchange_owner_tag) {
157       uint64_t old_tag = android_fdsan_create_owner_tag(ANDROID_FDSAN_OWNER_TYPE_UNIQUE_FD,
158                                                         reinterpret_cast<uint64_t>(old_addr));
159       uint64_t new_tag = android_fdsan_create_owner_tag(ANDROID_FDSAN_OWNER_TYPE_UNIQUE_FD,
160                                                         reinterpret_cast<uint64_t>(new_addr));
161       android_fdsan_exchange_owner_tag(fd, old_tag, new_tag);
162     }
163   }
CloseDefaultCloser164   static void Close(int fd, void* addr) {
165     if (android_fdsan_close_with_tag) {
166       uint64_t tag = android_fdsan_create_owner_tag(ANDROID_FDSAN_OWNER_TYPE_UNIQUE_FD,
167                                                     reinterpret_cast<uint64_t>(addr));
168       android_fdsan_close_with_tag(fd, tag);
169     } else {
170       close(fd);
171     }
172   }
173 #else
174   static void Close(int fd) {
175     // Even if close(2) fails with EINTR, the fd will have been closed.
176     // Using TEMP_FAILURE_RETRY will either lead to EBADF or closing someone
177     // else's fd.
178     // http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
179     ::close(fd);
180   }
181 #endif
182 };
183 
184 using unique_fd = unique_fd_impl<DefaultCloser>;
185 
186 #if !defined(_WIN32) && !defined(__TRUSTY__)
187 
188 // Inline functions, so that they can be used header-only.
189 
190 // See pipe(2).
191 // This helper hides the details of converting to unique_fd, and also hides the
192 // fact that macOS doesn't support O_CLOEXEC or O_NONBLOCK directly.
193 template <typename Closer>
194 inline bool Pipe(unique_fd_impl<Closer>* read, unique_fd_impl<Closer>* write,
195                  int flags = O_CLOEXEC) {
196   int pipefd[2];
197 
198 #if defined(__linux__)
199   if (pipe2(pipefd, flags) != 0) {
200     return false;
201   }
202 #else  // defined(__APPLE__)
203   if (flags & ~(O_CLOEXEC | O_NONBLOCK)) {
204     return false;
205   }
206   if (pipe(pipefd) != 0) {
207     return false;
208   }
209 
210   if (flags & O_CLOEXEC) {
211     if (fcntl(pipefd[0], F_SETFD, FD_CLOEXEC) != 0 || fcntl(pipefd[1], F_SETFD, FD_CLOEXEC) != 0) {
212       close(pipefd[0]);
213       close(pipefd[1]);
214       return false;
215     }
216   }
217   if (flags & O_NONBLOCK) {
218     if (fcntl(pipefd[0], F_SETFL, O_NONBLOCK) != 0 || fcntl(pipefd[1], F_SETFL, O_NONBLOCK) != 0) {
219       close(pipefd[0]);
220       close(pipefd[1]);
221       return false;
222     }
223   }
224 #endif
225 
226   read->reset(pipefd[0]);
227   write->reset(pipefd[1]);
228   return true;
229 }
230 
231 // See socketpair(2).
232 // This helper hides the details of converting to unique_fd.
233 template <typename Closer>
Socketpair(int domain,int type,int protocol,unique_fd_impl<Closer> * left,unique_fd_impl<Closer> * right)234 inline bool Socketpair(int domain, int type, int protocol, unique_fd_impl<Closer>* left,
235                        unique_fd_impl<Closer>* right) {
236   int sockfd[2];
237   if (socketpair(domain, type, protocol, sockfd) != 0) {
238     return false;
239   }
240   left->reset(sockfd[0]);
241   right->reset(sockfd[1]);
242   return true;
243 }
244 
245 // See socketpair(2).
246 // This helper hides the details of converting to unique_fd.
247 template <typename Closer>
Socketpair(int type,unique_fd_impl<Closer> * left,unique_fd_impl<Closer> * right)248 inline bool Socketpair(int type, unique_fd_impl<Closer>* left, unique_fd_impl<Closer>* right) {
249   return Socketpair(AF_UNIX, type, 0, left, right);
250 }
251 
252 // See fdopen(3).
253 // Using fdopen with unique_fd correctly is more annoying than it should be,
254 // because fdopen doesn't close the file descriptor received upon failure.
Fdopen(unique_fd && ufd,const char * mode)255 inline FILE* Fdopen(unique_fd&& ufd, const char* mode) {
256   int fd = ufd.release();
257   FILE* file = fdopen(fd, mode);
258   if (!file) {
259     close(fd);
260   }
261   return file;
262 }
263 
264 // See fdopendir(3).
265 // Using fdopendir with unique_fd correctly is more annoying than it should be,
266 // because fdopen doesn't close the file descriptor received upon failure.
Fdopendir(unique_fd && ufd)267 inline DIR* Fdopendir(unique_fd&& ufd) {
268   int fd = ufd.release();
269   DIR* dir = fdopendir(fd);
270   if (dir == nullptr) {
271     close(fd);
272   }
273   return dir;
274 }
275 
276 #endif  // !defined(_WIN32) && !defined(__TRUSTY__)
277 
278 // A wrapper type that can be implicitly constructed from either int or
279 // unique_fd. This supports cases where you don't actually own the file
280 // descriptor, and can't take ownership, but are temporarily acting as if
281 // you're the owner.
282 //
283 // One example would be a function that needs to also allow
284 // STDERR_FILENO, not just a newly-opened fd. Another example would be JNI code
285 // that's using a file descriptor that's actually owned by a
286 // ParcelFileDescriptor or whatever on the Java side, but where the JNI code
287 // would like to enforce this weaker sense of "temporary ownership".
288 //
289 // If you think of unique_fd as being like std::string in that represents
290 // ownership, borrowed_fd is like std::string_view (and int is like const
291 // char*).
292 struct borrowed_fd {
borrowed_fdborrowed_fd293   /* implicit */ borrowed_fd(int fd) : fd_(fd) {}  // NOLINT
294   template <typename T>
borrowed_fdborrowed_fd295   /* implicit */ borrowed_fd(const unique_fd_impl<T>& ufd) : fd_(ufd.get()) {}  // NOLINT
296 
getborrowed_fd297   int get() const { return fd_; }
298 
299   bool operator>=(int rhs) const { return get() >= rhs; }
300   bool operator<(int rhs) const { return get() < rhs; }
301   bool operator==(int rhs) const { return get() == rhs; }
302   bool operator!=(int rhs) const { return get() != rhs; }
303 
304  private:
305   int fd_ = -1;
306 };
307 }  // namespace base
308 }  // namespace android
309 
310 template <typename T>
311 int close(const android::base::unique_fd_impl<T>&)
312     __attribute__((__unavailable__("close called on unique_fd")));
313 
314 template <typename T>
315 FILE* fdopen(const android::base::unique_fd_impl<T>&, const char* mode)
316     __attribute__((__unavailable__("fdopen takes ownership of the fd passed in; either dup the "
317                                    "unique_fd, or use android::base::Fdopen to pass ownership")));
318 
319 template <typename T>
320 DIR* fdopendir(const android::base::unique_fd_impl<T>&) __attribute__((
321     __unavailable__("fdopendir takes ownership of the fd passed in; either dup the "
322                     "unique_fd, or use android::base::Fdopendir to pass ownership")));
323