summaryrefslogtreecommitdiffstats
path: root/xpcom/build/PoisonIOInterposerBase.cpp
blob: 0a25a3d1f8173ddc3585dc4764e36e54425d185c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "mozilla/Maybe.h"
#include "mozilla/Mutex.h"
#include "mozilla/UniquePtr.h"

#include <algorithm>

#include "PoisonIOInterposer.h"

#include "prlock.h"

#ifdef MOZ_REPLACE_MALLOC
#  include "replace_malloc_bridge.h"
#endif

// Auxiliary method to convert file descriptors to ids
#if defined(XP_WIN)
#  include <io.h>
inline mozilla::Maybe<intptr_t> FileDescriptorToHandle(int aFd) {
  intptr_t handle = _get_osfhandle(aFd);
  if ((handle == -1) || (handle == -2)) {
    // -1: Invalid handle. -2: stdin/out/err not associated with a stream.
    return mozilla::Nothing();
  }
  return mozilla::Some(handle);
}
#else
inline mozilla::Maybe<intptr_t> FileDescriptorToHandle(int aFd) {
  return mozilla::Some<intptr_t>(aFd);
}
#endif /* if not XP_WIN */

namespace {

class DebugFilesAutoLock final {
 public:
  static PRLock* getDebugFileIDsLock() {
    static PRLock* sLock = PR_NewLock();
    return sLock;
  }

  DebugFilesAutoLock() { PR_Lock(getDebugFileIDsLock()); }

  ~DebugFilesAutoLock() { PR_Unlock(getDebugFileIDsLock()); }
};

// The ChunkedList<T> class implements, at the high level, a non-iterable
// list of instances of T. Its goal is to be somehow minimalist for the
// use case of storing the debug files handles here, with the property of
// not requiring a lock to look up whether it contains a specific value.
// It is also chunked in blocks of chunk_size bytes so that its
// initialization doesn't require a memory allocation, while keeping the
// possibility to increase its size as necessary. Note that chunks are
// never deallocated (except in the destructor).
// All operations are essentially O(N) but N is not expected to be large
// enough to matter.
template <typename T, size_t chunk_size = 64>
class ChunkedList {
  struct ListChunk {
    static const size_t kLength =
        (chunk_size - sizeof(ListChunk*)) / sizeof(mozilla::Atomic<T>);

    mozilla::Atomic<T> mElements[kLength];
    mozilla::UniquePtr<ListChunk> mNext;

    ListChunk() : mNext(nullptr) {}
  };

  ListChunk mList;
  mozilla::Atomic<size_t> mLength;

 public:
  ChunkedList() : mLength(0) {}

  ~ChunkedList() {
    // There can be writes happening after this destructor runs, so keep
    // the list contents and don't reset mLength. But if there are more
    // elements left than the first chunk can hold, then all hell breaks
    // loose for any write that would happen after that because any extra
    // chunk would be deallocated, so just crash in that case.
    MOZ_RELEASE_ASSERT(mLength <= ListChunk::kLength);
  }

  // Add an element at the end of the last chunk of the list. Create a new
  // chunk if there is not enough room.
  // This is not thread-safe with another thread calling Add or Remove.
  void Add(T aValue) {
    ListChunk* list = &mList;
    size_t position = mLength;
    for (; position >= ListChunk::kLength; position -= ListChunk::kLength) {
      if (!list->mNext) {
        list->mNext.reset(new ListChunk());
      }
      list = list->mNext.get();
    }
    // Use an order of operations that ensures any racing Contains call
    // can't be hurt.
    list->mElements[position] = aValue;
    mLength++;
  }

