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