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 (409f3966645a)

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 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 * vim: set ts=8 sts=4 et sw=4 tw=99:
 * 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 "vm/SavedStacks.h"

#include "mozilla/ArrayUtils.h"
#include "mozilla/Attributes.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/Move.h"

#include <algorithm>
#include <math.h>

#include "jsapi.h"
#include "jsfriendapi.h"
#include "jsmath.h"
#include "jsnum.h"

#include "gc/FreeOp.h"
#include "gc/HashUtil.h"
#include "gc/Marking.h"
#include "gc/Policy.h"
#include "gc/Rooting.h"
#include "js/CharacterEncoding.h"
#include "js/SavedFrameAPI.h"
#include "js/Vector.h"
#include "util/StringBuffer.h"
#include "vm/Debugger.h"
#include "vm/GeckoProfiler.h"
#include "vm/JSScript.h"
#include "vm/Realm.h"
#include "vm/SavedFrame.h"
#include "vm/Time.h"
#include "vm/WrapperObject.h"

#include "vm/GeckoProfiler-inl.h"
#include "vm/JSContext-inl.h"
#include "vm/NativeObject-inl.h"
#include "vm/Stack-inl.h"

using mozilla::AddToHash;
using mozilla::DebugOnly;
using mozilla::Maybe;
using mozilla::Nothing;
using mozilla::Some;

namespace js {

/**
 * Maximum number of saved frames returned for an async stack.
 */
const uint32_t ASYNC_STACK_MAX_FRAME_COUNT = 60;

void
LiveSavedFrameCache::trace(JSTracer* trc)
{
    if (!initialized())
        return;

    for (auto* entry = frames->begin(); entry < frames->end(); entry++) {
        TraceEdge(trc,
                  &entry->savedFrame,
                  "LiveSavedFrameCache::frames SavedFrame");
    }
}

bool
LiveSavedFrameCache::insert(JSContext* cx, FramePtr& framePtr, const jsbytecode* pc,
                            HandleSavedFrame savedFrame)
{
    MOZ_ASSERT(savedFrame);
    MOZ_ASSERT(initialized());

#ifdef DEBUG
    // There should not already be an entry for this frame. Checking the full stack
    // really slows down some tests, so just check the first and last five hundred.
    size_t limit = std::min(frames->length() / 2, size_t(500));
    for (size_t i = 0; i < limit; i++) {
        MOZ_ASSERT(Key(framePtr) != (*frames)[i].key);
        MOZ_ASSERT(Key(framePtr) != (*frames)[frames->length() - 1 - i].key);
    }
#endif

    if (!frames->emplaceBack(framePtr, pc, savedFrame)) {
        ReportOutOfMemory(cx);
        return false;
    }

    framePtr.setHasCachedSavedFrame();

    return true;
}

void
LiveSavedFrameCache::find(JSContext* cx, FramePtr& framePtr, const jsbytecode* pc,
                          MutableHandleSavedFrame frame) const
{
    MOZ_ASSERT(initialized());
    MOZ_ASSERT(framePtr.hasCachedSavedFrame());

    // If we flushed the cache due to a realm mismatch, then we shouldn't
    // expect to find any frames in the cache.
    if (frames->empty()) {
        frame.set(nullptr);
        return;
    }

    // All our SavedFrames should be in the same realm. If the last
    // entry's SavedFrame's realm doesn't match cx's, flush the cache.
    if (frames->back().savedFrame->realm() != cx->realm()) {
#ifdef DEBUG
        // Check that they are, indeed, all in the same realm.
        auto compartment = frames->back().savedFrame->realm();
        for (const auto& f : (*frames))
            MOZ_ASSERT(compartment == f.savedFrame->realm());
#endif
        frames->clear();
        frame.set(nullptr);
        return;
    }

    Key key(framePtr);
    while (key != frames->back().key) {
        MOZ_ASSERT(frames->back().savedFrame->realm() == cx->realm());

        // We know that the cache does contain an entry for frameIter's frame,
        // since its bit is set. That entry must be below this one in the stack,
        // so frames->back() must correspond to a frame younger than
        // frameIter's. If frameIter is the youngest frame with its bit set,
        // then its entry is the youngest that is valid, and we can pop this
        // entry. Even if frameIter is not the youngest frame with its bit set,
        // since we're going to push new cache entries for all frames younger
        // than frameIter, we must pop it anyway.
        frames->popBack();

        // If the frame's bit was set, the frame should always have an entry in
        // the cache. (If we purged the entire cache because its SavedFrames had
        // been captured for a different compartment, then we would have
        // returned early above.)
        MOZ_ALWAYS_TRUE(!frames->empty());
    }

    // The youngest valid frame may have run some code, so its current pc may
    // not match its cache entry's pc. In this case, just treat it as a miss. No
    // older frame has executed any code; it would have been necessary to pop
    // this frame for that to happen, but this frame's bit is set.
    if (pc != frames->back().pc) {
        frames->popBack();

        // Since we've removed this entry from the cache, clear the bit on its
        // frame. Usually we'll repopulate the cache anyway, but if there's an
        // OOM that might not happen.
        framePtr.clearHasCachedSavedFrame();
        frame.set(nullptr);
        return;
    }

    frame.set(frames->back().savedFrame);
}

void
LiveSavedFrameCache::findWithoutInvalidation(const FramePtr& framePtr,
                                             MutableHandleSavedFrame frame) const
{
    MOZ_ASSERT(initialized());
    MOZ_ASSERT(framePtr.hasCachedSavedFrame());

    Key key(framePtr);
    for (auto& entry : (*frames)) {
        if (entry.key == key) {
            frame.set(entry.savedFrame);
            return;
        }
    }

    frame.set(nullptr);
}

struct SavedFrame::Lookup {
    Lookup(JSAtom* source, uint32_t line, uint32_t column,
           JSAtom* functionDisplayName, JSAtom* asyncCause, SavedFrame* parent,
           JSPrincipals* principals,
           const Maybe<LiveSavedFrameCache::FramePtr>& framePtr = Nothing(),
           jsbytecode* pc = nullptr, Activation* activation = nullptr)
      : source(source),
        line(line),
        column(column),
        functionDisplayName(functionDisplayName),
        asyncCause(asyncCause),
        parent(parent),
        principals(principals),
        framePtr(framePtr),
        pc(pc),
        activation(activation)
    {
        MOZ_ASSERT(source);
        MOZ_ASSERT_IF(framePtr.isSome(), activation);
#ifdef JS_MORE_DETERMINISTIC
        column = 0;
#endif
    }

    explicit Lookup(SavedFrame& savedFrame)
      : source(savedFrame.getSource()),
        line(savedFrame.getLine()),
        column(savedFrame.getColumn()),
        functionDisplayName(savedFrame.getFunctionDisplayName()),
        asyncCause(savedFrame.getAsyncCause()),
        parent(savedFrame.getParent()),
        principals(savedFrame.getPrincipals()),
        framePtr(Nothing()),
        pc(nullptr),
        activation(nullptr)
    {
        MOZ_ASSERT(source);
    }

    JSAtom*       source;
    uint32_t      line;
    uint32_t      column;
    JSAtom*       functionDisplayName;
    JSAtom*       asyncCause;
    SavedFrame*   parent;
    JSPrincipals* principals;

    // These are used only by the LiveSavedFrameCache and not used for identity or
    // hashing.
    Maybe<LiveSavedFrameCache::FramePtr> framePtr;
    jsbytecode*                          pc;
    Activation*                          activation;

    void trace(JSTracer* trc) {
        TraceManuallyBarrieredEdge(trc, &source, "SavedFrame::Lookup::source");
        if (functionDisplayName) {
            TraceManuallyBarrieredEdge(trc, &functionDisplayName,
                                       "SavedFrame::Lookup::functionDisplayName");
        }
        if (asyncCause)
            TraceManuallyBarrieredEdge(trc, &asyncCause, "SavedFrame::Lookup::asyncCause");
        if (parent)
            TraceManuallyBarrieredEdge(trc, &parent, "SavedFrame::Lookup::parent");
    }
};

class MOZ_STACK_CLASS SavedFrame::AutoLookupVector : public JS::CustomAutoRooter {
  public:
    explicit AutoLookupVector(JSContext* cx)
      : JS::CustomAutoRooter(cx),
        lookups(cx)
    { }

    typedef Vector<Lookup, ASYNC_STACK_MAX_FRAME_COUNT> LookupVector;
    inline LookupVector* operator->() { return &lookups; }
    inline HandleLookup operator[](size_t i) { return HandleLookup(lookups[i]); }
    inline HandleLookup back() { return HandleLookup(lookups.back()); }

  private:
    LookupVector lookups;

