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.

Implementation

Mercurial (e5ef045527c6)

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

#ifndef __IPC_GLUE_IPCMESSAGEUTILS_H__
#define __IPC_GLUE_IPCMESSAGEUTILS_H__

#include "base/process_util.h"
#include "chrome/common/ipc_message_utils.h"

#include "mozilla/ArrayUtils.h"
#include "mozilla/Attributes.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/dom/ipc/StructuredCloneData.h"
#include "mozilla/EnumSet.h"
#include "mozilla/EnumTypeTraits.h"
#include "mozilla/Maybe.h"
#include "mozilla/net/WebSocketFrame.h"
#include "mozilla/TimeStamp.h"
#ifdef XP_WIN
#  include "mozilla/TimeStamp_windows.h"
#endif
#include "mozilla/TypeTraits.h"
#include "mozilla/IntegerTypeTraits.h"

#include <limits>
#include <stdint.h>
#include <type_traits>

#include "nsExceptionHandler.h"
#include "nsHashKeys.h"
#include "nsID.h"
#include "nsILoadInfo.h"
#include "nsIWidget.h"
#include "nsMemory.h"
#include "nsString.h"
#include "nsTArray.h"
#include "nsTHashtable.h"
#include "js/StructuredClone.h"
#include "nsCSSPropertyID.h"

#ifdef _MSC_VER
#  pragma warning(disable : 4800)
#endif

#if !defined(OS_POSIX)
// This condition must be kept in sync with the one in
// ipc_message_utils.h, but this dummy definition of
// base::FileDescriptor acts as a static assert that we only get one
// def or the other (or neither, in which case code using
// FileDescriptor fails to build)
namespace base {
struct FileDescriptor {};
}  // namespace base
#endif

namespace mozilla {

// This is a cross-platform approximation to HANDLE, which we expect
// to be typedef'd to void* or thereabouts.
typedef uintptr_t WindowsHandle;

// XXX there are out of place and might be generally useful.  Could
// move to nscore.h or something.
struct void_t {
  bool operator==(const void_t&) const { return true; }
};
struct null_t {
  bool operator==(const null_t&) const { return true; }
};

struct SerializedStructuredCloneBuffer final {
  SerializedStructuredCloneBuffer()
      : data(JS::StructuredCloneScope::Unassigned) {}

  SerializedStructuredCloneBuffer(const SerializedStructuredCloneBuffer& aOther)
      : SerializedStructuredCloneBuffer() {
    *this = aOther;
  }

  SerializedStructuredCloneBuffer& operator=(
      const SerializedStructuredCloneBuffer& aOther) {
    data.Clear();
    data.initScope(aOther.data.scope());
    MOZ_RELEASE_ASSERT(data.Append(aOther.data), "out of memory");
    return *this;
  }

  bool operator==(const SerializedStructuredCloneBuffer& aOther) const {
    // The copy assignment operator and the equality operator are
    // needed by the IPDL generated code. We relied on the copy
    // assignment operator at some places but we never use the
    // equality operator.
    return false;
  }

  JSStructuredCloneData data;
};

}  // namespace mozilla

namespace IPC {

/**
 * Generic enum serializer.
 *
 * Consider using the specializations below, such as ContiguousEnumSerializer.
 *
 * This is a generic serializer for any enum type used in IPDL.
 * Programmers can define ParamTraits<E> for enum type E by deriving
 * EnumSerializer<E, MyEnumValidator> where MyEnumValidator is a struct
 * that has to define a static IsLegalValue function returning whether
 * a given value is a legal value of the enum type at hand.
 *
 * \sa https://developer.mozilla.org/en/IPDL/Type_Serialization
 */
template <typename E, typename EnumValidator>
struct EnumSerializer {
  typedef E paramType;
  typedef typename mozilla::UnsignedStdintTypeForSize<sizeof(paramType)>::Type
      uintParamType;

  static void Write(Message* aMsg, const paramType& aValue) {
    MOZ_RELEASE_ASSERT(EnumValidator::IsLegalValue(aValue));
    WriteParam(aMsg, uintParamType(aValue));
  }

  static bool Read(const Message* aMsg, PickleIterator* aIter,
                   paramType* aResult) {
    uintParamType value;
    if (!ReadParam(aMsg, aIter, &value)) {
      CrashReporter::AnnotateCrashReport(
          CrashReporter::Annotation::IPCReadErrorReason,
          NS_LITERAL_CSTRING("Bad iter"));
      return false;
    } else if (!EnumValidator::IsLegalValue(paramType(value))) {
      CrashReporter::AnnotateCrashReport(
          CrashReporter::Annotation::IPCReadErrorReason,
          NS_LITERAL_CSTRING("Illegal value"));
      return false;
    }
    *aResult = paramType(value);
    return true;
  }
};

template <typename E, E MinLegal, E HighBound>
class ContiguousEnumValidator {
  // Silence overzealous -Wtype-limits bug in GCC fixed in GCC 4.8:
  // "comparison of unsigned expression >= 0 is always true"
  // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=11856
  template <typename T>
  static bool IsLessThanOrEqual(T a, T b) {
    return a <= b;
  }

