DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (b6d82b1a6b02)

VCS Links

Line Code
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 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * vim: set ts=8 sw=2 et 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 "gc/Nursery-inl.h"

#include "mozilla/DebugOnly.h"
#include "mozilla/IntegerPrintfMacros.h"
#include "mozilla/Move.h"
#include "mozilla/Unused.h"

#include "jsutil.h"

#include "builtin/MapObject.h"
#include "debugger/DebugAPI.h"
#include "gc/FreeOp.h"
#include "gc/GCInternals.h"
#include "gc/Memory.h"
#include "gc/PublicIterators.h"
#include "jit/JitFrames.h"
#include "jit/JitRealm.h"
#include "vm/ArrayObject.h"
#if defined(DEBUG)
#  include "vm/EnvironmentObject.h"
#endif
#include "vm/JSONPrinter.h"
#include "vm/Realm.h"
#include "vm/Time.h"
#include "vm/TypedArrayObject.h"
#include "vm/TypeInference.h"

#include "gc/Marking-inl.h"
#include "gc/Zone-inl.h"
#include "vm/NativeObject-inl.h"

using namespace js;
using namespace gc;

using mozilla::DebugOnly;
using mozilla::PodCopy;
using mozilla::TimeDuration;
using mozilla::TimeStamp;

constexpr uintptr_t CanaryMagicValue = 0xDEADB15D;

#ifdef JS_GC_ZEAL
struct js::Nursery::Canary {
  uintptr_t magicValue;
  Canary* next;
};
#endif

namespace js {
struct NurseryChunk {
  char data[Nursery::NurseryChunkUsableSize];
  gc::ChunkTrailer trailer;
  static NurseryChunk* fromChunk(gc::Chunk* chunk);
  void poisonAndInit(JSRuntime* rt, size_t size = ChunkSize);
  void poisonRange(size_t from, size_t size, uint8_t value,
                   MemCheckKind checkKind);
  void poisonAfterEvict(size_t extent = ChunkSize);

  // The end of the range is always ChunkSize - ArenaSize.
  void markPagesUnusedHard(size_t from);
  // The start of the range is always the beginning of the chunk.
  MOZ_MUST_USE bool markPagesInUseHard(size_t to);

  uintptr_t start() const { return uintptr_t(&data); }
  uintptr_t end() const { return uintptr_t(&trailer); }
  gc::Chunk* toChunk(JSRuntime* rt);
};
static_assert(sizeof(js::NurseryChunk) == gc::ChunkSize,
              "Nursery chunk size must match gc::Chunk size.");

}  // namespace js

inline void js::NurseryChunk::poisonAndInit(JSRuntime* rt, size_t size) {
  poisonRange(0, size, JS_FRESH_NURSERY_PATTERN, MemCheckKind::MakeUndefined);
  MOZ_MAKE_MEM_UNDEFINED(&trailer, sizeof(trailer));
  new (&trailer) gc::ChunkTrailer(rt, &rt->gc.storeBuffer());
}

inline void js::NurseryChunk::poisonRange(size_t from, size_t size,
                                          uint8_t value,
                                          MemCheckKind checkKind) {
  MOZ_ASSERT(from <= js::Nursery::NurseryChunkUsableSize);
  MOZ_ASSERT(from + size <= ChunkSize);

  uint8_t* start = reinterpret_cast<uint8_t*>(this) + from;

  // We can poison the same chunk more than once, so first make sure memory
  // sanitizers will let us poison it.
  MOZ_MAKE_MEM_UNDEFINED(start, size);
  Poison(start, value, size, checkKind);
}

inline void js::NurseryChunk::poisonAfterEvict(size_t extent) {
  MOZ_ASSERT(extent <= ChunkSize);
  poisonRange(0, extent, JS_SWEPT_NURSERY_PATTERN, MemCheckKind::MakeNoAccess);
}

inline void js::NurseryChunk::markPagesUnusedHard(size_t from) {
  MOZ_ASSERT(from < ChunkSize - ArenaSize);
  MarkPagesUnusedHard(reinterpret_cast<void*>(start() + from),
                      ChunkSize - ArenaSize - from);
}

inline bool js::NurseryChunk::markPagesInUseHard(size_t to) {
  MOZ_ASSERT(to <= ChunkSize - ArenaSize);
  return MarkPagesInUseHard(reinterpret_cast<void*>(start()), to);
}

// static
inline js::NurseryChunk* js::NurseryChunk::fromChunk(Chunk* chunk) {
  return reinterpret_cast<NurseryChunk*>(chunk);
}

inline Chunk* js::NurseryChunk::toChunk(JSRuntime* rt) {
  auto chunk = reinterpret_cast<Chunk*>(this);
  chunk->init(rt);
  return chunk;
}

void js::NurseryDecommitTask::queueChunk(
    NurseryChunk* nchunk, const AutoLockHelperThreadState& lock) {
  // Using the chunk pointers to build the queue is infallible.
  Chunk* chunk = nchunk->toChunk(runtime());
  chunk->info.prev = nullptr;
  chunk->info.next = queue;
  queue = chunk;
}

void js::NurseryDecommitTask::queueRange(
    size_t newCapacity, NurseryChunk& newChunk,
    const AutoLockHelperThreadState& lock) {
  MOZ_ASSERT(!partialChunk || partialChunk == &newChunk);

  // Only save this to decommit later if there's at least one page to
  // decommit.
  if (JS_ROUNDUP(newCapacity, SystemPageSize()) >=
      JS_ROUNDDOWN(Nursery::NurseryChunkUsableSize, SystemPageSize())) {
    // Clear the existing decommit request because it may be a larger request
    // for the same chunk.
    partialChunk = nullptr;
    return;
  }
  partialChunk = &newChunk;
  partialCapacity = newCapacity;
}

Chunk* js::NurseryDecommitTask::popChunk(
    const AutoLockHelperThreadState& lock) {
  if (!queue) {
    return nullptr;
  }

  Chunk* chunk = queue;
  queue = chunk->info.next;
  chunk->info.next = nullptr;
  MOZ_ASSERT(chunk->info.prev == nullptr);
  return chunk;
}

void js::NurseryDecommitTask::run() {
  Chunk* chunk;

  {
    AutoLockHelperThreadState lock;

    while ((chunk = popChunk(lock)) || partialChunk) {
      if (chunk) {
        AutoUnlockHelperThreadState unlock(lock);
        decommitChunk(chunk);
        continue;
      }

      if (partialChunk) {
        decommitRange(lock);
        continue;
      }
    }

    setFinishing(lock);
  }
}

void js::NurseryDecommitTask::decommitChunk(Chunk* chunk) {
  chunk->decommitAllArenas();
  {
    AutoLockGC lock(runtime());
    runtime()->gc.recycleChunk(chunk, lock);
  }
}

void js::NurseryDecommitTask::decommitRange(AutoLockHelperThreadState& lock) {
  // Clear this field here before releasing the lock. While the lock is
  // released the main thread may make new decommit requests or update the range
  // of the current requested chunk, but it won't attempt to use any
  // might-be-decommitted-soon memory.
  NurseryChunk* thisPartialChunk = partialChunk;
  size_t thisPartialCapacity = partialCapacity;
  partialChunk = nullptr;
  {
    AutoUnlockHelperThreadState unlock(lock);
    thisPartialChunk->markPagesUnusedHard(thisPartialCapacity);
  }
}

js::Nursery::Nursery(JSRuntime* rt)
    : runtime_(rt),
      position_(0),
      currentStartChunk_(0),
      currentStartPosition_(0),
      currentEnd_(0),
      currentStringEnd_(0),
      currentChunk_(0),
      capacity_(0),
      chunkCountLimit_(0),
      timeInChunkAlloc_(0),
      profileThreshold_(0),
      enableProfiling_(false),
      canAllocateStrings_(true),
      reportTenurings_(0),
      minorGCTriggerReason_(JS::GCReason::NO_REASON),
      decommitTask(rt)
