Source code

Revision control

Other Tools

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 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188
/* -*- Mode: C++; tab-width: 2; 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 "base/basictypes.h"

#include "jsfriendapi.h"

#include "nsAutoPtr.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsJSNPRuntime.h"
#include "nsNPAPIPlugin.h"
#include "nsNPAPIPluginInstance.h"
#include "nsIGlobalObject.h"
#include "nsIScriptGlobalObject.h"
#include "nsIScriptContext.h"
#include "nsDOMJSUtils.h"
#include "nsJSUtils.h"
#include "mozilla/dom/Document.h"
#include "nsIXPConnect.h"
#include "xpcpublic.h"
#include "nsIContent.h"
#include "nsPluginInstanceOwner.h"
#include "nsWrapperCacheInlines.h"
#include "js/GCHashTable.h"
#include "js/Symbol.h"
#include "js/TracingAPI.h"
#include "js/Wrapper.h"
#include "mozilla/HashFunctions.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/dom/ScriptSettings.h"

#define NPRUNTIME_JSCLASS_NAME "NPObject JS wrapper class"

using namespace mozilla::plugins::parent;
using namespace mozilla;

#include "mozilla/plugins/PluginScriptableObjectParent.h"
using mozilla::plugins::ParentNPObject;
using mozilla::plugins::PluginScriptableObjectParent;

struct JSObjWrapperHasher {
  typedef nsJSObjWrapperKey Key;
  typedef Key Lookup;

  static uint32_t hash(const Lookup& l) {
    return js::MovableCellHasher<JS::Heap<JSObject*>>::hash(l.mJSObj) ^
           HashGeneric(l.mNpp);
  }

  static bool match(const Key& k, const Lookup& l) {
    return js::MovableCellHasher<JS::Heap<JSObject*>>::match(k.mJSObj,
                                                             l.mJSObj) &&
           k.mNpp == l.mNpp;
  }
};

namespace JS {
template <>
struct GCPolicy<nsJSObjWrapper*> {
  static void trace(JSTracer* trc, nsJSObjWrapper** wrapper, const char* name) {
    MOZ_ASSERT(wrapper);
    MOZ_ASSERT(*wrapper);
    (*wrapper)->trace(trc);
  }

  static bool isValid(const nsJSObjWrapper *&wrapper) {
    return true;
  }
};
}  // namespace JS

class NPObjWrapperHashEntry : public PLDHashEntryHdr {
 public:
  NPObject* mNPObj;  // Must be the first member for the PLDHash stubs to work
  JS::TenuredHeap<JSObject*> mJSObj;
  NPP mNpp;
};

// Hash of JSObject wrappers that wraps JSObjects as NPObjects. There
// will be one wrapper per JSObject per plugin instance, i.e. if two
// plugins access the JSObject x, two wrappers for x will be
// created. This is needed to be able to properly drop the wrappers
// when a plugin is torn down in case there's a leak in the plugin (we
// don't want to leak the world just because a plugin leaks an
// NPObject).
typedef JS::GCHashMap<nsJSObjWrapperKey, nsJSObjWrapper*, JSObjWrapperHasher,
                      js::SystemAllocPolicy>
    JSObjWrapperTable;
static UniquePtr<JSObjWrapperTable> sJSObjWrappers;

// Whether it's safe to iterate sJSObjWrappers.  Set to true when sJSObjWrappers
// has been initialized and is not currently being enumerated.
static bool sJSObjWrappersAccessible = false;

// Hash of NPObject wrappers that wrap NPObjects as JSObjects.
static PLDHashTable* sNPObjWrappers;

// Global wrapper count. This includes JSObject wrappers *and*
// NPObject wrappers. When this count goes to zero, there are no more
// wrappers and we can kill off hash tables etc.
static int32_t sWrapperCount;

static bool sCallbackIsRegistered = false;

static nsTArray<NPObject*>* sDelayedReleases;

namespace {

inline bool NPObjectIsOutOfProcessProxy(NPObject* obj) {
  return obj->_class == PluginScriptableObjectParent::GetClass();
}

}  // namespace

// Helper class that suppresses any JS exceptions that were thrown while
// the plugin executed JS, if the nsJSObjWrapper has a destroy pending.
// Note that this class is the product (vestige?) of a long evolution in how
// error reporting worked, and hence the mIsDestroyPending check, and hence this
// class in general, may or may not actually be necessary.

class MOZ_STACK_CLASS AutoJSExceptionSuppressor {
 public:
  AutoJSExceptionSuppressor(dom::AutoEntryScript& aes, nsJSObjWrapper* aWrapper)
      : mAes(aes), mIsDestroyPending(aWrapper->mDestroyPending) {}

  ~AutoJSExceptionSuppressor() {
    if (mIsDestroyPending) {
      mAes.ClearException();
    }
  }

 protected:
  dom::AutoEntryScript& mAes;
  bool mIsDestroyPending;
};

NPClass nsJSObjWrapper::sJSObjWrapperNPClass = {
    NP_CLASS_STRUCT_VERSION,           nsJSObjWrapper::NP_Allocate,
    nsJSObjWrapper::NP_Deallocate,     nsJSObjWrapper::NP_Invalidate,
    nsJSObjWrapper::NP_HasMethod,      nsJSObjWrapper::NP_Invoke,
    nsJSObjWrapper::NP_InvokeDefault,  nsJSObjWrapper::NP_HasProperty,
    nsJSObjWrapper::NP_GetProperty,    nsJSObjWrapper::NP_SetProperty,
    nsJSObjWrapper::NP_RemoveProperty, nsJSObjWrapper::NP_Enumerate,
    nsJSObjWrapper::NP_Construct};

class NPObjWrapperProxyHandler : public js::BaseProxyHandler {
  static const char family;

 public:
  static const NPObjWrapperProxyHandler singleton;

  constexpr NPObjWrapperProxyHandler() : BaseProxyHandler(&family) {}

  bool defineProperty(JSContext* cx, JS::Handle<JSObject*> proxy,
                      JS::Handle<jsid> id,
                      JS::Handle<JS::PropertyDescriptor> desc,
                      JS::ObjectOpResult& result) const override {
    ::JS_ReportErrorASCII(cx,
                          "Trying to add unsupported property on NPObject!");
    return false;
  }

  bool getPrototypeIfOrdinary(
      JSContext* cx, JS::Handle<JSObject*> proxy, bool* isOrdinary,
      JS::MutableHandle<JSObject*> proto) const override {
    *isOrdinary = true;
    proto.set(js::GetStaticPrototype(proxy));
    return true;
  }

  bool isExtensible(JSContext* cx, JS::Handle<JSObject*> proxy,
                    bool* extensible) const override {
    // Needs to be extensible so nsObjectLoadingContent can mutate our
    // __proto__.
    *extensible = true;
    return true;
  }

  bool preventExtensions(JSContext* cx, JS::Handle<JSObject*> proxy,
                         JS::ObjectOpResult& result) const override {
    result.succeed();
    return true;
  }

  bool getOwnPropertyDescriptor(
      JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id,
      JS::MutableHandle<JS::PropertyDescriptor> desc) const override;

  bool ownPropertyKeys(JSContext* cx, JS::Handle<JSObject*> proxy,
                       JS::MutableHandleVector<jsid> properties) const override;

  bool delete_(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id,
               JS::ObjectOpResult& result) const override;

  bool get(JSContext* cx, JS::Handle<JSObject*> proxy,
           JS::Handle<JS::Value> receiver, JS::Handle<jsid> id,
           JS::MutableHandle<JS::Value> vp) const override;

  bool set(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id,
           JS::Handle<JS::Value> vp, JS::Handle<JS::Value> receiver,
           JS::ObjectOpResult& result) const override;

  bool isCallable(JSObject* obj) const override { return true; }
  bool call(JSContext* cx, JS::Handle<JSObject*> proxy,
            const JS::CallArgs& args) const override;

  bool isConstructor(JSObject* obj) const override { return true; }
  bool construct(JSContext* cx, JS::Handle<JSObject*> proxy,
                 const JS::CallArgs& args) const override;

  bool finalizeInBackground(const JS::Value& priv) const override {
    return false;
  }
  void finalize(JSFreeOp* fop, JSObject* proxy) const override;

  size_t objectMoved(JSObject* obj, JSObject* old) const override;
};

const char NPObjWrapperProxyHandler::family = 0;
const NPObjWrapperProxyHandler NPObjWrapperProxyHandler::singleton;

static bool NPObjWrapper_Resolve(JSContext* cx, JS::Handle<JSObject*> obj,
                                 JS::Handle<jsid> id, bool* resolved,
                                 JS::MutableHandle<JSObject*> method);

static bool NPObjWrapper_toPrimitive(JSContext* cx, unsigned argc,
                                     JS::Value* vp);

static bool CreateNPObjectMember(NPP npp, JSContext* cx,
                                 JS::Handle<JSObject*> obj, NPObject* npobj,
                                 JS::Handle<jsid> id,
                                 NPVariant* getPropertyResult,
                                 JS::MutableHandle<JS::Value> vp);

const js::Class sNPObjWrapperProxyClass =
    PROXY_CLASS_DEF(NPRUNTIME_JSCLASS_NAME, JSCLASS_HAS_RESERVED_SLOTS(1));

typedef struct NPObjectMemberPrivate {
  JS::Heap<JSObject*> npobjWrapper;
  JS::Heap<JS::Value> fieldValue;
  JS::Heap<jsid> methodName;
  NPP npp = nullptr;
} NPObjectMemberPrivate;

static void NPObjectMember_Finalize(JSFreeOp* fop, JSObject* obj);

static bool NPObjectMember_Call(JSContext* cx, unsigned argc, JS::Value* vp);

static void NPObjectMember_Trace(JSTracer* trc, JSObject* obj);

static bool NPObjectMember_toPrimitive(JSContext* cx, unsigned argc,
                                       JS::Value* vp);

static const JSClassOps sNPObjectMemberClassOps = {nullptr,
                                                   nullptr,
                                                   nullptr,
                                                   nullptr,
                                                   nullptr,
                                                   nullptr,
                                                   NPObjectMember_Finalize,
                                                   NPObjectMember_Call,
                                                   nullptr,
                                                   nullptr,
                                                   NPObjectMember_Trace};

static const JSClass sNPObjectMemberClass = {
    "NPObject Ambiguous Member class",
    JSCLASS_HAS_PRIVATE | JSCLASS_FOREGROUND_FINALIZE,
    &sNPObjectMemberClassOps};

static void OnWrapperDestroyed();

static void TraceJSObjWrappers(JSTracer* trc, void* data) {
  if (sJSObjWrappers) {
    sJSObjWrappers->trace(trc);
  }
}

static void DelayedReleaseGCCallback(JSGCStatus status) {
  if (JSGC_END == status) {
    // Take ownership of sDelayedReleases and null it out now. The
    // _releaseobject call below can reenter GC and double-free these objects.
    nsAutoPtr<nsTArray<NPObject*>> delayedReleases(sDelayedReleases);
    sDelayedReleases = nullptr;

    if (delayedReleases) {
      for (uint32_t i = 0; i < delayedReleases->Length(); ++i) {
        NPObject* obj = (*delayedReleases)[i];
        if (obj) _releaseobject(obj);
        OnWrapperDestroyed();
      }
    }
  }
}

static bool RegisterGCCallbacks() {
  if (sCallbackIsRegistered) {
    return true;
  }

  // Register a callback to trace wrapped JSObjects.
  JSContext* cx = dom::danger::GetJSContext();
  if (!JS_AddExtraGCRootsTracer(cx, TraceJSObjWrappers, nullptr)) {
    return false;
  }

  // Register our GC callback to perform delayed destruction of finalized
  // NPObjects.
  xpc::AddGCCallback(DelayedReleaseGCCallback);

  sCallbackIsRegistered = true;

  return true;
}

static void UnregisterGCCallbacks() {
  MOZ_ASSERT(sCallbackIsRegistered);

  // Remove tracing callback.
  JSContext* cx = dom::danger::GetJSContext();
  JS_RemoveExtraGCRootsTracer(cx, TraceJSObjWrappers, nullptr);

  // Remove delayed destruction callback.
  if (sCallbackIsRegistered) {
    xpc::RemoveGCCallback(DelayedReleaseGCCallback);
    sCallbackIsRegistered = false;
  }
}

static bool CreateJSObjWrapperTable() {
  MOZ_ASSERT(!sJSObjWrappersAccessible);
  MOZ_ASSERT(!sJSObjWrappers);

  if (!RegisterGCCallbacks()) {
    return false;
  }

  sJSObjWrappers = MakeUnique<JSObjWrapperTable>();
  sJSObjWrappersAccessible = true;
  return true;
}

static void DestroyJSObjWrapperTable() {
  MOZ_ASSERT(sJSObjWrappersAccessible);
  MOZ_ASSERT(sJSObjWrappers);
  MOZ_ASSERT(sJSObjWrappers->count() == 0);

  // No more wrappers. Delete the table.
  sJSObjWrappers = nullptr;
  sJSObjWrappersAccessible = false;
}

static bool CreateNPObjWrapperTable() {
  MOZ_ASSERT(!sNPObjWrappers);

  if (!RegisterGCCallbacks()) {
    return false;
  }

  sNPObjWrappers =
      new PLDHashTable(PLDHashTable::StubOps(), sizeof(NPObjWrapperHashEntry));
  return true;
}

static void DestroyNPObjWrapperTable() {
  MOZ_ASSERT(sNPObjWrappers->EntryCount() == 0);

  delete sNPObjWrappers;
  sNPObjWrappers = nullptr;
}

static void OnWrapperCreated() { ++sWrapperCount; }

static void OnWrapperDestroyed() {
  NS_ASSERTION(sWrapperCount, "Whaaa, unbalanced created/destroyed calls!");

  if (--sWrapperCount == 0) {
    if (sJSObjWrappersAccessible) {
      DestroyJSObjWrapperTable();
    }

    if (sNPObjWrappers) {
      // No more wrappers, and our hash was initialized. Finish the
      // hash to prevent leaking it.
      DestroyNPObjWrapperTable();
    }

    UnregisterGCCallbacks();
  }
}

namespace mozilla {
namespace plugins {
namespace parent {

static nsIGlobalObject* GetGlobalObject(NPP npp) {
  NS_ENSURE_TRUE(npp, nullptr);

  nsNPAPIPluginInstance* inst = (nsNPAPIPluginInstance*)npp->ndata;
  NS_ENSURE_TRUE(inst, nullptr);

  RefPtr<nsPluginInstanceOwner> owner = inst->GetOwner();
  NS_ENSURE_TRUE(owner, nullptr);

  nsCOMPtr<dom::Document> doc;
  owner->GetDocument(getter_AddRefs(doc));
  NS_ENSURE_TRUE(doc, nullptr);

  return doc->GetScopeObject();
}

}  // namespace parent
}  // namespace plugins
}  // namespace mozilla

static NPP LookupNPP(NPObject* npobj);

static JS::Value NPVariantToJSVal(NPP npp, JSContext* cx,
                                  const NPVariant* variant) {
  switch (variant->type) {
    case NPVariantType_Void:
      return JS::UndefinedValue();
    case NPVariantType_Null:
      return JS::NullValue();
    case NPVariantType_Bool:
      return JS::BooleanValue(NPVARIANT_TO_BOOLEAN(*variant));
    case NPVariantType_Int32: {
      // Don't use INT_TO_JSVAL directly to prevent bugs when dealing
      // with ints larger than what fits in a integer JS::Value.
      return ::JS_NumberValue(NPVARIANT_TO_INT32(*variant));
    }
    case NPVariantType_Double: {
      return ::JS_NumberValue(NPVARIANT_TO_DOUBLE(*variant));
    }
    case NPVariantType_String: {
      const NPString* s = &NPVARIANT_TO_STRING(*variant);
      NS_ConvertUTF8toUTF16 utf16String(s->UTF8Characters, s->UTF8Length);

      JSString* str =
          ::JS_NewUCStringCopyN(cx, utf16String.get(), utf16String.Length());

      if (str) {
        return JS::StringValue(str);
      }

      break;
    }
    case NPVariantType_Object: {
      if (npp) {
        JSObject* obj = nsNPObjWrapper::GetNewOrUsed(
            npp, cx, NPVARIANT_TO_OBJECT(*variant));

        if (obj) {
          return JS::ObjectValue(*obj);
        }
      }

      NS_ERROR("Error wrapping NPObject!");

      break;
    }
    default:
      NS_ERROR("Unknown NPVariant type!");
  }

  NS_ERROR("Unable to convert NPVariant to jsval!");

  return JS::UndefinedValue();
}

bool JSValToNPVariant(NPP npp, JSContext* cx, const JS::Value& val,
                      NPVariant* variant) {
  NS_ASSERTION(npp, "Must have an NPP to wrap a jsval!");

  if (val.isPrimitive()) {
    if (val.isUndefined()) {
      VOID_TO_NPVARIANT(*variant);
    } else if (val.isNull()) {
      NULL_TO_NPVARIANT(*variant);
    } else if (val.isBoolean()) {
      BOOLEAN_TO_NPVARIANT(val.toBoolean(), *variant);
    } else if (val.isInt32()) {
      INT32_TO_NPVARIANT(val.toInt32(), *variant);
    } else if (val.isDouble()) {
      double d = val.toDouble();
      int i;
      if (JS_DoubleIsInt32(d, &i)) {
        INT32_TO_NPVARIANT(i, *variant);
      } else {
        DOUBLE_TO_NPVARIANT(d, *variant);
      }
    } else if (val.isString()) {
      JSString* jsstr = val.toString();

      nsAutoJSString str;
      if (!str.init(cx, jsstr)) {
        return false;
      }

      uint32_t len;
      char* p = ToNewUTF8String(str, &len);

      if (!p) {
        return false;
      }

      STRINGN_TO_NPVARIANT(p, len, *variant);
    } else {
      NS_ERROR("Unknown primitive type!");

      return false;
    }

    return true;
  }

  // The reflected plugin object may be in another compartment if the plugin
  // element has since been adopted into a new document. We don't bother
  // transplanting the plugin objects, and just do a unwrap with security
  // checks if we encounter one of them as an argument. If the unwrap fails,
  // we run with the original wrapped object, since sometimes there are
  // legitimate cases where a security wrapper ends up here (for example,
  // Location objects, which are _always_ behind security wrappers).
  JS::Rooted<JSObject*> obj(cx, &val.toObject());
  JS::Rooted<JSObject*> global(cx);
  // CheckedUnwrapStatic is fine here; if we get a Location or WindowProxy,
  // we'll just use the current global instead.
  obj = js::CheckedUnwrapStatic(obj);
  if (obj) {
    global = JS::GetNonCCWObjectGlobal(obj);
  } else {
    obj = &val.toObject();
    global = JS::CurrentGlobalOrNull(cx);
  }

  NPObject* npobj = nsJSObjWrapper::GetNewOrUsed(npp, obj, global);
  if (!npobj) {
    return false;
  }

  // Pass over ownership of npobj to *variant
  OBJECT_TO_NPVARIANT(npobj, *variant);

  return true;
}

static void ThrowJSExceptionASCII(JSContext* cx, const char* message) {
  const char* ex = PeekException();

  if (ex) {
    nsAutoString ucex;

    if (message) {
      AppendASCIItoUTF16(mozilla::MakeStringSpan(message), ucex);

      ucex.AppendLiteral(" [plugin exception: ");
    }

    AppendUTF8toUTF16(mozilla::MakeStringSpan(ex), ucex);

    if (message) {
      ucex.AppendLiteral("].");
    }

    JSString* str = ::JS_NewUCStringCopyN(cx, ucex.get(), ucex.Length());

    if (str) {
      JS::Rooted<JS::Value> exn(cx, JS::StringValue(str));
      ::JS_SetPendingException(cx, exn);
    }

    PopException();
  } else {
    ::JS_ReportErrorASCII(cx, "%s", message);
  }
}

static bool ReportExceptionIfPending(JSContext* cx) {
  const char* ex = PeekException();

  if (!ex) {
    return true;
  }

  ThrowJSExceptionASCII(cx, nullptr);

  return false;
}

nsJSObjWrapper::nsJSObjWrapper(NPP npp)
    : mJSObj(nullptr),
      mJSObjGlobal(nullptr),
      mNpp(npp),
      mDestroyPending(false) {
  MOZ_COUNT_CTOR(nsJSObjWrapper);
  OnWrapperCreated();
}

nsJSObjWrapper::~nsJSObjWrapper() {
  MOZ_COUNT_DTOR(nsJSObjWrapper);

  // Invalidate first, since it relies on sJSObjWrappers.
  NP_Invalidate(this);

  OnWrapperDestroyed();
}

// static
NPObject* nsJSObjWrapper::NP_Allocate(NPP npp, NPClass* aClass) {
  NS_ASSERTION(aClass == &sJSObjWrapperNPClass,
               "Huh, wrong class passed to NP_Allocate()!!!");

  return new nsJSObjWrapper(npp);
}

// static
void nsJSObjWrapper::NP_Deallocate(NPObject* npobj) {
  // nsJSObjWrapper::~nsJSObjWrapper() will call NP_Invalidate().
  delete (nsJSObjWrapper*)npobj;
}

// static
void nsJSObjWrapper::NP_Invalidate(NPObject* npobj) {
  nsJSObjWrapper* jsnpobj = (nsJSObjWrapper*)npobj;

  if (jsnpobj && jsnpobj->mJSObj) {
    if (sJSObjWrappersAccessible) {
      // Remove the wrapper from the hash
      nsJSObjWrapperKey key(jsnpobj->mJSObj, jsnpobj->mNpp);
      JSObjWrapperTable::Ptr ptr = sJSObjWrappers->lookup(key);
      MOZ_ASSERT(ptr.found());
      sJSObjWrappers->remove(ptr);
    }

    // Forget our reference to the JSObject.
    jsnpobj->mJSObj = nullptr;
    jsnpobj->mJSObjGlobal = nullptr;
  }
}

static bool GetProperty(JSContext* cx, JSObject* objArg, NPIdentifier npid,
                        JS::MutableHandle<JS::Value> rval) {
  NS_ASSERTION(NPIdentifierIsInt(npid) || NPIdentifierIsString(npid),
               "id must be either string or int!\n");
  JS::Rooted<JSObject*> obj(cx, objArg);
  JS::Rooted<jsid> id(cx, NPIdentifierToJSId(npid));
  return ::JS_GetPropertyById(cx, obj, id, rval);
}

static void MarkCrossZoneNPIdentifier(JSContext* cx, NPIdentifier npid) {
  JS_MarkCrossZoneId(cx, NPIdentifierToJSId(npid));
}

// static
bool nsJSObjWrapper::NP_HasMethod(NPObject* npobj, NPIdentifier id) {
  NPP npp = NPPStack::Peek();
  nsIGlobalObject* globalObject = GetGlobalObject(npp);
  if (NS_WARN_IF(!globalObject)) {
    return false;
  }

  dom::AutoEntryScript aes(globalObject, "NPAPI HasMethod");
  JSContext* cx = aes.cx();

  if (!npobj) {
    ThrowJSExceptionASCII(cx, "Null npobj in nsJSObjWrapper::NP_HasMethod!");

    return false;
  }

  nsJSObjWrapper* npjsobj = (nsJSObjWrapper*)npobj;

  JSAutoRealm ar(cx, npjsobj->mJSObjGlobal);
  MarkCrossZoneNPIdentifier(cx, id);

  AutoJSExceptionSuppressor suppressor(aes, npjsobj);

  JS::Rooted<JS::Value> v(cx);
  bool ok = GetProperty(cx, npjsobj->mJSObj, id, &v);

  return ok && !v.isPrimitive() && ::JS_ObjectIsFunction(v.toObjectOrNull());
}

static bool doInvoke(NPObject* npobj, NPIdentifier method,
                     const NPVariant* args, uint32_t argCount, bool ctorCall,
                     NPVariant* result) {
  NPP npp = NPPStack::Peek();

  nsCOMPtr<nsIGlobalObject> globalObject = GetGlobalObject(npp);
  if (NS_WARN_IF(!globalObject)) {
    return false;
  }

  // We're about to run script via JS_CallFunctionValue, so we need an
  // AutoEntryScript. NPAPI plugins are Gecko-specific and not in any spec.
  dom::AutoEntryScript aes(globalObject, "NPAPI doInvoke");
  JSContext* cx = aes.cx();

  if (!npobj || !result) {
    ThrowJSExceptionASCII(cx, "Null npobj, or result in doInvoke!");

    return false;
  }

  // Initialize *result
  VOID_TO_NPVARIANT(*result);

  nsJSObjWrapper* npjsobj = (nsJSObjWrapper*)npobj;

  JS::Rooted<JSObject*> jsobj(cx, npjsobj->mJSObj);
  JSAutoRealm ar(cx, npjsobj->mJSObjGlobal);
  MarkCrossZoneNPIdentifier(cx, method);
  JS::Rooted<JS::Value> fv(cx);

  AutoJSExceptionSuppressor suppressor(aes, npjsobj);

  if (method != NPIdentifier_VOID) {
    if (!GetProperty(cx, jsobj, method, &fv) ||
        ::JS_TypeOfValue(cx, fv) != JSTYPE_FUNCTION) {
      return false;
    }
  } else {
    fv.setObject(*jsobj);
  }

  // Convert args
  JS::RootedVector<JS::Value> jsargs(cx);
  if (!jsargs.reserve(argCount)) {
    ::JS_ReportOutOfMemory(cx);
    return false;
  }
  for (uint32_t i = 0; i < argCount; ++i) {
    jsargs.infallibleAppend(NPVariantToJSVal(npp, cx, args + i));
  }

  JS::Rooted<JS::Value> v(cx);
  bool ok = false;

  if (ctorCall) {
    JSObject* newObj = ::JS_New(cx, jsobj, jsargs);

    if (newObj) {
      v.setObject(*newObj);
      ok = true;
    }
  } else {
    ok = ::JS_CallFunctionValue(cx, jsobj, fv, jsargs, &v);
  }

  if (ok) ok = JSValToNPVariant(npp, cx, v, result);

  return ok;
}

// static
bool nsJSObjWrapper::NP_Invoke(NPObject* npobj, NPIdentifier method,
                               const NPVariant* args, uint32_t argCount,
                               NPVariant* result) {
  if (method == NPIdentifier_VOID) {
    return false;
  }

  return doInvoke(npobj, method, args, argCount, false, result);
}

// static
bool nsJSObjWrapper::NP_InvokeDefault(NPObject* npobj, const NPVariant* args,
                                      uint32_t argCount, NPVariant* result) {
  return doInvoke(npobj, NPIdentifier_VOID, args, argCount, false, result);
}

// static
bool nsJSObjWrapper::NP_HasProperty(NPObject* npobj, NPIdentifier npid) {
  NPP npp = NPPStack::Peek();
  nsIGlobalObject* globalObject = GetGlobalObject(npp);
  if (NS_WARN_IF(!globalObject)) {
    return false;
  }

  dom::AutoEntryScript aes(globalObject, "NPAPI HasProperty");
  JSContext* cx = aes.cx();

  if (!npobj) {
    ThrowJSExceptionASCII(cx, "Null npobj in nsJSObjWrapper::NP_HasProperty!");

    return false;
  }

  nsJSObjWrapper* npjsobj = (nsJSObjWrapper*)npobj;
  bool found, ok = false;

  AutoJSExceptionSuppressor suppressor(aes, npjsobj);
  JS::Rooted<JSObject*> jsobj(cx, npjsobj->mJSObj);
  JSAutoRealm ar(cx, npjsobj->mJSObjGlobal);
  MarkCrossZoneNPIdentifier(cx, npid);

  NS_ASSERTION(NPIdentifierIsInt(npid) || NPIdentifierIsString(npid),
               "id must be either string or int!\n");
  JS::Rooted<jsid> id(cx, NPIdentifierToJSId(npid));
  ok = ::JS_HasPropertyById(cx, jsobj, id, &found);
  return ok && found;
}

// static
bool nsJSObjWrapper::NP_GetProperty(NPObject* npobj, NPIdentifier id,
                                    NPVariant* result) {
  NPP npp = NPPStack::Peek();

  nsCOMPtr<nsIGlobalObject> globalObject = GetGlobalObject(npp);
  if (NS_WARN_IF(!globalObject)) {
    return false;
  }

  // We're about to run script via JS_CallFunctionValue, so we need an
  // AutoEntryScript. NPAPI plugins are Gecko-specific and not in any spec.
  dom::AutoEntryScript aes(globalObject, "NPAPI get");
  JSContext* cx = aes.cx();

  if (!npobj) {
    ThrowJSExceptionASCII(cx, "Null npobj in nsJSObjWrapper::NP_GetProperty!");

    return false;
  }

  nsJSObjWrapper* npjsobj = (nsJSObjWrapper*)npobj;

  AutoJSExceptionSuppressor suppressor(aes, npjsobj);
  JSAutoRealm ar(cx, npjsobj->mJSObjGlobal);
  MarkCrossZoneNPIdentifier(cx, id);

  JS::Rooted<JS::Value> v(cx);
  return (GetProperty(cx, npjsobj->mJSObj, id, &v) &&
          JSValToNPVariant(npp, cx, v, result));
}

// static
bool nsJSObjWrapper::NP_SetProperty(NPObject* npobj, NPIdentifier npid,
                                    const NPVariant* value) {
  NPP npp = NPPStack::Peek();

  nsCOMPtr<nsIGlobalObject> globalObject = GetGlobalObject(npp);
  if (NS_WARN_IF(!globalObject)) {
    return false;
  }

  // We're about to run script via JS_CallFunctionValue, so we need an
  // AutoEntryScript. NPAPI plugins are Gecko-specific and not in any spec.
  dom::AutoEntryScript aes(globalObject, "NPAPI set");
  JSContext* cx = aes.cx();

  if (!npobj) {
    ThrowJSExceptionASCII(cx, "Null npobj in nsJSObjWrapper::NP_SetProperty!");

    return false;
  }

  nsJSObjWrapper* npjsobj = (nsJSObjWrapper*)npobj;
  bool ok = false;

  AutoJSExceptionSuppressor suppressor(aes, npjsobj);
  JS::Rooted<JSObject*> jsObj(cx, npjsobj->mJSObj);
  JSAutoRealm ar(cx, npjsobj->mJSObjGlobal);
  MarkCrossZoneNPIdentifier(cx, npid);

  JS::Rooted<JS::Value> v(cx, NPVariantToJSVal(npp, cx, value));

  NS_ASSERTION(NPIdentifierIsInt(npid) || NPIdentifierIsString(npid),
               "id must be either string or int!\n");
  JS::Rooted<jsid> id(cx, NPIdentifierToJSId(npid));
  ok = ::JS_SetPropertyById(cx, jsObj, id, v);

  return ok;
}

// static
bool nsJSObjWrapper::NP_RemoveProperty(NPObject* npobj, NPIdentifier npid) {
  NPP npp = NPPStack::Peek();
  nsIGlobalObject* globalObject = GetGlobalObject(npp);
  if (NS_WARN_IF(!globalObject)) {
    return false;
  }

  dom::AutoEntryScript aes(globalObject, "NPAPI RemoveProperty");
  JSContext* cx = aes.cx();

  if (!npobj) {
    ThrowJSExceptionASCII(cx,
                          "Null npobj in nsJSObjWrapper::NP_RemoveProperty!");

    return false;
  }

  nsJSObjWrapper* npjsobj = (nsJSObjWrapper*)npobj;

  AutoJSExceptionSuppressor suppressor(aes, npjsobj);
  JS::ObjectOpResult result;
  JS::Rooted<JSObject*> obj(cx, npjsobj->mJSObj);
  JSAutoRealm ar(cx, npjsobj->mJSObjGlobal);
  MarkCrossZoneNPIdentifier(cx, npid);

  NS_ASSERTION(NPIdentifierIsInt(npid) || NPIdentifierIsString(npid),
               "id must be either string or int!\n");
  JS::Rooted<jsid> id(cx, NPIdentifierToJSId(npid));
  if (!::JS_DeletePropertyById(cx, obj, id, result)) return false;

  if (result) {
    // FIXME: See bug 425823, we shouldn't need to do this, and once
    // that bug is fixed we can remove this code.
    bool hasProp;
    if (!::JS_HasPropertyById(cx, obj, id, &hasProp)) return false;
    if (!hasProp) return true;

    // The property might have been deleted, but it got
    // re-resolved, so no, it's not really deleted.
    result.failCantDelete();
  }

  return result.reportError(cx, obj, id);
}

// static
bool nsJSObjWrapper::NP_Enumerate(NPObject* npobj, NPIdentifier** idarray,
                                  uint32_t* count) {
  NPP npp = NPPStack::Peek();
  nsIGlobalObject* globalObject = GetGlobalObject(npp);
  if (NS_WARN_IF(!globalObject)) {
    return false;
  }

  dom::AutoEntryScript aes(globalObject, "NPAPI Enumerate");
  JSContext* cx = aes.cx();

  *idarray = 0;
  *count = 0;

  if (!npobj) {
    ThrowJSExceptionASCII(cx, "Null npobj in nsJSObjWrapper::NP_Enumerate!");

    return false;
  }

  nsJSObjWrapper* npjsobj = (nsJSObjWrapper*)npobj;

  AutoJSExceptionSuppressor suppressor(aes, npjsobj);
  JS::Rooted<JSObject*> jsobj(cx, npjsobj->mJSObj);
  JSAutoRealm ar(cx, npjsobj->mJSObjGlobal);

  JS::Rooted<JS::IdVector> ida(cx, JS::IdVector(cx));
  if (!JS_Enumerate(cx, jsobj, &ida)) {
    return false;
  }

  *count = ida.length();
  *idarray = (NPIdentifier*)malloc(*count * sizeof(NPIdentifier));
  if (!*idarray) {
    ThrowJSExceptionASCII(cx, "Memory allocation failed for NPIdentifier!");
    return false;
  }

  for (uint32_t i = 0; i < *count; i++) {
    JS::Rooted<JS::Value> v(cx);
    if (!JS_IdToValue(cx, ida[i], &v)) {
      free(*idarray);
      return false;
    }

    NPIdentifier id;
    if (v.isString()) {
      JS::Rooted<JSString*> str(cx, v.toString());
      str = JS_AtomizeAndPinJSString(cx, str);
      if (!str) {
        free(*idarray);
        return false;
      }
      id = StringToNPIdentifier(cx, str);
    } else {
      NS_ASSERTION(v.isInt32(),
                   "The element in ida must be either string or int!\n");
      id = IntToNPIdentifier(v.toInt32());
    }

    (*idarray)[i] = id;
  }

  return true;
}

// static
bool nsJSObjWrapper::NP_Construct(NPObject* npobj, const NPVariant* args,
                                  uint32_t argCount, NPVariant* result) {
  return doInvoke(npobj, NPIdentifier_VOID, args, argCount, true, result);
}

// Look up or create an NPObject that wraps the JSObject obj.

// static
NPObject* nsJSObjWrapper::GetNewOrUsed(NPP npp, JS::Handle<JSObject*> obj,
                                       JS::Handle<JSObject*> objGlobal) {
  if (!npp) {
    NS_ERROR("Null NPP passed to nsJSObjWrapper::GetNewOrUsed()!");

    return nullptr;
  }

  MOZ_ASSERT(JS_IsGlobalObject(objGlobal));
  MOZ_RELEASE_ASSERT(js::GetObjectCompartment(obj) ==
                     js::GetObjectCompartment(objGlobal));

  // No need to enter the right compartment here as we only get the
  // class and private from the JSObject, neither of which cares about
  // compartments.

  if (nsNPObjWrapper::IsWrapper(obj)) {
    // obj is one of our own, its private data is the NPObject we're
    // looking for.

    NPObject* npobj = (NPObject*)js::GetProxyPrivate(obj).toPrivate();

    // If the private is null, that means that the object has already been torn
    // down, possible because the owning plugin was destroyed (there can be
    // multiple plugins, so the fact that it was destroyed does not prevent one
    // of its dead JS objects from being passed to another plugin). There's not
    // much use in wrapping such a dead object, so we just return null, causing
    // us to throw.
    if (!npobj) return nullptr;

    if (LookupNPP(npobj) == npp) return _retainobject(npobj);
  }

  if (!sJSObjWrappers) {
    // No hash yet (or any more), initialize it.
    if (!CreateJSObjWrapperTable()) return nullptr;
  }
  MOZ_ASSERT(sJSObjWrappersAccessible);

  JSObjWrapperTable::Ptr p =
      sJSObjWrappers->lookup(nsJSObjWrapperKey(obj, npp));
  if (p) {
    MOZ_ASSERT(p->value());
    // Found a live nsJSObjWrapper, return it.

    return _retainobject(p->value());
  }

  // No existing nsJSObjWrapper, create one.

  nsJSObjWrapper* wrapper =
      (nsJSObjWrapper*)_createobject(npp, &sJSObjWrapperNPClass);

  if (!wrapper) {
    // Out of memory, entry not yet added to table.
    return nullptr;
  }

  wrapper->mJSObj = obj;
  wrapper->mJSObjGlobal = objGlobal;

  // Insert the new wrapper into the hashtable, rooting the JSObject. Its
  // lifetime is now tied to that of the NPObject.
  if (!sJSObjWrappers->putNew(nsJSObjWrapperKey(obj, npp), wrapper)) {
    // Out of memory, free the wrapper we created.
    _releaseobject(wrapper);
    return nullptr;
  }

  return wrapper;
}

// Climb the prototype chain, unwrapping as necessary until we find an NP object
// wrapper.
//
// Because this function unwraps, its return value must be wrapped for the cx
// compartment for callers that plan to hold onto the result or do anything
// substantial with it.
static JSObject* GetNPObjectWrapper(JSContext* cx, JS::Handle<JSObject*> aObj,
                                    bool wrapResult = true) {
  JS::Rooted<JSObject*> obj(cx, aObj);

  // We can't have WindowProxy or Location objects with NP object wrapper
  // objects on their proto chain, since they have immutable prototypes.  So
  // CheckedUnwrapStatic is ok here.
  while (obj && (obj = js::CheckedUnwrapStatic(obj))) {
    if (nsNPObjWrapper::IsWrapper(obj)) {
      if (wrapResult && !JS_WrapObject(cx, &obj)) {
        return nullptr;
      }
      return obj;
    }

    JSAutoRealm ar(cx, obj);
    if (!::JS_GetPrototype(cx, obj, &obj)) {
      return nullptr;
    }
  }
  return nullptr;
}

static NPObject* GetNPObject(JSContext* cx, JS::Handle<JSObject*> aObj) {
  JS::Rooted<JSObject*> obj(cx, aObj);
  obj = GetNPObjectWrapper(cx, obj, /* wrapResult = */ false);
  if (!obj) {
    return nullptr;
  }

  return (NPObject*)js::GetProxyPrivate(obj).toPrivate();
}

