/*
 * Copyright (C) 2022 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 "../includes/memutils.h"

#include <nfc_int.h>
#include <rw_int.h>

constexpr size_t kBufferSize = 16;
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);
}

void poc_cback(tRW_EVENT, tRW_DATA*) {
}

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);

    tNFC_ACTIVATE_DEVT p_activate_params = { };
    p_activate_params.protocol = NFC_PROTOCOL_ISO_DEP;
    p_activate_params.rf_tech_param.mode = NFC_DISCOVERY_TYPE_POLL_A;
    RW_SetActivatedTagType(&p_activate_params, &poc_cback);
    FAIL_CHECK(rw_cb.p_cback == &poc_cback);

    GKI_init();
    rw_init();
    uint16_t bufLen = 0;
    enable_selective_overload = ENABLE_ALL;
    uint8_t* buffer = (uint8_t*)malloc(sizeof(uint8_t) * kBufferSize);
    FAIL_CHECK(buffer);
    uint8_t* buffer_ptr = buffer;
    buffer = buffer + kBufferSize;

    isTestInProgress = true;
    nfc_ncif_proc_ee_discover_req(buffer, bufLen);
    enable_selective_overload = ENABLE_FREE_CHECK | ENABLE_REALLOC_CHECK;
    isTestInProgress = false;

    free(buffer_ptr);
    return EXIT_SUCCESS;
}
