An emulator, assembler, and disassembler for the Sega Game Gear
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.
 
 
 
 
 

396 regels
11 KiB

  1. /* Copyright (C) 2014-2016 Ben Kurtovic <ben.kurtovic@gmail.com>
  2. Released under the terms of the MIT License. See LICENSE for details. */
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <time.h>
  7. #include "disassembler.h"
  8. #include "disassembler/arguments.h"
  9. #include "disassembler/mnemonics.h"
  10. #include "disassembler/sizes.h"
  11. #include "mmu.h"
  12. #include "rom.h"
  13. #include "util.h"
  14. #include "version.h"
  15. #define HRULE \
  16. "----------------------------------------------------------------------------"
  17. #define NUM_BANKS(rom) \
  18. (((rom)->size + MMU_ROM_BANK_SIZE - 1) / MMU_ROM_BANK_SIZE)
  19. #define MAX_BYTES_PER_LINE 16
  20. /* Structs and things */
  21. typedef struct {
  22. size_t cap, len;
  23. char **lines;
  24. } Disassembly;
  25. typedef enum {
  26. DT_BINARY = 0,
  27. DT_CODE,
  28. DT_HEADER
  29. } DataType;
  30. typedef struct {
  31. const uint8_t *data;
  32. DataType *types;
  33. size_t size;
  34. int8_t slot;
  35. } ROMBank;
  36. /*
  37. Format a sequence of bytes of a certain length as a pretty string.
  38. The result must be freed by the caller.
  39. */
  40. static char* format_bytestring(const uint8_t *bytes, size_t size)
  41. {
  42. // TODO: smarter alignment; pad to full len (then remove pad from TRACE())
  43. if (!size)
  44. return NULL;
  45. char *str = cr_malloc(sizeof(char) * (3 * size));
  46. size_t i;
  47. for (i = 0; i < size; i++) {
  48. snprintf(&str[3 * i], 3, "%02X", bytes[i]);
  49. str[3 * i + 2] = ' ';
  50. }
  51. str[3 * size - 1] = '\0';
  52. return str;
  53. }
  54. /*
  55. Free the given DisasInstr struct.
  56. */
  57. void disas_instr_free(DisasInstr *instr)
  58. {
  59. free(instr->bytestr);
  60. free(instr->line);
  61. free(instr);
  62. }
  63. /*
  64. Disassemble a single instruction starting at the given address.
  65. Return a dynamically allocated structure containing various interesting
  66. fields. This must be freed by the user with disas_instr_free().
  67. */
  68. DisasInstr* disassemble_instruction(const uint8_t *bytes)
  69. {
  70. size_t size = get_instr_size(bytes);
  71. char *bytestr = format_bytestring(bytes, size);
  72. char *mnemonic = decode_mnemonic(bytes);
  73. char *args = decode_arguments(bytes);
  74. char *line;
  75. if (args) {
  76. line = cr_malloc(strlen(mnemonic) + strlen(args) + 2);
  77. sprintf(line, "%s\t%s", mnemonic, args);
  78. free(args);
  79. } else {
  80. line = cr_strdup(mnemonic);
  81. }
  82. DisasInstr *instr = cr_malloc(sizeof(DisasInstr));
  83. instr->size = size;
  84. instr->bytestr = bytestr;
  85. instr->line = line;
  86. return instr;
  87. }
  88. /*
  89. Append a line to the end of a disassembly.
  90. */
  91. static void write_line(Disassembly *dis, char *line)
  92. {
  93. dis->lines[dis->len++] = line;
  94. if (dis->len >= dis->cap) {
  95. dis->cap *= 2;
  96. dis->lines = cr_realloc(dis->lines, sizeof(char*) * dis->cap);
  97. }
  98. }
  99. /*
  100. Macro that wraps write_line() in a printf-like interface.
  101. */
  102. #define WRITE_LINE_(dis, fmt, ...) \
  103. do { \
  104. char *tmp_buffer_; \
  105. if (asprintf(&tmp_buffer_, fmt "\n", __VA_ARGS__) < 0) \
  106. OUT_OF_MEMORY() \
  107. write_line(dis, tmp_buffer_); \
  108. } while(0);
  109. #define WRITE_LINE(dis, ...) WRITE_LINE_(dis, __VA_ARGS__, NULL)
  110. /*
  111. Write some metadata comments to the top of the disassembly.
  112. */
  113. static void write_metadata(Disassembly *dis, const ROM *rom)
  114. {
  115. time_t t;
  116. struct tm *tm_info;
  117. char buf[64];
  118. time(&t);
  119. tm_info = localtime(&t);
  120. strftime(buf, sizeof buf, "on %a %b %d, %Y at %H:%M:%S", tm_info);
  121. WRITE_LINE(dis, ";; GAME GEAR ROM DISASSEMBLY")
  122. WRITE_LINE(dis, ";; File: %s", rom->name)
  123. WRITE_LINE(dis, ";; Generated %s by crater %s", buf, CRATER_VERSION)
  124. WRITE_LINE(dis, ";; " HRULE)
  125. WRITE_LINE(dis, "")
  126. }
  127. /*
  128. Given a size, fill 'output' with a pretty string. Modified from rom.c.
  129. */
  130. static char* size_to_string(char *output, size_t size)
  131. {
  132. if (size >= (1 << 20))
  133. sprintf(output, "%zu MB", size >> 20);
  134. else
  135. sprintf(output, "%zu KB", size >> 10);
  136. return output;
  137. }
  138. /*
  139. Extract appropriate assembler directives from a ROM's header.
  140. */
  141. static void disassemble_header(Disassembly *dis, const ROM *rom)
  142. {
  143. char buf[64];
  144. const char *size, *product, *region;
  145. DEBUG("Disassembling header")
  146. size = size_to_string(buf, rom->size);
  147. product = rom_product(rom);
  148. region = rom_region(rom);
  149. WRITE_LINE(dis, ".rom_size\t\"%s\"%s\t; $%zX bytes in %zu banks",
  150. size, strlen(size) < 6 ? "\t" : "", rom->size, NUM_BANKS(rom))
  151. WRITE_LINE(dis, ".rom_header\t$%04X",
  152. rom->header_location)
  153. WRITE_LINE(dis, ".rom_checksum\t%s",
  154. (rom->reported_checksum == rom->expected_checksum) ? "on" : "off")
  155. WRITE_LINE(dis, ".rom_product\t%u\t\t; %s",
  156. rom->product_code, product ? product : "(unknown)")
  157. WRITE_LINE(dis, ".rom_version\t%u",
  158. rom->version)
  159. WRITE_LINE(dis, ".rom_region\t%u\t\t; %s",
  160. rom->region_code, region ? region : "(unknown)")
  161. WRITE_LINE(dis, ".rom_declsize\t$%X\t\t; %s",
  162. rom->declared_size,
  163. size_to_string(buf, size_code_to_bytes(rom->declared_size)))
  164. }
  165. /*
  166. Initialize and return an array of ROMBank objects for the given ROM.
  167. */
  168. static ROMBank* init_banks(const ROM *rom)
  169. {
  170. size_t nbanks = NUM_BANKS(rom), i;
  171. ROMBank *banks = cr_malloc(sizeof(ROMBank) * (nbanks + 1));
  172. DataType *types = cr_calloc(sizeof(DataType), rom->size);
  173. for (i = 0; i < nbanks; i++) {
  174. if (i == nbanks - 1 && rom->size % MMU_ROM_BANK_SIZE)
  175. banks[i].size = rom->size % MMU_ROM_BANK_SIZE;
  176. else
  177. banks[i].size = MMU_ROM_BANK_SIZE;
  178. banks[i].data = rom->data + (i * MMU_ROM_BANK_SIZE);
  179. banks[i].types = types + (i * MMU_ROM_BANK_SIZE);
  180. banks[i].slot = -1;
  181. }
  182. banks[nbanks].data = NULL; // Sentinel
  183. return banks;
  184. }
  185. /*
  186. Deallocate the given array of ROM banks.
  187. */
  188. static void free_banks(ROMBank *banks)
  189. {
  190. free(banks[0].types);
  191. free(banks);
  192. }
  193. /*
  194. Mark the ROM's header as non-binary/non-code inside of the relevant bank.
  195. */
  196. static void mark_header(const ROM *rom, ROMBank *banks)
  197. {
  198. size_t i;
  199. for (i = 0; i < HEADER_SIZE; i++)
  200. banks[0].types[rom->header_location + i] = DT_HEADER;
  201. }
  202. /*
  203. Render a line of binary data within a block.
  204. */
  205. static void render_binary(Disassembly *dis, size_t *idx, const ROMBank *bank)
  206. {
  207. size_t span = 1, i;
  208. while (span < MAX_BYTES_PER_LINE && bank->types[*idx + span] == DT_BINARY)
  209. span++;
  210. char buf[4 * MAX_BYTES_PER_LINE + 1];
  211. for (i = 0; i < span; i++)
  212. sprintf(buf + 4 * i, "$%02X ", bank->data[*idx + i]);
  213. buf[4 * span - 1] = '\0';
  214. WRITE_LINE(dis, ".byte %s", buf)
  215. (*idx) += span;
  216. }
  217. /*
  218. Render a single instruction within a block.
  219. */
  220. static void render_code(Disassembly *dis, size_t *idx, const ROMBank *bank)
  221. {
  222. DisasInstr *instr = disassemble_instruction(bank->data + *idx);
  223. char padding[16], *split;
  224. if ((split = strchr(instr->line, '\t'))) {
  225. size_t tabs = (40 - (instr->line + strlen(instr->line) - split)) / 8;
  226. padding[tabs] = '\0';
  227. while (tabs-- > 0)
  228. padding[tabs] = '\t';
  229. } else {
  230. strcpy(padding, "\t\t\t\t\t");
  231. }
  232. WRITE_LINE(dis, "\t%s%s\t; %s", instr->line, padding, instr->bytestr)
  233. (*idx) += instr->size;
  234. disas_instr_free(instr);
  235. }
  236. /*
  237. Render fully analyzed banks into lines of disassembly.
  238. */
  239. static void render_banks(Disassembly *dis, const ROMBank *banks)
  240. {
  241. size_t bn = 0, idx;
  242. DEBUG("Rendering lines")
  243. while (banks[bn].data) {
  244. TRACE("Rendering bank 0x%02zX (0x%06zX-0x%06zX)", bn,
  245. bn * MMU_ROM_BANK_SIZE, bn * MMU_ROM_BANK_SIZE + banks[bn].size)
  246. WRITE_LINE(dis, "")
  247. WRITE_LINE(dis, ";; " HRULE)
  248. WRITE_LINE(dis, "")
  249. WRITE_LINE(dis, ".block $%02zX", bn)
  250. idx = 0;
  251. while (idx < banks[bn].size) {
  252. switch (banks[bn].types[idx]) {
  253. case DT_BINARY:
  254. render_binary(dis, &idx, &banks[bn]);
  255. break;
  256. case DT_CODE:
  257. render_code(dis, &idx, &banks[bn]);
  258. break;
  259. case DT_HEADER:
  260. idx += HEADER_SIZE;
  261. break;
  262. default:
  263. FATAL("invalid data type %d at addr 0x%06zX",
  264. banks[bn].types[idx], bn * MMU_ROM_BANK_SIZE + idx)
  265. }
  266. }
  267. bn++;
  268. }
  269. }
  270. /*
  271. Disassemble a ROM into an array of strings, each storing one source line.
  272. Each line is newline-terminated. The array itself is terminated with a NULL
  273. element. Each line, and the overall array, must be free()d by the caller.
  274. */
  275. char** disassemble(const ROM *rom)
  276. {
  277. Disassembly dis = {.cap = 16, .len = 0};
  278. dis.lines = cr_malloc(sizeof(char*) * dis.cap);
  279. write_metadata(&dis, rom);
  280. disassemble_header(&dis, rom);
  281. ROMBank *banks = init_banks(rom);
  282. mark_header(rom, banks);
  283. // TODO: analyze(): set DT_CODE (future: make labels, slots) where appropriate
  284. for (size_t i = 0; i < 0x1000; i++)
  285. banks[0].types[i] = DT_CODE;
  286. render_banks(&dis, banks);
  287. free_banks(banks);
  288. write_line(&dis, NULL);
  289. return dis.lines;
  290. }
  291. /*
  292. Write a disassembly created by disassemble() to the given output file.
  293. Return whether the file was written successfully. This function frees the
  294. disassembly along the way.
  295. */
  296. static bool write_disassembly(const char *path, char **lines)
  297. {
  298. FILE *fp;
  299. char **itr = lines;
  300. if (!(fp = fopen(path, "w"))) {
  301. ERROR_ERRNO("couldn't open destination file")
  302. return false;
  303. }
  304. while (*itr) {
  305. if (!fwrite(*itr, strlen(*itr), 1, fp)) {
  306. fclose(fp);
  307. do free(*itr); while (*(++itr));
  308. ERROR_ERRNO("couldn't write to destination file")
  309. return false;
  310. }
  311. free(*itr);
  312. itr++;
  313. }
  314. fclose(fp);
  315. free(lines);
  316. return true;
  317. }
  318. /*
  319. Disassemble the binary file at the input path into z80 source code.
  320. Return true if the operation was a success and false if it was a failure.
  321. Errors are printed to STDOUT; if the operation was successful then nothing
  322. is printed.
  323. */
  324. bool disassemble_file(const char *src_path, const char *dst_path)
  325. {
  326. ROM *rom;
  327. const char *errmsg;
  328. char **lines;
  329. DEBUG("Disassembling: %s -> %s", src_path, dst_path)
  330. if ((errmsg = rom_open(&rom, src_path))) {
  331. ERROR("couldn't load ROM image '%s': %s", src_path, errmsg)
  332. return false;
  333. }
  334. lines = disassemble(rom);
  335. rom_close(rom);
  336. DEBUG("Writing output file")
  337. return write_disassembly(dst_path, lines);
  338. }