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.

Mercurial (c68fe15a81fc)

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
/* -*- 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/. */

/* Data conversion between native and JavaScript types. */

#include "mozilla/ArrayUtils.h"
#include "mozilla/Range.h"

#include "xpcprivate.h"
#include "nsIScriptError.h"
#include "nsISimpleEnumerator.h"
#include "nsWrapperCache.h"
#include "nsJSUtils.h"
#include "nsQueryObject.h"
#include "nsScriptError.h"
#include "WrapperFactory.h"

#include "nsWrapperCacheInlines.h"

#include "jsapi.h"
#include "jsfriendapi.h"
#include "js/Array.h"  // JS::GetArrayLength, JS::IsArrayObject, JS::NewArrayObject
#include "js/CharacterEncoding.h"
#include "js/MemoryFunctions.h"

#include "mozilla/dom/BindingUtils.h"
#include "mozilla/dom/DOMException.h"
#include "mozilla/dom/PrimitiveConversions.h"
#include "mozilla/dom/Promise.h"

using namespace xpc;
using namespace mozilla;
using namespace mozilla::dom;
using namespace JS;

//#define STRICT_CHECK_OF_UNICODE
#ifdef STRICT_CHECK_OF_UNICODE
#  define ILLEGAL_RANGE(c) (0 != ((c)&0xFF80))
#else  // STRICT_CHECK_OF_UNICODE
#  define ILLEGAL_RANGE(c) (0 != ((c)&0xFF00))
#endif  // STRICT_CHECK_OF_UNICODE

#define ILLEGAL_CHAR_RANGE(c) (0 != ((c)&0x80))

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

// static
bool XPCConvert::GetISupportsFromJSObject(JSObject* obj, nsISupports** iface) {
  const JSClass* jsclass = js::GetObjectClass(obj);
  MOZ_ASSERT(jsclass, "obj has no class");
  if (jsclass && (jsclass->flags & JSCLASS_HAS_PRIVATE) &&
      (jsclass->flags & JSCLASS_PRIVATE_IS_NSISUPPORTS)) {
    *iface = (nsISupports*)xpc_GetJSPrivate(obj);
    return true;
  }
  *iface = UnwrapDOMObjectToISupports(obj);
  return !!*iface;
}

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