    virtual void trace(JSTracer* trc) override {
        for (size_t i = 0; i < lookups.length(); i++)
            lookups[i].trace(trc);
    }
};

/* static */ bool
SavedFrame::HashPolicy::hasHash(const Lookup& l)
{
    return SavedFramePtrHasher::hasHash(l.parent);
}

/* static */ bool
SavedFrame::HashPolicy::ensureHash(const Lookup& l)
{
    return SavedFramePtrHasher::ensureHash(l.parent);
}

/* static */ HashNumber
SavedFrame::HashPolicy::hash(const Lookup& lookup)
{
    JS::AutoCheckCannotGC nogc;
    // Assume that we can take line mod 2^32 without losing anything of
    // interest.  If that assumption changes, we'll just need to start with 0
    // and add another overload of AddToHash with more arguments.
    return AddToHash(lookup.line,
                     lookup.column,
                     lookup.source,
                     lookup.functionDisplayName,
                     lookup.asyncCause,
                     SavedFramePtrHasher::hash(lookup.parent),
                     JSPrincipalsPtrHasher::hash(lookup.principals));
}

/* static */ bool
SavedFrame::HashPolicy::match(SavedFrame* existing, const Lookup& lookup)
{
    MOZ_ASSERT(existing);

    if (existing->getLine() != lookup.line)
        return false;

    if (existing->getColumn() != lookup.column)
        return false;

    if (existing->getParent() != lookup.parent)
        return false;

    if (existing->getPrincipals() != lookup.principals)
        return false;

    JSAtom* source = existing->getSource();
    if (source != lookup.source)
        return false;

    JSAtom* functionDisplayName = existing->getFunctionDisplayName();
    if (functionDisplayName != lookup.functionDisplayName)
        return false;

    JSAtom* asyncCause = existing->getAsyncCause();
    if (asyncCause != lookup.asyncCause)
        return false;

    return true;
}

/* static */ void
SavedFrame::HashPolicy::rekey(Key& key, const Key& newKey)
{
    key = newKey;
}

/* static */ bool
SavedFrame::finishSavedFrameInit(JSContext* cx, HandleObject ctor, HandleObject proto)
{
    // The only object with the SavedFrame::class_ that doesn't have a source
    // should be the prototype.
    proto->as<NativeObject>().setReservedSlot(SavedFrame::JSSLOT_SOURCE, NullValue());

    return FreezeObject(cx, proto);
}

static const ClassOps SavedFrameClassOps = {
    nullptr,                    // addProperty
    nullptr,                    // delProperty
    nullptr,                    // enumerate
    nullptr,                    // newEnumerate
    nullptr,                    // resolve
    nullptr,                    // mayResolve
    SavedFrame::finalize,       // finalize
    nullptr,                    // call
    nullptr,                    // hasInstance
    nullptr,                    // construct
    nullptr,                    // trace
};

const ClassSpec SavedFrame::classSpec_ = {
    GenericCreateConstructor<SavedFrame::construct, 0, gc::AllocKind::FUNCTION>,
    GenericCreatePrototype,
    SavedFrame::staticFunctions,
    nullptr,
    SavedFrame::protoFunctions,
    SavedFrame::protoAccessors,
    SavedFrame::finishSavedFrameInit,
    ClassSpec::DontDefineConstructor
};

/* static */ const Class SavedFrame::class_ = {
    "SavedFrame",
    JSCLASS_HAS_PRIVATE |
    JSCLASS_HAS_RESERVED_SLOTS(SavedFrame::JSSLOT_COUNT) |
    JSCLASS_HAS_CACHED_PROTO(JSProto_SavedFrame) |
    JSCLASS_IS_ANONYMOUS |
    JSCLASS_FOREGROUND_FINALIZE,
    &SavedFrameClassOps,
    &SavedFrame::classSpec_
};

/* static */ const JSFunctionSpec
SavedFrame::staticFunctions[] = {
    JS_FS_END
};

/* static */ const JSFunctionSpec
SavedFrame::protoFunctions[] = {
    JS_FN("constructor", SavedFrame::construct, 0, 0),
    JS_FN("toString", SavedFrame::toStringMethod, 0, 0),
    JS_FS_END
};

/* static */ const JSPropertySpec
SavedFrame::protoAccessors[] = {
    JS_PSG("source", SavedFrame::sourceProperty, 0),
    JS_PSG("line", SavedFrame::lineProperty, 0),
    JS_PSG("column", SavedFrame::columnProperty, 0),
    JS_PSG("functionDisplayName", SavedFrame::functionDisplayNameProperty, 0),
    JS_PSG("asyncCause", SavedFrame::asyncCauseProperty, 0),
    JS_PSG("asyncParent", SavedFrame::asyncParentProperty, 0),
    JS_PSG("parent", SavedFrame::parentProperty, 0),
    JS_PS_END
};

/* static */ void
SavedFrame::finalize(FreeOp* fop, JSObject* obj)
{
    MOZ_ASSERT(fop->onMainThread());
    JSPrincipals* p = obj->as<SavedFrame>().getPrincipals();
    if (p) {
        JSRuntime* rt = obj->runtimeFromMainThread();
        JS_DropPrincipals(rt->mainContextFromOwnThread(), p);
    }
}

JSAtom*
SavedFrame::getSource()
{
    const Value& v = getReservedSlot(JSSLOT_SOURCE);
    JSString* s = v.toString();
    return &s->asAtom();
}

uint32_t
SavedFrame::getLine()
{
    const Value& v = getReservedSlot(JSSLOT_LINE);
    return v.toPrivateUint32();
}

uint32_t
SavedFrame::getColumn()
{
    const Value& v = getReservedSlot(JSSLOT_COLUMN);
    return v.toPrivateUint32();
}

JSAtom*
SavedFrame::getFunctionDisplayName()
{
    const Value& v = getReservedSlot(JSSLOT_FUNCTIONDISPLAYNAME);
    if (v.isNull())
        return nullptr;
    JSString* s = v.toString();
    return &s->asAtom();
}

JSAtom*
SavedFrame::getAsyncCause()
{
    const Value& v = getReservedSlot(JSSLOT_ASYNCCAUSE);
    if (v.isNull())
        return nullptr;
    JSString* s = v.toString();
    return &s->asAtom();
}

SavedFrame*
SavedFrame::getParent() const
{
    const Value& v = getReservedSlot(JSSLOT_PARENT);
    return v.isObject() ? &v.toObject().as<SavedFrame>() : nullptr;
}

JSPrincipals*
SavedFrame::getPrincipals()
{
    const Value& v = getReservedSlot(JSSLOT_PRINCIPALS);
    if (v.isUndefined())
        return nullptr;
    return static_cast<JSPrincipals*>(v.toPrivate());
}

void
SavedFrame::initSource(JSAtom* source)
{
    MOZ_ASSERT(source);
    initReservedSlot(JSSLOT_SOURCE, StringValue(source));
}

void
SavedFrame::initLine(uint32_t line)
{
    initReservedSlot(JSSLOT_LINE, PrivateUint32Value(line));
}

void
SavedFrame::initColumn(uint32_t column)
{
#ifdef JS_MORE_DETERMINISTIC
    column = 0;
#endif
    initReservedSlot(JSSLOT_COLUMN, PrivateUint32Value(column));
}

void
SavedFrame::initPrincipals(JSPrincipals* principals)
{
    if (principals)
        JS_HoldPrincipals(principals);
    initPrincipalsAlreadyHeld(principals);
}

void
SavedFrame::initPrincipalsAlreadyHeld(JSPrincipals* principals)
{
    MOZ_ASSERT_IF(principals, principals->refcount > 0);
    initReservedSlot(JSSLOT_PRINCIPALS, PrivateValue(principals));
}

void
SavedFrame::initFunctionDisplayName(JSAtom* maybeName)
{
    initReservedSlot(JSSLOT_FUNCTIONDISPLAYNAME, maybeName ? StringValue(maybeName) : NullValue());
}

void
SavedFrame::initAsyncCause(JSAtom* maybeCause)
{
    initReservedSlot(JSSLOT_ASYNCCAUSE, maybeCause ? StringValue(maybeCause) : NullValue());
}

void
SavedFrame::initParent(SavedFrame* maybeParent)
{
    initReservedSlot(JSSLOT_PARENT, ObjectOrNullValue(maybeParent));
}

void
SavedFrame::initFromLookup(JSContext* cx, SavedFrame::HandleLookup lookup)
{
    // Make sure any atoms used in the lookup are marked in the current zone.
    // Normally we would try to keep these mark bits up to date around the
    // points where the context moves between compartments, but Lookups live on
    // the stack (where the atoms are kept alive regardless) and this is a
    // more convenient pinchpoint.
    if (lookup->source)
        cx->markAtom(lookup->source);
    if (lookup->functionDisplayName)
        cx->markAtom(lookup->functionDisplayName);
    if (lookup->asyncCause)
        cx->markAtom(lookup->asyncCause);

    initSource(lookup->source);
    initLine(lookup->line);
    initColumn(lookup->column);
    initFunctionDisplayName(lookup->functionDisplayName);
    initAsyncCause(lookup->asyncCause);
    initParent(lookup->parent);
    initPrincipals(lookup->principals);
}

/* static */ SavedFrame*
SavedFrame::create(JSContext* cx)
{
    RootedGlobalObject global(cx, cx->global());
    cx->check(global);

    // Ensure that we don't try to capture the stack again in the
    // `SavedStacksMetadataBuilder` for this new SavedFrame object, and
    // accidentally cause O(n^2) behavior.
    SavedStacks::AutoReentrancyGuard guard(cx->realm()->savedStacks());

    RootedNativeObject proto(cx, GlobalObject::getOrCreateSavedFramePrototype(cx, global));
    if (!proto)
        return nullptr;
    cx->check(proto);

    return NewObjectWithGivenProto<SavedFrame>(cx, proto, TenuredObject);
}

bool
SavedFrame::isSelfHosted(JSContext* cx)
{
    JSAtom* source = getSource();
    return source == cx->names().selfHosted;
}

bool
SavedFrame::isWasm()
{
    // See WasmFrameIter::computeLine() comment.
    return bool(getColumn() & wasm::WasmFrameIter::ColumnBit);
}

uint32_t
SavedFrame::wasmFuncIndex()
{
    // See WasmFrameIter::computeLine() comment.
    MOZ_ASSERT(isWasm());
    return getColumn() & ~wasm::WasmFrameIter::ColumnBit;
}

uint32_t
SavedFrame::wasmBytecodeOffset()
{
    // See WasmFrameIter::computeLine() comment.
    MOZ_ASSERT(isWasm());
    return getLine();
}

/* static */ bool
SavedFrame::construct(JSContext* cx, unsigned argc, Value* vp)
{
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_NO_CONSTRUCTOR,
                              "SavedFrame");
    return false;
}

