/*
 * 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 "../includes/common.h"
#include "../includes/memutils.h"
#include "nfc_types.h"
#include "rw_int.h"
#include "sys/types.h"
#include "tags_defs.h"
#include <stdint.h>
#include <sys/sysinfo.h>
#include <vector>

void rw_i93_send_to_upper(NFC_HDR *p_resp);

struct sysinfo memInfo;
extern tRW_CB rw_cb;
std ::vector<uint8_t> p_buff;
std ::vector<uint8_t> v_pmsg;
char enable_selective_overload = ENABLE_NONE;

void poc_cback(tRW_EVENT /* event */, tRW_DATA * /* p_rw_data */) {}

void *GKI_getbuf(uint16_t size) {
  enable_selective_overload = ENABLE_ALL;
  p_buff.resize(size);
  enable_selective_overload = ENABLE_FREE_CHECK | ENABLE_REALLOC_CHECK;
  return (void *)p_buff.data();
}

int main() {
  // Check if there is structure mismatch between testing library and the
  // library that is being tested
  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();

  // find the free memory available
  sysinfo(&memInfo);
  unsigned long long freeVirtualMem = memInfo.freeram;
  freeVirtualMem += memInfo.freeswap;
  freeVirtualMem *= memInfo.mem_unit;
  FAIL_CHECK((sizeof(NFC_HDR) + UINT16_MAX) < freeVirtualMem * 0.8);

  // Call rw_i93_send_to_upper() with large value of p_msg->len
  v_pmsg.resize(sizeof(NFC_HDR) + UINT16_MAX);
  NFC_HDR *p_msg = (NFC_HDR *)v_pmsg.data();
  rw_cb.tcb.i93.sent_cmd = I93_CMD_READ_SINGLE_BLOCK;
  p_msg->offset = 0;
  p_msg->len = UINT16_MAX;
  rw_cb.p_cback = &poc_cback;
  rw_i93_send_to_upper(p_msg);
  return EXIT_SUCCESS;
}