// static
bool XPCConvert::NativeData2JS(JSContext* cx, MutableHandleValue d,
                               const void* s, const nsXPTType& type,
                               const nsID* iid, uint32_t arrlen,
                               nsresult* pErr) {
  MOZ_ASSERT(s, "bad param");

  if (pErr) {
    *pErr = NS_ERROR_XPC_BAD_CONVERT_NATIVE;
  }

  switch (type.Tag()) {
    case nsXPTType::T_I8:
      d.setInt32(*static_cast<const int8_t*>(s));
      return true;
    case nsXPTType::T_I16:
      d.setInt32(*static_cast<const int16_t*>(s));
      return true;
    case nsXPTType::T_I32:
      d.setInt32(*static_cast<const int32_t*>(s));
      return true;
    case nsXPTType::T_I64:
      d.setNumber(static_cast<double>(*static_cast<const int64_t*>(s)));
      return true;
    case nsXPTType::T_U8:
      d.setInt32(*static_cast<const uint8_t*>(s));
      return true;
    case nsXPTType::T_U16:
      d.setInt32(*static_cast<const uint16_t*>(s));
      return true;
    case nsXPTType::T_U32:
      d.setNumber(*static_cast<const uint32_t*>(s));
      return true;
    case nsXPTType::T_U64:
      d.setNumber(static_cast<double>(*static_cast<const uint64_t*>(s)));
      return true;
    case nsXPTType::T_FLOAT:
      d.setNumber(*static_cast<const float*>(s));
      return true;
    case nsXPTType::T_DOUBLE:
      d.setNumber(*static_cast<const double*>(s));
      return true;
    case nsXPTType::T_BOOL:
      d.setBoolean(*static_cast<const bool*>(s));
      return true;
    case nsXPTType::T_CHAR: {
      char p = *static_cast<const char*>(s);

#ifdef STRICT_CHECK_OF_UNICODE
      MOZ_ASSERT(!ILLEGAL_CHAR_RANGE(p), "passing non ASCII data");
#endif  // STRICT_CHECK_OF_UNICODE

      JSString* str = JS_NewStringCopyN(cx, &p, 1);
      if (!str) {
        return false;
      }

      d.setString(str);
      return true;
    }
    case nsXPTType::T_WCHAR: {
      char16_t p = *static_cast<const char16_t*>(s);

      JSString* str = JS_NewUCStringCopyN(cx, &p, 1);
      if (!str) {
        return false;
      }

      d.setString(str);
      return true;
    }

    case nsXPTType::T_JSVAL: {
      d.set(*static_cast<const Value*>(s));
      return JS_WrapValue(cx, d);
    }

    case nsXPTType::T_VOID:
      XPC_LOG_ERROR(("XPCConvert::NativeData2JS : void* params not supported"));
      return false;

    case nsXPTType::T_NSIDPTR: {
      nsID* iid2 = *static_cast<nsID* const*>(s);
      if (!iid2) {
        d.setNull();
        return true;
      }

      return xpc::ID2JSValue(cx, *iid2, d);
    }

    case nsXPTType::T_NSID:
      return xpc::ID2JSValue(cx, *static_cast<const nsID*>(s), d);

    case nsXPTType::T_ASTRING: {
      const nsAString* p = static_cast<const nsAString*>(s);
      if (!p || p->IsVoid()) {
        d.setNull();
        return true;
      }

      nsStringBuffer* buf;
      if (!XPCStringConvert::ReadableToJSVal(cx, *p, &buf, d)) {
        return false;
      }
      if (buf) {
        buf->AddRef();
      }
      return true;
    }

    case nsXPTType::T_CHAR_STR: {
      const char* p = *static_cast<const char* const*>(s);
      arrlen = p ? strlen(p) : 0;
      [[fallthrough]];
    }
    case nsXPTType::T_PSTRING_SIZE_IS: {
      const char* p = *static_cast<const char* const*>(s);
      if (!p) {
        d.setNull();
        return true;
      }

#ifdef STRICT_CHECK_OF_UNICODE
      bool isAscii = true;
      for (uint32_t i = 0; i < arrlen; i++) {
        if (ILLEGAL_CHAR_RANGE(p[i])) {
          isAscii = false;
        }
      }
      MOZ_ASSERT(isAscii, "passing non ASCII data");
#endif  // STRICT_CHECK_OF_UNICODE

      JSString* str = JS_NewStringCopyN(cx, p, arrlen);
      if (!str) {
        return false;
      }

      d.setString(str);
      return true;
    }

    case nsXPTType::T_WCHAR_STR: {
      const char16_t* p = *static_cast<const char16_t* const*>(s);
      arrlen = p ? nsCharTraits<char16_t>::length(p) : 0;
      [[fallthrough]];
    }
    case nsXPTType::T_PWSTRING_SIZE_IS: {
      const char16_t* p = *static_cast<const char16_t* const*>(s);
      if (!p) {
        d.setNull();
        return true;
      }

      JSString* str = JS_NewUCStringCopyN(cx, p, arrlen);
      if (!str) {
        return false;
      }

      d.setString(str);
      return true;
    }

    case nsXPTType::T_UTF8STRING: {
      const nsACString* utf8String = static_cast<const nsACString*>(s);

      if (!utf8String || utf8String->IsVoid()) {
        d.setNull();
        return true;
      }

      if (utf8String->IsEmpty()) {
        d.set(JS_GetEmptyStringValue(cx));
        return true;
      }

      uint32_t len = utf8String->Length();
      auto allocLen = CheckedUint32(len) + 1;
      if (!allocLen.isValid()) {
        return false;
      }

      // Usage of UTF-8 in XPConnect is mostly for things that are
      // almost always ASCII, so the inexact allocations below
      // should be fine.

      if (IsUtf8Latin1(*utf8String)) {
        using UniqueLatin1Chars =
            js::UniquePtr<JS::Latin1Char[], JS::FreePolicy>;

        UniqueLatin1Chars buffer(static_cast<JS::Latin1Char*>(
            JS_string_malloc(cx, allocLen.value())));
        if (!buffer) {
          return false;
        }

        size_t written = LossyConvertUtf8toLatin1(
            *utf8String, MakeSpan(reinterpret_cast<char*>(buffer.get()), len));
        buffer[written] = 0;

        // written can never exceed len, so the truncation is OK.
        JSString* str = JS_NewLatin1String(cx, std::move(buffer), written);
        if (!str) {
          return false;
        }

        d.setString(str);
        return true;
      }

      // 1-byte sequences decode to 1 UTF-16 code unit
      // 2-byte sequences decode to 1 UTF-16 code unit
      // 3-byte sequences decode to 1 UTF-16 code unit
      // 4-byte sequences decode to 2 UTF-16 code units
      // So the number of output code units never exceeds
      // the number of input code units (but see the comment
      // below). allocLen already takes the zero terminator
      // into account.
      allocLen *= sizeof(char16_t);
      if (!allocLen.isValid()) {
        return false;
      }

      JS::UniqueTwoByteChars buffer(
          static_cast<char16_t*>(JS_string_malloc(cx, allocLen.value())));
      if (!buffer) {
        return false;
      }

      // For its internal simplicity, ConvertUTF8toUTF16 requires the
      // destination to be one code unit longer than the source, but
      // it never actually writes more code units than the number of
      // code units in the source. That's why it's OK to claim the
      // output buffer has len + 1 space but then still expect to
      // have space for the zero terminator.
      size_t written = ConvertUtf8toUtf16(
          *utf8String, MakeSpan(buffer.get(), allocLen.value()));
      MOZ_RELEASE_ASSERT(written <= len);
      buffer[written] = 0;

      JSString* str = JS_NewUCStringDontDeflate(cx, std::move(buffer), written);
      if (!str) {
        return false;
      }

      d.setString(str);
      return true;
    }
    case nsXPTType::T_CSTRING: {
      const nsACString* cString = static_cast<const nsACString*>(s);

      if (!cString || cString->IsVoid()) {
        d.setNull();
        return true;
      }

      // c-strings (binary blobs) are deliberately not converted from
      // UTF-8 to UTF-16. T_UTF8Sting is for UTF-8 encoded strings
      // with automatic conversion.
      JSString* str = JS_NewStringCopyN(cx, cString->Data(), cString->Length());
      if (!str) {
        return false;
      }

      d.setString(str);
      return true;
    }

    case nsXPTType::T_INTERFACE:
    case nsXPTType::T_INTERFACE_IS: {
      nsISupports* iface = *static_cast<nsISupports* const*>(s);
      if (!iface) {
        d.setNull();
        return true;
      }

      if (iid->Equals(NS_GET_IID(nsIVariant))) {
        nsCOMPtr<nsIVariant> variant = do_QueryInterface(iface);
        if (!variant) {
          return false;
        }

        return XPCVariant::VariantDataToJS(cx, variant, pErr, d);
      }

      xpcObjectHelper helper(iface);
      return NativeInterface2JSObject(cx, d, helper, iid, true, pErr);
    }

    case nsXPTType::T_DOMOBJECT: {
      void* ptr = *static_cast<void* const*>(s);
      if (!ptr) {
        d.setNull();
        return true;
      }

      return type.GetDOMObjectInfo().Wrap(cx, ptr, d);
    }

    case nsXPTType::T_PROMISE: {
      Promise* promise = *static_cast<Promise* const*>(s);
      if (!promise) {
        d.setNull();
        return true;
      }

      RootedObject jsobj(cx, promise->PromiseObj());
      if (!JS_WrapObject(cx, &jsobj)) {
        return false;
      }
      d.setObject(*jsobj);
      return true;
    }

    case nsXPTType::T_LEGACY_ARRAY:
      return NativeArray2JS(cx, d, *static_cast<const void* const*>(s),
                            type.ArrayElementType(), iid, arrlen, pErr);

    case nsXPTType::T_ARRAY: {
      auto* array = static_cast<const xpt::detail::UntypedTArray*>(s);
      return NativeArray2JS(cx, d, array->Elements(), type.ArrayElementType(),
                            iid, array->Length(), pErr);
    }

    default:
      NS_ERROR("bad type");
      return false;
  }
  return true;
}

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

#ifdef DEBUG
static bool CheckChar16InCharRange(char16_t c) {
  if (ILLEGAL_RANGE(c)) {
    /* U+0080/U+0100 - U+FFFF data lost. */
    static const size_t MSG_BUF_SIZE = 64;
    char msg[MSG_BUF_SIZE];
    snprintf(msg, MSG_BUF_SIZE,
             "char16_t out of char range; high bits of data lost: 0x%x",
             int(c));
    NS_WARNING(msg);
    return false;
  }

  return true;
}

template <typename CharT>
static void CheckCharsInCharRange(const CharT* chars, size_t len) {
  for (size_t i = 0; i < len; i++) {
    if (!CheckChar16InCharRange(chars[i])) {
      break;
    }
  }
}
#endif

template <typename T>
bool ConvertToPrimitive(JSContext* cx, HandleValue v, T* retval) {
  return ValueToPrimitive<T, eDefault>(cx, v, "Value", retval);
}

