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.
 
 
 
 
 

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