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 (6863f516ba38)

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 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * vim: set ts=8 sts=2 et sw=2 tw=80:
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "vm/Stack-inl.h"

#include <utility>

#include "gc/Marking.h"
#include "jit/BaselineFrame.h"
#include "jit/JitcodeMap.h"
#include "jit/JitRealm.h"
#include "jit/shared/CodeGenerator-shared.h"
#include "vm/Debugger.h"
#include "vm/JSContext.h"
#include "vm/Opcodes.h"
#include "wasm/WasmInstance.h"

#include "jit/JSJitFrameIter-inl.h"
#include "vm/Compartment-inl.h"
#include "vm/EnvironmentObject-inl.h"
#include "vm/Interpreter-inl.h"
#include "vm/Probes-inl.h"

using namespace js;

using mozilla::ArrayLength;
using mozilla::DebugOnly;
using mozilla::Maybe;

/*****************************************************************************/

void InterpreterFrame::initExecuteFrame(JSContext* cx, HandleScript script,
                                        AbstractFramePtr evalInFramePrev,
                                        const Value& newTargetValue,
                                        HandleObject envChain) {
  flags_ = 0;
  script_ = script;

  // newTarget = NullValue is an initial sentinel for "please fill me in from
  // the stack". It should never be passed from Ion code.
  RootedValue newTarget(cx, newTargetValue);
  if (script->isDirectEvalInFunction()) {
    FrameIter iter(cx);
    if (newTarget.isNull() && iter.hasScript() &&
        iter.script()->bodyScope()->hasOnChain(ScopeKind::Function)) {
      newTarget = iter.newTarget();
    }
  } else if (evalInFramePrev) {
    if (newTarget.isNull() && evalInFramePrev.hasScript() &&
        evalInFramePrev.script()->bodyScope()->hasOnChain(
            ScopeKind::Function)) {
      newTarget = evalInFramePrev.newTarget();
    }
  }

  Value* dstvp = (Value*)this - 1;
  dstvp[0] = newTarget;

  envChain_ = envChain.get();
  prev_ = nullptr;
  prevpc_ = nullptr;
  prevsp_ = nullptr;

  evalInFramePrev_ = evalInFramePrev;
  MOZ_ASSERT_IF(evalInFramePrev, isDebuggerEvalFrame());

  if (script->isDebuggee()) {
    setIsDebuggee();
  }

#ifdef DEBUG
  Debug_SetValueRangeToCrashOnTouch(&rval_, 1);
#endif
}

bool InterpreterFrame::isNonGlobalEvalFrame() const {
  return isEvalFrame() && script()->bodyScope()->as<EvalScope>().isNonGlobal();
}

ArrayObject* InterpreterFrame::createRestParameter(JSContext* cx) {
  MOZ_ASSERT(script()->hasRest());
  unsigned nformal = callee().nargs() - 1, nactual = numActualArgs();
  unsigned nrest = (nactual > nformal) ? nactual - nformal : 0;
  Value* restvp = argv() + nformal;
  return ObjectGroup::newArrayObject(cx, restvp, nrest, GenericObject,
                                     ObjectGroup::NewArrayKind::UnknownIndex);
}

static inline void AssertScopeMatchesEnvironment(Scope* scope,
                                                 JSObject* originalEnv) {
#ifdef DEBUG
  JSObject* env = originalEnv;
  for (ScopeIter si(scope); si; si++) {
    if (si.kind() == ScopeKind::NonSyntactic) {
      while (env->is<WithEnvironmentObject>() ||
             env->is<NonSyntacticVariablesObject>() ||
             (env->is<LexicalEnvironmentObject>() &&
              !env->as<LexicalEnvironmentObject>().isSyntactic())) {
        MOZ_ASSERT(!IsSyntacticEnvironment(env));
        env = &env->as<EnvironmentObject>().enclosingEnvironment();
      }
    } else if (si.hasSyntacticEnvironment()) {
      switch (si.kind()) {
        case ScopeKind::Function:
          MOZ_ASSERT(
              env->as<CallObject>().callee().existingScriptNonDelazifying() ==
              si.scope()->as<FunctionScope>().script());
          env = &env->as<CallObject>().enclosingEnvironment();
          break;

        case ScopeKind::FunctionBodyVar:
        case ScopeKind::ParameterExpressionVar:
          MOZ_ASSERT(&env->as<VarEnvironmentObject>().scope() == si.scope());
          env = &env->as<VarEnvironmentObject>().enclosingEnvironment();
          break;

        case ScopeKind::Lexical:
        case ScopeKind::SimpleCatch:
        case ScopeKind::Catch:
        case ScopeKind::NamedLambda:
        case ScopeKind::StrictNamedLambda:
          MOZ_ASSERT(&env->as<LexicalEnvironmentObject>().scope() ==
                     si.scope());
          env = &env->as<LexicalEnvironmentObject>().enclosingEnvironment();
          break;

        case ScopeKind::With:
          MOZ_ASSERT(&env->as<WithEnvironmentObject>().scope() == si.scope());
          env = &env->as<WithEnvironmentObject>().enclosingEnvironment();
          break;

        case ScopeKind::Eval:
        case ScopeKind::StrictEval:
          env = &env->as<VarEnvironmentObject>().enclosingEnvironment();
          break;

        case ScopeKind::Global:
          MOZ_ASSERT(env->as<LexicalEnvironmentObject>().isGlobal());
          env = &env->as<LexicalEnvironmentObject>().enclosingEnvironment();
          MOZ_ASSERT(env->is<GlobalObject>());
          break;

        case ScopeKind::NonSyntactic:
          MOZ_CRASH("NonSyntactic should not have a syntactic environment");
          break;

        case ScopeKind::Module:
          MOZ_ASSERT(&env->as<ModuleEnvironmentObject>().module() ==
                     si.scope()->as<ModuleScope>().module());
          env = &env->as<ModuleEnvironmentObject>().enclosingEnvironment();
          break;

        case ScopeKind::WasmInstance:
          env =
              &env->as<WasmInstanceEnvironmentObject>().enclosingEnvironment();
          break;

        case ScopeKind::WasmFunction:
          env = &env->as<WasmFunctionCallObject>().enclosingEnvironment();
          break;
      }
    }
  }

  // In the case of a non-syntactic env chain, the immediate parent of the
  // outermost non-syntactic env may be the global lexical env, or, if
  // called from Debugger, a DebugEnvironmentProxy.
  //
  // In the case of a syntactic env chain, the outermost env is always a
  // GlobalObject.
  MOZ_ASSERT(env->is<GlobalObject>() || IsGlobalLexicalEnvironment(env) ||
             env->is<DebugEnvironmentProxy>());
#endif
}

static inline void AssertScopeMatchesEnvironment(InterpreterFrame* fp,
                                                 jsbytecode* pc) {
#ifdef DEBUG
  // If we OOMed before fully initializing the environment chain, the scope
  // and environment will definitely mismatch.
  if (fp->script()->initialEnvironmentShape() && fp->hasInitialEnvironment()) {
    AssertScopeMatchesEnvironment(fp->script()->innermostScope(pc),
                                  fp->environmentChain());
  }
#endif
}

bool InterpreterFrame::initFunctionEnvironmentObjects(JSContext* cx) {
  return js::InitFunctionEnvironmentObjects(cx, this);
}

bool InterpreterFrame::prologue(JSContext* cx) {
  RootedScript script(cx, this->script());

  MOZ_ASSERT(cx->interpreterRegs().pc == script->code());
  MOZ_ASSERT(cx->realm() == script->realm());

  if (isEvalFrame() || isGlobalFrame()) {
    HandleObject env = environmentChain();
    if (!CheckGlobalOrEvalDeclarationConflicts(cx, env, script)) {
      // Treat this as a script entry, for consistency with Ion.
      if (script->trackRecordReplayProgress()) {
        mozilla::recordreplay::AdvanceExecutionProgressCounter();
      }
      return false;
    }
    return probes::EnterScript(cx, script, nullptr, this);
  }

  if (isModuleFrame()) {
    return probes::EnterScript(cx, script, nullptr, this);
  }

  MOZ_ASSERT(isFunctionFrame());

  // At this point, we've yet to push any environments. Check that they
  // match the enclosing scope.
  AssertScopeMatchesEnvironment(script->enclosingScope(), environmentChain());

  if (callee().needsFunctionEnvironmentObjects() &&
      !initFunctionEnvironmentObjects(cx)) {
    return false;
  }

  MOZ_ASSERT_IF(isConstructing(),
                thisArgument().isObject() ||
                    thisArgument().isMagic(JS_UNINITIALIZED_LEXICAL));

  return probes::EnterScript(cx, script, script->functionNonDelazifying(),
                             this);
}

