From Craig Silverstein: rework handling of Script_options.
[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('r', "relocatable", N_("Generate relocatable output"), NULL,
534                 ONE_DASH, &General_options::set_relocatable),
535   // -R really means -rpath, but can mean --just-symbols for
536   // compatibility with GNU ld.  -rpath is always -rpath, so we list
537   // it separately.
538   SPECIAL('R', NULL, N_("Add DIR to runtime search path"),
539           N_("-R DIR"), ONE_DASH, &handle_r_option),
540   GENERAL_ARG('\0', "rpath", NULL, N_("-rpath DIR"), ONE_DASH,
541               &General_options::add_to_rpath),
542   SPECIAL('\0', "just-symbols", N_("Read only symbol values from file"),
543           N_("-R FILE, --just-symbols FILE"), TWO_DASHES,
544           &handle_just_symbols_option),
545   GENERAL_ARG('\0', "rpath-link",
546               N_("Add DIR to link time shared library search path"),
547               N_("--rpath-link DIR"), TWO_DASHES,
548               &General_options::add_to_rpath_link),
549   GENERAL_NOARG('s', "strip-all", N_("Strip all symbols"), NULL,
550                 TWO_DASHES, &General_options::set_strip_all),
551   GENERAL_NOARG('\0', "strip-debug-gdb",
552                 N_("Strip debug symbols that are unused by gdb "
553                    "(at least versions <= 6.7)"),
554                 NULL, TWO_DASHES, &General_options::set_strip_debug_gdb),
555   // This must come after -Sdebug since it's a prefix of it.
556   GENERAL_NOARG('S', "strip-debug", N_("Strip debugging information"), NULL,
557                 TWO_DASHES, &General_options::set_strip_debug),
558   GENERAL_NOARG('\0', "shared", N_("Generate shared library"),
559                 NULL, ONE_DASH, &General_options::set_shared),
560   GENERAL_NOARG('\0', "static", N_("Do not link against shared libraries"),
561                 NULL, ONE_DASH, &General_options::set_static),
562   GENERAL_NOARG('\0', "stats", N_("Print resource usage statistics"),
563                 NULL, TWO_DASHES, &General_options::set_stats),
564   GENERAL_ARG('\0', "sysroot", N_("Set target system root directory"),
565               N_("--sysroot DIR"), TWO_DASHES, &General_options::set_sysroot),
566   GENERAL_ARG('\0', "Tbss", N_("Set the address of the bss segment"),
567               N_("-Tbss ADDRESS"), ONE_DASH,
568               &General_options::set_Tbss),
569   GENERAL_ARG('\0', "Tdata", N_("Set the address of the data segment"),
570               N_("-Tdata ADDRESS"), ONE_DASH,
571               &General_options::set_Tdata),
572   GENERAL_ARG('\0', "Ttext", N_("Set the address of the text segment"),
573               N_("-Ttext ADDRESS"), ONE_DASH,
574               &General_options::set_Ttext),
575   // This must come after -Ttext and friends since it's a prefix of
576   // them.
577   SPECIAL('T', "script", N_("Read linker script"),
578           N_("-T FILE, --script FILE"), TWO_DASHES,
579           &invoke_script),
580   SPECIAL('\0', "version-script", N_("Read version script"),
581           N_("--version-script FILE"), TWO_DASHES,
582           &invoke_version_script),
583   GENERAL_NOARG('\0', "threads", N_("Run the linker multi-threaded"),
584                 NULL, TWO_DASHES, &General_options::set_threads),
585   GENERAL_NOARG('\0', "no-threads", N_("Do not run the linker multi-threaded"),
586                 NULL, TWO_DASHES, &General_options::set_no_threads),
587   GENERAL_ARG('\0', "thread-count", N_("Number of threads to use"),
588               N_("--thread-count COUNT"), TWO_DASHES,
589               &General_options::set_thread_count),
590   GENERAL_ARG('\0', "thread-count-initial",
591               N_("Number of threads to use in initial pass"),
592               N_("--thread-count-initial COUNT"), TWO_DASHES,
593               &General_options::set_thread_count_initial),
594   GENERAL_ARG('\0', "thread-count-middle",
595               N_("Number of threads to use in middle pass"),
596               N_("--thread-count-middle COUNT"), TWO_DASHES,
597               &General_options::set_thread_count_middle),
598   GENERAL_ARG('\0', "thread-count-final",
599               N_("Number of threads to use in final pass"),
600               N_("--thread-count-final COUNT"), TWO_DASHES,
601               &General_options::set_thread_count_final),
602   POSDEP_NOARG('\0', "whole-archive",
603                N_("Include all archive contents"),
604                NULL, TWO_DASHES,
605                &Position_dependent_options::set_whole_archive),
606   POSDEP_NOARG('\0', "no-whole-archive",
607                N_("Include only needed archive contents"),
608                NULL, TWO_DASHES,
609                &Position_dependent_options::set_no_whole_archive),
610
611   GENERAL_ARG('z', NULL,
612               N_("Subcommands as follows:\n\
613     -z execstack              Mark output as requiring executable stack\n\
614     -z noexecstack            Mark output as not requiring executable stack\n\
615     -z max-page-size=SIZE     Set maximum page size to SIZE\n\
616     -z common-page-size=SIZE  Set common page size to SIZE"),
617               N_("-z SUBCOMMAND"), ONE_DASH,
618               &General_options::handle_z_option),
619
620   SPECIAL('(', "start-group", N_("Start a library search group"), NULL,
621           TWO_DASHES, &start_group),
622   SPECIAL(')', "end-group", N_("End a library search group"), NULL,
623           TWO_DASHES, &end_group),
624   SPECIAL('\0', "help", N_("Report usage information"), NULL,
625           TWO_DASHES, &help),
626   SPECIAL('v', "version", N_("Report version information"), NULL,
627           TWO_DASHES, &version),
628   GENERAL_ARG('\0', "debug", N_("Turn on debugging (all,task,script)"),
629               N_("--debug=TYPE"), TWO_DASHES,
630               &General_options::handle_debug_option)
631 };
632
633 const int options::Command_line_options::options_size =
634   sizeof (options) / sizeof (options[0]);
635
636 // The -z options.
637
638 const options::One_z_option
639 options::Command_line_options::z_options[] =
640 {
641   { "execstack", &General_options::set_execstack, NULL },
642   { "noexecstack", &General_options::set_noexecstack, NULL },
643   { "max-page-size", NULL, &General_options::set_max_page_size },
644   { "common-page-size", NULL, &General_options::set_common_page_size }
645 };
646
647 const int options::Command_line_options::z_options_size =
648   sizeof(z_options) / sizeof(z_options[0]);
649
650 // The --debug options.
651
652 const options::One_debug_option
653 options::Command_line_options::debug_options[] =
654 {
655   { "all", DEBUG_ALL },
656   { "task", DEBUG_TASK },
657   { "script", DEBUG_SCRIPT }
658 };
659
660 const int options::Command_line_options::debug_options_size =
661   sizeof(debug_options) / sizeof(debug_options[0]);
662
663 // The default values for the general options.
664
665 General_options::General_options()
666   : entry_(NULL),
667     export_dynamic_(false),
668     soname_(NULL),
669     dynamic_linker_(NULL),
670     search_path_(),
671     optimization_level_(0),
672     output_file_name_("a.out"),
673     oformat_(OBJECT_FORMAT_ELF),
674     oformat_string_(NULL),
675     is_relocatable_(false),
676     strip_(STRIP_NONE),
677     allow_shlib_undefined_(false),
678     symbolic_(false),
679     compress_debug_sections_(NO_COMPRESSION),
680     detect_odr_violations_(false),
681     create_eh_frame_hdr_(false),
682     rpath_(),
683     rpath_link_(),
684     is_shared_(false),
685     is_static_(false),
686     print_stats_(false),
687     sysroot_(),
688     bss_segment_address_(-1U),   // -1 indicates value not set by user
689     data_segment_address_(-1U),
690     text_segment_address_(-1U),
691     threads_(false),
692     thread_count_initial_(0),
693     thread_count_middle_(0),
694     thread_count_final_(0),
695     execstack_(EXECSTACK_FROM_INPUT),
696     max_page_size_(0),
697     common_page_size_(0),
698     debug_(0)
699 {
700   // We initialize demangle_ based on the environment variable
701   // COLLECT_NO_DEMANGLE.  The gcc collect2 program will demangle the
702   // output of the linker, unless COLLECT_NO_DEMANGLE is set in the
703   // environment.  Acting the same way here lets us provide the same
704   // interface by default.
705   this->demangle_ = getenv("COLLECT_NO_DEMANGLE") == NULL;
706 }
707
708 // Handle the --oformat option.
709
710 void
711 General_options::set_oformat(const char* arg)
712 {
713   this->oformat_string_ = arg;
714   this->oformat_ = string_to_object_format(arg);
715 }
716
717 // The x86_64 kernel build converts a binary file to an object file
718 // using -r --format binary --oformat elf32-i386 foo.o.  In order to
719 // support that for gold we support determining the default target
720 // choice from the output format.  We recognize names that the GNU
721 // linker uses.
722
723 Target*
724 General_options::default_target() const
725 {
726   if (this->oformat_string_ != NULL)
727     {
728       Target* target = select_target_by_name(this->oformat_string_);
729       if (target != NULL)
730         return target;
731
732       gold_error(_("unrecognized output format %s"),
733                  this->oformat_string_);
734     }
735
736   // The GOLD_DEFAULT_xx macros are defined by the configure script.
737   Target* target = select_target(elfcpp::GOLD_DEFAULT_MACHINE,
738                                  GOLD_DEFAULT_SIZE,
739                                  GOLD_DEFAULT_BIG_ENDIAN,
740                                  0, 0);
741   gold_assert(target != NULL);
742   return target;
743 }
744
745 // Handle the -z option.
746
747 void
748 General_options::handle_z_option(const char* arg)
749 {
750   // ARG may be a word, like "noexec", or it may be an option in its
751   // own right, like "max-page-size=SIZE".
752   const char* argarg = strchr(arg, '=');   // the argument to the -z argument
753   int arglen;
754   if (argarg)
755     {
756       arglen = argarg - arg;
757       argarg++;
758     }
759   else
760     arglen = strlen(arg);
761
762   const int z_options_size = options::Command_line_options::z_options_size;
763   const gold::options::One_z_option* z_options =
764     gold::options::Command_line_options::z_options;
765   for (int i = 0; i < z_options_size; ++i)
766     {
767       if (memcmp(arg, z_options[i].name, arglen) == 0
768           && z_options[i].name[arglen] == '\0')
769         {
770           if (z_options[i].set_noarg && argarg)
771             gold::gold_fatal(_("-z subcommand does not take an argument: %s\n"),
772                              z_options[i].name);
773           else if (z_options[i].set_arg && !argarg)
774             gold::gold_fatal(_("-z subcommand requires an argument: %s\n"),
775                              z_options[i].name);
776           else if (z_options[i].set_arg)
777             (this->*(z_options[i].set_arg))(argarg);
778           else
779             (this->*(z_options[i].set_noarg))(true);
780           return;
781         }
782     }
783
784   gold::gold_fatal(_("%s: unrecognized -z subcommand: %s\n"),
785                    program_name, arg);
786 }
787
788 // Handle the --debug option.
789
790 void
791 General_options::handle_debug_option(const char* arg)
792 {
793   const int debug_options_size =
794     options::Command_line_options::debug_options_size;
795   const gold::options::One_debug_option* debug_options =
796     options::Command_line_options::debug_options;
797   for (int i = 0; i < debug_options_size; ++i)
798     {
799       if (strcmp(arg, debug_options[i].name) == 0)
800         {
801           this->set_debug(debug_options[i].debug_flags);
802           return;
803         }
804     }
805
806   fprintf(stderr, _("%s: unrecognized --debug subcommand: %s\n"),
807           program_name, arg);
808   ::exit(EXIT_FAILURE);
809 }
810
811 // Add the sysroot, if any, to the search paths.
812
813 void
814 General_options::add_sysroot()
815 {
816   if (this->sysroot_.empty())
817     {
818       this->sysroot_ = get_default_sysroot();
819       if (this->sysroot_.empty())
820         return;
821     }
822
823   const char* sysroot = this->sysroot_.c_str();
824   char* canonical_sysroot = lrealpath(sysroot);
825
826   for (Dir_list::iterator p = this->search_path_.begin();
827        p != this->search_path_.end();
828        ++p)
829     p->add_sysroot(sysroot, canonical_sysroot);
830
831   free(canonical_sysroot);
832 }
833
834 // The default values for the position dependent options.
835
836 Position_dependent_options::Position_dependent_options()
837   : do_static_search_(false),
838     as_needed_(false),
839     include_whole_archive_(false),
840     input_format_(General_options::OBJECT_FORMAT_ELF)
841 {
842 }
843
844 // Set the input format.
845
846 void
847 Position_dependent_options::set_format(const char* arg)
848 {
849   this->input_format_ = string_to_object_format(arg);
850 }
851
852 // Search_directory methods.
853
854 // This is called if we have a sysroot.  Apply the sysroot if
855 // appropriate.  Record whether the directory is in the sysroot.
856
857 void
858 Search_directory::add_sysroot(const char* sysroot,
859                               const char* canonical_sysroot)
860 {
861   gold_assert(*sysroot != '\0');
862   if (this->put_in_sysroot_)
863     {
864       if (!IS_DIR_SEPARATOR(this->name_[0])
865           && !IS_DIR_SEPARATOR(sysroot[strlen(sysroot) - 1]))
866         this->name_ = '/' + this->name_;
867       this->name_ = sysroot + this->name_;
868       this->is_in_sysroot_ = true;
869     }
870   else
871     {
872       // Check whether this entry is in the sysroot.  To do this
873       // correctly, we need to use canonical names.  Otherwise we will
874       // get confused by the ../../.. paths that gcc tends to use.
875       char* canonical_name = lrealpath(this->name_.c_str());
876       int canonical_name_len = strlen(canonical_name);
877       int canonical_sysroot_len = strlen(canonical_sysroot);
878       if (canonical_name_len > canonical_sysroot_len
879           && IS_DIR_SEPARATOR(canonical_name[canonical_sysroot_len]))
880         {
881           canonical_name[canonical_sysroot_len] = '\0';
882           if (FILENAME_CMP(canonical_name, canonical_sysroot) == 0)
883             this->is_in_sysroot_ = true;
884         }
885       free(canonical_name);
886     }
887 }
888
889 // Input_arguments methods.
890
891 // Add a file to the list.
892
893 void
894 Input_arguments::add_file(const Input_file_argument& file)
895 {
896   if (!this->in_group_)
897     this->input_argument_list_.push_back(Input_argument(file));
898   else
899     {
900       gold_assert(!this->input_argument_list_.empty());
901       gold_assert(this->input_argument_list_.back().is_group());
902       this->input_argument_list_.back().group()->add_file(file);
903     }
904 }
905
906 // Start a group.
907
908 void
909 Input_arguments::start_group()
910 {
911   gold_assert(!this->in_group_);
912   Input_file_group* group = new Input_file_group();
913   this->input_argument_list_.push_back(Input_argument(group));
914   this->in_group_ = true;
915 }
916
917 // End a group.
918
919 void
920 Input_arguments::end_group()
921 {
922   gold_assert(this->in_group_);
923   this->in_group_ = false;
924 }
925
926 // Command_line options.
927
928 Command_line::Command_line()
929   : options_(), position_options_(), script_options_(), inputs_()
930 {
931 }
932
933 // Process the command line options.  For process_one_option,
934 // i is the index of argv to process next, and the return value
935 // is the index of the next option to process (i+1 or i+2, or argc
936 // to indicate processing is done).  no_more_options is set to true
937 // if (and when) "--" is seen as an option.
938
939 int
940 Command_line::process_one_option(int argc, char** argv, int i,
941                                  bool* no_more_options)
942 {
943   const int options_size = options::Command_line_options::options_size;
944   const options::One_option* options = options::Command_line_options::options;
945   gold_assert(i < argc);
946
947   if (argv[i][0] != '-' || *no_more_options)
948     {
949       this->add_file(argv[i], false);
950       return i + 1;
951     }
952
953   // Option starting with '-'.
954   int dashes = 1;
955   if (argv[i][1] == '-')
956     {
957       dashes = 2;
958       if (argv[i][2] == '\0')
959         {
960           *no_more_options = true;
961           return i + 1;
962         }
963     }
964
965   // Look for a long option match.
966   char* opt = argv[i] + dashes;
967   char first = opt[0];
968   int skiparg = 0;
969   char* arg = strchr(opt, '=');
970   bool argument_with_equals = arg != NULL;
971   if (arg != NULL)
972     {
973       *arg = '\0';
974       ++arg;
975     }
976   else if (i + 1 < argc)
977     {
978       arg = argv[i + 1];
979       skiparg = 1;
980     }
981
982   int j;
983   for (j = 0; j < options_size; ++j)
984     {
985       if (options[j].long_option != NULL
986           && (dashes == 2
987               || (options[j].dash
988                   != options::One_option::EXACTLY_TWO_DASHES))
989           && first == options[j].long_option[0]
990           && strcmp(opt, options[j].long_option) == 0)
991         {
992           if (options[j].special)
993             {
994               // Restore the '=' we clobbered above.
995               if (arg != NULL && skiparg == 0)
996                 arg[-1] = '=';
997               i += options[j].special(argc - i, argv + i, opt, true, this);
998             }
999           else
1000             {
1001               if (!options[j].takes_argument())
1002                 {
1003                   if (argument_with_equals)
1004                     this->usage(_("unexpected argument"), argv[i]);
1005                   arg = NULL;
1006                   skiparg = 0;
1007                 }
1008               else
1009                 {
1010                   if (arg == NULL)
1011                     this->usage(_("missing argument"), argv[i]);
1012                 }
1013               this->apply_option(options[j], arg);
1014               i += skiparg + 1;
1015             }
1016           break;
1017         }
1018     }
1019   if (j < options_size)
1020     return i;
1021
1022   // If we saw two dashes, we needed to have seen a long option.
1023   if (dashes == 2)
1024     this->usage(_("unknown option"), argv[i]);
1025
1026   // Look for a short option match.  There may be more than one
1027   // short option in a given argument.
1028   bool done = false;
1029   char* s = argv[i] + 1;
1030   ++i;
1031   while (*s != '\0' && !done)
1032     {
1033       char opt = *s;
1034       int j;
1035       for (j = 0; j < options_size; ++j)
1036         {
1037           if (options[j].short_option == opt)
1038             {
1039               if (options[j].special)
1040                 {
1041                   // Undo the argument skip done above.
1042                   --i;
1043                   i += options[j].special(argc - i, argv + i, s, false,
1044                                           this);
1045                   done = true;
1046                 }
1047               else
1048                 {
1049                   arg = NULL;
1050                   if (options[j].takes_argument())
1051                     {
1052                       if (s[1] != '\0')
1053                         {
1054                           arg = s + 1;
1055                           done = true;
1056                         }
1057                       else if (i < argc)
1058                         {
1059                           arg = argv[i];
1060                           ++i;
1061                         }
1062                       else
1063                         this->usage(_("missing argument"), opt);
1064                     }
1065                   this->apply_option(options[j], arg);
1066                 }
1067               break;
1068             }
1069         }
1070
1071       if (j >= options_size)
1072         this->usage(_("unknown option"), *s);
1073
1074       ++s;
1075     }
1076   return i;
1077 }
1078
1079
1080 void
1081 Command_line::process(int argc, char** argv)
1082 {
1083   bool no_more_options = false;
1084   int i = 0;
1085   while (i < argc)
1086     i = process_one_option(argc, argv, i, &no_more_options);
1087
1088   if (this->inputs_.in_group())
1089     {
1090       fprintf(stderr, _("%s: missing group end\n"), program_name);
1091       this->usage();
1092     }
1093
1094   // FIXME: We should only do this when configured in native mode.
1095   this->options_.add_to_search_path_with_sysroot("/lib");
1096   this->options_.add_to_search_path_with_sysroot("/usr/lib");
1097
1098   this->options_.add_sysroot();
1099
1100   // Ensure options don't contradict each other and are otherwise kosher.
1101   this->normalize_options();
1102 }
1103
1104 // Extract an option argument for a special option.  LONGNAME is the
1105 // long name of the option.  This sets *PRET to the return value for
1106 // the special function handler to skip to the next option.
1107
1108 const char*
1109 Command_line::get_special_argument(const char* longname, int argc, char** argv,
1110                                    const char* arg, bool long_option,
1111                                    int *pret)
1112 {
1113   if (long_option)
1114     {
1115       size_t longlen = strlen(longname);
1116       gold_assert(strncmp(arg, longname, longlen) == 0);
1117       arg += longlen;
1118       if (*arg == '=')
1119         {
1120           *pret = 1;
1121           return arg + 1;
1122         }
1123       else if (argc > 1)
1124         {
1125           gold_assert(*arg == '\0');
1126           *pret = 2;
1127           return argv[1];
1128         }
1129     }
1130   else
1131     {
1132       if (arg[1] != '\0')
1133         {
1134           *pret = 1;
1135           return arg + 1;
1136         }
1137       else if (argc > 1)
1138         {
1139           *pret = 2;
1140           return argv[1];
1141         }
1142     }
1143
1144   this->usage(_("missing argument"), arg);
1145 }
1146
1147 // Ensure options don't contradict each other and are otherwise kosher.
1148
1149 void
1150 Command_line::normalize_options()
1151 {
1152   if (this->options_.shared() && this->options_.relocatable())
1153     gold_fatal(_("-shared and -r are incompatible"));
1154
1155   if (this->options_.oformat() != General_options::OBJECT_FORMAT_ELF
1156       && (this->options_.shared() || this->options_.relocatable()))
1157     gold_fatal(_("binary output format not compatible with -shared or -r"));
1158
1159   // If the user specifies both -s and -r, convert the -s as -S.
1160   // -r requires us to keep externally visible symbols!
1161   if (this->options_.strip_all() && this->options_.relocatable())
1162     {
1163       // Clears the strip_all() status, replacing it with strip_debug().
1164       this->options_.set_strip_debug(true);
1165     }
1166
1167   // FIXME: we can/should be doing a lot more sanity checking here.
1168 }
1169
1170
1171 // Apply a command line option.
1172
1173 void
1174 Command_line::apply_option(const options::One_option& opt,
1175                            const char* arg)
1176 {
1177   if (arg == NULL)
1178     {
1179       if (opt.general_noarg)
1180         (this->options_.*(opt.general_noarg))(true);
1181       else if (opt.dependent_noarg)
1182         (this->position_options_.*(opt.dependent_noarg))(true);
1183       else
1184         gold_unreachable();
1185     }
1186   else
1187     {
1188       if (opt.general_arg)
1189         (this->options_.*(opt.general_arg))(arg);
1190       else if (opt.dependent_arg)
1191         (this->position_options_.*(opt.dependent_arg))(arg);
1192       else
1193         gold_unreachable();
1194     }
1195 }
1196
1197 // Add an input file or library.
1198
1199 void
1200 Command_line::add_file(const char* name, bool is_lib)
1201 {
1202   Input_file_argument file(name, is_lib, "", false, this->position_options_);
1203   this->inputs_.add_file(file);
1204 }
1205
1206 // Handle the -l option, which requires special treatment.
1207
1208 int
1209 Command_line::process_l_option(int argc, char** argv, char* arg,
1210                                bool long_option)
1211 {
1212   int ret;
1213   const char* libname = this->get_special_argument("library", argc, argv, arg,
1214                                                    long_option, &ret);
1215   this->add_file(libname, true);
1216   return ret;
1217 }
1218
1219 // Handle the --start-group option.
1220
1221 void
1222 Command_line::start_group(const char* arg)
1223 {
1224   if (this->inputs_.in_group())
1225     this->usage(_("may not nest groups"), arg);
1226   this->inputs_.start_group();
1227 }
1228
1229 // Handle the --end-group option.
1230
1231 void
1232 Command_line::end_group(const char* arg)
1233 {
1234   if (!this->inputs_.in_group())
1235     this->usage(_("group end without group start"), arg);
1236   this->inputs_.end_group();
1237 }
1238
1239 // Report a usage error.  */
1240
1241 void
1242 Command_line::usage()
1243 {
1244   fprintf(stderr,
1245           _("%s: use the --help option for usage information\n"),
1246           program_name);
1247   ::exit(EXIT_FAILURE);
1248 }
1249
1250 void
1251 Command_line::usage(const char* msg, const char *opt)
1252 {
1253   fprintf(stderr,
1254           _("%s: %s: %s\n"),
1255           program_name, opt, msg);
1256   this->usage();
1257 }
1258
1259 void
1260 Command_line::usage(const char* msg, char opt)
1261 {
1262   fprintf(stderr,
1263           _("%s: -%c: %s\n"),
1264           program_name, opt, msg);
1265   this->usage();
1266 }
1267
1268 } // End namespace gold.