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