void InterpreterFrame::epilogue(JSContext* cx, jsbytecode* pc) {
  RootedScript script(cx, this->script());
  MOZ_ASSERT(cx->realm() == script->realm());
  probes::ExitScript(cx, script, script->functionNonDelazifying(),
                     hasPushedGeckoProfilerFrame());

  // Check that the scope matches the environment at the point of leaving
  // the frame.
  AssertScopeMatchesEnvironment(this, pc);

  EnvironmentIter ei(cx, this, pc);
  UnwindAllEnvironmentsInFrame(cx, ei);

  if (isFunctionFrame()) {
    if (!callee().isGenerator() && !callee().isAsync() && isConstructing() &&
        thisArgument().isObject() && returnValue().isPrimitive()) {
      setReturnValue(thisArgument());
    }

    return;
  }

  MOZ_ASSERT(isEvalFrame() || isGlobalFrame() || isModuleFrame());
}

bool InterpreterFrame::checkReturn(JSContext* cx, HandleValue thisv) {
  MOZ_ASSERT(script()->isDerivedClassConstructor());
  MOZ_ASSERT(isFunctionFrame());
  MOZ_ASSERT(callee().isClassConstructor());

  HandleValue retVal = returnValue();
  if (retVal.isObject()) {
    return true;
  }

  if (!retVal.isUndefined()) {
    ReportValueError(cx, JSMSG_BAD_DERIVED_RETURN, JSDVG_IGNORE_STACK, retVal,
                     nullptr);
    return false;
  }

  if (thisv.isMagic(JS_UNINITIALIZED_LEXICAL)) {
    return ThrowUninitializedThis(cx, this);
  }

  setReturnValue(thisv);
  return true;
}

bool InterpreterFrame::pushVarEnvironment(JSContext* cx, HandleScope scope) {
  return js::PushVarEnvironmentObject(cx, scope, this);
}

bool InterpreterFrame::pushLexicalEnvironment(JSContext* cx,
                                              Handle<LexicalScope*> scope) {
  LexicalEnvironmentObject* env =
      LexicalEnvironmentObject::createForFrame(cx, scope, this);
  if (!env) {
    return false;
  }

  pushOnEnvironmentChain(*env);
  return true;
}

bool InterpreterFrame::freshenLexicalEnvironment(JSContext* cx) {
  Rooted<LexicalEnvironmentObject*> env(
      cx, &envChain_->as<LexicalEnvironmentObject>());
  LexicalEnvironmentObject* fresh = LexicalEnvironmentObject::clone(cx, env);
  if (!fresh) {
    return false;
  }

  replaceInnermostEnvironment(*fresh);
  return true;
}

bool InterpreterFrame::recreateLexicalEnvironment(JSContext* cx) {
  Rooted<LexicalEnvironmentObject*> env(
      cx, &envChain_->as<LexicalEnvironmentObject>());
  LexicalEnvironmentObject* fresh = LexicalEnvironmentObject::recreate(cx, env);
  if (!fresh) {
    return false;
  }

  replaceInnermostEnvironment(*fresh);
  return true;
}

void InterpreterFrame::trace(JSTracer* trc, Value* sp, jsbytecode* pc) {
  TraceRoot(trc, &envChain_, "env chain");
  TraceRoot(trc, &script_, "script");

  if (flags_ & HAS_ARGS_OBJ) {
    TraceRoot(trc, &argsObj_, "arguments");
  }

  if (hasReturnValue()) {
    TraceRoot(trc, &rval_, "rval");
  }

  MOZ_ASSERT(sp >= slots());

  if (hasArgs()) {
    // Trace the callee and |this|. When we're doing a moving GC, we
    // need to fix up the callee pointer before we use it below, under
    // numFormalArgs() and script().
    TraceRootRange(trc, 2, argv_ - 2, "fp callee and this");

    // Trace arguments.
    unsigned argc = Max(numActualArgs(), numFormalArgs());
    TraceRootRange(trc, argc + isConstructing(), argv_, "fp argv");
  } else {
    // Trace newTarget.
    TraceRoot(trc, ((Value*)this) - 1, "stack newTarget");
  }

  JSScript* script = this->script();
  size_t nfixed = script->nfixed();
  size_t nlivefixed = script->calculateLiveFixed(pc);

  if (nfixed == nlivefixed) {
    // All locals are live.
    traceValues(trc, 0, sp - slots());
  } else {
    // Trace operand stack.
    traceValues(trc, nfixed, sp - slots());

    // Clear dead block-scoped locals.
    while (nfixed > nlivefixed) {
      unaliasedLocal(--nfixed).setUndefined();
    }

    // Trace live locals.
    traceValues(trc, 0, nlivefixed);
  }

  if (auto* debugEnvs = script->realm()->debugEnvs()) {
    debugEnvs->traceLiveFrame(trc, this);
  }
}

void InterpreterFrame::traceValues(JSTracer* trc, unsigned start,
                                   unsigned end) {
  if (start < end) {
    TraceRootRange(trc, end - start, slots() + start, "vm_stack");
  }
}

static void TraceInterpreterActivation(JSTracer* trc,
                                       InterpreterActivation* act) {
  for (InterpreterFrameIterator frames(act); !frames.done(); ++frames) {
    InterpreterFrame* fp = frames.frame();
    fp->trace(trc, frames.sp(), frames.pc());
  }
}

void js::TraceInterpreterActivations(JSContext* cx, JSTracer* trc) {
  for (ActivationIterator iter(cx); !iter.done(); ++iter) {
    Activation* act = iter.activation();
    if (act->isInterpreter()) {
      TraceInterpreterActivation(trc, act->asInterpreter());
    }
  }
}

/*****************************************************************************/

// Unlike the other methods of this class, this method is defined here so that
// we don't have to #include jsautooplen.h in vm/Stack.h.
void InterpreterRegs::setToEndOfScript() { sp = fp()->base(); }

/*****************************************************************************/

InterpreterFrame* InterpreterStack::pushInvokeFrame(
    JSContext* cx, const CallArgs& args, MaybeConstruct constructing) {
  LifoAlloc::Mark mark = allocator_.mark();

  RootedFunction fun(cx, &args.callee().as<JSFunction>());
  RootedScript script(cx, fun->nonLazyScript());

  Value* argv;
  InterpreterFrame* fp = getCallFrame(cx, args, script, constructing, &argv);
  if (!fp) {
    return nullptr;
  }

  fp->mark_ = mark;
  fp->initCallFrame(nullptr, nullptr, nullptr, *fun, script, argv,
                    args.length(), constructing);
  return fp;
}

InterpreterFrame* InterpreterStack::pushExecuteFrame(
    JSContext* cx, HandleScript script, const Value& newTargetValue,
    HandleObject envChain, AbstractFramePtr evalInFrame) {
  LifoAlloc::Mark mark = allocator_.mark();

  unsigned nvars = 1 /* newTarget */ + script->nslots();
  uint8_t* buffer =
      allocateFrame(cx, sizeof(InterpreterFrame) + nvars * sizeof(Value));
  if (!buffer) {
    return nullptr;
  }

  InterpreterFrame* fp =
      reinterpret_cast<InterpreterFrame*>(buffer + 1 * sizeof(Value));
  fp->mark_ = mark;
  fp->initExecuteFrame(cx, script, evalInFrame, newTargetValue, envChain);
  fp->initLocals();

  return fp;
}

/*****************************************************************************/

JitFrameIter::JitFrameIter(const JitFrameIter& another) { *this = another; }

JitFrameIter& JitFrameIter::operator=(const JitFrameIter& another) {
  MOZ_ASSERT(this != &another);

  act_ = another.act_;
  mustUnwindActivation_ = another.mustUnwindActivation_;

  if (isSome()) {
    iter_.destroy();
  }
  if (!another.isSome()) {
    return *this;
  }

  if (another.isJSJit()) {
    iter_.construct<jit::JSJitFrameIter>(another.asJSJit());
  } else {
    MOZ_ASSERT(another.isWasm());
    iter_.construct<wasm::WasmFrameIter>(another.asWasm());
  }

  return *this;
}

