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 bool global_offset_changed
; /* referenced in labels.c */
78 static struct location location
;
79 int in_abs_seg
; /* Flag we are in ABSOLUTE seg */
80 int32_t abs_seg
; /* ABSOLUTE segment basis */
81 int32_t abs_offset
; /* ABSOLUTE offset */
83 static struct RAA
*offsets
;
85 static struct SAA
*forwrefs
; /* keep track of forward references */
86 static const struct forwrefinfo
*forwref
;
88 static Preproc
*preproc
;
90 op_normal
, /* Preprocess and assemble */
91 op_preprocess
, /* Preprocess only */
92 op_depend
, /* Generate dependencies */
94 static enum op_type operating_mode
;
95 /* Dependency flags */
96 static bool depend_emit_phony
= false;
97 static bool depend_missing_ok
= false;
98 static const char *depend_target
= NULL
;
99 static const char *depend_file
= NULL
;
102 * Which of the suppressible warnings are suppressed. Entry zero
103 * isn't an actual warning, but it used for -w+error/-Werror.
105 static bool suppressed
[ERR_WARN_MAX
+1] = {
106 true, false, true, false, false, true, false, true, true, false
110 * The option names for the suppressible warnings. As before, entry
113 static const char *suppressed_names
[ERR_WARN_MAX
+1] = {
114 "error", "macro-params", "macro-selfref", "orphan-labels",
115 "number-overflow", "gnu-elf-extensions", "float-overflow",
116 "float-denorm", "float-underflow", "float-toolong"
120 * The explanations for the suppressible warnings. As before, entry
123 static const char *suppressed_what
[ERR_WARN_MAX
+1] = {
124 "treat warnings as errors",
125 "macro calls with wrong parameter count",
126 "cyclic macro references",
127 "labels alone on lines without trailing `:'",
128 "numeric constants does not fit in 64 bits",
129 "using 8- or 16-bit relocation in ELF32, a GNU extension",
130 "floating point overflow",
131 "floating point denormal",
132 "floating point underflow",
133 "too many digits in floating-point number"
137 * This is a null preprocessor which just copies lines from input
138 * to output. It's used when someone explicitly requests that NASM
139 * not preprocess their source file.
142 static void no_pp_reset(char *, int, efunc
, evalfunc
, ListGen
*, StrList
**);
143 static char *no_pp_getline(void);
144 static void no_pp_cleanup(int);
145 static Preproc no_pp
= {
152 * get/set current offset...
154 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
155 raa_read(offsets,location.segment))
156 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
157 (void)(offsets=raa_write(offsets,location.segment,(x))))
159 static int want_usage
;
160 static int terminate_after_phase
;
161 int user_nolist
= 0; /* fbk 9/2/00 */
163 static void nasm_fputs(const char *line
, FILE * outfile
)
166 fputs(line
, outfile
);
172 /* Convert a struct tm to a POSIX-style time constant */
173 static int64_t posix_mktime(struct tm
*tm
)
176 int64_t y
= tm
->tm_year
;
178 /* See IEEE 1003.1:2004, section 4.14 */
180 t
= (y
-70)*365 + (y
-69)/4 - (y
-1)/100 + (y
+299)/400;
192 static void define_macros_early(void)
195 struct tm lt
, *lt_p
, gm
, *gm_p
;
198 lt_p
= localtime(&official_compile_time
);
202 strftime(temp
, sizeof temp
, "__DATE__=\"%Y-%m-%d\"", <
);
204 strftime(temp
, sizeof temp
, "__DATE_NUM__=%Y%m%d", <
);
206 strftime(temp
, sizeof temp
, "__TIME__=\"%H:%M:%S\"", <
);
208 strftime(temp
, sizeof temp
, "__TIME_NUM__=%H%M%S", <
);
212 gm_p
= gmtime(&official_compile_time
);
216 strftime(temp
, sizeof temp
, "__UTC_DATE__=\"%Y-%m-%d\"", &gm
);
218 strftime(temp
, sizeof temp
, "__UTC_DATE_NUM__=%Y%m%d", &gm
);
220 strftime(temp
, sizeof temp
, "__UTC_TIME__=\"%H:%M:%S\"", &gm
);
222 strftime(temp
, sizeof temp
, "__UTC_TIME_NUM__=%H%M%S", &gm
);
227 posix_time
= posix_mktime(&gm
);
229 posix_time
= posix_mktime(<
);
234 snprintf(temp
, sizeof temp
, "__POSIX_TIME__=%"PRId64
, posix_time
);
239 static void define_macros_late(void)
243 snprintf(temp
, sizeof(temp
), "__OUTPUT_FORMAT__=%s\n",
248 static void emit_dependencies(StrList
*list
)
254 if (depend_file
&& strcmp(depend_file
, "-")) {
255 deps
= fopen(depend_file
, "w");
257 report_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
258 "unable to write dependency file `%s'", depend_file
);
265 linepos
= fprintf(deps
, "%s:", depend_target
);
266 for (l
= list
; l
; l
= l
->next
) {
267 len
= strlen(l
->str
);
268 if (linepos
+ len
> 62) {
269 fprintf(deps
, " \\\n ");
272 fprintf(deps
, " %s", l
->str
);
275 fprintf(deps
, "\n\n");
277 for (l
= list
; l
; l
= nl
) {
278 if (depend_emit_phony
)
279 fprintf(deps
, "%s:\n\n", l
->str
);
289 int main(int argc
, char **argv
)
291 StrList
*depend_list
= NULL
, **depend_ptr
;
293 time(&official_compile_time
);
296 want_usage
= terminate_after_phase
= false;
297 report_error
= report_error_gnu
;
303 nasm_set_malloc_error(report_error
);
304 offsets
= raa_init();
305 forwrefs
= saa_init((int32_t)sizeof(struct forwrefinfo
));
308 operating_mode
= op_normal
;
312 register_output_formats();
314 /* Define some macros dependent on the runtime, but not
315 on the command line. */
316 define_macros_early();
318 parse_cmdline(argc
, argv
);
320 if (terminate_after_phase
) {
326 /* If debugging info is disabled, suppress any debug calls */
327 if (!using_debug_info
)
328 ofmt
->current_dfmt
= &null_debug_form
;
331 pp_extra_stdmac(ofmt
->stdmac
);
332 parser_global_info(ofmt
, &location
);
333 eval_global_info(ofmt
, lookup_label
, &location
);
335 /* define some macros dependent of command-line */
336 define_macros_late();
338 depend_ptr
= (depend_file
|| (operating_mode
== op_depend
))
339 ? &depend_list
: NULL
;
341 depend_target
= outname
;
343 switch (operating_mode
) {
348 if (depend_missing_ok
)
349 pp_include_path(NULL
); /* "assume generated" */
351 preproc
->reset(inname
, 0, report_error
, evaluate
, &nasmlist
,
353 if (outname
[0] == '\0')
354 ofmt
->filename(inname
, outname
, report_error
);
356 while ((line
= preproc
->getline()))
365 char *file_name
= NULL
;
366 int32_t prior_linnum
= 0;
370 ofile
= fopen(outname
, "w");
372 report_error(ERR_FATAL
| ERR_NOFILE
,
373 "unable to open output file `%s'",
378 location
.known
= false;
381 preproc
->reset(inname
, 2, report_error
, evaluate
, &nasmlist
,
384 while ((line
= preproc
->getline())) {
386 * We generate %line directives if needed for later programs
388 int32_t linnum
= prior_linnum
+= lineinc
;
389 int altline
= src_get(&linnum
, &file_name
);
391 if (altline
== 1 && lineinc
== 1)
392 nasm_fputs("", ofile
);
394 lineinc
= (altline
!= -1 || lineinc
!= 1);
395 fprintf(ofile
? ofile
: stdout
,
396 "%%line %"PRId32
"+%d %s\n", linnum
, lineinc
,
399 prior_linnum
= linnum
;
401 nasm_fputs(line
, ofile
);
404 nasm_free(file_name
);
408 if (ofile
&& terminate_after_phase
)
416 * We must call ofmt->filename _anyway_, even if the user
417 * has specified their own output file, because some
418 * formats (eg OBJ and COFF) use ofmt->filename to find out
419 * the name of the input file and then put that inside the
422 ofmt
->filename(inname
, outname
, report_error
);
424 ofile
= fopen(outname
, "wb");
426 report_error(ERR_FATAL
| ERR_NOFILE
,
427 "unable to open output file `%s'", outname
);
431 * We must call init_labels() before ofmt->init() since
432 * some object formats will want to define labels in their
433 * init routines. (eg OS/2 defines the FLAT group)
437 ofmt
->init(ofile
, report_error
, define_label
, evaluate
);
439 assemble_file(inname
, depend_ptr
);
441 if (!terminate_after_phase
) {
442 ofmt
->cleanup(using_debug_info
);
446 * Despite earlier comments, we need this fclose.
447 * The object output drivers only fclose on cleanup,
448 * and we just skipped that.
461 emit_dependencies(depend_list
);
471 if (terminate_after_phase
)
478 * Get a parameter for a command line option.
479 * First arg must be in the form of e.g. -f...
481 static char *get_param(char *p
, char *q
, bool *advance
)
484 if (p
[2]) { /* the parameter's in the option */
486 while (nasm_isspace(*p
))
494 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
495 "option `-%c' requires an argument", p
[1]);
502 static void copy_filename(char *dst
, const char *src
)
504 size_t len
= strlen(src
);
506 if (len
>= (size_t)FILENAME_MAX
) {
507 report_error(ERR_FATAL
| ERR_NOFILE
, "file name too long");
510 strncpy(dst
, src
, FILENAME_MAX
);
514 * Convert a string to Make-safe form
516 static char *quote_for_make(const char *str
)
521 size_t n
= 1; /* Terminating zero */
527 for (p
= str
; *p
; p
++) {
531 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
551 /* Convert N backslashes at the end of filename to 2N backslashes */
555 os
= q
= nasm_malloc(n
);
558 for (p
= str
; *p
; p
++) {
601 #define OPT_POSTFIX 1
602 struct textargs textopts
[] = {
603 {"prefix", OPT_PREFIX
},
604 {"postfix", OPT_POSTFIX
},
608 static bool stopoptions
= false;
609 static bool process_arg(char *p
, char *q
)
613 bool advance
= false;
619 if (p
[0] == '-' && !stopoptions
) {
620 if (strchr("oOfpPdDiIlFXuUZwW", p
[1])) {
621 /* These parameters take values */
622 if (!(param
= get_param(p
, q
, &advance
)))
631 case 'o': /* output file */
632 copy_filename(outname
, param
);
635 case 'f': /* output format */
636 ofmt
= ofmt_find(param
);
638 report_error(ERR_FATAL
| ERR_NOFILE
| ERR_USAGE
,
639 "unrecognised output format `%s' - "
640 "use -hf for a list", param
);
642 ofmt
->current_dfmt
= ofmt
->debug_formats
[0];
646 case 'O': /* Optimization level */
651 /* Naked -O == -Ox */
652 optimizing
= INT_MAX
>> 1; /* Almost unlimited */
656 case '0': case '1': case '2': case '3': case '4':
657 case '5': case '6': case '7': case '8': case '9':
658 opt
= strtoul(param
, ¶m
, 10);
660 /* -O0 -> optimizing == -1, 0.98 behaviour */
661 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
663 optimizing
= opt
- 1;
671 opt_verbose_info
= true;
676 optimizing
= INT_MAX
>> 1; /* Almost unlimited */
680 report_error(ERR_FATAL
,
681 "unknown optimization option -O%c\n",
690 case 'p': /* pre-include */
692 pp_pre_include(param
);
695 case 'd': /* pre-define */
697 pp_pre_define(param
);
700 case 'u': /* un-define */
702 pp_pre_undefine(param
);
705 case 'i': /* include search path */
707 pp_include_path(param
);
710 case 'l': /* listing file */
711 copy_filename(listname
, param
);
714 case 'Z': /* error messages file */
715 strcpy(errname
, param
);
718 case 'F': /* specify debug format */
719 ofmt
->current_dfmt
= dfmt_find(ofmt
, param
);
720 if (!ofmt
->current_dfmt
) {
721 report_error(ERR_FATAL
| ERR_NOFILE
| ERR_USAGE
,
722 "unrecognized debug format `%s' for"
723 " output format `%s'",
724 param
, ofmt
->shortname
);
726 using_debug_info
= true;
729 case 'X': /* specify error reporting format */
730 if (nasm_stricmp("vc", param
) == 0)
731 report_error
= report_error_vc
;
732 else if (nasm_stricmp("gnu", param
) == 0)
733 report_error
= report_error_gnu
;
735 report_error(ERR_FATAL
| ERR_NOFILE
| ERR_USAGE
,
736 "unrecognized error reporting format `%s'",
741 using_debug_info
= true;
746 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
748 " [options...] [--] filename\n"
749 " or nasm -v for version info\n\n"
750 " -t assemble in SciTech TASM compatible mode\n"
751 " -g generate debug information in selected format.\n");
753 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
754 " -a don't preprocess (assemble only)\n"
755 " -M generate Makefile dependencies on stdout\n"
756 " -MG d:o, missing files assumed generated\n\n"
757 " -Z<file> redirect error messages to file\n"
758 " -s redirect error messages to stdout\n\n"
759 " -F format select a debugging format\n\n"
760 " -I<path> adds a pathname to the include file path\n");
762 (" -O<digit> optimize branch offsets (-O0 disables, default)\n"
763 " -P<file> pre-includes a file\n"
764 " -D<macro>[=<value>] pre-defines a macro\n"
765 " -U<macro> undefines a macro\n"
766 " -X<format> specifies error reporting format (gnu or vc)\n"
767 " -w+foo enables warning foo (equiv. -Wfoo)\n"
768 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
770 for (i
= 0; i
<= ERR_WARN_MAX
; i
++)
771 printf(" %-23s %s (default %s)\n",
772 suppressed_names
[i
], suppressed_what
[i
],
773 suppressed
[i
] ? "off" : "on");
775 ("\nresponse files should contain command line parameters"
776 ", one per line.\n");
778 printf("\nvalid output formats for -f are"
779 " (`*' denotes default):\n");
780 ofmt_list(ofmt
, stdout
);
782 printf("\nFor a list of valid output formats, use -hf.\n");
783 printf("For a list of debug formats, use -f <form> -y.\n");
785 exit(0); /* never need usage message here */
789 printf("\nvalid debug formats for '%s' output format are"
790 " ('*' denotes default):\n", ofmt
->shortname
);
791 dfmt_list(ofmt
, stdout
);
796 tasm_compatible_mode
= true;
801 const char *nasm_version_string
=
802 "NASM version " NASM_VER
" compiled on " __DATE__
807 puts(nasm_version_string
);
808 exit(0); /* never need usage message here */
812 case 'e': /* preprocess only */
814 operating_mode
= op_preprocess
;
817 case 'a': /* assemble only - don't preprocess */
822 if (param
[0] == 'n' && param
[1] == 'o' && param
[2] == '-') {
831 if (param
[0] != '+' && param
[0] != '-') {
832 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
833 "invalid option to `-w'");
836 suppress
= (param
[0] == '-');
840 for (i
= 0; i
<= ERR_WARN_MAX
; i
++)
841 if (!nasm_stricmp(param
, suppressed_names
[i
]))
843 if (i
<= ERR_WARN_MAX
)
844 suppressed
[i
] = suppress
;
845 else if (!nasm_stricmp(param
, "all"))
846 for (i
= 1; i
<= ERR_WARN_MAX
; i
++)
847 suppressed
[i
] = suppress
;
848 else if (!nasm_stricmp(param
, "none"))
849 for (i
= 1; i
<= ERR_WARN_MAX
; i
++)
850 suppressed
[i
] = !suppress
;
852 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
853 "invalid warning `%s'", param
);
859 operating_mode
= op_depend
;
862 operating_mode
= op_depend
;
863 depend_missing_ok
= true;
866 depend_emit_phony
= true;
877 depend_target
= quote_for_make(q
);
881 report_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
882 "unknown dependency option `-M%c'", p
[2]);
885 if (advance
&& (!q
|| !q
[0])) {
886 report_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
887 "option `-M%c' requires a parameter", p
[2]);
896 if (p
[2] == 0) { /* -- => stop processing options */
900 for (s
= 0; textopts
[s
].label
; s
++) {
901 if (!nasm_stricmp(p
+ 2, textopts
[s
].label
)) {
912 report_error(ERR_NONFATAL
| ERR_NOFILE
|
914 "option `--%s' requires an argument",
918 advance
= 1, param
= q
;
921 if (s
== OPT_PREFIX
) {
922 strncpy(lprefix
, param
, PREFIX_MAX
- 1);
923 lprefix
[PREFIX_MAX
- 1] = 0;
926 if (s
== OPT_POSTFIX
) {
927 strncpy(lpostfix
, param
, POSTFIX_MAX
- 1);
928 lpostfix
[POSTFIX_MAX
- 1] = 0;
935 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
936 "unrecognised option `--%s'", p
+ 2);
944 if (!ofmt
->setinfo(GI_SWITCH
, &p
))
945 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
946 "unrecognised option `-%c'", p
[1]);
951 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
952 "more than one input file specified");
954 copy_filename(inname
, p
);
961 #define ARG_BUF_DELTA 128
963 static void process_respfile(FILE * rfile
)
965 char *buffer
, *p
, *q
, *prevarg
;
966 int bufsize
, prevargsize
;
968 bufsize
= prevargsize
= ARG_BUF_DELTA
;
969 buffer
= nasm_malloc(ARG_BUF_DELTA
);
970 prevarg
= nasm_malloc(ARG_BUF_DELTA
);
973 while (1) { /* Loop to handle all lines in file */
975 while (1) { /* Loop to handle long lines */
976 q
= fgets(p
, bufsize
- (p
- buffer
), rfile
);
980 if (p
> buffer
&& p
[-1] == '\n')
982 if (p
- buffer
> bufsize
- 10) {
985 bufsize
+= ARG_BUF_DELTA
;
986 buffer
= nasm_realloc(buffer
, bufsize
);
991 if (!q
&& p
== buffer
) {
993 process_arg(prevarg
, NULL
);
1000 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1001 * them are present at the end of the line.
1003 *(p
= &buffer
[strcspn(buffer
, "\r\n\032")]) = '\0';
1005 while (p
> buffer
&& nasm_isspace(p
[-1]))
1009 while (nasm_isspace(*p
))
1012 if (process_arg(prevarg
, p
))
1015 if ((int) strlen(p
) > prevargsize
- 10) {
1016 prevargsize
+= ARG_BUF_DELTA
;
1017 prevarg
= nasm_realloc(prevarg
, prevargsize
);
1019 strncpy(prevarg
, p
, prevargsize
);
1023 /* Function to process args from a string of args, rather than the
1024 * argv array. Used by the environment variable and response file
1027 static void process_args(char *args
)
1029 char *p
, *q
, *arg
, *prevarg
;
1030 char separator
= ' ';
1033 if (*p
&& *p
!= '-')
1038 while (*p
&& *p
!= separator
)
1040 while (*p
== separator
)
1044 if (process_arg(prevarg
, arg
))
1048 process_arg(arg
, NULL
);
1051 static void process_response_file(const char *file
)
1054 FILE *f
= fopen(file
, "r");
1059 while (fgets(str
, sizeof str
, f
)) {
1065 static void parse_cmdline(int argc
, char **argv
)
1068 char *envreal
, *envcopy
= NULL
, *p
, *arg
;
1070 *inname
= *outname
= *listname
= *errname
= '\0';
1073 * First, process the NASMENV environment variable.
1075 envreal
= getenv("NASMENV");
1078 envcopy
= nasm_strdup(envreal
);
1079 process_args(envcopy
);
1084 * Now process the actual command line.
1089 if (argv
[0][0] == '@') {
1090 /* We have a response file, so process this as a set of
1091 * arguments like the environment variable. This allows us
1092 * to have multiple arguments on a single line, which is
1093 * different to the -@resp file processing below for regular
1096 process_response_file(argv
[0]+1);
1100 if (!stopoptions
&& argv
[0][0] == '-' && argv
[0][1] == '@') {
1101 p
= get_param(argv
[0], argc
> 1 ? argv
[1] : NULL
, &advance
);
1103 rfile
= fopen(p
, "r");
1105 process_respfile(rfile
);
1108 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1109 "unable to open response file `%s'", p
);
1112 advance
= process_arg(argv
[0], argc
> 1 ? argv
[1] : NULL
);
1113 argv
+= advance
, argc
-= advance
;
1116 /* Look for basic command line typos. This definitely doesn't
1117 catch all errors, but it might help cases of fumbled fingers. */
1119 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1120 "no input file specified");
1121 else if (!strcmp(inname
, errname
) ||
1122 !strcmp(inname
, outname
) ||
1123 !strcmp(inname
, listname
) ||
1124 (depend_file
&& !strcmp(inname
, depend_file
)))
1125 report_error(ERR_FATAL
| ERR_NOFILE
| ERR_USAGE
,
1126 "file `%s' is both input and output file",
1130 error_file
= fopen(errname
, "w");
1132 error_file
= stderr
; /* Revert to default! */
1133 report_error(ERR_FATAL
| ERR_NOFILE
| ERR_USAGE
,
1134 "cannot open file `%s' for error messages",
1140 /* List of directives */
1142 D_NONE
, D_ABSOLUTE
, D_BITS
, D_COMMON
, D_CPU
, D_DEBUG
, D_DEFAULT
,
1143 D_EXTERN
, D_FLOAT
, D_GLOBAL
, D_LIST
, D_SECTION
, D_SEGMENT
, D_WARNING
1145 static const char *directives
[] = {
1146 "", "absolute", "bits", "common", "cpu", "debug", "default",
1147 "extern", "float", "global", "list", "section", "segment", "warning"
1149 static enum directives
getkw(char **directive
, char **value
);
1151 static void assemble_file(char *fname
, StrList
**depend_ptr
)
1153 char *directive
, *value
, *p
, *q
, *special
, *line
, debugid
[80];
1159 struct tokenval tokval
;
1163 if (cmd_sb
== 32 && cmd_cpu
< IF_386
)
1164 report_error(ERR_FATAL
, "command line: "
1165 "32-bit segment size requires a higher cpu");
1167 pass_max
= (optimizing
> 0 ? optimizing
: 0) + 2; /* passes 1, optimizing, then 2 */
1168 pass0
= !(optimizing
> 0); /* start at 1 if not optimizing */
1169 for (passn
= 1; pass0
<= 2; passn
++) {
1173 pass1
= pass0
== 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1174 pass2
= passn
> 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1175 /* pass0 0, 0, 0, ..., 1, 2 */
1177 def_label
= passn
> 1 ? redefine_label
: define_label
;
1179 globalbits
= sb
= cmd_sb
; /* set 'bits' to command line default */
1183 nasmlist
.init(listname
, report_error
);
1186 global_offset_changed
= false; /* set by redefine_label */
1187 location
.segment
= ofmt
->section(NULL
, pass2
, &sb
);
1190 saa_rewind(forwrefs
);
1191 forwref
= saa_rstruct(forwrefs
);
1193 offsets
= raa_init();
1195 preproc
->reset(fname
, pass1
, report_error
, evaluate
, &nasmlist
,
1196 pass1
== 2 ? depend_ptr
: NULL
);
1200 location
.known
= true;
1201 location
.offset
= offs
= GET_CURR_OFFS
;
1203 while ((line
= preproc
->getline())) {
1207 /* here we parse our directives; this is not handled by the 'real'
1210 d
= getkw(&directive
, &value
);
1215 case D_SEGMENT
: /* [SEGMENT n] */
1217 seg
= ofmt
->section(value
, pass2
, &sb
);
1218 if (seg
== NO_SEG
) {
1219 report_error(pass1
== 1 ? ERR_NONFATAL
: ERR_PANIC
,
1220 "segment name `%s' not recognized",
1224 location
.segment
= seg
;
1227 case D_EXTERN
: /* [EXTERN label:special] */
1229 value
++; /* skip initial $ if present */
1232 while (*q
&& *q
!= ':')
1236 ofmt
->symdef(value
, 0L, 0L, 3, q
);
1238 } else if (passn
== 1) {
1243 while (*q
&& *q
!= ':') {
1249 report_error(ERR_NONFATAL
,
1250 "identifier expected after EXTERN");
1258 if (!is_extern(value
)) { /* allow re-EXTERN to be ignored */
1260 pass0
= 1; /* fake pass 1 in labels.c */
1261 declare_as_global(value
, special
,
1263 define_label(value
, seg_alloc(), 0L, NULL
,
1264 false, true, ofmt
, report_error
);
1267 } /* else pass0 == 1 */
1269 case D_BITS
: /* [BITS bits] */
1270 globalbits
= sb
= get_bits(value
);
1272 case D_GLOBAL
: /* [GLOBAL symbol:special] */
1274 value
++; /* skip initial $ if present */
1275 if (pass0
== 2) { /* pass 2 */
1277 while (*q
&& *q
!= ':')
1281 ofmt
->symdef(value
, 0L, 0L, 3, q
);
1283 } else if (pass2
== 1) { /* pass == 1 */
1288 while (*q
&& *q
!= ':') {
1294 report_error(ERR_NONFATAL
,
1295 "identifier expected after GLOBAL");
1303 declare_as_global(value
, special
, report_error
);
1306 case D_COMMON
: /* [COMMON symbol size:special] */
1308 value
++; /* skip initial $ if present */
1314 while (*p
&& !nasm_isspace(*p
)) {
1320 report_error(ERR_NONFATAL
,
1321 "identifier expected after COMMON");
1327 while (*p
&& nasm_isspace(*p
))
1330 while (*q
&& *q
!= ':')
1337 size
= readnum(p
, &rn_error
);
1339 report_error(ERR_NONFATAL
,
1340 "invalid size specified"
1341 " in COMMON declaration");
1343 define_common(value
, seg_alloc(), size
,
1344 special
, ofmt
, report_error
);
1346 report_error(ERR_NONFATAL
,
1347 "no size specified in"
1348 " COMMON declaration");
1349 } else if (pass0
== 2) { /* pass == 2 */
1351 while (*q
&& *q
!= ':') {
1352 if (nasm_isspace(*q
))
1358 ofmt
->symdef(value
, 0L, 0L, 3, q
);
1362 case D_ABSOLUTE
: /* [ABSOLUTE address] */
1364 stdscan_bufptr
= value
;
1365 tokval
.t_type
= TOKEN_INVALID
;
1366 e
= evaluate(stdscan
, NULL
, &tokval
, NULL
, pass2
,
1367 report_error
, NULL
);
1370 report_error(pass0
==
1371 1 ? ERR_NONFATAL
: ERR_PANIC
,
1372 "cannot use non-relocatable expression as "
1373 "ABSOLUTE address");
1375 abs_seg
= reloc_seg(e
);
1376 abs_offset
= reloc_value(e
);
1378 } else if (passn
== 1)
1379 abs_offset
= 0x100; /* don't go near zero in case of / */
1381 report_error(ERR_PANIC
, "invalid ABSOLUTE address "
1384 location
.segment
= NO_SEG
;
1386 case D_DEBUG
: /* [DEBUG] */
1392 while (*p
&& !nasm_isspace(*p
)) {
1399 report_error(passn
== 1 ? ERR_NONFATAL
: ERR_PANIC
,
1400 "identifier expected after DEBUG");
1403 while (*p
&& nasm_isspace(*p
))
1406 ofmt
->current_dfmt
->debug_directive(debugid
, p
);
1408 case D_WARNING
: /* [WARNING {+|-}warn-name] */
1410 while (*value
&& nasm_isspace(*value
))
1413 if (*value
== '+' || *value
== '-') {
1414 validid
= (*value
== '-') ? true : false;
1419 for (i
= 1; i
<= ERR_WARN_MAX
; i
++)
1420 if (!nasm_stricmp(value
, suppressed_names
[i
]))
1422 if (i
<= ERR_WARN_MAX
)
1423 suppressed
[i
] = validid
;
1425 report_error(ERR_NONFATAL
,
1426 "invalid warning id in WARNING directive");
1429 case D_CPU
: /* [CPU] */
1430 cpu
= get_cpu(value
);
1432 case D_LIST
: /* [LIST {+|-}] */
1433 while (*value
&& nasm_isspace(*value
))
1436 if (*value
== '+') {
1439 if (*value
== '-') {
1446 case D_DEFAULT
: /* [DEFAULT] */
1448 stdscan_bufptr
= value
;
1449 tokval
.t_type
= TOKEN_INVALID
;
1450 if (stdscan(NULL
, &tokval
) == TOKEN_SPECIAL
) {
1451 switch ((int)tokval
.t_integer
) {
1467 if (float_option(value
)) {
1468 report_error(pass1
== 1 ? ERR_NONFATAL
: ERR_PANIC
,
1469 "unknown 'float' directive: %s",
1474 if (!ofmt
->directive(directive
, value
, pass2
))
1475 report_error(pass1
== 1 ? ERR_NONFATAL
: ERR_PANIC
,
1476 "unrecognised directive [%s]",
1480 report_error(ERR_NONFATAL
,
1481 "invalid parameter to [%s] directive",
1484 } else { /* it isn't a directive */
1486 parse_line(pass1
, line
, &output_ins
,
1487 report_error
, evaluate
, def_label
);
1489 if (!(optimizing
> 0) && pass0
== 2) {
1490 if (forwref
!= NULL
&& globallineno
== forwref
->lineno
) {
1491 output_ins
.forw_ref
= true;
1493 output_ins
.oprs
[forwref
->operand
].opflags
|=
1495 forwref
= saa_rstruct(forwrefs
);
1496 } while (forwref
!= NULL
1497 && forwref
->lineno
== globallineno
);
1499 output_ins
.forw_ref
= false;
1502 if (!(optimizing
> 0) && output_ins
.forw_ref
) {
1504 for (i
= 0; i
< output_ins
.operands
; i
++) {
1505 if (output_ins
.oprs
[i
].
1506 opflags
& OPFLAG_FORWARD
) {
1507 struct forwrefinfo
*fwinf
=
1508 (struct forwrefinfo
*)
1509 saa_wstruct(forwrefs
);
1510 fwinf
->lineno
= globallineno
;
1514 } else { /* passn > 1 */
1516 * Hack to prevent phase error in the code
1520 * If the second operand is a forward reference,
1521 * the UNITY property of the number 1 in that
1522 * operand is cancelled. Otherwise the above
1523 * sequence will cause a phase error.
1525 * This hack means that the above code will
1526 * generate 286+ code.
1528 * The forward reference will mean that the
1529 * operand will not have the UNITY property on
1530 * the first pass, so the pass behaviours will
1534 if (output_ins
.operands
>= 2 &&
1535 (output_ins
.oprs
[1].opflags
& OPFLAG_FORWARD
) &&
1536 !(IMMEDIATE
& ~output_ins
.oprs
[1].type
))
1538 /* Remove special properties bits */
1539 output_ins
.oprs
[1].type
&= ~REG_SMASK
;
1547 if (output_ins
.opcode
== I_EQU
) {
1550 * Special `..' EQUs get processed in pass two,
1551 * except `..@' macro-processor EQUs which are done
1552 * in the normal place.
1554 if (!output_ins
.label
)
1555 report_error(ERR_NONFATAL
,
1556 "EQU not preceded by label");
1558 else if (output_ins
.label
[0] != '.' ||
1559 output_ins
.label
[1] != '.' ||
1560 output_ins
.label
[2] == '@') {
1561 if (output_ins
.operands
== 1 &&
1562 (output_ins
.oprs
[0].type
& IMMEDIATE
) &&
1563 output_ins
.oprs
[0].wrt
== NO_SEG
) {
1566 opflags
& OPFLAG_EXTERN
;
1567 def_label(output_ins
.label
,
1568 output_ins
.oprs
[0].segment
,
1569 output_ins
.oprs
[0].offset
, NULL
,
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
[0].wrt
== NO_SEG
1579 && (output_ins
.oprs
[1].
1581 && output_ins
.oprs
[1].segment
==
1583 && output_ins
.oprs
[1].wrt
==
1585 def_label(output_ins
.label
,
1588 output_ins
.oprs
[1].offset
, NULL
,
1592 report_error(ERR_NONFATAL
,
1593 "bad syntax for EQU");
1597 * Special `..' EQUs get processed here, except
1598 * `..@' macro processor EQUs which are done above.
1600 if (output_ins
.label
[0] == '.' &&
1601 output_ins
.label
[1] == '.' &&
1602 output_ins
.label
[2] != '@') {
1603 if (output_ins
.operands
== 1 &&
1604 (output_ins
.oprs
[0].type
& IMMEDIATE
)) {
1605 define_label(output_ins
.label
,
1606 output_ins
.oprs
[0].segment
,
1607 output_ins
.oprs
[0].offset
,
1608 NULL
, false, false, ofmt
,
1610 } else if (output_ins
.operands
== 2
1611 && (output_ins
.oprs
[0].
1613 && (output_ins
.oprs
[0].type
& COLON
)
1614 && output_ins
.oprs
[0].segment
==
1616 && (output_ins
.oprs
[1].
1618 && output_ins
.oprs
[1].segment
==
1620 define_label(output_ins
.label
,
1623 output_ins
.oprs
[1].offset
,
1624 NULL
, false, false, ofmt
,
1627 report_error(ERR_NONFATAL
,
1628 "bad syntax for EQU");
1631 } else { /* instruction isn't an EQU */
1635 int64_t l
= insn_size(location
.segment
, offs
, sb
, cpu
,
1636 &output_ins
, report_error
);
1638 /* if (using_debug_info) && output_ins.opcode != -1) */
1639 if (using_debug_info
)
1640 { /* fbk 03/25/01 */
1641 /* this is done here so we can do debug type info */
1643 TYS_ELEMENTS(output_ins
.operands
);
1644 switch (output_ins
.opcode
) {
1647 TYS_ELEMENTS(output_ins
.oprs
[0].
1652 TYS_ELEMENTS(output_ins
.oprs
[0].
1657 TYS_ELEMENTS(output_ins
.oprs
[0].
1662 TYS_ELEMENTS(output_ins
.oprs
[0].
1667 TYS_ELEMENTS(output_ins
.oprs
[0].
1672 TYS_ELEMENTS(output_ins
.oprs
[0].
1677 TYS_ELEMENTS(output_ins
.oprs
[0].
1681 typeinfo
|= TY_BYTE
;
1684 typeinfo
|= TY_WORD
;
1687 if (output_ins
.eops_float
)
1688 typeinfo
|= TY_FLOAT
;
1690 typeinfo
|= TY_DWORD
;
1693 typeinfo
|= TY_QWORD
;
1696 typeinfo
|= TY_TBYTE
;
1699 typeinfo
|= TY_OWORD
;
1702 typeinfo
|= TY_YWORD
;
1705 typeinfo
= TY_LABEL
;
1709 ofmt
->current_dfmt
->debug_typevalue(typeinfo
);
1714 SET_CURR_OFFS(offs
);
1717 * else l == -1 => invalid instruction, which will be
1718 * flagged as an error on pass 2
1722 offs
+= assemble(location
.segment
, offs
, sb
, cpu
,
1723 &output_ins
, ofmt
, report_error
,
1725 SET_CURR_OFFS(offs
);
1729 cleanup_insn(&output_ins
);
1732 location
.offset
= offs
= GET_CURR_OFFS
;
1733 } /* end while (line = preproc->getline... */
1735 if (pass1
== 2 && global_offset_changed
)
1736 report_error(ERR_NONFATAL
,
1737 "phase error detected at end of assembly.");
1740 preproc
->cleanup(1);
1742 if (pass1
== 1 && terminate_after_phase
) {
1749 if (passn
>= pass_max
- 2 ||
1750 (passn
> 1 && !global_offset_changed
))
1754 preproc
->cleanup(0);
1757 if (optimizing
> 0 && opt_verbose_info
) /* -On and -Ov switches */
1759 "info:: assembly required 1+%d+1 passes\n", passn
-3);
1761 } /* exit from assemble_file (...) */
1763 static enum directives
getkw(char **directive
, char **value
)
1769 /* allow leading spaces or tabs */
1770 while (*buf
== ' ' || *buf
== '\t')
1778 while (*p
&& *p
!= ']')
1786 while (*p
&& *p
!= ';') {
1787 if (!nasm_isspace(*p
))
1793 *directive
= p
= buf
+ 1;
1794 while (*buf
&& *buf
!= ' ' && *buf
!= ']' && *buf
!= '\t')
1801 while (nasm_isspace(*buf
))
1802 buf
++; /* beppu - skip leading whitespace */
1809 return bsii(*directive
, directives
, elements(directives
));
1813 * gnu style error reporting
1814 * This function prints an error message to error_file in the
1815 * style used by GNU. An example would be:
1816 * file.asm:50: error: blah blah blah
1817 * where file.asm is the name of the file, 50 is the line number on
1818 * which the error occurs (or is detected) and "error:" is one of
1819 * the possible optional diagnostics -- it can be "error" or "warning"
1820 * or something else. Finally the line terminates with the actual
1823 * @param severity the severity of the warning or error
1824 * @param fmt the printf style format string
1826 static void report_error_gnu(int severity
, const char *fmt
, ...)
1830 if (is_suppressed_warning(severity
))
1833 if (severity
& ERR_NOFILE
)
1834 fputs("nasm: ", error_file
);
1836 char *currentfile
= NULL
;
1838 src_get(&lineno
, ¤tfile
);
1839 fprintf(error_file
, "%s:%"PRId32
": ", currentfile
, lineno
);
1840 nasm_free(currentfile
);
1843 report_error_common(severity
, fmt
, ap
);
1848 * MS style error reporting
1849 * This function prints an error message to error_file in the
1850 * style used by Visual C and some other Microsoft tools. An example
1852 * file.asm(50) : error: blah blah blah
1853 * where file.asm is the name of the file, 50 is the line number on
1854 * which the error occurs (or is detected) and "error:" is one of
1855 * the possible optional diagnostics -- it can be "error" or "warning"
1856 * or something else. Finally the line terminates with the actual
1859 * @param severity the severity of the warning or error
1860 * @param fmt the printf style format string
1862 static void report_error_vc(int severity
, const char *fmt
, ...)
1866 if (is_suppressed_warning(severity
))
1869 if (severity
& ERR_NOFILE
)
1870 fputs("nasm: ", error_file
);
1872 char *currentfile
= NULL
;
1874 src_get(&lineno
, ¤tfile
);
1875 fprintf(error_file
, "%s(%"PRId32
") : ", currentfile
, lineno
);
1876 nasm_free(currentfile
);
1879 report_error_common(severity
, fmt
, ap
);
1884 * check for supressed warning
1885 * checks for suppressed warning or pass one only warning and we're
1888 * @param severity the severity of the warning or error
1889 * @return true if we should abort error/warning printing
1891 static bool is_suppressed_warning(int severity
)
1894 * See if it's a suppressed warning.
1896 return (severity
& ERR_MASK
) == ERR_WARNING
&&
1897 (((severity
& ERR_WARN_MASK
) != 0 &&
1898 suppressed
[(severity
& ERR_WARN_MASK
) >> ERR_WARN_SHR
]) ||
1899 /* See if it's a pass-one only warning and we're not in pass one. */
1900 ((severity
& ERR_PASS1
) && pass0
!= 1));
1904 * common error reporting
1905 * This is the common back end of the error reporting schemes currently
1906 * implemented. It prints the nature of the warning and then the
1907 * specific error message to error_file and may or may not return. It
1908 * doesn't return if the error severity is a "panic" or "debug" type.
1910 * @param severity the severity of the warning or error
1911 * @param fmt the printf style format string
1913 static void report_error_common(int severity
, const char *fmt
,
1916 switch (severity
& (ERR_MASK
|ERR_NO_SEVERITY
)) {
1918 fputs("warning: ", error_file
);
1921 fputs("error: ", error_file
);
1924 fputs("fatal: ", error_file
);
1927 fputs("panic: ", error_file
);
1930 fputs("debug: ", error_file
);
1936 vfprintf(error_file
, fmt
, args
);
1937 putc('\n', error_file
);
1939 if (severity
& ERR_USAGE
)
1942 switch (severity
& ERR_MASK
) {
1944 /* no further action, by definition */
1947 if (!suppressed
[0]) /* Treat warnings as errors */
1948 terminate_after_phase
= true;
1951 terminate_after_phase
= true;
1960 exit(1); /* instantly die */
1961 break; /* placate silly compilers */
1964 /* abort(); *//* halt, catch fire, and dump core */
1970 static void usage(void)
1972 fputs("type `nasm -h' for help\n", error_file
);
1975 static void register_output_formats(void)
1977 ofmt
= ofmt_register(report_error
);
1980 #define BUF_DELTA 512
1982 static FILE *no_pp_fp
;
1983 static efunc no_pp_err
;
1984 static ListGen
*no_pp_list
;
1985 static int32_t no_pp_lineinc
;
1987 static void no_pp_reset(char *file
, int pass
, efunc error
, evalfunc eval
,
1988 ListGen
* listgen
, StrList
**deplist
)
1990 src_set_fname(nasm_strdup(file
));
1994 no_pp_fp
= fopen(file
, "r");
1996 no_pp_err(ERR_FATAL
| ERR_NOFILE
,
1997 "unable to open input file `%s'", file
);
1998 no_pp_list
= listgen
;
1999 (void)pass
; /* placate compilers */
2000 (void)eval
; /* placate compilers */
2003 StrList
*sl
= nasm_malloc(strlen(file
)+1+sizeof sl
->next
);
2005 strcpy(sl
->str
, file
);
2010 static char *no_pp_getline(void)
2012 char *buffer
, *p
, *q
;
2015 bufsize
= BUF_DELTA
;
2016 buffer
= nasm_malloc(BUF_DELTA
);
2017 src_set_linnum(src_get_linnum() + no_pp_lineinc
);
2019 while (1) { /* Loop to handle %line */
2022 while (1) { /* Loop to handle long lines */
2023 q
= fgets(p
, bufsize
- (p
- buffer
), no_pp_fp
);
2027 if (p
> buffer
&& p
[-1] == '\n')
2029 if (p
- buffer
> bufsize
- 10) {
2031 offset
= p
- buffer
;
2032 bufsize
+= BUF_DELTA
;
2033 buffer
= nasm_realloc(buffer
, bufsize
);
2034 p
= buffer
+ offset
;
2038 if (!q
&& p
== buffer
) {
2044 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2045 * them are present at the end of the line.
2047 buffer
[strcspn(buffer
, "\r\n\032")] = '\0';
2049 if (!nasm_strnicmp(buffer
, "%line", 5)) {
2052 char *nm
= nasm_malloc(strlen(buffer
));
2053 if (sscanf(buffer
+ 5, "%"PRId32
"+%d %s", &ln
, &li
, nm
) == 3) {
2054 nasm_free(src_set_fname(nm
));
2064 no_pp_list
->line(LIST_READ
, buffer
);
2069 static void no_pp_cleanup(int pass
)
2071 (void)pass
; /* placate GCC */
2075 static uint32_t get_cpu(char *value
)
2077 if (!strcmp(value
, "8086"))
2079 if (!strcmp(value
, "186"))
2081 if (!strcmp(value
, "286"))
2083 if (!strcmp(value
, "386"))
2085 if (!strcmp(value
, "486"))
2087 if (!strcmp(value
, "586") || !nasm_stricmp(value
, "pentium"))
2089 if (!strcmp(value
, "686") ||
2090 !nasm_stricmp(value
, "ppro") ||
2091 !nasm_stricmp(value
, "pentiumpro") || !nasm_stricmp(value
, "p2"))
2093 if (!nasm_stricmp(value
, "p3") || !nasm_stricmp(value
, "katmai"))
2095 if (!nasm_stricmp(value
, "p4") || /* is this right? -- jrc */
2096 !nasm_stricmp(value
, "willamette"))
2097 return IF_WILLAMETTE
;
2098 if (!nasm_stricmp(value
, "prescott"))
2100 if (!nasm_stricmp(value
, "x64") ||
2101 !nasm_stricmp(value
, "x86-64"))
2103 if (!nasm_stricmp(value
, "ia64") ||
2104 !nasm_stricmp(value
, "ia-64") ||
2105 !nasm_stricmp(value
, "itanium") ||
2106 !nasm_stricmp(value
, "itanic") || !nasm_stricmp(value
, "merced"))
2109 report_error(pass0
< 2 ? ERR_NONFATAL
: ERR_FATAL
,
2110 "unknown 'cpu' type");
2112 return IF_PLEVEL
; /* the maximum level */
2115 static int get_bits(char *value
)
2119 if ((i
= atoi(value
)) == 16)
2120 return i
; /* set for a 16-bit segment */
2123 report_error(ERR_NONFATAL
,
2124 "cannot specify 32-bit segment on processor below a 386");
2127 } else if (i
== 64) {
2128 if (cpu
< IF_X86_64
) {
2129 report_error(ERR_NONFATAL
,
2130 "cannot specify 64-bit segment on processor below an x86-64");
2134 report_error(ERR_NONFATAL
,
2135 "%s output format does not support 64-bit code",
2140 report_error(pass0
< 2 ? ERR_NONFATAL
: ERR_FATAL
,
2141 "`%s' is not a valid segment size; must be 16, 32 or 64",