 public:
  static bool IsLegalValue(E e) {
    return IsLessThanOrEqual(MinLegal, e) && e < HighBound;
  }
};

template <typename E, E MinLegal, E MaxLegal>
class ContiguousEnumValidatorInclusive {
  // Silence overzealous -Wtype-limits bug in GCC fixed in GCC 4.8:
  // "comparison of unsigned expression >= 0 is always true"
  // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=11856
  template <typename T>
  static bool IsLessThanOrEqual(T a, T b) {
    return a <= b;
  }

 public:
  static bool IsLegalValue(E e) {
    return IsLessThanOrEqual(MinLegal, e) && e <= MaxLegal;
  }
};

template <typename E, E AllBits>
struct BitFlagsEnumValidator {
  static bool IsLegalValue(E e) { return (e & AllBits) == e; }
};

/**
 * Specialization of EnumSerializer for enums with contiguous enum values.
 *
 * Provide two values: MinLegal, HighBound. An enum value x will be
 * considered legal if MinLegal <= x < HighBound.
 *
 * For example, following is definition of serializer for enum type FOO.
 * \code
 * enum FOO { FOO_FIRST, FOO_SECOND, FOO_LAST, NUM_FOO };
 *
 * template <>
 * struct ParamTraits<FOO>:
 *     public ContiguousEnumSerializer<FOO, FOO_FIRST, NUM_FOO> {};
 * \endcode
 * FOO_FIRST, FOO_SECOND, and FOO_LAST are valid value.
 */
template <typename E, E MinLegal, E HighBound>
struct ContiguousEnumSerializer
    : EnumSerializer<E, ContiguousEnumValidator<E, MinLegal, HighBound>> {};

/**
 * This is similar to ContiguousEnumSerializer, but the last template
 * parameter is expected to be the highest legal value, rather than a
 * sentinel value. This is intended to support enumerations that don't
 * have sentinel values.
 */
template <typename E, E MinLegal, E MaxLegal>
struct ContiguousEnumSerializerInclusive
    : EnumSerializer<E,
                     ContiguousEnumValidatorInclusive<E, MinLegal, MaxLegal>> {
};

/**
 * Specialization of EnumSerializer for enums representing bit flags.
 *
 * Provide one value: AllBits. An enum value x will be
 * considered legal if (x & AllBits) == x;
 *
 * Example:
 * \code
 * enum FOO {
 *   FOO_FIRST =  1 << 0,
 *   FOO_SECOND = 1 << 1,
 *   FOO_LAST =   1 << 2,
 *   ALL_BITS =   (1 << 3) - 1
 * };
 *
 * template <>
 * struct ParamTraits<FOO>:
 *     public BitFlagsEnumSerializer<FOO, FOO::ALL_BITS> {};
 * \endcode
 */
template <typename E, E AllBits>
struct BitFlagsEnumSerializer
    : EnumSerializer<E, BitFlagsEnumValidator<E, AllBits>> {};

/**
 * A helper class for serializing plain-old data (POD) structures.
 * The memory representation of the structure is written to and read from
 * the serialized stream directly, without individual processing of the
 * structure's members.
 *
 * Derive ParamTraits<T> from PlainOldDataSerializer<T> if T is POD.
 *
 * Note: For POD structures with enumeration fields, this will not do
 *   validation of the enum values the way serializing the fields
 *   individually would. Prefer serializing the fields individually
 *   in such cases.
 */
template <typename T>
struct PlainOldDataSerializer {
  // TODO: Once the mozilla::IsPod trait is in good enough shape (bug 900042),
  //       static_assert that mozilla::IsPod<T>::value is true.
  typedef T paramType;

  static void Write(Message* aMsg, const paramType& aParam) {
    aMsg->WriteBytes(&aParam, sizeof(aParam));
  }

  static bool Read(const Message* aMsg, PickleIterator* aIter,
                   paramType* aResult) {
    return aMsg->ReadBytesInto(aIter, aResult, sizeof(paramType));
  }
};

/**
 * A helper class for serializing empty structs. Since the struct is empty there
 * is nothing to write, and a priori we know the result of the read.
 */
template <typename T>
struct EmptyStructSerializer {
  typedef T paramType;