JitFrameIter::JitFrameIter(jit::JitActivation* act, bool mustUnwindActivation) {
  act_ = act;
  mustUnwindActivation_ = mustUnwindActivation;
  MOZ_ASSERT(act->hasExitFP(),
             "packedExitFP is used to determine if JSJit or wasm");
  if (act->hasJSExitFP()) {
    iter_.construct<jit::JSJitFrameIter>(act);
  } else {
    MOZ_ASSERT(act->hasWasmExitFP());
    iter_.construct<wasm::WasmFrameIter>(act);
  }
  settle();
}

void JitFrameIter::skipNonScriptedJSFrames() {
  if (isJSJit()) {
    // Stop at the first scripted frame.
    jit::JSJitFrameIter& frames = asJSJit();
    while (!frames.isScripted() && !frames.done()) {
      ++frames;
    }
    settle();
  }
}

bool JitFrameIter::isSelfHostedIgnoringInlining() const {
  MOZ_ASSERT(!done());

  if (isWasm()) {
    return false;
  }

  return asJSJit().script()->selfHosted();
}

JS::Realm* JitFrameIter::realm() const {
  MOZ_ASSERT(!done());

  if (isWasm()) {
    return asWasm().instance()->realm();
  }

  return asJSJit().script()->realm();
}

uint8_t* JitFrameIter::resumePCinCurrentFrame() const {
  if (isWasm()) {
    return asWasm().resumePCinCurrentFrame();
  }
  return asJSJit().resumePCinCurrentFrame();
}

bool JitFrameIter::done() const {
  if (!isSome()) {
    return true;
  }
  if (isJSJit()) {
    return asJSJit().done();
  }
  if (isWasm()) {
    return asWasm().done();
  }
  MOZ_CRASH("unhandled case");
}

void JitFrameIter::settle() {
  if (isJSJit()) {
    const jit::JSJitFrameIter& jitFrame = asJSJit();
    if (jitFrame.type() != jit::FrameType::WasmToJSJit) {
      return;
    }

    // Transition from js jit frames to wasm frames: we're on the
    // wasm-to-jit fast path. The current stack layout is as follows:
    // (stack grows downward)
    //
    // [--------------------]
    // [WASM FUNC           ]
    // [WASM JIT EXIT FRAME ]
    // [JIT WASM ENTRY FRAME] <-- we're here.
    //
    // So prevFP points to the wasm jit exit FP, maintaing the invariant in
    // WasmFrameIter that the first frame is an exit frame and can be
    // popped.

    wasm::Frame* prevFP = (wasm::Frame*)jitFrame.prevFp();

    if (mustUnwindActivation_) {
      act_->setWasmExitFP(prevFP);
    }

    iter_.destroy();
    iter_.construct<wasm::WasmFrameIter>(act_, prevFP);
    MOZ_ASSERT(!asWasm().done());
    return;
  }

  if (isWasm()) {
    const wasm::WasmFrameIter& wasmFrame = asWasm();
    if (!wasmFrame.unwoundIonCallerFP()) {
      return;
    }

    // Transition from wasm frames to jit frames: we're on the
    // jit-to-wasm fast path. The current stack layout is as follows:
    // (stack grows downward)
    //
    // [--------------------]
    // [JIT FRAME           ]
    // [WASM JIT ENTRY FRAME] <-- we're here
    //
    // The wasm iterator has saved the previous jit frame pointer for us.

    MOZ_ASSERT(wasmFrame.done());
    uint8_t* prevFP = wasmFrame.unwoundIonCallerFP();
    jit::FrameType prevFrameType = wasmFrame.unwoundIonFrameType();

    if (mustUnwindActivation_) {
      act_->setJSExitFP(prevFP);
    }

    iter_.destroy();
    iter_.construct<jit::JSJitFrameIter>(act_, prevFrameType, prevFP);
    MOZ_ASSERT(!asJSJit().done());
    return;
  }
}

void JitFrameIter::operator++() {
  MOZ_ASSERT(isSome());
  if (isJSJit()) {
    const jit::JSJitFrameIter& jitFrame = asJSJit();

    jit::JitFrameLayout* prevFrame = nullptr;
    if (mustUnwindActivation_ && jitFrame.isScripted()) {
      prevFrame = jitFrame.jsFrame();
    }

    ++asJSJit();

    if (prevFrame) {
      // Unwind the frame by updating packedExitFP. This is necessary
      // so that (1) debugger exception unwind and leave frame hooks
      // don't see this frame when they use ScriptFrameIter, and (2)
      // ScriptFrameIter does not crash when accessing an IonScript
      // that's destroyed by the ionScript->decref call.
      EnsureBareExitFrame(act_, prevFrame);
    }
  } else if (isWasm()) {
    ++asWasm();
  } else {
    MOZ_CRASH("unhandled case");
  }
  settle();
}

OnlyJSJitFrameIter::OnlyJSJitFrameIter(jit::JitActivation* act)
    : JitFrameIter(act) {
  settle();
}

OnlyJSJitFrameIter::OnlyJSJitFrameIter(JSContext* cx)
    : OnlyJSJitFrameIter(cx->activation()->asJit()) {}

OnlyJSJitFrameIter::OnlyJSJitFrameIter(const ActivationIterator& iter)
    : OnlyJSJitFrameIter(iter->asJit()) {}

/*****************************************************************************/

void FrameIter::popActivation() {
  ++data_.activations_;
  settleOnActivation();
}

bool FrameIter::principalsSubsumeFrame() const {
  // If the caller supplied principals, only show frames which are
  // subsumed (of the same origin or of an origin accessible) by these
  // principals.

  MOZ_ASSERT(!done());

  if (!data_.principals_) {
    return true;
  }

  JSSubsumesOp subsumes = data_.cx_->runtime()->securityCallbacks->subsumes;
  if (!subsumes) {
    return true;
  }

  JS::AutoSuppressGCAnalysis nogc;
  return subsumes(data_.principals_, realm()->principals());
}

void FrameIter::popInterpreterFrame() {
  MOZ_ASSERT(data_.state_ == INTERP);

  ++data_.interpFrames_;

  if (data_.interpFrames_.done()) {
    popActivation();
  } else {
    data_.pc_ = data_.interpFrames_.pc();
  }
}

void FrameIter::settleOnActivation() {
  MOZ_ASSERT(!data_.cx_->inUnsafeCallWithABI);

  while (true) {
    if (data_.activations_.done()) {
      data_.state_ = DONE;
      return;
    }

    Activation* activation = data_.activations_.activation();

    if (activation->isJit()) {
      data_.jitFrames_ = JitFrameIter(activation->asJit());
      data_.jitFrames_.skipNonScriptedJSFrames();
      if (data_.jitFrames_.done()) {
        // It's possible to have an JitActivation with no scripted
        // frames, for instance if we hit an over-recursion during
        // bailout.
        ++data_.activations_;
        continue;
      }
      data_.state_ = JIT;
      nextJitFrame();
      return;
    }

    MOZ_ASSERT(activation->isInterpreter());

    InterpreterActivation* interpAct = activation->asInterpreter();
    data_.interpFrames_ = InterpreterFrameIterator(interpAct);

    // If we OSR'ed into JIT code, skip the interpreter frame so that
    // the same frame is not reported twice.
    if (data_.interpFrames_.frame()->runningInJit()) {
      ++data_.interpFrames_;
      if (data_.interpFrames_.done()) {
        ++data_.activations_;
        continue;
      }
    }

    MOZ_ASSERT(!data_.interpFrames_.frame()->runningInJit());
    data_.pc_ = data_.interpFrames_.pc();
    data_.state_ = INTERP;
    return;
  }
}

FrameIter::Data::Data(JSContext* cx, DebuggerEvalOption debuggerEvalOption,
                      JSPrincipals* principals)
    : cx_(cx),
      debuggerEvalOption_(debuggerEvalOption),
      principals_(principals),
      state_(DONE),
      pc_(nullptr),
      interpFrames_(nullptr),
      activations_(cx),
      ionInlineFrameNo_(0) {}

