psx emulator
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
2.2 KiB

  1. #include "boot.h"
  2. #include <assert.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include "cpu.h"
  7. #include "insn.h"
  8. #include "log.h"
  9. #include "psx.h"
  10. static const uint8_t MAGIC[0x10] = "PS-X EXE";
  11. static const uint8_t RESERVED[0x10] = {0};
  12. psx_header_t parse_psx_header(byte_arr_t *prgm) {
  13. psx_header_t header;
  14. // TODO: Convert asserts into recoverable error
  15. debug("Checking header struct size");
  16. assert(sizeof header == 0x38 - 0x10);
  17. debug("Checking program size is greater than header");
  18. assert(prgm->size >= 0x800);
  19. debug("Checking magic number in header");
  20. assert(memcmp(MAGIC, prgm->data, sizeof MAGIC) == 0);
  21. memcpy(&header, &prgm->data[sizeof MAGIC], sizeof header);
  22. debug("Checking file size in header matches program size");
  23. assert(header.size_file == prgm->size - 0x800);
  24. debug("Checking A34h region is zero");
  25. assert(memcmp(RESERVED, &prgm->data[0x38], sizeof RESERVED) == 0);
  26. return header;
  27. }
  28. uint32_t translate_addr(uint32_t addr) {
  29. if (addr >= 0xA0000000) {
  30. addr = addr - 0xA0000000;
  31. } else if (addr >= 0x80000000) {
  32. addr = addr - 0x80000000;
  33. }
  34. return addr;
  35. }
  36. void boot_psx_prgm(byte_arr_t *prgm) {
  37. debug("Parsing program header");
  38. psx_header_t header = parse_psx_header(prgm);
  39. debug("Program header");
  40. debug("size=%u bytes", header.size_file);
  41. debug("pc=%08x, gp=%08x, sp=%08x, fp=%08x", header.pc, header.gp, header.sp,
  42. header.fp);
  43. debug("data=%08x (%u bytes)", header.addr_data, header.size_data);
  44. debug("bss=%08x (%u bytes)", header.addr_bss, header.size_bss);
  45. debug("dest=%08x", header.addr_dest);
  46. cpu_t *cpu = malloc(sizeof *cpu);
  47. uint32_t start = translate_addr(header.addr_dest);
  48. assert(start + header.size_file < MAIN_RAM_SIZE);
  49. memcpy(&cpu->main_ram[start], &prgm->data[0x800], header.size_file);
  50. cpu->pc = header.pc;
  51. cpu->regs[REG_GP] = header.gp;
  52. cpu->regs[REG_SP] = header.sp;
  53. cpu->regs[REG_FP] = header.fp;
  54. psx_t psx = {header, cpu};
  55. while (1) {
  56. debug("Executing instruction at %08x", psx.cpu->pc);
  57. const uint32_t insn = cpu_read32(cpu, psx.cpu->pc);
  58. insn_execute(cpu, insn);
  59. psx.cpu->pc += 1;
  60. }
  61. }