nasmlib/file: move memory-mapping functions out of file.c
[nasm.git] / asm / nasm.c
blob29cade7a87fb1570b93be6d1aad6e1d41637cda2
1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2016 The NASM Authors - All Rights Reserved
4 * See the file AUTHORS included with the NASM distribution for
5 * the specific copyright holders.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following
9 * conditions are met:
11 * * Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * * Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
19 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
20 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
29 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
30 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 * ----------------------------------------------------------------------- */
35 * The Netwide Assembler main program module
38 #include "compiler.h"
40 #include <stdio.h>
41 #include <stdarg.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <ctype.h>
45 #include <limits.h>
46 #include <time.h>
48 #include "nasm.h"
49 #include "nasmlib.h"
50 #include "saa.h"
51 #include "raa.h"
52 #include "float.h"
53 #include "stdscan.h"
54 #include "insns.h"
55 #include "preproc.h"
56 #include "parser.h"
57 #include "eval.h"
58 #include "assemble.h"
59 #include "labels.h"
60 #include "outform.h"
61 #include "listing.h"
62 #include "iflag.h"
63 #include "ver.h"
66 * This is the maximum number of optimization passes to do. If we ever
67 * find a case where the optimizer doesn't naturally converge, we might
68 * have to drop this value so the assembler doesn't appear to just hang.
70 #define MAX_OPTIMIZE (INT_MAX >> 1)
72 struct forwrefinfo { /* info held on forward refs. */
73 int lineno;
74 int operand;
77 static int get_bits(char *value);
78 static iflag_t get_cpu(char *cpu_str);
79 static void parse_cmdline(int, char **, int);
80 static void assemble_file(char *, StrList **);
81 static bool is_suppressed_warning(int severity);
82 static bool skip_this_pass(int severity);
83 static void nasm_verror_gnu(int severity, const char *fmt, va_list args);
84 static void nasm_verror_vc(int severity, const char *fmt, va_list args);
85 static void nasm_verror_common(int severity, const char *fmt, va_list args);
86 static void usage(void);
88 static bool using_debug_info, opt_verbose_info;
89 static const char *debug_format;
91 bool tasm_compatible_mode = false;
92 int pass0, passn;
93 int globalrel = 0;
94 int globalbnd = 0;
96 static time_t official_compile_time;
98 static char inname[FILENAME_MAX];
99 static char outname[FILENAME_MAX];
100 static char listname[FILENAME_MAX];
101 static char errname[FILENAME_MAX];
102 static int globallineno; /* for forward-reference tracking */
103 /* static int pass = 0; */
104 const struct ofmt *ofmt = &OF_DEFAULT;
105 const struct ofmt_alias *ofmt_alias = NULL;
106 const struct dfmt *dfmt;
108 static FILE *error_file; /* Where to write error messages */
110 FILE *ofile = NULL;
111 int optimizing = MAX_OPTIMIZE; /* number of optimization passes to take */
112 static int cmd_sb = 16; /* by default */
114 static iflag_t cpu;
115 static iflag_t cmd_cpu;
117 int64_t global_offset_changed; /* referenced in labels.c */
118 int64_t prev_offset_changed;
119 int32_t stall_count;
121 struct location location;
122 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
123 int32_t abs_seg; /* ABSOLUTE segment basis */
124 int32_t abs_offset; /* ABSOLUTE offset */
126 static struct RAA *offsets;
128 static struct SAA *forwrefs; /* keep track of forward references */
129 static const struct forwrefinfo *forwref;
131 static const struct preproc_ops *preproc;
133 #define OP_NORMAL (1u << 0)
134 #define OP_PREPROCESS (1u << 1)
135 #define OP_DEPEND (1u << 2)
137 static unsigned int operating_mode;
139 /* Dependency flags */
140 static bool depend_emit_phony = false;
141 static bool depend_missing_ok = false;
142 static const char *depend_target = NULL;
143 static const char *depend_file = NULL;
146 * Which of the suppressible warnings are suppressed. Entry zero
147 * isn't an actual warning, but it used for -w+error/-Werror.
150 static bool warning_on[ERR_WARN_MAX+1]; /* Current state */
151 static bool warning_on_global[ERR_WARN_MAX+1]; /* Command-line state */
153 static const struct warning {
154 const char *name;
155 const char *help;
156 bool enabled;
157 } warnings[ERR_WARN_MAX+1] = {
158 {"error", "treat warnings as errors", false},
159 {"macro-params", "macro calls with wrong parameter count", true},
160 {"macro-selfref", "cyclic macro references", false},
161 {"macro-defaults", "macros with more default than optional parameters", true},
162 {"orphan-labels", "labels alone on lines without trailing `:'", true},
163 {"number-overflow", "numeric constant does not fit", true},
164 {"gnu-elf-extensions", "using 8- or 16-bit relocation in ELF32, a GNU extension", false},
165 {"float-overflow", "floating point overflow", true},
166 {"float-denorm", "floating point denormal", false},
167 {"float-underflow", "floating point underflow", false},
168 {"float-toolong", "too many digits in floating-point number", true},
169 {"user", "%warning directives", true},
170 {"lock", "lock prefix on unlockable instructions", true},
171 {"hle", "invalid hle prefixes", true},
172 {"bnd", "invalid bnd prefixes", true},
173 {"zext-reloc", "relocation zero-extended to match output format", true},
174 {"ptr", "non-NASM keyword used in other assemblers", true},
177 static bool want_usage;
178 static bool terminate_after_phase;
179 bool user_nolist = false;
181 static char *quote_for_make(const char *str);
183 static int64_t get_curr_offs(void)
185 return in_abs_seg ? abs_offset : raa_read(offsets, location.segment);
188 static void set_curr_offs(int64_t l_off)
190 if (in_abs_seg)
191 abs_offset = l_off;
192 else
193 offsets = raa_write(offsets, location.segment, l_off);
196 static void nasm_fputs(const char *line, FILE * outfile)
198 if (outfile) {
199 fputs(line, outfile);
200 putc('\n', outfile);
201 } else
202 puts(line);
205 /* Convert a struct tm to a POSIX-style time constant */
206 static int64_t make_posix_time(struct tm *tm)
208 int64_t t;
209 int64_t y = tm->tm_year;
211 /* See IEEE 1003.1:2004, section 4.14 */
213 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
214 t += tm->tm_yday;
215 t *= 24;
216 t += tm->tm_hour;
217 t *= 60;
218 t += tm->tm_min;
219 t *= 60;
220 t += tm->tm_sec;
222 return t;
225 static void define_macros_early(void)
227 char temp[128];
228 struct tm lt, *lt_p, gm, *gm_p;
229 int64_t posix_time;
231 lt_p = localtime(&official_compile_time);
232 if (lt_p) {
233 lt = *lt_p;
235 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &lt);
236 preproc->pre_define(temp);
237 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &lt);
238 preproc->pre_define(temp);
239 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &lt);
240 preproc->pre_define(temp);
241 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &lt);
242 preproc->pre_define(temp);
245 gm_p = gmtime(&official_compile_time);
246 if (gm_p) {
247 gm = *gm_p;
249 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
250 preproc->pre_define(temp);
251 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
252 preproc->pre_define(temp);
253 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
254 preproc->pre_define(temp);
255 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
256 preproc->pre_define(temp);
259 if (gm_p)
260 posix_time = make_posix_time(&gm);
261 else if (lt_p)
262 posix_time = make_posix_time(&lt);
263 else
264 posix_time = 0;
266 if (posix_time) {
267 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
268 preproc->pre_define(temp);
272 static void define_macros_late(void)
274 char temp[128];
277 * In case if output format is defined by alias
278 * we have to put shortname of the alias itself here
279 * otherwise ABI backward compatibility gets broken.
281 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s",
282 ofmt_alias ? ofmt_alias->shortname : ofmt->shortname);
283 preproc->pre_define(temp);
286 static void emit_dependencies(StrList *list)
288 FILE *deps;
289 int linepos, len;
290 StrList *l, *nl;
292 if (depend_file && strcmp(depend_file, "-")) {
293 deps = nasm_open_write(depend_file, NF_TEXT);
294 if (!deps) {
295 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
296 "unable to write dependency file `%s'", depend_file);
297 return;
299 } else {
300 deps = stdout;
303 linepos = fprintf(deps, "%s:", depend_target);
304 list_for_each(l, list) {
305 char *file = quote_for_make(l->str);
306 len = strlen(file);
307 if (linepos + len > 62 && linepos > 1) {
308 fprintf(deps, " \\\n ");
309 linepos = 1;
311 fprintf(deps, " %s", file);
312 linepos += len+1;
313 nasm_free(file);
315 fprintf(deps, "\n\n");
317 list_for_each_safe(l, nl, list) {
318 if (depend_emit_phony)
319 fprintf(deps, "%s:\n\n", l->str);
320 nasm_free(l);
323 if (deps != stdout)
324 fclose(deps);
327 int main(int argc, char **argv)
329 StrList *depend_list = NULL, **depend_ptr;
331 time(&official_compile_time);
333 iflag_set(&cpu, IF_PLEVEL);
334 iflag_set(&cmd_cpu, IF_PLEVEL);
336 pass0 = 0;
337 want_usage = terminate_after_phase = false;
338 nasm_set_verror(nasm_verror_gnu);
340 error_file = stderr;
342 tolower_init();
343 src_init();
345 offsets = raa_init();
346 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
348 preproc = &nasmpp;
349 operating_mode = OP_NORMAL;
351 parse_cmdline(argc, argv, 1);
352 if (terminate_after_phase) {
353 if (want_usage)
354 usage();
355 return 1;
359 * Define some macros dependent on the runtime, but not
360 * on the command line (as those are scanned in cmdline pass 2.)
362 preproc->init();
363 define_macros_early();
365 parse_cmdline(argc, argv, 2);
366 if (terminate_after_phase) {
367 if (want_usage)
368 usage();
369 return 1;
372 if (!using_debug_info) {
373 /* No debug info, redirect to the null backend (empty stubs) */
374 dfmt = &null_debug_form;
375 } else if (!debug_format) {
376 /* Default debug format for this backend */
377 dfmt = ofmt->default_dfmt;
378 } else {
379 dfmt = dfmt_find(ofmt, debug_format);
380 if (!dfmt) {
381 nasm_fatal(ERR_NOFILE | ERR_USAGE,
382 "unrecognized debug format `%s' for"
383 " output format `%s'",
384 debug_format, ofmt->shortname);
388 if (ofmt->stdmac)
389 preproc->extra_stdmac(ofmt->stdmac);
391 /* define some macros dependent of command-line */
392 define_macros_late();
394 depend_ptr = (depend_file || (operating_mode & OP_DEPEND)) ? &depend_list : NULL;
395 if (!depend_target)
396 depend_target = quote_for_make(outname);
398 if (operating_mode & OP_DEPEND) {
399 char *line;
401 if (depend_missing_ok)
402 preproc->include_path(NULL); /* "assume generated" */
404 preproc->reset(inname, 0, depend_ptr);
405 if (outname[0] == '\0')
406 ofmt->filename(inname, outname);
407 ofile = NULL;
408 while ((line = preproc->getline()))
409 nasm_free(line);
410 preproc->cleanup(0);
411 } else if (operating_mode & OP_PREPROCESS) {
412 char *line;
413 const char *file_name = NULL;
414 int32_t prior_linnum = 0;
415 int lineinc = 0;
417 if (*outname) {
418 ofile = nasm_open_write(outname, NF_TEXT);
419 if (!ofile)
420 nasm_fatal(ERR_NOFILE,
421 "unable to open output file `%s'",
422 outname);
423 } else
424 ofile = NULL;
426 location.known = false;
428 /* pass = 1; */
429 preproc->reset(inname, 3, depend_ptr);
430 memcpy(warning_on, warning_on_global,
431 (ERR_WARN_MAX+1) * sizeof(bool));
433 while ((line = preproc->getline())) {
435 * We generate %line directives if needed for later programs
437 int32_t linnum = prior_linnum += lineinc;
438 int altline = src_get(&linnum, &file_name);
439 if (altline) {
440 if (altline == 1 && lineinc == 1)
441 nasm_fputs("", ofile);
442 else {
443 lineinc = (altline != -1 || lineinc != 1);
444 fprintf(ofile ? ofile : stdout,
445 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
446 file_name);
448 prior_linnum = linnum;
450 nasm_fputs(line, ofile);
451 nasm_free(line);
453 preproc->cleanup(0);
454 if (ofile)
455 fclose(ofile);
456 if (ofile && terminate_after_phase)
457 remove(outname);
458 ofile = NULL;
461 if (operating_mode & OP_NORMAL) {
463 * We must call ofmt->filename _anyway_, even if the user
464 * has specified their own output file, because some
465 * formats (eg OBJ and COFF) use ofmt->filename to find out
466 * the name of the input file and then put that inside the
467 * file.
469 ofmt->filename(inname, outname);
471 ofile = nasm_open_write(outname, (ofmt->flags & OFMT_TEXT) ? NF_TEXT : NF_BINARY);
472 if (!ofile)
473 nasm_fatal(ERR_NOFILE,
474 "unable to open output file `%s'", outname);
477 * We must call init_labels() before ofmt->init() since
478 * some object formats will want to define labels in their
479 * init routines. (eg OS/2 defines the FLAT group)
481 init_labels();
483 ofmt->init();
484 dfmt->init();
486 assemble_file(inname, depend_ptr);
488 if (!terminate_after_phase) {
489 ofmt->cleanup();
490 cleanup_labels();
491 fflush(ofile);
492 if (ferror(ofile)) {
493 nasm_error(ERR_NONFATAL|ERR_NOFILE,
494 "write error on output file `%s'", outname);
495 terminate_after_phase = true;
499 if (ofile) {
500 fclose(ofile);
501 if (terminate_after_phase)
502 remove(outname);
503 ofile = NULL;
507 if (depend_list && !terminate_after_phase)
508 emit_dependencies(depend_list);
510 if (want_usage)
511 usage();
513 raa_free(offsets);
514 saa_free(forwrefs);
515 eval_cleanup();
516 stdscan_cleanup();
517 src_free();
519 return terminate_after_phase;
523 * Get a parameter for a command line option.
524 * First arg must be in the form of e.g. -f...
526 static char *get_param(char *p, char *q, bool *advance)
528 *advance = false;
529 if (p[2]) /* the parameter's in the option */
530 return nasm_skip_spaces(p + 2);
531 if (q && q[0]) {
532 *advance = true;
533 return q;
535 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
536 "option `-%c' requires an argument", p[1]);
537 return NULL;
541 * Copy a filename
543 static void copy_filename(char *dst, const char *src)
545 size_t len = strlen(src);
547 if (len >= (size_t)FILENAME_MAX) {
548 nasm_fatal(ERR_NOFILE, "file name too long");
549 return;
551 strncpy(dst, src, FILENAME_MAX);
555 * Convert a string to Make-safe form
557 static char *quote_for_make(const char *str)
559 const char *p;
560 char *os, *q;
562 size_t n = 1; /* Terminating zero */
563 size_t nbs = 0;
565 if (!str)
566 return NULL;
568 for (p = str; *p; p++) {
569 switch (*p) {
570 case ' ':
571 case '\t':
572 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
573 n += nbs + 2;
574 nbs = 0;
575 break;
576 case '$':
577 case '#':
578 nbs = 0;
579 n += 2;
580 break;
581 case '\\':
582 nbs++;
583 n++;
584 break;
585 default:
586 nbs = 0;
587 n++;
588 break;
592 /* Convert N backslashes at the end of filename to 2N backslashes */
593 if (nbs)
594 n += nbs;
596 os = q = nasm_malloc(n);
598 nbs = 0;
599 for (p = str; *p; p++) {
600 switch (*p) {
601 case ' ':
602 case '\t':
603 while (nbs--)
604 *q++ = '\\';
605 *q++ = '\\';
606 *q++ = *p;
607 break;
608 case '$':
609 *q++ = *p;
610 *q++ = *p;
611 nbs = 0;
612 break;
613 case '#':
614 *q++ = '\\';
615 *q++ = *p;
616 nbs = 0;
617 break;
618 case '\\':
619 *q++ = *p;
620 nbs++;
621 break;
622 default:
623 *q++ = *p;
624 nbs = 0;
625 break;
628 while (nbs--)
629 *q++ = '\\';
631 *q = '\0';
633 return os;
636 struct textargs {
637 const char *label;
638 int value;
641 enum text_options {
642 OPT_PREFIX,
643 OPT_POSTFIX
645 static const struct textargs textopts[] = {
646 {"prefix", OPT_PREFIX},
647 {"postfix", OPT_POSTFIX},
648 {NULL, 0}
651 static void show_version(void)
653 printf("NASM version %s compiled on %s%s\n",
654 nasm_version, nasm_date, nasm_compile_options);
655 exit(0);
658 static bool stopoptions = false;
659 static bool process_arg(char *p, char *q, int pass)
661 char *param;
662 int i;
663 bool advance = false;
664 bool do_warn;
666 if (!p || !p[0])
667 return false;
669 if (p[0] == '-' && !stopoptions) {
670 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
671 /* These parameters take values */
672 if (!(param = get_param(p, q, &advance)))
673 return advance;
676 switch (p[1]) {
677 case 's':
678 if (pass == 1)
679 error_file = stdout;
680 break;
682 case 'o': /* output file */
683 if (pass == 2)
684 copy_filename(outname, param);
685 break;
687 case 'f': /* output format */
688 if (pass == 1) {
689 ofmt = ofmt_find(param, &ofmt_alias);
690 if (!ofmt) {
691 nasm_fatal(ERR_NOFILE | ERR_USAGE,
692 "unrecognised output format `%s' - "
693 "use -hf for a list", param);
696 break;
698 case 'O': /* Optimization level */
699 if (pass == 2) {
700 int opt;
702 if (!*param) {
703 /* Naked -O == -Ox */
704 optimizing = MAX_OPTIMIZE;
705 } else {
706 while (*param) {
707 switch (*param) {
708 case '0': case '1': case '2': case '3': case '4':
709 case '5': case '6': case '7': case '8': case '9':
710 opt = strtoul(param, &param, 10);
712 /* -O0 -> optimizing == -1, 0.98 behaviour */
713 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
714 if (opt < 2)
715 optimizing = opt - 1;
716 else
717 optimizing = opt;
718 break;
720 case 'v':
721 case '+':
722 param++;
723 opt_verbose_info = true;
724 break;
726 case 'x':
727 param++;
728 optimizing = MAX_OPTIMIZE;
729 break;
731 default:
732 nasm_fatal(0,
733 "unknown optimization option -O%c\n",
734 *param);
735 break;
738 if (optimizing > MAX_OPTIMIZE)
739 optimizing = MAX_OPTIMIZE;
742 break;
744 case 'p': /* pre-include */
745 case 'P':
746 if (pass == 2)
747 preproc->pre_include(param);
748 break;
750 case 'd': /* pre-define */
751 case 'D':
752 if (pass == 2)
753 preproc->pre_define(param);
754 break;
756 case 'u': /* un-define */
757 case 'U':
758 if (pass == 2)
759 preproc->pre_undefine(param);
760 break;
762 case 'i': /* include search path */
763 case 'I':
764 if (pass == 2)
765 preproc->include_path(param);
766 break;
768 case 'l': /* listing file */
769 if (pass == 2)
770 copy_filename(listname, param);
771 break;
773 case 'Z': /* error messages file */
774 if (pass == 1)
775 copy_filename(errname, param);
776 break;
778 case 'F': /* specify debug format */
779 if (pass == 2) {
780 using_debug_info = true;
781 debug_format = param;
783 break;
785 case 'X': /* specify error reporting format */
786 if (pass == 1) {
787 if (nasm_stricmp("vc", param) == 0)
788 nasm_set_verror(nasm_verror_vc);
789 else if (nasm_stricmp("gnu", param) == 0)
790 nasm_set_verror(nasm_verror_gnu);
791 else
792 nasm_fatal(ERR_NOFILE | ERR_USAGE,
793 "unrecognized error reporting format `%s'",
794 param);
796 break;
798 case 'g':
799 if (pass == 2) {
800 using_debug_info = true;
801 if (p[2])
802 debug_format = nasm_skip_spaces(p + 2);
804 break;
806 case 'h':
807 printf
808 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
809 "[-l listfile]\n"
810 " [options...] [--] filename\n"
811 " or nasm -v (or --v) for version info\n\n"
812 " -t assemble in SciTech TASM compatible mode\n");
813 printf
814 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
815 " -a don't preprocess (assemble only)\n"
816 " -M generate Makefile dependencies on stdout\n"
817 " -MG d:o, missing files assumed generated\n"
818 " -MF <file> set Makefile dependency file\n"
819 " -MD <file> assemble and generate dependencies\n"
820 " -MT <file> dependency target name\n"
821 " -MQ <file> dependency target name (quoted)\n"
822 " -MP emit phony target\n\n"
823 " -Z<file> redirect error messages to file\n"
824 " -s redirect error messages to stdout\n\n"
825 " -g generate debugging information\n\n"
826 " -F format select a debugging format\n\n"
827 " -gformat same as -g -F format\n\n"
828 " -o outfile write output to an outfile\n\n"
829 " -f format select an output format\n\n"
830 " -l listfile write listing to a listfile\n\n"
831 " -I<path> adds a pathname to the include file path\n");
832 printf
833 (" -O<digit> optimize branch offsets\n"
834 " -O0: No optimization\n"
835 " -O1: Minimal optimization\n"
836 " -Ox: Multipass optimization (default)\n\n"
837 " -P<file> pre-includes a file\n"
838 " -D<macro>[=<value>] pre-defines a macro\n"
839 " -U<macro> undefines a macro\n"
840 " -X<format> specifies error reporting format (gnu or vc)\n"
841 " -w+foo enables warning foo (equiv. -Wfoo)\n"
842 " -w-foo disable warning foo (equiv. -Wno-foo)\n\n"
843 " -h show invocation summary and exit\n\n"
844 "--prefix,--postfix\n"
845 " this options prepend or append the given argument to all\n"
846 " extern and global variables\n"
847 "Warnings:\n");
848 for (i = 0; i <= ERR_WARN_MAX; i++)
849 printf(" %-23s %s (default %s)\n",
850 warnings[i].name, warnings[i].help,
851 warnings[i].enabled ? "on" : "off");
852 printf
853 ("\nresponse files should contain command line parameters"
854 ", one per line.\n");
855 if (p[2] == 'f') {
856 printf("\nvalid output formats for -f are"
857 " (`*' denotes default):\n");
858 ofmt_list(ofmt, stdout);
859 } else {
860 printf("\nFor a list of valid output formats, use -hf.\n");
861 printf("For a list of debug formats, use -f <form> -y.\n");
863 exit(0); /* never need usage message here */
864 break;
866 case 'y':
867 printf("\nvalid debug formats for '%s' output format are"
868 " ('*' denotes default):\n", ofmt->shortname);
869 dfmt_list(ofmt, stdout);
870 exit(0);
871 break;
873 case 't':
874 if (pass == 2)
875 tasm_compatible_mode = true;
876 break;
878 case 'v':
879 show_version();
880 break;
882 case 'e': /* preprocess only */
883 case 'E':
884 if (pass == 1)
885 operating_mode = OP_PREPROCESS;
886 break;
888 case 'a': /* assemble only - don't preprocess */
889 if (pass == 1)
890 preproc = &preproc_nop;
891 break;
893 case 'W':
894 if (pass == 2) {
895 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
896 do_warn = false;
897 param += 3;
898 } else {
899 do_warn = true;
901 goto set_warning;
903 break;
905 case 'w':
906 if (pass == 2) {
907 if (param[0] != '+' && param[0] != '-') {
908 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
909 "invalid option to `-w'");
910 break;
912 do_warn = (param[0] == '+');
913 param++;
914 goto set_warning;
916 break;
918 set_warning:
919 for (i = 0; i <= ERR_WARN_MAX; i++) {
920 if (!nasm_stricmp(param, warnings[i].name))
921 break;
923 if (i <= ERR_WARN_MAX) {
924 warning_on_global[i] = do_warn;
925 } else if (!nasm_stricmp(param, "all")) {
926 for (i = 1; i <= ERR_WARN_MAX; i++)
927 warning_on_global[i] = do_warn;
928 } else if (!nasm_stricmp(param, "none")) {
929 for (i = 1; i <= ERR_WARN_MAX; i++)
930 warning_on_global[i] = !do_warn;
931 } else {
932 /* Ignore invalid warning names; forward compatibility */
934 break;
936 case 'M':
937 if (pass == 2) {
938 switch (p[2]) {
939 case 0:
940 operating_mode = OP_DEPEND;
941 break;
942 case 'G':
943 operating_mode = OP_DEPEND;
944 depend_missing_ok = true;
945 break;
946 case 'P':
947 depend_emit_phony = true;
948 break;
949 case 'D':
950 operating_mode = OP_NORMAL;
951 depend_file = q;
952 advance = true;
953 break;
954 case 'F':
955 depend_file = q;
956 advance = true;
957 break;
958 case 'T':
959 depend_target = q;
960 advance = true;
961 break;
962 case 'Q':
963 depend_target = quote_for_make(q);
964 advance = true;
965 break;
966 default:
967 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
968 "unknown dependency option `-M%c'", p[2]);
969 break;
971 if (advance && (!q || !q[0])) {
972 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
973 "option `-M%c' requires a parameter", p[2]);
974 break;
977 break;
979 case '-':
981 int s;
983 if (p[2] == 0) { /* -- => stop processing options */
984 stopoptions = 1;
985 break;
988 if (!nasm_stricmp(p, "--v"))
989 show_version();
991 if (!nasm_stricmp(p, "--version"))
992 show_version();
994 for (s = 0; textopts[s].label; s++) {
995 if (!nasm_stricmp(p + 2, textopts[s].label)) {
996 break;
1000 switch (s) {
1002 case OPT_PREFIX:
1003 case OPT_POSTFIX:
1005 if (!q) {
1006 nasm_error(ERR_NONFATAL | ERR_NOFILE |
1007 ERR_USAGE,
1008 "option `--%s' requires an argument",
1009 p + 2);
1010 break;
1011 } else {
1012 advance = 1, param = q;
1015 switch (s) {
1016 case OPT_PREFIX:
1017 if (pass == 2)
1018 strlcpy(lprefix, param, PREFIX_MAX);
1019 break;
1020 case OPT_POSTFIX:
1021 if (pass == 2)
1022 strlcpy(lpostfix, param, POSTFIX_MAX);
1023 break;
1024 default:
1025 nasm_panic(ERR_NOFILE,
1026 "internal error");
1027 break;
1029 break;
1032 default:
1034 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1035 "unrecognised option `--%s'", p + 2);
1036 break;
1039 break;
1042 default:
1043 if (!ofmt->setinfo(GI_SWITCH, &p))
1044 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1045 "unrecognised option `-%c'", p[1]);
1046 break;
1048 } else if (pass == 2) {
1049 if (*inname) {
1050 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1051 "more than one input file specified");
1052 } else {
1053 copy_filename(inname, p);
1057 return advance;
1060 #define ARG_BUF_DELTA 128
1062 static void process_respfile(FILE * rfile, int pass)
1064 char *buffer, *p, *q, *prevarg;
1065 int bufsize, prevargsize;
1067 bufsize = prevargsize = ARG_BUF_DELTA;
1068 buffer = nasm_malloc(ARG_BUF_DELTA);
1069 prevarg = nasm_malloc(ARG_BUF_DELTA);
1070 prevarg[0] = '\0';
1072 while (1) { /* Loop to handle all lines in file */
1073 p = buffer;
1074 while (1) { /* Loop to handle long lines */
1075 q = fgets(p, bufsize - (p - buffer), rfile);
1076 if (!q)
1077 break;
1078 p += strlen(p);
1079 if (p > buffer && p[-1] == '\n')
1080 break;
1081 if (p - buffer > bufsize - 10) {
1082 int offset;
1083 offset = p - buffer;
1084 bufsize += ARG_BUF_DELTA;
1085 buffer = nasm_realloc(buffer, bufsize);
1086 p = buffer + offset;
1090 if (!q && p == buffer) {
1091 if (prevarg[0])
1092 process_arg(prevarg, NULL, pass);
1093 nasm_free(buffer);
1094 nasm_free(prevarg);
1095 return;
1099 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1100 * them are present at the end of the line.
1102 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1104 while (p > buffer && nasm_isspace(p[-1]))
1105 *--p = '\0';
1107 p = nasm_skip_spaces(buffer);
1109 if (process_arg(prevarg, p, pass))
1110 *p = '\0';
1112 if ((int) strlen(p) > prevargsize - 10) {
1113 prevargsize += ARG_BUF_DELTA;
1114 prevarg = nasm_realloc(prevarg, prevargsize);
1116 strncpy(prevarg, p, prevargsize);
1120 /* Function to process args from a string of args, rather than the
1121 * argv array. Used by the environment variable and response file
1122 * processing.
1124 static void process_args(char *args, int pass)
1126 char *p, *q, *arg, *prevarg;
1127 char separator = ' ';
1129 p = args;
1130 if (*p && *p != '-')
1131 separator = *p++;
1132 arg = NULL;
1133 while (*p) {
1134 q = p;
1135 while (*p && *p != separator)
1136 p++;
1137 while (*p == separator)
1138 *p++ = '\0';
1139 prevarg = arg;
1140 arg = q;
1141 if (process_arg(prevarg, arg, pass))
1142 arg = NULL;
1144 if (arg)
1145 process_arg(arg, NULL, pass);
1148 static void process_response_file(const char *file, int pass)
1150 char str[2048];
1151 FILE *f = nasm_open_read(file, NF_TEXT);
1152 if (!f) {
1153 perror(file);
1154 exit(-1);
1156 while (fgets(str, sizeof str, f)) {
1157 process_args(str, pass);
1159 fclose(f);
1162 static void parse_cmdline(int argc, char **argv, int pass)
1164 FILE *rfile;
1165 char *envreal, *envcopy = NULL, *p;
1166 int i;
1168 *inname = *outname = *listname = *errname = '\0';
1170 for (i = 0; i <= ERR_WARN_MAX; i++)
1171 warning_on_global[i] = warnings[i].enabled;
1174 * First, process the NASMENV environment variable.
1176 envreal = getenv("NASMENV");
1177 if (envreal) {
1178 envcopy = nasm_strdup(envreal);
1179 process_args(envcopy, pass);
1180 nasm_free(envcopy);
1184 * Now process the actual command line.
1186 while (--argc) {
1187 bool advance;
1188 argv++;
1189 if (argv[0][0] == '@') {
1191 * We have a response file, so process this as a set of
1192 * arguments like the environment variable. This allows us
1193 * to have multiple arguments on a single line, which is
1194 * different to the -@resp file processing below for regular
1195 * NASM.
1197 process_response_file(argv[0]+1, pass);
1198 argc--;
1199 argv++;
1201 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1202 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1203 if (p) {
1204 rfile = nasm_open_read(p, NF_TEXT);
1205 if (rfile) {
1206 process_respfile(rfile, pass);
1207 fclose(rfile);
1208 } else
1209 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1210 "unable to open response file `%s'", p);
1212 } else
1213 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL, pass);
1214 argv += advance, argc -= advance;
1218 * Look for basic command line typos. This definitely doesn't
1219 * catch all errors, but it might help cases of fumbled fingers.
1221 if (pass != 2)
1222 return;
1224 if (!*inname)
1225 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1226 "no input file specified");
1227 else if (!strcmp(inname, errname) ||
1228 !strcmp(inname, outname) ||
1229 !strcmp(inname, listname) ||
1230 (depend_file && !strcmp(inname, depend_file)))
1231 nasm_fatal(ERR_NOFILE | ERR_USAGE,
1232 "file `%s' is both input and output file",
1233 inname);
1235 if (*errname) {
1236 error_file = nasm_open_write(errname, NF_TEXT);
1237 if (!error_file) {
1238 error_file = stderr; /* Revert to default! */
1239 nasm_fatal(ERR_NOFILE | ERR_USAGE,
1240 "cannot open file `%s' for error messages",
1241 errname);
1246 static enum directives getkw(char **directive, char **value);
1248 static void assemble_file(char *fname, StrList **depend_ptr)
1250 char *directive, *value, *p, *q, *special, *line;
1251 insn output_ins;
1252 int i, validid;
1253 bool rn_error;
1254 int32_t seg;
1255 int64_t offs;
1256 struct tokenval tokval;
1257 expr *e;
1258 int pass_max;
1259 char debugid[128];
1260 int sb;
1262 if (cmd_sb == 32 && iflag_ffs(&cmd_cpu) < IF_386)
1263 nasm_fatal(0, "command line: 32-bit segment size requires a higher cpu");
1265 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1266 for (passn = 1; pass0 <= 2; passn++) {
1267 int pass1, pass2;
1268 ldfunc def_label;
1270 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1271 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1272 /* pass0 0, 0, 0, ..., 1, 2 */
1274 def_label = passn > 1 ? redefine_label : define_label;
1276 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1277 cpu = cmd_cpu;
1278 if (pass0 == 2) {
1279 lfmt->init(listname);
1281 in_abs_seg = false;
1282 global_offset_changed = 0; /* set by redefine_label */
1283 location.segment = ofmt->section(NULL, pass2, &sb);
1284 globalbits = sb;
1285 if (passn > 1) {
1286 saa_rewind(forwrefs);
1287 forwref = saa_rstruct(forwrefs);
1288 raa_free(offsets);
1289 offsets = raa_init();
1291 preproc->reset(fname, pass1, pass1 == 2 ? depend_ptr : NULL);
1292 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1294 globallineno = 0;
1295 if (passn == 1)
1296 location.known = true;
1297 location.offset = offs = get_curr_offs();
1299 while ((line = preproc->getline())) {
1300 enum directives d;
1301 globallineno++;
1304 * Here we parse our directives; this is not handled by the
1305 * 'real' parser. This really should be a separate function.
1307 directive = line;
1308 d = getkw(&directive, &value);
1309 if (d) {
1310 int err = 0;
1312 switch (d) {
1313 case D_SEGMENT: /* [SEGMENT n] */
1314 case D_SECTION:
1315 seg = ofmt->section(value, pass2, &sb);
1316 if (seg == NO_SEG) {
1317 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1318 "segment name `%s' not recognized",
1319 value);
1320 } else {
1321 in_abs_seg = false;
1322 location.segment = seg;
1324 break;
1325 case D_SECTALIGN: /* [SECTALIGN n] */
1326 if (*value) {
1327 stdscan_reset();
1328 stdscan_set(value);
1329 tokval.t_type = TOKEN_INVALID;
1330 e = evaluate(stdscan, NULL, &tokval, NULL, pass2, NULL);
1331 if (e) {
1332 unsigned int align = (unsigned int)e->value;
1333 if ((uint64_t)e->value > 0x7fffffff) {
1335 * FIXME: Please make some sane message here
1336 * ofmt should have some 'check' method which
1337 * would report segment alignment bounds.
1339 nasm_fatal(0,
1340 "incorrect segment alignment `%s'", value);
1341 } else if (!is_power2(align)) {
1342 nasm_error(ERR_NONFATAL,
1343 "segment alignment `%s' is not power of two",
1344 value);
1347 /* callee should be able to handle all details */
1348 if (location.segment != NO_SEG)
1349 ofmt->sectalign(location.segment, align);
1352 break;
1353 case D_EXTERN: /* [EXTERN label:special] */
1354 if (*value == '$')
1355 value++; /* skip initial $ if present */
1356 if (pass0 == 2) {
1357 q = value;
1358 while (*q && *q != ':')
1359 q++;
1360 if (*q == ':') {
1361 *q++ = '\0';
1362 ofmt->symdef(value, 0L, 0L, 3, q);
1364 } else if (passn == 1) {
1365 q = value;
1366 validid = true;
1367 if (!isidstart(*q))
1368 validid = false;
1369 while (*q && *q != ':') {
1370 if (!isidchar(*q))
1371 validid = false;
1372 q++;
1374 if (!validid) {
1375 nasm_error(ERR_NONFATAL,
1376 "identifier expected after EXTERN");
1377 break;
1379 if (*q == ':') {
1380 *q++ = '\0';
1381 special = q;
1382 } else
1383 special = NULL;
1384 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1385 int temp = pass0;
1386 pass0 = 1; /* fake pass 1 in labels.c */
1387 declare_as_global(value, special);
1388 define_label(value, seg_alloc(), 0L, NULL,
1389 false, true);
1390 pass0 = temp;
1392 } /* else pass0 == 1 */
1393 break;
1394 case D_BITS: /* [BITS bits] */
1395 globalbits = sb = get_bits(value);
1396 break;
1397 case D_GLOBAL: /* [GLOBAL symbol:special] */
1398 if (*value == '$')
1399 value++; /* skip initial $ if present */
1400 if (pass0 == 2) { /* pass 2 */
1401 q = value;
1402 while (*q && *q != ':')
1403 q++;
1404 if (*q == ':') {
1405 *q++ = '\0';
1406 ofmt->symdef(value, 0L, 0L, 3, q);
1408 } else if (pass2 == 1) { /* pass == 1 */
1409 q = value;
1410 validid = true;
1411 if (!isidstart(*q))
1412 validid = false;
1413 while (*q && *q != ':') {
1414 if (!isidchar(*q))
1415 validid = false;
1416 q++;
1418 if (!validid) {
1419 nasm_error(ERR_NONFATAL,
1420 "identifier expected after GLOBAL");
1421 break;
1423 if (*q == ':') {
1424 *q++ = '\0';
1425 special = q;
1426 } else
1427 special = NULL;
1428 declare_as_global(value, special);
1429 } /* pass == 1 */
1430 break;
1431 case D_COMMON: /* [COMMON symbol size:special] */
1433 int64_t size;
1435 if (*value == '$')
1436 value++; /* skip initial $ if present */
1437 p = value;
1438 validid = true;
1439 if (!isidstart(*p))
1440 validid = false;
1441 while (*p && !nasm_isspace(*p)) {
1442 if (!isidchar(*p))
1443 validid = false;
1444 p++;
1446 if (!validid) {
1447 nasm_error(ERR_NONFATAL,
1448 "identifier expected after COMMON");
1449 break;
1451 if (*p) {
1452 p = nasm_zap_spaces_fwd(p);
1453 q = p;
1454 while (*q && *q != ':')
1455 q++;
1456 if (*q == ':') {
1457 *q++ = '\0';
1458 special = q;
1459 } else {
1460 special = NULL;
1462 size = readnum(p, &rn_error);
1463 if (rn_error) {
1464 nasm_error(ERR_NONFATAL,
1465 "invalid size specified"
1466 " in COMMON declaration");
1467 break;
1469 } else {
1470 nasm_error(ERR_NONFATAL,
1471 "no size specified in"
1472 " COMMON declaration");
1473 break;
1476 if (pass0 < 2) {
1477 define_common(value, seg_alloc(), size, special);
1478 } else if (pass0 == 2) {
1479 if (special)
1480 ofmt->symdef(value, 0L, 0L, 3, special);
1482 break;
1484 case D_ABSOLUTE: /* [ABSOLUTE address] */
1485 stdscan_reset();
1486 stdscan_set(value);
1487 tokval.t_type = TOKEN_INVALID;
1488 e = evaluate(stdscan, NULL, &tokval, NULL, pass2, NULL);
1489 if (e) {
1490 if (!is_reloc(e))
1491 nasm_error(pass0 ==
1492 1 ? ERR_NONFATAL : ERR_PANIC,
1493 "cannot use non-relocatable expression as "
1494 "ABSOLUTE address");
1495 else {
1496 abs_seg = reloc_seg(e);
1497 abs_offset = reloc_value(e);
1499 } else if (passn == 1)
1500 abs_offset = 0x100; /* don't go near zero in case of / */
1501 else
1502 nasm_panic(0, "invalid ABSOLUTE address "
1503 "in pass two");
1504 in_abs_seg = true;
1505 location.segment = NO_SEG;
1506 break;
1507 case D_DEBUG: /* [DEBUG] */
1509 bool badid, overlong;
1511 p = value;
1512 q = debugid;
1513 badid = overlong = false;
1514 if (!isidstart(*p)) {
1515 badid = true;
1516 } else {
1517 while (*p && !nasm_isspace(*p)) {
1518 if (q >= debugid + sizeof debugid - 1) {
1519 overlong = true;
1520 break;
1522 if (!isidchar(*p))
1523 badid = true;
1524 *q++ = *p++;
1526 *q = 0;
1528 if (badid) {
1529 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1530 "identifier expected after DEBUG");
1531 break;
1533 if (overlong) {
1534 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1535 "DEBUG identifier too long");
1536 break;
1538 p = nasm_skip_spaces(p);
1539 if (pass0 == 2)
1540 dfmt->debug_directive(debugid, p);
1541 break;
1543 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1544 value = nasm_skip_spaces(value);
1545 switch(*value) {
1546 case '-': validid = 0; value++; break;
1547 case '+': validid = 1; value++; break;
1548 case '*': validid = 2; value++; break;
1549 default: validid = 1; break;
1552 for (i = 1; i <= ERR_WARN_MAX; i++)
1553 if (!nasm_stricmp(value, warnings[i].name))
1554 break;
1555 if (i <= ERR_WARN_MAX) {
1556 switch(validid) {
1557 case 0:
1558 warning_on[i] = false;
1559 break;
1560 case 1:
1561 warning_on[i] = true;
1562 break;
1563 case 2:
1564 warning_on[i] = warning_on_global[i];
1565 break;
1568 break;
1569 case D_CPU: /* [CPU] */
1570 cpu = get_cpu(value);
1571 break;
1572 case D_LIST: /* [LIST {+|-}] */
1573 value = nasm_skip_spaces(value);
1574 if (*value == '+') {
1575 user_nolist = 0;
1576 } else {
1577 if (*value == '-') {
1578 user_nolist = 1;
1579 } else {
1580 err = 1;
1583 break;
1584 case D_DEFAULT: /* [DEFAULT] */
1585 stdscan_reset();
1586 stdscan_set(value);
1587 tokval.t_type = TOKEN_INVALID;
1588 if (stdscan(NULL, &tokval) != TOKEN_INVALID) {
1589 switch ((int)tokval.t_integer) {
1590 case S_REL:
1591 globalrel = 1;
1592 break;
1593 case S_ABS:
1594 globalrel = 0;
1595 break;
1596 case P_BND:
1597 globalbnd = 1;
1598 break;
1599 case P_NOBND:
1600 globalbnd = 0;
1601 break;
1602 default:
1603 err = 1;
1604 break;
1606 } else {
1607 err = 1;
1609 break;
1610 case D_FLOAT:
1611 if (float_option(value)) {
1612 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1613 "unknown 'float' directive: %s",
1614 value);
1616 break;
1617 case D_PRAGMA:
1618 /* Currently the pragma directive doesn't do anything */
1619 break;
1620 default:
1621 if (ofmt->directive(d, value, pass2))
1622 break;
1623 /* else fall through */
1624 case D_unknown:
1625 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1626 "unrecognised directive [%s]",
1627 directive);
1628 break;
1630 if (err) {
1631 nasm_error(ERR_NONFATAL,
1632 "invalid parameter to [%s] directive",
1633 directive);
1635 } else { /* it isn't a directive */
1636 parse_line(pass1, line, &output_ins, def_label);
1638 if (optimizing > 0) {
1639 if (forwref != NULL && globallineno == forwref->lineno) {
1640 output_ins.forw_ref = true;
1641 do {
1642 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1643 forwref = saa_rstruct(forwrefs);
1644 } while (forwref != NULL
1645 && forwref->lineno == globallineno);
1646 } else
1647 output_ins.forw_ref = false;
1649 if (output_ins.forw_ref) {
1650 if (passn == 1) {
1651 for (i = 0; i < output_ins.operands; i++) {
1652 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {
1653 struct forwrefinfo *fwinf = (struct forwrefinfo *)saa_wstruct(forwrefs);
1654 fwinf->lineno = globallineno;
1655 fwinf->operand = i;
1662 /* forw_ref */
1663 if (output_ins.opcode == I_EQU) {
1664 if (pass1 == 1) {
1666 * Special `..' EQUs get processed in pass two,
1667 * except `..@' macro-processor EQUs which are done
1668 * in the normal place.
1670 if (!output_ins.label)
1671 nasm_error(ERR_NONFATAL,
1672 "EQU not preceded by label");
1674 else if (output_ins.label[0] != '.' ||
1675 output_ins.label[1] != '.' ||
1676 output_ins.label[2] == '@') {
1677 if (output_ins.operands == 1 &&
1678 (output_ins.oprs[0].type & IMMEDIATE) &&
1679 output_ins.oprs[0].wrt == NO_SEG) {
1680 bool isext = !!(output_ins.oprs[0].opflags & OPFLAG_EXTERN);
1681 def_label(output_ins.label,
1682 output_ins.oprs[0].segment,
1683 output_ins.oprs[0].offset, NULL,
1684 false, isext);
1685 } else if (output_ins.operands == 2
1686 && (output_ins.oprs[0].type & IMMEDIATE)
1687 && (output_ins.oprs[0].type & COLON)
1688 && output_ins.oprs[0].segment == NO_SEG
1689 && output_ins.oprs[0].wrt == NO_SEG
1690 && (output_ins.oprs[1].type & IMMEDIATE)
1691 && output_ins.oprs[1].segment == NO_SEG
1692 && output_ins.oprs[1].wrt == NO_SEG) {
1693 def_label(output_ins.label,
1694 output_ins.oprs[0].offset | SEG_ABS,
1695 output_ins.oprs[1].offset,
1696 NULL, false, false);
1697 } else
1698 nasm_error(ERR_NONFATAL,
1699 "bad syntax for EQU");
1701 } else {
1703 * Special `..' EQUs get processed here, except
1704 * `..@' macro processor EQUs which are done above.
1706 if (output_ins.label[0] == '.' &&
1707 output_ins.label[1] == '.' &&
1708 output_ins.label[2] != '@') {
1709 if (output_ins.operands == 1 &&
1710 (output_ins.oprs[0].type & IMMEDIATE)) {
1711 define_label(output_ins.label,
1712 output_ins.oprs[0].segment,
1713 output_ins.oprs[0].offset,
1714 NULL, false, false);
1715 } else if (output_ins.operands == 2
1716 && (output_ins.oprs[0].type & IMMEDIATE)
1717 && (output_ins.oprs[0].type & COLON)
1718 && output_ins.oprs[0].segment == NO_SEG
1719 && (output_ins.oprs[1].type & IMMEDIATE)
1720 && output_ins.oprs[1].segment == NO_SEG) {
1721 define_label(output_ins.label,
1722 output_ins.oprs[0].offset | SEG_ABS,
1723 output_ins.oprs[1].offset,
1724 NULL, false, false);
1725 } else
1726 nasm_error(ERR_NONFATAL,
1727 "bad syntax for EQU");
1730 } else { /* instruction isn't an EQU */
1732 if (pass1 == 1) {
1734 int64_t l = insn_size(location.segment, offs, sb, cpu,
1735 &output_ins);
1736 l *= output_ins.times;
1738 /* if (using_debug_info) && output_ins.opcode != -1) */
1739 if (using_debug_info)
1740 { /* fbk 03/25/01 */
1741 /* this is done here so we can do debug type info */
1742 int32_t typeinfo =
1743 TYS_ELEMENTS(output_ins.operands);
1744 switch (output_ins.opcode) {
1745 case I_RESB:
1746 typeinfo =
1747 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1748 break;
1749 case I_RESW:
1750 typeinfo =
1751 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1752 break;
1753 case I_RESD:
1754 typeinfo =
1755 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1756 break;
1757 case I_RESQ:
1758 typeinfo =
1759 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1760 break;
1761 case I_REST:
1762 typeinfo =
1763 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1764 break;
1765 case I_RESO:
1766 typeinfo =
1767 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;
1768 break;
1769 case I_RESY:
1770 typeinfo =
1771 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;
1772 break;
1773 case I_DB:
1774 typeinfo |= TY_BYTE;
1775 break;
1776 case I_DW:
1777 typeinfo |= TY_WORD;
1778 break;
1779 case I_DD:
1780 if (output_ins.eops_float)
1781 typeinfo |= TY_FLOAT;
1782 else
1783 typeinfo |= TY_DWORD;
1784 break;
1785 case I_DQ:
1786 typeinfo |= TY_QWORD;
1787 break;
1788 case I_DT:
1789 typeinfo |= TY_TBYTE;
1790 break;
1791 case I_DO:
1792 typeinfo |= TY_OWORD;
1793 break;
1794 case I_DY:
1795 typeinfo |= TY_YWORD;
1796 break;
1797 default:
1798 typeinfo = TY_LABEL;
1802 dfmt->debug_typevalue(typeinfo);
1804 if (l != -1) {
1805 offs += l;
1806 set_curr_offs(offs);
1809 * else l == -1 => invalid instruction, which will be
1810 * flagged as an error on pass 2
1813 } else {
1814 offs += assemble(location.segment, offs, sb, cpu,
1815 &output_ins);
1816 set_curr_offs(offs);
1819 } /* not an EQU */
1820 cleanup_insn(&output_ins);
1822 nasm_free(line);
1823 location.offset = offs = get_curr_offs();
1824 } /* end while (line = preproc->getline... */
1826 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1827 nasm_error(ERR_NONFATAL,
1828 "phase error detected at end of assembly.");
1830 if (pass1 == 1)
1831 preproc->cleanup(1);
1833 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1834 pass0++;
1835 } else if (global_offset_changed &&
1836 global_offset_changed < prev_offset_changed) {
1837 prev_offset_changed = global_offset_changed;
1838 stall_count = 0;
1839 } else {
1840 stall_count++;
1843 if (terminate_after_phase)
1844 break;
1846 if ((stall_count > 997) || (passn >= pass_max)) {
1847 /* We get here if the labels don't converge
1848 * Example: FOO equ FOO + 1
1850 nasm_error(ERR_NONFATAL,
1851 "Can't find valid values for all labels "
1852 "after %d passes, giving up.", passn);
1853 nasm_error(ERR_NONFATAL,
1854 "Possible causes: recursive EQUs, macro abuse.");
1855 break;
1859 preproc->cleanup(0);
1860 lfmt->cleanup();
1861 if (!terminate_after_phase && opt_verbose_info) {
1862 /* -On and -Ov switches */
1863 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1867 static enum directives getkw(char **directive, char **value)
1869 char *p, *q, *buf;
1871 buf = nasm_skip_spaces(*directive);
1873 /* it should be enclosed in [ ] */
1874 if (*buf != '[')
1875 return D_none;
1876 q = strchr(buf, ']');
1877 if (!q)
1878 return D_none;
1880 /* stip off the comments */
1881 p = strchr(buf, ';');
1882 if (p) {
1883 if (p < q) /* ouch! somwhere inside */
1884 return D_none;
1885 *p = '\0';
1888 /* no brace, no trailing spaces */
1889 *q = '\0';
1890 nasm_zap_spaces_rev(--q);
1892 /* directive */
1893 p = nasm_skip_spaces(++buf);
1894 q = nasm_skip_word(p);
1895 if (!q)
1896 return D_none; /* sigh... no value there */
1897 *q = '\0';
1898 *directive = p;
1900 /* and value finally */
1901 p = nasm_skip_spaces(++q);
1902 *value = p;
1904 return find_directive(*directive);
1908 * gnu style error reporting
1909 * This function prints an error message to error_file in the
1910 * style used by GNU. An example would be:
1911 * file.asm:50: error: blah blah blah
1912 * where file.asm is the name of the file, 50 is the line number on
1913 * which the error occurs (or is detected) and "error:" is one of
1914 * the possible optional diagnostics -- it can be "error" or "warning"
1915 * or something else. Finally the line terminates with the actual
1916 * error message.
1918 * @param severity the severity of the warning or error
1919 * @param fmt the printf style format string
1921 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1923 const char *currentfile = NULL;
1924 int32_t lineno = 0;
1926 if (is_suppressed_warning(severity))
1927 return;
1929 if (!(severity & ERR_NOFILE))
1930 src_get(&lineno, &currentfile);
1932 if (!skip_this_pass(severity)) {
1933 if (currentfile) {
1934 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1935 } else {
1936 fputs("nasm: ", error_file);
1940 nasm_verror_common(severity, fmt, ap);
1944 * MS style error reporting
1945 * This function prints an error message to error_file in the
1946 * style used by Visual C and some other Microsoft tools. An example
1947 * would be:
1948 * file.asm(50) : error: blah blah blah
1949 * where file.asm is the name of the file, 50 is the line number on
1950 * which the error occurs (or is detected) and "error:" is one of
1951 * the possible optional diagnostics -- it can be "error" or "warning"
1952 * or something else. Finally the line terminates with the actual
1953 * error message.
1955 * @param severity the severity of the warning or error
1956 * @param fmt the printf style format string
1958 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1960 const char *currentfile = NULL;
1961 int32_t lineno = 0;
1963 if (is_suppressed_warning(severity))
1964 return;
1966 if (!(severity & ERR_NOFILE))
1967 src_get(&lineno, &currentfile);
1969 if (!skip_this_pass(severity)) {
1970 if (currentfile) {
1971 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1972 } else {
1973 fputs("nasm: ", error_file);
1977 nasm_verror_common(severity, fmt, ap);
1981 * check for supressed warning
1982 * checks for suppressed warning or pass one only warning and we're
1983 * not in pass 1
1985 * @param severity the severity of the warning or error
1986 * @return true if we should abort error/warning printing
1988 static bool is_suppressed_warning(int severity)
1990 /* Not a warning at all */
1991 if ((severity & ERR_MASK) != ERR_WARNING)
1992 return false;
1994 /* Might be a warning but suppresed explicitly */
1995 if (severity & ERR_WARN_MASK)
1996 return !warning_on[WARN_IDX(severity)];
1997 else
1998 return false;
2001 static bool skip_this_pass(int severity)
2003 /* See if it's a pass-specific warning which should be skipped. */
2005 if ((severity & ERR_MASK) > ERR_WARNING)
2006 return false;
2009 * passn is 1 on the very first pass only.
2010 * pass0 is 2 on the code-generation (final) pass only.
2011 * These are the passes we care about in this case.
2013 return (((severity & ERR_PASS1) && passn != 1) ||
2014 ((severity & ERR_PASS2) && pass0 != 2));
2018 * common error reporting
2019 * This is the common back end of the error reporting schemes currently
2020 * implemented. It prints the nature of the warning and then the
2021 * specific error message to error_file and may or may not return. It
2022 * doesn't return if the error severity is a "panic" or "debug" type.
2024 * @param severity the severity of the warning or error
2025 * @param fmt the printf style format string
2027 static void nasm_verror_common(int severity, const char *fmt, va_list args)
2029 char msg[1024];
2030 const char *pfx;
2032 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
2033 case ERR_WARNING:
2034 pfx = "warning: ";
2035 break;
2036 case ERR_NONFATAL:
2037 pfx = "error: ";
2038 break;
2039 case ERR_FATAL:
2040 pfx = "fatal: ";
2041 break;
2042 case ERR_PANIC:
2043 pfx = "panic: ";
2044 break;
2045 case ERR_DEBUG:
2046 pfx = "debug: ";
2047 break;
2048 default:
2049 pfx = "";
2050 break;
2053 vsnprintf(msg, sizeof msg - 64, fmt, args);
2054 if ((severity & (ERR_WARN_MASK|ERR_PP_LISTMACRO)) == ERR_WARN_MASK) {
2055 char *p = strchr(msg, '\0');
2056 snprintf(p, 64, " [-w+%s]", warnings[WARN_IDX(severity)].name);
2059 if (!skip_this_pass(severity))
2060 fprintf(error_file, "%s%s\n", pfx, msg);
2062 /* Are we recursing from error_list_macros? */
2063 if (severity & ERR_PP_LISTMACRO)
2064 return;
2067 * Don't suppress this with skip_this_pass(), or we don't get
2068 * pass1 or preprocessor warnings in the list file
2070 lfmt->error(severity, pfx, msg);
2072 if (severity & ERR_USAGE)
2073 want_usage = true;
2075 preproc->error_list_macros(severity);
2077 switch (severity & ERR_MASK) {
2078 case ERR_DEBUG:
2079 /* no further action, by definition */
2080 break;
2081 case ERR_WARNING:
2082 /* Treat warnings as errors */
2083 if (warning_on[WARN_IDX(ERR_WARN_TERM)])
2084 terminate_after_phase = true;
2085 break;
2086 case ERR_NONFATAL:
2087 terminate_after_phase = true;
2088 break;
2089 case ERR_FATAL:
2090 if (ofile) {
2091 fclose(ofile);
2092 remove(outname);
2093 ofile = NULL;
2095 if (want_usage)
2096 usage();
2097 exit(1); /* instantly die */
2098 break; /* placate silly compilers */
2099 case ERR_PANIC:
2100 fflush(NULL);
2101 /* abort(); */ /* halt, catch fire, and dump core */
2102 if (ofile) {
2103 fclose(ofile);
2104 remove(outname);
2105 ofile = NULL;
2107 exit(3);
2108 break;
2112 static void usage(void)
2114 fputs("type `nasm -h' for help\n", error_file);
2117 static iflag_t get_cpu(char *value)
2119 iflag_t r;
2121 iflag_clear_all(&r);
2123 if (!strcmp(value, "8086"))
2124 iflag_set(&r, IF_8086);
2125 else if (!strcmp(value, "186"))
2126 iflag_set(&r, IF_186);
2127 else if (!strcmp(value, "286"))
2128 iflag_set(&r, IF_286);
2129 else if (!strcmp(value, "386"))
2130 iflag_set(&r, IF_386);
2131 else if (!strcmp(value, "486"))
2132 iflag_set(&r, IF_486);
2133 else if (!strcmp(value, "586") ||
2134 !nasm_stricmp(value, "pentium"))
2135 iflag_set(&r, IF_PENT);
2136 else if (!strcmp(value, "686") ||
2137 !nasm_stricmp(value, "ppro") ||
2138 !nasm_stricmp(value, "pentiumpro") ||
2139 !nasm_stricmp(value, "p2"))
2140 iflag_set(&r, IF_P6);
2141 else if (!nasm_stricmp(value, "p3") ||
2142 !nasm_stricmp(value, "katmai"))
2143 iflag_set(&r, IF_KATMAI);
2144 else if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2145 !nasm_stricmp(value, "willamette"))
2146 iflag_set(&r, IF_WILLAMETTE);
2147 else if (!nasm_stricmp(value, "prescott"))
2148 iflag_set(&r, IF_PRESCOTT);
2149 else if (!nasm_stricmp(value, "x64") ||
2150 !nasm_stricmp(value, "x86-64"))
2151 iflag_set(&r, IF_X86_64);
2152 else if (!nasm_stricmp(value, "ia64") ||
2153 !nasm_stricmp(value, "ia-64") ||
2154 !nasm_stricmp(value, "itanium")||
2155 !nasm_stricmp(value, "itanic") ||
2156 !nasm_stricmp(value, "merced"))
2157 iflag_set(&r, IF_IA64);
2158 else {
2159 iflag_set(&r, IF_PLEVEL);
2160 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2161 "unknown 'cpu' type");
2163 return r;
2166 static int get_bits(char *value)
2168 int i;
2170 if ((i = atoi(value)) == 16)
2171 return i; /* set for a 16-bit segment */
2172 else if (i == 32) {
2173 if (iflag_ffs(&cpu) < IF_386) {
2174 nasm_error(ERR_NONFATAL,
2175 "cannot specify 32-bit segment on processor below a 386");
2176 i = 16;
2178 } else if (i == 64) {
2179 if (iflag_ffs(&cpu) < IF_X86_64) {
2180 nasm_error(ERR_NONFATAL,
2181 "cannot specify 64-bit segment on processor below an x86-64");
2182 i = 16;
2184 } else {
2185 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2186 "`%s' is not a valid segment size; must be 16, 32 or 64",
2187 value);
2188 i = 16;
2190 return i;