// static
bool XPCConvert::JSData2Native(JSContext* cx, void* d, HandleValue s,
                               const nsXPTType& type, const nsID* iid,
                               uint32_t arrlen, nsresult* pErr) {
  MOZ_ASSERT(d, "bad param");

  js::AssertSameCompartment(cx, s);

  if (pErr) {
    *pErr = NS_ERROR_XPC_BAD_CONVERT_JS;
  }

  bool sizeis =
      type.Tag() == TD_PSTRING_SIZE_IS || type.Tag() == TD_PWSTRING_SIZE_IS;

  switch (type.Tag()) {
    case nsXPTType::T_I8:
      return ConvertToPrimitive(cx, s, static_cast<int8_t*>(d));
    case nsXPTType::T_I16:
      return ConvertToPrimitive(cx, s, static_cast<int16_t*>(d));
    case nsXPTType::T_I32:
      return ConvertToPrimitive(cx, s, static_cast<int32_t*>(d));
    case nsXPTType::T_I64:
      return ConvertToPrimitive(cx, s, static_cast<int64_t*>(d));
    case nsXPTType::T_U8:
      return ConvertToPrimitive(cx, s, static_cast<uint8_t*>(d));
    case nsXPTType::T_U16:
      return ConvertToPrimitive(cx, s, static_cast<uint16_t*>(d));
    case nsXPTType::T_U32:
      return ConvertToPrimitive(cx, s, static_cast<uint32_t*>(d));
    case nsXPTType::T_U64:
      return ConvertToPrimitive(cx, s, static_cast<uint64_t*>(d));
    case nsXPTType::T_FLOAT:
      return ConvertToPrimitive(cx, s, static_cast<float*>(d));
    case nsXPTType::T_DOUBLE:
      return ConvertToPrimitive(cx, s, static_cast<double*>(d));
    case nsXPTType::T_BOOL:
      return ConvertToPrimitive(cx, s, static_cast<bool*>(d));
    case nsXPTType::T_CHAR: {
      JSString* str = ToString(cx, s);
      if (!str) {
        return false;
      }

      char16_t ch;
      if (JS_GetStringLength(str) == 0) {
        ch = 0;
      } else {
        if (!JS_GetStringCharAt(cx, str, 0, &ch)) {
          return false;
        }
      }
#ifdef DEBUG
      CheckChar16InCharRange(ch);
#endif
      *((char*)d) = char(ch);
      break;
    }
    case nsXPTType::T_WCHAR: {
      JSString* str;
      if (!(str = ToString(cx, s))) {
        return false;
      }
      size_t length = JS_GetStringLength(str);
      if (length == 0) {
        *((uint16_t*)d) = 0;
        break;
      }

      char16_t ch;
      if (!JS_GetStringCharAt(cx, str, 0, &ch)) {
        return false;
      }

      *((uint16_t*)d) = uint16_t(ch);
      break;
    }
    case nsXPTType::T_JSVAL:
      *((Value*)d) = s;
      break;
    case nsXPTType::T_VOID:
      XPC_LOG_ERROR(("XPCConvert::JSData2Native : void* params not supported"));
      NS_ERROR("void* params not supported");
      return false;

    case nsXPTType::T_NSIDPTR:
      if (Maybe<nsID> id = xpc::JSValue2ID(cx, s)) {
        *((const nsID**)d) = id.ref().Clone();
        return true;
      }
      return false;

    case nsXPTType::T_NSID:
      if (Maybe<nsID> id = xpc::JSValue2ID(cx, s)) {
        *((nsID*)d) = id.ref();
        return true;
      }
      return false;

    case nsXPTType::T_ASTRING: {
      nsAString* ws = (nsAString*)d;
      if (s.isUndefined() || s.isNull()) {
        ws->SetIsVoid(true);
        return true;
      }
      size_t length = 0;
      JSString* str = ToString(cx, s);
      if (!str) {
        return false;
      }

      length = JS_GetStringLength(str);
      if (!length) {
        ws->Truncate();
        return true;
      }

      return AssignJSString(cx, *ws, str);
    }

    case nsXPTType::T_CHAR_STR:
    case nsXPTType::T_PSTRING_SIZE_IS: {
      if (s.isUndefined() || s.isNull()) {
        if (sizeis && 0 != arrlen) {
          if (pErr) {
            *pErr = NS_ERROR_XPC_NOT_ENOUGH_CHARS_IN_STRING;
          }
          return false;
        }
        *((char**)d) = nullptr;
        return true;
      }

      JSString* str = ToString(cx, s);
      if (!str) {
        return false;
      }

#ifdef DEBUG
      if (JS_StringHasLatin1Chars(str)) {
        size_t len;
        AutoCheckCannotGC nogc;
        const Latin1Char* chars =
            JS_GetLatin1StringCharsAndLength(cx, nogc, str, &len);
        if (chars) {
          CheckCharsInCharRange(chars, len);
        }
      } else {
        size_t len;
        AutoCheckCannotGC nogc;
        const char16_t* chars =
            JS_GetTwoByteStringCharsAndLength(cx, nogc, str, &len);
        if (chars) {
          CheckCharsInCharRange(chars, len);
        }
      }
#endif  // DEBUG

      size_t length = JS_GetStringEncodingLength(cx, str);
      if (length == size_t(-1)) {
        return false;
      }
      if (sizeis) {
        if (length > arrlen) {
          if (pErr) {
            *pErr = NS_ERROR_XPC_NOT_ENOUGH_CHARS_IN_STRING;
          }
          return false;
        }
        if (length < arrlen) {
          length = arrlen;
        }
      }
      char* buffer = static_cast<char*>(moz_xmalloc(length + 1));
      if (!JS_EncodeStringToBuffer(cx, str, buffer, length)) {
        free(buffer);
        return false;
      }
      buffer[length] = '\0';
      *((void**)d) = buffer;
      return true;
    }

    case nsXPTType::T_WCHAR_STR:
    case nsXPTType::T_PWSTRING_SIZE_IS: {
      JSString* str;

      if (s.isUndefined() || s.isNull()) {
        if (sizeis && 0 != arrlen) {
          if (pErr) {
            *pErr = NS_ERROR_XPC_NOT_ENOUGH_CHARS_IN_STRING;
          }
          return false;
        }
        *((char16_t**)d) = nullptr;
        return true;
      }

      if (!(str = ToString(cx, s))) {
        return false;
      }
      size_t len = JS_GetStringLength(str);
      if (sizeis) {
        if (len > arrlen) {
          if (pErr) {
            *pErr = NS_ERROR_XPC_NOT_ENOUGH_CHARS_IN_STRING;
          }
          return false;
        }
        if (len < arrlen) {
          len = arrlen;
        }
      }

      size_t byte_len = (len + 1) * sizeof(char16_t);
      *((void**)d) = moz_xmalloc(byte_len);
      mozilla::Range<char16_t> destChars(*((char16_t**)d), len + 1);
      if (!JS_CopyStringChars(cx, destChars, str)) {
        return false;
      }
      destChars[len] = 0;

      return true;
    }

    case nsXPTType::T_UTF8STRING: {
      nsACString* rs = (nsACString*)d;
      if (s.isNull() || s.isUndefined()) {
        rs->SetIsVoid(true);
        return true;
      }

      // The JS val is neither null nor void...
      JSString* str = ToString(cx, s);
      if (!str) {
        return false;
      }

      size_t length = JS_GetStringLength(str);
      if (!length) {
        rs->Truncate();
        return true;
      }

      JSLinearString* linear = JS_EnsureLinearString(cx, str);
      if (!linear) {
        return false;
      }

      size_t utf8Length = JS::GetDeflatedUTF8StringLength(linear);
      if (!rs->SetLength(utf8Length, fallible)) {
        if (pErr) {
          *pErr = NS_ERROR_OUT_OF_MEMORY;
        }
        return false;
      }

      mozilla::DebugOnly<size_t> written = JS::DeflateStringToUTF8Buffer(
          linear, mozilla::MakeSpan(rs->BeginWriting(), utf8Length));
      MOZ_ASSERT(written == utf8Length);

      return true;
    }

    case nsXPTType::T_CSTRING: {
      nsACString* rs = (nsACString*)d;
      if (s.isNull() || s.isUndefined()) {
        rs->SetIsVoid(true);
        return true;
      }

      // The JS val is neither null nor void...
      JSString* str = ToString(cx, s);
      if (!str) {
        return false;
      }

      size_t length = JS_GetStringEncodingLength(cx, str);
      if (length == size_t(-1)) {
        return false;
      }

      if (!length) {
        rs->Truncate();
        return true;
      }

      if (!rs->SetLength(uint32_t(length), fallible)) {
        if (pErr) {
          *pErr = NS_ERROR_OUT_OF_MEMORY;
        }
        return false;
      }
      if (rs->Length() != uint32_t(length)) {
        return false;
      }
      if (!JS_EncodeStringToBuffer(cx, str, rs->BeginWriting(), length)) {
        return false;
      }

      return true;
    }

    case nsXPTType::T_INTERFACE:
    case nsXPTType::T_INTERFACE_IS: {
      MOZ_ASSERT(iid, "can't do interface conversions without iid");

      if (iid->Equals(NS_GET_IID(nsIVariant))) {
        nsCOMPtr<nsIVariant> variant = XPCVariant::newVariant(cx, s);
        if (!variant) {
          return false;
        }

        variant.forget(static_cast<nsISupports**>(d));
        return true;
      }

      if (s.isNullOrUndefined()) {
        *((nsISupports**)d) = nullptr;
        return true;
      }

      // only wrap JSObjects
      if (!s.isObject()) {
        if (pErr && s.isInt32() && 0 == s.toInt32()) {
          *pErr = NS_ERROR_XPC_BAD_CONVERT_JS_ZERO_ISNOT_NULL;
        }
        return false;
      }

      RootedObject src(cx, &s.toObject());
      return JSObject2NativeInterface(cx, (void**)d, src, iid, nullptr, pErr);
    }

    case nsXPTType::T_DOMOBJECT: {
      if (s.isNullOrUndefined()) {
        *((void**)d) = nullptr;
        return true;
      }

      // Can't handle non-JSObjects
      if (!s.isObject()) {
        return false;
      }

      nsresult err = type.GetDOMObjectInfo().Unwrap(s, (void**)d, cx);
      if (pErr) {
        *pErr = err;
      }
      return NS_SUCCEEDED(err);
    }

    case nsXPTType::T_PROMISE: {
      nsIGlobalObject* glob = CurrentNativeGlobal(cx);
      if (!glob) {
        if (pErr) {
          *pErr = NS_ERROR_UNEXPECTED;
        }
        return false;
      }

      // Call Promise::Resolve to create a Promise object. This allows us to
      // support returning non-promise values from Promise-returning functions
      // in JS.
      IgnoredErrorResult err;
      *(Promise**)d = Promise::Resolve(glob, cx, s, err).take();
      bool ok = !err.Failed();
      if (pErr) {
        *pErr = err.StealNSResult();
      }

      return ok;
    }

    case nsXPTType::T_LEGACY_ARRAY: {
      void** dest = (void**)d;
      const nsXPTType& elty = type.ArrayElementType();

      *dest = nullptr;

      // FIXME: XPConnect historically has shortcut the JSArray2Native codepath
      // in its caller if arrlen is 0, allowing arbitrary values to be passed as
      // arrays and interpreted as the empty array (bug 1458987).
      //
      // NOTE: Once this is fixed, null/undefined should be allowed for arrays
      // if arrlen is 0.
      if (arrlen == 0) {
        return true;
      }

      bool ok = JSArray2Native(
          cx, s, elty, iid, pErr, [&](uint32_t* aLength) -> void* {
            // Check that we have enough elements in our array.
            if (*aLength < arrlen) {
              if (pErr) {
                *pErr = NS_ERROR_XPC_NOT_ENOUGH_ELEMENTS_IN_ARRAY;
              }
              return nullptr;
            }
            *aLength = arrlen;

            // Allocate the backing buffer & return it.
            *dest = moz_xmalloc(*aLength * elty.Stride());
            return *dest;
          });

      if (!ok && *dest) {
        // An error occurred, free any allocated backing buffer.
        free(*dest);
        *dest = nullptr;
      }
      return ok;
    }

    case nsXPTType::T_ARRAY: {
      auto* dest = (xpt::detail::UntypedTArray*)d;
      const nsXPTType& elty = type.ArrayElementType();

      bool ok = JSArray2Native(cx, s, elty, iid, pErr,
                               [&](uint32_t* aLength) -> void* {
                                 if (!dest->SetLength(elty, *aLength)) {
                                   if (pErr) {
                                     *pErr = NS_ERROR_OUT_OF_MEMORY;
                                   }
                                   return nullptr;
                                 }
                                 return dest->Elements();
                               });

      if (!ok) {
        // An error occurred, free any allocated backing buffer.
        dest->Clear();
      }
      return ok;
    }

    default:
      NS_ERROR("bad type");
      return false;
  }
  return true;
}