FrameIter::Data::Data(const FrameIter::Data& other)
    : cx_(other.cx_),
      debuggerEvalOption_(other.debuggerEvalOption_),
      principals_(other.principals_),
      state_(other.state_),
      pc_(other.pc_),
      interpFrames_(other.interpFrames_),
      activations_(other.activations_),
      jitFrames_(other.jitFrames_),
      ionInlineFrameNo_(other.ionInlineFrameNo_) {}

FrameIter::FrameIter(JSContext* cx, DebuggerEvalOption debuggerEvalOption)
    : data_(cx, debuggerEvalOption, nullptr),
      ionInlineFrames_(cx, (js::jit::JSJitFrameIter*)nullptr) {
  settleOnActivation();

  // No principals so we can see all frames.
  MOZ_ASSERT_IF(!done(), principalsSubsumeFrame());
}

FrameIter::FrameIter(JSContext* cx, DebuggerEvalOption debuggerEvalOption,
                     JSPrincipals* principals)
    : data_(cx, debuggerEvalOption, principals),
      ionInlineFrames_(cx, (js::jit::JSJitFrameIter*)nullptr) {
  settleOnActivation();

  // If we're not allowed to see this frame, call operator++ to skip this (and
  // other) cross-origin frames.
  if (!done() && !principalsSubsumeFrame()) {
    ++*this;
  }
}

FrameIter::FrameIter(const FrameIter& other)
    : data_(other.data_),
      ionInlineFrames_(other.data_.cx_,
                       isIonScripted() ? &other.ionInlineFrames_ : nullptr) {}

FrameIter::FrameIter(const Data& data)
    : data_(data),
      ionInlineFrames_(data.cx_, isIonScripted() ? &jsJitFrame() : nullptr) {
  MOZ_ASSERT(data.cx_);
  if (isIonScripted()) {
    while (ionInlineFrames_.frameNo() != data.ionInlineFrameNo_) {
      ++ionInlineFrames_;
    }
  }
}

void FrameIter::nextJitFrame() {
  MOZ_ASSERT(data_.jitFrames_.isSome());

  if (isJSJit()) {
    if (jsJitFrame().isIonScripted()) {
      ionInlineFrames_.resetOn(&jsJitFrame());
      data_.pc_ = ionInlineFrames_.pc();
    } else {
      MOZ_ASSERT(jsJitFrame().isBaselineJS());
      jsJitFrame().baselineScriptAndPc(nullptr, &data_.pc_);
    }
    return;
  }

  MOZ_ASSERT(isWasm());
  data_.pc_ = nullptr;
}

void FrameIter::popJitFrame() {
  MOZ_ASSERT(data_.state_ == JIT);
  MOZ_ASSERT(data_.jitFrames_.isSome());

  if (isJSJit() && jsJitFrame().isIonScripted() && ionInlineFrames_.more()) {
    ++ionInlineFrames_;
    data_.pc_ = ionInlineFrames_.pc();
    return;
  }

  ++data_.jitFrames_;
  data_.jitFrames_.skipNonScriptedJSFrames();

  if (!data_.jitFrames_.done()) {
    nextJitFrame();
  } else {
    data_.jitFrames_.reset();
    popActivation();
  }
}

FrameIter& FrameIter::operator++() {
  while (true) {
    switch (data_.state_) {
      case DONE:
        MOZ_CRASH("Unexpected state");
      case INTERP:
        if (interpFrame()->isDebuggerEvalFrame() &&
            data_.debuggerEvalOption_ == FOLLOW_DEBUGGER_EVAL_PREV_LINK) {
          AbstractFramePtr eifPrev = interpFrame()->evalInFramePrev();

          popInterpreterFrame();

          while (!hasUsableAbstractFramePtr() ||
                 abstractFramePtr() != eifPrev) {
            if (data_.state_ == JIT) {
              popJitFrame();
            } else {
              popInterpreterFrame();
            }
          }

          break;
        }
        popInterpreterFrame();
        break;
      case JIT:
        popJitFrame();
        break;
    }

    if (done() || principalsSubsumeFrame()) {
      break;
    }
  }

  return *this;
}

FrameIter::Data* FrameIter::copyData() const {
  Data* data = data_.cx_->new_<Data>(data_);
  if (!data) {
    return nullptr;
  }

  if (data && isIonScripted()) {
    data->ionInlineFrameNo_ = ionInlineFrames_.frameNo();
  }
  return data;
}

void* FrameIter::rawFramePtr() const {
  switch (data_.state_) {
    case DONE:
      return nullptr;
    case INTERP:
      return interpFrame();
    case JIT:
      if (isJSJit()) {
        return jsJitFrame().fp();
      }
      MOZ_ASSERT(isWasm());
      return nullptr;
  }
  MOZ_CRASH("Unexpected state");
}

JS::Compartment* FrameIter::compartment() const {
  switch (data_.state_) {
    case DONE:
      break;
    case INTERP:
    case JIT:
      return data_.activations_->compartment();
  }
  MOZ_CRASH("Unexpected state");
}

Realm* FrameIter::realm() const {
  MOZ_ASSERT(!done());

  if (hasScript()) {
    return script()->realm();
  }

  return wasmInstance()->realm();
}

bool FrameIter::isEvalFrame() const {
  switch (data_.state_) {
    case DONE:
      break;
    case INTERP:
      return interpFrame()->isEvalFrame();
    case JIT:
      if (isJSJit()) {
        if (jsJitFrame().isBaselineJS()) {
          return jsJitFrame().baselineFrame()->isEvalFrame();
        }
        MOZ_ASSERT(!script()->isForEval());
        return false;
      }
      MOZ_ASSERT(isWasm());
      return false;
  }
  MOZ_CRASH("Unexpected state");
}

bool FrameIter::isFunctionFrame() const {
  MOZ_ASSERT(!done());
  switch (data_.state_) {
    case DONE:
      break;
    case INTERP:
      return interpFrame()->isFunctionFrame();
    case JIT:
      if (isJSJit()) {
        if (jsJitFrame().isBaselineJS()) {
          return jsJitFrame().baselineFrame()->isFunctionFrame();
        }
        return script()->functionNonDelazifying();
      }
      MOZ_ASSERT(isWasm());
      return false;
  }
  MOZ_CRASH("Unexpected state");
}

JSAtom* FrameIter::maybeFunctionDisplayAtom() const {
  switch (data_.state_) {
    case DONE:
      break;
    case INTERP:
    case JIT:
      if (isWasm()) {
        return wasmFrame().functionDisplayAtom();
      }
      if (isFunctionFrame()) {
        return calleeTemplate()->displayAtom();
      }
      return nullptr;
  }

  MOZ_CRASH("Unexpected state");
}

ScriptSource* FrameIter::scriptSource() const {
  switch (data_.state_) {
    case DONE:
      break;
    case INTERP:
    case JIT:
      return script()->scriptSource();
  }

  MOZ_CRASH("Unexpected state");
}

const char* FrameIter::filename() const {
  switch (data_.state_) {
    case DONE:
      break;
    case INTERP:
    case JIT:
      if (isWasm()) {
        return wasmFrame().filename();
      }
      return script()->filename();
  }

  MOZ_CRASH("Unexpected state");
}

const char16_t* FrameIter::displayURL() const {
  switch (data_.state_) {
    case DONE:
      break;
    case INTERP:
    case JIT:
      if (isWasm()) {
        return wasmFrame().displayURL();
      }
      ScriptSource* ss = script()->scriptSource();
      return ss->hasDisplayURL() ? ss->displayURL() : nullptr;
  }
  MOZ_CRASH("Unexpected state");
}

unsigned FrameIter::computeLine(uint32_t* column) const {
  switch (data_.state_) {
    case DONE:
      break;
    case INTERP:
    case JIT:
      if (isWasm()) {
        return wasmFrame().computeLine(column);
      }
      return PCToLineNumber(script(), pc(), column);
  }

  MOZ_CRASH("Unexpected state");
}

bool FrameIter::mutedErrors() const {
  switch (data_.state_) {
    case DONE:
      break;
    case INTERP:
    case JIT:
      if (isWasm()) {
        return wasmFrame().mutedErrors();
      }
      return script()->mutedErrors();
  }
  MOZ_CRASH("Unexpected state");
}

