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.
 
 
 
 
 

589 lines
18 KiB

  1. /* Copyright (C) 2014-2015 Ben Kurtovic <ben.kurtovic@gmail.com>
  2. Released under the terms of the MIT License. See LICENSE for details. */
  3. #include <libgen.h>
  4. #include <limits.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include "assembler.h"
  8. #include "assembler/errors.h"
  9. #include "assembler/io.h"
  10. #include "assembler/state.h"
  11. #include "logging.h"
  12. #define DIRECTIVE_MARKER '.'
  13. #define DIR_INCLUDE ".include"
  14. #define DIR_ORIGIN ".org"
  15. #define DIR_OPTIMIZER ".optimizer"
  16. #define DIR_ROM_SIZE ".rom_size"
  17. #define DIR_ROM_HEADER ".rom_header"
  18. #define DIR_ROM_CHECKSUM ".rom_checksum"
  19. #define DIR_ROM_PRODUCT ".rom_product"
  20. #define DIR_ROM_VERSION ".rom_version"
  21. #define DIR_ROM_REGION ".rom_region"
  22. #define DIR_ROM_DECLSIZE ".rom_declsize"
  23. #define DIRECTIVE_HAS_ARG(line, d) ((line)->length > strlen(d))
  24. #define IS_DIRECTIVE(line, d) \
  25. (((line)->length >= strlen(d)) && \
  26. !strncmp((line)->data, d, strlen(d)) && \
  27. (!DIRECTIVE_HAS_ARG(line, d) || (line)->data[strlen(d)] == ' '))
  28. #define DIRECTIVE_OFFSET(line, d) \
  29. (DIRECTIVE_HAS_ARG(line, d) ? strlen(d) : 0)
  30. /*
  31. Preprocess a single source line (source, length) into a normalized ASMLine.
  32. *Only* the data and length fields in the ASMLine object are populated. The
  33. normalization process converts tabs to spaces, lowercases all alphabetical
  34. characters, and removes runs of multiple spaces (outside of string
  35. literals), strips comments, and other things.
  36. Return NULL if an ASM line was not generated from the source, i.e. if it is
  37. blank after being stripped.
  38. */
  39. static ASMLine* normalize_line(const char *source, size_t length)
  40. {
  41. char *data = malloc(sizeof(char) * length);
  42. if (!data)
  43. OUT_OF_MEMORY()
  44. size_t si, di, slashes = 0;
  45. bool has_content = false, space_pending = false, in_string = false;
  46. for (si = di = 0; si < length; si++) {
  47. char c = source[si];
  48. if (c == '\\')
  49. slashes++;
  50. else
  51. slashes = 0;
  52. if (in_string) {
  53. if (c == '"' && (slashes % 2) == 0)
  54. in_string = false;
  55. data[di++] = c;
  56. } else {
  57. if (c == ';')
  58. break;
  59. if (c == '"' && (slashes % 2) == 0)
  60. in_string = true;
  61. if (c >= 'A' && c <= 'Z')
  62. c += 'a' - 'A';
  63. if (c == ' ' || c == '\t')
  64. space_pending = true;
  65. else {
  66. if (space_pending) {
  67. if (has_content)
  68. data[di++] = ' ';
  69. space_pending = false;
  70. }
  71. has_content = true;
  72. data[di++] = c;
  73. }
  74. }
  75. }
  76. if (!has_content) {
  77. free(data);
  78. return NULL;
  79. }
  80. ASMLine *line = malloc(sizeof(ASMLine));
  81. if (!line)
  82. OUT_OF_MEMORY()
  83. data = realloc(data, sizeof(char) * di);
  84. if (!data)
  85. OUT_OF_MEMORY()
  86. line->data = data;
  87. line->length = di;
  88. return line;
  89. }
  90. /*
  91. Read and return the target path from an include directive.
  92. This function allocates a buffer to store the filename; it must be free()'d
  93. after calling read_source_file(). If a syntax error occurs while trying to
  94. read the path, it returns NULL.
  95. */
  96. char* read_include_path(const ASMLine *line)
  97. {
  98. size_t maxlen = strlen(line->filename) + line->length, i, start, slashes;
  99. if (maxlen >= INT_MAX) // Allows us to safely downcast to int later
  100. return NULL;
  101. char *path = malloc(sizeof(char) * maxlen);
  102. if (!path)
  103. OUT_OF_MEMORY()
  104. if (!(i = DIRECTIVE_OFFSET(line, DIR_INCLUDE)))
  105. goto error;
  106. if (line->length - i <= 4) // Not long enough to hold a non-zero argument
  107. goto error;
  108. if (line->data[i++] != ' ' || line->data[i++] != '"')
  109. goto error;
  110. // TODO: parse escaped characters properly
  111. for (start = i, slashes = 0; i < line->length; i++) {
  112. if (line->data[i] == '"' && (slashes % 2) == 0)
  113. break;
  114. if (line->data[i] == '\\')
  115. slashes++;
  116. else
  117. slashes = 0;
  118. }
  119. if (i != line->length - 1) // Junk present after closing quote
  120. goto error;
  121. char *dup = strdup(line->filename);
  122. if (!dup)
  123. OUT_OF_MEMORY()
  124. // TODO: should normalize filenames in some way to prevent accidental dupes
  125. snprintf(path, maxlen, "%s/%.*s", dirname(dup), (int) (i - start),
  126. line->data + start);
  127. free(dup);
  128. return path;
  129. error:
  130. free(path);
  131. return NULL;
  132. }
  133. /*
  134. Return whether the given path has already been loaded.
  135. */
  136. static bool path_has_been_loaded(
  137. const char *path, const LineBuffer *root, const ASMInclude *include)
  138. {
  139. if (!strcmp(path, root->filename))
  140. return true;
  141. while (include) {
  142. if (!strcmp(path, include->lines->filename))
  143. return true;
  144. include = include->next;
  145. }
  146. return false;
  147. }
  148. /*
  149. Build a LineBuffer into a ASMLines, normalizing them along the way.
  150. This function operates recursively to handle includes, but handles no other
  151. preprocessor directives.
  152. On success, NULL is returned; *head points to the head of the new ASMLine
  153. list, and *tail to its tail (assuming it is non-NULL). On error, an
  154. ErrorInfo object is returned, and *head and *tail are not modified.
  155. *includes may be updated in either case.
  156. */
  157. static ErrorInfo* build_asm_lines(
  158. const LineBuffer *root, const LineBuffer *source, ASMLine **head,
  159. ASMLine **tail, ASMInclude **includes)
  160. {
  161. ASMLine dummy = {.next = NULL};
  162. ASMLine *line, *prev = &dummy;
  163. const Line *orig, *next_orig = source->lines;
  164. while ((orig = next_orig)) {
  165. line = normalize_line(orig->data, orig->length);
  166. next_orig = orig->next;
  167. if (!line)
  168. continue;
  169. // Populate ASMLine fields not set by normalize_line():
  170. line->original = orig;
  171. line->filename = source->filename;
  172. line->next = NULL;
  173. if (IS_DIRECTIVE(line, DIR_INCLUDE)) {
  174. ErrorInfo *ei;
  175. char *path = read_include_path(line);
  176. if (!path) {
  177. ei = error_info_create(line, ET_INCLUDE, ED_INC_BAD_ARG);
  178. asm_lines_free(line);
  179. asm_lines_free(dummy.next);
  180. return ei;
  181. }
  182. if (path_has_been_loaded(path, root, *includes)) {
  183. ei = error_info_create(line, ET_INCLUDE, ED_INC_RECURSION);
  184. asm_lines_free(line);
  185. asm_lines_free(dummy.next);
  186. free(path);
  187. return ei;
  188. }
  189. DEBUG("- reading included file: %s", path)
  190. LineBuffer *incbuffer = read_source_file(path, false);
  191. free(path);
  192. if (!incbuffer) {
  193. ei = error_info_create(line, ET_INCLUDE, ED_INC_FILE_READ);
  194. asm_lines_free(line);
  195. asm_lines_free(dummy.next);
  196. return ei;
  197. }
  198. ASMInclude *include = malloc(sizeof(ASMInclude));
  199. if (!include)
  200. OUT_OF_MEMORY()
  201. include->lines = incbuffer;
  202. include->next = *includes;
  203. *includes = include;
  204. ASMLine *inchead, *inctail;
  205. if ((ei = build_asm_lines(root, incbuffer, &inchead, &inctail,
  206. includes))) {
  207. error_info_append(ei, line);
  208. asm_lines_free(line);
  209. asm_lines_free(dummy.next);
  210. return ei;
  211. }
  212. prev->next = inchead;
  213. prev = inctail;
  214. asm_lines_free(line); // Destroy only the .include line
  215. }
  216. else {
  217. prev->next = line;
  218. prev = line;
  219. }
  220. }
  221. *head = dummy.next;
  222. if (tail)
  223. *tail = prev;
  224. return NULL;
  225. }
  226. /*
  227. Read in a boolean argument from the given line and store it in *result.
  228. auto_val is used if the argument's value is "auto". Return true on success
  229. and false on failure; in the latter case, *result is not modified.
  230. */
  231. static inline bool read_bool_argument(
  232. bool *result, const ASMLine *line, const char *directive, bool auto_val)
  233. {
  234. const char *arg = line->data + (DIRECTIVE_OFFSET(line, directive) + 1);
  235. ssize_t len = line->length - (DIRECTIVE_OFFSET(line, directive) + 1);
  236. if (len <= 0 || len > 5)
  237. return false;
  238. switch (len) {
  239. case 1: // 0, 1
  240. if (*arg == '0' || *arg == '1')
  241. return (*result = *arg - '0'), true;
  242. return false;
  243. case 2: // on
  244. if (!strncmp(arg, "on", 2))
  245. return (*result = true), true;
  246. return false;
  247. case 3: // off
  248. if (!strncmp(arg, "off", 3))
  249. return (*result = false), true;
  250. return false;
  251. case 4: // true, auto
  252. if (!strncmp(arg, "true", 4))
  253. return (*result = true), true;
  254. if (!strncmp(arg, "auto", 4))
  255. return (*result = auto_val), true;
  256. return false;
  257. case 5: // false
  258. if (!strncmp(arg, "false", 5))
  259. return (*result = false), true;
  260. return false;
  261. }
  262. return false;
  263. }
  264. /*
  265. Preprocess the LineBuffer into ASMLines. Change some state along the way.
  266. This function processes include directives, so read_source_file() may be
  267. called multiple times (along with the implications that has), and
  268. state->includes may be modified.
  269. On success, NULL is returned. On error, an ErrorInfo object is returned.
  270. state->lines and state->includes may still be modified.
  271. */
  272. static ErrorInfo* preprocess(AssemblerState *state, const LineBuffer *source)
  273. {
  274. // state->header.offset <-- check in list of acceptable values
  275. // state->header.product_code <-- range check
  276. // state->header.version <-- range check
  277. // state->header.region <-- string conversion, check
  278. // state->header.rom_size <-- value/range check
  279. // state->rom_size <-- value check
  280. // if giving rom size, check header offset is in rom size range
  281. // if giving reported and actual rom size, check reported is <= actual
  282. #define CATCH_DUPES(line, first, oldval, newval) \
  283. if (first && oldval != newval) { \
  284. ei = error_info_create(line, ET_PREPROC, ED_PP_DUPLICATE); \
  285. error_info_append(ei, first); \
  286. asm_lines_free(condemned); \
  287. return ei; \
  288. } \
  289. oldval = newval; \
  290. first = line;
  291. #define REQUIRE_ARG(line, d) \
  292. if (!DIRECTIVE_HAS_ARG(line, d)) { \
  293. asm_lines_free(condemned); \
  294. return error_info_create(line, ET_PREPROC, ED_PP_NO_ARG); \
  295. }
  296. #define VALIDATE(retval) \
  297. if (!(retval)) { \
  298. asm_lines_free(condemned); \
  299. return error_info_create(line, ET_PREPROC, ED_PP_BAD_ARG); \
  300. }
  301. DEBUG("Running preprocessor:")
  302. ErrorInfo* ei;
  303. if ((ei = build_asm_lines(source, source, &state->lines, NULL,
  304. &state->includes)))
  305. return ei;
  306. ASMLine dummy = {.next = state->lines};
  307. ASMLine *prev, *line = &dummy, *next = state->lines, *condemned = NULL;
  308. const ASMLine *first_optimizer = NULL, *first_checksum = NULL;
  309. while ((prev = line, line = next)) {
  310. next = line->next;
  311. if (line->data[0] == DIRECTIVE_MARKER) {
  312. if (IS_DIRECTIVE(line, DIR_ORIGIN))
  313. continue; // Origins are handled by tokenizer
  314. DEBUG("- handling directive: %.*s", (int) line->length, line->data)
  315. if (IS_DIRECTIVE(line, DIR_OPTIMIZER)) {
  316. REQUIRE_ARG(line, DIR_OPTIMIZER)
  317. bool arg;
  318. VALIDATE(read_bool_argument(&arg, line, DIR_OPTIMIZER, false))
  319. CATCH_DUPES(line, first_optimizer, state->optimizer, arg)
  320. }
  321. else if (IS_DIRECTIVE(line, DIR_ROM_SIZE)) {
  322. // TODO
  323. }
  324. else if (IS_DIRECTIVE(line, DIR_ROM_HEADER)) {
  325. // TODO
  326. }
  327. else if (IS_DIRECTIVE(line, DIR_ROM_CHECKSUM)) {
  328. REQUIRE_ARG(line, DIR_ROM_CHECKSUM)
  329. bool arg;
  330. VALIDATE(read_bool_argument(&arg, line, DIR_ROM_CHECKSUM, true))
  331. CATCH_DUPES(line, first_checksum, state->header.checksum, arg)
  332. }
  333. else if (IS_DIRECTIVE(line, DIR_ROM_PRODUCT)) {
  334. // TODO
  335. }
  336. else if (IS_DIRECTIVE(line, DIR_ROM_VERSION)) {
  337. // TODO
  338. }
  339. else if (IS_DIRECTIVE(line, DIR_ROM_REGION)) {
  340. // TODO
  341. }
  342. else if (IS_DIRECTIVE(line, DIR_ROM_DECLSIZE)) {
  343. // TODO
  344. }
  345. else {
  346. asm_lines_free(condemned);
  347. return error_info_create(line, ET_PREPROC, ED_PP_UNKNOWN);
  348. }
  349. // Remove directive from lines, and schedule it for deletion:
  350. line->next = condemned;
  351. condemned = line;
  352. prev->next = next;
  353. line = prev;
  354. }
  355. }
  356. state->rom_size = 8; // TODO
  357. asm_lines_free(condemned);
  358. state->lines = dummy.next; // Fix list head if first line was a directive
  359. #ifdef DEBUG_MODE
  360. DEBUG("Dumping ASMLines:")
  361. const ASMLine *temp = state->lines;
  362. while (temp) {
  363. DEBUG("- %-40.*s [%s:%02zu]", (int) temp->length, temp->data,
  364. temp->filename, temp->original->lineno)
  365. temp = temp->next;
  366. }
  367. #endif
  368. return NULL;
  369. #undef VALIDATE
  370. #undef REQUIRE_ARG
  371. #undef CATCH_DUPES
  372. }
  373. /*
  374. Tokenize ASMLines into ASMInstructions.
  375. On success, state->instructions is modified and NULL is returned. On error,
  376. an ErrorInfo object is returned and state->instructions is not modified.
  377. state->symtable may or may not be modified regardless of success.
  378. */
  379. static ErrorInfo* tokenize(AssemblerState *state)
  380. {
  381. // TODO
  382. // verify no instructions clash with header offset
  383. // if rom size is set, verify nothing overflows
  384. return NULL;
  385. }
  386. /*
  387. Resolve default placeholder values in assembler state, such as ROM size.
  388. On success, no new heap objects are allocated. On error, an ErrorInfo
  389. object is returned.
  390. */
  391. static ErrorInfo* resolve_defaults(AssemblerState *state)
  392. {
  393. // TODO
  394. // if (!state.rom_size)
  395. // set to max possible >= 32 KB, or error if too many instructions
  396. // if (state.header.rom_size)
  397. // check reported rom size is <= actual rom size
  398. // if (!state.header.rom_size)
  399. // set to actual rom size
  400. return NULL;
  401. }
  402. /*
  403. Resolve symbol placeholders in instructions such as jumps and branches.
  404. On success, no new heap objects are allocated. On error, an ErrorInfo
  405. object is returned.
  406. */
  407. static ErrorInfo* resolve_symbols(AssemblerState *state)
  408. {
  409. // TODO
  410. return NULL;
  411. }
  412. /*
  413. Convert finalized ASMInstructions into a binary data block.
  414. This function should never fail.
  415. */
  416. static void serialize_binary(AssemblerState *state, uint8_t *binary)
  417. {
  418. // TODO
  419. for (size_t i = 0; i < state->rom_size; i++)
  420. binary[i] = 'X';
  421. }
  422. /*
  423. Assemble the z80 source code in the source code buffer into binary data.
  424. If successful, return the size of the assembled binary data and change
  425. *binary_ptr to point to the assembled ROM data buffer. *binary_ptr must be
  426. free()'d when finished.
  427. If an error occurred, return 0 and update *ei_ptr to point to an ErrorInfo
  428. object which can be shown to the user with error_info_print(). The
  429. ErrorInfo object must be destroyed with error_info_destroy() when finished.
  430. In either case, only one of *binary_ptr and *ei_ptr is modified.
  431. */
  432. size_t assemble(const LineBuffer *source, uint8_t **binary_ptr, ErrorInfo **ei_ptr)
  433. {
  434. AssemblerState state;
  435. ErrorInfo *error_info;
  436. size_t retval = 0;
  437. state_init(&state);
  438. if ((error_info = preprocess(&state, source)))
  439. goto error;
  440. if (!(state.symtable = malloc(sizeof(ASMSymbolTable))))
  441. OUT_OF_MEMORY()
  442. for (size_t bucket = 0; bucket < SYMBOL_TABLE_BUCKETS; bucket++)
  443. state.symtable->buckets[bucket] = NULL;
  444. if ((error_info = tokenize(&state)))
  445. goto error;
  446. if ((error_info = resolve_defaults(&state)))
  447. goto error;
  448. if ((error_info = resolve_symbols(&state)))
  449. goto error;
  450. uint8_t *binary = malloc(sizeof(uint8_t) * state.rom_size);
  451. if (!binary)
  452. OUT_OF_MEMORY()
  453. serialize_binary(&state, binary);
  454. *binary_ptr = binary;
  455. retval = state.rom_size;
  456. goto cleanup;
  457. error:
  458. *ei_ptr = error_info;
  459. cleanup:
  460. asm_lines_free(state.lines);
  461. asm_includes_free(state.includes);
  462. asm_instructions_free(state.instructions);
  463. asm_symtable_free(state.symtable);
  464. return retval;
  465. }
  466. /*
  467. Assemble the z80 source code at the input path into a binary file.
  468. Return true if the operation was a success and false if it was a failure.
  469. Errors are printed to STDOUT; if the operation was successful then nothing
  470. is printed.
  471. */
  472. bool assemble_file(const char *src_path, const char *dst_path)
  473. {
  474. LineBuffer *source = read_source_file(src_path, true);
  475. if (!source)
  476. return false;
  477. uint8_t *binary;
  478. ErrorInfo *error_info;
  479. size_t size = assemble(source, &binary, &error_info);
  480. line_buffer_free(source);
  481. if (!size) {
  482. error_info_print(error_info, stderr);
  483. error_info_destroy(error_info);
  484. return false;
  485. }
  486. bool success = write_binary_file(dst_path, binary, size);
  487. free(binary);
  488. return success;
  489. }