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.
 
 
 
 
 

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