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