gfxFontUtils.cpp 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790
  1. /* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. #include "mozilla/ArrayUtils.h"
  6. #include "mozilla/BinarySearch.h"
  7. #include "gfxFontUtils.h"
  8. #include "nsServiceManagerUtils.h"
  9. #include "mozilla/dom/EncodingUtils.h"
  10. #include "mozilla/Preferences.h"
  11. #include "mozilla/Services.h"
  12. #include "mozilla/BinarySearch.h"
  13. #include "mozilla/Sprintf.h"
  14. #include "nsCOMPtr.h"
  15. #include "nsIUUIDGenerator.h"
  16. #include "nsIUnicodeDecoder.h"
  17. #include "harfbuzz/hb.h"
  18. #include "plbase64.h"
  19. #include "mozilla/Logging.h"
  20. #define LOG(log, args) MOZ_LOG(gfxPlatform::GetLog(log), \
  21. LogLevel::Debug, args)
  22. #define UNICODE_BMP_LIMIT 0x10000
  23. using namespace mozilla;
  24. #pragma pack(1)
  25. typedef struct {
  26. AutoSwap_PRUint16 format;
  27. AutoSwap_PRUint16 reserved;
  28. AutoSwap_PRUint32 length;
  29. AutoSwap_PRUint32 language;
  30. AutoSwap_PRUint32 startCharCode;
  31. AutoSwap_PRUint32 numChars;
  32. } Format10CmapHeader;
  33. typedef struct {
  34. AutoSwap_PRUint16 format;
  35. AutoSwap_PRUint16 reserved;
  36. AutoSwap_PRUint32 length;
  37. AutoSwap_PRUint32 language;
  38. AutoSwap_PRUint32 numGroups;
  39. } Format12CmapHeader;
  40. typedef struct {
  41. AutoSwap_PRUint32 startCharCode;
  42. AutoSwap_PRUint32 endCharCode;
  43. AutoSwap_PRUint32 startGlyphId;
  44. } Format12Group;
  45. #pragma pack()
  46. void
  47. gfxSparseBitSet::Dump(const char* aPrefix, eGfxLog aWhichLog) const
  48. {
  49. NS_ASSERTION(mBlocks.DebugGetHeader(), "mHdr is null, this is bad");
  50. uint32_t b, numBlocks = mBlocks.Length();
  51. for (b = 0; b < numBlocks; b++) {
  52. Block *block = mBlocks[b].get();
  53. if (!block) {
  54. continue;
  55. }
  56. const int BUFSIZE = 256;
  57. char outStr[BUFSIZE];
  58. int index = 0;
  59. index += snprintf(&outStr[index], BUFSIZE - index, "%s u+%6.6x [", aPrefix, (b << BLOCK_INDEX_SHIFT));
  60. for (int i = 0; i < 32; i += 4) {
  61. for (int j = i; j < i + 4; j++) {
  62. uint8_t bits = block->mBits[j];
  63. uint8_t flip1 = ((bits & 0xaa) >> 1) | ((bits & 0x55) << 1);
  64. uint8_t flip2 = ((flip1 & 0xcc) >> 2) | ((flip1 & 0x33) << 2);
  65. uint8_t flipped = ((flip2 & 0xf0) >> 4) | ((flip2 & 0x0f) << 4);
  66. index += snprintf(&outStr[index], BUFSIZE - index, "%2.2x", flipped);
  67. }
  68. if (i + 4 != 32) index += snprintf(&outStr[index], BUFSIZE - index, " ");
  69. }
  70. index += snprintf(&outStr[index], BUFSIZE - index, "]");
  71. LOG(aWhichLog, ("%s", outStr));
  72. }
  73. }
  74. nsresult
  75. gfxFontUtils::ReadCMAPTableFormat10(const uint8_t *aBuf, uint32_t aLength,
  76. gfxSparseBitSet& aCharacterMap)
  77. {
  78. // Ensure table is large enough that we can safely read the header
  79. NS_ENSURE_TRUE(aLength >= sizeof(Format10CmapHeader),
  80. NS_ERROR_GFX_CMAP_MALFORMED);
  81. // Sanity-check header fields
  82. const Format10CmapHeader *cmap10 =
  83. reinterpret_cast<const Format10CmapHeader*>(aBuf);
  84. NS_ENSURE_TRUE(uint16_t(cmap10->format) == 10,
  85. NS_ERROR_GFX_CMAP_MALFORMED);
  86. NS_ENSURE_TRUE(uint16_t(cmap10->reserved) == 0,
  87. NS_ERROR_GFX_CMAP_MALFORMED);
  88. uint32_t tablelen = cmap10->length;
  89. NS_ENSURE_TRUE(tablelen >= sizeof(Format10CmapHeader) &&
  90. tablelen <= aLength, NS_ERROR_GFX_CMAP_MALFORMED);
  91. NS_ENSURE_TRUE(cmap10->language == 0, NS_ERROR_GFX_CMAP_MALFORMED);
  92. uint32_t numChars = cmap10->numChars;
  93. NS_ENSURE_TRUE(tablelen == sizeof(Format10CmapHeader) +
  94. numChars * sizeof(uint16_t), NS_ERROR_GFX_CMAP_MALFORMED);
  95. uint32_t charCode = cmap10->startCharCode;
  96. NS_ENSURE_TRUE(charCode <= CMAP_MAX_CODEPOINT &&
  97. charCode + numChars <= CMAP_MAX_CODEPOINT,
  98. NS_ERROR_GFX_CMAP_MALFORMED);
  99. // glyphs[] array immediately follows the subtable header
  100. const AutoSwap_PRUint16 *glyphs =
  101. reinterpret_cast<const AutoSwap_PRUint16 *>(cmap10 + 1);
  102. for (uint32_t i = 0; i < numChars; ++i) {
  103. if (uint16_t(*glyphs) != 0) {
  104. aCharacterMap.set(charCode);
  105. }
  106. ++charCode;
  107. ++glyphs;
  108. }
  109. aCharacterMap.Compact();
  110. return NS_OK;
  111. }
  112. nsresult
  113. gfxFontUtils::ReadCMAPTableFormat12(const uint8_t *aBuf, uint32_t aLength,
  114. gfxSparseBitSet& aCharacterMap)
  115. {
  116. // Ensure table is large enough that we can safely read the header
  117. NS_ENSURE_TRUE(aLength >= sizeof(Format12CmapHeader),
  118. NS_ERROR_GFX_CMAP_MALFORMED);
  119. // Sanity-check header fields
  120. const Format12CmapHeader *cmap12 =
  121. reinterpret_cast<const Format12CmapHeader*>(aBuf);
  122. NS_ENSURE_TRUE(uint16_t(cmap12->format) == 12,
  123. NS_ERROR_GFX_CMAP_MALFORMED);
  124. NS_ENSURE_TRUE(uint16_t(cmap12->reserved) == 0,
  125. NS_ERROR_GFX_CMAP_MALFORMED);
  126. uint32_t tablelen = cmap12->length;
  127. NS_ENSURE_TRUE(tablelen >= sizeof(Format12CmapHeader) &&
  128. tablelen <= aLength, NS_ERROR_GFX_CMAP_MALFORMED);
  129. NS_ENSURE_TRUE(cmap12->language == 0, NS_ERROR_GFX_CMAP_MALFORMED);
  130. // Check that the table is large enough for the group array
  131. const uint32_t numGroups = cmap12->numGroups;
  132. NS_ENSURE_TRUE((tablelen - sizeof(Format12CmapHeader)) /
  133. sizeof(Format12Group) >= numGroups,
  134. NS_ERROR_GFX_CMAP_MALFORMED);
  135. // The array of groups immediately follows the subtable header.
  136. const Format12Group *group =
  137. reinterpret_cast<const Format12Group*>(aBuf + sizeof(Format12CmapHeader));
  138. // Check that groups are in correct order and do not overlap,
  139. // and record character coverage in aCharacterMap.
  140. uint32_t prevEndCharCode = 0;
  141. for (uint32_t i = 0; i < numGroups; i++, group++) {
  142. uint32_t startCharCode = group->startCharCode;
  143. const uint32_t endCharCode = group->endCharCode;
  144. NS_ENSURE_TRUE((prevEndCharCode < startCharCode || i == 0) &&
  145. startCharCode <= endCharCode &&
  146. endCharCode <= CMAP_MAX_CODEPOINT,
  147. NS_ERROR_GFX_CMAP_MALFORMED);
  148. // don't include a character that maps to glyph ID 0 (.notdef)
  149. if (group->startGlyphId == 0) {
  150. startCharCode++;
  151. }
  152. if (startCharCode <= endCharCode) {
  153. aCharacterMap.SetRange(startCharCode, endCharCode);
  154. }
  155. prevEndCharCode = endCharCode;
  156. }
  157. aCharacterMap.Compact();
  158. return NS_OK;
  159. }
  160. nsresult
  161. gfxFontUtils::ReadCMAPTableFormat4(const uint8_t *aBuf, uint32_t aLength,
  162. gfxSparseBitSet& aCharacterMap)
  163. {
  164. enum {
  165. OffsetFormat = 0,
  166. OffsetLength = 2,
  167. OffsetLanguage = 4,
  168. OffsetSegCountX2 = 6
  169. };
  170. NS_ENSURE_TRUE(ReadShortAt(aBuf, OffsetFormat) == 4,
  171. NS_ERROR_GFX_CMAP_MALFORMED);
  172. uint16_t tablelen = ReadShortAt(aBuf, OffsetLength);
  173. NS_ENSURE_TRUE(tablelen <= aLength, NS_ERROR_GFX_CMAP_MALFORMED);
  174. NS_ENSURE_TRUE(tablelen > 16, NS_ERROR_GFX_CMAP_MALFORMED);
  175. // This field should normally (except for Mac platform subtables) be zero according to
  176. // the OT spec, but some buggy fonts have lang = 1 (which would be English for MacOS).
  177. // E.g. Arial Narrow Bold, v. 1.1 (Tiger), Arial Unicode MS (see bug 530614).
  178. // So accept either zero or one here; the error should be harmless.
  179. NS_ENSURE_TRUE((ReadShortAt(aBuf, OffsetLanguage) & 0xfffe) == 0,
  180. NS_ERROR_GFX_CMAP_MALFORMED);
  181. uint16_t segCountX2 = ReadShortAt(aBuf, OffsetSegCountX2);
  182. NS_ENSURE_TRUE(tablelen >= 16 + (segCountX2 * 4),
  183. NS_ERROR_GFX_CMAP_MALFORMED);
  184. const uint16_t segCount = segCountX2 / 2;
  185. const uint16_t *endCounts = reinterpret_cast<const uint16_t*>(aBuf + 14);
  186. const uint16_t *startCounts = endCounts + 1 /* skip one uint16_t for reservedPad */ + segCount;
  187. const uint16_t *idDeltas = startCounts + segCount;
  188. const uint16_t *idRangeOffsets = idDeltas + segCount;
  189. uint16_t prevEndCount = 0;
  190. for (uint16_t i = 0; i < segCount; i++) {
  191. const uint16_t endCount = ReadShortAt16(endCounts, i);
  192. const uint16_t startCount = ReadShortAt16(startCounts, i);
  193. const uint16_t idRangeOffset = ReadShortAt16(idRangeOffsets, i);
  194. // sanity-check range
  195. // This permits ranges to overlap by 1 character, which is strictly
  196. // incorrect but occurs in Baskerville on OS X 10.7 (see bug 689087),
  197. // and appears to be harmless in practice
  198. NS_ENSURE_TRUE(startCount >= prevEndCount && startCount <= endCount,
  199. NS_ERROR_GFX_CMAP_MALFORMED);
  200. prevEndCount = endCount;
  201. if (idRangeOffset == 0) {
  202. // figure out if there's a code in the range that would map to
  203. // glyph ID 0 (.notdef); if so, we need to skip setting that
  204. // character code in the map
  205. const uint16_t skipCode = 65536 - ReadShortAt16(idDeltas, i);
  206. if (startCount < skipCode) {
  207. aCharacterMap.SetRange(startCount,
  208. std::min<uint16_t>(skipCode - 1,
  209. endCount));
  210. }
  211. if (skipCode < endCount) {
  212. aCharacterMap.SetRange(std::max<uint16_t>(startCount,
  213. skipCode + 1),
  214. endCount);
  215. }
  216. } else {
  217. // const uint16_t idDelta = ReadShortAt16(idDeltas, i); // Unused: self-documenting.
  218. for (uint32_t c = startCount; c <= endCount; ++c) {
  219. if (c == 0xFFFF)
  220. break;
  221. const uint16_t *gdata = (idRangeOffset/2
  222. + (c - startCount)
  223. + &idRangeOffsets[i]);
  224. NS_ENSURE_TRUE((uint8_t*)gdata > aBuf &&
  225. (uint8_t*)gdata < aBuf + aLength,
  226. NS_ERROR_GFX_CMAP_MALFORMED);
  227. // make sure we have a glyph
  228. if (*gdata != 0) {
  229. // The glyph index at this point is:
  230. uint16_t glyph = ReadShortAt16(idDeltas, i) + *gdata;
  231. if (glyph) {
  232. aCharacterMap.set(c);
  233. }
  234. }
  235. }
  236. }
  237. }
  238. aCharacterMap.Compact();
  239. return NS_OK;
  240. }
  241. nsresult
  242. gfxFontUtils::ReadCMAPTableFormat14(const uint8_t *aBuf, uint32_t aLength,
  243. UniquePtr<uint8_t[]>& aTable)
  244. {
  245. enum {
  246. OffsetFormat = 0,
  247. OffsetTableLength = 2,
  248. OffsetNumVarSelectorRecords = 6,
  249. OffsetVarSelectorRecords = 10,
  250. SizeOfVarSelectorRecord = 11,
  251. VSRecOffsetVarSelector = 0,
  252. VSRecOffsetDefUVSOffset = 3,
  253. VSRecOffsetNonDefUVSOffset = 7,
  254. SizeOfDefUVSTable = 4,
  255. DefUVSOffsetStartUnicodeValue = 0,
  256. DefUVSOffsetAdditionalCount = 3,
  257. SizeOfNonDefUVSTable = 5,
  258. NonDefUVSOffsetUnicodeValue = 0,
  259. NonDefUVSOffsetGlyphID = 3
  260. };
  261. NS_ENSURE_TRUE(aLength >= OffsetVarSelectorRecords,
  262. NS_ERROR_GFX_CMAP_MALFORMED);
  263. NS_ENSURE_TRUE(ReadShortAt(aBuf, OffsetFormat) == 14,
  264. NS_ERROR_GFX_CMAP_MALFORMED);
  265. uint32_t tablelen = ReadLongAt(aBuf, OffsetTableLength);
  266. NS_ENSURE_TRUE(tablelen <= aLength, NS_ERROR_GFX_CMAP_MALFORMED);
  267. NS_ENSURE_TRUE(tablelen >= OffsetVarSelectorRecords,
  268. NS_ERROR_GFX_CMAP_MALFORMED);
  269. const uint32_t numVarSelectorRecords = ReadLongAt(aBuf, OffsetNumVarSelectorRecords);
  270. NS_ENSURE_TRUE((tablelen - OffsetVarSelectorRecords) /
  271. SizeOfVarSelectorRecord >= numVarSelectorRecords,
  272. NS_ERROR_GFX_CMAP_MALFORMED);
  273. const uint8_t *records = aBuf + OffsetVarSelectorRecords;
  274. for (uint32_t i = 0; i < numVarSelectorRecords;
  275. i++, records += SizeOfVarSelectorRecord) {
  276. const uint32_t varSelector = ReadUint24At(records, VSRecOffsetVarSelector);
  277. const uint32_t defUVSOffset = ReadLongAt(records, VSRecOffsetDefUVSOffset);
  278. const uint32_t nonDefUVSOffset = ReadLongAt(records, VSRecOffsetNonDefUVSOffset);
  279. NS_ENSURE_TRUE(varSelector <= CMAP_MAX_CODEPOINT &&
  280. defUVSOffset <= tablelen - 4 &&
  281. nonDefUVSOffset <= tablelen - 4,
  282. NS_ERROR_GFX_CMAP_MALFORMED);
  283. if (defUVSOffset) {
  284. const uint32_t numUnicodeValueRanges = ReadLongAt(aBuf, defUVSOffset);
  285. NS_ENSURE_TRUE((tablelen - defUVSOffset) /
  286. SizeOfDefUVSTable >= numUnicodeValueRanges,
  287. NS_ERROR_GFX_CMAP_MALFORMED);
  288. const uint8_t *tables = aBuf + defUVSOffset + 4;
  289. uint32_t prevEndUnicode = 0;
  290. for (uint32_t j = 0; j < numUnicodeValueRanges; j++, tables += SizeOfDefUVSTable) {
  291. const uint32_t startUnicode = ReadUint24At(tables, DefUVSOffsetStartUnicodeValue);
  292. const uint32_t endUnicode = startUnicode + tables[DefUVSOffsetAdditionalCount];
  293. NS_ENSURE_TRUE((prevEndUnicode < startUnicode || j == 0) &&
  294. endUnicode <= CMAP_MAX_CODEPOINT,
  295. NS_ERROR_GFX_CMAP_MALFORMED);
  296. prevEndUnicode = endUnicode;
  297. }
  298. }
  299. if (nonDefUVSOffset) {
  300. const uint32_t numUVSMappings = ReadLongAt(aBuf, nonDefUVSOffset);
  301. NS_ENSURE_TRUE((tablelen - nonDefUVSOffset) /
  302. SizeOfNonDefUVSTable >= numUVSMappings,
  303. NS_ERROR_GFX_CMAP_MALFORMED);
  304. const uint8_t *tables = aBuf + nonDefUVSOffset + 4;
  305. uint32_t prevUnicode = 0;
  306. for (uint32_t j = 0; j < numUVSMappings; j++, tables += SizeOfNonDefUVSTable) {
  307. const uint32_t unicodeValue = ReadUint24At(tables, NonDefUVSOffsetUnicodeValue);
  308. NS_ENSURE_TRUE((prevUnicode < unicodeValue || j == 0) &&
  309. unicodeValue <= CMAP_MAX_CODEPOINT,
  310. NS_ERROR_GFX_CMAP_MALFORMED);
  311. prevUnicode = unicodeValue;
  312. }
  313. }
  314. }
  315. aTable = MakeUnique<uint8_t[]>(tablelen);
  316. memcpy(aTable.get(), aBuf, tablelen);
  317. return NS_OK;
  318. }
  319. // For fonts with two format-4 tables, we allow the first one (Unicode platform)
  320. // to be replaced by the Microsoft-platform subtable.
  321. #define acceptableFormat4(p,e,k) (((p) == PLATFORM_ID_MICROSOFT && (e) == EncodingIDMicrosoft) || \
  322. ((p) == PLATFORM_ID_UNICODE))
  323. #define acceptableUCS4Encoding(p, e, k) \
  324. ((p) == PLATFORM_ID_MICROSOFT && (e) == EncodingIDUCS4ForMicrosoftPlatform)
  325. #define acceptablePlatform(p) ((p) == PLATFORM_ID_UNICODE || (p) == PLATFORM_ID_MICROSOFT)
  326. #define isSymbol(p,e) ((p) == PLATFORM_ID_MICROSOFT && (e) == EncodingIDSymbol)
  327. #define isUVSEncoding(p, e) ((p) == PLATFORM_ID_UNICODE && (e) == EncodingIDUVSForUnicodePlatform)
  328. uint32_t
  329. gfxFontUtils::FindPreferredSubtable(const uint8_t *aBuf, uint32_t aBufLength,
  330. uint32_t *aTableOffset,
  331. uint32_t *aUVSTableOffset,
  332. bool *aSymbolEncoding)
  333. {
  334. enum {
  335. OffsetVersion = 0,
  336. OffsetNumTables = 2,
  337. SizeOfHeader = 4,
  338. TableOffsetPlatformID = 0,
  339. TableOffsetEncodingID = 2,
  340. TableOffsetOffset = 4,
  341. SizeOfTable = 8,
  342. SubtableOffsetFormat = 0
  343. };
  344. enum {
  345. EncodingIDSymbol = 0,
  346. EncodingIDMicrosoft = 1,
  347. EncodingIDDefaultForUnicodePlatform = 0,
  348. EncodingIDUCS4ForUnicodePlatform = 3,
  349. EncodingIDUVSForUnicodePlatform = 5,
  350. EncodingIDUCS4ForMicrosoftPlatform = 10
  351. };
  352. if (aUVSTableOffset) {
  353. *aUVSTableOffset = 0;
  354. }
  355. if (!aBuf || aBufLength < SizeOfHeader) {
  356. // cmap table is missing, or too small to contain header fields!
  357. return 0;
  358. }
  359. // uint16_t version = ReadShortAt(aBuf, OffsetVersion); // Unused: self-documenting.
  360. uint16_t numTables = ReadShortAt(aBuf, OffsetNumTables);
  361. if (aBufLength < uint32_t(SizeOfHeader + numTables * SizeOfTable)) {
  362. return 0;
  363. }
  364. // save the format we want here
  365. uint32_t keepFormat = 0;
  366. const uint8_t *table = aBuf + SizeOfHeader;
  367. for (uint16_t i = 0; i < numTables; ++i, table += SizeOfTable) {
  368. const uint16_t platformID = ReadShortAt(table, TableOffsetPlatformID);
  369. if (!acceptablePlatform(platformID))
  370. continue;
  371. const uint16_t encodingID = ReadShortAt(table, TableOffsetEncodingID);
  372. const uint32_t offset = ReadLongAt(table, TableOffsetOffset);
  373. if (aBufLength - 2 < offset) {
  374. // this subtable is not valid - beyond end of buffer
  375. return 0;
  376. }
  377. const uint8_t *subtable = aBuf + offset;
  378. const uint16_t format = ReadShortAt(subtable, SubtableOffsetFormat);
  379. if (isSymbol(platformID, encodingID)) {
  380. keepFormat = format;
  381. *aTableOffset = offset;
  382. *aSymbolEncoding = true;
  383. break;
  384. } else if (format == 4 && acceptableFormat4(platformID, encodingID, keepFormat)) {
  385. keepFormat = format;
  386. *aTableOffset = offset;
  387. *aSymbolEncoding = false;
  388. } else if ((format == 10 || format == 12) &&
  389. acceptableUCS4Encoding(platformID, encodingID, keepFormat)) {
  390. keepFormat = format;
  391. *aTableOffset = offset;
  392. *aSymbolEncoding = false;
  393. if (platformID > PLATFORM_ID_UNICODE || !aUVSTableOffset || *aUVSTableOffset) {
  394. break; // we don't want to try anything else when this format is available.
  395. }
  396. } else if (format == 14 && isUVSEncoding(platformID, encodingID) && aUVSTableOffset) {
  397. *aUVSTableOffset = offset;
  398. if (keepFormat == 10 || keepFormat == 12) {
  399. break;
  400. }
  401. }
  402. }
  403. return keepFormat;
  404. }
  405. nsresult
  406. gfxFontUtils::ReadCMAP(const uint8_t *aBuf, uint32_t aBufLength,
  407. gfxSparseBitSet& aCharacterMap,
  408. uint32_t& aUVSOffset,
  409. bool& aUnicodeFont, bool& aSymbolFont)
  410. {
  411. uint32_t offset;
  412. bool symbol;
  413. uint32_t format = FindPreferredSubtable(aBuf, aBufLength,
  414. &offset, &aUVSOffset, &symbol);
  415. switch (format) {
  416. case 4:
  417. if (symbol) {
  418. aUnicodeFont = false;
  419. aSymbolFont = true;
  420. } else {
  421. aUnicodeFont = true;
  422. aSymbolFont = false;
  423. }
  424. return ReadCMAPTableFormat4(aBuf + offset, aBufLength - offset,
  425. aCharacterMap);
  426. case 10:
  427. aUnicodeFont = true;
  428. aSymbolFont = false;
  429. return ReadCMAPTableFormat10(aBuf + offset, aBufLength - offset,
  430. aCharacterMap);
  431. case 12:
  432. aUnicodeFont = true;
  433. aSymbolFont = false;
  434. return ReadCMAPTableFormat12(aBuf + offset, aBufLength - offset,
  435. aCharacterMap);
  436. default:
  437. break;
  438. }
  439. return NS_ERROR_FAILURE;
  440. }
  441. #pragma pack(1)
  442. typedef struct {
  443. AutoSwap_PRUint16 format;
  444. AutoSwap_PRUint16 length;
  445. AutoSwap_PRUint16 language;
  446. AutoSwap_PRUint16 segCountX2;
  447. AutoSwap_PRUint16 searchRange;
  448. AutoSwap_PRUint16 entrySelector;
  449. AutoSwap_PRUint16 rangeShift;
  450. AutoSwap_PRUint16 arrays[1];
  451. } Format4Cmap;
  452. typedef struct {
  453. AutoSwap_PRUint16 format;
  454. AutoSwap_PRUint32 length;
  455. AutoSwap_PRUint32 numVarSelectorRecords;
  456. typedef struct {
  457. AutoSwap_PRUint24 varSelector;
  458. AutoSwap_PRUint32 defaultUVSOffset;
  459. AutoSwap_PRUint32 nonDefaultUVSOffset;
  460. } VarSelectorRecord;
  461. VarSelectorRecord varSelectorRecords[1];
  462. } Format14Cmap;
  463. typedef struct {
  464. AutoSwap_PRUint32 numUVSMappings;
  465. typedef struct {
  466. AutoSwap_PRUint24 unicodeValue;
  467. AutoSwap_PRUint16 glyphID;
  468. } UVSMapping;
  469. UVSMapping uvsMappings[1];
  470. } NonDefUVSTable;
  471. #pragma pack()
  472. uint32_t
  473. gfxFontUtils::MapCharToGlyphFormat4(const uint8_t* aBuf, uint32_t aLength,
  474. char16_t aCh)
  475. {
  476. const Format4Cmap *cmap4 = reinterpret_cast<const Format4Cmap*>(aBuf);
  477. uint16_t segCount = (uint16_t)(cmap4->segCountX2) / 2;
  478. const AutoSwap_PRUint16* endCodes = &cmap4->arrays[0];
  479. const AutoSwap_PRUint16* startCodes = &cmap4->arrays[segCount + 1];
  480. const AutoSwap_PRUint16* idDelta = &startCodes[segCount];
  481. const AutoSwap_PRUint16* idRangeOffset = &idDelta[segCount];
  482. // Sanity-check that the fixed-size arrays don't exceed the buffer.
  483. const uint8_t* const limit = aBuf + aLength;
  484. if ((const uint8_t*)(&idRangeOffset[segCount]) > limit) {
  485. return 0; // broken font, just bail out safely
  486. }
  487. // For most efficient binary search, we want to work on a range of segment
  488. // indexes that is a power of 2 so that we can always halve it by shifting.
  489. // So we find the largest power of 2 that is <= segCount.
  490. // We will offset this range by segOffset so as to reach the end
  491. // of the table, provided that doesn't put us beyond the target
  492. // value from the outset.
  493. uint32_t powerOf2 = mozilla::FindHighestBit(segCount);
  494. uint32_t segOffset = segCount - powerOf2;
  495. uint32_t idx = 0;
  496. if (uint16_t(startCodes[segOffset]) <= aCh) {
  497. idx = segOffset;
  498. }
  499. // Repeatedly halve the size of the range until we find the target group
  500. while (powerOf2 > 1) {
  501. powerOf2 >>= 1;
  502. if (uint16_t(startCodes[idx + powerOf2]) <= aCh) {
  503. idx += powerOf2;
  504. }
  505. }
  506. if (aCh >= uint16_t(startCodes[idx]) && aCh <= uint16_t(endCodes[idx])) {
  507. uint16_t result;
  508. if (uint16_t(idRangeOffset[idx]) == 0) {
  509. result = aCh;
  510. } else {
  511. uint16_t offset = aCh - uint16_t(startCodes[idx]);
  512. const AutoSwap_PRUint16* glyphIndexTable =
  513. (const AutoSwap_PRUint16*)((const char*)&idRangeOffset[idx] +
  514. uint16_t(idRangeOffset[idx]));
  515. if ((const uint8_t*)(glyphIndexTable + offset + 1) > limit) {
  516. return 0; // broken font, just bail out safely
  517. }
  518. result = glyphIndexTable[offset];
  519. }
  520. // Note that this is unsigned 16-bit arithmetic, and may wrap around
  521. // (which is required behavior per spec)
  522. result += uint16_t(idDelta[idx]);
  523. return result;
  524. }
  525. return 0;
  526. }
  527. uint32_t
  528. gfxFontUtils::MapCharToGlyphFormat10(const uint8_t *aBuf, uint32_t aCh)
  529. {
  530. const Format10CmapHeader *cmap10 =
  531. reinterpret_cast<const Format10CmapHeader*>(aBuf);
  532. uint32_t startChar = cmap10->startCharCode;
  533. uint32_t numChars = cmap10->numChars;
  534. if (aCh < startChar || aCh >= startChar + numChars) {
  535. return 0;
  536. }
  537. const AutoSwap_PRUint16 *glyphs =
  538. reinterpret_cast<const AutoSwap_PRUint16 *>(cmap10 + 1);
  539. uint16_t glyph = glyphs[aCh - startChar];
  540. return glyph;
  541. }
  542. uint32_t
  543. gfxFontUtils::MapCharToGlyphFormat12(const uint8_t *aBuf, uint32_t aCh)
  544. {
  545. const Format12CmapHeader *cmap12 =
  546. reinterpret_cast<const Format12CmapHeader*>(aBuf);
  547. // We know that numGroups is within range for the subtable size
  548. // because it was checked by ReadCMAPTableFormat12.
  549. uint32_t numGroups = cmap12->numGroups;
  550. // The array of groups immediately follows the subtable header.
  551. const Format12Group *groups =
  552. reinterpret_cast<const Format12Group*>(aBuf + sizeof(Format12CmapHeader));
  553. // For most efficient binary search, we want to work on a range that
  554. // is a power of 2 so that we can always halve it by shifting.
  555. // So we find the largest power of 2 that is <= numGroups.
  556. // We will offset this range by rangeOffset so as to reach the end
  557. // of the table, provided that doesn't put us beyond the target
  558. // value from the outset.
  559. uint32_t powerOf2 = mozilla::FindHighestBit(numGroups);
  560. uint32_t rangeOffset = numGroups - powerOf2;
  561. uint32_t range = 0;
  562. uint32_t startCharCode;
  563. if (groups[rangeOffset].startCharCode <= aCh) {
  564. range = rangeOffset;
  565. }
  566. // Repeatedly halve the size of the range until we find the target group
  567. while (powerOf2 > 1) {
  568. powerOf2 >>= 1;
  569. if (groups[range + powerOf2].startCharCode <= aCh) {
  570. range += powerOf2;
  571. }
  572. }
  573. // Check if the character is actually present in the range and return
  574. // the corresponding glyph ID
  575. startCharCode = groups[range].startCharCode;
  576. if (startCharCode <= aCh && groups[range].endCharCode >= aCh) {
  577. return groups[range].startGlyphId + aCh - startCharCode;
  578. }
  579. // Else it's not present, so return the .notdef glyph
  580. return 0;
  581. }
  582. namespace {
  583. struct Format14CmapWrapper
  584. {
  585. const Format14Cmap& mCmap14;
  586. explicit Format14CmapWrapper(const Format14Cmap& cmap14) : mCmap14(cmap14) {}
  587. uint32_t operator[](size_t index) const {
  588. return mCmap14.varSelectorRecords[index].varSelector;
  589. }
  590. };
  591. struct NonDefUVSTableWrapper
  592. {
  593. const NonDefUVSTable& mTable;
  594. explicit NonDefUVSTableWrapper(const NonDefUVSTable& table) : mTable(table) {}
  595. uint32_t operator[](size_t index) const {
  596. return mTable.uvsMappings[index].unicodeValue;
  597. }
  598. };
  599. } // namespace
  600. uint16_t
  601. gfxFontUtils::MapUVSToGlyphFormat14(const uint8_t *aBuf, uint32_t aCh, uint32_t aVS)
  602. {
  603. using mozilla::BinarySearch;
  604. const Format14Cmap *cmap14 = reinterpret_cast<const Format14Cmap*>(aBuf);
  605. size_t index;
  606. if (!BinarySearch(Format14CmapWrapper(*cmap14),
  607. 0, cmap14->numVarSelectorRecords, aVS, &index)) {
  608. return 0;
  609. }
  610. const uint32_t nonDefUVSOffset = cmap14->varSelectorRecords[index].nonDefaultUVSOffset;
  611. if (!nonDefUVSOffset) {
  612. return 0;
  613. }
  614. const NonDefUVSTable *table = reinterpret_cast<const NonDefUVSTable*>
  615. (aBuf + nonDefUVSOffset);
  616. if (BinarySearch(NonDefUVSTableWrapper(*table), 0, table->numUVSMappings,
  617. aCh, &index)) {
  618. return table->uvsMappings[index].glyphID;
  619. }
  620. return 0;
  621. }
  622. uint32_t
  623. gfxFontUtils::MapCharToGlyph(const uint8_t *aCmapBuf, uint32_t aBufLength,
  624. uint32_t aUnicode, uint32_t aVarSelector)
  625. {
  626. uint32_t offset, uvsOffset;
  627. bool symbol;
  628. uint32_t format = FindPreferredSubtable(aCmapBuf, aBufLength, &offset,
  629. &uvsOffset, &symbol);
  630. uint32_t gid;
  631. switch (format) {
  632. case 4:
  633. gid = aUnicode < UNICODE_BMP_LIMIT ?
  634. MapCharToGlyphFormat4(aCmapBuf + offset, aBufLength - offset,
  635. char16_t(aUnicode)) : 0;
  636. break;
  637. case 10:
  638. gid = MapCharToGlyphFormat10(aCmapBuf + offset, aUnicode);
  639. break;
  640. case 12:
  641. gid = MapCharToGlyphFormat12(aCmapBuf + offset, aUnicode);
  642. break;
  643. default:
  644. NS_WARNING("unsupported cmap format, glyphs will be missing");
  645. gid = 0;
  646. }
  647. if (aVarSelector && uvsOffset && gid) {
  648. uint32_t varGID =
  649. gfxFontUtils::MapUVSToGlyphFormat14(aCmapBuf + uvsOffset,
  650. aUnicode, aVarSelector);
  651. if (!varGID) {
  652. aUnicode = gfxFontUtils::GetUVSFallback(aUnicode, aVarSelector);
  653. if (aUnicode) {
  654. switch (format) {
  655. case 4:
  656. if (aUnicode < UNICODE_BMP_LIMIT) {
  657. varGID = MapCharToGlyphFormat4(aCmapBuf + offset,
  658. aBufLength - offset,
  659. char16_t(aUnicode));
  660. }
  661. break;
  662. case 10:
  663. varGID = MapCharToGlyphFormat10(aCmapBuf + offset,
  664. aUnicode);
  665. break;
  666. case 12:
  667. varGID = MapCharToGlyphFormat12(aCmapBuf + offset,
  668. aUnicode);
  669. break;
  670. }
  671. }
  672. }
  673. if (varGID) {
  674. gid = varGID;
  675. }
  676. // else the variation sequence was not supported, use default mapping
  677. // of the character code alone
  678. }
  679. return gid;
  680. }
  681. void gfxFontUtils::ParseFontList(const nsAString& aFamilyList,
  682. nsTArray<nsString>& aFontList)
  683. {
  684. const char16_t kComma = char16_t(',');
  685. // append each font name to the list
  686. nsAutoString fontname;
  687. const char16_t *p, *p_end;
  688. aFamilyList.BeginReading(p);
  689. aFamilyList.EndReading(p_end);
  690. while (p < p_end) {
  691. const char16_t *nameStart = p;
  692. while (++p != p_end && *p != kComma)
  693. /* nothing */ ;
  694. // pull out a single name and clean out leading/trailing whitespace
  695. fontname = Substring(nameStart, p);
  696. fontname.CompressWhitespace(true, true);
  697. // append it to the list
  698. aFontList.AppendElement(fontname);
  699. ++p;
  700. }
  701. }
  702. void gfxFontUtils::AppendPrefsFontList(const char *aPrefName,
  703. nsTArray<nsString>& aFontList)
  704. {
  705. // get the list of single-face font families
  706. nsAdoptingString fontlistValue = Preferences::GetString(aPrefName);
  707. if (!fontlistValue) {
  708. return;
  709. }
  710. ParseFontList(fontlistValue, aFontList);
  711. }
  712. void gfxFontUtils::GetPrefsFontList(const char *aPrefName,
  713. nsTArray<nsString>& aFontList)
  714. {
  715. aFontList.Clear();
  716. AppendPrefsFontList(aPrefName, aFontList);
  717. }
  718. // produce a unique font name that is (1) a valid Postscript name and (2) less
  719. // than 31 characters in length. Using AddFontMemResourceEx on Windows fails
  720. // for names longer than 30 characters in length.
  721. #define MAX_B64_LEN 32
  722. nsresult gfxFontUtils::MakeUniqueUserFontName(nsAString& aName)
  723. {
  724. nsCOMPtr<nsIUUIDGenerator> uuidgen =
  725. do_GetService("@mozilla.org/uuid-generator;1");
  726. NS_ENSURE_TRUE(uuidgen, NS_ERROR_OUT_OF_MEMORY);
  727. nsID guid;
  728. NS_ASSERTION(sizeof(guid) * 2 <= MAX_B64_LEN, "size of nsID has changed!");
  729. nsresult rv = uuidgen->GenerateUUIDInPlace(&guid);
  730. NS_ENSURE_SUCCESS(rv, rv);
  731. char guidB64[MAX_B64_LEN] = {0};
  732. if (!PL_Base64Encode(reinterpret_cast<char*>(&guid), sizeof(guid), guidB64))
  733. return NS_ERROR_FAILURE;
  734. // all b64 characters except for '/' are allowed in Postscript names, so convert / ==> -
  735. char *p;
  736. for (p = guidB64; *p; p++) {
  737. if (*p == '/')
  738. *p = '-';
  739. }
  740. aName.AssignLiteral(u"uf");
  741. aName.AppendASCII(guidB64);
  742. return NS_OK;
  743. }
  744. // TrueType/OpenType table handling code
  745. // need byte aligned structs
  746. #pragma pack(1)
  747. // name table stores set of name record structures, followed by
  748. // large block containing all the strings. name record offset and length
  749. // indicates the offset and length within that block.
  750. // http://www.microsoft.com/typography/otspec/name.htm
  751. struct NameRecordData {
  752. uint32_t offset;
  753. uint32_t length;
  754. };
  755. #pragma pack()
  756. static bool
  757. IsValidSFNTVersion(uint32_t version)
  758. {
  759. // normally 0x00010000, CFF-style OT fonts == 'OTTO' and Apple TT fonts = 'true'
  760. // 'typ1' is also possible for old Type 1 fonts in a SFNT container but not supported
  761. return version == 0x10000 ||
  762. version == TRUETYPE_TAG('O','T','T','O') ||
  763. version == TRUETYPE_TAG('t','r','u','e');
  764. }
  765. // Copy and swap UTF-16 values, assume no surrogate pairs, can be in place.
  766. // aInBuf and aOutBuf are NOT necessarily 16-bit-aligned, so we should avoid
  767. // accessing them directly as uint16_t* values.
  768. // aLen is count of UTF-16 values, so the byte buffers are twice that.
  769. static void
  770. CopySwapUTF16(const char* aInBuf, char* aOutBuf, uint32_t aLen)
  771. {
  772. const char* end = aInBuf + aLen * 2;
  773. while (aInBuf < end) {
  774. uint8_t b0 = *aInBuf++;
  775. *aOutBuf++ = *aInBuf++;
  776. *aOutBuf++ = b0;
  777. }
  778. }
  779. gfxUserFontType
  780. gfxFontUtils::DetermineFontDataType(const uint8_t *aFontData, uint32_t aFontDataLength)
  781. {
  782. // test for OpenType font data
  783. // problem: EOT-Lite with 0x10000 length will look like TrueType!
  784. if (aFontDataLength >= sizeof(SFNTHeader)) {
  785. const SFNTHeader *sfntHeader = reinterpret_cast<const SFNTHeader*>(aFontData);
  786. uint32_t sfntVersion = sfntHeader->sfntVersion;
  787. if (IsValidSFNTVersion(sfntVersion)) {
  788. return GFX_USERFONT_OPENTYPE;
  789. }
  790. }
  791. // test for WOFF
  792. if (aFontDataLength >= sizeof(AutoSwap_PRUint32)) {
  793. const AutoSwap_PRUint32 *version =
  794. reinterpret_cast<const AutoSwap_PRUint32*>(aFontData);
  795. if (uint32_t(*version) == TRUETYPE_TAG('w','O','F','F')) {
  796. return GFX_USERFONT_WOFF;
  797. }
  798. if (Preferences::GetBool(GFX_PREF_WOFF2_ENABLED) &&
  799. uint32_t(*version) == TRUETYPE_TAG('w','O','F','2')) {
  800. return GFX_USERFONT_WOFF2;
  801. }
  802. }
  803. // tests for other formats here
  804. return GFX_USERFONT_UNKNOWN;
  805. }
  806. static int
  807. DirEntryCmp(const void* aKey, const void* aItem)
  808. {
  809. int32_t tag = *static_cast<const int32_t*>(aKey);
  810. const TableDirEntry* entry = static_cast<const TableDirEntry*>(aItem);
  811. return tag - int32_t(entry->tag);
  812. }
  813. /* static */
  814. TableDirEntry*
  815. gfxFontUtils::FindTableDirEntry(const void* aFontData, uint32_t aTableTag)
  816. {
  817. const SFNTHeader* header =
  818. reinterpret_cast<const SFNTHeader*>(aFontData);
  819. const TableDirEntry* dir =
  820. reinterpret_cast<const TableDirEntry*>(header + 1);
  821. return static_cast<TableDirEntry*>
  822. (bsearch(&aTableTag, dir, uint16_t(header->numTables),
  823. sizeof(TableDirEntry), DirEntryCmp));
  824. }
  825. /* static */
  826. hb_blob_t*
  827. gfxFontUtils::GetTableFromFontData(const void* aFontData, uint32_t aTableTag)
  828. {
  829. const TableDirEntry* dir = FindTableDirEntry(aFontData, aTableTag);
  830. if (dir) {
  831. return hb_blob_create(reinterpret_cast<const char*>(aFontData) +
  832. dir->offset, dir->length,
  833. HB_MEMORY_MODE_READONLY, nullptr, nullptr);
  834. }
  835. return nullptr;
  836. }
  837. nsresult
  838. gfxFontUtils::RenameFont(const nsAString& aName, const uint8_t *aFontData,
  839. uint32_t aFontDataLength, FallibleTArray<uint8_t> *aNewFont)
  840. {
  841. NS_ASSERTION(aNewFont, "null font data array");
  842. uint64_t dataLength(aFontDataLength);
  843. // new name table
  844. static const uint32_t neededNameIDs[] = {NAME_ID_FAMILY,
  845. NAME_ID_STYLE,
  846. NAME_ID_UNIQUE,
  847. NAME_ID_FULL,
  848. NAME_ID_POSTSCRIPT};
  849. // calculate new name table size
  850. uint16_t nameCount = ArrayLength(neededNameIDs);
  851. // leave room for null-terminator
  852. uint32_t nameStrLength = (aName.Length() + 1) * sizeof(char16_t);
  853. if (nameStrLength > 65535) {
  854. // The name length _in bytes_ must fit in an unsigned short field;
  855. // therefore, a name longer than this cannot be used.
  856. return NS_ERROR_FAILURE;
  857. }
  858. // round name table size up to 4-byte multiple
  859. uint32_t nameTableSize = (sizeof(NameHeader) +
  860. sizeof(NameRecord) * nameCount +
  861. nameStrLength +
  862. 3) & ~3;
  863. if (dataLength + nameTableSize > UINT32_MAX)
  864. return NS_ERROR_FAILURE;
  865. // bug 505386 - need to handle unpadded font length
  866. uint32_t paddedFontDataSize = (aFontDataLength + 3) & ~3;
  867. uint32_t adjFontDataSize = paddedFontDataSize + nameTableSize;
  868. // create new buffer: old font data plus new name table
  869. if (!aNewFont->AppendElements(adjFontDataSize, fallible))
  870. return NS_ERROR_OUT_OF_MEMORY;
  871. // copy the old font data
  872. uint8_t *newFontData = reinterpret_cast<uint8_t*>(aNewFont->Elements());
  873. // null the last four bytes in case the font length is not a multiple of 4
  874. memset(newFontData + aFontDataLength, 0, paddedFontDataSize - aFontDataLength);
  875. // copy font data
  876. memcpy(newFontData, aFontData, aFontDataLength);
  877. // null out the last 4 bytes for checksum calculations
  878. memset(newFontData + adjFontDataSize - 4, 0, 4);
  879. NameHeader *nameHeader = reinterpret_cast<NameHeader*>(newFontData +
  880. paddedFontDataSize);
  881. // -- name header
  882. nameHeader->format = 0;
  883. nameHeader->count = nameCount;
  884. nameHeader->stringOffset = sizeof(NameHeader) + nameCount * sizeof(NameRecord);
  885. // -- name records
  886. uint32_t i;
  887. NameRecord *nameRecord = reinterpret_cast<NameRecord*>(nameHeader + 1);
  888. for (i = 0; i < nameCount; i++, nameRecord++) {
  889. nameRecord->platformID = PLATFORM_ID_MICROSOFT;
  890. nameRecord->encodingID = ENCODING_ID_MICROSOFT_UNICODEBMP;
  891. nameRecord->languageID = LANG_ID_MICROSOFT_EN_US;
  892. nameRecord->nameID = neededNameIDs[i];
  893. nameRecord->offset = 0;
  894. nameRecord->length = nameStrLength;
  895. }
  896. // -- string data, located after the name records, stored in big-endian form
  897. char16_t *strData = reinterpret_cast<char16_t*>(nameRecord);
  898. mozilla::NativeEndian::copyAndSwapToBigEndian(strData,
  899. aName.BeginReading(),
  900. aName.Length());
  901. strData[aName.Length()] = 0; // add null termination
  902. // adjust name table header to point to the new name table
  903. SFNTHeader *sfntHeader = reinterpret_cast<SFNTHeader*>(newFontData);
  904. // table directory entries begin immediately following SFNT header
  905. TableDirEntry *dirEntry =
  906. FindTableDirEntry(newFontData, TRUETYPE_TAG('n','a','m','e'));
  907. // function only called if font validates, so this should always be true
  908. MOZ_ASSERT(dirEntry, "attempt to rename font with no name table");
  909. uint32_t numTables = sfntHeader->numTables;
  910. // note: dirEntry now points to 'name' table record
  911. // recalculate name table checksum
  912. uint32_t checkSum = 0;
  913. AutoSwap_PRUint32 *nameData = reinterpret_cast<AutoSwap_PRUint32*> (nameHeader);
  914. AutoSwap_PRUint32 *nameDataEnd = nameData + (nameTableSize >> 2);
  915. while (nameData < nameDataEnd)
  916. checkSum = checkSum + *nameData++;
  917. // adjust name table entry to point to new name table
  918. dirEntry->offset = paddedFontDataSize;
  919. dirEntry->length = nameTableSize;
  920. dirEntry->checkSum = checkSum;
  921. // fix up checksums
  922. uint32_t checksum = 0;
  923. // checksum for font = (checksum of header) + (checksum of tables)
  924. uint32_t headerLen = sizeof(SFNTHeader) + sizeof(TableDirEntry) * numTables;
  925. const AutoSwap_PRUint32 *headerData =
  926. reinterpret_cast<const AutoSwap_PRUint32*>(newFontData);
  927. // header length is in bytes, checksum calculated in longwords
  928. for (i = 0; i < (headerLen >> 2); i++, headerData++) {
  929. checksum += *headerData;
  930. }
  931. uint32_t headOffset = 0;
  932. dirEntry = reinterpret_cast<TableDirEntry*>(newFontData + sizeof(SFNTHeader));
  933. for (i = 0; i < numTables; i++, dirEntry++) {
  934. if (dirEntry->tag == TRUETYPE_TAG('h','e','a','d')) {
  935. headOffset = dirEntry->offset;
  936. }
  937. checksum += dirEntry->checkSum;
  938. }
  939. NS_ASSERTION(headOffset != 0, "no head table for font");
  940. HeadTable *headData = reinterpret_cast<HeadTable*>(newFontData + headOffset);
  941. headData->checkSumAdjustment = HeadTable::HEAD_CHECKSUM_CALC_CONST - checksum;
  942. return NS_OK;
  943. }
  944. // This is only called after the basic validity of the downloaded sfnt
  945. // data has been checked, so it should never fail to find the name table
  946. // (though it might fail to read it, if memory isn't available);
  947. // other checks here are just for extra paranoia.
  948. nsresult
  949. gfxFontUtils::GetFullNameFromSFNT(const uint8_t* aFontData, uint32_t aLength,
  950. nsAString& aFullName)
  951. {
  952. aFullName.AssignLiteral("(MISSING NAME)"); // should always get replaced
  953. const TableDirEntry *dirEntry =
  954. FindTableDirEntry(aFontData, TRUETYPE_TAG('n','a','m','e'));
  955. // should never fail, as we're only called after font validation succeeded
  956. NS_ENSURE_TRUE(dirEntry, NS_ERROR_NOT_AVAILABLE);
  957. uint32_t len = dirEntry->length;
  958. NS_ENSURE_TRUE(aLength > len && aLength - len >= dirEntry->offset,
  959. NS_ERROR_UNEXPECTED);
  960. hb_blob_t *nameBlob =
  961. hb_blob_create((const char*)aFontData + dirEntry->offset, len,
  962. HB_MEMORY_MODE_READONLY, nullptr, nullptr);
  963. nsresult rv = GetFullNameFromTable(nameBlob, aFullName);
  964. hb_blob_destroy(nameBlob);
  965. return rv;
  966. }
  967. nsresult
  968. gfxFontUtils::GetFullNameFromTable(hb_blob_t *aNameTable,
  969. nsAString& aFullName)
  970. {
  971. nsAutoString name;
  972. nsresult rv =
  973. gfxFontUtils::ReadCanonicalName(aNameTable,
  974. gfxFontUtils::NAME_ID_FULL,
  975. name);
  976. if (NS_SUCCEEDED(rv) && !name.IsEmpty()) {
  977. aFullName = name;
  978. return NS_OK;
  979. }
  980. rv = gfxFontUtils::ReadCanonicalName(aNameTable,
  981. gfxFontUtils::NAME_ID_FAMILY,
  982. name);
  983. if (NS_SUCCEEDED(rv) && !name.IsEmpty()) {
  984. nsAutoString styleName;
  985. rv = gfxFontUtils::ReadCanonicalName(aNameTable,
  986. gfxFontUtils::NAME_ID_STYLE,
  987. styleName);
  988. if (NS_SUCCEEDED(rv) && !styleName.IsEmpty()) {
  989. name.Append(' ');
  990. name.Append(styleName);
  991. aFullName = name;
  992. }
  993. return NS_OK;
  994. }
  995. return NS_ERROR_NOT_AVAILABLE;
  996. }
  997. nsresult
  998. gfxFontUtils::GetFamilyNameFromTable(hb_blob_t *aNameTable,
  999. nsAString& aFullName)
  1000. {
  1001. nsAutoString name;
  1002. nsresult rv =
  1003. gfxFontUtils::ReadCanonicalName(aNameTable,
  1004. gfxFontUtils::NAME_ID_FAMILY,
  1005. name);
  1006. if (NS_SUCCEEDED(rv) && !name.IsEmpty()) {
  1007. aFullName = name;
  1008. return NS_OK;
  1009. }
  1010. return NS_ERROR_NOT_AVAILABLE;
  1011. }
  1012. enum {
  1013. CANONICAL_LANG_ID = gfxFontUtils::LANG_ID_MICROSOFT_EN_US,
  1014. PLATFORM_ID = gfxFontUtils::PLATFORM_ID_MICROSOFT
  1015. };
  1016. nsresult
  1017. gfxFontUtils::ReadNames(const char *aNameData, uint32_t aDataLen,
  1018. uint32_t aNameID, int32_t aPlatformID,
  1019. nsTArray<nsString>& aNames)
  1020. {
  1021. return ReadNames(aNameData, aDataLen, aNameID, LANG_ALL,
  1022. aPlatformID, aNames);
  1023. }
  1024. nsresult
  1025. gfxFontUtils::ReadCanonicalName(hb_blob_t *aNameTable, uint32_t aNameID,
  1026. nsString& aName)
  1027. {
  1028. uint32_t nameTableLen;
  1029. const char *nameTable = hb_blob_get_data(aNameTable, &nameTableLen);
  1030. return ReadCanonicalName(nameTable, nameTableLen, aNameID, aName);
  1031. }
  1032. nsresult
  1033. gfxFontUtils::ReadCanonicalName(const char *aNameData, uint32_t aDataLen,
  1034. uint32_t aNameID, nsString& aName)
  1035. {
  1036. nsresult rv;
  1037. nsTArray<nsString> names;
  1038. // first, look for the English name (this will succeed 99% of the time)
  1039. rv = ReadNames(aNameData, aDataLen, aNameID, CANONICAL_LANG_ID,
  1040. PLATFORM_ID, names);
  1041. NS_ENSURE_SUCCESS(rv, rv);
  1042. // otherwise, grab names for all languages
  1043. if (names.Length() == 0) {
  1044. rv = ReadNames(aNameData, aDataLen, aNameID, LANG_ALL,
  1045. PLATFORM_ID, names);
  1046. NS_ENSURE_SUCCESS(rv, rv);
  1047. }
  1048. // return the first name (99.9% of the time names will
  1049. // contain a single English name)
  1050. if (names.Length()) {
  1051. aName.Assign(names[0]);
  1052. return NS_OK;
  1053. }
  1054. return NS_ERROR_FAILURE;
  1055. }
  1056. // Charsets to use for decoding Mac platform font names.
  1057. // This table is sorted by {encoding, language}, with the wildcard "ANY" being
  1058. // greater than any defined values for each field; we use a binary search on both
  1059. // fields, and fall back to matching only encoding if necessary
  1060. // Some "redundant" entries for specific combinations are included such as
  1061. // encoding=roman, lang=english, in order that common entries will be found
  1062. // on the first search.
  1063. #define ANY 0xffff
  1064. const gfxFontUtils::MacFontNameCharsetMapping gfxFontUtils::gMacFontNameCharsets[] =
  1065. {
  1066. { ENCODING_ID_MAC_ROMAN, LANG_ID_MAC_ENGLISH, "macintosh" },
  1067. { ENCODING_ID_MAC_ROMAN, LANG_ID_MAC_ICELANDIC, "x-mac-icelandic" },
  1068. { ENCODING_ID_MAC_ROMAN, LANG_ID_MAC_TURKISH, "x-mac-turkish" },
  1069. { ENCODING_ID_MAC_ROMAN, LANG_ID_MAC_POLISH, "x-mac-ce" },
  1070. { ENCODING_ID_MAC_ROMAN, LANG_ID_MAC_ROMANIAN, "x-mac-romanian" },
  1071. { ENCODING_ID_MAC_ROMAN, LANG_ID_MAC_CZECH, "x-mac-ce" },
  1072. { ENCODING_ID_MAC_ROMAN, LANG_ID_MAC_SLOVAK, "x-mac-ce" },
  1073. { ENCODING_ID_MAC_ROMAN, ANY, "macintosh" },
  1074. { ENCODING_ID_MAC_JAPANESE, LANG_ID_MAC_JAPANESE, "Shift_JIS" },
  1075. { ENCODING_ID_MAC_JAPANESE, ANY, "Shift_JIS" },
  1076. { ENCODING_ID_MAC_TRAD_CHINESE, LANG_ID_MAC_TRAD_CHINESE, "Big5" },
  1077. { ENCODING_ID_MAC_TRAD_CHINESE, ANY, "Big5" },
  1078. { ENCODING_ID_MAC_KOREAN, LANG_ID_MAC_KOREAN, "EUC-KR" },
  1079. { ENCODING_ID_MAC_KOREAN, ANY, "EUC-KR" },
  1080. { ENCODING_ID_MAC_ARABIC, LANG_ID_MAC_ARABIC, "x-mac-arabic" },
  1081. { ENCODING_ID_MAC_ARABIC, LANG_ID_MAC_URDU, "x-mac-farsi" },
  1082. { ENCODING_ID_MAC_ARABIC, LANG_ID_MAC_FARSI, "x-mac-farsi" },
  1083. { ENCODING_ID_MAC_ARABIC, ANY, "x-mac-arabic" },
  1084. { ENCODING_ID_MAC_HEBREW, LANG_ID_MAC_HEBREW, "x-mac-hebrew" },
  1085. { ENCODING_ID_MAC_HEBREW, ANY, "x-mac-hebrew" },
  1086. { ENCODING_ID_MAC_GREEK, ANY, "x-mac-greek" },
  1087. { ENCODING_ID_MAC_CYRILLIC, ANY, "x-mac-cyrillic" },
  1088. { ENCODING_ID_MAC_DEVANAGARI, ANY, "x-mac-devanagari"},
  1089. { ENCODING_ID_MAC_GURMUKHI, ANY, "x-mac-gurmukhi" },
  1090. { ENCODING_ID_MAC_GUJARATI, ANY, "x-mac-gujarati" },
  1091. { ENCODING_ID_MAC_SIMP_CHINESE, LANG_ID_MAC_SIMP_CHINESE, "gb18030" },
  1092. { ENCODING_ID_MAC_SIMP_CHINESE, ANY, "gb18030" }
  1093. };
  1094. const char* gfxFontUtils::gISOFontNameCharsets[] =
  1095. {
  1096. /* 0 */ "windows-1252", /* US-ASCII */
  1097. /* 1 */ nullptr , /* spec says "ISO 10646" but does not specify encoding form! */
  1098. /* 2 */ "windows-1252" /* ISO-8859-1 */
  1099. };
  1100. const char* gfxFontUtils::gMSFontNameCharsets[] =
  1101. {
  1102. /* [0] ENCODING_ID_MICROSOFT_SYMBOL */ "" ,
  1103. /* [1] ENCODING_ID_MICROSOFT_UNICODEBMP */ "" ,
  1104. /* [2] ENCODING_ID_MICROSOFT_SHIFTJIS */ "Shift_JIS" ,
  1105. /* [3] ENCODING_ID_MICROSOFT_PRC */ nullptr ,
  1106. /* [4] ENCODING_ID_MICROSOFT_BIG5 */ "Big5" ,
  1107. /* [5] ENCODING_ID_MICROSOFT_WANSUNG */ nullptr ,
  1108. /* [6] ENCODING_ID_MICROSOFT_JOHAB */ nullptr ,
  1109. /* [7] reserved */ nullptr ,
  1110. /* [8] reserved */ nullptr ,
  1111. /* [9] reserved */ nullptr ,
  1112. /*[10] ENCODING_ID_MICROSOFT_UNICODEFULL */ ""
  1113. };
  1114. struct MacCharsetMappingComparator
  1115. {
  1116. typedef gfxFontUtils::MacFontNameCharsetMapping MacFontNameCharsetMapping;
  1117. const MacFontNameCharsetMapping& mSearchValue;
  1118. explicit MacCharsetMappingComparator(const MacFontNameCharsetMapping& aSearchValue)
  1119. : mSearchValue(aSearchValue) {}
  1120. int operator()(const MacFontNameCharsetMapping& aEntry) const {
  1121. if (mSearchValue < aEntry) {
  1122. return -1;
  1123. }
  1124. if (aEntry < mSearchValue) {
  1125. return 1;
  1126. }
  1127. return 0;
  1128. }
  1129. };
  1130. // Return the name of the charset we should use to decode a font name
  1131. // given the name table attributes.
  1132. // Special return values:
  1133. // "" charset is UTF16BE, no need for a converter
  1134. // nullptr unknown charset, do not attempt conversion
  1135. const char*
  1136. gfxFontUtils::GetCharsetForFontName(uint16_t aPlatform, uint16_t aScript, uint16_t aLanguage)
  1137. {
  1138. switch (aPlatform)
  1139. {
  1140. case PLATFORM_ID_UNICODE:
  1141. return "";
  1142. case PLATFORM_ID_MAC:
  1143. {
  1144. MacFontNameCharsetMapping searchValue = { aScript, aLanguage, nullptr };
  1145. for (uint32_t i = 0; i < 2; ++i) {
  1146. size_t idx;
  1147. if (BinarySearchIf(gMacFontNameCharsets, 0, ArrayLength(gMacFontNameCharsets),
  1148. MacCharsetMappingComparator(searchValue), &idx)) {
  1149. return gMacFontNameCharsets[idx].mCharsetName;
  1150. }
  1151. // no match, so try again finding one in any language
  1152. searchValue.mLanguage = ANY;
  1153. }
  1154. }
  1155. break;
  1156. case PLATFORM_ID_ISO:
  1157. if (aScript < ArrayLength(gISOFontNameCharsets)) {
  1158. return gISOFontNameCharsets[aScript];
  1159. }
  1160. break;
  1161. case PLATFORM_ID_MICROSOFT:
  1162. if (aScript < ArrayLength(gMSFontNameCharsets)) {
  1163. return gMSFontNameCharsets[aScript];
  1164. }
  1165. break;
  1166. }
  1167. return nullptr;
  1168. }
  1169. // convert a raw name from the name table to an nsString, if possible;
  1170. // return value indicates whether conversion succeeded
  1171. bool
  1172. gfxFontUtils::DecodeFontName(const char *aNameData, int32_t aByteLen,
  1173. uint32_t aPlatformCode, uint32_t aScriptCode,
  1174. uint32_t aLangCode, nsAString& aName)
  1175. {
  1176. if (aByteLen <= 0) {
  1177. NS_WARNING("empty font name");
  1178. aName.SetLength(0);
  1179. return true;
  1180. }
  1181. const char *csName = GetCharsetForFontName(aPlatformCode, aScriptCode, aLangCode);
  1182. if (!csName) {
  1183. // nullptr -> unknown charset
  1184. #ifdef DEBUG
  1185. char warnBuf[128];
  1186. if (aByteLen > 64)
  1187. aByteLen = 64;
  1188. SprintfLiteral(warnBuf, "skipping font name, unknown charset %d:%d:%d for <%.*s>",
  1189. aPlatformCode, aScriptCode, aLangCode, aByteLen, aNameData);
  1190. NS_WARNING(warnBuf);
  1191. #endif
  1192. return false;
  1193. }
  1194. if (csName[0] == 0) {
  1195. // empty charset name: data is utf16be, no need to instantiate a converter
  1196. uint32_t strLen = aByteLen / 2;
  1197. aName.SetLength(strLen);
  1198. #ifdef IS_LITTLE_ENDIAN
  1199. CopySwapUTF16(aNameData, reinterpret_cast<char*>(aName.BeginWriting()),
  1200. strLen);
  1201. #else
  1202. memcpy(aName.BeginWriting(), aNameData, strLen * 2);
  1203. #endif
  1204. return true;
  1205. }
  1206. nsCOMPtr<nsIUnicodeDecoder> decoder =
  1207. mozilla::dom::EncodingUtils::DecoderForEncoding(csName);
  1208. if (!decoder) {
  1209. NS_WARNING("failed to get the decoder for a font name string");
  1210. return false;
  1211. }
  1212. int32_t destLength;
  1213. nsresult rv = decoder->GetMaxLength(aNameData, aByteLen, &destLength);
  1214. if (NS_FAILED(rv)) {
  1215. NS_WARNING("decoder->GetMaxLength failed, invalid font name?");
  1216. return false;
  1217. }
  1218. // make space for the converted string
  1219. aName.SetLength(destLength);
  1220. rv = decoder->Convert(aNameData, &aByteLen,
  1221. aName.BeginWriting(), &destLength);
  1222. if (NS_FAILED(rv)) {
  1223. NS_WARNING("decoder->Convert failed, invalid font name?");
  1224. return false;
  1225. }
  1226. aName.Truncate(destLength); // set the actual length
  1227. return true;
  1228. }
  1229. nsresult
  1230. gfxFontUtils::ReadNames(const char *aNameData, uint32_t aDataLen,
  1231. uint32_t aNameID,
  1232. int32_t aLangID, int32_t aPlatformID,
  1233. nsTArray<nsString>& aNames)
  1234. {
  1235. NS_ASSERTION(aDataLen != 0, "null name table");
  1236. if (!aDataLen) {
  1237. return NS_ERROR_FAILURE;
  1238. }
  1239. // -- name table data
  1240. const NameHeader *nameHeader = reinterpret_cast<const NameHeader*>(aNameData);
  1241. uint32_t nameCount = nameHeader->count;
  1242. // -- sanity check the number of name records
  1243. if (uint64_t(nameCount) * sizeof(NameRecord) > aDataLen) {
  1244. NS_WARNING("invalid font (name table data)");
  1245. return NS_ERROR_FAILURE;
  1246. }
  1247. // -- iterate through name records
  1248. const NameRecord *nameRecord
  1249. = reinterpret_cast<const NameRecord*>(aNameData + sizeof(NameHeader));
  1250. uint64_t nameStringsBase = uint64_t(nameHeader->stringOffset);
  1251. uint32_t i;
  1252. for (i = 0; i < nameCount; i++, nameRecord++) {
  1253. uint32_t platformID;
  1254. // skip over unwanted nameID's
  1255. if (uint32_t(nameRecord->nameID) != aNameID) {
  1256. continue;
  1257. }
  1258. // skip over unwanted platform data
  1259. platformID = nameRecord->platformID;
  1260. if (aPlatformID != PLATFORM_ALL &&
  1261. platformID != uint32_t(aPlatformID)) {
  1262. continue;
  1263. }
  1264. // skip over unwanted languages
  1265. if (aLangID != LANG_ALL &&
  1266. uint32_t(nameRecord->languageID) != uint32_t(aLangID)) {
  1267. continue;
  1268. }
  1269. // add name to names array
  1270. // -- calculate string location
  1271. uint32_t namelen = nameRecord->length;
  1272. uint32_t nameoff = nameRecord->offset; // offset from base of string storage
  1273. if (nameStringsBase + uint64_t(nameoff) + uint64_t(namelen)
  1274. > aDataLen) {
  1275. NS_WARNING("invalid font (name table strings)");
  1276. return NS_ERROR_FAILURE;
  1277. }
  1278. // -- decode if necessary and make nsString
  1279. nsAutoString name;
  1280. DecodeFontName(aNameData + nameStringsBase + nameoff, namelen,
  1281. platformID, uint32_t(nameRecord->encodingID),
  1282. uint32_t(nameRecord->languageID), name);
  1283. uint32_t k, numNames;
  1284. bool foundName = false;
  1285. numNames = aNames.Length();
  1286. for (k = 0; k < numNames; k++) {
  1287. if (name.Equals(aNames[k])) {
  1288. foundName = true;
  1289. break;
  1290. }
  1291. }
  1292. if (!foundName)
  1293. aNames.AppendElement(name);
  1294. }
  1295. return NS_OK;
  1296. }
  1297. #pragma pack(1)
  1298. struct COLRBaseGlyphRecord {
  1299. AutoSwap_PRUint16 glyphId;
  1300. AutoSwap_PRUint16 firstLayerIndex;
  1301. AutoSwap_PRUint16 numLayers;
  1302. };
  1303. struct COLRLayerRecord {
  1304. AutoSwap_PRUint16 glyphId;
  1305. AutoSwap_PRUint16 paletteEntryIndex;
  1306. };
  1307. struct CPALColorRecord {
  1308. uint8_t blue;
  1309. uint8_t green;
  1310. uint8_t red;
  1311. uint8_t alpha;
  1312. };
  1313. #pragma pack()
  1314. bool
  1315. gfxFontUtils::ValidateColorGlyphs(hb_blob_t* aCOLR, hb_blob_t* aCPAL)
  1316. {
  1317. unsigned int colrLength;
  1318. const COLRHeader* colr =
  1319. reinterpret_cast<const COLRHeader*>(hb_blob_get_data(aCOLR, &colrLength));
  1320. unsigned int cpalLength;
  1321. const CPALHeaderVersion0* cpal =
  1322. reinterpret_cast<const CPALHeaderVersion0*>(hb_blob_get_data(aCPAL, &cpalLength));
  1323. if (!colr || !cpal || !colrLength || !cpalLength) {
  1324. return false;
  1325. }
  1326. if (uint16_t(colr->version) != 0 || uint16_t(cpal->version) != 0) {
  1327. // We only support version 0 headers.
  1328. return false;
  1329. }
  1330. const uint32_t offsetBaseGlyphRecord = colr->offsetBaseGlyphRecord;
  1331. const uint16_t numBaseGlyphRecord = colr->numBaseGlyphRecord;
  1332. const uint32_t offsetLayerRecord = colr->offsetLayerRecord;
  1333. const uint16_t numLayerRecords = colr->numLayerRecords;
  1334. const uint32_t offsetFirstColorRecord = cpal->offsetFirstColorRecord;
  1335. const uint16_t numColorRecords = cpal->numColorRecords;
  1336. const uint32_t numPaletteEntries = cpal->numPaletteEntries;
  1337. if (offsetBaseGlyphRecord >= colrLength) {
  1338. return false;
  1339. }
  1340. if (offsetLayerRecord >= colrLength) {
  1341. return false;
  1342. }
  1343. if (offsetFirstColorRecord >= cpalLength) {
  1344. return false;
  1345. }
  1346. if (!numPaletteEntries) {
  1347. return false;
  1348. }
  1349. if (sizeof(COLRBaseGlyphRecord) * numBaseGlyphRecord >
  1350. colrLength - offsetBaseGlyphRecord) {
  1351. // COLR base glyph record will be overflow
  1352. return false;
  1353. }
  1354. if (sizeof(COLRLayerRecord) * numLayerRecords >
  1355. colrLength - offsetLayerRecord) {
  1356. // COLR layer record will be overflow
  1357. return false;
  1358. }
  1359. if (sizeof(CPALColorRecord) * numColorRecords >
  1360. cpalLength - offsetFirstColorRecord) {
  1361. // CPAL color record will be overflow
  1362. return false;
  1363. }
  1364. if (numPaletteEntries * uint16_t(cpal->numPalettes) != numColorRecords ) {
  1365. // palette of CPAL color record will be overflow.
  1366. return false;
  1367. }
  1368. uint16_t lastGlyphId = 0;
  1369. const COLRBaseGlyphRecord* baseGlyph =
  1370. reinterpret_cast<const COLRBaseGlyphRecord*>(
  1371. reinterpret_cast<const uint8_t*>(colr) + offsetBaseGlyphRecord);
  1372. for (uint16_t i = 0; i < numBaseGlyphRecord; i++, baseGlyph++) {
  1373. const uint32_t firstLayerIndex = baseGlyph->firstLayerIndex;
  1374. const uint16_t numLayers = baseGlyph->numLayers;
  1375. const uint16_t glyphId = baseGlyph->glyphId;
  1376. if (lastGlyphId && lastGlyphId >= glyphId) {
  1377. // glyphId must be sorted
  1378. return false;
  1379. }
  1380. lastGlyphId = glyphId;
  1381. if (!numLayers) {
  1382. // no layer
  1383. return false;
  1384. }
  1385. if (firstLayerIndex + numLayers > numLayerRecords) {
  1386. // layer length of target glyph is overflow
  1387. return false;
  1388. }
  1389. }
  1390. const COLRLayerRecord* layer =
  1391. reinterpret_cast<const COLRLayerRecord*>(
  1392. reinterpret_cast<const uint8_t*>(colr) + offsetLayerRecord);
  1393. for (uint16_t i = 0; i < numLayerRecords; i++, layer++) {
  1394. if (uint16_t(layer->paletteEntryIndex) >= numPaletteEntries &&
  1395. uint16_t(layer->paletteEntryIndex) != 0xFFFF) {
  1396. // CPAL palette entry record is overflow
  1397. return false;
  1398. }
  1399. }
  1400. return true;
  1401. }
  1402. static int
  1403. CompareBaseGlyph(const void* key, const void* data)
  1404. {
  1405. uint32_t glyphId = (uint32_t)(uintptr_t)key;
  1406. const COLRBaseGlyphRecord* baseGlyph =
  1407. reinterpret_cast<const COLRBaseGlyphRecord*>(data);
  1408. uint32_t baseGlyphId = uint16_t(baseGlyph->glyphId);
  1409. if (baseGlyphId == glyphId) {
  1410. return 0;
  1411. }
  1412. return baseGlyphId > glyphId ? -1 : 1;
  1413. }
  1414. static
  1415. COLRBaseGlyphRecord*
  1416. LookForBaseGlyphRecord(const COLRHeader* aCOLR, uint32_t aGlyphId)
  1417. {
  1418. const uint8_t* baseGlyphRecords =
  1419. reinterpret_cast<const uint8_t*>(aCOLR) +
  1420. uint32_t(aCOLR->offsetBaseGlyphRecord);
  1421. // BaseGlyphRecord is sorted by glyphId
  1422. return reinterpret_cast<COLRBaseGlyphRecord*>(
  1423. bsearch((void*)(uintptr_t)aGlyphId,
  1424. baseGlyphRecords,
  1425. uint16_t(aCOLR->numBaseGlyphRecord),
  1426. sizeof(COLRBaseGlyphRecord),
  1427. CompareBaseGlyph));
  1428. }
  1429. bool
  1430. gfxFontUtils::GetColorGlyphLayers(hb_blob_t* aCOLR,
  1431. hb_blob_t* aCPAL,
  1432. uint32_t aGlyphId,
  1433. const mozilla::gfx::Color& aDefaultColor,
  1434. nsTArray<uint16_t>& aGlyphs,
  1435. nsTArray<mozilla::gfx::Color>& aColors)
  1436. {
  1437. unsigned int blobLength;
  1438. const COLRHeader* colr =
  1439. reinterpret_cast<const COLRHeader*>(hb_blob_get_data(aCOLR,
  1440. &blobLength));
  1441. MOZ_ASSERT(colr, "Cannot get COLR raw data");
  1442. MOZ_ASSERT(blobLength, "Found COLR data, but length is 0");
  1443. COLRBaseGlyphRecord* baseGlyph = LookForBaseGlyphRecord(colr, aGlyphId);
  1444. if (!baseGlyph) {
  1445. return false;
  1446. }
  1447. const CPALHeaderVersion0* cpal =
  1448. reinterpret_cast<const CPALHeaderVersion0*>(
  1449. hb_blob_get_data(aCPAL, &blobLength));
  1450. MOZ_ASSERT(cpal, "Cannot get CPAL raw data");
  1451. MOZ_ASSERT(blobLength, "Found CPAL data, but length is 0");
  1452. const COLRLayerRecord* layer =
  1453. reinterpret_cast<const COLRLayerRecord*>(
  1454. reinterpret_cast<const uint8_t*>(colr) +
  1455. uint32_t(colr->offsetLayerRecord) +
  1456. sizeof(COLRLayerRecord) * uint16_t(baseGlyph->firstLayerIndex));
  1457. const uint16_t numLayers = baseGlyph->numLayers;
  1458. const uint32_t offsetFirstColorRecord = cpal->offsetFirstColorRecord;
  1459. for (uint16_t layerIndex = 0; layerIndex < numLayers; layerIndex++) {
  1460. aGlyphs.AppendElement(uint16_t(layer->glyphId));
  1461. if (uint16_t(layer->paletteEntryIndex) == 0xFFFF) {
  1462. aColors.AppendElement(aDefaultColor);
  1463. } else {
  1464. const CPALColorRecord* color =
  1465. reinterpret_cast<const CPALColorRecord*>(
  1466. reinterpret_cast<const uint8_t*>(cpal) +
  1467. offsetFirstColorRecord +
  1468. sizeof(CPALColorRecord) * uint16_t(layer->paletteEntryIndex));
  1469. aColors.AppendElement(mozilla::gfx::Color(color->red / 255.0,
  1470. color->green / 255.0,
  1471. color->blue / 255.0,
  1472. color->alpha / 255.0));
  1473. }
  1474. layer++;
  1475. }
  1476. return true;
  1477. }
  1478. #ifdef XP_WIN
  1479. /* static */
  1480. bool
  1481. gfxFontUtils::IsCffFont(const uint8_t* aFontData)
  1482. {
  1483. // this is only called after aFontData has passed basic validation,
  1484. // so we know there is enough data present to allow us to read the version!
  1485. const SFNTHeader *sfntHeader = reinterpret_cast<const SFNTHeader*>(aFontData);
  1486. return (sfntHeader->sfntVersion == TRUETYPE_TAG('O','T','T','O'));
  1487. }
  1488. #endif
  1489. #undef acceptablePlatform
  1490. #undef isSymbol
  1491. #undef isUVSEncoding
  1492. #undef LOG
  1493. #undef LOG_ENABLED