bool FrameIter::isConstructing() const {
  switch (data_.state_) {
    case DONE:
      break;
    case JIT:
      MOZ_ASSERT(isJSJit());
      if (jsJitFrame().isIonScripted()) {
        return ionInlineFrames_.isConstructing();
      }
      MOZ_ASSERT(jsJitFrame().isBaselineJS());
      return jsJitFrame().isConstructing();
    case INTERP:
      return interpFrame()->isConstructing();
  }

  MOZ_CRASH("Unexpected state");
}

bool FrameIter::ensureHasRematerializedFrame(JSContext* cx) {
  MOZ_ASSERT(isIon());
  return !!activation()->asJit()->getRematerializedFrame(cx, jsJitFrame());
}

bool FrameIter::hasUsableAbstractFramePtr() const {
  switch (data_.state_) {
    case DONE:
      return false;
    case JIT:
      if (isJSJit()) {
        if (jsJitFrame().isBaselineJS()) {
          return true;
        }

        MOZ_ASSERT(jsJitFrame().isIonScripted());
        return !!activation()->asJit()->lookupRematerializedFrame(
            jsJitFrame().fp(), ionInlineFrames_.frameNo());
      }
      MOZ_ASSERT(isWasm());
      return wasmFrame().debugEnabled();
    case INTERP:
      return true;
  }
  MOZ_CRASH("Unexpected state");
}

AbstractFramePtr FrameIter::abstractFramePtr() const {
  MOZ_ASSERT(hasUsableAbstractFramePtr());
  switch (data_.state_) {
    case DONE:
      break;
    case JIT: {
      if (isJSJit()) {
        if (jsJitFrame().isBaselineJS()) {
          return jsJitFrame().baselineFrame();
        }
        MOZ_ASSERT(isIonScripted());
        return activation()->asJit()->lookupRematerializedFrame(
            jsJitFrame().fp(), ionInlineFrames_.frameNo());
      }
      MOZ_ASSERT(isWasm());
      MOZ_ASSERT(wasmFrame().debugEnabled());
      return wasmFrame().debugFrame();
    }
    case INTERP:
      MOZ_ASSERT(interpFrame());
      return AbstractFramePtr(interpFrame());
  }
  MOZ_CRASH("Unexpected state");
}

void FrameIter::updatePcQuadratic() {
  switch (data_.state_) {
    case DONE:
      break;
    case INTERP: {
      InterpreterFrame* frame = interpFrame();
      InterpreterActivation* activation = data_.activations_->asInterpreter();

      // Look for the current frame.
      data_.interpFrames_ = InterpreterFrameIterator(activation);
      while (data_.interpFrames_.frame() != frame) {
        ++data_.interpFrames_;
      }

      // Update the pc.
      MOZ_ASSERT(data_.interpFrames_.frame() == frame);
      data_.pc_ = data_.interpFrames_.pc();
      return;
    }
    case JIT:
      if (jsJitFrame().isBaselineJS()) {
        jit::BaselineFrame* frame = jsJitFrame().baselineFrame();
        jit::JitActivation* activation = data_.activations_->asJit();

        // activation's exitFP may be invalid, so create a new
        // activation iterator.
        data_.activations_ = ActivationIterator(data_.cx_);
        while (data_.activations_.activation() != activation) {
          ++data_.activations_;
        }

        // Look for the current frame.
        data_.jitFrames_ = JitFrameIter(data_.activations_->asJit());
        while (!isJSJit() || !jsJitFrame().isBaselineJS() ||
               jsJitFrame().baselineFrame() != frame) {
          ++data_.jitFrames_;
        }

        // Update the pc.
        MOZ_ASSERT(jsJitFrame().baselineFrame() == frame);
        jsJitFrame().baselineScriptAndPc(nullptr, &data_.pc_);
        return;
      }
      break;
  }
  MOZ_CRASH("Unexpected state");
}

void FrameIter::wasmUpdateBytecodeOffset() {
  MOZ_RELEASE_ASSERT(isWasm(), "Unexpected state");

  wasm::DebugFrame* frame = wasmFrame().debugFrame();

  // Relookup the current frame, updating the bytecode offset in the process.
  data_.jitFrames_ = JitFrameIter(data_.activations_->asJit());
  while (wasmFrame().debugFrame() != frame) {
    ++data_.jitFrames_;
  }

  MOZ_ASSERT(wasmFrame().debugFrame() == frame);
}

JSFunction* FrameIter::calleeTemplate() const {
  switch (data_.state_) {
    case DONE:
      break;
    case INTERP:
      MOZ_ASSERT(isFunctionFrame());
      return &interpFrame()->callee();
    case JIT:
      if (jsJitFrame().isBaselineJS()) {
        return jsJitFrame().callee();
      }
      MOZ_ASSERT(jsJitFrame().isIonScripted());
      return ionInlineFrames_.calleeTemplate();
  }
  MOZ_CRASH("Unexpected state");
}

JSFunction* FrameIter::callee(JSContext* cx) const {
  switch (data_.state_) {
    case DONE:
      break;
    case INTERP:
      return calleeTemplate();
    case JIT:
      if (isIonScripted()) {
        jit::MaybeReadFallback recover(cx, activation()->asJit(),
                                       &jsJitFrame());
        return ionInlineFrames_.callee(recover);
      }
      MOZ_ASSERT(jsJitFrame().isBaselineJS());
      return calleeTemplate();
  }
  MOZ_CRASH("Unexpected state");
}

bool FrameIter::matchCallee(JSContext* cx, HandleFunction fun) const {
  RootedFunction currentCallee(cx, calleeTemplate());

  // As we do not know if the calleeTemplate is the real function, or the
  // template from which it would be cloned, we compare properties which are
  // stable across the cloning of JSFunctions.
  if (((currentCallee->flags() ^ fun->flags()) &
       JSFunction::STABLE_ACROSS_CLONES) != 0 ||
      currentCallee->nargs() != fun->nargs()) {
    return false;
  }

  // Use the same condition as |js::CloneFunctionObject|, to know if we should
  // expect both functions to have the same JSScript. If so, and if they are
  // different, then they cannot be equal.
  RootedObject global(cx, &fun->global());
  bool useSameScript =
      CanReuseScriptForClone(fun->realm(), currentCallee, global);
  if (useSameScript &&
      (currentCallee->hasScript() != fun->hasScript() ||
       currentCallee->nonLazyScript() != fun->nonLazyScript())) {
    return false;
  }

  // If none of the previous filters worked, then take the risk of
  // invalidating the frame to identify the JSFunction.
  return callee(cx) == fun;
}

unsigned FrameIter::numActualArgs() const {
  switch (data_.state_) {
    case DONE:
      break;
    case INTERP:
      MOZ_ASSERT(isFunctionFrame());
      return interpFrame()->numActualArgs();
    case JIT:
      if (isIonScripted()) {
        return ionInlineFrames_.numActualArgs();
      }
      MOZ_ASSERT(jsJitFrame().isBaselineJS());
      return jsJitFrame().numActualArgs();
  }
  MOZ_CRASH("Unexpected state");
}

unsigned FrameIter::numFormalArgs() const {
  return script()->functionNonDelazifying()->nargs();
}

Value FrameIter::unaliasedActual(unsigned i,
                                 MaybeCheckAliasing checkAliasing) const {
  return abstractFramePtr().unaliasedActual(i, checkAliasing);
}

JSObject* FrameIter::environmentChain(JSContext* cx) const {
  switch (data_.state_) {
    case DONE:
      break;
    case JIT:
      if (isJSJit()) {
        if (isIonScripted()) {
          jit::MaybeReadFallback recover(cx, activation()->asJit(),
                                         &jsJitFrame());
          return ionInlineFrames_.environmentChain(recover);
        }
        return jsJitFrame().baselineFrame()->environmentChain();
      }
      MOZ_ASSERT(isWasm());
      return wasmFrame().debugFrame()->environmentChain();
    case INTERP:
      return interpFrame()->environmentChain();
  }
  MOZ_CRASH("Unexpected state");
}