#ifdef JS_GC_ZEAL
      ,
      lastCanary_(nullptr)
#endif
{
  const char* env = getenv("MOZ_NURSERY_STRINGS");
  if (env && *env) {
    canAllocateStrings_ = (*env == '1');
  }
}

bool js::Nursery::init(uint32_t maxNurseryBytes, AutoLockGCBgAlloc& lock) {
  // The nursery is permanently disabled when recording or replaying. Nursery
  // collections may occur at non-deterministic points in execution.
  if (mozilla::recordreplay::IsRecordingOrReplaying()) {
    maxNurseryBytes = 0;
  }

  // maxNurseryBytes parameter is rounded down to a multiple of chunk size.
  chunkCountLimit_ = maxNurseryBytes >> ChunkShift;

  // If no chunks are specified then the nursery is permanently disabled.
  if (chunkCountLimit_ == 0) {
    return true;
  }

  if (!allocateNextChunk(0, lock)) {
    return false;
  }
  capacity_ = roundSize(tunables().gcMinNurseryBytes());
  MOZ_ASSERT(capacity_ >= ArenaSize);
  // After this point the Nursery has been enabled.

  setCurrentChunk(0);
  setStartPosition();
  poisonAndInitCurrentChunk();

  char* env = getenv("JS_GC_PROFILE_NURSERY");
  if (env) {
    if (0 == strcmp(env, "help")) {
      fprintf(stderr,
              "JS_GC_PROFILE_NURSERY=N\n"
              "\tReport minor GC's taking at least N microseconds.\n");
      exit(0);
    }
    enableProfiling_ = true;
    profileThreshold_ = TimeDuration::FromMicroseconds(atoi(env));
  }

  env = getenv("JS_GC_REPORT_TENURING");
  if (env) {
    if (0 == strcmp(env, "help")) {
      fprintf(stderr,
              "JS_GC_REPORT_TENURING=N\n"
              "\tAfter a minor GC, report any ObjectGroups with at least N "
              "instances tenured.\n");
      exit(0);
    }
    reportTenurings_ = atoi(env);
  }

  if (!runtime()->gc.storeBuffer().enable()) {
    return false;
  }

  MOZ_ASSERT(isEnabled());
  return true;
}

js::Nursery::~Nursery() { disable(); }

void js::Nursery::enable() {
  MOZ_ASSERT(isEmpty());
  MOZ_ASSERT(!runtime()->gc.isVerifyPreBarriersEnabled());
  if (isEnabled() || !chunkCountLimit()) {
    return;
  }

  {
    AutoLockGCBgAlloc lock(runtime());
    if (!allocateNextChunk(0, lock)) {
      return;
    }
    capacity_ = roundSize(tunables().gcMinNurseryBytes());
    MOZ_ASSERT(capacity_ >= ArenaSize);
  }

  setCurrentChunk(0);
  setStartPosition();
  poisonAndInitCurrentChunk();
#ifdef JS_GC_ZEAL
  if (runtime()->hasZealMode(ZealMode::GenerationalGC)) {
    enterZealMode();
  }
#endif

  MOZ_ALWAYS_TRUE(runtime()->gc.storeBuffer().enable());
}

void js::Nursery::disable() {
  MOZ_ASSERT(isEmpty());
  if (!isEnabled()) {
    return;
  }

  // Freeing the chunks must not race with decommitting part of one of our
  // chunks. So join the decommitTask here and also below.
  decommitTask.join();
  freeChunksFrom(0);
  capacity_ = 0;

  // We must reset currentEnd_ so that there is no space for anything in the
  // nursery. JIT'd code uses this even if the nursery is disabled.
  currentEnd_ = 0;
  currentStringEnd_ = 0;
  position_ = 0;
  runtime()->gc.storeBuffer().disable();

  decommitTask.join();
}

void js::Nursery::enableStrings() {
  MOZ_ASSERT(isEmpty());
  canAllocateStrings_ = true;
  currentStringEnd_ = currentEnd_;
}

void js::Nursery::disableStrings() {
  MOZ_ASSERT(isEmpty());
  canAllocateStrings_ = false;
  currentStringEnd_ = 0;
}

bool js::Nursery::isEmpty() const {
  if (!isEnabled()) {
    return true;
  }

  if (!runtime()->hasZealMode(ZealMode::GenerationalGC)) {
    MOZ_ASSERT(currentStartChunk_ == 0);
    MOZ_ASSERT(currentStartPosition_ == chunk(0).start());
  }
  return position() == currentStartPosition_;
}

#ifdef JS_GC_ZEAL
void js::Nursery::enterZealMode() {
  if (isEnabled()) {
    if (isSubChunkMode()) {
      // The poisoning call below must not race with background decommit,
      // which could be attempting to decommit the currently-unused part of this
      // chunk.
      decommitTask.join();
      {
        AutoEnterOOMUnsafeRegion oomUnsafe;
        if (!chunk(0).markPagesInUseHard(ChunkSize - ArenaSize)) {
          oomUnsafe.crash("Out of memory trying to extend chunk for zeal mode");
        }
      }

      // It'd be simpler to poison the whole chunk, but we can't do that
      // because the nursery might be partially used.
      chunk(0).poisonRange(capacity_, NurseryChunkUsableSize - capacity_,
                           JS_FRESH_NURSERY_PATTERN,
                           MemCheckKind::MakeUndefined);
    }
    capacity_ = chunkCountLimit() * ChunkSize;
    setCurrentEnd();
  }
}

void js::Nursery::leaveZealMode() {
  if (isEnabled()) {
    MOZ_ASSERT(isEmpty());
    setCurrentChunk(0);
    setStartPosition();
    poisonAndInitCurrentChunk();
  }
}
#endif  // JS_GC_ZEAL

JSObject* js::Nursery::allocateObject(JSContext* cx, size_t size,
                                      size_t nDynamicSlots,
                                      const JSClass* clasp) {
  // Ensure there's enough space to replace the contents with a
  // RelocationOverlay.
  MOZ_ASSERT(size >= sizeof(RelocationOverlay));

  // Sanity check the finalizer.
  MOZ_ASSERT_IF(clasp->hasFinalize(),
                CanNurseryAllocateFinalizedClass(clasp) || clasp->isProxy());

  // Make the object allocation.
  JSObject* obj = static_cast<JSObject*>(allocate(size));
  if (!obj) {
    return nullptr;
  }

  // If we want external slots, add them.
  HeapSlot* slots = nullptr;
  if (nDynamicSlots) {
    MOZ_ASSERT(clasp->isNative());
    slots = static_cast<HeapSlot*>(
        allocateBuffer(cx->zone(), nDynamicSlots * sizeof(HeapSlot)));
    if (!slots) {
      // It is safe to leave the allocated object uninitialized, since we
      // do not visit unallocated things in the nursery.
      return nullptr;
    }
  }

  // Store slots pointer directly in new object. If no dynamic slots were
  // requested, caller must initialize slots_ field itself as needed. We
  // don't know if the caller was a native object or not.
  if (nDynamicSlots) {
    static_cast<NativeObject*>(obj)->initSlots(slots);
  }

  gcTracer.traceNurseryAlloc(obj, size);
  return obj;
}

Cell* js::Nursery::allocateString(Zone* zone, size_t size, AllocKind kind) {
  // Ensure there's enough space to replace the contents with a
  // RelocationOverlay.
  MOZ_ASSERT(size >= sizeof(RelocationOverlay));

  size_t allocSize =
      JS_ROUNDUP(sizeof(StringLayout) - 1 + size, CellAlignBytes);
  auto header = static_cast<StringLayout*>(allocate(allocSize));
  if (!header) {
    return nullptr;
  }
  header->zone = zone;

  auto cell = reinterpret_cast<Cell*>(&header->cell);
  gcTracer.traceNurseryAlloc(cell, kind);
  return cell;
}

