/*
 * Copyright (C) 2024 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 <dlfcn.h>
#include <stdlib.h>

#include "../includes/common.h"
#include "../includes/memutils.h"
#include "nci_hmsgs.h"

#define BUFFER_SIZE 16
#define OVERFLOWED_VALUE 2

char enable_selective_overload = ENABLE_NONE;

static void (*real_GKI_freebuf)(void *ptr) = nullptr;
static void *(*real_GKI_getpoolbuf)(uint8_t pool_id) = nullptr;
char *buffer = nullptr;

void init(void) {
    real_GKI_freebuf = (void (*)(void *))dlsym(RTLD_NEXT, "_Z11GKI_freebufPv");
    real_GKI_getpoolbuf = (void *(*)(uint8_t))dlsym(RTLD_NEXT, "_Z14GKI_getpoolbufh");
    FAIL_CHECK(real_GKI_freebuf);
    FAIL_CHECK(real_GKI_getpoolbuf);
}

void *GKI_getpoolbuf(uint8_t pool_id) {
    if (pool_id == OVERFLOWED_VALUE) {
        buffer = (char *)malloc(BUFFER_SIZE);
        return (void *)(buffer + BUFFER_SIZE - OVERFLOWED_VALUE);
    }
    return real_GKI_getpoolbuf(pool_id);
}

void GKI_freebuf(void *ptr) {
    if (buffer) {
        if (ptr == (void *)(buffer + BUFFER_SIZE - OVERFLOWED_VALUE)) {
            free(buffer);
            buffer = nullptr;
            return;
        }
    }
    real_GKI_freebuf(ptr);
}

int main() {
    uint8_t p_param_tlvs[UINT8_MAX];

    // tlv_size is set to UINT8_MAX which leads to an integer overflow. The fix returns if the
    // integer oveflow is observed. Without fix, a buffer of size 2 (which is less than required)
    // gets allocated. This leads to a OOB access in nci_snd_set_routing_cmd and a SIG_SEGV occurs
    // which leads to test failure.
    init();
    enable_selective_overload = ENABLE_ALL;
    nci_snd_set_routing_cmd(false /* more */, 0 /* num_tlv */, UINT8_MAX, p_param_tlvs);
    enable_selective_overload = ENABLE_FREE_CHECK | ENABLE_REALLOC_CHECK;
    return EXIT_SUCCESS;
}