static JSObject* NPObjWrapper_GetResolvedProps(JSContext* cx,
                                               JS::Handle<JSObject*> obj) {
  JS::Value slot = js::GetProxyReservedSlot(obj, 0);
  if (slot.isObject()) return &slot.toObject();

  MOZ_ASSERT(slot.isUndefined());

  JSObject* res = JS_NewObject(cx, nullptr);
  if (!res) return nullptr;

  SetProxyReservedSlot(obj, 0, JS::ObjectValue(*res));
  return res;
}

bool NPObjWrapperProxyHandler::delete_(JSContext* cx,
                                       JS::Handle<JSObject*> proxy,
                                       JS::Handle<jsid> id,
                                       JS::ObjectOpResult& result) const {
  NPObject* npobj = GetNPObject(cx, proxy);

  if (!npobj || !npobj->_class || !npobj->_class->hasProperty ||
      !npobj->_class->removeProperty) {
    ThrowJSExceptionASCII(cx, "Bad NPObject as private data!");

    return false;
  }

  JS::Rooted<JSObject*> resolvedProps(cx,
                                      NPObjWrapper_GetResolvedProps(cx, proxy));
  if (!resolvedProps) return false;
  if (!JS_DeletePropertyById(cx, resolvedProps, id, result)) return false;

  PluginDestructionGuard pdg(LookupNPP(npobj));

  NPIdentifier identifier = JSIdToNPIdentifier(id);

  if (!NPObjectIsOutOfProcessProxy(npobj)) {
    bool hasProperty = npobj->_class->hasProperty(npobj, identifier);
    if (!ReportExceptionIfPending(cx)) return false;

    if (!hasProperty) return result.succeed();
  }

  // This removeProperty hook may throw an exception and return false; or just
  // return false without an exception pending, which behaves like `delete
  // obj.prop` returning false: in strict mode it becomes a TypeError. Legacy
  // code---nothing else that uses the JSAPI works this way anymore.
  bool succeeded = npobj->_class->removeProperty(npobj, identifier);
  if (!ReportExceptionIfPending(cx)) return false;
  return succeeded ? result.succeed() : result.failCantDelete();
}

