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.
 
 
 
 
 

711 lines
18 KiB

  1. /* Copyright (C) 2014-2015 Ben Kurtovic <ben.kurtovic@gmail.com>
  2. Released under the terms of the MIT License. See LICENSE for details. */
  3. #include <errno.h>
  4. #include <libgen.h>
  5. #include <limits.h>
  6. #include <stdio.h>
  7. #include <string.h>
  8. #include <sys/stat.h>
  9. #include "assembler.h"
  10. #include "logging.h"
  11. #include "util.h"
  12. #define DEFAULT_HEADER_OFFSET 0x7FF0
  13. #define DEFAULT_REGION "GG Export"
  14. #define DIRECTIVE(d) ("." d)
  15. #define DIR_INCLUDE "include"
  16. #define DIR_ORIGIN "org"
  17. #define IS_DIRECTIVE(line, d) \
  18. ((line->length >= strlen(DIRECTIVE(d))) && \
  19. !strncmp(line->data, DIRECTIVE(d), strlen(DIRECTIVE(d))))
  20. #define DIRECTIVE_OFFSET(line, d) \
  21. (line->length > strlen(DIRECTIVE(d)) ? strlen(DIRECTIVE(d)) : 0)
  22. #define SYMBOL_TABLE_BUCKETS 128
  23. /* Internal structs */
  24. struct ASMLine {
  25. char *data;
  26. size_t length;
  27. const Line *original;
  28. const char *filename;
  29. struct ASMLine *next;
  30. };
  31. typedef struct ASMLine ASMLine;
  32. struct ASMInclude {
  33. LineBuffer *lines;
  34. struct ASMInclude *next;
  35. };
  36. typedef struct ASMInclude ASMInclude;
  37. struct ASMInstruction {
  38. size_t offset;
  39. uint8_t length;
  40. uint8_t b1, b2, b3, b4;
  41. uint8_t virtual_byte;
  42. char *symbol;
  43. struct ASMInstruction *next;
  44. };
  45. typedef struct ASMInstruction ASMInstruction;
  46. struct ASMSymbol {
  47. size_t offset;
  48. char *symbol;
  49. struct ASMSymbol *next;
  50. };
  51. typedef struct ASMSymbol ASMSymbol;
  52. typedef struct {
  53. ASMSymbol *buckets[SYMBOL_TABLE_BUCKETS];
  54. } ASMSymbolTable;
  55. typedef struct {
  56. size_t offset;
  57. bool checksum;
  58. uint32_t product_code;
  59. uint8_t version;
  60. uint8_t region;
  61. uint8_t rom_size;
  62. } ASMHeaderInfo;
  63. typedef struct {
  64. ASMHeaderInfo header;
  65. bool optimizer;
  66. size_t rom_size;
  67. ASMLine *lines;
  68. ASMInclude *includes;
  69. ASMInstruction *instructions;
  70. ASMSymbolTable *symtable;
  71. } AssemblerState;
  72. /*
  73. Deallocate a LineBuffer previously created with read_source_file().
  74. */
  75. static void free_line_buffer(LineBuffer *buffer)
  76. {
  77. Line *line = buffer->lines, *temp;
  78. while (line) {
  79. temp = line->next;
  80. free(line->data);
  81. free(line);
  82. line = temp;
  83. }
  84. free(buffer->filename);
  85. free(buffer);
  86. }
  87. /*
  88. Read the contents of the source file at the given path into a line buffer.
  89. Return the buffer if reading was successful; it must be freed with
  90. free_line_buffer() when done. Return NULL if an error occurred while
  91. reading. A message will be printed to stderr in this case.
  92. */
  93. static LineBuffer* read_source_file(const char *path)
  94. {
  95. FILE *fp;
  96. struct stat st;
  97. if (!(fp = fopen(path, "r"))) {
  98. ERROR_ERRNO("couldn't open source file")
  99. return NULL;
  100. }
  101. if (fstat(fileno(fp), &st)) {
  102. fclose(fp);
  103. ERROR_ERRNO("couldn't open source file")
  104. return NULL;
  105. }
  106. if (!(st.st_mode & S_IFREG)) {
  107. fclose(fp);
  108. ERROR("couldn't open source file: %s", st.st_mode & S_IFDIR ?
  109. "Is a directory" : "Is not a regular file")
  110. return NULL;
  111. }
  112. LineBuffer *source = malloc(sizeof(LineBuffer));
  113. if (!source)
  114. OUT_OF_MEMORY()
  115. source->lines = NULL;
  116. source->filename = malloc(sizeof(char) * (strlen(path) + 1));
  117. if (!source->filename)
  118. OUT_OF_MEMORY()
  119. strcpy(source->filename, path);
  120. Line dummy = {.next = NULL};
  121. Line *line, *prev = &dummy;
  122. size_t lineno = 1;
  123. while (1) {
  124. char *data = NULL;
  125. size_t cap = 0;
  126. ssize_t len;
  127. if ((len = getline(&data, &cap, fp)) < 0) {
  128. if (feof(fp))
  129. break;
  130. if (errno == ENOMEM)
  131. OUT_OF_MEMORY()
  132. ERROR_ERRNO("couldn't read source file")
  133. fclose(fp);
  134. source->lines = dummy.next;
  135. free_line_buffer(source);
  136. return NULL;
  137. }
  138. line = malloc(sizeof(Line));
  139. if (!line)
  140. OUT_OF_MEMORY()
  141. line->data = data;
  142. line->length = feof(fp) ? len : (len - 1);
  143. line->lineno = lineno++;
  144. line->next = NULL;
  145. prev->next = line;
  146. prev = line;
  147. }
  148. fclose(fp);
  149. source->lines = dummy.next;
  150. return source;
  151. }
  152. /*
  153. Write an assembled binary file to the given path.
  154. Return whether the file was written successfully. On error, a message is
  155. printed to stderr.
  156. */
  157. static bool write_binary_file(const char *path, const uint8_t *data, size_t size)
  158. {
  159. FILE *fp;
  160. if (!(fp = fopen(path, "wb"))) {
  161. ERROR_ERRNO("couldn't open destination file")
  162. return false;
  163. }
  164. if (!fwrite(data, size, 1, fp)) {
  165. fclose(fp);
  166. ERROR_ERRNO("couldn't write to destination file")
  167. return false;
  168. }
  169. fclose(fp);
  170. return true;
  171. }
  172. /*
  173. Print an ErrorInfo object returned by assemble() to the given stream.
  174. */
  175. void error_info_print(const ErrorInfo *error_info, FILE *file)
  176. {
  177. // TODO
  178. fprintf(file, "Error: Unknown error\n");
  179. }
  180. /*
  181. Destroy an ErrorInfo object created by assemble().
  182. */
  183. void error_info_destroy(ErrorInfo *error_info)
  184. {
  185. if (!error_info)
  186. return;
  187. // TODO
  188. free(error_info);
  189. }
  190. /*
  191. Initialize default values in an AssemblerState object.
  192. */
  193. static void init_state(AssemblerState *state)
  194. {
  195. state->header.offset = DEFAULT_HEADER_OFFSET;
  196. state->header.checksum = true;
  197. state->header.product_code = 0;
  198. state->header.version = 0;
  199. state->header.region = region_string_to_code(DEFAULT_REGION);
  200. state->header.rom_size = 0;
  201. state->optimizer = false;
  202. state->rom_size = 0;
  203. state->lines = NULL;
  204. state->includes = NULL;
  205. state->instructions = NULL;
  206. state->symtable = NULL;
  207. }
  208. /*
  209. Deallocate an ASMLine list.
  210. */
  211. static void free_asm_lines(ASMLine *line)
  212. {
  213. while (line) {
  214. ASMLine *temp = line->next;
  215. free(line->data);
  216. free(line);
  217. line = temp;
  218. }
  219. }
  220. /*
  221. Deallocate an ASMInclude list.
  222. */
  223. static void free_asm_includes(ASMInclude *include)
  224. {
  225. while (include) {
  226. ASMInclude *temp = include->next;
  227. free_line_buffer(include->lines);
  228. free(include);
  229. include = temp;
  230. }
  231. }
  232. /*
  233. Deallocate an ASMInstruction list.
  234. */
  235. static void free_asm_instructions(ASMInstruction *inst)
  236. {
  237. while (inst) {
  238. ASMInstruction *temp = inst->next;
  239. if (inst->symbol)
  240. free(inst->symbol);
  241. free(inst);
  242. inst = temp;
  243. }
  244. }
  245. /*
  246. Deallocate an ASMSymbolTable.
  247. */
  248. static void free_asm_symtable(ASMSymbolTable *symtable)
  249. {
  250. if (!symtable)
  251. return;
  252. for (size_t bucket = 0; bucket < SYMBOL_TABLE_BUCKETS; bucket++) {
  253. ASMSymbol *sym = symtable->buckets[bucket], *temp;
  254. while (sym) {
  255. temp = sym->next;
  256. free(sym->symbol);
  257. free(sym);
  258. sym = temp;
  259. }
  260. }
  261. free(symtable);
  262. }
  263. /*
  264. Preprocess a single source line (source, length) into a normalized ASMLine.
  265. *Only* the data and length fields in the ASMLine object are populated. The
  266. normalization process converts tabs to spaces, lowercases all alphabetical
  267. characters, and removes runs of multiple spaces (outside of string
  268. literals), strips comments, and other things.
  269. Return NULL if an ASM line was not generated from the source, i.e. if it is
  270. blank after being stripped.
  271. */
  272. static ASMLine* normalize_line(const char *source, size_t length)
  273. {
  274. char *data = malloc(sizeof(char) * length);
  275. if (!data)
  276. OUT_OF_MEMORY()
  277. size_t si, di, slashes = 0;
  278. bool has_content = false, space_pending = false, in_string = false;
  279. for (si = di = 0; si < length; si++) {
  280. char c = source[si];
  281. if (c == '\\')
  282. slashes++;
  283. else
  284. slashes = 0;
  285. if (in_string) {
  286. if (c == '"' && (slashes % 2) == 0)
  287. in_string = false;
  288. data[di++] = c;
  289. } else {
  290. if (c == ';')
  291. break;
  292. if (c == '"' && (slashes % 2) == 0)
  293. in_string = true;
  294. if (c >= 'A' && c <= 'Z')
  295. c += 'a' - 'A';
  296. if (c == '\t' || c == ' ')
  297. space_pending = true;
  298. else {
  299. if (space_pending) {
  300. if (has_content)
  301. data[di++] = ' ';
  302. space_pending = false;
  303. }
  304. has_content = true;
  305. data[di++] = c;
  306. }
  307. }
  308. }
  309. if (!has_content) {
  310. free(data);
  311. return NULL;
  312. }
  313. ASMLine *line = malloc(sizeof(ASMLine));
  314. if (!line)
  315. OUT_OF_MEMORY()
  316. data = realloc(data, sizeof(char) * di);
  317. if (!data)
  318. OUT_OF_MEMORY()
  319. line->data = data;
  320. line->length = di;
  321. return line;
  322. }
  323. /*
  324. Read and return the target path from an include directive.
  325. This function allocates a buffer to store the filename; it must be free()'d
  326. after calling read_source_file(). If a syntax error occurs while trying to
  327. read the path, it returns NULL.
  328. */
  329. char* read_include_path(const ASMLine *line)
  330. {
  331. size_t maxlen = strlen(line->filename) + line->length, i, start, slashes;
  332. if (maxlen >= INT_MAX) // Allows us to safely downcast to int later
  333. return NULL;
  334. char *path = malloc(sizeof(char) * maxlen);
  335. if (!path)
  336. OUT_OF_MEMORY()
  337. if (!(i = DIRECTIVE_OFFSET(line, DIR_INCLUDE)))
  338. goto error;
  339. if (line->length - i <= 4) // Not long enough to hold a non-zero argument
  340. goto error;
  341. if (line->data[i++] != ' ' || line->data[i++] != '"')
  342. goto error;
  343. // TODO: parse escaped characters properly
  344. for (start = i, slashes = 0; i < line->length; i++) {
  345. if (line->data[i] == '"' && (slashes % 2) == 0)
  346. break;
  347. if (line->data[i] == '\\')
  348. slashes++;
  349. else
  350. slashes = 0;
  351. }
  352. if (i != line->length - 1) // Junk present after closing quote
  353. goto error;
  354. char *dup = strdup(line->filename);
  355. if (!dup)
  356. OUT_OF_MEMORY()
  357. snprintf(path, maxlen, "%s/%.*s", dirname(dup), (int) (i - start),
  358. line->data + start);
  359. free(dup);
  360. return path;
  361. error:
  362. free(path);
  363. return NULL;
  364. }
  365. /*
  366. Build a LineBuffer into a ASMLines, normalizing them along the way.
  367. This function operates recursively to handle includes, but handles no other
  368. preprocessor directives.
  369. On success, NULL is returned; *head points to the head of the new ASMLine
  370. list, and *tail to its tail (assuming it is non-NULL). On error, an
  371. ErrorInfo object is returned, and *head and *tail are not modified.
  372. *includes may be updated in either case.
  373. */
  374. static ErrorInfo* build_asm_lines(
  375. const LineBuffer *source, ASMLine **head, ASMLine **tail,
  376. ASMInclude **includes)
  377. {
  378. ASMLine dummy = {.next = NULL};
  379. ASMLine *line, *prev = &dummy;
  380. const Line *orig, *next_orig = source->lines;
  381. while ((orig = next_orig)) {
  382. line = normalize_line(orig->data, orig->length);
  383. next_orig = orig->next;
  384. if (!line)
  385. continue;
  386. // Populate ASMLine fields not set by normalize_line():
  387. line->original = orig;
  388. line->filename = source->filename;
  389. line->next = NULL;
  390. if (IS_DIRECTIVE(line, DIR_INCLUDE)) {
  391. ErrorInfo *ei;
  392. char *path = read_include_path(line);
  393. free_asm_lines(line); // Destroy only the .include line
  394. if (!path) {
  395. // TODO: syntax error
  396. // ei = create_error(orig);
  397. free_asm_lines(dummy.next);
  398. return ei;
  399. }
  400. // TODO: update read_source_file() to change error behavior...
  401. // TODO: handle recursive includes properly
  402. LineBuffer *incbuffer = read_source_file(path);
  403. free(path);
  404. if (!incbuffer) {
  405. // TODO: return read error...
  406. // ei = create_error(orig);
  407. free_asm_lines(dummy.next);
  408. return ei;
  409. }
  410. ASMInclude *include = malloc(sizeof(ASMInclude));
  411. if (!include)
  412. OUT_OF_MEMORY()
  413. include->lines = incbuffer;
  414. include->next = *includes;
  415. *includes = include;
  416. ASMLine *inctail;
  417. if ((ei = build_asm_lines(incbuffer, &line, &inctail, includes))) {
  418. // TODO: nest EI
  419. // append_include_to_error(ei, orig);
  420. free_asm_lines(dummy.next);
  421. return ei;
  422. }
  423. prev->next = line;
  424. prev = inctail;
  425. }
  426. else {
  427. prev->next = line;
  428. prev = line;
  429. }
  430. }
  431. *head = dummy.next;
  432. if (tail)
  433. *tail = prev;
  434. return NULL;
  435. }
  436. /*
  437. Preprocess the LineBuffer into ASMLines. Change some state along the way.
  438. This function processes include directives, so read_source_file() may be
  439. called multiple times (along with the implications that has), and
  440. state->includes may be modified.
  441. On success, NULL is returned. On error, an ErrorInfo object is returned.
  442. state->lines and state->includes may still be modified.
  443. */
  444. static ErrorInfo* preprocess(AssemblerState *state, const LineBuffer *source)
  445. {
  446. // TODO
  447. // state->header.offset <-- check in list of acceptable values
  448. // state->header.checksum <-- boolean check
  449. // state->header.product_code <-- range check
  450. // state->header.version <-- range check
  451. // state->header.region <-- string conversion, check
  452. // state->header.rom_size <-- value/range check
  453. // state->optimizer <-- boolean check
  454. // state->rom_size <-- value check
  455. // if giving rom size, check header offset is in rom size range
  456. // if giving reported and actual rom size, check reported is <= actual
  457. // ensure no duplicate explicit assignments
  458. ErrorInfo* ei;
  459. if ((ei = build_asm_lines(source, &state->lines, NULL, &state->includes)))
  460. return ei;
  461. // TODO: iterate here for all global preprocessor directives
  462. #ifdef DEBUG_MODE
  463. DEBUG("Dumping ASMLines:")
  464. const ASMLine *temp = state->lines;
  465. while (temp) {
  466. DEBUG("- %-40.*s [%s:%02zu]", (int) temp->length, temp->data,
  467. temp->filename, temp->original->lineno)
  468. temp = temp->next;
  469. }
  470. #endif
  471. return NULL;
  472. }
  473. /*
  474. Tokenize ASMLines into ASMInstructions.
  475. On success, state->instructions is modified and NULL is returned. On error,
  476. an ErrorInfo object is returned and state->instructions is not modified.
  477. state->symtable may or may not be modified regardless of success.
  478. */
  479. static ErrorInfo* tokenize(AssemblerState *state)
  480. {
  481. // TODO
  482. // verify no instructions clash with header offset
  483. // if rom size is set, verify nothing overflows
  484. return NULL;
  485. }
  486. /*
  487. Resolve default placeholder values in assembler state, such as ROM size.
  488. On success, no new heap objects are allocated. On error, an ErrorInfo
  489. object is returned.
  490. */
  491. static ErrorInfo* resolve_defaults(AssemblerState *state)
  492. {
  493. // TODO
  494. // if (!state.rom_size)
  495. // set to max possible >= 32 KB, or error if too many instructions
  496. // if (state.header.rom_size)
  497. // check reported rom size is <= actual rom size
  498. // if (!state.header.rom_size)
  499. // set to actual rom size
  500. return NULL;
  501. }
  502. /*
  503. Resolve symbol placeholders in instructions such as jumps and branches.
  504. On success, no new heap objects are allocated. On error, an ErrorInfo
  505. object is returned.
  506. */
  507. static ErrorInfo* resolve_symbols(AssemblerState *state)
  508. {
  509. // TODO
  510. return NULL;
  511. }
  512. /*
  513. Convert finalized ASMInstructions into a binary data block.
  514. This function should never fail.
  515. */
  516. static void serialize_binary(AssemblerState *state, uint8_t *binary)
  517. {
  518. // TODO
  519. for (size_t i = 0; i < state->rom_size; i++)
  520. binary[i] = 'X';
  521. }
  522. /*
  523. Assemble the z80 source code in the source code buffer into binary data.
  524. If successful, return the size of the assembled binary data and change
  525. *binary_ptr to point to the assembled ROM data buffer. *binary_ptr must be
  526. free()'d when finished.
  527. If an error occurred, return 0 and update *ei_ptr to point to an ErrorInfo
  528. object which can be shown to the user with error_info_print(). The
  529. ErrorInfo object must be destroyed with error_info_destroy() when finished.
  530. In either case, only one of *binary_ptr and *ei_ptr is modified.
  531. */
  532. size_t assemble(const LineBuffer *source, uint8_t **binary_ptr, ErrorInfo **ei_ptr)
  533. {
  534. AssemblerState state;
  535. ErrorInfo *error_info;
  536. size_t retval = 0;
  537. init_state(&state);
  538. if ((error_info = preprocess(&state, source)))
  539. goto error;
  540. if (!(state.symtable = malloc(sizeof(ASMSymbolTable))))
  541. OUT_OF_MEMORY()
  542. for (size_t bucket = 0; bucket < SYMBOL_TABLE_BUCKETS; bucket++)
  543. state.symtable->buckets[bucket] = NULL;
  544. if ((error_info = tokenize(&state)))
  545. goto error;
  546. if ((error_info = resolve_defaults(&state)))
  547. goto error;
  548. if ((error_info = resolve_symbols(&state)))
  549. goto error;
  550. uint8_t *binary = malloc(sizeof(uint8_t) * state.rom_size);
  551. if (!binary)
  552. OUT_OF_MEMORY()
  553. serialize_binary(&state, binary);
  554. *binary_ptr = binary;
  555. retval = state.rom_size;
  556. goto cleanup;
  557. error:
  558. *ei_ptr = error_info;
  559. cleanup:
  560. free_asm_lines(state.lines);
  561. free_asm_includes(state.includes);
  562. free_asm_instructions(state.instructions);
  563. free_asm_symtable(state.symtable);
  564. return retval;
  565. }
  566. /*
  567. Assemble the z80 source code at the input path into a binary file.
  568. Return true if the operation was a success and false if it was a failure.
  569. Errors are printed to STDOUT; if the operation was successful then nothing
  570. is printed.
  571. */
  572. bool assemble_file(const char *src_path, const char *dst_path)
  573. {
  574. LineBuffer *source = read_source_file(src_path);
  575. if (!source)
  576. return false;
  577. uint8_t *binary;
  578. ErrorInfo *error_info;
  579. size_t size = assemble(source, &binary, &error_info);
  580. free_line_buffer(source);
  581. if (!size) {
  582. error_info_print(error_info, stderr);
  583. error_info_destroy(error_info);
  584. return false;
  585. }
  586. bool success = write_binary_file(dst_path, binary, size);
  587. free(binary);
  588. return success;
  589. }