
#include "stdio.h"
#include "errno.h"
#include "stdlib.h"
#include "string.h"
#include "debug.h"
#include "../main.h"

#include "../riscv_cpu/riscv.h"
// cpu外设
#include "../riscv_cpu/print.h"
#include "../riscv_cpu/timer.h"


long get_file_size(FILE *stream)
{
	long file_size = -1;
	long cur_offset = ftell(stream);	// 获取当前偏移位置
	if (cur_offset == -1) {
		DBG_LOG("ftell failed :%s\n", strerror(errno));
		return -1;
	}
	if (fseek(stream, 0, SEEK_END) != 0) {	// 移动文件指针到文件末尾
		DBG_LOG("fseek failed: %s\n", strerror(errno));
		return -1;
	}
	file_size = ftell(stream);	// 获取此时偏移值，即文件大小
	if (file_size == -1) {
		DBG_LOG("ftell failed :%s\n", strerror(errno));
	}
	if (fseek(stream, cur_offset, SEEK_SET) != 0) {	// 将文件指针恢复初始位置
		DBG_LOG("fseek failed: %s\n", strerror(errno));
		return -1;
	}
	return file_size;
}



riscv_t riscv = { 0 };


int thread_fun(void* t)
{
  int argc;
  char** argv;
  argc = get_argv(&argv);

  char *bin_name="riscv.bin";
  if(argc>1){
    bin_name=argv[1];
  }

  DBG_LOG("riscv start\n");
  FILE *file=fopen(bin_name, "rb" );
  if(file==NULL)
  {
    DBG_LOG("open file %s error\n",bin_name);
    return -1;
  }
  riscv.rom_size = get_file_size(file);
  DBG_LOG("rom size: %d\n", riscv.rom_size);
  riscv.rom = calloc((riscv.rom_size + 3) / 4, 4);
  fread(riscv.rom, 1, riscv.rom_size, file);
  fclose(file);

  riscv_register_device(&riscv, print_dev());
  riscv_register_device(&riscv, timer_dev());
  riscv_init(&riscv, riscv.rom, 0x80000000, riscv.rom_size);
  riscv_device_init(&riscv);
  riscv_run(&riscv);

  return 0;
}