bool NPObjWrapperProxyHandler::set(JSContext* cx, JS::Handle<JSObject*> proxy,
                                   JS::Handle<jsid> id,
                                   JS::Handle<JS::Value> vp,
                                   JS::Handle<JS::Value> receiver,
                                   JS::ObjectOpResult& result) const {
  NPObject* npobj = GetNPObject(cx, proxy);

  if (!npobj || !npobj->_class || !npobj->_class->hasProperty ||
      !npobj->_class->setProperty) {
    ThrowJSExceptionASCII(cx, "Bad NPObject as private data!");

    return false;
  }

  // Find out what plugin (NPP) is the owner of the object we're
  // manipulating, and make it own any JSObject wrappers created here.
  NPP npp = LookupNPP(npobj);

  if (!npp) {
    ThrowJSExceptionASCII(cx, "No NPP found for NPObject!");

    return false;
  }

  {
    bool resolved = false;
    JS::Rooted<JSObject*> method(cx);
    if (!NPObjWrapper_Resolve(cx, proxy, id, &resolved, &method)) return false;
    if (!resolved) {
      // We don't have a property/method with this id. Forward to the prototype
      // chain.
      return js::BaseProxyHandler::set(cx, proxy, id, vp, receiver, result);
    }
  }

  PluginDestructionGuard pdg(npp);

  NPIdentifier identifier = JSIdToNPIdentifier(id);

  if (!NPObjectIsOutOfProcessProxy(npobj)) {
    bool hasProperty = npobj->_class->hasProperty(npobj, identifier);
    if (!ReportExceptionIfPending(cx)) return false;

    if (!hasProperty) {
      ThrowJSExceptionASCII(cx,
                            "Trying to set unsupported property on NPObject!");

      return false;
    }
  }

  NPVariant npv;
  if (!JSValToNPVariant(npp, cx, vp, &npv)) {
    ThrowJSExceptionASCII(cx, "Error converting jsval to NPVariant!");

    return false;
  }

  bool ok = npobj->_class->setProperty(npobj, identifier, &npv);
  _releasevariantvalue(&npv);  // Release the variant
  if (!ReportExceptionIfPending(cx)) return false;

  if (!ok) {
    ThrowJSExceptionASCII(cx, "Error setting property on NPObject!");

    return false;
  }

  return result.succeed();
}