static bool
SavedFrameSubsumedByPrincipals(JSContext* cx, JSPrincipals* principals, HandleSavedFrame frame)
{
    auto subsumes = cx->runtime()->securityCallbacks->subsumes;
    if (!subsumes)
        return true;

    MOZ_ASSERT(!ReconstructedSavedFramePrincipals::is(principals));

    auto framePrincipals = frame->getPrincipals();

    // Handle SavedFrames that have been reconstructed from stacks in a heap
    // snapshot.
    if (framePrincipals == &ReconstructedSavedFramePrincipals::IsSystem)
        return cx->runningWithTrustedPrincipals();
    if (framePrincipals == &ReconstructedSavedFramePrincipals::IsNotSystem)
        return true;

    return subsumes(principals, framePrincipals);
}

// Return the first SavedFrame in the chain that starts with |frame| whose
// for which the given match function returns true. If there is no such frame,
// return nullptr. |skippedAsync| is set to true if any of the skipped frames
// had the |asyncCause| property set, otherwise it is explicitly set to false.
template<typename Matcher>
static SavedFrame*
GetFirstMatchedFrame(JSContext* cx, JSPrincipals* principals, Matcher& matches,
                     HandleSavedFrame frame, JS::SavedFrameSelfHosted selfHosted,
                     bool& skippedAsync)
{
    skippedAsync = false;

    RootedSavedFrame rootedFrame(cx, frame);
    while (rootedFrame) {
        if ((selfHosted == JS::SavedFrameSelfHosted::Include ||
             !rootedFrame->isSelfHosted(cx)) &&
            matches(cx, principals, rootedFrame))
        {
            return rootedFrame;
        }

        if (rootedFrame->getAsyncCause())
            skippedAsync = true;

        rootedFrame = rootedFrame->getParent();
    }

    return nullptr;
}

// Return the first SavedFrame in the chain that starts with |frame| whose
// principals are subsumed by |principals|, according to |subsumes|. If there is
// no such frame, return nullptr. |skippedAsync| is set to true if any of the
// skipped frames had the |asyncCause| property set, otherwise it is explicitly
// set to false.
static SavedFrame*
GetFirstSubsumedFrame(JSContext* cx, JSPrincipals* principals, HandleSavedFrame frame,
                      JS::SavedFrameSelfHosted selfHosted, bool& skippedAsync)
{
    return GetFirstMatchedFrame(cx, principals, SavedFrameSubsumedByPrincipals, frame, selfHosted,
                                skippedAsync);
}

JS_FRIEND_API(JSObject*)
GetFirstSubsumedSavedFrame(JSContext* cx, JSPrincipals* principals,
                           HandleObject savedFrame,
                           JS::SavedFrameSelfHosted selfHosted)
{
    if (!savedFrame)
        return nullptr;

    auto subsumes = cx->runtime()->securityCallbacks->subsumes;
    if (!subsumes)
        return nullptr;

    auto matcher =
    [subsumes](JSContext* cx, JSPrincipals* principals, HandleSavedFrame frame) -> bool {
        return subsumes(principals, frame->getPrincipals());
    };

    bool skippedAsync;
    RootedSavedFrame frame(cx, &savedFrame->as<SavedFrame>());
    return GetFirstMatchedFrame(cx, principals, matcher, frame, selfHosted, skippedAsync);
}

static MOZ_MUST_USE bool
SavedFrame_checkThis(JSContext* cx, CallArgs& args, const char* fnName,
                     MutableHandleObject frame)
{
    const Value& thisValue = args.thisv();

    if (!thisValue.isObject()) {
        JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_NOT_NONNULL_OBJECT,
                                  InformalValueTypeName(thisValue));
        return false;
    }

    JSObject* thisObject = CheckedUnwrap(&thisValue.toObject());
    if (!thisObject || !thisObject->is<SavedFrame>()) {
        JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_INCOMPATIBLE_PROTO,
                                  SavedFrame::class_.name, fnName,
                                  thisObject ? thisObject->getClass()->name : "object");
        return false;
    }

    // Check for SavedFrame.prototype, which has the same class as SavedFrame
    // instances, however doesn't actually represent a captured stack frame. It
    // is the only object that is<SavedFrame>() but doesn't have a source.
    if (!SavedFrame::isSavedFrameAndNotProto(*thisObject)) {
        JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_INCOMPATIBLE_PROTO,
                                  SavedFrame::class_.name, fnName, "prototype object");
        return false;
    }

    // Now set "frame" to the actual object we were invoked in (which may be a
    // wrapper), not the unwrapped version.  Consumers will need to know what
    // that original object was, and will do principal checks as needed.
    frame.set(&thisValue.toObject());
    return true;
}

// Get the SavedFrame * from the current this value and handle any errors that
// might occur therein.
//
// These parameters must already exist when calling this macro:
//   - JSContext* cx
//   - unsigned   argc
//   - Value*     vp
//   - const char* fnName
// These parameters will be defined after calling this macro:
//   - CallArgs args
//   - Rooted<SavedFrame*> frame (will be non-null)
#define THIS_SAVEDFRAME(cx, argc, vp, fnName, args, frame)             \
    CallArgs args = CallArgsFromVp(argc, vp);                          \
    RootedObject frame(cx);                                            \
    if (!SavedFrame_checkThis(cx, args, fnName, &frame))               \
        return false;

} /* namespace js */