  static void Write(Message* aMsg, const paramType& aParam) {}

  static bool Read(const Message* aMsg, PickleIterator* aIter,
                   paramType* aResult) {
    *aResult = {};
    return true;
  }
};

template <>
struct ParamTraits<int8_t> {
  typedef int8_t paramType;

  static void Write(Message* aMsg, const paramType& aParam) {
    aMsg->WriteBytes(&aParam, sizeof(aParam));
  }

  static bool Read(const Message* aMsg, PickleIterator* aIter,
                   paramType* aResult) {
    return aMsg->ReadBytesInto(aIter, aResult, sizeof(*aResult));
  }

  static void Log(const paramType& aParam, std::wstring* aLog) {
    // Use 0xff to avoid sign extension.
    aLog->append(StringPrintf(L"0x%02x", aParam & 0xff));
  }
};

template <>
struct ParamTraits<uint8_t> {
  typedef uint8_t paramType;

  static void Write(Message* aMsg, const paramType& aParam) {
    aMsg->WriteBytes(&aParam, sizeof(aParam));
  }

  static bool Read(const Message* aMsg, PickleIterator* aIter,
                   paramType* aResult) {
    return aMsg->ReadBytesInto(aIter, aResult, sizeof(*aResult));
  }

  static void Log(const paramType& aParam, std::wstring* aLog) {
    aLog->append(StringPrintf(L"0x%02x", aParam));
  }
};

#if !defined(OS_POSIX)
// See above re: keeping definitions in sync
template <>
struct ParamTraits<base::FileDescriptor> {
  typedef base::FileDescriptor paramType;
  static void Write(Message* aMsg, const paramType& aParam) {
    MOZ_CRASH("FileDescriptor isn't meaningful on this platform");
  }
  static bool Read(const Message* aMsg, PickleIterator* aIter,
                   paramType* aResult) {
    MOZ_CRASH("FileDescriptor isn't meaningful on this platform");
    return false;
  }
};
#endif  // !defined(OS_POSIX)

template <>
struct ParamTraits<nsACString> {
  typedef nsACString paramType;

  static void Write(Message* aMsg, const paramType& aParam) {
    bool isVoid = aParam.IsVoid();
    aMsg->WriteBool(isVoid);

    if (isVoid)
      // represents a nullptr pointer
      return;

    uint32_t length = aParam.Length();
    WriteParam(aMsg, length);
    aMsg->WriteBytes(aParam.BeginReading(), length);
  }

  static bool Read(const Message* aMsg, PickleIterator* aIter,
                   paramType* aResult) {
    bool isVoid;
    if (!aMsg->ReadBool(aIter, &isVoid)) return false;

    if (isVoid) {
      aResult->SetIsVoid(true);
      return true;
    }

    uint32_t length;
    if (!ReadParam(aMsg, aIter, &length)) {
      return false;
    }
    if (!aMsg->HasBytesAvailable(aIter, length)) {
      return false;
    }
    aResult->SetLength(length);

    return aMsg->ReadBytesInto(aIter, aResult->BeginWriting(), length);
  }

  static void Log(const paramType& aParam, std::wstring* aLog) {
    if (aParam.IsVoid())
      aLog->append(L"(NULL)");
    else
      aLog->append(UTF8ToWide(aParam.BeginReading()));
  }
};

template <>
struct ParamTraits<nsAString> {
  typedef nsAString paramType;

  static void Write(Message* aMsg, const paramType& aParam) {
    bool isVoid = aParam.IsVoid();
    aMsg->WriteBool(isVoid);

    if (isVoid)
      // represents a nullptr pointer
      return;

    uint32_t length = aParam.Length();
    WriteParam(aMsg, length);
    aMsg->WriteBytes(aParam.BeginReading(), length * sizeof(char16_t));
  }

  static bool Read(const Message* aMsg, PickleIterator* aIter,
                   paramType* aResult) {
    bool isVoid;
    if (!aMsg->ReadBool(aIter, &isVoid)) return false;

    if (isVoid) {
      aResult->SetIsVoid(true);
      return true;
    }

    uint32_t length;
    if (!ReadParam(aMsg, aIter, &length)) {
      return false;
    }

    mozilla::CheckedInt<uint32_t> byteLength =
        mozilla::CheckedInt<uint32_t>(length) * sizeof(char16_t);
    if (!byteLength.isValid() ||
        !aMsg->HasBytesAvailable(aIter, byteLength.value())) {
      return false;
    }

    aResult->SetLength(length);

    return aMsg->ReadBytesInto(aIter, aResult->BeginWriting(),
                               byteLength.value());
  }