static bool CallNPMethod(JSContext* cx, unsigned argc, JS::Value* vp);

bool NPObjWrapperProxyHandler::get(JSContext* cx, JS::Handle<JSObject*> proxy,
                                   JS::Handle<JS::Value> receiver,
                                   JS::Handle<jsid> id,
                                   JS::MutableHandle<JS::Value> vp) const {
  NPObject* npobj = GetNPObject(cx, proxy);

  if (!npobj || !npobj->_class || !npobj->_class->hasProperty ||
      !npobj->_class->hasMethod || !npobj->_class->getProperty) {
    ThrowJSExceptionASCII(cx, "Bad NPObject as private data!");

    return false;
  }

  if (JSID_IS_SYMBOL(id)) {
    JS::RootedSymbol sym(cx, JSID_TO_SYMBOL(id));
    if (JS::GetSymbolCode(sym) == JS::SymbolCode::toPrimitive) {
      JS::RootedObject obj(
          cx, JS_GetFunctionObject(JS_NewFunction(cx, NPObjWrapper_toPrimitive,
                                                  1, 0, "Symbol.toPrimitive")));
      if (!obj) return false;
      vp.setObject(*obj);
      return true;
    }

    if (JS::GetSymbolCode(sym) == JS::SymbolCode::toStringTag) {
      JS::RootedString tag(cx, JS_NewStringCopyZ(cx, NPRUNTIME_JSCLASS_NAME));
      if (!tag) {
        return false;
      }

      vp.setString(tag);
      return true;
    }

    return js::BaseProxyHandler::get(cx, proxy, receiver, id, vp);
  }

  // Find out what plugin (NPP) is the owner of the object we're
  // manipulating, and make it own any JSObject wrappers created here.
  NPP npp = LookupNPP(npobj);
  if (!npp) {
    ThrowJSExceptionASCII(cx, "No NPP found for NPObject!");

    return false;
  }

  {
    bool resolved = false;
    JS::Rooted<JSObject*> method(cx);
    if (!NPObjWrapper_Resolve(cx, proxy, id, &resolved, &method)) return false;
    if (method) {
      vp.setObject(*method);
      return true;
    }
    if (!resolved) {
      // We don't have a property/method with this id. Forward to the prototype
      // chain.
      return js::BaseProxyHandler::get(cx, proxy, receiver, id, vp);
    }
  }

  PluginDestructionGuard pdg(npp);

  bool hasProperty, hasMethod;

  NPVariant npv;
  VOID_TO_NPVARIANT(npv);

  NPIdentifier identifier = JSIdToNPIdentifier(id);

  if (NPObjectIsOutOfProcessProxy(npobj)) {
    PluginScriptableObjectParent* actor =
        static_cast<ParentNPObject*>(npobj)->parent;

    // actor may be null if the plugin crashed.
    if (!actor) return false;

    bool success =
        actor->GetPropertyHelper(identifier, &hasProperty, &hasMethod, &npv);

    if (!ReportExceptionIfPending(cx)) {
      if (success) _releasevariantvalue(&npv);
      return false;
    }

    if (success) {
      // We return NPObject Member class here to support ambiguous members.
      if (hasProperty && hasMethod)
        return CreateNPObjectMember(npp, cx, proxy, npobj, id, &npv, vp);

      if (hasProperty) {
        vp.set(NPVariantToJSVal(npp, cx, &npv));
        _releasevariantvalue(&npv);

        if (!ReportExceptionIfPending(cx)) return false;
        return true;
      }
    }
    return js::BaseProxyHandler::get(cx, proxy, receiver, id, vp);
  }

  hasProperty = npobj->_class->hasProperty(npobj, identifier);
  if (!ReportExceptionIfPending(cx)) return false;

  hasMethod = npobj->_class->hasMethod(npobj, identifier);
  if (!ReportExceptionIfPending(cx)) return false;

  // We return NPObject Member class here to support ambiguous members.
  if (hasProperty && hasMethod)
    return CreateNPObjectMember(npp, cx, proxy, npobj, id, nullptr, vp);

  if (hasProperty) {
    if (npobj->_class->getProperty(npobj, identifier, &npv))
      vp.set(NPVariantToJSVal(npp, cx, &npv));

    _releasevariantvalue(&npv);

    if (!ReportExceptionIfPending(cx)) return false;
    return true;
  }

  return js::BaseProxyHandler::get(cx, proxy, receiver, id, vp);
}

