/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include <cassert>
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>

#include "se_defines.h"

SE_GLOBALS()

struct input {
  size_t sz;
  char buf[8];
};

void test_case(std::string content) {
  if (content.length() < sizeof(input)) {
    // Input is small
    return;
  }

  input* i = (input*)content.data();

  printf("i->sz: %zx\n", i->sz);

  if (i->sz < 8) {
    // Too small
    return;
  }

  int dummy_var = 0xdeadbeef;

  char buffer[i->sz]; // Dynamic stack allocation
  memcpy(buffer, i->buf, 8);

  printf("Addr of dummy_var: %p\n", &dummy_var);
  printf("Addr of buffer: %p\n", buffer);

  if (dummy_var != 0xdeadbeef) {
    SE_STEP(true);
  }

  if (dummy_var == 0xaaaaaaaa) {
    SE_TARGET_STATE(true);
  }
}

int main(int argc, char* argv[]) {
  std::istream* input;
  std::ifstream file;
  if (argc < 2) {
    input = &std::cin; // No file name provided, read from stdin
  } else {
    file.open(argv[1]);
    if (!file) {
      std::cerr << "Could not open the file.\n";
      return 1;
    }
    input = &file; // File opened successfully, read from file
  }
  std::string content(
      (std::istreambuf_iterator<char>(*input)),
      std::istreambuf_iterator<char>());
  test_case(content);
  return 0;
}
