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