static bool CallNPMethodInternal(JSContext* cx, JS::Handle<JSObject*> obj,
                                 unsigned argc, JS::Value* argv,
                                 JS::Value* rval, bool ctorCall) {
  NPObject* npobj = GetNPObject(cx, obj);

  if (!npobj || !npobj->_class) {
    ThrowJSExceptionASCII(cx, "Bad NPObject as private data!");

    return false;
  }

  // Find out what plugin (NPP) is the owner of the object we're
  // manipulating, and make it own any JSObject wrappers created here.
  NPP npp = LookupNPP(npobj);

  if (!npp) {
    ThrowJSExceptionASCII(cx, "Error finding NPP for NPObject!");

    return false;
  }

  PluginDestructionGuard pdg(npp);

  NPVariant npargs_buf[8];
  NPVariant* npargs = npargs_buf;

  if (argc > (sizeof(npargs_buf) / sizeof(NPVariant))) {
    // Our stack buffer isn't large enough to hold all arguments,
    // malloc a buffer.
    npargs = (NPVariant*)malloc(argc * sizeof(NPVariant));

    if (!npargs) {
      ThrowJSExceptionASCII(cx, "Out of memory!");

      return false;
    }
  }

  // Convert arguments
  uint32_t i;
  for (i = 0; i < argc; ++i) {
    if (!JSValToNPVariant(npp, cx, argv[i], npargs + i)) {
      ThrowJSExceptionASCII(cx, "Error converting jsvals to NPVariants!");

      if (npargs != npargs_buf) {
        free(npargs);
      }

      return false;
    }
  }

  NPVariant v;
  VOID_TO_NPVARIANT(v);

  JSObject* funobj = argv[-2].toObjectOrNull();
  bool ok;
  const char* msg = "Error calling method on NPObject!";

  if (ctorCall) {
    // construct a new NPObject based on the NPClass in npobj. Fail if
    // no construct method is available.

    if (NP_CLASS_STRUCT_VERSION_HAS_CTOR(npobj->_class) &&
        npobj->_class->construct) {
      ok = npobj->_class->construct(npobj, npargs, argc, &v);
    } else {
      ok = false;

      msg = "Attempt to construct object from class with no constructor.";
    }
  } else if (funobj != obj) {
    // A obj.function() style call is made, get the method name from
    // the function object.

    if (npobj->_class->invoke) {
      JSFunction* fun = ::JS_GetObjectFunction(funobj);
      JS::Rooted<JSString*> funId(cx, ::JS_GetFunctionId(fun));
      JSString* name = ::JS_AtomizeAndPinJSString(cx, funId);
      NPIdentifier id = StringToNPIdentifier(cx, name);

      ok = npobj->_class->invoke(npobj, id, npargs, argc, &v);
    } else {
      ok = false;

      msg = "Attempt to call a method on object with no invoke method.";
    }
  } else {
    if (npobj->_class->invokeDefault) {
      // obj is a callable object that is being called, no method name
      // available then. Invoke the default method.

      ok = npobj->_class->invokeDefault(npobj, npargs, argc, &v);
    } else {
      ok = false;

      msg =
          "Attempt to call a default method on object with no "
          "invokeDefault method.";
    }
  }

  // Release arguments.
  for (i = 0; i < argc; ++i) {
    _releasevariantvalue(npargs + i);
  }

  if (npargs != npargs_buf) {
    free(npargs);
  }

  if (!ok) {
    // ReportExceptionIfPending returns a return value, which is true
    // if no exception was thrown. In that case, throw our own.
    if (ReportExceptionIfPending(cx)) ThrowJSExceptionASCII(cx, msg);

    return false;
  }

  *rval = NPVariantToJSVal(npp, cx, &v);

  // *rval now owns the value, release our reference.
  _releasevariantvalue(&v);

  return ReportExceptionIfPending(cx);
}

