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