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