void* js::Nursery::allocate(size_t size) {
  MOZ_ASSERT(isEnabled());
  MOZ_ASSERT(!JS::RuntimeHeapIsBusy());
  MOZ_ASSERT(CurrentThreadCanAccessRuntime(runtime()));
  MOZ_ASSERT_IF(currentChunk_ == currentStartChunk_,
                position() >= currentStartPosition_);
  MOZ_ASSERT(position() % CellAlignBytes == 0);
  MOZ_ASSERT(size % CellAlignBytes == 0);

#ifdef JS_GC_ZEAL
  static const size_t CanarySize =
      (sizeof(Nursery::Canary) + CellAlignBytes - 1) & ~CellAlignMask;
  if (runtime()->gc.hasZealMode(ZealMode::CheckNursery)) {
    size += CanarySize;
  }
#endif

  if (currentEnd() < position() + size) {
    unsigned chunkno = currentChunk_ + 1;
    MOZ_ASSERT(chunkno <= chunkCountLimit());
    MOZ_ASSERT(chunkno <= maxChunkCount());
    MOZ_ASSERT(chunkno <= allocatedChunkCount());
    if (chunkno == maxChunkCount()) {
      return nullptr;
    }
    if (MOZ_UNLIKELY(chunkno == allocatedChunkCount())) {
      mozilla::TimeStamp start = ReallyNow();
      {
        AutoLockGCBgAlloc lock(runtime());
        if (!allocateNextChunk(chunkno, lock)) {
          return nullptr;
        }
      }
      timeInChunkAlloc_ += ReallyNow() - start;
      MOZ_ASSERT(chunkno < allocatedChunkCount());
    }
    setCurrentChunk(chunkno);
    poisonAndInitCurrentChunk();
  }

  void* thing = (void*)position();
  position_ = position() + size;
  // We count this regardless of the profiler's state, assuming that it costs
  // just as much to count it, as to check the profiler's state and decide not
  // to count it.
  stats().noteNurseryAlloc();

  DebugOnlyPoison(thing, JS_ALLOCATED_NURSERY_PATTERN, size,
                  MemCheckKind::MakeUndefined);

#ifdef JS_GC_ZEAL
  if (runtime()->gc.hasZealMode(ZealMode::CheckNursery)) {
    auto canary = reinterpret_cast<Canary*>(position() - CanarySize);
    canary->magicValue = CanaryMagicValue;
    canary->next = nullptr;
    if (lastCanary_) {
      MOZ_ASSERT(!lastCanary_->next);
      lastCanary_->next = canary;
    }
    lastCanary_ = canary;
  }
#endif

  return thing;
}

void* js::Nursery::allocateBuffer(Zone* zone, size_t nbytes) {
  MOZ_ASSERT(nbytes > 0);

  if (nbytes <= MaxNurseryBufferSize) {
    void* buffer = allocate(nbytes);
    if (buffer) {
      return buffer;
    }
  }

  void* buffer = zone->pod_malloc<uint8_t>(nbytes);
  if (buffer && !registerMallocedBuffer(buffer)) {
    js_free(buffer);
    return nullptr;
  }
  return buffer;
}

void* js::Nursery::allocateBuffer(JSObject* obj, size_t nbytes) {
  MOZ_ASSERT(obj);
  MOZ_ASSERT(nbytes > 0);

  if (!IsInsideNursery(obj)) {
    return obj->zone()->pod_malloc<uint8_t>(nbytes);
  }
  return allocateBuffer(obj->zone(), nbytes);
}

void* js::Nursery::allocateBufferSameLocation(JSObject* obj, size_t nbytes) {
  MOZ_ASSERT(obj);
  MOZ_ASSERT(nbytes > 0);
  MOZ_ASSERT(nbytes <= MaxNurseryBufferSize);

  if (!IsInsideNursery(obj)) {
    return obj->zone()->pod_malloc<uint8_t>(nbytes);
  }

  return allocate(nbytes);
}

void* js::Nursery::allocateZeroedBuffer(
    Zone* zone, size_t nbytes, arena_id_t arena /*= js::MallocArena*/) {
  MOZ_ASSERT(nbytes > 0);

  if (nbytes <= MaxNurseryBufferSize) {
    void* buffer = allocate(nbytes);
    if (buffer) {
      memset(buffer, 0, nbytes);
      return buffer;
    }
  }

  void* buffer = zone->pod_calloc<uint8_t>(nbytes, arena);
  if (buffer && !registerMallocedBuffer(buffer)) {
    js_free(buffer);
    return nullptr;
  }
  return buffer;
}

void* js::Nursery::allocateZeroedBuffer(
    JSObject* obj, size_t nbytes, arena_id_t arena /*= js::MallocArena*/) {
  MOZ_ASSERT(obj);
  MOZ_ASSERT(nbytes > 0);

  if (!IsInsideNursery(obj)) {
    return obj->zone()->pod_calloc<uint8_t>(nbytes, arena);
  }
  return allocateZeroedBuffer(obj->zone(), nbytes, arena);
}

void* js::Nursery::reallocateBuffer(JSObject* obj, void* oldBuffer,
                                    size_t oldBytes, size_t newBytes) {
  if (!IsInsideNursery(obj)) {
    return obj->zone()->pod_realloc<uint8_t>((uint8_t*)oldBuffer, oldBytes,
                                             newBytes);
  }

  if (!isInside(oldBuffer)) {
    void* newBuffer = obj->zone()->pod_realloc<uint8_t>((uint8_t*)oldBuffer,
                                                        oldBytes, newBytes);
    if (newBuffer && oldBuffer != newBuffer) {
      MOZ_ALWAYS_TRUE(mallocedBuffers.rekeyAs(oldBuffer, newBuffer, newBuffer));
    }
    return newBuffer;
  }

  // The nursery cannot make use of the returned slots data.
  if (newBytes < oldBytes) {
    return oldBuffer;
  }

  void* newBuffer = allocateBuffer(obj->zone(), newBytes);
  if (newBuffer) {
    PodCopy((uint8_t*)newBuffer, (uint8_t*)oldBuffer, oldBytes);
  }
  return newBuffer;
}

void js::Nursery::freeBuffer(void* buffer) {
  if (!isInside(buffer)) {
    removeMallocedBuffer(buffer);
    js_free(buffer);
  }
}

void Nursery::setIndirectForwardingPointer(void* oldData, void* newData) {
  MOZ_ASSERT(isInside(oldData));

  // Bug 1196210: If a zero-capacity header lands in the last 2 words of a
  // jemalloc chunk abutting the start of a nursery chunk, the (invalid)
  // newData pointer will appear to be "inside" the nursery.
  MOZ_ASSERT(!isInside(newData) || (uintptr_t(newData) & ChunkMask) == 0);

  AutoEnterOOMUnsafeRegion oomUnsafe;
#ifdef DEBUG
  if (ForwardedBufferMap::Ptr p = forwardedBuffers.lookup(oldData)) {
    MOZ_ASSERT(p->value() == newData);
  }
#endif
  if (!forwardedBuffers.put(oldData, newData)) {
    oomUnsafe.crash("Nursery::setForwardingPointer");
  }
}

#ifdef DEBUG
static bool IsWriteableAddress(void* ptr) {
  volatile uint64_t* vPtr = reinterpret_cast<volatile uint64_t*>(ptr);
  *vPtr = *vPtr;
  return true;
}
#endif

