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.
 
 
 
 
 

522 lines
16 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 <stdbool.h>
  6. #include <stdint.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include "preprocessor.h"
  11. #include "directives.h"
  12. #include "errors.h"
  13. #include "io.h"
  14. #include "parse_util.h"
  15. #include "../logging.h"
  16. #include "../rom.h"
  17. #include "../util.h"
  18. /* Helper macros for preprocess() */
  19. #define FAIL_ON_COND_(cond, err_desc) \
  20. if ((cond)) { \
  21. ei = error_info_create(line, ET_PREPROC, err_desc); \
  22. goto cleanup; \
  23. }
  24. #define CALL_GENERIC_PARSER_(arg_type) \
  25. parse_##arg_type((arg_type*) &arg, line, directive)
  26. #define CALL_SPECIFIC_PARSER_(arg_type, parser) \
  27. parse_##parser((arg_type*) &arg, line, directive)
  28. #define DISPATCH_(first, second, target, ...) target
  29. #define CALL_PARSER_(...) \
  30. DISPATCH_(__VA_ARGS__, CALL_SPECIFIC_PARSER_, CALL_GENERIC_PARSER_, \
  31. __VA_ARGS__)(__VA_ARGS__)
  32. #define VALIDATE(func) \
  33. FAIL_ON_COND_(!(func(arg)), ED_PP_BAD_ARG)
  34. #define CHECK_RANGE(bound) \
  35. FAIL_ON_COND_(arg > bound, ED_PP_ARG_RANGE)
  36. #define USE_PARSER(...) \
  37. FAIL_ON_COND_(!CALL_PARSER_(__VA_ARGS__), ED_PP_BAD_ARG)
  38. #define PARSER_BRANCH(arg_type, true_part, false_part) \
  39. if (CALL_PARSER_(arg_type)) {true_part} else {false_part}
  40. #define SAVE_LINE(target) \
  41. if (!dir_is_auto) target = line;
  42. #define BEGIN_DIRECTIVE_BLOCK \
  43. ssize_t first_ctr = -1; \
  44. if (0) {}
  45. #define BEGIN_DIRECTIVE(d, arg_type, dest_loc, auto_val) \
  46. else if (first_ctr++, IS_DIRECTIVE(line, d)) { \
  47. directive = d; \
  48. FAIL_ON_COND_(!DIRECTIVE_HAS_ARG(line, directive), ED_PP_NO_ARG) \
  49. arg_type arg = 0; \
  50. arg_type* dest = &(dest_loc); \
  51. bool dir_is_auto = DIRECTIVE_IS_AUTO(line, directive); \
  52. if (dir_is_auto) { \
  53. arg = auto_val; \
  54. } else {
  55. #define END_DIRECTIVE \
  56. } \
  57. if (firsts[first_ctr] && *dest != arg) { \
  58. ei = error_info_create(line, ET_PREPROC, ED_PP_DUPLICATE); \
  59. error_info_append(ei, firsts[first_ctr]); \
  60. goto cleanup; \
  61. } \
  62. *dest = arg; \
  63. firsts[first_ctr] = line; \
  64. }
  65. #define END_DIRECTIVE_BLOCK \
  66. else FAIL_ON_COND_(true, ED_PP_UNKNOWN)
  67. /*
  68. Return whether the given character is a valid label character.
  69. */
  70. static inline bool is_valid_label_char(char c, bool first)
  71. {
  72. return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
  73. (!first && c >= '0' && c <= '9') || c == '_';
  74. }
  75. /*
  76. Preprocess a single source line for labels.
  77. Return the index of first non-whitespace non-label character. *head_ptr is
  78. updated to the first label in sequence, and *tail_ptr to the last. Both
  79. will be set to NULL if the line doesn't contain labels.
  80. */
  81. static size_t read_labels(
  82. const char *source, size_t length, ASMLine **head_ptr, ASMLine **tail_ptr)
  83. {
  84. size_t start = 0, i, nexti;
  85. while (start < length && (source[start] == ' ' || source[start] == '\t'))
  86. start++;
  87. i = start;
  88. while (i < length && is_valid_label_char(source[i], i == start))
  89. i++;
  90. if (i == start || i == length || source[i] != ':') {
  91. *head_ptr = NULL;
  92. *tail_ptr = NULL;
  93. return 0;
  94. }
  95. ASMLine *line = malloc(sizeof(ASMLine));
  96. if (!line)
  97. OUT_OF_MEMORY()
  98. line->data = malloc(sizeof(char) * (i - start + 1));
  99. if (!line->data)
  100. OUT_OF_MEMORY()
  101. strncpy(line->data, source + start, i - start + 1);
  102. line->length = i - start + 1;
  103. nexti = read_labels(source + i + 1, length - i - 1, &line->next, tail_ptr);
  104. *head_ptr = line;
  105. if (!nexti)
  106. *tail_ptr = line;
  107. return i + 1 + nexti;
  108. }
  109. /*
  110. Preprocess a single source line (source, length) into one or more ASMLines.
  111. Only the data, length, and next fields of the ASMLine objects are
  112. populated. The normalization process strips comments, makes various
  113. adjustments outside of string literals (converts tabs to spaces, lowercases
  114. all alphabetical characters, and removes runs of multiple spaces), among
  115. other things.
  116. Return NULL if an ASM line was not generated from the source, i.e. if it is
  117. blank after being stripped.
  118. */
  119. static ASMLine* normalize_line(const char *source, size_t length)
  120. {
  121. ASMLine *head, *tail;
  122. size_t offset = read_labels(source, length, &head, &tail);
  123. source += offset;
  124. length -= offset;
  125. char *data = malloc(sizeof(char) * length);
  126. if (!data)
  127. OUT_OF_MEMORY()
  128. size_t si, di, slashes = 0;
  129. bool has_content = false, space_pending = false, in_string = false;
  130. for (si = di = 0; si < length; si++) {
  131. char c = source[si];
  132. if (c == '\\')
  133. slashes++;
  134. else
  135. slashes = 0;
  136. if (in_string) {
  137. if (c == '"' && (slashes % 2) == 0)
  138. in_string = false;
  139. data[di++] = c;
  140. } else {
  141. if (c == ';')
  142. break;
  143. if (c == '"' && (slashes % 2) == 0)
  144. in_string = true;
  145. if (c >= 'A' && c <= 'Z')
  146. c += 'a' - 'A';
  147. if (c == ' ' || c == '\t')
  148. space_pending = true;
  149. else {
  150. if (space_pending) {
  151. if (has_content)
  152. data[di++] = ' ';
  153. space_pending = false;
  154. }
  155. has_content = true;
  156. data[di++] = c;
  157. }
  158. }
  159. }
  160. if (!has_content) {
  161. free(data);
  162. return head;
  163. }
  164. ASMLine *line = malloc(sizeof(ASMLine));
  165. if (!line)
  166. OUT_OF_MEMORY()
  167. data = realloc(data, sizeof(char) * di);
  168. if (!data)
  169. OUT_OF_MEMORY()
  170. line->data = data;
  171. line->length = di;
  172. line->next = NULL;
  173. if (head) { // Line has labels, so link the main part up
  174. tail->next = line;
  175. return head;
  176. }
  177. return line;
  178. }
  179. /*
  180. Read and return the target path from an include directive.
  181. This function allocates a buffer to store the filename; it must be free()'d
  182. after calling read_source_file(). If a syntax error occurs while trying to
  183. read the path, it returns NULL.
  184. */
  185. static char* read_include_path(const ASMLine *line)
  186. {
  187. size_t maxlen = strlen(line->filename) + line->length, i, start, slashes;
  188. if (maxlen >= INT_MAX) // Allows us to safely downcast to int later
  189. return NULL;
  190. char *path = malloc(sizeof(char) * maxlen);
  191. if (!path)
  192. OUT_OF_MEMORY()
  193. if (!(i = DIRECTIVE_OFFSET(line, DIR_INCLUDE)))
  194. goto error;
  195. if (line->length - i <= 4) // Not long enough to hold a non-zero argument
  196. goto error;
  197. if (line->data[i++] != ' ' || line->data[i++] != '"')
  198. goto error;
  199. // TODO: parse escaped characters properly <-- use new parse_util func here
  200. for (start = i, slashes = 0; i < line->length; i++) {
  201. if (line->data[i] == '"' && (slashes % 2) == 0)
  202. break;
  203. if (line->data[i] == '\\')
  204. slashes++;
  205. else
  206. slashes = 0;
  207. }
  208. if (i != line->length - 1) // Junk present after closing quote
  209. goto error;
  210. char *dup = strdup(line->filename);
  211. if (!dup)
  212. OUT_OF_MEMORY()
  213. // TODO: should normalize filenames in some way to prevent accidental dupes
  214. snprintf(path, maxlen, "%s/%.*s", dirname(dup), (int) (i - start),
  215. line->data + start);
  216. free(dup);
  217. return path;
  218. error:
  219. free(path);
  220. return NULL;
  221. }
  222. /*
  223. Return whether the given path has already been loaded.
  224. */
  225. static bool path_has_been_loaded(
  226. const char *path, const LineBuffer *root, const ASMInclude *include)
  227. {
  228. if (!strcmp(path, root->filename))
  229. return true;
  230. while (include) {
  231. if (!strcmp(path, include->lines->filename))
  232. return true;
  233. include = include->next;
  234. }
  235. return false;
  236. }
  237. /*
  238. Build a LineBuffer into a ASMLines, normalizing them along the way.
  239. This function operates recursively to handle includes, but handles no other
  240. preprocessor directives.
  241. On success, NULL is returned; *head points to the head of the new ASMLine
  242. list, and *tail to its tail (assuming it is non-NULL). On error, an
  243. ErrorInfo object is returned, and *head and *tail are not modified.
  244. *includes may be updated in either case.
  245. */
  246. static ErrorInfo* build_asm_lines(
  247. const LineBuffer *root, const LineBuffer *source, ASMLine **head,
  248. ASMLine **tail, ASMInclude **includes)
  249. {
  250. ErrorInfo *ei;
  251. ASMLine dummy = {.next = NULL};
  252. ASMLine *line, *prev = &dummy, *temp;
  253. const Line *orig, *next_orig = source->lines;
  254. while ((orig = next_orig)) {
  255. line = temp = normalize_line(orig->data, orig->length);
  256. next_orig = orig->next;
  257. if (!line)
  258. continue;
  259. // Populate ASMLine fields not set by normalize_line():
  260. while (temp) {
  261. temp->original = orig;
  262. temp->filename = source->filename;
  263. temp = temp->next;
  264. }
  265. // If there are multiple ASMLines, all but the last must be labels:
  266. while (line->next) {
  267. prev->next = line;
  268. prev = line;
  269. line = line->next;
  270. }
  271. if (IS_DIRECTIVE(line, DIR_INCLUDE)) {
  272. char *path = read_include_path(line);
  273. if (!path) {
  274. ei = error_info_create(line, ET_INCLUDE, ED_INC_BAD_ARG);
  275. goto error;
  276. }
  277. if (path_has_been_loaded(path, root, *includes)) {
  278. free(path);
  279. ei = error_info_create(line, ET_INCLUDE, ED_INC_RECURSION);
  280. goto error;
  281. }
  282. DEBUG("- reading included file: %s", path)
  283. LineBuffer *incbuffer = read_source_file(path, false);
  284. free(path);
  285. if (!incbuffer) {
  286. ei = error_info_create(line, ET_INCLUDE, ED_INC_FILE_READ);
  287. goto error;
  288. }
  289. ASMInclude *include = malloc(sizeof(ASMInclude));
  290. if (!include)
  291. OUT_OF_MEMORY()
  292. include->lines = incbuffer;
  293. include->next = *includes;
  294. *includes = include;
  295. ASMLine *inchead, *inctail;
  296. if ((ei = build_asm_lines(root, incbuffer, &inchead, &inctail,
  297. includes))) {
  298. error_info_append(ei, line);
  299. goto error;
  300. }
  301. prev->next = inchead;
  302. prev = inctail;
  303. asm_lines_free(line); // Destroy only the .include line
  304. }
  305. else {
  306. prev->next = line;
  307. prev = line;
  308. }
  309. }
  310. *head = dummy.next;
  311. if (tail)
  312. *tail = prev;
  313. return NULL;
  314. error:
  315. asm_lines_free(line);
  316. asm_lines_free(dummy.next);
  317. return ei;
  318. }
  319. /*
  320. Return whether the given ROM size is valid.
  321. */
  322. static inline bool is_rom_size_valid(size_t size)
  323. {
  324. return size_bytes_to_code(size) != INVALID_SIZE_CODE;
  325. }
  326. /*
  327. Return whether the given header offset is a valid location.
  328. */
  329. static inline bool is_header_offset_valid(uint16_t offset)
  330. {
  331. return offset == 0x7FF0 || offset == 0x3FF0 || offset == 0x1FF0;
  332. }
  333. /*
  334. Preprocess the LineBuffer into ASMLines. Change some state along the way.
  335. This function processes include directives, so read_source_file() may be
  336. called multiple times (along with the implications that has), and
  337. state->includes may be modified.
  338. On success, NULL is returned. On error, an ErrorInfo object is returned.
  339. state->lines and state->includes may still be modified.
  340. */
  341. ErrorInfo* preprocess(AssemblerState *state, const LineBuffer *source)
  342. {
  343. ErrorInfo* ei = NULL;
  344. DEBUG("Running preprocessor:")
  345. if ((ei = build_asm_lines(source, source, &state->lines, NULL,
  346. &state->includes)))
  347. return ei;
  348. const ASMLine *firsts[NUM_DIRECTIVES];
  349. for (size_t i = 0; i < NUM_DIRECTIVES; i++)
  350. firsts[i] = NULL;
  351. ASMLine dummy = {.next = state->lines};
  352. ASMLine *prev, *line = &dummy, *next = state->lines, *condemned = NULL;
  353. const ASMLine *rom_size_line = NULL, *rom_declsize_line = NULL;
  354. const char *directive;
  355. while ((prev = line, line = next)) {
  356. next = line->next;
  357. if (line->data[0] != DIRECTIVE_MARKER)
  358. continue;
  359. if (IS_LOCAL_DIRECTIVE(line))
  360. continue; // "Local" directives are handled by the tokenizer
  361. DEBUG("- handling directive: %.*s", (int) line->length, line->data)
  362. BEGIN_DIRECTIVE_BLOCK
  363. BEGIN_DIRECTIVE(DIR_OPTIMIZER, bool, state->optimizer, false)
  364. USE_PARSER(bool)
  365. END_DIRECTIVE
  366. BEGIN_DIRECTIVE(DIR_ROM_SIZE, size_t, state->rom_size, 0)
  367. PARSER_BRANCH(uint32_t, {}, {
  368. USE_PARSER(uint32_t, rom_size)
  369. })
  370. VALIDATE(is_rom_size_valid)
  371. SAVE_LINE(rom_size_line)
  372. END_DIRECTIVE
  373. BEGIN_DIRECTIVE(DIR_ROM_HEADER, size_t, state->header.offset, DEFAULT_HEADER_OFFSET)
  374. USE_PARSER(uint16_t)
  375. VALIDATE(is_header_offset_valid)
  376. END_DIRECTIVE
  377. BEGIN_DIRECTIVE(DIR_ROM_CHECKSUM, bool, state->header.checksum, true)
  378. USE_PARSER(bool)
  379. END_DIRECTIVE
  380. BEGIN_DIRECTIVE(DIR_ROM_PRODUCT, uint32_t, state->header.product_code, 0)
  381. USE_PARSER(uint32_t)
  382. CHECK_RANGE(160000)
  383. END_DIRECTIVE
  384. BEGIN_DIRECTIVE(DIR_ROM_VERSION, uint8_t, state->header.version, 0)
  385. USE_PARSER(uint8_t)
  386. CHECK_RANGE(0x10)
  387. END_DIRECTIVE
  388. BEGIN_DIRECTIVE(DIR_ROM_REGION, uint8_t, state->header.region, DEFAULT_REGION)
  389. PARSER_BRANCH(uint8_t, {
  390. CHECK_RANGE(0x10)
  391. VALIDATE(region_code_to_string)
  392. }, {
  393. USE_PARSER(uint8_t, region_string)
  394. })
  395. END_DIRECTIVE
  396. BEGIN_DIRECTIVE(DIR_ROM_DECLSIZE, uint8_t, state->header.rom_size, DEFAULT_DECLSIZE)
  397. PARSER_BRANCH(uint8_t, {
  398. CHECK_RANGE(0x10)
  399. VALIDATE(size_code_to_bytes)
  400. }, {
  401. USE_PARSER(uint8_t, size_code)
  402. })
  403. SAVE_LINE(rom_declsize_line)
  404. END_DIRECTIVE
  405. END_DIRECTIVE_BLOCK
  406. // Remove directive from lines, and schedule it for deletion:
  407. line->next = condemned;
  408. condemned = line;
  409. prev->next = next;
  410. line = prev;
  411. }
  412. if (rom_size_line && state->header.offset + HEADER_SIZE > state->rom_size) {
  413. // TODO: maybe should force offset to be explicit, otherwise autofix
  414. ei = error_info_create(rom_size_line, ET_LAYOUT, ED_LYT_HEADER_RANGE);
  415. goto cleanup;
  416. }
  417. if (rom_size_line && rom_declsize_line &&
  418. size_code_to_bytes(state->header.rom_size) > state->rom_size) {
  419. ei = error_info_create(rom_size_line, ET_LAYOUT, ED_LYT_DECLARE_RANGE);
  420. error_info_append(ei, rom_declsize_line);
  421. goto cleanup;
  422. }
  423. if (!rom_declsize_line) // Mark as undefined, for resolve_defaults()
  424. state->header.rom_size = INVALID_SIZE_CODE;
  425. cleanup:
  426. asm_lines_free(condemned);
  427. state->lines = dummy.next; // Fix list head if first line was a directive
  428. return ei;
  429. }