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.
 
 
 
 
 

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