void js::Nursery::forwardBufferPointer(HeapSlot** pSlotsElems) {
  HeapSlot* old = *pSlotsElems;

  if (!isInside(old)) {
    return;
  }

  // The new location for this buffer is either stored inline with it or in
  // the forwardedBuffers table.
  do {
    if (ForwardedBufferMap::Ptr p = forwardedBuffers.lookup(old)) {
      *pSlotsElems = reinterpret_cast<HeapSlot*>(p->value());
      break;
    }

    *pSlotsElems = *reinterpret_cast<HeapSlot**>(old);
  } while (false);

  MOZ_ASSERT(!isInside(*pSlotsElems));
  MOZ_ASSERT(IsWriteableAddress(*pSlotsElems));
}

js::TenuringTracer::TenuringTracer(JSRuntime* rt, Nursery* nursery)
    : JSTracer(rt, JSTracer::TracerKindTag::Tenuring, TraceWeakMapKeysValues),
      nursery_(*nursery),
      tenuredSize(0),
      tenuredCells(0),
      objHead(nullptr),
      objTail(&objHead),
      stringHead(nullptr),
      stringTail(&stringHead) {}

inline float js::Nursery::calcPromotionRate(bool* validForTenuring) const {
  float used = float(previousGC.nurseryUsedBytes);
  float capacity = float(previousGC.nurseryCapacity);
  float tenured = float(previousGC.tenuredBytes);
  float rate;

  if (previousGC.nurseryUsedBytes > 0) {
    if (validForTenuring) {
      // We can only use promotion rates if they're likely to be valid,
      // they're only valid if the nursery was at least 90% full.
      *validForTenuring = used > capacity * 0.9f;
    }
    rate = tenured / used;
  } else {
    if (validForTenuring) {
      *validForTenuring = false;
    }
    rate = 0.0f;
  }

  return rate;
}

void js::Nursery::renderProfileJSON(JSONPrinter& json) const {
  if (!isEnabled()) {
    json.beginObject();
    json.property("status", "nursery disabled");
    json.endObject();
    return;
  }

  if (previousGC.reason == JS::GCReason::NO_REASON) {
    // If the nursery was empty when the last minorGC was requested, then
    // no nursery collection will have been performed but JSON may still be
    // requested. (And as a public API, this function should not crash in
    // such a case.)
    json.beginObject();
    json.property("status", "nursery empty");
    json.endObject();
    return;
  }

  json.beginObject();

  json.property("status", "complete");

  json.property("reason", JS::ExplainGCReason(previousGC.reason));
  json.property("bytes_tenured", previousGC.tenuredBytes);
  json.property("cells_tenured", previousGC.tenuredCells);
  json.property("strings_tenured",
                stats().getStat(gcstats::STAT_STRINGS_TENURED));
  json.property("bytes_used", previousGC.nurseryUsedBytes);
  json.property("cur_capacity", previousGC.nurseryCapacity);
  const size_t newCapacity = capacity();
  if (newCapacity != previousGC.nurseryCapacity) {
    json.property("new_capacity", newCapacity);
  }
  if (previousGC.nurseryCommitted != previousGC.nurseryCapacity) {
    json.property("lazy_capacity", previousGC.nurseryCommitted);
  }
  if (!timeInChunkAlloc_.IsZero()) {
    json.property("chunk_alloc_us", timeInChunkAlloc_, json.MICROSECONDS);
  }

  // These counters only contain consistent data if the profiler is enabled,
  // and then there's no guarentee.
  if (runtime()->geckoProfiler().enabled()) {
    json.property("cells_allocated_nursery",
                  stats().allocsSinceMinorGCNursery());
    json.property("cells_allocated_tenured",
                  stats().allocsSinceMinorGCTenured());
  }

  if (stats().getStat(gcstats::STAT_OBJECT_GROUPS_PRETENURED)) {
    json.property("groups_pretenured",
                  stats().getStat(gcstats::STAT_OBJECT_GROUPS_PRETENURED));
  }
  if (stats().getStat(gcstats::STAT_NURSERY_STRING_REALMS_DISABLED)) {
    json.property(
        "nursery_string_realms_disabled",
        stats().getStat(gcstats::STAT_NURSERY_STRING_REALMS_DISABLED));
  }

  json.beginObjectProperty("phase_times");

#define EXTRACT_NAME(name, text) #name,
  static const char* const names[] = {
      FOR_EACH_NURSERY_PROFILE_TIME(EXTRACT_NAME)
#undef EXTRACT_NAME
          ""};

  size_t i = 0;
  for (auto time : profileDurations_) {
    json.property(names[i++], time, json.MICROSECONDS);
  }

  json.endObject();  // timings value

  json.endObject();
}

// static
void js::Nursery::printProfileHeader() {
  fprintf(stderr, "MinorGC:               Reason  PRate Size        ");
#define PRINT_HEADER(name, text) fprintf(stderr, " %6s", text);
  FOR_EACH_NURSERY_PROFILE_TIME(PRINT_HEADER)
#undef PRINT_HEADER
  fprintf(stderr, "\n");
}

// static
void js::Nursery::printProfileDurations(const ProfileDurations& times) {
  for (auto time : times) {
    fprintf(stderr, " %6" PRIi64, static_cast<int64_t>(time.ToMicroseconds()));
  }
  fprintf(stderr, "\n");
}

void js::Nursery::printTotalProfileTimes() {
  if (enableProfiling_) {
    fprintf(stderr, "MinorGC TOTALS: %7" PRIu64 " collections:             ",
            runtime()->gc.minorGCCount());
    printProfileDurations(totalDurations_);
  }
}

void js::Nursery::maybeClearProfileDurations() {
  for (auto& duration : profileDurations_) {
    duration = mozilla::TimeDuration();
  }
}

inline void js::Nursery::startProfile(ProfileKey key) {
  startTimes_[key] = ReallyNow();
}

inline void js::Nursery::endProfile(ProfileKey key) {
  profileDurations_[key] = ReallyNow() - startTimes_[key];
  totalDurations_[key] += profileDurations_[key];
}

bool js::Nursery::shouldCollect() const {
  if (isEmpty()) {
    return false;
  }

  if (minorGCRequested()) {
    return true;
  }

  bool belowBytesThreshold =
      freeSpace() < tunables().nurseryFreeThresholdForIdleCollection();
  bool belowFractionThreshold =
      float(freeSpace()) / float(capacity()) <
      tunables().nurseryFreeThresholdForIdleCollectionFraction();

  // We want to use belowBytesThreshold when the nursery is sufficiently large,
  // and belowFractionThreshold when it's small.
  //
  // When the nursery is small then belowBytesThreshold is a lower threshold
  // (triggered earlier) than belowFractionThreshold. So if the fraction
  // threshold is true, the bytes one will be true also. The opposite is true
  // when the nursery is large.
  //
  // Therefore, by the time we cross the threshold we care about, we've already
  // crossed the other one, and we can boolean AND to use either condition
  // without encoding any "is the nursery big/small" test/threshold. The point
  // at which they cross is when the nursery is: BytesThreshold /
  // FractionThreshold large.
  //
  // With defaults that's:
  //
  //   1MB = 256KB / 0.25
  //
  return belowBytesThreshold && belowFractionThreshold;
}

// typeReason is the gcReason for specified type, for example,
// FULL_CELL_PTR_OBJ_BUFFER is the gcReason for JSObject.
static inline bool IsFullStoreBufferReason(JS::GCReason reason,
                                           JS::GCReason typeReason) {
  return reason == typeReason ||
         reason == JS::GCReason::FULL_WHOLE_CELL_BUFFER ||
         reason == JS::GCReason::FULL_GENERIC_BUFFER ||
         reason == JS::GCReason::FULL_VALUE_BUFFER ||
         reason == JS::GCReason::FULL_SLOT_BUFFER ||
         reason == JS::GCReason::FULL_SHAPE_BUFFER;
}

