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.
 
 
 
 
 

874 lines
23 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. LineBuffer *incbuffer = read_source_file(path, false);
  516. free(path);
  517. if (!incbuffer) {
  518. ei = create_error(line, ET_INCLUDE, ED_FILE_READ_ERR);
  519. free_asm_lines(line);
  520. free_asm_lines(dummy.next);
  521. return ei;
  522. }
  523. ASMInclude *include = malloc(sizeof(ASMInclude));
  524. if (!include)
  525. OUT_OF_MEMORY()
  526. include->lines = incbuffer;
  527. include->next = *includes;
  528. *includes = include;
  529. ASMLine *inchead, *inctail;
  530. if ((ei = build_asm_lines(root, incbuffer, &inchead, &inctail,
  531. includes))) {
  532. append_to_error(ei, line);
  533. free_asm_lines(line);
  534. free_asm_lines(dummy.next);
  535. return ei;
  536. }
  537. prev->next = inchead;
  538. prev = inctail;
  539. free_asm_lines(line); // Destroy only the .include line
  540. }
  541. else {
  542. prev->next = line;
  543. prev = line;
  544. }
  545. }
  546. *head = dummy.next;
  547. if (tail)
  548. *tail = prev;
  549. return NULL;
  550. }
  551. /*
  552. Preprocess the LineBuffer into ASMLines. Change some state along the way.
  553. This function processes include directives, so read_source_file() may be
  554. called multiple times (along with the implications that has), and
  555. state->includes may be modified.
  556. On success, NULL is returned. On error, an ErrorInfo object is returned.
  557. state->lines and state->includes may still be modified.
  558. */
  559. static ErrorInfo* preprocess(AssemblerState *state, const LineBuffer *source)
  560. {
  561. // state->header.offset <-- check in list of acceptable values
  562. // state->header.checksum <-- boolean check
  563. // state->header.product_code <-- range check
  564. // state->header.version <-- range check
  565. // state->header.region <-- string conversion, check
  566. // state->header.rom_size <-- value/range check
  567. // state->optimizer <-- boolean check
  568. // state->rom_size <-- value check
  569. // if giving rom size, check header offset is in rom size range
  570. // if giving reported and actual rom size, check reported is <= actual
  571. // ensure no duplicate explicit assignments
  572. ErrorInfo* ei;
  573. if ((ei = build_asm_lines(source, source, &state->lines, NULL,
  574. &state->includes)))
  575. return ei;
  576. const ASMLine *line = state->lines;
  577. while (line) {
  578. if (line->data[0] == DIRECTIVE_MARKER) {
  579. DEBUG("got marker on line: %.*s", (int) line->length, line->data)
  580. if (IS_DIRECTIVE(line, DIR_ORIGIN)) {
  581. // Do nothing; origins are handled by tokenizer
  582. } else if (IS_DIRECTIVE(line, DIR_OPTIMIZER)) {
  583. // TODO
  584. } else if (IS_DIRECTIVE(line, DIR_ROM_SIZE)) {
  585. // TODO
  586. } else if (IS_DIRECTIVE(line, DIR_ROM_HEADER)) {
  587. // TODO
  588. } else if (IS_DIRECTIVE(line, DIR_ROM_CHECKSUM)) {
  589. // TODO
  590. } else if (IS_DIRECTIVE(line, DIR_ROM_PRODUCT)) {
  591. // TODO
  592. } else if (IS_DIRECTIVE(line, DIR_ROM_VERSION)) {
  593. // TODO
  594. } else if (IS_DIRECTIVE(line, DIR_ROM_REGION)) {
  595. // TODO
  596. } else if (IS_DIRECTIVE(line, DIR_ROM_DECLSIZE)) {
  597. // TODO
  598. } else {
  599. ei = create_error(line, ET_PREPROCESSOR, ED_UNKNOWN_DIRECTIVE);
  600. return ei;
  601. }
  602. }
  603. line = line->next;
  604. }
  605. state->rom_size = 8; // TODO
  606. #ifdef DEBUG_MODE
  607. DEBUG("Dumping ASMLines:")
  608. const ASMLine *temp = state->lines;
  609. while (temp) {
  610. DEBUG("- %-40.*s [%s:%02zu]", (int) temp->length, temp->data,
  611. temp->filename, temp->original->lineno)
  612. temp = temp->next;
  613. }
  614. #endif
  615. return NULL;
  616. }
  617. /*
  618. Tokenize ASMLines into ASMInstructions.
  619. On success, state->instructions is modified and NULL is returned. On error,
  620. an ErrorInfo object is returned and state->instructions is not modified.
  621. state->symtable may or may not be modified regardless of success.
  622. */
  623. static ErrorInfo* tokenize(AssemblerState *state)
  624. {
  625. // TODO
  626. // verify no instructions clash with header offset
  627. // if rom size is set, verify nothing overflows
  628. return NULL;
  629. }
  630. /*
  631. Resolve default placeholder values in assembler state, such as ROM size.
  632. On success, no new heap objects are allocated. On error, an ErrorInfo
  633. object is returned.
  634. */
  635. static ErrorInfo* resolve_defaults(AssemblerState *state)
  636. {
  637. // TODO
  638. // if (!state.rom_size)
  639. // set to max possible >= 32 KB, or error if too many instructions
  640. // if (state.header.rom_size)
  641. // check reported rom size is <= actual rom size
  642. // if (!state.header.rom_size)
  643. // set to actual rom size
  644. return NULL;
  645. }
  646. /*
  647. Resolve symbol placeholders in instructions such as jumps and branches.
  648. On success, no new heap objects are allocated. On error, an ErrorInfo
  649. object is returned.
  650. */
  651. static ErrorInfo* resolve_symbols(AssemblerState *state)
  652. {
  653. // TODO
  654. return NULL;
  655. }
  656. /*
  657. Convert finalized ASMInstructions into a binary data block.
  658. This function should never fail.
  659. */
  660. static void serialize_binary(AssemblerState *state, uint8_t *binary)
  661. {
  662. // TODO
  663. for (size_t i = 0; i < state->rom_size; i++)
  664. binary[i] = 'X';
  665. }
  666. /*
  667. Assemble the z80 source code in the source code buffer into binary data.
  668. If successful, return the size of the assembled binary data and change
  669. *binary_ptr to point to the assembled ROM data buffer. *binary_ptr must be
  670. free()'d when finished.
  671. If an error occurred, return 0 and update *ei_ptr to point to an ErrorInfo
  672. object which can be shown to the user with error_info_print(). The
  673. ErrorInfo object must be destroyed with error_info_destroy() when finished.
  674. In either case, only one of *binary_ptr and *ei_ptr is modified.
  675. */
  676. size_t assemble(const LineBuffer *source, uint8_t **binary_ptr, ErrorInfo **ei_ptr)
  677. {
  678. AssemblerState state;
  679. ErrorInfo *error_info;
  680. size_t retval = 0;
  681. init_state(&state);
  682. if ((error_info = preprocess(&state, source)))
  683. goto error;
  684. if (!(state.symtable = malloc(sizeof(ASMSymbolTable))))
  685. OUT_OF_MEMORY()
  686. for (size_t bucket = 0; bucket < SYMBOL_TABLE_BUCKETS; bucket++)
  687. state.symtable->buckets[bucket] = NULL;
  688. if ((error_info = tokenize(&state)))
  689. goto error;
  690. if ((error_info = resolve_defaults(&state)))
  691. goto error;
  692. if ((error_info = resolve_symbols(&state)))
  693. goto error;
  694. uint8_t *binary = malloc(sizeof(uint8_t) * state.rom_size);
  695. if (!binary)
  696. OUT_OF_MEMORY()
  697. serialize_binary(&state, binary);
  698. *binary_ptr = binary;
  699. retval = state.rom_size;
  700. goto cleanup;
  701. error:
  702. *ei_ptr = error_info;
  703. cleanup:
  704. free_asm_lines(state.lines);
  705. free_asm_includes(state.includes);
  706. free_asm_instructions(state.instructions);
  707. free_asm_symtable(state.symtable);
  708. return retval;
  709. }
  710. /*
  711. Assemble the z80 source code at the input path into a binary file.
  712. Return true if the operation was a success and false if it was a failure.
  713. Errors are printed to STDOUT; if the operation was successful then nothing
  714. is printed.
  715. */
  716. bool assemble_file(const char *src_path, const char *dst_path)
  717. {
  718. LineBuffer *source = read_source_file(src_path, true);
  719. if (!source)
  720. return false;
  721. uint8_t *binary;
  722. ErrorInfo *error_info;
  723. size_t size = assemble(source, &binary, &error_info);
  724. free_line_buffer(source);
  725. if (!size) {
  726. error_info_print(error_info, stderr);
  727. error_info_destroy(error_info);
  728. return false;
  729. }
  730. bool success = write_binary_file(dst_path, binary, size);
  731. free(binary);
  732. return success;
  733. }