  static void Log(const paramType& aParam, std::wstring* aLog) {
    if (aParam.IsVoid())
      aLog->append(L"(NULL)");
    else {
#ifdef WCHAR_T_IS_UTF16
      aLog->append(reinterpret_cast<const wchar_t*>(aParam.BeginReading()));
#else
      uint32_t length = aParam.Length();
      for (uint32_t index = 0; index < length; index++) {
        aLog->push_back(std::wstring::value_type(aParam[index]));
      }
#endif
    }
  }
};

template <>
struct ParamTraits<nsCString> : ParamTraits<nsACString> {
  typedef nsCString paramType;
};

template <>
struct ParamTraits<nsLiteralCString> : ParamTraits<nsACString> {
  typedef nsLiteralCString paramType;
};

#ifdef MOZILLA_INTERNAL_API

template <>
struct ParamTraits<nsAutoCString> : ParamTraits<nsCString> {
  typedef nsAutoCString paramType;
};

#endif  // MOZILLA_INTERNAL_API

template <>
struct ParamTraits<nsString> : ParamTraits<nsAString> {
  typedef nsString paramType;
};

template <>
struct ParamTraits<nsLiteralString> : ParamTraits<nsAString> {
  typedef nsLiteralString paramType;
};

template <>
struct ParamTraits<nsDependentSubstring> : ParamTraits<nsAString> {
  typedef nsDependentSubstring paramType;
};

template <>
struct ParamTraits<nsDependentCSubstring> : ParamTraits<nsACString> {
  typedef nsDependentCSubstring paramType;
};

#ifdef MOZILLA_INTERNAL_API

template <>
struct ParamTraits<nsAutoString> : ParamTraits<nsString> {
  typedef nsAutoString paramType;
};

#endif  // MOZILLA_INTERNAL_API

template <>
struct ParamTraits<nsTHashtable<nsUint64HashKey>> {
  typedef nsTHashtable<nsUint64HashKey> paramType;

  static void Write(Message* aMsg, const paramType& aParam) {
    uint32_t count = aParam.Count();
    WriteParam(aMsg, count);
    for (auto iter = aParam.ConstIter(); !iter.Done(); iter.Next()) {
      WriteParam(aMsg, iter.Get()->GetKey());
    }
  }

  static bool Read(const Message* aMsg, PickleIterator* aIter,
                   paramType* aResult) {
    uint32_t count;
    if (!ReadParam(aMsg, aIter, &count)) {
      return false;
    }
    paramType table(count);
    for (uint32_t i = 0; i < count; ++i) {
      uint64_t key;
      if (!ReadParam(aMsg, aIter, &key)) {
        return false;
      }
      table.PutEntry(key);
    }
    *aResult = std::move(table);
    return true;
  }
};

// Pickle::ReadBytes and ::WriteBytes take the length in ints, so we must
// ensure there is no overflow. This returns |false| if it would overflow.
// Otherwise, it returns |true| and places the byte length in |aByteLength|.
bool ByteLengthIsValid(uint32_t aNumElements, size_t aElementSize,
                       int* aByteLength);

// Note: IPDL will sometimes codegen specialized implementations of
// nsTArray serialization and deserialization code in
// implementSpecialArrayPickling(). This is needed when ParamTraits<E>
// is not defined.
template <typename E>
struct ParamTraits<nsTArray<E>> {
  typedef nsTArray<E> paramType;

  // We write arrays of integer or floating-point data using a single pickling
  // call, rather than writing each element individually.  We deliberately do
  // not use mozilla::IsPod here because it is perfectly reasonable to have
  // a data structure T for which IsPod<T>::value is true, yet also have a
  // ParamTraits<T> specialization.
  static const bool sUseWriteBytes =
      (mozilla::IsIntegral<E>::value || mozilla::IsFloatingPoint<E>::value);

  static void Write(Message* aMsg, const paramType& aParam) {
    uint32_t length = aParam.Length();
    WriteParam(aMsg, length);

    if (sUseWriteBytes) {
      int pickledLength = 0;
      MOZ_RELEASE_ASSERT(ByteLengthIsValid(length, sizeof(E), &pickledLength));
      aMsg->WriteBytes(aParam.Elements(), pickledLength);
    } else {
      const E* elems = aParam.Elements();
      for (uint32_t index = 0; index < length; index++) {
        WriteParam(aMsg, elems[index]);
      }
    }
  }

