DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (014c61389f0b)

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
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "mozilla/Logging.h"

#include "gfxUserFontSet.h"
#include "gfxPlatform.h"
#include "nsIProtocolHandler.h"
#include "gfxFontConstants.h"
#include "mozilla/FontPropertyTypes.h"
#include "mozilla/Preferences.h"
#include "mozilla/Services.h"
#include "mozilla/StaticPrefs_gfx.h"
#include "mozilla/Telemetry.h"
#include "mozilla/gfx/2D.h"
#include "gfxPlatformFontList.h"
#include "mozilla/ServoStyleSet.h"
#include "mozilla/PostTraversalTask.h"

#include "opentype-sanitiser.h"
#include "ots-memory-stream.h"

using namespace mozilla;

mozilla::LogModule* gfxUserFontSet::GetUserFontsLog() {
  static LazyLogModule sLog("userfonts");
  return sLog;
}

#define LOG(args) \
  MOZ_LOG(gfxUserFontSet::GetUserFontsLog(), mozilla::LogLevel::Debug, args)
#define LOG_ENABLED() \
  MOZ_LOG_TEST(gfxUserFontSet::GetUserFontsLog(), mozilla::LogLevel::Debug)

static uint64_t sFontSetGeneration = 0;

// Based on ots::ExpandingMemoryStream from ots-memory-stream.h,
// adapted to use Mozilla allocators and to allow the final
// memory buffer to be adopted by the client.
class ExpandingMemoryStream : public ots::OTSStream {
 public:
  ExpandingMemoryStream(size_t initial, size_t limit)
      : mLength(initial), mLimit(limit), mOff(0) {
    mPtr = moz_xmalloc(mLength);
  }

  ~ExpandingMemoryStream() { free(mPtr); }

  // Return the buffer, resized to fit its contents (as it may have been
  // over-allocated during growth), and give up ownership of it so the
  // caller becomes responsible to call free() when finished with it.
  void* forget() {
    void* p = moz_xrealloc(mPtr, mOff);
    mPtr = nullptr;
    return p;
  }

  bool WriteRaw(const void* data, size_t length) override {
    if ((mOff + length > mLength) ||
        (mLength > std::numeric_limits<size_t>::max() - mOff)) {
      if (mLength == mLimit) {
        return false;
      }
      size_t newLength = (mLength + 1) * 2;
      if (newLength < mLength) {
        return false;
      }
      if (newLength > mLimit) {
        newLength = mLimit;
      }
      mPtr = moz_xrealloc(mPtr, newLength);
      mLength = newLength;
      return WriteRaw(data, length);
    }
    std::memcpy(static_cast<char*>(mPtr) + mOff, data, length);
    mOff += length;
    return true;
  }

  bool Seek(off_t position) override {
    if (position < 0) {
      return false;
    }
    if (static_cast<size_t>(position) > mLength) {
      return false;
    }
    mOff = position;
    return true;
  }

  off_t Tell() const override { return mOff; }

 private:
  void* mPtr;
  size_t mLength;
  const size_t mLimit;
  off_t mOff;
};

gfxUserFontEntry::gfxUserFontEntry(
    gfxUserFontSet* aFontSet, const nsTArray<gfxFontFaceSrc>& aFontFaceSrcList,
    WeightRange aWeight, StretchRange aStretch, SlantStyleRange aStyle,
    const nsTArray<gfxFontFeature>& aFeatureSettings,
    const nsTArray<gfxFontVariation>& aVariationSettings,
    uint32_t aLanguageOverride, gfxCharacterMap* aUnicodeRanges,
    StyleFontDisplay aFontDisplay, RangeFlags aRangeFlags)
    : gfxFontEntry(NS_LITERAL_CSTRING("userfont")),
      mUserFontLoadState(STATUS_NOT_LOADED),
      mFontDataLoadingState(NOT_LOADING),
      mUnsupportedFormat(false),
      mFontDisplay(aFontDisplay),
      mLoader(nullptr),
      mFontSet(aFontSet) {
  mIsUserFontContainer = true;
  mSrcList = aFontFaceSrcList;
  mSrcIndex = 0;
  mWeightRange = aWeight;
  mStretchRange = aStretch;
  mStyleRange = aStyle;
  mFeatureSettings.AppendElements(aFeatureSettings);
  mVariationSettings.AppendElements(aVariationSettings);
  mLanguageOverride = aLanguageOverride;
  mCharacterMap = aUnicodeRanges;
  mRangeFlags = aRangeFlags;
}

void gfxUserFontEntry::UpdateAttributes(
    WeightRange aWeight, StretchRange aStretch, SlantStyleRange aStyle,
    const nsTArray<gfxFontFeature>& aFeatureSettings,
    const nsTArray<gfxFontVariation>& aVariationSettings,
    uint32_t aLanguageOverride, gfxCharacterMap* aUnicodeRanges,
    StyleFontDisplay aFontDisplay, RangeFlags aRangeFlags) {
  // Remove the entry from the user font cache, if present there, as the cache
  // key may no longer be correct with the new attributes.
  gfxUserFontSet::UserFontCache::ForgetFont(this);

  mFontDisplay = aFontDisplay;
  mWeightRange = aWeight;
  mStretchRange = aStretch;
  mStyleRange = aStyle;
  mFeatureSettings = aFeatureSettings;
  mVariationSettings = aVariationSettings;
  mLanguageOverride = aLanguageOverride;
  mCharacterMap = aUnicodeRanges;
  mRangeFlags = aRangeFlags;
}

gfxUserFontEntry::~gfxUserFontEntry() {
  // Assert that we don't drop any gfxUserFontEntry objects during a Servo
  // traversal, since PostTraversalTask objects can hold raw pointers to
  // gfxUserFontEntry objects.
  MOZ_ASSERT(!ServoStyleSet::IsInServoTraversal());
}

bool gfxUserFontEntry::Matches(
    const nsTArray<gfxFontFaceSrc>& aFontFaceSrcList, WeightRange aWeight,
    StretchRange aStretch, SlantStyleRange aStyle,
    const nsTArray<gfxFontFeature>& aFeatureSettings,
    const nsTArray<gfxFontVariation>& aVariationSettings,
    uint32_t aLanguageOverride, gfxCharacterMap* aUnicodeRanges,
    StyleFontDisplay aFontDisplay, RangeFlags aRangeFlags) {
  return Weight() == aWeight && Stretch() == aStretch &&
         SlantStyle() == aStyle && mFeatureSettings == aFeatureSettings &&
         mVariationSettings == aVariationSettings &&
         mLanguageOverride == aLanguageOverride &&
         mSrcList == aFontFaceSrcList && mFontDisplay == aFontDisplay &&
         mRangeFlags == aRangeFlags &&
         ((!aUnicodeRanges && !mCharacterMap) ||
          (aUnicodeRanges && mCharacterMap &&
           mCharacterMap->Equals(aUnicodeRanges)));
}

gfxFont* gfxUserFontEntry::CreateFontInstance(const gfxFontStyle* aFontStyle) {
  MOZ_ASSERT_UNREACHABLE(
      "should only be creating a gfxFont"
      " with an actual platform font entry");

  // userfont entry is a container, can't create font from the container
  return nullptr;
}

class MOZ_STACK_CLASS gfxOTSContext : public ots::OTSContext {
 public:
  gfxOTSContext() {
    // Whether to apply OTS validation to OpenType Layout tables
    mCheckOTLTables = StaticPrefs::gfx_downloadable_fonts_otl_validation();
    // Whether to preserve Variation tables in downloaded fonts
    mCheckVariationTables =
        StaticPrefs::gfx_downloadable_fonts_validate_variation_tables();
    // Whether to preserve color bitmap glyphs
    mKeepColorBitmaps =
        StaticPrefs::gfx_downloadable_fonts_keep_color_bitmaps();
  }

