1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2018 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
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
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. */
77 static void parse_cmdline(int, char **, int);
78 static void assemble_file(const char *, StrList
**);
79 static bool is_suppressed_warning(int severity
);
80 static bool skip_this_pass(int severity
);
81 static void nasm_verror_gnu(int severity
, const char *fmt
, va_list args
);
82 static void nasm_verror_vc(int severity
, const char *fmt
, va_list args
);
83 static void nasm_verror_common(int severity
, const char *fmt
, va_list args
);
84 static void usage(void);
86 static bool using_debug_info
, opt_verbose_info
;
87 static const char *debug_format
;
89 #ifndef ABORT_ON_PANIC
90 # define ABORT_ON_PANIC 0
92 static bool abort_on_panic
= ABORT_ON_PANIC
;
94 bool tasm_compatible_mode
= false;
96 static int pass1
, pass2
; /* XXX: Get rid of these, they are redundant */
100 struct compile_time official_compile_time
;
104 static const char *listname
;
105 static const char *errname
;
107 static int globallineno
; /* for forward-reference tracking */
108 /* static int pass = 0; */
109 const struct ofmt
*ofmt
= &OF_DEFAULT
;
110 const struct ofmt_alias
*ofmt_alias
= NULL
;
111 const struct dfmt
*dfmt
;
113 static FILE *error_file
; /* Where to write error messages */
116 int optimizing
= MAX_OPTIMIZE
; /* number of optimization passes to take */
117 static int cmd_sb
= 16; /* by default */
120 static iflag_t cmd_cpu
;
122 struct location location
;
123 bool in_absolute
; /* Flag we are in ABSOLUTE seg */
124 struct location absolute
; /* Segment/offset inside ABSOLUTE */
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
;
144 StrList
*depend_list
;
146 static bool want_usage
;
147 static bool terminate_after_phase
;
148 bool user_nolist
= false;
150 static char *quote_for_pmake(const char *str
);
151 static char *quote_for_wmake(const char *str
);
152 static char *(*quote_for_make
)(const char *) = quote_for_pmake
;
154 static int64_t get_curr_offs(void)
156 return in_absolute
? absolute
.offset
: raa_read(offsets
, location
.segment
);
159 static void set_curr_offs(int64_t l_off
)
162 absolute
.offset
= l_off
;
164 offsets
= raa_write(offsets
, location
.segment
, l_off
);
167 static void nasm_fputs(const char *line
, FILE * outfile
)
170 fputs(line
, outfile
);
176 static void define_macros_early(void)
178 const struct compile_time
* const oct
= &official_compile_time
;
181 if (oct
->have_local
) {
182 strftime(temp
, sizeof temp
, "__DATE__=\"%Y-%m-%d\"", &oct
->local
);
183 preproc
->pre_define(temp
);
184 strftime(temp
, sizeof temp
, "__DATE_NUM__=%Y%m%d", &oct
->local
);
185 preproc
->pre_define(temp
);
186 strftime(temp
, sizeof temp
, "__TIME__=\"%H:%M:%S\"", &oct
->local
);
187 preproc
->pre_define(temp
);
188 strftime(temp
, sizeof temp
, "__TIME_NUM__=%H%M%S", &oct
->local
);
189 preproc
->pre_define(temp
);
193 strftime(temp
, sizeof temp
, "__UTC_DATE__=\"%Y-%m-%d\"", &oct
->gm
);
194 preproc
->pre_define(temp
);
195 strftime(temp
, sizeof temp
, "__UTC_DATE_NUM__=%Y%m%d", &oct
->gm
);
196 preproc
->pre_define(temp
);
197 strftime(temp
, sizeof temp
, "__UTC_TIME__=\"%H:%M:%S\"", &oct
->gm
);
198 preproc
->pre_define(temp
);
199 strftime(temp
, sizeof temp
, "__UTC_TIME_NUM__=%H%M%S", &oct
->gm
);
200 preproc
->pre_define(temp
);
203 if (oct
->have_posix
) {
204 snprintf(temp
, sizeof temp
, "__POSIX_TIME__=%"PRId64
, oct
->posix
);
205 preproc
->pre_define(temp
);
209 static void define_macros_late(void)
214 * In case if output format is defined by alias
215 * we have to put shortname of the alias itself here
216 * otherwise ABI backward compatibility gets broken.
218 snprintf(temp
, sizeof(temp
), "__OUTPUT_FORMAT__=%s",
219 ofmt_alias
? ofmt_alias
->shortname
: ofmt
->shortname
);
220 preproc
->pre_define(temp
);
223 static void emit_dependencies(StrList
*list
)
228 bool wmake
= (quote_for_make
== quote_for_wmake
);
229 const char *wrapstr
, *nulltarget
;
231 wrapstr
= wmake
? " &\n " : " \\\n ";
232 nulltarget
= wmake
? "\t%null\n" : "";
234 if (depend_file
&& strcmp(depend_file
, "-")) {
235 deps
= nasm_open_write(depend_file
, NF_TEXT
);
237 nasm_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
238 "unable to write dependency file `%s'", depend_file
);
245 linepos
= fprintf(deps
, "%s :", depend_target
);
246 list_for_each(l
, list
) {
247 char *file
= quote_for_make(l
->str
);
249 if (linepos
+ len
> 62 && linepos
> 1) {
250 fputs(wrapstr
, deps
);
253 fprintf(deps
, " %s", file
);
257 fprintf(deps
, "\n\n");
259 list_for_each_safe(l
, nl
, list
) {
260 if (depend_emit_phony
) {
261 char *file
= quote_for_make(l
->str
);
262 fprintf(deps
, "%s :\n%s\n", file
, nulltarget
);
272 /* Convert a struct tm to a POSIX-style time constant */
273 static int64_t make_posix_time(const struct tm
*tm
)
276 int64_t y
= tm
->tm_year
;
278 /* See IEEE 1003.1:2004, section 4.14 */
280 t
= (y
-70)*365 + (y
-69)/4 - (y
-1)/100 + (y
+299)/400;
292 static void timestamp(void)
294 struct compile_time
* const oct
= &official_compile_time
;
295 const struct tm
*tp
, *best_gm
;
301 tp
= localtime(&oct
->t
);
304 best_gm
= &oct
->local
;
305 oct
->have_local
= true;
308 tp
= gmtime(&oct
->t
);
313 if (!oct
->have_local
)
314 oct
->local
= oct
->gm
;
316 oct
->gm
= oct
->local
;
320 oct
->posix
= make_posix_time(best_gm
);
321 oct
->have_posix
= true;
325 int main(int argc
, char **argv
)
327 StrList
**depend_ptr
;
331 iflag_set_default_cpu(&cpu
);
332 iflag_set_default_cpu(&cmd_cpu
);
335 want_usage
= terminate_after_phase
= false;
336 nasm_set_verror(nasm_verror_gnu
);
343 offsets
= raa_init();
344 forwrefs
= saa_init((int32_t)sizeof(struct forwrefinfo
));
347 operating_mode
= OP_NORMAL
;
349 parse_cmdline(argc
, argv
, 1);
350 if (terminate_after_phase
) {
357 * Define some macros dependent on the runtime, but not
358 * on the command line (as those are scanned in cmdline pass 2.)
361 define_macros_early();
363 parse_cmdline(argc
, argv
, 2);
364 if (terminate_after_phase
) {
370 /* Save away the default state of warnings */
371 memcpy(warning_state_init
, warning_state
, sizeof warning_state
);
373 if (!using_debug_info
) {
374 /* No debug info, redirect to the null backend (empty stubs) */
375 dfmt
= &null_debug_form
;
376 } else if (!debug_format
) {
377 /* Default debug format for this backend */
378 dfmt
= ofmt
->default_dfmt
;
380 dfmt
= dfmt_find(ofmt
, debug_format
);
382 nasm_fatal(ERR_NOFILE
| ERR_USAGE
,
383 "unrecognized debug format `%s' for"
384 " output format `%s'",
385 debug_format
, ofmt
->shortname
);
390 preproc
->extra_stdmac(ofmt
->stdmac
);
392 /* no output file name? */
394 outname
= filename_set_extension(inname
, ofmt
->extension
);
396 /* define some macros dependent of command-line */
397 define_macros_late();
399 depend_ptr
= (depend_file
|| (operating_mode
& OP_DEPEND
)) ? &depend_list
: NULL
;
402 depend_target
= quote_for_make(outname
);
404 if (operating_mode
& OP_DEPEND
) {
407 if (depend_missing_ok
)
408 preproc
->include_path(NULL
); /* "assume generated" */
410 preproc
->reset(inname
, 0, depend_ptr
);
412 while ((line
= preproc
->getline()))
415 } else if (operating_mode
& OP_PREPROCESS
) {
417 const char *file_name
= NULL
;
418 int32_t prior_linnum
= 0;
422 ofile
= nasm_open_write(outname
, NF_TEXT
);
424 nasm_fatal(ERR_NOFILE
,
425 "unable to open output file `%s'",
430 location
.known
= false;
433 preproc
->reset(inname
, 3, depend_ptr
);
435 /* Revert all warnings to the default state */
436 memcpy(warning_state
, warning_state_init
, sizeof warning_state
);
438 while ((line
= preproc
->getline())) {
440 * We generate %line directives if needed for later programs
442 int32_t linnum
= prior_linnum
+= lineinc
;
443 int altline
= src_get(&linnum
, &file_name
);
445 if (altline
== 1 && lineinc
== 1)
446 nasm_fputs("", ofile
);
448 lineinc
= (altline
!= -1 || lineinc
!= 1);
449 fprintf(ofile
? ofile
: stdout
,
450 "%%line %"PRId32
"+%d %s\n", linnum
, lineinc
,
453 prior_linnum
= linnum
;
455 nasm_fputs(line
, ofile
);
461 if (ofile
&& terminate_after_phase
)
466 if (operating_mode
& OP_NORMAL
) {
467 ofile
= nasm_open_write(outname
, (ofmt
->flags
& OFMT_TEXT
) ? NF_TEXT
: NF_BINARY
);
469 nasm_fatal(ERR_NOFILE
,
470 "unable to open output file `%s'", outname
);
473 * We must call init_labels() before ofmt->init() since
474 * some object formats will want to define labels in their
475 * init routines. (eg OS/2 defines the FLAT group)
482 assemble_file(inname
, depend_ptr
);
484 if (!terminate_after_phase
) {
489 nasm_error(ERR_NONFATAL
|ERR_NOFILE
,
490 "write error on output file `%s'", outname
);
491 terminate_after_phase
= true;
497 if (terminate_after_phase
)
503 if (depend_list
&& !terminate_after_phase
)
504 emit_dependencies(depend_list
);
515 return terminate_after_phase
;
519 * Get a parameter for a command line option.
520 * First arg must be in the form of e.g. -f...
522 static char *get_param(char *p
, char *q
, bool *advance
)
525 if (p
[2]) /* the parameter's in the option */
526 return nasm_skip_spaces(p
+ 2);
531 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
532 "option `-%c' requires an argument", p
[1]);
539 static void copy_filename(const char **dst
, const char *src
, const char *what
)
542 nasm_fatal(0, "more than one %s file specified: %s\n", what
, src
);
544 *dst
= nasm_strdup(src
);
548 * Convert a string to a POSIX make-safe form
550 static char *quote_for_pmake(const char *str
)
555 size_t n
= 1; /* Terminating zero */
561 for (p
= str
; *p
; p
++) {
565 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
585 /* Convert N backslashes at the end of filename to 2N backslashes */
589 os
= q
= nasm_malloc(n
);
592 for (p
= str
; *p
; p
++) {
630 * Convert a string to a Watcom make-safe form
632 static char *quote_for_wmake(const char *str
)
638 size_t n
= 1; /* Terminating zero */
643 for (p
= str
; *p
; p
++) {
668 os
= q
= nasm_malloc(n
);
673 for (p
= str
; *p
; p
++) {
707 enum text_options opt
;
710 static const struct textargs textopts
[] = {
711 {"v", OPT_VERSION
, false},
712 {"version", OPT_VERSION
, false},
713 {"abort-on-panic", OPT_ABORT_ON_PANIC
, false},
714 {"prefix", OPT_PREFIX
, true},
715 {"postfix", OPT_POSTFIX
, true},
716 {NULL
, OPT_BOGUS
, false}
719 static void show_version(void)
721 printf("NASM version %s compiled on %s%s\n",
722 nasm_version
, nasm_date
, nasm_compile_options
);
726 static bool stopoptions
= false;
727 static bool process_arg(char *p
, char *q
, int pass
)
731 bool advance
= false;
736 if (p
[0] == '-' && !stopoptions
) {
737 if (strchr("oOfpPdDiIlFXuUZwW", p
[1])) {
738 /* These parameters take values */
739 if (!(param
= get_param(p
, q
, &advance
)))
749 case 'o': /* output file */
751 copy_filename(&outname
, param
, "output");
754 case 'f': /* output format */
756 ofmt
= ofmt_find(param
, &ofmt_alias
);
758 nasm_fatal(ERR_NOFILE
| ERR_USAGE
,
759 "unrecognised output format `%s' - "
760 "use -hf for a list", param
);
765 case 'O': /* Optimization level */
770 /* Naked -O == -Ox */
771 optimizing
= MAX_OPTIMIZE
;
775 case '0': case '1': case '2': case '3': case '4':
776 case '5': case '6': case '7': case '8': case '9':
777 opt
= strtoul(param
, ¶m
, 10);
779 /* -O0 -> optimizing == -1, 0.98 behaviour */
780 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
782 optimizing
= opt
- 1;
790 opt_verbose_info
= true;
795 optimizing
= MAX_OPTIMIZE
;
800 "unknown optimization option -O%c\n",
805 if (optimizing
> MAX_OPTIMIZE
)
806 optimizing
= MAX_OPTIMIZE
;
811 case 'p': /* pre-include */
814 preproc
->pre_include(param
);
817 case 'd': /* pre-define */
820 preproc
->pre_define(param
);
823 case 'u': /* un-define */
826 preproc
->pre_undefine(param
);
829 case 'i': /* include search path */
832 preproc
->include_path(param
);
835 case 'l': /* listing file */
837 copy_filename(&listname
, param
, "listing");
840 case 'Z': /* error messages file */
842 copy_filename(&errname
, param
, "error");
845 case 'F': /* specify debug format */
847 using_debug_info
= true;
848 debug_format
= param
;
852 case 'X': /* specify error reporting format */
854 if (nasm_stricmp("vc", param
) == 0)
855 nasm_set_verror(nasm_verror_vc
);
856 else if (nasm_stricmp("gnu", param
) == 0)
857 nasm_set_verror(nasm_verror_gnu
);
859 nasm_fatal(ERR_NOFILE
| ERR_USAGE
,
860 "unrecognized error reporting format `%s'",
867 using_debug_info
= true;
869 debug_format
= nasm_skip_spaces(p
+ 2);
875 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
877 " [options...] [--] filename\n"
878 " or nasm -v (or --v) for version info\n\n"
879 " -t assemble in SciTech TASM compatible mode\n");
881 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
882 " -a don't preprocess (assemble only)\n"
883 " -M generate Makefile dependencies on stdout\n"
884 " -MG d:o, missing files assumed generated\n"
885 " -MF <file> set Makefile dependency file\n"
886 " -MD <file> assemble and generate dependencies\n"
887 " -MT <file> dependency target name\n"
888 " -MQ <file> dependency target name (quoted)\n"
889 " -MP emit phony target\n\n"
890 " -Z<file> redirect error messages to file\n"
891 " -s redirect error messages to stdout\n\n"
892 " -g generate debugging information\n\n"
893 " -F format select a debugging format\n\n"
894 " -gformat same as -g -F format\n\n"
895 " -o outfile write output to an outfile\n\n"
896 " -f format select an output format\n\n"
897 " -l listfile write listing to a listfile\n\n"
898 " -I<path> adds a pathname to the include file path\n");
900 (" -O<digit> optimize branch offsets\n"
901 " -O0: No optimization\n"
902 " -O1: Minimal optimization\n"
903 " -Ox: Multipass optimization (default)\n\n"
904 " -P<file> pre-includes a file\n"
905 " -D<macro>[=<value>] pre-defines a macro\n"
906 " -U<macro> undefines a macro\n"
907 " -X<format> specifies error reporting format (gnu or vc)\n"
908 " -w+foo enables warning foo (equiv. -Wfoo)\n"
909 " -w-foo disable warning foo (equiv. -Wno-foo)\n\n"
910 " -w[+-]error[=foo] can be used to promote warnings to errors\n"
911 " -h show invocation summary and exit\n\n"
912 "--prefix,--postfix\n"
913 " these options prepend or append the given string\n"
914 " to all extern and global variables\n"
916 "Response files should contain command line parameters,\n"
919 "Warnings for the -W/-w options:\n");
920 for (i
= 0; i
<= ERR_WARN_ALL
; i
++)
921 printf(" %-23s %s%s\n",
922 warnings
[i
].name
, warnings
[i
].help
,
923 i
== ERR_WARN_ALL
? "\n" :
924 warnings
[i
].enabled
? " (default on)" :
927 printf("valid output formats for -f are"
928 " (`*' denotes default):\n");
929 ofmt_list(ofmt
, stdout
);
931 printf("For a list of valid output formats, use -hf.\n");
932 printf("For a list of debug formats, use -f <form> -y.\n");
934 exit(0); /* never need usage message here */
938 printf("\nvalid debug formats for '%s' output format are"
939 " ('*' denotes default):\n", ofmt
->shortname
);
940 dfmt_list(ofmt
, stdout
);
946 tasm_compatible_mode
= true;
953 case 'e': /* preprocess only */
956 operating_mode
= OP_PREPROCESS
;
959 case 'a': /* assemble only - don't preprocess */
961 preproc
= &preproc_nop
;
967 if (!set_warning_status(param
)) {
968 nasm_error(ERR_WARNING
|ERR_NOFILE
|ERR_WARN_UNK_WARNING
,
969 "unknown warning option: %s", param
);
978 quote_for_make
= quote_for_wmake
;
992 operating_mode
= OP_DEPEND
;
995 operating_mode
= OP_DEPEND
;
996 depend_missing_ok
= true;
999 depend_emit_phony
= true;
1002 operating_mode
= OP_NORMAL
;
1015 depend_target
= quote_for_make(q
);
1019 /* handled in pass 1 */
1022 nasm_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
1023 "unknown dependency option `-M%c'", p
[2]);
1027 if (advance
&& (!q
|| !q
[0])) {
1028 nasm_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
1029 "option `-M%c' requires a parameter", p
[2]);
1036 const struct textargs
*tx
;
1038 if (p
[2] == 0) { /* -- => stop processing options */
1043 for (tx
= textopts
; tx
->label
; tx
++) {
1044 if (!nasm_stricmp(p
+ 2, tx
->label
))
1050 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1051 "option `--%s' requires an argument",
1062 case OPT_ABORT_ON_PANIC
:
1063 abort_on_panic
= true;
1067 strlcpy(lprefix
, q
, PREFIX_MAX
);
1071 strlcpy(lpostfix
, q
, POSTFIX_MAX
);
1074 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1075 "unrecognized option `--%s'", p
+ 2);
1084 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1085 "unrecognised option `-%c'", p
[1]);
1088 } else if (pass
== 2) {
1089 /* In theory we could allow multiple input files... */
1090 copy_filename(&inname
, p
, "input");
1096 #define ARG_BUF_DELTA 128
1098 static void process_respfile(FILE * rfile
, int pass
)
1100 char *buffer
, *p
, *q
, *prevarg
;
1101 int bufsize
, prevargsize
;
1103 bufsize
= prevargsize
= ARG_BUF_DELTA
;
1104 buffer
= nasm_malloc(ARG_BUF_DELTA
);
1105 prevarg
= nasm_malloc(ARG_BUF_DELTA
);
1108 while (1) { /* Loop to handle all lines in file */
1110 while (1) { /* Loop to handle long lines */
1111 q
= fgets(p
, bufsize
- (p
- buffer
), rfile
);
1115 if (p
> buffer
&& p
[-1] == '\n')
1117 if (p
- buffer
> bufsize
- 10) {
1119 offset
= p
- buffer
;
1120 bufsize
+= ARG_BUF_DELTA
;
1121 buffer
= nasm_realloc(buffer
, bufsize
);
1122 p
= buffer
+ offset
;
1126 if (!q
&& p
== buffer
) {
1128 process_arg(prevarg
, NULL
, pass
);
1135 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1136 * them are present at the end of the line.
1138 *(p
= &buffer
[strcspn(buffer
, "\r\n\032")]) = '\0';
1140 while (p
> buffer
&& nasm_isspace(p
[-1]))
1143 p
= nasm_skip_spaces(buffer
);
1145 if (process_arg(prevarg
, p
, pass
))
1148 if ((int) strlen(p
) > prevargsize
- 10) {
1149 prevargsize
+= ARG_BUF_DELTA
;
1150 prevarg
= nasm_realloc(prevarg
, prevargsize
);
1152 strncpy(prevarg
, p
, prevargsize
);
1156 /* Function to process args from a string of args, rather than the
1157 * argv array. Used by the environment variable and response file
1160 static void process_args(char *args
, int pass
)
1162 char *p
, *q
, *arg
, *prevarg
;
1163 char separator
= ' ';
1166 if (*p
&& *p
!= '-')
1171 while (*p
&& *p
!= separator
)
1173 while (*p
== separator
)
1177 if (process_arg(prevarg
, arg
, pass
))
1181 process_arg(arg
, NULL
, pass
);
1184 static void process_response_file(const char *file
, int pass
)
1187 FILE *f
= nasm_open_read(file
, NF_TEXT
);
1192 while (fgets(str
, sizeof str
, f
)) {
1193 process_args(str
, pass
);
1198 static void parse_cmdline(int argc
, char **argv
, int pass
)
1201 char *envreal
, *envcopy
= NULL
, *p
;
1204 /* Initialize all the warnings to their default state */
1205 for (i
= 0; i
< ERR_WARN_ALL
; i
++) {
1206 warning_state_init
[i
] = warning_state
[i
] =
1207 warnings
[i
].enabled
? WARN_ST_ENABLED
: 0;
1211 * First, process the NASMENV environment variable.
1213 envreal
= getenv("NASMENV");
1215 envcopy
= nasm_strdup(envreal
);
1216 process_args(envcopy
, pass
);
1221 * Now process the actual command line.
1226 if (argv
[0][0] == '@') {
1228 * We have a response file, so process this as a set of
1229 * arguments like the environment variable. This allows us
1230 * to have multiple arguments on a single line, which is
1231 * different to the -@resp file processing below for regular
1234 process_response_file(argv
[0]+1, pass
);
1238 if (!stopoptions
&& argv
[0][0] == '-' && argv
[0][1] == '@') {
1239 p
= get_param(argv
[0], argc
> 1 ? argv
[1] : NULL
, &advance
);
1241 rfile
= nasm_open_read(p
, NF_TEXT
);
1243 process_respfile(rfile
, pass
);
1246 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1247 "unable to open response file `%s'", p
);
1250 advance
= process_arg(argv
[0], argc
> 1 ? argv
[1] : NULL
, pass
);
1251 argv
+= advance
, argc
-= advance
;
1255 * Look for basic command line typos. This definitely doesn't
1256 * catch all errors, but it might help cases of fumbled fingers.
1262 nasm_fatal(ERR_NOFILE
| ERR_USAGE
, "no input file specified");
1264 else if ((errname
&& !strcmp(inname
, errname
)) ||
1265 (outname
&& !strcmp(inname
, outname
)) ||
1266 (listname
&& !strcmp(inname
, listname
)) ||
1267 (depend_file
&& !strcmp(inname
, depend_file
)))
1268 nasm_fatal(ERR_USAGE
, "will not overwrite input file");
1271 error_file
= nasm_open_write(errname
, NF_TEXT
);
1273 error_file
= stderr
; /* Revert to default! */
1274 nasm_fatal(ERR_NOFILE
| ERR_USAGE
,
1275 "cannot open file `%s' for error messages",
1281 static void assemble_file(const char *fname
, StrList
**depend_ptr
)
1288 uint64_t prev_offset_changed
;
1289 unsigned int stall_count
= 0; /* Make sure we make forward progress... */
1295 if (!iflag_cpu_level_ok(&cmd_cpu
, IF_386
))
1296 nasm_fatal(0, "command line: 32-bit segment size requires a higher cpu");
1299 if (!iflag_cpu_level_ok(&cmd_cpu
, IF_X86_64
))
1300 nasm_fatal(0, "command line: 64-bit segment size requires a higher cpu");
1307 pass_max
= prev_offset_changed
= (INT_MAX
>> 1) + 2; /* Almost unlimited */
1308 for (passn
= 1; pass0
<= 2; passn
++) {
1311 pass1
= pass0
== 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1312 pass2
= passn
> 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1313 /* pass0 0, 0, 0, ..., 1, 2 */
1315 def_label
= passn
> 1 ? redefine_label
: define_label
;
1317 globalbits
= cmd_sb
; /* set 'bits' to command line default */
1320 lfmt
->init(listname
);
1321 } else if (passn
== 1 && listname
) {
1322 /* Remove the list file in case we die before the output pass */
1325 in_absolute
= false;
1326 global_offset_changed
= 0; /* set by redefine_label */
1327 location
.segment
= ofmt
->section(NULL
, pass2
, &globalbits
);
1329 saa_rewind(forwrefs
);
1330 forwref
= saa_rstruct(forwrefs
);
1332 offsets
= raa_init();
1334 preproc
->reset(fname
, pass1
, pass1
== 2 ? depend_ptr
: NULL
);
1336 /* Revert all warnings to the default state */
1337 memcpy(warning_state
, warning_state_init
, sizeof warning_state
);
1341 location
.known
= true;
1342 location
.offset
= offs
= get_curr_offs();
1344 while ((line
= preproc
->getline())) {
1348 * Here we parse our directives; this is not handled by the
1351 if (process_directives(line
))
1352 goto end_of_line
; /* Just do final cleanup */
1354 /* Not a directive, or even something that starts with [ */
1356 parse_line(pass1
, line
, &output_ins
, def_label
);
1358 if (optimizing
> 0) {
1359 if (forwref
!= NULL
&& globallineno
== forwref
->lineno
) {
1360 output_ins
.forw_ref
= true;
1362 output_ins
.oprs
[forwref
->operand
].opflags
|= OPFLAG_FORWARD
;
1363 forwref
= saa_rstruct(forwrefs
);
1364 } while (forwref
!= NULL
1365 && forwref
->lineno
== globallineno
);
1367 output_ins
.forw_ref
= false;
1369 if (output_ins
.forw_ref
) {
1371 for (i
= 0; i
< output_ins
.operands
; i
++) {
1372 if (output_ins
.oprs
[i
].opflags
& OPFLAG_FORWARD
) {
1373 struct forwrefinfo
*fwinf
= (struct forwrefinfo
*)saa_wstruct(forwrefs
);
1374 fwinf
->lineno
= globallineno
;
1383 if (output_ins
.opcode
== I_EQU
) {
1386 * Special `..' EQUs get processed in pass two,
1387 * except `..@' macro-processor EQUs which are done
1388 * in the normal place.
1390 if (!output_ins
.label
)
1391 nasm_error(ERR_NONFATAL
,
1392 "EQU not preceded by label");
1394 else if (output_ins
.label
[0] != '.' ||
1395 output_ins
.label
[1] != '.' ||
1396 output_ins
.label
[2] == '@') {
1397 if (output_ins
.operands
== 1 &&
1398 (output_ins
.oprs
[0].type
& IMMEDIATE
) &&
1399 output_ins
.oprs
[0].wrt
== NO_SEG
) {
1400 bool isext
= !!(output_ins
.oprs
[0].opflags
& OPFLAG_EXTERN
);
1401 def_label(output_ins
.label
,
1402 output_ins
.oprs
[0].segment
,
1403 output_ins
.oprs
[0].offset
, NULL
,
1405 } else if (output_ins
.operands
== 2
1406 && (output_ins
.oprs
[0].type
& IMMEDIATE
)
1407 && (output_ins
.oprs
[0].type
& COLON
)
1408 && output_ins
.oprs
[0].segment
== NO_SEG
1409 && output_ins
.oprs
[0].wrt
== NO_SEG
1410 && (output_ins
.oprs
[1].type
& IMMEDIATE
)
1411 && output_ins
.oprs
[1].segment
== NO_SEG
1412 && output_ins
.oprs
[1].wrt
== NO_SEG
) {
1413 def_label(output_ins
.label
,
1414 output_ins
.oprs
[0].offset
| SEG_ABS
,
1415 output_ins
.oprs
[1].offset
,
1416 NULL
, false, false);
1418 nasm_error(ERR_NONFATAL
,
1419 "bad syntax for EQU");
1423 * Special `..' EQUs get processed here, except
1424 * `..@' macro processor EQUs which are done above.
1426 if (output_ins
.label
[0] == '.' &&
1427 output_ins
.label
[1] == '.' &&
1428 output_ins
.label
[2] != '@') {
1429 if (output_ins
.operands
== 1 &&
1430 (output_ins
.oprs
[0].type
& IMMEDIATE
)) {
1431 define_label(output_ins
.label
,
1432 output_ins
.oprs
[0].segment
,
1433 output_ins
.oprs
[0].offset
,
1434 NULL
, false, false);
1435 } else if (output_ins
.operands
== 2
1436 && (output_ins
.oprs
[0].type
& IMMEDIATE
)
1437 && (output_ins
.oprs
[0].type
& COLON
)
1438 && output_ins
.oprs
[0].segment
== NO_SEG
1439 && (output_ins
.oprs
[1].type
& IMMEDIATE
)
1440 && output_ins
.oprs
[1].segment
== NO_SEG
) {
1441 define_label(output_ins
.label
,
1442 output_ins
.oprs
[0].offset
| SEG_ABS
,
1443 output_ins
.oprs
[1].offset
,
1444 NULL
, false, false);
1446 nasm_error(ERR_NONFATAL
,
1447 "bad syntax for EQU");
1450 } else { /* instruction isn't an EQU */
1453 nasm_assert(output_ins
.times
>= 0);
1455 for (n
= 1; n
<= output_ins
.times
; n
++) {
1457 int64_t l
= insn_size(location
.segment
, offs
,
1458 globalbits
, &output_ins
);
1460 /* if (using_debug_info) && output_ins.opcode != -1) */
1461 if (using_debug_info
)
1462 { /* fbk 03/25/01 */
1463 /* this is done here so we can do debug type info */
1465 TYS_ELEMENTS(output_ins
.operands
);
1466 switch (output_ins
.opcode
) {
1469 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_BYTE
;
1473 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_WORD
;
1477 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_DWORD
;
1481 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_QWORD
;
1485 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_TBYTE
;
1489 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_OWORD
;
1493 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_YWORD
;
1497 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_ZWORD
;
1500 typeinfo
|= TY_BYTE
;
1503 typeinfo
|= TY_WORD
;
1506 if (output_ins
.eops_float
)
1507 typeinfo
|= TY_FLOAT
;
1509 typeinfo
|= TY_DWORD
;
1512 typeinfo
|= TY_QWORD
;
1515 typeinfo
|= TY_TBYTE
;
1518 typeinfo
|= TY_OWORD
;
1521 typeinfo
|= TY_YWORD
;
1524 typeinfo
|= TY_ZWORD
;
1527 typeinfo
= TY_LABEL
;
1531 dfmt
->debug_typevalue(typeinfo
);
1535 * For INCBIN, let the code in assemble
1536 * handle TIMES, so we don't have to read the
1537 * input file over and over.
1541 set_curr_offs(offs
);
1544 * else l == -1 => invalid instruction, which will be
1545 * flagged as an error on pass 2
1549 lfmt
->uplevel(LIST_TIMES
);
1550 offs
+= assemble(location
.segment
, offs
,
1551 globalbits
, &output_ins
);
1552 set_curr_offs(offs
);
1556 if (output_ins
.times
> 1)
1557 lfmt
->downlevel(LIST_TIMES
);
1559 cleanup_insn(&output_ins
);
1563 location
.offset
= offs
= get_curr_offs();
1564 } /* end while (line = preproc->getline... */
1566 if (pass0
== 2 && global_offset_changed
&& !terminate_after_phase
)
1567 nasm_error(ERR_NONFATAL
,
1568 "phase error detected at end of assembly.");
1571 preproc
->cleanup(1);
1573 if ((passn
> 1 && !global_offset_changed
) || pass0
== 2) {
1575 } else if (global_offset_changed
&&
1576 global_offset_changed
< prev_offset_changed
) {
1577 prev_offset_changed
= global_offset_changed
;
1583 if (terminate_after_phase
)
1586 if ((stall_count
> 997U) || (passn
>= pass_max
)) {
1587 /* We get here if the labels don't converge
1588 * Example: FOO equ FOO + 1
1590 nasm_error(ERR_NONFATAL
,
1591 "Can't find valid values for all labels "
1592 "after %d passes, giving up.", passn
);
1593 nasm_error(ERR_NONFATAL
,
1594 "Possible causes: recursive EQUs, macro abuse.");
1599 preproc
->cleanup(0);
1601 if (!terminate_after_phase
&& opt_verbose_info
) {
1602 /* -On and -Ov switches */
1603 fprintf(stdout
, "info: assembly required 1+%d+1 passes\n", passn
-3);
1608 * gnu style error reporting
1609 * This function prints an error message to error_file in the
1610 * style used by GNU. An example would be:
1611 * file.asm:50: error: blah blah blah
1612 * where file.asm is the name of the file, 50 is the line number on
1613 * which the error occurs (or is detected) and "error:" is one of
1614 * the possible optional diagnostics -- it can be "error" or "warning"
1615 * or something else. Finally the line terminates with the actual
1618 * @param severity the severity of the warning or error
1619 * @param fmt the printf style format string
1621 static void nasm_verror_gnu(int severity
, const char *fmt
, va_list ap
)
1623 const char *currentfile
= NULL
;
1626 if (is_suppressed_warning(severity
))
1629 if (!(severity
& ERR_NOFILE
)) {
1630 src_get(&lineno
, ¤tfile
);
1631 if (!currentfile
|| (severity
& ERR_TOPFILE
)) {
1632 currentfile
= inname
[0] ? inname
: outname
[0] ? outname
: NULL
;
1637 if (!skip_this_pass(severity
)) {
1639 fprintf(error_file
, "%s:", currentfile
? currentfile
: "nasm");
1641 fprintf(error_file
, "%s:%"PRId32
": ", currentfile
, lineno
);
1644 nasm_verror_common(severity
, fmt
, ap
);
1648 * MS style error reporting
1649 * This function prints an error message to error_file in the
1650 * style used by Visual C and some other Microsoft tools. An example
1652 * file.asm(50) : error: blah blah blah
1653 * where file.asm is the name of the file, 50 is the line number on
1654 * which the error occurs (or is detected) and "error:" is one of
1655 * the possible optional diagnostics -- it can be "error" or "warning"
1656 * or something else. Finally the line terminates with the actual
1659 * @param severity the severity of the warning or error
1660 * @param fmt the printf style format string
1662 static void nasm_verror_vc(int severity
, const char *fmt
, va_list ap
)
1664 const char *currentfile
= NULL
;
1667 if (is_suppressed_warning(severity
))
1670 if (!(severity
& ERR_NOFILE
))
1671 src_get(&lineno
, ¤tfile
);
1673 if (!skip_this_pass(severity
)) {
1675 fprintf(error_file
, "%s(%"PRId32
") : ", currentfile
, lineno
);
1677 fputs("nasm: ", error_file
);
1681 nasm_verror_common(severity
, fmt
, ap
);
1685 * check to see if this is a suppressable warning
1687 static inline bool is_valid_warning(int severity
)
1689 /* Not a warning at all */
1690 if ((severity
& ERR_MASK
) != ERR_WARNING
)
1693 return WARN_IDX(severity
) < ERR_WARN_ALL
;
1697 * check for suppressed warning
1698 * checks for suppressed warning or pass one only warning and we're
1701 * @param severity the severity of the warning or error
1702 * @return true if we should abort error/warning printing
1704 static bool is_suppressed_warning(int severity
)
1706 /* Might be a warning but suppresed explicitly */
1707 if (is_valid_warning(severity
))
1708 return !(warning_state
[WARN_IDX(severity
)] & WARN_ST_ENABLED
);
1713 static bool warning_is_error(int severity
)
1715 if (is_valid_warning(severity
))
1716 return !!(warning_state
[WARN_IDX(severity
)] & WARN_ST_ERROR
);
1721 static bool skip_this_pass(int severity
)
1724 * See if it's a pass-specific error or warning which should be skipped.
1725 * We cannot skip errors stronger than ERR_NONFATAL as by definition
1726 * they cannot be resumed from.
1728 if ((severity
& ERR_MASK
) > ERR_NONFATAL
)
1732 * passn is 1 on the very first pass only.
1733 * pass0 is 2 on the code-generation (final) pass only.
1734 * These are the passes we care about in this case.
1736 return (((severity
& ERR_PASS1
) && passn
!= 1) ||
1737 ((severity
& ERR_PASS2
) && pass0
!= 2));
1741 * common error reporting
1742 * This is the common back end of the error reporting schemes currently
1743 * implemented. It prints the nature of the warning and then the
1744 * specific error message to error_file and may or may not return. It
1745 * doesn't return if the error severity is a "panic" or "debug" type.
1747 * @param severity the severity of the warning or error
1748 * @param fmt the printf style format string
1750 static void nasm_verror_common(int severity
, const char *fmt
, va_list args
)
1755 switch (severity
& (ERR_MASK
|ERR_NO_SEVERITY
)) {
1776 vsnprintf(msg
, sizeof msg
- 64, fmt
, args
);
1777 if (is_valid_warning(severity
) && WARN_IDX(severity
) != ERR_WARN_OTHER
) {
1778 char *p
= strchr(msg
, '\0');
1779 snprintf(p
, 64, " [-w+%s]", warnings
[WARN_IDX(severity
)].name
);
1782 if (!skip_this_pass(severity
))
1783 fprintf(error_file
, "%s%s\n", pfx
, msg
);
1785 /* Are we recursing from error_list_macros? */
1786 if (severity
& ERR_PP_LISTMACRO
)
1790 * Don't suppress this with skip_this_pass(), or we don't get
1791 * pass1 or preprocessor warnings in the list file
1793 lfmt
->error(severity
, pfx
, msg
);
1795 if (skip_this_pass(severity
))
1798 if (severity
& ERR_USAGE
)
1801 preproc
->error_list_macros(severity
);
1803 switch (severity
& ERR_MASK
) {
1805 /* no further action, by definition */
1808 /* Treat warnings as errors */
1809 if (warning_is_error(severity
))
1810 terminate_after_phase
= true;
1813 terminate_after_phase
= true;
1823 exit(1); /* instantly die */
1824 break; /* placate silly compilers */
1829 abort(); /* halt, catch fire, dump core/stop debugger */
1841 static void usage(void)
1843 fputs("type `nasm -h' for help\n", error_file
);