  // This method uses infallible allocation so that an OOM failure will
  // show up as an OOM crash rather than an IPC FatalError.
  static bool Read(const Message* aMsg, PickleIterator* aIter,
                   paramType* aResult) {
    uint32_t length;
    if (!ReadParam(aMsg, aIter, &length)) {
      return false;
    }

    if (sUseWriteBytes) {
      int pickledLength = 0;
      if (!ByteLengthIsValid(length, sizeof(E), &pickledLength)) {
        return false;
      }

      E* elements = aResult->AppendElements(length);
      return aMsg->ReadBytesInto(aIter, elements, pickledLength);
    } else {
      // Each ReadParam<E> may read more than 1 byte each; this is an attempt
      // to minimally validate that the length isn't much larger than what's
      // actually available in aMsg.
      if (!aMsg->HasBytesAvailable(aIter, length)) {
        return false;
      }

      aResult->SetCapacity(length);

      for (uint32_t index = 0; index < length; index++) {
        E* element = aResult->AppendElement();
        if (!ReadParam(aMsg, aIter, element)) {
          return false;
        }
      }
      return true;
    }
  }

  static void Log(const paramType& aParam, std::wstring* aLog) {
    for (uint32_t index = 0; index < aParam.Length(); index++) {
      if (index) {
        aLog->append(L" ");
      }
      LogParam(aParam[index], aLog);
    }
  }
};

template <typename E>
struct ParamTraits<FallibleTArray<E>> {
  typedef FallibleTArray<E> paramType;

  static void Write(Message* aMsg, const paramType& aParam) {
    WriteParam(aMsg, static_cast<const nsTArray<E>&>(aParam));
  }

  // Deserialize the array infallibly, but return a FallibleTArray.
  static bool Read(const Message* aMsg, PickleIterator* aIter,
                   paramType* aResult) {
    nsTArray<E> temp;
    if (!ReadParam(aMsg, aIter, &temp)) return false;

    aResult->SwapElements(temp);
    return true;
  }

  static void Log(const paramType& aParam, std::wstring* aLog) {
    LogParam(static_cast<const nsTArray<E>&>(aParam), aLog);
  }
};

template <typename E, size_t N>
struct ParamTraits<AutoTArray<E, N>> : ParamTraits<nsTArray<E>> {
  typedef AutoTArray<E, N> paramType;
};

template <>
struct ParamTraits<float> {
  typedef float paramType;

  static void Write(Message* aMsg, const paramType& aParam) {
    aMsg->WriteBytes(&aParam, sizeof(paramType));
  }

  static bool Read(const Message* aMsg, PickleIterator* aIter,
                   paramType* aResult) {
    return aMsg->ReadBytesInto(aIter, aResult, sizeof(*aResult));
  }

  static void Log(const paramType& aParam, std::wstring* aLog) {
    aLog->append(StringPrintf(L"%g", aParam));
  }
};

template <>
struct ParamTraits<nsCSSPropertyID>
    : public ContiguousEnumSerializer<nsCSSPropertyID, eCSSProperty_UNKNOWN,
                                      eCSSProperty_COUNT> {};

template <>
struct ParamTraits<mozilla::void_t> {
  typedef mozilla::void_t paramType;
  static void Write(Message* aMsg, const paramType& aParam) {}
  static bool Read(const Message* aMsg, PickleIterator* aIter,
                   paramType* aResult) {
    *aResult = paramType();
    return true;
  }
};

template <>
struct ParamTraits<mozilla::null_t> {
  typedef mozilla::null_t paramType;
  static void Write(Message* aMsg, const paramType& aParam) {}
  static bool Read(const Message* aMsg, PickleIterator* aIter,
                   paramType* aResult) {
    *aResult = paramType();
    return true;
  }
};

template <>
struct ParamTraits<nsID> {
  typedef nsID paramType;

  static void Write(Message* aMsg, const paramType& aParam) {
    WriteParam(aMsg, aParam.m0);
    WriteParam(aMsg, aParam.m1);
    WriteParam(aMsg, aParam.m2);
    for (unsigned int i = 0; i < mozilla::ArrayLength(aParam.m3); i++) {
      WriteParam(aMsg, aParam.m3[i]);
    }
  }

  static bool Read(const Message* aMsg, PickleIterator* aIter,
                   paramType* aResult) {
    if (!ReadParam(aMsg, aIter, &(aResult->m0)) ||
        !ReadParam(aMsg, aIter, &(aResult->m1)) ||
        !ReadParam(aMsg, aIter, &(aResult->m2)))
      return false;

    for (unsigned int i = 0; i < mozilla::ArrayLength(aResult->m3); i++)
      if (!ReadParam(aMsg, aIter, &(aResult->m3[i]))) return false;

    return true;
  }