/***************************************************************************/
// static
bool XPCConvert::NativeInterface2JSObject(JSContext* cx, MutableHandleValue d,
                                          xpcObjectHelper& aHelper,
                                          const nsID* iid,
                                          bool allowNativeWrapper,
                                          nsresult* pErr) {
  if (!iid) {
    iid = &NS_GET_IID(nsISupports);
  }

  d.setNull();
  if (!aHelper.Object()) {
    return true;
  }
  if (pErr) {
    *pErr = NS_ERROR_XPC_BAD_CONVERT_NATIVE;
  }

  // We used to have code here that unwrapped and simply exposed the
  // underlying JSObject. That caused anomolies when JSComponents were
  // accessed from other JS code - they didn't act like other xpconnect
  // wrapped components. So, instead, we create "double wrapped" objects
  // (that means an XPCWrappedNative around an nsXPCWrappedJS). This isn't
  // optimal -- we could detect this and roll the functionality into a
  // single wrapper, but the current solution is good enough for now.
  XPCWrappedNativeScope* xpcscope = ObjectScope(JS::CurrentGlobalOrNull(cx));
  if (!xpcscope) {
    return false;
  }

  JSAutoRealm ar(cx, xpcscope->GetGlobalForWrappedNatives());

  // First, see if this object supports the wrapper cache. In that case, the
  // object to use is found as cache->GetWrapper(). If that is null, then the
  // object will create (and fill the cache) from its WrapObject call.
  nsWrapperCache* cache = aHelper.GetWrapperCache();

  RootedObject flat(cx, cache ? cache->GetWrapper() : nullptr);
  if (!flat && cache) {
    RootedObject global(cx, CurrentGlobalOrNull(cx));
    flat = cache->WrapObject(cx, nullptr);
    if (!flat) {
      return false;
    }
  }
  if (flat) {
    if (allowNativeWrapper && !JS_WrapObject(cx, &flat)) {
      return false;
    }
    d.setObjectOrNull(flat);
    return true;
  }

  // NOTE(nika): Remove if Promise becomes non-nsISupports
  if (iid->Equals(NS_GET_IID(nsISupports))) {
    // Check for a Promise being returned via nsISupports.  In that
    // situation, we want to dig out its underlying JS object and return
    // that.
    RefPtr<Promise> promise = do_QueryObject(aHelper.Object());
    if (promise) {
      flat = promise->PromiseObj();
      if (!JS_WrapObject(cx, &flat)) {
        return false;
      }
      d.setObjectOrNull(flat);
      return true;
    }
  }

  // Go ahead and create an XPCWrappedNative for this object.
  RefPtr<XPCNativeInterface> iface = XPCNativeInterface::GetNewOrUsed(cx, iid);
  if (!iface) {
    return false;
  }

  RefPtr<XPCWrappedNative> wrapper;
  nsresult rv = XPCWrappedNative::GetNewOrUsed(cx, aHelper, xpcscope, iface,
                                               getter_AddRefs(wrapper));
  if (NS_FAILED(rv) && pErr) {
    *pErr = rv;
  }

  // If creating the wrapped native failed, then return early.
  if (NS_FAILED(rv) || !wrapper) {
    return false;
  }

  // If we're not creating security wrappers, we can return the
  // XPCWrappedNative as-is here.
  flat = wrapper->GetFlatJSObject();
  if (!allowNativeWrapper) {
    d.setObjectOrNull(flat);
    if (pErr) {
      *pErr = NS_OK;
    }
    return true;
  }

  // The call to wrap here handles both cross-compartment and same-compartment
  // security wrappers.
  RootedObject original(cx, flat);
  if (!JS_WrapObject(cx, &flat)) {
    return false;
  }

  d.setObjectOrNull(flat);

  if (pErr) {
    *pErr = NS_OK;
  }

  return true;
}

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

