FileDescriptorShuffle.h (2353B)
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */ 3 /* This Source Code Form is subject to the terms of the Mozilla Public 4 * License, v. 2.0. If a copy of the MPL was not distributed with this 5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 #ifndef mozilla_ipc_FileDescriptorShuffle_h 8 #define mozilla_ipc_FileDescriptorShuffle_h 9 10 #include "mozilla/Span.h" 11 #include "nsTArray.h" 12 13 #include <functional> 14 #include <utility> 15 16 // This class converts a set of file descriptor mapping, which may 17 // contain conflicts (like {a->b, b->c} or {a->b, b->a}) into a 18 // sequence of dup2() operations that can be performed between fork 19 // and exec, or with posix_spawn_file_actions_adddup2. It may create 20 // temporary duplicates of fds to use as the source of a dup2; they 21 // are closed on destruction. 22 // 23 // The dup2 sequence is guaranteed to not contain dup2(x, x) for any 24 // x; if such an element is present in the input, it will be dup2()ed 25 // from a temporary fd to ensure that the close-on-exec bit is cleared. 26 // 27 // In general, this is *not* guaranteed to minimize the use of 28 // temporary fds. 29 30 namespace mozilla { 31 namespace ipc { 32 33 class FileDescriptorShuffle { 34 public: 35 FileDescriptorShuffle() = default; 36 ~FileDescriptorShuffle(); 37 38 using MappingRef = mozilla::Span<const std::pair<int, int>>; 39 40 // Translate the given mapping, creating temporary fds as needed. 41 // Can fail (return false) on failure to duplicate fds. 42 bool Init(MappingRef aMapping); 43 44 // Accessor for the dup2() sequence. Do not use the returned value 45 // or the fds contained in it after this object is destroyed. 46 MappingRef Dup2Sequence() const { return mMapping; } 47 48 // Tests whether the given fd is used as a destination in this mapping. 49 // Can be used to close other fds after performing the dup2()s. 50 bool MapsTo(int aFd) const; 51 52 // Forget the information, so that it's destructor will not try to 53 // delete FDs duped by itself. 54 void Forget() { mTempFds.Clear(); } 55 56 private: 57 nsTArray<std::pair<int, int>> mMapping; 58 nsTArray<int> mTempFds; 59 int mMaxDst; 60 61 FileDescriptorShuffle(const FileDescriptorShuffle&) = delete; 62 void operator=(const FileDescriptorShuffle&) = delete; 63 }; 64 65 } // namespace ipc 66 } // namespace mozilla 67 68 #endif // mozilla_ipc_FileDescriptorShuffle_h