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.
 
 
 
 
 

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