1 /* The Netwide Assembler main program module
3 * The Netwide Assembler is copyright (C) 1996 Simon Tatham and
4 * Julian Hall. All rights reserved. The software is
5 * redistributable under the license given in the file "LICENSE"
6 * distributed in the NASM archive.
35 struct forwrefinfo
{ /* info held on forward refs. */
40 static int get_bits(char *value
);
41 static uint32_t get_cpu(char *cpu_str
);
42 static void parse_cmdline(int, char **);
43 static void assemble_file(char *, StrList
**);
44 static void register_output_formats(void);
45 static void report_error_gnu(int severity
, const char *fmt
, ...);
46 static void report_error_vc(int severity
, const char *fmt
, ...);
47 static void report_error_common(int severity
, const char *fmt
,
49 static bool is_suppressed_warning(int severity
);
50 static void usage(void);
51 static efunc report_error
;
53 static int using_debug_info
, opt_verbose_info
;
54 bool tasm_compatible_mode
= false;
59 time_t official_compile_time
;
61 static char inname
[FILENAME_MAX
];
62 static char outname
[FILENAME_MAX
];
63 static char listname
[FILENAME_MAX
];
64 static char errname
[FILENAME_MAX
];
65 static int globallineno
; /* for forward-reference tracking */
66 /* static int pass = 0; */
67 static struct ofmt
*ofmt
= NULL
;
69 static FILE *error_file
; /* Where to write error messages */
71 static FILE *ofile
= NULL
;
72 int optimizing
= -1; /* number of optimization passes to take */
73 static int sb
, cmd_sb
= 16; /* by default */
74 static uint32_t cmd_cpu
= IF_PLEVEL
; /* highest level by default */
75 static uint32_t cpu
= IF_PLEVEL
; /* passed to insn_size & assemble.c */
76 int64_t global_offset_changed
; /* referenced in labels.c */
77 int64_t prev_offset_changed
;
80 static struct location location
;
81 int in_abs_seg
; /* Flag we are in ABSOLUTE seg */
82 int32_t abs_seg
; /* ABSOLUTE segment basis */
83 int32_t abs_offset
; /* ABSOLUTE offset */
85 static struct RAA
*offsets
;
87 static struct SAA
*forwrefs
; /* keep track of forward references */
88 static const struct forwrefinfo
*forwref
;
90 static Preproc
*preproc
;
92 op_normal
, /* Preprocess and assemble */
93 op_preprocess
, /* Preprocess only */
94 op_depend
, /* Generate dependencies */
96 static enum op_type operating_mode
;
97 /* Dependency flags */
98 static bool depend_emit_phony
= false;
99 static bool depend_missing_ok
= false;
100 static const char *depend_target
= NULL
;
101 static const char *depend_file
= NULL
;
104 * Which of the suppressible warnings are suppressed. Entry zero
105 * isn't an actual warning, but it used for -w+error/-Werror.
108 static bool warning_on
[ERR_WARN_MAX
+1]; /* Current state */
109 static bool warning_on_global
[ERR_WARN_MAX
+1]; /* Command-line state */
111 static const struct warning
{
115 } warnings
[ERR_WARN_MAX
+1] = {
116 {"error", "treat warnings as errors", false},
117 {"macro-params", "macro calls with wrong parameter count", true},
118 {"macro-selfref", "cyclic macro references", false},
119 {"macro-defaults", "macros with more default than optional parameters", true},
120 {"orphan-labels", "labels alone on lines without trailing `:'", true},
121 {"number-overflow", "numeric constant does not fit", true},
122 {"gnu-elf-extensions", "using 8- or 16-bit relocation in ELF32, a GNU extension", false},
123 {"float-overflow", "floating point overflow", true},
124 {"float-denorm", "floating point denormal", false},
125 {"float-underflow", "floating point underflow", false},
126 {"float-toolong", "too many digits in floating-point number", true},
127 {"user", "%warning directives", true},
131 * This is a null preprocessor which just copies lines from input
132 * to output. It's used when someone explicitly requests that NASM
133 * not preprocess their source file.
136 static void no_pp_reset(char *, int, efunc
, evalfunc
, ListGen
*, StrList
**);
137 static char *no_pp_getline(void);
138 static void no_pp_cleanup(int);
139 static Preproc no_pp
= {
146 * get/set current offset...
148 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
149 raa_read(offsets,location.segment))
150 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
151 (void)(offsets=raa_write(offsets,location.segment,(x))))
153 static int want_usage
;
154 static int terminate_after_phase
;
155 int user_nolist
= 0; /* fbk 9/2/00 */
157 static void nasm_fputs(const char *line
, FILE * outfile
)
160 fputs(line
, outfile
);
166 /* Convert a struct tm to a POSIX-style time constant */
167 static int64_t posix_mktime(struct tm
*tm
)
170 int64_t y
= tm
->tm_year
;
172 /* See IEEE 1003.1:2004, section 4.14 */
174 t
= (y
-70)*365 + (y
-69)/4 - (y
-1)/100 + (y
+299)/400;
186 static void define_macros_early(void)
189 struct tm lt
, *lt_p
, gm
, *gm_p
;
192 lt_p
= localtime(&official_compile_time
);
196 strftime(temp
, sizeof temp
, "__DATE__=\"%Y-%m-%d\"", <
);
198 strftime(temp
, sizeof temp
, "__DATE_NUM__=%Y%m%d", <
);
200 strftime(temp
, sizeof temp
, "__TIME__=\"%H:%M:%S\"", <
);
202 strftime(temp
, sizeof temp
, "__TIME_NUM__=%H%M%S", <
);
206 gm_p
= gmtime(&official_compile_time
);
210 strftime(temp
, sizeof temp
, "__UTC_DATE__=\"%Y-%m-%d\"", &gm
);
212 strftime(temp
, sizeof temp
, "__UTC_DATE_NUM__=%Y%m%d", &gm
);
214 strftime(temp
, sizeof temp
, "__UTC_TIME__=\"%H:%M:%S\"", &gm
);
216 strftime(temp
, sizeof temp
, "__UTC_TIME_NUM__=%H%M%S", &gm
);
221 posix_time
= posix_mktime(&gm
);
223 posix_time
= posix_mktime(<
);
228 snprintf(temp
, sizeof temp
, "__POSIX_TIME__=%"PRId64
, posix_time
);
233 static void define_macros_late(void)
237 snprintf(temp
, sizeof(temp
), "__OUTPUT_FORMAT__=%s\n",
242 static void emit_dependencies(StrList
*list
)
248 if (depend_file
&& strcmp(depend_file
, "-")) {
249 deps
= fopen(depend_file
, "w");
251 report_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
252 "unable to write dependency file `%s'", depend_file
);
259 linepos
= fprintf(deps
, "%s:", depend_target
);
260 for (l
= list
; l
; l
= l
->next
) {
261 len
= strlen(l
->str
);
262 if (linepos
+ len
> 62) {
263 fprintf(deps
, " \\\n ");
266 fprintf(deps
, " %s", l
->str
);
269 fprintf(deps
, "\n\n");
271 for (l
= list
; l
; l
= nl
) {
272 if (depend_emit_phony
)
273 fprintf(deps
, "%s:\n\n", l
->str
);
283 int main(int argc
, char **argv
)
285 StrList
*depend_list
= NULL
, **depend_ptr
;
287 time(&official_compile_time
);
290 want_usage
= terminate_after_phase
= false;
291 report_error
= report_error_gnu
;
297 nasm_set_malloc_error(report_error
);
298 offsets
= raa_init();
299 forwrefs
= saa_init((int32_t)sizeof(struct forwrefinfo
));
302 operating_mode
= op_normal
;
306 register_output_formats();
308 /* Define some macros dependent on the runtime, but not
309 on the command line. */
310 define_macros_early();
312 parse_cmdline(argc
, argv
);
314 if (terminate_after_phase
) {
320 /* If debugging info is disabled, suppress any debug calls */
321 if (!using_debug_info
)
322 ofmt
->current_dfmt
= &null_debug_form
;
325 pp_extra_stdmac(ofmt
->stdmac
);
326 parser_global_info(ofmt
, &location
);
327 eval_global_info(ofmt
, lookup_label
, &location
);
329 /* define some macros dependent of command-line */
330 define_macros_late();
332 depend_ptr
= (depend_file
|| (operating_mode
== op_depend
))
333 ? &depend_list
: NULL
;
335 depend_target
= outname
;
337 switch (operating_mode
) {
342 if (depend_missing_ok
)
343 pp_include_path(NULL
); /* "assume generated" */
345 preproc
->reset(inname
, 0, report_error
, evaluate
, &nasmlist
,
347 if (outname
[0] == '\0')
348 ofmt
->filename(inname
, outname
, report_error
);
350 while ((line
= preproc
->getline()))
359 char *file_name
= NULL
;
360 int32_t prior_linnum
= 0;
364 ofile
= fopen(outname
, "w");
366 report_error(ERR_FATAL
| ERR_NOFILE
,
367 "unable to open output file `%s'",
372 location
.known
= false;
375 preproc
->reset(inname
, 3, report_error
, evaluate
, &nasmlist
,
378 while ((line
= preproc
->getline())) {
380 * We generate %line directives if needed for later programs
382 int32_t linnum
= prior_linnum
+= lineinc
;
383 int altline
= src_get(&linnum
, &file_name
);
385 if (altline
== 1 && lineinc
== 1)
386 nasm_fputs("", ofile
);
388 lineinc
= (altline
!= -1 || lineinc
!= 1);
389 fprintf(ofile
? ofile
: stdout
,
390 "%%line %"PRId32
"+%d %s\n", linnum
, lineinc
,
393 prior_linnum
= linnum
;
395 nasm_fputs(line
, ofile
);
398 nasm_free(file_name
);
402 if (ofile
&& terminate_after_phase
)
410 * We must call ofmt->filename _anyway_, even if the user
411 * has specified their own output file, because some
412 * formats (eg OBJ and COFF) use ofmt->filename to find out
413 * the name of the input file and then put that inside the
416 ofmt
->filename(inname
, outname
, report_error
);
418 ofile
= fopen(outname
, "wb");
420 report_error(ERR_FATAL
| ERR_NOFILE
,
421 "unable to open output file `%s'", outname
);
425 * We must call init_labels() before ofmt->init() since
426 * some object formats will want to define labels in their
427 * init routines. (eg OS/2 defines the FLAT group)
431 ofmt
->init(ofile
, report_error
, define_label
, evaluate
);
433 assemble_file(inname
, depend_ptr
);
435 if (!terminate_after_phase
) {
436 ofmt
->cleanup(using_debug_info
);
440 * Despite earlier comments, we need this fclose.
441 * The object output drivers only fclose on cleanup,
442 * and we just skipped that.
455 emit_dependencies(depend_list
);
465 if (terminate_after_phase
)
472 * Get a parameter for a command line option.
473 * First arg must be in the form of e.g. -f...
475 static char *get_param(char *p
, char *q
, bool *advance
)
478 if (p
[2]) { /* the parameter's in the option */
480 while (nasm_isspace(*p
))
488 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
489 "option `-%c' requires an argument", p
[1]);
496 static void copy_filename(char *dst
, const char *src
)
498 size_t len
= strlen(src
);
500 if (len
>= (size_t)FILENAME_MAX
) {
501 report_error(ERR_FATAL
| ERR_NOFILE
, "file name too long");
504 strncpy(dst
, src
, FILENAME_MAX
);
508 * Convert a string to Make-safe form
510 static char *quote_for_make(const char *str
)
515 size_t n
= 1; /* Terminating zero */
521 for (p
= str
; *p
; p
++) {
525 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
545 /* Convert N backslashes at the end of filename to 2N backslashes */
549 os
= q
= nasm_malloc(n
);
552 for (p
= str
; *p
; p
++) {
595 #define OPT_POSTFIX 1
596 struct textargs textopts
[] = {
597 {"prefix", OPT_PREFIX
},
598 {"postfix", OPT_POSTFIX
},
602 static bool stopoptions
= false;
603 static bool process_arg(char *p
, char *q
)
607 bool advance
= false;
613 if (p
[0] == '-' && !stopoptions
) {
614 if (strchr("oOfpPdDiIlFXuUZwW", p
[1])) {
615 /* These parameters take values */
616 if (!(param
= get_param(p
, q
, &advance
)))
625 case 'o': /* output file */
626 copy_filename(outname
, param
);
629 case 'f': /* output format */
630 ofmt
= ofmt_find(param
);
632 report_error(ERR_FATAL
| ERR_NOFILE
| ERR_USAGE
,
633 "unrecognised output format `%s' - "
634 "use -hf for a list", param
);
638 case 'O': /* Optimization level */
643 /* Naked -O == -Ox */
644 optimizing
= INT_MAX
>> 1; /* Almost unlimited */
648 case '0': case '1': case '2': case '3': case '4':
649 case '5': case '6': case '7': case '8': case '9':
650 opt
= strtoul(param
, ¶m
, 10);
652 /* -O0 -> optimizing == -1, 0.98 behaviour */
653 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
655 optimizing
= opt
- 1;
663 opt_verbose_info
= true;
668 optimizing
= INT_MAX
>> 1; /* Almost unlimited */
672 report_error(ERR_FATAL
,
673 "unknown optimization option -O%c\n",
682 case 'p': /* pre-include */
684 pp_pre_include(param
);
687 case 'd': /* pre-define */
689 pp_pre_define(param
);
692 case 'u': /* un-define */
694 pp_pre_undefine(param
);
697 case 'i': /* include search path */
699 pp_include_path(param
);
702 case 'l': /* listing file */
703 copy_filename(listname
, param
);
706 case 'Z': /* error messages file */
707 strcpy(errname
, param
);
710 case 'F': /* specify debug format */
711 ofmt
->current_dfmt
= dfmt_find(ofmt
, param
);
712 if (!ofmt
->current_dfmt
) {
713 report_error(ERR_FATAL
| ERR_NOFILE
| ERR_USAGE
,
714 "unrecognized debug format `%s' for"
715 " output format `%s'",
716 param
, ofmt
->shortname
);
718 using_debug_info
= true;
721 case 'X': /* specify error reporting format */
722 if (nasm_stricmp("vc", param
) == 0)
723 report_error
= report_error_vc
;
724 else if (nasm_stricmp("gnu", param
) == 0)
725 report_error
= report_error_gnu
;
727 report_error(ERR_FATAL
| ERR_NOFILE
| ERR_USAGE
,
728 "unrecognized error reporting format `%s'",
733 using_debug_info
= true;
738 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
740 " [options...] [--] filename\n"
741 " or nasm -v for version info\n\n"
742 " -t assemble in SciTech TASM compatible mode\n"
743 " -g generate debug information in selected format.\n");
745 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
746 " -a don't preprocess (assemble only)\n"
747 " -M generate Makefile dependencies on stdout\n"
748 " -MG d:o, missing files assumed generated\n\n"
749 " -Z<file> redirect error messages to file\n"
750 " -s redirect error messages to stdout\n\n"
751 " -F format select a debugging format\n\n"
752 " -I<path> adds a pathname to the include file path\n");
754 (" -O<digit> optimize branch offsets (-O0 disables, default)\n"
755 " -P<file> pre-includes a file\n"
756 " -D<macro>[=<value>] pre-defines a macro\n"
757 " -U<macro> undefines a macro\n"
758 " -X<format> specifies error reporting format (gnu or vc)\n"
759 " -w+foo enables warning foo (equiv. -Wfoo)\n"
760 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
762 for (i
= 0; i
<= ERR_WARN_MAX
; i
++)
763 printf(" %-23s %s (default %s)\n",
764 warnings
[i
].name
, warnings
[i
].help
,
765 warnings
[i
].enabled
? "on" : "off");
767 ("\nresponse files should contain command line parameters"
768 ", one per line.\n");
770 printf("\nvalid output formats for -f are"
771 " (`*' denotes default):\n");
772 ofmt_list(ofmt
, stdout
);
774 printf("\nFor a list of valid output formats, use -hf.\n");
775 printf("For a list of debug formats, use -f <form> -y.\n");
777 exit(0); /* never need usage message here */
781 printf("\nvalid debug formats for '%s' output format are"
782 " ('*' denotes default):\n", ofmt
->shortname
);
783 dfmt_list(ofmt
, stdout
);
788 tasm_compatible_mode
= true;
792 printf("NASM version %s compiled on %s%s\n",
793 nasm_version
, nasm_date
, nasm_compile_options
);
794 exit(0); /* never need usage message here */
797 case 'e': /* preprocess only */
799 operating_mode
= op_preprocess
;
802 case 'a': /* assemble only - don't preprocess */
807 if (param
[0] == 'n' && param
[1] == 'o' && param
[2] == '-') {
816 if (param
[0] != '+' && param
[0] != '-') {
817 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
818 "invalid option to `-w'");
821 do_warn
= (param
[0] == '+');
825 for (i
= 0; i
<= ERR_WARN_MAX
; i
++)
826 if (!nasm_stricmp(param
, warnings
[i
].name
))
828 if (i
<= ERR_WARN_MAX
)
829 warning_on_global
[i
] = do_warn
;
830 else if (!nasm_stricmp(param
, "all"))
831 for (i
= 1; i
<= ERR_WARN_MAX
; i
++)
832 warning_on_global
[i
] = do_warn
;
833 else if (!nasm_stricmp(param
, "none"))
834 for (i
= 1; i
<= ERR_WARN_MAX
; i
++)
835 warning_on_global
[i
] = !do_warn
;
837 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
838 "invalid warning `%s'", param
);
844 operating_mode
= op_depend
;
847 operating_mode
= op_depend
;
848 depend_missing_ok
= true;
851 depend_emit_phony
= true;
862 depend_target
= quote_for_make(q
);
866 report_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
867 "unknown dependency option `-M%c'", p
[2]);
870 if (advance
&& (!q
|| !q
[0])) {
871 report_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
872 "option `-M%c' requires a parameter", p
[2]);
881 if (p
[2] == 0) { /* -- => stop processing options */
885 for (s
= 0; textopts
[s
].label
; s
++) {
886 if (!nasm_stricmp(p
+ 2, textopts
[s
].label
)) {
897 report_error(ERR_NONFATAL
| ERR_NOFILE
|
899 "option `--%s' requires an argument",
903 advance
= 1, param
= q
;
906 if (s
== OPT_PREFIX
) {
907 strncpy(lprefix
, param
, PREFIX_MAX
- 1);
908 lprefix
[PREFIX_MAX
- 1] = 0;
911 if (s
== OPT_POSTFIX
) {
912 strncpy(lpostfix
, param
, POSTFIX_MAX
- 1);
913 lpostfix
[POSTFIX_MAX
- 1] = 0;
920 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
921 "unrecognised option `--%s'", p
+ 2);
929 if (!ofmt
->setinfo(GI_SWITCH
, &p
))
930 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
931 "unrecognised option `-%c'", p
[1]);
936 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
937 "more than one input file specified");
939 copy_filename(inname
, p
);
946 #define ARG_BUF_DELTA 128
948 static void process_respfile(FILE * rfile
)
950 char *buffer
, *p
, *q
, *prevarg
;
951 int bufsize
, prevargsize
;
953 bufsize
= prevargsize
= ARG_BUF_DELTA
;
954 buffer
= nasm_malloc(ARG_BUF_DELTA
);
955 prevarg
= nasm_malloc(ARG_BUF_DELTA
);
958 while (1) { /* Loop to handle all lines in file */
960 while (1) { /* Loop to handle long lines */
961 q
= fgets(p
, bufsize
- (p
- buffer
), rfile
);
965 if (p
> buffer
&& p
[-1] == '\n')
967 if (p
- buffer
> bufsize
- 10) {
970 bufsize
+= ARG_BUF_DELTA
;
971 buffer
= nasm_realloc(buffer
, bufsize
);
976 if (!q
&& p
== buffer
) {
978 process_arg(prevarg
, NULL
);
985 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
986 * them are present at the end of the line.
988 *(p
= &buffer
[strcspn(buffer
, "\r\n\032")]) = '\0';
990 while (p
> buffer
&& nasm_isspace(p
[-1]))
994 while (nasm_isspace(*p
))
997 if (process_arg(prevarg
, p
))
1000 if ((int) strlen(p
) > prevargsize
- 10) {
1001 prevargsize
+= ARG_BUF_DELTA
;
1002 prevarg
= nasm_realloc(prevarg
, prevargsize
);
1004 strncpy(prevarg
, p
, prevargsize
);
1008 /* Function to process args from a string of args, rather than the
1009 * argv array. Used by the environment variable and response file
1012 static void process_args(char *args
)
1014 char *p
, *q
, *arg
, *prevarg
;
1015 char separator
= ' ';
1018 if (*p
&& *p
!= '-')
1023 while (*p
&& *p
!= separator
)
1025 while (*p
== separator
)
1029 if (process_arg(prevarg
, arg
))
1033 process_arg(arg
, NULL
);
1036 static void process_response_file(const char *file
)
1039 FILE *f
= fopen(file
, "r");
1044 while (fgets(str
, sizeof str
, f
)) {
1050 static void parse_cmdline(int argc
, char **argv
)
1053 char *envreal
, *envcopy
= NULL
, *p
, *arg
;
1056 *inname
= *outname
= *listname
= *errname
= '\0';
1057 for (i
= 0; i
<= ERR_WARN_MAX
; i
++)
1058 warning_on_global
[i
] = warnings
[i
].enabled
;
1061 * First, process the NASMENV environment variable.
1063 envreal
= getenv("NASMENV");
1066 envcopy
= nasm_strdup(envreal
);
1067 process_args(envcopy
);
1072 * Now process the actual command line.
1077 if (argv
[0][0] == '@') {
1078 /* We have a response file, so process this as a set of
1079 * arguments like the environment variable. This allows us
1080 * to have multiple arguments on a single line, which is
1081 * different to the -@resp file processing below for regular
1084 process_response_file(argv
[0]+1);
1088 if (!stopoptions
&& argv
[0][0] == '-' && argv
[0][1] == '@') {
1089 p
= get_param(argv
[0], argc
> 1 ? argv
[1] : NULL
, &advance
);
1091 rfile
= fopen(p
, "r");
1093 process_respfile(rfile
);
1096 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1097 "unable to open response file `%s'", p
);
1100 advance
= process_arg(argv
[0], argc
> 1 ? argv
[1] : NULL
);
1101 argv
+= advance
, argc
-= advance
;
1104 /* Look for basic command line typos. This definitely doesn't
1105 catch all errors, but it might help cases of fumbled fingers. */
1107 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1108 "no input file specified");
1109 else if (!strcmp(inname
, errname
) ||
1110 !strcmp(inname
, outname
) ||
1111 !strcmp(inname
, listname
) ||
1112 (depend_file
&& !strcmp(inname
, depend_file
)))
1113 report_error(ERR_FATAL
| ERR_NOFILE
| ERR_USAGE
,
1114 "file `%s' is both input and output file",
1118 error_file
= fopen(errname
, "w");
1120 error_file
= stderr
; /* Revert to default! */
1121 report_error(ERR_FATAL
| ERR_NOFILE
| ERR_USAGE
,
1122 "cannot open file `%s' for error messages",
1128 /* List of directives */
1130 D_NONE
, D_ABSOLUTE
, D_BITS
, D_COMMON
, D_CPU
, D_DEBUG
, D_DEFAULT
,
1131 D_EXTERN
, D_FLOAT
, D_GLOBAL
, D_LIST
, D_SECTION
, D_SEGMENT
, D_WARNING
1133 static const char *directives
[] = {
1134 "", "absolute", "bits", "common", "cpu", "debug", "default",
1135 "extern", "float", "global", "list", "section", "segment", "warning"
1137 static enum directives
getkw(char **directive
, char **value
);
1139 static void assemble_file(char *fname
, StrList
**depend_ptr
)
1141 char *directive
, *value
, *p
, *q
, *special
, *line
, debugid
[80];
1147 struct tokenval tokval
;
1151 if (cmd_sb
== 32 && cmd_cpu
< IF_386
)
1152 report_error(ERR_FATAL
, "command line: "
1153 "32-bit segment size requires a higher cpu");
1155 pass_max
= prev_offset_changed
= (INT_MAX
>> 1) + 2; /* Almost unlimited */
1156 for (passn
= 1; pass0
<= 2; passn
++) {
1160 pass1
= pass0
== 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1161 pass2
= passn
> 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1162 /* pass0 0, 0, 0, ..., 1, 2 */
1164 def_label
= passn
> 1 ? redefine_label
: define_label
;
1166 globalbits
= sb
= cmd_sb
; /* set 'bits' to command line default */
1170 nasmlist
.init(listname
, report_error
);
1173 global_offset_changed
= 0; /* set by redefine_label */
1174 location
.segment
= ofmt
->section(NULL
, pass2
, &sb
);
1177 saa_rewind(forwrefs
);
1178 forwref
= saa_rstruct(forwrefs
);
1180 offsets
= raa_init();
1182 preproc
->reset(fname
, pass1
, report_error
, evaluate
, &nasmlist
,
1183 pass1
== 2 ? depend_ptr
: NULL
);
1184 memcpy(warning_on
, warning_on_global
, (ERR_WARN_MAX
+1) * sizeof(bool));
1188 location
.known
= true;
1189 location
.offset
= offs
= GET_CURR_OFFS
;
1191 while ((line
= preproc
->getline())) {
1195 /* here we parse our directives; this is not handled by the 'real'
1198 d
= getkw(&directive
, &value
);
1203 case D_SEGMENT
: /* [SEGMENT n] */
1205 seg
= ofmt
->section(value
, pass2
, &sb
);
1206 if (seg
== NO_SEG
) {
1207 report_error(pass1
== 1 ? ERR_NONFATAL
: ERR_PANIC
,
1208 "segment name `%s' not recognized",
1212 location
.segment
= seg
;
1215 case D_EXTERN
: /* [EXTERN label:special] */
1217 value
++; /* skip initial $ if present */
1220 while (*q
&& *q
!= ':')
1224 ofmt
->symdef(value
, 0L, 0L, 3, q
);
1226 } else if (passn
== 1) {
1231 while (*q
&& *q
!= ':') {
1237 report_error(ERR_NONFATAL
,
1238 "identifier expected after EXTERN");
1246 if (!is_extern(value
)) { /* allow re-EXTERN to be ignored */
1248 pass0
= 1; /* fake pass 1 in labels.c */
1249 declare_as_global(value
, special
,
1251 define_label(value
, seg_alloc(), 0L, NULL
,
1252 false, true, ofmt
, report_error
);
1255 } /* else pass0 == 1 */
1257 case D_BITS
: /* [BITS bits] */
1258 globalbits
= sb
= get_bits(value
);
1260 case D_GLOBAL
: /* [GLOBAL symbol:special] */
1262 value
++; /* skip initial $ if present */
1263 if (pass0
== 2) { /* pass 2 */
1265 while (*q
&& *q
!= ':')
1269 ofmt
->symdef(value
, 0L, 0L, 3, q
);
1271 } else if (pass2
== 1) { /* pass == 1 */
1276 while (*q
&& *q
!= ':') {
1282 report_error(ERR_NONFATAL
,
1283 "identifier expected after GLOBAL");
1291 declare_as_global(value
, special
, report_error
);
1294 case D_COMMON
: /* [COMMON symbol size:special] */
1296 value
++; /* skip initial $ if present */
1302 while (*p
&& !nasm_isspace(*p
)) {
1308 report_error(ERR_NONFATAL
,
1309 "identifier expected after COMMON");
1315 while (*p
&& nasm_isspace(*p
))
1318 while (*q
&& *q
!= ':')
1325 size
= readnum(p
, &rn_error
);
1327 report_error(ERR_NONFATAL
,
1328 "invalid size specified"
1329 " in COMMON declaration");
1331 define_common(value
, seg_alloc(), size
,
1332 special
, ofmt
, report_error
);
1334 report_error(ERR_NONFATAL
,
1335 "no size specified in"
1336 " COMMON declaration");
1337 } else if (pass0
== 2) { /* pass == 2 */
1339 while (*q
&& *q
!= ':') {
1340 if (nasm_isspace(*q
))
1346 ofmt
->symdef(value
, 0L, 0L, 3, q
);
1350 case D_ABSOLUTE
: /* [ABSOLUTE address] */
1352 stdscan_bufptr
= value
;
1353 tokval
.t_type
= TOKEN_INVALID
;
1354 e
= evaluate(stdscan
, NULL
, &tokval
, NULL
, pass2
,
1355 report_error
, NULL
);
1358 report_error(pass0
==
1359 1 ? ERR_NONFATAL
: ERR_PANIC
,
1360 "cannot use non-relocatable expression as "
1361 "ABSOLUTE address");
1363 abs_seg
= reloc_seg(e
);
1364 abs_offset
= reloc_value(e
);
1366 } else if (passn
== 1)
1367 abs_offset
= 0x100; /* don't go near zero in case of / */
1369 report_error(ERR_PANIC
, "invalid ABSOLUTE address "
1372 location
.segment
= NO_SEG
;
1374 case D_DEBUG
: /* [DEBUG] */
1380 while (*p
&& !nasm_isspace(*p
)) {
1387 report_error(passn
== 1 ? ERR_NONFATAL
: ERR_PANIC
,
1388 "identifier expected after DEBUG");
1391 while (*p
&& nasm_isspace(*p
))
1394 ofmt
->current_dfmt
->debug_directive(debugid
, p
);
1396 case D_WARNING
: /* [WARNING {+|-|*}warn-name] */
1397 while (*value
&& nasm_isspace(*value
))
1401 case '-': validid
= 0; value
++; break;
1402 case '+': validid
= 1; value
++; break;
1403 case '*': validid
= 2; value
++; break;
1404 default: validid
= 1; break;
1407 for (i
= 1; i
<= ERR_WARN_MAX
; i
++)
1408 if (!nasm_stricmp(value
, warnings
[i
].name
))
1410 if (i
<= ERR_WARN_MAX
) {
1413 warning_on
[i
] = false;
1416 warning_on
[i
] = true;
1419 warning_on
[i
] = warning_on_global
[i
];
1424 report_error(ERR_NONFATAL
,
1425 "invalid warning id in WARNING directive");
1427 case D_CPU
: /* [CPU] */
1428 cpu
= get_cpu(value
);
1430 case D_LIST
: /* [LIST {+|-}] */
1431 while (*value
&& nasm_isspace(*value
))
1434 if (*value
== '+') {
1437 if (*value
== '-') {
1444 case D_DEFAULT
: /* [DEFAULT] */
1446 stdscan_bufptr
= value
;
1447 tokval
.t_type
= TOKEN_INVALID
;
1448 if (stdscan(NULL
, &tokval
) == TOKEN_SPECIAL
) {
1449 switch ((int)tokval
.t_integer
) {
1465 if (float_option(value
)) {
1466 report_error(pass1
== 1 ? ERR_NONFATAL
: ERR_PANIC
,
1467 "unknown 'float' directive: %s",
1472 if (!ofmt
->directive(directive
, value
, pass2
))
1473 report_error(pass1
== 1 ? ERR_NONFATAL
: ERR_PANIC
,
1474 "unrecognised directive [%s]",
1478 report_error(ERR_NONFATAL
,
1479 "invalid parameter to [%s] directive",
1482 } else { /* it isn't a directive */
1484 parse_line(pass1
, line
, &output_ins
,
1485 report_error
, evaluate
, def_label
);
1487 if (optimizing
> 0) {
1488 if (forwref
!= NULL
&& globallineno
== forwref
->lineno
) {
1489 output_ins
.forw_ref
= true;
1491 output_ins
.oprs
[forwref
->operand
].opflags
|=
1493 forwref
= saa_rstruct(forwrefs
);
1494 } while (forwref
!= NULL
1495 && forwref
->lineno
== globallineno
);
1497 output_ins
.forw_ref
= false;
1500 if (optimizing
> 0) {
1502 for (i
= 0; i
< output_ins
.operands
; i
++) {
1503 if (output_ins
.oprs
[i
].
1504 opflags
& OPFLAG_FORWARD
) {
1505 struct forwrefinfo
*fwinf
=
1506 (struct forwrefinfo
*)
1507 saa_wstruct(forwrefs
);
1508 fwinf
->lineno
= globallineno
;
1516 if (output_ins
.opcode
== I_EQU
) {
1519 * Special `..' EQUs get processed in pass two,
1520 * except `..@' macro-processor EQUs which are done
1521 * in the normal place.
1523 if (!output_ins
.label
)
1524 report_error(ERR_NONFATAL
,
1525 "EQU not preceded by label");
1527 else if (output_ins
.label
[0] != '.' ||
1528 output_ins
.label
[1] != '.' ||
1529 output_ins
.label
[2] == '@') {
1530 if (output_ins
.operands
== 1 &&
1531 (output_ins
.oprs
[0].type
& IMMEDIATE
) &&
1532 output_ins
.oprs
[0].wrt
== NO_SEG
) {
1533 bool isext
= !!(output_ins
.oprs
[0].opflags
1535 def_label(output_ins
.label
,
1536 output_ins
.oprs
[0].segment
,
1537 output_ins
.oprs
[0].offset
, NULL
,
1540 } else if (output_ins
.operands
== 2
1541 && (output_ins
.oprs
[0].type
& IMMEDIATE
)
1542 && (output_ins
.oprs
[0].type
& COLON
)
1543 && output_ins
.oprs
[0].segment
== NO_SEG
1544 && output_ins
.oprs
[0].wrt
== NO_SEG
1545 && (output_ins
.oprs
[1].type
& IMMEDIATE
)
1546 && output_ins
.oprs
[1].segment
== NO_SEG
1547 && output_ins
.oprs
[1].wrt
== NO_SEG
) {
1548 def_label(output_ins
.label
,
1549 output_ins
.oprs
[0].offset
| SEG_ABS
,
1550 output_ins
.oprs
[1].offset
,
1551 NULL
, false, false, ofmt
,
1554 report_error(ERR_NONFATAL
,
1555 "bad syntax for EQU");
1559 * Special `..' EQUs get processed here, except
1560 * `..@' macro processor EQUs which are done above.
1562 if (output_ins
.label
[0] == '.' &&
1563 output_ins
.label
[1] == '.' &&
1564 output_ins
.label
[2] != '@') {
1565 if (output_ins
.operands
== 1 &&
1566 (output_ins
.oprs
[0].type
& IMMEDIATE
)) {
1567 define_label(output_ins
.label
,
1568 output_ins
.oprs
[0].segment
,
1569 output_ins
.oprs
[0].offset
,
1570 NULL
, false, false, ofmt
,
1572 } else if (output_ins
.operands
== 2
1573 && (output_ins
.oprs
[0].
1575 && (output_ins
.oprs
[0].type
& COLON
)
1576 && output_ins
.oprs
[0].segment
==
1578 && (output_ins
.oprs
[1].
1580 && output_ins
.oprs
[1].segment
==
1582 define_label(output_ins
.label
,
1585 output_ins
.oprs
[1].offset
,
1586 NULL
, false, false, ofmt
,
1589 report_error(ERR_NONFATAL
,
1590 "bad syntax for EQU");
1593 } else { /* instruction isn't an EQU */
1597 int64_t l
= insn_size(location
.segment
, offs
, sb
, cpu
,
1598 &output_ins
, report_error
);
1600 /* if (using_debug_info) && output_ins.opcode != -1) */
1601 if (using_debug_info
)
1602 { /* fbk 03/25/01 */
1603 /* this is done here so we can do debug type info */
1605 TYS_ELEMENTS(output_ins
.operands
);
1606 switch (output_ins
.opcode
) {
1609 TYS_ELEMENTS(output_ins
.oprs
[0].
1614 TYS_ELEMENTS(output_ins
.oprs
[0].
1619 TYS_ELEMENTS(output_ins
.oprs
[0].
1624 TYS_ELEMENTS(output_ins
.oprs
[0].
1629 TYS_ELEMENTS(output_ins
.oprs
[0].
1634 TYS_ELEMENTS(output_ins
.oprs
[0].
1639 TYS_ELEMENTS(output_ins
.oprs
[0].
1643 typeinfo
|= TY_BYTE
;
1646 typeinfo
|= TY_WORD
;
1649 if (output_ins
.eops_float
)
1650 typeinfo
|= TY_FLOAT
;
1652 typeinfo
|= TY_DWORD
;
1655 typeinfo
|= TY_QWORD
;
1658 typeinfo
|= TY_TBYTE
;
1661 typeinfo
|= TY_OWORD
;
1664 typeinfo
|= TY_YWORD
;
1667 typeinfo
= TY_LABEL
;
1671 ofmt
->current_dfmt
->debug_typevalue(typeinfo
);
1676 SET_CURR_OFFS(offs
);
1679 * else l == -1 => invalid instruction, which will be
1680 * flagged as an error on pass 2
1684 offs
+= assemble(location
.segment
, offs
, sb
, cpu
,
1685 &output_ins
, ofmt
, report_error
,
1687 SET_CURR_OFFS(offs
);
1691 cleanup_insn(&output_ins
);
1694 location
.offset
= offs
= GET_CURR_OFFS
;
1695 } /* end while (line = preproc->getline... */
1696 if (pass1
== 2 && global_offset_changed
)
1697 report_error(ERR_NONFATAL
,
1698 "phase error detected at end of assembly.");
1701 preproc
->cleanup(1);
1703 if (pass1
== 1 && terminate_after_phase
) {
1711 if ((passn
> 1 && !global_offset_changed
) || pass0
== 2)
1713 else if (global_offset_changed
&& global_offset_changed
< prev_offset_changed
) {
1714 prev_offset_changed
= global_offset_changed
;
1719 if((stall_count
> 997) || (passn
>= pass_max
))
1720 /* We get here if the labels don't converge
1721 * Example: FOO equ FOO + 1
1723 report_error(ERR_NONFATAL
,
1724 "Can't find valid values for all labels "
1725 "after %d passes, giving up.\n"
1726 " Possible cause: recursive equ's.", passn
);
1729 preproc
->cleanup(0);
1731 if (opt_verbose_info
) /* -On and -Ov switches */
1733 "info:: assembly required 1+%d+1 passes\n", passn
-3);
1734 } /* exit from assemble_file (...) */
1736 static enum directives
getkw(char **directive
, char **value
)
1742 /* allow leading spaces or tabs */
1743 while (*buf
== ' ' || *buf
== '\t')
1751 while (*p
&& *p
!= ']')
1759 while (*p
&& *p
!= ';') {
1760 if (!nasm_isspace(*p
))
1766 *directive
= p
= buf
+ 1;
1767 while (*buf
&& *buf
!= ' ' && *buf
!= ']' && *buf
!= '\t')
1774 while (nasm_isspace(*buf
))
1775 buf
++; /* beppu - skip leading whitespace */
1782 return bsii(*directive
, directives
, elements(directives
));
1786 * gnu style error reporting
1787 * This function prints an error message to error_file in the
1788 * style used by GNU. An example would be:
1789 * file.asm:50: error: blah blah blah
1790 * where file.asm is the name of the file, 50 is the line number on
1791 * which the error occurs (or is detected) and "error:" is one of
1792 * the possible optional diagnostics -- it can be "error" or "warning"
1793 * or something else. Finally the line terminates with the actual
1796 * @param severity the severity of the warning or error
1797 * @param fmt the printf style format string
1799 static void report_error_gnu(int severity
, const char *fmt
, ...)
1803 if (is_suppressed_warning(severity
))
1806 if (severity
& ERR_NOFILE
)
1807 fputs("nasm: ", error_file
);
1809 char *currentfile
= NULL
;
1811 src_get(&lineno
, ¤tfile
);
1812 fprintf(error_file
, "%s:%"PRId32
": ", currentfile
, lineno
);
1813 nasm_free(currentfile
);
1816 report_error_common(severity
, fmt
, ap
);
1821 * MS style error reporting
1822 * This function prints an error message to error_file in the
1823 * style used by Visual C and some other Microsoft tools. An example
1825 * file.asm(50) : error: blah blah blah
1826 * where file.asm is the name of the file, 50 is the line number on
1827 * which the error occurs (or is detected) and "error:" is one of
1828 * the possible optional diagnostics -- it can be "error" or "warning"
1829 * or something else. Finally the line terminates with the actual
1832 * @param severity the severity of the warning or error
1833 * @param fmt the printf style format string
1835 static void report_error_vc(int severity
, const char *fmt
, ...)
1839 if (is_suppressed_warning(severity
))
1842 if (severity
& ERR_NOFILE
)
1843 fputs("nasm: ", error_file
);
1845 char *currentfile
= NULL
;
1847 src_get(&lineno
, ¤tfile
);
1848 fprintf(error_file
, "%s(%"PRId32
") : ", currentfile
, lineno
);
1849 nasm_free(currentfile
);
1852 report_error_common(severity
, fmt
, ap
);
1857 * check for supressed warning
1858 * checks for suppressed warning or pass one only warning and we're
1861 * @param severity the severity of the warning or error
1862 * @return true if we should abort error/warning printing
1864 static bool is_suppressed_warning(int severity
)
1867 * See if it's a suppressed warning.
1869 return (severity
& ERR_MASK
) == ERR_WARNING
&&
1870 (((severity
& ERR_WARN_MASK
) != 0 &&
1871 !warning_on
[(severity
& ERR_WARN_MASK
) >> ERR_WARN_SHR
]) ||
1872 /* See if it's a pass-one only warning and we're not in pass one. */
1873 ((severity
& ERR_PASS1
) && pass0
!= 1) ||
1874 ((severity
& ERR_PASS2
) && pass0
!= 2));
1878 * common error reporting
1879 * This is the common back end of the error reporting schemes currently
1880 * implemented. It prints the nature of the warning and then the
1881 * specific error message to error_file and may or may not return. It
1882 * doesn't return if the error severity is a "panic" or "debug" type.
1884 * @param severity the severity of the warning or error
1885 * @param fmt the printf style format string
1887 static void report_error_common(int severity
, const char *fmt
,
1890 switch (severity
& (ERR_MASK
|ERR_NO_SEVERITY
)) {
1892 fputs("warning: ", error_file
);
1895 fputs("error: ", error_file
);
1898 fputs("fatal: ", error_file
);
1901 fputs("panic: ", error_file
);
1904 fputs("debug: ", error_file
);
1910 vfprintf(error_file
, fmt
, args
);
1911 putc('\n', error_file
);
1913 if (severity
& ERR_USAGE
)
1916 switch (severity
& ERR_MASK
) {
1918 /* no further action, by definition */
1921 if (warning_on
[0]) /* Treat warnings as errors */
1922 terminate_after_phase
= true;
1925 terminate_after_phase
= true;
1934 exit(1); /* instantly die */
1935 break; /* placate silly compilers */
1938 /* abort(); *//* halt, catch fire, and dump core */
1944 static void usage(void)
1946 fputs("type `nasm -h' for help\n", error_file
);
1949 static void register_output_formats(void)
1951 ofmt
= ofmt_register(report_error
);
1954 #define BUF_DELTA 512
1956 static FILE *no_pp_fp
;
1957 static efunc no_pp_err
;
1958 static ListGen
*no_pp_list
;
1959 static int32_t no_pp_lineinc
;
1961 static void no_pp_reset(char *file
, int pass
, efunc error
, evalfunc eval
,
1962 ListGen
* listgen
, StrList
**deplist
)
1964 src_set_fname(nasm_strdup(file
));
1968 no_pp_fp
= fopen(file
, "r");
1970 no_pp_err(ERR_FATAL
| ERR_NOFILE
,
1971 "unable to open input file `%s'", file
);
1972 no_pp_list
= listgen
;
1973 (void)pass
; /* placate compilers */
1974 (void)eval
; /* placate compilers */
1977 StrList
*sl
= nasm_malloc(strlen(file
)+1+sizeof sl
->next
);
1979 strcpy(sl
->str
, file
);
1984 static char *no_pp_getline(void)
1986 char *buffer
, *p
, *q
;
1989 bufsize
= BUF_DELTA
;
1990 buffer
= nasm_malloc(BUF_DELTA
);
1991 src_set_linnum(src_get_linnum() + no_pp_lineinc
);
1993 while (1) { /* Loop to handle %line */
1996 while (1) { /* Loop to handle long lines */
1997 q
= fgets(p
, bufsize
- (p
- buffer
), no_pp_fp
);
2001 if (p
> buffer
&& p
[-1] == '\n')
2003 if (p
- buffer
> bufsize
- 10) {
2005 offset
= p
- buffer
;
2006 bufsize
+= BUF_DELTA
;
2007 buffer
= nasm_realloc(buffer
, bufsize
);
2008 p
= buffer
+ offset
;
2012 if (!q
&& p
== buffer
) {
2018 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2019 * them are present at the end of the line.
2021 buffer
[strcspn(buffer
, "\r\n\032")] = '\0';
2023 if (!nasm_strnicmp(buffer
, "%line", 5)) {
2026 char *nm
= nasm_malloc(strlen(buffer
));
2027 if (sscanf(buffer
+ 5, "%"PRId32
"+%d %s", &ln
, &li
, nm
) == 3) {
2028 nasm_free(src_set_fname(nm
));
2038 no_pp_list
->line(LIST_READ
, buffer
);
2043 static void no_pp_cleanup(int pass
)
2045 (void)pass
; /* placate GCC */
2049 static uint32_t get_cpu(char *value
)
2051 if (!strcmp(value
, "8086"))
2053 if (!strcmp(value
, "186"))
2055 if (!strcmp(value
, "286"))
2057 if (!strcmp(value
, "386"))
2059 if (!strcmp(value
, "486"))
2061 if (!strcmp(value
, "586") || !nasm_stricmp(value
, "pentium"))
2063 if (!strcmp(value
, "686") ||
2064 !nasm_stricmp(value
, "ppro") ||
2065 !nasm_stricmp(value
, "pentiumpro") || !nasm_stricmp(value
, "p2"))
2067 if (!nasm_stricmp(value
, "p3") || !nasm_stricmp(value
, "katmai"))
2069 if (!nasm_stricmp(value
, "p4") || /* is this right? -- jrc */
2070 !nasm_stricmp(value
, "willamette"))
2071 return IF_WILLAMETTE
;
2072 if (!nasm_stricmp(value
, "prescott"))
2074 if (!nasm_stricmp(value
, "x64") ||
2075 !nasm_stricmp(value
, "x86-64"))
2077 if (!nasm_stricmp(value
, "ia64") ||
2078 !nasm_stricmp(value
, "ia-64") ||
2079 !nasm_stricmp(value
, "itanium") ||
2080 !nasm_stricmp(value
, "itanic") || !nasm_stricmp(value
, "merced"))
2083 report_error(pass0
< 2 ? ERR_NONFATAL
: ERR_FATAL
,
2084 "unknown 'cpu' type");
2086 return IF_PLEVEL
; /* the maximum level */
2089 static int get_bits(char *value
)
2093 if ((i
= atoi(value
)) == 16)
2094 return i
; /* set for a 16-bit segment */
2097 report_error(ERR_NONFATAL
,
2098 "cannot specify 32-bit segment on processor below a 386");
2101 } else if (i
== 64) {
2102 if (cpu
< IF_X86_64
) {
2103 report_error(ERR_NONFATAL
,
2104 "cannot specify 64-bit segment on processor below an x86-64");
2108 report_error(ERR_NONFATAL
,
2109 "%s output format does not support 64-bit code",
2114 report_error(pass0
< 2 ? ERR_NONFATAL
: ERR_FATAL
,
2115 "`%s' is not a valid segment size; must be 16, 32 or 64",