void js::Nursery::collect(JS::GCReason reason) {
  JSRuntime* rt = runtime();
  MOZ_ASSERT(!rt->mainContextFromOwnThread()->suppressGC);

  mozilla::recordreplay::AutoDisallowThreadEvents disallow;

  if (!isEnabled() || isEmpty()) {
    // Our barriers are not always exact, and there may be entries in the
    // storebuffer even when the nursery is disabled or empty. It's not safe
    // to keep these entries as they may refer to tenured cells which may be
    // freed after this point.
    rt->gc.storeBuffer().clear();
  }

  if (!isEnabled()) {
    return;
  }

#ifdef JS_GC_ZEAL
  if (rt->gc.hasZealMode(ZealMode::CheckNursery)) {
    for (auto canary = lastCanary_; canary; canary = canary->next) {
      MOZ_ASSERT(canary->magicValue == CanaryMagicValue);
    }
  }
  lastCanary_ = nullptr;
#endif

  stats().beginNurseryCollection(reason);
  gcTracer.traceMinorGCStart();

  maybeClearProfileDurations();
  startProfile(ProfileKey::Total);

  // The analysis marks TenureCount as not problematic for GC hazards because
  // it is only used here, and ObjectGroup pointers are never
  // nursery-allocated.
  MOZ_ASSERT(!IsNurseryAllocable(AllocKind::OBJECT_GROUP));

  TenureCountCache tenureCounts;
  previousGC.reason = JS::GCReason::NO_REASON;
  if (!isEmpty()) {
    doCollection(reason, tenureCounts);
  } else {
    previousGC.nurseryUsedBytes = 0;
    previousGC.nurseryCapacity = capacity();
    previousGC.nurseryCommitted = committed();
    previousGC.tenuredBytes = 0;
    previousGC.tenuredCells = 0;
  }

  // Resize the nursery.
  maybeResizeNursery(reason);

  // Poison/initialise the first chunk.
  if (isEnabled() && previousGC.nurseryUsedBytes) {
    // In most cases Nursery::clear() has not poisoned this chunk or marked it
    // as NoAccess; so we only need to poison the region used during the last
    // cycle.  Also, if the heap was recently expanded we don't want to
    // re-poison the new memory.  In both cases we only need to poison until
    // previousGC.nurseryUsedBytes.
    //
    // In cases where this is not true, like generational zeal mode or subchunk
    // mode, poisonAndInitCurrentChunk() will ignore its parameter.  It will
    // also clamp the parameter.
    poisonAndInitCurrentChunk(previousGC.nurseryUsedBytes);
  }

  const float promotionRate = doPretenuring(rt, reason, tenureCounts);

  // We ignore gcMaxBytes when allocating for minor collection. However, if we
  // overflowed, we disable the nursery. The next time we allocate, we'll fail
  // because bytes >= gcMaxBytes.
  if (rt->gc.heapSize.bytes() >= tunables().gcMaxBytes()) {
    disable();
  }

  endProfile(ProfileKey::Total);
  rt->gc.incMinorGcNumber();

  TimeDuration totalTime = profileDurations_[ProfileKey::Total];
  rt->addTelemetry(JS_TELEMETRY_GC_MINOR_US, totalTime.ToMicroseconds());
  rt->addTelemetry(JS_TELEMETRY_GC_MINOR_REASON, uint32_t(reason));
  if (totalTime.ToMilliseconds() > 1.0) {
    rt->addTelemetry(JS_TELEMETRY_GC_MINOR_REASON_LONG, uint32_t(reason));
  }
  rt->addTelemetry(JS_TELEMETRY_GC_NURSERY_BYTES, committed());

  stats().endNurseryCollection(reason);
  gcTracer.traceMinorGCEnd();
  timeInChunkAlloc_ = mozilla::TimeDuration();

  if (enableProfiling_ && totalTime >= profileThreshold_) {
    stats().maybePrintProfileHeaders();

    fprintf(stderr, "MinorGC: %20s %5.1f%% %5zu       ",
            JS::ExplainGCReason(reason), promotionRate * 100,
            capacity() / 1024);
    printProfileDurations(profileDurations_);

    if (reportTenurings_) {
      for (auto& entry : tenureCounts.entries) {
        if (entry.count >= reportTenurings_) {
          fprintf(stderr, "  %d x ", entry.count);
          AutoSweepObjectGroup sweep(entry.group);
          entry.group->print(sweep);
        }
      }
    }
  }
}

void js::Nursery::doCollection(JS::GCReason reason,
                               TenureCountCache& tenureCounts) {
  JSRuntime* rt = runtime();
  AutoGCSession session(rt, JS::HeapState::MinorCollecting);
  AutoSetThreadIsPerformingGC performingGC;
  AutoStopVerifyingBarriers av(rt, false);
  AutoDisableProxyCheck disableStrictProxyChecking;
  mozilla::DebugOnly<AutoEnterOOMUnsafeRegion> oomUnsafeRegion;

  const size_t initialNurseryCapacity = capacity();
  const size_t initialNurseryUsedBytes = usedSpace();

  // Move objects pointed to by roots from the nursery to the major heap.
  TenuringTracer mover(rt, this);

  // Mark the store buffer. This must happen first.
  StoreBuffer& sb = runtime()->gc.storeBuffer();

  // The MIR graph only contains nursery pointers if cancelIonCompilations()
  // is set on the store buffer, in which case we cancel all compilations
  // of such graphs.
  startProfile(ProfileKey::CancelIonCompilations);
  if (sb.cancelIonCompilations()) {
    js::CancelOffThreadIonCompilesUsingNurseryPointers(rt);
  }
  endProfile(ProfileKey::CancelIonCompilations);

  startProfile(ProfileKey::TraceValues);
  sb.traceValues(mover);
  endProfile(ProfileKey::TraceValues);

  startProfile(ProfileKey::TraceCells);
  sb.traceCells(mover);
  endProfile(ProfileKey::TraceCells);

  startProfile(ProfileKey::TraceSlots);
  sb.traceSlots(mover);
  endProfile(ProfileKey::TraceSlots);

  startProfile(ProfileKey::TraceWholeCells);
  sb.traceWholeCells(mover);
  endProfile(ProfileKey::TraceWholeCells);

  startProfile(ProfileKey::TraceGenericEntries);
  sb.traceGenericEntries(&mover);
  endProfile(ProfileKey::TraceGenericEntries);

  startProfile(ProfileKey::MarkRuntime);
  rt->gc.traceRuntimeForMinorGC(&mover, session);
  endProfile(ProfileKey::MarkRuntime);

  startProfile(ProfileKey::MarkDebugger);
  {
    gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::MARK_ROOTS);
    DebugAPI::traceAllForMovingGC(&mover);
  }
  endProfile(ProfileKey::MarkDebugger);

  startProfile(ProfileKey::SweepCaches);
  rt->gc.purgeRuntimeForMinorGC();
  endProfile(ProfileKey::SweepCaches);

  // Most of the work is done here. This loop iterates over objects that have
  // been moved to the major heap. If these objects have any outgoing pointers
  // to the nursery, then those nursery objects get moved as well, until no
  // objects are left to move. That is, we iterate to a fixed point.
  startProfile(ProfileKey::CollectToFP);
  collectToFixedPoint(mover, tenureCounts);
  endProfile(ProfileKey::CollectToFP);

  // Sweep to update any pointers to nursery objects that have now been
  // tenured.
  startProfile(ProfileKey::Sweep);
  sweep(&mover);
  endProfile(ProfileKey::Sweep);

  // Update any slot or element pointers whose destination has been tenured.
  startProfile(ProfileKey::UpdateJitActivations);
  js::jit::UpdateJitActivationsForMinorGC(rt);
  forwardedBuffers.clearAndCompact();
  endProfile(ProfileKey::UpdateJitActivations);

  startProfile(ProfileKey::ObjectsTenuredCallback);
  rt->gc.callObjectsTenuredCallback();
  endProfile(ProfileKey::ObjectsTenuredCallback);

  // Sweep.
  startProfile(ProfileKey::FreeMallocedBuffers);
  rt->gc.queueBuffersForFreeAfterMinorGC(mallocedBuffers);
  endProfile(ProfileKey::FreeMallocedBuffers);

  startProfile(ProfileKey::ClearNursery);
  clear();
  endProfile(ProfileKey::ClearNursery);

  startProfile(ProfileKey::ClearStoreBuffer);
  runtime()->gc.storeBuffer().clear();
  endProfile(ProfileKey::ClearStoreBuffer);

  // Make sure hashtables have been updated after the collection.
  startProfile(ProfileKey::CheckHashTables);
