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.
 
 
 
 
 

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