  virtual ~gfxOTSContext() {
    MOZ_ASSERT(mMessages.IsEmpty(), "should have called TakeMessages");
  }

  virtual ots::TableAction GetTableAction(uint32_t aTag) override {
    // Preserve Graphite, color glyph and SVG tables,
    // and possibly OTL and Variation tables (depending on prefs)
    if ((!mCheckOTLTables && (aTag == TRUETYPE_TAG('G', 'D', 'E', 'F') ||
                              aTag == TRUETYPE_TAG('G', 'P', 'O', 'S') ||
                              aTag == TRUETYPE_TAG('G', 'S', 'U', 'B'))) ||
        (!mCheckVariationTables &&
         (aTag == TRUETYPE_TAG('a', 'v', 'a', 'r') ||
          aTag == TRUETYPE_TAG('c', 'v', 'a', 'r') ||
          aTag == TRUETYPE_TAG('f', 'v', 'a', 'r') ||
          aTag == TRUETYPE_TAG('g', 'v', 'a', 'r') ||
          aTag == TRUETYPE_TAG('H', 'V', 'A', 'R') ||
          aTag == TRUETYPE_TAG('M', 'V', 'A', 'R') ||
          aTag == TRUETYPE_TAG('S', 'T', 'A', 'T') ||
          aTag == TRUETYPE_TAG('V', 'V', 'A', 'R'))) ||
        aTag == TRUETYPE_TAG('S', 'V', 'G', ' ') ||
        aTag == TRUETYPE_TAG('C', 'O', 'L', 'R') ||
        aTag == TRUETYPE_TAG('C', 'P', 'A', 'L') ||
        (mKeepColorBitmaps && (aTag == TRUETYPE_TAG('C', 'B', 'D', 'T') ||
                               aTag == TRUETYPE_TAG('C', 'B', 'L', 'C'))) ||
        false) {
      return ots::TABLE_ACTION_PASSTHRU;
    }
    return ots::TABLE_ACTION_DEFAULT;
  }

  virtual void Message(int level, const char* format,
                       ...) MSGFUNC_FMT_ATTR override {
    va_list va;
    va_start(va, format);

    nsCString msg;
    msg.AppendPrintf(format, va);

    va_end(va);

    if (level > 0) {
      // For warnings (rather than errors that cause the font to fail),
      // we only report the first instance of any given message.
      if (mWarningsIssued.Contains(msg)) {
        return;
      }
      mWarningsIssued.PutEntry(msg);
    }

    mMessages.AppendElement(msg);
  }

  bool Process(ots::OTSStream* aOutput, const uint8_t* aInput, size_t aLength,
               nsTArray<nsCString>& aMessages) {
    bool ok = ots::OTSContext::Process(aOutput, aInput, aLength);
    aMessages = TakeMessages();
    return ok;
  }

  nsTArray<nsCString>&& TakeMessages() { return std::move(mMessages); }

 private:
  nsTHashtable<nsCStringHashKey> mWarningsIssued;
  nsTArray<nsCString> mMessages;
  bool mCheckOTLTables;
  bool mCheckVariationTables;
  bool mKeepColorBitmaps;
};

// Call the OTS library to sanitize an sfnt before attempting to use it.
// Returns a newly-allocated block, or nullptr in case of fatal errors.
const uint8_t* gfxUserFontEntry::SanitizeOpenTypeData(
    const uint8_t* aData, uint32_t aLength, uint32_t& aSaneLength,
    gfxUserFontType& aFontType, nsTArray<nsCString>& aMessages) {
  aFontType = gfxFontUtils::DetermineFontDataType(aData, aLength);
  Telemetry::Accumulate(Telemetry::WEBFONT_FONTTYPE, uint32_t(aFontType));

  if (aFontType == GFX_USERFONT_UNKNOWN) {
    aSaneLength = 0;
    return nullptr;
  }

  uint32_t lengthHint = aLength;
  if (aFontType == GFX_USERFONT_WOFF) {
    lengthHint *= 2;
  } else if (aFontType == GFX_USERFONT_WOFF2) {
    lengthHint *= 3;
  }

  // limit output/expansion to 256MB
  ExpandingMemoryStream output(lengthHint, 1024 * 1024 * 256);

  gfxOTSContext otsContext;
  if (!otsContext.Process(&output, aData, aLength, aMessages)) {
    // Failed to decode/sanitize the font, so discard it.
    aSaneLength = 0;
    return nullptr;
  }

  aSaneLength = output.Tell();
  return static_cast<const uint8_t*>(output.forget());
}

void gfxUserFontEntry::StoreUserFontData(gfxFontEntry* aFontEntry,
                                         bool aPrivate,
                                         const nsACString& aOriginalName,
                                         FallibleTArray<uint8_t>* aMetadata,
                                         uint32_t aMetaOrigLen,
                                         uint8_t aCompression) {
  if (!aFontEntry->mUserFontData) {
    aFontEntry->mUserFontData = MakeUnique<gfxUserFontData>();
  }
  gfxUserFontData* userFontData = aFontEntry->mUserFontData.get();
  userFontData->mSrcIndex = mSrcIndex;
  const gfxFontFaceSrc& src = mSrcList[mSrcIndex];
  switch (src.mSourceType) {
    case gfxFontFaceSrc::eSourceType_Local:
      userFontData->mLocalName = src.mLocalName;
      break;
    case gfxFontFaceSrc::eSourceType_URL:
      userFontData->mURI = src.mURI;
      userFontData->mPrincipal = mPrincipal;
      break;
    case gfxFontFaceSrc::eSourceType_Buffer:
      userFontData->mIsBuffer = true;
      break;
  }
  userFontData->mPrivate = aPrivate;
  userFontData->mFormat = src.mFormatFlags;
  userFontData->mRealName = aOriginalName;
  if (aMetadata) {
    userFontData->mMetadata.SwapElements(*aMetadata);
    userFontData->mMetaOrigLen = aMetaOrigLen;
    userFontData->mCompression = aCompression;
  }
}

size_t gfxUserFontData::SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const {
  return aMallocSizeOf(this) +
         mMetadata.ShallowSizeOfExcludingThis(aMallocSizeOf) +
         mLocalName.SizeOfExcludingThisIfUnshared(aMallocSizeOf) +
         mRealName.SizeOfExcludingThisIfUnshared(aMallocSizeOf);
  // Not counting mURI and mPrincipal, as those will be shared.
}

/*virtual*/
gfxUserFontFamily::~gfxUserFontFamily() {
  // Should not be dropped by stylo
  MOZ_ASSERT(NS_IsMainThread());
}

gfxFontSrcPrincipal* gfxFontFaceSrc::LoadPrincipal(
    const gfxUserFontSet& aFontSet) const {
  MOZ_ASSERT(mSourceType == eSourceType_URL);
  if (mUseOriginPrincipal && mOriginPrincipal) {
    return mOriginPrincipal;
  }
  return aFontSet.GetStandardFontLoadPrincipal();
}

