Debian Codegraph @

src/input.c

raw symbols SCIP
1 // ACME - a crossassembler for producing 6502/65c02/65816/65ce02 code.
2 // Copyright (C) 1998-2025 Marco Baye
3 // Have a look at "acme.c" for further info
4 //
5 // Input stuff
6 // 19 Nov 2014 Merged Johann Klasek's report listing generator patch
7 // 9 Jan 2018 Allowed "//" comments
8 #include "input.h"
9 #include "config.h"
10 #include "alu.h"
11 #include "dynabuf.h"
12 #include "global.h"
13 #include "platform.h"
14 #include "section.h"
15 #include "symbol.h"
16 #include "tree.h"
17
18
19 // type definitions
20
21 // values for current_input.state
22 enum inputstate {
23 INPUTSTATE_SOF, // start of file (check for BOM and hashbang)
24 INPUTSTATE_NORMAL, // everything's fine
25 INPUTSTATE_AGAIN, // re-process last byte
26 INPUTSTATE_SKIPBLANKS, // shrink multiple spaces
27 INPUTSTATE_LF, // send start-of-line after end-of-statement
28 INPUTSTATE_CR, // same, but also remember to skip LF
29 INPUTSTATE_SKIPLF, // skip LF if that's next
30 INPUTSTATE_COMMENT, // skip characters until newline or EOF
31 INPUTSTATE_EOB, // send end-of-block after end-of-statement
32 INPUTSTATE_EOF, // send end-of-file after end-of-statement
33 INPUTSTATE_BOMCHECK, // first byte in file looks like first byte of BOM
34 INPUTSTATE_BOMFAIL, // send second byte of non-BOM and then the byte read from file
35 };
36
37
38 // constants
39
40 const char FILE_READBINARY[] = "rb";
41 #define CHAR_LF (10) // line feed (in file)
42 // (10) // start of line (in high-level format)
43 #define CHAR_CR (13) // carriage return (in file)
44 // (13) // end of file (in high-level format)
45 // if the characters above are changed, don't forget to adjust byte_flags[]!
46
47 // current input structure
48 static struct input current_input = {
49 {
50 "<none>", // file name where code initially came from (differs during macro execution)
51 0, // line number
52 // (these init values are for error msgs before any real input is established)
53 },
54 INPUTSRC_NONE,
55 INPUTSTATE_EOF, // state of input
56 {
57 NULL // RAM read pointer or file handle
58 },
59 FALSE // do not write to report file
60 };
61
62
63 // variables
64
65 char GotByte; // last byte read (processed)
66 // name of source file used for resolving relative paths
67 // (i.e. not changed during macro execution):
68 const char *input_plat_pathref_filename = ""; // file name in platform format
69
70
71 // functions
72
73 // report generator stuff:
74
75 // remember source code character for report generator
76 #define HEXBUFSIZE 9 // actually, 4+1 is enough, but for systems without snprintf(), let's be extra-safe.
77 #define IF_WANTED_REPORT_SRCCHAR(c) do { if (current_input.report) report_srcchar(c); } while(0)
78
79 static void report_printline(int line_number)
80 {
81 int ii;
82 char hex_address[HEXBUFSIZE];
83 char hexdump[2 * REPORT_BINBUFSIZE + 2 + 1]; // +2 for '.' and terminator, +1 to suppress compiler warning
84
85 // suppress empty lines
86 if (report->bin_used == 0) {
87 if ((report->asc_buf[0] == '\0')
88 || ((report->asc_buf[0] == ' ') && (report->asc_buf[1] == '\0'))) {
89 report->asc_used = 0;
90 return;
91 }
92 }
93
94 // line start after line break detected and EOS processed,
95 // build report line:
96 // show line number...
97 fprintf(report->fd, "%6d ", line_number);
98 // prepare outbytes' start address
99 if (report->bin_used) {
100 #if _BSD_SOURCE || _XOPEN_SOURCE >= 500 || _ISOC99_SOURCE || _POSIX_C_SOURCE >= 200112L
101 snprintf(hex_address, HEXBUFSIZE, "%04x", report->bin_address);
102 #else
103 sprintf(hex_address, "%04x", report->bin_address);
104 #endif
105 } else {
106 hex_address[0] = '\0';
107 }
108 // prepare outbytes
109 hexdump[0] = '\0';
110 for (ii = 0; ii < report->bin_used; ++ii)
111 sprintf(hexdump + 2 * ii, "%02x", (unsigned int) (unsigned char) (report->bin_buf[ii]));
112 // if binary buffer is full, overwrite last byte with "..."
113 if (report->bin_used == REPORT_BINBUFSIZE)
114 sprintf(hexdump + 2 * (REPORT_BINBUFSIZE - 1), "...");
115 // show address and bytes
116 fprintf(report->fd, "%-4s %-19s", hex_address, hexdump);
117 // at this point the output should be a multiple of 8 characters
118 // so far to preserve tabs of the source...
119 if (report->asc_used == REPORT_ASCBUFSIZE)
120 --report->asc_used;
121 report->asc_buf[report->asc_used] = '\0';
122 fprintf(report->fd, "%s\n", report->asc_buf); // show source line
123 report->asc_used = 0; // reset buffers
124 report->bin_used = 0;
125 }
126
127 // flush line buffer
128 static void report_flush(void)
129 {
130 if (current_input.report) {
131 report_printline(current_input.location.line_number);
132 }
133 }
134
135 // insert explanation about change in input
136 static void report_inputchange(const char prefix[], const char filename[])
137 {
138 if (current_input.report) {
139 fprintf(report->fd, "\n; ******** %s%s\n", prefix, filename);
140 report->new_input = TRUE;
141 }
142 }
143
144 static void report_srcchar(int new_char)
145 {
146 static char prev_char = '\0';
147
148 if (new_char == EOF)
149 new_char = '\n';
150
151 if (report->new_input) {
152 report->new_input = FALSE;
153 prev_char = '\0';
154 }
155 if (prev_char == '\n') {
156 report_printline(current_input.location.line_number - 1);
157 }
158 if (new_char != '\n' && new_char != '\r') { // detect line break
159 if (report->asc_used < REPORT_ASCBUFSIZE)
160 report->asc_buf[report->asc_used++] = new_char;
161 }
162 prev_char = new_char;
163 }
164
165
166 // the byte order mark (Unicode code point 0xfeff) becomes 0xef 0xbb 0xbf when
167 // encoded in UTF-8. though UTF-8 files no not need any byte order mark, some
168 // text editors add it anyway. these definitions are used to ignore it instead
169 // of treating it as a label:
170 #define UTF8BOM_1ST 0xef
171 #define UTF8BOM_2ND 0xbb
172 #define UTF8BOM_3RD 0xbf
173 // deliver source code from current file (!) in shortened high-level format
174 static char get_processed_from_file(void)
175 {
176 static int from_file = 0;
177
178 for (;;) {
179 switch (current_input.state) {
180 case INPUTSTATE_SOF:
181 // fetch first byte from the current source file
182 from_file = getc(current_input.u.fd);
183 // check for first byte of UTF-8-encoded BOM
184 if (from_file == UTF8BOM_1ST) {
185 current_input.state = INPUTSTATE_BOMCHECK;
186 break;
187 }
188 IF_WANTED_REPORT_SRCCHAR(from_file);
189 // check for hashbang line and ignore
190 if (from_file == '#') {
191 // remember to skip remainder of line
192 current_input.state = INPUTSTATE_COMMENT;
193 return CHAR_EOS; // end of statement
194 }
195 current_input.state = INPUTSTATE_AGAIN;
196 break;
197 case INPUTSTATE_NORMAL:
198 // fetch a fresh byte from the current source file
199 from_file = getc(current_input.u.fd);
200 IF_WANTED_REPORT_SRCCHAR(from_file);
201 // now process it
202 /*FALLTHROUGH*/
203 case INPUTSTATE_AGAIN:
204 // Process the latest byte again. Of course, this only
205 // makes sense if the loop has executed at least once,
206 // otherwise the contents of from_file are undefined.
207 // If the source is changed so there is a possibility
208 // to enter INPUTSTATE_AGAIN mode without first having
209 // defined "from_file", trouble may arise...
210 current_input.state = INPUTSTATE_NORMAL;
211 // EOF must be checked first because it cannot be used
212 // as an index into global_byte_flags[]
213 if (from_file == EOF) {
214 // remember to send an end-of-file
215 current_input.state = INPUTSTATE_EOF;
216 return CHAR_EOS; // end of statement
217 }
218
219 // check whether character is special one
220 // if not, everything's cool and froody, so return it
221 if (BYTE_IS_SYNTAX_CHAR(from_file) == 0)
222 return (char) from_file;
223
224 // check special characters ("0x00 TAB LF CR SPC / : ; }")
225 switch (from_file) {
226 case '\t':
227 case ' ':
228 // remember to skip all following blanks
229 current_input.state = INPUTSTATE_SKIPBLANKS;
230 return ' ';
231
232 case CHAR_LF: // LF character
233 // remember to send a start-of-line
234 current_input.state = INPUTSTATE_LF;
235 return CHAR_EOS; // end of statement
236
237 case CHAR_CR: // CR character
238 // remember to check CRLF + send start-of-line
239 current_input.state = INPUTSTATE_CR;
240 return CHAR_EOS; // end of statement
241
242 case CHAR_EOB:
243 // remember to send an end-of-block
244 current_input.state = INPUTSTATE_EOB;
245 return CHAR_EOS; // end of statement
246
247 case '/':
248 // to check for "//", get another byte:
249 from_file = getc(current_input.u.fd);
250 IF_WANTED_REPORT_SRCCHAR(from_file);
251 if (from_file != '/') {
252 // not "//", so:
253 current_input.state = INPUTSTATE_AGAIN; // second byte must be parsed normally later on
254 return '/'; // first byte is returned normally right now
255 }
256 // it's really "//", so act as if ';'
257 /*FALLTHROUGH*/
258 case ';':
259 // remember to skip remainder of line
260 current_input.state = INPUTSTATE_COMMENT;
261 return CHAR_EOS; // end of statement
262
263 case ':': // statement delimiter
264 // just deliver an EOS instead
265 return CHAR_EOS; // end of statement
266
267 default:
268 // complain if byte is 0
269 throw_error("Source file contains illegal character."); // FIXME - throw some dynamic "did not expect XYZ character" error instead!
270 return (char) from_file;
271 }
272 case INPUTSTATE_SKIPBLANKS:
273 // read until non-blank, then deliver that
274 do {
275 from_file = getc(current_input.u.fd);
276 IF_WANTED_REPORT_SRCCHAR(from_file);
277 } while ((from_file == '\t') || (from_file == ' '));
278 // re-process last byte
279 current_input.state = INPUTSTATE_AGAIN;
280 break;
281 case INPUTSTATE_LF:
282 // return start-of-line, then continue in normal mode
283 current_input.state = INPUTSTATE_NORMAL;
284 return CHAR_SOL; // new line
285
286 case INPUTSTATE_CR:
287 // return start-of-line, remember to check for LF
288 current_input.state = INPUTSTATE_SKIPLF;
289 return CHAR_SOL; // new line
290
291 case INPUTSTATE_SKIPLF:
292 from_file = getc(current_input.u.fd);
293 IF_WANTED_REPORT_SRCCHAR(from_file);
294 // if LF, ignore it and fetch another byte
295 // otherwise, process current byte
296 if (from_file == CHAR_LF)
297 current_input.state = INPUTSTATE_NORMAL;
298 else
299 current_input.state = INPUTSTATE_AGAIN;
300 break;
301 case INPUTSTATE_COMMENT:
302 // read until end-of-line or end-of-file
303 do {
304 from_file = getc(current_input.u.fd);
305 IF_WANTED_REPORT_SRCCHAR(from_file);
306 } while ((from_file != EOF) && (from_file != CHAR_CR) && (from_file != CHAR_LF));
307 // re-process last byte
308 current_input.state = INPUTSTATE_AGAIN;
309 break;
310 case INPUTSTATE_EOB:
311 // deliver EOB
312 current_input.state = INPUTSTATE_NORMAL;
313 return CHAR_EOB; // end of block
314
315 case INPUTSTATE_EOF:
316 // deliver EOF
317 current_input.state = INPUTSTATE_NORMAL;
318 return CHAR_EOF; // end of file
319
320 // two cases for BOM:
321 case INPUTSTATE_BOMCHECK:
322 // first byte matches BOM, so check second:
323 from_file = getc(current_input.u.fd);
324 if (from_file != UTF8BOM_2ND) {
325 // second byte does not match, so return first byte and remember to re-process second:
326 IF_WANTED_REPORT_SRCCHAR(UTF8BOM_1ST);
327 IF_WANTED_REPORT_SRCCHAR(from_file);
328 current_input.state = INPUTSTATE_AGAIN;
329 return UTF8BOM_1ST;
330 }
331 // first two bytes match BOM, so check third:
332 from_file = getc(current_input.u.fd);
333 if (from_file != UTF8BOM_3RD) {
334 // third byte does not match, so return first byte and make sure the others are delivered later:
335 IF_WANTED_REPORT_SRCCHAR(UTF8BOM_1ST);
336 IF_WANTED_REPORT_SRCCHAR(UTF8BOM_2ND);
337 IF_WANTED_REPORT_SRCCHAR(from_file);
338 current_input.state = INPUTSTATE_BOMFAIL; // next time, deliver second byte
339 return UTF8BOM_1ST;
340 }
341 // found three-byte BOM, so ignore by starting normally with next byte:
342 current_input.state = INPUTSTATE_NORMAL;
343 break;
344
345 case INPUTSTATE_BOMFAIL:
346 // third byte did not match BOM. first byte has already been delivered.
347 // deliver second byte and remember to re-process third:
348 current_input.state = INPUTSTATE_AGAIN; // next time, deliver byte last read
349 return UTF8BOM_2ND;
350
351 default:
352 BUG("StrangeInputMode", current_input.state);
353 }
354 }
355 }
356
357 int subst_chars_left = 0; // number of bytes left in buffer
358 boolean subst_enabled = TRUE; // flag to disable substing (for example while substing, or when copying block to RAM)
359 const char *subst_read_ptr = NULL; // pointer to read bytes from
360 STRUCT_DYNABUF_REF(subst_buffer, 40); // buffer to hold substitution result
361
362 // fetch next byte from buffer
363 static char subst_get_char(void)
364 {
365 if (subst_chars_left-- == 0)
366 BUG("NoSubstLeft", 0);
367 return *(subst_read_ptr++);
368 }
369 // read symbol name from source and then setup substitution buffer with contents
370 // of symbol (string or integer). int is converted to decimal digits.
371 // example:
372 // if "somesymbol" is 42 and "endsymbol" is 47,
373 // basename?(somesymbol)middle?endsymbol=9
374 // becomes
375 // basename42middle47=9
376 // this would happen in two steps,
377 // the first result would be "42m" and the second would be "47="
378 static void subst_substitute(void) // now GotByte = '?'
379 {
380 scope_t tmp_scope;
381 struct symbol *tmp_symbol;
382 boolean parenthesized;
383
384 if (GotByte != '?')
385 BUG("NotQuestionMark", GotByte);
386
387 GetByte(); // eat '?' character
388 // handle parentheses
389 if (GotByte == '(') {
390 GetByte(); // eat '(' character
391 parenthesized = TRUE;
392 } else {
393 parenthesized = FALSE;
394 }
395
396 // reading symbol name will clobber GlobalDynaBuf, so we'll use our own
397 // buffer as tmp storage:
398 dynabuf_clear(subst_buffer);
399 dynabuf_add_bytes(subst_buffer, GlobalDynaBuf->buffer, GlobalDynaBuf->size);
400
401 // read symbol name into GlobalDynaBuf and get symbol ptr:
402 if (input_read_scope_and_symbol_name(&tmp_scope)) {
403 tmp_symbol = NULL; // remember failure (check after restoring GlobalDynaBuf)
404 } else {
405 tmp_symbol = symbol_find(tmp_scope); // reads name from GlobalDynaBuf
406 tmp_symbol->has_been_read = TRUE;
407 }
408
409 // restore previous contents of GlobalDynaBuf:
410 dynabuf_clear(GlobalDynaBuf);
411 dynabuf_add_bytes(GlobalDynaBuf, subst_buffer->buffer, subst_buffer->size);
412
413 // read symbol and put value into subst buffer
414 dynabuf_clear(subst_buffer);
415 if (tmp_symbol == NULL) {
416 goto fail; // input_read_scope_and_symbol_name will have thrown error
417 }
418 if (tmp_symbol->object.type == NULL) {
419 throw_error("Substitution symbol is undefined.");
420 // FIXME - set type to undefined int, just to make sure later refs via type do not crash!
421 goto fail;
422 } else if (tmp_symbol->object.type == &type_number) {
423 if (tmp_symbol->object.u.number.ntype != NUMTYPE_INT) {
424 throw_error("Substitution symbol is undefined or not integer.");
425 goto fail;
426 }
427 dynabuf_add_signed_long(subst_buffer, (long) tmp_symbol->object.u.number.val.intval);
428 } else if (tmp_symbol->object.type == &type_string) {
429 dynabuf_add_bytes(subst_buffer, tmp_symbol->object.u.string->payload, tmp_symbol->object.u.string->length);
430 } else {
431 throw_error("Substitution symbol is neither number nor string.");
432 goto fail;
433 }
434
435 // check for closing parenthesis
436 if (parenthesized) {
437 SKIPSPACE();
438 if (GotByte == ')') {
439 GetByte(); // eat ')'
440 } else {
441 throw_error("Substitution does not end with ')' character.");
442 goto fail;
443 }
444 }
445 // now append the delimiter character to the buffer, otherwise it would
446 // be lost because reading from the buffer keeps clobbering GotByte:
447 dynabuf_append(subst_buffer, GotByte);
448 subst_chars_left = subst_buffer->size;
449 subst_read_ptr = subst_buffer->buffer;
450 // FIXME: do we need checks for "buffer contains braces, colon, EOS, ..."
451 // or is it enough to add "user, do not try stupid things" to docs?
452 return;
453 fail:
454 dynabuf_clear(subst_buffer);
455 dynabuf_append(subst_buffer, GotByte);
456 subst_chars_left = subst_buffer->size;
457 subst_read_ptr = subst_buffer->buffer;
458 }
459
460 // This function delivers the next byte from the currently active byte source
461 // in shortened high-level format. FIXME - use fn ptr?
462 // do not use inside quotes!
463 // CAUTION, symbol substitutions cause this fn to be called recursively!
464 char GetByte(void)
465 {
466 // substitution buffer has priority, so if anything is in there,
467 // deliver that:
468 if (subst_chars_left) {
469 GotByte = subst_get_char();
470 } else {
471 // otherwise get a byte from file/ram:
472
473 // If byte source is RAM, then no conversions are
474 // necessary, because in RAM the source already has
475 // high-level format
476 // Otherwise, the source is a file. This means we will call
477 // get_processed_from_file() which will do a shit load of conversions.
478 switch (current_input.srctype) {
479 case INPUTSRC_RAM:
480 GotByte = *(current_input.u.ram_ptr++);
481 if (current_input.state== INPUTSTATE_NORMAL)
482 IF_WANTED_REPORT_SRCCHAR(GotByte);
483 break;
484 case INPUTSRC_FILE:
485 GotByte = get_processed_from_file();
486 break;
487 default:
488 BUG("IllegalInputSrc", current_input.srctype);
489 }
490
491 if (GotByte == CHAR_SOL)
492 current_input.location.line_number++;
493 }
494 // check for '?' substitutions
495 if ((GotByte == '?') && (subst_enabled) && (subst_chars_left == 0)) {
496 // start a new substitution
497 /*
498 the check for "subst_chars_left" is needed because characters from the buffer
499 are not allowed to start a new substitution, except for the very last char!
500 the last char wasn't part of the result, it was the original delimiter. example:
501 cd = "xyz"
502 !info ab?cd?ef
503 the first '?' causes a lookup for "cd" and will write the result "xyz" to the
504 buffer. then the second '?' (now GotByte because it was the keyword delimiter)
505 will be appended to the buffer because otherwise it would get lost during buffer
506 reads.
507 */
508 subst_enabled = FALSE; // no substitutions in substitutions!
509 subst_substitute(); // do the actual work
510 subst_enabled = TRUE; // back to previous state
511 // because the delimiter is put into the buffer, we know the
512 // buffer isn't empty, even if the substitution result was "".
513 // so this is allowed:
514 GotByte = subst_get_char();
515 }
516 return GotByte;
517 }
518
519 // This function delivers the next byte from the currently active byte source
520 // in un-shortened high-level format.
521 // This function complains if CHAR_EOS (end of statement) is read.
522 static void get_quoted_byte(void)
523 {
524 int from_file; // must be an int to catch EOF
525
526 // substitution buffer has priority, so if anything is in there,
527 // deliver that:
528 if (subst_chars_left) {
529 GotByte = subst_get_char();
530 return;
531 }
532
533 switch (current_input.srctype) {
534 case INPUTSRC_RAM:
535 // if byte source is RAM, then no conversion is necessary,
536 // because in RAM the source already has high-level format
537 GotByte = *(current_input.u.ram_ptr++);
538 IF_WANTED_REPORT_SRCCHAR(GotByte);
539 break;
540 case INPUTSRC_FILE:
541 // fetch a fresh byte from the current source file
542 from_file = getc(current_input.u.fd);
543 IF_WANTED_REPORT_SRCCHAR(from_file);
544 switch (from_file) {
545 case EOF:
546 // remember to send an end-of-file
547 current_input.state = INPUTSTATE_EOF;
548 GotByte = CHAR_EOS; // end of statement
549 break;
550 case CHAR_LF: // LF character
551 // remember to send a start-of-line
552 current_input.state = INPUTSTATE_LF;
553 GotByte = CHAR_EOS; // end of statement
554 break;
555 case CHAR_CR: // CR character
556 // remember to check for CRLF + send a start-of-line
557 current_input.state = INPUTSTATE_CR;
558 GotByte = CHAR_EOS; // end of statement
559 break;
560 default:
561 GotByte = from_file;
562 }
563 break;
564 default:
565 BUG("IllegalInputSrc", current_input.srctype);
566 }
567 // now check for end of statement
568 if (GotByte == CHAR_EOS)
569 throw_error("Quotes still open at end of line.");
570 }
571
572 // ensure that the remainder of the current statement is empty, for example
573 // after mnemonics using implied addressing.
574 void parser_ensure_EOS(void) // now GotByte = first char to test
575 {
576 SKIPSPACE();
577 if (GotByte) {
578 // FIXME - move this to its own function!
579 char buf[80]; // actually needed are 51
580 char quote; // character before and after
581
582 // FIXME - change quoting: do not assume char is printable!
583 quote = (GotByte == '\'') ? '"' : '\''; // use single quotes, unless byte is a single quote (then use double quotes)
584 sprintf(buf, "Expected end-of-statement, found %c%c%c instead.", quote, GotByte, quote);
585 throw_error(buf);
586 parser_skip_remainder();
587 }
588 }
589
590 // read string to dynabuf until closing quote is found
591 // returns 1 on error (unterminated)
592 static int quoted_to_dynabuf(char closing_quote)
593 {
594 boolean escaped = FALSE;
595
596 //dynabuf_clear(GlobalDynaBuf); // do not clear, some callers want to append to existing contents!
597 for (;;) {
598 get_quoted_byte();
599 if (GotByte == CHAR_EOS)
600 return 1; // unterminated string constant; get_quoted_byte will have complained already
601
602 if (escaped) {
603 // previous byte was backslash, so do not check for closing quote nor backslash
604 escaped = FALSE;
605 // do not actually _convert_ escape sequences, that is
606 // done in input_read_string_literal() below!
607 // TODO - but maybe check for illegal escape sequences?
608 // at the moment checking is only done when the string
609 // gets used for something...
610 } else {
611 // non-escaped: only closing quote and backslash are of interest
612 if (GotByte == closing_quote)
613 return 0; // ok
614
615 if (GotByte == '\\') {
616 if (config.dialect >= V0_97__BACKSLASH_ESCAPING) {
617 escaped = TRUE; // since v0.97, backslashes are escape characters
618 } else {
619 // earlier versions did not care about backslashes
620 }
621 }
622 }
623 DYNABUF_APPEND(GlobalDynaBuf, GotByte);
624 }
625 }
626
627 // helper function to assemble a number from hex digits
628 // returns 1 on error
629 static int shift_hex_nibble(char *target, char digit)
630 {
631 if (digit >= '0' && digit <= '9') {
632 digit -= '0';
633 } else if (digit >= 'a' && digit <= 'f') {
634 digit = digit - 'a' + 10;
635 } else if (digit >= 'A' && digit <= 'F') {
636 digit = digit - 'A' + 10;
637 } else {
638 throw_error("Invalid hex digit after \\x, expected 0-9/a-f.");
639 return 1; // error
640 }
641 *target = (*target << 4) | digit;
642 return 0; // ok
643 }
644
645 // state machine for backslash escaping:
646 enum escape {
647 ESCAPE_NONE, // un-escaped, i.e. normal
648 ESCAPE_BACKSLASH, // after reading a backslash
649 ESCAPE_HEX1, // after reading "\x", expecting first hex digit
650 ESCAPE_HEX2, // after reading "\x", expecting second hex digit
651 };
652 // process backslash escapes in GlobalDynaBuf (so size might shrink)
653 // returns 1 on excaping errors
654 int unescape_dynabuf(void)
655 {
656 int read_index = 0,
657 write_index = 0;
658 char byte;
659 enum escape escape_state = ESCAPE_NONE;
660 char hexbyte = 0;
661 int err = 0;
662
663 // CAUTION - contents of dynabuf are not terminated:
664 while (read_index < GlobalDynaBuf->size) {
665 byte = GLOBALDYNABUF_CURRENT[read_index++];
666 switch (escape_state) {
667 case ESCAPE_NONE:
668 if (byte == '\\') {
669 escape_state = ESCAPE_BACKSLASH;
670 } else {
671 GLOBALDYNABUF_CURRENT[write_index++] = byte;
672 }
673 break;
674 case ESCAPE_BACKSLASH:
675 escape_state = ESCAPE_NONE; // default for all chars but 'x'!
676 switch (byte) {
677 case '\\':
678 case '\'':
679 case '"':
680 break;
681 case '0': // NUL
682 byte = 0;
683 break;
684 case 't': // TAB
685 byte = 9;
686 break;
687 case 'n': // LF
688 byte = 10;
689 break;
690 case 'r': // CR
691 byte = 13;
692 break;
693 case 'x': // hex value
694 escape_state = ESCAPE_HEX1; // now expect first hex digit
695 // now an "x" will be written, which will be overwritten later!
696 break;
697 // TODO - 'a' to BEL? others?
698 default:
699 throw_error("Unsupported backslash sequence."); // TODO - add unexpected character to error message?
700 err = 1;
701 }
702 GLOBALDYNABUF_CURRENT[write_index++] = byte;
703 break;
704 case ESCAPE_HEX1:
705 hexbyte = 0;
706 if (shift_hex_nibble(&hexbyte, byte)) {
707 escape_state = ESCAPE_NONE; // error -> back to default state
708 err = 1;
709 } else {
710 escape_state = ESCAPE_HEX2; // ok -> expect second hex digit
711 }
712 break;
713 case ESCAPE_HEX2:
714 if (shift_hex_nibble(&hexbyte, byte)) {
715 err = 1;
716 } else {
717 // parsing "\x" has written "x", so overwrite it:
718 GLOBALDYNABUF_CURRENT[write_index - 1] = hexbyte;
719 }
720 escape_state = ESCAPE_NONE; // go back to default state
721 break;
722 default:
723 BUG("StrangeEscapeState1", escape_state);
724 }
725 }
726 GlobalDynaBuf->size = write_index;
727 switch (escape_state) {
728 case ESCAPE_NONE:
729 break;
730 case ESCAPE_BACKSLASH: // this should have been caught earlier
731 BUG("PartialEscapeSequence", 0);
732 case ESCAPE_HEX1:
733 case ESCAPE_HEX2:
734 throw_error("Expected two hex digits after \\x sequence."); // TODO - add unexpected character to error message?
735 err = 1;
736 break;
737 default:
738 BUG("StrangeEscapeState2", escape_state);
739 }
740 return err;
741 }
742
743
744 // clear dynabuf, read string to it until closing quote is found, then
745 // process backslash escapes (so size might shrink)
746 // returns 1 on error (unterminated or escaping error)
747 int input_read_string_literal(char closing_quote)
748 {
749 dynabuf_clear(GlobalDynaBuf);
750 if (quoted_to_dynabuf(closing_quote))
751 return 1; // unterminated
752
753 // eat closing quote
754 GetByte();
755
756 // since v0.97 we need to process backslashes:
757 if (config.dialect >= V0_97__BACKSLASH_ESCAPING) {
758 return unescape_dynabuf();
759 } else {
760 return 0; // older versions did not support backslash escapes, so return "ok"
761 }
762 }
763
764
765 // skip remainder of statement, for example on error
766 // FIXME - compare to fn below! merge?
767 void parser_skip_remainder(void)
768 {
769 // read characters until end-of-statement, but check for quotes,
770 // otherwise this might treat a quoted colon like EOS!
771 dynabuf_clear(GlobalDynaBuf);
772 while (GotByte != CHAR_EOS) {
773 // check for quotes
774 if ((GotByte == '"') || (GotByte == '\'')) {
775 if (quoted_to_dynabuf(GotByte))
776 break; // error (CHAR_EOS before closing quote)
777 }
778 GetByte();
779 }
780 dynabuf_clear(GlobalDynaBuf);
781 }
782
783 // clear dynabuf, read remainder of statement into it, making sure to keep quoted stuff intact
784 void input_read_statement(char terminator)
785 {
786 int err;
787
788 SKIPSPACE();
789 dynabuf_clear(GlobalDynaBuf);
790 while ((GotByte != terminator) && (GotByte != CHAR_EOS)) {
791 // append to GlobalDynaBuf and check for quotes
792 DYNABUF_APPEND(GlobalDynaBuf, GotByte);
793 if ((GotByte == '"') || (GotByte == '\'')) {
794 err = quoted_to_dynabuf(GotByte);
795 // here GotByte changes, it might become CHAR_EOS
796 DYNABUF_APPEND(GlobalDynaBuf, GotByte); // add closing quotes (or CHAR_EOS) as well
797 if (err)
798 break; // on error, exit before eating CHAR_EOS via GetByte()
799 }
800 GetByte();
801 }
802 dynabuf_append(GlobalDynaBuf, CHAR_EOS); // ensure terminator
803 }
804
805 // Read block into GlobalDynabuf
806 // (reading starts with next byte, so call directly after reading opening brace).
807 // After calling this function, GotByte holds '}'. Unless EOF was found first,
808 // but then a serious error would have been thrown.
809 static void block_to_dynabuf(void)
810 {
811 char byte;
812 int depth = 1; // to find matching block end
813 boolean substflagbuf = subst_enabled;
814
815 // make sure not to subst while reading block (should only be done while parsing)
816 subst_enabled = FALSE;
817
818 // prepare global dynamic buffer
819 dynabuf_clear(GlobalDynaBuf);
820 do {
821 byte = GetByte();
822 // store
823 DYNABUF_APPEND(GlobalDynaBuf, byte);
824 // now check for some special characters
825 switch (byte) {
826 case CHAR_EOF: // End-of-file in block? Sorry, no way.
827 throw_serious_error(exception_no_right_brace);
828
829 case '"': // Quotes? Okay, read quoted stuff.
830 case '\'':
831 quoted_to_dynabuf(byte);
832 DYNABUF_APPEND(GlobalDynaBuf, GotByte); // add closing quote
833 break;
834 case CHAR_SOB:
835 ++depth;
836 break;
837 case CHAR_EOB:
838 --depth;
839 break;
840 }
841 } while (depth);
842
843 // restore subst state
844 subst_enabled = substflagbuf;
845 }
846 // Skip block (starting with next byte, so call directly after reading opening brace).
847 // After calling this function, GotByte holds '}'. Unless EOF was found first,
848 // but then a serious error would have been thrown.
849 void input_block_skip(void)
850 {
851 block_to_dynabuf();
852 }
853 // Read block into GlobalDynabuf, make a copy and store pointer in struct.
854 // (reading starts with next byte, so call directly after reading opening brace).
855 // After calling this function, GotByte holds '}'. Unless EOF was found first,
856 // but then a serious error would have been thrown.
857 void input_block_getcopy(struct block *block)
858 {
859 // first store line number...
860 block->line_number = current_input.location.line_number;
861 // ...then get block
862 block_to_dynabuf();
863 // add EOF, just to make sure block is never read too far
864 dynabuf_append(GlobalDynaBuf, CHAR_EOS);
865 dynabuf_append(GlobalDynaBuf, CHAR_EOF);
866 // store pointer to copy
867 block->body = dynabuf_get_copy(GlobalDynaBuf);
868 }
869
870 // Append to GlobalDynaBuf while characters are legal for keywords.
871 // Throws given error message if no characters found.
872 // Returns number of characters added.
873 static int append_keyword_to_global_dynabuf(const char error_for_zero_length[])
874 {
875 int length = 0;
876
877 // add characters to buffer until an illegal one comes along
878 while (BYTE_CONTINUES_KEYWORD(GotByte)) {
879 DYNABUF_APPEND(GlobalDynaBuf, GotByte);
880 ++length;
881 GetByte();
882 }
883 if (length == 0)
884 throw_error(error_for_zero_length);
885 return length;
886 }
887
888 const char exception_no_symbol_name[] = "Expected symbol name.";
889 // append optional '.'/'@' prefix to GlobalDynaBuf, then keep
890 // appending while characters are legal for keywords.
891 // throw "Expected symbol name" error if none.
892 // return whether there was an error.
893 int input_append_symbol_name_to_global_dynabuf(void)
894 {
895 if ((GotByte == LOCAL_PREFIX)
896 || (GotByte == CHEAP_PREFIX)) {
897 dynabuf_append(GlobalDynaBuf, GotByte);
898 GetByte();
899 } else if (!BYTE_STARTS_KEYWORD(GotByte)) {
900 // FIXME - show invalid char in error message!
901 throw_error(exception_no_symbol_name);
902 return 1; // error
903 }
904 return append_keyword_to_global_dynabuf(exception_no_symbol_name) == 0; // zero length -> error!
905 }
906
907 // read symbol name into GlobalDynaBuf, set scope,
908 // return whether there was an error (namely, "Expected symbol name.")
909 int input_readscopeandsymbolname(scope_t *scope, boolean dotkluge)
910 {
911 int err;
912
913 SKIPSPACE();
914 dynabuf_clear(GlobalDynaBuf);
915
916 if (dotkluge) {
917 // this happens after the expression parser has eaten the '.'
918 // and did not find a decimal digit. -> not a float value ->
919 // must be a local symbol -> we must restore the '.' in front!
920 dynabuf_append(GlobalDynaBuf, '.');
921 err = append_keyword_to_global_dynabuf(exception_no_symbol_name) == 0; // zero length -> error!
922 } else {
923 err = input_append_symbol_name_to_global_dynabuf();
924 }
925 // add terminator to buffer (increments buffer's length counter)
926 dynabuf_append(GlobalDynaBuf, '\0');
927 if (err) {
928 *scope = SCOPE_GLOBAL; // bogus, but at least not un-initialized
929 return 1; // error
930 }
931 if (GLOBALDYNABUF_CURRENT[0] == LOCAL_PREFIX) {
932 *scope = section_now->local_scope;
933 } else if (GLOBALDYNABUF_CURRENT[0] == CHEAP_PREFIX) {
934 *scope = section_now->cheap_scope;
935 } else {
936 *scope = SCOPE_GLOBAL;
937 }
938 return 0; // no error
939 }
940
941 // Clear dynamic buffer, then append to it until an illegal (for a keyword)
942 // character is read. Zero-terminate the string. Return its length (without
943 // terminator).
944 // Zero lengths will produce an error.
945 int parser_read_keyword(void)
946 {
947 int length;
948
949 dynabuf_clear(GlobalDynaBuf);
950 // FIXME: atm, all callers have checked the first char already, therefore the
951 // error message in the next line will never be shown, and that's why it's not
952 // in the docs. Clean this up!
953 length = append_keyword_to_global_dynabuf("Expected keyword or symbol name.");
954 // add terminator to buffer (increments buffer's length counter)
955 dynabuf_append(GlobalDynaBuf, '\0');
956 return length;
957 }
958
959 // Clear dynamic buffer, then append to it until an illegal (for a keyword)
960 // character is read. Zero-terminate the string, then convert to lower case.
961 // Return its length (without terminator).
962 // Zero lengths will produce an "Expected keyword" error.
963 int parser_read_and_lower_keyword(void)
964 {
965 int length;
966
967 dynabuf_clear(GlobalDynaBuf);
968 length = append_keyword_to_global_dynabuf("Expected keyword.");
969 // add terminator to buffer (increments buffer's length counter)
970 dynabuf_append(GlobalDynaBuf, '\0');
971 dynabuf_to_lower(GlobalDynaBuf, GlobalDynaBuf); // convert to lower case
972 return length;
973 }
974
975 // shared ending when trying to read a file name.
976 // The file name given in the assembler source code is converted from
977 // UNIX style to platform style.
978 // Returns nonzero on error. Filename in GlobalDynaBuf, including terminator.
979 // Errors are handled and reported, but caller should call
980 // parser_skip_remainder() then.
981 static int read_filename_shared_end(boolean *absolute)
982 {
983 // check length
984 if (GlobalDynaBuf->size == 0) {
985 throw_error("No file name given.");
986 return 1; // error
987 }
988
989 // terminate string
990 dynabuf_append(GlobalDynaBuf, '\0');
991 // add another zero byte to make sure the buffer is large enough so the
992 // string could grow another byte:
993 dynabuf_append(GlobalDynaBuf, '\0');
994 // (this is an extremely ugly kluge for an extremely unlikely situation,
995 // but still less ugly than all other workarounds I could think of. see
996 // _riscos.c for the extremely unlikely situation where this is needed)
997
998 // platform-specific path name conversion
999 // (and tell absolute/relative paths apart)
1000 platform_convert_path(absolute, GLOBALDYNABUF_CURRENT);
1001
1002 return 0; // ok
1003 }
1004
1005 // parse string and return in GlobalDynaBuf
1006 static int get_string(void)
1007 {
1008 struct object object;
1009
1010 if (config.dialect >= V0_97__BACKSLASH_ESCAPING) {
1011 // since v0.97 the expression parser supports string objects:
1012 ALU_any_result(&object);
1013 if (object.type == &type_string) {
1014 dynabuf_clear(GlobalDynaBuf);
1015 dynabuf_add_bytes(GlobalDynaBuf, object.u.string->payload, object.u.string->length);
1016 } else {
1017 throw_error("Expression did not return a string.");
1018 return 1;
1019 }
1020 } else {
1021 // in older versions, strings could only be given as literals:
1022 if (GotByte != '"') {
1023 throw_error("Quotes not found.");
1024 return 1;
1025 }
1026 if (input_read_string_literal('"')) {
1027 return 1; // unterminated or escaping error
1028 }
1029 }
1030 return 0; // ok
1031 }
1032
1033 // try to read a file name for an input file.
1034 // library access by using <...> quoting is allowed.
1035 // flags for "library access" and "absolute path" will be set accordingly.
1036 // The file name given in the assembler source code is converted from
1037 // UNIX style to platform style.
1038 // on success, returns zero. filename is in GlobalDynaBuf, caller should then
1039 // call includepaths_open_ro().
1040 // on error, returns nonzero. errors are handled and reported, but caller should
1041 // then call parser_skip_remainder().
1042 int input_read_input_filename(struct filespecflags *flags)
1043 {
1044 SKIPSPACE();
1045 if (GotByte == '<') {
1046 // <path/to/file> means library access:
1047 flags->uses_lib = TRUE;
1048 if (input_read_string_literal('>'))
1049 return 1; // unterminated or escaping error
1050 } else {
1051 // "path/to/file" or SOME_STRING_SYMBOL means non-library access:
1052 flags->uses_lib = FALSE;
1053 if (get_string())
1054 return 1; // unterminated, escaping error or not a string
1055 }
1056 // check length, remember abs/rel, terminate, do platform conversion
1057 return read_filename_shared_end(&flags->absolute);
1058 }
1059
1060 // Try to read a comma, skipping spaces before and after. Return TRUE if comma
1061 // found, otherwise FALSE.
1062 int parser_accept_comma(void)
1063 {
1064 SKIPSPACE();
1065 if (GotByte != ',')
1066 return FALSE;
1067
1068 NEXTANDSKIPSPACE();
1069 return TRUE;
1070 }
1071
1072 // Try to read given character.
1073 // If found, eat character and return TRUE.
1074 // If not found, throw syntax error and return FALSE.
1075 int parser_expect(int chr)
1076 {
1077 // one caller uses this to read the '=' part of "!=", so
1078 // do not call SKIPSPACE() here!
1079 if (GotByte == chr) {
1080 GetByte(); // eat expected char
1081 return TRUE;
1082 }
1083 throw_error(exception_syntax); // FIXME - build "expected X, found Y" error msg!
1084 return FALSE;
1085 }
1086
1087 // force input system to return "end of file" on next read
1088 // (back end function for "!eof" pseudo opcode)
1089 void input_force_eof(void)
1090 {
1091 current_input.state = INPUTSTATE_EOF;
1092 }
1093
1094
1095 // enable/disable writing to report file
1096 // (only enable if report file has been opened!)
1097 void input_set_report_enabled(boolean new_state)
1098 {
1099 current_input.report = new_state;
1100 }
1101
1102
1103 static STRUCT_DYNABUF_REF(pathbuf, 256); // to combine search path and file spec
1104
1105 // copy platform-specific library search path into pathbuf:
1106 static void library_path_to_pathbuf(void)
1107 {
1108 dynabuf_clear(pathbuf);
1109 // CAUTION: the second part of the condition below implies the first part,
1110 // so the first part seems useless. but the first part allows for the
1111 // compiler to remove the check completely on some platforms.
1112 if ((PLATFORM_USE_ENV_VAR) && (config.platform_lib_prefix == NULL)) {
1113 throw_error("Library path not set. Use --libpath or create an environment variable.");
1114 } else {
1115 dynabuf_add_string(pathbuf, config.platform_lib_prefix);
1116 }
1117 }
1118
1119 // copy "default search path" from current file's file name into pathbuf:
1120 static void default_path_to_pathbuf(void)
1121 {
1122 const char *start = input_plat_pathref_filename,
1123 *readptr,
1124 *found;
1125
1126 dynabuf_clear(pathbuf);
1127 if (config.dialect >= V0_98__PATHS_AND_SYMBOLCHANGE) {
1128 // scan filename for last directory separator
1129 readptr = start;
1130 found = NULL;
1131 while (*readptr) {
1132 if ((*readptr == DIRECTORY_SEPARATOR)
1133 || (*readptr == ALTERNATIVE_DIR_SEP)) {
1134 found = readptr;
1135 }
1136 ++readptr;
1137 }
1138 if (found) {
1139 // +1 because we want the separator as well:
1140 dynabuf_add_bytes(pathbuf, start, found - start + 1);
1141 }
1142 } else {
1143 // do nothing -
1144 // pathbuf is empty, which means "default search path" is "",
1145 // which is exactly like it was in older versions.
1146 }
1147 }
1148
1149 // try to read a file name for an output file ("!to" and "!sl" only).
1150 // library access by using <...> quoting is forbidden.
1151 // The file name given in the assembler source code is converted from
1152 // UNIX style to platform style.
1153 // on success, returns zero. filename is in GlobalDynaBuf, caller should then
1154 // make a copy to pass it to fopen() later on.
1155 // on error, returns nonzero. errors are handled and reported, but caller should
1156 // then call parser_skip_remainder().
1157 // FIXME - the name suggests this fn reads "the" output filename, but it only
1158 // reads "an" output filename: either symbollist or the real output file.
1159 int input_read_output_filename(void)
1160 {
1161 boolean absolute;
1162
1163 SKIPSPACE();
1164 if (GotByte == '<') {
1165 // <path/to/file> means library access:
1166 throw_error("Writing to library not supported.");
1167 return 1; // error
1168 }
1169 // we expect "path/to/file" or SOME_STRING_SYMBOL:
1170 // in the past, output filenames had to be given as literals and could not be
1171 // created dynamically at runtime. because this "security feature" can now be
1172 // circumvented using the symbol expansion mechanism, it does not make sense to
1173 // keep it, it would only add complexity.
1174 if (get_string())
1175 return 1; // unterminated, escaping error or not a string
1176
1177 // check length, remember abs/rel, terminate, do platform conversion:
1178 if (read_filename_shared_end(&absolute))
1179 return 1; // empty string
1180
1181 if (absolute) {
1182 // keep file name as it is
1183 } else {
1184 // get current file's path
1185 default_path_to_pathbuf();
1186 // add output file name
1187 dynabuf_add_string(pathbuf, GLOBALDYNABUF_CURRENT);
1188 // terminate
1189 dynabuf_append(pathbuf, '\0');
1190 // copy full file name back to GlobalDynaBuf
1191 dynabuf_clear(GlobalDynaBuf);
1192 dynabuf_add_string(GlobalDynaBuf, pathbuf->buffer);
1193 dynabuf_append(GlobalDynaBuf, '\0');
1194 }
1195
1196 return 0; // ok
1197 }
1198
1199 // write current "location" (file name and line number) to given target
1200 void input_get_location(struct location *target)
1201 {
1202 *target = current_input.location;
1203 }
1204
1205
1206 // "input change" stuff:
1207
1208 // save current input struct in buffer, then switch input to new source code file
1209 void inputchange_new_file(struct inputchange_buf *icb, FILE *fd, const char *eternal_plat_filename)
1210 {
1211 report_flush();
1212
1213 // remember old state in buffer struct
1214 icb->input = current_input;
1215 icb->gb = GotByte;
1216 // set new state
1217 current_input.location.plat_filename = eternal_plat_filename;
1218 current_input.location.line_number = 1;
1219 current_input.srctype = INPUTSRC_FILE;
1220 current_input.state = INPUTSTATE_SOF;
1221 current_input.u.fd = fd;
1222
1223 report_inputchange("Source: ", eternal_plat_filename);
1224 }
1225 // save current input struct in buffer, then switch to RAM
1226 void inputchange_new_ram(struct inputchange_buf *icb)
1227 {
1228 report_flush();
1229
1230 // remember old state in buffer struct
1231 icb->input = current_input;
1232 icb->gb = GotByte;
1233 // set new state (not useable yet, as pointer and line number are not yet set up)
1234 current_input.srctype = INPUTSRC_RAM; // set new byte source
1235 current_input.u.ram_ptr = NULL; // force crash if used before setup is finished
1236 }
1237 // FIXME - merge these three functions into a single one (by always using a "location"):
1238 // setup for reading from RAM (for parsing loop conditions etc.)
1239 void inputchange_set_ram(int line_num, const char *body)
1240 {
1241 current_input.location.line_number = line_num;
1242 current_input.u.ram_ptr = body;
1243 input_set_report_enabled(FALSE); // do not expand loops in report file (reverts to previous state when changing input back)
1244 }
1245 // switch input to macro parameters
1246 void inputchange_macro1_params(const struct location *def, const char *params)
1247 {
1248 current_input.location = *def;
1249 current_input.u.ram_ptr = params;
1250 current_input.state = INPUTSTATE_NORMAL; // FIXME - fix others!
1251
1252 report_inputchange("macro from ", def->plat_filename);
1253 }
1254 // switch from macro parameters to macro body
1255 void inputchange_macro2_body(const char *macro_body)
1256 {
1257 current_input.u.ram_ptr = macro_body;
1258 current_input.state = INPUTSTATE_NORMAL; // FIXME - fix others!
1259 }
1260 // restore input struct from buffer
1261 void inputchange_back(const struct inputchange_buf *icb)
1262 {
1263 report_flush();
1264
1265 // restore old state from buffer struct
1266 current_input = icb->input;
1267 GotByte = icb->gb;
1268
1269 switch (current_input.srctype) {
1270 case INPUTSRC_NONE:
1271 report_inputchange("done", "");
1272 break;
1273 case INPUTSRC_FILE:
1274 report_inputchange("Source: ", current_input.location.plat_filename);
1275 break;
1276 case INPUTSRC_RAM:
1277 report_inputchange("back", "");
1278 break;
1279 default:
1280 BUG("IllegalInputSrc", current_input.srctype);
1281 }
1282 }
1283
1284
1285 // "include path" stuff:
1286
1287 // ring list struct for "include path items"
1288 struct ipi {
1289 struct ipi *next,
1290 *prev;
1291 const char *path;
1292 };
1293
1294 // head element
1295 static struct ipi ipi_head = {&ipi_head, &ipi_head, NULL};
1296
1297 // add entry
1298 void includepaths_add(const char *path)
1299 {
1300 struct ipi *ipi;
1301
1302 ipi = safe_malloc(sizeof(*ipi));
1303 ipi->path = path;
1304 ipi->next = &ipi_head;
1305 ipi->prev = ipi_head.prev;
1306 ipi->next->prev = ipi;
1307 ipi->prev->next = ipi;
1308 }
1309
1310 // add filename (from GlobalDynaBuf) to pathbuf and try to open file:
1311 static FILE *combine_and_open_ro(void)
1312 {
1313 FILE *stream;
1314
1315 // if path does not end with directory separator, add one:
1316 if (pathbuf->size
1317 && (pathbuf->buffer[pathbuf->size - 1] != DIRECTORY_SEPARATOR)
1318 && (pathbuf->buffer[pathbuf->size - 1] != ALTERNATIVE_DIR_SEP)) {
1319 dynabuf_append(pathbuf, DIRECTORY_SEPARATOR);
1320 }
1321 // add file name
1322 dynabuf_add_string(pathbuf, GLOBALDYNABUF_CURRENT);
1323 // terminate
1324 dynabuf_append(pathbuf, '\0');
1325 // try to open for reading
1326 stream = fopen(pathbuf->buffer, FILE_READBINARY);
1327 if (config.process_verbosity >= 9)
1328 printf("Trying \"%s\"...%s\n", pathbuf->buffer, stream ? " OK!" : "");
1329 return stream;
1330 }
1331
1332 // open file for reading
1333 // "flags" decide whether library access, search paths or absolute path is wanted.
1334 // file name is expected in GlobalDynaBuf, in platform style and terminated.
1335 // returns NULL or open stream
1336 // on success, GlobalDynaBuf contains full file name in platform style
1337 FILE *includepaths_open_ro(struct filespecflags *flags)
1338 {
1339 FILE *stream;
1340 struct ipi *ipi;
1341
1342 if (flags->uses_lib) {
1343 // use library prefix
1344 library_path_to_pathbuf();
1345 stream = combine_and_open_ro();
1346 } else {
1347 // first try current default prefix
1348 if (flags->absolute)
1349 dynabuf_clear(pathbuf); // which is "" if absolute
1350 else
1351 default_path_to_pathbuf(); // or current path if relative
1352 stream = combine_and_open_ro();
1353 if (stream == NULL) {
1354 // default prefix failed, so try list entries:
1355 // (does not seem to make much sense for absolute paths,
1356 // but maybe some windows user used search paths like
1357 // "D:" or "E:" - oh well...)
1358 for (ipi = ipi_head.next; ipi != &ipi_head; ipi = ipi->next) {
1359 dynabuf_clear(pathbuf);
1360 dynabuf_add_string(pathbuf, ipi->path);
1361 stream = combine_and_open_ro();
1362 if (stream) {
1363 break;
1364 }
1365 }
1366 }
1367 }
1368 if (stream) {
1369 // copy successful file name back to GlobalDynaBuf
1370 dynabuf_clear(GlobalDynaBuf);
1371 dynabuf_add_string(GlobalDynaBuf, pathbuf->buffer);
1372 dynabuf_append(GlobalDynaBuf, '\0');
1373 } else {
1374 // CAUTION, I'm re-using the path dynabuf to assemble the error message:
1375 dynabuf_clear(pathbuf);
1376 dynabuf_add_string(pathbuf, "Cannot open input file ");
1377 dynabuf_append(pathbuf, flags->uses_lib ? '<' : '\"');
1378 dynabuf_add_string(pathbuf, GLOBALDYNABUF_CURRENT);
1379 dynabuf_append(pathbuf, flags->uses_lib ? '>' : '\"');
1380 dynabuf_append(pathbuf, '.');
1381 dynabuf_append(pathbuf, '\0');
1382 throw_error(pathbuf->buffer);
1383 }
1384 //fprintf(stderr, "File is [%s]\n", GLOBALDYNABUF_CURRENT);
1385 return stream;
1386 }