namespace JS {

static inline js::SavedFrame*
UnwrapSavedFrame(JSContext* cx, JSPrincipals* principals, HandleObject obj,
                 SavedFrameSelfHosted selfHosted, bool& skippedAsync)
{
    if (!obj)
        return nullptr;

    RootedObject savedFrameObj(cx, CheckedUnwrap(obj));
    if (!savedFrameObj)
        return nullptr;

    MOZ_RELEASE_ASSERT(js::SavedFrame::isSavedFrameAndNotProto(*savedFrameObj));
    js::RootedSavedFrame frame(cx, &savedFrameObj->as<js::SavedFrame>());
    return GetFirstSubsumedFrame(cx, principals, frame, selfHosted, skippedAsync);
}

JS_PUBLIC_API(SavedFrameResult)
GetSavedFrameSource(JSContext* cx, JSPrincipals* principals, HandleObject savedFrame,
                    MutableHandleString sourcep,
                    SavedFrameSelfHosted selfHosted /* = SavedFrameSelfHosted::Include */)
{
    js::AssertHeapIsIdle();
    CHECK_THREAD(cx);
    MOZ_RELEASE_ASSERT(cx->realm());

    {
        bool skippedAsync;
        js::RootedSavedFrame frame(cx, UnwrapSavedFrame(cx, principals, savedFrame, selfHosted,
                                                        skippedAsync));
        if (!frame) {
            sourcep.set(cx->runtime()->emptyString);
            return SavedFrameResult::AccessDenied;
        }
        sourcep.set(frame->getSource());
    }
    if (sourcep->isAtom())
        cx->markAtom(&sourcep->asAtom());
    return SavedFrameResult::Ok;
}

JS_PUBLIC_API(SavedFrameResult)
GetSavedFrameLine(JSContext* cx, JSPrincipals* principals, HandleObject savedFrame,
                  uint32_t* linep,
                  SavedFrameSelfHosted selfHosted /* = SavedFrameSelfHosted::Include */)
{
    js::AssertHeapIsIdle();
    CHECK_THREAD(cx);
    MOZ_RELEASE_ASSERT(cx->realm());
    MOZ_ASSERT(linep);

    bool skippedAsync;
    js::RootedSavedFrame frame(cx, UnwrapSavedFrame(cx, principals, savedFrame, selfHosted,
                                                    skippedAsync));
    if (!frame) {
        *linep = 0;
        return SavedFrameResult::AccessDenied;
    }
    *linep = frame->getLine();
    return SavedFrameResult::Ok;
}

JS_PUBLIC_API(SavedFrameResult)
GetSavedFrameColumn(JSContext* cx, JSPrincipals* principals, HandleObject savedFrame,
                    uint32_t* columnp,
                    SavedFrameSelfHosted selfHosted /* = SavedFrameSelfHosted::Include */)
{
    js::AssertHeapIsIdle();
    CHECK_THREAD(cx);
    MOZ_RELEASE_ASSERT(cx->realm());
    MOZ_ASSERT(columnp);

    bool skippedAsync;
    js::RootedSavedFrame frame(cx, UnwrapSavedFrame(cx, principals, savedFrame, selfHosted,
                                                    skippedAsync));
    if (!frame) {
        *columnp = 0;
        return SavedFrameResult::AccessDenied;
    }
    *columnp = frame->getColumn();
    return SavedFrameResult::Ok;
}

JS_PUBLIC_API(SavedFrameResult)
GetSavedFrameFunctionDisplayName(JSContext* cx, JSPrincipals* principals, HandleObject savedFrame,
                                 MutableHandleString namep,
                                 SavedFrameSelfHosted selfHosted /* = SavedFrameSelfHosted::Include */)
{
    js::AssertHeapIsIdle();
    CHECK_THREAD(cx);
    MOZ_RELEASE_ASSERT(cx->realm());

    {
        bool skippedAsync;
        js::RootedSavedFrame frame(cx, UnwrapSavedFrame(cx, principals, savedFrame, selfHosted,
                                                        skippedAsync));
        if (!frame) {
            namep.set(nullptr);
            return SavedFrameResult::AccessDenied;
        }
        namep.set(frame->getFunctionDisplayName());
    }
    if (namep && namep->isAtom())
        cx->markAtom(&namep->asAtom());
    return SavedFrameResult::Ok;
}

JS_PUBLIC_API(SavedFrameResult)
GetSavedFrameAsyncCause(JSContext* cx, JSPrincipals* principals, HandleObject savedFrame,
                        MutableHandleString asyncCausep,
                        SavedFrameSelfHosted unused_ /* = SavedFrameSelfHosted::Include */)
{
    js::AssertHeapIsIdle();
    CHECK_THREAD(cx);
    MOZ_RELEASE_ASSERT(cx->realm());

    {
        bool skippedAsync;
        // This function is always called with self-hosted frames excluded by
        // GetValueIfNotCached in dom/bindings/Exceptions.cpp. However, we want
        // to include them because our Promise implementation causes us to have
        // the async cause on a self-hosted frame. So we just ignore the
        // parameter and always include self-hosted frames.
        js::RootedSavedFrame frame(cx, UnwrapSavedFrame(cx, principals, savedFrame,
                                                        SavedFrameSelfHosted::Include,
                                                        skippedAsync));
        if (!frame) {
            asyncCausep.set(nullptr);
            return SavedFrameResult::AccessDenied;
        }
        asyncCausep.set(frame->getAsyncCause());
        if (!asyncCausep && skippedAsync)
            asyncCausep.set(cx->names().Async);
    }
    if (asyncCausep && asyncCausep->isAtom())
        cx->markAtom(&asyncCausep->asAtom());
    return SavedFrameResult::Ok;
}

JS_PUBLIC_API(SavedFrameResult)
GetSavedFrameAsyncParent(JSContext* cx, JSPrincipals* principals, HandleObject savedFrame,
                         MutableHandleObject asyncParentp,
                         SavedFrameSelfHosted selfHosted /* = SavedFrameSelfHosted::Include */)
{
    js::AssertHeapIsIdle();
    CHECK_THREAD(cx);
    MOZ_RELEASE_ASSERT(cx->realm());

    bool skippedAsync;
    js::RootedSavedFrame frame(cx, UnwrapSavedFrame(cx, principals, savedFrame, selfHosted,
                                                    skippedAsync));
    if (!frame) {
        asyncParentp.set(nullptr);
        return SavedFrameResult::AccessDenied;
    }
    js::RootedSavedFrame parent(cx, frame->getParent());

    // The current value of |skippedAsync| is not interesting, because we are
    // interested in whether we would cross any async parents to get from here
    // to the first subsumed parent frame instead.
    js::RootedSavedFrame subsumedParent(cx, GetFirstSubsumedFrame(cx, principals, parent,
                                                                  selfHosted, skippedAsync));

    // Even if |parent| is not subsumed, we still want to return a pointer to it
    // rather than |subsumedParent| so it can pick up any |asyncCause| from the
    // inaccessible part of the chain.
    if (subsumedParent && (subsumedParent->getAsyncCause() || skippedAsync))
        asyncParentp.set(parent);
    else
        asyncParentp.set(nullptr);
    return SavedFrameResult::Ok;
}

JS_PUBLIC_API(SavedFrameResult)
GetSavedFrameParent(JSContext* cx, JSPrincipals* principals, HandleObject savedFrame,
                    MutableHandleObject parentp,
                    SavedFrameSelfHosted selfHosted /* = SavedFrameSelfHosted::Include */)
{
    js::AssertHeapIsIdle();
    CHECK_THREAD(cx);
    MOZ_RELEASE_ASSERT(cx->realm());

    bool skippedAsync;
    js::RootedSavedFrame frame(cx, UnwrapSavedFrame(cx, principals, savedFrame, selfHosted,
                                                    skippedAsync));
    if (!frame) {
        parentp.set(nullptr);
        return SavedFrameResult::AccessDenied;
    }
    js::RootedSavedFrame parent(cx, frame->getParent());

    // The current value of |skippedAsync| is not interesting, because we are
    // interested in whether we would cross any async parents to get from here
    // to the first subsumed parent frame instead.
    js::RootedSavedFrame subsumedParent(cx, GetFirstSubsumedFrame(cx, principals, parent,
                                                                  selfHosted, skippedAsync));

    // Even if |parent| is not subsumed, we still want to return a pointer to it
    // rather than |subsumedParent| so it can pick up any |asyncCause| from the
    // inaccessible part of the chain.
    if (subsumedParent && !(subsumedParent->getAsyncCause() || skippedAsync))
        parentp.set(parent);
    else
        parentp.set(nullptr);
    return SavedFrameResult::Ok;
}

static bool
FormatStackFrameLine(JSContext* cx, js::StringBuffer& sb, js::HandleSavedFrame frame)
{
    if (frame->isWasm()) {
        // See comment in WasmFrameIter::computeLine().
        return sb.append("wasm-function[")
            && NumberValueToStringBuffer(cx, NumberValue(frame->wasmFuncIndex()), sb)
            && sb.append(']');
    }

    return NumberValueToStringBuffer(cx, NumberValue(frame->getLine()), sb);
}

static bool
FormatStackFrameColumn(JSContext* cx, js::StringBuffer& sb, js::HandleSavedFrame frame)
{
    if (frame->isWasm()) {
        // See comment in WasmFrameIter::computeLine().
        js::ToCStringBuf cbuf;
        const char* cstr = NumberToCString(cx, &cbuf, frame->wasmBytecodeOffset(), 16);
        if (!cstr)
            return false;

        return sb.append("0x")
            && sb.append(cstr, strlen(cstr));
    }

    return NumberValueToStringBuffer(cx, NumberValue(frame->getColumn()), sb);
}

static bool
FormatSpiderMonkeyStackFrame(JSContext* cx, js::StringBuffer& sb,
                             js::HandleSavedFrame frame, size_t indent,
                             bool skippedAsync)
{
    RootedString asyncCause(cx, frame->getAsyncCause());
    if (!asyncCause && skippedAsync)
        asyncCause.set(cx->names().Async);

    js::RootedAtom name(cx, frame->getFunctionDisplayName());
    return (!indent || sb.appendN(' ', indent))
        && (!asyncCause || (sb.append(asyncCause) && sb.append('*')))
        && (!name || sb.append(name))
        && sb.append('@')
        && sb.append(frame->getSource())
        && sb.append(':')
        && FormatStackFrameLine(cx, sb, frame)
        && sb.append(':')
        && FormatStackFrameColumn(cx, sb, frame)
        && sb.append('\n');
}

static bool
FormatV8StackFrame(JSContext* cx, js::StringBuffer& sb,
                   js::HandleSavedFrame frame, size_t indent, bool lastFrame)
{
    js::RootedAtom name(cx, frame->getFunctionDisplayName());
    return sb.appendN(' ', indent + 4)
        && sb.append('a')
        && sb.append('t')
        && sb.append(' ')
        && (!name || (sb.append(name) &&
                      sb.append(' ') &&
                      sb.append('(')))
        && sb.append(frame->getSource())
        && sb.append(':')
        && FormatStackFrameLine(cx, sb, frame)
        && sb.append(':')
        && FormatStackFrameColumn(cx, sb, frame)
        && (!name || sb.append(')'))
        && (lastFrame || sb.append('\n'));
}

JS_PUBLIC_API(bool)
BuildStackString(JSContext* cx, JSPrincipals* principals, HandleObject stack,
                 MutableHandleString stringp, size_t indent, js::StackFormat format)
{
    js::AssertHeapIsIdle();
    CHECK_THREAD(cx);
    MOZ_RELEASE_ASSERT(cx->realm());

    js::StringBuffer sb(cx);

    if (format == js::StackFormat::Default)
        format = cx->runtime()->stackFormat();
    MOZ_ASSERT(format != js::StackFormat::Default);

    // Enter a new block to constrain the scope of possibly entering the stack's
    // realm. This ensures that when we finish the StringBuffer, we are back in
    // the cx's original compartment, and fulfill our contract with callers to
    // place the output string in the cx's current realm.
    {
        bool skippedAsync;
        js::RootedSavedFrame frame(cx, UnwrapSavedFrame(cx, principals, stack,
                                                        SavedFrameSelfHosted::Exclude,
                                                        skippedAsync));
        if (!frame) {
            stringp.set(cx->runtime()->emptyString);
            return true;
        }

        js::RootedSavedFrame parent(cx);
        do {
            MOZ_ASSERT(SavedFrameSubsumedByPrincipals(cx, principals, frame));
            MOZ_ASSERT(!frame->isSelfHosted(cx));

            parent = frame->getParent();
            bool skippedNextAsync;
            js::RootedSavedFrame nextFrame(cx, js::GetFirstSubsumedFrame(cx, principals, parent,
                                                                         SavedFrameSelfHosted::Exclude, skippedNextAsync));

            switch (format) {
                case js::StackFormat::SpiderMonkey:
                    if (!FormatSpiderMonkeyStackFrame(cx, sb, frame, indent, skippedAsync))
                        return false;
                    break;
                case js::StackFormat::V8:
                    if (!FormatV8StackFrame(cx, sb, frame, indent, !nextFrame))
                        return false;
                    break;
                case js::StackFormat::Default:
                    MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Unexpected value");
                    break;
            }

            frame = nextFrame;
            skippedAsync = skippedNextAsync;
        } while (frame);
    }

    JSString* str = sb.finishString();
    if (!str)
        return false;
    cx->check(str);
    stringp.set(str);
    return true;
}

JS_PUBLIC_API(bool)
IsMaybeWrappedSavedFrame(JSObject* obj)
{
    MOZ_ASSERT(obj);
    return js::SavedFrame::isSavedFrameOrWrapperAndNotProto(*obj);
}

JS_PUBLIC_API(bool)
IsUnwrappedSavedFrame(JSObject* obj)
{
    MOZ_ASSERT(obj);
    return js::SavedFrame::isSavedFrameAndNotProto(*obj);
}

} /* namespace JS */

