summaryrefslogtreecommitdiffstats
path: root/js/src/ds/LifoAlloc.cpp
blob: dc0b172b65e013e47ef889b31401a0b892d765d5 (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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
/* -*- 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 "ds/LifoAlloc.h"

#include "mozilla/Likely.h"
#include "mozilla/MathAlgorithms.h"

#include <algorithm>

#include "ds/MemoryProtectionExceptionHandler.h"

#ifdef LIFO_CHUNK_PROTECT
#  include "gc/Memory.h"
#endif

using namespace js;

using mozilla::RoundUpPow2;
using mozilla::tl::BitSize;

namespace js {
namespace detail {

/* static */
UniquePtr<BumpChunk> BumpChunk::newWithCapacity(size_t size) {
  MOZ_DIAGNOSTIC_ASSERT(size >= sizeof(BumpChunk));
  void* mem = js_malloc(size);
  if (!mem) {
    return nullptr;
  }

  UniquePtr<BumpChunk> result(new (mem) BumpChunk(size));

  // We assume that the alignment of LIFO_ALLOC_ALIGN is less than that of the
  // underlying memory allocator -- creating a new BumpChunk should always
  // satisfy the LIFO_ALLOC_ALIGN alignment constraint.
  MOZ_ASSERT(AlignPtr(result->begin()) == result->begin());
  return result;
}

#ifdef LIFO_CHUNK_PROTECT

static uint8_t* AlignPtrUp(uint8_t* ptr, uintptr_t align) {
  MOZ_ASSERT(mozilla::IsPowerOfTwo(align));
  uintptr_t uptr = uintptr_t(ptr);
  uintptr_t diff = uptr & (align - 1);
  diff = (align - diff) & (align - 1);
  uptr = uptr + diff;
  return (uint8_t*)uptr;
}

static uint8_t* AlignPtrDown(uint8_t* ptr, uintptr_t align) {
  MOZ_ASSERT(mozilla::IsPowerOfTwo(align));
  uintptr_t uptr = uintptr_t(ptr);
  uptr = uptr & ~(align - 1);
  return (uint8_t*)uptr;
}

void BumpChunk::setReadOnly() {
  uintptr_t pageSize = gc::SystemPageSize();
  // The allocated chunks might not be aligned on page boundaries. This code
  // is used to ensure that we are changing the memory protection of pointers
  // which are within the range of the BumpChunk, or that the range formed by
  // [b .. e] is empty.
  uint8_t* b = base();
  uint8_t* e = capacity_;
  b = AlignPtrUp(b, pageSize);
  e = AlignPtrDown(e, pageSize);
  if (e <= b) {
    return;
  }
  js::MemoryProtectionExceptionHandler::addRegion(base(), capacity_ - base());
  gc::MakePagesReadOnly(b, e - b);
}

void BumpChunk::setReadWrite() {
  uintptr_t pageSize = gc::SystemPageSize();
  // The allocated chunks might not be aligned on page boundaries. This code
  // is used to ensure that we are changing the memory protection of pointers
  // which are within the range of the BumpChunk, or that the range formed by
  // [b .. e] is empty.
  uint8_t* b = base();
  uint8_t* e = capacity_;
  b = AlignPtrUp(b, pageSize);
  e = AlignPtrDown(e, pageSize);
  if (e <= b) {
    return;
  }
  gc::UnprotectPages(b, e - b);
  js::MemoryProtectionExceptionHandler::removeRegion(base());
}

#endif

}  // namespace detail
}  // namespace js

void LifoAlloc::reset(size_t defaultChunkSize) {
  MOZ_ASSERT(mozilla::IsPowerOfTwo(defaultChunkSize));

  while (!chunks_.empty()) {
    chunks_.popFirst();
  }
  while (!oversize_.empty()) {
    oversize_.popFirst();
  }
  while (!unused_.empty()) {
    unused_.popFirst();
  }
  defaultChunkSize_ = defaultChunkSize;
  oversizeThreshold_ = defaultChunkSize;
  markCount = 0;
  curSize_ = 0;
  smallAllocsSize_ = 0;
}

void LifoAlloc::freeAll() {
  // When free-ing all chunks, we can no longer determine which chunks were
  // transferred and which were not, so simply clear the heuristic to zero
  // right away.
  smallAllocsSize_ = 0;

  while (!chunks_.empty()) {
    UniqueBumpChunk bc = chunks_.popFirst();
    decrementCurSize(bc->computedSizeOfIncludingThis());
  }
  while (!oversize_.empty()) {
    UniqueBumpChunk bc = oversize_.popFirst();
    decrementCurSize(bc->computedSizeOfIncludingThis());
  }
  while (!unused_.empty()) {
    UniqueBumpChunk bc = unused_.popFirst();
    decrementCurSize(bc->computedSizeOfIncludingThis());
  }

  // Nb: maintaining curSize_ correctly isn't easy.  Fortunately, this is an
  // excellent sanity check.
  MOZ_ASSERT(curSize_ == 0);
}

