An emulator, assembler, and disassembler for the Sega Game Gear
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 

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