1/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "unflatten/ResChunkPullParser.h"
18#include "util/Util.h"
19
20#include <androidfw/ResourceTypes.h>
21#include <cstddef>
22
23namespace aapt {
24
25using android::ResChunk_header;
26
27ResChunkPullParser::Event ResChunkPullParser::next() {
28    if (!isGoodEvent(mEvent)) {
29        return mEvent;
30    }
31
32    if (mEvent == Event::StartDocument) {
33        mCurrentChunk = mData;
34    } else {
35        mCurrentChunk = (const ResChunk_header*)
36                (((const char*) mCurrentChunk) + util::deviceToHost32(mCurrentChunk->size));
37    }
38
39    const std::ptrdiff_t diff = (const char*) mCurrentChunk - (const char*) mData;
40    assert(diff >= 0 && "diff is negative");
41    const size_t offset = static_cast<const size_t>(diff);
42
43    if (offset == mLen) {
44        mCurrentChunk = nullptr;
45        return (mEvent = Event::EndDocument);
46    } else if (offset + sizeof(ResChunk_header) > mLen) {
47        mLastError = "chunk is past the end of the document";
48        mCurrentChunk = nullptr;
49        return (mEvent = Event::BadDocument);
50    }
51
52    if (util::deviceToHost16(mCurrentChunk->headerSize) < sizeof(ResChunk_header)) {
53        mLastError = "chunk has too small header";
54        mCurrentChunk = nullptr;
55        return (mEvent = Event::BadDocument);
56    } else if (util::deviceToHost32(mCurrentChunk->size) <
57            util::deviceToHost16(mCurrentChunk->headerSize)) {
58        mLastError = "chunk's total size is smaller than header";
59        mCurrentChunk = nullptr;
60        return (mEvent = Event::BadDocument);
61    } else if (offset + util::deviceToHost32(mCurrentChunk->size) > mLen) {
62        mLastError = "chunk's data extends past the end of the document";
63        mCurrentChunk = nullptr;
64        return (mEvent = Event::BadDocument);
65    }
66    return (mEvent = Event::Chunk);
67}
68
69} // namespace aapt
70