blob: d81e2d7b5ad810ca34d66ae547ed64e1bba7a605 [file] [log] [blame]
Avi Drissmane4622aa2022-09-08 20:36:061// Copyright 2017 The Chromium Authors
jcivellidad0cef2017-02-16 18:38:592// 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
David Sanders6e709942022-04-05 06:49:2611#include "base/base_export.h"
jcivellidad0cef2017-02-16 18:38:5912#include "base/files/memory_mapped_file.h"
13#include "base/files/scoped_file.h"
jcivellidad0cef2017-02-16 18:38:5914
15namespace 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.
20class BASE_EXPORT FileDescriptorStore {
21 public:
David Bienvenub4b441e2020-09-23 05:49:5722 FileDescriptorStore(const FileDescriptorStore&) = delete;
23 FileDescriptorStore& operator=(const FileDescriptorStore&) = delete;
jcivellidad0cef2017-02-16 18:38:5924 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_;
jcivellidad0cef2017-02-16 18:38:5969};
70
71} // namespace base
72
73#endif // BASE_FILE_DESCRIPTOR_STORE_H_