WebKit Roll 61390:61491.
[chromium-blink-merge.git] / base / file_descriptor_shuffle.cc
blob2bb156bf3c7d5005cd55242744f6e5e0d5f0e38e
1 // Copyright (c) 2009 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 #include "base/file_descriptor_shuffle.h"
7 #include <errno.h>
8 #include <unistd.h>
10 #include "base/eintr_wrapper.h"
11 #include "base/logging.h"
13 namespace base {
15 bool PerformInjectiveMultimapDestructive(
16 InjectiveMultimap* m, InjectionDelegate* delegate) {
17 static const size_t kMaxExtraFDs = 16;
18 int extra_fds[kMaxExtraFDs];
19 unsigned next_extra_fd = 0;
21 // DANGER: this function may not allocate.
23 for (InjectiveMultimap::iterator i = m->begin(); i != m->end(); ++i) {
24 int temp_fd = -1;
26 // We DCHECK the injectiveness of the mapping.
27 for (InjectiveMultimap::iterator j = i + 1; j != m->end(); ++j) {
28 DCHECK(i->dest != j->dest) << "Both fd " << i->source
29 << " and " << j->source << " map to " << i->dest;
32 const bool is_identity = i->source == i->dest;
34 for (InjectiveMultimap::iterator j = i + 1; j != m->end(); ++j) {
35 if (!is_identity && i->dest == j->source) {
36 if (temp_fd == -1) {
37 if (!delegate->Duplicate(&temp_fd, i->dest))
38 return false;
39 if (next_extra_fd < kMaxExtraFDs) {
40 extra_fds[next_extra_fd++] = temp_fd;
41 } else {
42 RAW_LOG(ERROR, "PerformInjectiveMultimapDestructive overflowed "
43 "extra_fds. Leaking file descriptors!");
47 j->source = temp_fd;
48 j->close = false;
51 if (i->close && i->source == j->dest)
52 i->close = false;
54 if (i->close && i->source == j->source) {
55 i->close = false;
56 j->close = true;
60 if (!is_identity) {
61 if (!delegate->Move(i->source, i->dest))
62 return false;
65 if (!is_identity && i->close)
66 delegate->Close(i->source);
69 for (unsigned i = 0; i < next_extra_fd; i++)
70 delegate->Close(extra_fds[i]);
72 return true;
75 bool PerformInjectiveMultimap(const InjectiveMultimap& m_in,
76 InjectionDelegate* delegate) {
77 InjectiveMultimap m(m_in);
78 return PerformInjectiveMultimapDestructive(&m, delegate);
81 bool FileDescriptorTableInjection::Duplicate(int* result, int fd) {
82 *result = HANDLE_EINTR(dup(fd));
83 return *result >= 0;
86 bool FileDescriptorTableInjection::Move(int src, int dest) {
87 return HANDLE_EINTR(dup2(src, dest)) != -1;
90 void FileDescriptorTableInjection::Close(int fd) {
91 int ret = HANDLE_EINTR(close(fd));
92 DPCHECK(ret == 0);
95 } // namespace base