bool FrameIter::hasInitialEnvironment(JSContext* cx) const {
  if (hasUsableAbstractFramePtr()) {
    return abstractFramePtr().hasInitialEnvironment();
  }

  if (isWasm()) {
    // See JSFunction::needsFunctionEnvironmentObjects().
    return false;
  }

  MOZ_ASSERT(isJSJit() && isIonScripted());
  bool hasInitialEnv = false;
  jit::MaybeReadFallback recover(cx, activation()->asJit(), &jsJitFrame());
  ionInlineFrames_.environmentChain(recover, &hasInitialEnv);

  return hasInitialEnv;
}

CallObject& FrameIter::callObj(JSContext* cx) const {
  MOZ_ASSERT(calleeTemplate()->needsCallObject());
  MOZ_ASSERT(hasInitialEnvironment(cx));

  JSObject* pobj = environmentChain(cx);
  while (!pobj->is<CallObject>()) {
    pobj = pobj->enclosingEnvironment();
  }
  return pobj->as<CallObject>();
}

bool FrameIter::hasArgsObj() const { return abstractFramePtr().hasArgsObj(); }

ArgumentsObject& FrameIter::argsObj() const {
  MOZ_ASSERT(hasArgsObj());
  return abstractFramePtr().argsObj();
}

Value FrameIter::thisArgument(JSContext* cx) const {
  MOZ_ASSERT(isFunctionFrame());

  switch (data_.state_) {
    case DONE:
      break;
    case JIT:
      if (isIonScripted()) {
        jit::MaybeReadFallback recover(cx, activation()->asJit(),
                                       &jsJitFrame());
        return ionInlineFrames_.thisArgument(recover);
      }
      return jsJitFrame().baselineFrame()->thisArgument();
    case INTERP:
      return interpFrame()->thisArgument();
  }
  MOZ_CRASH("Unexpected state");
}

Value FrameIter::newTarget() const {
  switch (data_.state_) {
    case DONE:
      break;
    case INTERP:
      return interpFrame()->newTarget();
    case JIT:
      MOZ_ASSERT(jsJitFrame().isBaselineJS());
      return jsJitFrame().baselineFrame()->newTarget();
  }
  MOZ_CRASH("Unexpected state");
}

Value FrameIter::returnValue() const {
  switch (data_.state_) {
    case DONE:
      break;
    case JIT:
      if (jsJitFrame().isBaselineJS()) {
        return jsJitFrame().baselineFrame()->returnValue();
      }
      break;
    case INTERP:
      return interpFrame()->returnValue();
  }
  MOZ_CRASH("Unexpected state");
}

void FrameIter::setReturnValue(const Value& v) {
  switch (data_.state_) {
    case DONE:
      break;
    case JIT:
      if (jsJitFrame().isBaselineJS()) {
        jsJitFrame().baselineFrame()->setReturnValue(v);
        return;
      }
      break;
    case INTERP:
      interpFrame()->setReturnValue(v);
      return;
  }
  MOZ_CRASH("Unexpected state");
}

size_t FrameIter::numFrameSlots() const {
  switch (data_.state_) {
    case DONE:
      break;
    case JIT: {
      if (isIonScripted()) {
        return ionInlineFrames_.snapshotIterator().numAllocations() -
               ionInlineFrames_.script()->nfixed();
      }
      jit::BaselineFrame* frame = jsJitFrame().baselineFrame();
      return frame->numValueSlots() - jsJitFrame().script()->nfixed();
    }
    case INTERP:
      MOZ_ASSERT(data_.interpFrames_.sp() >= interpFrame()->base());
      return data_.interpFrames_.sp() - interpFrame()->base();
  }
  MOZ_CRASH("Unexpected state");
}

Value FrameIter::frameSlotValue(size_t index) const {
  switch (data_.state_) {
    case DONE:
      break;
    case JIT:
      if (isIonScripted()) {
        jit::SnapshotIterator si(ionInlineFrames_.snapshotIterator());
        index += ionInlineFrames_.script()->nfixed();
        return si.maybeReadAllocByIndex(index);
      }
      index += jsJitFrame().script()->nfixed();
      return *jsJitFrame().baselineFrame()->valueSlot(index);
    case INTERP:
      return interpFrame()->base()[index];
  }
  MOZ_CRASH("Unexpected state");
}

#ifdef DEBUG
bool js::SelfHostedFramesVisible() {
  static bool checked = false;
  static bool visible = false;
  if (!checked) {
    checked = true;
    char* env = getenv("MOZ_SHOW_ALL_JS_FRAMES");
    visible = !!env;
  }
  return visible;
}
#endif

void NonBuiltinFrameIter::settle() {
  if (!SelfHostedFramesVisible()) {
    while (!done() && hasScript() && script()->selfHosted()) {
      FrameIter::operator++();
    }
  }
}

void NonBuiltinScriptFrameIter::settle() {
  if (!SelfHostedFramesVisible()) {
    while (!done() && script()->selfHosted()) {
      ScriptFrameIter::operator++();
    }
  }
}

Value ActivationEntryMonitor::asyncStack(JSContext* cx) {
  RootedValue stack(cx, ObjectOrNullValue(cx->asyncStackForNewActivations()));
  if (!cx->compartment()->wrap(cx, &stack)) {
    cx->clearPendingException();
    return UndefinedValue();
  }
  return stack;
}

void ActivationEntryMonitor::init(JSContext* cx, InterpreterFrame* entryFrame) {
  // The InterpreterFrame is not yet part of an Activation, so it won't
  // be traced if we trigger GC here. Suppress GC to avoid this.
  gc::AutoSuppressGC suppressGC(cx);
  RootedValue stack(cx, asyncStack(cx));
  const char* asyncCause = cx->asyncCauseForNewActivations;
  if (entryFrame->isFunctionFrame()) {
    entryMonitor_->Entry(cx, &entryFrame->callee(), stack, asyncCause);
  } else {
    entryMonitor_->Entry(cx, entryFrame->script(), stack, asyncCause);
  }
}

void ActivationEntryMonitor::init(JSContext* cx, jit::CalleeToken entryToken) {
  // The CalleeToken is not traced at this point and we also don't want
  // a GC to discard the code we're about to enter, so we suppress GC.
  gc::AutoSuppressGC suppressGC(cx);
  RootedValue stack(cx, asyncStack(cx));
  const char* asyncCause = cx->asyncCauseForNewActivations;
  if (jit::CalleeTokenIsFunction(entryToken)) {
    entryMonitor_->Entry(cx_, jit::CalleeTokenToFunction(entryToken), stack,
                         asyncCause);
  } else {
    entryMonitor_->Entry(cx_, jit::CalleeTokenToScript(entryToken), stack,
                         asyncCause);
  }
}

/*****************************************************************************/

jit::JitActivation::JitActivation(JSContext* cx)
    : Activation(cx, Jit),
      packedExitFP_(nullptr),
      encodedWasmExitReason_(0),
      prevJitActivation_(cx->jitActivation),
      rematerializedFrames_(),
      ionRecovery_(cx),
      bailoutData_(nullptr),
      lastProfilingFrame_(nullptr),
      lastProfilingCallSite_(nullptr) {
  cx->jitActivation = this;
  registerProfiling();
}

jit::JitActivation::~JitActivation() {
  if (isProfiling()) {
    unregisterProfiling();
  }
  cx_->jitActivation = prevJitActivation_;

  // All reocvered value are taken from activation during the bailout.
  MOZ_ASSERT(ionRecovery_.empty());

  // The BailoutFrameInfo should have unregistered itself from the
  // JitActivations.
  MOZ_ASSERT(!bailoutData_);

  // Traps get handled immediately.
  MOZ_ASSERT(!isWasmTrapping());

  clearRematerializedFrames();
}

void jit::JitActivation::setBailoutData(jit::BailoutFrameInfo* bailoutData) {
  MOZ_ASSERT(!bailoutData_);
  bailoutData_ = bailoutData;
}

void jit::JitActivation::cleanBailoutData() {
  MOZ_ASSERT(bailoutData_);
  bailoutData_ = nullptr;
}

void jit::JitActivation::removeRematerializedFrame(uint8_t* top) {
  if (!rematerializedFrames_) {
    return;
  }

  if (RematerializedFrameTable::Ptr p = rematerializedFrames_->lookup(top)) {
    rematerializedFrames_->remove(p);
  }
}

