/*
 * Copyright (C) 2025 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 "../includes/common.h"
#include "binary_loader.h"

size_t kItems = 2;
size_t kSize = SIZE_MAX;
void* kAddress = &kItems;

typedef void* (*skia_alloc_func)(void*, unsigned long, unsigned long);

void* calloc(size_t item, size_t size) {
    if (item * size == kItems * kSize) {
        return kAddress;
    }

    // memset to imitate actual calloc() call
    void* ptr = malloc(item * size);
    memset(ptr, 0, item * size);
    return ptr;
}

int main(int /* argc */, char* argv[]) {
    // Get the path to the shared library and offset from command-line arguments
    const char* libPath = argv[1];
    const uintptr_t functionOffset = strtoul(argv[2], nullptr, 0) + 1;

    // Get function address of 'skia_alloc_func()' from loaded library
    BinaryLoader binaryLoader(libPath);
    const uintptr_t functionAddress = binaryLoader.getFunctionAddress(functionOffset);
    FAIL_CHECK(functionAddress);

    // Create function pointer to 'skia_alloc_func()'
    skia_alloc_func skia_alloc_ptr = (skia_alloc_func)functionAddress;

    // Call vulnerable function. Without fix, function returns pointer from the overloaded calloc().
    // With Fix, null pointer is returned.
    void* result = skia_alloc_ptr(nullptr, kItems, kSize);
    if (result == nullptr) {
        return EXIT_SUCCESS;
    }
    if (result == kAddress) {
        return EXIT_VULNERABLE;
    }
    return EXIT_FAILURE;
}