// static
bool XPCConvert::JSObject2NativeInterface(JSContext* cx, void** dest,
                                          HandleObject src, const nsID* iid,
                                          nsISupports* aOuter, nsresult* pErr) {
  MOZ_ASSERT(dest, "bad param");
  MOZ_ASSERT(src, "bad param");
  MOZ_ASSERT(iid, "bad param");

  js::AssertSameCompartment(cx, src);

  *dest = nullptr;
  if (pErr) {
    *pErr = NS_ERROR_XPC_BAD_CONVERT_JS;
  }

  nsISupports* iface;

  if (!aOuter) {
    // Note that if we have a non-null aOuter then it means that we are
    // forcing the creation of a wrapper even if the object *is* a
    // wrappedNative or other wise has 'nsISupportness'.
    // This allows wrapJSAggregatedToNative to work.

    // If we're looking at a security wrapper, see now if we're allowed to
    // pass it to C++. If we are, then fall through to the code below. If
    // we aren't, throw an exception eagerly.
    //
    // NB: It's very important that we _don't_ unwrap in the aOuter case,
    // because the caller may explicitly want to create the XPCWrappedJS
    // around a security wrapper. XBL does this with Xrays from the XBL
    // scope - see nsBindingManager::GetBindingImplementation.
    //
    // It's also very important that "inner" be rooted here.
    RootedObject inner(
        cx, js::CheckedUnwrapDynamic(src, cx,
                                     /* stopAtWindowProxy = */ false));
    if (!inner) {
      if (pErr) {
        *pErr = NS_ERROR_XPC_SECURITY_MANAGER_VETO;
      }
      return false;
    }

    // Is this really a native xpcom object with a wrapper?
    XPCWrappedNative* wrappedNative = nullptr;
    if (IS_WN_REFLECTOR(inner)) {
      wrappedNative = XPCWrappedNative::Get(inner);
    }
    if (wrappedNative) {
      iface = wrappedNative->GetIdentityObject();
      return NS_SUCCEEDED(iface->QueryInterface(*iid, dest));
    }
    // else...

    // Deal with slim wrappers here.
    if (GetISupportsFromJSObject(inner ? inner : src, &iface)) {
      if (iface && NS_SUCCEEDED(iface->QueryInterface(*iid, dest))) {
        return true;
      }

      // If that failed, and iid is for mozIDOMWindowProxy, we actually
      // want the outer!
      if (iid->Equals(NS_GET_IID(mozIDOMWindowProxy))) {
        if (nsCOMPtr<mozIDOMWindow> inner = do_QueryInterface(iface)) {
          iface = nsPIDOMWindowInner::From(inner)->GetOuterWindow();
          return NS_SUCCEEDED(iface->QueryInterface(*iid, dest));
        }
      }

      return false;
    }

    // NOTE(nika): Remove if Promise becomes non-nsISupports
    // Deal with Promises being passed as nsISupports.  In that situation we
    // want to create a dom::Promise and use that.
    if (iid->Equals(NS_GET_IID(nsISupports))) {
      RootedObject innerObj(RootingCx(), inner);
      if (IsPromiseObject(innerObj)) {
        nsIGlobalObject* glob = NativeGlobal(innerObj);
        RefPtr<Promise> p = Promise::CreateFromExisting(glob, innerObj);
        return p && NS_SUCCEEDED(p->QueryInterface(*iid, dest));
      }
    }
  }

  RefPtr<nsXPCWrappedJS> wrapper;
  nsresult rv =
      nsXPCWrappedJS::GetNewOrUsed(cx, src, *iid, getter_AddRefs(wrapper));
  if (pErr) {
    *pErr = rv;
  }

  if (NS_FAILED(rv) || !wrapper) {
    return false;
  }

  // If the caller wanted to aggregate this JS object to a native,
  // attach it to the wrapper. Note that we allow a maximum of one
  // aggregated native for a given XPCWrappedJS.
  if (aOuter) {
    wrapper->SetAggregatedNativeObject(aOuter);
  }

  // We need to go through the QueryInterface logic to make this return
  // the right thing for the various 'special' interfaces; e.g.
  // nsISimpleEnumerator. We must use AggregatedQueryInterface in cases where
  // there is an outer to avoid nasty recursion.
  rv = aOuter ? wrapper->AggregatedQueryInterface(*iid, dest)
              : wrapper->QueryInterface(*iid, dest);
  if (pErr) {
    *pErr = rv;
  }
  return NS_SUCCEEDED(rv);
}

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