void jit::JitActivation::clearRematerializedFrames() {
  if (!rematerializedFrames_) {
    return;
  }

  for (RematerializedFrameTable::Enum e(*rematerializedFrames_); !e.empty();
       e.popFront()) {
    e.removeFront();
  }
}

jit::RematerializedFrame* jit::JitActivation::getRematerializedFrame(
    JSContext* cx, const JSJitFrameIter& iter, size_t inlineDepth) {
  MOZ_ASSERT(iter.activation() == this);
  MOZ_ASSERT(iter.isIonScripted());

  if (!rematerializedFrames_) {
    rematerializedFrames_ = cx->make_unique<RematerializedFrameTable>(cx);
    if (!rematerializedFrames_) {
      return nullptr;
    }
  }

  uint8_t* top = iter.fp();
  RematerializedFrameTable::AddPtr p = rematerializedFrames_->lookupForAdd(top);
  if (!p) {
    RematerializedFrameVector frames(cx);

    // The unit of rematerialization is an uninlined frame and its inlined
    // frames. Since inlined frames do not exist outside of snapshots, it
    // is impossible to synchronize their rematerialized copies to
    // preserve identity. Therefore, we always rematerialize an uninlined
    // frame and all its inlined frames at once.
    InlineFrameIterator inlineIter(cx, &iter);
    MaybeReadFallback recover(cx, this, &iter);

    // Frames are often rematerialized with the cx inside a Debugger's
    // realm. To recover slots and to create CallObjects, we need to
    // be in the script's realm.
    AutoRealmUnchecked ar(cx, iter.script()->realm());

    if (!RematerializedFrame::RematerializeInlineFrames(cx, top, inlineIter,
                                                        recover, frames)) {
      return nullptr;
    }

    if (!rematerializedFrames_->add(p, top, std::move(frames))) {
      ReportOutOfMemory(cx);
      return nullptr;
    }

    // See comment in unsetPrevUpToDateUntil.
    DebugEnvironments::unsetPrevUpToDateUntil(cx,
                                              p->value()[inlineDepth].get());
  }

  return p->value()[inlineDepth].get();
}

jit::RematerializedFrame* jit::JitActivation::lookupRematerializedFrame(
    uint8_t* top, size_t inlineDepth) {
  if (!rematerializedFrames_) {
    return nullptr;
  }
  if (RematerializedFrameTable::Ptr p = rematerializedFrames_->lookup(top)) {
    return inlineDepth < p->value().length() ? p->value()[inlineDepth].get()
                                             : nullptr;
  }
  return nullptr;
}

void jit::JitActivation::removeRematerializedFramesFromDebugger(JSContext* cx,
                                                                uint8_t* top) {
  // Ion bailout can fail due to overrecursion and OOM. In such cases we
  // cannot honor any further Debugger hooks on the frame, and need to
  // ensure that its Debugger.Frame entry is cleaned up.
  if (!cx->realm()->isDebuggee() || !rematerializedFrames_) {
    return;
  }
  if (RematerializedFrameTable::Ptr p = rematerializedFrames_->lookup(top)) {
    for (uint32_t i = 0; i < p->value().length(); i++) {
      Debugger::handleUnrecoverableIonBailoutError(cx, p->value()[i].get());
    }
    rematerializedFrames_->remove(p);
  }
}

void jit::JitActivation::traceRematerializedFrames(JSTracer* trc) {
  if (!rematerializedFrames_) {
    return;
  }
  for (RematerializedFrameTable::Enum e(*rematerializedFrames_); !e.empty();
       e.popFront()) {
    e.front().value().trace(trc);
  }
}

bool jit::JitActivation::registerIonFrameRecovery(
    RInstructionResults&& results) {
  // Check that there is no entry in the vector yet.
  MOZ_ASSERT(!maybeIonFrameRecovery(results.frame()));
  if (!ionRecovery_.append(std::move(results))) {
    return false;
  }

  return true;
}

jit::RInstructionResults* jit::JitActivation::maybeIonFrameRecovery(
    JitFrameLayout* fp) {
  for (RInstructionResults* it = ionRecovery_.begin(); it != ionRecovery_.end();
       it++) {
    if (it->frame() == fp) {
      return it;
    }
  }

  return nullptr;
}

void jit::JitActivation::removeIonFrameRecovery(JitFrameLayout* fp) {
  RInstructionResults* elem = maybeIonFrameRecovery(fp);
  if (!elem) {
    return;
  }

  ionRecovery_.erase(elem);
}

void jit::JitActivation::traceIonRecovery(JSTracer* trc) {
  for (RInstructionResults* it = ionRecovery_.begin(); it != ionRecovery_.end();
       it++) {
    it->trace(trc);
  }
}

void jit::JitActivation::startWasmTrap(wasm::Trap trap, uint32_t bytecodeOffset,
                                       const wasm::RegisterState& state) {
  MOZ_ASSERT(!isWasmTrapping());

  bool unwound;
  wasm::UnwindState unwindState;
  MOZ_RELEASE_ASSERT(wasm::StartUnwinding(state, &unwindState, &unwound));
  MOZ_ASSERT(unwound == (trap == wasm::Trap::IndirectCallBadSig));

  void* pc = unwindState.pc;
  wasm::Frame* fp = unwindState.fp;

  const wasm::Code& code = fp->tls->instance->code();
  MOZ_RELEASE_ASSERT(&code == wasm::LookupCode(pc));

  // If the frame was unwound, the bytecodeOffset must be recovered from the
  // callsite so that it is accurate.
  if (unwound) {
    bytecodeOffset = code.lookupCallSite(pc)->lineOrBytecode();
  }

  setWasmExitFP(fp);
  wasmTrapData_.emplace();
  wasmTrapData_->resumePC =
      ((uint8_t*)state.pc) + jit::WasmTrapInstructionLength;
  wasmTrapData_->unwoundPC = pc;
  wasmTrapData_->trap = trap;
  wasmTrapData_->bytecodeOffset = bytecodeOffset;

  MOZ_ASSERT(isWasmTrapping());
}

void jit::JitActivation::finishWasmTrap() {
  MOZ_ASSERT(isWasmTrapping());
  packedExitFP_ = nullptr;
  wasmTrapData_.reset();
  MOZ_ASSERT(!isWasmTrapping());
}

InterpreterFrameIterator& InterpreterFrameIterator::operator++() {
  MOZ_ASSERT(!done());
  if (fp_ != activation_->entryFrame_) {
    pc_ = fp_->prevpc();
    sp_ = fp_->prevsp();
    fp_ = fp_->prev();
  } else {
    pc_ = nullptr;
    sp_ = nullptr;
    fp_ = nullptr;
  }
  return *this;
}

void Activation::registerProfiling() {
  MOZ_ASSERT(isProfiling());
  cx_->profilingActivation_ = this;
}

void Activation::unregisterProfiling() {
  MOZ_ASSERT(isProfiling());
  MOZ_ASSERT(cx_->profilingActivation_ == this);
  cx_->profilingActivation_ = prevProfiling_;
}

ActivationIterator::ActivationIterator(JSContext* cx)
    : activation_(cx->activation_) {
  MOZ_ASSERT(cx == TlsContext.get());
}

ActivationIterator& ActivationIterator::operator++() {
  MOZ_ASSERT(activation_);
  activation_ = activation_->prev();
  return *this;
}

JS::ProfilingFrameIterator::ProfilingFrameIterator(
    JSContext* cx, const RegisterState& state,
    const Maybe<uint64_t>& samplePositionInProfilerBuffer)
    : cx_(cx),
      samplePositionInProfilerBuffer_(samplePositionInProfilerBuffer),
      activation_(nullptr) {
  if (!cx->runtime()->geckoProfiler().enabled()) {
    MOZ_CRASH(
        "ProfilingFrameIterator called when geckoProfiler not enabled for "
        "runtime.");
  }

  if (!cx->profilingActivation()) {
    return;
  }

  // If profiler sampling is not enabled, skip.
  if (!cx->isProfilerSamplingEnabled()) {
    return;
  }

  activation_ = cx->profilingActivation();

  MOZ_ASSERT(activation_->isProfiling());

  static_assert(sizeof(wasm::ProfilingFrameIterator) <= StorageSpace &&
                    sizeof(jit::JSJitProfilingFrameIterator) <= StorageSpace,
                "ProfilingFrameIterator::storage_ is too small");
  static_assert(alignof(void*) >= alignof(wasm::ProfilingFrameIterator) &&
                    alignof(void*) >= alignof(jit::JSJitProfilingFrameIterator),
                "ProfilingFrameIterator::storage_ is too weakly aligned");

  iteratorConstruct(state);
  settle();
}