#ifdef JS_GC_ZEAL
  if (rt->hasZealMode(ZealMode::CheckHashTablesOnMinorGC)) {
    CheckHashTablesAfterMovingGC(rt);
  }
#endif
  endProfile(ProfileKey::CheckHashTables);

  previousGC.reason = reason;
  previousGC.nurseryCapacity = initialNurseryCapacity;
  previousGC.nurseryCommitted = spaceToEnd(allocatedChunkCount());
  previousGC.nurseryUsedBytes = initialNurseryUsedBytes;
  previousGC.tenuredBytes = mover.tenuredSize;
  previousGC.tenuredCells = mover.tenuredCells;
}

float js::Nursery::doPretenuring(JSRuntime* rt, JS::GCReason reason,
                                 TenureCountCache& tenureCounts) {
  // If we are promoting the nursery, or exhausted the store buffer with
  // pointers to nursery things, which will force a collection well before
  // the nursery is full, look for object groups that are getting promoted
  // excessively and try to pretenure them.
  startProfile(ProfileKey::Pretenure);
  bool validPromotionRate;
  const float promotionRate = calcPromotionRate(&validPromotionRate);
  uint32_t pretenureCount = 0;
  bool attempt = tunables().attemptPretenuring();

  bool pretenureObj, pretenureStr;
  if (attempt) {
    // Should we do pretenuring regardless of gcreason?
    bool shouldPretenure = validPromotionRate &&
                           promotionRate > tunables().pretenureThreshold() &&
                           previousGC.nurseryUsedBytes >= 4 * 1024 * 1024;
    pretenureObj =
        shouldPretenure ||
        IsFullStoreBufferReason(reason, JS::GCReason::FULL_CELL_PTR_OBJ_BUFFER);
    pretenureStr =
        shouldPretenure ||
        IsFullStoreBufferReason(reason, JS::GCReason::FULL_CELL_PTR_STR_BUFFER);
  } else {
    pretenureObj = false;
    pretenureStr = false;
  }

  if (pretenureObj) {
    JSContext* cx = rt->mainContextFromOwnThread();
    uint32_t threshold = tunables().pretenureGroupThreshold();
    for (auto& entry : tenureCounts.entries) {
      if (entry.count < threshold) {
        continue;
      }

      ObjectGroup* group = entry.group;
      AutoRealm ar(cx, group);
      AutoSweepObjectGroup sweep(group);
      if (group->canPreTenure(sweep)) {
        group->setShouldPreTenure(sweep, cx);
        pretenureCount++;
      }
    }
  }
  stats().setStat(gcstats::STAT_OBJECT_GROUPS_PRETENURED, pretenureCount);

  mozilla::Maybe<AutoGCSession> session;
  uint32_t numStringsTenured = 0;
  uint32_t numNurseryStringRealmsDisabled = 0;
  for (ZonesIter zone(rt, SkipAtoms); !zone.done(); zone.next()) {
    if (pretenureStr && zone->allocNurseryStrings &&
        zone->tenuredStrings >= 30 * 1000) {
      if (!session.isSome()) {
        session.emplace(rt, JS::HeapState::MinorCollecting);
      }
      CancelOffThreadIonCompile(zone);
      bool preserving = zone->isPreservingCode();
      zone->setPreservingCode(false);
      zone->discardJitCode(rt->defaultFreeOp());
      zone->setPreservingCode(preserving);
      for (RealmsInZoneIter r(zone); !r.done(); r.next()) {
        if (jit::JitRealm* jitRealm = r->jitRealm()) {
          jitRealm->discardStubs();
          jitRealm->setStringsCanBeInNursery(false);
          numNurseryStringRealmsDisabled++;
        }
      }
      zone->allocNurseryStrings = false;
    }
    numStringsTenured += zone->tenuredStrings;
    zone->tenuredStrings = 0;
  }
  session.reset();  // End the minor GC session, if running one.
  stats().setStat(gcstats::STAT_NURSERY_STRING_REALMS_DISABLED,
                  numNurseryStringRealmsDisabled);
  stats().setStat(gcstats::STAT_STRINGS_TENURED, numStringsTenured);
  endProfile(ProfileKey::Pretenure);

  rt->addTelemetry(JS_TELEMETRY_GC_PRETENURE_COUNT, pretenureCount);
  rt->addTelemetry(JS_TELEMETRY_GC_NURSERY_PROMOTION_RATE, promotionRate * 100);

  return promotionRate;
}

bool js::Nursery::registerMallocedBuffer(void* buffer) {
  MOZ_ASSERT(buffer);
  return mallocedBuffers.putNew(buffer);
}

void js::Nursery::sweep(JSTracer* trc) {
  // Sweep unique IDs first before we sweep any tables that may be keyed based
  // on them.
  for (Cell* cell : cellsWithUid_) {
    JSObject* obj = static_cast<JSObject*>(cell);
    if (!IsForwarded(obj)) {
      obj->zone()->removeUniqueId(obj);
    } else {
      JSObject* dst = Forwarded(obj);
      dst->zone()->transferUniqueId(dst, obj);
    }
  }
  cellsWithUid_.clear();

  for (CompartmentsIter c(runtime()); !c.done(); c.next()) {
    c->sweepAfterMinorGC(trc);
  }

  for (ZonesIter zone(trc->runtime(), SkipAtoms); !zone.done(); zone.next()) {
    zone->sweepAfterMinorGC(trc);
  }

  sweepDictionaryModeObjects();
  sweepMapAndSetObjects();
}

void js::Nursery::clear() {
  // Poison the nursery contents so touching a freed object will crash.
  unsigned firstClearChunk;
  if (runtime()->hasZealMode(ZealMode::GenerationalGC)) {
    // Poison all the chunks used in this cycle. The new start chunk is
    // reposioned in Nursery::collect() but there's no point optimising that in
    // this case.
    firstClearChunk = currentStartChunk_;
  } else {
    // In normal mode we start at the second chunk, the first one will be used
    // in the next cycle and poisoned in Nusery::collect();
    MOZ_ASSERT(currentStartChunk_ == 0);
    firstClearChunk = 1;
  }
  for (unsigned i = firstClearChunk; i < currentChunk_; ++i) {
    chunk(i).poisonAfterEvict();
  }
  // Clear only the used part of the chunk because that's the part we touched,
  // but only if it's not going to be re-used immediately (>= firstClearChunk).
  if (currentChunk_ >= firstClearChunk) {
    chunk(currentChunk_)
        .poisonAfterEvict(position() - chunk(currentChunk_).start());
  }

  // Reset the start chunk & position if we're not in this zeal mode, or we're
  // in it and close to the end of the nursery.
  MOZ_ASSERT(maxChunkCount() > 0);
  if (!runtime()->hasZealMode(ZealMode::GenerationalGC) ||
      (runtime()->hasZealMode(ZealMode::GenerationalGC) &&
       currentChunk_ + 1 == maxChunkCount())) {
    setCurrentChunk(0);
  }

  // Set current start position for isEmpty checks.
  setStartPosition();
}