void gfxUserFontEntry::GetFamilyNameAndURIForLogging(nsACString& aFamilyName,
                                                     nsACString& aURI) {
  aFamilyName = mFamilyName;

  aURI.Truncate();
  if (mSrcIndex == mSrcList.Length()) {
    aURI.AppendLiteral("(end of source list)");
  } else {
    if (mSrcList[mSrcIndex].mURI) {
      mSrcList[mSrcIndex].mURI->GetSpec(aURI);
      // If the source URI was very long, elide the middle of it.
      // In principle, the byte-oriented chopping here could leave us
      // with partial UTF-8 characters at the point where we cut it,
      // but it really doesn't matter as this is just for logging.
      const uint32_t kMaxURILengthForLogging = 256;
      // UTF-8 ellipsis, with spaces to allow additional wrap opportunities
      // in the resulting log message
      const char kEllipsis[] = {' ', '\xE2', '\x80', '\xA6', ' '};
      if (aURI.Length() > kMaxURILengthForLogging) {
        aURI.Replace(kMaxURILengthForLogging / 2,
                     aURI.Length() - kMaxURILengthForLogging, kEllipsis,
                     ArrayLength(kEllipsis));
      }
    } else {
      aURI.AppendLiteral("(invalid URI)");
    }
  }
}

struct WOFFHeader {
  AutoSwap_PRUint32 signature;
  AutoSwap_PRUint32 flavor;
  AutoSwap_PRUint32 length;
  AutoSwap_PRUint16 numTables;
  AutoSwap_PRUint16 reserved;
  AutoSwap_PRUint32 totalSfntSize;
  AutoSwap_PRUint16 majorVersion;
  AutoSwap_PRUint16 minorVersion;
  AutoSwap_PRUint32 metaOffset;
  AutoSwap_PRUint32 metaCompLen;
  AutoSwap_PRUint32 metaOrigLen;
  AutoSwap_PRUint32 privOffset;
  AutoSwap_PRUint32 privLen;
};

struct WOFF2Header {
  AutoSwap_PRUint32 signature;
  AutoSwap_PRUint32 flavor;
  AutoSwap_PRUint32 length;
  AutoSwap_PRUint16 numTables;
  AutoSwap_PRUint16 reserved;
  AutoSwap_PRUint32 totalSfntSize;
  AutoSwap_PRUint32 totalCompressedSize;
  AutoSwap_PRUint16 majorVersion;
  AutoSwap_PRUint16 minorVersion;
  AutoSwap_PRUint32 metaOffset;
  AutoSwap_PRUint32 metaCompLen;
  AutoSwap_PRUint32 metaOrigLen;
  AutoSwap_PRUint32 privOffset;
  AutoSwap_PRUint32 privLen;
};

template <typename HeaderT>
void CopyWOFFMetadata(const uint8_t* aFontData, uint32_t aLength,
                      FallibleTArray<uint8_t>* aMetadata,
                      uint32_t* aMetaOrigLen) {
  // This function may be called with arbitrary, unvalidated "font" data
  // from @font-face, so it needs to be careful to bounds-check, etc.,
  // before trying to read anything.
  // This just saves a copy of the compressed data block; it does NOT check
  // that the block can be successfully decompressed, or that it contains
  // well-formed/valid XML metadata.
  if (aLength < sizeof(HeaderT)) {
    return;
  }
  const HeaderT* woff = reinterpret_cast<const HeaderT*>(aFontData);
  uint32_t metaOffset = woff->metaOffset;
  uint32_t metaCompLen = woff->metaCompLen;
  if (!metaOffset || !metaCompLen || !woff->metaOrigLen) {
    return;
  }
  if (metaOffset >= aLength || metaCompLen > aLength - metaOffset) {
    return;
  }
  if (!aMetadata->SetLength(woff->metaCompLen, fallible)) {
    return;
  }
  memcpy(aMetadata->Elements(), aFontData + metaOffset, metaCompLen);
  *aMetaOrigLen = woff->metaOrigLen;
}

void gfxUserFontEntry::LoadNextSrc() {
  NS_ASSERTION(mSrcIndex < mSrcList.Length(),
               "already at the end of the src list for user font");
  NS_ASSERTION((mUserFontLoadState == STATUS_NOT_LOADED ||
                mUserFontLoadState == STATUS_LOAD_PENDING ||
                mUserFontLoadState == STATUS_LOADING) &&
                   mFontDataLoadingState < LOADING_FAILED,
               "attempting to load a font that has either completed or failed");

  if (mUserFontLoadState == STATUS_NOT_LOADED) {
    SetLoadState(STATUS_LOADING);
    mFontDataLoadingState = LOADING_STARTED;
    mUnsupportedFormat = false;
  } else {
    // we were already loading; move to the next source,
    // but don't reset state - if we've already timed out,
    // that counts against the new download
    mSrcIndex++;
  }

  DoLoadNextSrc(false);
}

void gfxUserFontEntry::ContinueLoad() {
  MOZ_ASSERT(mUserFontLoadState == STATUS_LOAD_PENDING);
  MOZ_ASSERT(mSrcList[mSrcIndex].mSourceType ==
             gfxFontFaceSrc::eSourceType_URL);

  SetLoadState(STATUS_LOADING);
  DoLoadNextSrc(true);
  if (LoadState() != STATUS_LOADING) {
    MOZ_ASSERT(mUserFontLoadState != STATUS_LOAD_PENDING,
               "Not in parallel traversal, shouldn't get LOAD_PENDING again");
    // Loading is synchronously finished (loaded from cache or failed). We
    // need to increment the generation so that we flush the style data to
    // use the new loaded font face.
    // Without parallel traversal, we would simply get the right font data
    // after the first call to DoLoadNextSrc() in this case, so we don't need
    // to touch the generation to trigger another restyle.
    // XXX We may want to return synchronously in parallel traversal in those
    // cases as well if possible, so that we don't have an additional restyle.
    // That doesn't work currently because Document::GetDocShell (called from
    // FontFaceSet::CheckFontLoad) dereferences a weak pointer, which is not
    // allowed in parallel traversal.
    IncrementGeneration();
  }
}

static bool IgnorePrincipal(gfxFontSrcURI* aURI) {
  return aURI->InheritsSecurityContext();
}

