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.
 
 
 
 
 

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