namespace js {

/* static */ bool
SavedFrame::sourceProperty(JSContext* cx, unsigned argc, Value* vp)
{
    THIS_SAVEDFRAME(cx, argc, vp, "(get source)", args, frame);
    JSPrincipals* principals = cx->realm()->principals();
    RootedString source(cx);
    if (JS::GetSavedFrameSource(cx, principals, frame, &source) == JS::SavedFrameResult::Ok) {
        if (!cx->compartment()->wrap(cx, &source))
            return false;
        args.rval().setString(source);
    } else {
        args.rval().setNull();
    }
    return true;
}

/* static */ bool
SavedFrame::lineProperty(JSContext* cx, unsigned argc, Value* vp)
{
    THIS_SAVEDFRAME(cx, argc, vp, "(get line)", args, frame);
    JSPrincipals* principals = cx->realm()->principals();
    uint32_t line;
    if (JS::GetSavedFrameLine(cx, principals, frame, &line) == JS::SavedFrameResult::Ok)
        args.rval().setNumber(line);
    else
        args.rval().setNull();
    return true;
}

/* static */ bool
SavedFrame::columnProperty(JSContext* cx, unsigned argc, Value* vp)
{
    THIS_SAVEDFRAME(cx, argc, vp, "(get column)", args, frame);
    JSPrincipals* principals = cx->realm()->principals();
    uint32_t column;
    if (JS::GetSavedFrameColumn(cx, principals, frame, &column) == JS::SavedFrameResult::Ok)
        args.rval().setNumber(column);
    else
        args.rval().setNull();
    return true;
}

/* static */ bool
SavedFrame::functionDisplayNameProperty(JSContext* cx, unsigned argc, Value* vp)
{
    THIS_SAVEDFRAME(cx, argc, vp, "(get functionDisplayName)", args, frame);
    JSPrincipals* principals = cx->realm()->principals();
    RootedString name(cx);
    JS::SavedFrameResult result =
        JS::GetSavedFrameFunctionDisplayName(cx, principals, frame, &name);
    if (result == JS::SavedFrameResult::Ok && name) {
        if (!cx->compartment()->wrap(cx, &name))
            return false;
        args.rval().setString(name);
    } else {
        args.rval().setNull();
    }
    return true;
}

/* static */ bool
SavedFrame::asyncCauseProperty(JSContext* cx, unsigned argc, Value* vp)
{
    THIS_SAVEDFRAME(cx, argc, vp, "(get asyncCause)", args, frame);
    JSPrincipals* principals = cx->realm()->principals();
    RootedString asyncCause(cx);
    JS::SavedFrameResult result = JS::GetSavedFrameAsyncCause(cx, principals, frame, &asyncCause);
    if (result == JS::SavedFrameResult::Ok && asyncCause) {
        if (!cx->compartment()->wrap(cx, &asyncCause))
            return false;
        args.rval().setString(asyncCause);
    } else {
        args.rval().setNull();
    }
    return true;
}

/* static */ bool
SavedFrame::asyncParentProperty(JSContext* cx, unsigned argc, Value* vp)
{
    THIS_SAVEDFRAME(cx, argc, vp, "(get asyncParent)", args, frame);
    JSPrincipals* principals = cx->realm()->principals();
    RootedObject asyncParent(cx);
    (void) JS::GetSavedFrameAsyncParent(cx, principals, frame, &asyncParent);
    if (!cx->compartment()->wrap(cx, &asyncParent))
        return false;
    args.rval().setObjectOrNull(asyncParent);
    return true;
}

/* static */ bool
SavedFrame::parentProperty(JSContext* cx, unsigned argc, Value* vp)
{
    THIS_SAVEDFRAME(cx, argc, vp, "(get parent)", args, frame);
    JSPrincipals* principals = cx->realm()->principals();
    RootedObject parent(cx);
    (void) JS::GetSavedFrameParent(cx, principals, frame, &parent);
    if (!cx->compartment()->wrap(cx, &parent))
        return false;
    args.rval().setObjectOrNull(parent);
    return true;
}

/* static */ bool
SavedFrame::toStringMethod(JSContext* cx, unsigned argc, Value* vp)
{
    THIS_SAVEDFRAME(cx, argc, vp, "toString", args, frame);
    JSPrincipals* principals = cx->realm()->principals();
    RootedString string(cx);
    if (!JS::BuildStackString(cx, principals, frame, &string))
        return false;
    args.rval().setString(string);
    return true;
}

bool
SavedStacks::saveCurrentStack(JSContext* cx, MutableHandleSavedFrame frame,
                              JS::StackCapture&& capture /* = JS::StackCapture(JS::AllFrames()) */)
{
    MOZ_RELEASE_ASSERT(cx->realm());
    MOZ_DIAGNOSTIC_ASSERT(&cx->realm()->savedStacks() == this);

    if (creatingSavedFrame ||
        cx->isExceptionPending() ||
        !cx->global() ||
        !cx->global()->isStandardClassResolved(JSProto_Object))
    {
        frame.set(nullptr);
        return true;
    }

    AutoGeckoProfilerEntry labelFrame(cx, "js::SavedStacks::saveCurrentStack");
    return insertFrames(cx, frame, std::move(capture));
}

bool
SavedStacks::copyAsyncStack(JSContext* cx, HandleObject asyncStack, HandleString asyncCause,
                            MutableHandleSavedFrame adoptedStack,
                            const Maybe<size_t>& maxFrameCount)
{
    MOZ_RELEASE_ASSERT(cx->realm());
    MOZ_DIAGNOSTIC_ASSERT(&cx->realm()->savedStacks() == this);

    RootedAtom asyncCauseAtom(cx, AtomizeString(cx, asyncCause));
    if (!asyncCauseAtom)
        return false;

    RootedObject asyncStackObj(cx, CheckedUnwrap(asyncStack));
    MOZ_RELEASE_ASSERT(asyncStackObj);
    MOZ_RELEASE_ASSERT(js::SavedFrame::isSavedFrameAndNotProto(*asyncStackObj));
    adoptedStack.set(&asyncStackObj->as<js::SavedFrame>());

    if (!adoptAsyncStack(cx, adoptedStack, asyncCauseAtom, maxFrameCount))
        return false;

    return true;
}

void
SavedStacks::sweep()
{
    frames.sweep();
    pcLocationMap.sweep();
}

void
SavedStacks::trace(JSTracer* trc)
{
    pcLocationMap.trace(trc);
}

uint32_t
SavedStacks::count()
{
    return frames.count();
}

void
SavedStacks::clear()
{
    frames.clear();
}

size_t
SavedStacks::sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf)
{
    return frames.shallowSizeOfExcludingThis(mallocSizeOf) +
           pcLocationMap.shallowSizeOfExcludingThis(mallocSizeOf);
}

