/**
 * Copyright (C) 2021 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 <FontUtils.h>
#include <unistd.h>
#include "../includes/common.h"
#include "../includes/memutils.h"

using namespace minikin;

char enable_selective_overload = ENABLE_NONE;

bool isTestInProgress = false;

struct sigaction new_action, old_action;

void sigsegv_handler(int signum, siginfo_t *info, void* context) {
    if (isTestInProgress && info->si_signo == SIGSEGV) {
        (*old_action.sa_sigaction)(signum, info, context);
        return;
    }
    _exit (EXIT_FAILURE);
}

int main() {
    sigemptyset(&new_action.sa_mask);
    new_action.sa_flags = SA_SIGINFO;
    new_action.sa_sigaction = sigsegv_handler;
    sigaction(SIGSEGV, &new_action, &old_action);

    uint8_t majorVersion = 1;
    uint8_t minorVersion = 0;
    uint8_t axisOffset = 0x10;
    uint8_t axisCount = 0xFF;
    uint8_t axisSize = 0x14;

    size_t allocatedSize = sizeof(uint8_t) * 16;
    enable_selective_overload = ENABLE_ALL;
    uint8_t* fvarData = (uint8_t*) malloc(allocatedSize);
    enable_selective_overload = ENABLE_FREE_CHECK | ENABLE_REALLOC_CHECK;
    FAIL_CHECK(fvarData);
    memset(fvarData, 0x0, allocatedSize);

    fvarData[1] = majorVersion;
    fvarData[3] = minorVersion;
    fvarData[5] = axisOffset;
    fvarData[8] = axisCount;
    fvarData[9] = axisCount;
    fvarData[11] = axisSize;

    size_t fvarSize = axisOffset + axisOffset * ((axisCount << 8) | axisCount);
    std::unordered_set < uint32_t > axes;
    isTestInProgress = true;
    analyzeAxes(fvarData, fvarSize, &axes);
    isTestInProgress = false;
    free(fvarData);
    return EXIT_SUCCESS;
}