JS::ProfilingFrameIterator::~ProfilingFrameIterator() {
  if (!done()) {
    MOZ_ASSERT(activation_->isProfiling());
    iteratorDestroy();
  }
}

void JS::ProfilingFrameIterator::operator++() {
  MOZ_ASSERT(!done());
  MOZ_ASSERT(activation_->isJit());
  if (isWasm()) {
    ++wasmIter();
  } else {
    ++jsJitIter();
  }
  settle();
}

void JS::ProfilingFrameIterator::settleFrames() {
  // Handle transition frames (see comment in JitFrameIter::operator++).
  if (isJSJit() && !jsJitIter().done() &&
      jsJitIter().frameType() == jit::FrameType::WasmToJSJit) {
    wasm::Frame* fp = (wasm::Frame*)jsJitIter().fp();
    iteratorDestroy();
    new (storage()) wasm::ProfilingFrameIterator(*activation_->asJit(), fp);
    kind_ = Kind::Wasm;
    MOZ_ASSERT(!wasmIter().done());
    return;
  }

  if (isWasm() && wasmIter().done() && wasmIter().unwoundIonCallerFP()) {
    uint8_t* fp = wasmIter().unwoundIonCallerFP();
    iteratorDestroy();
    // Using this ctor will skip the first ion->wasm frame, which is
    // needed because the profiling iterator doesn't know how to unwind
    // when the callee has no script.
    new (storage())
        jit::JSJitProfilingFrameIterator((jit::CommonFrameLayout*)fp);
    kind_ = Kind::JSJit;
    MOZ_ASSERT(!jsJitIter().done());
    return;
  }
}

void JS::ProfilingFrameIterator::settle() {
  settleFrames();
  while (iteratorDone()) {
    iteratorDestroy();
    activation_ = activation_->prevProfiling();
    if (!activation_) {
      return;
    }
    iteratorConstruct();
    settleFrames();
  }
}

void JS::ProfilingFrameIterator::iteratorConstruct(const RegisterState& state) {
  MOZ_ASSERT(!done());
  MOZ_ASSERT(activation_->isJit());

  jit::JitActivation* activation = activation_->asJit();

  // We want to know if we should start with a wasm profiling frame iterator
  // or not. To determine this, there are three possibilities:
  // - we've exited to C++ from wasm, in which case the activation
  //   exitFP low bit is tagged and we can test hasWasmExitFP().
  // - we're in wasm code, so we can do a lookup on PC.
  // - in all the other cases, we're not in wasm or we haven't exited from
  //   wasm.
  if (activation->hasWasmExitFP() || wasm::InCompiledCode(state.pc)) {
    new (storage()) wasm::ProfilingFrameIterator(*activation, state);
    kind_ = Kind::Wasm;
    return;
  }

  new (storage()) jit::JSJitProfilingFrameIterator(cx_, state.pc);
  kind_ = Kind::JSJit;
}

void JS::ProfilingFrameIterator::iteratorConstruct() {
  MOZ_ASSERT(!done());
  MOZ_ASSERT(activation_->isJit());

  jit::JitActivation* activation = activation_->asJit();

  // The same reasoning as in the above iteratorConstruct variant applies
  // here, except that it's even simpler: since this activation is higher up
  // on the stack, it can only have exited to C++, through wasm or ion.
  if (activation->hasWasmExitFP()) {
    new (storage()) wasm::ProfilingFrameIterator(*activation);
    kind_ = Kind::Wasm;
    return;
  }

  auto* fp = (jit::ExitFrameLayout*)activation->jsExitFP();
  new (storage()) jit::JSJitProfilingFrameIterator(fp);
  kind_ = Kind::JSJit;
}

void JS::ProfilingFrameIterator::iteratorDestroy() {
  MOZ_ASSERT(!done());
  MOZ_ASSERT(activation_->isJit());

  if (isWasm()) {
    wasmIter().~ProfilingFrameIterator();
    return;
  }

  jsJitIter().~JSJitProfilingFrameIterator();
}

bool JS::ProfilingFrameIterator::iteratorDone() {
  MOZ_ASSERT(!done());
  MOZ_ASSERT(activation_->isJit());

  if (isWasm()) {
    return wasmIter().done();
  }

  return jsJitIter().done();
}

void* JS::ProfilingFrameIterator::stackAddress() const {
  MOZ_ASSERT(!done());
  MOZ_ASSERT(activation_->isJit());

  if (isWasm()) {
    return wasmIter().stackAddress();
  }

  return jsJitIter().stackAddress();
}

Maybe<JS::ProfilingFrameIterator::Frame>
JS::ProfilingFrameIterator::getPhysicalFrameAndEntry(
    jit::JitcodeGlobalEntry* entry) const {
  void* stackAddr = stackAddress();

  if (isWasm()) {
    Frame frame;
    frame.kind = Frame_Wasm;
    frame.stackAddress = stackAddr;
    frame.returnAddress = nullptr;
    frame.activation = activation_;
    frame.label = nullptr;
    frame.endStackAddress = activation_->asJit()->jsOrWasmExitFP();
    return mozilla::Some(frame);
  }

  MOZ_ASSERT(isJSJit());

  // Look up an entry for the return address.
  void* returnAddr = jsJitIter().resumePCinCurrentFrame();
  jit::JitcodeGlobalTable* table =
      cx_->runtime()->jitRuntime()->getJitcodeGlobalTable();
  if (samplePositionInProfilerBuffer_) {
    *entry = table->lookupForSamplerInfallible(
        returnAddr, cx_->runtime(), *samplePositionInProfilerBuffer_);
  } else {
    *entry = table->lookupInfallible(returnAddr);
  }

  MOZ_ASSERT(entry->isIon() || entry->isIonCache() || entry->isBaseline() ||
             entry->isDummy());

  // Dummy frames produce no stack frames.
  if (entry->isDummy()) {
    return mozilla::Nothing();
  }

  Frame frame;
  frame.kind = entry->isBaseline() ? Frame_Baseline : Frame_Ion;
  frame.stackAddress = stackAddr;
  frame.returnAddress = returnAddr;
  frame.activation = activation_;
  frame.label = nullptr;
  frame.endStackAddress = activation_->asJit()->jsOrWasmExitFP();
  return mozilla::Some(frame);
}

uint32_t JS::ProfilingFrameIterator::extractStack(Frame* frames,
                                                  uint32_t offset,
                                                  uint32_t end) const {
  if (offset >= end) {
    return 0;
  }

  jit::JitcodeGlobalEntry entry;
  Maybe<Frame> physicalFrame = getPhysicalFrameAndEntry(&entry);

  // Dummy frames produce no stack frames.
  if (physicalFrame.isNothing()) {
    return 0;
  }

  if (isWasm()) {
    frames[offset] = physicalFrame.value();
    frames[offset].label = wasmIter().label();
    return 1;
  }

  // Extract the stack for the entry.  Assume maximum inlining depth is <64
  const char* labels[64];
  uint32_t depth = entry.callStackAtAddr(cx_->runtime(),
                                         jsJitIter().resumePCinCurrentFrame(),
                                         labels, ArrayLength(labels));
  MOZ_ASSERT(depth < ArrayLength(labels));
  for (uint32_t i = 0; i < depth; i++) {
    if (offset + i >= end) {
      return i;
    }
    frames[offset + i] = physicalFrame.value();
    frames[offset + i].label = labels[i];
  }

  return depth;
}

Maybe<JS::ProfilingFrameIterator::Frame>
JS::ProfilingFrameIterator::getPhysicalFrameWithoutLabel() const {
  jit::JitcodeGlobalEntry unused;
  return getPhysicalFrameAndEntry(&unused);
}

bool JS::ProfilingFrameIterator::isWasm() const {
  MOZ_ASSERT(!done());
  return kind_ == Kind::Wasm;
}

bool JS::ProfilingFrameIterator::isJSJit() const {
  return kind_ == Kind::JSJit;
}