  static void Log(const paramType& aParam, std::wstring* aLog) {
    aLog->append(L"{");
    aLog->append(
        StringPrintf(L"%8.8X-%4.4X-%4.4X-", aParam.m0, aParam.m1, aParam.m2));
    for (unsigned int i = 0; i < mozilla::ArrayLength(aParam.m3); i++)
      aLog->append(StringPrintf(L"%2.2X", aParam.m3[i]));
    aLog->append(L"}");
  }
};

template <>
struct ParamTraits<mozilla::TimeDuration> {
  typedef mozilla::TimeDuration paramType;
  static void Write(Message* aMsg, const paramType& aParam) {
    WriteParam(aMsg, aParam.mValue);
  }
  static bool Read(const Message* aMsg, PickleIterator* aIter,
                   paramType* aResult) {
    return ReadParam(aMsg, aIter, &aResult->mValue);
  };
};

template <>
struct ParamTraits<mozilla::TimeStamp> {
  typedef mozilla::TimeStamp paramType;
  static void Write(Message* aMsg, const paramType& aParam) {
    WriteParam(aMsg, aParam.mValue);
  }
  static bool Read(const Message* aMsg, PickleIterator* aIter,
                   paramType* aResult) {
    return ReadParam(aMsg, aIter, &aResult->mValue);
  };
};

#ifdef XP_WIN

template <>
struct ParamTraits<mozilla::TimeStampValue> {
  typedef mozilla::TimeStampValue paramType;
  static void Write(Message* aMsg, const paramType& aParam) {
    WriteParam(aMsg, aParam.mGTC);
    WriteParam(aMsg, aParam.mQPC);
    WriteParam(aMsg, aParam.mUsedCanonicalNow);
    WriteParam(aMsg, aParam.mIsNull);
    WriteParam(aMsg, aParam.mHasQPC);
  }
  static bool Read(const Message* aMsg, PickleIterator* aIter,
                   paramType* aResult) {
    return (ReadParam(aMsg, aIter, &aResult->mGTC) &&
            ReadParam(aMsg, aIter, &aResult->mQPC) &&
            ReadParam(aMsg, aIter, &aResult->mUsedCanonicalNow) &&
            ReadParam(aMsg, aIter, &aResult->mIsNull) &&
            ReadParam(aMsg, aIter, &aResult->mHasQPC));
  }
};

#else

template <>
struct ParamTraits<mozilla::TimeStamp63Bit> {
  typedef mozilla::TimeStamp63Bit paramType;
  static void Write(Message* aMsg, const paramType& aParam) {
    WriteParam(aMsg, aParam.mUsedCanonicalNow);
    WriteParam(aMsg, aParam.mTimeStamp);
  }
  static bool Read(const Message* aMsg, PickleIterator* aIter,
                   paramType* aResult) {
    bool success = true;
    uint64_t result;

    success &= ReadParam(aMsg, aIter, &result);
    aResult->mUsedCanonicalNow = result & 0x01;

    success &= ReadParam(aMsg, aIter, &result);
    aResult->mTimeStamp = result & 0x7FFFFFFFFFFFFFFF;

    return success;
  }
};

#endif

template <>
struct ParamTraits<mozilla::dom::ipc::StructuredCloneData> {
  typedef mozilla::dom::ipc::StructuredCloneData paramType;

  static void Write(Message* aMsg, const paramType& aParam) {
    aParam.WriteIPCParams(aMsg);
  }

  static bool Read(const Message* aMsg, PickleIterator* aIter,
                   paramType* aResult) {
    return aResult->ReadIPCParams(aMsg, aIter);
  }

  static void Log(const paramType& aParam, std::wstring* aLog) {
    LogParam(aParam.DataLength(), aLog);
  }
};

template <>
struct ParamTraits<mozilla::net::WebSocketFrameData> {
  typedef mozilla::net::WebSocketFrameData paramType;

  static void Write(Message* aMsg, const paramType& aParam) {
    aParam.WriteIPCParams(aMsg);
  }

  static bool Read(const Message* aMsg, PickleIterator* aIter,
                   paramType* aResult) {
    return aResult->ReadIPCParams(aMsg, aIter);
  }
};

template <>
struct ParamTraits<JSStructuredCloneData> {
  typedef JSStructuredCloneData paramType;

  static void Write(Message* aMsg, const paramType& aParam) {
    MOZ_ASSERT(!(aParam.Size() % sizeof(uint64_t)));
    WriteParam(aMsg, aParam.Size());
    aParam.ForEachDataChunk([&](const char* aData, size_t aSize) {
      return aMsg->WriteBytes(aData, aSize, sizeof(uint64_t));
    });
  }