// Given that we have captured a stack frame with the given principals and
// source, return true if the requested `StackCapture` has been satisfied and
// stack walking can halt. Return false otherwise (and stack walking and frame
// capturing should continue).
static inline bool
captureIsSatisfied(JSContext* cx, JSPrincipals* principals, const JSAtom* source,
                   JS::StackCapture& capture)
{
    class Matcher
    {
        JSContext* cx_;
        JSPrincipals* framePrincipals_;
        const JSAtom* frameSource_;

      public:
        Matcher(JSContext* cx, JSPrincipals* principals, const JSAtom* source)
          : cx_(cx)
          , framePrincipals_(principals)
          , frameSource_(source)
        { }

        bool match(JS::FirstSubsumedFrame& target) {
            auto subsumes = cx_->runtime()->securityCallbacks->subsumes;
            return (!subsumes || subsumes(target.principals, framePrincipals_)) &&
                   (!target.ignoreSelfHosted || frameSource_ != cx_->names().selfHosted);
        }

        bool match(JS::MaxFrames& target) {
            return target.maxFrames == 1;
        }

        bool match(JS::AllFrames&) {
            return false;
        }
    };

    Matcher m(cx, principals, source);
    return capture.match(m);
}

bool
SavedStacks::insertFrames(JSContext* cx, MutableHandleSavedFrame frame,
                          JS::StackCapture&& capture)
{
    // In order to look up a cached SavedFrame object, we need to have its parent
    // SavedFrame, which means we need to walk the stack from oldest frame to
    // youngest. However, FrameIter walks the stack from youngest frame to
    // oldest. The solution is to append stack frames to a vector as we walk the
    // stack with FrameIter, and then do a second pass through that vector in
    // reverse order after the traversal has completed and get or create the
    // SavedFrame objects at that time.
    //
    // To avoid making many copies of FrameIter (whose copy constructor is
    // relatively slow), we use a vector of `SavedFrame::Lookup` objects, which
    // only contain the FrameIter data we need. The `SavedFrame::Lookup`
    // objects are partially initialized with everything except their parent
    // pointers on the first pass, and then we fill in the parent pointers as we
    // return in the second pass.

    // Accumulate the vector of Lookup objects here, youngest to oldest.
    SavedFrame::AutoLookupVector stackChain(cx);

    // If we find an async parent or a cached saved frame, then that supplies
    // the parent of the frames we have placed in stackChain. If we walk the
    // stack all the way to the end, this remains null.
    RootedSavedFrame parent(cx, nullptr);

    // Choose the right frame iteration strategy to accomodate both
    // evalInFramePrev links and the LiveSavedFrameCache. For background, see
    // the LiveSavedFrameCache comments in Stack.h.
    //
    // If we're using the LiveSavedFrameCache, then don't handle evalInFramePrev
    // links by skipping over the frames altogether; that violates the cache's
    // assumptions. Instead, traverse the entire stack, but choose each
    // SavedFrame's parent as directed by the evalInFramePrev link, if any.
    //
    // If we're not using the LiveSavedFrameCache, it's hard to recover the
    // frame to which the evalInFramePrev link refers, so we just let FrameIter
    // skip those frames. Then each SavedFrame's parent is simply the frame that
    // follows it in the stackChain vector, even when it has an evalInFramePrev
    // link.
    FrameIter iter(cx,
                   capture.is<JS::AllFrames>()
                   ? FrameIter::IGNORE_DEBUGGER_EVAL_PREV_LINK
                   : FrameIter::FOLLOW_DEBUGGER_EVAL_PREV_LINK);

    // Once we've seen one frame with its hasCachedSavedFrame bit set, all its
    // parents (that can be cached) ought to have it set too.
    DebugOnly<bool> seenCached = false;

    while (!iter.done()) {
        Activation& activation = *iter.activation();
        Maybe<LiveSavedFrameCache::FramePtr> framePtr = LiveSavedFrameCache::FramePtr::create(iter);

        if (framePtr) {
            MOZ_ASSERT_IF(seenCached, framePtr->hasCachedSavedFrame());
            seenCached |= framePtr->hasCachedSavedFrame();
        }

        if (capture.is<JS::AllFrames>() && framePtr && framePtr->hasCachedSavedFrame())
        {
            auto* cache = activation.getLiveSavedFrameCache(cx);
            if (!cache)
                return false;
            cache->find(cx, *framePtr, iter.pc(), &parent);

            // Even though iter.hasCachedSavedFrame() was true, we can't
            // necessarily stop walking the stack here. We can get cache misses
            // for two reasons:
            // 1) This is the youngest valid frame in the cache, and it has run
            //    code and advanced to a new pc since it was cached.
            // 2) The cache was populated with SavedFrames captured for a
            //    different compartment, and got purged completely. We will
            //    repopulate it from scratch.
            if (parent)
                break;
        }

        // We'll be pushing this frame onto stackChain. Gather the information
        // needed to construct the SavedFrame::Lookup.
        Rooted<LocationValue> location(cx);
        {
            AutoRealmUnchecked ar(cx, iter.realm());
            if (!cx->realm()->savedStacks().getLocation(cx, iter, &location))
                return false;
        }

        RootedAtom displayAtom(cx, iter.maybeFunctionDisplayAtom());

        auto principals = iter.realm()->principals();
        MOZ_ASSERT_IF(framePtr && !iter.isWasm(), iter.pc());

        if (!stackChain->emplaceBack(location.source(),
                                     location.line(),
                                     location.column(),
                                     displayAtom,
                                     nullptr, // asyncCause
                                     nullptr, // parent (not known yet)
                                     principals,
                                     framePtr,
                                     iter.pc(),
                                     &activation))
        {
            ReportOutOfMemory(cx);
            return false;
        }

        if (captureIsSatisfied(cx, principals, location.source(), capture)) {
            // The stack should end after the frame we just saved.
            parent.set(nullptr);
            break;
        }

        ++iter;
        framePtr = LiveSavedFrameCache::FramePtr::create(iter);

        if (iter.activation() != &activation && capture.is<JS::AllFrames>()) {
            // If there were no cache hits in the entire activation, clear its
            // cache so we'll be able to push new ones when we build the
            // SavedFrame chain.
            activation.clearLiveSavedFrameCache();
        }

        // If we have crossed into a new activation, check whether the prior
        // activation had an async parent set.
        //
        // If the async call was explicit (async function resumptions, most
        // testing facilities), then the async parent stack has priority over
        // any actual frames still on the JavaScript stack. If the async call
        // was implicit (DOM CallbackObject::CallSetup calls), then the async
        // parent stack is used only if there were no other frames on the
        // stack.
        //
        // Captures using FirstSubsumedFrame expect us to ignore async parents.
        if (iter.activation() != &activation &&
            activation.asyncStack() &&
            (activation.asyncCallIsExplicit() || iter.done()) &&
            !capture.is<JS::FirstSubsumedFrame>())
        {
            // Atomize the async cause string. There should only be a few
            // different strings used.
            const char* cause = activation.asyncCause();
            RootedAtom causeAtom(cx, AtomizeUTF8Chars(cx, cause, strlen(cause)));
            if (!causeAtom)
                return false;

            // Translate our capture into a frame count limit for
            // adoptAsyncStack, which will impose further limits.
            Maybe<size_t> maxFrames =
                !capture.is<JS::MaxFrames>() ? Nothing()
                : capture.as<JS::MaxFrames>().maxFrames == 0 ? Nothing()
                : Some(capture.as<JS::MaxFrames>().maxFrames);

            // Clip the stack if needed, attach the async cause string to the
            // top frame, and copy it into our compartment if necessary.
            parent.set(activation.asyncStack());
            if (!adoptAsyncStack(cx, &parent, causeAtom, maxFrames))
                return false;
            break;
        }

        if (capture.is<JS::MaxFrames>())
            capture.as<JS::MaxFrames>().maxFrames--;
    }

    // Iterate through |stackChain| in reverse order and get or create the
    // actual SavedFrame instances.
    frame.set(parent);
    for (size_t i = stackChain->length(); i != 0; i--) {
        SavedFrame::HandleLookup lookup = stackChain[i-1];
        lookup->parent = frame;

        // If necessary, adjust the parent of a debugger eval frame to point to
        // the frame in whose scope the eval occurs - if we're using
        // LiveSavedFrameCache. Otherwise, we simply ask the FrameIter to follow
        // evalInFramePrev links, so that the parent is always the last frame we
        // created.
        if (capture.is<JS::AllFrames>() && lookup->framePtr) {
            if (!checkForEvalInFramePrev(cx, lookup))
                return false;
        }

        frame.set(getOrCreateSavedFrame(cx, lookup));
        if (!frame)
            return false;

        if (capture.is<JS::AllFrames>() && lookup->framePtr) {
            auto* cache = lookup->activation->getLiveSavedFrameCache(cx);
            if (!cache || !cache->insert(cx, *lookup->framePtr, lookup->pc, frame))
                return false;
        }
    }

    return true;
}