// Round at the same page granularity used by malloc.
static size_t MallocGoodSize(size_t aSize) {
#if defined(MOZ_MEMORY)
  return malloc_good_size(aSize);
#else
  return aSize;
#endif
}

// Heuristic to choose the size of the next BumpChunk for small allocations.
// `start` is the size of the first chunk. `used` is the total size of all
// BumpChunks in this LifoAlloc so far.
static size_t NextSize(size_t start, size_t used) {
  // Double the size, up to 1 MB.
  const size_t mb = 1 * 1024 * 1024;
  if (used < mb) {
    return std::max(start, used);
  }

  // After 1 MB, grow more gradually, to waste less memory.
  // The sequence (in megabytes) begins:
  // 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5, ...
  return RoundUp(used / 8, mb);
}

LifoAlloc::UniqueBumpChunk LifoAlloc::newChunkWithCapacity(size_t n,
                                                           bool oversize) {
  MOZ_ASSERT(fallibleScope_,
             "[OOM] Cannot allocate a new chunk in an infallible scope.");

  // Compute the size which should be requested in order to be able to fit |n|
  // bytes in a newly allocated chunk, or default to |defaultChunkSize_|.

  size_t minSize;
  if (MOZ_UNLIKELY(!detail::BumpChunk::allocSizeWithRedZone(n, &minSize) ||
                   (minSize & (size_t(1) << (BitSize<size_t>::value - 1))))) {
    return nullptr;
  }

  // Note: When computing chunkSize growth, we only are interested in chunks
  // used for small allocations. This excludes unused chunks, oversized chunks,
  // and chunks transferred in from another LifoAlloc.
  MOZ_ASSERT(curSize_ >= smallAllocsSize_);
  const size_t chunkSize = (oversize || minSize > defaultChunkSize_)
                               ? MallocGoodSize(minSize)
                               : NextSize(defaultChunkSize_, smallAllocsSize_);

  // Create a new BumpChunk, and allocate space for it.
  UniqueBumpChunk result = detail::BumpChunk::newWithCapacity(chunkSize);
  if (!result) {
    return nullptr;
  }
  MOZ_ASSERT(result->computedSizeOfIncludingThis() == chunkSize);
  return result;
}

LifoAlloc::UniqueBumpChunk LifoAlloc::getOrCreateChunk(size_t n) {
  // Look for existing unused BumpChunks to satisfy the request, and pick the
  // first one which is large enough, and move it into the list of used
  // chunks.
  if (!unused_.empty()) {
    if (unused_.begin()->canAlloc(n)) {
      return unused_.popFirst();
    }

    BumpChunkList::Iterator e(unused_.end());
    for (BumpChunkList::Iterator i(unused_.begin()); i->next() != e.get();
         ++i) {
      detail::BumpChunk* elem = i->next();
      MOZ_ASSERT(elem->empty());
      if (elem->canAlloc(n)) {
        BumpChunkList temp = unused_.splitAfter(i.get());
        UniqueBumpChunk newChunk = temp.popFirst();
        unused_.appendAll(std::move(temp));
        return newChunk;
      }
    }
  }

  // Allocate a new BumpChunk with enough space for the next allocation.
  UniqueBumpChunk newChunk = newChunkWithCapacity(n, false);
  if (!newChunk) {
    return newChunk;
  }
  incrementCurSize(newChunk->computedSizeOfIncludingThis());
  return newChunk;
}

void* LifoAlloc::allocImplColdPath(size_t n) {
  void* result;
  UniqueBumpChunk newChunk = getOrCreateChunk(n);
  if (!newChunk) {
    return nullptr;
  }

  // This new chunk is about to be used for small allocations.
  smallAllocsSize_ += newChunk->computedSizeOfIncludingThis();

  // Since we just created a large enough chunk, this can't fail.
  chunks_.append(std::move(newChunk));
  result = chunks_.last()->tryAlloc(n);
  MOZ_ASSERT(result);
  return result;
}

void* LifoAlloc::allocImplOversize(size_t n) {
  void* result;
  UniqueBumpChunk newChunk = newChunkWithCapacity(n, true);
  if (!newChunk) {
    return nullptr;
  }
  incrementCurSize(newChunk->computedSizeOfIncludingThis());

  // Since we just created a large enough chunk, this can't fail.
  oversize_.append(std::move(newChunk));
  result = oversize_.last()->tryAlloc(n);
  MOZ_ASSERT(result);
  return result;
}

bool LifoAlloc::ensureUnusedApproximateColdPath(size_t n, size_t total) {
  for (detail::BumpChunk& bc : unused_) {
    total += bc.unused();
    if (total >= n) {
      return true;
    }
  }

  UniqueBumpChunk newChunk = newChunkWithCapacity(n, false);
  if (!newChunk) {
    return false;
  }
  incrementCurSize(newChunk->computedSizeOfIncludingThis());
  unused_.pushFront(std::move(newChunk));
  return true;
}

