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