OSDN Git Service

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