05d6f88dd645d01a5242c31231c69a24cfbaf55b
[external/binutils.git] / gold / options.cc
1 // options.c -- handle command line options for gold
2
3 // Copyright 2006, 2007, 2008, 2009, 2010, 2011 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 <cerrno>
26 #include <cstdlib>
27 #include <cstring>
28 #include <fstream>
29 #include <vector>
30 #include <iostream>
31 #include <sys/stat.h>
32 #include "filenames.h"
33 #include "libiberty.h"
34 #include "demangle.h"
35 #include "../bfd/bfdver.h"
36
37 #include "debug.h"
38 #include "script.h"
39 #include "target-select.h"
40 #include "options.h"
41 #include "plugin.h"
42
43 namespace gold
44 {
45
46 General_options
47 Position_dependent_options::default_options_;
48
49 namespace options
50 {
51
52 // This flag is TRUE if we should register the command-line options as they
53 // are constructed.  It is set after construction of the options within
54 // class Position_dependent_options.
55 static bool ready_to_register = false;
56
57 // This global variable is set up as General_options is constructed.
58 static std::vector<const One_option*> registered_options;
59
60 // These are set up at the same time -- the variables that accept one
61 // dash, two, or require -z.  A single variable may be in more than
62 // one of these data structures.
63 typedef Unordered_map<std::string, One_option*> Option_map;
64 static Option_map* long_options = NULL;
65 static One_option* short_options[128];
66
67 void
68 One_option::register_option()
69 {
70   if (!ready_to_register)
71     return;
72
73   registered_options.push_back(this);
74
75   // We can't make long_options a static Option_map because we can't
76   // guarantee that will be initialized before register_option() is
77   // first called.
78   if (long_options == NULL)
79     long_options = new Option_map;
80
81   // TWO_DASHES means that two dashes are preferred, but one is ok too.
82   if (!this->longname.empty())
83     (*long_options)[this->longname] = this;
84
85   const int shortname_as_int = static_cast<int>(this->shortname);
86   gold_assert(shortname_as_int >= 0 && shortname_as_int < 128);
87   if (this->shortname != '\0')
88     {
89       gold_assert(short_options[shortname_as_int] == NULL);
90       short_options[shortname_as_int] = this;
91     }
92 }
93
94 void
95 One_option::print() const
96 {
97   bool comma = false;
98   printf("  ");
99   int len = 2;
100   if (this->shortname != '\0')
101     {
102       len += printf("-%c", this->shortname);
103       if (this->helparg)
104         {
105           // -z takes long-names only.
106           gold_assert(this->dashes != DASH_Z);
107           len += printf(" %s", gettext(this->helparg));
108         }
109       comma = true;
110     }
111   if (!this->longname.empty()
112       && !(this->longname[0] == this->shortname
113            && this->longname[1] == '\0'))
114     {
115       if (comma)
116         len += printf(", ");
117       switch (this->dashes)
118         {
119         case options::ONE_DASH: case options::EXACTLY_ONE_DASH:
120           len += printf("-");
121           break;
122         case options::TWO_DASHES: case options::EXACTLY_TWO_DASHES:
123           len += printf("--");
124           break;
125         case options::DASH_Z:
126           len += printf("-z ");
127           break;
128         default:
129           gold_unreachable();
130         }
131       len += printf("%s", this->longname.c_str());
132       if (this->helparg)
133         {
134           // For most options, we print "--frob FOO".  But for -z
135           // we print "-z frob=FOO".
136           len += printf("%c%s", this->dashes == options::DASH_Z ? '=' : ' ',
137                         gettext(this->helparg));
138         }
139     }
140
141   if (len >= 30)
142     {
143       printf("\n");
144       len = 0;
145     }
146   for (; len < 30; ++len)
147     std::putchar(' ');
148
149   // TODO: if we're boolean, add " (default)" when appropriate.
150   printf("%s\n", gettext(this->helpstring));
151 }
152
153 void
154 help()
155 {
156   printf(_("Usage: %s [options] file...\nOptions:\n"), gold::program_name);
157
158   std::vector<const One_option*>::const_iterator it;
159   for (it = registered_options.begin(); it != registered_options.end(); ++it)
160     (*it)->print();
161
162   // config.guess and libtool.m4 look in ld --help output for the
163   // string "supported targets".
164   printf(_("%s: supported targets:"), gold::program_name);
165   std::vector<const char*> supported_names;
166   gold::supported_target_names(&supported_names);
167   for (std::vector<const char*>::const_iterator p = supported_names.begin();
168        p != supported_names.end();
169        ++p)
170     printf(" %s", *p);
171   printf("\n");
172
173   printf(_("%s: supported emulations:"), gold::program_name);
174   supported_names.clear();
175   gold::supported_emulation_names(&supported_names);
176   for (std::vector<const char*>::const_iterator p = supported_names.begin();
177        p != supported_names.end();
178        ++p)
179     printf(" %s", *p);
180   printf("\n");
181
182   // REPORT_BUGS_TO is defined in bfd/bfdver.h.
183   const char* report = REPORT_BUGS_TO;
184   if (*report != '\0')
185     printf(_("Report bugs to %s\n"), report);
186 }
187
188 // For bool, arg will be NULL (boolean options take no argument);
189 // we always just set to true.
190 void
191 parse_bool(const char*, const char*, bool* retval)
192 {
193   *retval = true;
194 }
195
196 void
197 parse_uint(const char* option_name, const char* arg, int* retval)
198 {
199   char* endptr;
200   *retval = strtol(arg, &endptr, 0);
201   if (*endptr != '\0' || retval < 0)
202     gold_fatal(_("%s: invalid option value (expected an integer): %s"),
203                option_name, arg);
204 }
205
206 void
207 parse_int(const char* option_name, const char* arg, int* retval)
208 {
209   char* endptr;
210   *retval = strtol(arg, &endptr, 0);
211   if (*endptr != '\0')
212     gold_fatal(_("%s: invalid option value (expected an integer): %s"),
213                option_name, arg);
214 }
215
216 void
217 parse_uint64(const char* option_name, const char* arg, uint64_t* retval)
218 {
219   char* endptr;
220   *retval = strtoull(arg, &endptr, 0);
221   if (*endptr != '\0')
222     gold_fatal(_("%s: invalid option value (expected an integer): %s"),
223                option_name, arg);
224 }
225
226 void
227 parse_double(const char* option_name, const char* arg, double* retval)
228 {
229   char* endptr;
230   *retval = strtod(arg, &endptr);
231   if (*endptr != '\0')
232     gold_fatal(_("%s: invalid option value "
233                  "(expected a floating point number): %s"),
234                option_name, arg);
235 }
236
237 void
238 parse_percent(const char* option_name, const char* arg, double* retval)
239 {
240   char* endptr;
241   *retval = strtod(arg, &endptr) / 100.0;
242   if (*endptr != '\0')
243     gold_fatal(_("%s: invalid option value "
244                  "(expected a floating point number): %s"),
245                option_name, arg);
246 }
247
248 void
249 parse_string(const char* option_name, const char* arg, const char** retval)
250 {
251   if (*arg == '\0')
252     gold_fatal(_("%s: must take a non-empty argument"), option_name);
253   *retval = arg;
254 }
255
256 void
257 parse_optional_string(const char*, const char* arg, const char** retval)
258 {
259   *retval = arg;
260 }
261
262 void
263 parse_dirlist(const char*, const char* arg, Dir_list* retval)
264 {
265   retval->push_back(Search_directory(arg, false));
266 }
267
268 void
269 parse_set(const char*, const char* arg, String_set* retval)
270 {
271   retval->insert(std::string(arg));
272 }
273
274 void
275 parse_choices(const char* option_name, const char* arg, const char** retval,
276               const char* choices[], int num_choices)
277 {
278   for (int i = 0; i < num_choices; i++)
279     if (strcmp(choices[i], arg) == 0)
280       {
281         *retval = arg;
282         return;
283       }
284
285   // If we get here, the user did not enter a valid choice, so we die.
286   std::string choices_list;
287   for (int i = 0; i < num_choices; i++)
288     {
289       choices_list += choices[i];
290       if (i != num_choices - 1)
291         choices_list += ", ";
292     }
293   gold_fatal(_("%s: must take one of the following arguments: %s"),
294              option_name, choices_list.c_str());
295 }
296
297 } // End namespace options.
298
299 // Define the handler for "special" options (set via DEFINE_special).
300
301 void
302 General_options::parse_help(const char*, const char*, Command_line*)
303 {
304   options::help();
305   ::exit(EXIT_SUCCESS);
306 }
307
308 void
309 General_options::parse_version(const char* opt, const char*, Command_line*)
310 {
311   bool print_short = (opt[0] == '-' && opt[1] == 'v');
312   gold::print_version(print_short);
313   this->printed_version_ = true;
314   if (!print_short)
315     ::exit(EXIT_SUCCESS);
316 }
317
318 void
319 General_options::parse_V(const char*, const char*, Command_line*)
320 {
321   gold::print_version(true);
322   this->printed_version_ = true;
323
324   printf(_("  Supported targets:\n"));
325   std::vector<const char*> supported_names;
326   gold::supported_target_names(&supported_names);
327   for (std::vector<const char*>::const_iterator p = supported_names.begin();
328        p != supported_names.end();
329        ++p)
330     printf("   %s\n", *p);
331
332   printf(_("  Supported emulations:\n"));
333   supported_names.clear();
334   gold::supported_emulation_names(&supported_names);
335   for (std::vector<const char*>::const_iterator p = supported_names.begin();
336        p != supported_names.end();
337        ++p)
338     printf("   %s\n", *p);
339 }
340
341 void
342 General_options::parse_defsym(const char*, const char* arg,
343                               Command_line* cmdline)
344 {
345   cmdline->script_options().define_symbol(arg);
346 }
347
348 void
349 General_options::parse_incremental(const char*, const char*,
350                                    Command_line*)
351 {
352   this->incremental_mode_ = INCREMENTAL_AUTO;
353 }
354
355 void
356 General_options::parse_no_incremental(const char*, const char*,
357                                       Command_line*)
358 {
359   this->incremental_mode_ = INCREMENTAL_OFF;
360 }
361
362 void
363 General_options::parse_incremental_full(const char*, const char*,
364                                         Command_line*)
365 {
366   this->incremental_mode_ = INCREMENTAL_FULL;
367 }
368
369 void
370 General_options::parse_incremental_update(const char*, const char*,
371                                           Command_line*)
372 {
373   this->incremental_mode_ = INCREMENTAL_UPDATE;
374 }
375
376 void
377 General_options::parse_incremental_changed(const char*, const char*,
378                                            Command_line*)
379 {
380   this->implicit_incremental_ = true;
381   this->incremental_disposition_ = INCREMENTAL_CHANGED;
382 }
383
384 void
385 General_options::parse_incremental_unchanged(const char*, const char*,
386                                              Command_line*)
387 {
388   this->implicit_incremental_ = true;
389   this->incremental_disposition_ = INCREMENTAL_UNCHANGED;
390 }
391
392 void
393 General_options::parse_incremental_unknown(const char*, const char*,
394                                            Command_line*)
395 {
396   this->implicit_incremental_ = true;
397   this->incremental_disposition_ = INCREMENTAL_CHECK;
398 }
399
400 void
401 General_options::parse_library(const char*, const char* arg,
402                                Command_line* cmdline)
403 {
404   Input_file_argument::Input_file_type type;
405   const char* name;
406   if (arg[0] == ':')
407     {
408       type = Input_file_argument::INPUT_FILE_TYPE_SEARCHED_FILE;
409       name = arg + 1;
410     }
411   else
412     {
413       type = Input_file_argument::INPUT_FILE_TYPE_LIBRARY;
414       name = arg;
415     }
416   Input_file_argument file(name, type, "", false, *this);
417   cmdline->inputs().add_file(file);
418 }
419
420 #ifdef ENABLE_PLUGINS
421 void
422 General_options::parse_plugin(const char*, const char* arg,
423                               Command_line*)
424 {
425   this->add_plugin(arg);
426 }
427
428 // Parse --plugin-opt.
429
430 void
431 General_options::parse_plugin_opt(const char*, const char* arg,
432                                   Command_line*)
433 {
434   this->add_plugin_option(arg);
435 }
436 #endif // ENABLE_PLUGINS
437
438 void
439 General_options::parse_R(const char* option, const char* arg,
440                          Command_line* cmdline)
441 {
442   struct stat s;
443   if (::stat(arg, &s) != 0 || S_ISDIR(s.st_mode))
444     this->add_to_rpath(arg);
445   else
446     this->parse_just_symbols(option, arg, cmdline);
447 }
448
449 void
450 General_options::parse_just_symbols(const char*, const char* arg,
451                                     Command_line* cmdline)
452 {
453   Input_file_argument file(arg, Input_file_argument::INPUT_FILE_TYPE_FILE,
454                            "", true, *this);
455   cmdline->inputs().add_file(file);
456 }
457
458 // Handle --section-start.
459
460 void
461 General_options::parse_section_start(const char*, const char* arg,
462                                      Command_line*)
463 {
464   const char* eq = strchr(arg, '=');
465   if (eq == NULL)
466     {
467       gold_error(_("invalid argument to --section-start; "
468                    "must be SECTION=ADDRESS"));
469       return;
470     }
471
472   std::string section_name(arg, eq - arg);
473
474   ++eq;
475   const char* val_start = eq;
476   if (eq[0] == '0' && (eq[1] == 'x' || eq[1] == 'X'))
477     eq += 2;
478   if (*eq == '\0')
479     {
480       gold_error(_("--section-start address missing"));
481       return;
482     }
483   uint64_t addr = 0;
484   hex_init();
485   for (; *eq != '\0'; ++eq)
486     {
487       if (!hex_p(*eq))
488         {
489           gold_error(_("--section-start argument %s is not a valid hex number"),
490                      val_start);
491           return;
492         }
493       addr <<= 4;
494       addr += hex_value(*eq);
495     }
496
497   this->section_starts_[section_name] = addr;
498 }
499
500 // Look up a --section-start value.
501
502 bool
503 General_options::section_start(const char* secname, uint64_t* paddr) const
504 {
505   if (this->section_starts_.empty())
506     return false;
507   std::map<std::string, uint64_t>::const_iterator p =
508     this->section_starts_.find(secname);
509   if (p == this->section_starts_.end())
510     return false;
511   *paddr = p->second;
512   return true;
513 }
514
515 void
516 General_options::parse_static(const char*, const char*, Command_line*)
517 {
518   this->set_static(true);
519 }
520
521 void
522 General_options::parse_script(const char*, const char* arg,
523                               Command_line* cmdline)
524 {
525   if (!read_commandline_script(arg, cmdline))
526     gold::gold_fatal(_("unable to parse script file %s"), arg);
527 }
528
529 void
530 General_options::parse_version_script(const char*, const char* arg,
531                                       Command_line* cmdline)
532 {
533   if (!read_version_script(arg, cmdline))
534     gold::gold_fatal(_("unable to parse version script file %s"), arg);
535 }
536
537 void
538 General_options::parse_dynamic_list(const char*, const char* arg,
539                                     Command_line* cmdline)
540 {
541   if (!read_dynamic_list(arg, cmdline, &this->dynamic_list_))
542     gold::gold_fatal(_("unable to parse dynamic-list script file %s"), arg);
543 }
544
545 void
546 General_options::parse_start_group(const char*, const char*,
547                                    Command_line* cmdline)
548 {
549   cmdline->inputs().start_group();
550 }
551
552 void
553 General_options::parse_end_group(const char*, const char*,
554                                  Command_line* cmdline)
555 {
556   cmdline->inputs().end_group();
557 }
558
559 void
560 General_options::parse_start_lib(const char*, const char*,
561                                  Command_line* cmdline)
562 {
563   cmdline->inputs().start_lib(cmdline->position_dependent_options());
564 }
565
566 void
567 General_options::parse_end_lib(const char*, const char*,
568                                Command_line* cmdline)
569 {
570   cmdline->inputs().end_lib();
571 }
572
573 // The function add_excluded_libs() in ld/ldlang.c of GNU ld breaks up a list
574 // of names separated by commas or colons and puts them in a linked list.
575 // We implement the same parsing of names here but store names in an unordered
576 // map to speed up searching of names.
577
578 void
579 General_options::parse_exclude_libs(const char*, const char* arg,
580                                     Command_line*)
581 {
582   const char* p = arg;
583
584   while (*p != '\0')
585     {
586       size_t length = strcspn(p, ",:");
587       this->excluded_libs_.insert(std::string(p, length));
588       p += (p[length] ? length + 1 : length);
589     }
590 }
591
592 // The checking logic is based on the function check_excluded_libs() in
593 // ld/ldlang.c of GNU ld but our implementation is different because we use
594 // an unordered map instead of a linked list, which is what GNU ld uses.  GNU
595 // ld searches sequentially in the excluded libs list.  For a given archive,
596 // a match is found if the archive's name matches exactly one of the list
597 // entry or if the archive's name is of the form FOO.a and FOO matches exactly
598 // one of the list entry.  An entry "ALL" in the list is considered as a
599 // wild-card and matches any given name.
600
601 bool
602 General_options::check_excluded_libs(const std::string &name) const
603 {
604   Unordered_set<std::string>::const_iterator p;
605
606   // Exit early for the most common case.
607   if (excluded_libs_.empty())
608     return false;
609
610   // If we see "ALL", all archives are excluded from automatic export.
611   p = excluded_libs_.find(std::string("ALL"));
612   if (p != excluded_libs_.end())
613     return true;
614
615   // First strip off any directories in name.
616   const char* basename = lbasename(name.c_str());
617
618   // Try finding an exact match.
619   p = excluded_libs_.find(std::string(basename));
620   if (p != excluded_libs_.end())
621     return true;
622
623   // Try matching NAME without ".a" at the end.
624   size_t length = strlen(basename);
625   if ((length >= 2)
626       && (basename[length - 2] == '.')
627       && (basename[length - 1] == 'a'))
628     {
629       p = excluded_libs_.find(std::string(basename, length - 2));
630       if (p != excluded_libs_.end())
631         return true;
632     }
633
634   return false;
635 }
636
637 // Recognize input and output target names.  The GNU linker accepts
638 // these with --format and --oformat.  This code is intended to be
639 // minimally compatible.  In practice for an ELF target this would be
640 // the same target as the input files; that name always start with
641 // "elf".  Non-ELF targets would be "srec", "symbolsrec", "tekhex",
642 // "binary", "ihex".
643
644 General_options::Object_format
645 General_options::string_to_object_format(const char* arg)
646 {
647   if (strncmp(arg, "elf", 3) == 0)
648     return gold::General_options::OBJECT_FORMAT_ELF;
649   else if (strcmp(arg, "binary") == 0)
650     return gold::General_options::OBJECT_FORMAT_BINARY;
651   else
652     {
653       gold::gold_error(_("format '%s' not supported; treating as elf "
654                          "(supported formats: elf, binary)"),
655                        arg);
656       return gold::General_options::OBJECT_FORMAT_ELF;
657     }
658 }
659
660 void
661 General_options::parse_fix_v4bx(const char*, const char*,
662                                 Command_line*)
663 {
664   this->fix_v4bx_ = FIX_V4BX_REPLACE;
665 }
666
667 void
668 General_options::parse_fix_v4bx_interworking(const char*, const char*,
669                                              Command_line*)
670 {
671   this->fix_v4bx_ = FIX_V4BX_INTERWORKING;
672 }
673
674 void
675 General_options::parse_EB(const char*, const char*, Command_line*)
676 {
677   this->endianness_ = ENDIANNESS_BIG;
678 }
679
680 void
681 General_options::parse_EL(const char*, const char*, Command_line*)
682 {
683   this->endianness_ = ENDIANNESS_LITTLE;
684 }
685
686 } // End namespace gold.
687
688 namespace
689 {
690
691 void
692 usage()
693 {
694   fprintf(stderr,
695           _("%s: use the --help option for usage information\n"),
696           gold::program_name);
697   ::exit(EXIT_FAILURE);
698 }
699
700 void
701 usage(const char* msg, const char* opt)
702 {
703   fprintf(stderr,
704           _("%s: %s: %s\n"),
705           gold::program_name, opt, msg);
706   usage();
707 }
708
709 // If the default sysroot is relocatable, try relocating it based on
710 // the prefix FROM.
711
712 static char*
713 get_relative_sysroot(const char* from)
714 {
715   char* path = make_relative_prefix(gold::program_name, from,
716                                     TARGET_SYSTEM_ROOT);
717   if (path != NULL)
718     {
719       struct stat s;
720       if (::stat(path, &s) == 0 && S_ISDIR(s.st_mode))
721         return path;
722       free(path);
723     }
724
725   return NULL;
726 }
727
728 // Return the default sysroot.  This is set by the --with-sysroot
729 // option to configure.  Note we do not free the return value of
730 // get_relative_sysroot, which is a small memory leak, but is
731 // necessary since we store this pointer directly in General_options.
732
733 static const char*
734 get_default_sysroot()
735 {
736   const char* sysroot = TARGET_SYSTEM_ROOT;
737   if (*sysroot == '\0')
738     return NULL;
739
740   if (TARGET_SYSTEM_ROOT_RELOCATABLE)
741     {
742       char* path = get_relative_sysroot(BINDIR);
743       if (path == NULL)
744         path = get_relative_sysroot(TOOLBINDIR);
745       if (path != NULL)
746         return path;
747     }
748
749   return sysroot;
750 }
751
752 // Parse a long option.  Such options have the form
753 // <-|--><option>[=arg].  If "=arg" is not present but the option
754 // takes an argument, the next word is taken to the be the argument.
755 // If equals_only is set, then only the <option>=<arg> form is
756 // accepted, not the <option><space><arg> form.  Returns a One_option
757 // struct or NULL if argv[i] cannot be parsed as a long option.  In
758 // the not-NULL case, *arg is set to the option's argument (NULL if
759 // the option takes no argument), and *i is advanced past this option.
760 // NOTE: it is safe for argv and arg to point to the same place.
761 gold::options::One_option*
762 parse_long_option(int argc, const char** argv, bool equals_only,
763                   const char** arg, int* i)
764 {
765   const char* const this_argv = argv[*i];
766
767   const char* equals = strchr(this_argv, '=');
768   const char* option_start = this_argv + strspn(this_argv, "-");
769   std::string option(option_start,
770                      equals ? equals - option_start : strlen(option_start));
771
772   gold::options::Option_map::iterator it
773       = gold::options::long_options->find(option);
774   if (it == gold::options::long_options->end())
775     return NULL;
776
777   gold::options::One_option* retval = it->second;
778
779   // If the dash-count doesn't match, we fail.
780   if (this_argv[0] != '-')  // no dashes at all: had better be "-z <longopt>"
781     {
782       if (retval->dashes != gold::options::DASH_Z)
783         return NULL;
784     }
785   else if (this_argv[1] != '-')   // one dash
786     {
787       if (retval->dashes != gold::options::ONE_DASH
788           && retval->dashes != gold::options::EXACTLY_ONE_DASH
789           && retval->dashes != gold::options::TWO_DASHES)
790         return NULL;
791     }
792   else                            // two dashes (or more!)
793     {
794       if (retval->dashes != gold::options::TWO_DASHES
795           && retval->dashes != gold::options::EXACTLY_TWO_DASHES
796           && retval->dashes != gold::options::ONE_DASH)
797         return NULL;
798     }
799
800   // Now that we know the option is good (or else bad in a way that
801   // will cause us to die), increment i to point past this argv.
802   ++(*i);
803
804   // Figure out the option's argument, if any.
805   if (!retval->takes_argument())
806     {
807       if (equals)
808         usage(_("unexpected argument"), this_argv);
809       else
810         *arg = NULL;
811     }
812   else
813     {
814       if (equals)
815         *arg = equals + 1;
816       else if (retval->takes_optional_argument())
817         *arg = retval->default_value;
818       else if (*i < argc && !equals_only)
819         *arg = argv[(*i)++];
820       else
821         usage(_("missing argument"), this_argv);
822     }
823
824   return retval;
825 }
826
827 // Parse a short option.  Such options have the form -<option>[arg].
828 // If "arg" is not present but the option takes an argument, the next
829 // word is taken to the be the argument.  If the option does not take
830 // an argument, it may be followed by another short option.  Returns a
831 // One_option struct or NULL if argv[i] cannot be parsed as a short
832 // option.  In the not-NULL case, *arg is set to the option's argument
833 // (NULL if the option takes no argument), and *i is advanced past
834 // this option.  This function keeps *i the same if we parsed a short
835 // option that does not take an argument, that looks to be followed by
836 // another short option in the same word.
837 gold::options::One_option*
838 parse_short_option(int argc, const char** argv, int pos_in_argv_i,
839                    const char** arg, int* i)
840 {
841   const char* const this_argv = argv[*i];
842
843   if (this_argv[0] != '-')
844     return NULL;
845
846   // We handle -z as a special case.
847   static gold::options::One_option dash_z("", gold::options::DASH_Z,
848                                           'z', "", NULL, "Z-OPTION", false,
849                                           NULL);
850   gold::options::One_option* retval = NULL;
851   if (this_argv[pos_in_argv_i] == 'z')
852     retval = &dash_z;
853   else
854     {
855       const int char_as_int = static_cast<int>(this_argv[pos_in_argv_i]);
856       if (char_as_int > 0 && char_as_int < 128)
857         retval = gold::options::short_options[char_as_int];
858     }
859
860   if (retval == NULL)
861     return NULL;
862
863   // Figure out the option's argument, if any.
864   if (!retval->takes_argument())
865     {
866       *arg = NULL;
867       // We only advance past this argument if it's the only one in argv.
868       if (this_argv[pos_in_argv_i + 1] == '\0')
869         ++(*i);
870     }
871   else
872     {
873       // If we take an argument, we'll eat up this entire argv entry.
874       ++(*i);
875       if (this_argv[pos_in_argv_i + 1] != '\0')
876         *arg = this_argv + pos_in_argv_i + 1;
877       else if (retval->takes_optional_argument())
878         *arg = retval->default_value;
879       else if (*i < argc)
880         *arg = argv[(*i)++];
881       else
882         usage(_("missing argument"), this_argv);
883     }
884
885   // If we're a -z option, we need to parse our argument as a
886   // long-option, e.g. "-z stacksize=8192".
887   if (retval == &dash_z)
888     {
889       int dummy_i = 0;
890       const char* dash_z_arg = *arg;
891       retval = parse_long_option(1, arg, true, arg, &dummy_i);
892       if (retval == NULL)
893         usage(_("unknown -z option"), dash_z_arg);
894     }
895
896   return retval;
897 }
898
899 } // End anonymous namespace.
900
901 namespace gold
902 {
903
904 General_options::General_options()
905   : printed_version_(false),
906     execstack_status_(EXECSTACK_FROM_INPUT),
907     icf_status_(ICF_NONE),
908     static_(false),
909     do_demangle_(false),
910     plugins_(NULL),
911     dynamic_list_(),
912     incremental_mode_(INCREMENTAL_OFF),
913     incremental_disposition_(INCREMENTAL_CHECK),
914     implicit_incremental_(false),
915     excluded_libs_(),
916     symbols_to_retain_(),
917     section_starts_(),
918     fix_v4bx_(FIX_V4BX_NONE),
919     endianness_(ENDIANNESS_NOT_SET)
920 {
921   // Turn off option registration once construction is complete.
922   gold::options::ready_to_register = false;
923 }
924
925 General_options::Object_format
926 General_options::format_enum() const
927 {
928   return General_options::string_to_object_format(this->format());
929 }
930
931 General_options::Object_format
932 General_options::oformat_enum() const
933 {
934   return General_options::string_to_object_format(this->oformat());
935 }
936
937 // Add the sysroot, if any, to the search paths.
938
939 void
940 General_options::add_sysroot()
941 {
942   if (this->sysroot() == NULL || this->sysroot()[0] == '\0')
943     {
944       this->set_sysroot(get_default_sysroot());
945       if (this->sysroot() == NULL || this->sysroot()[0] == '\0')
946         return;
947     }
948
949   char* canonical_sysroot = lrealpath(this->sysroot());
950
951   for (Dir_list::iterator p = this->library_path_.value.begin();
952        p != this->library_path_.value.end();
953        ++p)
954     p->add_sysroot(this->sysroot(), canonical_sysroot);
955
956   free(canonical_sysroot);
957 }
958
959 // Return whether FILENAME is in a system directory.
960
961 bool
962 General_options::is_in_system_directory(const std::string& filename) const
963 {
964   for (Dir_list::const_iterator p = this->library_path_.value.begin();
965        p != this->library_path_.value.end();
966        ++p)
967     {
968       // We use a straight string comparison rather than calling
969       // FILENAME_CMP because we are only interested in the cases
970       // where we found the file in a system directory, which means
971       // that we used the directory name as a prefix for a -L search.
972       if (p->is_system_directory()
973           && filename.compare(0, p->name().size(), p->name()) == 0)
974         return true;
975     }
976   return false;
977 }
978
979 // Add a plugin to the list of plugins.
980
981 void
982 General_options::add_plugin(const char* filename)
983 {
984   if (this->plugins_ == NULL)
985     this->plugins_ = new Plugin_manager(*this);
986   this->plugins_->add_plugin(filename);
987 }
988
989 // Add a plugin option to a plugin.
990
991 void
992 General_options::add_plugin_option(const char* arg)
993 {
994   if (this->plugins_ == NULL)
995     gold_fatal("--plugin-opt requires --plugin.");
996   this->plugins_->add_plugin_option(arg);
997 }
998
999 // Set up variables and other state that isn't set up automatically by
1000 // the parse routine, and ensure options don't contradict each other
1001 // and are otherwise kosher.
1002
1003 void
1004 General_options::finalize()
1005 {
1006   // Normalize the strip modifiers.  They have a total order:
1007   // strip_all > strip_debug > strip_non_line > strip_debug_gdb.
1008   // If one is true, set all beneath it to true as well.
1009   if (this->strip_all())
1010     this->set_strip_debug(true);
1011   if (this->strip_debug())
1012     this->set_strip_debug_non_line(true);
1013   if (this->strip_debug_non_line())
1014     this->set_strip_debug_gdb(true);
1015
1016   if (this->Bshareable())
1017     this->set_shared(true);
1018
1019   // If the user specifies both -s and -r, convert the -s to -S.
1020   // -r requires us to keep externally visible symbols!
1021   if (this->strip_all() && this->relocatable())
1022     {
1023       this->set_strip_all(false);
1024       gold_assert(this->strip_debug());
1025     }
1026
1027   // For us, -dc and -dp are synonyms for --define-common.
1028   if (this->dc())
1029     this->set_define_common(true);
1030   if (this->dp())
1031     this->set_define_common(true);
1032
1033   // We also set --define-common if we're not relocatable, as long as
1034   // the user didn't explicitly ask for something different.
1035   if (!this->user_set_define_common())
1036     this->set_define_common(!this->relocatable());
1037
1038   // execstack_status_ is a three-state variable; update it based on
1039   // -z [no]execstack.
1040   if (this->execstack())
1041     this->set_execstack_status(EXECSTACK_YES);
1042   else if (this->noexecstack())
1043     this->set_execstack_status(EXECSTACK_NO);
1044
1045   // icf_status_ is a three-state variable; update it based on the
1046   // value of this->icf().
1047   if (strcmp(this->icf(), "none") == 0)
1048     this->set_icf_status(ICF_NONE);
1049   else if (strcmp(this->icf(), "safe") == 0)
1050     this->set_icf_status(ICF_SAFE);
1051   else
1052     this->set_icf_status(ICF_ALL);
1053
1054   // Handle the optional argument for --demangle.
1055   if (this->user_set_demangle())
1056     {
1057       this->set_do_demangle(true);
1058       const char* style = this->demangle();
1059       if (*style != '\0')
1060         {
1061           enum demangling_styles style_code;
1062
1063           style_code = cplus_demangle_name_to_style(style);
1064           if (style_code == unknown_demangling)
1065             gold_fatal("unknown demangling style '%s'", style);
1066           cplus_demangle_set_style(style_code);
1067         }
1068     }
1069   else if (this->user_set_no_demangle())
1070     this->set_do_demangle(false);
1071   else
1072     {
1073       // Testing COLLECT_NO_DEMANGLE makes our default demangling
1074       // behaviour identical to that of gcc's linker wrapper.
1075       this->set_do_demangle(getenv("COLLECT_NO_DEMANGLE") == NULL);
1076     }
1077
1078   // -M is equivalent to "-Map -".
1079   if (this->print_map() && !this->user_set_Map())
1080     {
1081       this->set_Map("-");
1082       this->set_user_set_Map();
1083     }
1084
1085   // Using -n or -N implies -static.
1086   if (this->nmagic() || this->omagic())
1087     this->set_static(true);
1088
1089   // If --thread_count is specified, it applies to
1090   // --thread-count-{initial,middle,final}, though it doesn't override
1091   // them.
1092   if (this->thread_count() > 0 && this->thread_count_initial() == 0)
1093     this->set_thread_count_initial(this->thread_count());
1094   if (this->thread_count() > 0 && this->thread_count_middle() == 0)
1095     this->set_thread_count_middle(this->thread_count());
1096   if (this->thread_count() > 0 && this->thread_count_final() == 0)
1097     this->set_thread_count_final(this->thread_count());
1098
1099   // Let's warn if you set the thread-count but we're going to ignore it.
1100 #ifndef ENABLE_THREADS
1101   if (this->threads())
1102     {
1103       gold_warning(_("ignoring --threads: "
1104                      "%s was compiled without thread support"),
1105                    program_name);
1106       this->set_threads(false);
1107     }
1108   if (this->thread_count() > 0 || this->thread_count_initial() > 0
1109       || this->thread_count_middle() > 0 || this->thread_count_final() > 0)
1110     gold_warning(_("ignoring --thread-count: "
1111                    "%s was compiled without thread support"),
1112                  program_name);
1113 #endif
1114
1115   if (this->user_set_Y())
1116     {
1117       std::string s = this->Y();
1118       if (s.compare(0, 2, "P,") == 0)
1119         s.erase(0, 2);
1120
1121       size_t pos = 0;
1122       size_t next_pos;
1123       do
1124         {
1125           next_pos = s.find(':', pos);
1126           size_t len = (next_pos == std::string::npos
1127                         ? next_pos
1128                         : next_pos - pos);
1129           if (len != 0)
1130             this->add_to_library_path_with_sysroot(s.substr(pos, len).c_str());
1131           pos = next_pos + 1;
1132         }
1133       while (next_pos != std::string::npos);
1134     }
1135   else if (!this->nostdlib())
1136     {
1137       // Even if they don't specify it, we add -L /lib and -L /usr/lib.
1138       // FIXME: We should only do this when configured in native mode.
1139       this->add_to_library_path_with_sysroot("/lib");
1140       this->add_to_library_path_with_sysroot("/usr/lib");
1141     }
1142
1143   // Parse the contents of -retain-symbols-file into a set.
1144   if (this->retain_symbols_file())
1145     {
1146       std::ifstream in;
1147       in.open(this->retain_symbols_file());
1148       if (!in)
1149         gold_fatal(_("unable to open -retain-symbols-file file %s: %s"),
1150                    this->retain_symbols_file(), strerror(errno));
1151       std::string line;
1152       std::getline(in, line);   // this chops off the trailing \n, if any
1153       while (in)
1154         {
1155           if (!line.empty() && line[line.length() - 1] == '\r')   // Windows
1156             line.resize(line.length() - 1);
1157           this->symbols_to_retain_.insert(line);
1158           std::getline(in, line);
1159         }
1160     }
1161
1162   if (this->shared() && !this->user_set_allow_shlib_undefined())
1163     this->set_allow_shlib_undefined(true);
1164
1165   // Normalize library_path() by adding the sysroot to all directories
1166   // in the path, as appropriate.
1167   this->add_sysroot();
1168
1169   // Now that we've normalized the options, check for contradictory ones.
1170   if (this->shared() && this->is_static())
1171     gold_fatal(_("-shared and -static are incompatible"));
1172   if (this->shared() && this->pie())
1173     gold_fatal(_("-shared and -pie are incompatible"));
1174
1175   if (this->shared() && this->relocatable())
1176     gold_fatal(_("-shared and -r are incompatible"));
1177   if (this->pie() && this->relocatable())
1178     gold_fatal(_("-pie and -r are incompatible"));
1179
1180   if (!this->shared())
1181     {
1182       if (this->filter() != NULL)
1183         gold_fatal(_("-F/--filter may not used without -shared"));
1184       if (this->any_auxiliary())
1185         gold_fatal(_("-f/--auxiliary may not be used without -shared"));
1186     }
1187
1188   // TODO: implement support for -retain-symbols-file with -r, if needed.
1189   if (this->relocatable() && this->retain_symbols_file())
1190     gold_fatal(_("-retain-symbols-file does not yet work with -r"));
1191
1192   if (this->oformat_enum() != General_options::OBJECT_FORMAT_ELF
1193       && (this->shared()
1194           || this->pie()
1195           || this->relocatable()))
1196     gold_fatal(_("binary output format not compatible "
1197                  "with -shared or -pie or -r"));
1198
1199   if (this->user_set_hash_bucket_empty_fraction()
1200       && (this->hash_bucket_empty_fraction() < 0.0
1201           || this->hash_bucket_empty_fraction() >= 1.0))
1202     gold_fatal(_("--hash-bucket-empty-fraction value %g out of range "
1203                  "[0.0, 1.0)"),
1204                this->hash_bucket_empty_fraction());
1205
1206   if (this->implicit_incremental_ && this->incremental_mode_ == INCREMENTAL_OFF)
1207     gold_fatal(_("Options --incremental-changed, --incremental-unchanged, "
1208                  "--incremental-unknown require the use of --incremental"));
1209
1210   // FIXME: we can/should be doing a lot more sanity checking here.
1211 }
1212
1213 // Search_directory methods.
1214
1215 // This is called if we have a sysroot.  Apply the sysroot if
1216 // appropriate.  Record whether the directory is in the sysroot.
1217
1218 void
1219 Search_directory::add_sysroot(const char* sysroot,
1220                               const char* canonical_sysroot)
1221 {
1222   gold_assert(*sysroot != '\0');
1223   if (this->put_in_sysroot_)
1224     {
1225       if (!IS_DIR_SEPARATOR(this->name_[0])
1226           && !IS_DIR_SEPARATOR(sysroot[strlen(sysroot) - 1]))
1227         this->name_ = '/' + this->name_;
1228       this->name_ = sysroot + this->name_;
1229       this->is_in_sysroot_ = true;
1230     }
1231   else
1232     {
1233       // Check whether this entry is in the sysroot.  To do this
1234       // correctly, we need to use canonical names.  Otherwise we will
1235       // get confused by the ../../.. paths that gcc tends to use.
1236       char* canonical_name = lrealpath(this->name_.c_str());
1237       int canonical_name_len = strlen(canonical_name);
1238       int canonical_sysroot_len = strlen(canonical_sysroot);
1239       if (canonical_name_len > canonical_sysroot_len
1240           && IS_DIR_SEPARATOR(canonical_name[canonical_sysroot_len]))
1241         {
1242           canonical_name[canonical_sysroot_len] = '\0';
1243           if (FILENAME_CMP(canonical_name, canonical_sysroot) == 0)
1244             this->is_in_sysroot_ = true;
1245         }
1246       free(canonical_name);
1247     }
1248 }
1249
1250 // Input_arguments methods.
1251
1252 // Add a file to the list.
1253
1254 Input_argument&
1255 Input_arguments::add_file(Input_file_argument& file)
1256 {
1257   file.set_arg_serial(++this->file_count_);
1258   if (this->in_group_)
1259     {
1260       gold_assert(!this->input_argument_list_.empty());
1261       gold_assert(this->input_argument_list_.back().is_group());
1262       return this->input_argument_list_.back().group()->add_file(file);
1263     }
1264   if (this->in_lib_)
1265     {
1266       gold_assert(!this->input_argument_list_.empty());
1267       gold_assert(this->input_argument_list_.back().is_lib());
1268       return this->input_argument_list_.back().lib()->add_file(file);
1269     }
1270   this->input_argument_list_.push_back(Input_argument(file));
1271   return this->input_argument_list_.back();
1272 }
1273
1274 // Start a group.
1275
1276 void
1277 Input_arguments::start_group()
1278 {
1279   if (this->in_group_)
1280     gold_fatal(_("May not nest groups"));
1281   if (this->in_lib_)
1282     gold_fatal(_("may not nest groups in libraries"));
1283   Input_file_group* group = new Input_file_group();
1284   this->input_argument_list_.push_back(Input_argument(group));
1285   this->in_group_ = true;
1286 }
1287
1288 // End a group.
1289
1290 void
1291 Input_arguments::end_group()
1292 {
1293   if (!this->in_group_)
1294     gold_fatal(_("Group end without group start"));
1295   this->in_group_ = false;
1296 }
1297
1298 // Start a lib.
1299
1300 void
1301 Input_arguments::start_lib(const Position_dependent_options& options)
1302 {
1303   if (this->in_lib_)
1304     gold_fatal(_("may not nest libraries"));
1305   if (this->in_group_)
1306     gold_fatal(_("may not nest libraries in groups"));
1307   Input_file_lib* lib = new Input_file_lib(options);
1308   this->input_argument_list_.push_back(Input_argument(lib));
1309   this->in_lib_ = true;
1310 }
1311
1312 // End a lib.
1313
1314 void
1315 Input_arguments::end_lib()
1316 {
1317   if (!this->in_lib_)
1318     gold_fatal(_("lib end without lib start"));
1319   this->in_lib_ = false;
1320 }
1321
1322 // Command_line options.
1323
1324 Command_line::Command_line()
1325 {
1326 }
1327
1328 // Pre_options is the hook that sets the ready_to_register flag.
1329
1330 Command_line::Pre_options::Pre_options()
1331 {
1332   gold::options::ready_to_register = true;
1333 }
1334
1335 // Process the command line options.  For process_one_option, i is the
1336 // index of argv to process next, and must be an option (that is,
1337 // start with a dash).  The return value is the index of the next
1338 // option to process (i+1 or i+2, or argc to indicate processing is
1339 // done).  no_more_options is set to true if (and when) "--" is seen
1340 // as an option.
1341
1342 int
1343 Command_line::process_one_option(int argc, const char** argv, int i,
1344                                  bool* no_more_options)
1345 {
1346   gold_assert(argv[i][0] == '-' && !(*no_more_options));
1347
1348   // If we are reading "--", then just set no_more_options and return.
1349   if (argv[i][1] == '-' && argv[i][2] == '\0')
1350     {
1351       *no_more_options = true;
1352       return i + 1;
1353     }
1354
1355   int new_i = i;
1356   options::One_option* option = NULL;
1357   const char* arg = NULL;
1358
1359   // First, try to process argv as a long option.
1360   option = parse_long_option(argc, argv, false, &arg, &new_i);
1361   if (option)
1362     {
1363       option->reader->parse_to_value(argv[i], arg, this, &this->options_);
1364       return new_i;
1365     }
1366
1367   // Now, try to process argv as a short option.  Since several short
1368   // options can be combined in one argv, we may have to parse a lot
1369   // until we're done reading this argv.
1370   int pos_in_argv_i = 1;
1371   while (new_i == i)
1372     {
1373       option = parse_short_option(argc, argv, pos_in_argv_i, &arg, &new_i);
1374       if (!option)
1375         break;
1376       option->reader->parse_to_value(argv[i], arg, this, &this->options_);
1377       ++pos_in_argv_i;
1378     }
1379   if (option)
1380     return new_i;
1381
1382   // I guess it's neither a long option nor a short option.
1383   usage(_("unknown option"), argv[i]);
1384   return argc;
1385 }
1386
1387
1388 void
1389 Command_line::process(int argc, const char** argv)
1390 {
1391   bool no_more_options = false;
1392   int i = 0;
1393   while (i < argc)
1394     {
1395       this->position_options_.copy_from_options(this->options());
1396       if (no_more_options || argv[i][0] != '-')
1397         {
1398           Input_file_argument file(argv[i],
1399                                    Input_file_argument::INPUT_FILE_TYPE_FILE,
1400                                    "", false, this->position_options_);
1401           this->inputs_.add_file(file);
1402           ++i;
1403         }
1404       else
1405         i = process_one_option(argc, argv, i, &no_more_options);
1406     }
1407
1408   if (this->inputs_.in_group())
1409     {
1410       fprintf(stderr, _("%s: missing group end\n"), program_name);
1411       usage();
1412     }
1413
1414   // Normalize the options and ensure they don't contradict each other.
1415   this->options_.finalize();
1416 }
1417
1418 // Finalize the version script options and return them.
1419
1420 const Version_script_info&
1421 Command_line::version_script()
1422 {
1423   this->options_.finalize_dynamic_list();
1424   Version_script_info* vsi = this->script_options_.version_script_info();
1425   vsi->finalize();
1426   return *vsi;
1427 }
1428
1429 } // End namespace gold.