LifoAlloc::Mark LifoAlloc::mark() {
  markCount++;
  Mark res;
  if (!chunks_.empty()) {
    res.chunk = chunks_.last()->mark();
  }
  if (!oversize_.empty()) {
    res.oversize = oversize_.last()->mark();
  }
  return res;
}

void LifoAlloc::release(Mark mark) {
  markCount--;
#ifdef DEBUG
  auto assertIsContained = [](const detail::BumpChunk::Mark& m,
                              BumpChunkList& list) {
    if (m.markedChunk()) {
      bool contained = false;
      for (const detail::BumpChunk& chunk : list) {
        if (&chunk == m.markedChunk() && chunk.contains(m)) {
          contained = true;
          break;
        }
      }
      MOZ_ASSERT(contained);
    }
  };
  assertIsContained(mark.chunk, chunks_);
  assertIsContained(mark.oversize, oversize_);
#endif

  BumpChunkList released;
  auto cutAtMark = [&released](const detail::BumpChunk::Mark& m,
                               BumpChunkList& list) {
    // Move the blocks which are after the mark to the set released chunks.
    if (!m.markedChunk()) {
      released = std::move(list);
    } else {
      released = list.splitAfter(m.markedChunk());
    }

    // Release everything which follows the mark in the last chunk.
    if (!list.empty()) {
      list.last()->release(m);
    }
  };

  // Release the content of all the blocks which are after the marks, and keep
  // blocks as unused.
  cutAtMark(mark.chunk, chunks_);
  for (detail::BumpChunk& bc : released) {
    bc.release();

    // Chunks moved from (after a mark) in chunks_ to unused_ are no longer
    // considered small allocations.
    smallAllocsSize_ -= bc.computedSizeOfIncludingThis();
  }
  unused_.appendAll(std::move(released));

  // Free the content of all the blocks which are after the marks.
  cutAtMark(mark.oversize, oversize_);
  while (!released.empty()) {
    UniqueBumpChunk bc = released.popFirst();
    decrementCurSize(bc->computedSizeOfIncludingThis());
  }
}

void LifoAlloc::steal(LifoAlloc* other) {
  MOZ_ASSERT(!other->markCount);
  MOZ_DIAGNOSTIC_ASSERT(unused_.empty());
  MOZ_DIAGNOSTIC_ASSERT(chunks_.empty());
  MOZ_DIAGNOSTIC_ASSERT(oversize_.empty());

  // Copy everything from |other| to |this| except for |peakSize_|, which
  // requires some care.
  chunks_ = std::move(other->chunks_);
  oversize_ = std::move(other->oversize_);
  unused_ = std::move(other->unused_);
  markCount = other->markCount;
  defaultChunkSize_ = other->defaultChunkSize_;
  oversizeThreshold_ = other->oversizeThreshold_;
  curSize_ = other->curSize_;
  peakSize_ = std::max(peakSize_, other->peakSize_);
  smallAllocsSize_ = other->smallAllocsSize_;
#if defined(DEBUG) || defined(JS_OOM_BREAKPOINT)
  fallibleScope_ = other->fallibleScope_;
#endif

  other->reset(defaultChunkSize_);
}

void LifoAlloc::transferFrom(LifoAlloc* other) {
  MOZ_ASSERT(!markCount);
  MOZ_ASSERT(!other->markCount);

  // Transferred chunks are not counted as part of |smallAllocsSize| as this
  // could introduce bias in the |NextSize| heuristics, leading to
  // over-allocations in *this* LifoAlloc. As well, to avoid interference with
  // small allocations made with |this|, the last chunk of the |chunks_| list
  // should remain the last chunk. Therefore, the transferred chunks are
  // prepended to the |chunks_| list.
  incrementCurSize(other->curSize_);

  appendUnused(std::move(other->unused_));
  chunks_.prependAll(std::move(other->chunks_));
  oversize_.prependAll(std::move(other->oversize_));
  other->curSize_ = 0;
  other->smallAllocsSize_ = 0;
}

void LifoAlloc::transferUnusedFrom(LifoAlloc* other) {
  MOZ_ASSERT(!markCount);

  size_t size = 0;
  for (detail::BumpChunk& bc : other->unused_) {
    size += bc.computedSizeOfIncludingThis();
  }

  appendUnused(std::move(other->unused_));
  incrementCurSize(size);
  other->decrementCurSize(size);
}

#ifdef LIFO_CHUNK_PROTECT
void LifoAlloc::setReadOnly() {
  for (detail::BumpChunk& bc : chunks_) {
    bc.setReadOnly();
  }
  for (detail::BumpChunk& bc : oversize_) {
    bc.setReadOnly();
  }
  for (detail::BumpChunk& bc : unused_) {
    bc.setReadOnly();
  }
}

void LifoAlloc::setReadWrite() {
  for (detail::BumpChunk& bc : chunks_) {
    bc.setReadWrite();
  }
  for (detail::BumpChunk& bc : oversize_) {
    bc.setReadWrite();
  }
  for (detail::BumpChunk& bc : unused_) {
    bc.setReadWrite();
  }
}
#endif