// static
nsresult XPCConvert::ConstructException(nsresult rv, const char* message,
                                        const char* ifaceName,
                                        const char* methodName,
                                        nsISupports* data, Exception** exceptn,
                                        JSContext* cx, Value* jsExceptionPtr) {
  MOZ_ASSERT(!cx == !jsExceptionPtr,
             "Expected cx and jsExceptionPtr to cooccur.");

  static const char format[] = "\'%s\' when calling method: [%s::%s]";
  const char* msg = message;
  nsAutoCString sxmsg;  // must have the same lifetime as msg

  nsCOMPtr<nsIScriptError> errorObject = do_QueryInterface(data);
  if (errorObject) {
    nsString xmsg;
    if (NS_SUCCEEDED(errorObject->GetMessageMoz(xmsg))) {
      CopyUTF16toUTF8(xmsg, sxmsg);
      msg = sxmsg.get();
    }
  }
  if (!msg) {
    if (!nsXPCException::NameAndFormatForNSResult(rv, nullptr, &msg) || !msg) {
      msg = "<error>";
    }
  }

  nsCString msgStr(msg);
  if (ifaceName && methodName) {
    msgStr.AppendPrintf(format, msg, ifaceName, methodName);
  }

  RefPtr<Exception> e =
      new Exception(msgStr, rv, EmptyCString(), nullptr, data);

  if (cx && jsExceptionPtr) {
    e->StowJSVal(*jsExceptionPtr);
  }

  e.forget(exceptn);
  return NS_OK;
}

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

class MOZ_STACK_CLASS AutoExceptionRestorer {
 public:
  AutoExceptionRestorer(JSContext* cx, const Value& v)
      : mContext(cx), tvr(cx, v) {
    JS_ClearPendingException(mContext);
  }

  ~AutoExceptionRestorer() { JS_SetPendingException(mContext, tvr); }

 private:
  JSContext* const mContext;
  RootedValue tvr;
};

static nsresult JSErrorToXPCException(JSContext* cx, const char* toStringResult,
                                      const char* ifaceName,
                                      const char* methodName,
                                      const JSErrorReport* report,
                                      Exception** exceptn) {
  nsresult rv = NS_ERROR_FAILURE;
  RefPtr<nsScriptError> data;
  if (report) {
    nsAutoString bestMessage;
    if (report->message()) {
      CopyUTF8toUTF16(mozilla::MakeStringSpan(report->message().c_str()),
                      bestMessage);
    } else if (toStringResult) {
      CopyUTF8toUTF16(mozilla::MakeStringSpan(toStringResult), bestMessage);
    } else {
      bestMessage.AssignLiteral("JavaScript Error");
    }

    const char16_t* linebuf = report->linebuf();
    uint32_t flags = report->isWarning() ? nsIScriptError::warningFlag
                                         : nsIScriptError::errorFlag;

    data = new nsScriptError();
    data->nsIScriptError::InitWithWindowID(
        bestMessage, NS_ConvertASCIItoUTF16(report->filename),
        linebuf ? nsDependentString(linebuf, report->linebufLength())
                : EmptyString(),
        report->lineno, report->tokenOffset(), flags,
        NS_LITERAL_CSTRING("XPConnect JavaScript"),
        nsJSUtils::GetCurrentlyRunningCodeInnerWindowID(cx));
  }

  if (data) {
    // Pass nullptr for the message: ConstructException will get a message
    // from the nsIScriptError.
    rv = XPCConvert::ConstructException(
        NS_ERROR_XPC_JAVASCRIPT_ERROR_WITH_DETAILS, nullptr, ifaceName,
        methodName, static_cast<nsIScriptError*>(data.get()), exceptn, nullptr,
        nullptr);
  } else {
    rv = XPCConvert::ConstructException(NS_ERROR_XPC_JAVASCRIPT_ERROR, nullptr,
                                        ifaceName, methodName, nullptr, exceptn,
                                        nullptr, nullptr);
  }
  return rv;
}