void gfxUserFontEntry::DoLoadNextSrc(bool aForceAsync) {
  uint32_t numSrc = mSrcList.Length();

  // load each src entry in turn, until a local face is found
  // or a download begins successfully
  while (mSrcIndex < numSrc) {
    gfxFontFaceSrc& currSrc = mSrcList[mSrcIndex];

    // src local ==> lookup and load immediately

    if (currSrc.mSourceType == gfxFontFaceSrc::eSourceType_Local) {
      // Don't look up local fonts if the font whitelist is being used.
      gfxPlatformFontList* pfl = gfxPlatformFontList::PlatformFontList();
      gfxFontEntry* fe =
          pfl && pfl->IsFontFamilyWhitelistActive()
              ? nullptr
              : gfxPlatform::GetPlatform()->LookupLocalFont(
                    currSrc.mLocalName, Weight(), Stretch(), SlantStyle());
      nsTArray<gfxUserFontSet*> fontSets;
      GetUserFontSets(fontSets);
      for (gfxUserFontSet* fontSet : fontSets) {
        // We need to note on each gfxUserFontSet that contains the user
        // font entry that we used a local() rule.
        fontSet->SetLocalRulesUsed();
      }
      if (fe) {
        LOG(("userfonts (%p) [src %d] loaded local: (%s) for (%s) gen: %8.8x\n",
             mFontSet, mSrcIndex, currSrc.mLocalName.get(), mFamilyName.get(),
             uint32_t(mFontSet->mGeneration)));
        fe->mFeatureSettings.AppendElements(mFeatureSettings);
        fe->mVariationSettings.AppendElements(mVariationSettings);
        fe->mLanguageOverride = mLanguageOverride;
        fe->mFamilyName = mFamilyName;
        fe->mRangeFlags = mRangeFlags;
        // For src:local(), we don't care whether the request is from
        // a private window as there's no issue of caching resources;
        // local fonts are just available all the time.
        StoreUserFontData(fe, false, nsCString(), nullptr, 0,
                          gfxUserFontData::kUnknownCompression);
        mPlatformFontEntry = fe;
        SetLoadState(STATUS_LOADED);
        Telemetry::Accumulate(Telemetry::WEBFONT_SRCTYPE,
                              currSrc.mSourceType + 1);
        return;
      } else {
        LOG(("userfonts (%p) [src %d] failed local: (%s) for (%s)\n", mFontSet,
             mSrcIndex, currSrc.mLocalName.get(), mFamilyName.get()));
      }
    }

    // src url ==> start the load process
    else if (currSrc.mSourceType == gfxFontFaceSrc::eSourceType_URL) {
      if (gfxPlatform::GetPlatform()->IsFontFormatSupported(
              currSrc.mFormatFlags)) {
        if (ServoStyleSet* set = ServoStyleSet::Current()) {
          // Only support style worker threads synchronously getting
          // entries from the font cache when it's not a data: URI
          // @font-face that came from UA or user sheets, since we
          // were not able to call IsFontLoadAllowed ahead of time
          // for these entries.
          if (currSrc.mUseOriginPrincipal && IgnorePrincipal(currSrc.mURI)) {
            set->AppendTask(PostTraversalTask::LoadFontEntry(this));
            SetLoadState(STATUS_LOAD_PENDING);
            return;
          }
        }

        // see if we have an existing entry for this source
        gfxFontEntry* fe =
            gfxUserFontSet::UserFontCache::GetFont(currSrc, *this);
        if (fe) {
          mPlatformFontEntry = fe;
          SetLoadState(STATUS_LOADED);
          if (LOG_ENABLED()) {
            LOG(
                ("userfonts (%p) [src %d] "
                 "loaded uri from cache: (%s) for (%s)\n",
                 mFontSet, mSrcIndex, currSrc.mURI->GetSpecOrDefault().get(),
                 mFamilyName.get()));
          }
          return;
        }

        if (ServoStyleSet* set = ServoStyleSet::Current()) {
          // If we need to start a font load and we're on a style
          // worker thread, we have to defer it.
          set->AppendTask(PostTraversalTask::LoadFontEntry(this));
          SetLoadState(STATUS_LOAD_PENDING);
          return;
        }

        // record the principal we should use for the load for use when
        // creating a channel and when caching the loaded entry.
        mPrincipal = currSrc.LoadPrincipal(*mFontSet);

        bool loadDoesntSpin = !aForceAsync && currSrc.mURI->SyncLoadIsOK();

        if (loadDoesntSpin) {
          uint8_t* buffer = nullptr;
          uint32_t bufferLength = 0;

          // sync load font immediately
          nsresult rv =
              mFontSet->SyncLoadFontData(this, &currSrc, buffer, bufferLength);

          if (NS_SUCCEEDED(rv) && LoadPlatformFontSync(buffer, bufferLength)) {
            SetLoadState(STATUS_LOADED);
            Telemetry::Accumulate(Telemetry::WEBFONT_SRCTYPE,
                                  currSrc.mSourceType + 1);
            return;
          } else {
            mFontSet->LogMessage(this, "font load failed",
                                 nsIScriptError::errorFlag, rv);
          }

        } else {
          // otherwise load font async
          nsresult rv = mFontSet->StartLoad(this, &currSrc);
          bool loadOK = NS_SUCCEEDED(rv);

          if (loadOK) {
            if (LOG_ENABLED()) {
              LOG(("userfonts (%p) [src %d] loading uri: (%s) for (%s)\n",
                   mFontSet, mSrcIndex, currSrc.mURI->GetSpecOrDefault().get(),
                   mFamilyName.get()));
            }
            return;
          } else {
            mFontSet->LogMessage(this, "download failed",
                                 nsIScriptError::errorFlag, rv);
          }
        }
      } else {
        // We don't log a warning to the web console yet,
        // as another source may load successfully
        mUnsupportedFormat = true;
      }
    }

    // FontFace buffer ==> load immediately

    else {
      MOZ_ASSERT(currSrc.mSourceType == gfxFontFaceSrc::eSourceType_Buffer);

      uint8_t* buffer = nullptr;
      uint32_t bufferLength = 0;

      // sync load font immediately
      currSrc.mBuffer->TakeBuffer(buffer, bufferLength);
      if (buffer && LoadPlatformFontSync(buffer, bufferLength)) {
        // LoadPlatformFontSync takes ownership of the buffer, so no need
        // to free it here.
        SetLoadState(STATUS_LOADED);
        Telemetry::Accumulate(Telemetry::WEBFONT_SRCTYPE,
                              currSrc.mSourceType + 1);
        return;
      } else {
        mFontSet->LogMessage(this, "font load failed",
                             nsIScriptError::errorFlag);
      }
    }

    mSrcIndex++;
  }

  if (mUnsupportedFormat) {
    mFontSet->LogMessage(this, "no supported format found",
                         nsIScriptError::warningFlag);
  }

  // all src's failed; mark this entry as unusable (so fallback will occur)
  LOG(("userfonts (%p) failed all src for (%s)\n", mFontSet,
       mFamilyName.get()));
  mFontDataLoadingState = LOADING_FAILED;
  SetLoadState(STATUS_FAILED);
}

void gfxUserFontEntry::SetLoadState(UserFontLoadState aLoadState) {
  mUserFontLoadState = aLoadState;
}

MOZ_DEFINE_MALLOC_SIZE_OF_ON_ALLOC(UserFontMallocSizeOfOnAlloc)

bool gfxUserFontEntry::LoadPlatformFontSync(const uint8_t* aFontData,
                                            uint32_t aLength) {
  AUTO_PROFILER_LABEL("gfxUserFontEntry::LoadPlatformFontSync", OTHER);
  NS_ASSERTION((mUserFontLoadState == STATUS_NOT_LOADED ||
                mUserFontLoadState == STATUS_LOAD_PENDING ||
                mUserFontLoadState == STATUS_LOADING) &&
                   mFontDataLoadingState < LOADING_FAILED,
               "attempting to load a font that has either completed or failed");

  // Unwrap/decompress/sanitize or otherwise munge the downloaded data
  // to make a usable sfnt structure.

  // Call the OTS sanitizer; this will also decode WOFF to sfnt
  // if necessary. The original data in aFontData is left unchanged.
  uint32_t saneLen;
  gfxUserFontType fontType;
  nsTArray<nsCString> messages;
  const uint8_t* saneData =
      SanitizeOpenTypeData(aFontData, aLength, saneLen, fontType, messages);

  return LoadPlatformFont(aFontData, aLength, fontType, saneData, saneLen,
                          std::move(messages));
}

