* as.h (strdup): Don't declare.
[external/binutils.git] / gas / as.c
1 /* as.c - GAS main program.
2    Copyright (C) 1987, 90, 91, 92, 93, 94, 95, 1996
3    Free Software Foundation, Inc.
4
5    This file is part of GAS, the GNU Assembler.
6
7    GAS is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2, or (at your option)
10    any later version.
11
12    GAS is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GAS; see the file COPYING.  If not, write to
19    the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
20
21 /*
22  * Main program for AS; a 32-bit assembler of GNU.
23  * Understands command arguments.
24  * Has a few routines that don't fit in other modules because they
25  * are shared.
26  *
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  */
35
36 #include "ansidecl.h"
37 #include "libiberty.h"
38
39 #define COMMON
40
41 #include "as.h"
42 #include "subsegs.h"
43 #include "output-file.h"
44 #include "sb.h"
45 #include "macro.h"
46
47 static void perform_an_assembly_pass PARAMS ((int argc, char **argv));
48 static int macro_expr PARAMS ((const char *, int, sb *, int *));
49
50 int listing;                    /* true if a listing is wanted */
51
52 static char *listing_filename = NULL;   /* Name of listing file.  */
53
54 /* Maximum level of macro nesting.  */
55
56 int max_macro_nest = 100;
57
58 char *myname;                   /* argv[0] */
59 #ifdef BFD_ASSEMBLER
60 segT reg_section, expr_section;
61 segT text_section, data_section, bss_section;
62 #endif
63
64 int chunksize = 5000;
65
66 /* To monitor memory allocation more effectively, make this non-zero.
67    Then the chunk sizes for gas and bfd will be reduced.  */
68 int debug_memory = 0;
69
70 \f
71 void
72 print_version_id ()
73 {
74   static int printed;
75   if (printed)
76     return;
77   printed = 1;
78
79   fprintf (stderr, "GNU assembler version %s (%s)", GAS_VERSION, TARGET_ALIAS);
80 #ifdef BFD_ASSEMBLER
81   fprintf (stderr, ", using BFD version %s", BFD_VERSION);
82 #endif
83   fprintf (stderr, "\n");
84 }
85
86 void
87 show_usage (stream)
88      FILE *stream;
89 {
90   fprintf (stream, "Usage: %s [option...] [asmfile...]\n", myname);
91
92   fprintf (stream, "\
93 Options:\n\
94 -a[sub-option...]       turn on listings\n\
95   Sub-options [default hls]:\n\
96   d     omit debugging directives\n\
97   h     include high-level source\n\
98   l     include assembly\n\
99   n     omit forms processing\n\
100   s     include symbols\n\
101   =file set listing file name (must be last sub-option)\n");
102   fprintf (stream, "\
103 -D                      produce assembler debugging messages\n\
104 --defsym SYM=VAL        define symbol SYM to given value\n\
105 -f                      skip whitespace and comment preprocessing\n\
106 --help                  show this message and exit\n\
107 -I DIR                  add DIR to search list for .include directives\n\
108 -J                      don't warn about signed overflow\n\
109 -K                      warn when differences altered for long displacements\n\
110 -L                      keep local symbols (starting with `L')\n");
111   fprintf (stream, "\
112 -M,--mri                assemble in MRI compatibility mode\n\
113 -nocpp                  ignored\n\
114 -o OBJFILE              name the object-file output OBJFILE (default a.out)\n\
115 -R                      fold data section into text section\n\
116 --statistics            print various measured statistics from execution\n\
117 --version               print assembler version number and exit\n\
118 -W                      suppress warnings\n\
119 -w                      ignored\n\
120 -X                      ignored\n\
121 -Z                      generate object file even after errors\n");
122
123   md_show_usage (stream);
124 }
125
126 #ifdef USE_EMULATIONS
127 #define EMULATION_ENVIRON "AS_EMULATION"
128
129 extern struct emulation mipsbelf, mipslelf, mipself;
130 extern struct emulation mipsbecoff, mipslecoff, mipsecoff;
131
132 static const char *emulation_name;
133 static struct emulation *const emulations[] = { EMULATIONS };
134 static const int n_emulations = sizeof (emulations) / sizeof (emulations[0]);
135
136 static void
137 select_emulation_mode (argc, argv)
138      int argc;
139      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 ()
184 {
185   abort ();
186 }
187
188 void
189 common_emul_init ()
190 {
191   this_format = this_emulation->format;
192
193   if (this_emulation->leading_underscore == 2)
194     this_emulation->leading_underscore = this_format->dfl_leading_underscore;
195
196   if (this_emulation->default_endian != 2)
197     target_big_endian = this_emulation->default_endian;
198
199   if (this_emulation->fake_label_name == 0)
200     {
201       if (this_emulation->leading_underscore)
202         this_emulation->fake_label_name = "L0\001";
203       else
204         /* What other parameters should we test?  */
205         this_emulation->fake_label_name = ".L0\001";
206     }
207 }
208 #endif
209
210 /*
211  * Since it is easy to do here we interpret the special arg "-"
212  * to mean "use stdin" and we set that argv[] pointing to "".
213  * After we have munged argv[], the only things left are source file
214  * name(s) and ""(s) denoting stdin. These file names are used
215  * (perhaps more than once) later.
216  *
217  * check for new machine-dep cmdline options in
218  * md_parse_option definitions in config/tc-*.c
219  */
220
221 void
222 parse_args (pargc, pargv)
223      int *pargc;
224      char ***pargv;
225 {
226   int old_argc, new_argc;
227   char **old_argv, **new_argv;
228
229   /* Starting the short option string with '-' is for programs that
230      expect options and other ARGV-elements in any order and that care about
231      the ordering of the two.  We describe each non-option ARGV-element
232      as if it were the argument of an option with character code 1.  */
233
234   char *shortopts;
235   extern CONST char *md_shortopts;
236   static const char std_shortopts[] =
237     {
238       '-', 'J',
239 #ifndef WORKING_DOT_WORD
240       /* -K is not meaningful if .word is not being hacked.  */
241       'K',
242 #endif
243       'L', 'M', 'R', 'W', 'Z', 'f', 'a', ':', ':', 'D', 'I', ':', 'o', ':',
244 #ifndef VMS
245       /* -v takes an argument on VMS, so we don't make it a generic
246          option.  */
247       'v',
248 #endif
249       'w', 'X',
250       '\0'
251     };
252   struct option *longopts;
253   extern struct option md_longopts[];
254   extern size_t md_longopts_size;
255   static const struct option std_longopts[] = {
256 #define OPTION_HELP (OPTION_STD_BASE)
257     {"help", no_argument, NULL, OPTION_HELP},
258     {"mri", no_argument, NULL, 'M'},
259 #define OPTION_NOCPP (OPTION_STD_BASE + 1)
260     {"nocpp", no_argument, NULL, OPTION_NOCPP},
261 #define OPTION_STATISTICS (OPTION_STD_BASE + 2)
262     {"statistics", no_argument, NULL, OPTION_STATISTICS},
263 #define OPTION_VERSION (OPTION_STD_BASE + 3)
264     {"version", no_argument, NULL, OPTION_VERSION},
265 #define OPTION_DUMPCONFIG (OPTION_STD_BASE + 4)
266     {"dump-config", no_argument, NULL, OPTION_DUMPCONFIG},
267 #define OPTION_VERBOSE (OPTION_STD_BASE + 5)
268     {"verbose", no_argument, NULL, OPTION_VERBOSE},
269 #define OPTION_EMULATION (OPTION_STD_BASE + 6)
270     {"emulation", required_argument, NULL, OPTION_EMULATION},
271 #define OPTION_DEFSYM (OPTION_STD_BASE + 7)
272     {"defsym", required_argument, NULL, OPTION_DEFSYM}
273   };
274
275   /* Construct the option lists from the standard list and the
276      target dependent list.  */
277   shortopts = concat (std_shortopts, md_shortopts, (char *) NULL);
278   longopts = (struct option *) xmalloc (sizeof (std_longopts) + md_longopts_size);
279   memcpy (longopts, std_longopts, sizeof (std_longopts));
280   memcpy ((char *) longopts + sizeof (std_longopts),
281           md_longopts, md_longopts_size);
282
283   /* Make a local copy of the old argv.  */
284   old_argc = *pargc;
285   old_argv = *pargv;
286
287   /* Initialize a new argv that contains no options.  */
288   new_argv = (char **) xmalloc (sizeof (char *) * (old_argc + 1));
289   new_argv[0] = old_argv[0];
290   new_argc = 1;
291   new_argv[new_argc] = NULL;
292
293   while (1)
294     {
295       /* getopt_long_only is like getopt_long, but '-' as well as '--' can
296          indicate a long option.  */
297       int longind;
298       int optc = getopt_long_only (old_argc, old_argv, shortopts, longopts,
299                                    &longind);
300
301       if (optc == -1)
302         break;
303
304       switch (optc)
305         {
306         default:
307           /* md_parse_option should return 1 if it recognizes optc,
308              0 if not.  */
309           if (md_parse_option (optc, optarg) != 0)
310             break;
311           /* `-v' isn't included in the general short_opts list, so check for
312              it explicity here before deciding we've gotten a bad argument.  */
313           if (optc == 'v')
314             {
315 #ifdef VMS
316               /* Telling getopt to treat -v's value as optional can result
317                  in it picking up a following filename argument here.  The
318                  VMS code in md_parse_option can return 0 in that case,
319                  but it has no way of pushing the filename argument back.  */
320               if (optarg && *optarg)
321                 new_argv[new_argc++] = optarg,  new_argv[new_argc] = NULL;
322               else
323 #else
324               case 'v':
325 #endif
326               case OPTION_VERBOSE:
327                 print_version_id ();
328               break;
329             }
330           /*FALLTHRU*/
331
332         case '?':
333           exit (EXIT_FAILURE);
334
335         case 1:                 /* File name.  */
336           if (!strcmp (optarg, "-"))
337             optarg = "";
338           new_argv[new_argc++] = optarg;
339           new_argv[new_argc] = NULL;
340           break;
341
342         case OPTION_HELP:
343           show_usage (stdout);
344           exit (EXIT_SUCCESS);
345
346         case OPTION_NOCPP:
347           break;
348
349         case OPTION_STATISTICS:
350           flag_print_statistics = 1;
351           break;
352
353         case OPTION_VERSION:
354           print_version_id ();
355           exit (EXIT_SUCCESS);
356
357         case OPTION_EMULATION:
358 #ifdef USE_EMULATIONS
359           if (strcmp (optarg, this_emulation->name))
360             as_fatal ("multiple emulation names specified");
361 #else
362           as_fatal ("emulations not handled in this configuration");
363 #endif
364           break;
365
366         case OPTION_DUMPCONFIG:
367           fprintf (stderr, "alias = %s\n", TARGET_ALIAS);
368           fprintf (stderr, "canonical = %s\n", TARGET_CANONICAL);
369           fprintf (stderr, "cpu-type = %s\n", TARGET_CPU);
370 #ifdef TARGET_OBJ_FORMAT
371           fprintf (stderr, "format = %s\n", TARGET_OBJ_FORMAT);
372 #endif
373 #ifdef TARGET_FORMAT
374           fprintf (stderr, "bfd-target = %s\n", TARGET_FORMAT);
375 #endif
376           exit (EXIT_SUCCESS);
377
378         case OPTION_DEFSYM:
379           {
380             char *s;
381             long i;
382             symbolS *sym;
383
384             for (s = optarg; *s != '\0' && *s != '='; s++)
385               ;
386             if (*s == '\0')
387               as_fatal ("bad defsym; format is --defsym name=value");
388             *s++ = '\0';
389             i = strtol (s, (char **) NULL, 0);
390             sym = symbol_new (optarg, absolute_section, (valueT) i,
391                               &zero_address_frag);
392             symbol_table_insert (sym);
393           }
394           break;
395
396         case 'J':
397           flag_signed_overflow_ok = 1;
398           break;
399
400 #ifndef WORKING_DOT_WORD
401         case 'K':
402           flag_warn_displacement = 1;
403           break;
404 #endif
405
406         case 'L':
407           flag_keep_locals = 1;
408           break;
409
410         case 'M':
411           flag_mri = 1;
412 #ifdef TC_M68K
413           flag_m68k_mri = 1;
414 #endif
415           break;
416
417         case 'R':
418           flag_readonly_data_in_text = 1;
419           break;
420
421         case 'W':
422           flag_no_warnings = 1;
423           break;
424
425         case 'Z':
426           flag_always_generate_output = 1;
427           break;
428
429         case 'a':
430           if (optarg)
431             {
432               while (*optarg)
433                 {
434                   switch (*optarg)
435                     {
436                     case 'd':
437                       listing |= LISTING_NODEBUG;
438                       break;
439                     case 'h':
440                       listing |= LISTING_HLL;
441                       break;
442                     case 'l':
443                       listing |= LISTING_LISTING;
444                       break;
445                     case 'n':
446                       listing |= LISTING_NOFORM;
447                       break;
448                     case 's':
449                       listing |= LISTING_SYMBOLS;
450                       break;
451                     case '=':
452                       listing_filename = xstrdup (optarg + 1);
453                       optarg += strlen (listing_filename);
454                       break;
455                     default:
456                       as_fatal ("invalid listing option `%c'", *optarg);
457                       break;
458                     }
459                   optarg++;
460                 }
461             }
462           if (!listing)
463             listing = LISTING_DEFAULT;
464           break;
465
466         case 'D':
467           /* DEBUG is implemented: it debugs different */
468           /* things from other people's assemblers. */
469           flag_debug = 1;
470           break;
471
472         case 'f':
473           flag_no_comments = 1;
474           break;
475
476         case 'I':
477           {                     /* Include file directory */
478             char *temp = xstrdup (optarg);
479             add_include_dir (temp);
480             break;
481           }
482
483         case 'o':
484           out_file_name = xstrdup (optarg);
485           break;
486
487         case 'w':
488           break;
489
490         case 'X':
491           /* -X means treat warnings as errors */
492           break;
493         }
494     }
495
496   free (shortopts);
497   free (longopts);
498
499   *pargc = new_argc;
500   *pargv = new_argv;
501 }
502
503 static void dump_statistics ();
504 static long start_time;
505
506 int 
507 main (argc, argv)
508      int argc;
509      char **argv;
510 {
511   int macro_alternate;
512   int macro_strip_at;
513   int keep_it;
514
515   start_time = get_run_time ();
516
517   if (debug_memory)
518     {
519 #ifdef BFD_ASSEMBLER
520       extern long _bfd_chunksize;
521       _bfd_chunksize = 64;
522 #endif
523       chunksize = 64;
524     }
525
526 #ifdef HOST_SPECIAL_INIT
527   HOST_SPECIAL_INIT (argc, argv);
528 #endif
529
530   myname = argv[0];
531   xmalloc_set_program_name (myname);
532
533   START_PROGRESS (myname, 0);
534
535 #ifndef OBJ_DEFAULT_OUTPUT_FILE_NAME
536 #define OBJ_DEFAULT_OUTPUT_FILE_NAME "a.out"
537 #endif
538
539   out_file_name = OBJ_DEFAULT_OUTPUT_FILE_NAME;
540
541   hex_init ();
542 #ifdef BFD_ASSEMBLER
543   bfd_init ();
544 #endif
545
546 #ifdef USE_EMULATIONS
547   select_emulation_mode (argc, argv);
548 #endif
549
550   PROGRESS (1);
551   symbol_begin ();
552   frag_init ();
553   subsegs_begin ();
554   parse_args (&argc, &argv);
555   read_begin ();
556   input_scrub_begin ();
557   expr_begin ();
558
559   if (flag_print_statistics)
560     xatexit (dump_statistics);
561
562   macro_alternate = 0;
563   macro_strip_at = 0;
564 #ifdef TC_I960
565   macro_strip_at = flag_mri;
566 #endif
567 #ifdef TC_A29K
568   /* For compatibility with the AMD 29K family macro assembler
569      specification.  */
570   macro_alternate = 1;
571   macro_strip_at = 1;
572 #endif
573
574   macro_init (macro_alternate, flag_mri, macro_strip_at, macro_expr);
575
576   PROGRESS (1);
577
578 #ifdef BFD_ASSEMBLER
579   output_file_create (out_file_name);
580   assert (stdoutput != 0);
581 #endif
582
583 #ifdef tc_init_after_args
584   tc_init_after_args ();
585 #endif
586
587   PROGRESS (1);
588
589   perform_an_assembly_pass (argc, argv);        /* Assemble it. */
590
591 #ifdef md_end
592   md_end ();
593 #endif
594
595   if (seen_at_least_1_file ()
596       && !((had_warnings () && flag_always_generate_output)
597            || had_errors () > 0))
598     keep_it = 1;
599   else
600     keep_it = 0;
601
602   if (keep_it)
603     write_object_file ();
604
605 #ifndef NO_LISTING
606   listing_print (listing_filename);
607 #endif
608
609 #ifndef OBJ_VMS /* does its own file handling */
610 #ifndef BFD_ASSEMBLER
611   if (keep_it)
612 #endif
613     output_file_close (out_file_name);
614 #endif
615
616   if (!keep_it)
617     unlink (out_file_name);
618
619   input_scrub_end ();
620
621   END_PROGRESS (myname);
622
623   /* Use xexit instead of return, because under VMS environments they
624      may not place the same interpretation on the value given.  */
625   if ((had_warnings () && flag_always_generate_output)
626       || had_errors () > 0)
627     xexit (EXIT_FAILURE);
628   xexit (EXIT_SUCCESS);
629 }
630
631 static void
632 dump_statistics ()
633 {
634   extern char **environ;
635 #ifdef HAVE_SBRK
636   char *lim = (char *) sbrk (0);
637 #endif
638   long run_time = get_run_time () - start_time;
639
640   fprintf (stderr, "%s: total time in assembly: %ld.%06ld\n",
641            myname, run_time / 1000000, run_time % 1000000);
642 #ifdef HAVE_SBRK
643   fprintf (stderr, "%s: data size %ld\n",
644            myname, (long) (lim - (char *) &environ));
645 #endif
646
647   subsegs_print_statistics (stderr);
648   write_print_statistics (stderr);
649   symbol_print_statistics (stderr);
650   read_print_statistics (stderr);
651
652 #ifdef tc_print_statistics
653   tc_print_statistics (stderr);
654 #endif
655 #ifdef obj_print_statistics
656   obj_print_statistics (stderr);
657 #endif
658 }
659 \f
660
661 /*                      perform_an_assembly_pass()
662  *
663  * Here to attempt 1 pass over each input file.
664  * We scan argv[*] looking for filenames or exactly "" which is
665  * shorthand for stdin. Any argv that is NULL is not a file-name.
666  * We set need_pass_2 TRUE if, after this, we still have unresolved
667  * expressions of the form (unknown value)+-(unknown value).
668  *
669  * Note the un*x semantics: there is only 1 logical input file, but it
670  * may be a catenation of many 'physical' input files.
671  */
672 static void 
673 perform_an_assembly_pass (argc, argv)
674      int argc;
675      char **argv;
676 {
677   int saw_a_file = 0;
678 #ifdef BFD_ASSEMBLER
679   flagword applicable;
680 #endif
681
682   need_pass_2 = 0;
683
684 #ifndef BFD_ASSEMBLER
685 #ifdef MANY_SEGMENTS
686   {
687     unsigned int i;
688     for (i = SEG_E0; i < SEG_UNKNOWN; i++)
689       segment_info[i].fix_root = 0;
690   }
691   /* Create the three fixed ones */
692   {
693     segT seg;
694
695 #ifdef TE_APOLLO
696     seg = subseg_new (".wtext", 0);
697 #else
698     seg = subseg_new (".text", 0);
699 #endif
700     assert (seg == SEG_E0);
701     seg = subseg_new (".data", 0);
702     assert (seg == SEG_E1);
703     seg = subseg_new (".bss", 0);
704     assert (seg == SEG_E2);
705 #ifdef TE_APOLLO
706     create_target_segments ();
707 #endif
708   }
709
710 #else /* not MANY_SEGMENTS */
711   text_fix_root = NULL;
712   data_fix_root = NULL;
713   bss_fix_root = NULL;
714 #endif /* not MANY_SEGMENTS */
715 #else /* BFD_ASSEMBLER */
716   /* Create the standard sections, and those the assembler uses
717      internally.  */
718   text_section = subseg_new (".text", 0);
719   data_section = subseg_new (".data", 0);
720   bss_section = subseg_new (".bss", 0);
721   /* @@ FIXME -- we're setting the RELOC flag so that sections are assumed
722      to have relocs, otherwise we don't find out in time. */
723   applicable = bfd_applicable_section_flags (stdoutput);
724   bfd_set_section_flags (stdoutput, text_section,
725                          applicable & (SEC_ALLOC | SEC_LOAD | SEC_RELOC
726                                        | SEC_CODE | SEC_READONLY));
727   /* @@ FIXME -- SEC_CODE seems to mean code only, rather than code possibly.*/
728   bfd_set_section_flags (stdoutput, data_section,
729                          applicable & (SEC_ALLOC | SEC_LOAD | SEC_RELOC));
730   bfd_set_section_flags (stdoutput, bss_section, applicable & SEC_ALLOC);
731   seg_info (bss_section)->bss = 1;
732   subseg_new (BFD_ABS_SECTION_NAME, 0);
733   subseg_new (BFD_UND_SECTION_NAME, 0);
734   reg_section = subseg_new ("*GAS `reg' section*", 0);
735   expr_section = subseg_new ("*GAS `expr' section*", 0);
736
737 #endif /* BFD_ASSEMBLER */
738
739   subseg_set (text_section, 0);
740
741   /* This may add symbol table entries, which requires having an open BFD,
742      and sections already created, in BFD_ASSEMBLER mode.  */
743   md_begin ();
744
745   argv++;                       /* skip argv[0] */
746   argc--;                       /* skip argv[0] */
747   while (argc--)
748     {
749       if (*argv)
750         {                       /* Is it a file-name argument? */
751           PROGRESS (1);
752           saw_a_file++;
753           /* argv->"" if stdin desired, else->filename */
754           read_a_source_file (*argv);
755         }
756       argv++;                   /* completed that argv */
757     }
758   if (!saw_a_file)
759     read_a_source_file ("");
760 }                               /* perform_an_assembly_pass() */
761
762 /* The interface between the macro code and gas expression handling.  */
763
764 static int
765 macro_expr (emsg, idx, in, val)
766      const char *emsg;
767      int idx;
768      sb *in;
769      int *val;
770 {
771   char *hold;
772   expressionS ex;
773
774   sb_terminate (in);
775
776   hold = input_line_pointer;
777   input_line_pointer = in->ptr + idx;
778   expression (&ex);
779   idx = input_line_pointer - in->ptr;
780   input_line_pointer = hold;
781
782   if (ex.X_op != O_constant)
783     as_bad ("%s", emsg);
784
785   *val = (int) ex.X_add_number;
786
787   return idx;
788 }
789
790 /* end of as.c */