// static
nsresult XPCConvert::JSValToXPCException(JSContext* cx, MutableHandleValue s,
                                         const char* ifaceName,
                                         const char* methodName,
                                         Exception** exceptn) {
  AutoExceptionRestorer aer(cx, s);

  if (!s.isPrimitive()) {
    // we have a JSObject
    RootedObject obj(cx, s.toObjectOrNull());

    if (!obj) {
      NS_ERROR("when is an object not an object?");
      return NS_ERROR_FAILURE;
    }

    // is this really a native xpcom object with a wrapper?
    JSObject* unwrapped =
        js::CheckedUnwrapDynamic(obj, cx, /* stopAtWindowProxy = */ false);
    if (!unwrapped) {
      return NS_ERROR_XPC_SECURITY_MANAGER_VETO;
    }
    // It's OK to use ReflectorToISupportsStatic, because we have already
    // stripped off wrappers.
    if (nsCOMPtr<nsISupports> supports =
            ReflectorToISupportsStatic(unwrapped)) {
      nsCOMPtr<Exception> iface = do_QueryInterface(supports);
      if (iface) {
        // just pass through the exception (with extra ref and all)
        iface.forget(exceptn);
        return NS_OK;
      }

      // it is a wrapped native, but not an exception!
      return ConstructException(NS_ERROR_XPC_JS_THREW_NATIVE_OBJECT, nullptr,
                                ifaceName, methodName, supports, exceptn,
                                nullptr, nullptr);
    } else {
      // It is a JSObject, but not a wrapped native...

      // If it is an engine Error with an error report then let's
      // extract the report and build an xpcexception from that
      const JSErrorReport* report;
      if (nullptr != (report = JS_ErrorFromException(cx, obj))) {
        JS::UniqueChars toStringResult;
        RootedString str(cx, ToString(cx, s));
        if (str) {
          toStringResult = JS_EncodeStringToUTF8(cx, str);
        }
        return JSErrorToXPCException(cx, toStringResult.get(), ifaceName,
                                     methodName, report, exceptn);
      }

      // XXX we should do a check against 'js_ErrorClass' here and
      // do the right thing - even though it has no JSErrorReport,
      // The fact that it is a JSError exceptions means we can extract
      // particular info and our 'result' should reflect that.

      // otherwise we'll just try to convert it to a string

      JSString* str = ToString(cx, s);
      if (!str) {
        return NS_ERROR_FAILURE;
      }

      JS::UniqueChars strBytes = JS_EncodeStringToLatin1(cx, str);
      if (!strBytes) {
        return NS_ERROR_FAILURE;
      }

      return ConstructException(NS_ERROR_XPC_JS_THREW_JS_OBJECT, strBytes.get(),
                                ifaceName, methodName, nullptr, exceptn, cx,
                                s.address());
    }
  }

  if (s.isUndefined() || s.isNull()) {
    return ConstructException(NS_ERROR_XPC_JS_THREW_NULL, nullptr, ifaceName,
                              methodName, nullptr, exceptn, cx, s.address());
  }

  if (s.isNumber()) {
    // lets see if it looks like an nsresult
    nsresult rv;
    double number;
    bool isResult = false;

    if (s.isInt32()) {
      rv = (nsresult)s.toInt32();
      if (NS_FAILED(rv)) {
        isResult = true;
      } else {
        number = (double)s.toInt32();
      }
    } else {
      number = s.toDouble();
      if (number > 0.0 && number < (double)0xffffffff &&
          0.0 == fmod(number, 1)) {
        // Visual Studio 9 doesn't allow casting directly from a
        // double to an enumeration type, contrary to 5.2.9(10) of
        // C++11, so add an intermediate cast.
        rv = (nsresult)(uint32_t)number;
        if (NS_FAILED(rv)) {
          isResult = true;
        }
      }
    }

    if (isResult) {
      return ConstructException(rv, nullptr, ifaceName, methodName, nullptr,
                                exceptn, cx, s.address());
    } else {
      // XXX all this nsISupportsDouble code seems a little redundant
      // now that we're storing the Value in the exception...
      nsCOMPtr<nsISupportsDouble> data;
      nsCOMPtr<nsIComponentManager> cm;
      if (NS_FAILED(NS_GetComponentManager(getter_AddRefs(cm))) || !cm ||
          NS_FAILED(cm->CreateInstanceByContractID(
              NS_SUPPORTS_DOUBLE_CONTRACTID, nullptr,
              NS_GET_IID(nsISupportsDouble), getter_AddRefs(data))))
        return NS_ERROR_FAILURE;
      data->SetData(number);
      rv = ConstructException(NS_ERROR_XPC_JS_THREW_NUMBER, nullptr, ifaceName,
                              methodName, data, exceptn, cx, s.address());
      return rv;
    }
  }

  // otherwise we'll just try to convert it to a string
  // Note: e.g., bools get converted to JSStrings by this code.

  JSString* str = ToString(cx, s);
  if (str) {
    if (JS::UniqueChars strBytes = JS_EncodeStringToLatin1(cx, str)) {
      return ConstructException(NS_ERROR_XPC_JS_THREW_STRING, strBytes.get(),
                                ifaceName, methodName, nullptr, exceptn, cx,
                                s.address());
    }
  }
  return NS_ERROR_FAILURE;
}

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

// array fun...

// static
bool XPCConvert::NativeArray2JS(JSContext* cx, MutableHandleValue d,
                                const void* buf, const nsXPTType& type,
                                const nsID* iid, uint32_t count,
                                nsresult* pErr) {
  MOZ_ASSERT(buf || count == 0, "Must have buf or 0 elements");

  RootedObject array(cx, JS::NewArrayObject(cx, count));
  if (!array) {
    return false;
  }

  if (pErr) {
    *pErr = NS_ERROR_XPC_BAD_CONVERT_NATIVE;
  }

  RootedValue current(cx, JS::NullValue());
  for (uint32_t i = 0; i < count; ++i) {
    if (!NativeData2JS(cx, &current, type.ElementPtr(buf, i), type, iid, 0,
                       pErr) ||
        !JS_DefineElement(cx, array, i, current, JSPROP_ENUMERATE))
      return false;
  }

  if (pErr) {
    *pErr = NS_OK;
  }
  d.setObject(*array);
  return true;
}

// static
bool XPCConvert::JSArray2Native(JSContext* cx, JS::HandleValue aJSVal,
                                const nsXPTType& aEltType, const nsIID* aIID,
                                nsresult* pErr,
                                const ArrayAllocFixupLen& aAllocFixupLen) {
  // Wrap aAllocFixupLen to check length is within bounds & initialize the
  // allocated memory if needed.
  auto allocFixupLen = [&](uint32_t* aLength) -> void* {
    if (*aLength > (UINT32_MAX / aEltType.Stride())) {
      return nullptr;  // Byte length doesn't fit in uint32_t
    }

    void* buf = aAllocFixupLen(aLength);

    // Ensure the buffer has valid values for each element. We can skip this
    // for arithmetic types, as they do not require initialization.
    if (buf && !aEltType.IsArithmetic()) {
      for (uint32_t i = 0; i < *aLength; ++i) {
        InitializeValue(aEltType, aEltType.ElementPtr(buf, i));
      }
    }
    return buf;
  };

  // JSArray2Native only accepts objects (Array and TypedArray).
  if (!aJSVal.isObject()) {
    if (pErr) {
      *pErr = NS_ERROR_XPC_CANT_CONVERT_PRIMITIVE_TO_ARRAY;
    }
    return false;
  }
  RootedObject jsarray(cx, &aJSVal.toObject());

  if (pErr) {
    *pErr = NS_ERROR_XPC_BAD_CONVERT_JS;
  }

  if (JS_IsTypedArrayObject(jsarray)) {
    // Fast conversion of typed arrays to native using memcpy. No float or
    // double canonicalization is done. ArrayBuffers are not accepted;
    // create a properly typed array view on them first. The element type of
    // array must match the XPCOM type in size, type and signedness exactly.
    // As an exception, Uint8ClampedArray is allowed for arrays of uint8_t.
    // DataViews are not supported.

    nsXPTTypeTag tag;
    switch (JS_GetArrayBufferViewType(jsarray)) {
      case js::Scalar::Int8:
        tag = TD_INT8;
        break;
      case js::Scalar::Uint8:
        tag = TD_UINT8;
        break;
      case js::Scalar::Uint8Clamped:
        tag = TD_UINT8;
        break;
      case js::Scalar::Int16:
        tag = TD_INT16;
        break;
      case js::Scalar::Uint16:
        tag = TD_UINT16;
        break;
      case js::Scalar::Int32:
        tag = TD_INT32;
        break;
      case js::Scalar::Uint32:
        tag = TD_UINT32;
        break;
      case js::Scalar::Float32:
        tag = TD_FLOAT;
        break;
      case js::Scalar::Float64:
        tag = TD_DOUBLE;
        break;
      default:
        return false;
    }
    if (aEltType.Tag() != tag) {
      return false;
    }

    // Allocate the backing buffer before getting the view data in case
    // allocFixupLen can cause GCs.
    uint32_t length = JS_GetTypedArrayLength(jsarray);
    void* buf = allocFixupLen(&length);
    if (!buf) {
      return false;
    }

    // Get the backing memory buffer to copy out of.
    JS::AutoCheckCannotGC nogc;
    bool isShared = false;
    const void* data = JS_GetArrayBufferViewData(jsarray, &isShared, nogc);

    // Require opting in to shared memory - a future project.
    if (isShared) {
      return false;
    }

    // Directly copy data into the allocated target buffer.
    memcpy(buf, data, length * aEltType.Stride());
    return true;
  }

  // If jsarray is not a TypedArrayObject, check for an Array object.
  uint32_t length = 0;
  bool isArray = false;
  if (!JS::IsArrayObject(cx, jsarray, &isArray) || !isArray ||
      !JS::GetArrayLength(cx, jsarray, &length)) {
    if (pErr) {
      *pErr = NS_ERROR_XPC_CANT_CONVERT_OBJECT_TO_ARRAY;
    }
    return false;
  }

  void* buf = allocFixupLen(&length);
  if (!buf) {
    return false;
  }

  // Translate each array element separately.
  RootedValue current(cx);
  for (uint32_t i = 0; i < length; ++i) {
    if (!JS_GetElement(cx, jsarray, i, &current) ||
        !JSData2Native(cx, aEltType.ElementPtr(buf, i), current, aEltType, aIID,
                       0, pErr)) {
      // Array element conversion failed. Clean up all elements converted
      // before the error. Caller handles freeing 'buf'.
      for (uint32_t j = 0; j < i; ++j) {
        DestructValue(aEltType, aEltType.ElementPtr(buf, j));
      }
      return false;
    }
  }

  return true;
}

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