void gfxUserFontEntry::StartPlatformFontLoadOnWorkerThread(
    const uint8_t* aFontData, uint32_t aLength,
    nsMainThreadPtrHandle<nsIFontLoadCompleteCallback> aCallback) {
  MOZ_ASSERT(sFontLoadingThread);
  MOZ_ASSERT(sFontLoadingThread->IsOnCurrentThread());

  uint32_t saneLen;
  gfxUserFontType fontType;
  nsTArray<nsCString> messages;
  const uint8_t* saneData =
      SanitizeOpenTypeData(aFontData, aLength, saneLen, fontType, messages);

  nsCOMPtr<nsIRunnable> event =
      NewRunnableMethod<const uint8_t*, uint32_t, gfxUserFontType,
                        const uint8_t*, uint32_t, nsTArray<nsCString>&&,
                        nsMainThreadPtrHandle<nsIFontLoadCompleteCallback>>(
          "gfxUserFontEntry::ContinuePlatformFontLoadOnMainThread", this,
          &gfxUserFontEntry::ContinuePlatformFontLoadOnMainThread, aFontData,
          aLength, fontType, saneData, saneLen, std::move(messages), aCallback);
  NS_DispatchToMainThread(event.forget());
}

bool gfxUserFontEntry::LoadPlatformFont(const uint8_t* aOriginalFontData,
                                        uint32_t aOriginalLength,
                                        gfxUserFontType aFontType,
                                        const uint8_t* aSanitizedFontData,
                                        uint32_t aSanitizedLength,
                                        nsTArray<nsCString>&& aMessages) {
  MOZ_ASSERT(NS_IsMainThread());

  for (const auto& msg : aMessages) {
    mFontSet->LogMessage(this, msg.get());
  }

  if (!aSanitizedFontData) {
    mFontSet->LogMessage(this, "rejected by sanitizer");
  } else {
    // Check whether aSanitizedFontData is a known OpenType format; it might be
    // a TrueType Collection, which OTS would accept but we don't yet
    // know how to handle. If so, discard.
    if (gfxFontUtils::DetermineFontDataType(
            aSanitizedFontData, aSanitizedLength) != GFX_USERFONT_OPENTYPE) {
      mFontSet->LogMessage(this, "not a supported OpenType format");
      free((void*)aSanitizedFontData);
      aSanitizedFontData = nullptr;
    }
  }

  // Because platform font activation code may replace the name table
  // in the font with a synthetic one, we save the original name so that
  // it can be reported via the InspectorUtils API.
  nsAutoCString originalFullName;

  gfxFontEntry* fe = nullptr;
  uint32_t fontCompressionRatio = 0;
  size_t computedSize = 0;

  if (aSanitizedFontData) {
    if (aSanitizedLength) {
      fontCompressionRatio =
          uint32_t(100.0 * aOriginalLength / aSanitizedLength + 0.5);
      if (aFontType == GFX_USERFONT_WOFF || aFontType == GFX_USERFONT_WOFF2) {
        Telemetry::Accumulate(aFontType == GFX_USERFONT_WOFF
                                  ? Telemetry::WEBFONT_COMPRESSION_WOFF
                                  : Telemetry::WEBFONT_COMPRESSION_WOFF2,
                              fontCompressionRatio);
      }
    }

    // The sanitizer ensures that we have a valid sfnt and a usable
    // name table, so this should never fail unless we're out of
    // memory, and GetFullNameFromSFNT is not directly exposed to
    // arbitrary/malicious data from the web.
    gfxFontUtils::GetFullNameFromSFNT(aSanitizedFontData, aSanitizedLength,
                                      originalFullName);

    // Record size for memory reporting purposes. We measure this now
    // because by the time we potentially want to collect reports, this
    // data block may have been handed off to opaque OS font APIs that
    // don't allow us to retrieve or measure it directly.
    // The *OnAlloc function will also tell DMD about this block, as the
    // OS font code may hold on to it for an extended period.
    computedSize = UserFontMallocSizeOfOnAlloc(aSanitizedFontData);

    // Here ownership of aSanitizedFontData is passed to the platform,
    // which will delete it when no longer required
    fe = gfxPlatform::GetPlatform()->MakePlatformFont(
        mName, Weight(), Stretch(), SlantStyle(), aSanitizedFontData,
        aSanitizedLength);
    if (!fe) {
      mFontSet->LogMessage(this, "not usable by platform");
    }
  }

  if (fe) {
    fe->mComputedSizeOfUserFont = computedSize;

    // Save a copy of the metadata block (if present) for InspectorUtils
    // to use if required. Ownership of the metadata block will be passed
    // to the gfxUserFontData record below.
    FallibleTArray<uint8_t> metadata;
    uint32_t metaOrigLen = 0;
    uint8_t compression = gfxUserFontData::kUnknownCompression;
    if (aFontType == GFX_USERFONT_WOFF) {
      CopyWOFFMetadata<WOFFHeader>(aOriginalFontData, aOriginalLength,
                                   &metadata, &metaOrigLen);
      compression = gfxUserFontData::kZlibCompression;
    } else if (aFontType == GFX_USERFONT_WOFF2) {
      CopyWOFFMetadata<WOFF2Header>(aOriginalFontData, aOriginalLength,
                                    &metadata, &metaOrigLen);
      compression = gfxUserFontData::kBrotliCompression;
    }

    // copy OpenType feature/language settings from the userfont entry to the
    // newly-created font entry
    fe->mFeatureSettings.AppendElements(mFeatureSettings);
    fe->mVariationSettings.AppendElements(mVariationSettings);
    fe->mLanguageOverride = mLanguageOverride;
    fe->mFamilyName = mFamilyName;
    fe->mRangeFlags = mRangeFlags;
    StoreUserFontData(fe, mFontSet->GetPrivateBrowsing(), originalFullName,
                      &metadata, metaOrigLen, compression);
    if (LOG_ENABLED()) {
      LOG((
          "userfonts (%p) [src %d] loaded uri: (%s) for (%s) "
          "(%p) gen: %8.8x compress: %d%%\n",
          mFontSet, mSrcIndex,
          mSrcList[mSrcIndex].mURI->GetSpecOrDefault().get(), mFamilyName.get(),
          this, uint32_t(mFontSet->mGeneration), fontCompressionRatio));
    }
    mPlatformFontEntry = fe;
    SetLoadState(STATUS_LOADED);
    gfxUserFontSet::UserFontCache::CacheFont(fe);
  } else {
    if (LOG_ENABLED()) {
      LOG(
          ("userfonts (%p) [src %d] failed uri: (%s) for (%s)"
           " error making platform font\n",
           mFontSet, mSrcIndex,
           mSrcList[mSrcIndex].mURI->GetSpecOrDefault().get(),
           mFamilyName.get()));
    }
  }

  // The downloaded data can now be discarded; the font entry is using the
  // sanitized copy
  free((void*)aOriginalFontData);

  return fe != nullptr;
}

void gfxUserFontEntry::Load() {
  if (mUserFontLoadState == STATUS_NOT_LOADED) {
    LoadNextSrc();
  }
}

void gfxUserFontEntry::IncrementGeneration() {
  nsTArray<gfxUserFontSet*> fontSets;
  GetUserFontSets(fontSets);
  for (gfxUserFontSet* fontSet : fontSets) {
    fontSet->IncrementGeneration();
  }
}

// This is called when a font download finishes.
// Ownership of aFontData passes in here, and the font set must
// ensure that it is eventually deleted via free().
void gfxUserFontEntry::FontDataDownloadComplete(
    const uint8_t* aFontData, uint32_t aLength, nsresult aDownloadStatus,
    nsIFontLoadCompleteCallback* aCallback) {
  MOZ_ASSERT(NS_IsMainThread());

  // forget about the loader, as we no longer potentially need to cancel it
  // if the entry is obsoleted
  mLoader = nullptr;

  // download successful, make platform font using font data
  if (NS_SUCCEEDED(aDownloadStatus) &&
      mFontDataLoadingState != LOADING_TIMED_OUT) {
    if (StaticPrefs::gfx_downloadable_fonts_sanitize_omt()) {
      LoadPlatformFontAsync(aFontData, aLength, aCallback);
    } else {
      bool loaded = LoadPlatformFontSync(aFontData, aLength);
      aFontData = nullptr;
      if (loaded) {
        IncrementGeneration();
        aCallback->FontLoadComplete();
      } else {
        FontLoadFailed(aCallback);
      }
    }
    return;
  }

  // download failed
  mFontSet->LogMessage(
      this,
      (mFontDataLoadingState != LOADING_TIMED_OUT ? "download failed"
                                                  : "download timed out"),
      nsIScriptError::errorFlag, aDownloadStatus);

  if (aFontData) {
    free((void*)aFontData);
  }

  FontLoadFailed(aCallback);
}