  static bool Read(const Message* aMsg, PickleIterator* aIter,
                   paramType* aResult) {
    size_t length = 0;
    if (!ReadParam(aMsg, aIter, &length)) {
      return false;
    }
    MOZ_ASSERT(!(length % sizeof(uint64_t)));

    mozilla::BufferList<InfallibleAllocPolicy> buffers(0, 0, 4096);

    // Borrowing is not suitable to use for IPC to hand out data
    // because we often want to store the data somewhere for
    // processing after IPC has released the underlying buffers. One
    // case is PContentChild::SendGetXPCOMProcessAttributes. We can't
    // return a borrowed buffer because the out param outlives the
    // IPDL callback.
    if (length &&
        !aMsg->ExtractBuffers(aIter, length, &buffers, sizeof(uint64_t))) {
      return false;
    }

    bool success;
    mozilla::BufferList<js::SystemAllocPolicy> out =
        buffers.MoveFallible<js::SystemAllocPolicy>(&success);
    if (!success) {
      return false;
    }

    *aResult = JSStructuredCloneData(
        std::move(out), JS::StructuredCloneScope::DifferentProcess);

    return true;
  }
};

template <>
struct ParamTraits<mozilla::SerializedStructuredCloneBuffer> {
  typedef mozilla::SerializedStructuredCloneBuffer paramType;

  static void Write(Message* aMsg, const paramType& aParam) {
    WriteParam(aMsg, aParam.data);
  }

  static bool Read(const Message* aMsg, PickleIterator* aIter,
                   paramType* aResult) {
    return ReadParam(aMsg, aIter, &aResult->data);
  }

  static void Log(const paramType& aParam, std::wstring* aLog) {
    LogParam(aParam.data.Size(), aLog);
  }
};

template <>
struct ParamTraits<nsIWidget::TouchPointerState>
    : public BitFlagsEnumSerializer<nsIWidget::TouchPointerState,
                                    nsIWidget::TouchPointerState::ALL_BITS> {};

template <class T>
struct ParamTraits<mozilla::Maybe<T>> {
  typedef mozilla::Maybe<T> paramType;

  static void Write(Message* msg, const paramType& param) {
    if (param.isSome()) {
      WriteParam(msg, true);
      WriteParam(msg, param.value());
    } else {
      WriteParam(msg, false);
    }
  }

  static bool Read(const Message* msg, PickleIterator* iter,
                   paramType* result) {
    bool isSome;
    if (!ReadParam(msg, iter, &isSome)) {
      return false;
    }
    if (isSome) {
      T tmp;
      if (!ReadParam(msg, iter, &tmp)) {
        return false;
      }
      *result = mozilla::Some(std::move(tmp));
    } else {
      *result = mozilla::Nothing();
    }
    return true;
  }
};

template <typename T, typename U>
struct ParamTraits<mozilla::EnumSet<T, U>> {
  typedef mozilla::EnumSet<T, U> paramType;
  typedef U serializedType;

  static void Write(Message* msg, const paramType& param) {
    MOZ_RELEASE_ASSERT(IsLegalValue(param.serialize()));
    WriteParam(msg, param.serialize());
  }

  static bool Read(const Message* msg, PickleIterator* iter,
                   paramType* result) {
    serializedType tmp;

    if (ReadParam(msg, iter, &tmp)) {
      if (IsLegalValue(tmp)) {
        result->deserialize(tmp);
        return true;
      }
    }

    return false;
  }

  static constexpr serializedType AllEnumBits() {
    return ~serializedType(0) >> (std::numeric_limits<serializedType>::digits -
                                  (mozilla::MaxEnumValue<T>::value + 1));
  }

  static constexpr bool IsLegalValue(const serializedType value) {
    static_assert(mozilla::MaxEnumValue<T>::value <
                      std::numeric_limits<serializedType>::digits,
                  "Enum max value is not in the range!");
    static_assert(
        std::is_unsigned<decltype(mozilla::MaxEnumValue<T>::value)>::value,
        "Type of MaxEnumValue<T>::value specialization should be unsigned!");

    return (value & AllEnumBits()) == value;
  }
};

template <class... Ts>
struct ParamTraits<mozilla::Variant<Ts...>> {
  typedef mozilla::Variant<Ts...> paramType;
  using Tag = typename mozilla::detail::VariantTag<Ts...>::Type;

  static void Write(Message* msg, const paramType& param) {
    WriteParam(msg, param.tag);
    param.match([msg](const auto& t) { WriteParam(msg, t); });
  }

  // Because VariantReader is a nested struct, we need the dummy template
  // parameter to avoid making VariantReader<0> an explicit specialization,
  // which is not allowed for a nested class template
  template <size_t N, typename dummy = void>
  struct VariantReader {
    using Next = VariantReader<N - 1>;

