From Craig Silverstein: Add support for --demangle.
[external/binutils.git] / gold / options.cc
1 // options.c -- handle command line options for gold
2
3 // Copyright 2006, 2007 Free Software Foundation, Inc.
4 // Written by Ian Lance Taylor <iant@google.com>.
5
6 // This file is part of gold.
7
8 // This program 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 of the License, or
11 // (at your option) any later version.
12
13 // This program 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 this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
21 // MA 02110-1301, USA.
22
23 #include "gold.h"
24
25 #include <cstdlib>
26 #include <iostream>
27 #include <sys/stat.h>
28 #include "filenames.h"
29 #include "libiberty.h"
30
31 #include "options.h"
32
33 namespace gold
34 {
35
36 // The information we keep for a single command line option.
37
38 struct options::One_option
39 {
40   // The single character option name, or '\0' if this is only a long
41   // option.
42   char short_option;
43
44   // The long option name, or NULL if this is only a short option.
45   const char* long_option;
46
47   // Description of the option for --help output, or NULL if there is none.
48   const char* doc;
49
50   // How to print the option name in --help output, or NULL to use the
51   // default.
52   const char* help_output;
53
54   // Long option dash control.  This is ignored if long_option is
55   // NULL.
56   enum
57     {
58       // Long option normally takes one dash; two dashes are also
59       // accepted.
60       ONE_DASH,
61       // Long option normally takes two dashes; one dash is also
62       // accepted.
63       TWO_DASHES,
64       // Long option always takes two dashes.
65       EXACTLY_TWO_DASHES
66     } dash;
67
68   // Function for special handling, or NULL.  Returns the number of
69   // arguments to skip.  This will normally be at least 1, but it may
70   // be 0 if this function changes *argv.  ARG points to the location
71   // in *ARGV where the option starts, which may be helpful for a
72   // short option.
73   int (*special)(int argc, char** argv, char *arg, bool long_option,
74                  Command_line*);
75
76   // If this is a position independent option which does not take an
77   // argument, this is the member function to call to record it.
78   void (General_options::*general_noarg)();
79
80   // If this is a position independent function which takes an
81   // argument, this is the member function to call to record it.
82   void (General_options::*general_arg)(const char*);
83
84   // If this is a position dependent option which does not take an
85   // argument, this is the member function to call to record it.
86   void (Position_dependent_options::*dependent_noarg)();
87
88   // If this is a position dependent option which takes an argument,
89   // this is the member function to record it.
90   void (Position_dependent_options::*dependent_arg)(const char*);
91
92   // Return whether this option takes an argument.
93   bool
94   takes_argument() const
95   { return this->general_arg != NULL || this->dependent_arg != NULL; }
96 };
97
98 // We have a separate table for -z options.
99
100 struct options::One_z_option
101 {
102   // The name of the option.
103   const char* name;
104
105   // The member function in General_options called to record it.
106   void (General_options::*set)();
107 };
108
109 class options::Command_line_options
110 {
111  public:
112   static const One_option options[];
113   static const int options_size;
114   static const One_z_option z_options[];
115   static const int z_options_size;
116 };
117
118 } // End namespace gold.
119
120 namespace
121 {
122
123 // Handle the special -l option, which adds an input file.
124
125 int
126 library(int argc, char** argv, char* arg, bool long_option,
127         gold::Command_line* cmdline)
128 {
129   return cmdline->process_l_option(argc, argv, arg, long_option);
130 }
131
132 // Handle the special -T/--script option, which reads a linker script.
133
134 int
135 invoke_script(int argc, char** argv, char* arg, bool long_option,
136               gold::Command_line* cmdline)
137 {
138   int ret;
139   const char* script_name = cmdline->get_special_argument("script", argc, argv,
140                                                           arg, long_option,
141                                                           &ret);
142   if (!read_commandline_script(script_name, cmdline))
143     gold::gold_error(_("%s: unable to parse script file %s\n"),
144                      gold::program_name, arg);
145   return ret;
146 }
147
148 // Handle the special --start-group option.
149
150 int
151 start_group(int, char**, char* arg, bool, gold::Command_line* cmdline)
152 {
153   cmdline->start_group(arg);
154   return 1;
155 }
156
157 // Handle the special --end-group option.
158
159 int
160 end_group(int, char**, char* arg, bool, gold::Command_line* cmdline)
161 {
162   cmdline->end_group(arg);
163   return 1;
164 }
165
166 // Report usage information for ld --help, and exit.
167
168 int
169 help(int, char**, char*, bool, gold::Command_line*)
170 {
171   printf(_("Usage: %s [options] file...\nOptions:\n"), gold::program_name);
172
173   const int options_size = gold::options::Command_line_options::options_size;
174   const gold::options::One_option* options =
175     gold::options::Command_line_options::options;
176   for (int i = 0; i < options_size; ++i)
177     {
178       if (options[i].doc == NULL)
179         continue;
180
181       printf("  ");
182       int len = 2;
183       bool comma = false;
184
185       int j = i;
186       do
187         {
188           if (options[j].help_output != NULL)
189             {
190               if (comma)
191                 {
192                   printf(", ");
193                   len += 2;
194                 }
195               printf(options[j].help_output);
196               len += std::strlen(options[i].help_output);
197               comma = true;
198             }
199           else
200             {
201               if (options[j].short_option != '\0')
202                 {
203                   if (comma)
204                     {
205                       printf(", ");
206                       len += 2;
207                     }
208                   printf("-%c", options[j].short_option);
209                   len += 2;
210                   comma = true;
211                 }
212
213               if (options[j].long_option != NULL)
214                 {
215                   if (comma)
216                     {
217                       printf(", ");
218                       len += 2;
219                     }
220                   if (options[j].dash == gold::options::One_option::ONE_DASH)
221                     {
222                       printf("-");
223                       ++len;
224                     }
225                   else
226                     {
227                       printf("--");
228                       len += 2;
229                     }
230                   printf("%s", options[j].long_option);
231                   len += std::strlen(options[j].long_option);
232                   comma = true;
233                 }
234             }
235           ++j;
236         }
237       while (j < options_size && options[j].doc == NULL);
238
239       if (len >= 30)
240         {
241           printf("\n");
242           len = 0;
243         }
244       for (; len < 30; ++len)
245         std::putchar(' ');
246
247       std::puts(options[i].doc);
248     }
249
250   ::exit(0);
251
252   return 0;
253 }
254
255 // Report version information.
256
257 int
258 version(int, char**, char* opt, bool, gold::Command_line*)
259 {
260   gold::print_version(opt[0] == 'v' && opt[1] == '\0');
261   ::exit(0);
262   return 0;
263 }
264
265 // If the default sysroot is relocatable, try relocating it based on
266 // the prefix FROM.
267
268 char*
269 get_relative_sysroot(const char* from)
270 {
271   char* path = make_relative_prefix(gold::program_name, from,
272                                     TARGET_SYSTEM_ROOT);
273   if (path != NULL)
274     {
275       struct stat s;
276       if (::stat(path, &s) == 0 && S_ISDIR(s.st_mode))
277         return path;
278       free(path);
279     }
280
281   return NULL;
282 }
283
284 // Return the default sysroot.  This is set by the --with-sysroot
285 // option to configure.
286
287 std::string
288 get_default_sysroot()
289 {
290   const char* sysroot = TARGET_SYSTEM_ROOT;
291   if (*sysroot == '\0')
292     return "";
293
294   if (TARGET_SYSTEM_ROOT_RELOCATABLE)
295     {
296       char* path = get_relative_sysroot (BINDIR);
297       if (path == NULL)
298         path = get_relative_sysroot (TOOLBINDIR);
299       if (path != NULL)
300         {
301           std::string ret = path;
302           free(path);
303           return ret;
304         }
305     }
306
307   return sysroot;
308 }
309
310 } // End anonymous namespace.
311
312 namespace gold
313 {
314
315 // Helper macros used to specify the options.  We could also do this
316 // using constructors, but then g++ would generate code to initialize
317 // the array.  We want the array to be initialized statically so that
318 // we get better startup time.
319
320 #define GENERAL_NOARG(short_option, long_option, doc, help, dash, func) \
321   { short_option, long_option, doc, help, options::One_option::dash, \
322       NULL, func, NULL, NULL, NULL }
323 #define GENERAL_ARG(short_option, long_option, doc, help, dash, func)   \
324   { short_option, long_option, doc, help, options::One_option::dash, \
325       NULL, NULL, func, NULL, NULL }
326 #define POSDEP_NOARG(short_option, long_option, doc, help, dash, func)  \
327   { short_option, long_option, doc, help, options::One_option::dash, \
328       NULL,  NULL, NULL, func, NULL }
329 #define POSDEP_ARG(short_option, long_option, doc, help, dash, func)    \
330   { short_option, long_option, doc, help, options::One_option::dash, \
331       NULL, NULL, NULL, NULL, func }
332 #define SPECIAL(short_option, long_option, doc, help, dash, func)       \
333   { short_option, long_option, doc, help, options::One_option::dash, \
334       func, NULL, NULL, NULL, NULL }
335
336 // Here is the actual list of options which we accept.
337
338 const options::One_option
339 options::Command_line_options::options[] =
340 {
341   GENERAL_NOARG('\0', "allow-shlib-undefined",
342                 N_("Allow unresolved references in shared libraries"),
343                 NULL, TWO_DASHES,
344                 &General_options::set_allow_shlib_undefined),
345   GENERAL_NOARG('\0', "no-allow-shlib-undefined",
346                 N_("Do not allow unresolved references in shared libraries"),
347                 NULL, TWO_DASHES,
348                 &General_options::set_no_allow_shlib_undefined),
349   POSDEP_NOARG('\0', "as-needed",
350                N_("Only set DT_NEEDED for dynamic libs if used"),
351                NULL, TWO_DASHES, &Position_dependent_options::set_as_needed),
352   POSDEP_NOARG('\0', "no-as-needed",
353                N_("Always DT_NEEDED for dynamic libs (default)"),
354                NULL, TWO_DASHES, &Position_dependent_options::clear_as_needed),
355   POSDEP_NOARG('\0', "Bdynamic",
356                N_("-l searches for shared libraries"),
357                NULL, ONE_DASH,
358                &Position_dependent_options::set_dynamic_search),
359   POSDEP_NOARG('\0', "Bstatic",
360                N_("-l does not search for shared libraries"),
361                NULL, ONE_DASH,
362                &Position_dependent_options::set_static_search),
363   GENERAL_NOARG('\0', "Bsymbolic", N_("Bind defined symbols locally"),
364                 NULL, ONE_DASH, &General_options::set_symbolic),
365   GENERAL_NOARG('\0', "demangle", N_("Demangle C++ symbols in log messages"),
366                 NULL, TWO_DASHES, &General_options::set_demangle),
367   GENERAL_NOARG('\0', "no-demangle",
368                 N_("Do not demangle C++ symbols in log messages"),
369                 NULL, TWO_DASHES, &General_options::clear_demangle),
370   GENERAL_NOARG('\0', "detect-odr-violations",
371                 N_("Try to detect violations of the One Definition Rule"),
372                 NULL, TWO_DASHES, &General_options::set_detect_odr_violations),
373   GENERAL_NOARG('E', "export-dynamic", N_("Export all dynamic symbols"),
374                 NULL, TWO_DASHES, &General_options::set_export_dynamic),
375   GENERAL_NOARG('\0', "eh-frame-hdr", N_("Create exception frame header"),
376                 NULL, TWO_DASHES, &General_options::set_create_eh_frame_hdr),
377   GENERAL_ARG('I', "dynamic-linker", N_("Set dynamic linker path"),
378               N_("-I PROGRAM, --dynamic-linker PROGRAM"), TWO_DASHES,
379               &General_options::set_dynamic_linker),
380   SPECIAL('l', "library", N_("Search for library LIBNAME"),
381           N_("-lLIBNAME, --library LIBNAME"), TWO_DASHES,
382           &library),
383   GENERAL_ARG('L', "library-path", N_("Add directory to search path"),
384               N_("-L DIR, --library-path DIR"), TWO_DASHES,
385               &General_options::add_to_search_path),
386   GENERAL_ARG('m', NULL, N_("Ignored for compatibility"), NULL, ONE_DASH,
387               &General_options::ignore),
388   GENERAL_ARG('o', "output", N_("Set output file name"),
389               N_("-o FILE, --output FILE"), TWO_DASHES,
390               &General_options::set_output_file_name),
391   GENERAL_ARG('O', NULL, N_("Optimize output file size"),
392               N_("-O level"), ONE_DASH,
393               &General_options::set_optimization_level),
394   GENERAL_NOARG('r', NULL, N_("Generate relocatable output"), NULL,
395                 ONE_DASH, &General_options::set_relocatable),
396   GENERAL_ARG('R', "rpath", N_("Add DIR to runtime search path"),
397               N_("-R DIR, -rpath DIR"), ONE_DASH,
398               &General_options::add_to_rpath),
399   GENERAL_ARG('\0', "rpath-link",
400               N_("Add DIR to link time shared library search path"),
401               N_("--rpath-link DIR"), TWO_DASHES,
402               &General_options::add_to_rpath_link),
403   GENERAL_NOARG('s', "strip-all", N_("Strip all symbols"), NULL,
404                 TWO_DASHES, &General_options::set_strip_all),
405   GENERAL_NOARG('S', "strip-debug", N_("Strip debugging information"), NULL,
406                 TWO_DASHES, &General_options::set_strip_debug),
407   GENERAL_NOARG('\0', "shared", N_("Generate shared library"),
408                 NULL, ONE_DASH, &General_options::set_shared),
409   GENERAL_NOARG('\0', "static", N_("Do not link against shared libraries"),
410                 NULL, ONE_DASH, &General_options::set_static),
411   GENERAL_NOARG('\0', "stats", N_("Print resource usage statistics"),
412                 NULL, TWO_DASHES, &General_options::set_stats),
413   GENERAL_ARG('\0', "sysroot", N_("Set target system root directory"),
414               N_("--sysroot DIR"), TWO_DASHES, &General_options::set_sysroot),
415   GENERAL_ARG('\0', "Ttext", N_("Set the address of the .text section"),
416               N_("-Ttext ADDRESS"), ONE_DASH,
417               &General_options::set_text_segment_address),
418   // This must come after -Ttext since it's a prefix of it.
419   SPECIAL('T', "script", N_("Read linker script"),
420           N_("-T FILE, --script FILE"), TWO_DASHES,
421           &invoke_script),
422   GENERAL_NOARG('\0', "threads", N_("Run the linker multi-threaded"),
423                 NULL, TWO_DASHES, &General_options::set_threads),
424   GENERAL_NOARG('\0', "no-threads", N_("Do not run the linker multi-threaded"),
425                 NULL, TWO_DASHES, &General_options::clear_threads),
426   GENERAL_ARG('\0', "thread-count", N_("Number of threads to use"),
427               N_("--thread-count COUNT"), TWO_DASHES,
428               &General_options::set_thread_count),
429   GENERAL_ARG('\0', "thread-count-initial",
430               N_("Number of threads to use in initial pass"),
431               N_("--thread-count-initial COUNT"), TWO_DASHES,
432               &General_options::set_thread_count_initial),
433   GENERAL_ARG('\0', "thread-count-middle",
434               N_("Number of threads to use in middle pass"),
435               N_("--thread-count-middle COUNT"), TWO_DASHES,
436               &General_options::set_thread_count_middle),
437   GENERAL_ARG('\0', "thread-count-final",
438               N_("Number of threads to use in final pass"),
439               N_("--thread-count-final COUNT"), TWO_DASHES,
440               &General_options::set_thread_count_final),
441   POSDEP_NOARG('\0', "whole-archive",
442                N_("Include all archive contents"),
443                NULL, TWO_DASHES,
444                &Position_dependent_options::set_whole_archive),
445   POSDEP_NOARG('\0', "no-whole-archive",
446                N_("Include only needed archive contents"),
447                NULL, TWO_DASHES,
448                &Position_dependent_options::clear_whole_archive),
449
450   GENERAL_ARG('z', NULL,
451               N_("Subcommands as follows:\n\
452     -z execstack              Mark output as requiring executable stack\n\
453     -z noexecstack            Mark output as not requiring executable stack"),
454               N_("-z SUBCOMMAND"), ONE_DASH,
455               &General_options::handle_z_option),
456
457   SPECIAL('(', "start-group", N_("Start a library search group"), NULL,
458           TWO_DASHES, &start_group),
459   SPECIAL(')', "end-group", N_("End a library search group"), NULL,
460           TWO_DASHES, &end_group),
461   SPECIAL('\0', "help", N_("Report usage information"), NULL,
462           TWO_DASHES, &help),
463   SPECIAL('v', "version", N_("Report version information"), NULL,
464           TWO_DASHES, &version)
465 };
466
467 const int options::Command_line_options::options_size =
468   sizeof (options) / sizeof (options[0]);
469
470 // The -z options.
471
472 const options::One_z_option
473 options::Command_line_options::z_options[] =
474 {
475   { "execstack", &General_options::set_execstack },
476   { "noexecstack", &General_options::set_noexecstack },
477 };
478
479 const int options::Command_line_options::z_options_size =
480   sizeof(z_options) / sizeof(z_options[0]);
481
482 // The default values for the general options.
483
484 General_options::General_options()
485   : export_dynamic_(false),
486     dynamic_linker_(NULL),
487     search_path_(),
488     optimization_level_(0),
489     output_file_name_("a.out"),
490     is_relocatable_(false),
491     strip_(STRIP_NONE),
492     allow_shlib_undefined_(false),
493     symbolic_(false),
494     detect_odr_violations_(false),
495     create_eh_frame_hdr_(false),
496     rpath_(),
497     rpath_link_(),
498     is_shared_(false),
499     is_static_(false),
500     print_stats_(false),
501     sysroot_(),
502     text_segment_address_(-1U),   // -1 indicates value not set by user
503     threads_(false),
504     thread_count_initial_(0),
505     thread_count_middle_(0),
506     thread_count_final_(0),
507     execstack_(EXECSTACK_FROM_INPUT)
508 {
509   // We initialize demangle_ based on the environment variable
510   // COLLECT_NO_DEMANGLE.  The gcc collect2 program will demangle the
511   // output of the linker, unless COLLECT_NO_DEMANGLE is set in the
512   // environment.  Acting the same way here lets us provide the same
513   // interface by default.
514   this->demangle_ = getenv("COLLECT_NO_DEMANGLE") == NULL;
515 }
516
517 // The default values for the position dependent options.
518
519 Position_dependent_options::Position_dependent_options()
520   : do_static_search_(false),
521     as_needed_(false),
522     include_whole_archive_(false)
523 {
524 }
525
526 // Handle the -z option.
527
528 void
529 General_options::handle_z_option(const char* arg)
530 {
531   const int z_options_size = options::Command_line_options::z_options_size;
532   const gold::options::One_z_option* z_options =
533     gold::options::Command_line_options::z_options;
534   for (int i = 0; i < z_options_size; ++i)
535     {
536       if (strcmp(arg, z_options[i].name) == 0)
537         {
538           (this->*(z_options[i].set))();
539           return;
540         }
541     }
542
543   fprintf(stderr, _("%s: unrecognized -z subcommand: %s\n"),
544           program_name, arg);
545   ::exit(1);
546 }
547
548 // Add the sysroot, if any, to the search paths.
549
550 void
551 General_options::add_sysroot()
552 {
553   if (this->sysroot_.empty())
554     {
555       this->sysroot_ = get_default_sysroot();
556       if (this->sysroot_.empty())
557         return;
558     }
559
560   const char* sysroot = this->sysroot_.c_str();
561   char* canonical_sysroot = lrealpath(sysroot);
562
563   for (Dir_list::iterator p = this->search_path_.begin();
564        p != this->search_path_.end();
565        ++p)
566     p->add_sysroot(sysroot, canonical_sysroot);
567
568   free(canonical_sysroot);
569 }
570
571 // Search_directory methods.
572
573 // This is called if we have a sysroot.  Apply the sysroot if
574 // appropriate.  Record whether the directory is in the sysroot.
575
576 void
577 Search_directory::add_sysroot(const char* sysroot,
578                               const char* canonical_sysroot)
579 {
580   gold_assert(*sysroot != '\0');
581   if (this->put_in_sysroot_)
582     {
583       if (!IS_DIR_SEPARATOR(this->name_[0])
584           && !IS_DIR_SEPARATOR(sysroot[strlen(sysroot) - 1]))
585         this->name_ = '/' + this->name_;
586       this->name_ = sysroot + this->name_;
587       this->is_in_sysroot_ = true;
588     }
589   else
590     {
591       // Check whether this entry is in the sysroot.  To do this
592       // correctly, we need to use canonical names.  Otherwise we will
593       // get confused by the ../../.. paths that gcc tends to use.
594       char* canonical_name = lrealpath(this->name_.c_str());
595       int canonical_name_len = strlen(canonical_name);
596       int canonical_sysroot_len = strlen(canonical_sysroot);
597       if (canonical_name_len > canonical_sysroot_len
598           && IS_DIR_SEPARATOR(canonical_name[canonical_sysroot_len]))
599         {
600           canonical_name[canonical_sysroot_len] = '\0';
601           if (FILENAME_CMP(canonical_name, canonical_sysroot) == 0)
602             this->is_in_sysroot_ = true;
603         }
604       free(canonical_name);
605     }
606 }
607
608 // Input_arguments methods.
609
610 // Add a file to the list.
611
612 void
613 Input_arguments::add_file(const Input_file_argument& file)
614 {
615   if (!this->in_group_)
616     this->input_argument_list_.push_back(Input_argument(file));
617   else
618     {
619       gold_assert(!this->input_argument_list_.empty());
620       gold_assert(this->input_argument_list_.back().is_group());
621       this->input_argument_list_.back().group()->add_file(file);
622     }
623 }
624
625 // Start a group.
626
627 void
628 Input_arguments::start_group()
629 {
630   gold_assert(!this->in_group_);
631   Input_file_group* group = new Input_file_group();
632   this->input_argument_list_.push_back(Input_argument(group));
633   this->in_group_ = true;
634 }
635
636 // End a group.
637
638 void
639 Input_arguments::end_group()
640 {
641   gold_assert(this->in_group_);
642   this->in_group_ = false;
643 }
644
645 // Command_line options.
646
647 Command_line::Command_line()
648   : options_(), position_options_(), inputs_()
649 {
650 }
651
652 // Process the command line options.  For process_one_option,
653 // i is the index of argv to process next, and the return value
654 // is the index of the next option to process (i+1 or i+2, or argc
655 // to indicate processing is done).  no_more_options is set to true
656 // if (and when) "--" is seen as an option.
657
658 int
659 Command_line::process_one_option(int argc, char** argv, int i,
660                                  bool* no_more_options)
661 {
662   const int options_size = options::Command_line_options::options_size;
663   const options::One_option* options = options::Command_line_options::options;
664   gold_assert(i < argc);
665
666   if (argv[i][0] != '-' || *no_more_options)
667     {
668       this->add_file(argv[i], false);
669       return i + 1;
670     }
671
672   // Option starting with '-'.
673   int dashes = 1;
674   if (argv[i][1] == '-')
675     {
676       dashes = 2;
677       if (argv[i][2] == '\0')
678         {
679           *no_more_options = true;
680           return i + 1;
681         }
682     }
683
684   // Look for a long option match.
685   char* opt = argv[i] + dashes;
686   char first = opt[0];
687   int skiparg = 0;
688   char* arg = strchr(opt, '=');
689   bool argument_with_equals = arg != NULL;
690   if (arg != NULL)
691     {
692       *arg = '\0';
693       ++arg;
694     }
695   else if (i + 1 < argc)
696     {
697       arg = argv[i + 1];
698       skiparg = 1;
699     }
700
701   int j;
702   for (j = 0; j < options_size; ++j)
703     {
704       if (options[j].long_option != NULL
705           && (dashes == 2
706           || (options[j].dash
707               != options::One_option::EXACTLY_TWO_DASHES))
708           && first == options[j].long_option[0]
709           && strcmp(opt, options[j].long_option) == 0)
710         {
711           if (options[j].special)
712             {
713               // Restore the '=' we clobbered above.
714               if (arg != NULL && skiparg == 0)
715                 arg[-1] = '=';
716               i += options[j].special(argc - i, argv + i, opt, true, this);
717             }
718           else
719             {
720               if (!options[j].takes_argument())
721                 {
722                   if (argument_with_equals)
723                     this->usage(_("unexpected argument"), argv[i]);
724                   arg = NULL;
725                   skiparg = 0;
726                 }
727               else
728                 {
729                   if (arg == NULL)
730                     this->usage(_("missing argument"), argv[i]);
731                 }
732               this->apply_option(options[j], arg);
733               i += skiparg + 1;
734             }
735           break;
736         }
737     }
738   if (j < options_size)
739     return i;
740
741   // If we saw two dashes, we needed to have seen a long option.
742   if (dashes == 2)
743     this->usage(_("unknown option"), argv[i]);
744
745   // Look for a short option match.  There may be more than one
746   // short option in a given argument.
747   bool done = false;
748   char* s = argv[i] + 1;
749   ++i;
750   while (*s != '\0' && !done)
751     {
752       char opt = *s;
753       int j;
754       for (j = 0; j < options_size; ++j)
755         {
756           if (options[j].short_option == opt)
757             {
758               if (options[j].special)
759                 {
760                   // Undo the argument skip done above.
761                   --i;
762                   i += options[j].special(argc - i, argv + i, s, false,
763                                           this);
764                   done = true;
765                 }
766               else
767                 {
768                   arg = NULL;
769                   if (options[j].takes_argument())
770                     {
771                       if (s[1] != '\0')
772                         {
773                           arg = s + 1;
774                           done = true;
775                         }
776                       else if (i < argc)
777                         {
778                           arg = argv[i];
779                           ++i;
780                         }
781                       else
782                         this->usage(_("missing argument"), opt);
783                     }
784                   this->apply_option(options[j], arg);
785                 }
786               break;
787             }
788         }
789
790       if (j >= options_size)
791         this->usage(_("unknown option"), *s);
792
793       ++s;
794     }
795   return i;
796 }
797
798
799 void
800 Command_line::process(int argc, char** argv)
801 {
802   bool no_more_options = false;
803   int i = 0;
804   while (i < argc)
805     i = process_one_option(argc, argv, i, &no_more_options);
806
807   if (this->inputs_.in_group())
808     {
809       fprintf(stderr, _("%s: missing group end\n"), program_name);
810       this->usage();
811     }
812
813   // FIXME: We should only do this when configured in native mode.
814   this->options_.add_to_search_path_with_sysroot("/lib");
815   this->options_.add_to_search_path_with_sysroot("/usr/lib");
816
817   this->options_.add_sysroot();
818
819   // Ensure options don't contradict each other and are otherwise kosher.
820   this->normalize_options();
821 }
822
823 // Extract an option argument for a special option.  LONGNAME is the
824 // long name of the option.  This sets *PRET to the return value for
825 // the special function handler to skip to the next option.
826
827 const char*
828 Command_line::get_special_argument(const char* longname, int argc, char** argv,
829                                    const char* arg, bool long_option,
830                                    int *pret)
831 {
832   if (long_option)
833     {
834       size_t longlen = strlen(longname);
835       gold_assert(strncmp(arg, longname, longlen) == 0);
836       arg += longlen;
837       if (*arg == '=')
838         {
839           *pret = 1;
840           return arg + 1;
841         }
842       else if (argc > 1)
843         {
844           gold_assert(*arg == '\0');
845           *pret = 2;
846           return argv[1];
847         }
848     }
849   else
850     {
851       if (arg[1] != '\0')
852         {
853           *pret = 1;
854           return arg + 1;
855         }
856       else if (argc > 1)
857         {
858           *pret = 2;
859           return argv[1];
860         }
861     }
862
863   this->usage(_("missing argument"), arg);
864 }
865
866 // Ensure options don't contradict each other and are otherwise kosher.
867
868 void
869 Command_line::normalize_options()
870 {
871   // If the user specifies both -s and -r, convert the -s as -S.
872   // -r requires us to keep externally visible symbols!
873   if (this->options_.strip_all() && this->options_.is_relocatable())
874     {
875       // Clears the strip_all() status, replacing it with strip_debug().
876       this->options_.set_strip_debug();
877     }
878
879   // FIXME: we can/should be doing a lot more sanity checking here.
880 }
881
882
883 // Apply a command line option.
884
885 void
886 Command_line::apply_option(const options::One_option& opt,
887                            const char* arg)
888 {
889   if (arg == NULL)
890     {
891       if (opt.general_noarg)
892         (this->options_.*(opt.general_noarg))();
893       else if (opt.dependent_noarg)
894         (this->position_options_.*(opt.dependent_noarg))();
895       else
896         gold_unreachable();
897     }
898   else
899     {
900       if (opt.general_arg)
901         (this->options_.*(opt.general_arg))(arg);
902       else if (opt.dependent_arg)
903         (this->position_options_.*(opt.dependent_arg))(arg);
904       else
905         gold_unreachable();
906     }
907 }
908
909 // Add an input file or library.
910
911 void
912 Command_line::add_file(const char* name, bool is_lib)
913 {
914   Input_file_argument file(name, is_lib, "", this->position_options_);
915   this->inputs_.add_file(file);
916 }
917
918 // Handle the -l option, which requires special treatment.
919
920 int
921 Command_line::process_l_option(int argc, char** argv, char* arg,
922                                bool long_option)
923 {
924   int ret;
925   const char* libname = this->get_special_argument("library", argc, argv, arg,
926                                                    long_option, &ret);
927   this->add_file(libname, true);
928   return ret;
929 }
930
931 // Handle the --start-group option.
932
933 void
934 Command_line::start_group(const char* arg)
935 {
936   if (this->inputs_.in_group())
937     this->usage(_("may not nest groups"), arg);
938   this->inputs_.start_group();
939 }
940
941 // Handle the --end-group option.
942
943 void
944 Command_line::end_group(const char* arg)
945 {
946   if (!this->inputs_.in_group())
947     this->usage(_("group end without group start"), arg);
948   this->inputs_.end_group();
949 }
950
951 // Report a usage error.  */
952
953 void
954 Command_line::usage()
955 {
956   fprintf(stderr,
957           _("%s: use the --help option for usage information\n"),
958           program_name);
959   ::exit(1);
960 }
961
962 void
963 Command_line::usage(const char* msg, const char *opt)
964 {
965   fprintf(stderr,
966           _("%s: %s: %s\n"),
967           program_name, opt, msg);
968   this->usage();
969 }
970
971 void
972 Command_line::usage(const char* msg, char opt)
973 {
974   fprintf(stderr,
975           _("%s: -%c: %s\n"),
976           program_name, opt, msg);
977   this->usage();
978 }
979
980 } // End namespace gold.