1 // Copyright (c) 2011 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.
5 #ifndef BASE_FILE_DESCRIPTOR_SHUFFLE_H_
6 #define BASE_FILE_DESCRIPTOR_SHUFFLE_H_
9 // This code exists to perform the shuffling of file descriptors which is
10 // commonly needed when forking subprocesses. The naive approve is very simple,
11 // just call dup2 to setup the desired descriptors, but wrong. It's tough to
12 // handle the edge cases (like mapping 0 -> 1, 1 -> 0) correctly.
14 // In order to unittest this code, it's broken into the abstract action (an
15 // injective multimap) and the concrete code for dealing with file descriptors.
16 // Users should use the code like this:
17 // base::InjectiveMultimap file_descriptor_map;
18 // file_descriptor_map.push_back(base::InjectionArc(devnull, 0, true));
19 // file_descriptor_map.push_back(base::InjectionArc(devnull, 2, true));
20 // file_descriptor_map.push_back(base::InjectionArc(pipe[1], 1, true));
21 // base::ShuffleFileDescriptors(file_descriptor_map);
23 // and trust the the Right Thing will get done.
27 #include "base/base_export.h"
28 #include "base/compiler_specific.h"
32 // A Delegate which performs the actions required to perform an injective
33 // multimapping in place.
34 class InjectionDelegate
{
36 // Duplicate |fd|, an element of the domain, and write a fresh element of the
37 // domain into |result|. Returns true iff successful.
38 virtual bool Duplicate(int* result
, int fd
) = 0;
39 // Destructively move |src| to |dest|, overwriting |dest|. Returns true iff
41 virtual bool Move(int src
, int dest
) = 0;
42 // Delete an element of the domain.
43 virtual void Close(int fd
) = 0;
46 virtual ~InjectionDelegate() {}
49 // An implementation of the InjectionDelegate interface using the file
50 // descriptor table of the current process as the domain.
51 class FileDescriptorTableInjection
: public InjectionDelegate
{
52 virtual bool Duplicate(int* result
, int fd
) OVERRIDE
;
53 virtual bool Move(int src
, int dest
) OVERRIDE
;
54 virtual void Close(int fd
) OVERRIDE
;
57 // A single arc of the directed graph which describes an injective multimapping.
59 InjectionArc(int in_source
, int in_dest
, bool in_close
)
67 bool close
; // if true, delete the source element after performing the
71 typedef std::vector
<InjectionArc
> InjectiveMultimap
;
73 BASE_EXPORT
bool PerformInjectiveMultimap(const InjectiveMultimap
& map
,
74 InjectionDelegate
* delegate
);
76 BASE_EXPORT
bool PerformInjectiveMultimapDestructive(
77 InjectiveMultimap
* map
,
78 InjectionDelegate
* delegate
);
80 // This function will not call malloc but will mutate |map|
81 static inline bool ShuffleFileDescriptors(InjectiveMultimap
* map
) {
82 FileDescriptorTableInjection delegate
;
83 return PerformInjectiveMultimapDestructive(map
, &delegate
);
88 #endif // BASE_FILE_DESCRIPTOR_SHUFFLE_H_