An emulator, assembler, and disassembler for the Sega Game Gear
Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 

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