1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2017 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(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 bool tasm_compatible_mode
= false;
91 static int pass1
, pass2
; /* XXX: Get rid of these, they are redundant */
95 struct compile_time official_compile_time
;
97 static char inname
[FILENAME_MAX
];
98 static char outname
[FILENAME_MAX
];
99 static char listname
[FILENAME_MAX
];
100 static char errname
[FILENAME_MAX
];
101 static int globallineno
; /* for forward-reference tracking */
102 /* static int pass = 0; */
103 const struct ofmt
*ofmt
= &OF_DEFAULT
;
104 const struct ofmt_alias
*ofmt_alias
= NULL
;
105 const struct dfmt
*dfmt
;
107 static FILE *error_file
; /* Where to write error messages */
110 int optimizing
= MAX_OPTIMIZE
; /* number of optimization passes to take */
111 static int cmd_sb
= 16; /* by default */
114 static iflag_t cmd_cpu
;
116 struct location location
;
117 bool in_absolute
; /* Flag we are in ABSOLUTE seg */
118 struct location absolute
; /* Segment/offset inside ABSOLUTE */
120 static struct RAA
*offsets
;
122 static struct SAA
*forwrefs
; /* keep track of forward references */
123 static const struct forwrefinfo
*forwref
;
125 static const struct preproc_ops
*preproc
;
127 #define OP_NORMAL (1u << 0)
128 #define OP_PREPROCESS (1u << 1)
129 #define OP_DEPEND (1u << 2)
131 static unsigned int operating_mode
;
133 /* Dependency flags */
134 static bool depend_emit_phony
= false;
135 static bool depend_missing_ok
= false;
136 static const char *depend_target
= NULL
;
137 static const char *depend_file
= NULL
;
138 StrList
*depend_list
;
140 static bool want_usage
;
141 static bool terminate_after_phase
;
142 bool user_nolist
= false;
144 static char *quote_for_pmake(const char *str
);
145 static char *quote_for_wmake(const char *str
);
146 static char *(*quote_for_make
)(const char *) = quote_for_pmake
;
148 static int64_t get_curr_offs(void)
150 return in_absolute
? absolute
.offset
: raa_read(offsets
, location
.segment
);
153 static void set_curr_offs(int64_t l_off
)
156 absolute
.offset
= l_off
;
158 offsets
= raa_write(offsets
, location
.segment
, l_off
);
161 static void nasm_fputs(const char *line
, FILE * outfile
)
164 fputs(line
, outfile
);
170 static void define_macros_early(void)
172 const struct compile_time
* const oct
= &official_compile_time
;
175 if (oct
->have_local
) {
176 strftime(temp
, sizeof temp
, "__DATE__=\"%Y-%m-%d\"", &oct
->local
);
177 preproc
->pre_define(temp
);
178 strftime(temp
, sizeof temp
, "__DATE_NUM__=%Y%m%d", &oct
->local
);
179 preproc
->pre_define(temp
);
180 strftime(temp
, sizeof temp
, "__TIME__=\"%H:%M:%S\"", &oct
->local
);
181 preproc
->pre_define(temp
);
182 strftime(temp
, sizeof temp
, "__TIME_NUM__=%H%M%S", &oct
->local
);
183 preproc
->pre_define(temp
);
187 strftime(temp
, sizeof temp
, "__UTC_DATE__=\"%Y-%m-%d\"", &oct
->gm
);
188 preproc
->pre_define(temp
);
189 strftime(temp
, sizeof temp
, "__UTC_DATE_NUM__=%Y%m%d", &oct
->gm
);
190 preproc
->pre_define(temp
);
191 strftime(temp
, sizeof temp
, "__UTC_TIME__=\"%H:%M:%S\"", &oct
->gm
);
192 preproc
->pre_define(temp
);
193 strftime(temp
, sizeof temp
, "__UTC_TIME_NUM__=%H%M%S", &oct
->gm
);
194 preproc
->pre_define(temp
);
197 if (oct
->have_posix
) {
198 snprintf(temp
, sizeof temp
, "__POSIX_TIME__=%"PRId64
, oct
->posix
);
199 preproc
->pre_define(temp
);
203 static void define_macros_late(void)
208 * In case if output format is defined by alias
209 * we have to put shortname of the alias itself here
210 * otherwise ABI backward compatibility gets broken.
212 snprintf(temp
, sizeof(temp
), "__OUTPUT_FORMAT__=%s",
213 ofmt_alias
? ofmt_alias
->shortname
: ofmt
->shortname
);
214 preproc
->pre_define(temp
);
217 static void emit_dependencies(StrList
*list
)
222 bool wmake
= (quote_for_make
== quote_for_wmake
);
223 const char *wrapstr
, *nulltarget
;
225 wrapstr
= wmake
? " &\n " : " \\\n ";
226 nulltarget
= wmake
? "\t%null\n" : "";
228 if (depend_file
&& strcmp(depend_file
, "-")) {
229 deps
= nasm_open_write(depend_file
, NF_TEXT
);
231 nasm_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
232 "unable to write dependency file `%s'", depend_file
);
239 linepos
= fprintf(deps
, "%s :", depend_target
);
240 list_for_each(l
, list
) {
241 char *file
= quote_for_make(l
->str
);
243 if (linepos
+ len
> 62 && linepos
> 1) {
244 fputs(wrapstr
, deps
);
247 fprintf(deps
, " %s", file
);
251 fprintf(deps
, "\n\n");
253 list_for_each_safe(l
, nl
, list
) {
254 if (depend_emit_phony
) {
255 char *file
= quote_for_make(l
->str
);
256 fprintf(deps
, "%s :\n%s\n", file
, nulltarget
);
266 /* Convert a struct tm to a POSIX-style time constant */
267 static int64_t make_posix_time(const struct tm
*tm
)
270 int64_t y
= tm
->tm_year
;
272 /* See IEEE 1003.1:2004, section 4.14 */
274 t
= (y
-70)*365 + (y
-69)/4 - (y
-1)/100 + (y
+299)/400;
286 static void timestamp(void)
288 struct compile_time
* const oct
= &official_compile_time
;
289 const struct tm
*tp
, *best_gm
;
295 tp
= localtime(&oct
->t
);
298 best_gm
= &oct
->local
;
299 oct
->have_local
= true;
302 tp
= gmtime(&oct
->t
);
307 if (!oct
->have_local
)
308 oct
->local
= oct
->gm
;
310 oct
->gm
= oct
->local
;
314 oct
->posix
= make_posix_time(best_gm
);
315 oct
->have_posix
= true;
319 int main(int argc
, char **argv
)
321 StrList
**depend_ptr
;
325 iflag_set(&cpu
, IF_PLEVEL
);
326 iflag_set(&cmd_cpu
, IF_PLEVEL
);
329 want_usage
= terminate_after_phase
= false;
330 nasm_set_verror(nasm_verror_gnu
);
337 offsets
= raa_init();
338 forwrefs
= saa_init((int32_t)sizeof(struct forwrefinfo
));
341 operating_mode
= OP_NORMAL
;
343 parse_cmdline(argc
, argv
, 1);
344 if (terminate_after_phase
) {
351 * Define some macros dependent on the runtime, but not
352 * on the command line (as those are scanned in cmdline pass 2.)
355 define_macros_early();
357 parse_cmdline(argc
, argv
, 2);
358 if (terminate_after_phase
) {
364 /* Save away the default state of warnings */
365 memcpy(warning_state_init
, warning_state
, sizeof warning_state
);
367 if (!using_debug_info
) {
368 /* No debug info, redirect to the null backend (empty stubs) */
369 dfmt
= &null_debug_form
;
370 } else if (!debug_format
) {
371 /* Default debug format for this backend */
372 dfmt
= ofmt
->default_dfmt
;
374 dfmt
= dfmt_find(ofmt
, debug_format
);
376 nasm_fatal(ERR_NOFILE
| ERR_USAGE
,
377 "unrecognized debug format `%s' for"
378 " output format `%s'",
379 debug_format
, ofmt
->shortname
);
384 preproc
->extra_stdmac(ofmt
->stdmac
);
386 /* define some macros dependent of command-line */
387 define_macros_late();
389 depend_ptr
= (depend_file
|| (operating_mode
& OP_DEPEND
)) ? &depend_list
: NULL
;
392 depend_target
= quote_for_make(outname
);
394 if (operating_mode
& OP_DEPEND
) {
397 if (depend_missing_ok
)
398 preproc
->include_path(NULL
); /* "assume generated" */
400 preproc
->reset(inname
, 0, depend_ptr
);
401 if (outname
[0] == '\0')
402 ofmt
->filename(inname
, outname
);
404 while ((line
= preproc
->getline()))
407 } else if (operating_mode
& OP_PREPROCESS
) {
409 const char *file_name
= NULL
;
410 int32_t prior_linnum
= 0;
414 ofile
= nasm_open_write(outname
, NF_TEXT
);
416 nasm_fatal(ERR_NOFILE
,
417 "unable to open output file `%s'",
422 location
.known
= false;
425 preproc
->reset(inname
, 3, depend_ptr
);
427 /* Revert all warnings to the default state */
428 memcpy(warning_state
, warning_state_init
, sizeof warning_state
);
430 while ((line
= preproc
->getline())) {
432 * We generate %line directives if needed for later programs
434 int32_t linnum
= prior_linnum
+= lineinc
;
435 int altline
= src_get(&linnum
, &file_name
);
437 if (altline
== 1 && lineinc
== 1)
438 nasm_fputs("", ofile
);
440 lineinc
= (altline
!= -1 || lineinc
!= 1);
441 fprintf(ofile
? ofile
: stdout
,
442 "%%line %"PRId32
"+%d %s\n", linnum
, lineinc
,
445 prior_linnum
= linnum
;
447 nasm_fputs(line
, ofile
);
453 if (ofile
&& terminate_after_phase
)
458 if (operating_mode
& OP_NORMAL
) {
460 * We must call ofmt->filename _anyway_, even if the user
461 * has specified their own output file, because some
462 * formats (eg OBJ and COFF) use ofmt->filename to find out
463 * the name of the input file and then put that inside the
466 ofmt
->filename(inname
, outname
);
468 ofile
= nasm_open_write(outname
, (ofmt
->flags
& OFMT_TEXT
) ? NF_TEXT
: NF_BINARY
);
470 nasm_fatal(ERR_NOFILE
,
471 "unable to open output file `%s'", outname
);
474 * We must call init_labels() before ofmt->init() since
475 * some object formats will want to define labels in their
476 * init routines. (eg OS/2 defines the FLAT group)
483 assemble_file(inname
, depend_ptr
);
485 if (!terminate_after_phase
) {
490 nasm_error(ERR_NONFATAL
|ERR_NOFILE
,
491 "write error on output file `%s'", outname
);
492 terminate_after_phase
= true;
498 if (terminate_after_phase
)
504 if (depend_list
&& !terminate_after_phase
)
505 emit_dependencies(depend_list
);
516 return terminate_after_phase
;
520 * Get a parameter for a command line option.
521 * First arg must be in the form of e.g. -f...
523 static char *get_param(char *p
, char *q
, bool *advance
)
526 if (p
[2]) /* the parameter's in the option */
527 return nasm_skip_spaces(p
+ 2);
532 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
533 "option `-%c' requires an argument", p
[1]);
540 static void copy_filename(char *dst
, const char *src
)
542 size_t len
= strlen(src
);
544 if (len
>= (size_t)FILENAME_MAX
) {
545 nasm_fatal(ERR_NOFILE
, "file name too long");
548 strncpy(dst
, src
, FILENAME_MAX
);
552 * Convert a string to a POSIX make-safe form
554 static char *quote_for_pmake(const char *str
)
559 size_t n
= 1; /* Terminating zero */
565 for (p
= str
; *p
; p
++) {
569 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
589 /* Convert N backslashes at the end of filename to 2N backslashes */
593 os
= q
= nasm_malloc(n
);
596 for (p
= str
; *p
; p
++) {
634 * Convert a string to a Watcom make-safe form
636 static char *quote_for_wmake(const char *str
)
642 size_t n
= 1; /* Terminating zero */
647 for (p
= str
; *p
; p
++) {
671 os
= q
= nasm_malloc(n
);
676 for (p
= str
; *p
; p
++) {
710 static const struct textargs textopts
[] = {
711 {"prefix", OPT_PREFIX
},
712 {"postfix", OPT_POSTFIX
},
716 static void show_version(void)
718 printf("NASM version %s compiled on %s%s\n",
719 nasm_version
, nasm_date
, nasm_compile_options
);
723 static bool stopoptions
= false;
724 static bool process_arg(char *p
, char *q
, int pass
)
728 bool advance
= false;
733 if (p
[0] == '-' && !stopoptions
) {
734 if (strchr("oOfpPdDiIlFXuUZwW", p
[1])) {
735 /* These parameters take values */
736 if (!(param
= get_param(p
, q
, &advance
)))
746 case 'o': /* output file */
748 copy_filename(outname
, param
);
751 case 'f': /* output format */
753 ofmt
= ofmt_find(param
, &ofmt_alias
);
755 nasm_fatal(ERR_NOFILE
| ERR_USAGE
,
756 "unrecognised output format `%s' - "
757 "use -hf for a list", param
);
762 case 'O': /* Optimization level */
767 /* Naked -O == -Ox */
768 optimizing
= MAX_OPTIMIZE
;
772 case '0': case '1': case '2': case '3': case '4':
773 case '5': case '6': case '7': case '8': case '9':
774 opt
= strtoul(param
, ¶m
, 10);
776 /* -O0 -> optimizing == -1, 0.98 behaviour */
777 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
779 optimizing
= opt
- 1;
787 opt_verbose_info
= true;
792 optimizing
= MAX_OPTIMIZE
;
797 "unknown optimization option -O%c\n",
802 if (optimizing
> MAX_OPTIMIZE
)
803 optimizing
= MAX_OPTIMIZE
;
808 case 'p': /* pre-include */
811 preproc
->pre_include(param
);
814 case 'd': /* pre-define */
817 preproc
->pre_define(param
);
820 case 'u': /* un-define */
823 preproc
->pre_undefine(param
);
826 case 'i': /* include search path */
829 preproc
->include_path(param
);
832 case 'l': /* listing file */
834 copy_filename(listname
, param
);
837 case 'Z': /* error messages file */
839 copy_filename(errname
, param
);
842 case 'F': /* specify debug format */
844 using_debug_info
= true;
845 debug_format
= param
;
849 case 'X': /* specify error reporting format */
851 if (nasm_stricmp("vc", param
) == 0)
852 nasm_set_verror(nasm_verror_vc
);
853 else if (nasm_stricmp("gnu", param
) == 0)
854 nasm_set_verror(nasm_verror_gnu
);
856 nasm_fatal(ERR_NOFILE
| ERR_USAGE
,
857 "unrecognized error reporting format `%s'",
864 using_debug_info
= true;
866 debug_format
= nasm_skip_spaces(p
+ 2);
872 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
874 " [options...] [--] filename\n"
875 " or nasm -v (or --v) for version info\n\n"
876 " -t assemble in SciTech TASM compatible mode\n");
878 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
879 " -a don't preprocess (assemble only)\n"
880 " -M generate Makefile dependencies on stdout\n"
881 " -MG d:o, missing files assumed generated\n"
882 " -MF <file> set Makefile dependency file\n"
883 " -MD <file> assemble and generate dependencies\n"
884 " -MT <file> dependency target name\n"
885 " -MQ <file> dependency target name (quoted)\n"
886 " -MP emit phony target\n\n"
887 " -Z<file> redirect error messages to file\n"
888 " -s redirect error messages to stdout\n\n"
889 " -g generate debugging information\n\n"
890 " -F format select a debugging format\n\n"
891 " -gformat same as -g -F format\n\n"
892 " -o outfile write output to an outfile\n\n"
893 " -f format select an output format\n\n"
894 " -l listfile write listing to a listfile\n\n"
895 " -I<path> adds a pathname to the include file path\n");
897 (" -O<digit> optimize branch offsets\n"
898 " -O0: No optimization\n"
899 " -O1: Minimal optimization\n"
900 " -Ox: Multipass optimization (default)\n\n"
901 " -P<file> pre-includes a file\n"
902 " -D<macro>[=<value>] pre-defines a macro\n"
903 " -U<macro> undefines a macro\n"
904 " -X<format> specifies error reporting format (gnu or vc)\n"
905 " -w+foo enables warning foo (equiv. -Wfoo)\n"
906 " -w-foo disable warning foo (equiv. -Wno-foo)\n\n"
907 " -w[+-]error[=foo] can be used to promote warnings to errors\n"
908 " -h show invocation summary and exit\n\n"
909 "--prefix,--postfix\n"
910 " these options prepend or append the given string\n"
911 " to all extern and global variables\n"
913 "Response files should contain command line parameters,\n"
916 "Warnings for the -W/-w options:\n");
917 for (i
= 0; i
<= ERR_WARN_ALL
; i
++)
918 printf(" %-23s %s%s\n",
919 warnings
[i
].name
, warnings
[i
].help
,
920 i
== ERR_WARN_ALL
? "\n" :
921 warnings
[i
].enabled
? " (default on)" :
924 printf("valid output formats for -f are"
925 " (`*' denotes default):\n");
926 ofmt_list(ofmt
, stdout
);
928 printf("For a list of valid output formats, use -hf.\n");
929 printf("For a list of debug formats, use -f <form> -y.\n");
931 exit(0); /* never need usage message here */
935 printf("\nvalid debug formats for '%s' output format are"
936 " ('*' denotes default):\n", ofmt
->shortname
);
937 dfmt_list(ofmt
, stdout
);
943 tasm_compatible_mode
= true;
950 case 'e': /* preprocess only */
953 operating_mode
= OP_PREPROCESS
;
956 case 'a': /* assemble only - don't preprocess */
958 preproc
= &preproc_nop
;
964 if (!set_warning_status(param
)) {
965 nasm_error(ERR_WARNING
|ERR_NOFILE
|ERR_WARN_UNK_WARNING
,
966 "unknown warning option: %s", param
);
975 quote_for_make
= quote_for_wmake
;
989 operating_mode
= OP_DEPEND
;
992 operating_mode
= OP_DEPEND
;
993 depend_missing_ok
= true;
996 depend_emit_phony
= true;
999 operating_mode
= OP_NORMAL
;
1012 depend_target
= quote_for_make(q
);
1016 /* handled in pass 1 */
1019 nasm_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
1020 "unknown dependency option `-M%c'", p
[2]);
1024 if (advance
&& (!q
|| !q
[0])) {
1025 nasm_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
1026 "option `-M%c' requires a parameter", p
[2]);
1035 if (p
[2] == 0) { /* -- => stop processing options */
1040 if (!nasm_stricmp(p
, "--v"))
1043 if (!nasm_stricmp(p
, "--version"))
1046 for (s
= 0; textopts
[s
].label
; s
++) {
1047 if (!nasm_stricmp(p
+ 2, textopts
[s
].label
)) {
1057 nasm_error(ERR_NONFATAL
| ERR_NOFILE
|
1059 "option `--%s' requires an argument",
1063 advance
= 1, param
= q
;
1069 strlcpy(lprefix
, param
, PREFIX_MAX
);
1073 strlcpy(lpostfix
, param
, POSTFIX_MAX
);
1084 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1085 "unrecognised option `--%s'", p
+ 2);
1093 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1094 "unrecognised option `-%c'", p
[1]);
1097 } else if (pass
== 2) {
1099 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1100 "more than one input file specified");
1102 copy_filename(inname
, p
);
1109 #define ARG_BUF_DELTA 128
1111 static void process_respfile(FILE * rfile
, int pass
)
1113 char *buffer
, *p
, *q
, *prevarg
;
1114 int bufsize
, prevargsize
;
1116 bufsize
= prevargsize
= ARG_BUF_DELTA
;
1117 buffer
= nasm_malloc(ARG_BUF_DELTA
);
1118 prevarg
= nasm_malloc(ARG_BUF_DELTA
);
1121 while (1) { /* Loop to handle all lines in file */
1123 while (1) { /* Loop to handle long lines */
1124 q
= fgets(p
, bufsize
- (p
- buffer
), rfile
);
1128 if (p
> buffer
&& p
[-1] == '\n')
1130 if (p
- buffer
> bufsize
- 10) {
1132 offset
= p
- buffer
;
1133 bufsize
+= ARG_BUF_DELTA
;
1134 buffer
= nasm_realloc(buffer
, bufsize
);
1135 p
= buffer
+ offset
;
1139 if (!q
&& p
== buffer
) {
1141 process_arg(prevarg
, NULL
, pass
);
1148 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1149 * them are present at the end of the line.
1151 *(p
= &buffer
[strcspn(buffer
, "\r\n\032")]) = '\0';
1153 while (p
> buffer
&& nasm_isspace(p
[-1]))
1156 p
= nasm_skip_spaces(buffer
);
1158 if (process_arg(prevarg
, p
, pass
))
1161 if ((int) strlen(p
) > prevargsize
- 10) {
1162 prevargsize
+= ARG_BUF_DELTA
;
1163 prevarg
= nasm_realloc(prevarg
, prevargsize
);
1165 strncpy(prevarg
, p
, prevargsize
);
1169 /* Function to process args from a string of args, rather than the
1170 * argv array. Used by the environment variable and response file
1173 static void process_args(char *args
, int pass
)
1175 char *p
, *q
, *arg
, *prevarg
;
1176 char separator
= ' ';
1179 if (*p
&& *p
!= '-')
1184 while (*p
&& *p
!= separator
)
1186 while (*p
== separator
)
1190 if (process_arg(prevarg
, arg
, pass
))
1194 process_arg(arg
, NULL
, pass
);
1197 static void process_response_file(const char *file
, int pass
)
1200 FILE *f
= nasm_open_read(file
, NF_TEXT
);
1205 while (fgets(str
, sizeof str
, f
)) {
1206 process_args(str
, pass
);
1211 static void parse_cmdline(int argc
, char **argv
, int pass
)
1214 char *envreal
, *envcopy
= NULL
, *p
;
1217 *inname
= *outname
= *listname
= *errname
= '\0';
1219 /* Initialize all the warnings to their default state */
1220 for (i
= 0; i
< ERR_WARN_ALL
; i
++) {
1221 warning_state_init
[i
] = warning_state
[i
] =
1222 warnings
[i
].enabled
? WARN_ST_ENABLED
: 0;
1226 * First, process the NASMENV environment variable.
1228 envreal
= getenv("NASMENV");
1230 envcopy
= nasm_strdup(envreal
);
1231 process_args(envcopy
, pass
);
1236 * Now process the actual command line.
1241 if (argv
[0][0] == '@') {
1243 * We have a response file, so process this as a set of
1244 * arguments like the environment variable. This allows us
1245 * to have multiple arguments on a single line, which is
1246 * different to the -@resp file processing below for regular
1249 process_response_file(argv
[0]+1, pass
);
1253 if (!stopoptions
&& argv
[0][0] == '-' && argv
[0][1] == '@') {
1254 p
= get_param(argv
[0], argc
> 1 ? argv
[1] : NULL
, &advance
);
1256 rfile
= nasm_open_read(p
, NF_TEXT
);
1258 process_respfile(rfile
, pass
);
1261 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1262 "unable to open response file `%s'", p
);
1265 advance
= process_arg(argv
[0], argc
> 1 ? argv
[1] : NULL
, pass
);
1266 argv
+= advance
, argc
-= advance
;
1270 * Look for basic command line typos. This definitely doesn't
1271 * catch all errors, but it might help cases of fumbled fingers.
1277 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1278 "no input file specified");
1279 else if (!strcmp(inname
, errname
) ||
1280 !strcmp(inname
, outname
) ||
1281 !strcmp(inname
, listname
) ||
1282 (depend_file
&& !strcmp(inname
, depend_file
)))
1283 nasm_fatal(ERR_NOFILE
| ERR_USAGE
,
1284 "file `%s' is both input and output file",
1288 error_file
= nasm_open_write(errname
, NF_TEXT
);
1290 error_file
= stderr
; /* Revert to default! */
1291 nasm_fatal(ERR_NOFILE
| ERR_USAGE
,
1292 "cannot open file `%s' for error messages",
1298 static void assemble_file(char *fname
, StrList
**depend_ptr
)
1305 uint64_t prev_offset_changed
;
1306 unsigned int stall_count
= 0; /* Make sure we make forward progress... */
1308 if (cmd_sb
== 32 && iflag_ffs(&cmd_cpu
) < IF_386
)
1309 nasm_fatal(0, "command line: 32-bit segment size requires a higher cpu");
1311 pass_max
= prev_offset_changed
= (INT_MAX
>> 1) + 2; /* Almost unlimited */
1312 for (passn
= 1; pass0
<= 2; passn
++) {
1315 pass1
= pass0
== 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1316 pass2
= passn
> 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1317 /* pass0 0, 0, 0, ..., 1, 2 */
1319 def_label
= passn
> 1 ? redefine_label
: define_label
;
1321 globalbits
= cmd_sb
; /* set 'bits' to command line default */
1324 lfmt
->init(listname
);
1325 } else if (passn
== 1 && *listname
) {
1326 /* Remove the list file in case we die before the output pass */
1329 in_absolute
= false;
1330 global_offset_changed
= 0; /* set by redefine_label */
1331 location
.segment
= ofmt
->section(NULL
, pass2
, &globalbits
);
1333 saa_rewind(forwrefs
);
1334 forwref
= saa_rstruct(forwrefs
);
1336 offsets
= raa_init();
1338 preproc
->reset(fname
, pass1
, pass1
== 2 ? depend_ptr
: NULL
);
1340 /* Revert all warnings to the default state */
1341 memcpy(warning_state
, warning_state_init
, sizeof warning_state
);
1345 location
.known
= true;
1346 location
.offset
= offs
= get_curr_offs();
1348 while ((line
= preproc
->getline())) {
1352 * Here we parse our directives; this is not handled by the
1355 if (process_directives(line
))
1356 goto end_of_line
; /* Just do final cleanup */
1358 /* Not a directive, or even something that starts with [ */
1360 parse_line(pass1
, line
, &output_ins
, def_label
);
1362 if (optimizing
> 0) {
1363 if (forwref
!= NULL
&& globallineno
== forwref
->lineno
) {
1364 output_ins
.forw_ref
= true;
1366 output_ins
.oprs
[forwref
->operand
].opflags
|= OPFLAG_FORWARD
;
1367 forwref
= saa_rstruct(forwrefs
);
1368 } while (forwref
!= NULL
1369 && forwref
->lineno
== globallineno
);
1371 output_ins
.forw_ref
= false;
1373 if (output_ins
.forw_ref
) {
1375 for (i
= 0; i
< output_ins
.operands
; i
++) {
1376 if (output_ins
.oprs
[i
].opflags
& OPFLAG_FORWARD
) {
1377 struct forwrefinfo
*fwinf
= (struct forwrefinfo
*)saa_wstruct(forwrefs
);
1378 fwinf
->lineno
= globallineno
;
1387 if (output_ins
.opcode
== I_EQU
) {
1390 * Special `..' EQUs get processed in pass two,
1391 * except `..@' macro-processor EQUs which are done
1392 * in the normal place.
1394 if (!output_ins
.label
)
1395 nasm_error(ERR_NONFATAL
,
1396 "EQU not preceded by label");
1398 else if (output_ins
.label
[0] != '.' ||
1399 output_ins
.label
[1] != '.' ||
1400 output_ins
.label
[2] == '@') {
1401 if (output_ins
.operands
== 1 &&
1402 (output_ins
.oprs
[0].type
& IMMEDIATE
) &&
1403 output_ins
.oprs
[0].wrt
== NO_SEG
) {
1404 bool isext
= !!(output_ins
.oprs
[0].opflags
& OPFLAG_EXTERN
);
1405 def_label(output_ins
.label
,
1406 output_ins
.oprs
[0].segment
,
1407 output_ins
.oprs
[0].offset
, NULL
,
1409 } else if (output_ins
.operands
== 2
1410 && (output_ins
.oprs
[0].type
& IMMEDIATE
)
1411 && (output_ins
.oprs
[0].type
& COLON
)
1412 && output_ins
.oprs
[0].segment
== NO_SEG
1413 && output_ins
.oprs
[0].wrt
== NO_SEG
1414 && (output_ins
.oprs
[1].type
& IMMEDIATE
)
1415 && output_ins
.oprs
[1].segment
== NO_SEG
1416 && output_ins
.oprs
[1].wrt
== NO_SEG
) {
1417 def_label(output_ins
.label
,
1418 output_ins
.oprs
[0].offset
| SEG_ABS
,
1419 output_ins
.oprs
[1].offset
,
1420 NULL
, false, false);
1422 nasm_error(ERR_NONFATAL
,
1423 "bad syntax for EQU");
1427 * Special `..' EQUs get processed here, except
1428 * `..@' macro processor EQUs which are done above.
1430 if (output_ins
.label
[0] == '.' &&
1431 output_ins
.label
[1] == '.' &&
1432 output_ins
.label
[2] != '@') {
1433 if (output_ins
.operands
== 1 &&
1434 (output_ins
.oprs
[0].type
& IMMEDIATE
)) {
1435 define_label(output_ins
.label
,
1436 output_ins
.oprs
[0].segment
,
1437 output_ins
.oprs
[0].offset
,
1438 NULL
, false, false);
1439 } else if (output_ins
.operands
== 2
1440 && (output_ins
.oprs
[0].type
& IMMEDIATE
)
1441 && (output_ins
.oprs
[0].type
& COLON
)
1442 && output_ins
.oprs
[0].segment
== NO_SEG
1443 && (output_ins
.oprs
[1].type
& IMMEDIATE
)
1444 && output_ins
.oprs
[1].segment
== NO_SEG
) {
1445 define_label(output_ins
.label
,
1446 output_ins
.oprs
[0].offset
| SEG_ABS
,
1447 output_ins
.oprs
[1].offset
,
1448 NULL
, false, false);
1450 nasm_error(ERR_NONFATAL
,
1451 "bad syntax for EQU");
1454 } else { /* instruction isn't an EQU */
1457 nasm_assert(output_ins
.times
>= 0);
1459 for (n
= 1; n
<= output_ins
.times
; n
++) {
1461 int64_t l
= insn_size(location
.segment
, offs
,
1462 globalbits
, &output_ins
);
1464 /* if (using_debug_info) && output_ins.opcode != -1) */
1465 if (using_debug_info
)
1466 { /* fbk 03/25/01 */
1467 /* this is done here so we can do debug type info */
1469 TYS_ELEMENTS(output_ins
.operands
);
1470 switch (output_ins
.opcode
) {
1473 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_BYTE
;
1477 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_WORD
;
1481 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_DWORD
;
1485 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_QWORD
;
1489 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_TBYTE
;
1493 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_OWORD
;
1497 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_YWORD
;
1501 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_ZWORD
;
1504 typeinfo
|= TY_BYTE
;
1507 typeinfo
|= TY_WORD
;
1510 if (output_ins
.eops_float
)
1511 typeinfo
|= TY_FLOAT
;
1513 typeinfo
|= TY_DWORD
;
1516 typeinfo
|= TY_QWORD
;
1519 typeinfo
|= TY_TBYTE
;
1522 typeinfo
|= TY_OWORD
;
1525 typeinfo
|= TY_YWORD
;
1528 typeinfo
|= TY_ZWORD
;
1531 typeinfo
= TY_LABEL
;
1535 dfmt
->debug_typevalue(typeinfo
);
1539 * For INCBIN, let the code in assemble
1540 * handle TIMES, so we don't have to read the
1541 * input file over and over.
1545 set_curr_offs(offs
);
1548 * else l == -1 => invalid instruction, which will be
1549 * flagged as an error on pass 2
1553 lfmt
->uplevel(LIST_TIMES
);
1554 offs
+= assemble(location
.segment
, offs
,
1555 globalbits
, &output_ins
);
1556 set_curr_offs(offs
);
1560 if (output_ins
.times
> 1)
1561 lfmt
->downlevel(LIST_TIMES
);
1563 cleanup_insn(&output_ins
);
1567 location
.offset
= offs
= get_curr_offs();
1568 } /* end while (line = preproc->getline... */
1570 if (pass0
== 2 && global_offset_changed
&& !terminate_after_phase
)
1571 nasm_error(ERR_NONFATAL
,
1572 "phase error detected at end of assembly.");
1575 preproc
->cleanup(1);
1577 if ((passn
> 1 && !global_offset_changed
) || pass0
== 2) {
1579 } else if (global_offset_changed
&&
1580 global_offset_changed
< prev_offset_changed
) {
1581 prev_offset_changed
= global_offset_changed
;
1587 if (terminate_after_phase
)
1590 if ((stall_count
> 997U) || (passn
>= pass_max
)) {
1591 /* We get here if the labels don't converge
1592 * Example: FOO equ FOO + 1
1594 nasm_error(ERR_NONFATAL
,
1595 "Can't find valid values for all labels "
1596 "after %d passes, giving up.", passn
);
1597 nasm_error(ERR_NONFATAL
,
1598 "Possible causes: recursive EQUs, macro abuse.");
1603 preproc
->cleanup(0);
1605 if (!terminate_after_phase
&& opt_verbose_info
) {
1606 /* -On and -Ov switches */
1607 fprintf(stdout
, "info: assembly required 1+%d+1 passes\n", passn
-3);
1612 * gnu style error reporting
1613 * This function prints an error message to error_file in the
1614 * style used by GNU. An example would be:
1615 * file.asm:50: error: blah blah blah
1616 * where file.asm is the name of the file, 50 is the line number on
1617 * which the error occurs (or is detected) and "error:" is one of
1618 * the possible optional diagnostics -- it can be "error" or "warning"
1619 * or something else. Finally the line terminates with the actual
1622 * @param severity the severity of the warning or error
1623 * @param fmt the printf style format string
1625 static void nasm_verror_gnu(int severity
, const char *fmt
, va_list ap
)
1627 const char *currentfile
= NULL
;
1630 if (is_suppressed_warning(severity
))
1633 if (!(severity
& ERR_NOFILE
))
1634 src_get(&lineno
, ¤tfile
);
1636 if (!skip_this_pass(severity
)) {
1638 fprintf(error_file
, "%s:%"PRId32
": ", currentfile
, lineno
);
1640 fputs("nasm: ", error_file
);
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 */
1827 /* abort(); */ /* halt, catch fire, and dump core */
1838 static void usage(void)
1840 fputs("type `nasm -h' for help\n", error_file
);