bool
SavedStacks::adoptAsyncStack(JSContext* cx, MutableHandleSavedFrame asyncStack,
                             HandleAtom asyncCause,
                             const Maybe<size_t>& maxFrameCount)
{
    MOZ_ASSERT(asyncStack);
    MOZ_ASSERT(asyncCause);

    // If maxFrameCount is Nothing, the caller asked for an unlimited number of
    // stack frames, but async stacks are not limited by the available stack
    // memory, so we need to set an arbitrary limit when collecting them. We
    // still don't enforce an upper limit if the caller requested more frames.
    size_t maxFrames = maxFrameCount.valueOr(ASYNC_STACK_MAX_FRAME_COUNT);

    // Turn the chain of frames starting with asyncStack into a vector of Lookup
    // objects in |stackChain|, youngest to oldest.
    SavedFrame::AutoLookupVector stackChain(cx);
    SavedFrame* currentSavedFrame = asyncStack;
    while (currentSavedFrame && stackChain->length() < maxFrames) {
        if (!stackChain->emplaceBack(*currentSavedFrame)) {
            ReportOutOfMemory(cx);
            return false;
        }

        currentSavedFrame = currentSavedFrame->getParent();
    }

    // Attach the asyncCause to the youngest frame.
    stackChain[0]->asyncCause = asyncCause;

    // If we walked the entire stack, and it's in cx's realm, we don't
    // need to rebuild the full chain again using the lookup objects - we can
    // just use the existing chain. Only the asyncCause on the youngest frame
    // needs to be changed.
    if (currentSavedFrame == nullptr &&
        asyncStack->realm() == cx->realm())
    {
        SavedFrame::HandleLookup lookup = stackChain[0];
        lookup->parent = asyncStack->getParent();
        asyncStack.set(getOrCreateSavedFrame(cx, lookup));
        return !!asyncStack;
    }

    // If we captured the maximum number of frames and the caller requested no
    // specific limit, we only return half of them. This means that if we do
    // many subsequent captures with the same async stack, it's likely we can
    // use the optimization above.
    if (maxFrameCount.isNothing() && currentSavedFrame)
        stackChain->shrinkBy(ASYNC_STACK_MAX_FRAME_COUNT / 2);

    // Iterate through |stackChain| in reverse order and get or create the
    // actual SavedFrame instances.
    asyncStack.set(nullptr);
    while (!stackChain->empty()) {
        SavedFrame::HandleLookup lookup = stackChain.back();
        lookup->parent = asyncStack;
        asyncStack.set(getOrCreateSavedFrame(cx, lookup));
        if (!asyncStack)
            return false;
        stackChain->popBack();
    }

    return true;
}

// Given a |lookup| for which we're about to construct a SavedFrame, if it
// refers to a Debugger eval frame, adjust |lookup|'s parent to be the frame's
// evalInFramePrev target.
//
// Debugger eval frames run code in the scope of some random older frame on the
// stack (the 'target' frame). It is our custom to report the target as the
// immediate parent of the eval frame. The LiveSavedFrameCache requires us not
// to skip frames, so instead we walk the entire stack, and just give Debugger
// eval frames the right parents as we encounter them.
//
// Call this function only if we are using the LiveSavedFrameCache; otherwise,
// FrameIter has already taken care of getting us the right parent.
bool
SavedStacks::checkForEvalInFramePrev(JSContext* cx, SavedFrame::HandleLookup lookup)
{
    MOZ_ASSERT(lookup->framePtr);
    if (!lookup->framePtr->isInterpreterFrame())
        return true;

    InterpreterFrame& interpreterFrame = lookup->framePtr->asInterpreterFrame();
    if (!interpreterFrame.isDebuggerEvalFrame())
        return true;

    LiveSavedFrameCache::FramePtr target =
        LiveSavedFrameCache::FramePtr::create(interpreterFrame.evalInFramePrev());

    // If we're caching the frame to which |lookup| refers, then we should
    // definitely have the target frame in the cache as well.
    MOZ_ASSERT(target.hasCachedSavedFrame());

    // Search the chain of activations for a LiveSavedFrameCache that has an
    // entry for target.
    RootedSavedFrame saved(cx, nullptr);
    for (Activation* act = lookup->activation; act; act = act->prev()) {
        // It's okay to force allocation of a cache here; we're about to put
        // something in the top cache, and all the lower ones should exist
        // already.
        auto* cache = act->getLiveSavedFrameCache(cx);
        if (!cache)
            return false;

        cache->findWithoutInvalidation(target, &saved);
        if (saved)
            break;
    }

    // Since |target| has its cached bit set, we should have found it.
    MOZ_ALWAYS_TRUE(saved);

    lookup->parent = saved;
    return true;
}

SavedFrame*
SavedStacks::getOrCreateSavedFrame(JSContext* cx, SavedFrame::HandleLookup lookup)
{
    const SavedFrame::Lookup& lookupInstance = lookup.get();
    DependentAddPtr<SavedFrame::Set> p(cx, frames, lookupInstance);
    if (p) {
        MOZ_ASSERT(*p);
        return *p;
    }

    RootedSavedFrame frame(cx, createFrameFromLookup(cx, lookup));
    if (!frame)
        return nullptr;

    if (!p.add(cx, frames, lookupInstance, frame))
        return nullptr;

    return frame;
}

SavedFrame*
SavedStacks::createFrameFromLookup(JSContext* cx, SavedFrame::HandleLookup lookup)
{
    RootedSavedFrame frame(cx, SavedFrame::create(cx));
    if (!frame)
        return nullptr;
    frame->initFromLookup(cx, lookup);

    if (!FreezeObject(cx, frame))
        return nullptr;

    return frame;
}

