Debian Codegraph @

js/src/jsapi-tests/testGCAllocator.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 */
4 /* This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7
8 #include "mozilla/MathAlgorithms.h"
9
10 #include <cstdlib>
11
12 #include "jsmath.h"
13
14 #include "gc/Allocator.h"
15 #include "gc/Memory.h"
16 #include "gc/Nursery.h"
17 #include "gc/Zone.h"
18 #include "jsapi-tests/tests.h"
19 #include "vm/PlainObject.h"
20
21 #if defined(XP_WIN)
22 # include "util/WindowsWrapper.h"
23 # include <psapi.h>
24 #elif defined(__wasi__)
25 // Nothing.
26 #else
27 # include <algorithm>
28 # include <errno.h>
29 # include <sys/mman.h>
30 # include <sys/resource.h>
31 # include <sys/stat.h>
32 # include <sys/types.h>
33 # include <unistd.h>
34 #endif
35
36 #include "gc/BufferAllocator-inl.h"
37 #include "gc/StoreBuffer-inl.h"
38 #include "vm/JSContext-inl.h"
39 #include "vm/JSObject-inl.h"
40
41 using namespace js;
42 using namespace js::gc;
43
44 BEGIN_TEST(testGCAllocator) {
45 #ifdef JS_64BIT
46 // If we're using the scattershot allocator, this test does not apply.
47 if (js::gc::UsingScattershotAllocator()) {
48 return true;
49 }
50 #endif
51
52 size_t PageSize = js::gc::SystemPageSize();
53
54 /* Finish any ongoing background free activity. */
55 js::gc::FinishGC(cx);
56
57 bool growUp = false;
58 CHECK(addressesGrowUp(&growUp));
59
60 if (growUp) {
61 return testGCAllocatorUp(PageSize);
62 } else {
63 return testGCAllocatorDown(PageSize);
64 }
65 }
66
67 static const size_t Chunk = 512 * 1024;
68 static const size_t Alignment = 2 * Chunk;
69 static const int MaxTempChunks = 4096;
70 static const size_t StagingSize = 16 * Chunk;
71
72 bool addressesGrowUp(bool* resultOut) {
73 /*
74 * Try to detect whether the OS allocates memory in increasing or decreasing
75 * address order by making several allocations and comparing the addresses.
76 */
77
78 static const unsigned ChunksToTest = 20;
79 static const int ThresholdCount = 15;
80
81 void* chunks[ChunksToTest];
82 for (unsigned i = 0; i < ChunksToTest; i++) {
83 chunks[i] = mapMemory(2 * Chunk);
84 CHECK(chunks[i]);
85 }
86
87 int upCount = 0;
88 int downCount = 0;
89
90 for (unsigned i = 0; i < ChunksToTest - 1; i++) {
91 if (chunks[i] < chunks[i + 1]) {
92 upCount++;
93 } else {
94 downCount++;
95 }
96 }
97
98 for (unsigned i = 0; i < ChunksToTest; i++) {
99 unmapPages(chunks[i], 2 * Chunk);
100 }
101
102 /* Check results were mostly consistent. */
103 CHECK(abs(upCount - downCount) >= ThresholdCount);
104
105 *resultOut = upCount > downCount;
106
107 return true;
108 }
109
110 size_t offsetFromAligned(void* p) { return uintptr_t(p) % Alignment; }
111
112 enum AllocType { UseNormalAllocator, UseLastDitchAllocator };
113
114 bool testGCAllocatorUp(const size_t PageSize) {
115 const size_t UnalignedSize = StagingSize + Alignment - PageSize;
116 void* chunkPool[MaxTempChunks];
117 // Allocate a contiguous chunk that we can partition for testing.
118 void* stagingArea = mapMemory(UnalignedSize);
119 if (!stagingArea) {
120 return false;
121 }
122 // Ensure that the staging area is aligned.
123 unmapPages(stagingArea, UnalignedSize);
124 if (offsetFromAligned(stagingArea)) {
125 const size_t Offset = offsetFromAligned(stagingArea);
126 // Place the area at the lowest aligned address.
127 stagingArea = (void*)(uintptr_t(stagingArea) + (Alignment - Offset));
128 }
129 mapMemoryAt(stagingArea, StagingSize);
130 // Make sure there are no available chunks below the staging area.
131 int tempChunks;
132 if (!fillSpaceBeforeStagingArea(tempChunks, stagingArea, chunkPool, false)) {
133 return false;
134 }
135 // Unmap the staging area so we can set it up for testing.
136 unmapPages(stagingArea, StagingSize);
137 // Check that the first chunk is used if it is aligned.
138 CHECK(positionIsCorrect("xxooxxx---------", stagingArea, chunkPool,
139 tempChunks));
140 // Check that the first chunk is used if it can be aligned.
141 CHECK(positionIsCorrect("x-ooxxx---------", stagingArea, chunkPool,
142 tempChunks));
143 // Check that an aligned chunk after a single unalignable chunk is used.
144 CHECK(positionIsCorrect("x--xooxxx-------", stagingArea, chunkPool,
145 tempChunks));
146 // Check that we fall back to the slow path after two unalignable chunks.
147 CHECK(positionIsCorrect("x--xx--xoo--xxx-", stagingArea, chunkPool,
148 tempChunks));
149 // Check that we also fall back after an unalignable and an alignable chunk.
150 CHECK(positionIsCorrect("x--xx---x-oo--x-", stagingArea, chunkPool,
151 tempChunks));
152 // Check that the last ditch allocator works as expected.
153 CHECK(positionIsCorrect("x--xx--xx-oox---", stagingArea, chunkPool,
154 tempChunks, UseLastDitchAllocator));
155 // Check that the last ditch allocator can deal with naturally aligned chunks.
156 CHECK(positionIsCorrect("x--xx--xoo------", stagingArea, chunkPool,
157 tempChunks, UseLastDitchAllocator));
158
159 // Clean up.
160 while (--tempChunks >= 0) {
161 unmapPages(chunkPool[tempChunks], 2 * Chunk);
162 }
163 return true;
164 }
165
166 bool testGCAllocatorDown(const size_t PageSize) {
167 const size_t UnalignedSize = StagingSize + Alignment - PageSize;
168 void* chunkPool[MaxTempChunks];
169 // Allocate a contiguous chunk that we can partition for testing.
170 void* stagingArea = mapMemory(UnalignedSize);
171 if (!stagingArea) {
172 return false;
173 }
174 // Ensure that the staging area is aligned.
175 unmapPages(stagingArea, UnalignedSize);
176 if (offsetFromAligned(stagingArea)) {
177 void* stagingEnd = (void*)(uintptr_t(stagingArea) + UnalignedSize);
178 const size_t Offset = offsetFromAligned(stagingEnd);
179 // Place the area at the highest aligned address.
180 stagingArea = (void*)(uintptr_t(stagingEnd) - Offset - StagingSize);
181 }
182 mapMemoryAt(stagingArea, StagingSize);
183 // Make sure there are no available chunks above the staging area.
184 int tempChunks;
185 if (!fillSpaceBeforeStagingArea(tempChunks, stagingArea, chunkPool, true)) {
186 return false;
187 }
188 // Unmap the staging area so we can set it up for testing.
189 unmapPages(stagingArea, StagingSize);
190 // Check that the first chunk is used if it is aligned.
191 CHECK(positionIsCorrect("---------xxxooxx", stagingArea, chunkPool,
192 tempChunks));
193 // Check that the first chunk is used if it can be aligned.
194 CHECK(positionIsCorrect("---------xxxoo-x", stagingArea, chunkPool,
195 tempChunks));
196 // Check that an aligned chunk after a single unalignable chunk is used.
197 CHECK(positionIsCorrect("-------xxxoox--x", stagingArea, chunkPool,
198 tempChunks));
199 // Check that we fall back to the slow path after two unalignable chunks.
200 CHECK(positionIsCorrect("-xxx--oox--xx--x", stagingArea, chunkPool,
201 tempChunks));
202 // Check that we also fall back after an unalignable and an alignable chunk.
203 CHECK(positionIsCorrect("-x--oo-x---xx--x", stagingArea, chunkPool,
204 tempChunks));
205 // Check that the last ditch allocator works as expected.
206 CHECK(positionIsCorrect("---xoo-xx--xx--x", stagingArea, chunkPool,
207 tempChunks, UseLastDitchAllocator));
208 // Check that the last ditch allocator can deal with naturally aligned chunks.
209 CHECK(positionIsCorrect("------oox--xx--x", stagingArea, chunkPool,
210 tempChunks, UseLastDitchAllocator));
211
212 // Clean up.
213 while (--tempChunks >= 0) {
214 unmapPages(chunkPool[tempChunks], 2 * Chunk);
215 }
216 return true;
217 }
218
219 bool fillSpaceBeforeStagingArea(int& tempChunks, void* stagingArea,
220 void** chunkPool, bool addressesGrowDown) {
221 // Make sure there are no available chunks before the staging area.
222 tempChunks = 0;
223 chunkPool[tempChunks++] = mapMemory(2 * Chunk);
224 while (tempChunks < MaxTempChunks && chunkPool[tempChunks - 1] &&
225 (chunkPool[tempChunks - 1] < stagingArea) ^ addressesGrowDown) {
226 chunkPool[tempChunks++] = mapMemory(2 * Chunk);
227 if (!chunkPool[tempChunks - 1]) {
228 break; // We already have our staging area, so OOM here is okay.
229 }
230 if ((chunkPool[tempChunks - 1] < chunkPool[tempChunks - 2]) ^
231 addressesGrowDown) {
232 break; // The address growth direction is inconsistent!
233 }
234 }
235 // OOM also means success in this case.
236 if (!chunkPool[tempChunks - 1]) {
237 --tempChunks;
238 return true;
239 }
240 // Bail if we can't guarantee the right address space layout.
241 if ((chunkPool[tempChunks - 1] < stagingArea) ^ addressesGrowDown ||
242 (tempChunks > 1 &&
243 (chunkPool[tempChunks - 1] < chunkPool[tempChunks - 2]) ^
244 addressesGrowDown)) {
245 while (--tempChunks >= 0) {
246 unmapPages(chunkPool[tempChunks], 2 * Chunk);
247 }
248 unmapPages(stagingArea, StagingSize);
249 return false;
250 }
251 return true;
252 }
253
254 bool positionIsCorrect(const char* str, void* base, void** chunkPool,
255 int tempChunks,
256 AllocType allocator = UseNormalAllocator) {
257 // str represents a region of memory, with each character representing a
258 // region of Chunk bytes. str should contain only x, o and -, where
259 // x = mapped by the test to set up the initial conditions,
260 // o = mapped by the GC allocator, and
261 // - = unmapped.
262 // base should point to a region of contiguous free memory
263 // large enough to hold strlen(str) chunks of Chunk bytes.
264 int len = strlen(str);
265 int i;
266 // Find the index of the desired address.
267 for (i = 0; i < len && str[i] != 'o'; ++i);
268 void* desired = (void*)(uintptr_t(base) + i * Chunk);
269 // Map the regions indicated by str.
270 for (i = 0; i < len; ++i) {
271 if (str[i] == 'x') {
272 mapMemoryAt((void*)(uintptr_t(base) + i * Chunk), Chunk);
273 }
274 }
275 // Allocate using the GC's allocator.
276 void* result;
277 if (allocator == UseNormalAllocator) {
278 result = js::gc::MapAlignedPages(2 * Chunk, Alignment);
279 } else {
280 result = js::gc::TestMapAlignedPagesLastDitch(2 * Chunk, Alignment);
281 }
282 // Clean up the mapped regions.
283 if (result) {
284 js::gc::UnmapPages(result, 2 * Chunk);
285 }
286 for (--i; i >= 0; --i) {
287 if (str[i] == 'x') {
288 unmapPages((void*)(uintptr_t(base) + i * Chunk), Chunk);
289 }
290 }
291 // CHECK returns, so clean up on failure.
292 if (result != desired) {
293 while (--tempChunks >= 0) {
294 unmapPages(chunkPool[tempChunks], 2 * Chunk);
295 }
296 }
297 return result == desired;
298 }
299
300 #if defined(XP_WIN)
301
302 void* mapMemoryAt(void* desired, size_t length) {
303 return VirtualAlloc(desired, length, MEM_COMMIT | MEM_RESERVE,
304 PAGE_READWRITE);
305 }
306
307 void* mapMemory(size_t length) {
308 return VirtualAlloc(nullptr, length, MEM_COMMIT | MEM_RESERVE,
309 PAGE_READWRITE);
310 }
311
312 void unmapPages(void* p, size_t size) {
313 MOZ_ALWAYS_TRUE(VirtualFree(p, 0, MEM_RELEASE));
314 }
315
316 #elif defined(__wasi__)
317
318 void* mapMemoryAt(void* desired, size_t length) { return nullptr; }
319
320 void* mapMemory(size_t length) {
321 void* addr = nullptr;
322 if (int err = posix_memalign(&addr, js::gc::SystemPageSize(), length)) {
323 MOZ_ASSERT(err == ENOMEM);
324 }
325 MOZ_ASSERT(addr);
326 memset(addr, 0, length);
327 return addr;
328 }
329
330 void unmapPages(void* p, size_t size) { free(p); }
331
332 #else
333
334 void* mapMemoryAt(void* desired, size_t length) {
335 void* region = mmap(desired, length, PROT_READ | PROT_WRITE,
336 MAP_PRIVATE | MAP_ANON, -1, 0);
337 if (region == MAP_FAILED) {
338 return nullptr;
339 }
340 if (region != desired) {
341 if (munmap(region, length)) {
342 MOZ_RELEASE_ASSERT(errno == ENOMEM);
343 }
344 return nullptr;
345 }
346 return region;
347 }
348
349 void* mapMemory(size_t length) {
350 int prot = PROT_READ | PROT_WRITE;
351 int flags = MAP_PRIVATE | MAP_ANON;
352 int fd = -1;
353 off_t offset = 0;
354 void* region = mmap(nullptr, length, prot, flags, fd, offset);
355 if (region == MAP_FAILED) {
356 return nullptr;
357 }
358 return region;
359 }
360
361 void unmapPages(void* p, size_t size) {
362 if (munmap(p, size)) {
363 MOZ_RELEASE_ASSERT(errno == ENOMEM);
364 }
365 }
366
367 #endif
368
369 END_TEST(testGCAllocator)
370
371 class AutoAddGCRootsTracer {
372 JSContext* cx_;
373 JSTraceDataOp traceOp_;
374 void* data_;
375
376 public:
377 AutoAddGCRootsTracer(JSContext* cx, JSTraceDataOp traceOp, void* data)
378 : cx_(cx), traceOp_(traceOp), data_(data) {
379 JS_AddExtraGCRootsTracer(cx, traceOp, data);
380 }
381 ~AutoAddGCRootsTracer() { JS_RemoveExtraGCRootsTracer(cx_, traceOp_, data_); }
382 };
383
384 static size_t SomeAllocSizes[] = {16,
385 17,
386 31,
387 32,
388 100,
389 200,
390 240,
391 256,
392 1000,
393 4096,
394 5000,
395 16 * 1024,
396 100 * 1024,
397 255 * 1024,
398 256 * 1024,
399 600 * 1024,
400 1 * 1024 * 1024,
401 3 * 1024 * 1024,
402 10 * 1024 * 1024};
403
404 static void WriteAllocData(void* alloc, size_t bytes) {
405 auto* data = reinterpret_cast<uint32_t*>(alloc);
406 size_t length = std::min(bytes / sizeof(uint32_t), size_t(4096));
407 for (size_t i = 0; i < length; i++) {
408 data[i] = i;
409 }
410 }
411
412 static bool CheckAllocData(void* alloc, size_t bytes) {
413 const auto* data = reinterpret_cast<uint32_t*>(alloc);
414 size_t length = std::min(bytes / sizeof(uint32_t), size_t(4096));
415 for (size_t i = 0; i < length; i++) {
416 if (data[i] != i) {
417 return false;
418 }
419 }
420 return true;
421 }
422
423 class BufferHolderObject : public NativeObject {
424 public:
425 static const JSClass class_;
426
427 static BufferHolderObject* create(JSContext* cx);
428
429 void setBuffer(void* buffer);
430
431 private:
432 static const JSClassOps classOps_;
433
434 static void trace(JSTracer* trc, JSObject* obj);
435 };
436
437 const JSClass BufferHolderObject::class_ = {"BufferHolderObject",
438 JSCLASS_HAS_RESERVED_SLOTS(1),
439 &BufferHolderObject::classOps_};
440
441 const JSClassOps BufferHolderObject::classOps_ = {
442 nullptr, // addProperty
443 nullptr, // delProperty
444 nullptr, // enumerate
445 nullptr, // newEnumerate
446 nullptr, // resolve
447 nullptr, // mayResolve
448 nullptr, // finalize
449 nullptr, // call
450 nullptr, // construct
451 BufferHolderObject::trace, // trace
452 };
453
454 /* static */
455 BufferHolderObject* BufferHolderObject::create(JSContext* cx) {
456 NativeObject* obj = NewObjectWithGivenProto(cx, &class_, nullptr);
457 if (!obj) {
458 return nullptr;
459 }
460
461 BufferHolderObject* holder = &obj->as<BufferHolderObject>();
462 holder->setBuffer(nullptr);
463 return holder;
464 }
465
466 void BufferHolderObject::setBuffer(void* buffer) {
467 setFixedSlot(0, JS::PrivateValue(buffer));
468 }
469
470 /* static */
471 void BufferHolderObject::trace(JSTracer* trc, JSObject* obj) {
472 NativeObject* holder = &obj->as<NativeObject>();
473 void* buffer = holder->getFixedSlot(0).toPrivate();
474 if (buffer) {
475 TraceBufferEdge(trc, obj, &buffer, "BufferHolderObject buffer");
476 if (buffer != holder->getFixedSlot(0).toPrivate()) {
477 holder->setFixedSlot(0, JS::PrivateValue(buffer));
478 }
479 }
480 }
481
482 BEGIN_TEST(testBufferAllocator_API) {
483 AutoLeaveZeal leaveZeal(cx);
484
485 Rooted<BufferHolderObject*> holder(cx, BufferHolderObject::create(cx));
486 CHECK(holder);
487
488 JS::NonIncrementalGC(cx, JS::GCOptions::Shrink, JS::GCReason::API);
489
490 Zone* zone = cx->zone();
491 size_t initialGCHeapSize = zone->gcHeapSize.bytes();
492 size_t initialMallocHeapSize = zone->mallocHeapSize.bytes();
493
494 for (size_t requestSize : SomeAllocSizes) {
495 size_t goodSize = GetGoodAllocSize(requestSize);
496
497 size_t wastage = goodSize - requestSize;
498 double fraction = double(wastage) / double(goodSize);
499 fprintf(stderr, "%8zu -> %8zu %7zu (%3.1f%%)\n", requestSize, goodSize,
500 wastage, fraction * 100.0);
501
502 CHECK(goodSize >= requestSize);
503 if (requestSize > 64) {
504 CHECK(goodSize < 2 * requestSize);
505 }
506 CHECK(GetGoodAllocSize(goodSize) == goodSize);
507
508 // Check we don't waste space requesting 1MB aligned sizes.
509 if (requestSize >= ChunkSize) {
510 CHECK(goodSize == RoundUp(requestSize, ChunkSize));
511 }
512
513 for (bool nurseryOwned : {true, false}) {
514 void* alloc = AllocBuffer(zone, requestSize, nurseryOwned);
515 CHECK(alloc);
516
517 CHECK(IsBufferAlloc(alloc));
518 size_t actualSize = GetAllocSize(zone, alloc);
519 CHECK(actualSize == GetGoodAllocSize(requestSize));
520
521 CHECK(IsNurseryOwned(zone, alloc) == nurseryOwned);
522
523 WriteAllocData(alloc, actualSize);
524 CHECK(CheckAllocData(alloc, actualSize));
525
526 CHECK(!IsBufferAllocMarkedBlack(zone, alloc));
527
528 CHECK(cx->runtime()->gc.isPointerWithinBufferAlloc(alloc));
529
530 holder->setBuffer(alloc);
531 if (nurseryOwned) {
532 // Hack to force minor GC. We've marked our alloc 'nursery owned' even
533 // though that isn't true.
534 NewPlainObject(cx);
535 // Hack to force marking our holder.
536 cx->runtime()->gc.storeBuffer().putWholeCell(holder);
537 }
538 JS_GC(cx);
539
540 // Post GC marking state depends on whether allocation is small or not.
541 // Small allocations will remain marked whereas others will have their
542 // mark state cleared.
543
544 CHECK(CheckAllocData(alloc, actualSize));
545
546 holder->setBuffer(nullptr);
547 JS_GC(cx);
548
549 CHECK(zone->gcHeapSize.bytes() == initialGCHeapSize);
550 CHECK(zone->mallocHeapSize.bytes() == initialMallocHeapSize);
551 }
552 }
553
554 return true;
555 }
556 END_TEST(testBufferAllocator_API)
557
558 BEGIN_TEST(testBufferAllocator_realloc) {
559 AutoLeaveZeal leaveZeal(cx);
560
561 Rooted<BufferHolderObject*> holder(cx, BufferHolderObject::create(cx));
562 CHECK(holder);
563
564 JS::NonIncrementalGC(cx, JS::GCOptions::Shrink, JS::GCReason::API);
565
566 Zone* zone = cx->zone();
567 size_t initialGCHeapSize = zone->gcHeapSize.bytes();
568 size_t initialMallocHeapSize = zone->mallocHeapSize.bytes();
569
570 for (bool nurseryOwned : {false, true}) {
571 for (size_t requestSize : SomeAllocSizes) {
572 if (nurseryOwned && requestSize < Nursery::MaxNurseryBufferSize) {
573 continue;
574 }
575
576 // Realloc nullptr.
577 void* alloc = ReallocBuffer(zone, nullptr, requestSize, nurseryOwned);
578 CHECK(alloc);
579 CHECK(IsBufferAlloc(alloc));
580 CHECK(IsNurseryOwned(zone, alloc) == nurseryOwned);
581 size_t actualSize = GetAllocSize(zone, alloc);
582 WriteAllocData(alloc, actualSize);
583 holder->setBuffer(alloc);
584
585 // Realloc to same size.
586 void* prev = alloc;
587 alloc = ReallocBuffer(zone, alloc, requestSize, nurseryOwned);
588 CHECK(alloc);
589 CHECK(alloc == prev);
590 CHECK(actualSize == GetAllocSize(zone, alloc));
591 CHECK(IsNurseryOwned(zone, alloc) == nurseryOwned);
592 CHECK(CheckAllocData(alloc, actualSize));
593
594 // Grow.
595 size_t newSize = requestSize + requestSize / 2;
596 alloc = ReallocBuffer(zone, alloc, newSize, nurseryOwned);
597 CHECK(alloc);
598 CHECK(IsNurseryOwned(zone, alloc) == nurseryOwned);
599 CHECK(CheckAllocData(alloc, actualSize));
600
601 // Shrink.
602 newSize = newSize / 2;
603 alloc = ReallocBuffer(zone, alloc, newSize, nurseryOwned);
604 CHECK(alloc);
605 CHECK(IsNurseryOwned(zone, alloc) == nurseryOwned);
606 actualSize = GetAllocSize(zone, alloc);
607 CHECK(CheckAllocData(alloc, actualSize));
608
609 // Free.
610 holder->setBuffer(nullptr);
611 FreeBuffer(zone, alloc);
612 }
613
614 NewPlainObject(cx); // Force minor GC.
615 JS_GC(cx);
616 }
617
618 CHECK(zone->gcHeapSize.bytes() == initialGCHeapSize);
619 CHECK(zone->mallocHeapSize.bytes() == initialMallocHeapSize);
620
621 return true;
622 }
623 END_TEST(testBufferAllocator_realloc)
624
625 BEGIN_TEST(testBufferAllocator_reallocInPlace) {
626 AutoLeaveZeal leaveZeal(cx);
627
628 Rooted<BufferHolderObject*> holder(cx, BufferHolderObject::create(cx));
629 CHECK(holder);
630
631 JS::NonIncrementalGC(cx, JS::GCOptions::Shrink, JS::GCReason::API);
632
633 Zone* zone = cx->zone();
634 size_t initialGCHeapSize = zone->gcHeapSize.bytes();
635 size_t initialMallocHeapSize = zone->mallocHeapSize.bytes();
636
637 // Check that we resize some buffers in place if the sizes allow.
638
639 // Grow medium -> medium: supported if free space after allocation
640 // We should be able to grow in place if it's the last thing allocated.
641 // *** If this starts failing we may need to allocate a new zone ***
642 CHECK(TestRealloc(1024, 2048, true));
643
644 // Shrink medium -> medium: supported
645 CHECK(TestRealloc(2048, 1024, true));
646
647 // Grow large -> large: not supported
648 CHECK(TestRealloc(1 * 1024 * 1024, 2 * 1024 * 1024, false));
649
650 // Shrink large -> large: supported on non-Windows platforms
651 #ifdef XP_WIN
652 CHECK(TestRealloc(2 * 1024 * 1024, 1 * 1024 * 1024, false));
653 #else
654 CHECK(TestRealloc(2 * 1024 * 1024, 1 * 1024 * 1024, true));
655 #endif
656
657 JS_GC(cx);
658 CHECK(zone->gcHeapSize.bytes() == initialGCHeapSize);
659 CHECK(zone->mallocHeapSize.bytes() == initialMallocHeapSize);
660
661 return true;
662 }
663
664 bool TestRealloc(size_t fromSize, size_t toSize, bool expectedInPlace) {
665 fprintf(stderr, "TestRealloc %zu -> %zu %u\n", fromSize, toSize,
666 unsigned(expectedInPlace));
667
668 Zone* zone = cx->zone();
669 void* alloc = AllocBuffer(zone, fromSize, false);
670 CHECK(alloc);
671
672 void* newAlloc = ReallocBuffer(zone, alloc, toSize, false);
673 CHECK(newAlloc);
674
675 if (expectedInPlace) {
676 CHECK(newAlloc == alloc);
677 } else {
678 CHECK(newAlloc != alloc);
679 }
680
681 FreeBuffer(zone, newAlloc);
682 return true;
683 }
684 END_TEST(testBufferAllocator_reallocInPlace)
685
686 BEGIN_TEST(testBufferAllocator_predicatesOnOtherAllocs) {
687 if (!cx->runtime()->gc.nursery().isEnabled()) {
688 fprintf(stderr, "Skipping test as nursery is disabled.\n");
689 }
690
691 AutoLeaveZeal leaveZeal(cx);
692
693 JS_GC(cx);
694 auto [buffer, isMalloced] = cx->nursery().allocNurseryOrMallocBuffer(
695 cx->zone(), 256, js::MallocArena);
696 CHECK(buffer);
697 CHECK(!isMalloced);
698 CHECK(cx->nursery().isInside(buffer));
699 CHECK(!IsBufferAlloc(buffer));
700
701 RootedObject obj(cx, NewPlainObject(cx));
702 CHECK(obj);
703 CHECK(IsInsideNursery(obj));
704 CHECK(!IsBufferAlloc(obj));
705
706 JS_GC(cx);
707 CHECK(!IsInsideNursery(obj));
708 CHECK(!IsBufferAlloc(obj));
709
710 return true;
711 }
712 END_TEST(testBufferAllocator_predicatesOnOtherAllocs)
713
714 BEGIN_TEST(testBufferAllocator_stress) {
715 AutoLeaveZeal leaveZeal(cx);
716
717 unsigned seed = unsigned(GenerateRandomSeed());
718 fprintf(stderr, "Random seed: 0x%x\n", seed);
719 std::srand(seed);
720
721 Rooted<PlainObject*> holder(
722 cx, NewPlainObjectWithAllocKind(cx, gc::AllocKind::OBJECT2));
723 CHECK(holder);
724
725 JS::NonIncrementalGC(cx, JS::GCOptions::Shrink, JS::GCReason::API);
726 Zone* zone = cx->zone();
727
728 size_t initialGCHeapSize = zone->gcHeapSize.bytes();
729 size_t initialMallocHeapSize = zone->mallocHeapSize.bytes();
730
731 void* liveAllocs[MaxLiveAllocs];
732 mozilla::PodZero(&liveAllocs);
733
734 AutoGCParameter setMaxHeap(cx, JSGC_MAX_BYTES, uint32_t(-1));
735 AutoGCParameter param1(cx, JSGC_INCREMENTAL_GC_ENABLED, true);
736 AutoGCParameter param2(cx, JSGC_PER_ZONE_GC_ENABLED, true);
737
738 #ifdef JS_GC_ZEAL
739 JS::SetGCZeal(cx, 10, 50);
740 #endif
741
742 holder->initFixedSlot(0, JS::PrivateValue(&liveAllocs));
743 AutoAddGCRootsTracer addTracer(cx, traceAllocs, &holder);
744
745 for (size_t i = 0; i < Iterations; i++) {
746 size_t index = std::rand() % MaxLiveAllocs;
747 size_t bytes = randomSize();
748
749 if (!liveAllocs[index]) {
750 liveAllocs[index] = AllocBuffer(zone, bytes, false);
751 } else {
752 void* ptr = ReallocBuffer(zone, liveAllocs[index], bytes, false);
753 if (ptr) {
754 liveAllocs[index] = ptr;
755 }
756 }
757
758 index = std::rand() % MaxLiveAllocs;
759 if (liveAllocs[index]) {
760 if (std::rand() % 1) {
761 FreeBuffer(zone, liveAllocs[index]);
762 }
763 liveAllocs[index] = nullptr;
764 }
765
766 // Trigger zeal GCs.
767 NewPlainObject(cx);
768
769 if ((i % 500) == 0) {
770 // Trigger extra minor GCs.
771 cx->minorGC(JS::GCReason::API);
772 }
773 }
774
775 mozilla::PodArrayZero(liveAllocs);
776
777 #ifdef JS_GC_ZEAL
778 JS::SetGCZeal(cx, 0, 100);
779 #endif
780
781 JS::PrepareForFullGC(cx);
782 JS::NonIncrementalGC(cx, JS::GCOptions::Shrink, JS::GCReason::API);
783
784 CHECK(zone->gcHeapSize.bytes() == initialGCHeapSize);
785 CHECK(zone->mallocHeapSize.bytes() == initialMallocHeapSize);
786
787 return true;
788 }
789
790 static constexpr size_t Iterations = 50000;
791 static constexpr size_t MaxLiveAllocs = 500;
792
793 static size_t randomSize() {
794 constexpr size_t Log2MinSize = 4;
795 constexpr size_t Log2MaxSize = 22; // Up to 4MB.
796
797 double r = double(std::rand()) / double(RAND_MAX);
798 double log2size = (Log2MaxSize - Log2MinSize) * r + Log2MinSize;
799 MOZ_ASSERT(log2size <= Log2MaxSize);
800 return size_t(std::pow(2.0, log2size));
801 }
802
803 static void traceAllocs(JSTracer* trc, void* data) {
804 auto& holder = *static_cast<Rooted<PlainObject*>*>(data);
805 auto* liveAllocs = static_cast<void**>(holder->getFixedSlot(0).toPrivate());
806 for (size_t i = 0; i < MaxLiveAllocs; i++) {
807 void** bufferp = &liveAllocs[i];
808 if (*bufferp) {
809 TraceBufferEdge(trc, holder, bufferp, "test buffer");
810 }
811 }
812 }
813 END_TEST(testBufferAllocator_stress)