size_t js::Nursery::spaceToEnd(unsigned chunkCount) const {
  if (chunkCount == 0) {
    return 0;
  }

  unsigned lastChunk = chunkCount - 1;

  MOZ_ASSERT(lastChunk >= currentStartChunk_);
  MOZ_ASSERT(currentStartPosition_ - chunk(currentStartChunk_).start() <=
             NurseryChunkUsableSize);

  size_t bytes;

  if (chunkCount != 1) {
    // In the general case we have to add:
    //  + the bytes used in the first
    //    chunk which may be less than the total size of a chunk since in some
    //    zeal modes we start the first chunk at some later position
    //    (currentStartPosition_).
    //  + the size of all the other chunks.
    bytes = (chunk(currentStartChunk_).end() - currentStartPosition_) +
            ((lastChunk - currentStartChunk_) * ChunkSize);
  } else {
    // In sub-chunk mode, but it also works whenever chunkCount == 1, we need to
    // use currentEnd_ since it may not refer to a full chunk.
    bytes = currentEnd_ - currentStartPosition_;
  }

  MOZ_ASSERT(bytes <= maxChunkCount() * ChunkSize);

  return bytes;
}

MOZ_ALWAYS_INLINE void js::Nursery::setCurrentChunk(unsigned chunkno) {
  MOZ_ASSERT(chunkno < chunkCountLimit());
  MOZ_ASSERT(chunkno < allocatedChunkCount());

  currentChunk_ = chunkno;
  position_ = chunk(chunkno).start();
  setCurrentEnd();
}

void js::Nursery::poisonAndInitCurrentChunk(size_t extent) {
  if (runtime()->hasZealMode(ZealMode::GenerationalGC) || !isSubChunkMode()) {
    chunk(currentChunk_).poisonAndInit(runtime());
  } else {
    extent = Min(capacity_, extent);
    MOZ_ASSERT(extent <= NurseryChunkUsableSize);
    chunk(currentChunk_).poisonAndInit(runtime(), extent);
  }
}

MOZ_ALWAYS_INLINE void js::Nursery::setCurrentEnd() {
  MOZ_ASSERT_IF(isSubChunkMode(),
                currentChunk_ == 0 && currentEnd_ <= chunk(0).end());
  currentEnd_ =
      chunk(currentChunk_).start() + Min(capacity_, NurseryChunkUsableSize);
  if (canAllocateStrings_) {
    currentStringEnd_ = currentEnd_;
  }
}

bool js::Nursery::allocateNextChunk(const unsigned chunkno,
                                    AutoLockGCBgAlloc& lock) {
  const unsigned priorCount = allocatedChunkCount();
  const unsigned newCount = priorCount + 1;

  MOZ_ASSERT((chunkno == currentChunk_ + 1) ||
             (chunkno == 0 && allocatedChunkCount() == 0));
  MOZ_ASSERT(chunkno == allocatedChunkCount());
  MOZ_ASSERT(chunkno < chunkCountLimit());

  if (!chunks_.resize(newCount)) {
    return false;
  }

  Chunk* newChunk;
  newChunk = runtime()->gc.getOrAllocChunk(lock);
  if (!newChunk) {
    chunks_.shrinkTo(priorCount);
    return false;
  }

  chunks_[chunkno] = NurseryChunk::fromChunk(newChunk);
  return true;
}

MOZ_ALWAYS_INLINE void js::Nursery::setStartPosition() {
  currentStartChunk_ = currentChunk_;
  currentStartPosition_ = position();
}

void js::Nursery::maybeResizeNursery(JS::GCReason reason) {
  if (maybeResizeExact(reason)) {
    return;
  }

  // This incorrect promotion rate results in better nursery sizing
  // decisions, however we should to better tuning based on the real
  // promotion rate in the future.
  const float promotionRate =
      float(previousGC.tenuredBytes) / float(previousGC.nurseryCapacity);

  // Object lifetimes aren't going to behave linearly, but a better
  // relationship that works for all programs and can be predicted in
  // advance doesn't exist.
  static const float GrowThreshold = 0.03f;
  static const float ShrinkThreshold = 0.01f;
  static const float PromotionGoal = (GrowThreshold + ShrinkThreshold) / 2.0f;
  const float factor = promotionRate / PromotionGoal;
  MOZ_ASSERT(factor >= 0.0f);

#ifdef DEBUG
  // This is |... <= SIZE_MAX|, just without the implicit value-changing
  // conversion that expression would involve and modern clang would warn about.
  static const float SizeMaxPlusOne =
      2.0f * float(1ULL << (sizeof(void*) * CHAR_BIT - 1));
  MOZ_ASSERT((float(capacity()) * factor) < SizeMaxPlusOne);
#endif

  size_t newCapacity = size_t(float(capacity()) * factor);

  const size_t minNurseryBytes = roundSize(tunables().gcMinNurseryBytes());
  MOZ_ASSERT(minNurseryBytes >= ArenaSize);

  // If one of these conditions is true then we always shrink or grow the
  // nursery. This way the thresholds still have an effect even if the goal
  // seeking says the current size is ideal.
  size_t lowLimit = Max(minNurseryBytes, capacity() / 2);
  size_t highLimit =
      Min((CheckedInt<size_t>(chunkCountLimit()) * ChunkSize).value(),
          (CheckedInt<size_t>(capacity()) * 2).value());
  newCapacity = roundSize(mozilla::Clamp(newCapacity, lowLimit, highLimit));

  if (maxChunkCount() < chunkCountLimit() && promotionRate > GrowThreshold &&
      newCapacity > capacity()) {
    growAllocableSpace(newCapacity);
  } else if (capacity() >= minNurseryBytes + SubChunkStep &&
             promotionRate < ShrinkThreshold && newCapacity < capacity()) {
    shrinkAllocableSpace(newCapacity);
  }
}

bool js::Nursery::maybeResizeExact(JS::GCReason reason) {
  // Shrink the nursery to its minimum size if we ran out of memory or
  // received a memory pressure event.
  if (gc::IsOOMReason(reason) || runtime()->gc.systemHasLowMemory()) {
    minimizeAllocableSpace();
    return true;
  }

#ifdef JS_GC_ZEAL
  // This zeal mode disabled nursery resizing.
  if (runtime()->hasZealMode(ZealMode::GenerationalGC)) {
    return true;
  }
#endif

  MOZ_ASSERT(tunables().gcMaxNurseryBytes() >= ArenaSize);
  CheckedInt<unsigned> newMaxNurseryChunksChecked =
      (JS_ROUND(CheckedInt<size_t>(tunables().gcMaxNurseryBytes()), ChunkSize) /
       ChunkSize)
          .toChecked<unsigned>();
  if (!newMaxNurseryChunksChecked.isValid()) {
    // The above calculation probably overflowed (I don't think it can
    // underflow).
    newMaxNurseryChunksChecked = 1;
  }
  unsigned newMaxNurseryChunks = newMaxNurseryChunksChecked.value();
  if (newMaxNurseryChunks == 0) {
    // The above code rounded down, but don't round down all the way to zero.
    newMaxNurseryChunks = 1;
  }
  if (newMaxNurseryChunks != chunkCountLimit_) {
    chunkCountLimit_ = newMaxNurseryChunks;
    // The configured maximum nursery size is changing.
    if (JS_HOWMANY(capacity_, gc::ChunkSize) > newMaxNurseryChunks) {
      // We need to shrink the nursery.
      static_assert(NurseryChunkUsableSize < ChunkSize,
                    "Usable size must be smaller than total size or this "
                    "calculation might overflow");
      shrinkAllocableSpace(newMaxNurseryChunks * ChunkSize);
      return true;
    }
  }

  const size_t minNurseryBytes = roundSize(tunables().gcMinNurseryBytes());
  MOZ_ASSERT(minNurseryBytes >= ArenaSize);

  if (minNurseryBytes > capacity()) {
    // the configured minimum nursery size is changing, so grow the nursery.
    MOZ_ASSERT(minNurseryBytes <= roundSize(tunables().gcMaxNurseryBytes()));
    growAllocableSpace(minNurseryBytes);
    return true;
  }

  return false;
}