static bool CallNPMethod(JSContext* cx, unsigned argc, JS::Value* vp) {
  JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
  if (!args.thisv().isObject()) {
    ThrowJSExceptionASCII(cx,
                          "plug-in method called on incompatible non-object");
    return false;
  }
  JS::Rooted<JSObject*> obj(cx, &args.thisv().toObject());
  return CallNPMethodInternal(cx, obj, args.length(), args.array(), vp, false);
}

bool NPObjWrapperProxyHandler::getOwnPropertyDescriptor(
    JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id,
    JS::MutableHandle<JS::PropertyDescriptor> desc) const {
  bool resolved = false;
  JS::Rooted<JSObject*> method(cx);
  if (!NPObjWrapper_Resolve(cx, proxy, id, &resolved, &method)) return false;
  if (!resolved) {
    // No such property.
    desc.object().set(nullptr);
    return true;
  }

  // This returns a descriptor with |null| JS value if this is a plugin
  // property (as opposed to a method). That should be fine, hopefully, as the
  // previous code had very inconsistent behavior in this case as well. The main
  // reason for returning a descriptor here is to make property enumeration work
  // correctly (it will call getOwnPropertyDescriptor to check enumerability).
  JS::Rooted<JS::Value> val(cx, JS::ObjectOrNullValue(method));
  desc.initFields(proxy, val, JSPROP_ENUMERATE, nullptr, nullptr);
  return true;
}

bool NPObjWrapperProxyHandler::ownPropertyKeys(
    JSContext* cx, JS::Handle<JSObject*> proxy,
    JS::MutableHandleVector<jsid> properties) const {
  NPObject* npobj = GetNPObject(cx, proxy);
  if (!npobj || !npobj->_class) {
    ThrowJSExceptionASCII(cx, "Bad NPObject as private data!");
    return false;
  }

  PluginDestructionGuard pdg(LookupNPP(npobj));

  if (!NP_CLASS_STRUCT_VERSION_HAS_ENUM(npobj->_class) ||
      !npobj->_class->enumerate) {
    return true;
  }

  NPIdentifier* identifiers;
  uint32_t length;
  if (!npobj->_class->enumerate(npobj, &identifiers, &length)) {
    if (ReportExceptionIfPending(cx)) {
      // ReportExceptionIfPending returns a return value, which is true
      // if no exception was thrown. In that case, throw our own.
      ThrowJSExceptionASCII(cx,
                            "Error enumerating properties on scriptable "
                            "plugin object");
    }
    return false;
  }

  if (!properties.reserve(length)) return false;

  JS::Rooted<jsid> id(cx);
  for (uint32_t i = 0; i < length; i++) {
    id = NPIdentifierToJSId(identifiers[i]);
    properties.infallibleAppend(id);
  }

  free(identifiers);
  return true;
}

// This function is very similar to a resolve hook for native objects. Instead
// of defining properties on the object, it defines them on a resolvedProps
// object (a plain JS object that's never exposed to script) that's stored in
// the NPObjWrapper proxy's reserved slot. The behavior is as follows:
//
// - *resolvedp is set to true iff the plugin object has a property or method
//   (or both) with this id.
//
// - If the plugin object has a *property* with this id, the caller is
//   responsible for getting/setting its value. In this case we assign |null|
//   to resolvedProps[id] so we don't have to call hasProperty each time.
//
// - If the plugin object has a *method* with this id, we create a JSFunction to
//   call it and assign it to resolvedProps[id]. This function is also assigned
//   to the |method| outparam so callers can return it directly if we're doing a
//   |get|.
static bool NPObjWrapper_Resolve(JSContext* cx, JS::Handle<JSObject*> obj,
                                 JS::Handle<jsid> id, bool* resolvedp,
                                 JS::MutableHandle<JSObject*> method) {
  if (JSID_IS_SYMBOL(id)) return true;

  AUTO_PROFILER_LABEL("NPObjWrapper_Resolve", JS);

  NPObject* npobj = GetNPObject(cx, obj);

  if (!npobj || !npobj->_class || !npobj->_class->hasProperty ||
      !npobj->_class->hasMethod) {
    ThrowJSExceptionASCII(cx, "Bad NPObject as private data!");

    return false;
  }

  JS::Rooted<JSObject*> resolvedProps(cx,
                                      NPObjWrapper_GetResolvedProps(cx, obj));
  if (!resolvedProps) return false;
  JS::Rooted<JS::Value> res(cx);
  if (!JS_GetPropertyById(cx, resolvedProps, id, &res)) return false;
  if (res.isObjectOrNull()) {
    method.set(res.toObjectOrNull());
    *resolvedp = true;
    return true;
  }

  PluginDestructionGuard pdg(LookupNPP(npobj));

  NPIdentifier identifier = JSIdToNPIdentifier(id);

  bool hasProperty = npobj->_class->hasProperty(npobj, identifier);
  if (!ReportExceptionIfPending(cx)) return false;

  if (hasProperty) {
    if (!JS_SetPropertyById(cx, resolvedProps, id, JS::NullHandleValue))
      return false;
    *resolvedp = true;

    return true;
  }

  bool hasMethod = npobj->_class->hasMethod(npobj, identifier);
  if (!ReportExceptionIfPending(cx)) return false;

  if (hasMethod) {
    NS_ASSERTION(JSID_IS_STRING(id) || JSID_IS_INT(id),
                 "id must be either string or int!\n");

    JSFunction* fnc = ::JS_DefineFunctionById(
        cx, resolvedProps, id, CallNPMethod, 0, JSPROP_ENUMERATE);
    if (!fnc) return false;

    method.set(JS_GetFunctionObject(fnc));
    *resolvedp = true;
    return true;
  }

  // no property or method
  return true;
}

