1 /*
2  * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  *     * Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *     * Redistributions in binary form must reproduce the above
11  * copyright notice, this list of conditions and the following disclaimer
12  * in the documentation and/or other materials provided with the
13  * distribution.
14  *     * Neither the name of Google Inc. nor the names of its
15  * contributors may be used to endorse or promote products derived from
16  * this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30 
31 #include "third_party/blink/renderer/platform/image-decoders/bmp/bmp_image_reader.h"
32 
33 #include "third_party/blink/renderer/platform/image-decoders/jpeg/jpeg_image_decoder.h"
34 #include "third_party/blink/renderer/platform/image-decoders/png/png_image_decoder.h"
35 
36 namespace {
37 
38 // See comments on lookup_table_addresses_ in the header.
39 constexpr uint8_t nBitTo8BitlookupTable[] = {
40     // 1 bit
41     0, 255,
42     // 2 bits
43     0, 85, 170, 255,
44     // 3 bits
45     0, 36, 73, 109, 146, 182, 219, 255,
46     // 4 bits
47     0, 17, 34, 51, 68, 85, 102, 119, 136, 153, 170, 187, 204, 221, 238, 255,
48     // 5 bits
49     0, 8, 16, 25, 33, 41, 49, 58, 66, 74, 82, 90, 99, 107, 115, 123, 132, 140,
50     148, 156, 165, 173, 181, 189, 197, 206, 214, 222, 230, 239, 247, 255,
51     // 6 bits
52     0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 45, 49, 53, 57, 61, 65, 69, 73, 77,
53     81, 85, 89, 93, 97, 101, 105, 109, 113, 117, 121, 125, 130, 134, 138, 142,
54     146, 150, 154, 158, 162, 166, 170, 174, 178, 182, 186, 190, 194, 198, 202,
55     206, 210, 215, 219, 223, 227, 231, 235, 239, 243, 247, 251, 255,
56     // 7 bits
57     0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38,
58     40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76,
59     78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110,
60     112, 114, 116, 118, 120, 122, 124, 126, 129, 131, 133, 135, 137, 139, 141,
61     143, 145, 147, 149, 151, 153, 155, 157, 159, 161, 163, 165, 167, 169, 171,
62     173, 175, 177, 179, 181, 183, 185, 187, 189, 191, 193, 195, 197, 199, 201,
63     203, 205, 207, 209, 211, 213, 215, 217, 219, 221, 223, 225, 227, 229, 231,
64     233, 235, 237, 239, 241, 243, 245, 247, 249, 251, 253, 255,
65 };
66 
67 }  // namespace
68 
69 namespace blink {
70 
BMPImageReader(ImageDecoder * parent,size_t decoded_and_header_offset,size_t img_data_offset,bool is_in_ico)71 BMPImageReader::BMPImageReader(ImageDecoder* parent,
72                                size_t decoded_and_header_offset,
73                                size_t img_data_offset,
74                                bool is_in_ico)
75     : parent_(parent),
76       decoded_offset_(decoded_and_header_offset),
77       header_offset_(decoded_and_header_offset),
78       img_data_offset_(img_data_offset),
79       is_in_ico_(is_in_ico) {
80   // Clue-in decodeBMP() that we need to detect the correct info header size.
81   memset(&info_header_, 0, sizeof(info_header_));
82 }
83 
84 BMPImageReader::~BMPImageReader() = default;
85 
SetData(SegmentReader * data)86 void BMPImageReader::SetData(SegmentReader* data) {
87   data_ = data;
88   fast_reader_.SetData(data);
89   if (alternate_decoder_)
90     alternate_decoder_->SetData(data_.get(), parent_->IsAllDataReceived());
91 }
92 
DecodeBMP(bool only_size)93 bool BMPImageReader::DecodeBMP(bool only_size) {
94   // Defensively clear the FastSharedBufferReader's cache, as another caller
95   // may have called SharedBuffer::MergeSegmentsIntoBuffer().
96   fast_reader_.ClearCache();
97 
98   // Calculate size of info header.
99   if (!info_header_.size && !ReadInfoHeaderSize())
100     return false;
101 
102   const size_t header_end = header_offset_ + info_header_.size;
103   // Read and process info header.
104   if ((decoded_offset_ < header_end) && !ProcessInfoHeader())
105     return false;
106 
107   // If there is an applicable color profile, it must be processed now, since
108   // once the image size is available, the decoding machinery assumes the color
109   // space is as well.  Unfortunately, since the profile appears after
110   // everything else, this may delay processing until all data is received.
111   // Luckily, few BMPs have an embedded color profile.
112   const bool use_alternate_decoder =
113       (info_header_.compression == JPEG) || (info_header_.compression == PNG);
114   if (!use_alternate_decoder && info_header_.profile_data &&
115       !ProcessEmbeddedColorProfile())
116     return false;
117 
118   // Set our size if we haven't already.  In ICO files, IsDecodedSizeAvailable()
119   // always returns true (since it reflects the size in the directory, which has
120   // already been read); call SetSize() anyway, since it sanity-checks that the
121   // size here matches the directory.
122   if ((is_in_ico_ || !parent_->IsDecodedSizeAvailable()) &&
123       !parent_->SetSize(static_cast<unsigned>(info_header_.width),
124                         static_cast<unsigned>(info_header_.height)))
125     return false;
126 
127   if (only_size)
128     return true;
129 
130   if (use_alternate_decoder)
131     return DecodeAlternateFormat();
132 
133   // Read and process the bitmasks, if needed.
134   if (need_to_process_bitmasks_ && !ProcessBitmasks())
135     return false;
136 
137   // Read and process the color table, if needed.
138   if (need_to_process_color_table_ && !ProcessColorTable())
139     return false;
140 
141   // Initialize the framebuffer if needed.
142   DCHECK(buffer_);  // Parent should set this before asking us to decode!
143   if ((buffer_->GetStatus() == ImageFrame::kFrameEmpty) && !InitFrame())
144     return false;
145 
146   // Decode the data.
147   if (!decoding_and_mask_ && !PastEndOfImage(0) &&
148       !DecodePixelData((info_header_.compression != RLE4) &&
149                        (info_header_.compression != RLE8) &&
150                        (info_header_.compression != RLE24)))
151     return false;
152 
153   // If the image has an AND mask and there was no alpha data, process the
154   // mask.
155   if (is_in_ico_ && !decoding_and_mask_ &&
156       ((info_header_.bit_count < 16) || !bit_masks_[3] ||
157        !seen_non_zero_alpha_pixel_)) {
158     // Reset decoding coordinates to start of image.
159     coord_.SetX(0);
160     coord_.SetY(is_top_down_ ? 0 : (parent_->Size().Height() - 1));
161 
162     // The AND mask is stored as 1-bit data.
163     info_header_.bit_count = 1;
164 
165     decoding_and_mask_ = true;
166   }
167   if (decoding_and_mask_ && !DecodePixelData(true))
168     return false;
169 
170   // Done!
171   buffer_->SetStatus(ImageFrame::kFrameComplete);
172   return true;
173 }
174 
ReadInfoHeaderSize()175 bool BMPImageReader::ReadInfoHeaderSize() {
176   // Get size of info header.
177   DCHECK_EQ(decoded_offset_, header_offset_);
178   if ((decoded_offset_ > data_->size()) ||
179       ((data_->size() - decoded_offset_) < 4))
180     return false;
181   info_header_.size = ReadUint32(0);
182   // Don't increment decoded_offset here, it just makes the code in
183   // ProcessInfoHeader() more confusing.
184 
185   // Don't allow the header to overflow (which would be harmless here, but
186   // problematic or at least confusing in other places), or to overrun the
187   // image data.
188   const size_t header_end = header_offset_ + info_header_.size;
189   if ((header_end < header_offset_) ||
190       (img_data_offset_ && (img_data_offset_ < header_end)))
191     return parent_->SetFailed();
192 
193   // See if this is a header size we understand.  See comments in
194   // ReadInfoHeader() for more.
195   // OS/2 1.x (and Windows V2): 12
196   if (info_header_.size == 12)
197     is_os21x_ = true;
198   // Windows V3+: 40, 52, 56, 108, 124
199   else if ((info_header_.size == 40) || HasRGBMasksInHeader())
200     ;
201   // OS/2 2.x: any multiple of 4 between 16 and 64, inclusive, or 42 or 46
202   else if ((info_header_.size >= 16) && (info_header_.size <= 64) &&
203            (!(info_header_.size & 3) || (info_header_.size == 42) ||
204             (info_header_.size == 46)))
205     is_os22x_ = true;
206   else
207     return parent_->SetFailed();
208 
209   return true;
210 }
211 
ProcessInfoHeader()212 bool BMPImageReader::ProcessInfoHeader() {
213   // Read info header.
214   DCHECK_EQ(decoded_offset_, header_offset_);
215   if ((decoded_offset_ > data_->size()) ||
216       ((data_->size() - decoded_offset_) < info_header_.size) ||
217       !ReadInfoHeader())
218     return false;
219 
220   // Sanity-check header values before doing further fixup.
221   if (!IsInfoHeaderValid())
222     return parent_->SetFailed();
223 
224   // For paletted images, bitmaps can set clr_used to 0 to mean "all colors", so
225   // set it to the maximum number of colors for this bit depth.  Also do this
226   // for bitmaps that put too large a value here.
227   if (info_header_.bit_count < 16) {
228     const uint32_t max_colors = uint32_t{1} << info_header_.bit_count;
229     if (!info_header_.clr_used || (info_header_.clr_used > max_colors))
230       info_header_.clr_used = max_colors;
231   }
232 
233   // For any bitmaps that set their BitCount to the wrong value, reset the
234   // counts now that we've calculated the number of necessary colors, since
235   // other code relies on this value being correct.
236   if (info_header_.compression == RLE8)
237     info_header_.bit_count = 8;
238   else if (info_header_.compression == RLE4)
239     info_header_.bit_count = 4;
240 
241   // Tell caller what still needs to be processed.
242   if (info_header_.bit_count >= 16)
243     need_to_process_bitmasks_ = true;
244   else if (info_header_.bit_count)
245     need_to_process_color_table_ = true;
246 
247   decoded_offset_ += info_header_.size;
248   return true;
249 }
250 
ReadInfoHeader()251 bool BMPImageReader::ReadInfoHeader() {
252   // Supported info header formats:
253   // * BITMAPCOREHEADER/OS21XBITMAPHEADER/"Windows V2".  Windows 2.x (?),
254   //   OS/2 1.x.  12 bytes.  Incompatible with all below headers.
255   // * BITMAPINFOHEADER/"Windows V3".  Windows 3.x.  40 bytes.  Changes width/
256   //   height fields to 32 bit and adds features such as compression types.
257   //   (Nomenclature: Note that "Windows V3" here and "BITMAPV3..." below are
258   //   different things.)
259   // * OS22XBITMAPHEADER/BITMAPCOREHEADER2.  OS/2 2.x.  16-64 bytes.  The first
260   //   40 bytes are basically identical to BITMAPINFOHEADER, save that most
261   //   fields are optional.  Further fields, if present, are incompatible with
262   //   all below headers.  Adds features such as halftoning and color spaces
263   //   (not implemented here).
264   // * BITMAPV2HEADER/BITMAPV2INFOHEADER.  52 bytes.  Extends BITMAPINFOHEADER
265   //   with R/G/B masks.  Poorly-documented and obscure.
266   // * BITMAPV3HEADER/BITMAPV3INFOHEADER.  56 bytes.  Extends BITMAPV2HEADER
267   //   with an alpha mask.  Poorly-documented and obscure.
268   // * BITMAPV4HEADER/"Windows V4".  Windows 95.  108 bytes.  Extends
269   //   BITMAPV3HEADER with color space support.
270   // * BITMAPV5HEADER/"Windows V5".  Windows 98.  124 bytes.  Extends
271   //   BITMAPV4HEADER with ICC profile support.
272 
273   // Pre-initialize some fields that not all headers set.
274   info_header_.compression = RGB;
275   info_header_.clr_used = 0;
276   info_header_.profile_data = 0;
277   info_header_.profile_size = 0;
278 
279   if (is_os21x_) {
280     info_header_.width = ReadUint16(4);
281     info_header_.height = ReadUint16(6);
282     info_header_.bit_count = ReadUint16(10);
283     return true;
284   }
285 
286   info_header_.width = ReadUint32(4);
287   info_header_.height = ReadUint32(8);
288   if (is_in_ico_)
289     info_header_.height /= 2;
290   // Detect top-down BMPs.
291   if (info_header_.height < 0) {
292     // We can't negate INT32_MIN below to get a positive int32_t.
293     // IsInfoHeaderValid() will reject heights of 1 << 16 or larger anyway,
294     // so just reject this bitmap now.
295     if (info_header_.height == INT32_MIN)
296       return parent_->SetFailed();
297     is_top_down_ = true;
298     info_header_.height = -info_header_.height;
299   }
300 
301   info_header_.bit_count = ReadUint16(14);
302 
303   // Read compression type, if present.
304   if (info_header_.size >= 20) {
305     const uint32_t compression = ReadUint32(16);
306 
307     // Detect OS/2 2.x-specific compression types.
308     if ((compression == 3) && (info_header_.bit_count == 1)) {
309       info_header_.compression = HUFFMAN1D;
310       is_os22x_ = true;
311     } else if ((compression == 4) && (info_header_.bit_count == 24)) {
312       info_header_.compression = RLE24;
313       is_os22x_ = true;
314     } else if (compression > ALPHABITFIELDS) {
315       return parent_->SetFailed();  // Some type we don't understand.
316     } else {
317       info_header_.compression = static_cast<CompressionType>(compression);
318     }
319   }
320 
321   // Read colors used, if present.
322   if (info_header_.size >= 36)
323     info_header_.clr_used = ReadUint32(32);
324 
325   // If we can safely read the four bitmasks from 40-56 bytes in, do that here.
326   // If the bit depth is less than 16, these values will be ignored by the image
327   // data decoders. If the bit depth is at least 16 but the compression format
328   // isn't [ALPHA]BITFIELDS, the RGB bitmasks will be ignored and overwritten in
329   // processBitmasks(). (The alpha bitmask will never be overwritten: images
330   // that actually want alpha have to specify a valid alpha mask. See comments
331   // in ProcessBitmasks().)
332   //
333   // For other BMPs, bit_masks_[] et. al will be initialized later during
334   // ProcessBitmasks().
335   if (HasRGBMasksInHeader()) {
336     bit_masks_[0] = ReadUint32(40);
337     bit_masks_[1] = ReadUint32(44);
338     bit_masks_[2] = ReadUint32(48);
339   }
340   if (HasAlphaMaskInHeader())
341     bit_masks_[3] = ReadUint32(52);
342 
343   // Read color space information, if present and desirable.
344   if (HasColorSpaceInfoInHeader() && !parent_->IgnoresColorSpace()) {
345     enum {
346       kLcsCalibratedRGB = 0x00000000,
347       kLcssRGB = 0x73524742,               // "sRGB"
348       kLcsWindowsColorSpace = 0x57696E20,  // "Win "
349       kProfileLinked = 0x4c494e4b,         // "LINK"
350       kProfileEmbedded = 0x4d424544,       // "MBED"
351     };
352 
353     const uint32_t cs_type = ReadUint32(56);
354     switch (cs_type) {
355       case kLcsCalibratedRGB: {  // Endpoints and gamma specified directly
356         skcms_ICCProfile profile;
357         skcms_Init(&profile);
358 
359         // Convert chromaticity values from 2.30 fixed point to floating point.
360         const auto fxpt2dot30_to_float = [](uint32_t fxpt2dot30) {
361           return fxpt2dot30 * 9.31322574615478515625e-10f;
362         };
363         const float rx = fxpt2dot30_to_float(ReadUint32(60));
364         const float ry = fxpt2dot30_to_float(ReadUint32(64));
365         const float gx = fxpt2dot30_to_float(ReadUint32(72));
366         const float gy = fxpt2dot30_to_float(ReadUint32(76));
367         const float bx = fxpt2dot30_to_float(ReadUint32(84));
368         const float by = fxpt2dot30_to_float(ReadUint32(88));
369         // BMPs do not explicitly encode a white point.  Using the sRGB
370         // illuminant (D65) seems reasonable given that Windows' system color
371         // space is sRGB.
372         constexpr float kD65x = 0.31271;
373         constexpr float kD65y = 0.32902;
374         skcms_Matrix3x3 to_xyzd50;
375         if (!skcms_PrimariesToXYZD50(rx, ry, gx, gy, bx, by, kD65x, kD65y,
376                                      &to_xyzd50)) {
377           // Some real-world images have bogus values, e.g. all zeros.  Ignore
378           // the color space data in such cases, rather than failing.
379           break;
380         }
381         skcms_SetXYZD50(&profile, &to_xyzd50);
382 
383         // Convert gamma values from 16.16 fixed point to transfer functions.
384         const auto fxpt16dot16_to_fn = [](uint32_t fxpt16dot16) {
385           skcms_TransferFunction fn;
386           fn.a = 1.0f;
387           fn.b = fn.c = fn.d = fn.e = fn.f = 0.0f;
388           // Petzold's "Programming Windows" claims the gamma here is a decoding
389           // gamma (e.g. 2.2), as opposed to the inverse, an encoding gamma
390           // (like PNG encodes in its gAMA chunk).
391           fn.g = SkFixedToFloat(fxpt16dot16);
392           return fn;
393         };
394         profile.has_trc = true;
395         profile.trc[0].table_entries = 0;
396         profile.trc[0].parametric = fxpt16dot16_to_fn(ReadUint32(96));
397         profile.trc[1].table_entries = 0;
398         profile.trc[1].parametric = fxpt16dot16_to_fn(ReadUint32(100));
399         profile.trc[2].table_entries = 0;
400         profile.trc[2].parametric = fxpt16dot16_to_fn(ReadUint32(104));
401 
402         parent_->SetEmbeddedColorProfile(
403             std::make_unique<ColorProfile>(profile));
404         break;
405       }
406 
407       case kLcssRGB:               // sRGB
408       case kLcsWindowsColorSpace:  // "The Windows default color space" (sRGB)
409         parent_->SetEmbeddedColorProfile(
410             std::make_unique<ColorProfile>(*skcms_sRGB_profile()));
411         break;
412 
413       case kProfileEmbedded:  // Embedded ICC profile
414         if (info_header_.size >= 120) {
415           info_header_.profile_data = header_offset_ + ReadUint32(112);
416           info_header_.profile_size = ReadUint32(116);
417         }
418         break;
419 
420       case kProfileLinked:     // Linked ICC profile.  Unsupported; presents
421                                // security concerns.
422       default:                 // Unknown.
423         break;
424     }
425   }
426 
427   return true;
428 }
429 
IsInfoHeaderValid() const430 bool BMPImageReader::IsInfoHeaderValid() const {
431   // Non-positive widths/heights are invalid.  (We've already flipped the
432   // sign of the height for top-down bitmaps.)
433   if ((info_header_.width <= 0) || !info_header_.height)
434     return false;
435 
436   // Only Windows V3+ has ICOs and top-down bitmaps.
437   if ((is_in_ico_ || is_top_down_) && (is_os21x_ || is_os22x_))
438     return false;
439 
440   // Only bit depths of 1, 4, 8, or 24 are universally supported.
441   if ((info_header_.bit_count != 1) && (info_header_.bit_count != 4) &&
442       (info_header_.bit_count != 8) && (info_header_.bit_count != 24)) {
443     // Windows V3+ additionally supports bit depths of 0 (for embedded
444     // JPEG/PNG images), 2 (on Windows CE), 16, and 32.
445     if (is_os21x_ || is_os22x_ ||
446         (info_header_.bit_count && (info_header_.bit_count != 2) &&
447          (info_header_.bit_count != 16) && (info_header_.bit_count != 32)))
448       return false;
449   }
450 
451   // Each compression type is only valid with certain bit depths (except RGB,
452   // which can be used with any bit depth). Also, some formats do not support
453   // some compression types.
454   switch (info_header_.compression) {
455     case RGB:
456       if (!info_header_.bit_count)
457         return false;
458       break;
459 
460     case RLE8:
461       // Supposedly there are undocumented formats like "BitCount = 1,
462       // Compression = RLE4" (which means "4 bit, but with a 2-color table"),
463       // so also allow the paletted RLE compression types to have too low a
464       // bit count; we'll correct this later.
465       if (!info_header_.bit_count || (info_header_.bit_count > 8))
466         return false;
467       break;
468 
469     case RLE4:
470       // See comments in RLE8.
471       if (!info_header_.bit_count || (info_header_.bit_count > 4))
472         return false;
473       break;
474 
475     case BITFIELDS:
476     case ALPHABITFIELDS:
477       // Only valid for Windows V3+.
478       if (is_os21x_ || is_os22x_ ||
479           ((info_header_.bit_count != 16) && (info_header_.bit_count != 32)))
480         return false;
481       break;
482 
483     case JPEG:
484     case PNG:
485       // Only valid for Windows V3+.  We don't support embedding these inside
486       // ICO files.
487       if (is_os21x_ || is_os22x_ || info_header_.bit_count || !img_data_offset_)
488         return false;
489       break;
490 
491     case HUFFMAN1D:
492       // Only valid for OS/2 2.x.
493       if (!is_os22x_ || (info_header_.bit_count != 1))
494         return false;
495       break;
496 
497     case RLE24:
498       // Only valid for OS/2 2.x.
499       if (!is_os22x_ || (info_header_.bit_count != 24))
500         return false;
501       break;
502 
503     default:
504       // Some type we don't understand.  This should have been caught in
505       // ReadInfoHeader().
506       NOTREACHED();
507       return false;
508   }
509 
510   // Reject the following valid bitmap types that we don't currently bother
511   // decoding.  Few other people decode these either, they're unlikely to be
512   // in much use.
513   // TODO(pkasting): Consider supporting these someday.
514   //   * Bitmaps larger than 2^16 pixels in either dimension.
515   if ((info_header_.width >= (1 << 16)) || (info_header_.height >= (1 << 16)))
516     return false;
517   //   * OS/2 2.x Huffman-encoded monochrome bitmaps (see
518   //      http://www.fileformat.info/mirror/egff/ch09_05.htm , re: "G31D"
519   //      algorithm; this seems to be used in TIFF files as well).
520   if (info_header_.compression == HUFFMAN1D)
521     return false;
522 
523   return true;
524 }
525 
DecodeAlternateFormat()526 bool BMPImageReader::DecodeAlternateFormat() {
527   // Create decoder if necessary.
528   if (!alternate_decoder_) {
529     if (info_header_.compression == JPEG) {
530       alternate_decoder_ = std::make_unique<JPEGImageDecoder>(
531           parent_->GetAlphaOption(), parent_->GetColorBehavior(),
532           parent_->GetMaxDecodedBytes(), img_data_offset_);
533     } else {
534       alternate_decoder_ = std::make_unique<PNGImageDecoder>(
535           parent_->GetAlphaOption(), ImageDecoder::kDefaultBitDepth,
536           parent_->GetColorBehavior(), parent_->GetMaxDecodedBytes(),
537           img_data_offset_);
538     }
539     alternate_decoder_->SetData(data_.get(), parent_->IsAllDataReceived());
540   }
541 
542   // Decode the image.
543   if (alternate_decoder_->IsSizeAvailable()) {
544     if (alternate_decoder_->Size() != parent_->Size())
545       return parent_->SetFailed();
546 
547     alternate_decoder_->SetMemoryAllocator(buffer_->GetAllocator());
548     const auto* frame = alternate_decoder_->DecodeFrameBufferAtIndex(0);
549     alternate_decoder_->SetMemoryAllocator(nullptr);
550 
551     if (frame)
552       *buffer_ = *frame;
553   }
554   return alternate_decoder_->Failed()
555              ? parent_->SetFailed()
556              : (buffer_->GetStatus() == ImageFrame::kFrameComplete);
557 }
558 
ProcessEmbeddedColorProfile()559 bool BMPImageReader::ProcessEmbeddedColorProfile() {
560   // Ensure we have received the whole profile.
561   if ((info_header_.profile_data > data_->size()) ||
562       ((data_->size() - info_header_.profile_data) < info_header_.profile_size))
563     return false;
564 
565   // Parse the profile.
566   auto owned_buffer = std::make_unique<char[]>(info_header_.profile_size);
567   const char* buffer = fast_reader_.GetConsecutiveData(
568       info_header_.profile_data, info_header_.profile_size, owned_buffer.get());
569   auto profile = ColorProfile::Create(buffer, info_header_.profile_size);
570   if (!profile)
571     return parent_->SetFailed();
572   parent_->SetEmbeddedColorProfile(std::move(profile));
573 
574   // Zero |profile_data| so we don't try to process the profile again in the
575   // future.
576   info_header_.profile_data = 0;
577   return true;
578 }
579 
ProcessBitmasks()580 bool BMPImageReader::ProcessBitmasks() {
581   // Create bit_masks_[] values for R/G/B.
582   if ((info_header_.compression != BITFIELDS) &&
583       (info_header_.compression != ALPHABITFIELDS)) {
584     // The format doesn't actually use bitmasks.  To simplify the decode
585     // logic later, create bitmasks for the RGB data.  For Windows V4+,
586     // this overwrites the masks we read from the header, which are
587     // supposed to be ignored in non-BITFIELDS cases.
588     // 16 bits:    MSB <-                     xRRRRRGG GGGBBBBB -> LSB
589     // 24/32 bits: MSB <- [AAAAAAAA] RRRRRRRR GGGGGGGG BBBBBBBB -> LSB
590     const int num_bits = (info_header_.bit_count == 16) ? 5 : 8;
591     for (int i = 0; i <= 2; ++i) {
592       bit_masks_[i] = ((uint32_t{1} << (num_bits * (3 - i))) - 1) ^
593                       ((uint32_t{1} << (num_bits * (2 - i))) - 1);
594     }
595   } else if (!HasRGBMasksInHeader()) {
596     // For HasRGBMasksInHeader() bitmaps, this was already done when we read the
597     // info header.
598 
599     // Fail if we don't have enough file space for the bitmasks.
600     const size_t header_end = header_offset_ + info_header_.size;
601     const bool read_alpha = info_header_.compression == ALPHABITFIELDS;
602     const size_t kBitmasksSize = read_alpha ? 16 : 12;
603     const size_t bitmasks_end = header_end + kBitmasksSize;
604     if ((bitmasks_end < header_end) ||
605         (img_data_offset_ && (img_data_offset_ < bitmasks_end)))
606       return parent_->SetFailed();
607 
608     // Read bitmasks.
609     if ((data_->size() - decoded_offset_) < kBitmasksSize)
610       return false;
611     bit_masks_[0] = ReadUint32(0);
612     bit_masks_[1] = ReadUint32(4);
613     bit_masks_[2] = ReadUint32(8);
614     if (read_alpha)
615       bit_masks_[3] = ReadUint32(12);
616 
617     decoded_offset_ += kBitmasksSize;
618   }
619 
620   // Alpha is a poorly-documented and inconsistently-used feature.
621   //
622   // BITMAPV3HEADER+ have an alpha bitmask in the info header.  Unlike the R/G/B
623   // bitmasks, the MSDN docs don't indicate that it is only valid for the
624   // BITFIELDS compression format, so we respect it at all times.
625   //
626   // Windows CE supports the ALPHABITFIELDS compression format, which is rare.
627   // We assume any mask specified by this format is valid as well.
628   //
629   // To complicate things, Windows V3 BMPs, which lack a mask, can specify 32bpp
630   // format, which to any sane reader would imply an 8-bit alpha channel -- and
631   // for BMPs-in-ICOs, that's precisely what's intended to happen. There also
632   // exist standalone BMPs in this format which clearly expect the alpha channel
633   // to be respected. However, there are many other BMPs which, for example,
634   // fill this channel with all 0s, yet clearly expect to not be displayed as a
635   // fully-transparent rectangle.
636   //
637   // If these were the only two types of Windows V3, 32bpp BMPs in the wild,
638   // we could distinguish between them by scanning the alpha channel in the
639   // image, looking for nonzero values, and only enabling alpha if we found
640   // some. (It turns out we have to do this anyway, because, crazily, there
641   // are also Windows V4+ BMPs with an explicit, non-zero alpha mask, which
642   // then zero-fill their alpha channels! See comments in
643   // processNonRLEData().)
644   //
645   // Unfortunately there are also V3 BMPs -- indeed, probably more than the
646   // number of 32bpp, V3 BMPs which intentionally use alpha -- which specify
647   // 32bpp format, use nonzero (and non-255) alpha values, and yet expect to
648   // be rendered fully-opaque. And other browsers do so.
649   //
650   // So it's impossible to display every BMP in the way its creators intended,
651   // and we have to choose what to break. Given the paragraph above, we match
652   // other browsers and ignore alpha in Windows V3 BMPs except inside ICO
653   // files.
654   if (!HasAlphaMaskInHeader() && (info_header_.compression != ALPHABITFIELDS)) {
655     const bool use_mask = is_in_ico_ &&
656                           (info_header_.compression != BITFIELDS) &&
657                           (info_header_.bit_count == 32);
658     bit_masks_[3] = use_mask ? uint32_t{0xff000000} : 0;
659   }
660 
661   // Check masks and set shift and LUT address values.
662   for (int i = 0; i < 4; ++i) {
663     // Trim the mask to the allowed bit depth.  Some Windows V4+ BMPs
664     // specify a bogus alpha channel in bits that don't exist in the pixel
665     // data (for example, bits 25-31 in a 24-bit RGB format).
666     if (info_header_.bit_count < 32) {
667       bit_masks_[i] &= ((uint32_t{1} << info_header_.bit_count) - 1);
668     }
669 
670     // For empty masks (common on the alpha channel, especially after the
671     // trimming above), quickly clear the shift and LUT address and
672     // continue, to avoid an infinite loop in the counting code below.
673     uint32_t temp_mask = bit_masks_[i];
674     if (!temp_mask) {
675       bit_shifts_right_[i] = 0;
676       lookup_table_addresses_[i] = nullptr;
677       continue;
678     }
679 
680     // Make sure bitmask does not overlap any other bitmasks.
681     for (int j = 0; j < i; ++j) {
682       if (temp_mask & bit_masks_[j])
683         return parent_->SetFailed();
684     }
685 
686     // Count offset into pixel data.
687     for (bit_shifts_right_[i] = 0; !(temp_mask & 1); temp_mask >>= 1)
688       ++bit_shifts_right_[i];
689 
690     // Count size of mask.
691     size_t num_bits = 0;
692     for (; temp_mask & 1; temp_mask >>= 1)
693       ++num_bits;
694 
695     // Make sure bitmask is contiguous.
696     if (temp_mask)
697       return parent_->SetFailed();
698 
699     // Since RGBABuffer tops out at 8 bits per channel, adjust the shift
700     // amounts to use the most significant 8 bits of the channel.
701     if (num_bits >= 8) {
702       bit_shifts_right_[i] += (num_bits - 8);
703       num_bits = 0;
704     }
705 
706     // Calculate LUT address.
707     lookup_table_addresses_[i] =
708         num_bits ? (nBitTo8BitlookupTable + (1 << num_bits) - 2) : nullptr;
709   }
710 
711   // We've now decoded all the non-image data we care about.  Skip anything
712   // else before the actual raster data.
713   if (img_data_offset_)
714     decoded_offset_ = img_data_offset_;
715   need_to_process_bitmasks_ = false;
716   return true;
717 }
718 
ProcessColorTable()719 bool BMPImageReader::ProcessColorTable() {
720   // On non-OS/2 1.x, an extra padding byte is present, which we need to skip.
721   const size_t bytes_per_color = is_os21x_ ? 3 : 4;
722 
723   const size_t header_end = header_offset_ + info_header_.size;
724   size_t colors_in_palette = info_header_.clr_used;
725   size_t table_size_in_bytes = colors_in_palette * bytes_per_color;
726   const size_t table_end = header_end + table_size_in_bytes;
727   if (table_end < header_end)
728     return parent_->SetFailed();
729 
730   // Some BMPs don't contain a complete palette.  Avoid reading off the end.
731   if (img_data_offset_ && (img_data_offset_ < table_end)) {
732     colors_in_palette = (img_data_offset_ - header_end) / bytes_per_color;
733     table_size_in_bytes = colors_in_palette * bytes_per_color;
734   }
735 
736   // Read color table.
737   if ((decoded_offset_ > data_->size()) ||
738       ((data_->size() - decoded_offset_) < table_size_in_bytes))
739     return false;
740   color_table_.resize(info_header_.clr_used);
741 
742   for (size_t i = 0; i < colors_in_palette; ++i) {
743     color_table_[i].rgb_blue = ReadUint8(0);
744     color_table_[i].rgb_green = ReadUint8(1);
745     color_table_[i].rgb_red = ReadUint8(2);
746     decoded_offset_ += bytes_per_color;
747   }
748   // Explicitly zero any colors past the end of a truncated palette.
749   for (size_t i = colors_in_palette; i < info_header_.clr_used; ++i) {
750     color_table_[i].rgb_blue = 0;
751     color_table_[i].rgb_green = 0;
752     color_table_[i].rgb_red = 0;
753   }
754 
755   // We've now decoded all the non-image data we care about.  Skip anything
756   // else before the actual raster data.
757   if (img_data_offset_)
758     decoded_offset_ = img_data_offset_;
759   need_to_process_color_table_ = false;
760   return true;
761 }
762 
InitFrame()763 bool BMPImageReader::InitFrame() {
764   if (!buffer_->AllocatePixelData(parent_->Size().Width(),
765                                   parent_->Size().Height(),
766                                   parent_->ColorSpaceForSkImages()))
767     return parent_->SetFailed();  // Unable to allocate.
768 
769   buffer_->ZeroFillPixelData();
770   buffer_->SetStatus(ImageFrame::kFramePartial);
771   // SetSize() calls EraseARGB(), which resets the alpha flag, so we force it
772   // back to false here.  We'll set it to true later in all cases where these 0s
773   // could actually show through.
774   buffer_->SetHasAlpha(false);
775 
776   // For BMPs, the frame always fills the entire image.
777   buffer_->SetOriginalFrameRect(IntRect(IntPoint(), parent_->Size()));
778 
779   if (!is_top_down_)
780     coord_.SetY(parent_->Size().Height() - 1);
781   return true;
782 }
783 
DecodePixelData(bool non_rle)784 bool BMPImageReader::DecodePixelData(bool non_rle) {
785   const IntPoint coord(coord_);
786   const ProcessingResult result =
787       non_rle ? ProcessNonRLEData(false, 0) : ProcessRLEData();
788   if (coord_ != coord)
789     buffer_->SetPixelsChanged(true);
790   return (result == kFailure) ? parent_->SetFailed() : (result == kSuccess);
791 }
792 
ProcessRLEData()793 BMPImageReader::ProcessingResult BMPImageReader::ProcessRLEData() {
794   if (decoded_offset_ > data_->size())
795     return kInsufficientData;
796 
797   // RLE decoding is poorly specified.  Two main problems:
798   // (1) Are EOL markers necessary?  What happens when we have too many
799   //     pixels for one row?
800   //     http://www.fileformat.info/format/bmp/egff.htm says extra pixels
801   //     should wrap to the next line.  Real BMPs I've encountered seem to
802   //     instead expect extra pixels to be ignored until the EOL marker is
803   //     seen, although this has only happened in a few cases and I suspect
804   //     those BMPs may be invalid.  So we only change lines on EOL (or Delta
805   //     with dy > 0), and fail in most cases when pixels extend past the end
806   //     of the line.
807   // (2) When Delta, EOL, or EOF are seen, what happens to the "skipped"
808   //     pixels?
809   //     http://www.daubnet.com/formats/BMP.html says these should be filled
810   //     with color 0.  However, the "do nothing" and "don't care" comments
811   //     of other references suggest leaving these alone, i.e. letting them
812   //     be transparent to the background behind the image.  This seems to
813   //     match how MSPAINT treats BMPs, so we do that.  Note that when we
814   //     actually skip pixels for a case like this, we need to note on the
815   //     framebuffer that we have alpha.
816 
817   // Impossible to decode row-at-a-time, so just do things as a stream of
818   // bytes.
819   while (true) {
820     // Every entry takes at least two bytes; bail if there isn't enough
821     // data.
822     if ((data_->size() - decoded_offset_) < 2)
823       return kInsufficientData;
824 
825     // For every entry except EOF, we'd better not have reached the end of
826     // the image.
827     const uint8_t count = ReadUint8(0);
828     const uint8_t code = ReadUint8(1);
829     if ((count || (code != 1)) && PastEndOfImage(0))
830       return kFailure;
831 
832     // Decode.
833     if (!count) {
834       switch (code) {
835         case 0:  // Magic token: EOL
836           // Skip any remaining pixels in this row.
837           if (coord_.X() < parent_->Size().Width())
838             buffer_->SetHasAlpha(true);
839           ColorCorrectCurrentRow();
840           MoveBufferToNextRow();
841 
842           decoded_offset_ += 2;
843           break;
844 
845         case 1:  // Magic token: EOF
846           // Skip any remaining pixels in the image.
847           if ((coord_.X() < parent_->Size().Width()) ||
848               (is_top_down_ ? (coord_.Y() < (parent_->Size().Height() - 1))
849                             : (coord_.Y() > 0)))
850             buffer_->SetHasAlpha(true);
851           ColorCorrectCurrentRow();
852           // There's no need to move |coord_| here to trigger the caller
853           // to call SetPixelsChanged().  If the only thing that's changed
854           // is the alpha state, that will be properly written into the
855           // underlying SkBitmap when we mark the frame complete.
856           return kSuccess;
857 
858         case 2: {  // Magic token: Delta
859           // The next two bytes specify dx and dy.  Bail if there isn't
860           // enough data.
861           if ((data_->size() - decoded_offset_) < 4)
862             return kInsufficientData;
863 
864           // Fail if this takes us past the end of the desired row or
865           // past the end of the image.
866           const uint8_t dx = ReadUint8(2);
867           const uint8_t dy = ReadUint8(3);
868           if (dx || dy) {
869             buffer_->SetHasAlpha(true);
870             if (dy)
871               ColorCorrectCurrentRow();
872           }
873           if (((coord_.X() + dx) > parent_->Size().Width()) ||
874               PastEndOfImage(dy))
875             return kFailure;
876 
877           // Skip intervening pixels.
878           coord_.Move(dx, is_top_down_ ? dy : -dy);
879 
880           decoded_offset_ += 4;
881           break;
882         }
883 
884         default: {  // Absolute mode
885           // |code| pixels specified as in BI_RGB, zero-padded at the end
886           // to a multiple of 16 bits.
887           // Because ProcessNonRLEData() expects decoded_offset_ to
888           // point to the beginning of the pixel data, bump it past
889           // the escape bytes and then reset if decoding failed.
890           decoded_offset_ += 2;
891           const ProcessingResult result = ProcessNonRLEData(true, code);
892           if (result != kSuccess) {
893             decoded_offset_ -= 2;
894             return result;
895           }
896           break;
897         }
898       }
899     } else {  // Encoded mode
900       // The following color data is repeated for |count| total pixels.
901       // Strangely, some BMPs seem to specify excessively large counts
902       // here; ignore pixels past the end of the row.
903       const int end_x = std::min(coord_.X() + count, parent_->Size().Width());
904 
905       if (info_header_.compression == RLE24) {
906         // Bail if there isn't enough data.
907         if ((data_->size() - decoded_offset_) < 4)
908           return kInsufficientData;
909 
910         // One BGR triple that we copy |count| times.
911         FillRGBA(end_x, ReadUint8(3), ReadUint8(2), code, 0xff);
912         decoded_offset_ += 4;
913       } else {
914         // RLE8 has one color index that gets repeated; RLE4 has two
915         // color indexes in the upper and lower 4 bits of the byte,
916         // which are alternated.
917         wtf_size_t color_indexes[2] = {code, code};
918         if (info_header_.compression == RLE4) {
919           color_indexes[0] = (color_indexes[0] >> 4) & 0xf;
920           color_indexes[1] &= 0xf;
921         }
922         for (wtf_size_t which = 0; coord_.X() < end_x;) {
923           // Some images specify color values past the end of the
924           // color table; set these pixels to black.
925           if (color_indexes[which] < info_header_.clr_used)
926             SetI(color_indexes[which]);
927           else
928             SetRGBA(0, 0, 0, 255);
929           which = !which;
930         }
931 
932         decoded_offset_ += 2;
933       }
934     }
935   }
936 }
937 
ProcessNonRLEData(bool in_rle,int num_pixels)938 BMPImageReader::ProcessingResult BMPImageReader::ProcessNonRLEData(
939     bool in_rle,
940     int num_pixels) {
941   if (decoded_offset_ > data_->size())
942     return kInsufficientData;
943 
944   if (!in_rle)
945     num_pixels = parent_->Size().Width();
946 
947   // Fail if we're being asked to decode more pixels than remain in the row.
948   const int end_x = coord_.X() + num_pixels;
949   if (end_x > parent_->Size().Width())
950     return kFailure;
951 
952   // Determine how many bytes of data the requested number of pixels
953   // requires.
954   const size_t pixels_per_byte = 8 / info_header_.bit_count;
955   const size_t bytes_per_pixel = info_header_.bit_count / 8;
956   const size_t unpadded_num_bytes =
957       (info_header_.bit_count < 16)
958           ? ((num_pixels + pixels_per_byte - 1) / pixels_per_byte)
959           : (num_pixels * bytes_per_pixel);
960   // RLE runs are zero-padded at the end to a multiple of 16 bits.  Non-RLE
961   // data is in rows and is zero-padded to a multiple of 32 bits.
962   const size_t align_bits = in_rle ? 1 : 3;
963   const size_t padded_num_bytes =
964       (unpadded_num_bytes + align_bits) & ~align_bits;
965 
966   // Decode as many rows as we can.  (For RLE, where we only want to decode
967   // one row, we've already checked that this condition is true.)
968   while (!PastEndOfImage(0)) {
969     // Bail if we don't have enough data for the desired number of pixels.
970     if ((data_->size() - decoded_offset_) < padded_num_bytes)
971       return kInsufficientData;
972 
973     if (info_header_.bit_count < 16) {
974       // Paletted data.  Pixels are stored little-endian within bytes.
975       // Decode pixels one byte at a time, left to right (so, starting at
976       // the most significant bits in the byte).
977       const uint8_t mask = (1 << info_header_.bit_count) - 1;
978       for (size_t end_offset = decoded_offset_ + unpadded_num_bytes;
979            decoded_offset_ < end_offset; ++decoded_offset_) {
980         uint8_t pixel_data = ReadUint8(0);
981         for (size_t pixel = 0;
982              (pixel < pixels_per_byte) && (coord_.X() < end_x); ++pixel) {
983           const wtf_size_t color_index =
984               (pixel_data >> (8 - info_header_.bit_count)) & mask;
985           if (decoding_and_mask_) {
986             // There's no way to accurately represent an AND + XOR
987             // operation as an RGBA image, so where the AND values
988             // are 1, we simply set the framebuffer pixels to fully
989             // transparent, on the assumption that most ICOs on the
990             // web will not be doing a lot of inverting.
991             if (color_index) {
992               SetRGBA(0, 0, 0, 0);
993               buffer_->SetHasAlpha(true);
994             } else {
995               coord_.Move(1, 0);
996             }
997           } else {
998             // See comments near the end of ProcessRLEData().
999             if (color_index < info_header_.clr_used)
1000               SetI(color_index);
1001             else
1002               SetRGBA(0, 0, 0, 255);
1003           }
1004           pixel_data <<= info_header_.bit_count;
1005         }
1006       }
1007     } else {
1008       // RGB data.  Decode pixels one at a time, left to right.
1009       for (; coord_.X() < end_x; decoded_offset_ += bytes_per_pixel) {
1010         const uint32_t pixel = ReadCurrentPixel(bytes_per_pixel);
1011 
1012         // Some BMPs specify an alpha channel but don't actually use it
1013         // (it contains all 0s).  To avoid displaying these images as
1014         // fully-transparent, decode as if images are fully opaque
1015         // until we actually see a non-zero alpha value; at that point,
1016         // reset any previously-decoded pixels to fully transparent and
1017         // continue decoding based on the real alpha channel values.
1018         // As an optimization, avoid calling SetHasAlpha(true) for
1019         // images where all alpha values are 255; opaque images are
1020         // faster to draw.
1021         int alpha = GetAlpha(pixel);
1022         if (!seen_non_zero_alpha_pixel_ && !alpha) {
1023           seen_zero_alpha_pixel_ = true;
1024           alpha = 255;
1025         } else {
1026           seen_non_zero_alpha_pixel_ = true;
1027           if (seen_zero_alpha_pixel_) {
1028             buffer_->ZeroFillPixelData();
1029             seen_zero_alpha_pixel_ = false;
1030           } else if (alpha != 255) {
1031             buffer_->SetHasAlpha(true);
1032           }
1033         }
1034 
1035         SetRGBA(GetComponent(pixel, 0), GetComponent(pixel, 1),
1036                 GetComponent(pixel, 2), alpha);
1037       }
1038     }
1039 
1040     // Success, keep going.
1041     decoded_offset_ += (padded_num_bytes - unpadded_num_bytes);
1042     if (in_rle)
1043       return kSuccess;
1044     ColorCorrectCurrentRow();
1045     MoveBufferToNextRow();
1046   }
1047 
1048   // Finished decoding whole image.
1049   return kSuccess;
1050 }
1051 
MoveBufferToNextRow()1052 void BMPImageReader::MoveBufferToNextRow() {
1053   coord_.Move(-coord_.X(), is_top_down_ ? 1 : -1);
1054 }
1055 
ColorCorrectCurrentRow()1056 void BMPImageReader::ColorCorrectCurrentRow() {
1057   if (decoding_and_mask_)
1058     return;
1059   // Postprocess the image data according to the profile.
1060   const ColorProfileTransform* const transform = parent_->ColorTransform();
1061   if (!transform)
1062     return;
1063   ImageFrame::PixelData* const row = buffer_->GetAddr(0, coord_.Y());
1064   const skcms_PixelFormat fmt = XformColorFormat();
1065   const skcms_AlphaFormat alpha =
1066       (buffer_->HasAlpha() && buffer_->PremultiplyAlpha())
1067           ? skcms_AlphaFormat_PremulAsEncoded
1068           : skcms_AlphaFormat_Unpremul;
1069   const bool success =
1070       skcms_Transform(row, fmt, alpha, transform->SrcProfile(), row, fmt, alpha,
1071                       transform->DstProfile(), parent_->Size().Width());
1072   DCHECK(success);
1073   buffer_->SetPixelsChanged(true);
1074 }
1075 
1076 }  // namespace blink
1077