Debian Codegraph @

src/acme.c

raw symbols SCIP
1 // ACME - a crossassembler for producing 6502/65c02/65816/65ce02 code.
2 // Copyright (C) 1998-2025 Marco Baye
3 //
4 // This program is free software; you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation; either version 2 of the License, or
7 // (at your option) any later version.
8 //
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with this program; if not, write to the Free Software
16 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 #include "acme.h"
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include "alu.h"
22 #include "cliargs.h"
23 #include "config.h"
24 #include "cpu.h"
25 #include "dynabuf.h"
26 #include "encoding.h"
27 #include "flow.h"
28 #include "global.h"
29 #include "input.h"
30 #include "macro.h"
31 #include "mnemo.h"
32 #include "output.h"
33 #include "platform.h"
34 #include "pseudoopcodes.h"
35 #include "section.h"
36 #include "symbol.h"
37 #include "version.h"
38
39
40 // constants
41 static const char FILE_WRITETEXT[] = "w";
42 static const char FILE_WRITEBINARY[] = "wb";
43 // names for error messages
44 static const char name_outfile[] = "output filename";
45 static const char arg_symbollist[] = "symbol list filename";
46 static const char arg_reportfile[] = "report filename";
47 static const char arg_vicelabels[] = "VICE labels filename";
48 // long options
49 #define OPTION_HELP "help"
50 #define OPTION_FORMAT "format"
51 #define OPTION_OUTFILE "outfile"
52 #define OPTION_LABELDUMP "labeldump" // old
53 #define OPTION_SYMBOLLIST "symbollist" // new
54 #define OPTION_VICELABELS "vicelabels"
55 #define OPTION_REPORT "report"
56 #define OPTION_SETPC "setpc"
57 #define OPTION_FROM_TO "from-to"
58 #define OPTION_CPU "cpu"
59 #define OPTION_INITMEM "initmem"
60 #define OPTION_MAXERRORS "maxerrors"
61 #define OPTION_MAXDEPTH "maxdepth"
62 #define OPTION_USE_STDOUT "use-stdout"
63 #define OPTION_VERSION "version"
64 #define OPTION_MSVC "msvc"
65 #define OPTION_COLOR "color"
66 #define OPTION_FULLSTOP "fullstop"
67 #define OPTION_IGNORE_ZEROES "ignore-zeroes"
68 #define OPTION_STRICT_SEGMENTS "strict-segments"
69 #define OPTION_STRICT "strict"
70 #define OPTION_LIBPATH "libpath"
71 #define OPTION_DIALECT "dialect"
72 #define OPTION_PLEASE "please"
73 #define OPTION_DEBUGLEVEL "debuglevel"
74 #define OPTION_TEST "test"
75 // options for "-W"
76 #define OPTIONWNO_LABEL_INDENT "no-label-indent"
77 #define OPTIONWNO_OLD_FOR "no-old-for"
78 #define OPTIONWNO_BIN_LEN "no-bin-len"
79 #define OPTIONWTYPE_MISMATCH "type-mismatch"
80
81
82 // variables
83 static const char **toplevel_sources_plat; // source file names given on command line (platform-style)
84 static int toplevel_src_count = 0;
85
86
87 // show release and platform info (and exit, if wanted)
88 static void show_version(int exit_after)
89 {
90 puts(
91 "This is ACME, release " RELEASE " (\"" CODENAME "\"), " CHANGE_DATE " " CHANGE_YEAR "\n"
92 " " PLATFORM_VERSION);
93 if (exit_after)
94 exit(EXIT_SUCCESS);
95 }
96
97
98 // show full help (headline, release/platform/version, copyright, dedication,
99 // warranty disclaimer, usage) and exit program (SUCCESS)
100 static void show_help_and_exit(void)
101 {
102 puts(
103 "ACME - the ACME Crossassembler for Multiple Environments\n"
104 " Copyright (C) 1998-" CHANGE_YEAR " Marco Baye");
105 show_version(FALSE);
106 puts(
107 "ACME comes with ABSOLUTELY NO WARRANTY; for details read the help file.\n"
108 " This is free software, and you are welcome to redistribute it under\n"
109 " certain conditions; as outlined in the GNU General Public License.\n"
110 "Dedicated to the wisest being I ever had the pleasure of reading\n"
111 " books of (currently spending some time dead for tax reasons).\n"
112 "The newest version can be found at the ACME homepage:\n"
113 " " HOME_PAGE "\n"
114 "\n"
115 "Usage:\n"
116 "acme [OPTION...] [FILE]...\n"
117 "\n"
118 "Options:\n"
119 " -h, --" OPTION_HELP " show this help and exit\n"
120 " -f, --" OPTION_FORMAT " FORMAT set output file format\n"
121 " -o, --" OPTION_OUTFILE " FILE set output file name\n"
122 " -r, --" OPTION_REPORT " FILE set report file name\n"
123 " -l, --" OPTION_SYMBOLLIST " FILE set symbol list file name\n"
124 " --" OPTION_LABELDUMP " (old name for --" OPTION_SYMBOLLIST ")\n"
125 " --" OPTION_VICELABELS " FILE set file name for label dump in VICE format\n"
126 " --" OPTION_SETPC " VALUE set program counter\n"
127 " --" OPTION_FROM_TO " VALUE VALUE set start and end+1 of output file\n"
128 " --" OPTION_CPU " CPU set target processor\n"
129 " --" OPTION_INITMEM " VALUE define 'empty' memory\n"
130 " --" OPTION_MAXERRORS " NUMBER set number of errors before exiting\n"
131 " --" OPTION_MAXDEPTH " NUMBER set recursion depth for macro calls and !src\n"
132 " --" OPTION_IGNORE_ZEROES " do not determine number size by leading zeroes\n"
133 " --" OPTION_STRICT_SEGMENTS " turn segment overlap warnings into errors\n"
134 " --" OPTION_STRICT " treat all warnings like errors\n"
135 " -vDIGIT set verbosity level\n"
136 " -D SYMBOL=VALUE define global symbol\n"
137 " -I PATH/TO/DIR add search path for input files\n"
138 " --" OPTION_LIBPATH " PATH/TO/DIR set path to ACME library\n"
139 // TODO: replace these:
140 " -W" OPTIONWNO_LABEL_INDENT " suppress warnings about indented labels\n"
141 " -W" OPTIONWNO_OLD_FOR " (old, use \"--dialect 0.94.8\" instead)\n"
142 " -W" OPTIONWNO_BIN_LEN " suppress warnings about lengths of binary literals\n"
143 " -W" OPTIONWTYPE_MISMATCH " enable type checking (warn about type mismatch)\n"
144 // with this line and add a separate function:
145 //" -W show warning level options\n"
146 " --" OPTION_USE_STDOUT " fix for 'Relaunch64' IDE (see docs)\n"
147 " --" OPTION_MSVC " output errors in MS VS format\n"
148 " --" OPTION_COLOR " use ANSI color codes for error output\n"
149 " --" OPTION_FULLSTOP " use '.' as pseudo opcode prefix\n"
150 " --" OPTION_DIALECT " VERSION behave like different version\n"
151 " --" OPTION_DEBUGLEVEL " VALUE drop all higher-level debug messages\n"
152 " --" OPTION_TEST " enable experimental features\n"
153 PLATFORM_OPTION_HELP
154 " -V, --" OPTION_VERSION " show version and exit\n");
155 exit(EXIT_SUCCESS);
156 }
157
158
159 // initialise report struct
160 static void report_init(struct report *report)
161 {
162 report->fd = NULL;
163 report->new_input = FALSE;
164 report->asc_used = 0;
165 report->bin_used = 0;
166 }
167 // open report file
168 static void report_open(struct report *report, const char *filename)
169 {
170 // show filename _now_ because I do not want to massage it into perror()
171 printf("Opening report file \"%s\".\n", filename);
172 report->fd = fopen(filename, FILE_WRITETEXT);
173 if (report->fd == NULL) {
174 perror("Error: Cannot open report file");
175 exit(ACME_finalize(EXIT_FAILURE));
176 }
177 input_set_report_enabled(TRUE);
178 }
179 // close report file
180 static void report_close(struct report *report)
181 {
182 if (report && report->fd) {
183 input_set_report_enabled(FALSE);
184 fclose(report->fd);
185 report->fd = NULL;
186 }
187 }
188
189
190 // error handling
191
192 // tidy up before exiting by saving symbol list and close other output files
193 int ACME_finalize(int exit_code)
194 {
195 FILE *fd;
196
197 report_close(report);
198 if (config.symbollist_filename) {
199 // show filename _now_ because I do not want to massage it into perror()
200 printf("Writing symbol list file \"%s\".\n", config.symbollist_filename);
201 fd = fopen(config.symbollist_filename, FILE_WRITETEXT); // FIXME - what if filename is given via !sl in sub-dir? fix path!
202 if (fd) {
203 symbols_list(fd);
204 fclose(fd);
205 PLATFORM_SETFILETYPE_TEXT(config.symbollist_filename);
206 } else {
207 perror("Error: Cannot open symbol list file");
208 exit_code = EXIT_FAILURE;
209 }
210 }
211 if (config.vicelabels_filename) {
212 // show filename _now_ because I do not want to massage it into perror()
213 printf("Writing VICE label dump file \"%s\".\n", config.vicelabels_filename);
214 fd = fopen(config.vicelabels_filename, FILE_WRITETEXT);
215 if (fd) {
216 symbols_vicelabels(fd);
217 fclose(fd);
218 PLATFORM_SETFILETYPE_TEXT(config.vicelabels_filename);
219 } else {
220 perror("Error: Cannot open VICE label dump file");
221 exit_code = EXIT_FAILURE;
222 }
223 }
224 return exit_code;
225 }
226
227
228 // save output file
229 static void save_output_file(void)
230 {
231 const char *body;
232 intval_t amount,
233 loadaddr;
234 unsigned char header[4];
235 int headersize = 0;
236 FILE *fd;
237
238 // if no output file chosen, tell user and do nothing
239 if (config.output_filename == NULL) {
240 fputs("No output file specified (use the \"-o\" option or the \"!to\" pseudo opcode).\n", stderr);
241 return;
242 }
243 // show output filename _now_ because I do not want to massage it into
244 // every possible perror() call.
245 printf("Writing output file \"%s\".\n", config.output_filename);
246
247 // get memory pointer, block size and load address
248 output_get_result(&body, &amount, &loadaddr);
249
250 // generate header according to file format
251 switch (config.outfile_format) {
252 case OUTFILE_FORMAT_UNSPECIFIED:
253 case OUTFILE_FORMAT_PLAIN:
254 headersize = 0; // no header
255 break;
256 case OUTFILE_FORMAT_CBM:
257 if (loadaddr > 0xffff) {
258 fprintf(stderr, "Error: Load address 0x%04x too large for cbm file format.\n", loadaddr);
259 exit(ACME_finalize(EXIT_FAILURE));
260 }
261 header[0] = loadaddr & 255;
262 header[1] = loadaddr >> 8;
263 headersize = 2; // 16-bit load address, little-endian
264 break;
265 case OUTFILE_FORMAT_APPLE:
266 if (loadaddr > 0xffff) {
267 fprintf(stderr, "Error: Load address 0x%04x too large for apple file format.\n", loadaddr);
268 exit(ACME_finalize(EXIT_FAILURE));
269 }
270 if (amount > 0xffff) {
271 fprintf(stderr, "Error: File size 0x%04x too large for apple file format.\n", amount);
272 exit(ACME_finalize(EXIT_FAILURE));
273 }
274 header[0] = loadaddr & 255;
275 header[1] = loadaddr >> 8;
276 header[2] = amount & 255;
277 header[3] = amount >> 8;
278 headersize = 4; // 16-bit load address and 16-bit length, little-endian
279 break;
280 default:
281 BUG("IllegalOutformat1", config.outfile_format);
282 }
283
284 // open file
285 fd = fopen(config.output_filename, FILE_WRITEBINARY); // FIXME - what if filename is given via !to in sub-dir? fix path!
286 if (fd == NULL) {
287 perror("Error: Cannot open output file");
288 exit(ACME_finalize(EXIT_FAILURE));
289 }
290
291 if (config.process_verbosity >= 1) {
292 printf("Saving %d (0x%04x) bytes (0x%04x - 0x%04x exclusive).\n",
293 amount, amount, loadaddr, loadaddr + amount);
294 }
295
296 // write header and body:
297 // checking header size and body size explicitly for non-zero values
298 // facilitates checking the return value of fwrite(), because writing
299 // one object of size zero returns 0, not 1:
300 if (headersize) {
301 if (fwrite(header, headersize, 1, fd) != 1) {
302 perror("Error: Cannot write header to output file");
303 exit(ACME_finalize(EXIT_FAILURE));
304 }
305 }
306 if (amount) {
307 if (fwrite(body, amount, 1, fd) != 1) {
308 perror("Error: Cannot write to output file");
309 exit(ACME_finalize(EXIT_FAILURE));
310 }
311 }
312 if (fclose(fd)) {
313 perror("Error: Cannot flush output file");
314 exit(ACME_finalize(EXIT_FAILURE));
315 }
316
317 // set file type
318 switch (config.outfile_format) {
319 case OUTFILE_FORMAT_UNSPECIFIED:
320 case OUTFILE_FORMAT_PLAIN:
321 PLATFORM_SETFILETYPE_PLAIN(config.output_filename);
322 break;
323 case OUTFILE_FORMAT_APPLE:
324 PLATFORM_SETFILETYPE_APPLE(config.output_filename);
325 break;
326 case OUTFILE_FORMAT_CBM:
327 PLATFORM_SETFILETYPE_CBM(config.output_filename);
328 break;
329 default:
330 BUG("IllegalOutformat2", config.outfile_format);
331 }
332 }
333
334
335 // definitions for pass flags:
336 #define PF_IS_FINAL_PASS (1u << 0) // mostly for special warnings
337 #define PF_IS_ERROR_PASS (1u << 1) // throw "Symbol not defined" and other errors that could be suppressed
338 #define PF_GENERATE_OUTPUT (1u << 2) // generate output and/or report file
339
340 // perform a single pass
341 static void perform_pass(bits passflags)
342 {
343 FILE *fd;
344 int ii;
345
346 // init variables
347 pass.counters.undefineds = 0;
348 //pass.counters.needvalue = 0; FIXME - use
349 pass.counters.symbolchanges = 0;
350 pass.counters.errors = 0;
351 pass.counters.warnings = 0;
352 pass.counters.suppressed_errors = 0;
353 pass.flags.complain_about_undefined = !!(passflags & PF_IS_ERROR_PASS);
354 pass.flags.throw_all_errors = !!(passflags & PF_IS_ERROR_PASS);
355 pass.flags.is_final_pass = !!(passflags & PF_IS_FINAL_PASS);
356 pass.flags.generate_output = !!(passflags & PF_GENERATE_OUTPUT);
357
358 if (config.process_verbosity >= 2)
359 printf("Pass %d:\n", pass.number);
360
361 if (pass.flags.generate_output) {
362 // if wanted, open report listing
363 if (config.report_filename)
364 report_open(report, config.report_filename);
365 }
366 cputype_passinit(); // set default cpu type
367 output_passinit(); // clear segment list, disable output, undefine pc, ...
368 encoding_passinit(); // set default encoding
369 section_passinit(); // set initial zone (untitled)
370 // if start address was given on command line, use it to define pc:
371 if (config.initial_pc != NO_VALUE_GIVEN)
372 programcounter_set(config.initial_pc, 0); // 0 -> no segment flags
373 // process toplevel files
374 for (ii = 0; ii < toplevel_src_count; ++ii) {
375 fd = fopen(toplevel_sources_plat[ii], FILE_READBINARY);
376 if (fd) {
377 parse_source_code_file(fd, toplevel_sources_plat[ii]);
378 fclose(fd);
379 } else {
380 fprintf(stderr, "Error: Cannot open toplevel file \"%s\".\n", toplevel_sources_plat[ii]);
381 if (toplevel_sources_plat[ii][0] == '-')
382 fprintf(stderr, "Options (starting with '-') must be given _before_ source files!\n");
383 ++pass.counters.errors;
384 }
385 }
386 output_endofpass(); // make sure last code segment is closed
387 // TODO: atm "--from-to" reads two number literals. if that is changed
388 // in the future to two general expressions, this is the point where
389 // they would need to be evaluated.
390 if (config.process_verbosity >= 8)
391 printf("Undefined expressions: %d. Symbol updates: %d.\n", pass.counters.undefineds, pass.counters.symbolchanges);
392 // FIXME - make this into next if's "else" block:
393 if (pass.counters.errors)
394 exit(ACME_finalize(EXIT_FAILURE));
395
396 if (pass.flags.generate_output) {
397 // FIXME - add some code here to do "if there were errors, call BUG()"
398 // if report listing is open, close it
399 if (config.report_filename)
400 report_close(report);
401 save_output_file();
402 }
403 // now increment pass number
404 // this must be done _after_ the pass because assignments done via
405 // "-D SYMBOL=VALUE" cli args must be handled as if they were done at
406 // the start of pass 1, so we cannot change that variable at the start
407 // of the pass.
408 ++pass.number;
409 }
410
411 static struct report global_report;
412
413 // do passes until done (or errors occurred).
414 static void do_actual_work(void)
415 {
416 int undefs_before; // number of undefined results in previous pass
417
418 report = &global_report; // let global pointer point to something
419 report_init(report); // we must init struct before doing passes
420
421 sanity.macro_recursions_left = config.sanity_limit;
422 sanity.source_recursions_left = config.sanity_limit;
423
424 // init output system
425 output_init();
426
427 // first pass:
428 perform_pass(0);
429 // pretend there has been a previous pass, with one more undefined result
430 undefs_before = pass.counters.undefineds + 1;
431
432 // further passes:
433 // keep doing passes as long as the number of undefined results keeps decreasing.
434 // stop on zero (FIXME - zero-check pass.counters.needvalue instead!)
435 while ((pass.counters.undefineds && (pass.counters.undefineds < undefs_before)) || pass.counters.symbolchanges) {
436 undefs_before = pass.counters.undefineds;
437 perform_pass(0);
438 if (pass.number > config.sanity_limit) {
439 throw_serious_error("Exceeded maximum number of passes, please see docs.");
440 // ...or maybe do one additional pass where all errors are reported, including "not defined" and "value has changed".
441 }
442 }
443 // FIXME - do an optional extra pass, as a debugging aid?
444
445 // final pass:
446 // any errors left?
447 // FIXME - use pass.counters.needvalue instead of pass.counters.undefineds?
448 if ((pass.counters.undefineds == 0) && (pass.counters.suppressed_errors == 0)) {
449 // victory lap
450 if (config.process_verbosity >= 2)
451 puts("Extra pass to generate output.");
452 perform_pass(PF_IS_FINAL_PASS | PF_GENERATE_OUTPUT);
453 } else {
454 // There are still errors (unsolvable by doing further passes),
455 // so perform additional pass to find and show them.
456 if (config.process_verbosity >= 2)
457 puts("Extra pass to display errors.");
458 perform_pass(PF_IS_FINAL_PASS | PF_IS_ERROR_PASS); // perform pass, but now show "value undefined" and others
459 // FIXME - perform_pass() calls exit() when there were errors,
460 // so if controls returns here, call BUG()!
461 // (this can be triggered using ifdef/ifndef)
462 }
463 }
464
465
466 // copy string to DynaBuf
467 static void keyword_to_dynabuf(const char keyword[])
468 {
469 dynabuf_clear(GlobalDynaBuf);
470 dynabuf_add_string(GlobalDynaBuf, keyword);
471 dynabuf_append(GlobalDynaBuf, '\0');
472 dynabuf_to_lower(GlobalDynaBuf, GlobalDynaBuf); // convert to lower case
473 }
474
475
476 // set output format
477 static void set_output_format(const char format_name[])
478 {
479 // caution, name may be NULL!
480 if (format_name) {
481 keyword_to_dynabuf(format_name);
482 config.outfile_format = outputformat_find();
483 if (config.outfile_format != OUTFILE_FORMAT_UNSPECIFIED)
484 return; // ok
485
486 fputs("Error: Unknown output format.\n", stderr);
487 } else {
488 fputs("Error: No output format specified.\n", stderr);
489 }
490 fprintf(stderr, "Supported formats are:\n\n\t%s\n\n", outputformat_names);
491 exit(EXIT_FAILURE);
492 }
493
494
495 // set CPU type
496 static void set_starting_cpu(const char cpu_name[])
497 {
498 const struct cpu_type *new_cpu_type;
499
500 // caution, name may be NULL!
501 if (cpu_name) {
502 keyword_to_dynabuf(cpu_name);
503 new_cpu_type = cputype_find();
504 if (new_cpu_type) {
505 config.initial_cpu_type = new_cpu_type;
506 return; // ok
507 }
508 fputs("Error: Unknown CPU type.\n", stderr);
509 } else {
510 fputs("Error: No CPU type specified.\n", stderr);
511 }
512 fprintf(stderr, "Supported types are:\n\n\t%s\n\n", cputype_names);
513 exit(EXIT_FAILURE);
514 }
515
516
517 // helper function to complain about error in cli args, does not return
518 static void exit__cli_arg_error(const char format[], const char arg[])
519 {
520 fprintf(stderr, "%s", cliargs_error);
521 fprintf(stderr, format, arg);
522 fprintf(stderr, "\n");
523 exit(EXIT_FAILURE);
524 }
525 // exit with "Error in CLI arguments: ..." message
526 void ACME_cli_args_error(const char msg[])
527 {
528 exit__cli_arg_error("%s", msg);
529 }
530
531
532 // return signed long representation of string.
533 // copes with hexadecimal if prefixed with "$", "0x" or "0X".
534 // copes with octal if prefixed with "&". FIXME - add "0o" prefix?
535 // copes with binary if prefixed with "%". FIXME - add "0b" prefix!
536 // assumes decimal otherwise.
537 static signed long string_to_number(const char *string)
538 {
539 signed long result;
540 char *end;
541 int base = 10;
542
543 if (*string == '%') {
544 base = 2;
545 ++string;
546 } else if (*string == '&') {
547 base = 8;
548 ++string;
549 } else if (*string == '$') {
550 base = 16;
551 ++string;
552 } else if ((*string == '0') && ((string[1] == 'x') || (string[1] == 'X'))) {
553 base = 16;
554 string += 2;
555 }
556 result = strtol(string, &end, base);
557 if (*end)
558 exit__cli_arg_error("Could not parse \"%s\" as number.", end);
559 return result;
560 }
561 // wrapper for fn above: complain about negative numbers
562 static signed long string_to_nonneg_number(const char *string)
563 {
564 signed long result = string_to_number(string);
565
566 if (result < 0)
567 exit__cli_arg_error("Invalid value, number is negative: \"%s\".", string);
568 return result;
569 }
570
571
572 // set initial memory contents
573 static void set_mem_contents(const char expression[])
574 {
575 config.mem_init_value = string_to_number(expression);
576 if ((config.mem_init_value < -128) || (config.mem_init_value > 255))
577 exit__cli_arg_error("%s", "Initmem value must be in 0..0xff range.");
578 }
579
580
581 // define symbol
582 // FIXME - replace all this with a call to some kind of "hey parser, parse this string" function?
583 // but then we would have to pass a "do backslash escapes even if older dialect selected" flag...
584 static void define_symbol(const char definition[])
585 {
586 const char *walk = definition;
587 struct symbol *symbol;
588 signed long intvalue;
589 boolean escaped;
590
591 // copy symbol name (everything up to the '=' char) to GlobalDynaBuf and add terminator:
592 dynabuf_clear(GlobalDynaBuf);
593 while ((*walk != '=') && (*walk != '\0'))
594 dynabuf_append(GlobalDynaBuf, *walk++);
595 dynabuf_append(GlobalDynaBuf, '\0');
596 // use name to make symbol
597 symbol = symbol_for_cli_def();
598 // now we can clobber GlobalDynaBuf
599
600 // no '=' or nothing after? then complain and die:
601 if ((*walk == '\0') || (walk[1] == '\0'))
602 exit__cli_arg_error("\"%s\" does not have SYMBOL=VALUE format.", definition);
603 ++walk; // eat '='
604 // now check value type (at the moment only integers and strings are possible)
605 if (*walk == '"') {
606 // it starts with a doublequote, so it must be a string
607 ++walk; // eat '"'
608 dynabuf_clear(GlobalDynaBuf);
609 escaped = FALSE;
610 for (;;) {
611 if (*walk == '\0')
612 exit__cli_arg_error("Closing quote not found after -D %s.", definition);
613 if (escaped) {
614 // previous byte was backslash, so do not check for closing quote nor backslash
615 escaped = FALSE;
616 } else {
617 // non-escaped: only closing quote and backslash are of interest
618 if (*walk == '"')
619 break; // leave loop
620 if (*walk == '\\')
621 escaped = TRUE;
622 }
623 DYNABUF_APPEND(GlobalDynaBuf, *walk++);
624 }
625 if (walk[1] != '\0')
626 exit__cli_arg_error("Garbage after closing quote at -D %s.", definition);
627 unescape_dynabuf();
628 symbol_define_string(symbol);
629 } else {
630 // integer
631 intvalue = string_to_number(walk);
632 symbol_define_int(symbol, intvalue);
633 }
634 }
635
636
637 struct dialect_info {
638 enum dialect dialect;
639 const char *version;
640 const char *description;
641 };
642 struct dialect_info dialects[] = {
643 {V0_85__OLDEST_SUPPORTED, "0.85", "(the oldest version supported)"},
644 {V0_86__DEPRECATE_REALPC, "0.86", "\"!realpc\" gives a warning, \"!to\" wants a file format"},
645 // {V0_93__SHORTER_SETPC_WARNING, "0.93", "\"*=\" in offset assembly gives shorter warning but still switches off"},
646 {V0_94_6__RIGHT_ASSOC_POWER, "0.94.6", "\"power of\" is now right-associative"},
647 // {V, "0.94.7", "empty code segments are no longer included in output file"},
648 {V0_94_8__DISABLED_OBSOLETE, "0.94.8", "\"*=\" works inside \"!pseudopc\", disabled \"!cbm/!realpc/!subzone\""},
649 {V0_94_12__NEW_FOR_SYNTAX, "0.94.12", "new \"!for\" syntax"},
650 {V0_95_2__NEW_ANC_OPCODE, "0.95.2", "changed ANC#8 from 0x2b to 0x0b"},
651 {V0_97__BACKSLASH_ESCAPING, "0.97", "backslash escaping and strings"},
652 {V0_98__PATHS_AND_SYMBOLCHANGE, "0.98", "paths are relative to current file"},
653 // {V__CURRENT_VERSION, "default", "default"},
654 {V__FUTURE_VERSION, "future", "enable all experimental features"},
655 {0, NULL, NULL} // NULLs terminate
656 };
657
658 // choose dialect (mimic behaviour of different version)
659 static void set_dialect(const char version[])
660 {
661 struct dialect_info *dia;
662
663 // caution, version may be NULL!
664 if (version) {
665 // scan array
666 for (dia = dialects; dia->version; ++dia) {
667 if (strcmp(version, dia->version) == 0) {
668 config.dialect = dia->dialect;
669 return; // found
670 }
671 }
672 fputs("Error: Unknown dialect specifier.\n", stderr);
673 } else {
674 fputs("Error: No dialect specified.\n", stderr);
675 }
676 // output table of possible versions and die
677 fputs(
678 "Supported dialects are:\n"
679 "\n"
680 "\tdialect\t\tdescription\n"
681 "\t-------\t\t-----------\n", stderr);
682 for (dia = dialects; dia->version; ++dia)
683 fprintf(stderr, "\t%s\t\t%s\n", dia->version, dia->description);
684 fputc('\n', stderr);
685 exit(EXIT_FAILURE);
686 }
687
688
689 // handle long options (like "--example"). Return unknown string.
690 static const char *long_option(const char *string)
691 {
692 if (strcmp(string, OPTION_HELP) == 0)
693 show_help_and_exit();
694 else if (strcmp(string, OPTION_FORMAT) == 0)
695 set_output_format(cliargs_get_next()); // NULL is ok (handled like unknown)
696 else if (strcmp(string, OPTION_OUTFILE) == 0)
697 config.output_filename = cliargs_safe_get_next(name_outfile);
698 else if (strcmp(string, OPTION_LABELDUMP) == 0) // old
699 config.symbollist_filename = cliargs_safe_get_next(arg_symbollist);
700 else if (strcmp(string, OPTION_SYMBOLLIST) == 0) // new
701 config.symbollist_filename = cliargs_safe_get_next(arg_symbollist);
702 else if (strcmp(string, OPTION_VICELABELS) == 0)
703 config.vicelabels_filename = cliargs_safe_get_next(arg_vicelabels);
704 else if (strcmp(string, OPTION_REPORT) == 0)
705 config.report_filename = cliargs_safe_get_next(arg_reportfile);
706 else if (strcmp(string, OPTION_SETPC) == 0)
707 config.initial_pc = string_to_nonneg_number(cliargs_safe_get_next("program counter"));
708 else if (strcmp(string, OPTION_FROM_TO) == 0) {
709 config.outfile_start = string_to_nonneg_number(cliargs_safe_get_next("start address of output file"));
710 config.outfile_limit = string_to_nonneg_number(cliargs_safe_get_next("end+1 of output file"));
711 } else if (strcmp(string, OPTION_CPU) == 0)
712 set_starting_cpu(cliargs_get_next()); // NULL is ok (handled like unknown)
713 else if (strcmp(string, OPTION_INITMEM) == 0)
714 set_mem_contents(cliargs_safe_get_next("initmem value"));
715 else if (strcmp(string, OPTION_MAXERRORS) == 0)
716 config.max_errors = string_to_number(cliargs_safe_get_next("maximum error count"));
717 else if (strcmp(string, OPTION_MAXDEPTH) == 0)
718 config.sanity_limit = string_to_number(cliargs_safe_get_next("recursion depth"));
719 else if (strcmp(string, OPTION_USE_STDOUT) == 0)
720 config.msg_stream = stdout;
721 else if (strcmp(string, OPTION_MSVC) == 0)
722 config.format_msvc = TRUE;
723 else if (strcmp(string, OPTION_FULLSTOP) == 0)
724 config.pseudoop_prefix = '.';
725 else if (strcmp(string, OPTION_IGNORE_ZEROES) == 0)
726 config.honor_leading_zeroes = FALSE;
727 else if (strcmp(string, OPTION_STRICT_SEGMENTS) == 0)
728 config.strict_segments = TRUE;
729 else if (strcmp(string, OPTION_STRICT) == 0)
730 config.all_warnings_are_errors = TRUE;
731 else if (strcmp(string, OPTION_LIBPATH) == 0)
732 platform_set_lib_path(cliargs_safe_get_next("path to library"));
733 else if (strcmp(string, OPTION_DIALECT) == 0)
734 set_dialect(cliargs_get_next()); // NULL is ok (handled like unknown)
735 else if (strcmp(string, OPTION_PLEASE) == 0)
736 ++config.politeness;
737 else if (strcmp(string, OPTION_DEBUGLEVEL) == 0)
738 config.debuglevel = string_to_number(cliargs_safe_get_next("debug level"));
739 else if (strcmp(string, OPTION_TEST) == 0) {
740 config.dialect = V__FUTURE_VERSION;
741 config.test_new_features = TRUE;
742 } PLATFORM_LONGOPTION_CODE
743 else if (strcmp(string, OPTION_COLOR) == 0)
744 config.format_color = TRUE;
745 else if (strcmp(string, OPTION_VERSION) == 0)
746 show_version(TRUE);
747 else
748 return string;
749 return NULL;
750 }
751
752
753 // handle short options (like "-e"). Return unknown character.
754 static char short_option(const char *argument)
755 {
756 while (*argument) {
757 switch (*argument) {
758 case 'D': // "-D" define constants
759 if (argument[1])
760 define_symbol(argument + 1);
761 else
762 define_symbol(cliargs_safe_get_next("symbol definition"));
763 goto done;
764 case 'f': // "-f" selects output format
765 set_output_format(cliargs_get_next()); // NULL is ok (handled like unknown)
766 break;
767 case 'h': // "-h" shows help
768 show_help_and_exit();
769 break;
770 case 'I': // "-I" adds an include directory
771 if (argument[1])
772 includepaths_add(argument + 1);
773 else
774 includepaths_add(cliargs_safe_get_next("include path"));
775 goto done;
776 case 'l': // "-l" selects symbol list filename
777 config.symbollist_filename = cliargs_safe_get_next(arg_symbollist);
778 break;
779 case 'o': // "-o" selects output filename
780 config.output_filename = cliargs_safe_get_next(name_outfile);
781 break;
782 case 'r': // "-r" selects report filename
783 config.report_filename = cliargs_safe_get_next(arg_reportfile);
784 break;
785 case 'v': // "-v" changes verbosity
786 ++config.process_verbosity;
787 if ((argument[1] >= '0') && (argument[1] <= '9'))
788 config.process_verbosity = *(++argument) - '0';
789 break;
790 // platform specific switches are inserted here
791 PLATFORM_SHORTOPTION_CODE
792 case 'V': // "-V" shows version
793 show_version(TRUE);
794 break;
795 case 'W': // "-W" tunes warning level
796 if (strcmp(argument + 1, OPTIONWNO_LABEL_INDENT) == 0) {
797 config.warn_on_indented_labels = FALSE;
798 goto done;
799 } else if (strcmp(argument + 1, OPTIONWNO_OLD_FOR) == 0) {
800 config.dialect = V0_94_12__NEW_FOR_SYNTAX - 1;
801 goto done;
802 } else if (strcmp(argument + 1, OPTIONWNO_BIN_LEN) == 0) {
803 config.warn_bin_mask = 0;
804 goto done;
805 } else if (strcmp(argument + 1, OPTIONWTYPE_MISMATCH) == 0) {
806 config.warn_on_type_mismatch = TRUE;
807 goto done;
808 } else {
809 exit__cli_arg_error("Unknown warning level \"%s\".", argument);
810 }
811 break;
812 default: // unknown ones: program termination
813 return *argument;
814 }
815 ++argument;
816 }
817 done:
818 return '\0';
819 }
820
821
822 // guess what
823 int main(int argc, const char *argv[])
824 {
825 // make sure that if someone compiles this for ancient platforms
826 // they edit config.h accordingly:
827 // (on modern compilers this block will be optimized away anyway)
828 if ((sizeof(intval_t) < 4) || (sizeof(uintval_t) < 4)) {
829 fprintf(stderr, "Error: typedefs for intval_t and uintval_t must use types with at least 32 bits.\nPlease edit config.h and recompile.\n");
830 exit(EXIT_FAILURE);
831 }
832 config_default(&config);
833 // if called without any arguments, show usage info (not full help)
834 if (argc == 1)
835 show_help_and_exit();
836 cliargs_init(argc, argv);
837 // init pass number because any assignments done via "-D SYMBOL=VALUE"
838 // cli args must be handled as if they happened at the start of pass 1:
839 pass.number = 1;
840 // init platform-specific stuff.
841 // this may read the library path from an environment variable.
842 PLATFORM_INIT;
843 // handle command line arguments
844 // (this will handle all "-D SYMBOL=VALUE" assignments)
845 cliargs_handle_options(short_option, long_option);
846 // generate list of files to process
847 cliargs_get_rest(&toplevel_src_count, &toplevel_sources_plat, "No top level sources given");
848
849 // now that we have processed all cli switches, check a few values for
850 // valid range:
851 if ((config.initial_pc != NO_VALUE_GIVEN) && (config.initial_pc >= OUTBUF_MAXSIZE))
852 throw_error("Program counter exceeds maximum outbuffer size.");
853 if ((config.outfile_start != NO_VALUE_GIVEN) && (config.outfile_start >= OUTBUF_MAXSIZE))
854 throw_error("Start address of output file exceeds maximum outbuffer size.");
855 // "limit" is end+1 and therefore we need ">" instead of ">=":
856 if ((config.outfile_limit != NO_VALUE_GIVEN) && (config.outfile_limit > OUTBUF_MAXSIZE))
857 throw_error("End+1 of output file exceeds maximum outbuffer size.");
858 if ((config.outfile_start != NO_VALUE_GIVEN)
859 && (config.outfile_limit != NO_VALUE_GIVEN)
860 && (config.outfile_start >= config.outfile_limit))
861 throw_error("Start address of output file exceeds end+1.");
862 // since version 0.98, "--strict-segments" are default:
863 if (config.dialect >= V0_98__PATHS_AND_SYMBOLCHANGE)
864 config.strict_segments = TRUE;
865
866 // make throw_error() behave normally instead of exiting with "Error in CLI arguments: ..."
867 throw__done_with_cli_args();
868
869 // do the actual work
870 do_actual_work();
871 return ACME_finalize(EXIT_SUCCESS); // dump labels, if wanted
872 }