void gfxUserFontEntry::LoadPlatformFontAsync(
    const uint8_t* aFontData, uint32_t aLength,
    nsIFontLoadCompleteCallback* aCallback) {
  // Ensure the font loading thread is available.
  if (!sFontLoadingThread) {
    sFontLoadingThread =
        new LazyIdleThread(5000, NS_LITERAL_CSTRING("FontLoader"));
  }

  nsMainThreadPtrHandle<nsIFontLoadCompleteCallback> cb(
      new nsMainThreadPtrHolder<nsIFontLoadCompleteCallback>("FontLoader",
                                                             aCallback));

  // Do the OpenType sanitization over on the font loading thread.  Once that is
  // complete, we'll continue in ContinuePlatformFontLoadOnMainThread.
  //
  // We hold a strong reference to the gfxUserFontSet during this work, since
  // the document might be closed while we are OMT, and release it at the end
  // of ContinuePlatformFontLoadOnMainThread.

  mFontSet->AddRef();

  nsCOMPtr<nsIRunnable> event =
      NewRunnableMethod<const uint8_t*, uint32_t,
                        nsMainThreadPtrHandle<nsIFontLoadCompleteCallback>>(
          "gfxUserFontEntry::StartPlatformFontLoadOnWorkerThread", this,
          &gfxUserFontEntry::StartPlatformFontLoadOnWorkerThread, aFontData,
          aLength, cb);
  MOZ_ALWAYS_SUCCEEDS(
      sFontLoadingThread->Dispatch(event.forget(), NS_DISPATCH_NORMAL));
}

void gfxUserFontEntry::ContinuePlatformFontLoadOnMainThread(
    const uint8_t* aOriginalFontData, uint32_t aOriginalLength,
    gfxUserFontType aFontType, const uint8_t* aSanitizedFontData,
    uint32_t aSanitizedLength, nsTArray<nsCString>&& aMessages,
    nsMainThreadPtrHandle<nsIFontLoadCompleteCallback> aCallback) {
  MOZ_ASSERT(NS_IsMainThread());

  bool loaded = LoadPlatformFont(aOriginalFontData, aOriginalLength, aFontType,
                                 aSanitizedFontData, aSanitizedLength,
                                 std::move(aMessages));
  aOriginalFontData = nullptr;
  aSanitizedFontData = nullptr;

  if (loaded) {
    IncrementGeneration();
    aCallback->FontLoadComplete();
  } else {
    FontLoadFailed(aCallback);
  }

  mFontSet->Release();  // for the AddRef in LoadPlatformFontAsync
}

void gfxUserFontEntry::FontLoadFailed(nsIFontLoadCompleteCallback* aCallback) {
  MOZ_ASSERT(NS_IsMainThread());

  // Error occurred.  Make sure the FontFace's promise is rejected if the
  // load timed out, or else load the next src.
  if (mFontDataLoadingState == LOADING_TIMED_OUT) {
    mFontDataLoadingState = LOADING_FAILED;
    SetLoadState(STATUS_FAILED);
  } else {
    LoadNextSrc();
  }

  // We ignore the status returned by LoadNext();
  // even if loading failed, we need to bump the font-set generation
  // and return true in order to trigger reflow, so that fallback
  // will be used where the text was "masked" by the pending download
  IncrementGeneration();
  aCallback->FontLoadComplete();
}

void gfxUserFontEntry::GetUserFontSets(nsTArray<gfxUserFontSet*>& aResult) {
  aResult.Clear();
  aResult.AppendElement(mFontSet);
}

gfxUserFontSet::gfxUserFontSet()
    : mFontFamilies(4),
      mRebuildGeneration(0),
      mLocalRulesUsed(false),
      mRebuildLocalRules(false),
      mDownloadCount(0),
      mDownloadSize(0) {
  IncrementGeneration(true);
  gfxPlatformFontList* fp = gfxPlatformFontList::PlatformFontList();
  if (fp) {
    fp->AddUserFontSet(this);
  }
}

gfxUserFontSet::~gfxUserFontSet() {
  gfxPlatformFontList* fp = gfxPlatformFontList::PlatformFontList();
  if (fp) {
    fp->RemoveUserFontSet(this);
  }
}

already_AddRefed<gfxUserFontEntry> gfxUserFontSet::FindOrCreateUserFontEntry(
    const nsACString& aFamilyName,
    const nsTArray<gfxFontFaceSrc>& aFontFaceSrcList, WeightRange aWeight,
    StretchRange aStretch, SlantStyleRange aStyle,
    const nsTArray<gfxFontFeature>& aFeatureSettings,
    const nsTArray<gfxFontVariation>& aVariationSettings,
    uint32_t aLanguageOverride, gfxCharacterMap* aUnicodeRanges,
    StyleFontDisplay aFontDisplay, RangeFlags aRangeFlags) {
  RefPtr<gfxUserFontEntry> entry;

  // If there's already a userfont entry in the family whose descriptors all
  // match, we can just move it to the end of the list instead of adding a new
  // face that will always "shadow" the old one.
  // Note that we can't do this for platform font entries, even if the
  // style descriptors match, as they might have had a different source list,
  // but we no longer have the old source list available to check.
  gfxUserFontFamily* family = LookupFamily(aFamilyName);
  if (family) {
    entry = FindExistingUserFontEntry(
        family, aFontFaceSrcList, aWeight, aStretch, aStyle, aFeatureSettings,
        aVariationSettings, aLanguageOverride, aUnicodeRanges, aFontDisplay,
        aRangeFlags);
  }

  if (!entry) {
    entry = CreateUserFontEntry(aFontFaceSrcList, aWeight, aStretch, aStyle,
                                aFeatureSettings, aVariationSettings,
                                aLanguageOverride, aUnicodeRanges, aFontDisplay,
                                aRangeFlags);
    entry->mFamilyName = aFamilyName;
  }

  return entry.forget();
}

gfxUserFontEntry* gfxUserFontSet::FindExistingUserFontEntry(
    gfxUserFontFamily* aFamily,
    const nsTArray<gfxFontFaceSrc>& aFontFaceSrcList, WeightRange aWeight,
    StretchRange aStretch, SlantStyleRange aStyle,
    const nsTArray<gfxFontFeature>& aFeatureSettings,
    const nsTArray<gfxFontVariation>& aVariationSettings,
    uint32_t aLanguageOverride, gfxCharacterMap* aUnicodeRanges,
    StyleFontDisplay aFontDisplay, RangeFlags aRangeFlags) {
  nsTArray<RefPtr<gfxFontEntry>>& fontList = aFamily->GetFontList();

  for (size_t i = 0, count = fontList.Length(); i < count; i++) {
    if (!fontList[i]->mIsUserFontContainer) {
      continue;
    }

    gfxUserFontEntry* existingUserFontEntry =
        static_cast<gfxUserFontEntry*>(fontList[i].get());
    if (!existingUserFontEntry->Matches(
            aFontFaceSrcList, aWeight, aStretch, aStyle, aFeatureSettings,
            aVariationSettings, aLanguageOverride, aUnicodeRanges, aFontDisplay,
            aRangeFlags)) {
      continue;
    }

    return existingUserFontEntry;
  }

  return nullptr;
}

