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.
 
 
 
 
 

448 lines
14 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. Preprocess a single source line (source, length) into a normalized ASMLine.
  69. *Only* the data and length fields in the ASMLine object are populated. The
  70. normalization process converts tabs to spaces, lowercases all alphabetical
  71. characters, and removes runs of multiple spaces (outside of string
  72. literals), strips comments, and other things.
  73. Return NULL if an ASM line was not generated from the source, i.e. if it is
  74. blank after being stripped.
  75. */
  76. static ASMLine* normalize_line(const char *source, size_t length)
  77. {
  78. char *data = malloc(sizeof(char) * length);
  79. if (!data)
  80. OUT_OF_MEMORY()
  81. size_t si, di, slashes = 0;
  82. bool has_content = false, space_pending = false, in_string = false;
  83. for (si = di = 0; si < length; si++) {
  84. char c = source[si];
  85. if (c == '\\')
  86. slashes++;
  87. else
  88. slashes = 0;
  89. if (in_string) {
  90. if (c == '"' && (slashes % 2) == 0)
  91. in_string = false;
  92. data[di++] = c;
  93. } else {
  94. if (c == ';')
  95. break;
  96. if (c == '"' && (slashes % 2) == 0)
  97. in_string = true;
  98. if (c >= 'A' && c <= 'Z')
  99. c += 'a' - 'A';
  100. if (c == ' ' || c == '\t')
  101. space_pending = true;
  102. else {
  103. if (space_pending) {
  104. if (has_content)
  105. data[di++] = ' ';
  106. space_pending = false;
  107. }
  108. has_content = true;
  109. data[di++] = c;
  110. }
  111. }
  112. }
  113. if (!has_content) {
  114. free(data);
  115. return NULL;
  116. }
  117. ASMLine *line = malloc(sizeof(ASMLine));
  118. if (!line)
  119. OUT_OF_MEMORY()
  120. data = realloc(data, sizeof(char) * di);
  121. if (!data)
  122. OUT_OF_MEMORY()
  123. line->data = data;
  124. line->length = di;
  125. return line;
  126. }
  127. /*
  128. Read and return the target path from an include directive.
  129. This function allocates a buffer to store the filename; it must be free()'d
  130. after calling read_source_file(). If a syntax error occurs while trying to
  131. read the path, it returns NULL.
  132. */
  133. static char* read_include_path(const ASMLine *line)
  134. {
  135. size_t maxlen = strlen(line->filename) + line->length, i, start, slashes;
  136. if (maxlen >= INT_MAX) // Allows us to safely downcast to int later
  137. return NULL;
  138. char *path = malloc(sizeof(char) * maxlen);
  139. if (!path)
  140. OUT_OF_MEMORY()
  141. if (!(i = DIRECTIVE_OFFSET(line, DIR_INCLUDE)))
  142. goto error;
  143. if (line->length - i <= 4) // Not long enough to hold a non-zero argument
  144. goto error;
  145. if (line->data[i++] != ' ' || line->data[i++] != '"')
  146. goto error;
  147. // TODO: parse escaped characters properly
  148. for (start = i, slashes = 0; i < line->length; i++) {
  149. if (line->data[i] == '"' && (slashes % 2) == 0)
  150. break;
  151. if (line->data[i] == '\\')
  152. slashes++;
  153. else
  154. slashes = 0;
  155. }
  156. if (i != line->length - 1) // Junk present after closing quote
  157. goto error;
  158. char *dup = strdup(line->filename);
  159. if (!dup)
  160. OUT_OF_MEMORY()
  161. // TODO: should normalize filenames in some way to prevent accidental dupes
  162. snprintf(path, maxlen, "%s/%.*s", dirname(dup), (int) (i - start),
  163. line->data + start);
  164. free(dup);
  165. return path;
  166. error:
  167. free(path);
  168. return NULL;
  169. }
  170. /*
  171. Return whether the given path has already been loaded.
  172. */
  173. static bool path_has_been_loaded(
  174. const char *path, const LineBuffer *root, const ASMInclude *include)
  175. {
  176. if (!strcmp(path, root->filename))
  177. return true;
  178. while (include) {
  179. if (!strcmp(path, include->lines->filename))
  180. return true;
  181. include = include->next;
  182. }
  183. return false;
  184. }
  185. /*
  186. Build a LineBuffer into a ASMLines, normalizing them along the way.
  187. This function operates recursively to handle includes, but handles no other
  188. preprocessor directives.
  189. On success, NULL is returned; *head points to the head of the new ASMLine
  190. list, and *tail to its tail (assuming it is non-NULL). On error, an
  191. ErrorInfo object is returned, and *head and *tail are not modified.
  192. *includes may be updated in either case.
  193. */
  194. static ErrorInfo* build_asm_lines(
  195. const LineBuffer *root, const LineBuffer *source, ASMLine **head,
  196. ASMLine **tail, ASMInclude **includes)
  197. {
  198. ErrorInfo *ei;
  199. ASMLine dummy = {.next = NULL};
  200. ASMLine *line, *prev = &dummy;
  201. const Line *orig, *next_orig = source->lines;
  202. while ((orig = next_orig)) {
  203. line = normalize_line(orig->data, orig->length);
  204. next_orig = orig->next;
  205. if (!line)
  206. continue;
  207. // Populate ASMLine fields not set by normalize_line():
  208. line->original = orig;
  209. line->filename = source->filename;
  210. line->next = NULL;
  211. if (IS_DIRECTIVE(line, DIR_INCLUDE)) {
  212. char *path = read_include_path(line);
  213. if (!path) {
  214. ei = error_info_create(line, ET_INCLUDE, ED_INC_BAD_ARG);
  215. goto error;
  216. }
  217. if (path_has_been_loaded(path, root, *includes)) {
  218. free(path);
  219. ei = error_info_create(line, ET_INCLUDE, ED_INC_RECURSION);
  220. goto error;
  221. }
  222. DEBUG("- reading included file: %s", path)
  223. LineBuffer *incbuffer = read_source_file(path, false);
  224. free(path);
  225. if (!incbuffer) {
  226. ei = error_info_create(line, ET_INCLUDE, ED_INC_FILE_READ);
  227. goto error;
  228. }
  229. ASMInclude *include = malloc(sizeof(ASMInclude));
  230. if (!include)
  231. OUT_OF_MEMORY()
  232. include->lines = incbuffer;
  233. include->next = *includes;
  234. *includes = include;
  235. ASMLine *inchead, *inctail;
  236. if ((ei = build_asm_lines(root, incbuffer, &inchead, &inctail,
  237. includes))) {
  238. error_info_append(ei, line);
  239. goto error;
  240. }
  241. prev->next = inchead;
  242. prev = inctail;
  243. asm_lines_free(line); // Destroy only the .include line
  244. }
  245. else {
  246. prev->next = line;
  247. prev = line;
  248. }
  249. }
  250. *head = dummy.next;
  251. if (tail)
  252. *tail = prev;
  253. return NULL;
  254. error:
  255. asm_lines_free(line);
  256. asm_lines_free(dummy.next);
  257. return ei;
  258. }
  259. /*
  260. Return whether the given ROM size is valid.
  261. */
  262. static inline bool is_rom_size_valid(size_t size)
  263. {
  264. return size_bytes_to_code(size) != INVALID_SIZE_CODE;
  265. }
  266. /*
  267. Return whether the given header offset is a valid location.
  268. */
  269. static inline bool is_header_offset_valid(uint16_t offset)
  270. {
  271. return offset == 0x7FF0 || offset == 0x3FF0 || offset == 0x1FF0;
  272. }
  273. /*
  274. Preprocess the LineBuffer into ASMLines. Change some state along the way.
  275. This function processes include directives, so read_source_file() may be
  276. called multiple times (along with the implications that has), and
  277. state->includes may be modified.
  278. On success, NULL is returned. On error, an ErrorInfo object is returned.
  279. state->lines and state->includes may still be modified.
  280. */
  281. ErrorInfo* preprocess(AssemblerState *state, const LineBuffer *source)
  282. {
  283. ErrorInfo* ei = NULL;
  284. DEBUG("Running preprocessor:")
  285. if ((ei = build_asm_lines(source, source, &state->lines, NULL,
  286. &state->includes)))
  287. return ei;
  288. const ASMLine *firsts[NUM_DIRECTIVES];
  289. for (size_t i = 0; i < NUM_DIRECTIVES; i++)
  290. firsts[i] = NULL;
  291. ASMLine dummy = {.next = state->lines};
  292. ASMLine *prev, *line = &dummy, *next = state->lines, *condemned = NULL;
  293. const ASMLine *rom_size_line = NULL, *rom_declsize_line = NULL;
  294. const char *directive;
  295. while ((prev = line, line = next)) {
  296. next = line->next;
  297. if (line->data[0] != DIRECTIVE_MARKER)
  298. continue;
  299. if (IS_DIRECTIVE(line, DIR_ORIGIN))
  300. continue; // Origins are handled by tokenizer
  301. DEBUG("- handling directive: %.*s", (int) line->length, line->data)
  302. BEGIN_DIRECTIVE_BLOCK
  303. BEGIN_DIRECTIVE(DIR_OPTIMIZER, bool, state->optimizer, false)
  304. USE_PARSER(bool)
  305. END_DIRECTIVE
  306. BEGIN_DIRECTIVE(DIR_ROM_SIZE, size_t, state->rom_size, 0)
  307. PARSER_BRANCH(uint32_t, {}, {
  308. USE_PARSER(uint32_t, rom_size)
  309. })
  310. VALIDATE(is_rom_size_valid)
  311. SAVE_LINE(rom_size_line)
  312. END_DIRECTIVE
  313. BEGIN_DIRECTIVE(DIR_ROM_HEADER, size_t, state->header.offset, DEFAULT_HEADER_OFFSET)
  314. USE_PARSER(uint16_t)
  315. VALIDATE(is_header_offset_valid)
  316. END_DIRECTIVE
  317. BEGIN_DIRECTIVE(DIR_ROM_CHECKSUM, bool, state->header.checksum, true)
  318. USE_PARSER(bool)
  319. END_DIRECTIVE
  320. BEGIN_DIRECTIVE(DIR_ROM_PRODUCT, uint32_t, state->header.product_code, 0)
  321. USE_PARSER(uint32_t)
  322. CHECK_RANGE(160000)
  323. END_DIRECTIVE
  324. BEGIN_DIRECTIVE(DIR_ROM_VERSION, uint8_t, state->header.version, 0)
  325. USE_PARSER(uint8_t)
  326. CHECK_RANGE(0x10)
  327. END_DIRECTIVE
  328. BEGIN_DIRECTIVE(DIR_ROM_REGION, uint8_t, state->header.region, DEFAULT_REGION)
  329. PARSER_BRANCH(uint8_t, {
  330. CHECK_RANGE(0x10)
  331. VALIDATE(region_code_to_string)
  332. }, {
  333. USE_PARSER(uint8_t, region_string)
  334. })
  335. END_DIRECTIVE
  336. BEGIN_DIRECTIVE(DIR_ROM_DECLSIZE, uint8_t, state->header.rom_size, DEFAULT_DECLSIZE)
  337. PARSER_BRANCH(uint8_t, {
  338. CHECK_RANGE(0x10)
  339. VALIDATE(size_code_to_bytes)
  340. }, {
  341. USE_PARSER(uint8_t, size_code)
  342. })
  343. SAVE_LINE(rom_declsize_line)
  344. END_DIRECTIVE
  345. END_DIRECTIVE_BLOCK
  346. // Remove directive from lines, and schedule it for deletion:
  347. line->next = condemned;
  348. condemned = line;
  349. prev->next = next;
  350. line = prev;
  351. }
  352. if (rom_size_line && state->header.offset + HEADER_SIZE > state->rom_size) {
  353. ei = error_info_create(rom_size_line, ET_PREPROC, ED_PP_HEADER_RANGE);
  354. goto cleanup;
  355. }
  356. if (rom_size_line && rom_declsize_line &&
  357. size_code_to_bytes(state->header.rom_size) > state->rom_size) {
  358. ei = error_info_create(rom_size_line, ET_PREPROC, ED_PP_DECLARE_RANGE);
  359. error_info_append(ei, rom_declsize_line);
  360. goto cleanup;
  361. }
  362. if (!rom_declsize_line) // Mark as undefined, for resolve_defaults()
  363. state->header.rom_size = INVALID_SIZE_CODE;
  364. cleanup:
  365. asm_lines_free(condemned);
  366. state->lines = dummy.next; // Fix list head if first line was a directive
  367. return ei;
  368. }