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);
85 static void help(char xopt
);
87 static bool using_debug_info
, opt_verbose_info
;
88 static const char *debug_format
;
90 #ifndef ABORT_ON_PANIC
91 # define ABORT_ON_PANIC 0
93 static bool abort_on_panic
= ABORT_ON_PANIC
;
96 bool tasm_compatible_mode
= false;
99 static int pass1
, pass2
; /* XXX: Get rid of these, they are redundant */
103 struct compile_time official_compile_time
;
107 static const char *listname
;
108 static const char *errname
;
110 static int64_t globallineno
; /* for forward-reference tracking */
112 /* static int pass = 0; */
113 const struct ofmt
*ofmt
= &OF_DEFAULT
;
114 const struct ofmt_alias
*ofmt_alias
= NULL
;
115 const struct dfmt
*dfmt
;
117 static FILE *error_file
; /* Where to write error messages */
120 struct optimization optimizing
=
121 { MAX_OPTIMIZE
, OPTIM_ALL_ENABLED
}; /* number of optimization passes to take */
122 static int cmd_sb
= 16; /* by default */
125 static iflag_t cmd_cpu
;
127 struct location location
;
128 bool in_absolute
; /* Flag we are in ABSOLUTE seg */
129 struct location absolute
; /* Segment/offset inside ABSOLUTE */
131 static struct RAA
*offsets
;
133 static struct SAA
*forwrefs
; /* keep track of forward references */
134 static const struct forwrefinfo
*forwref
;
136 static const struct preproc_ops
*preproc
;
137 static StrList
*include_path
;
139 #define OP_NORMAL (1u << 0)
140 #define OP_PREPROCESS (1u << 1)
141 #define OP_DEPEND (1u << 2)
143 static unsigned int operating_mode
;
145 /* Dependency flags */
146 static bool depend_emit_phony
= false;
147 static bool depend_missing_ok
= false;
148 static const char *depend_target
= NULL
;
149 static const char *depend_file
= NULL
;
150 StrList
*depend_list
;
152 static bool want_usage
;
153 static bool terminate_after_phase
;
154 bool user_nolist
= false;
156 static char *quote_for_pmake(const char *str
);
157 static char *quote_for_wmake(const char *str
);
158 static char *(*quote_for_make
)(const char *) = quote_for_pmake
;
161 * Execution limits that can be set via a command-line option or %pragma
164 #define LIMIT_MAX_VAL (INT64_MAX >> 1) /* Effectively unlimited */
166 int64_t nasm_limit
[LIMIT_MAX
+1] =
167 { LIMIT_MAX_VAL
, 1000, 1000000, 1000000, 1000000, 2000000000 };
173 static const struct limit_info limit_info
[LIMIT_MAX
+1] = {
174 { "passes", "total number of passes" },
175 { "stalled-passes", "number of passes without forward progress" },
176 { "macro-levels", "levels of macro expansion"},
177 { "rep", "%rep count" },
178 { "eval", "expression evaluation descent"},
179 { "lines", "total source lines processed"}
182 enum directive_result
183 nasm_set_limit(const char *limit
, const char *valstr
)
190 for (i
= 0; i
<= LIMIT_MAX
; i
++) {
191 if (!nasm_stricmp(limit
, limit_info
[i
].name
))
196 errlevel
= ERR_WARNING
|ERR_NOFILE
|ERR_USAGE
;
198 errlevel
= ERR_WARNING
|ERR_PASS1
|ERR_WARN_UNKNOWN_PRAGMA
;
199 nasm_error(errlevel
, "unknown limit: `%s'", limit
);
203 if (!nasm_stricmp(valstr
, "unlimited")) {
206 val
= readnum(valstr
, &rn_error
);
207 if (rn_error
|| val
< 0) {
209 errlevel
= ERR_WARNING
|ERR_NOFILE
|ERR_USAGE
;
211 errlevel
= ERR_WARNING
|ERR_PASS1
|ERR_WARN_BAD_PRAGMA
;
212 nasm_error(errlevel
, "invalid limit value: `%s'", limit
);
215 if (val
> LIMIT_MAX_VAL
)
223 int64_t switch_segment(int32_t segment
)
225 location
.segment
= segment
;
226 if (segment
== NO_SEG
) {
227 location
.offset
= absolute
.offset
;
230 location
.offset
= raa_read(offsets
, segment
);
233 return location
.offset
;
236 static void set_curr_offs(int64_t l_off
)
239 absolute
.offset
= l_off
;
241 offsets
= raa_write(offsets
, location
.segment
, l_off
);
244 static void increment_offset(int64_t delta
)
246 if (unlikely(delta
== 0))
249 location
.offset
+= delta
;
250 set_curr_offs(location
.offset
);
253 static void nasm_fputs(const char *line
, FILE * outfile
)
256 fputs(line
, outfile
);
263 * Define system-defined macros that are not part of
264 * macros/standard.mac.
266 static void define_macros(void)
268 const struct compile_time
* const oct
= &official_compile_time
;
271 if (oct
->have_local
) {
272 strftime(temp
, sizeof temp
, "__DATE__=\"%Y-%m-%d\"", &oct
->local
);
273 preproc
->pre_define(temp
);
274 strftime(temp
, sizeof temp
, "__DATE_NUM__=%Y%m%d", &oct
->local
);
275 preproc
->pre_define(temp
);
276 strftime(temp
, sizeof temp
, "__TIME__=\"%H:%M:%S\"", &oct
->local
);
277 preproc
->pre_define(temp
);
278 strftime(temp
, sizeof temp
, "__TIME_NUM__=%H%M%S", &oct
->local
);
279 preproc
->pre_define(temp
);
283 strftime(temp
, sizeof temp
, "__UTC_DATE__=\"%Y-%m-%d\"", &oct
->gm
);
284 preproc
->pre_define(temp
);
285 strftime(temp
, sizeof temp
, "__UTC_DATE_NUM__=%Y%m%d", &oct
->gm
);
286 preproc
->pre_define(temp
);
287 strftime(temp
, sizeof temp
, "__UTC_TIME__=\"%H:%M:%S\"", &oct
->gm
);
288 preproc
->pre_define(temp
);
289 strftime(temp
, sizeof temp
, "__UTC_TIME_NUM__=%H%M%S", &oct
->gm
);
290 preproc
->pre_define(temp
);
293 if (oct
->have_posix
) {
294 snprintf(temp
, sizeof temp
, "__POSIX_TIME__=%"PRId64
, oct
->posix
);
295 preproc
->pre_define(temp
);
299 * In case if output format is defined by alias
300 * we have to put shortname of the alias itself here
301 * otherwise ABI backward compatibility gets broken.
303 snprintf(temp
, sizeof(temp
), "__OUTPUT_FORMAT__=%s",
304 ofmt_alias
? ofmt_alias
->shortname
: ofmt
->shortname
);
305 preproc
->pre_define(temp
);
308 * Output-format specific macros.
311 preproc
->extra_stdmac(ofmt
->stdmac
);
314 * Debug format, if any
316 if (dfmt
!= &null_debug_form
) {
317 snprintf(temp
, sizeof(temp
), "__DEBUG_FORMAT__=%s", dfmt
->shortname
);
318 preproc
->pre_define(temp
);
323 * Initialize the preprocessor, set up the include path, and define
324 * the system-included macros. This is called between passes 1 and 2
325 * of parsing the command options; ofmt and dfmt are defined at this
328 * Command-line specified preprocessor directives (-p, -d, -u,
329 * --pragma, --before) are processed after this function.
331 static void preproc_init(StrList
*list
)
333 struct strlist_entry
*l
;
338 list_for_each(l
, list
->head
)
339 preproc
->include_path(l
->str
);
342 static void emit_dependencies(StrList
*list
)
346 bool wmake
= (quote_for_make
== quote_for_wmake
);
347 const char *wrapstr
, *nulltarget
;
348 struct strlist_entry
*l
;
353 wrapstr
= wmake
? " &\n " : " \\\n ";
354 nulltarget
= wmake
? "\t%null\n" : "";
356 if (depend_file
&& strcmp(depend_file
, "-")) {
357 deps
= nasm_open_write(depend_file
, NF_TEXT
);
359 nasm_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
360 "unable to write dependency file `%s'", depend_file
);
367 linepos
= fprintf(deps
, "%s :", depend_target
);
368 list_for_each(l
, list
->head
) {
369 char *file
= quote_for_make(l
->str
);
371 if (linepos
+ len
> 62 && linepos
> 1) {
372 fputs(wrapstr
, deps
);
375 fprintf(deps
, " %s", file
);
379 fprintf(deps
, "\n\n");
381 list_for_each(l
, list
->head
) {
382 if (depend_emit_phony
) {
383 char *file
= quote_for_make(l
->str
);
384 fprintf(deps
, "%s :\n%s\n", file
, nulltarget
);
395 /* Convert a struct tm to a POSIX-style time constant */
396 static int64_t make_posix_time(const struct tm
*tm
)
399 int64_t y
= tm
->tm_year
;
401 /* See IEEE 1003.1:2004, section 4.14 */
403 t
= (y
-70)*365 + (y
-69)/4 - (y
-1)/100 + (y
+299)/400;
415 static void timestamp(void)
417 struct compile_time
* const oct
= &official_compile_time
;
418 const struct tm
*tp
, *best_gm
;
424 tp
= localtime(&oct
->t
);
427 best_gm
= &oct
->local
;
428 oct
->have_local
= true;
431 tp
= gmtime(&oct
->t
);
436 if (!oct
->have_local
)
437 oct
->local
= oct
->gm
;
439 oct
->gm
= oct
->local
;
443 oct
->posix
= make_posix_time(best_gm
);
444 oct
->have_posix
= true;
448 int main(int argc
, char **argv
)
452 iflag_set_default_cpu(&cpu
);
453 iflag_set_default_cpu(&cmd_cpu
);
455 include_path
= strlist_allocate();
458 want_usage
= terminate_after_phase
= false;
459 nasm_set_verror(nasm_verror_gnu
);
467 * We must call init_labels() before the command line parsing,
468 * because we may be setting prefixes/suffixes from the command
473 offsets
= raa_init();
474 forwrefs
= saa_init((int32_t)sizeof(struct forwrefinfo
));
477 operating_mode
= OP_NORMAL
;
479 parse_cmdline(argc
, argv
, 1);
480 if (terminate_after_phase
) {
486 /* At this point we have ofmt and the name of the desired debug format */
487 if (!using_debug_info
) {
488 /* No debug info, redirect to the null backend (empty stubs) */
489 dfmt
= &null_debug_form
;
490 } else if (!debug_format
) {
491 /* Default debug format for this backend */
492 dfmt
= ofmt
->default_dfmt
;
494 dfmt
= dfmt_find(ofmt
, debug_format
);
496 nasm_fatal_fl(ERR_NOFILE
| ERR_USAGE
,
497 "unrecognized debug format `%s' for"
498 " output format `%s'",
499 debug_format
, ofmt
->shortname
);
503 preproc_init(include_path
);
504 strlist_free(include_path
);
507 parse_cmdline(argc
, argv
, 2);
508 if (terminate_after_phase
) {
514 /* Save away the default state of warnings */
515 memcpy(warning_state_init
, warning_state
, sizeof warning_state
);
518 * If no output file name provided and this
519 * is a preprocess mode, we're perfectly
520 * fine to output into stdout.
523 if (!(operating_mode
& OP_PREPROCESS
))
524 outname
= filename_set_extension(inname
, ofmt
->extension
);
527 if (depend_file
|| (operating_mode
& OP_DEPEND
))
528 depend_list
= strlist_allocate();
531 depend_target
= quote_for_make(outname
);
533 if (operating_mode
& OP_DEPEND
) {
536 if (depend_missing_ok
)
537 preproc
->include_path(NULL
); /* "assume generated" */
539 preproc
->reset(inname
, 0, depend_list
);
541 while ((line
= preproc
->getline()))
544 } else if (operating_mode
& OP_PREPROCESS
) {
546 const char *file_name
= NULL
;
547 int32_t prior_linnum
= 0;
551 ofile
= nasm_open_write(outname
, NF_TEXT
);
553 nasm_fatal_fl(ERR_NOFILE
,
554 "unable to open output file `%s'",
559 location
.known
= false;
562 preproc
->reset(inname
, 3, depend_list
);
564 /* Revert all warnings to the default state */
565 memcpy(warning_state
, warning_state_init
, sizeof warning_state
);
567 while ((line
= preproc
->getline())) {
569 * We generate %line directives if needed for later programs
571 int32_t linnum
= prior_linnum
+= lineinc
;
572 int altline
= src_get(&linnum
, &file_name
);
574 if (altline
== 1 && lineinc
== 1)
575 nasm_fputs("", ofile
);
577 lineinc
= (altline
!= -1 || lineinc
!= 1);
578 fprintf(ofile
? ofile
: stdout
,
579 "%%line %"PRId32
"+%d %s\n", linnum
, lineinc
,
582 prior_linnum
= linnum
;
584 nasm_fputs(line
, ofile
);
590 if (ofile
&& terminate_after_phase
&& !keep_all
)
595 if (operating_mode
& OP_NORMAL
) {
596 ofile
= nasm_open_write(outname
, (ofmt
->flags
& OFMT_TEXT
) ? NF_TEXT
: NF_BINARY
);
598 nasm_fatal_fl(ERR_NOFILE
,
599 "unable to open output file `%s'", outname
);
604 assemble_file(inname
, depend_list
);
606 if (!terminate_after_phase
) {
611 nasm_error(ERR_NONFATAL
|ERR_NOFILE
,
612 "write error on output file `%s'", outname
);
613 terminate_after_phase
= true;
619 if (terminate_after_phase
&& !keep_all
)
625 if (depend_list
&& !terminate_after_phase
)
626 emit_dependencies(depend_list
);
637 return terminate_after_phase
;
641 * Get a parameter for a command line option.
642 * First arg must be in the form of e.g. -f...
644 static char *get_param(char *p
, char *q
, bool *advance
)
647 if (p
[2]) /* the parameter's in the option */
648 return nasm_skip_spaces(p
+ 2);
653 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
654 "option `-%c' requires an argument", p
[1]);
661 static void copy_filename(const char **dst
, const char *src
, const char *what
)
664 nasm_fatal("more than one %s file specified: %s\n", what
, src
);
666 *dst
= nasm_strdup(src
);
670 * Convert a string to a POSIX make-safe form
672 static char *quote_for_pmake(const char *str
)
677 size_t n
= 1; /* Terminating zero */
683 for (p
= str
; *p
; p
++) {
687 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
707 /* Convert N backslashes at the end of filename to 2N backslashes */
711 os
= q
= nasm_malloc(n
);
714 for (p
= str
; *p
; p
++) {
752 * Convert a string to a Watcom make-safe form
754 static char *quote_for_wmake(const char *str
)
760 size_t n
= 1; /* Terminating zero */
765 for (p
= str
; *p
; p
++) {
790 os
= q
= nasm_malloc(n
);
795 for (p
= str
; *p
; p
++) {
834 enum text_options opt
;
838 static const struct textargs textopts
[] = {
839 {"v", OPT_VERSION
, false, 0},
840 {"version", OPT_VERSION
, false, 0},
841 {"help", OPT_HELP
, false, 0},
842 {"abort-on-panic", OPT_ABORT_ON_PANIC
, false, 0},
843 {"prefix", OPT_MANGLE
, true, LM_GPREFIX
},
844 {"postfix", OPT_MANGLE
, true, LM_GSUFFIX
},
845 {"gprefix", OPT_MANGLE
, true, LM_GPREFIX
},
846 {"gpostfix", OPT_MANGLE
, true, LM_GSUFFIX
},
847 {"lprefix", OPT_MANGLE
, true, LM_LPREFIX
},
848 {"lpostfix", OPT_MANGLE
, true, LM_LSUFFIX
},
849 {"include", OPT_INCLUDE
, true, 0},
850 {"pragma", OPT_PRAGMA
, true, 0},
851 {"before", OPT_BEFORE
, true, 0},
852 {"limit-", OPT_LIMIT
, true, 0},
853 {"keep-all", OPT_KEEP_ALL
, false, 0},
854 {NULL
, OPT_BOGUS
, false, 0}
857 static void show_version(void)
859 printf("NASM version %s compiled on %s%s\n",
860 nasm_version
, nasm_date
, nasm_compile_options
);
864 static bool stopoptions
= false;
865 static bool process_arg(char *p
, char *q
, int pass
)
868 bool advance
= false;
873 if (p
[0] == '-' && !stopoptions
) {
874 if (strchr("oOfpPdDiIlFXuUZwW", p
[1])) {
875 /* These parameters take values */
876 if (!(param
= get_param(p
, q
, &advance
)))
886 case 'o': /* output file */
888 copy_filename(&outname
, param
, "output");
891 case 'f': /* output format */
893 ofmt
= ofmt_find(param
, &ofmt_alias
);
895 nasm_fatal_fl(ERR_NOFILE
| ERR_USAGE
,
896 "unrecognised output format `%s' - "
897 "use -hf for a list", param
);
902 case 'O': /* Optimization level */
907 /* Naked -O == -Ox */
908 optimizing
.level
= MAX_OPTIMIZE
;
912 case '0': case '1': case '2': case '3': case '4':
913 case '5': case '6': case '7': case '8': case '9':
914 opt
= strtoul(param
, ¶m
, 10);
916 /* -O0 -> optimizing.level == -1, 0.98 behaviour */
917 /* -O1 -> optimizing.level == 0, 0.98.09 behaviour */
919 optimizing
.level
= opt
- 1;
921 optimizing
.level
= opt
;
927 opt_verbose_info
= true;
932 optimizing
.level
= MAX_OPTIMIZE
;
936 nasm_fatal("unknown optimization option -O%c\n",
941 if (optimizing
.level
> MAX_OPTIMIZE
)
942 optimizing
.level
= MAX_OPTIMIZE
;
947 case 'p': /* pre-include */
950 preproc
->pre_include(param
);
953 case 'd': /* pre-define */
956 preproc
->pre_define(param
);
959 case 'u': /* un-define */
962 preproc
->pre_undefine(param
);
965 case 'i': /* include search path */
968 strlist_add_string(include_path
, param
);
971 case 'l': /* listing file */
973 copy_filename(&listname
, param
, "listing");
976 case 'Z': /* error messages file */
978 copy_filename(&errname
, param
, "error");
981 case 'F': /* specify debug format */
983 using_debug_info
= true;
984 debug_format
= param
;
988 case 'X': /* specify error reporting format */
990 if (nasm_stricmp("vc", param
) == 0)
991 nasm_set_verror(nasm_verror_vc
);
992 else if (nasm_stricmp("gnu", param
) == 0)
993 nasm_set_verror(nasm_verror_gnu
);
995 nasm_fatal_fl(ERR_NOFILE
| ERR_USAGE
,
996 "unrecognized error reporting format `%s'",
1003 using_debug_info
= true;
1005 debug_format
= nasm_skip_spaces(p
+ 2);
1011 exit(0); /* never need usage message here */
1015 printf("\nvalid debug formats for '%s' output format are"
1016 " ('*' denotes default):\n", ofmt
->shortname
);
1017 dfmt_list(ofmt
, stdout
);
1023 tasm_compatible_mode
= true;
1030 case 'e': /* preprocess only */
1033 operating_mode
= OP_PREPROCESS
;
1036 case 'a': /* assemble only - don't preprocess */
1038 preproc
= &preproc_nop
;
1044 if (!set_warning_status(param
)) {
1045 nasm_error(ERR_WARNING
|ERR_NOFILE
|ERR_WARN_UNK_WARNING
,
1046 "unknown warning option: %s", param
);
1055 quote_for_make
= quote_for_wmake
;
1069 operating_mode
= OP_DEPEND
;
1072 operating_mode
= OP_DEPEND
;
1073 depend_missing_ok
= true;
1076 depend_emit_phony
= true;
1079 operating_mode
= OP_NORMAL
;
1092 depend_target
= quote_for_make(q
);
1096 /* handled in pass 1 */
1099 nasm_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
1100 "unknown dependency option `-M%c'", p
[2]);
1104 if (advance
&& (!q
|| !q
[0])) {
1105 nasm_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
1106 "option `-M%c' requires a parameter", p
[2]);
1113 const struct textargs
*tx
;
1119 if (!*p
) { /* -- => stop processing options */
1125 for (tx
= textopts
; tx
->label
; tx
++) {
1126 olen
= strlen(tx
->label
);
1131 if (nasm_memicmp(p
, tx
->label
, olen
))
1134 if (tx
->label
[olen
-1] == '-')
1135 break; /* Incomplete option */
1137 if (!p
[olen
] || p
[olen
] == '=')
1138 break; /* Complete option */
1142 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1143 "unrecognized option `--%s'", p
);
1146 eqsave
= param
= strchr(p
+olen
, '=');
1156 /* Note: a null string is a valid parameter */
1158 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1159 "option `--%s' requires an argument",
1165 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1166 "option `--%s' does not take an argument",
1176 case OPT_ABORT_ON_PANIC
:
1177 abort_on_panic
= true;
1181 set_label_mangle(tx
->pvt
, param
);
1185 preproc
->pre_include(q
);
1189 preproc
->pre_command("pragma", param
);
1193 preproc
->pre_command(NULL
, param
);
1197 nasm_set_limit(p
+olen
, param
);
1210 *eqsave
= '='; /* Restore = argument separator */
1216 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1217 "unrecognised option `-%c'", p
[1]);
1220 } else if (pass
== 2) {
1221 /* In theory we could allow multiple input files... */
1222 copy_filename(&inname
, p
, "input");
1228 #define ARG_BUF_DELTA 128
1230 static void process_respfile(FILE * rfile
, int pass
)
1232 char *buffer
, *p
, *q
, *prevarg
;
1233 int bufsize
, prevargsize
;
1235 bufsize
= prevargsize
= ARG_BUF_DELTA
;
1236 buffer
= nasm_malloc(ARG_BUF_DELTA
);
1237 prevarg
= nasm_malloc(ARG_BUF_DELTA
);
1240 while (1) { /* Loop to handle all lines in file */
1242 while (1) { /* Loop to handle long lines */
1243 q
= fgets(p
, bufsize
- (p
- buffer
), rfile
);
1247 if (p
> buffer
&& p
[-1] == '\n')
1249 if (p
- buffer
> bufsize
- 10) {
1251 offset
= p
- buffer
;
1252 bufsize
+= ARG_BUF_DELTA
;
1253 buffer
= nasm_realloc(buffer
, bufsize
);
1254 p
= buffer
+ offset
;
1258 if (!q
&& p
== buffer
) {
1260 process_arg(prevarg
, NULL
, pass
);
1267 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1268 * them are present at the end of the line.
1270 *(p
= &buffer
[strcspn(buffer
, "\r\n\032")]) = '\0';
1272 while (p
> buffer
&& nasm_isspace(p
[-1]))
1275 p
= nasm_skip_spaces(buffer
);
1277 if (process_arg(prevarg
, p
, pass
))
1280 if ((int) strlen(p
) > prevargsize
- 10) {
1281 prevargsize
+= ARG_BUF_DELTA
;
1282 prevarg
= nasm_realloc(prevarg
, prevargsize
);
1284 strncpy(prevarg
, p
, prevargsize
);
1288 /* Function to process args from a string of args, rather than the
1289 * argv array. Used by the environment variable and response file
1292 static void process_args(char *args
, int pass
)
1294 char *p
, *q
, *arg
, *prevarg
;
1295 char separator
= ' ';
1298 if (*p
&& *p
!= '-')
1303 while (*p
&& *p
!= separator
)
1305 while (*p
== separator
)
1309 if (process_arg(prevarg
, arg
, pass
))
1313 process_arg(arg
, NULL
, pass
);
1316 static void process_response_file(const char *file
, int pass
)
1319 FILE *f
= nasm_open_read(file
, NF_TEXT
);
1324 while (fgets(str
, sizeof str
, f
)) {
1325 process_args(str
, pass
);
1330 static void parse_cmdline(int argc
, char **argv
, int pass
)
1333 char *envreal
, *envcopy
= NULL
, *p
;
1336 /* Initialize all the warnings to their default state */
1337 for (i
= 0; i
< ERR_WARN_ALL
; i
++) {
1338 warning_state_init
[i
] = warning_state
[i
] =
1339 warnings
[i
].enabled
? WARN_ST_ENABLED
: 0;
1343 * First, process the NASMENV environment variable.
1345 envreal
= getenv("NASMENV");
1347 envcopy
= nasm_strdup(envreal
);
1348 process_args(envcopy
, pass
);
1353 * Now process the actual command line.
1358 if (argv
[0][0] == '@') {
1360 * We have a response file, so process this as a set of
1361 * arguments like the environment variable. This allows us
1362 * to have multiple arguments on a single line, which is
1363 * different to the -@resp file processing below for regular
1366 process_response_file(argv
[0]+1, pass
);
1370 if (!stopoptions
&& argv
[0][0] == '-' && argv
[0][1] == '@') {
1371 p
= get_param(argv
[0], argc
> 1 ? argv
[1] : NULL
, &advance
);
1373 rfile
= nasm_open_read(p
, NF_TEXT
);
1375 process_respfile(rfile
, pass
);
1378 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1379 "unable to open response file `%s'", p
);
1382 advance
= process_arg(argv
[0], argc
> 1 ? argv
[1] : NULL
, pass
);
1383 argv
+= advance
, argc
-= advance
;
1387 * Look for basic command line typos. This definitely doesn't
1388 * catch all errors, but it might help cases of fumbled fingers.
1394 nasm_fatal_fl(ERR_NOFILE
| ERR_USAGE
, "no input file specified");
1396 else if ((errname
&& !strcmp(inname
, errname
)) ||
1397 (outname
&& !strcmp(inname
, outname
)) ||
1398 (listname
&& !strcmp(inname
, listname
)) ||
1399 (depend_file
&& !strcmp(inname
, depend_file
)))
1400 nasm_fatal_fl(ERR_USAGE
, "will not overwrite input file");
1403 error_file
= nasm_open_write(errname
, NF_TEXT
);
1405 error_file
= stderr
; /* Revert to default! */
1406 nasm_fatal_fl(ERR_NOFILE
| ERR_USAGE
,
1407 "cannot open file `%s' for error messages",
1413 static void assemble_file(const char *fname
, StrList
*depend_list
)
1418 uint64_t prev_offset_changed
;
1419 int64_t stall_count
= 0; /* Make sure we make forward progress... */
1425 if (!iflag_cpu_level_ok(&cmd_cpu
, IF_386
))
1426 nasm_fatal("command line: 32-bit segment size requires a higher cpu");
1429 if (!iflag_cpu_level_ok(&cmd_cpu
, IF_X86_64
))
1430 nasm_fatal("command line: 64-bit segment size requires a higher cpu");
1437 prev_offset_changed
= nasm_limit
[LIMIT_PASSES
];
1438 for (passn
= 1; pass0
<= 2; passn
++) {
1439 pass1
= pass0
== 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1440 pass2
= passn
> 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1441 /* pass0 0, 0, 0, ..., 1, 2 */
1443 globalbits
= cmd_sb
; /* set 'bits' to command line default */
1446 lfmt
->init(listname
);
1447 } else if (passn
== 1 && listname
&& !keep_all
) {
1448 /* Remove the list file in case we die before the output pass */
1451 in_absolute
= false;
1452 global_offset_changed
= 0; /* set by redefine_label */
1454 saa_rewind(forwrefs
);
1455 forwref
= saa_rstruct(forwrefs
);
1457 offsets
= raa_init();
1459 location
.segment
= NO_SEG
;
1460 location
.offset
= 0;
1462 location
.known
= true;
1464 switch_segment(ofmt
->section(NULL
, pass2
, &globalbits
));
1465 preproc
->reset(fname
, pass1
, pass1
== 2 ? depend_list
: NULL
);
1467 /* Revert all warnings to the default state */
1468 memcpy(warning_state
, warning_state_init
, sizeof warning_state
);
1472 while ((line
= preproc
->getline())) {
1473 if (++globallineno
> nasm_limit
[LIMIT_LINES
])
1474 nasm_fatal("overall line count exceeds the maximum %"PRId64
"\n",
1475 nasm_limit
[LIMIT_LINES
]);
1478 * Here we parse our directives; this is not handled by the
1481 if (process_directives(line
))
1482 goto end_of_line
; /* Just do final cleanup */
1484 /* Not a directive, or even something that starts with [ */
1485 parse_line(pass1
, line
, &output_ins
);
1487 if (optimizing
.level
> 0) {
1488 if (forwref
!= NULL
&& globallineno
== forwref
->lineno
) {
1489 output_ins
.forw_ref
= true;
1491 output_ins
.oprs
[forwref
->operand
].opflags
|= OPFLAG_FORWARD
;
1492 forwref
= saa_rstruct(forwrefs
);
1493 } while (forwref
!= NULL
1494 && forwref
->lineno
== globallineno
);
1496 output_ins
.forw_ref
= false;
1498 if (output_ins
.forw_ref
) {
1500 for (i
= 0; i
< output_ins
.operands
; i
++) {
1501 if (output_ins
.oprs
[i
].opflags
& OPFLAG_FORWARD
) {
1502 struct forwrefinfo
*fwinf
= (struct forwrefinfo
*)saa_wstruct(forwrefs
);
1503 fwinf
->lineno
= globallineno
;
1512 if (output_ins
.opcode
== I_EQU
) {
1513 if (!output_ins
.label
) {
1514 nasm_error(ERR_NONFATAL
, "EQU not preceded by label");
1515 } else if (output_ins
.operands
== 1 &&
1516 (output_ins
.oprs
[0].type
& IMMEDIATE
) &&
1517 output_ins
.oprs
[0].wrt
== NO_SEG
) {
1518 define_label(output_ins
.label
,
1519 output_ins
.oprs
[0].segment
,
1520 output_ins
.oprs
[0].offset
, false);
1521 } else if (output_ins
.operands
== 2
1522 && (output_ins
.oprs
[0].type
& IMMEDIATE
)
1523 && (output_ins
.oprs
[0].type
& COLON
)
1524 && output_ins
.oprs
[0].segment
== NO_SEG
1525 && output_ins
.oprs
[0].wrt
== NO_SEG
1526 && (output_ins
.oprs
[1].type
& IMMEDIATE
)
1527 && output_ins
.oprs
[1].segment
== NO_SEG
1528 && output_ins
.oprs
[1].wrt
== NO_SEG
) {
1529 define_label(output_ins
.label
,
1530 output_ins
.oprs
[0].offset
| SEG_ABS
,
1531 output_ins
.oprs
[1].offset
, false);
1533 nasm_error(ERR_NONFATAL
, "bad syntax for EQU");
1535 } else { /* instruction isn't an EQU */
1538 nasm_assert(output_ins
.times
>= 0);
1540 for (n
= 1; n
<= output_ins
.times
; n
++) {
1542 int64_t l
= insn_size(location
.segment
,
1544 globalbits
, &output_ins
);
1546 /* if (using_debug_info) && output_ins.opcode != -1) */
1547 if (using_debug_info
)
1548 { /* fbk 03/25/01 */
1549 /* this is done here so we can do debug type info */
1551 TYS_ELEMENTS(output_ins
.operands
);
1552 switch (output_ins
.opcode
) {
1555 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_BYTE
;
1559 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_WORD
;
1563 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_DWORD
;
1567 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_QWORD
;
1571 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_TBYTE
;
1575 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_OWORD
;
1579 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_YWORD
;
1583 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_ZWORD
;
1586 typeinfo
|= TY_BYTE
;
1589 typeinfo
|= TY_WORD
;
1592 if (output_ins
.eops_float
)
1593 typeinfo
|= TY_FLOAT
;
1595 typeinfo
|= TY_DWORD
;
1598 typeinfo
|= TY_QWORD
;
1601 typeinfo
|= TY_TBYTE
;
1604 typeinfo
|= TY_OWORD
;
1607 typeinfo
|= TY_YWORD
;
1610 typeinfo
|= TY_ZWORD
;
1613 typeinfo
= TY_LABEL
;
1617 dfmt
->debug_typevalue(typeinfo
);
1621 * For INCBIN, let the code in assemble
1622 * handle TIMES, so we don't have to read the
1623 * input file over and over.
1626 increment_offset(l
);
1629 * else l == -1 => invalid instruction, which will be
1630 * flagged as an error on pass 2
1634 lfmt
->uplevel(LIST_TIMES
);
1635 increment_offset(assemble(location
.segment
,
1637 globalbits
, &output_ins
));
1641 if (output_ins
.times
> 1)
1642 lfmt
->downlevel(LIST_TIMES
);
1644 cleanup_insn(&output_ins
);
1648 } /* end while (line = preproc->getline... */
1650 if (global_offset_changed
&& !terminate_after_phase
) {
1653 nasm_error(ERR_WARNING
|ERR_WARN_PHASE
,
1654 "phase error during stabilization pass, hoping for the best");
1658 nasm_error(ERR_NONFATAL
,
1659 "phase error during code generation pass");
1663 /* This is normal, we'll keep going... */
1669 preproc
->cleanup(1);
1672 * Always run at least two optimization passes (pass0 == 0);
1673 * things like subsections will fail miserably without that.
1674 * Once we commit to a stabilization pass (pass0 == 1), we can't
1675 * go back, and if something goes bad, we can only hope
1676 * that we don't end up with a phase error at the end.
1678 if ((passn
> 1 && !global_offset_changed
) || pass0
> 0) {
1680 } else if (global_offset_changed
&&
1681 global_offset_changed
< prev_offset_changed
) {
1682 prev_offset_changed
= global_offset_changed
;
1688 if (terminate_after_phase
)
1691 if ((stall_count
> nasm_limit
[LIMIT_STALLED
]) ||
1692 (passn
>= nasm_limit
[LIMIT_PASSES
])) {
1693 /* We get here if the labels don't converge
1694 * Example: FOO equ FOO + 1
1696 nasm_error(ERR_NONFATAL
,
1697 "Can't find valid values for all labels "
1698 "after %"PRId64
" passes, giving up.", passn
);
1699 nasm_error(ERR_NONFATAL
,
1700 "Possible causes: recursive EQUs, macro abuse.");
1705 preproc
->cleanup(0);
1707 if (!terminate_after_phase
&& opt_verbose_info
) {
1708 /* -On and -Ov switches */
1709 fprintf(stdout
, "info: assembly required 1+%"PRId64
"+1 passes\n",
1715 * gnu style error reporting
1716 * This function prints an error message to error_file in the
1717 * style used by GNU. An example would be:
1718 * file.asm:50: error: blah blah blah
1719 * where file.asm is the name of the file, 50 is the line number on
1720 * which the error occurs (or is detected) and "error:" is one of
1721 * the possible optional diagnostics -- it can be "error" or "warning"
1722 * or something else. Finally the line terminates with the actual
1725 * @param severity the severity of the warning or error
1726 * @param fmt the printf style format string
1728 static void nasm_verror_gnu(int severity
, const char *fmt
, va_list ap
)
1730 const char *currentfile
= NULL
;
1733 if (is_suppressed_warning(severity
))
1736 if (!(severity
& ERR_NOFILE
)) {
1737 src_get(&lineno
, ¤tfile
);
1738 if (!currentfile
|| (severity
& ERR_TOPFILE
)) {
1739 currentfile
= inname
[0] ? inname
: outname
[0] ? outname
: NULL
;
1744 if (!skip_this_pass(severity
)) {
1746 fprintf(error_file
, "%s:", currentfile
? currentfile
: "nasm");
1748 fprintf(error_file
, "%s:%"PRId32
": ", currentfile
, lineno
);
1751 nasm_verror_common(severity
, fmt
, ap
);
1755 * MS style error reporting
1756 * This function prints an error message to error_file in the
1757 * style used by Visual C and some other Microsoft tools. An example
1759 * file.asm(50) : error: blah blah blah
1760 * where file.asm is the name of the file, 50 is the line number on
1761 * which the error occurs (or is detected) and "error:" is one of
1762 * the possible optional diagnostics -- it can be "error" or "warning"
1763 * or something else. Finally the line terminates with the actual
1766 * @param severity the severity of the warning or error
1767 * @param fmt the printf style format string
1769 static void nasm_verror_vc(int severity
, const char *fmt
, va_list ap
)
1771 const char *currentfile
= NULL
;
1774 if (is_suppressed_warning(severity
))
1777 if (!(severity
& ERR_NOFILE
))
1778 src_get(&lineno
, ¤tfile
);
1780 if (!skip_this_pass(severity
)) {
1782 fprintf(error_file
, "%s(%"PRId32
") : ", currentfile
, lineno
);
1784 fputs("nasm: ", error_file
);
1788 nasm_verror_common(severity
, fmt
, ap
);
1792 * check to see if this is a suppressable warning
1794 static inline bool is_valid_warning(int severity
)
1796 /* Not a warning at all */
1797 if ((severity
& ERR_MASK
) != ERR_WARNING
)
1800 return WARN_IDX(severity
) < ERR_WARN_ALL
;
1804 * check for suppressed warning
1805 * checks for suppressed warning or pass one only warning and we're
1808 * @param severity the severity of the warning or error
1809 * @return true if we should abort error/warning printing
1811 static bool is_suppressed_warning(int severity
)
1813 /* Might be a warning but suppresed explicitly */
1814 if (is_valid_warning(severity
) && !(severity
& ERR_USAGE
))
1815 return !(warning_state
[WARN_IDX(severity
)] & WARN_ST_ENABLED
);
1820 static bool warning_is_error(int severity
)
1822 if (is_valid_warning(severity
))
1823 return !!(warning_state
[WARN_IDX(severity
)] & WARN_ST_ERROR
);
1828 static bool skip_this_pass(int severity
)
1831 * See if it's a pass-specific error or warning which should be skipped.
1832 * We cannot skip errors stronger than ERR_NONFATAL as by definition
1833 * they cannot be resumed from.
1835 if ((severity
& ERR_MASK
) > ERR_NONFATAL
)
1839 * passn is 1 on the very first pass only.
1840 * pass0 is 2 on the code-generation (final) pass only.
1841 * These are the passes we care about in this case.
1843 return (((severity
& ERR_PASS1
) && passn
!= 1) ||
1844 ((severity
& ERR_PASS2
) && pass0
!= 2));
1848 * common error reporting
1849 * This is the common back end of the error reporting schemes currently
1850 * implemented. It prints the nature of the warning and then the
1851 * specific error message to error_file and may or may not return. It
1852 * doesn't return if the error severity is a "panic" or "debug" type.
1854 * @param severity the severity of the warning or error
1855 * @param fmt the printf style format string
1857 static void nasm_verror_common(int severity
, const char *fmt
, va_list args
)
1862 switch (severity
& (ERR_MASK
|ERR_NO_SEVERITY
)) {
1883 vsnprintf(msg
, sizeof msg
- 64, fmt
, args
);
1884 if (is_valid_warning(severity
) && WARN_IDX(severity
) != ERR_WARN_OTHER
) {
1885 char *p
= strchr(msg
, '\0');
1886 snprintf(p
, 64, " [-w+%s]", warnings
[WARN_IDX(severity
)].name
);
1889 if (!skip_this_pass(severity
))
1890 fprintf(error_file
, "%s%s\n", pfx
, msg
);
1892 /* Are we recursing from error_list_macros? */
1893 if (severity
& ERR_PP_LISTMACRO
)
1897 * Don't suppress this with skip_this_pass(), or we don't get
1898 * pass1 or preprocessor warnings in the list file
1900 lfmt
->error(severity
, pfx
, msg
);
1902 if (skip_this_pass(severity
))
1905 if (severity
& ERR_USAGE
)
1908 preproc
->error_list_macros(severity
);
1910 switch (severity
& ERR_MASK
) {
1912 /* no further action, by definition */
1915 /* Treat warnings as errors */
1916 if (warning_is_error(severity
))
1917 terminate_after_phase
= true;
1920 terminate_after_phase
= true;
1931 exit(1); /* instantly die */
1932 break; /* placate silly compilers */
1937 abort(); /* halt, catch fire, dump core/stop debugger */
1950 static void usage(void)
1952 fputs("type `nasm -h' for help\n", error_file
);
1955 static void help(const char xopt
)
1960 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
1962 " [options...] [--] filename\n"
1963 " or nasm -v (or --v) for version info\n\n"
1965 "Response files should contain command line parameters,\n"
1968 " -t assemble in SciTech TASM compatible mode\n");
1970 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
1971 " -a don't preprocess (assemble only)\n"
1972 " -M generate Makefile dependencies on stdout\n"
1973 " -MG d:o, missing files assumed generated\n"
1974 " -MF file set Makefile dependency file\n"
1975 " -MD file assemble and generate dependencies\n"
1976 " -MT file dependency target name\n"
1977 " -MQ file dependency target name (quoted)\n"
1978 " -MP emit phony target\n\n"
1979 " -Zfile redirect error messages to file\n"
1980 " -s redirect error messages to stdout\n\n"
1981 " -g generate debugging information\n\n"
1982 " -F format select a debugging format\n\n"
1983 " -gformat same as -g -F format\n\n"
1984 " -o outfile write output to an outfile\n\n"
1985 " -f format select an output format\n\n"
1986 " -l listfile write listing to a listfile\n\n"
1987 " -Ipath add a pathname to the include file path\n");
1989 (" -Olevel optimize opcodes, immediates and branch offsets\n"
1990 " -O0 no optimization\n"
1991 " -O1 minimal optimization\n"
1992 " -Ox multipass optimization (default)\n"
1993 " -Pfile pre-include a file (also --include)\n"
1994 " -Dmacro[=str] pre-define a macro\n"
1995 " -Umacro undefine a macro\n"
1996 " -Xformat specifiy error reporting format (gnu or vc)\n"
1997 " -w+foo enable warning foo (equiv. -Wfoo)\n"
1998 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
1999 " -w[+-]error[=foo]\n"
2000 " promote [specific] warnings to errors\n"
2001 " -h show invocation summary and exit (also --help)\n\n"
2002 " --pragma str pre-executes a specific %%pragma\n"
2003 " --before str add line (usually a preprocessor statement) before the input\n"
2004 " --prefix str prepend the given string to all the given string\n"
2005 " to all extern, common and global symbols (also --gprefix)\n"
2006 " --postfix str append the given string to all the given string\n"
2007 " to all extern, common and global symbols (also --gpostfix)\n"
2008 " --lprefix str prepend the given string to all other symbols\n"
2009 " --lpostfix str append the given string to all other symbols\n"
2010 " --keep-all output files will not be removed even if an error happens\n"
2011 " --limit-X val set execution limit X\n");
2013 for (i
= 0; i
<= LIMIT_MAX
; i
++) {
2014 printf(" %-15s %s (default ",
2015 limit_info
[i
].name
, limit_info
[i
].help
);
2016 if (nasm_limit
[i
] < LIMIT_MAX_VAL
) {
2017 printf("%"PRId64
")\n", nasm_limit
[i
]);
2019 printf("unlimited)\n");
2023 printf("\nWarnings for the -W/-w options:\n");
2025 for (i
= 0; i
<= ERR_WARN_ALL
; i
++)
2026 printf(" %-23s %s%s\n",
2027 warnings
[i
].name
, warnings
[i
].help
,
2028 i
== ERR_WARN_ALL
? "\n" :
2029 warnings
[i
].enabled
? " (default on)" :
2033 printf("valid output formats for -f are"
2034 " (`*' denotes default):\n");
2035 ofmt_list(ofmt
, stdout
);
2037 printf("For a list of valid output formats, use -hf.\n");
2038 printf("For a list of debug formats, use -f <format> -y.\n");