file_descriptor_store.h 2.3 KB

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