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.
33 struct forwrefinfo
{ /* info held on forward refs. */
38 static int get_bits(char *value
);
39 static uint32_t get_cpu(char *cpu_str
);
40 static void parse_cmdline(int, char **);
41 static void assemble_file(char *, FILE *);
42 static void register_output_formats(void);
43 static void report_error_gnu(int severity
, const char *fmt
, ...);
44 static void report_error_vc(int severity
, const char *fmt
, ...);
45 static void report_error_common(int severity
, const char *fmt
,
47 static bool is_suppressed_warning(int severity
);
48 static void usage(void);
49 static efunc report_error
;
51 static int using_debug_info
, opt_verbose_info
;
52 bool tasm_compatible_mode
= false;
57 time_t official_compile_time
;
59 static char inname
[FILENAME_MAX
];
60 static char outname
[FILENAME_MAX
];
61 static char listname
[FILENAME_MAX
];
62 static char errname
[FILENAME_MAX
];
63 static int globallineno
; /* for forward-reference tracking */
64 /* static int pass = 0; */
65 static struct ofmt
*ofmt
= NULL
;
67 static FILE *error_file
; /* Where to write error messages */
69 static FILE *ofile
= NULL
;
70 int optimizing
= -1; /* number of optimization passes to take */
71 static int sb
, cmd_sb
= 16; /* by default */
72 static uint32_t cmd_cpu
= IF_PLEVEL
; /* highest level by default */
73 static uint32_t cpu
= IF_PLEVEL
; /* passed to insn_size & assemble.c */
74 bool global_offset_changed
; /* referenced in labels.c */
76 static struct location location
;
77 int in_abs_seg
; /* Flag we are in ABSOLUTE seg */
78 int32_t abs_seg
; /* ABSOLUTE segment basis */
79 int32_t abs_offset
; /* ABSOLUTE offset */
81 static struct RAA
*offsets
;
83 static struct SAA
*forwrefs
; /* keep track of forward references */
84 static const struct forwrefinfo
*forwref
;
86 static Preproc
*preproc
;
88 op_normal
, /* Preprocess and assemble */
89 op_preprocess
, /* Preprocess only */
90 op_depend
, /* Generate dependencies */
92 static enum op_type operating_mode
;
93 /* Dependency flags */
94 static bool depend_missing_ok
= false;
95 static const char *depend_target
= NULL
;
96 static const char *depend_file
= NULL
;
99 * Which of the suppressible warnings are suppressed. Entry zero
100 * isn't an actual warning, but it used for -w+error/-Werror.
102 static bool suppressed
[ERR_WARN_MAX
+1] = {
103 true, false, true, false, false, true, false, true, true, false
107 * The option names for the suppressible warnings. As before, entry
110 static const char *suppressed_names
[ERR_WARN_MAX
+1] = {
111 "error", "macro-params", "macro-selfref", "orphan-labels",
112 "number-overflow", "gnu-elf-extensions", "float-overflow",
113 "float-denorm", "float-underflow", "float-toolong"
117 * The explanations for the suppressible warnings. As before, entry
120 static const char *suppressed_what
[ERR_WARN_MAX
+1] = {
121 "treat warnings as errors",
122 "macro calls with wrong parameter count",
123 "cyclic macro references",
124 "labels alone on lines without trailing `:'",
125 "numeric constants does not fit in 64 bits",
126 "using 8- or 16-bit relocation in ELF32, a GNU extension",
127 "floating point overflow",
128 "floating point denormal",
129 "floating point underflow",
130 "too many digits in floating-point number"
134 * This is a null preprocessor which just copies lines from input
135 * to output. It's used when someone explicitly requests that NASM
136 * not preprocess their source file.
139 static void no_pp_reset(char *, int, efunc
, evalfunc
, ListGen
*, FILE *);
140 static char *no_pp_getline(void);
141 static void no_pp_cleanup(int);
142 static Preproc no_pp
= {
149 * get/set current offset...
151 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
152 raa_read(offsets,location.segment))
153 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
154 (void)(offsets=raa_write(offsets,location.segment,(x))))
156 static int want_usage
;
157 static int terminate_after_phase
;
158 int user_nolist
= 0; /* fbk 9/2/00 */
160 static void nasm_fputs(const char *line
, FILE * outfile
)
163 fputs(line
, outfile
);
169 /* Convert a struct tm to a POSIX-style time constant */
170 static int64_t posix_mktime(struct tm
*tm
)
173 int64_t y
= tm
->tm_year
;
175 /* See IEEE 1003.1:2004, section 4.14 */
177 t
= (y
-70)*365 + (y
-69)/4 - (y
-1)/100 + (y
+299)/400;
189 static void define_macros_early(void)
192 struct tm lt
, *lt_p
, gm
, *gm_p
;
195 lt_p
= localtime(&official_compile_time
);
199 strftime(temp
, sizeof temp
, "__DATE__=\"%Y-%m-%d\"", <
);
201 strftime(temp
, sizeof temp
, "__DATE_NUM__=%Y%m%d", <
);
203 strftime(temp
, sizeof temp
, "__TIME__=\"%H:%M:%S\"", <
);
205 strftime(temp
, sizeof temp
, "__TIME_NUM__=%H%M%S", <
);
209 gm_p
= gmtime(&official_compile_time
);
213 strftime(temp
, sizeof temp
, "__UTC_DATE__=\"%Y-%m-%d\"", &gm
);
215 strftime(temp
, sizeof temp
, "__UTC_DATE_NUM__=%Y%m%d", &gm
);
217 strftime(temp
, sizeof temp
, "__UTC_TIME__=\"%H:%M:%S\"", &gm
);
219 strftime(temp
, sizeof temp
, "__UTC_TIME_NUM__=%H%M%S", &gm
);
224 posix_time
= posix_mktime(&gm
);
226 posix_time
= posix_mktime(<
);
231 snprintf(temp
, sizeof temp
, "__POSIX_TIME__=%"PRId64
, posix_time
);
236 static void define_macros_late(void)
240 snprintf(temp
, sizeof(temp
), "__OUTPUT_FORMAT__=%s\n",
245 int main(int argc
, char **argv
)
249 time(&official_compile_time
);
252 want_usage
= terminate_after_phase
= false;
253 report_error
= report_error_gnu
;
257 nasm_set_malloc_error(report_error
);
258 offsets
= raa_init();
259 forwrefs
= saa_init((int32_t)sizeof(struct forwrefinfo
));
262 operating_mode
= op_normal
;
266 register_output_formats();
268 /* Define some macros dependent on the runtime, but not
269 on the command line. */
270 define_macros_early();
272 parse_cmdline(argc
, argv
);
274 if (terminate_after_phase
) {
280 /* If debugging info is disabled, suppress any debug calls */
281 if (!using_debug_info
)
282 ofmt
->current_dfmt
= &null_debug_form
;
285 pp_extra_stdmac(ofmt
->stdmac
);
286 parser_global_info(ofmt
, &location
);
287 eval_global_info(ofmt
, lookup_label
, &location
);
289 /* define some macros dependent of command-line */
290 define_macros_late();
294 depends
= fopen(depend_file
, "w");
296 report_error(ERR_FATAL
| ERR_NOFILE
,
297 "unable to open dependencies file `%s'",
303 depend_target
= outname
;
305 switch (operating_mode
) {
313 if (depend_missing_ok
)
314 pp_include_path(NULL
); /* "assume generated" */
316 preproc
->reset(inname
, 0, report_error
, evaluate
, &nasmlist
,
318 if (outname
[0] == '\0')
319 ofmt
->filename(inname
, outname
, report_error
);
321 fprintf(depends
, "%s: %s", depend_target
, inname
);
322 while ((line
= preproc
->getline()))
331 char *file_name
= NULL
;
332 int32_t prior_linnum
= 0;
336 ofile
= fopen(outname
, "w");
338 report_error(ERR_FATAL
| ERR_NOFILE
,
339 "unable to open output file `%s'",
344 location
.known
= false;
347 preproc
->reset(inname
, 2, report_error
, evaluate
, &nasmlist
,
350 fprintf(depends
, "%s: %s", depend_target
, inname
);
352 while ((line
= preproc
->getline())) {
354 * We generate %line directives if needed for later programs
356 int32_t linnum
= prior_linnum
+= lineinc
;
357 int altline
= src_get(&linnum
, &file_name
);
359 if (altline
== 1 && lineinc
== 1)
360 nasm_fputs("", ofile
);
362 lineinc
= (altline
!= -1 || lineinc
!= 1);
363 fprintf(ofile
? ofile
: stdout
,
364 "%%line %"PRId32
"+%d %s\n", linnum
, lineinc
,
367 prior_linnum
= linnum
;
369 nasm_fputs(line
, ofile
);
372 nasm_free(file_name
);
376 if (ofile
&& terminate_after_phase
)
384 * We must call ofmt->filename _anyway_, even if the user
385 * has specified their own output file, because some
386 * formats (eg OBJ and COFF) use ofmt->filename to find out
387 * the name of the input file and then put that inside the
390 ofmt
->filename(inname
, outname
, report_error
);
392 ofile
= fopen(outname
, "wb");
394 report_error(ERR_FATAL
| ERR_NOFILE
,
395 "unable to open output file `%s'", outname
);
399 * We must call init_labels() before ofmt->init() since
400 * some object formats will want to define labels in their
401 * init routines. (eg OS/2 defines the FLAT group)
405 ofmt
->init(ofile
, report_error
, define_label
, evaluate
);
407 assemble_file(inname
, depends
);
409 if (!terminate_after_phase
) {
410 ofmt
->cleanup(using_debug_info
);
414 * We had an fclose on the output file here, but we
415 * actually do that in all the object file drivers as well,
416 * so we're leaving out the one here.
429 if (depends
!= stdout
)
441 if (terminate_after_phase
)
448 * Get a parameter for a command line option.
449 * First arg must be in the form of e.g. -f...
451 static char *get_param(char *p
, char *q
, bool *advance
)
454 if (p
[2]) { /* the parameter's in the option */
464 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
465 "option `-%c' requires an argument", p
[1]);
472 static void copy_filename(char *dst
, const char *src
)
474 size_t len
= strlen(src
);
476 if (len
>= (size_t)FILENAME_MAX
) {
477 report_error(ERR_FATAL
| ERR_NOFILE
, "file name too long");
480 strncpy(dst
, src
, FILENAME_MAX
);
484 * Convert a string to Make-safe form
486 static char *quote_for_make(const char *str
)
491 size_t n
= 1; /* Terminating zero */
497 for (p
= str
; *p
; p
++) {
501 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
521 /* Convert N backslashes at the end of filename to 2N backslashes */
525 os
= q
= nasm_malloc(n
);
528 for (p
= str
; *p
; p
++) {
571 #define OPT_POSTFIX 1
572 struct textargs textopts
[] = {
573 {"prefix", OPT_PREFIX
},
574 {"postfix", OPT_POSTFIX
},
578 static bool stopoptions
= false;
579 static bool process_arg(char *p
, char *q
)
583 bool advance
= false;
589 if (p
[0] == '-' && !stopoptions
) {
590 if (strchr("oOfpPdDiIlFXuUZwW", p
[1])) {
591 /* These parameters take values */
592 if (!(param
= get_param(p
, q
, &advance
)))
601 case 'o': /* output file */
602 copy_filename(outname
, param
);
605 case 'f': /* output format */
606 ofmt
= ofmt_find(param
);
608 report_error(ERR_FATAL
| ERR_NOFILE
| ERR_USAGE
,
609 "unrecognised output format `%s' - "
610 "use -hf for a list", param
);
612 ofmt
->current_dfmt
= ofmt
->debug_formats
[0];
616 case 'O': /* Optimization level */
621 /* Naked -O == -Ox */
622 optimizing
= INT_MAX
>> 1; /* Almost unlimited */
626 case '0': case '1': case '2': case '3': case '4':
627 case '5': case '6': case '7': case '8': case '9':
628 opt
= strtoul(param
, ¶m
, 10);
630 /* -O0 -> optimizing == -1, 0.98 behaviour */
631 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
633 optimizing
= opt
- 1;
641 opt_verbose_info
= true;
646 optimizing
= INT_MAX
>> 1; /* Almost unlimited */
650 report_error(ERR_FATAL
,
651 "unknown optimization option -O%c\n",
660 case 'p': /* pre-include */
662 pp_pre_include(param
);
665 case 'd': /* pre-define */
667 pp_pre_define(param
);
670 case 'u': /* un-define */
672 pp_pre_undefine(param
);
675 case 'i': /* include search path */
677 pp_include_path(param
);
680 case 'l': /* listing file */
681 copy_filename(listname
, param
);
684 case 'Z': /* error messages file */
685 strcpy(errname
, param
);
688 case 'F': /* specify debug format */
689 ofmt
->current_dfmt
= dfmt_find(ofmt
, param
);
690 if (!ofmt
->current_dfmt
) {
691 report_error(ERR_FATAL
| ERR_NOFILE
| ERR_USAGE
,
692 "unrecognized debug format `%s' for"
693 " output format `%s'",
694 param
, ofmt
->shortname
);
698 case 'X': /* specify error reporting format */
699 if (nasm_stricmp("vc", param
) == 0)
700 report_error
= report_error_vc
;
701 else if (nasm_stricmp("gnu", param
) == 0)
702 report_error
= report_error_gnu
;
704 report_error(ERR_FATAL
| ERR_NOFILE
| ERR_USAGE
,
705 "unrecognized error reporting format `%s'",
710 using_debug_info
= true;
715 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
717 " [options...] [--] filename\n"
718 " or nasm -v for version info\n\n"
719 " -t assemble in SciTech TASM compatible mode\n"
720 " -g generate debug information in selected format.\n");
722 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
723 " -a don't preprocess (assemble only)\n"
724 " -M generate Makefile dependencies on stdout\n"
725 " -MG d:o, missing files assumed generated\n\n"
726 " -Z<file> redirect error messages to file\n"
727 " -s redirect error messages to stdout\n\n"
728 " -F format select a debugging format\n\n"
729 " -I<path> adds a pathname to the include file path\n");
731 (" -O<digit> optimize branch offsets (-O0 disables, default)\n"
732 " -P<file> pre-includes a file\n"
733 " -D<macro>[=<value>] pre-defines a macro\n"
734 " -U<macro> undefines a macro\n"
735 " -X<format> specifies error reporting format (gnu or vc)\n"
736 " -w+foo enables warning foo (equiv. -Wfoo)\n"
737 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
739 for (i
= 0; i
<= ERR_WARN_MAX
; i
++)
740 printf(" %-23s %s (default %s)\n",
741 suppressed_names
[i
], suppressed_what
[i
],
742 suppressed
[i
] ? "off" : "on");
744 ("\nresponse files should contain command line parameters"
745 ", one per line.\n");
747 printf("\nvalid output formats for -f are"
748 " (`*' denotes default):\n");
749 ofmt_list(ofmt
, stdout
);
751 printf("\nFor a list of valid output formats, use -hf.\n");
752 printf("For a list of debug formats, use -f <form> -y.\n");
754 exit(0); /* never need usage message here */
758 printf("\nvalid debug formats for '%s' output format are"
759 " ('*' denotes default):\n", ofmt
->shortname
);
760 dfmt_list(ofmt
, stdout
);
765 tasm_compatible_mode
= true;
770 const char *nasm_version_string
=
771 "NASM version " NASM_VER
" compiled on " __DATE__
776 puts(nasm_version_string
);
777 exit(0); /* never need usage message here */
781 case 'e': /* preprocess only */
783 operating_mode
= op_preprocess
;
786 case 'a': /* assemble only - don't preprocess */
791 if (param
[0] == 'n' && param
[1] == 'o' && param
[2] == '-') {
800 if (param
[0] != '+' && param
[0] != '-') {
801 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
802 "invalid option to `-w'");
805 suppress
= (param
[0] == '-');
809 for (i
= 0; i
<= ERR_WARN_MAX
; i
++)
810 if (!nasm_stricmp(param
, suppressed_names
[i
]))
812 if (i
<= ERR_WARN_MAX
)
813 suppressed
[i
] = suppress
;
814 else if (!nasm_stricmp(param
, "all"))
815 for (i
= 1; i
<= ERR_WARN_MAX
; i
++)
816 suppressed
[i
] = suppress
;
817 else if (!nasm_stricmp(param
, "none"))
818 for (i
= 1; i
<= ERR_WARN_MAX
; i
++)
819 suppressed
[i
] = !suppress
;
821 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
822 "invalid warning `%s'", param
);
829 operating_mode
= op_depend
;
832 operating_mode
= op_depend
;
833 depend_missing_ok
= true;
844 depend_target
= quote_for_make(q
);
848 report_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
849 "unknown dependency option `-M%c'", p
[2]);
852 if (advance
&& (!q
|| !q
[0])) {
853 report_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
854 "option `-M%c' requires a parameter", p
[2]);
863 if (p
[2] == 0) { /* -- => stop processing options */
867 for (s
= 0; textopts
[s
].label
; s
++) {
868 if (!nasm_stricmp(p
+ 2, textopts
[s
].label
)) {
879 report_error(ERR_NONFATAL
| ERR_NOFILE
|
881 "option `--%s' requires an argument",
885 advance
= 1, param
= q
;
888 if (s
== OPT_PREFIX
) {
889 strncpy(lprefix
, param
, PREFIX_MAX
- 1);
890 lprefix
[PREFIX_MAX
- 1] = 0;
893 if (s
== OPT_POSTFIX
) {
894 strncpy(lpostfix
, param
, POSTFIX_MAX
- 1);
895 lpostfix
[POSTFIX_MAX
- 1] = 0;
902 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
903 "unrecognised option `--%s'", p
+ 2);
911 if (!ofmt
->setinfo(GI_SWITCH
, &p
))
912 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
913 "unrecognised option `-%c'", p
[1]);
918 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
919 "more than one input file specified");
921 copy_filename(inname
, p
);
928 #define ARG_BUF_DELTA 128
930 static void process_respfile(FILE * rfile
)
932 char *buffer
, *p
, *q
, *prevarg
;
933 int bufsize
, prevargsize
;
935 bufsize
= prevargsize
= ARG_BUF_DELTA
;
936 buffer
= nasm_malloc(ARG_BUF_DELTA
);
937 prevarg
= nasm_malloc(ARG_BUF_DELTA
);
940 while (1) { /* Loop to handle all lines in file */
942 while (1) { /* Loop to handle long lines */
943 q
= fgets(p
, bufsize
- (p
- buffer
), rfile
);
947 if (p
> buffer
&& p
[-1] == '\n')
949 if (p
- buffer
> bufsize
- 10) {
952 bufsize
+= ARG_BUF_DELTA
;
953 buffer
= nasm_realloc(buffer
, bufsize
);
958 if (!q
&& p
== buffer
) {
960 process_arg(prevarg
, NULL
);
967 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
968 * them are present at the end of the line.
970 *(p
= &buffer
[strcspn(buffer
, "\r\n\032")]) = '\0';
972 while (p
> buffer
&& isspace(p
[-1]))
979 if (process_arg(prevarg
, p
))
982 if ((int) strlen(p
) > prevargsize
- 10) {
983 prevargsize
+= ARG_BUF_DELTA
;
984 prevarg
= nasm_realloc(prevarg
, prevargsize
);
986 strncpy(prevarg
, p
, prevargsize
);
990 /* Function to process args from a string of args, rather than the
991 * argv array. Used by the environment variable and response file
994 static void process_args(char *args
)
996 char *p
, *q
, *arg
, *prevarg
;
997 char separator
= ' ';
1000 if (*p
&& *p
!= '-')
1005 while (*p
&& *p
!= separator
)
1007 while (*p
== separator
)
1011 if (process_arg(prevarg
, arg
))
1015 process_arg(arg
, NULL
);
1018 static void process_response_file(const char *file
)
1021 FILE *f
= fopen(file
, "r");
1026 while (fgets(str
, sizeof str
, f
)) {
1032 static void parse_cmdline(int argc
, char **argv
)
1035 char *envreal
, *envcopy
= NULL
, *p
, *arg
;
1037 *inname
= *outname
= *listname
= *errname
= '\0';
1040 * First, process the NASMENV environment variable.
1042 envreal
= getenv("NASMENV");
1045 envcopy
= nasm_strdup(envreal
);
1046 process_args(envcopy
);
1051 * Now process the actual command line.
1056 if (argv
[0][0] == '@') {
1057 /* We have a response file, so process this as a set of
1058 * arguments like the environment variable. This allows us
1059 * to have multiple arguments on a single line, which is
1060 * different to the -@resp file processing below for regular
1063 process_response_file(argv
[0]+1);
1067 if (!stopoptions
&& argv
[0][0] == '-' && argv
[0][1] == '@') {
1068 p
= get_param(argv
[0], argc
> 1 ? argv
[1] : NULL
, &advance
);
1070 rfile
= fopen(p
, "r");
1072 process_respfile(rfile
);
1075 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1076 "unable to open response file `%s'", p
);
1079 advance
= process_arg(argv
[0], argc
> 1 ? argv
[1] : NULL
);
1080 argv
+= advance
, argc
-= advance
;
1083 /* Look for basic command line typos. This definitely doesn't
1084 catch all errors, but it might help cases of fumbled fingers. */
1086 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1087 "no input file specified");
1088 else if (!strcmp(inname
, errname
) || !strcmp(inname
, outname
) ||
1089 !strcmp(inname
, listname
))
1090 report_error(ERR_FATAL
| ERR_NOFILE
| ERR_USAGE
,
1091 "file `%s' is both input and output file",
1095 error_file
= fopen(errname
, "w");
1097 error_file
= stderr
; /* Revert to default! */
1098 report_error(ERR_FATAL
| ERR_NOFILE
| ERR_USAGE
,
1099 "cannot open file `%s' for error messages",
1105 /* List of directives */
1107 D_NONE
, D_ABSOLUTE
, D_BITS
, D_COMMON
, D_CPU
, D_DEBUG
, D_DEFAULT
,
1108 D_EXTERN
, D_FLOAT
, D_GLOBAL
, D_LIST
, D_SECTION
, D_SEGMENT
, D_WARNING
1110 static const char *directives
[] = {
1111 "", "absolute", "bits", "common", "cpu", "debug", "default",
1112 "extern", "float", "global", "list", "section", "segment", "warning"
1114 static enum directives
getkw(char **directive
, char **value
);
1116 static void assemble_file(char *fname
, FILE *depends
)
1118 char *directive
, *value
, *p
, *q
, *special
, *line
, debugid
[80];
1124 struct tokenval tokval
;
1128 if (cmd_sb
== 32 && cmd_cpu
< IF_386
)
1129 report_error(ERR_FATAL
, "command line: "
1130 "32-bit segment size requires a higher cpu");
1132 pass_max
= (optimizing
> 0 ? optimizing
: 0) + 2; /* passes 1, optimizing, then 2 */
1133 pass0
= !(optimizing
> 0); /* start at 1 if not optimizing */
1134 for (passn
= 1; pass0
<= 2; passn
++) {
1138 pass1
= pass0
== 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1139 pass2
= passn
> 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1140 /* pass0 0, 0, 0, ..., 1, 2 */
1142 def_label
= passn
> 1 ? redefine_label
: define_label
;
1144 globalbits
= sb
= cmd_sb
; /* set 'bits' to command line default */
1148 nasmlist
.init(listname
, report_error
);
1151 global_offset_changed
= false; /* set by redefine_label */
1152 location
.segment
= ofmt
->section(NULL
, pass2
, &sb
);
1155 saa_rewind(forwrefs
);
1156 forwref
= saa_rstruct(forwrefs
);
1158 offsets
= raa_init();
1160 preproc
->reset(fname
, pass1
, report_error
, evaluate
, &nasmlist
,
1161 pass1
== 2 ? depends
: NULL
);
1162 if (pass1
== 2 && depends
)
1163 fprintf(depends
, "%s: %s", depend_target
, inname
);
1167 location
.known
= true;
1168 location
.offset
= offs
= GET_CURR_OFFS
;
1170 while ((line
= preproc
->getline())) {
1174 /* here we parse our directives; this is not handled by the 'real'
1177 d
= getkw(&directive
, &value
);
1182 case D_SEGMENT
: /* [SEGMENT n] */
1184 seg
= ofmt
->section(value
, pass2
, &sb
);
1185 if (seg
== NO_SEG
) {
1186 report_error(pass1
== 1 ? ERR_NONFATAL
: ERR_PANIC
,
1187 "segment name `%s' not recognized",
1191 location
.segment
= seg
;
1194 case D_EXTERN
: /* [EXTERN label:special] */
1196 value
++; /* skip initial $ if present */
1199 while (*q
&& *q
!= ':')
1203 ofmt
->symdef(value
, 0L, 0L, 3, q
);
1205 } else if (passn
== 1) {
1210 while (*q
&& *q
!= ':') {
1216 report_error(ERR_NONFATAL
,
1217 "identifier expected after EXTERN");
1225 if (!is_extern(value
)) { /* allow re-EXTERN to be ignored */
1227 pass0
= 1; /* fake pass 1 in labels.c */
1228 declare_as_global(value
, special
,
1230 define_label(value
, seg_alloc(), 0L, NULL
,
1231 false, true, ofmt
, report_error
);
1234 } /* else pass0 == 1 */
1236 case D_BITS
: /* [BITS bits] */
1237 globalbits
= sb
= get_bits(value
);
1239 case D_GLOBAL
: /* [GLOBAL symbol:special] */
1241 value
++; /* skip initial $ if present */
1242 if (pass0
== 2) { /* pass 2 */
1244 while (*q
&& *q
!= ':')
1248 ofmt
->symdef(value
, 0L, 0L, 3, q
);
1250 } else if (pass2
== 1) { /* pass == 1 */
1255 while (*q
&& *q
!= ':') {
1261 report_error(ERR_NONFATAL
,
1262 "identifier expected after GLOBAL");
1270 declare_as_global(value
, special
, report_error
);
1273 case D_COMMON
: /* [COMMON symbol size:special] */
1275 value
++; /* skip initial $ if present */
1281 while (*p
&& !isspace(*p
)) {
1287 report_error(ERR_NONFATAL
,
1288 "identifier expected after COMMON");
1294 while (*p
&& isspace(*p
))
1297 while (*q
&& *q
!= ':')
1304 size
= readnum(p
, &rn_error
);
1306 report_error(ERR_NONFATAL
,
1307 "invalid size specified"
1308 " in COMMON declaration");
1310 define_common(value
, seg_alloc(), size
,
1311 special
, ofmt
, report_error
);
1313 report_error(ERR_NONFATAL
,
1314 "no size specified in"
1315 " COMMON declaration");
1316 } else if (pass0
== 2) { /* pass == 2 */
1318 while (*q
&& *q
!= ':') {
1325 ofmt
->symdef(value
, 0L, 0L, 3, q
);
1329 case D_ABSOLUTE
: /* [ABSOLUTE address] */
1331 stdscan_bufptr
= value
;
1332 tokval
.t_type
= TOKEN_INVALID
;
1333 e
= evaluate(stdscan
, NULL
, &tokval
, NULL
, pass2
,
1334 report_error
, NULL
);
1337 report_error(pass0
==
1338 1 ? ERR_NONFATAL
: ERR_PANIC
,
1339 "cannot use non-relocatable expression as "
1340 "ABSOLUTE address");
1342 abs_seg
= reloc_seg(e
);
1343 abs_offset
= reloc_value(e
);
1345 } else if (passn
== 1)
1346 abs_offset
= 0x100; /* don't go near zero in case of / */
1348 report_error(ERR_PANIC
, "invalid ABSOLUTE address "
1351 location
.segment
= NO_SEG
;
1353 case D_DEBUG
: /* [DEBUG] */
1359 while (*p
&& !isspace(*p
)) {
1366 report_error(passn
== 1 ? ERR_NONFATAL
: ERR_PANIC
,
1367 "identifier expected after DEBUG");
1370 while (*p
&& isspace(*p
))
1373 ofmt
->current_dfmt
->debug_directive(debugid
, p
);
1375 case D_WARNING
: /* [WARNING {+|-}warn-name] */
1377 while (*value
&& isspace(*value
))
1380 if (*value
== '+' || *value
== '-') {
1381 validid
= (*value
== '-') ? true : false;
1386 for (i
= 1; i
<= ERR_WARN_MAX
; i
++)
1387 if (!nasm_stricmp(value
, suppressed_names
[i
]))
1389 if (i
<= ERR_WARN_MAX
)
1390 suppressed
[i
] = validid
;
1392 report_error(ERR_NONFATAL
,
1393 "invalid warning id in WARNING directive");
1396 case D_CPU
: /* [CPU] */
1397 cpu
= get_cpu(value
);
1399 case D_LIST
: /* [LIST {+|-}] */
1400 while (*value
&& isspace(*value
))
1403 if (*value
== '+') {
1406 if (*value
== '-') {
1413 case D_DEFAULT
: /* [DEFAULT] */
1415 stdscan_bufptr
= value
;
1416 tokval
.t_type
= TOKEN_INVALID
;
1417 if (stdscan(NULL
, &tokval
) == TOKEN_SPECIAL
) {
1418 switch ((int)tokval
.t_integer
) {
1434 if (float_option(value
)) {
1435 report_error(pass1
== 1 ? ERR_NONFATAL
: ERR_PANIC
,
1436 "unknown 'float' directive: %s",
1441 if (!ofmt
->directive(directive
, value
, pass2
))
1442 report_error(pass1
== 1 ? ERR_NONFATAL
: ERR_PANIC
,
1443 "unrecognised directive [%s]",
1447 report_error(ERR_NONFATAL
,
1448 "invalid parameter to [%s] directive",
1451 } else { /* it isn't a directive */
1453 parse_line(pass1
, line
, &output_ins
,
1454 report_error
, evaluate
, def_label
);
1456 if (!(optimizing
> 0) && pass0
== 2) {
1457 if (forwref
!= NULL
&& globallineno
== forwref
->lineno
) {
1458 output_ins
.forw_ref
= true;
1460 output_ins
.oprs
[forwref
->operand
].opflags
|=
1462 forwref
= saa_rstruct(forwrefs
);
1463 } while (forwref
!= NULL
1464 && forwref
->lineno
== globallineno
);
1466 output_ins
.forw_ref
= false;
1469 if (!(optimizing
> 0) && output_ins
.forw_ref
) {
1471 for (i
= 0; i
< output_ins
.operands
; i
++) {
1472 if (output_ins
.oprs
[i
].
1473 opflags
& OPFLAG_FORWARD
) {
1474 struct forwrefinfo
*fwinf
=
1475 (struct forwrefinfo
*)
1476 saa_wstruct(forwrefs
);
1477 fwinf
->lineno
= globallineno
;
1481 } else { /* passn > 1 */
1483 * Hack to prevent phase error in the code
1487 * If the second operand is a forward reference,
1488 * the UNITY property of the number 1 in that
1489 * operand is cancelled. Otherwise the above
1490 * sequence will cause a phase error.
1492 * This hack means that the above code will
1493 * generate 286+ code.
1495 * The forward reference will mean that the
1496 * operand will not have the UNITY property on
1497 * the first pass, so the pass behaviours will
1501 if (output_ins
.operands
>= 2 &&
1502 (output_ins
.oprs
[1].opflags
& OPFLAG_FORWARD
) &&
1503 !(IMMEDIATE
& ~output_ins
.oprs
[1].type
))
1505 /* Remove special properties bits */
1506 output_ins
.oprs
[1].type
&= ~REG_SMASK
;
1514 if (output_ins
.opcode
== I_EQU
) {
1517 * Special `..' EQUs get processed in pass two,
1518 * except `..@' macro-processor EQUs which are done
1519 * in the normal place.
1521 if (!output_ins
.label
)
1522 report_error(ERR_NONFATAL
,
1523 "EQU not preceded by label");
1525 else if (output_ins
.label
[0] != '.' ||
1526 output_ins
.label
[1] != '.' ||
1527 output_ins
.label
[2] == '@') {
1528 if (output_ins
.operands
== 1 &&
1529 (output_ins
.oprs
[0].type
& IMMEDIATE
) &&
1530 output_ins
.oprs
[0].wrt
== NO_SEG
) {
1533 opflags
& OPFLAG_EXTERN
;
1534 def_label(output_ins
.label
,
1535 output_ins
.oprs
[0].segment
,
1536 output_ins
.oprs
[0].offset
, NULL
,
1539 } else if (output_ins
.operands
== 2
1540 && (output_ins
.oprs
[0].
1542 && (output_ins
.oprs
[0].type
& COLON
)
1543 && output_ins
.oprs
[0].segment
==
1545 && output_ins
.oprs
[0].wrt
== NO_SEG
1546 && (output_ins
.oprs
[1].
1548 && output_ins
.oprs
[1].segment
==
1550 && output_ins
.oprs
[1].wrt
==
1552 def_label(output_ins
.label
,
1555 output_ins
.oprs
[1].offset
, NULL
,
1559 report_error(ERR_NONFATAL
,
1560 "bad syntax for EQU");
1564 * Special `..' EQUs get processed here, except
1565 * `..@' macro processor EQUs which are done above.
1567 if (output_ins
.label
[0] == '.' &&
1568 output_ins
.label
[1] == '.' &&
1569 output_ins
.label
[2] != '@') {
1570 if (output_ins
.operands
== 1 &&
1571 (output_ins
.oprs
[0].type
& IMMEDIATE
)) {
1572 define_label(output_ins
.label
,
1573 output_ins
.oprs
[0].segment
,
1574 output_ins
.oprs
[0].offset
,
1575 NULL
, false, false, ofmt
,
1577 } else if (output_ins
.operands
== 2
1578 && (output_ins
.oprs
[0].
1580 && (output_ins
.oprs
[0].type
& COLON
)
1581 && output_ins
.oprs
[0].segment
==
1583 && (output_ins
.oprs
[1].
1585 && output_ins
.oprs
[1].segment
==
1587 define_label(output_ins
.label
,
1590 output_ins
.oprs
[1].offset
,
1591 NULL
, false, false, ofmt
,
1594 report_error(ERR_NONFATAL
,
1595 "bad syntax for EQU");
1598 } else { /* instruction isn't an EQU */
1602 int64_t l
= insn_size(location
.segment
, offs
, sb
, cpu
,
1603 &output_ins
, report_error
);
1605 /* if (using_debug_info) && output_ins.opcode != -1) */
1606 if (using_debug_info
)
1607 { /* fbk 03/25/01 */
1608 /* this is done here so we can do debug type info */
1610 TYS_ELEMENTS(output_ins
.operands
);
1611 switch (output_ins
.opcode
) {
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].
1644 TYS_ELEMENTS(output_ins
.oprs
[0].
1648 typeinfo
|= TY_BYTE
;
1651 typeinfo
|= TY_WORD
;
1654 if (output_ins
.eops_float
)
1655 typeinfo
|= TY_FLOAT
;
1657 typeinfo
|= TY_DWORD
;
1660 typeinfo
|= TY_QWORD
;
1663 typeinfo
|= TY_TBYTE
;
1666 typeinfo
|= TY_OWORD
;
1669 typeinfo
|= TY_YWORD
;
1672 typeinfo
= TY_LABEL
;
1676 ofmt
->current_dfmt
->debug_typevalue(typeinfo
);
1681 SET_CURR_OFFS(offs
);
1684 * else l == -1 => invalid instruction, which will be
1685 * flagged as an error on pass 2
1689 offs
+= assemble(location
.segment
, offs
, sb
, cpu
,
1690 &output_ins
, ofmt
, report_error
,
1692 SET_CURR_OFFS(offs
);
1696 cleanup_insn(&output_ins
);
1699 location
.offset
= offs
= GET_CURR_OFFS
;
1700 } /* end while (line = preproc->getline... */
1702 if (pass1
== 2 && global_offset_changed
)
1703 report_error(ERR_NONFATAL
,
1704 "phase error detected at end of assembly.");
1707 preproc
->cleanup(1);
1709 if (pass1
== 1 && terminate_after_phase
) {
1716 if (passn
>= pass_max
- 2 ||
1717 (passn
> 1 && !global_offset_changed
))
1721 preproc
->cleanup(0);
1724 if (optimizing
> 0 && opt_verbose_info
) /* -On and -Ov switches */
1726 "info:: assembly required 1+%d+1 passes\n", passn
-3);
1728 } /* exit from assemble_file (...) */
1730 static enum directives
getkw(char **directive
, char **value
)
1736 /* allow leading spaces or tabs */
1737 while (*buf
== ' ' || *buf
== '\t')
1745 while (*p
&& *p
!= ']')
1753 while (*p
&& *p
!= ';') {
1760 *directive
= p
= buf
+ 1;
1761 while (*buf
&& *buf
!= ' ' && *buf
!= ']' && *buf
!= '\t')
1768 while (isspace(*buf
))
1769 buf
++; /* beppu - skip leading whitespace */
1776 return bsii(*directive
, directives
, elements(directives
));
1780 * gnu style error reporting
1781 * This function prints an error message to error_file in the
1782 * style used by GNU. An example would be:
1783 * file.asm:50: error: blah blah blah
1784 * where file.asm is the name of the file, 50 is the line number on
1785 * which the error occurs (or is detected) and "error:" is one of
1786 * the possible optional diagnostics -- it can be "error" or "warning"
1787 * or something else. Finally the line terminates with the actual
1790 * @param severity the severity of the warning or error
1791 * @param fmt the printf style format string
1793 static void report_error_gnu(int severity
, const char *fmt
, ...)
1797 if (is_suppressed_warning(severity
))
1800 if (severity
& ERR_NOFILE
)
1801 fputs("nasm: ", error_file
);
1803 char *currentfile
= NULL
;
1805 src_get(&lineno
, ¤tfile
);
1806 fprintf(error_file
, "%s:%"PRId32
": ", currentfile
, lineno
);
1807 nasm_free(currentfile
);
1810 report_error_common(severity
, fmt
, ap
);
1815 * MS style error reporting
1816 * This function prints an error message to error_file in the
1817 * style used by Visual C and some other Microsoft tools. An example
1819 * file.asm(50) : error: blah blah blah
1820 * where file.asm is the name of the file, 50 is the line number on
1821 * which the error occurs (or is detected) and "error:" is one of
1822 * the possible optional diagnostics -- it can be "error" or "warning"
1823 * or something else. Finally the line terminates with the actual
1826 * @param severity the severity of the warning or error
1827 * @param fmt the printf style format string
1829 static void report_error_vc(int severity
, const char *fmt
, ...)
1833 if (is_suppressed_warning(severity
))
1836 if (severity
& ERR_NOFILE
)
1837 fputs("nasm: ", error_file
);
1839 char *currentfile
= NULL
;
1841 src_get(&lineno
, ¤tfile
);
1842 fprintf(error_file
, "%s(%"PRId32
") : ", currentfile
, lineno
);
1843 nasm_free(currentfile
);
1846 report_error_common(severity
, fmt
, ap
);
1851 * check for supressed warning
1852 * checks for suppressed warning or pass one only warning and we're
1855 * @param severity the severity of the warning or error
1856 * @return true if we should abort error/warning printing
1858 static bool is_suppressed_warning(int severity
)
1861 * See if it's a suppressed warning.
1863 return (severity
& ERR_MASK
) == ERR_WARNING
&&
1864 (((severity
& ERR_WARN_MASK
) != 0 &&
1865 suppressed
[(severity
& ERR_WARN_MASK
) >> ERR_WARN_SHR
]) ||
1866 /* See if it's a pass-one only warning and we're not in pass one. */
1867 ((severity
& ERR_PASS1
) && pass0
!= 1));
1871 * common error reporting
1872 * This is the common back end of the error reporting schemes currently
1873 * implemented. It prints the nature of the warning and then the
1874 * specific error message to error_file and may or may not return. It
1875 * doesn't return if the error severity is a "panic" or "debug" type.
1877 * @param severity the severity of the warning or error
1878 * @param fmt the printf style format string
1880 static void report_error_common(int severity
, const char *fmt
,
1883 switch (severity
& ERR_MASK
) {
1885 fputs("warning: ", error_file
);
1888 fputs("error: ", error_file
);
1891 fputs("fatal: ", error_file
);
1894 fputs("panic: ", error_file
);
1897 fputs("debug: ", error_file
);
1901 vfprintf(error_file
, fmt
, args
);
1902 putc('\n', error_file
);
1904 if (severity
& ERR_USAGE
)
1907 switch (severity
& ERR_MASK
) {
1909 /* no further action, by definition */
1912 if (!suppressed
[0]) /* Treat warnings as errors */
1913 terminate_after_phase
= true;
1916 terminate_after_phase
= true;
1925 exit(1); /* instantly die */
1926 break; /* placate silly compilers */
1929 /* abort(); *//* halt, catch fire, and dump core */
1935 static void usage(void)
1937 fputs("type `nasm -h' for help\n", error_file
);
1940 static void register_output_formats(void)
1942 ofmt
= ofmt_register(report_error
);
1945 #define BUF_DELTA 512
1947 static FILE *no_pp_fp
;
1948 static efunc no_pp_err
;
1949 static ListGen
*no_pp_list
;
1950 static int32_t no_pp_lineinc
;
1952 static void no_pp_reset(char *file
, int pass
, efunc error
, evalfunc eval
,
1953 ListGen
* listgen
, FILE *depends
)
1955 src_set_fname(nasm_strdup(file
));
1959 no_pp_fp
= fopen(file
, "r");
1961 no_pp_err(ERR_FATAL
| ERR_NOFILE
,
1962 "unable to open input file `%s'", file
);
1963 no_pp_list
= listgen
;
1964 (void)pass
; /* placate compilers */
1965 (void)eval
; /* placate compilers */
1966 (void)depends
; /* placate compilers */
1969 static char *no_pp_getline(void)
1971 char *buffer
, *p
, *q
;
1974 bufsize
= BUF_DELTA
;
1975 buffer
= nasm_malloc(BUF_DELTA
);
1976 src_set_linnum(src_get_linnum() + no_pp_lineinc
);
1978 while (1) { /* Loop to handle %line */
1981 while (1) { /* Loop to handle long lines */
1982 q
= fgets(p
, bufsize
- (p
- buffer
), no_pp_fp
);
1986 if (p
> buffer
&& p
[-1] == '\n')
1988 if (p
- buffer
> bufsize
- 10) {
1990 offset
= p
- buffer
;
1991 bufsize
+= BUF_DELTA
;
1992 buffer
= nasm_realloc(buffer
, bufsize
);
1993 p
= buffer
+ offset
;
1997 if (!q
&& p
== buffer
) {
2003 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2004 * them are present at the end of the line.
2006 buffer
[strcspn(buffer
, "\r\n\032")] = '\0';
2008 if (!nasm_strnicmp(buffer
, "%line", 5)) {
2011 char *nm
= nasm_malloc(strlen(buffer
));
2012 if (sscanf(buffer
+ 5, "%"PRId32
"+%d %s", &ln
, &li
, nm
) == 3) {
2013 nasm_free(src_set_fname(nm
));
2023 no_pp_list
->line(LIST_READ
, buffer
);
2028 static void no_pp_cleanup(int pass
)
2030 (void)pass
; /* placate GCC */
2034 static uint32_t get_cpu(char *value
)
2036 if (!strcmp(value
, "8086"))
2038 if (!strcmp(value
, "186"))
2040 if (!strcmp(value
, "286"))
2042 if (!strcmp(value
, "386"))
2044 if (!strcmp(value
, "486"))
2046 if (!strcmp(value
, "586") || !nasm_stricmp(value
, "pentium"))
2048 if (!strcmp(value
, "686") ||
2049 !nasm_stricmp(value
, "ppro") ||
2050 !nasm_stricmp(value
, "pentiumpro") || !nasm_stricmp(value
, "p2"))
2052 if (!nasm_stricmp(value
, "p3") || !nasm_stricmp(value
, "katmai"))
2054 if (!nasm_stricmp(value
, "p4") || /* is this right? -- jrc */
2055 !nasm_stricmp(value
, "willamette"))
2056 return IF_WILLAMETTE
;
2057 if (!nasm_stricmp(value
, "prescott"))
2059 if (!nasm_stricmp(value
, "x64") ||
2060 !nasm_stricmp(value
, "x86-64"))
2062 if (!nasm_stricmp(value
, "ia64") ||
2063 !nasm_stricmp(value
, "ia-64") ||
2064 !nasm_stricmp(value
, "itanium") ||
2065 !nasm_stricmp(value
, "itanic") || !nasm_stricmp(value
, "merced"))
2068 report_error(pass0
< 2 ? ERR_NONFATAL
: ERR_FATAL
,
2069 "unknown 'cpu' type");
2071 return IF_PLEVEL
; /* the maximum level */
2074 static int get_bits(char *value
)
2078 if ((i
= atoi(value
)) == 16)
2079 return i
; /* set for a 16-bit segment */
2082 report_error(ERR_NONFATAL
,
2083 "cannot specify 32-bit segment on processor below a 386");
2086 } else if (i
== 64) {
2087 if (cpu
< IF_X86_64
) {
2088 report_error(ERR_NONFATAL
,
2089 "cannot specify 64-bit segment on processor below an x86-64");
2093 report_error(ERR_NONFATAL
,
2094 "%s output format does not support 64-bit code",
2099 report_error(pass0
< 2 ? ERR_NONFATAL
: ERR_FATAL
,
2100 "`%s' is not a valid segment size; must be 16, 32 or 64",