bool
SavedStacks::getLocation(JSContext* cx, const FrameIter& iter,
                         MutableHandle<LocationValue> locationp)
{
    // We should only ever be caching location values for scripts in this
    // compartment. Otherwise, we would get dead cross-compartment scripts in
    // the cache because our compartment's sweep method isn't called when their
    // compartment gets collected.
    MOZ_DIAGNOSTIC_ASSERT(&cx->realm()->savedStacks() == this);
    cx->check(iter.compartment());

    // When we have a |JSScript| for this frame, use a potentially memoized
    // location from our PCLocationMap and copy it into |locationp|. When we do
    // not have a |JSScript| for this frame (wasm frames), we take a slow path
    // that doesn't employ memoization, and update |locationp|'s slots directly.

    if (iter.isWasm()) {
        // Only asm.js has a displayURL.
        if (const char16_t* displayURL = iter.displayURL()) {
            locationp.setSource(AtomizeChars(cx, displayURL, js_strlen(displayURL)));
        } else {
            const char* filename = iter.filename() ? iter.filename() : "";
            locationp.setSource(Atomize(cx, filename, strlen(filename)));
        }
        if (!locationp.source())
            return false;

        // See WasmFrameIter::computeLine() comment.
        uint32_t column = 0;
        locationp.setLine(iter.computeLine(&column));
        locationp.setColumn(column);
        return true;
    }

    RootedScript script(cx, iter.script());
    jsbytecode* pc = iter.pc();

    PCKey key(script, pc);
    PCLocationMap::AddPtr p = pcLocationMap.lookupForAdd(key);

    if (!p) {
        RootedAtom source(cx);
        if (const char16_t* displayURL = iter.displayURL()) {
            source = AtomizeChars(cx, displayURL, js_strlen(displayURL));
        } else {
            const char* filename = script->filename() ? script->filename() : "";
            source = Atomize(cx, filename, strlen(filename));
        }
        if (!source)
            return false;

        uint32_t column;
        uint32_t line = PCToLineNumber(script, pc, &column);

        // Make the column 1-based. See comment above.
        LocationValue value(source, line, column + 1);
        if (!pcLocationMap.add(p, key, value)) {
            ReportOutOfMemory(cx);
            return false;
        }
    }

    locationp.set(p->value());
    return true;
}

void
SavedStacks::chooseSamplingProbability(Realm* realm)
{
    GlobalObject* global = realm->maybeGlobal();
    if (!global)
        return;

    GlobalObject::DebuggerVector* dbgs = global->getDebuggers();
    if (!dbgs || dbgs->empty())
        return;

    mozilla::DebugOnly<ReadBarriered<Debugger*>*> begin = dbgs->begin();
    mozilla::DebugOnly<bool> foundAnyDebuggers = false;

    double probability = 0;
    for (auto dbgp = dbgs->begin(); dbgp < dbgs->end(); dbgp++) {
        // The set of debuggers had better not change while we're iterating,
        // such that the vector gets reallocated.
        MOZ_ASSERT(dbgs->begin() == begin);

        if ((*dbgp)->trackingAllocationSites && (*dbgp)->enabled) {
            foundAnyDebuggers = true;
            probability = std::max((*dbgp)->allocationSamplingProbability,
                                   probability);
        }
    }
    MOZ_ASSERT(foundAnyDebuggers);

    if (!bernoulliSeeded) {
        mozilla::Array<uint64_t, 2> seed;
        GenerateXorShift128PlusSeed(seed);
        bernoulli.setRandomState(seed[0], seed[1]);
        bernoulliSeeded = true;
    }

    bernoulli.setProbability(probability);
}

JSObject*
SavedStacks::MetadataBuilder::build(JSContext* cx, HandleObject target,
                                    AutoEnterOOMUnsafeRegion& oomUnsafe) const
{
    RootedObject obj(cx, target);

    SavedStacks& stacks = cx->realm()->savedStacks();
    if (!stacks.bernoulli.trial())
        return nullptr;

    RootedSavedFrame frame(cx);
    if (!stacks.saveCurrentStack(cx, &frame))
        oomUnsafe.crash("SavedStacksMetadataBuilder");

    if (!Debugger::onLogAllocationSite(cx, obj, frame, mozilla::TimeStamp::Now()))
        oomUnsafe.crash("SavedStacksMetadataBuilder");

    MOZ_ASSERT_IF(frame, !frame->is<WrapperObject>());
    return frame;
}

const SavedStacks::MetadataBuilder SavedStacks::metadataBuilder;

/* static */ ReconstructedSavedFramePrincipals ReconstructedSavedFramePrincipals::IsSystem;
/* static */ ReconstructedSavedFramePrincipals ReconstructedSavedFramePrincipals::IsNotSystem;

UniqueChars
BuildUTF8StackString(JSContext* cx, JSPrincipals* principals, HandleObject stack)
{
    RootedString stackStr(cx);
    if (!JS::BuildStackString(cx, principals, stack, &stackStr))
        return nullptr;

    return JS_EncodeStringToUTF8(cx, stackStr);
}

uint32_t
FixupColumnForDisplay(uint32_t column)
{
    // As described in WasmFrameIter::computeLine(), for wasm frames, the
    // function index is returned as the column with the high bit set. In paths
    // that format error stacks into strings, this information can be used to
    // synthesize a proper wasm frame. But when raw column numbers are handed
    // out, we just fix them to 1 to avoid confusion.
    if (column & wasm::WasmFrameIter::ColumnBit)
        return 1;

    // XXX: Make the column 1-based as in other browsers, instead of 0-based
    // which is how SpiderMonkey stores it internally. This will be
    // unnecessary once bug 1144340 is fixed.
    return column + 1;
}

} /* namespace js */

namespace JS {
namespace ubi {

bool
ConcreteStackFrame<SavedFrame>::isSystem() const
{
    auto trustedPrincipals = get().runtimeFromAnyThread()->trustedPrincipals();
    return get().getPrincipals() == trustedPrincipals ||
           get().getPrincipals() == &js::ReconstructedSavedFramePrincipals::IsSystem;
}

bool
ConcreteStackFrame<SavedFrame>::constructSavedFrameStack(JSContext* cx,
                                                         MutableHandleObject outSavedFrameStack)
    const
{
    outSavedFrameStack.set(&get());
    if (!cx->compartment()->wrap(cx, outSavedFrameStack)) {
        outSavedFrameStack.set(nullptr);
        return false;
    }
    return true;
}

// A `mozilla::Variant` matcher that converts the inner value of a
// `JS::ubi::AtomOrTwoByteChars` string to a `JSAtom*`.
struct MOZ_STACK_CLASS AtomizingMatcher
{
    JSContext* cx;
    size_t     length;

    explicit AtomizingMatcher(JSContext* cx, size_t length)
      : cx(cx)
      , length(length)
    { }

    JSAtom* match(JSAtom* atom) {
        MOZ_ASSERT(atom);
        return atom;
    }

    JSAtom* match(const char16_t* chars) {
        MOZ_ASSERT(chars);
        return AtomizeChars(cx, chars, length);
    }
};

JS_PUBLIC_API(bool)
ConstructSavedFrameStackSlow(JSContext* cx, JS::ubi::StackFrame& frame,
                             MutableHandleObject outSavedFrameStack)
{
    SavedFrame::AutoLookupVector stackChain(cx);
    Rooted<JS::ubi::StackFrame> ubiFrame(cx, frame);

    while (ubiFrame.get()) {
        // Convert the source and functionDisplayName strings to atoms.

        js::RootedAtom source(cx);
        AtomizingMatcher atomizer(cx, ubiFrame.get().sourceLength());
        source = ubiFrame.get().source().match(atomizer);
        if (!source)
            return false;

        js::RootedAtom functionDisplayName(cx);
        auto nameLength = ubiFrame.get().functionDisplayNameLength();
        if (nameLength > 0) {
            AtomizingMatcher atomizer(cx, nameLength);
            functionDisplayName = ubiFrame.get().functionDisplayName().match(atomizer);
            if (!functionDisplayName)
                return false;
        }

        auto principals = js::ReconstructedSavedFramePrincipals::getSingleton(ubiFrame.get());

        if (!stackChain->emplaceBack(source, ubiFrame.get().line(), ubiFrame.get().column(),
                                     functionDisplayName, /* asyncCause */ nullptr,
                                     /* parent */ nullptr, principals))
        {
            ReportOutOfMemory(cx);
            return false;
        }

        ubiFrame = ubiFrame.get().parent();
    }

    js::RootedSavedFrame parentFrame(cx);
    for (size_t i = stackChain->length(); i != 0; i--) {
        SavedFrame::HandleLookup lookup = stackChain[i-1];
        lookup->parent = parentFrame;
        parentFrame = cx->realm()->savedStacks().getOrCreateSavedFrame(cx, lookup);
        if (!parentFrame)
            return false;
    }

    outSavedFrameStack.set(parentFrame);
    return true;
}


} // namespace ubi
} // namespace JS