    static bool Read(const Message* msg, PickleIterator* iter, Tag tag,
                     paramType* result) {
      // Since the VariantReader specializations start at N , we need to
      // subtract one to look at N - 1, the first valid tag.  This means our
      // comparisons are off by 1.  If we get to N = 0 then we have failed to
      // find a match to the tag.
      if (tag == N - 1) {
        // Recall, even though the template parameter is N, we are
        // actually interested in the N - 1 tag.
        typename mozilla::detail::Nth<N - 1, Ts...>::Type val;
        if (ReadParam(msg, iter, &val)) {
          *result = mozilla::AsVariant(val);
          return true;
        }
        return false;
      } else {
        return Next::Read(msg, iter, tag, result);
      }
    }

  };  // VariantReader<N>

  // Since we are conditioning on tag = N - 1 in the preceding specialization,
  // if we get to `VariantReader<0, dummy>` we have failed to find
  // a matching tag.
  template <typename dummy>
  struct VariantReader<0, dummy> {
    static bool Read(const Message* msg, PickleIterator* iter, Tag tag,
                     paramType* result) {
      return false;
    }
  };

  static bool Read(const Message* msg, PickleIterator* iter,
                   paramType* result) {
    Tag tag;
    if (ReadParam(msg, iter, &tag)) {
      return VariantReader<sizeof...(Ts)>::Read(msg, iter, tag, result);
    }
    return false;
  }
};

template <typename T>
struct ParamTraits<mozilla::dom::Optional<T>> {
  typedef mozilla::dom::Optional<T> paramType;

  static void Write(Message* aMsg, const paramType& aParam) {
    if (aParam.WasPassed()) {
      WriteParam(aMsg, true);
      WriteParam(aMsg, aParam.Value());
      return;
    }

    WriteParam(aMsg, false);
  }

  static bool Read(const Message* aMsg, PickleIterator* aIter,
                   paramType* aResult) {
    bool wasPassed = false;

    if (!ReadParam(aMsg, aIter, &wasPassed)) {
      return false;
    }

    aResult->Reset();

    if (wasPassed) {
      if (!ReadParam(aMsg, aIter, &aResult->Construct())) {
        return false;
      }
    }

    return true;
  }
};

struct CrossOriginOpenerPolicyValidator {
  static bool IsLegalValue(nsILoadInfo::CrossOriginOpenerPolicy e) {
    return e == nsILoadInfo::OPENER_POLICY_NULL ||
           e == nsILoadInfo::OPENER_POLICY_SAME_ORIGIN ||
           e == nsILoadInfo::OPENER_POLICY_SAME_SITE ||
           e == nsILoadInfo::OPENER_POLICY_SAME_ORIGIN_ALLOW_OUTGOING ||
           e == nsILoadInfo::OPENER_POLICY_SAME_SITE_ALLOW_OUTGOING;
  }
};

template <>
struct ParamTraits<nsILoadInfo::CrossOriginOpenerPolicy>
    : EnumSerializer<nsILoadInfo::CrossOriginOpenerPolicy,
                     CrossOriginOpenerPolicyValidator> {};

struct CrossOriginPolicyValidator {
  static bool IsLegalValue(nsILoadInfo::CrossOriginPolicy e) {
    return e == nsILoadInfo::CROSS_ORIGIN_POLICY_NULL ||
           e == nsILoadInfo::CROSS_ORIGIN_POLICY_ANONYMOUS ||
           e == nsILoadInfo::CROSS_ORIGIN_POLICY_USE_CREDENTIALS;
  }
};

template <>
struct ParamTraits<nsILoadInfo::CrossOriginPolicy>
    : EnumSerializer<nsILoadInfo::CrossOriginPolicy,
                     CrossOriginPolicyValidator> {};

// Helper class for reading bitfields.
// If T has bitfields members, derive ParamTraits<T> from BitfieldHelper<T>.
template <typename ParamType>
struct BitfieldHelper {
  // We need this helper because we can't get the address of a bitfield to
  // pass directly to ReadParam. So instead we read it into a temporary bool
  // and set the bitfield using a setter function
  static bool ReadBoolForBitfield(const Message* aMsg, PickleIterator* aIter,
                                  ParamType* aResult,
                                  void (ParamType::*aSetter)(bool)) {
    bool value;
    if (ReadParam(aMsg, aIter, &value)) {
      (aResult->*aSetter)(value);
      return true;
    }
    return false;
  }
};

} /* namespace IPC */

#endif /* __IPC_GLUE_IPCMESSAGEUTILS_H__ */