void NPObjWrapperProxyHandler::finalize(JSFreeOp* fop, JSObject* proxy) const {
  JS::AutoAssertGCCallback inCallback;

  NPObject* npobj = (NPObject*)js::GetProxyPrivate(proxy).toPrivate();
  if (npobj) {
    if (sNPObjWrappers) {
      // If the sNPObjWrappers map contains an entry that refers to this
      // wrapper, remove it.
      auto entry =
          static_cast<NPObjWrapperHashEntry*>(sNPObjWrappers->Search(npobj));
      if (entry && entry->mJSObj == proxy) {
        sNPObjWrappers->Remove(npobj);
      }
    }
  }

  if (!sDelayedReleases) sDelayedReleases = new nsTArray<NPObject*>;
  sDelayedReleases->AppendElement(npobj);
}

size_t NPObjWrapperProxyHandler::objectMoved(JSObject* obj,
                                             JSObject* old) const {
  // The wrapper JSObject has been moved, so we need to update the entry in the
  // sNPObjWrappers hash table, if present.

  if (!sNPObjWrappers) {
    return 0;
  }

  NPObject* npobj = (NPObject*)js::GetProxyPrivate(obj).toPrivate();
  if (!npobj) {
    return 0;
  }

  // Calling PLDHashTable::Search() will not result in GC.
  JS::AutoSuppressGCAnalysis nogc;

  auto entry =
      static_cast<NPObjWrapperHashEntry*>(sNPObjWrappers->Search(npobj));
  MOZ_ASSERT(entry && entry->mJSObj);
  MOZ_ASSERT(entry->mJSObj == old);
  entry->mJSObj = obj;
  return 0;
}

bool NPObjWrapperProxyHandler::call(JSContext* cx, JS::Handle<JSObject*> proxy,
                                    const JS::CallArgs& args) const {
  return CallNPMethodInternal(cx, proxy, args.length(), args.array(),
                              args.rval().address(), false);
}

bool NPObjWrapperProxyHandler::construct(JSContext* cx,
                                         JS::Handle<JSObject*> proxy,
                                         const JS::CallArgs& args) const {
  return CallNPMethodInternal(cx, proxy, args.length(), args.array(),
                              args.rval().address(), true);
}

static bool NPObjWrapper_toPrimitive(JSContext* cx, unsigned argc,
                                     JS::Value* vp) {
  // Plugins do not simply use the default OrdinaryToPrimitive behavior,
  // because that behavior involves calling toString or valueOf on objects
  // which weren't designed to accommodate this.  Usually this wouldn't be a
  // problem, because the absence of either property, or the presence of either
  // property with a value that isn't callable, will cause that property to
  // simply be ignored.  But there is a problem in one specific case: Java,
  // specifically java.lang.Integer.  The Integer class has static valueOf
  // methods, none of which are nullary, so the JS-reflected method will behave
  // poorly when called with no arguments.  We work around this problem by
  // giving plugins a [Symbol.toPrimitive]() method which uses only toString
  // and not valueOf.

  JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
  JS::RootedValue thisv(cx, args.thisv());
  if (thisv.isPrimitive()) return true;

  JS::RootedObject obj(cx, &thisv.toObject());
  JS::RootedValue v(cx);
  if (!JS_GetProperty(cx, obj, "toString", &v)) return false;
  if (v.isObject() && JS::IsCallable(&v.toObject())) {
    if (!JS_CallFunctionValue(cx, obj, v, JS::HandleValueArray::empty(),
                              args.rval()))
      return false;
    if (args.rval().isPrimitive()) return true;
  }

  JS_ReportErrorNumberASCII(cx, js::GetErrorMessage, nullptr,
                            JSMSG_CANT_CONVERT_TO, JS_GetClass(obj)->name,
                            "primitive type");
  return false;
}

bool nsNPObjWrapper::IsWrapper(JSObject* obj) {
  return js::GetObjectClass(obj) == &sNPObjWrapperProxyClass;
}

// An NPObject is going away, make sure we null out the JS object's
// private data in case this is an NPObject that came from a plugin
// and it's destroyed prematurely.

// static
void nsNPObjWrapper::OnDestroy(NPObject* npobj) {
  if (!npobj) {
    return;
  }

  if (npobj->_class == &nsJSObjWrapper::sJSObjWrapperNPClass) {
    // npobj is one of our own, no private data to clean up here.

    return;
  }

  if (!sNPObjWrappers) {
    // No hash yet (or any more), no used wrappers available.

    return;
  }

  auto entry =
      static_cast<NPObjWrapperHashEntry*>(sNPObjWrappers->Search(npobj));

  if (entry && entry->mJSObj) {
    // Found an NPObject wrapper, null out its JSObjects' private data.
    js::SetProxyPrivate(entry->mJSObj.unbarrieredGetPtr(),
                        JS::PrivateValue(nullptr));

    // Remove the npobj from the hash now that it went away.
    sNPObjWrappers->RawRemove(entry);

    // The finalize hook will call OnWrapperDestroyed().
  }
}

// Look up or create a JSObject that wraps the NPObject npobj. The return value
// is always in the compartment of the passed-in JSContext (it might be a CCW).

// static
JSObject* nsNPObjWrapper::GetNewOrUsed(NPP npp, JSContext* cx,
                                       NPObject* npobj) {
  if (!npobj) {
    NS_ERROR("Null NPObject passed to nsNPObjWrapper::GetNewOrUsed()!");

    return nullptr;
  }

  if (npobj->_class == &nsJSObjWrapper::sJSObjWrapperNPClass) {
    // npobj is one of our own, return its existing JSObject.

    JS::Rooted<JSObject*> obj(cx, ((nsJSObjWrapper*)npobj)->mJSObj);
    if (!JS_WrapObject(cx, &obj)) {
      return nullptr;
    }
    return obj;
  }

  if (!npp) {
    NS_ERROR("No npp passed to nsNPObjWrapper::GetNewOrUsed()!");

    return nullptr;
  }

  if (!sNPObjWrappers) {
    // No hash yet (or any more), initialize it.
    if (!CreateNPObjWrapperTable()) {
      return nullptr;
    }
  }

  auto entry =
      static_cast<NPObjWrapperHashEntry*>(sNPObjWrappers->Add(npobj, fallible));

  if (!entry) {
    // Out of memory
    JS_ReportOutOfMemory(cx);

    return nullptr;
  }

  if (entry->mJSObj) {
    // Found a NPObject wrapper. First check it is still alive.
    JSObject* obj = entry->mJSObj.unbarrieredGetPtr();
    if (js::gc::EdgeNeedsSweepUnbarriered(&obj)) {
      // The object is dead (finalization will happen at a later time). By the
      // time we leave this function, this entry will either be updated with a
      // new wrapper or removed if that fails. Clear it anyway to make sure
      // nothing touches the dead object.
      entry->mJSObj = nullptr;
    } else {
      // It may not be in the same compartment as cx, so we need to wrap it
      // before returning it.
      JS::Rooted<JSObject*> obj(cx, entry->mJSObj);
      if (!JS_WrapObject(cx, &obj)) {
        return nullptr;
      }
      return obj;
    }
  }

  entry->mNPObj = npobj;
  entry->mNpp = npp;

  uint32_t generation = sNPObjWrappers->Generation();

  // No existing JSObject, create one.

  JS::RootedValue priv(cx, JS::PrivateValue(nullptr));
  js::ProxyOptions options;
  options.setClass(&sNPObjWrapperProxyClass);
  JS::Rooted<JSObject*> obj(
      cx, js::NewProxyObject(cx, &NPObjWrapperProxyHandler::singleton, priv,
                             nullptr, options));

  if (generation != sNPObjWrappers->Generation()) {
    // Reload entry if the JS_NewObject call caused a GC and reallocated
    // the table (see bug 445229). This is guaranteed to succeed.

    entry = static_cast<NPObjWrapperHashEntry*>(sNPObjWrappers->Search(npobj));
    NS_ASSERTION(entry, "Hashtable didn't find what we just added?");
  }

  if (!obj) {
    // OOM? Remove the stale entry from the hash.

    sNPObjWrappers->RawRemove(entry);

    return nullptr;
  }

  OnWrapperCreated();

  entry->mJSObj = obj;

  js::SetProxyPrivate(obj, JS::PrivateValue(npobj));

  // The new JSObject now holds on to npobj
  _retainobject(npobj);

  return obj;
}

// static
void nsJSNPRuntime::OnPluginDestroy(NPP npp) {
  if (sJSObjWrappersAccessible) {
    // Prevent modification of sJSObjWrappers table if we go reentrant.
    sJSObjWrappersAccessible = false;

    for (auto iter = sJSObjWrappers->modIter(); !iter.done(); iter.next()) {
      nsJSObjWrapper* npobj = iter.get().value();
      MOZ_ASSERT(npobj->_class == &nsJSObjWrapper::sJSObjWrapperNPClass);
      if (npobj->mNpp == npp) {
        if (npobj->_class && npobj->_class->invalidate) {
          npobj->_class->invalidate(npobj);
        }

        _releaseobject(npobj);

        iter.remove();
      }
    }

    sJSObjWrappersAccessible = true;
  }

  if (sNPObjWrappers) {
    for (auto i = sNPObjWrappers->Iter(); !i.Done(); i.Next()) {
      auto entry = static_cast<NPObjWrapperHashEntry*>(i.Get());

      if (entry->mNpp == npp) {
        // HACK: temporarily hide the table we're enumerating so that
        // invalidate() and deallocate() don't touch it.
        PLDHashTable* tmp = sNPObjWrappers;
        sNPObjWrappers = nullptr;

        NPObject* npobj = entry->mNPObj;

        if (npobj->_class && npobj->_class->invalidate) {
          npobj->_class->invalidate(npobj);
        }

#ifdef NS_BUILD_REFCNT_LOGGING
        {
          int32_t refCnt = npobj->referenceCount;
          while (refCnt) {
            --refCnt;
            NS_LOG_RELEASE(npobj, refCnt, "BrowserNPObject");
          }
        }
#endif

        // Force deallocation of plugin objects since the plugin they came
        // from is being torn down.
        if (npobj->_class && npobj->_class->deallocate) {
          npobj->_class->deallocate(npobj);
        } else {
          free(npobj);
        }

        js::SetProxyPrivate(entry->mJSObj.unbarrieredGetPtr(),
                            JS::PrivateValue(nullptr));

        sNPObjWrappers = tmp;

        if (sDelayedReleases && sDelayedReleases->RemoveElement(npobj)) {
          OnWrapperDestroyed();
        }

        i.Remove();
      }
    }
  }
}