void gfxUserFontSet::AddUserFontEntry(const nsCString& aFamilyName,
                                      gfxUserFontEntry* aUserFontEntry) {
  gfxUserFontFamily* family = GetFamily(aFamilyName);
  family->AddFontEntry(aUserFontEntry);

  if (LOG_ENABLED()) {
    nsAutoCString weightString;
    aUserFontEntry->Weight().ToString(weightString);
    nsAutoCString stretchString;
    aUserFontEntry->Stretch().ToString(stretchString);
    LOG(
        ("userfonts (%p) added to \"%s\" (%p) style: %s weight: %s "
         "stretch: %s display: %d",
         this, aFamilyName.get(), aUserFontEntry,
         (aUserFontEntry->IsItalic()
              ? "italic"
              : (aUserFontEntry->IsOblique() ? "oblique" : "normal")),
         weightString.get(), stretchString.get(),
         static_cast<int>(aUserFontEntry->GetFontDisplay())));
  }
}

void gfxUserFontSet::IncrementGeneration(bool aIsRebuild) {
  // add one, increment again if zero
  ++sFontSetGeneration;
  if (sFontSetGeneration == 0) ++sFontSetGeneration;
  mGeneration = sFontSetGeneration;
  if (aIsRebuild) {
    mRebuildGeneration = mGeneration;
  }
}

void gfxUserFontSet::RebuildLocalRules() {
  if (mLocalRulesUsed) {
    mRebuildLocalRules = true;
    DoRebuildUserFontSet();
  }
}

gfxUserFontFamily* gfxUserFontSet::LookupFamily(
    const nsACString& aFamilyName) const {
  nsAutoCString key(aFamilyName);
  ToLowerCase(key);

  return mFontFamilies.GetWeak(key);
}

gfxUserFontFamily* gfxUserFontSet::GetFamily(const nsACString& aFamilyName) {
  nsAutoCString key(aFamilyName);
  ToLowerCase(key);

  gfxUserFontFamily* family = mFontFamilies.GetWeak(key);
  if (!family) {
    family = new gfxUserFontFamily(aFamilyName);
    mFontFamilies.Put(key, family);
  }
  return family;
}

void gfxUserFontSet::ForgetLocalFaces() {
  for (auto iter = mFontFamilies.Iter(); !iter.Done(); iter.Next()) {
    const auto fam = iter.Data();
    const auto& fonts = fam->GetFontList();
    for (const auto& f : fonts) {
      auto ufe = static_cast<gfxUserFontEntry*>(f.get());
      // If the user font entry has loaded an entry using src:local(),
      // discard it as no longer valid, and reset the load state so that
      // the load will be re-done based on the updated font list.
      if (ufe->GetPlatformFontEntry() &&
          ufe->GetPlatformFontEntry()->IsLocalUserFont()) {
        ufe->mPlatformFontEntry = nullptr;
        ufe->LoadCanceled();
      }
    }
  }
}

///////////////////////////////////////////////////////////////////////////////
// gfxUserFontSet::UserFontCache - re-use platform font entries for user fonts
// across pages/fontsets rather than instantiating new platform fonts.
//
// Entries are added to this cache when a platform font is instantiated from
// downloaded data, and removed when the platform font entry is destroyed.
// We don't need to use a timed expiration scheme here because the gfxFontEntry
// for a downloaded font will be kept alive by its corresponding gfxFont
// instance(s) until they are deleted, and *that* happens using an expiration
// tracker (gfxFontCache). The result is that the downloaded font instances
// recorded here will persist between pages and can get reused (provided the
// source URI and principal match, of course).
///////////////////////////////////////////////////////////////////////////////

nsTHashtable<gfxUserFontSet::UserFontCache::Entry>*
    gfxUserFontSet::UserFontCache::sUserFonts = nullptr;

NS_IMPL_ISUPPORTS(gfxUserFontSet::UserFontCache::Flusher, nsIObserver)

NS_IMETHODIMP
gfxUserFontSet::UserFontCache::Flusher::Observe(nsISupports* aSubject,
                                                const char* aTopic,
                                                const char16_t* aData) {
  if (!sUserFonts) {
    return NS_OK;
  }

  if (!strcmp(aTopic, "cacheservice:empty-cache")) {
    for (auto i = sUserFonts->Iter(); !i.Done(); i.Next()) {
      i.Remove();
    }
  } else if (!strcmp(aTopic, "last-pb-context-exited")) {
    for (auto i = sUserFonts->Iter(); !i.Done(); i.Next()) {
      if (i.Get()->IsPrivate()) {
        i.Remove();
      }
    }
  } else if (!strcmp(aTopic, "xpcom-shutdown")) {
    for (auto i = sUserFonts->Iter(); !i.Done(); i.Next()) {
      i.Get()->GetFontEntry()->DisconnectSVG();
    }
  } else {
    MOZ_ASSERT_UNREACHABLE("unexpected topic");
  }

  return NS_OK;
}

bool gfxUserFontSet::UserFontCache::Entry::KeyEquals(
    const KeyTypePointer aKey) const {
  const gfxFontEntry* fe = aKey->mFontEntry;

  if (!mURI->Equals(aKey->mURI)) {
    return false;
  }

  // For data: URIs, we don't care about the principal; otherwise, check it.
  if (!IgnorePrincipal(mURI)) {
    NS_ASSERTION(mPrincipal && aKey->mPrincipal,
                 "only data: URIs are allowed to omit the principal");
    if (!mPrincipal->Equals(aKey->mPrincipal)) {
      return false;
    }
  }

  if (mPrivate != aKey->mPrivate) {
    return false;
  }

  if (mFontEntry->SlantStyle() != fe->SlantStyle() ||
      mFontEntry->Weight() != fe->Weight() ||
      mFontEntry->Stretch() != fe->Stretch() ||
      mFontEntry->mFeatureSettings != fe->mFeatureSettings ||
      mFontEntry->mVariationSettings != fe->mVariationSettings ||
      mFontEntry->mLanguageOverride != fe->mLanguageOverride ||
      mFontEntry->mFamilyName != fe->mFamilyName) {
    return false;
  }

  return true;
}

void gfxUserFontSet::UserFontCache::CacheFont(gfxFontEntry* aFontEntry) {
  NS_ASSERTION(aFontEntry->mFamilyName.Length() != 0,
               "caching a font associated with no family yet");

  // if caching is disabled, simply return
  if (Preferences::GetBool("gfx.downloadable_fonts.disable_cache")) {
    return;
  }

  gfxUserFontData* data = aFontEntry->mUserFontData.get();
  if (data->mIsBuffer) {
#ifdef DEBUG_USERFONT_CACHE
    printf("userfontcache skipped fontentry with buffer source: %p\n",
           aFontEntry);
#endif
    return;
  }

  if (!sUserFonts) {
    sUserFonts = new nsTHashtable<Entry>;

    nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
    if (obs) {
      Flusher* flusher = new Flusher;
      obs->AddObserver(flusher, "cacheservice:empty-cache", false);
      obs->AddObserver(flusher, "last-pb-context-exited", false);
      obs->AddObserver(flusher, "xpcom-shutdown", false);
    }

    // Create and register a memory reporter for sUserFonts.
    // This reporter is never unregistered, but that's OK because
    // the reporter checks whether sUserFonts is null, so it would
    // be safe to call even after UserFontCache::Shutdown has deleted
    // the cache.
    RegisterStrongMemoryReporter(new MemoryReporter());
  }

  // For data: URIs, the principal is ignored; anyone who has the same
  // data: URI is able to load it and get an equivalent font.
  // Otherwise, the principal is used as part of the cache key.
  gfxFontSrcPrincipal* principal;
  if (IgnorePrincipal(data->mURI)) {
    principal = nullptr;
  } else {
    principal = data->mPrincipal;
  }
  sUserFonts->PutEntry(Key(data->mURI, principal, aFontEntry, data->mPrivate));

#ifdef DEBUG_USERFONT_CACHE
  printf("userfontcache added fontentry: %p\n", aFontEntry);
  Dump();
#endif
}

