An emulator, assembler, and disassembler for the Sega Game Gear
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 

516 рядки
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. dparse_##arg_type((arg_type*) &arg, line, directive)
  26. #define CALL_SPECIFIC_PARSER_(arg_type, parser) \
  27. dparse_##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 == '_' || 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. line->is_label = true;
  104. nexti = read_labels(source + i + 1, length - i - 1, &line->next, tail_ptr);
  105. *head_ptr = line;
  106. if (!nexti)
  107. *tail_ptr = line;
  108. return i + 1 + nexti;
  109. }
  110. /*
  111. Preprocess a single source line (source, length) into one or more ASMLines.
  112. Only the data, length, is_label, and next fields of the ASMLine objects are
  113. populated. The normalization process strips comments, makes various
  114. adjustments outside of string literals (converts tabs to spaces, lowercases
  115. all alphabetical characters, and removes runs of multiple spaces), among
  116. other things.
  117. Return NULL if an ASM line was not generated from the source, i.e. if it is
  118. blank after being stripped.
  119. */
  120. static ASMLine* normalize_line(const char *source, size_t length)
  121. {
  122. ASMLine *head, *tail;
  123. size_t offset = read_labels(source, length, &head, &tail);
  124. source += offset;
  125. length -= offset;
  126. char *data = malloc(sizeof(char) * length);
  127. if (!data)
  128. OUT_OF_MEMORY()
  129. size_t si, di, slashes = 0;
  130. bool has_content = false, space_pending = false, in_string = false;
  131. for (si = di = 0; si < length; si++) {
  132. char c = source[si];
  133. if (c == '\\')
  134. slashes++;
  135. else
  136. slashes = 0;
  137. if (in_string) {
  138. if (c == '"' && (slashes % 2) == 0)
  139. in_string = false;
  140. data[di++] = c;
  141. } else {
  142. if (c == ';')
  143. break;
  144. if (c == '"' && (slashes % 2) == 0)
  145. in_string = true;
  146. if (c >= 'A' && c <= 'Z')
  147. c += 'a' - 'A';
  148. if (c == ' ' || c == '\t')
  149. space_pending = true;
  150. else {
  151. if (space_pending) {
  152. if (has_content)
  153. data[di++] = ' ';
  154. space_pending = false;
  155. }
  156. has_content = true;
  157. data[di++] = c;
  158. }
  159. }
  160. }
  161. if (!has_content) {
  162. free(data);
  163. return head;
  164. }
  165. ASMLine *line = malloc(sizeof(ASMLine));
  166. if (!line)
  167. OUT_OF_MEMORY()
  168. data = realloc(data, sizeof(char) * di);
  169. if (!data)
  170. OUT_OF_MEMORY()
  171. line->data = data;
  172. line->length = di;
  173. line->is_label = false;
  174. line->next = NULL;
  175. if (head) { // Line has labels, so link the main part up
  176. tail->next = line;
  177. return head;
  178. }
  179. return line;
  180. }
  181. /*
  182. Read and return the target path from an include directive.
  183. This function allocates a buffer to store the filename; it must be free()'d
  184. after calling read_source_file(). If a syntax error occurs while trying to
  185. read the path, it returns NULL.
  186. */
  187. static char* read_include_path(const ASMLine *line)
  188. {
  189. size_t maxlen = strlen(line->filename) + line->length, i, baselen;
  190. if (maxlen >= INT_MAX) // Allows us to safely downcast to int later
  191. return NULL;
  192. char *path = malloc(sizeof(char) * maxlen), *base, *dup;
  193. if (!path)
  194. OUT_OF_MEMORY()
  195. if (!(i = DIRECTIVE_OFFSET(line, DIR_INCLUDE)))
  196. goto error;
  197. if (line->length - i <= 3) // Not long enough to hold a non-zero argument
  198. goto error;
  199. if (line->data[i++] != ' ')
  200. goto error;
  201. if (!parse_string(&base, &baselen, line->data + i, line->length - i))
  202. goto error;
  203. if (!(dup = strdup(line->filename)))
  204. OUT_OF_MEMORY()
  205. // TODO: should normalize filenames in some way to prevent accidental dupes
  206. snprintf(path, maxlen, "%s/%.*s", dirname(dup), (int) baselen, base);
  207. free(dup);
  208. free(base);
  209. return path;
  210. error:
  211. free(path);
  212. return NULL;
  213. }
  214. /*
  215. Return whether the given path has already been loaded.
  216. */
  217. static bool path_has_been_loaded(
  218. const char *path, const LineBuffer *root, const ASMInclude *include)
  219. {
  220. if (!strcmp(path, root->filename))
  221. return true;
  222. while (include) {
  223. if (!strcmp(path, include->lines->filename))
  224. return true;
  225. include = include->next;
  226. }
  227. return false;
  228. }
  229. /*
  230. Build a LineBuffer into a ASMLines, normalizing them along the way.
  231. This function operates recursively to handle includes, but handles no other
  232. preprocessor directives.
  233. On success, NULL is returned; *head points to the head of the new ASMLine
  234. list, and *tail to its tail (assuming it is non-NULL). On error, an
  235. ErrorInfo object is returned, and *head and *tail are not modified.
  236. *includes may be updated in either case.
  237. */
  238. static ErrorInfo* build_asm_lines(
  239. const LineBuffer *root, const LineBuffer *source, ASMLine **head,
  240. ASMLine **tail, ASMInclude **includes)
  241. {
  242. ErrorInfo *ei;
  243. ASMLine dummy = {.next = NULL};
  244. ASMLine *line, *prev = &dummy, *temp;
  245. const Line *orig, *next_orig = source->lines;
  246. while ((orig = next_orig)) {
  247. line = temp = normalize_line(orig->data, orig->length);
  248. next_orig = orig->next;
  249. if (!line)
  250. continue;
  251. // Populate ASMLine fields not set by normalize_line():
  252. while (temp) {
  253. temp->original = orig;
  254. temp->filename = source->filename;
  255. temp = temp->next;
  256. }
  257. // If there are multiple ASMLines, all but the last must be labels:
  258. while (line->next) {
  259. prev->next = line;
  260. prev = line;
  261. line = line->next;
  262. }
  263. if (IS_DIRECTIVE(line, DIR_INCLUDE)) {
  264. char *path = read_include_path(line);
  265. if (!path) {
  266. ei = error_info_create(line, ET_INCLUDE, ED_INC_BAD_ARG);
  267. goto error;
  268. }
  269. if (path_has_been_loaded(path, root, *includes)) {
  270. free(path);
  271. ei = error_info_create(line, ET_INCLUDE, ED_INC_RECURSION);
  272. goto error;
  273. }
  274. DEBUG("- reading included file: %s", path)
  275. LineBuffer *incbuffer = read_source_file(path, false);
  276. free(path);
  277. if (!incbuffer) {
  278. ei = error_info_create(line, ET_INCLUDE, ED_INC_FILE_READ);
  279. goto error;
  280. }
  281. ASMInclude *include = malloc(sizeof(ASMInclude));
  282. if (!include)
  283. OUT_OF_MEMORY()
  284. include->lines = incbuffer;
  285. include->next = *includes;
  286. *includes = include;
  287. ASMLine *inchead, *inctail;
  288. if ((ei = build_asm_lines(root, incbuffer, &inchead, &inctail,
  289. includes))) {
  290. error_info_append(ei, line);
  291. goto error;
  292. }
  293. prev->next = inchead;
  294. prev = inctail;
  295. asm_lines_free(line); // Destroy only the .include line
  296. }
  297. else {
  298. prev->next = line;
  299. prev = line;
  300. }
  301. }
  302. *head = dummy.next;
  303. if (tail)
  304. *tail = prev;
  305. return NULL;
  306. error:
  307. asm_lines_free(line);
  308. asm_lines_free(dummy.next);
  309. return ei;
  310. }
  311. /*
  312. Return whether the given ROM size is valid.
  313. */
  314. static inline bool is_rom_size_valid(size_t size)
  315. {
  316. return size_bytes_to_code(size) != INVALID_SIZE_CODE;
  317. }
  318. /*
  319. Return whether the given header offset is a valid location.
  320. */
  321. static inline bool is_header_offset_valid(uint16_t offset)
  322. {
  323. return offset == 0x7FF0 || offset == 0x3FF0 || offset == 0x1FF0;
  324. }
  325. /*
  326. Preprocess the LineBuffer into ASMLines. Change some state along the way.
  327. This function processes include directives, so read_source_file() may be
  328. called multiple times (along with the implications that has), and
  329. state->includes may be modified.
  330. On success, NULL is returned. On error, an ErrorInfo object is returned.
  331. state->lines and state->includes may still be modified.
  332. */
  333. ErrorInfo* preprocess(AssemblerState *state, const LineBuffer *source)
  334. {
  335. ErrorInfo* ei = NULL;
  336. DEBUG("Running preprocessor:")
  337. if ((ei = build_asm_lines(source, source, &state->lines, NULL,
  338. &state->includes)))
  339. return ei;
  340. const ASMLine *firsts[NUM_DIRECTIVES];
  341. for (size_t i = 0; i < NUM_DIRECTIVES; i++)
  342. firsts[i] = NULL;
  343. ASMLine dummy = {.next = state->lines};
  344. ASMLine *prev, *line = &dummy, *next = state->lines, *condemned = NULL;
  345. const ASMLine *rom_size_line = NULL, *rom_declsize_line = NULL;
  346. const char *directive;
  347. while ((prev = line, line = next)) {
  348. next = line->next;
  349. if (line->is_label || line->data[0] != DIRECTIVE_MARKER)
  350. continue;
  351. if (IS_LOCAL_DIRECTIVE(line))
  352. continue; // "Local" directives are handled by the tokenizer
  353. DEBUG("- handling directive: %.*s", (int) line->length, line->data)
  354. BEGIN_DIRECTIVE_BLOCK
  355. BEGIN_DIRECTIVE(DIR_OPTIMIZER, bool, state->optimizer, false)
  356. USE_PARSER(bool)
  357. END_DIRECTIVE
  358. BEGIN_DIRECTIVE(DIR_ROM_SIZE, size_t, state->rom_size, 0)
  359. PARSER_BRANCH(uint32_t, {}, {
  360. USE_PARSER(uint32_t, rom_size)
  361. })
  362. VALIDATE(is_rom_size_valid)
  363. SAVE_LINE(rom_size_line)
  364. END_DIRECTIVE
  365. BEGIN_DIRECTIVE(DIR_ROM_HEADER, size_t, state->header.offset, DEFAULT_HEADER_OFFSET)
  366. USE_PARSER(uint16_t)
  367. VALIDATE(is_header_offset_valid)
  368. END_DIRECTIVE
  369. BEGIN_DIRECTIVE(DIR_ROM_CHECKSUM, bool, state->header.checksum, true)
  370. USE_PARSER(bool)
  371. END_DIRECTIVE
  372. BEGIN_DIRECTIVE(DIR_ROM_PRODUCT, uint32_t, state->header.product_code, 0)
  373. USE_PARSER(uint32_t)
  374. CHECK_RANGE(160000)
  375. END_DIRECTIVE
  376. BEGIN_DIRECTIVE(DIR_ROM_VERSION, uint8_t, state->header.version, 0)
  377. USE_PARSER(uint8_t)
  378. CHECK_RANGE(0x10)
  379. END_DIRECTIVE
  380. BEGIN_DIRECTIVE(DIR_ROM_REGION, uint8_t, state->header.region, DEFAULT_REGION)
  381. PARSER_BRANCH(uint8_t, {
  382. CHECK_RANGE(0x10)
  383. VALIDATE(region_code_to_string)
  384. }, {
  385. USE_PARSER(uint8_t, region_string)
  386. })
  387. END_DIRECTIVE
  388. BEGIN_DIRECTIVE(DIR_ROM_DECLSIZE, uint8_t, state->header.rom_size, DEFAULT_DECLSIZE)
  389. PARSER_BRANCH(uint8_t, {
  390. CHECK_RANGE(0x10)
  391. VALIDATE(size_code_to_bytes)
  392. }, {
  393. USE_PARSER(uint8_t, size_code)
  394. })
  395. SAVE_LINE(rom_declsize_line)
  396. END_DIRECTIVE
  397. BEGIN_DIRECTIVE(DIR_CROSS_BLOCKS, bool, state->cross_blocks, false)
  398. USE_PARSER(bool)
  399. END_DIRECTIVE
  400. END_DIRECTIVE_BLOCK
  401. // Remove directive from lines, and schedule it for deletion:
  402. line->next = condemned;
  403. condemned = line;
  404. prev->next = next;
  405. line = prev;
  406. }
  407. if (rom_size_line && state->header.offset + HEADER_SIZE > state->rom_size) {
  408. // TODO: maybe should force offset to be explicit, otherwise autofix
  409. ei = error_info_create(rom_size_line, ET_LAYOUT, ED_LYT_HEADER_RANGE);
  410. goto cleanup;
  411. }
  412. if (rom_size_line && rom_declsize_line &&
  413. size_code_to_bytes(state->header.rom_size) > state->rom_size) {
  414. ei = error_info_create(rom_size_line, ET_LAYOUT, ED_LYT_DECL_RANGE);
  415. error_info_append(ei, rom_declsize_line);
  416. goto cleanup;
  417. }
  418. if (!rom_declsize_line) // Mark as undefined, for resolve_defaults()
  419. state->header.rom_size = INVALID_SIZE_CODE;
  420. cleanup:
  421. asm_lines_free(condemned);
  422. state->lines = dummy.next; // Fix list head if first line was a directive
  423. return ei;
  424. }