  // Remove an element from the list by replacing it with the last element
  // of the list, and then shrinking the list.
  // This is not thread-safe with another thread calling Add or Remove.
  void Remove(T aValue) {
    if (!mLength) {
      return;
    }
    ListChunk* list = &mList;
    size_t last = mLength - 1;
    do {
      size_t position = 0;
      // Look for an element matching the given value.
      for (; position < ListChunk::kLength; position++) {
        if (aValue == list->mElements[position]) {
          ListChunk* last_list = list;
          // Look for the last element in the list, starting from where we are
          // instead of starting over.
          for (; last >= ListChunk::kLength; last -= ListChunk::kLength) {
            last_list = last_list->mNext.get();
          }
          // Use an order of operations that ensures any racing Contains call
          // can't be hurt.
          T value = last_list->mElements[last];
          list->mElements[position] = value;
          mLength--;
          return;
        }
      }
      last -= ListChunk::kLength;
      list = list->mNext.get();
    } while (list);
  }

  // Returns whether the list contains the given value. It is meant to be safe
  // to use without locking, with the tradeoff of being not entirely accurate
  // if another thread adds or removes an element while this function runs.
  bool Contains(T aValue) {
    ListChunk* list = &mList;
    // Fix the range of the lookup to whatever the list length is when the
    // function is called.
    size_t length = mLength;
    do {
      size_t list_length = ListChunk::kLength;
      list_length = std::min(list_length, length);
      for (size_t position = 0; position < list_length; position++) {
        if (aValue == list->mElements[position]) {
          return true;
        }
      }
      length -= ListChunk::kLength;
      list = list->mNext.get();
    } while (list);

    return false;
  }
};

typedef ChunkedList<intptr_t> FdList;

// Return a list used to hold the IDs of the current debug files. On unix
// an ID is a file descriptor. On Windows it is a file HANDLE.
FdList& getDebugFileIDs() {
  static FdList DebugFileIDs;
  return DebugFileIDs;
}

}  // namespace

namespace mozilla {

// Auxiliary Method to test if a file descriptor is registered to be ignored
// by the poisoning IO interposer
bool IsDebugFile(intptr_t aFileID) {
  return getDebugFileIDs().Contains(aFileID);
}

}  // namespace mozilla

extern "C" {

void MozillaRegisterDebugHandle(intptr_t aHandle) {
  DebugFilesAutoLock lockedScope;
  FdList& DebugFileIDs = getDebugFileIDs();
  MOZ_ASSERT(!DebugFileIDs.Contains(aHandle));
  DebugFileIDs.Add(aHandle);
}

void MozillaRegisterDebugFD(int aFd) {
  mozilla::Maybe<intptr_t> handle = FileDescriptorToHandle(aFd);
  if (!handle.isSome()) {
    return;
  }
  MozillaRegisterDebugHandle(handle.value());
}

void MozillaRegisterDebugFILE(FILE* aFile) {
  int fd = fileno(aFile);
  if (fd == 1 || fd == 2) {
    return;
  }
  MozillaRegisterDebugFD(fd);
}

void MozillaUnRegisterDebugHandle(intptr_t aHandle) {
  DebugFilesAutoLock lockedScope;
  FdList& DebugFileIDs = getDebugFileIDs();
  MOZ_ASSERT(DebugFileIDs.Contains(aHandle));
  DebugFileIDs.Remove(aHandle);
}

void MozillaUnRegisterDebugFD(int aFd) {
  mozilla::Maybe<intptr_t> handle = FileDescriptorToHandle(aFd);
  if (!handle.isSome()) {
    return;
  }
  MozillaUnRegisterDebugHandle(handle.value());
}

void MozillaUnRegisterDebugFILE(FILE* aFile) {
  int fd = fileno(aFile);
  if (fd == 1 || fd == 2) {
    return;
  }
  fflush(aFile);
  MozillaUnRegisterDebugFD(fd);
}

}  // extern "C"

#ifdef MOZ_REPLACE_MALLOC
void mozilla::DebugFdRegistry::RegisterHandle(intptr_t aHandle) {
  MozillaRegisterDebugHandle(aHandle);
}

void mozilla::DebugFdRegistry::UnRegisterHandle(intptr_t aHandle) {
  MozillaUnRegisterDebugHandle(aHandle);
}
#endif