size_t js::Nursery::roundSize(size_t size) const {
  if (size >= ChunkSize) {
    size = JS_ROUND(size, ChunkSize);
  } else {
    size = Min(JS_ROUND(size, SubChunkStep),
               JS_ROUNDDOWN(NurseryChunkUsableSize, SubChunkStep));
  }
  return size;
}

void js::Nursery::growAllocableSpace(size_t newCapacity) {
  MOZ_ASSERT_IF(!isSubChunkMode(), newCapacity > currentChunk_ * ChunkSize);
  MOZ_ASSERT(newCapacity <= chunkCountLimit_ * ChunkSize);
  MOZ_ASSERT(newCapacity > capacity());

  if (isSubChunkMode()) {
    // Avoid growing into an area that's about to be decommitted.
    decommitTask.join();

    MOZ_ASSERT(currentChunk_ == 0);

    // The remainder of the chunk may have been decommitted.
    if (!chunk(0).markPagesInUseHard(Min(newCapacity, ChunkSize - ArenaSize))) {
      // The OS won't give us the memory we need, we can't grow.
      return;
    }

    // The capacity has changed and since we were in sub-chunk mode we need to
    // update the poison values / asan infomation for the now-valid region of
    // this chunk.
    size_t poisonSize = Min(newCapacity, NurseryChunkUsableSize) - capacity();
    // Don't poison the trailer.
    MOZ_ASSERT(capacity() + poisonSize <= NurseryChunkUsableSize);
    chunk(0).poisonRange(capacity(), poisonSize, JS_FRESH_NURSERY_PATTERN,
                         MemCheckKind::MakeUndefined);
  }

  capacity_ = newCapacity;

  setCurrentEnd();
}

void js::Nursery::freeChunksFrom(const unsigned firstFreeChunk) {
  MOZ_ASSERT(firstFreeChunk < chunks_.length());

  // The loop below may need to skip the first chunk, so we may use this so we
  // can modify it.
  unsigned firstChunkToDecommit = firstFreeChunk;

  if ((firstChunkToDecommit == 0) && isSubChunkMode()) {
    // Part of the first chunk may be hard-decommitted, un-decommit it so that
    // the GC's normal chunk-handling doesn't segfault.
    MOZ_ASSERT(currentChunk_ == 0);
    if (!chunk(0).markPagesInUseHard(ChunkSize - ArenaSize)) {
      // Free the chunk if we can't allocate its pages.
      UnmapPages(static_cast<void*>(&chunk(0)), ChunkSize);
      firstChunkToDecommit = 1;
    }
  }

  {
    AutoLockHelperThreadState lock;
    for (size_t i = firstChunkToDecommit; i < chunks_.length(); i++) {
      decommitTask.queueChunk(chunks_[i], lock);
    }
    decommitTask.startOrRunIfIdle(lock);
  }

  chunks_.shrinkTo(firstFreeChunk);
}

void js::Nursery::shrinkAllocableSpace(size_t newCapacity) {
#ifdef JS_GC_ZEAL
  if (runtime()->hasZealMode(ZealMode::GenerationalGC)) {
    return;
  }
#endif

  // Don't shrink the nursery to zero (use Nursery::disable() instead)
  // This can't happen due to the rounding-down performed above because of the
  // clamping in maybeResizeNursery().
  MOZ_ASSERT(newCapacity != 0);
  // Don't attempt to shrink it to the same size.
  if (newCapacity == capacity_) {
    return;
  }
  MOZ_ASSERT(newCapacity < capacity_);

  unsigned newCount = JS_HOWMANY(newCapacity, ChunkSize);
  if (newCount < allocatedChunkCount()) {
    freeChunksFrom(newCount);
  }

  size_t oldCapacity = capacity_;
  capacity_ = newCapacity;
  MOZ_ASSERT(capacity_ >= ArenaSize);

  setCurrentEnd();

  if (isSubChunkMode()) {
    MOZ_ASSERT(currentChunk_ == 0);
    chunk(0).poisonRange(newCapacity,
                         Min(oldCapacity, NurseryChunkUsableSize) - newCapacity,
                         JS_SWEPT_NURSERY_PATTERN, MemCheckKind::MakeNoAccess);

    AutoLockHelperThreadState lock;
    decommitTask.queueRange(capacity_, chunk(0), lock);
    decommitTask.startOrRunIfIdle(lock);
  }
}

void js::Nursery::minimizeAllocableSpace() {
  shrinkAllocableSpace(tunables().gcMinNurseryBytes());
}

bool js::Nursery::queueDictionaryModeObjectToSweep(NativeObject* obj) {
  MOZ_ASSERT(IsInsideNursery(obj));
  return dictionaryModeObjects_.append(obj);
}

uintptr_t js::Nursery::currentEnd() const {
  // These are separate asserts because it can be useful to see which one
  // failed.
  MOZ_ASSERT_IF(isSubChunkMode(), currentChunk_ == 0);
  MOZ_ASSERT_IF(isSubChunkMode(), currentEnd_ <= chunk(currentChunk_).end());
  MOZ_ASSERT_IF(!isSubChunkMode(), currentEnd_ == chunk(currentChunk_).end());
  MOZ_ASSERT(currentEnd_ != chunk(currentChunk_).start());
  return currentEnd_;
}

gcstats::Statistics& js::Nursery::stats() const {
  return runtime()->gc.stats();
}

MOZ_ALWAYS_INLINE const js::gc::GCSchedulingTunables& js::Nursery::tunables()
    const {
  return runtime()->gc.tunables;
}

bool js::Nursery::isSubChunkMode() const {
  return capacity() <= NurseryChunkUsableSize;
}

void js::Nursery::sweepDictionaryModeObjects() {
  for (auto obj : dictionaryModeObjects_) {
    if (!IsForwarded(obj)) {
      obj->sweepDictionaryListPointer();
    } else {
      Forwarded(obj)->updateDictionaryListPointerAfterMinorGC(obj);
    }
  }
  dictionaryModeObjects_.clear();
}

void js::Nursery::sweepMapAndSetObjects() {
  auto fop = runtime_->defaultFreeOp();

  for (auto mapobj : mapsWithNurseryMemory_) {
    MapObject::sweepAfterMinorGC(fop, mapobj);
  }
  mapsWithNurseryMemory_.clearAndFree();

  for (auto setobj : setsWithNurseryMemory_) {
    SetObject::sweepAfterMinorGC(fop, setobj);
  }
  setsWithNurseryMemory_.clearAndFree();
}

JS_PUBLIC_API void JS::EnableNurseryStrings(JSContext* cx) {
  AutoEmptyNursery empty(cx);
  ReleaseAllJITCode(cx->runtime()->defaultFreeOp());
  cx->runtime()->gc.nursery().enableStrings();
}

JS_PUBLIC_API void JS::DisableNurseryStrings(JSContext* cx) {
  AutoEmptyNursery empty(cx);
  ReleaseAllJITCode(cx->runtime()->defaultFreeOp());
  cx->runtime()->gc.nursery().disableStrings();
}