void gfxUserFontSet::UserFontCache::ForgetFont(gfxFontEntry* aFontEntry) {
  if (!sUserFonts) {
    // if we've already deleted the cache (i.e. during shutdown),
    // just ignore this
    return;
  }

  // We can't simply use RemoveEntry here because it's possible the principal
  // may have changed since the font was cached, in which case the lookup
  // would no longer find the entry (bug 838105).
  for (auto i = sUserFonts->Iter(); !i.Done(); i.Next()) {
    if (i.Get()->GetFontEntry() == aFontEntry) {
      i.Remove();
    }
  }

#ifdef DEBUG_USERFONT_CACHE
  printf("userfontcache removed fontentry: %p\n", aFontEntry);
  Dump();
#endif
}

gfxFontEntry* gfxUserFontSet::UserFontCache::GetFont(
    const gfxFontFaceSrc& aSrc, const gfxUserFontEntry& aUserFontEntry) {
  if (!sUserFonts || aUserFontEntry.mFontSet->BypassCache() ||
      Preferences::GetBool("gfx.downloadable_fonts.disable_cache")) {
    return nullptr;
  }

  // Ignore principal when looking up a data: URI.
  gfxFontSrcPrincipal* principal =
      IgnorePrincipal(aSrc.mURI) ? nullptr
                                 : aSrc.LoadPrincipal(*aUserFontEntry.mFontSet);

  Entry* entry = sUserFonts->GetEntry(
      Key(aSrc.mURI, principal, const_cast<gfxUserFontEntry*>(&aUserFontEntry),
          aUserFontEntry.mFontSet->GetPrivateBrowsing()));
  if (!entry) {
    return nullptr;
  }

  // We have to perform another content policy check here to prevent
  // cache poisoning. E.g. a.com loads a font into the cache but
  // b.com has a CSP not allowing any fonts to be loaded.
  if (!aUserFontEntry.mFontSet->IsFontLoadAllowed(aSrc)) {
    return nullptr;
  }

  return entry->GetFontEntry();
}

void gfxUserFontSet::UserFontCache::Shutdown() {
  if (sUserFonts) {
    delete sUserFonts;
    sUserFonts = nullptr;
  }
}

MOZ_DEFINE_MALLOC_SIZE_OF(UserFontsMallocSizeOf)

void gfxUserFontSet::UserFontCache::Entry::ReportMemory(
    nsIHandleReportCallback* aHandleReport, nsISupports* aData,
    bool aAnonymize) {
  MOZ_ASSERT(mFontEntry);
  nsAutoCString path("explicit/gfx/user-fonts/font(");

  if (aAnonymize) {
    path.AppendPrintf("<anonymized-%p>", this);
  } else {
    path.AppendPrintf("family=%s", mFontEntry->mFamilyName.get());
    if (mURI) {
      nsCString spec = mURI->GetSpecOrDefault();
      spec.ReplaceChar('/', '\\');
      // Some fonts are loaded using horrendously-long data: URIs;
      // truncate those before reporting them.
      if (mURI->get()->SchemeIs("data") && spec.Length() > 255) {
        spec.Truncate(252);
        spec.AppendLiteral("...");
      }
      path.AppendPrintf(", url=%s", spec.get());
    }
    if (mPrincipal) {
      nsCOMPtr<nsIURI> uri;
      mPrincipal->get()->GetURI(getter_AddRefs(uri));
      if (uri) {
        nsCString spec = uri->GetSpecOrDefault();
        if (!spec.IsEmpty()) {
          // Include a clue as to who loaded this resource. (Note
          // that because of font entry sharing, other pages may now
          // be using this resource, and the original page may not
          // even be loaded any longer.)
          spec.ReplaceChar('/', '\\');
          path.AppendPrintf(", principal=%s", spec.get());
        }
      }
    }
  }
  path.Append(')');

  aHandleReport->Callback(
      EmptyCString(), path, nsIMemoryReporter::KIND_HEAP,
      nsIMemoryReporter::UNITS_BYTES,
      mFontEntry->ComputedSizeOfExcludingThis(UserFontsMallocSizeOf),
      NS_LITERAL_CSTRING("Memory used by @font-face resource."), aData);
}

NS_IMPL_ISUPPORTS(gfxUserFontSet::UserFontCache::MemoryReporter,
                  nsIMemoryReporter)

NS_IMETHODIMP
gfxUserFontSet::UserFontCache::MemoryReporter::CollectReports(
    nsIHandleReportCallback* aHandleReport, nsISupports* aData,
    bool aAnonymize) {
  if (!sUserFonts) {
    return NS_OK;
  }

  for (auto it = sUserFonts->Iter(); !it.Done(); it.Next()) {
    it.Get()->ReportMemory(aHandleReport, aData, aAnonymize);
  }

  MOZ_COLLECT_REPORT(
      "explicit/gfx/user-fonts/cache-overhead", KIND_HEAP, UNITS_BYTES,
      sUserFonts->ShallowSizeOfIncludingThis(UserFontsMallocSizeOf),
      "Memory used by the @font-face cache, not counting the actual font "
      "resources.");

  return NS_OK;
}

StaticRefPtr<LazyIdleThread> gfxUserFontEntry::sFontLoadingThread;

#ifdef DEBUG_USERFONT_CACHE

void gfxUserFontSet::UserFontCache::Entry::Dump() {
  nsresult rv;

  nsAutoCString principalURISpec("(null)");
  bool setDomain = false;

  if (mPrincipal) {
    nsCOMPtr<nsIURI> principalURI;
    rv = mPrincipal->get()->GetURI(getter_AddRefs(principalURI));
    if (NS_SUCCEEDED(rv)) {
      principalURI->GetSpec(principalURISpec);
    }

    nsCOMPtr<nsIURI> domainURI;
    mPrincipal->get()->GetDomain(getter_AddRefs(domainURI));
    if (domainURI) {
      setDomain = true;
    }
  }

  NS_ASSERTION(mURI, "null URI in userfont cache entry");

  printf(
      "userfontcache fontEntry: %p fonturihash: %8.8x "
      "family: %s domainset: %s principal: [%s]\n",
      mFontEntry, mURI->Hash(), mFontEntry->FamilyName().get(),
      setDomain ? "true" : "false", principalURISpec.get());
}

void gfxUserFontSet::UserFontCache::Dump() {
  if (!sUserFonts) {
    return;
  }

  printf("userfontcache dump count: %d ========\n", sUserFonts->Count());
  for (auto it = sUserFonts->Iter(); !it.Done(); it.Next()) {
    it.Get()->Dump();
  }
  printf("userfontcache dump ==================\n");
}

#endif

#undef LOG
#undef LOG_ENABLED