outmacho: Fix relative relocations for 32-bit Mach-O (fix typo)
[nasm.git] / nasm.c
blob4df3c373c168b9fbb29a61f9394d194c781183a7
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 <inttypes.h>
46 #include <limits.h>
47 #include <time.h>
49 #include "nasm.h"
50 #include "nasmlib.h"
51 #include "saa.h"
52 #include "raa.h"
53 #include "float.h"
54 #include "stdscan.h"
55 #include "insns.h"
56 #include "preproc.h"
57 #include "parser.h"
58 #include "eval.h"
59 #include "assemble.h"
60 #include "labels.h"
61 #include "output/outform.h"
62 #include "listing.h"
63 #include "iflag.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 **);
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 struct ofmt *ofmt = &OF_DEFAULT;
105 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 sb, 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 static 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 = fopen(depend_file, "w");
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 /* Define some macros dependent on the runtime, but not
352 on the command line. */
353 define_macros_early();
355 parse_cmdline(argc, argv);
357 if (terminate_after_phase) {
358 if (want_usage)
359 usage();
360 return 1;
363 if (!using_debug_info) {
364 /* No debug info, redirect to the null backend (empty stubs) */
365 dfmt = &null_debug_form;
366 } else if (!debug_format) {
367 /* Default debug format for this backend */
368 dfmt = ofmt->default_dfmt;
369 } else {
370 dfmt = dfmt_find(ofmt, debug_format);
371 if (!dfmt) {
372 nasm_fatal(ERR_NOFILE | ERR_USAGE,
373 "unrecognized debug format `%s' for"
374 " output format `%s'",
375 debug_format, ofmt->shortname);
379 if (ofmt->stdmac)
380 preproc->extra_stdmac(ofmt->stdmac);
381 parser_global_info(&location);
382 eval_global_info(ofmt, lookup_label, &location);
384 /* define some macros dependent of command-line */
385 define_macros_late();
387 depend_ptr = (depend_file || (operating_mode & OP_DEPEND)) ? &depend_list : NULL;
388 if (!depend_target)
389 depend_target = quote_for_make(outname);
391 if (operating_mode & OP_DEPEND) {
392 char *line;
394 if (depend_missing_ok)
395 preproc->include_path(NULL); /* "assume generated" */
397 preproc->reset(inname, 0, depend_ptr);
398 if (outname[0] == '\0')
399 ofmt->filename(inname, outname);
400 ofile = NULL;
401 while ((line = preproc->getline()))
402 nasm_free(line);
403 preproc->cleanup(0);
404 } else if (operating_mode & OP_PREPROCESS) {
405 char *line;
406 const char *file_name = NULL;
407 int32_t prior_linnum = 0;
408 int lineinc = 0;
410 if (*outname) {
411 ofile = fopen(outname, "w");
412 if (!ofile)
413 nasm_fatal(ERR_NOFILE,
414 "unable to open output file `%s'",
415 outname);
416 } else
417 ofile = NULL;
419 location.known = false;
421 /* pass = 1; */
422 preproc->reset(inname, 3, depend_ptr);
423 memcpy(warning_on, warning_on_global,
424 (ERR_WARN_MAX+1) * sizeof(bool));
426 while ((line = preproc->getline())) {
428 * We generate %line directives if needed for later programs
430 int32_t linnum = prior_linnum += lineinc;
431 int altline = src_get(&linnum, &file_name);
432 if (altline) {
433 if (altline == 1 && lineinc == 1)
434 nasm_fputs("", ofile);
435 else {
436 lineinc = (altline != -1 || lineinc != 1);
437 fprintf(ofile ? ofile : stdout,
438 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
439 file_name);
441 prior_linnum = linnum;
443 nasm_fputs(line, ofile);
444 nasm_free(line);
446 preproc->cleanup(0);
447 if (ofile)
448 fclose(ofile);
449 if (ofile && terminate_after_phase)
450 remove(outname);
451 ofile = NULL;
454 if (operating_mode & OP_NORMAL) {
456 * We must call ofmt->filename _anyway_, even if the user
457 * has specified their own output file, because some
458 * formats (eg OBJ and COFF) use ofmt->filename to find out
459 * the name of the input file and then put that inside the
460 * file.
462 ofmt->filename(inname, outname);
464 ofile = fopen(outname, (ofmt->flags & OFMT_TEXT) ? "w" : "wb");
465 if (!ofile)
466 nasm_fatal(ERR_NOFILE,
467 "unable to open output file `%s'", outname);
470 * We must call init_labels() before ofmt->init() since
471 * some object formats will want to define labels in their
472 * init routines. (eg OS/2 defines the FLAT group)
474 init_labels();
476 ofmt->init();
477 dfmt->init();
479 assemble_file(inname, depend_ptr);
481 if (!terminate_after_phase) {
482 ofmt->cleanup();
483 cleanup_labels();
484 fflush(ofile);
485 if (ferror(ofile)) {
486 nasm_error(ERR_NONFATAL|ERR_NOFILE,
487 "write error on output file `%s'", outname);
488 terminate_after_phase = true;
492 if (ofile) {
493 fclose(ofile);
494 if (terminate_after_phase)
495 remove(outname);
496 ofile = NULL;
500 if (depend_list && !terminate_after_phase)
501 emit_dependencies(depend_list);
503 if (want_usage)
504 usage();
506 raa_free(offsets);
507 saa_free(forwrefs);
508 eval_cleanup();
509 stdscan_cleanup();
510 src_free();
512 return terminate_after_phase;
516 * Get a parameter for a command line option.
517 * First arg must be in the form of e.g. -f...
519 static char *get_param(char *p, char *q, bool *advance)
521 *advance = false;
522 if (p[2]) /* the parameter's in the option */
523 return nasm_skip_spaces(p + 2);
524 if (q && q[0]) {
525 *advance = true;
526 return q;
528 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
529 "option `-%c' requires an argument", p[1]);
530 return NULL;
534 * Copy a filename
536 static void copy_filename(char *dst, const char *src)
538 size_t len = strlen(src);
540 if (len >= (size_t)FILENAME_MAX) {
541 nasm_fatal(ERR_NOFILE, "file name too long");
542 return;
544 strncpy(dst, src, FILENAME_MAX);
548 * Convert a string to Make-safe form
550 static char *quote_for_make(const char *str)
552 const char *p;
553 char *os, *q;
555 size_t n = 1; /* Terminating zero */
556 size_t nbs = 0;
558 if (!str)
559 return NULL;
561 for (p = str; *p; p++) {
562 switch (*p) {
563 case ' ':
564 case '\t':
565 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
566 n += nbs + 2;
567 nbs = 0;
568 break;
569 case '$':
570 case '#':
571 nbs = 0;
572 n += 2;
573 break;
574 case '\\':
575 nbs++;
576 n++;
577 break;
578 default:
579 nbs = 0;
580 n++;
581 break;
585 /* Convert N backslashes at the end of filename to 2N backslashes */
586 if (nbs)
587 n += nbs;
589 os = q = nasm_malloc(n);
591 nbs = 0;
592 for (p = str; *p; p++) {
593 switch (*p) {
594 case ' ':
595 case '\t':
596 while (nbs--)
597 *q++ = '\\';
598 *q++ = '\\';
599 *q++ = *p;
600 break;
601 case '$':
602 *q++ = *p;
603 *q++ = *p;
604 nbs = 0;
605 break;
606 case '#':
607 *q++ = '\\';
608 *q++ = *p;
609 nbs = 0;
610 break;
611 case '\\':
612 *q++ = *p;
613 nbs++;
614 break;
615 default:
616 *q++ = *p;
617 nbs = 0;
618 break;
621 while (nbs--)
622 *q++ = '\\';
624 *q = '\0';
626 return os;
629 struct textargs {
630 const char *label;
631 int value;
634 enum text_options {
635 OPT_PREFIX,
636 OPT_POSTFIX
638 struct textargs textopts[] = {
639 {"prefix", OPT_PREFIX},
640 {"postfix", OPT_POSTFIX},
641 {NULL, 0}
644 static void show_version(void)
646 printf("NASM version %s compiled on %s%s\n",
647 nasm_version, nasm_date, nasm_compile_options);
648 exit(0);
651 static bool stopoptions = false;
652 static bool process_arg(char *p, char *q)
654 char *param;
655 int i;
656 bool advance = false;
657 bool do_warn;
659 if (!p || !p[0])
660 return false;
662 if (p[0] == '-' && !stopoptions) {
663 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
664 /* These parameters take values */
665 if (!(param = get_param(p, q, &advance)))
666 return advance;
669 switch (p[1]) {
670 case 's':
671 error_file = stdout;
672 break;
674 case 'o': /* output file */
675 copy_filename(outname, param);
676 break;
678 case 'f': /* output format */
679 ofmt = ofmt_find(param, &ofmt_alias);
680 if (!ofmt) {
681 nasm_fatal(ERR_NOFILE | ERR_USAGE,
682 "unrecognised output format `%s' - "
683 "use -hf for a list", param);
685 break;
687 case 'O': /* Optimization level */
689 int opt;
691 if (!*param) {
692 /* Naked -O == -Ox */
693 optimizing = MAX_OPTIMIZE;
694 } else {
695 while (*param) {
696 switch (*param) {
697 case '0': case '1': case '2': case '3': case '4':
698 case '5': case '6': case '7': case '8': case '9':
699 opt = strtoul(param, &param, 10);
701 /* -O0 -> optimizing == -1, 0.98 behaviour */
702 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
703 if (opt < 2)
704 optimizing = opt - 1;
705 else
706 optimizing = opt;
707 break;
709 case 'v':
710 case '+':
711 param++;
712 opt_verbose_info = true;
713 break;
715 case 'x':
716 param++;
717 optimizing = MAX_OPTIMIZE;
718 break;
720 default:
721 nasm_fatal(0,
722 "unknown optimization option -O%c\n",
723 *param);
724 break;
727 if (optimizing > MAX_OPTIMIZE)
728 optimizing = MAX_OPTIMIZE;
730 break;
733 case 'p': /* pre-include */
734 case 'P':
735 preproc->pre_include(param);
736 break;
738 case 'd': /* pre-define */
739 case 'D':
740 preproc->pre_define(param);
741 break;
743 case 'u': /* un-define */
744 case 'U':
745 preproc->pre_undefine(param);
746 break;
748 case 'i': /* include search path */
749 case 'I':
750 preproc->include_path(param);
751 break;
753 case 'l': /* listing file */
754 copy_filename(listname, param);
755 break;
757 case 'Z': /* error messages file */
758 copy_filename(errname, param);
759 break;
761 case 'F': /* specify debug format */
762 using_debug_info = true;
763 debug_format = param;
764 break;
766 case 'X': /* specify error reporting format */
767 if (nasm_stricmp("vc", param) == 0)
768 nasm_set_verror(nasm_verror_vc);
769 else if (nasm_stricmp("gnu", param) == 0)
770 nasm_set_verror(nasm_verror_gnu);
771 else
772 nasm_fatal(ERR_NOFILE | ERR_USAGE,
773 "unrecognized error reporting format `%s'",
774 param);
775 break;
777 case 'g':
778 using_debug_info = true;
779 if (p[2])
780 debug_format = nasm_skip_spaces(p + 2);
781 break;
783 case 'h':
784 printf
785 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
786 "[-l listfile]\n"
787 " [options...] [--] filename\n"
788 " or nasm -v (or --v) for version info\n\n"
789 " -t assemble in SciTech TASM compatible mode\n");
790 printf
791 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
792 " -a don't preprocess (assemble only)\n"
793 " -M generate Makefile dependencies on stdout\n"
794 " -MG d:o, missing files assumed generated\n"
795 " -MF <file> set Makefile dependency file\n"
796 " -MD <file> assemble and generate dependencies\n"
797 " -MT <file> dependency target name\n"
798 " -MQ <file> dependency target name (quoted)\n"
799 " -MP emit phony target\n\n"
800 " -Z<file> redirect error messages to file\n"
801 " -s redirect error messages to stdout\n\n"
802 " -g generate debugging information\n\n"
803 " -F format select a debugging format\n\n"
804 " -gformat same as -g -F format\n\n"
805 " -o outfile write output to an outfile\n\n"
806 " -f format select an output format\n\n"
807 " -l listfile write listing to a listfile\n\n"
808 " -I<path> adds a pathname to the include file path\n");
809 printf
810 (" -O<digit> optimize branch offsets\n"
811 " -O0: No optimization\n"
812 " -O1: Minimal optimization\n"
813 " -Ox: Multipass optimization (default)\n\n"
814 " -P<file> pre-includes a file\n"
815 " -D<macro>[=<value>] pre-defines a macro\n"
816 " -U<macro> undefines a macro\n"
817 " -X<format> specifies error reporting format (gnu or vc)\n"
818 " -w+foo enables warning foo (equiv. -Wfoo)\n"
819 " -w-foo disable warning foo (equiv. -Wno-foo)\n\n"
820 " -h show invocation summary and exit\n\n"
821 "--prefix,--postfix\n"
822 " this options prepend or append the given argument to all\n"
823 " extern and global variables\n"
824 "Warnings:\n");
825 for (i = 0; i <= ERR_WARN_MAX; i++)
826 printf(" %-23s %s (default %s)\n",
827 warnings[i].name, warnings[i].help,
828 warnings[i].enabled ? "on" : "off");
829 printf
830 ("\nresponse files should contain command line parameters"
831 ", one per line.\n");
832 if (p[2] == 'f') {
833 printf("\nvalid output formats for -f are"
834 " (`*' denotes default):\n");
835 ofmt_list(ofmt, stdout);
836 } else {
837 printf("\nFor a list of valid output formats, use -hf.\n");
838 printf("For a list of debug formats, use -f <form> -y.\n");
840 exit(0); /* never need usage message here */
841 break;
843 case 'y':
844 printf("\nvalid debug formats for '%s' output format are"
845 " ('*' denotes default):\n", ofmt->shortname);
846 dfmt_list(ofmt, stdout);
847 exit(0);
848 break;
850 case 't':
851 tasm_compatible_mode = true;
852 break;
854 case 'v':
855 show_version();
856 break;
858 case 'e': /* preprocess only */
859 case 'E':
860 operating_mode = OP_PREPROCESS;
861 break;
863 case 'a': /* assemble only - don't preprocess */
864 preproc = &preproc_nop;
865 break;
867 case 'W':
868 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
869 do_warn = false;
870 param += 3;
871 } else {
872 do_warn = true;
874 goto set_warning;
876 case 'w':
877 if (param[0] != '+' && param[0] != '-') {
878 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
879 "invalid option to `-w'");
880 break;
882 do_warn = (param[0] == '+');
883 param++;
885 set_warning:
886 for (i = 0; i <= ERR_WARN_MAX; i++) {
887 if (!nasm_stricmp(param, warnings[i].name))
888 break;
890 if (i <= ERR_WARN_MAX) {
891 warning_on_global[i] = do_warn;
892 } else if (!nasm_stricmp(param, "all")) {
893 for (i = 1; i <= ERR_WARN_MAX; i++)
894 warning_on_global[i] = do_warn;
895 } else if (!nasm_stricmp(param, "none")) {
896 for (i = 1; i <= ERR_WARN_MAX; i++)
897 warning_on_global[i] = !do_warn;
898 } else {
899 /* Ignore invalid warning names; forward compatibility */
901 break;
903 case 'M':
904 switch (p[2]) {
905 case 0:
906 operating_mode = OP_DEPEND;
907 break;
908 case 'G':
909 operating_mode = OP_DEPEND;
910 depend_missing_ok = true;
911 break;
912 case 'P':
913 depend_emit_phony = true;
914 break;
915 case 'D':
916 operating_mode = OP_NORMAL;
917 depend_file = q;
918 advance = true;
919 break;
920 case 'F':
921 depend_file = q;
922 advance = true;
923 break;
924 case 'T':
925 depend_target = q;
926 advance = true;
927 break;
928 case 'Q':
929 depend_target = quote_for_make(q);
930 advance = true;
931 break;
932 default:
933 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
934 "unknown dependency option `-M%c'", p[2]);
935 break;
937 if (advance && (!q || !q[0])) {
938 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
939 "option `-M%c' requires a parameter", p[2]);
940 break;
942 break;
944 case '-':
946 int s;
948 if (p[2] == 0) { /* -- => stop processing options */
949 stopoptions = 1;
950 break;
953 if (!nasm_stricmp(p, "--v"))
954 show_version();
956 for (s = 0; textopts[s].label; s++) {
957 if (!nasm_stricmp(p + 2, textopts[s].label)) {
958 break;
962 switch (s) {
964 case OPT_PREFIX:
965 case OPT_POSTFIX:
967 if (!q) {
968 nasm_error(ERR_NONFATAL | ERR_NOFILE |
969 ERR_USAGE,
970 "option `--%s' requires an argument",
971 p + 2);
972 break;
973 } else {
974 advance = 1, param = q;
977 switch (s) {
978 case OPT_PREFIX:
979 strlcpy(lprefix, param, PREFIX_MAX);
980 break;
981 case OPT_POSTFIX:
982 strlcpy(lpostfix, param, POSTFIX_MAX);
983 break;
984 default:
985 nasm_panic(ERR_NOFILE,
986 "internal error");
987 break;
989 break;
992 default:
994 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
995 "unrecognised option `--%s'", p + 2);
996 break;
999 break;
1002 default:
1003 if (!ofmt->setinfo(GI_SWITCH, &p))
1004 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1005 "unrecognised option `-%c'", p[1]);
1006 break;
1008 } else {
1009 if (*inname) {
1010 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1011 "more than one input file specified");
1012 } else {
1013 copy_filename(inname, p);
1017 return advance;
1020 #define ARG_BUF_DELTA 128
1022 static void process_respfile(FILE * rfile)
1024 char *buffer, *p, *q, *prevarg;
1025 int bufsize, prevargsize;
1027 bufsize = prevargsize = ARG_BUF_DELTA;
1028 buffer = nasm_malloc(ARG_BUF_DELTA);
1029 prevarg = nasm_malloc(ARG_BUF_DELTA);
1030 prevarg[0] = '\0';
1032 while (1) { /* Loop to handle all lines in file */
1033 p = buffer;
1034 while (1) { /* Loop to handle long lines */
1035 q = fgets(p, bufsize - (p - buffer), rfile);
1036 if (!q)
1037 break;
1038 p += strlen(p);
1039 if (p > buffer && p[-1] == '\n')
1040 break;
1041 if (p - buffer > bufsize - 10) {
1042 int offset;
1043 offset = p - buffer;
1044 bufsize += ARG_BUF_DELTA;
1045 buffer = nasm_realloc(buffer, bufsize);
1046 p = buffer + offset;
1050 if (!q && p == buffer) {
1051 if (prevarg[0])
1052 process_arg(prevarg, NULL);
1053 nasm_free(buffer);
1054 nasm_free(prevarg);
1055 return;
1059 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1060 * them are present at the end of the line.
1062 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1064 while (p > buffer && nasm_isspace(p[-1]))
1065 *--p = '\0';
1067 p = nasm_skip_spaces(buffer);
1069 if (process_arg(prevarg, p))
1070 *p = '\0';
1072 if ((int) strlen(p) > prevargsize - 10) {
1073 prevargsize += ARG_BUF_DELTA;
1074 prevarg = nasm_realloc(prevarg, prevargsize);
1076 strncpy(prevarg, p, prevargsize);
1080 /* Function to process args from a string of args, rather than the
1081 * argv array. Used by the environment variable and response file
1082 * processing.
1084 static void process_args(char *args)
1086 char *p, *q, *arg, *prevarg;
1087 char separator = ' ';
1089 p = args;
1090 if (*p && *p != '-')
1091 separator = *p++;
1092 arg = NULL;
1093 while (*p) {
1094 q = p;
1095 while (*p && *p != separator)
1096 p++;
1097 while (*p == separator)
1098 *p++ = '\0';
1099 prevarg = arg;
1100 arg = q;
1101 if (process_arg(prevarg, arg))
1102 arg = NULL;
1104 if (arg)
1105 process_arg(arg, NULL);
1108 static void process_response_file(const char *file)
1110 char str[2048];
1111 FILE *f = fopen(file, "r");
1112 if (!f) {
1113 perror(file);
1114 exit(-1);
1116 while (fgets(str, sizeof str, f)) {
1117 process_args(str);
1119 fclose(f);
1122 static void parse_cmdline(int argc, char **argv)
1124 FILE *rfile;
1125 char *envreal, *envcopy = NULL, *p;
1126 int i;
1128 *inname = *outname = *listname = *errname = '\0';
1130 for (i = 0; i <= ERR_WARN_MAX; i++)
1131 warning_on_global[i] = warnings[i].enabled;
1134 * First, process the NASMENV environment variable.
1136 envreal = getenv("NASMENV");
1137 if (envreal) {
1138 envcopy = nasm_strdup(envreal);
1139 process_args(envcopy);
1140 nasm_free(envcopy);
1144 * Now process the actual command line.
1146 while (--argc) {
1147 bool advance;
1148 argv++;
1149 if (argv[0][0] == '@') {
1151 * We have a response file, so process this as a set of
1152 * arguments like the environment variable. This allows us
1153 * to have multiple arguments on a single line, which is
1154 * different to the -@resp file processing below for regular
1155 * NASM.
1157 process_response_file(argv[0]+1);
1158 argc--;
1159 argv++;
1161 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1162 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1163 if (p) {
1164 rfile = fopen(p, "r");
1165 if (rfile) {
1166 process_respfile(rfile);
1167 fclose(rfile);
1168 } else
1169 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1170 "unable to open response file `%s'", p);
1172 } else
1173 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1174 argv += advance, argc -= advance;
1178 * Look for basic command line typos. This definitely doesn't
1179 * catch all errors, but it might help cases of fumbled fingers.
1181 if (!*inname)
1182 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1183 "no input file specified");
1184 else if (!strcmp(inname, errname) ||
1185 !strcmp(inname, outname) ||
1186 !strcmp(inname, listname) ||
1187 (depend_file && !strcmp(inname, depend_file)))
1188 nasm_fatal(ERR_NOFILE | ERR_USAGE,
1189 "file `%s' is both input and output file",
1190 inname);
1192 if (*errname) {
1193 error_file = fopen(errname, "w");
1194 if (!error_file) {
1195 error_file = stderr; /* Revert to default! */
1196 nasm_fatal(ERR_NOFILE | ERR_USAGE,
1197 "cannot open file `%s' for error messages",
1198 errname);
1203 static enum directives getkw(char **directive, char **value);
1205 static void assemble_file(char *fname, StrList **depend_ptr)
1207 char *directive, *value, *p, *q, *special, *line;
1208 insn output_ins;
1209 int i, validid;
1210 bool rn_error;
1211 int32_t seg;
1212 int64_t offs;
1213 struct tokenval tokval;
1214 expr *e;
1215 int pass_max;
1217 if (cmd_sb == 32 && iflag_ffs(&cmd_cpu) < IF_386)
1218 nasm_fatal(0, "command line: 32-bit segment size requires a higher cpu");
1220 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1221 for (passn = 1; pass0 <= 2; passn++) {
1222 int pass1, pass2;
1223 ldfunc def_label;
1225 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1226 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1227 /* pass0 0, 0, 0, ..., 1, 2 */
1229 def_label = passn > 1 ? redefine_label : define_label;
1231 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1232 cpu = cmd_cpu;
1233 if (pass0 == 2) {
1234 lfmt->init(listname);
1236 in_abs_seg = false;
1237 global_offset_changed = 0; /* set by redefine_label */
1238 location.segment = ofmt->section(NULL, pass2, &sb);
1239 globalbits = sb;
1240 if (passn > 1) {
1241 saa_rewind(forwrefs);
1242 forwref = saa_rstruct(forwrefs);
1243 raa_free(offsets);
1244 offsets = raa_init();
1246 preproc->reset(fname, pass1, pass1 == 2 ? depend_ptr : NULL);
1247 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1249 globallineno = 0;
1250 if (passn == 1)
1251 location.known = true;
1252 location.offset = offs = get_curr_offs();
1254 while ((line = preproc->getline())) {
1255 enum directives d;
1256 globallineno++;
1259 * Here we parse our directives; this is not handled by the
1260 * 'real' parser. This really should be a separate function.
1262 directive = line;
1263 d = getkw(&directive, &value);
1264 if (d) {
1265 int err = 0;
1267 switch (d) {
1268 case D_SEGMENT: /* [SEGMENT n] */
1269 case D_SECTION:
1270 seg = ofmt->section(value, pass2, &sb);
1271 if (seg == NO_SEG) {
1272 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1273 "segment name `%s' not recognized",
1274 value);
1275 } else {
1276 in_abs_seg = false;
1277 location.segment = seg;
1279 break;
1280 case D_SECTALIGN: /* [SECTALIGN n] */
1281 if (*value) {
1282 stdscan_reset();
1283 stdscan_set(value);
1284 tokval.t_type = TOKEN_INVALID;
1285 e = evaluate(stdscan, NULL, &tokval, NULL, pass2, NULL);
1286 if (e) {
1287 unsigned int align = (unsigned int)e->value;
1288 if ((uint64_t)e->value > 0x7fffffff) {
1290 * FIXME: Please make some sane message here
1291 * ofmt should have some 'check' method which
1292 * would report segment alignment bounds.
1294 nasm_fatal(0,
1295 "incorrect segment alignment `%s'", value);
1296 } else if (!is_power2(align)) {
1297 nasm_error(ERR_NONFATAL,
1298 "segment alignment `%s' is not power of two",
1299 value);
1302 /* callee should be able to handle all details */
1303 if (location.segment != NO_SEG)
1304 ofmt->sectalign(location.segment, align);
1307 break;
1308 case D_EXTERN: /* [EXTERN label:special] */
1309 if (*value == '$')
1310 value++; /* skip initial $ if present */
1311 if (pass0 == 2) {
1312 q = value;
1313 while (*q && *q != ':')
1314 q++;
1315 if (*q == ':') {
1316 *q++ = '\0';
1317 ofmt->symdef(value, 0L, 0L, 3, q);
1319 } else if (passn == 1) {
1320 q = value;
1321 validid = true;
1322 if (!isidstart(*q))
1323 validid = false;
1324 while (*q && *q != ':') {
1325 if (!isidchar(*q))
1326 validid = false;
1327 q++;
1329 if (!validid) {
1330 nasm_error(ERR_NONFATAL,
1331 "identifier expected after EXTERN");
1332 break;
1334 if (*q == ':') {
1335 *q++ = '\0';
1336 special = q;
1337 } else
1338 special = NULL;
1339 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1340 int temp = pass0;
1341 pass0 = 1; /* fake pass 1 in labels.c */
1342 declare_as_global(value, special);
1343 define_label(value, seg_alloc(), 0L, NULL,
1344 false, true);
1345 pass0 = temp;
1347 } /* else pass0 == 1 */
1348 break;
1349 case D_BITS: /* [BITS bits] */
1350 globalbits = sb = get_bits(value);
1351 break;
1352 case D_GLOBAL: /* [GLOBAL symbol:special] */
1353 if (*value == '$')
1354 value++; /* skip initial $ if present */
1355 if (pass0 == 2) { /* pass 2 */
1356 q = value;
1357 while (*q && *q != ':')
1358 q++;
1359 if (*q == ':') {
1360 *q++ = '\0';
1361 ofmt->symdef(value, 0L, 0L, 3, q);
1363 } else if (pass2 == 1) { /* pass == 1 */
1364 q = value;
1365 validid = true;
1366 if (!isidstart(*q))
1367 validid = false;
1368 while (*q && *q != ':') {
1369 if (!isidchar(*q))
1370 validid = false;
1371 q++;
1373 if (!validid) {
1374 nasm_error(ERR_NONFATAL,
1375 "identifier expected after GLOBAL");
1376 break;
1378 if (*q == ':') {
1379 *q++ = '\0';
1380 special = q;
1381 } else
1382 special = NULL;
1383 declare_as_global(value, special);
1384 } /* pass == 1 */
1385 break;
1386 case D_COMMON: /* [COMMON symbol size:special] */
1388 int64_t size;
1390 if (*value == '$')
1391 value++; /* skip initial $ if present */
1392 p = value;
1393 validid = true;
1394 if (!isidstart(*p))
1395 validid = false;
1396 while (*p && !nasm_isspace(*p)) {
1397 if (!isidchar(*p))
1398 validid = false;
1399 p++;
1401 if (!validid) {
1402 nasm_error(ERR_NONFATAL,
1403 "identifier expected after COMMON");
1404 break;
1406 if (*p) {
1407 p = nasm_zap_spaces_fwd(p);
1408 q = p;
1409 while (*q && *q != ':')
1410 q++;
1411 if (*q == ':') {
1412 *q++ = '\0';
1413 special = q;
1414 } else {
1415 special = NULL;
1417 size = readnum(p, &rn_error);
1418 if (rn_error) {
1419 nasm_error(ERR_NONFATAL,
1420 "invalid size specified"
1421 " in COMMON declaration");
1422 break;
1424 } else {
1425 nasm_error(ERR_NONFATAL,
1426 "no size specified in"
1427 " COMMON declaration");
1428 break;
1431 if (pass0 < 2) {
1432 define_common(value, seg_alloc(), size, special);
1433 } else if (pass0 == 2) {
1434 if (special)
1435 ofmt->symdef(value, 0L, 0L, 3, special);
1437 break;
1439 case D_ABSOLUTE: /* [ABSOLUTE address] */
1440 stdscan_reset();
1441 stdscan_set(value);
1442 tokval.t_type = TOKEN_INVALID;
1443 e = evaluate(stdscan, NULL, &tokval, NULL, pass2, NULL);
1444 if (e) {
1445 if (!is_reloc(e))
1446 nasm_error(pass0 ==
1447 1 ? ERR_NONFATAL : ERR_PANIC,
1448 "cannot use non-relocatable expression as "
1449 "ABSOLUTE address");
1450 else {
1451 abs_seg = reloc_seg(e);
1452 abs_offset = reloc_value(e);
1454 } else if (passn == 1)
1455 abs_offset = 0x100; /* don't go near zero in case of / */
1456 else
1457 nasm_panic(0, "invalid ABSOLUTE address "
1458 "in pass two");
1459 in_abs_seg = true;
1460 location.segment = NO_SEG;
1461 break;
1462 case D_DEBUG: /* [DEBUG] */
1464 char debugid[128];
1465 bool badid, overlong;
1467 p = value;
1468 q = debugid;
1469 badid = overlong = false;
1470 if (!isidstart(*p)) {
1471 badid = true;
1472 } else {
1473 while (*p && !nasm_isspace(*p)) {
1474 if (q >= debugid + sizeof debugid - 1) {
1475 overlong = true;
1476 break;
1478 if (!isidchar(*p))
1479 badid = true;
1480 *q++ = *p++;
1482 *q = 0;
1484 if (badid) {
1485 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1486 "identifier expected after DEBUG");
1487 break;
1489 if (overlong) {
1490 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1491 "DEBUG identifier too long");
1492 break;
1494 p = nasm_skip_spaces(p);
1495 if (pass0 == 2)
1496 dfmt->debug_directive(debugid, p);
1497 break;
1499 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1500 value = nasm_skip_spaces(value);
1501 switch(*value) {
1502 case '-': validid = 0; value++; break;
1503 case '+': validid = 1; value++; break;
1504 case '*': validid = 2; value++; break;
1505 default: validid = 1; break;
1508 for (i = 1; i <= ERR_WARN_MAX; i++)
1509 if (!nasm_stricmp(value, warnings[i].name))
1510 break;
1511 if (i <= ERR_WARN_MAX) {
1512 switch(validid) {
1513 case 0:
1514 warning_on[i] = false;
1515 break;
1516 case 1:
1517 warning_on[i] = true;
1518 break;
1519 case 2:
1520 warning_on[i] = warning_on_global[i];
1521 break;
1524 break;
1525 case D_CPU: /* [CPU] */
1526 cpu = get_cpu(value);
1527 break;
1528 case D_LIST: /* [LIST {+|-}] */
1529 value = nasm_skip_spaces(value);
1530 if (*value == '+') {
1531 user_nolist = 0;
1532 } else {
1533 if (*value == '-') {
1534 user_nolist = 1;
1535 } else {
1536 err = 1;
1539 break;
1540 case D_DEFAULT: /* [DEFAULT] */
1541 stdscan_reset();
1542 stdscan_set(value);
1543 tokval.t_type = TOKEN_INVALID;
1544 if (stdscan(NULL, &tokval) != TOKEN_INVALID) {
1545 switch ((int)tokval.t_integer) {
1546 case S_REL:
1547 globalrel = 1;
1548 break;
1549 case S_ABS:
1550 globalrel = 0;
1551 break;
1552 case P_BND:
1553 globalbnd = 1;
1554 break;
1555 case P_NOBND:
1556 globalbnd = 0;
1557 break;
1558 default:
1559 err = 1;
1560 break;
1562 } else {
1563 err = 1;
1565 break;
1566 case D_FLOAT:
1567 if (float_option(value)) {
1568 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1569 "unknown 'float' directive: %s",
1570 value);
1572 break;
1573 default:
1574 if (ofmt->directive(d, value, pass2))
1575 break;
1576 /* else fall through */
1577 case D_unknown:
1578 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1579 "unrecognised directive [%s]",
1580 directive);
1581 break;
1583 if (err) {
1584 nasm_error(ERR_NONFATAL,
1585 "invalid parameter to [%s] directive",
1586 directive);
1588 } else { /* it isn't a directive */
1589 parse_line(pass1, line, &output_ins, def_label);
1591 if (optimizing > 0) {
1592 if (forwref != NULL && globallineno == forwref->lineno) {
1593 output_ins.forw_ref = true;
1594 do {
1595 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1596 forwref = saa_rstruct(forwrefs);
1597 } while (forwref != NULL
1598 && forwref->lineno == globallineno);
1599 } else
1600 output_ins.forw_ref = false;
1602 if (output_ins.forw_ref) {
1603 if (passn == 1) {
1604 for (i = 0; i < output_ins.operands; i++) {
1605 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {
1606 struct forwrefinfo *fwinf = (struct forwrefinfo *)saa_wstruct(forwrefs);
1607 fwinf->lineno = globallineno;
1608 fwinf->operand = i;
1615 /* forw_ref */
1616 if (output_ins.opcode == I_EQU) {
1617 if (pass1 == 1) {
1619 * Special `..' EQUs get processed in pass two,
1620 * except `..@' macro-processor EQUs which are done
1621 * in the normal place.
1623 if (!output_ins.label)
1624 nasm_error(ERR_NONFATAL,
1625 "EQU not preceded by label");
1627 else if (output_ins.label[0] != '.' ||
1628 output_ins.label[1] != '.' ||
1629 output_ins.label[2] == '@') {
1630 if (output_ins.operands == 1 &&
1631 (output_ins.oprs[0].type & IMMEDIATE) &&
1632 output_ins.oprs[0].wrt == NO_SEG) {
1633 bool isext = !!(output_ins.oprs[0].opflags & OPFLAG_EXTERN);
1634 def_label(output_ins.label,
1635 output_ins.oprs[0].segment,
1636 output_ins.oprs[0].offset, NULL,
1637 false, isext);
1638 } else if (output_ins.operands == 2
1639 && (output_ins.oprs[0].type & IMMEDIATE)
1640 && (output_ins.oprs[0].type & COLON)
1641 && output_ins.oprs[0].segment == NO_SEG
1642 && output_ins.oprs[0].wrt == NO_SEG
1643 && (output_ins.oprs[1].type & IMMEDIATE)
1644 && output_ins.oprs[1].segment == NO_SEG
1645 && output_ins.oprs[1].wrt == NO_SEG) {
1646 def_label(output_ins.label,
1647 output_ins.oprs[0].offset | SEG_ABS,
1648 output_ins.oprs[1].offset,
1649 NULL, false, false);
1650 } else
1651 nasm_error(ERR_NONFATAL,
1652 "bad syntax for EQU");
1654 } else {
1656 * Special `..' EQUs get processed here, except
1657 * `..@' macro processor EQUs which are done above.
1659 if (output_ins.label[0] == '.' &&
1660 output_ins.label[1] == '.' &&
1661 output_ins.label[2] != '@') {
1662 if (output_ins.operands == 1 &&
1663 (output_ins.oprs[0].type & IMMEDIATE)) {
1664 define_label(output_ins.label,
1665 output_ins.oprs[0].segment,
1666 output_ins.oprs[0].offset,
1667 NULL, false, false);
1668 } else if (output_ins.operands == 2
1669 && (output_ins.oprs[0].type & IMMEDIATE)
1670 && (output_ins.oprs[0].type & COLON)
1671 && output_ins.oprs[0].segment == NO_SEG
1672 && (output_ins.oprs[1].type & IMMEDIATE)
1673 && output_ins.oprs[1].segment == NO_SEG) {
1674 define_label(output_ins.label,
1675 output_ins.oprs[0].offset | SEG_ABS,
1676 output_ins.oprs[1].offset,
1677 NULL, false, false);
1678 } else
1679 nasm_error(ERR_NONFATAL,
1680 "bad syntax for EQU");
1683 } else { /* instruction isn't an EQU */
1685 if (pass1 == 1) {
1687 int64_t l = insn_size(location.segment, offs, sb, cpu,
1688 &output_ins);
1690 /* if (using_debug_info) && output_ins.opcode != -1) */
1691 if (using_debug_info)
1692 { /* fbk 03/25/01 */
1693 /* this is done here so we can do debug type info */
1694 int32_t typeinfo =
1695 TYS_ELEMENTS(output_ins.operands);
1696 switch (output_ins.opcode) {
1697 case I_RESB:
1698 typeinfo =
1699 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1700 break;
1701 case I_RESW:
1702 typeinfo =
1703 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1704 break;
1705 case I_RESD:
1706 typeinfo =
1707 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1708 break;
1709 case I_RESQ:
1710 typeinfo =
1711 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1712 break;
1713 case I_REST:
1714 typeinfo =
1715 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1716 break;
1717 case I_RESO:
1718 typeinfo =
1719 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;
1720 break;
1721 case I_RESY:
1722 typeinfo =
1723 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;
1724 break;
1725 case I_DB:
1726 typeinfo |= TY_BYTE;
1727 break;
1728 case I_DW:
1729 typeinfo |= TY_WORD;
1730 break;
1731 case I_DD:
1732 if (output_ins.eops_float)
1733 typeinfo |= TY_FLOAT;
1734 else
1735 typeinfo |= TY_DWORD;
1736 break;
1737 case I_DQ:
1738 typeinfo |= TY_QWORD;
1739 break;
1740 case I_DT:
1741 typeinfo |= TY_TBYTE;
1742 break;
1743 case I_DO:
1744 typeinfo |= TY_OWORD;
1745 break;
1746 case I_DY:
1747 typeinfo |= TY_YWORD;
1748 break;
1749 default:
1750 typeinfo = TY_LABEL;
1754 dfmt->debug_typevalue(typeinfo);
1756 if (l != -1) {
1757 offs += l;
1758 set_curr_offs(offs);
1761 * else l == -1 => invalid instruction, which will be
1762 * flagged as an error on pass 2
1765 } else {
1766 offs += assemble(location.segment, offs, sb, cpu,
1767 &output_ins);
1768 set_curr_offs(offs);
1771 } /* not an EQU */
1772 cleanup_insn(&output_ins);
1774 nasm_free(line);
1775 location.offset = offs = get_curr_offs();
1776 } /* end while (line = preproc->getline... */
1778 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1779 nasm_error(ERR_NONFATAL,
1780 "phase error detected at end of assembly.");
1782 if (pass1 == 1)
1783 preproc->cleanup(1);
1785 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1786 pass0++;
1787 } else if (global_offset_changed &&
1788 global_offset_changed < prev_offset_changed) {
1789 prev_offset_changed = global_offset_changed;
1790 stall_count = 0;
1791 } else {
1792 stall_count++;
1795 if (terminate_after_phase)
1796 break;
1798 if ((stall_count > 997) || (passn >= pass_max)) {
1799 /* We get here if the labels don't converge
1800 * Example: FOO equ FOO + 1
1802 nasm_error(ERR_NONFATAL,
1803 "Can't find valid values for all labels "
1804 "after %d passes, giving up.", passn);
1805 nasm_error(ERR_NONFATAL,
1806 "Possible causes: recursive EQUs, macro abuse.");
1807 break;
1811 preproc->cleanup(0);
1812 lfmt->cleanup();
1813 if (!terminate_after_phase && opt_verbose_info) {
1814 /* -On and -Ov switches */
1815 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1819 static enum directives getkw(char **directive, char **value)
1821 char *p, *q, *buf;
1823 buf = nasm_skip_spaces(*directive);
1825 /* it should be enclosed in [ ] */
1826 if (*buf != '[')
1827 return D_none;
1828 q = strchr(buf, ']');
1829 if (!q)
1830 return D_none;
1832 /* stip off the comments */
1833 p = strchr(buf, ';');
1834 if (p) {
1835 if (p < q) /* ouch! somwhere inside */
1836 return D_none;
1837 *p = '\0';
1840 /* no brace, no trailing spaces */
1841 *q = '\0';
1842 nasm_zap_spaces_rev(--q);
1844 /* directive */
1845 p = nasm_skip_spaces(++buf);
1846 q = nasm_skip_word(p);
1847 if (!q)
1848 return D_none; /* sigh... no value there */
1849 *q = '\0';
1850 *directive = p;
1852 /* and value finally */
1853 p = nasm_skip_spaces(++q);
1854 *value = p;
1856 return find_directive(*directive);
1860 * gnu style error reporting
1861 * This function prints an error message to error_file in the
1862 * style used by GNU. An example would be:
1863 * file.asm:50: error: blah blah blah
1864 * where file.asm is the name of the file, 50 is the line number on
1865 * which the error occurs (or is detected) and "error:" is one of
1866 * the possible optional diagnostics -- it can be "error" or "warning"
1867 * or something else. Finally the line terminates with the actual
1868 * error message.
1870 * @param severity the severity of the warning or error
1871 * @param fmt the printf style format string
1873 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1875 const char *currentfile = NULL;
1876 int32_t lineno = 0;
1878 if (is_suppressed_warning(severity))
1879 return;
1881 if (!(severity & ERR_NOFILE))
1882 src_get(&lineno, &currentfile);
1884 if (!skip_this_pass(severity)) {
1885 if (currentfile) {
1886 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1887 } else {
1888 fputs("nasm: ", error_file);
1892 nasm_verror_common(severity, fmt, ap);
1896 * MS style error reporting
1897 * This function prints an error message to error_file in the
1898 * style used by Visual C and some other Microsoft tools. An example
1899 * would be:
1900 * file.asm(50) : error: blah blah blah
1901 * where file.asm is the name of the file, 50 is the line number on
1902 * which the error occurs (or is detected) and "error:" is one of
1903 * the possible optional diagnostics -- it can be "error" or "warning"
1904 * or something else. Finally the line terminates with the actual
1905 * error message.
1907 * @param severity the severity of the warning or error
1908 * @param fmt the printf style format string
1910 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1912 const char *currentfile = NULL;
1913 int32_t lineno = 0;
1915 if (is_suppressed_warning(severity))
1916 return;
1918 if (!(severity & ERR_NOFILE))
1919 src_get(&lineno, &currentfile);
1921 if (!skip_this_pass(severity)) {
1922 if (currentfile) {
1923 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1924 } else {
1925 fputs("nasm: ", error_file);
1929 nasm_verror_common(severity, fmt, ap);
1933 * check for supressed warning
1934 * checks for suppressed warning or pass one only warning and we're
1935 * not in pass 1
1937 * @param severity the severity of the warning or error
1938 * @return true if we should abort error/warning printing
1940 static bool is_suppressed_warning(int severity)
1942 /* Not a warning at all */
1943 if ((severity & ERR_MASK) != ERR_WARNING)
1944 return false;
1946 /* Might be a warning but suppresed explicitly */
1947 if (severity & ERR_WARN_MASK)
1948 return !warning_on[WARN_IDX(severity)];
1949 else
1950 return false;
1953 static bool skip_this_pass(int severity)
1955 /* See if it's a pass-specific warning which should be skipped. */
1957 if ((severity & ERR_MASK) > ERR_WARNING)
1958 return false;
1961 * passn is 1 on the very first pass only.
1962 * pass0 is 2 on the code-generation (final) pass only.
1963 * These are the passes we care about in this case.
1965 return (((severity & ERR_PASS1) && passn != 1) ||
1966 ((severity & ERR_PASS2) && pass0 != 2));
1970 * common error reporting
1971 * This is the common back end of the error reporting schemes currently
1972 * implemented. It prints the nature of the warning and then the
1973 * specific error message to error_file and may or may not return. It
1974 * doesn't return if the error severity is a "panic" or "debug" type.
1976 * @param severity the severity of the warning or error
1977 * @param fmt the printf style format string
1979 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1981 char msg[1024];
1982 const char *pfx;
1984 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1985 case ERR_WARNING:
1986 pfx = "warning: ";
1987 break;
1988 case ERR_NONFATAL:
1989 pfx = "error: ";
1990 break;
1991 case ERR_FATAL:
1992 pfx = "fatal: ";
1993 break;
1994 case ERR_PANIC:
1995 pfx = "panic: ";
1996 break;
1997 case ERR_DEBUG:
1998 pfx = "debug: ";
1999 break;
2000 default:
2001 pfx = "";
2002 break;
2005 vsnprintf(msg, sizeof msg - 64, fmt, args);
2006 if ((severity & (ERR_WARN_MASK|ERR_PP_LISTMACRO)) == ERR_WARN_MASK) {
2007 char *p = strchr(msg, '\0');
2008 snprintf(p, 64, " [-w+%s]", warnings[WARN_IDX(severity)].name);
2011 if (!skip_this_pass(severity))
2012 fprintf(error_file, "%s%s\n", pfx, msg);
2014 /* Are we recursing from error_list_macros? */
2015 if (severity & ERR_PP_LISTMACRO)
2016 return;
2019 * Don't suppress this with skip_this_pass(), or we don't get
2020 * pass1 or preprocessor warnings in the list file
2022 if ((severity & ERR_MASK) >= ERR_WARNING)
2023 lfmt->error(severity, pfx, msg);
2025 if (severity & ERR_USAGE)
2026 want_usage = true;
2028 preproc->error_list_macros(severity);
2030 switch (severity & ERR_MASK) {
2031 case ERR_DEBUG:
2032 /* no further action, by definition */
2033 break;
2034 case ERR_WARNING:
2035 /* Treat warnings as errors */
2036 if (warning_on[WARN_IDX(ERR_WARN_TERM)])
2037 terminate_after_phase = true;
2038 break;
2039 case ERR_NONFATAL:
2040 terminate_after_phase = true;
2041 break;
2042 case ERR_FATAL:
2043 if (ofile) {
2044 fclose(ofile);
2045 remove(outname);
2046 ofile = NULL;
2048 if (want_usage)
2049 usage();
2050 exit(1); /* instantly die */
2051 break; /* placate silly compilers */
2052 case ERR_PANIC:
2053 fflush(NULL);
2054 /* abort(); */ /* halt, catch fire, and dump core */
2055 if (ofile) {
2056 fclose(ofile);
2057 remove(outname);
2058 ofile = NULL;
2060 exit(3);
2061 break;
2065 static void usage(void)
2067 fputs("type `nasm -h' for help\n", error_file);
2070 static iflag_t get_cpu(char *value)
2072 iflag_t r;
2074 iflag_clear_all(&r);
2076 if (!strcmp(value, "8086"))
2077 iflag_set(&r, IF_8086);
2078 else if (!strcmp(value, "186"))
2079 iflag_set(&r, IF_186);
2080 else if (!strcmp(value, "286"))
2081 iflag_set(&r, IF_286);
2082 else if (!strcmp(value, "386"))
2083 iflag_set(&r, IF_386);
2084 else if (!strcmp(value, "486"))
2085 iflag_set(&r, IF_486);
2086 else if (!strcmp(value, "586") ||
2087 !nasm_stricmp(value, "pentium"))
2088 iflag_set(&r, IF_PENT);
2089 else if (!strcmp(value, "686") ||
2090 !nasm_stricmp(value, "ppro") ||
2091 !nasm_stricmp(value, "pentiumpro") ||
2092 !nasm_stricmp(value, "p2"))
2093 iflag_set(&r, IF_P6);
2094 else if (!nasm_stricmp(value, "p3") ||
2095 !nasm_stricmp(value, "katmai"))
2096 iflag_set(&r, IF_KATMAI);
2097 else if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2098 !nasm_stricmp(value, "willamette"))
2099 iflag_set(&r, IF_WILLAMETTE);
2100 else if (!nasm_stricmp(value, "prescott"))
2101 iflag_set(&r, IF_PRESCOTT);
2102 else if (!nasm_stricmp(value, "x64") ||
2103 !nasm_stricmp(value, "x86-64"))
2104 iflag_set(&r, IF_X86_64);
2105 else if (!nasm_stricmp(value, "ia64") ||
2106 !nasm_stricmp(value, "ia-64") ||
2107 !nasm_stricmp(value, "itanium")||
2108 !nasm_stricmp(value, "itanic") ||
2109 !nasm_stricmp(value, "merced"))
2110 iflag_set(&r, IF_IA64);
2111 else {
2112 iflag_set(&r, IF_PLEVEL);
2113 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2114 "unknown 'cpu' type");
2116 return r;
2119 static int get_bits(char *value)
2121 int i;
2123 if ((i = atoi(value)) == 16)
2124 return i; /* set for a 16-bit segment */
2125 else if (i == 32) {
2126 if (iflag_ffs(&cpu) < IF_386) {
2127 nasm_error(ERR_NONFATAL,
2128 "cannot specify 32-bit segment on processor below a 386");
2129 i = 16;
2131 } else if (i == 64) {
2132 if (iflag_ffs(&cpu) < IF_X86_64) {
2133 nasm_error(ERR_NONFATAL,
2134 "cannot specify 64-bit segment on processor below an x86-64");
2135 i = 16;
2137 } else {
2138 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2139 "`%s' is not a valid segment size; must be 16, 32 or 64",
2140 value);
2141 i = 16;
2143 return i;