1/*
2 * Copyright 2012 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "SkBitmap.h"
9#include "SkDeduper.h"
10#include "SkImage.h"
11#include "SkImageDeserializer.h"
12#include "SkImageGenerator.h"
13#include "SkMakeUnique.h"
14#include "SkReadBuffer.h"
15#include "SkStream.h"
16#include "SkTypeface.h"
17
18namespace {
19
20    // This generator intentionally should always fail on all attempts to get its pixels,
21    // simulating a bad or empty codec stream.
22    class EmptyImageGenerator final : public SkImageGenerator {
23    public:
24        EmptyImageGenerator(const SkImageInfo& info) : INHERITED(info) { }
25
26    private:
27        typedef SkImageGenerator INHERITED;
28    };
29
30    static sk_sp<SkImage> MakeEmptyImage(int width, int height) {
31        return SkImage::MakeFromGenerator(
32              skstd::make_unique<EmptyImageGenerator>(SkImageInfo::MakeN32Premul(width, height)));
33    }
34
35} // anonymous namespace
36
37
38static uint32_t default_flags() {
39    uint32_t flags = 0;
40    flags |= SkReadBuffer::kScalarIsFloat_Flag;
41    if (8 == sizeof(void*)) {
42        flags |= SkReadBuffer::kPtrIs64Bit_Flag;
43    }
44    return flags;
45}
46
47// This has an empty constructor and destructor, and is thread-safe, so we can use a singleton.
48static SkImageDeserializer gDefaultImageDeserializer;
49
50SkReadBuffer::SkReadBuffer() {
51    fFlags = default_flags();
52    fVersion = 0;
53    fMemoryPtr = nullptr;
54
55    fTFArray = nullptr;
56    fTFCount = 0;
57
58    fFactoryArray = nullptr;
59    fFactoryCount = 0;
60    fImageDeserializer = &gDefaultImageDeserializer;
61#ifdef DEBUG_NON_DETERMINISTIC_ASSERT
62    fDecodedBitmapIndex = -1;
63#endif // DEBUG_NON_DETERMINISTIC_ASSERT
64}
65
66SkReadBuffer::SkReadBuffer(const void* data, size_t size) {
67    fFlags = default_flags();
68    fVersion = 0;
69    fReader.setMemory(data, size);
70    fMemoryPtr = nullptr;
71
72    fTFArray = nullptr;
73    fTFCount = 0;
74
75    fFactoryArray = nullptr;
76    fFactoryCount = 0;
77    fImageDeserializer = &gDefaultImageDeserializer;
78#ifdef DEBUG_NON_DETERMINISTIC_ASSERT
79    fDecodedBitmapIndex = -1;
80#endif // DEBUG_NON_DETERMINISTIC_ASSERT
81}
82
83SkReadBuffer::SkReadBuffer(SkStream* stream) {
84    fFlags = default_flags();
85    fVersion = 0;
86    const size_t length = stream->getLength();
87    fMemoryPtr = sk_malloc_throw(length);
88    stream->read(fMemoryPtr, length);
89    fReader.setMemory(fMemoryPtr, length);
90
91    fTFArray = nullptr;
92    fTFCount = 0;
93
94    fFactoryArray = nullptr;
95    fFactoryCount = 0;
96    fImageDeserializer = &gDefaultImageDeserializer;
97#ifdef DEBUG_NON_DETERMINISTIC_ASSERT
98    fDecodedBitmapIndex = -1;
99#endif // DEBUG_NON_DETERMINISTIC_ASSERT
100}
101
102SkReadBuffer::~SkReadBuffer() {
103    sk_free(fMemoryPtr);
104}
105
106void SkReadBuffer::setImageDeserializer(SkImageDeserializer* deserializer) {
107    fImageDeserializer = deserializer ? deserializer : &gDefaultImageDeserializer;
108}
109
110bool SkReadBuffer::readBool() {
111    return fReader.readBool();
112}
113
114SkColor SkReadBuffer::readColor() {
115    return fReader.readInt();
116}
117
118int32_t SkReadBuffer::readInt() {
119    return fReader.readInt();
120}
121
122SkScalar SkReadBuffer::readScalar() {
123    return fReader.readScalar();
124}
125
126uint32_t SkReadBuffer::readUInt() {
127    return fReader.readU32();
128}
129
130int32_t SkReadBuffer::read32() {
131    return fReader.readInt();
132}
133
134uint8_t SkReadBuffer::peekByte() {
135    SkASSERT(fReader.available() > 0);
136    return *((uint8_t*) fReader.peek());
137}
138
139void SkReadBuffer::readString(SkString* string) {
140    size_t len;
141    const char* strContents = fReader.readString(&len);
142    string->set(strContents, len);
143}
144
145void SkReadBuffer::readColor4f(SkColor4f* color) {
146    memcpy(color, fReader.skip(sizeof(SkColor4f)), sizeof(SkColor4f));
147}
148
149void SkReadBuffer::readPoint(SkPoint* point) {
150    point->fX = fReader.readScalar();
151    point->fY = fReader.readScalar();
152}
153
154void SkReadBuffer::readMatrix(SkMatrix* matrix) {
155    fReader.readMatrix(matrix);
156}
157
158void SkReadBuffer::readIRect(SkIRect* rect) {
159    memcpy(rect, fReader.skip(sizeof(SkIRect)), sizeof(SkIRect));
160}
161
162void SkReadBuffer::readRect(SkRect* rect) {
163    memcpy(rect, fReader.skip(sizeof(SkRect)), sizeof(SkRect));
164}
165
166void SkReadBuffer::readRRect(SkRRect* rrect) {
167    fReader.readRRect(rrect);
168}
169
170void SkReadBuffer::readRegion(SkRegion* region) {
171    fReader.readRegion(region);
172}
173
174void SkReadBuffer::readPath(SkPath* path) {
175    fReader.readPath(path);
176}
177
178bool SkReadBuffer::readArray(void* value, size_t size, size_t elementSize) {
179    const size_t count = this->getArrayCount();
180    if (count == size) {
181        (void)fReader.skip(sizeof(uint32_t)); // Skip array count
182        const size_t byteLength = count * elementSize;
183        memcpy(value, fReader.skip(SkAlign4(byteLength)), byteLength);
184        return true;
185    }
186    SkASSERT(false);
187    fReader.skip(fReader.available());
188    return false;
189}
190
191bool SkReadBuffer::readByteArray(void* value, size_t size) {
192    return readArray(static_cast<unsigned char*>(value), size, sizeof(unsigned char));
193}
194
195bool SkReadBuffer::readColorArray(SkColor* colors, size_t size) {
196    return readArray(colors, size, sizeof(SkColor));
197}
198
199bool SkReadBuffer::readColor4fArray(SkColor4f* colors, size_t size) {
200    return readArray(colors, size, sizeof(SkColor4f));
201}
202
203bool SkReadBuffer::readIntArray(int32_t* values, size_t size) {
204    return readArray(values, size, sizeof(int32_t));
205}
206
207bool SkReadBuffer::readPointArray(SkPoint* points, size_t size) {
208    return readArray(points, size, sizeof(SkPoint));
209}
210
211bool SkReadBuffer::readScalarArray(SkScalar* values, size_t size) {
212    return readArray(values, size, sizeof(SkScalar));
213}
214
215uint32_t SkReadBuffer::getArrayCount() {
216    return *(uint32_t*)fReader.peek();
217}
218
219sk_sp<SkImage> SkReadBuffer::readBitmapAsImage() {
220    const int width = this->readInt();
221    const int height = this->readInt();
222
223    // The writer stored a boolean value to determine whether an SkBitmapHeap was used during
224    // writing. That feature is deprecated.
225    if (this->readBool()) {
226        this->readUInt(); // Bitmap index
227        this->readUInt(); // Bitmap generation ID
228        // Old unsupported SkBitmapHeap format.  No longer supported.
229    } else {
230        // The writer stored false, meaning the SkBitmap was not stored in an SkBitmapHeap.
231        const size_t length = this->readUInt();
232        if (length > 0) {
233#ifdef DEBUG_NON_DETERMINISTIC_ASSERT
234            fDecodedBitmapIndex++;
235#endif // DEBUG_NON_DETERMINISTIC_ASSERT
236            // A non-zero size means the SkBitmap was encoded. Read the data and pixel
237            // offset.
238            const void* data = this->skip(length);
239            const int32_t xOffset = this->readInt();
240            const int32_t yOffset = this->readInt();
241            SkIRect subset = SkIRect::MakeXYWH(xOffset, yOffset, width, height);
242            sk_sp<SkImage> image = fImageDeserializer->makeFromMemory(data, length, &subset);
243            if (image) {
244                return image;
245            }
246
247            // This bitmap was encoded when written, but we are unable to
248            // decode, possibly due to not having a decoder.  Even though we
249            // weren't able to decode the pixels, the readbuffer should still
250            // be intact, so we return true with an empty bitmap, so we don't
251            // force an abort of the larger deserialize.
252            return MakeEmptyImage(width, height);
253        } else {
254            SkBitmap bitmap;
255            if (SkBitmap::ReadRawPixels(this, &bitmap)) {
256                bitmap.setImmutable();
257                return SkImage::MakeFromBitmap(bitmap);
258            }
259        }
260    }
261    // Could not read the SkBitmap. Use a placeholder bitmap.
262    return nullptr;
263}
264
265sk_sp<SkImage> SkReadBuffer::readImage() {
266    if (fInflator) {
267        SkImage* img = fInflator->getImage(this->read32());
268        return img ? sk_ref_sp(img) : nullptr;
269    }
270
271    int width = this->read32();
272    int height = this->read32();
273    if (width <= 0 || height <= 0) {    // SkImage never has a zero dimension
274        this->validate(false);
275        return nullptr;
276    }
277
278    uint32_t encoded_size = this->getArrayCount();
279    if (encoded_size == 0) {
280        // The image could not be encoded at serialization time - return an empty placeholder.
281        (void)this->readUInt();  // Swallow that encoded_size == 0 sentinel.
282        return MakeEmptyImage(width, height);
283    }
284    if (encoded_size == 1) {
285        // We had to encode the image as raw pixels via SkBitmap.
286        (void)this->readUInt();  // Swallow that encoded_size == 1 sentinel.
287        SkBitmap bm;
288        if (SkBitmap::ReadRawPixels(this, &bm)) {
289            return SkImage::MakeFromBitmap(bm);
290        }
291        return MakeEmptyImage(width, height);
292    }
293
294    // The SkImage encoded itself.
295    sk_sp<SkData> encoded(this->readByteArrayAsData());
296
297    int originX = this->read32();
298    int originY = this->read32();
299    if (originX < 0 || originY < 0) {
300        this->validate(false);
301        return nullptr;
302    }
303
304    const SkIRect subset = SkIRect::MakeXYWH(originX, originY, width, height);
305
306    sk_sp<SkImage> image = fImageDeserializer->makeFromData(encoded.get(), &subset);
307    return image ? image : MakeEmptyImage(width, height);
308}
309
310sk_sp<SkTypeface> SkReadBuffer::readTypeface() {
311    if (fInflator) {
312        return sk_ref_sp(fInflator->getTypeface(this->read32()));
313    }
314
315    uint32_t index = this->readUInt();
316    if (0 == index || index > (unsigned)fTFCount) {
317        return nullptr;
318    } else {
319        SkASSERT(fTFArray);
320        return sk_ref_sp(fTFArray[index - 1]);
321    }
322}
323
324SkFlattenable* SkReadBuffer::readFlattenable(SkFlattenable::Type ft) {
325    //
326    // TODO: confirm that ft matches the factory we decide to use
327    //
328
329    SkFlattenable::Factory factory = nullptr;
330
331    if (fInflator) {
332        factory = fInflator->getFactory(this->read32());
333        if (!factory) {
334            return nullptr;
335        }
336    } else if (fFactoryCount > 0) {
337        int32_t index = fReader.readU32();
338        if (0 == index) {
339            return nullptr; // writer failed to give us the flattenable
340        }
341        index -= 1;     // we stored the index-base-1
342        if ((unsigned)index >= (unsigned)fFactoryCount) {
343            this->validate(false);
344            return nullptr;
345        }
346        factory = fFactoryArray[index];
347    } else {
348        SkString name;
349        if (this->peekByte()) {
350            // If the first byte is non-zero, the flattenable is specified by a string.
351            this->readString(&name);
352
353            // Add the string to the dictionary.
354            fFlattenableDict.set(fFlattenableDict.count() + 1, name);
355        } else {
356            // Read the index.  We are guaranteed that the first byte
357            // is zeroed, so we must shift down a byte.
358            uint32_t index = fReader.readU32() >> 8;
359            if (0 == index) {
360                return nullptr; // writer failed to give us the flattenable
361            }
362
363            SkString* namePtr = fFlattenableDict.find(index);
364            SkASSERT(namePtr);
365            name = *namePtr;
366        }
367
368        // Check if a custom Factory has been specified for this flattenable.
369        if (!(factory = this->getCustomFactory(name))) {
370            // If there is no custom Factory, check for a default.
371            if (!(factory = SkFlattenable::NameToFactory(name.c_str()))) {
372                return nullptr; // writer failed to give us the flattenable
373            }
374        }
375    }
376
377    // if we get here, factory may still be null, but if that is the case, the
378    // failure was ours, not the writer.
379    sk_sp<SkFlattenable> obj;
380    uint32_t sizeRecorded = fReader.readU32();
381    if (factory) {
382        size_t offset = fReader.offset();
383        obj = (*factory)(*this);
384        // check that we read the amount we expected
385        size_t sizeRead = fReader.offset() - offset;
386        if (sizeRecorded != sizeRead) {
387            this->validate(false);
388            return nullptr;
389        }
390    } else {
391        // we must skip the remaining data
392        fReader.skip(sizeRecorded);
393    }
394    return obj.release();
395}
396