1 // options.c -- handle command line options for gold
3 // Copyright 2006, 2007, 2008 Free Software Foundation, Inc.
4 // Written by Ian Lance Taylor <iant@google.com>.
6 // This file is part of gold.
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.
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.
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.
29 #include "filenames.h"
30 #include "libiberty.h"
35 #include "target-select.h"
42 Position_dependent_options::default_options_;
47 // This global variable is set up as General_options is constructed.
48 static std::vector<const One_option*> registered_options;
50 // These are set up at the same time -- the variables that accept one
51 // dash, two, or require -z. A single variable may be in more than
52 // one of thes data structures.
53 typedef Unordered_map<std::string, One_option*> Option_map;
54 static Option_map* long_options = NULL;
55 static One_option* short_options[128];
58 One_option::register_option()
60 registered_options.push_back(this);
62 // We can't make long_options a static Option_map because we can't
63 // guarantee that will be initialized before register_option() is
65 if (long_options == NULL)
66 long_options = new Option_map;
68 // TWO_DASHES means that two dashes are preferred, but one is ok too.
69 if (!this->longname.empty())
70 (*long_options)[this->longname] = this;
72 const int shortname_as_int = static_cast<int>(this->shortname);
73 gold_assert(shortname_as_int >= 0 && shortname_as_int < 128);
74 if (this->shortname != '\0')
75 short_options[shortname_as_int] = this;
79 One_option::print() const
84 if (this->shortname != '\0')
86 len += printf("-%c", this->shortname);
89 // -z takes long-names only.
90 gold_assert(this->dashes != DASH_Z);
91 len += printf(" %s", gettext(this->helparg));
95 if (!this->longname.empty()
96 && !(this->longname[0] == this->shortname
97 && this->longname[1] == '\0'))
101 switch (this->dashes)
103 case options::ONE_DASH: case options::EXACTLY_ONE_DASH:
106 case options::TWO_DASHES: case options::EXACTLY_TWO_DASHES:
109 case options::DASH_Z:
110 len += printf("-z ");
115 len += printf("%s", this->longname.c_str());
118 // For most options, we print "--frob FOO". But for -z
119 // we print "-z frob=FOO".
120 len += printf("%c%s", this->dashes == options::DASH_Z ? '=' : ' ',
121 gettext(this->helparg));
130 for (; len < 30; ++len)
133 // TODO: if we're boolean, add " (default)" when appropriate.
134 printf("%s\n", gettext(this->helpstring));
140 printf(_("Usage: %s [options] file...\nOptions:\n"), gold::program_name);
142 std::vector<const One_option*>::const_iterator it;
143 for (it = registered_options.begin(); it != registered_options.end(); ++it)
147 // For bool, arg will be NULL (boolean options take no argument);
148 // we always just set to true.
150 parse_bool(const char*, const char*, bool* retval)
156 parse_uint(const char* option_name, const char* arg, int* retval)
159 *retval = strtol(arg, &endptr, 0);
160 if (*endptr != '\0' || retval < 0)
161 gold_fatal(_("%s: invalid option value (expected an integer): %s"),
166 parse_uint64(const char* option_name, const char* arg, uint64_t *retval)
169 *retval = strtoull(arg, &endptr, 0);
171 gold_fatal(_("%s: invalid option value (expected an integer): %s"),
176 parse_double(const char* option_name, const char* arg, double* retval)
179 *retval = strtod(arg, &endptr);
181 gold_fatal(_("%s: invalid option value "
182 "(expected a floating point number): %s"),
187 parse_string(const char* option_name, const char* arg, const char** retval)
190 gold_fatal(_("%s: must take a non-empty argument"), option_name);
195 parse_optional_string(const char*, const char* arg, const char** retval)
201 parse_dirlist(const char*, const char* arg, Dir_list* retval)
203 retval->push_back(Search_directory(arg, false));
207 parse_choices(const char* option_name, const char* arg, const char** retval,
208 const char* choices[], int num_choices)
210 for (int i = 0; i < num_choices; i++)
211 if (strcmp(choices[i], arg) == 0)
217 // If we get here, the user did not enter a valid choice, so we die.
218 std::string choices_list;
219 for (int i = 0; i < num_choices; i++)
221 choices_list += choices[i];
222 if (i != num_choices - 1)
223 choices_list += ", ";
225 gold_fatal(_("%s: must take one of the following arguments: %s"),
226 option_name, choices_list.c_str());
229 } // End namespace options.
231 // Define the handler for "special" options (set via DEFINE_special).
234 General_options::parse_help(const char*, const char*, Command_line*)
237 ::exit(EXIT_SUCCESS);
241 General_options::parse_version(const char* opt, const char*, Command_line*)
243 gold::print_version(opt[0] == '-' && opt[1] == 'v');
244 ::exit(EXIT_SUCCESS);
248 General_options::parse_Bstatic(const char*, const char*, Command_line*)
250 this->set_Bdynamic(false);
254 General_options::parse_defsym(const char*, const char* arg,
255 Command_line* cmdline)
257 cmdline->script_options().define_symbol(arg);
261 General_options::parse_library(const char*, const char* arg,
262 Command_line* cmdline)
264 Input_file_argument file(arg, true, "", false, *this);
265 cmdline->inputs().add_file(file);
269 General_options::parse_R(const char* option, const char* arg,
270 Command_line* cmdline)
273 if (::stat(arg, &s) != 0 || S_ISDIR(s.st_mode))
274 this->add_to_rpath(arg);
276 this->parse_just_symbols(option, arg, cmdline);
280 General_options::parse_just_symbols(const char*, const char* arg,
281 Command_line* cmdline)
283 Input_file_argument file(arg, false, "", true, *this);
284 cmdline->inputs().add_file(file);
288 General_options::parse_static(const char*, const char*, Command_line*)
290 this->set_static(true);
294 General_options::parse_script(const char*, const char* arg,
295 Command_line* cmdline)
297 if (!read_commandline_script(arg, cmdline))
298 gold::gold_fatal(_("unable to parse script file %s"), arg);
302 General_options::parse_version_script(const char*, const char* arg,
303 Command_line* cmdline)
305 if (!read_version_script(arg, cmdline))
306 gold::gold_fatal(_("unable to parse version script file %s"), arg);
310 General_options::parse_start_group(const char*, const char*,
311 Command_line* cmdline)
313 cmdline->inputs().start_group();
317 General_options::parse_end_group(const char*, const char*,
318 Command_line* cmdline)
320 cmdline->inputs().end_group();
323 } // End namespace gold.
332 _("%s: use the --help option for usage information\n"),
334 ::exit(EXIT_FAILURE);
338 usage(const char* msg, const char *opt)
342 gold::program_name, opt, msg);
346 // Recognize input and output target names. The GNU linker accepts
347 // these with --format and --oformat. This code is intended to be
348 // minimally compatible. In practice for an ELF target this would be
349 // the same target as the input files; that name always start with
350 // "elf". Non-ELF targets would be "srec", "symbolsrec", "tekhex",
353 gold::General_options::Object_format
354 string_to_object_format(const char* arg)
356 if (strncmp(arg, "elf", 3) == 0)
357 return gold::General_options::OBJECT_FORMAT_ELF;
358 else if (strcmp(arg, "binary") == 0)
359 return gold::General_options::OBJECT_FORMAT_BINARY;
362 gold::gold_error(_("format '%s' not supported; treating as elf "
363 "(supported formats: elf, binary)"),
365 return gold::General_options::OBJECT_FORMAT_ELF;
369 // If the default sysroot is relocatable, try relocating it based on
373 get_relative_sysroot(const char* from)
375 char* path = make_relative_prefix(gold::program_name, from,
380 if (::stat(path, &s) == 0 && S_ISDIR(s.st_mode))
388 // Return the default sysroot. This is set by the --with-sysroot
389 // option to configure. Note we do not free the return value of
390 // get_relative_sysroot, which is a small memory leak, but is
391 // necessary since we store this pointer directly in General_options.
394 get_default_sysroot()
396 const char* sysroot = TARGET_SYSTEM_ROOT;
397 if (*sysroot == '\0')
400 if (TARGET_SYSTEM_ROOT_RELOCATABLE)
402 char* path = get_relative_sysroot(BINDIR);
404 path = get_relative_sysroot(TOOLBINDIR);
412 // Parse a long option. Such options have the form
413 // <-|--><option>[=arg]. If "=arg" is not present but the option
414 // takes an argument, the next word is taken to the be the argument.
415 // If equals_only is set, then only the <option>=<arg> form is
416 // accepted, not the <option><space><arg> form. Returns a One_option
417 // struct or NULL if argv[i] cannot be parsed as a long option. In
418 // the not-NULL case, *arg is set to the option's argument (NULL if
419 // the option takes no argument), and *i is advanced past this option.
420 // NOTE: it is safe for argv and arg to point to the same place.
421 gold::options::One_option*
422 parse_long_option(int argc, const char** argv, bool equals_only,
423 const char** arg, int* i)
425 const char* const this_argv = argv[*i];
427 const char* equals = strchr(this_argv, '=');
428 const char* option_start = this_argv + strspn(this_argv, "-");
429 std::string option(option_start,
430 equals ? equals - option_start : strlen(option_start));
432 gold::options::Option_map::iterator it
433 = gold::options::long_options->find(option);
434 if (it == gold::options::long_options->end())
437 gold::options::One_option* retval = it->second;
439 // If the dash-count doesn't match, we fail.
440 if (this_argv[0] != '-') // no dashes at all: had better be "-z <longopt>"
442 if (retval->dashes != gold::options::DASH_Z)
445 else if (this_argv[1] != '-') // one dash
447 if (retval->dashes != gold::options::ONE_DASH
448 && retval->dashes != gold::options::EXACTLY_ONE_DASH
449 && retval->dashes != gold::options::TWO_DASHES)
452 else // two dashes (or more!)
454 if (retval->dashes != gold::options::TWO_DASHES
455 && retval->dashes != gold::options::EXACTLY_TWO_DASHES
456 && retval->dashes != gold::options::ONE_DASH)
460 // Now that we know the option is good (or else bad in a way that
461 // will cause us to die), increment i to point past this argv.
464 // Figure out the option's argument, if any.
465 if (!retval->takes_argument())
468 usage(_("unexpected argument"), this_argv);
476 else if (retval->takes_optional_argument())
477 *arg = retval->default_value;
478 else if (*i < argc && !equals_only)
481 usage(_("missing argument"), this_argv);
487 // Parse a short option. Such options have the form -<option>[arg].
488 // If "arg" is not present but the option takes an argument, the next
489 // word is taken to the be the argument. If the option does not take
490 // an argument, it may be followed by another short option. Returns a
491 // One_option struct or NULL if argv[i] cannot be parsed as a short
492 // option. In the not-NULL case, *arg is set to the option's argument
493 // (NULL if the option takes no argument), and *i is advanced past
494 // this option. This function keeps *i the same if we parsed a short
495 // option that does not take an argument, that looks to be followed by
496 // another short option in the same word.
497 gold::options::One_option*
498 parse_short_option(int argc, const char** argv, int pos_in_argv_i,
499 const char** arg, int* i)
501 const char* const this_argv = argv[*i];
503 if (this_argv[0] != '-')
506 // We handle -z as a special case.
507 static gold::options::One_option dash_z("", gold::options::DASH_Z,
508 'z', "", "-z", "Z-OPTION", false,
510 gold::options::One_option* retval = NULL;
511 if (this_argv[pos_in_argv_i] == 'z')
515 const int char_as_int = static_cast<int>(this_argv[pos_in_argv_i]);
516 if (char_as_int > 0 && char_as_int < 128)
517 retval = gold::options::short_options[char_as_int];
523 // Figure out the option's argument, if any.
524 if (!retval->takes_argument())
527 // We only advance past this argument if it's the only one in argv.
528 if (this_argv[pos_in_argv_i + 1] == '\0')
533 // If we take an argument, we'll eat up this entire argv entry.
535 if (this_argv[pos_in_argv_i + 1] != '\0')
536 *arg = this_argv + pos_in_argv_i + 1;
537 else if (retval->takes_optional_argument())
538 *arg = retval->default_value;
542 usage(_("missing argument"), this_argv);
545 // If we're a -z option, we need to parse our argument as a
546 // long-option, e.g. "-z stacksize=8192".
547 if (retval == &dash_z)
550 const char* dash_z_arg = *arg;
551 retval = parse_long_option(1, arg, true, arg, &dummy_i);
553 usage(_("unknown -z option"), dash_z_arg);
559 } // End anonymous namespace.
564 General_options::General_options()
565 : execstack_status_(General_options::EXECSTACK_FROM_INPUT), static_(false),
570 General_options::Object_format
571 General_options::format_enum() const
573 return string_to_object_format(this->format());
576 General_options::Object_format
577 General_options::oformat_enum() const
579 return string_to_object_format(this->oformat());
582 // Add the sysroot, if any, to the search paths.
585 General_options::add_sysroot()
587 if (this->sysroot() == NULL || this->sysroot()[0] == '\0')
589 this->set_sysroot(get_default_sysroot());
590 if (this->sysroot() == NULL || this->sysroot()[0] == '\0')
594 char* canonical_sysroot = lrealpath(this->sysroot());
596 for (Dir_list::iterator p = this->library_path_.value.begin();
597 p != this->library_path_.value.end();
599 p->add_sysroot(this->sysroot(), canonical_sysroot);
601 free(canonical_sysroot);
604 // Set up variables and other state that isn't set up automatically by
605 // the parse routine, and ensure options don't contradict each other
606 // and are otherwise kosher.
609 General_options::finalize()
611 // Normalize the strip modifiers. They have a total order:
612 // strip_all > strip_debug > strip_debug_gdb. If one is true, set
613 // all beneath it to true as well.
614 if (this->strip_all())
615 this->set_strip_debug(true);
616 if (this->strip_debug())
617 this->set_strip_debug_gdb(true);
619 // If the user specifies both -s and -r, convert the -s to -S.
620 // -r requires us to keep externally visible symbols!
621 if (this->strip_all() && this->relocatable())
623 this->set_strip_all(false);
624 gold_assert(this->strip_debug());
627 // For us, -dc and -dp are synonyms for --define-common.
629 this->set_define_common(true);
631 this->set_define_common(true);
633 // We also set --define-common if we're not relocatable, as long as
634 // the user didn't explicitly ask for something different.
635 if (!this->user_set_define_common())
636 this->set_define_common(!this->relocatable());
638 // execstack_status_ is a three-state variable; update it based on
640 if (this->execstack())
641 this->set_execstack_status(EXECSTACK_YES);
642 else if (this->noexecstack())
643 this->set_execstack_status(EXECSTACK_NO);
645 // Handle the optional argument for --demangle.
646 if (this->user_set_demangle())
648 this->set_do_demangle(true);
649 const char* style = this->demangle();
652 enum demangling_styles style_code;
654 style_code = cplus_demangle_name_to_style(style);
655 if (style_code == unknown_demangling)
656 gold_fatal("unknown demangling style '%s'", style);
657 cplus_demangle_set_style(style_code);
660 else if (this->user_set_no_demangle())
661 this->set_do_demangle(false);
664 // Testing COLLECT_NO_DEMANGLE makes our default demangling
665 // behaviour identical to that of gcc's linker wrapper.
666 this->set_do_demangle(getenv("COLLECT_NO_DEMANGLE") == NULL);
669 // If --thread_count is specified, it applies to
670 // --thread-count-{initial,middle,final}, though it doesn't override
672 if (this->thread_count() > 0 && this->thread_count_initial() == 0)
673 this->set_thread_count_initial(this->thread_count());
674 if (this->thread_count() > 0 && this->thread_count_middle() == 0)
675 this->set_thread_count_middle(this->thread_count());
676 if (this->thread_count() > 0 && this->thread_count_final() == 0)
677 this->set_thread_count_final(this->thread_count());
679 // Let's warn if you set the thread-count but we're going to ignore it.
680 #ifndef ENABLE_THREADS
683 gold_warning(_("ignoring --threads: "
684 "%s was compiled without thread support"),
686 this->set_threads(false);
688 if (this->thread_count() > 0 || this->thread_count_initial() > 0
689 || this->thread_count_middle() > 0 || this->thread_count_final() > 0)
690 gold_warning(_("ignoring --thread-count: "
691 "%s was compiled without thread support"),
695 // Even if they don't specify it, we add -L /lib and -L /usr/lib.
696 // FIXME: We should only do this when configured in native mode.
697 this->add_to_library_path_with_sysroot("/lib");
698 this->add_to_library_path_with_sysroot("/usr/lib");
700 // Normalize library_path() by adding the sysroot to all directories
701 // in the path, as appropriate.
704 // Now that we've normalized the options, check for contradictory ones.
705 if (this->shared() && this->relocatable())
706 gold_fatal(_("-shared and -r are incompatible"));
708 if (this->oformat_enum() != General_options::OBJECT_FORMAT_ELF
709 && (this->shared() || this->relocatable()))
710 gold_fatal(_("binary output format not compatible with -shared or -r"));
712 if (this->user_set_hash_bucket_empty_fraction()
713 && (this->hash_bucket_empty_fraction() < 0.0
714 || this->hash_bucket_empty_fraction() >= 1.0))
715 gold_fatal(_("--hash-bucket-empty-fraction value %g out of range "
717 this->hash_bucket_empty_fraction());
719 // FIXME: we can/should be doing a lot more sanity checking here.
722 // Search_directory methods.
724 // This is called if we have a sysroot. Apply the sysroot if
725 // appropriate. Record whether the directory is in the sysroot.
728 Search_directory::add_sysroot(const char* sysroot,
729 const char* canonical_sysroot)
731 gold_assert(*sysroot != '\0');
732 if (this->put_in_sysroot_)
734 if (!IS_DIR_SEPARATOR(this->name_[0])
735 && !IS_DIR_SEPARATOR(sysroot[strlen(sysroot) - 1]))
736 this->name_ = '/' + this->name_;
737 this->name_ = sysroot + this->name_;
738 this->is_in_sysroot_ = true;
742 // Check whether this entry is in the sysroot. To do this
743 // correctly, we need to use canonical names. Otherwise we will
744 // get confused by the ../../.. paths that gcc tends to use.
745 char* canonical_name = lrealpath(this->name_.c_str());
746 int canonical_name_len = strlen(canonical_name);
747 int canonical_sysroot_len = strlen(canonical_sysroot);
748 if (canonical_name_len > canonical_sysroot_len
749 && IS_DIR_SEPARATOR(canonical_name[canonical_sysroot_len]))
751 canonical_name[canonical_sysroot_len] = '\0';
752 if (FILENAME_CMP(canonical_name, canonical_sysroot) == 0)
753 this->is_in_sysroot_ = true;
755 free(canonical_name);
759 // Input_arguments methods.
761 // Add a file to the list.
764 Input_arguments::add_file(const Input_file_argument& file)
766 if (!this->in_group_)
767 this->input_argument_list_.push_back(Input_argument(file));
770 gold_assert(!this->input_argument_list_.empty());
771 gold_assert(this->input_argument_list_.back().is_group());
772 this->input_argument_list_.back().group()->add_file(file);
779 Input_arguments::start_group()
782 gold_fatal(_("May not nest groups"));
783 Input_file_group* group = new Input_file_group();
784 this->input_argument_list_.push_back(Input_argument(group));
785 this->in_group_ = true;
791 Input_arguments::end_group()
793 if (!this->in_group_)
794 gold_fatal(_("Group end without group start"));
795 this->in_group_ = false;
798 // Command_line options.
800 Command_line::Command_line()
804 // Process the command line options. For process_one_option, i is the
805 // index of argv to process next, and must be an option (that is,
806 // start with a dash). The return value is the index of the next
807 // option to process (i+1 or i+2, or argc to indicate processing is
808 // done). no_more_options is set to true if (and when) "--" is seen
812 Command_line::process_one_option(int argc, const char** argv, int i,
813 bool* no_more_options)
815 gold_assert(argv[i][0] == '-' && !(*no_more_options));
817 // If we are reading "--", then just set no_more_options and return.
818 if (argv[i][1] == '-' && argv[i][2] == '\0')
820 *no_more_options = true;
825 options::One_option* option = NULL;
826 const char* arg = NULL;
828 // First, try to process argv as a long option.
829 option = parse_long_option(argc, argv, false, &arg, &new_i);
832 option->reader->parse_to_value(argv[i], arg, this, &this->options_);
836 // Now, try to process argv as a short option. Since several short
837 // options can be combined in one argv, we may have to parse a lot
838 // until we're done reading this argv.
839 int pos_in_argv_i = 1;
842 option = parse_short_option(argc, argv, pos_in_argv_i, &arg, &new_i);
845 option->reader->parse_to_value(argv[i], arg, this, &this->options_);
851 // I guess it's neither a long option nor a short option.
852 usage(_("unknown option"), argv[i]);
858 Command_line::process(int argc, const char** argv)
860 bool no_more_options = false;
864 this->position_options_.copy_from_options(this->options());
865 if (no_more_options || argv[i][0] != '-')
867 Input_file_argument file(argv[i], false, "", false,
868 this->position_options_);
869 this->inputs_.add_file(file);
873 i = process_one_option(argc, argv, i, &no_more_options);
876 if (this->inputs_.in_group())
878 fprintf(stderr, _("%s: missing group end\n"), program_name);
882 // Normalize the options and ensure they don't contradict each other.
883 this->options_.finalize();
886 } // End namespace gold.