Switch to GPLv3
[external/binutils.git] / gas / as.c
1 /* as.c - GAS main program.
2    Copyright 1987, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3    1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007
4    Free Software Foundation, Inc.
5
6    This file is part of GAS, the GNU Assembler.
7
8    GAS is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3, or (at your option)
11    any later version.
12
13    GAS is distributed in the hope that it will be useful, but WITHOUT
14    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15    or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
16    License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with GAS; see the file COPYING.  If not, write to the Free
20    Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA
21    02110-1301, USA.  */
22
23 /* Main program for AS; a 32-bit assembler of GNU.
24    Understands command arguments.
25    Has a few routines that don't fit in other modules because they
26    are shared.
27   
28                         bugs
29   
30    : initialisers
31         Since no-one else says they will support them in future: I
32    don't support them now.  */
33
34 #define COMMON
35
36 #include "as.h"
37 #include "subsegs.h"
38 #include "output-file.h"
39 #include "sb.h"
40 #include "macro.h"
41 #include "dwarf2dbg.h"
42 #include "dw2gencfi.h"
43 #include "bfdver.h"
44
45 #ifdef HAVE_ITBL_CPU
46 #include "itbl-ops.h"
47 #else
48 #define itbl_parse(itbl_file) 1
49 #define itbl_init()
50 #endif
51
52 #ifdef HAVE_SBRK
53 #ifdef NEED_DECLARATION_SBRK
54 extern PTR sbrk ();
55 #endif
56 #endif
57
58 #ifdef USING_CGEN
59 /* Perform any cgen specific initialisation for gas.  */
60 extern void gas_cgen_begin (void);
61 #endif
62
63 /* Keep a record of the itbl files we read in.  */
64 struct itbl_file_list
65 {
66   struct itbl_file_list *next;
67   char *name;
68 };
69
70 /* We build a list of defsyms as we read the options, and then define
71    them after we have initialized everything.  */
72 struct defsym_list
73 {
74   struct defsym_list *next;
75   char *name;
76   valueT value;
77 };
78
79
80 /* True if a listing is wanted.  */
81 int listing;
82
83 /* Type of debugging to generate.  */
84 enum debug_info_type debug_type = DEBUG_UNSPECIFIED;
85 int use_gnu_debug_info_extensions = 0;
86
87 #ifndef MD_DEBUG_FORMAT_SELECTOR
88 #define MD_DEBUG_FORMAT_SELECTOR NULL
89 #endif
90 static enum debug_info_type (*md_debug_format_selector) (int *) = MD_DEBUG_FORMAT_SELECTOR;
91
92 /* Maximum level of macro nesting.  */
93 int max_macro_nest = 100;
94
95 /* argv[0]  */
96 static char * myname;
97
98 /* The default obstack chunk size.  If we set this to zero, the
99    obstack code will use whatever will fit in a 4096 byte block.  */
100 int chunksize = 0;
101
102 /* To monitor memory allocation more effectively, make this non-zero.
103    Then the chunk sizes for gas and bfd will be reduced.  */
104 int debug_memory = 0;
105
106 /* Enable verbose mode.  */
107 int verbose = 0;
108
109 segT reg_section;
110 segT expr_section;
111 segT text_section;
112 segT data_section;
113 segT bss_section;
114
115 /* Name of listing file.  */
116 static char *listing_filename = NULL;
117
118 static struct defsym_list *defsyms;
119
120 static struct itbl_file_list *itbl_files;
121
122 static long start_time;
123
124 static int flag_macro_alternate;
125
126 \f
127 #ifdef USE_EMULATIONS
128 #define EMULATION_ENVIRON "AS_EMULATION"
129
130 extern struct emulation mipsbelf, mipslelf, mipself;
131 extern struct emulation mipsbecoff, mipslecoff, mipsecoff;
132 extern struct emulation i386coff, i386elf, i386aout;
133 extern struct emulation crisaout, criself;
134
135 static struct emulation *const emulations[] = { EMULATIONS };
136 static const int n_emulations = sizeof (emulations) / sizeof (emulations[0]);
137
138 static void
139 select_emulation_mode (int argc, char **argv)
140 {
141   int i;
142   char *p, *em = 0;
143
144   for (i = 1; i < argc; i++)
145     if (!strncmp ("--em", argv[i], 4))
146       break;
147
148   if (i == argc)
149     goto do_default;
150
151   p = strchr (argv[i], '=');
152   if (p)
153     p++;
154   else
155     p = argv[i + 1];
156
157   if (!p || !*p)
158     as_fatal (_("missing emulation mode name"));
159   em = p;
160
161  do_default:
162   if (em == 0)
163     em = getenv (EMULATION_ENVIRON);
164   if (em == 0)
165     em = DEFAULT_EMULATION;
166
167   if (em)
168     {
169       for (i = 0; i < n_emulations; i++)
170         if (!strcmp (emulations[i]->name, em))
171           break;
172       if (i == n_emulations)
173         as_fatal (_("unrecognized emulation name `%s'"), em);
174       this_emulation = emulations[i];
175     }
176   else
177     this_emulation = emulations[0];
178
179   this_emulation->init ();
180 }
181
182 const char *
183 default_emul_bfd_name (void)
184 {
185   abort ();
186   return NULL;
187 }
188
189 void
190 common_emul_init (void)
191 {
192   this_format = this_emulation->format;
193
194   if (this_emulation->leading_underscore == 2)
195     this_emulation->leading_underscore = this_format->dfl_leading_underscore;
196
197   if (this_emulation->default_endian != 2)
198     target_big_endian = this_emulation->default_endian;
199
200   if (this_emulation->fake_label_name == 0)
201     {
202       if (this_emulation->leading_underscore)
203         this_emulation->fake_label_name = "L0\001";
204       else
205         /* What other parameters should we test?  */
206         this_emulation->fake_label_name = ".L0\001";
207     }
208 }
209 #endif
210
211 void
212 print_version_id (void)
213 {
214   static int printed;
215
216   if (printed)
217     return;
218   printed = 1;
219
220   fprintf (stderr, _("GNU assembler version %s (%s) using BFD version %s\n"),
221            VERSION, TARGET_ALIAS, BFD_VERSION_STRING);
222 }
223
224 static void
225 show_usage (FILE * stream)
226 {
227   fprintf (stream, _("Usage: %s [option...] [asmfile...]\n"), myname);
228
229   fprintf (stream, _("\
230 Options:\n\
231   -a[sub-option...]       turn on listings\n\
232                           Sub-options [default hls]:\n\
233                           c      omit false conditionals\n\
234                           d      omit debugging directives\n\
235                           h      include high-level source\n\
236                           l      include assembly\n\
237                           m      include macro expansions\n\
238                           n      omit forms processing\n\
239                           s      include symbols\n\
240                           =FILE  list to FILE (must be last sub-option)\n"));
241
242   fprintf (stream, _("\
243   --alternate             initially turn on alternate macro syntax\n"));
244   fprintf (stream, _("\
245   -D                      produce assembler debugging messages\n"));
246   fprintf (stream, _("\
247   --defsym SYM=VAL        define symbol SYM to given value\n"));
248 #ifdef USE_EMULATIONS
249   {
250     int i;
251     char *def_em;
252
253     fprintf (stream, "\
254   --em=[");
255     for (i = 0; i < n_emulations - 1; i++)
256       fprintf (stream, "%s | ", emulations[i]->name);
257     fprintf (stream, "%s]\n", emulations[i]->name);
258
259     def_em = getenv (EMULATION_ENVIRON);
260     if (!def_em)
261       def_em = DEFAULT_EMULATION;
262     fprintf (stream, _("\
263                           emulate output (default %s)\n"), def_em);
264   }
265 #endif
266 #if defined OBJ_ELF || defined OBJ_MAYBE_ELF
267   fprintf (stream, _("\
268   --execstack             require executable stack for this object\n"));
269   fprintf (stream, _("\
270   --noexecstack           don't require executable stack for this object\n"));
271 #endif
272   fprintf (stream, _("\
273   -f                      skip whitespace and comment preprocessing\n"));
274   fprintf (stream, _("\
275   -g --gen-debug          generate debugging information\n"));
276   fprintf (stream, _("\
277   --gstabs                generate STABS debugging information\n"));
278   fprintf (stream, _("\
279   --gstabs+               generate STABS debug info with GNU extensions\n"));
280   fprintf (stream, _("\
281   --gdwarf-2              generate DWARF2 debugging information\n"));
282   fprintf (stream, _("\
283   --hash-size=<value>     set the hash table size close to <value>\n"));
284   fprintf (stream, _("\
285   --help                  show this message and exit\n"));
286   fprintf (stream, _("\
287   --target-help           show target specific options\n"));
288   fprintf (stream, _("\
289   -I DIR                  add DIR to search list for .include directives\n"));
290   fprintf (stream, _("\
291   -J                      don't warn about signed overflow\n"));
292   fprintf (stream, _("\
293   -K                      warn when differences altered for long displacements\n"));
294   fprintf (stream, _("\
295   -L,--keep-locals        keep local symbols (e.g. starting with `L')\n"));
296   fprintf (stream, _("\
297   -M,--mri                assemble in MRI compatibility mode\n"));
298   fprintf (stream, _("\
299   --MD FILE               write dependency information in FILE (default none)\n"));
300   fprintf (stream, _("\
301   -nocpp                  ignored\n"));
302   fprintf (stream, _("\
303   -o OBJFILE              name the object-file output OBJFILE (default a.out)\n"));
304   fprintf (stream, _("\
305   -R                      fold data section into text section\n"));
306   fprintf (stream, _("\
307   --reduce-memory-overheads \n\
308                           prefer smaller memory use at the cost of longer\n\
309                           assembly times\n"));
310   fprintf (stream, _("\
311   --statistics            print various measured statistics from execution\n"));
312   fprintf (stream, _("\
313   --strip-local-absolute  strip local absolute symbols\n"));
314   fprintf (stream, _("\
315   --traditional-format    Use same format as native assembler when possible\n"));
316   fprintf (stream, _("\
317   --version               print assembler version number and exit\n"));
318   fprintf (stream, _("\
319   -W  --no-warn           suppress warnings\n"));
320   fprintf (stream, _("\
321   --warn                  don't suppress warnings\n"));
322   fprintf (stream, _("\
323   --fatal-warnings        treat warnings as errors\n"));
324   fprintf (stream, _("\
325   --itbl INSTTBL          extend instruction set to include instructions\n\
326                           matching the specifications defined in file INSTTBL\n"));
327   fprintf (stream, _("\
328   -w                      ignored\n"));
329   fprintf (stream, _("\
330   -X                      ignored\n"));
331   fprintf (stream, _("\
332   -Z                      generate object file even after errors\n"));
333   fprintf (stream, _("\
334   --listing-lhs-width     set the width in words of the output data column of\n\
335                           the listing\n"));
336   fprintf (stream, _("\
337   --listing-lhs-width2    set the width in words of the continuation lines\n\
338                           of the output data column; ignored if smaller than\n\
339                           the width of the first line\n"));
340   fprintf (stream, _("\
341   --listing-rhs-width     set the max width in characters of the lines from\n\
342                           the source file\n"));
343   fprintf (stream, _("\
344   --listing-cont-lines    set the maximum number of continuation lines used\n\
345                           for the output data column of the listing\n"));
346   fprintf (stream, _("\
347   @FILE                   read options from FILE\n")); 
348
349   md_show_usage (stream);
350
351   fputc ('\n', stream);
352
353   if (REPORT_BUGS_TO[0] && stream == stdout)
354     fprintf (stream, _("Report bugs to %s\n"), REPORT_BUGS_TO);
355 }
356
357 /* Since it is easy to do here we interpret the special arg "-"
358    to mean "use stdin" and we set that argv[] pointing to "".
359    After we have munged argv[], the only things left are source file
360    name(s) and ""(s) denoting stdin. These file names are used
361    (perhaps more than once) later.
362
363    check for new machine-dep cmdline options in
364    md_parse_option definitions in config/tc-*.c.  */
365
366 static void
367 parse_args (int * pargc, char *** pargv)
368 {
369   int old_argc;
370   int new_argc;
371   char ** old_argv;
372   char ** new_argv;
373   /* Starting the short option string with '-' is for programs that
374      expect options and other ARGV-elements in any order and that care about
375      the ordering of the two.  We describe each non-option ARGV-element
376      as if it were the argument of an option with character code 1.  */
377   char *shortopts;
378   extern const char *md_shortopts;
379   static const char std_shortopts[] =
380   {
381     '-', 'J',
382 #ifndef WORKING_DOT_WORD
383     /* -K is not meaningful if .word is not being hacked.  */
384     'K',
385 #endif
386     'L', 'M', 'R', 'W', 'Z', 'a', ':', ':', 'D', 'f', 'g', ':',':', 'I', ':', 'o', ':',
387 #ifndef VMS
388     /* -v takes an argument on VMS, so we don't make it a generic
389        option.  */
390     'v',
391 #endif
392     'w', 'X',
393     /* New option for extending instruction set (see also --itbl below).  */
394     't', ':',
395     '\0'
396   };
397   struct option *longopts;
398   extern struct option md_longopts[];
399   extern size_t md_longopts_size;
400   /* Codes used for the long options with no short synonyms.  */
401   enum option_values
402     {
403       OPTION_HELP = OPTION_STD_BASE,
404       OPTION_NOCPP,
405       OPTION_STATISTICS,
406       OPTION_VERSION,
407       OPTION_DUMPCONFIG,
408       OPTION_VERBOSE,
409       OPTION_EMULATION,
410       OPTION_DEFSYM,
411       OPTION_INSTTBL,
412       OPTION_LISTING_LHS_WIDTH,
413       OPTION_LISTING_LHS_WIDTH2,
414       OPTION_LISTING_RHS_WIDTH,
415       OPTION_LISTING_CONT_LINES,
416       OPTION_DEPFILE,
417       OPTION_GSTABS,
418       OPTION_GSTABS_PLUS,
419       OPTION_GDWARF2,
420       OPTION_STRIP_LOCAL_ABSOLUTE,
421       OPTION_TRADITIONAL_FORMAT,
422       OPTION_WARN,
423       OPTION_TARGET_HELP,
424       OPTION_EXECSTACK,
425       OPTION_NOEXECSTACK,
426       OPTION_ALTERNATE,
427       OPTION_AL,
428       OPTION_HASH_TABLE_SIZE,
429       OPTION_REDUCE_MEMORY_OVERHEADS,
430       OPTION_WARN_FATAL
431     /* When you add options here, check that they do
432        not collide with OPTION_MD_BASE.  See as.h.  */
433     };
434   
435   static const struct option std_longopts[] =
436   {
437     /* Note: commas are placed at the start of the line rather than
438        the end of the preceeding line so that it is simpler to
439        selectively add and remove lines from this list.  */
440     {"alternate", no_argument, NULL, OPTION_ALTERNATE}
441     /* The entry for "a" is here to prevent getopt_long_only() from
442        considering that -a is an abbreviation for --alternate.  This is
443        necessary because -a=<FILE> is a valid switch but getopt would
444        normally reject it since --alternate does not take an argument.  */
445     ,{"a", optional_argument, NULL, 'a'}
446     /* Handle -al=<FILE>.  */
447     ,{"al", optional_argument, NULL, OPTION_AL}
448     ,{"defsym", required_argument, NULL, OPTION_DEFSYM}
449     ,{"dump-config", no_argument, NULL, OPTION_DUMPCONFIG}
450     ,{"emulation", required_argument, NULL, OPTION_EMULATION}
451 #if defined OBJ_ELF || defined OBJ_MAYBE_ELF
452     ,{"execstack", no_argument, NULL, OPTION_EXECSTACK}
453     ,{"noexecstack", no_argument, NULL, OPTION_NOEXECSTACK}
454 #endif
455     ,{"fatal-warnings", no_argument, NULL, OPTION_WARN_FATAL}
456     ,{"gdwarf-2", no_argument, NULL, OPTION_GDWARF2}
457     /* GCC uses --gdwarf-2 but GAS uses to use --gdwarf2,
458        so we keep it here for backwards compatibility.  */
459     ,{"gdwarf2", no_argument, NULL, OPTION_GDWARF2}
460     ,{"gen-debug", no_argument, NULL, 'g'}
461     ,{"gstabs", no_argument, NULL, OPTION_GSTABS}
462     ,{"gstabs+", no_argument, NULL, OPTION_GSTABS_PLUS}
463     ,{"hash-size", required_argument, NULL, OPTION_HASH_TABLE_SIZE}
464     ,{"help", no_argument, NULL, OPTION_HELP}
465     /* New option for extending instruction set (see also -t above).
466        The "-t file" or "--itbl file" option extends the basic set of
467        valid instructions by reading "file", a text file containing a
468        list of instruction formats.  The additional opcodes and their
469        formats are added to the built-in set of instructions, and
470        mnemonics for new registers may also be defined.  */
471     ,{"itbl", required_argument, NULL, OPTION_INSTTBL}
472     /* getopt allows abbreviations, so we do this to stop it from
473        treating -k as an abbreviation for --keep-locals.  Some
474        ports use -k to enable PIC assembly.  */
475     ,{"keep-locals", no_argument, NULL, 'L'}
476     ,{"keep-locals", no_argument, NULL, 'L'}
477     ,{"listing-lhs-width", required_argument, NULL, OPTION_LISTING_LHS_WIDTH}
478     ,{"listing-lhs-width2", required_argument, NULL, OPTION_LISTING_LHS_WIDTH2}
479     ,{"listing-rhs-width", required_argument, NULL, OPTION_LISTING_RHS_WIDTH}
480     ,{"listing-cont-lines", required_argument, NULL, OPTION_LISTING_CONT_LINES}
481     ,{"MD", required_argument, NULL, OPTION_DEPFILE}
482     ,{"mri", no_argument, NULL, 'M'}
483     ,{"nocpp", no_argument, NULL, OPTION_NOCPP}
484     ,{"no-warn", no_argument, NULL, 'W'}
485     ,{"reduce-memory-overheads", no_argument, NULL, OPTION_REDUCE_MEMORY_OVERHEADS}
486     ,{"statistics", no_argument, NULL, OPTION_STATISTICS}
487     ,{"strip-local-absolute", no_argument, NULL, OPTION_STRIP_LOCAL_ABSOLUTE}
488     ,{"version", no_argument, NULL, OPTION_VERSION}
489     ,{"verbose", no_argument, NULL, OPTION_VERBOSE}
490     ,{"target-help", no_argument, NULL, OPTION_TARGET_HELP}
491     ,{"traditional-format", no_argument, NULL, OPTION_TRADITIONAL_FORMAT}
492     ,{"warn", no_argument, NULL, OPTION_WARN}
493   };
494
495   /* Construct the option lists from the standard list and the target
496      dependent list.  Include space for an extra NULL option and
497      always NULL terminate.  */
498   shortopts = concat (std_shortopts, md_shortopts, (char *) NULL);
499   longopts = xmalloc (sizeof (std_longopts) + md_longopts_size + sizeof (struct option));
500   memcpy (longopts, std_longopts, sizeof (std_longopts));
501   memcpy (((char *) longopts) + sizeof (std_longopts), md_longopts, md_longopts_size);
502   memset (((char *) longopts) + sizeof (std_longopts) + md_longopts_size,
503           0, sizeof (struct option));
504
505   /* Make a local copy of the old argv.  */
506   old_argc = *pargc;
507   old_argv = *pargv;
508
509   /* Initialize a new argv that contains no options.  */
510   new_argv = xmalloc (sizeof (char *) * (old_argc + 1));
511   new_argv[0] = old_argv[0];
512   new_argc = 1;
513   new_argv[new_argc] = NULL;
514
515   while (1)
516     {
517       /* getopt_long_only is like getopt_long, but '-' as well as '--' can
518          indicate a long option.  */
519       int longind;
520       int optc = getopt_long_only (old_argc, old_argv, shortopts, longopts,
521                                    &longind);
522
523       if (optc == -1)
524         break;
525
526       switch (optc)
527         {
528         default:
529           /* md_parse_option should return 1 if it recognizes optc,
530              0 if not.  */
531           if (md_parse_option (optc, optarg) != 0)
532             break;
533           /* `-v' isn't included in the general short_opts list, so check for
534              it explicitly here before deciding we've gotten a bad argument.  */
535           if (optc == 'v')
536             {
537 #ifdef VMS
538               /* Telling getopt to treat -v's value as optional can result
539                  in it picking up a following filename argument here.  The
540                  VMS code in md_parse_option can return 0 in that case,
541                  but it has no way of pushing the filename argument back.  */
542               if (optarg && *optarg)
543                 new_argv[new_argc++] = optarg, new_argv[new_argc] = NULL;
544               else
545 #else
546               case 'v':
547 #endif
548               case OPTION_VERBOSE:
549                 print_version_id ();
550                 verbose = 1;
551               break;
552             }
553           else
554             as_bad (_("unrecognized option -%c%s"), optc, optarg ? optarg : "");
555           /* Fall through.  */
556
557         case '?':
558           exit (EXIT_FAILURE);
559
560         case 1:                 /* File name.  */
561           if (!strcmp (optarg, "-"))
562             optarg = "";
563           new_argv[new_argc++] = optarg;
564           new_argv[new_argc] = NULL;
565           break;
566
567         case OPTION_TARGET_HELP:
568           md_show_usage (stdout);
569           exit (EXIT_SUCCESS);
570
571         case OPTION_HELP:
572           show_usage (stdout);
573           exit (EXIT_SUCCESS);
574
575         case OPTION_NOCPP:
576           break;
577
578         case OPTION_STATISTICS:
579           flag_print_statistics = 1;
580           break;
581
582         case OPTION_STRIP_LOCAL_ABSOLUTE:
583           flag_strip_local_absolute = 1;
584           break;
585
586         case OPTION_TRADITIONAL_FORMAT:
587           flag_traditional_format = 1;
588           break;
589
590         case OPTION_VERSION:
591           /* This output is intended to follow the GNU standards document.  */
592           printf (_("GNU assembler %s\n"), BFD_VERSION_STRING);
593           printf (_("Copyright 2007 Free Software Foundation, Inc.\n"));
594           printf (_("\
595 This program is free software; you may redistribute it under the terms of\n\
596 the GNU General Public License version 3 or later.\n\
597 This program has absolutely no warranty.\n"));
598           printf (_("This assembler was configured for a target of `%s'.\n"),
599                   TARGET_ALIAS);
600           exit (EXIT_SUCCESS);
601
602         case OPTION_EMULATION:
603 #ifdef USE_EMULATIONS
604           if (strcmp (optarg, this_emulation->name))
605             as_fatal (_("multiple emulation names specified"));
606 #else
607           as_fatal (_("emulations not handled in this configuration"));
608 #endif
609           break;
610
611         case OPTION_DUMPCONFIG:
612           fprintf (stderr, _("alias = %s\n"), TARGET_ALIAS);
613           fprintf (stderr, _("canonical = %s\n"), TARGET_CANONICAL);
614           fprintf (stderr, _("cpu-type = %s\n"), TARGET_CPU);
615 #ifdef TARGET_OBJ_FORMAT
616           fprintf (stderr, _("format = %s\n"), TARGET_OBJ_FORMAT);
617 #endif
618 #ifdef TARGET_FORMAT
619           fprintf (stderr, _("bfd-target = %s\n"), TARGET_FORMAT);
620 #endif
621           exit (EXIT_SUCCESS);
622
623         case OPTION_DEFSYM:
624           {
625             char *s;
626             valueT i;
627             struct defsym_list *n;
628
629             for (s = optarg; *s != '\0' && *s != '='; s++)
630               ;
631             if (*s == '\0')
632               as_fatal (_("bad defsym; format is --defsym name=value"));
633             *s++ = '\0';
634             i = bfd_scan_vma (s, (const char **) NULL, 0);
635             n = xmalloc (sizeof *n);
636             n->next = defsyms;
637             n->name = optarg;
638             n->value = i;
639             defsyms = n;
640           }
641           break;
642
643         case OPTION_INSTTBL:
644         case 't':
645           {
646             /* optarg is the name of the file containing the instruction
647                formats, opcodes, register names, etc.  */
648             struct itbl_file_list *n;
649
650             if (optarg == NULL)
651               {
652                 as_warn (_("no file name following -t option"));
653                 break;
654               }
655
656             n = xmalloc (sizeof * n);
657             n->next = itbl_files;
658             n->name = optarg;
659             itbl_files = n;
660
661             /* Parse the file and add the new instructions to our internal
662                table.  If multiple instruction tables are specified, the
663                information from this table gets appended onto the existing
664                internal table.  */
665             itbl_files->name = xstrdup (optarg);
666             if (itbl_parse (itbl_files->name) != 0)
667               as_fatal (_("failed to read instruction table %s\n"),
668                         itbl_files->name);
669           }
670           break;
671
672         case OPTION_DEPFILE:
673           start_dependencies (optarg);
674           break;
675
676         case 'g':
677           /* Some backends, eg Alpha and Mips, use the -g switch for their
678              own purposes.  So we check here for an explicit -g and allow
679              the backend to decide if it wants to process it.  */
680           if (   old_argv[optind - 1][1] == 'g'
681               && md_parse_option (optc, optarg))
682             continue;
683
684           if (md_debug_format_selector)
685             debug_type = md_debug_format_selector (& use_gnu_debug_info_extensions);
686           else if (IS_ELF)
687             debug_type = DEBUG_DWARF2;
688           else
689             debug_type = DEBUG_STABS;
690           break;
691
692         case OPTION_GSTABS_PLUS:
693           use_gnu_debug_info_extensions = 1;
694           /* Fall through.  */
695         case OPTION_GSTABS:
696           debug_type = DEBUG_STABS;
697           break;
698
699         case OPTION_GDWARF2:
700           debug_type = DEBUG_DWARF2;
701           break;
702
703         case 'J':
704           flag_signed_overflow_ok = 1;
705           break;
706
707 #ifndef WORKING_DOT_WORD
708         case 'K':
709           flag_warn_displacement = 1;
710           break;
711 #endif
712         case 'L':
713           flag_keep_locals = 1;
714           break;
715
716         case OPTION_LISTING_LHS_WIDTH:
717           listing_lhs_width = atoi (optarg);
718           if (listing_lhs_width_second < listing_lhs_width)
719             listing_lhs_width_second = listing_lhs_width;
720           break;
721         case OPTION_LISTING_LHS_WIDTH2:
722           {
723             int tmp = atoi (optarg);
724
725             if (tmp > listing_lhs_width)
726               listing_lhs_width_second = tmp;
727           }
728           break;
729         case OPTION_LISTING_RHS_WIDTH:
730           listing_rhs_width = atoi (optarg);
731           break;
732         case OPTION_LISTING_CONT_LINES:
733           listing_lhs_cont_lines = atoi (optarg);
734           break;
735
736         case 'M':
737           flag_mri = 1;
738 #ifdef TC_M68K
739           flag_m68k_mri = 1;
740 #endif
741           break;
742
743         case 'R':
744           flag_readonly_data_in_text = 1;
745           break;
746
747         case 'W':
748           flag_no_warnings = 1;
749           break;
750
751         case OPTION_WARN:
752           flag_no_warnings = 0;
753           flag_fatal_warnings = 0;
754           break;
755
756         case OPTION_WARN_FATAL:
757           flag_no_warnings = 0;
758           flag_fatal_warnings = 1;
759           break;
760
761 #if defined OBJ_ELF || defined OBJ_MAYBE_ELF
762         case OPTION_EXECSTACK:
763           flag_execstack = 1;
764           flag_noexecstack = 0;
765           break;
766
767         case OPTION_NOEXECSTACK:
768           flag_noexecstack = 1;
769           flag_execstack = 0;
770           break;
771 #endif
772         case 'Z':
773           flag_always_generate_output = 1;
774           break;
775
776         case OPTION_AL:
777           listing |= LISTING_LISTING;
778           if (optarg)
779             listing_filename = xstrdup (optarg);
780           break;
781
782         case OPTION_ALTERNATE:
783           optarg = old_argv [optind - 1];
784           while (* optarg == '-')
785             optarg ++;
786
787           if (strcmp (optarg, "alternate") == 0)
788             {
789               flag_macro_alternate = 1;
790               break;
791             }
792           optarg ++;
793           /* Fall through.  */
794
795         case 'a':
796           if (optarg)
797             {
798               if (optarg != old_argv[optind] && optarg[-1] == '=')
799                 --optarg;
800
801               if (md_parse_option (optc, optarg) != 0)
802                 break;
803
804               while (*optarg)
805                 {
806                   switch (*optarg)
807                     {
808                     case 'c':
809                       listing |= LISTING_NOCOND;
810                       break;
811                     case 'd':
812                       listing |= LISTING_NODEBUG;
813                       break;
814                     case 'h':
815                       listing |= LISTING_HLL;
816                       break;
817                     case 'l':
818                       listing |= LISTING_LISTING;
819                       break;
820                     case 'm':
821                       listing |= LISTING_MACEXP;
822                       break;
823                     case 'n':
824                       listing |= LISTING_NOFORM;
825                       break;
826                     case 's':
827                       listing |= LISTING_SYMBOLS;
828                       break;
829                     case '=':
830                       listing_filename = xstrdup (optarg + 1);
831                       optarg += strlen (listing_filename);
832                       break;
833                     default:
834                       as_fatal (_("invalid listing option `%c'"), *optarg);
835                       break;
836                     }
837                   optarg++;
838                 }
839             }
840           if (!listing)
841             listing = LISTING_DEFAULT;
842           break;
843
844         case 'D':
845           /* DEBUG is implemented: it debugs different
846              things from other people's assemblers.  */
847           flag_debug = 1;
848           break;
849
850         case 'f':
851           flag_no_comments = 1;
852           break;
853
854         case 'I':
855           {                     /* Include file directory.  */
856             char *temp = xstrdup (optarg);
857
858             add_include_dir (temp);
859             break;
860           }
861
862         case 'o':
863           out_file_name = xstrdup (optarg);
864           break;
865
866         case 'w':
867           break;
868
869         case 'X':
870           /* -X means treat warnings as errors.  */
871           break;
872
873         case OPTION_REDUCE_MEMORY_OVERHEADS:
874           /* The only change we make at the moment is to reduce
875              the size of the hash tables that we use.  */
876           set_gas_hash_table_size (4051);
877           break;
878
879         case OPTION_HASH_TABLE_SIZE:
880           {
881             unsigned long new_size;
882
883             new_size = strtoul (optarg, NULL, 0);
884             if (new_size)
885               set_gas_hash_table_size (new_size);
886             else
887               as_fatal (_("--hash-size needs a numeric argument"));
888             break;
889           }
890         }
891     }
892
893   free (shortopts);
894   free (longopts);
895
896   *pargc = new_argc;
897   *pargv = new_argv;
898
899 #ifdef md_after_parse_args
900   md_after_parse_args ();
901 #endif
902 }
903
904 static void
905 dump_statistics (void)
906 {
907 #ifdef HAVE_SBRK
908   char *lim = (char *) sbrk (0);
909 #endif
910   long run_time = get_run_time () - start_time;
911
912   fprintf (stderr, _("%s: total time in assembly: %ld.%06ld\n"),
913            myname, run_time / 1000000, run_time % 1000000);
914 #ifdef HAVE_SBRK
915   fprintf (stderr, _("%s: data size %ld\n"),
916            myname, (long) (lim - (char *) &environ));
917 #endif
918
919   subsegs_print_statistics (stderr);
920   write_print_statistics (stderr);
921   symbol_print_statistics (stderr);
922   read_print_statistics (stderr);
923
924 #ifdef tc_print_statistics
925   tc_print_statistics (stderr);
926 #endif
927
928 #ifdef obj_print_statistics
929   obj_print_statistics (stderr);
930 #endif
931 }
932
933 #ifndef OBJ_VMS
934 static void
935 close_output_file (void)
936 {
937   output_file_close (out_file_name);
938 }
939 #endif
940
941 /* The interface between the macro code and gas expression handling.  */
942
943 static int
944 macro_expr (const char *emsg, int idx, sb *in, int *val)
945 {
946   char *hold;
947   expressionS ex;
948
949   sb_terminate (in);
950
951   hold = input_line_pointer;
952   input_line_pointer = in->ptr + idx;
953   expression_and_evaluate (&ex);
954   idx = input_line_pointer - in->ptr;
955   input_line_pointer = hold;
956
957   if (ex.X_op != O_constant)
958     as_bad ("%s", emsg);
959
960   *val = (int) ex.X_add_number;
961
962   return idx;
963 }
964 \f
965 /* Here to attempt 1 pass over each input file.
966    We scan argv[*] looking for filenames or exactly "" which is
967    shorthand for stdin. Any argv that is NULL is not a file-name.
968    We set need_pass_2 TRUE if, after this, we still have unresolved
969    expressions of the form (unknown value)+-(unknown value).
970
971    Note the un*x semantics: there is only 1 logical input file, but it
972    may be a catenation of many 'physical' input files.  */
973
974 static void
975 perform_an_assembly_pass (int argc, char ** argv)
976 {
977   int saw_a_file = 0;
978   flagword applicable;
979
980   need_pass_2 = 0;
981
982   /* Create the standard sections, and those the assembler uses
983      internally.  */
984   text_section = subseg_new (TEXT_SECTION_NAME, 0);
985   data_section = subseg_new (DATA_SECTION_NAME, 0);
986   bss_section = subseg_new (BSS_SECTION_NAME, 0);
987   /* @@ FIXME -- we're setting the RELOC flag so that sections are assumed
988      to have relocs, otherwise we don't find out in time.  */
989   applicable = bfd_applicable_section_flags (stdoutput);
990   bfd_set_section_flags (stdoutput, text_section,
991                          applicable & (SEC_ALLOC | SEC_LOAD | SEC_RELOC
992                                        | SEC_CODE | SEC_READONLY));
993   bfd_set_section_flags (stdoutput, data_section,
994                          applicable & (SEC_ALLOC | SEC_LOAD | SEC_RELOC
995                                        | SEC_DATA));
996   bfd_set_section_flags (stdoutput, bss_section, applicable & SEC_ALLOC);
997   seg_info (bss_section)->bss = 1;
998   subseg_new (BFD_ABS_SECTION_NAME, 0);
999   subseg_new (BFD_UND_SECTION_NAME, 0);
1000   reg_section = subseg_new ("*GAS `reg' section*", 0);
1001   expr_section = subseg_new ("*GAS `expr' section*", 0);
1002
1003   subseg_set (text_section, 0);
1004
1005   /* This may add symbol table entries, which requires having an open BFD,
1006      and sections already created.  */
1007   md_begin ();
1008
1009 #ifdef USING_CGEN
1010   gas_cgen_begin ();
1011 #endif
1012 #ifdef obj_begin
1013   obj_begin ();
1014 #endif
1015
1016   /* Skip argv[0].  */
1017   argv++;
1018   argc--;
1019
1020   while (argc--)
1021     {
1022       if (*argv)
1023         {                       /* Is it a file-name argument?  */
1024           PROGRESS (1);
1025           saw_a_file++;
1026           /* argv->"" if stdin desired, else->filename.  */
1027           read_a_source_file (*argv);
1028         }
1029       argv++;                   /* Completed that argv.  */
1030     }
1031   if (!saw_a_file)
1032     read_a_source_file ("");
1033 }
1034 \f
1035 #ifdef OBJ_ELF
1036 static void
1037 create_obj_attrs_section (void)
1038 {
1039   segT s;
1040   char *p;
1041   addressT addr;
1042   offsetT size;
1043   const char *name;
1044
1045   size = bfd_elf_obj_attr_size (stdoutput);
1046   if (size)
1047     {
1048       name = get_elf_backend_data (stdoutput)->obj_attrs_section;
1049       if (!name)
1050         name = ".gnu.attributes";
1051       s = subseg_new (name, 0);
1052       elf_section_type (s)
1053         = get_elf_backend_data (stdoutput)->obj_attrs_section_type;
1054       bfd_set_section_flags (stdoutput, s, SEC_READONLY | SEC_DATA);
1055       addr = frag_now_fix ();
1056       p = frag_more (size);
1057       bfd_elf_set_obj_attr_contents (stdoutput, (bfd_byte *)p, size);
1058     }
1059 }
1060 #endif
1061 \f
1062
1063 int
1064 main (int argc, char ** argv)
1065 {
1066   int macro_strip_at;
1067   int keep_it;
1068
1069   start_time = get_run_time ();
1070
1071 #if defined (HAVE_SETLOCALE) && defined (HAVE_LC_MESSAGES)
1072   setlocale (LC_MESSAGES, "");
1073 #endif
1074 #if defined (HAVE_SETLOCALE)
1075   setlocale (LC_CTYPE, "");
1076 #endif
1077   bindtextdomain (PACKAGE, LOCALEDIR);
1078   textdomain (PACKAGE);
1079
1080   if (debug_memory)
1081     chunksize = 64;
1082
1083 #ifdef HOST_SPECIAL_INIT
1084   HOST_SPECIAL_INIT (argc, argv);
1085 #endif
1086
1087   myname = argv[0];
1088   xmalloc_set_program_name (myname);
1089
1090   expandargv (&argc, &argv);
1091
1092   START_PROGRESS (myname, 0);
1093
1094 #ifndef OBJ_DEFAULT_OUTPUT_FILE_NAME
1095 #define OBJ_DEFAULT_OUTPUT_FILE_NAME "a.out"
1096 #endif
1097
1098   out_file_name = OBJ_DEFAULT_OUTPUT_FILE_NAME;
1099
1100   hex_init ();
1101   bfd_init ();
1102   bfd_set_error_program_name (myname);
1103
1104 #ifdef USE_EMULATIONS
1105   select_emulation_mode (argc, argv);
1106 #endif
1107
1108   PROGRESS (1);
1109   /* Call parse_args before any of the init/begin functions
1110      so that switches like --hash-size can be honored.  */
1111   parse_args (&argc, &argv);
1112   symbol_begin ();
1113   frag_init ();
1114   subsegs_begin ();
1115   read_begin ();
1116   input_scrub_begin ();
1117   expr_begin ();
1118
1119 #ifndef OBJ_VMS /* Does its own file handling.  */
1120   /* It has to be called after dump_statistics ().  */
1121   xatexit (close_output_file);
1122 #endif
1123
1124   if (flag_print_statistics)
1125     xatexit (dump_statistics);
1126
1127   macro_strip_at = 0;
1128 #ifdef TC_I960
1129   macro_strip_at = flag_mri;
1130 #endif
1131
1132   macro_init (flag_macro_alternate, flag_mri, macro_strip_at, macro_expr);
1133
1134   PROGRESS (1);
1135
1136   output_file_create (out_file_name);
1137   assert (stdoutput != 0);
1138
1139 #ifdef tc_init_after_args
1140   tc_init_after_args ();
1141 #endif
1142
1143   itbl_init ();
1144
1145   /* Now that we have fully initialized, and have created the output
1146      file, define any symbols requested by --defsym command line
1147      arguments.  */
1148   while (defsyms != NULL)
1149     {
1150       symbolS *sym;
1151       struct defsym_list *next;
1152
1153       sym = symbol_new (defsyms->name, absolute_section, defsyms->value,
1154                         &zero_address_frag);
1155       /* Make symbols defined on the command line volatile, so that they
1156          can be redefined inside a source file.  This makes this assembler's
1157          behaviour compatible with earlier versions, but it may not be
1158          completely intuitive.  */
1159       S_SET_VOLATILE (sym);
1160       symbol_table_insert (sym);
1161       next = defsyms->next;
1162       free (defsyms);
1163       defsyms = next;
1164     }
1165
1166   PROGRESS (1);
1167
1168   /* Assemble it.  */
1169   perform_an_assembly_pass (argc, argv);
1170
1171   cond_finish_check (-1);
1172
1173 #ifdef md_end
1174   md_end ();
1175 #endif
1176
1177 #ifdef OBJ_ELF
1178   if (IS_ELF)
1179     create_obj_attrs_section ();
1180 #endif
1181
1182 #if defined OBJ_ELF || defined OBJ_MAYBE_ELF
1183   if ((flag_execstack || flag_noexecstack)
1184       && OUTPUT_FLAVOR == bfd_target_elf_flavour)
1185     {
1186       segT gnustack;
1187
1188       gnustack = subseg_new (".note.GNU-stack", 0);
1189       bfd_set_section_flags (stdoutput, gnustack,
1190                              SEC_READONLY | (flag_execstack ? SEC_CODE : 0));
1191                                                                              
1192     }
1193 #endif
1194
1195   /* If we've been collecting dwarf2 .debug_line info, either for
1196      assembly debugging or on behalf of the compiler, emit it now.  */
1197   dwarf2_finish ();
1198
1199   /* If we constructed dwarf2 .eh_frame info, either via .cfi 
1200      directives from the user or by the backend, emit it now.  */
1201   cfi_finish ();
1202
1203   if (seen_at_least_1_file ()
1204       && (flag_always_generate_output || had_errors () == 0))
1205     keep_it = 1;
1206   else
1207     keep_it = 0;
1208
1209   /* This used to be done at the start of write_object_file in
1210      write.c, but that caused problems when doing listings when
1211      keep_it was zero.  This could probably be moved above md_end, but
1212      I didn't want to risk the change.  */
1213   subsegs_finish ();
1214
1215   if (keep_it)
1216     write_object_file ();
1217
1218 #ifndef NO_LISTING
1219   listing_print (listing_filename);
1220 #endif
1221
1222   if (flag_fatal_warnings && had_warnings () > 0 && had_errors () == 0)
1223     as_bad (_("%d warnings, treating warnings as errors"), had_warnings ());
1224
1225   if (had_errors () > 0 && ! flag_always_generate_output)
1226     keep_it = 0;
1227
1228   if (!keep_it)
1229     unlink_if_ordinary (out_file_name);
1230
1231   input_scrub_end ();
1232
1233   END_PROGRESS (myname);
1234
1235   /* Use xexit instead of return, because under VMS environments they
1236      may not place the same interpretation on the value given.  */
1237   if (had_errors () > 0)
1238     xexit (EXIT_FAILURE);
1239
1240   /* Only generate dependency file if assembler was successful.  */
1241   print_dependencies ();
1242
1243   xexit (EXIT_SUCCESS);
1244 }