// Internal implementation details for xpc::CleanupValue.

void xpc::InnerCleanupValue(const nsXPTType& aType, void* aValue,
                            uint32_t aArrayLen) {
  MOZ_ASSERT(!aType.IsArithmetic(),
             "Arithmetic types should not get to InnerCleanupValue!");
  MOZ_ASSERT(aArrayLen == 0 || aType.Tag() == nsXPTType::T_PSTRING_SIZE_IS ||
                 aType.Tag() == nsXPTType::T_PWSTRING_SIZE_IS ||
                 aType.Tag() == nsXPTType::T_LEGACY_ARRAY,
             "Array lengths may only appear for certain types!");

  switch (aType.Tag()) {
    // Pointer types
    case nsXPTType::T_DOMOBJECT:
      aType.GetDOMObjectInfo().Cleanup(*(void**)aValue);
      break;

    case nsXPTType::T_PROMISE:
      (*(mozilla::dom::Promise**)aValue)->Release();
      break;

    case nsXPTType::T_INTERFACE:
    case nsXPTType::T_INTERFACE_IS:
      (*(nsISupports**)aValue)->Release();
      break;

    // String types
    case nsXPTType::T_ASTRING:
      ((nsAString*)aValue)->Truncate();
      break;
    case nsXPTType::T_UTF8STRING:
    case nsXPTType::T_CSTRING:
      ((nsACString*)aValue)->Truncate();
      break;

    // Pointer Types
    case nsXPTType::T_NSIDPTR:
    case nsXPTType::T_CHAR_STR:
    case nsXPTType::T_WCHAR_STR:
    case nsXPTType::T_PSTRING_SIZE_IS:
    case nsXPTType::T_PWSTRING_SIZE_IS:
      free(*(void**)aValue);
      break;

    // Legacy Array Type
    case nsXPTType::T_LEGACY_ARRAY: {
      const nsXPTType& elty = aType.ArrayElementType();
      void* elements = *(void**)aValue;

      for (uint32_t i = 0; i < aArrayLen; ++i) {
        DestructValue(elty, elty.ElementPtr(elements, i));
      }
      free(elements);
      break;
    }

    // Array Type
    case nsXPTType::T_ARRAY: {
      const nsXPTType& elty = aType.ArrayElementType();
      auto* array = (xpt::detail::UntypedTArray*)aValue;

      for (uint32_t i = 0; i < array->Length(); ++i) {
        DestructValue(elty, elty.ElementPtr(array->Elements(), i));
      }
      array->Clear();
      break;
    }

    // Clear nsID& parameters to `0`
    case nsXPTType::T_NSID:
      ((nsID*)aValue)->Clear();
      break;

    // Clear the JS::Value to `undefined`
    case nsXPTType::T_JSVAL:
      ((JS::Value*)aValue)->setUndefined();
      break;

    // Non-arithmetic types requiring no cleanup
    case nsXPTType::T_VOID:
      break;

    default:
      MOZ_CRASH("Unknown Type!");
  }

  // Clear any non-complex values to the valid '0' state.
  if (!aType.IsComplex()) {
    aType.ZeroValue(aValue);
  }
}

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

// Implementation of xpc::InitializeValue.

void xpc::InitializeValue(const nsXPTType& aType, void* aValue) {
  switch (aType.Tag()) {
    // Use placement-new to initialize complex values
#define XPT_INIT_TYPE(tag, type) \
  case tag:                      \
    new (aValue) type();         \
    break;
    XPT_FOR_EACH_COMPLEX_TYPE(XPT_INIT_TYPE)
#undef XPT_INIT_TYPE

    // The remaining types have valid states where all bytes are '0'.
    default:
      aType.ZeroValue(aValue);
      break;
  }
}

// In XPT_FOR_EACH_COMPLEX_TYPE, typenames may be namespaced (such as
// xpt::UntypedTArray). Namespaced typenames cannot be used to explicitly invoke
// destructors, so this method acts as a helper to let us call the destructor of
// these objects.
template <typename T>
static void _DestructValueHelper(void* aValue) {
  static_cast<T*>(aValue)->~T();
}

void xpc::DestructValue(const nsXPTType& aType, void* aValue,
                        uint32_t aArrayLen) {
  // Get aValue into an clean, empty state.
  xpc::CleanupValue(aType, aValue, aArrayLen);

  // Run destructors on complex types.
  switch (aType.Tag()) {
#define XPT_RUN_DESTRUCTOR(tag, type)   \
  case tag:                             \
    _DestructValueHelper<type>(aValue); \
    break;
    XPT_FOR_EACH_COMPLEX_TYPE(XPT_RUN_DESTRUCTOR)
#undef XPT_RUN_DESTRUCTOR
    default:
      break;  // dtor is a no-op on other types.
  }
}