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.
34 struct forwrefinfo
{ /* info held on forward refs. */
39 static int get_bits(char *value
);
40 static uint32_t get_cpu(char *cpu_str
);
41 static void parse_cmdline(int, char **);
42 static void assemble_file(char *, StrList
**);
43 static void register_output_formats(void);
44 static void report_error_gnu(int severity
, const char *fmt
, ...);
45 static void report_error_vc(int severity
, const char *fmt
, ...);
46 static void report_error_common(int severity
, const char *fmt
,
48 static bool is_suppressed_warning(int severity
);
49 static void usage(void);
50 static efunc report_error
;
52 static int using_debug_info
, opt_verbose_info
;
53 bool tasm_compatible_mode
= false;
58 time_t official_compile_time
;
60 static char inname
[FILENAME_MAX
];
61 static char outname
[FILENAME_MAX
];
62 static char listname
[FILENAME_MAX
];
63 static char errname
[FILENAME_MAX
];
64 static int globallineno
; /* for forward-reference tracking */
65 /* static int pass = 0; */
66 static struct ofmt
*ofmt
= NULL
;
68 static FILE *error_file
; /* Where to write error messages */
70 static FILE *ofile
= NULL
;
71 int optimizing
= -1; /* number of optimization passes to take */
72 static int sb
, cmd_sb
= 16; /* by default */
73 static uint32_t cmd_cpu
= IF_PLEVEL
; /* highest level by default */
74 static uint32_t cpu
= IF_PLEVEL
; /* passed to insn_size & assemble.c */
75 bool global_offset_changed
; /* referenced in labels.c */
77 static struct location location
;
78 int in_abs_seg
; /* Flag we are in ABSOLUTE seg */
79 int32_t abs_seg
; /* ABSOLUTE segment basis */
80 int32_t abs_offset
; /* ABSOLUTE offset */
82 static struct RAA
*offsets
;
84 static struct SAA
*forwrefs
; /* keep track of forward references */
85 static const struct forwrefinfo
*forwref
;
87 static Preproc
*preproc
;
89 op_normal
, /* Preprocess and assemble */
90 op_preprocess
, /* Preprocess only */
91 op_depend
, /* Generate dependencies */
93 static enum op_type operating_mode
;
94 /* Dependency flags */
95 static bool depend_emit_phony
= false;
96 static bool depend_missing_ok
= false;
97 static const char *depend_target
= NULL
;
98 static const char *depend_file
= NULL
;
101 * Which of the suppressible warnings are suppressed. Entry zero
102 * isn't an actual warning, but it used for -w+error/-Werror.
104 static bool suppressed
[ERR_WARN_MAX
+1] = {
105 true, false, true, false, false, true, false, true, true, false
109 * The option names for the suppressible warnings. As before, entry
112 static const char *suppressed_names
[ERR_WARN_MAX
+1] = {
113 "error", "macro-params", "macro-selfref", "orphan-labels",
114 "number-overflow", "gnu-elf-extensions", "float-overflow",
115 "float-denorm", "float-underflow", "float-toolong"
119 * The explanations for the suppressible warnings. As before, entry
122 static const char *suppressed_what
[ERR_WARN_MAX
+1] = {
123 "treat warnings as errors",
124 "macro calls with wrong parameter count",
125 "cyclic macro references",
126 "labels alone on lines without trailing `:'",
127 "numeric constants does not fit in 64 bits",
128 "using 8- or 16-bit relocation in ELF32, a GNU extension",
129 "floating point overflow",
130 "floating point denormal",
131 "floating point underflow",
132 "too many digits in floating-point number"
136 * This is a null preprocessor which just copies lines from input
137 * to output. It's used when someone explicitly requests that NASM
138 * not preprocess their source file.
141 static void no_pp_reset(char *, int, efunc
, evalfunc
, ListGen
*, StrList
**);
142 static char *no_pp_getline(void);
143 static void no_pp_cleanup(int);
144 static Preproc no_pp
= {
151 * get/set current offset...
153 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
154 raa_read(offsets,location.segment))
155 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
156 (void)(offsets=raa_write(offsets,location.segment,(x))))
158 static int want_usage
;
159 static int terminate_after_phase
;
160 int user_nolist
= 0; /* fbk 9/2/00 */
162 static void nasm_fputs(const char *line
, FILE * outfile
)
165 fputs(line
, outfile
);
171 /* Convert a struct tm to a POSIX-style time constant */
172 static int64_t posix_mktime(struct tm
*tm
)
175 int64_t y
= tm
->tm_year
;
177 /* See IEEE 1003.1:2004, section 4.14 */
179 t
= (y
-70)*365 + (y
-69)/4 - (y
-1)/100 + (y
+299)/400;
191 static void define_macros_early(void)
194 struct tm lt
, *lt_p
, gm
, *gm_p
;
197 lt_p
= localtime(&official_compile_time
);
201 strftime(temp
, sizeof temp
, "__DATE__=\"%Y-%m-%d\"", <
);
203 strftime(temp
, sizeof temp
, "__DATE_NUM__=%Y%m%d", <
);
205 strftime(temp
, sizeof temp
, "__TIME__=\"%H:%M:%S\"", <
);
207 strftime(temp
, sizeof temp
, "__TIME_NUM__=%H%M%S", <
);
211 gm_p
= gmtime(&official_compile_time
);
215 strftime(temp
, sizeof temp
, "__UTC_DATE__=\"%Y-%m-%d\"", &gm
);
217 strftime(temp
, sizeof temp
, "__UTC_DATE_NUM__=%Y%m%d", &gm
);
219 strftime(temp
, sizeof temp
, "__UTC_TIME__=\"%H:%M:%S\"", &gm
);
221 strftime(temp
, sizeof temp
, "__UTC_TIME_NUM__=%H%M%S", &gm
);
226 posix_time
= posix_mktime(&gm
);
228 posix_time
= posix_mktime(<
);
233 snprintf(temp
, sizeof temp
, "__POSIX_TIME__=%"PRId64
, posix_time
);
238 static void define_macros_late(void)
242 snprintf(temp
, sizeof(temp
), "__OUTPUT_FORMAT__=%s\n",
247 static void emit_dependencies(StrList
*list
)
253 if (depend_file
&& strcmp(depend_file
, "-")) {
254 deps
= fopen(depend_file
, "w");
256 report_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
257 "unable to write dependency file `%s'", depend_file
);
264 linepos
= fprintf(deps
, "%s:", depend_target
);
265 for (l
= list
; l
; l
= l
->next
) {
266 len
= strlen(l
->str
);
267 if (linepos
+ len
> 62) {
268 fprintf(deps
, " \\\n ");
271 fprintf(deps
, " %s", l
->str
);
274 fprintf(deps
, "\n\n");
276 for (l
= list
; l
; l
= nl
) {
277 if (depend_emit_phony
)
278 fprintf(deps
, "%s:\n\n", l
->str
);
288 int main(int argc
, char **argv
)
290 StrList
*depend_list
= NULL
, **depend_ptr
;
292 time(&official_compile_time
);
295 want_usage
= terminate_after_phase
= false;
296 report_error
= report_error_gnu
;
300 nasm_set_malloc_error(report_error
);
301 offsets
= raa_init();
302 forwrefs
= saa_init((int32_t)sizeof(struct forwrefinfo
));
305 operating_mode
= op_normal
;
309 register_output_formats();
311 /* Define some macros dependent on the runtime, but not
312 on the command line. */
313 define_macros_early();
315 parse_cmdline(argc
, argv
);
317 if (terminate_after_phase
) {
323 /* If debugging info is disabled, suppress any debug calls */
324 if (!using_debug_info
)
325 ofmt
->current_dfmt
= &null_debug_form
;
328 pp_extra_stdmac(ofmt
->stdmac
);
329 parser_global_info(ofmt
, &location
);
330 eval_global_info(ofmt
, lookup_label
, &location
);
332 /* define some macros dependent of command-line */
333 define_macros_late();
335 depend_ptr
= (depend_file
|| (operating_mode
== op_depend
))
336 ? &depend_list
: NULL
;
338 depend_target
= outname
;
340 switch (operating_mode
) {
345 if (depend_missing_ok
)
346 pp_include_path(NULL
); /* "assume generated" */
348 preproc
->reset(inname
, 0, report_error
, evaluate
, &nasmlist
,
350 if (outname
[0] == '\0')
351 ofmt
->filename(inname
, outname
, report_error
);
353 while ((line
= preproc
->getline()))
362 char *file_name
= NULL
;
363 int32_t prior_linnum
= 0;
367 ofile
= fopen(outname
, "w");
369 report_error(ERR_FATAL
| ERR_NOFILE
,
370 "unable to open output file `%s'",
375 location
.known
= false;
378 preproc
->reset(inname
, 2, report_error
, evaluate
, &nasmlist
,
381 while ((line
= preproc
->getline())) {
383 * We generate %line directives if needed for later programs
385 int32_t linnum
= prior_linnum
+= lineinc
;
386 int altline
= src_get(&linnum
, &file_name
);
388 if (altline
== 1 && lineinc
== 1)
389 nasm_fputs("", ofile
);
391 lineinc
= (altline
!= -1 || lineinc
!= 1);
392 fprintf(ofile
? ofile
: stdout
,
393 "%%line %"PRId32
"+%d %s\n", linnum
, lineinc
,
396 prior_linnum
= linnum
;
398 nasm_fputs(line
, ofile
);
401 nasm_free(file_name
);
405 if (ofile
&& terminate_after_phase
)
413 * We must call ofmt->filename _anyway_, even if the user
414 * has specified their own output file, because some
415 * formats (eg OBJ and COFF) use ofmt->filename to find out
416 * the name of the input file and then put that inside the
419 ofmt
->filename(inname
, outname
, report_error
);
421 ofile
= fopen(outname
, "wb");
423 report_error(ERR_FATAL
| ERR_NOFILE
,
424 "unable to open output file `%s'", outname
);
428 * We must call init_labels() before ofmt->init() since
429 * some object formats will want to define labels in their
430 * init routines. (eg OS/2 defines the FLAT group)
434 ofmt
->init(ofile
, report_error
, define_label
, evaluate
);
436 assemble_file(inname
, depend_ptr
);
438 if (!terminate_after_phase
) {
439 ofmt
->cleanup(using_debug_info
);
443 * We had an fclose on the output file here, but we
444 * actually do that in all the object file drivers as well,
445 * so we're leaving out the one here.
457 emit_dependencies(depend_list
);
467 if (terminate_after_phase
)
474 * Get a parameter for a command line option.
475 * First arg must be in the form of e.g. -f...
477 static char *get_param(char *p
, char *q
, bool *advance
)
480 if (p
[2]) { /* the parameter's in the option */
490 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
491 "option `-%c' requires an argument", p
[1]);
498 static void copy_filename(char *dst
, const char *src
)
500 size_t len
= strlen(src
);
502 if (len
>= (size_t)FILENAME_MAX
) {
503 report_error(ERR_FATAL
| ERR_NOFILE
, "file name too long");
506 strncpy(dst
, src
, FILENAME_MAX
);
510 * Convert a string to Make-safe form
512 static char *quote_for_make(const char *str
)
517 size_t n
= 1; /* Terminating zero */
523 for (p
= str
; *p
; p
++) {
527 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
547 /* Convert N backslashes at the end of filename to 2N backslashes */
551 os
= q
= nasm_malloc(n
);
554 for (p
= str
; *p
; p
++) {
597 #define OPT_POSTFIX 1
598 struct textargs textopts
[] = {
599 {"prefix", OPT_PREFIX
},
600 {"postfix", OPT_POSTFIX
},
604 static bool stopoptions
= false;
605 static bool process_arg(char *p
, char *q
)
609 bool advance
= false;
615 if (p
[0] == '-' && !stopoptions
) {
616 if (strchr("oOfpPdDiIlFXuUZwW", p
[1])) {
617 /* These parameters take values */
618 if (!(param
= get_param(p
, q
, &advance
)))
627 case 'o': /* output file */
628 copy_filename(outname
, param
);
631 case 'f': /* output format */
632 ofmt
= ofmt_find(param
);
634 report_error(ERR_FATAL
| ERR_NOFILE
| ERR_USAGE
,
635 "unrecognised output format `%s' - "
636 "use -hf for a list", param
);
638 ofmt
->current_dfmt
= ofmt
->debug_formats
[0];
642 case 'O': /* Optimization level */
647 /* Naked -O == -Ox */
648 optimizing
= INT_MAX
>> 1; /* Almost unlimited */
652 case '0': case '1': case '2': case '3': case '4':
653 case '5': case '6': case '7': case '8': case '9':
654 opt
= strtoul(param
, ¶m
, 10);
656 /* -O0 -> optimizing == -1, 0.98 behaviour */
657 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
659 optimizing
= opt
- 1;
667 opt_verbose_info
= true;
672 optimizing
= INT_MAX
>> 1; /* Almost unlimited */
676 report_error(ERR_FATAL
,
677 "unknown optimization option -O%c\n",
686 case 'p': /* pre-include */
688 pp_pre_include(param
);
691 case 'd': /* pre-define */
693 pp_pre_define(param
);
696 case 'u': /* un-define */
698 pp_pre_undefine(param
);
701 case 'i': /* include search path */
703 pp_include_path(param
);
706 case 'l': /* listing file */
707 copy_filename(listname
, param
);
710 case 'Z': /* error messages file */
711 strcpy(errname
, param
);
714 case 'F': /* specify debug format */
715 ofmt
->current_dfmt
= dfmt_find(ofmt
, param
);
716 if (!ofmt
->current_dfmt
) {
717 report_error(ERR_FATAL
| ERR_NOFILE
| ERR_USAGE
,
718 "unrecognized debug format `%s' for"
719 " output format `%s'",
720 param
, ofmt
->shortname
);
724 case 'X': /* specify error reporting format */
725 if (nasm_stricmp("vc", param
) == 0)
726 report_error
= report_error_vc
;
727 else if (nasm_stricmp("gnu", param
) == 0)
728 report_error
= report_error_gnu
;
730 report_error(ERR_FATAL
| ERR_NOFILE
| ERR_USAGE
,
731 "unrecognized error reporting format `%s'",
736 using_debug_info
= true;
741 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
743 " [options...] [--] filename\n"
744 " or nasm -v for version info\n\n"
745 " -t assemble in SciTech TASM compatible mode\n"
746 " -g generate debug information in selected format.\n");
748 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
749 " -a don't preprocess (assemble only)\n"
750 " -M generate Makefile dependencies on stdout\n"
751 " -MG d:o, missing files assumed generated\n\n"
752 " -Z<file> redirect error messages to file\n"
753 " -s redirect error messages to stdout\n\n"
754 " -F format select a debugging format\n\n"
755 " -I<path> adds a pathname to the include file path\n");
757 (" -O<digit> optimize branch offsets (-O0 disables, default)\n"
758 " -P<file> pre-includes a file\n"
759 " -D<macro>[=<value>] pre-defines a macro\n"
760 " -U<macro> undefines a macro\n"
761 " -X<format> specifies error reporting format (gnu or vc)\n"
762 " -w+foo enables warning foo (equiv. -Wfoo)\n"
763 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
765 for (i
= 0; i
<= ERR_WARN_MAX
; i
++)
766 printf(" %-23s %s (default %s)\n",
767 suppressed_names
[i
], suppressed_what
[i
],
768 suppressed
[i
] ? "off" : "on");
770 ("\nresponse files should contain command line parameters"
771 ", one per line.\n");
773 printf("\nvalid output formats for -f are"
774 " (`*' denotes default):\n");
775 ofmt_list(ofmt
, stdout
);
777 printf("\nFor a list of valid output formats, use -hf.\n");
778 printf("For a list of debug formats, use -f <form> -y.\n");
780 exit(0); /* never need usage message here */
784 printf("\nvalid debug formats for '%s' output format are"
785 " ('*' denotes default):\n", ofmt
->shortname
);
786 dfmt_list(ofmt
, stdout
);
791 tasm_compatible_mode
= true;
796 const char *nasm_version_string
=
797 "NASM version " NASM_VER
" compiled on " __DATE__
802 puts(nasm_version_string
);
803 exit(0); /* never need usage message here */
807 case 'e': /* preprocess only */
809 operating_mode
= op_preprocess
;
812 case 'a': /* assemble only - don't preprocess */
817 if (param
[0] == 'n' && param
[1] == 'o' && param
[2] == '-') {
826 if (param
[0] != '+' && param
[0] != '-') {
827 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
828 "invalid option to `-w'");
831 suppress
= (param
[0] == '-');
835 for (i
= 0; i
<= ERR_WARN_MAX
; i
++)
836 if (!nasm_stricmp(param
, suppressed_names
[i
]))
838 if (i
<= ERR_WARN_MAX
)
839 suppressed
[i
] = suppress
;
840 else if (!nasm_stricmp(param
, "all"))
841 for (i
= 1; i
<= ERR_WARN_MAX
; i
++)
842 suppressed
[i
] = suppress
;
843 else if (!nasm_stricmp(param
, "none"))
844 for (i
= 1; i
<= ERR_WARN_MAX
; i
++)
845 suppressed
[i
] = !suppress
;
847 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
848 "invalid warning `%s'", param
);
854 operating_mode
= op_depend
;
857 operating_mode
= op_depend
;
858 depend_missing_ok
= true;
861 depend_emit_phony
= true;
872 depend_target
= quote_for_make(q
);
876 report_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
877 "unknown dependency option `-M%c'", p
[2]);
880 if (advance
&& (!q
|| !q
[0])) {
881 report_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
882 "option `-M%c' requires a parameter", p
[2]);
891 if (p
[2] == 0) { /* -- => stop processing options */
895 for (s
= 0; textopts
[s
].label
; s
++) {
896 if (!nasm_stricmp(p
+ 2, textopts
[s
].label
)) {
907 report_error(ERR_NONFATAL
| ERR_NOFILE
|
909 "option `--%s' requires an argument",
913 advance
= 1, param
= q
;
916 if (s
== OPT_PREFIX
) {
917 strncpy(lprefix
, param
, PREFIX_MAX
- 1);
918 lprefix
[PREFIX_MAX
- 1] = 0;
921 if (s
== OPT_POSTFIX
) {
922 strncpy(lpostfix
, param
, POSTFIX_MAX
- 1);
923 lpostfix
[POSTFIX_MAX
- 1] = 0;
930 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
931 "unrecognised option `--%s'", p
+ 2);
939 if (!ofmt
->setinfo(GI_SWITCH
, &p
))
940 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
941 "unrecognised option `-%c'", p
[1]);
946 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
947 "more than one input file specified");
949 copy_filename(inname
, p
);
956 #define ARG_BUF_DELTA 128
958 static void process_respfile(FILE * rfile
)
960 char *buffer
, *p
, *q
, *prevarg
;
961 int bufsize
, prevargsize
;
963 bufsize
= prevargsize
= ARG_BUF_DELTA
;
964 buffer
= nasm_malloc(ARG_BUF_DELTA
);
965 prevarg
= nasm_malloc(ARG_BUF_DELTA
);
968 while (1) { /* Loop to handle all lines in file */
970 while (1) { /* Loop to handle long lines */
971 q
= fgets(p
, bufsize
- (p
- buffer
), rfile
);
975 if (p
> buffer
&& p
[-1] == '\n')
977 if (p
- buffer
> bufsize
- 10) {
980 bufsize
+= ARG_BUF_DELTA
;
981 buffer
= nasm_realloc(buffer
, bufsize
);
986 if (!q
&& p
== buffer
) {
988 process_arg(prevarg
, NULL
);
995 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
996 * them are present at the end of the line.
998 *(p
= &buffer
[strcspn(buffer
, "\r\n\032")]) = '\0';
1000 while (p
> buffer
&& isspace(p
[-1]))
1007 if (process_arg(prevarg
, p
))
1010 if ((int) strlen(p
) > prevargsize
- 10) {
1011 prevargsize
+= ARG_BUF_DELTA
;
1012 prevarg
= nasm_realloc(prevarg
, prevargsize
);
1014 strncpy(prevarg
, p
, prevargsize
);
1018 /* Function to process args from a string of args, rather than the
1019 * argv array. Used by the environment variable and response file
1022 static void process_args(char *args
)
1024 char *p
, *q
, *arg
, *prevarg
;
1025 char separator
= ' ';
1028 if (*p
&& *p
!= '-')
1033 while (*p
&& *p
!= separator
)
1035 while (*p
== separator
)
1039 if (process_arg(prevarg
, arg
))
1043 process_arg(arg
, NULL
);
1046 static void process_response_file(const char *file
)
1049 FILE *f
= fopen(file
, "r");
1054 while (fgets(str
, sizeof str
, f
)) {
1060 static void parse_cmdline(int argc
, char **argv
)
1063 char *envreal
, *envcopy
= NULL
, *p
, *arg
;
1065 *inname
= *outname
= *listname
= *errname
= '\0';
1068 * First, process the NASMENV environment variable.
1070 envreal
= getenv("NASMENV");
1073 envcopy
= nasm_strdup(envreal
);
1074 process_args(envcopy
);
1079 * Now process the actual command line.
1084 if (argv
[0][0] == '@') {
1085 /* We have a response file, so process this as a set of
1086 * arguments like the environment variable. This allows us
1087 * to have multiple arguments on a single line, which is
1088 * different to the -@resp file processing below for regular
1091 process_response_file(argv
[0]+1);
1095 if (!stopoptions
&& argv
[0][0] == '-' && argv
[0][1] == '@') {
1096 p
= get_param(argv
[0], argc
> 1 ? argv
[1] : NULL
, &advance
);
1098 rfile
= fopen(p
, "r");
1100 process_respfile(rfile
);
1103 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1104 "unable to open response file `%s'", p
);
1107 advance
= process_arg(argv
[0], argc
> 1 ? argv
[1] : NULL
);
1108 argv
+= advance
, argc
-= advance
;
1111 /* Look for basic command line typos. This definitely doesn't
1112 catch all errors, but it might help cases of fumbled fingers. */
1114 report_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1115 "no input file specified");
1116 else if (!strcmp(inname
, errname
) ||
1117 !strcmp(inname
, outname
) ||
1118 !strcmp(inname
, listname
) ||
1119 (depend_file
&& !strcmp(inname
, depend_file
)))
1120 report_error(ERR_FATAL
| ERR_NOFILE
| ERR_USAGE
,
1121 "file `%s' is both input and output file",
1125 error_file
= fopen(errname
, "w");
1127 error_file
= stderr
; /* Revert to default! */
1128 report_error(ERR_FATAL
| ERR_NOFILE
| ERR_USAGE
,
1129 "cannot open file `%s' for error messages",
1135 /* List of directives */
1137 D_NONE
, D_ABSOLUTE
, D_BITS
, D_COMMON
, D_CPU
, D_DEBUG
, D_DEFAULT
,
1138 D_EXTERN
, D_FLOAT
, D_GLOBAL
, D_LIST
, D_SECTION
, D_SEGMENT
, D_WARNING
1140 static const char *directives
[] = {
1141 "", "absolute", "bits", "common", "cpu", "debug", "default",
1142 "extern", "float", "global", "list", "section", "segment", "warning"
1144 static enum directives
getkw(char **directive
, char **value
);
1146 static void assemble_file(char *fname
, StrList
**depend_ptr
)
1148 char *directive
, *value
, *p
, *q
, *special
, *line
, debugid
[80];
1154 struct tokenval tokval
;
1158 if (cmd_sb
== 32 && cmd_cpu
< IF_386
)
1159 report_error(ERR_FATAL
, "command line: "
1160 "32-bit segment size requires a higher cpu");
1162 pass_max
= (optimizing
> 0 ? optimizing
: 0) + 2; /* passes 1, optimizing, then 2 */
1163 pass0
= !(optimizing
> 0); /* start at 1 if not optimizing */
1164 for (passn
= 1; pass0
<= 2; passn
++) {
1168 pass1
= pass0
== 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1169 pass2
= passn
> 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1170 /* pass0 0, 0, 0, ..., 1, 2 */
1172 def_label
= passn
> 1 ? redefine_label
: define_label
;
1174 globalbits
= sb
= cmd_sb
; /* set 'bits' to command line default */
1178 nasmlist
.init(listname
, report_error
);
1181 global_offset_changed
= false; /* set by redefine_label */
1182 location
.segment
= ofmt
->section(NULL
, pass2
, &sb
);
1185 saa_rewind(forwrefs
);
1186 forwref
= saa_rstruct(forwrefs
);
1188 offsets
= raa_init();
1190 preproc
->reset(fname
, pass1
, report_error
, evaluate
, &nasmlist
,
1191 pass1
== 2 ? depend_ptr
: NULL
);
1195 location
.known
= true;
1196 location
.offset
= offs
= GET_CURR_OFFS
;
1198 while ((line
= preproc
->getline())) {
1202 /* here we parse our directives; this is not handled by the 'real'
1205 d
= getkw(&directive
, &value
);
1210 case D_SEGMENT
: /* [SEGMENT n] */
1212 seg
= ofmt
->section(value
, pass2
, &sb
);
1213 if (seg
== NO_SEG
) {
1214 report_error(pass1
== 1 ? ERR_NONFATAL
: ERR_PANIC
,
1215 "segment name `%s' not recognized",
1219 location
.segment
= seg
;
1222 case D_EXTERN
: /* [EXTERN label:special] */
1224 value
++; /* skip initial $ if present */
1227 while (*q
&& *q
!= ':')
1231 ofmt
->symdef(value
, 0L, 0L, 3, q
);
1233 } else if (passn
== 1) {
1238 while (*q
&& *q
!= ':') {
1244 report_error(ERR_NONFATAL
,
1245 "identifier expected after EXTERN");
1253 if (!is_extern(value
)) { /* allow re-EXTERN to be ignored */
1255 pass0
= 1; /* fake pass 1 in labels.c */
1256 declare_as_global(value
, special
,
1258 define_label(value
, seg_alloc(), 0L, NULL
,
1259 false, true, ofmt
, report_error
);
1262 } /* else pass0 == 1 */
1264 case D_BITS
: /* [BITS bits] */
1265 globalbits
= sb
= get_bits(value
);
1267 case D_GLOBAL
: /* [GLOBAL symbol:special] */
1269 value
++; /* skip initial $ if present */
1270 if (pass0
== 2) { /* pass 2 */
1272 while (*q
&& *q
!= ':')
1276 ofmt
->symdef(value
, 0L, 0L, 3, q
);
1278 } else if (pass2
== 1) { /* pass == 1 */
1283 while (*q
&& *q
!= ':') {
1289 report_error(ERR_NONFATAL
,
1290 "identifier expected after GLOBAL");
1298 declare_as_global(value
, special
, report_error
);
1301 case D_COMMON
: /* [COMMON symbol size:special] */
1303 value
++; /* skip initial $ if present */
1309 while (*p
&& !isspace(*p
)) {
1315 report_error(ERR_NONFATAL
,
1316 "identifier expected after COMMON");
1322 while (*p
&& isspace(*p
))
1325 while (*q
&& *q
!= ':')
1332 size
= readnum(p
, &rn_error
);
1334 report_error(ERR_NONFATAL
,
1335 "invalid size specified"
1336 " in COMMON declaration");
1338 define_common(value
, seg_alloc(), size
,
1339 special
, ofmt
, report_error
);
1341 report_error(ERR_NONFATAL
,
1342 "no size specified in"
1343 " COMMON declaration");
1344 } else if (pass0
== 2) { /* pass == 2 */
1346 while (*q
&& *q
!= ':') {
1353 ofmt
->symdef(value
, 0L, 0L, 3, q
);
1357 case D_ABSOLUTE
: /* [ABSOLUTE address] */
1359 stdscan_bufptr
= value
;
1360 tokval
.t_type
= TOKEN_INVALID
;
1361 e
= evaluate(stdscan
, NULL
, &tokval
, NULL
, pass2
,
1362 report_error
, NULL
);
1365 report_error(pass0
==
1366 1 ? ERR_NONFATAL
: ERR_PANIC
,
1367 "cannot use non-relocatable expression as "
1368 "ABSOLUTE address");
1370 abs_seg
= reloc_seg(e
);
1371 abs_offset
= reloc_value(e
);
1373 } else if (passn
== 1)
1374 abs_offset
= 0x100; /* don't go near zero in case of / */
1376 report_error(ERR_PANIC
, "invalid ABSOLUTE address "
1379 location
.segment
= NO_SEG
;
1381 case D_DEBUG
: /* [DEBUG] */
1387 while (*p
&& !isspace(*p
)) {
1394 report_error(passn
== 1 ? ERR_NONFATAL
: ERR_PANIC
,
1395 "identifier expected after DEBUG");
1398 while (*p
&& isspace(*p
))
1401 ofmt
->current_dfmt
->debug_directive(debugid
, p
);
1403 case D_WARNING
: /* [WARNING {+|-}warn-name] */
1405 while (*value
&& isspace(*value
))
1408 if (*value
== '+' || *value
== '-') {
1409 validid
= (*value
== '-') ? true : false;
1414 for (i
= 1; i
<= ERR_WARN_MAX
; i
++)
1415 if (!nasm_stricmp(value
, suppressed_names
[i
]))
1417 if (i
<= ERR_WARN_MAX
)
1418 suppressed
[i
] = validid
;
1420 report_error(ERR_NONFATAL
,
1421 "invalid warning id in WARNING directive");
1424 case D_CPU
: /* [CPU] */
1425 cpu
= get_cpu(value
);
1427 case D_LIST
: /* [LIST {+|-}] */
1428 while (*value
&& isspace(*value
))
1431 if (*value
== '+') {
1434 if (*value
== '-') {
1441 case D_DEFAULT
: /* [DEFAULT] */
1443 stdscan_bufptr
= value
;
1444 tokval
.t_type
= TOKEN_INVALID
;
1445 if (stdscan(NULL
, &tokval
) == TOKEN_SPECIAL
) {
1446 switch ((int)tokval
.t_integer
) {
1462 if (float_option(value
)) {
1463 report_error(pass1
== 1 ? ERR_NONFATAL
: ERR_PANIC
,
1464 "unknown 'float' directive: %s",
1469 if (!ofmt
->directive(directive
, value
, pass2
))
1470 report_error(pass1
== 1 ? ERR_NONFATAL
: ERR_PANIC
,
1471 "unrecognised directive [%s]",
1475 report_error(ERR_NONFATAL
,
1476 "invalid parameter to [%s] directive",
1479 } else { /* it isn't a directive */
1481 parse_line(pass1
, line
, &output_ins
,
1482 report_error
, evaluate
, def_label
);
1484 if (!(optimizing
> 0) && pass0
== 2) {
1485 if (forwref
!= NULL
&& globallineno
== forwref
->lineno
) {
1486 output_ins
.forw_ref
= true;
1488 output_ins
.oprs
[forwref
->operand
].opflags
|=
1490 forwref
= saa_rstruct(forwrefs
);
1491 } while (forwref
!= NULL
1492 && forwref
->lineno
== globallineno
);
1494 output_ins
.forw_ref
= false;
1497 if (!(optimizing
> 0) && output_ins
.forw_ref
) {
1499 for (i
= 0; i
< output_ins
.operands
; i
++) {
1500 if (output_ins
.oprs
[i
].
1501 opflags
& OPFLAG_FORWARD
) {
1502 struct forwrefinfo
*fwinf
=
1503 (struct forwrefinfo
*)
1504 saa_wstruct(forwrefs
);
1505 fwinf
->lineno
= globallineno
;
1509 } else { /* passn > 1 */
1511 * Hack to prevent phase error in the code
1515 * If the second operand is a forward reference,
1516 * the UNITY property of the number 1 in that
1517 * operand is cancelled. Otherwise the above
1518 * sequence will cause a phase error.
1520 * This hack means that the above code will
1521 * generate 286+ code.
1523 * The forward reference will mean that the
1524 * operand will not have the UNITY property on
1525 * the first pass, so the pass behaviours will
1529 if (output_ins
.operands
>= 2 &&
1530 (output_ins
.oprs
[1].opflags
& OPFLAG_FORWARD
) &&
1531 !(IMMEDIATE
& ~output_ins
.oprs
[1].type
))
1533 /* Remove special properties bits */
1534 output_ins
.oprs
[1].type
&= ~REG_SMASK
;
1542 if (output_ins
.opcode
== I_EQU
) {
1545 * Special `..' EQUs get processed in pass two,
1546 * except `..@' macro-processor EQUs which are done
1547 * in the normal place.
1549 if (!output_ins
.label
)
1550 report_error(ERR_NONFATAL
,
1551 "EQU not preceded by label");
1553 else if (output_ins
.label
[0] != '.' ||
1554 output_ins
.label
[1] != '.' ||
1555 output_ins
.label
[2] == '@') {
1556 if (output_ins
.operands
== 1 &&
1557 (output_ins
.oprs
[0].type
& IMMEDIATE
) &&
1558 output_ins
.oprs
[0].wrt
== NO_SEG
) {
1561 opflags
& OPFLAG_EXTERN
;
1562 def_label(output_ins
.label
,
1563 output_ins
.oprs
[0].segment
,
1564 output_ins
.oprs
[0].offset
, NULL
,
1567 } else if (output_ins
.operands
== 2
1568 && (output_ins
.oprs
[0].
1570 && (output_ins
.oprs
[0].type
& COLON
)
1571 && output_ins
.oprs
[0].segment
==
1573 && output_ins
.oprs
[0].wrt
== NO_SEG
1574 && (output_ins
.oprs
[1].
1576 && output_ins
.oprs
[1].segment
==
1578 && output_ins
.oprs
[1].wrt
==
1580 def_label(output_ins
.label
,
1583 output_ins
.oprs
[1].offset
, NULL
,
1587 report_error(ERR_NONFATAL
,
1588 "bad syntax for EQU");
1592 * Special `..' EQUs get processed here, except
1593 * `..@' macro processor EQUs which are done above.
1595 if (output_ins
.label
[0] == '.' &&
1596 output_ins
.label
[1] == '.' &&
1597 output_ins
.label
[2] != '@') {
1598 if (output_ins
.operands
== 1 &&
1599 (output_ins
.oprs
[0].type
& IMMEDIATE
)) {
1600 define_label(output_ins
.label
,
1601 output_ins
.oprs
[0].segment
,
1602 output_ins
.oprs
[0].offset
,
1603 NULL
, false, false, ofmt
,
1605 } else if (output_ins
.operands
== 2
1606 && (output_ins
.oprs
[0].
1608 && (output_ins
.oprs
[0].type
& COLON
)
1609 && output_ins
.oprs
[0].segment
==
1611 && (output_ins
.oprs
[1].
1613 && output_ins
.oprs
[1].segment
==
1615 define_label(output_ins
.label
,
1618 output_ins
.oprs
[1].offset
,
1619 NULL
, false, false, ofmt
,
1622 report_error(ERR_NONFATAL
,
1623 "bad syntax for EQU");
1626 } else { /* instruction isn't an EQU */
1630 int64_t l
= insn_size(location
.segment
, offs
, sb
, cpu
,
1631 &output_ins
, report_error
);
1633 /* if (using_debug_info) && output_ins.opcode != -1) */
1634 if (using_debug_info
)
1635 { /* fbk 03/25/01 */
1636 /* this is done here so we can do debug type info */
1638 TYS_ELEMENTS(output_ins
.operands
);
1639 switch (output_ins
.opcode
) {
1642 TYS_ELEMENTS(output_ins
.oprs
[0].
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].
1676 typeinfo
|= TY_BYTE
;
1679 typeinfo
|= TY_WORD
;
1682 if (output_ins
.eops_float
)
1683 typeinfo
|= TY_FLOAT
;
1685 typeinfo
|= TY_DWORD
;
1688 typeinfo
|= TY_QWORD
;
1691 typeinfo
|= TY_TBYTE
;
1694 typeinfo
|= TY_OWORD
;
1697 typeinfo
|= TY_YWORD
;
1700 typeinfo
= TY_LABEL
;
1704 ofmt
->current_dfmt
->debug_typevalue(typeinfo
);
1709 SET_CURR_OFFS(offs
);
1712 * else l == -1 => invalid instruction, which will be
1713 * flagged as an error on pass 2
1717 offs
+= assemble(location
.segment
, offs
, sb
, cpu
,
1718 &output_ins
, ofmt
, report_error
,
1720 SET_CURR_OFFS(offs
);
1724 cleanup_insn(&output_ins
);
1727 location
.offset
= offs
= GET_CURR_OFFS
;
1728 } /* end while (line = preproc->getline... */
1730 if (pass1
== 2 && global_offset_changed
)
1731 report_error(ERR_NONFATAL
,
1732 "phase error detected at end of assembly.");
1735 preproc
->cleanup(1);
1737 if (pass1
== 1 && terminate_after_phase
) {
1744 if (passn
>= pass_max
- 2 ||
1745 (passn
> 1 && !global_offset_changed
))
1749 preproc
->cleanup(0);
1752 if (optimizing
> 0 && opt_verbose_info
) /* -On and -Ov switches */
1754 "info:: assembly required 1+%d+1 passes\n", passn
-3);
1756 } /* exit from assemble_file (...) */
1758 static enum directives
getkw(char **directive
, char **value
)
1764 /* allow leading spaces or tabs */
1765 while (*buf
== ' ' || *buf
== '\t')
1773 while (*p
&& *p
!= ']')
1781 while (*p
&& *p
!= ';') {
1788 *directive
= p
= buf
+ 1;
1789 while (*buf
&& *buf
!= ' ' && *buf
!= ']' && *buf
!= '\t')
1796 while (isspace(*buf
))
1797 buf
++; /* beppu - skip leading whitespace */
1804 return bsii(*directive
, directives
, elements(directives
));
1808 * gnu style error reporting
1809 * This function prints an error message to error_file in the
1810 * style used by GNU. An example would be:
1811 * file.asm:50: error: blah blah blah
1812 * where file.asm is the name of the file, 50 is the line number on
1813 * which the error occurs (or is detected) and "error:" is one of
1814 * the possible optional diagnostics -- it can be "error" or "warning"
1815 * or something else. Finally the line terminates with the actual
1818 * @param severity the severity of the warning or error
1819 * @param fmt the printf style format string
1821 static void report_error_gnu(int severity
, const char *fmt
, ...)
1825 if (is_suppressed_warning(severity
))
1828 if (severity
& ERR_NOFILE
)
1829 fputs("nasm: ", error_file
);
1831 char *currentfile
= NULL
;
1833 src_get(&lineno
, ¤tfile
);
1834 fprintf(error_file
, "%s:%"PRId32
": ", currentfile
, lineno
);
1835 nasm_free(currentfile
);
1838 report_error_common(severity
, fmt
, ap
);
1843 * MS style error reporting
1844 * This function prints an error message to error_file in the
1845 * style used by Visual C and some other Microsoft tools. An example
1847 * file.asm(50) : error: blah blah blah
1848 * where file.asm is the name of the file, 50 is the line number on
1849 * which the error occurs (or is detected) and "error:" is one of
1850 * the possible optional diagnostics -- it can be "error" or "warning"
1851 * or something else. Finally the line terminates with the actual
1854 * @param severity the severity of the warning or error
1855 * @param fmt the printf style format string
1857 static void report_error_vc(int severity
, const char *fmt
, ...)
1861 if (is_suppressed_warning(severity
))
1864 if (severity
& ERR_NOFILE
)
1865 fputs("nasm: ", error_file
);
1867 char *currentfile
= NULL
;
1869 src_get(&lineno
, ¤tfile
);
1870 fprintf(error_file
, "%s(%"PRId32
") : ", currentfile
, lineno
);
1871 nasm_free(currentfile
);
1874 report_error_common(severity
, fmt
, ap
);
1879 * check for supressed warning
1880 * checks for suppressed warning or pass one only warning and we're
1883 * @param severity the severity of the warning or error
1884 * @return true if we should abort error/warning printing
1886 static bool is_suppressed_warning(int severity
)
1889 * See if it's a suppressed warning.
1891 return (severity
& ERR_MASK
) == ERR_WARNING
&&
1892 (((severity
& ERR_WARN_MASK
) != 0 &&
1893 suppressed
[(severity
& ERR_WARN_MASK
) >> ERR_WARN_SHR
]) ||
1894 /* See if it's a pass-one only warning and we're not in pass one. */
1895 ((severity
& ERR_PASS1
) && pass0
!= 1));
1899 * common error reporting
1900 * This is the common back end of the error reporting schemes currently
1901 * implemented. It prints the nature of the warning and then the
1902 * specific error message to error_file and may or may not return. It
1903 * doesn't return if the error severity is a "panic" or "debug" type.
1905 * @param severity the severity of the warning or error
1906 * @param fmt the printf style format string
1908 static void report_error_common(int severity
, const char *fmt
,
1911 switch (severity
& ERR_MASK
) {
1913 fputs("warning: ", error_file
);
1916 fputs("error: ", error_file
);
1919 fputs("fatal: ", error_file
);
1922 fputs("panic: ", error_file
);
1925 fputs("debug: ", error_file
);
1929 vfprintf(error_file
, fmt
, args
);
1930 putc('\n', error_file
);
1932 if (severity
& ERR_USAGE
)
1935 switch (severity
& ERR_MASK
) {
1937 /* no further action, by definition */
1940 if (!suppressed
[0]) /* Treat warnings as errors */
1941 terminate_after_phase
= true;
1944 terminate_after_phase
= true;
1953 exit(1); /* instantly die */
1954 break; /* placate silly compilers */
1957 /* abort(); *//* halt, catch fire, and dump core */
1963 static void usage(void)
1965 fputs("type `nasm -h' for help\n", error_file
);
1968 static void register_output_formats(void)
1970 ofmt
= ofmt_register(report_error
);
1973 #define BUF_DELTA 512
1975 static FILE *no_pp_fp
;
1976 static efunc no_pp_err
;
1977 static ListGen
*no_pp_list
;
1978 static int32_t no_pp_lineinc
;
1980 static void no_pp_reset(char *file
, int pass
, efunc error
, evalfunc eval
,
1981 ListGen
* listgen
, StrList
**deplist
)
1983 src_set_fname(nasm_strdup(file
));
1987 no_pp_fp
= fopen(file
, "r");
1989 no_pp_err(ERR_FATAL
| ERR_NOFILE
,
1990 "unable to open input file `%s'", file
);
1991 no_pp_list
= listgen
;
1992 (void)pass
; /* placate compilers */
1993 (void)eval
; /* placate compilers */
1996 StrList
*sl
= nasm_malloc(strlen(file
)+1+sizeof sl
->next
);
1998 strcpy(sl
->str
, file
);
2003 static char *no_pp_getline(void)
2005 char *buffer
, *p
, *q
;
2008 bufsize
= BUF_DELTA
;
2009 buffer
= nasm_malloc(BUF_DELTA
);
2010 src_set_linnum(src_get_linnum() + no_pp_lineinc
);
2012 while (1) { /* Loop to handle %line */
2015 while (1) { /* Loop to handle long lines */
2016 q
= fgets(p
, bufsize
- (p
- buffer
), no_pp_fp
);
2020 if (p
> buffer
&& p
[-1] == '\n')
2022 if (p
- buffer
> bufsize
- 10) {
2024 offset
= p
- buffer
;
2025 bufsize
+= BUF_DELTA
;
2026 buffer
= nasm_realloc(buffer
, bufsize
);
2027 p
= buffer
+ offset
;
2031 if (!q
&& p
== buffer
) {
2037 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2038 * them are present at the end of the line.
2040 buffer
[strcspn(buffer
, "\r\n\032")] = '\0';
2042 if (!nasm_strnicmp(buffer
, "%line", 5)) {
2045 char *nm
= nasm_malloc(strlen(buffer
));
2046 if (sscanf(buffer
+ 5, "%"PRId32
"+%d %s", &ln
, &li
, nm
) == 3) {
2047 nasm_free(src_set_fname(nm
));
2057 no_pp_list
->line(LIST_READ
, buffer
);
2062 static void no_pp_cleanup(int pass
)
2064 (void)pass
; /* placate GCC */
2068 static uint32_t get_cpu(char *value
)
2070 if (!strcmp(value
, "8086"))
2072 if (!strcmp(value
, "186"))
2074 if (!strcmp(value
, "286"))
2076 if (!strcmp(value
, "386"))
2078 if (!strcmp(value
, "486"))
2080 if (!strcmp(value
, "586") || !nasm_stricmp(value
, "pentium"))
2082 if (!strcmp(value
, "686") ||
2083 !nasm_stricmp(value
, "ppro") ||
2084 !nasm_stricmp(value
, "pentiumpro") || !nasm_stricmp(value
, "p2"))
2086 if (!nasm_stricmp(value
, "p3") || !nasm_stricmp(value
, "katmai"))
2088 if (!nasm_stricmp(value
, "p4") || /* is this right? -- jrc */
2089 !nasm_stricmp(value
, "willamette"))
2090 return IF_WILLAMETTE
;
2091 if (!nasm_stricmp(value
, "prescott"))
2093 if (!nasm_stricmp(value
, "x64") ||
2094 !nasm_stricmp(value
, "x86-64"))
2096 if (!nasm_stricmp(value
, "ia64") ||
2097 !nasm_stricmp(value
, "ia-64") ||
2098 !nasm_stricmp(value
, "itanium") ||
2099 !nasm_stricmp(value
, "itanic") || !nasm_stricmp(value
, "merced"))
2102 report_error(pass0
< 2 ? ERR_NONFATAL
: ERR_FATAL
,
2103 "unknown 'cpu' type");
2105 return IF_PLEVEL
; /* the maximum level */
2108 static int get_bits(char *value
)
2112 if ((i
= atoi(value
)) == 16)
2113 return i
; /* set for a 16-bit segment */
2116 report_error(ERR_NONFATAL
,
2117 "cannot specify 32-bit segment on processor below a 386");
2120 } else if (i
== 64) {
2121 if (cpu
< IF_X86_64
) {
2122 report_error(ERR_NONFATAL
,
2123 "cannot specify 64-bit segment on processor below an x86-64");
2127 report_error(ERR_NONFATAL
,
2128 "%s output format does not support 64-bit code",
2133 report_error(pass0
< 2 ? ERR_NONFATAL
: ERR_FATAL
,
2134 "`%s' is not a valid segment size; must be 16, 32 or 64",