file_descriptor_store.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2017 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_FILE_DESCRIPTOR_STORE_H_
  5. #define BASE_FILE_DESCRIPTOR_STORE_H_
  6. #include <map>
  7. #include <string>
  8. #include "base/files/memory_mapped_file.h"
  9. #include "base/files/scoped_file.h"
  10. namespace base {
  11. // The file descriptor store is used to associate file descriptors with keys
  12. // that must be unique.
  13. // It is used to share file descriptors from a process to its child.
  14. class BASE_EXPORT FileDescriptorStore {
  15. public:
  16. FileDescriptorStore(const FileDescriptorStore&) = delete;
  17. FileDescriptorStore& operator=(const FileDescriptorStore&) = delete;
  18. struct Descriptor {
  19. Descriptor(const std::string& key, base::ScopedFD fd);
  20. Descriptor(const std::string& key,
  21. base::ScopedFD fd,
  22. base::MemoryMappedFile::Region region);
  23. Descriptor(Descriptor&& other);
  24. ~Descriptor();
  25. Descriptor& operator=(Descriptor&& other) = default;
  26. // Globally unique key.
  27. std::string key;
  28. // Actual FD.
  29. base::ScopedFD fd;
  30. // Optional region, defaults to kWholeFile.
  31. base::MemoryMappedFile::Region region;
  32. };
  33. using Mapping = std::map<std::string, Descriptor>;
  34. // Returns the singleton instance of FileDescriptorStore.
  35. static FileDescriptorStore& GetInstance();
  36. // Gets a descriptor given a key and also populates |region|.
  37. // It is a fatal error if the key is not known.
  38. base::ScopedFD TakeFD(const std::string& key,
  39. base::MemoryMappedFile::Region* region);
  40. // Gets a descriptor given a key. Returns an empty ScopedFD on error.
  41. base::ScopedFD MaybeTakeFD(const std::string& key,
  42. base::MemoryMappedFile::Region* region);
  43. // Sets the descriptor for the given |key|. This sets the region associated
  44. // with |key| to kWholeFile.
  45. void Set(const std::string& key, base::ScopedFD fd);
  46. // Sets the descriptor and |region| for the given |key|.
  47. void Set(const std::string& key,
  48. base::ScopedFD fd,
  49. base::MemoryMappedFile::Region region);
  50. private:
  51. FileDescriptorStore();
  52. ~FileDescriptorStore();
  53. Mapping descriptors_;
  54. };
  55. } // namespace base
  56. #endif // BASE_FILE_DESCRIPTOR_STORE_H_