// static
void nsJSNPRuntime::OnPluginDestroyPending(NPP npp) {
  if (sJSObjWrappersAccessible) {
    // Prevent modification of sJSObjWrappers table if we go reentrant.
    sJSObjWrappersAccessible = false;
    for (auto iter = sJSObjWrappers->iter(); !iter.done(); iter.next()) {
      nsJSObjWrapper* npobj = iter.get().value();
      MOZ_ASSERT(npobj->_class == &nsJSObjWrapper::sJSObjWrapperNPClass);
      if (npobj->mNpp == npp) {
        npobj->mDestroyPending = true;
      }
    }
    sJSObjWrappersAccessible = true;
  }
}

// Find the NPP for a NPObject.
static NPP LookupNPP(NPObject* npobj) {
  if (npobj->_class == &nsJSObjWrapper::sJSObjWrapperNPClass) {
    nsJSObjWrapper* o = static_cast<nsJSObjWrapper*>(npobj);
    return o->mNpp;
  }

  auto entry =
      static_cast<NPObjWrapperHashEntry*>(sNPObjWrappers->Add(npobj, fallible));

  if (!entry) {
    return nullptr;
  }

  NS_ASSERTION(entry->mNpp, "Live NPObject entry w/o an NPP!");

  return entry->mNpp;
}

static bool CreateNPObjectMember(NPP npp, JSContext* cx,
                                 JS::Handle<JSObject*> aObj, NPObject* npobj,
                                 JS::Handle<jsid> id,
                                 NPVariant* getPropertyResult,
                                 JS::MutableHandle<JS::Value> vp) {
  if (!npobj || !npobj->_class || !npobj->_class->getProperty ||
      !npobj->_class->invoke) {
    ThrowJSExceptionASCII(cx, "Bad NPObject");

    return false;
  }

  NPObjectMemberPrivate* memberPrivate = new NPObjectMemberPrivate;

  JS::Rooted<JSObject*> obj(cx, aObj);

  JS::Rooted<JSObject*> memobj(cx, ::JS_NewObject(cx, &sNPObjectMemberClass));
  if (!memobj) {
    delete memberPrivate;
    return false;
  }

  vp.setObject(*memobj);

  ::JS_SetPrivate(memobj, (void*)memberPrivate);

  NPIdentifier identifier = JSIdToNPIdentifier(id);

  JS::Rooted<JS::Value> fieldValue(cx);
  NPVariant npv;

  if (getPropertyResult) {
    // Plugin has already handed us the value we want here.
    npv = *getPropertyResult;
  } else {
    VOID_TO_NPVARIANT(npv);

    NPBool hasProperty = npobj->_class->getProperty(npobj, identifier, &npv);
    if (!ReportExceptionIfPending(cx) || !hasProperty) {
      return false;
    }
  }

  fieldValue = NPVariantToJSVal(npp, cx, &npv);

  // npobjWrapper is the JSObject through which we make sure we don't
  // outlive the underlying NPObject, so make sure it points to the
  // real JSObject wrapper for the NPObject.
  obj = GetNPObjectWrapper(cx, obj);

  memberPrivate->npobjWrapper = obj;

  memberPrivate->fieldValue = fieldValue;
  memberPrivate->methodName = id;
  memberPrivate->npp = npp;

  // Finally, define the Symbol.toPrimitive property on |memobj|.

  JS::Rooted<jsid> toPrimitiveId(cx);
  toPrimitiveId =
      SYMBOL_TO_JSID(JS::GetWellKnownSymbol(cx, JS::SymbolCode::toPrimitive));

  JSFunction* fun = JS_NewFunction(cx, NPObjectMember_toPrimitive, 1, 0,
                                   "Symbol.toPrimitive");
  if (!fun) return false;

  JS::Rooted<JSObject*> funObj(cx, JS_GetFunctionObject(fun));
  if (!JS_DefinePropertyById(cx, memobj, toPrimitiveId, funObj, 0))
    return false;

  return true;
}

static void NPObjectMember_Finalize(JSFreeOp* fop, JSObject* obj) {
  NPObjectMemberPrivate* memberPrivate;

  memberPrivate = (NPObjectMemberPrivate*)::JS_GetPrivate(obj);
  if (!memberPrivate) return;

  delete memberPrivate;
}

static bool NPObjectMember_Call(JSContext* cx, unsigned argc, JS::Value* vp) {
  JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
  JS::Rooted<JSObject*> memobj(cx, &args.callee());
  NS_ENSURE_TRUE(memobj, false);

  NPObjectMemberPrivate* memberPrivate =
      (NPObjectMemberPrivate*)::JS_GetInstancePrivate(
          cx, memobj, &sNPObjectMemberClass, &args);
  if (!memberPrivate || !memberPrivate->npobjWrapper) return false;

  JS::Rooted<JSObject*> objWrapper(cx, memberPrivate->npobjWrapper);
  NPObject* npobj = GetNPObject(cx, objWrapper);
  if (!npobj) {
    ThrowJSExceptionASCII(cx, "Call on invalid member object");

    return false;
  }

  NPVariant npargs_buf[8];
  NPVariant* npargs = npargs_buf;

  if (args.length() > (sizeof(npargs_buf) / sizeof(NPVariant))) {
    // Our stack buffer isn't large enough to hold all arguments,
    // malloc a buffer.
    npargs = (NPVariant*)malloc(args.length() * sizeof(NPVariant));

    if (!npargs) {
      ThrowJSExceptionASCII(cx, "Out of memory!");

      return false;
    }
  }

  // Convert arguments
  for (uint32_t i = 0; i < args.length(); ++i) {
    if (!JSValToNPVariant(memberPrivate->npp, cx, args[i], npargs + i)) {
      ThrowJSExceptionASCII(cx, "Error converting jsvals to NPVariants!");

      if (npargs != npargs_buf) {
        free(npargs);
      }

      return false;
    }
  }

  NPVariant npv;
  bool ok = npobj->_class->invoke(npobj,
                                  JSIdToNPIdentifier(memberPrivate->methodName),
                                  npargs, args.length(), &npv);

  // Release arguments.
  for (uint32_t i = 0; i < args.length(); ++i) {
    _releasevariantvalue(npargs + i);
  }

  if (npargs != npargs_buf) {
    free(npargs);
  }

  if (!ok) {
    // ReportExceptionIfPending returns a return value, which is true
    // if no exception was thrown. In that case, throw our own.
    if (ReportExceptionIfPending(cx))
      ThrowJSExceptionASCII(cx, "Error calling method on NPObject!");

    return false;
  }

  args.rval().set(NPVariantToJSVal(memberPrivate->npp, cx, &npv));

  // *vp now owns the value, release our reference.
  _releasevariantvalue(&npv);

  return ReportExceptionIfPending(cx);
}

static void NPObjectMember_Trace(JSTracer* trc, JSObject* obj) {
  NPObjectMemberPrivate* memberPrivate =
      (NPObjectMemberPrivate*)::JS_GetPrivate(obj);
  if (!memberPrivate) return;

  // Our NPIdentifier is not always interned, so we must trace it.
  JS::TraceEdge(trc, &memberPrivate->methodName,
                "NPObjectMemberPrivate.methodName");

  JS::TraceEdge(trc, &memberPrivate->fieldValue,
                "NPObject Member => fieldValue");

  // There's no strong reference from our private data to the
  // NPObject, so make sure to mark the NPObject wrapper to keep the
  // NPObject alive as long as this NPObjectMember is alive.
  JS::TraceEdge(trc, &memberPrivate->npobjWrapper,
                "NPObject Member => npobjWrapper");
}

static bool NPObjectMember_toPrimitive(JSContext* cx, unsigned argc,
                                       JS::Value* vp) {
  JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
  JS::RootedValue thisv(cx, args.thisv());
  if (thisv.isPrimitive()) {
    args.rval().set(thisv);
    return true;
  }

  JS::RootedObject obj(cx, &thisv.toObject());
  NPObjectMemberPrivate* memberPrivate =
      (NPObjectMemberPrivate*)::JS_GetInstancePrivate(
          cx, obj, &sNPObjectMemberClass, &args);
  if (!memberPrivate) return false;

  JSType hint;
  if (!JS::GetFirstArgumentAsTypeHint(cx, args, &hint)) return false;

  args.rval().set(memberPrivate->fieldValue);
  if (args.rval().isObject()) {
    JS::Rooted<JSObject*> objVal(cx, &args.rval().toObject());
    return JS::ToPrimitive(cx, objVal, hint, args.rval());
  }
  return true;
}