1 //===-- CommandLine.cpp - Command line parser implementation --------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This class implements a command line argument processor that is useful when 11 // creating a tool. It provides a simple, minimalistic interface that is easily 12 // extensible and supports nonlocal (library) command line options. 13 // 14 // Note that rather than trying to figure out what this code does, you could try 15 // reading the library documentation located in docs/CommandLine.html 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/Support/CommandLine.h" 20 #include "llvm-c/Support.h" 21 #include "llvm/ADT/ArrayRef.h" 22 #include "llvm/ADT/SmallPtrSet.h" 23 #include "llvm/ADT/SmallString.h" 24 #include "llvm/ADT/StringMap.h" 25 #include "llvm/ADT/Twine.h" 26 #include "llvm/Config/config.h" 27 #include "llvm/Support/ConvertUTF.h" 28 #include "llvm/Support/Debug.h" 29 #include "llvm/Support/ErrorHandling.h" 30 #include "llvm/Support/Host.h" 31 #include "llvm/Support/ManagedStatic.h" 32 #include "llvm/Support/MemoryBuffer.h" 33 #include "llvm/Support/Path.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include <cerrno> 36 #include <cstdlib> 37 #include <map> 38 #include <system_error> 39 using namespace llvm; 40 using namespace cl; 41 42 #define DEBUG_TYPE "commandline" 43 44 //===----------------------------------------------------------------------===// 45 // Template instantiations and anchors. 46 // 47 namespace llvm { 48 namespace cl { 49 TEMPLATE_INSTANTIATION(class basic_parser<bool>); 50 TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>); 51 TEMPLATE_INSTANTIATION(class basic_parser<int>); 52 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>); 53 TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>); 54 TEMPLATE_INSTANTIATION(class basic_parser<double>); 55 TEMPLATE_INSTANTIATION(class basic_parser<float>); 56 TEMPLATE_INSTANTIATION(class basic_parser<std::string>); 57 TEMPLATE_INSTANTIATION(class basic_parser<char>); 58 59 TEMPLATE_INSTANTIATION(class opt<unsigned>); 60 TEMPLATE_INSTANTIATION(class opt<int>); 61 TEMPLATE_INSTANTIATION(class opt<std::string>); 62 TEMPLATE_INSTANTIATION(class opt<char>); 63 TEMPLATE_INSTANTIATION(class opt<bool>); 64 } 65 } // end namespace llvm::cl 66 67 // Pin the vtables to this file. 68 void GenericOptionValue::anchor() {} 69 void OptionValue<boolOrDefault>::anchor() {} 70 void OptionValue<std::string>::anchor() {} 71 void Option::anchor() {} 72 void basic_parser_impl::anchor() {} 73 void parser<bool>::anchor() {} 74 void parser<boolOrDefault>::anchor() {} 75 void parser<int>::anchor() {} 76 void parser<unsigned>::anchor() {} 77 void parser<unsigned long long>::anchor() {} 78 void parser<double>::anchor() {} 79 void parser<float>::anchor() {} 80 void parser<std::string>::anchor() {} 81 void parser<char>::anchor() {} 82 void StringSaver::anchor() {} 83 84 //===----------------------------------------------------------------------===// 85 86 class CommandLineParser { 87 public: 88 // Globals for name and overview of program. Program name is not a string to 89 // avoid static ctor/dtor issues. 90 std::string ProgramName; 91 const char *ProgramOverview; 92 93 // This collects additional help to be printed. 94 std::vector<const char *> MoreHelp; 95 96 SmallVector<Option *, 4> PositionalOpts; 97 SmallVector<Option *, 4> SinkOpts; 98 StringMap<Option *> OptionsMap; 99 100 Option *ConsumeAfterOpt; // The ConsumeAfter option if it exists. 101 102 CommandLineParser() : ProgramOverview(nullptr), ConsumeAfterOpt(nullptr) {} 103 104 void ParseCommandLineOptions(int argc, const char *const *argv, 105 const char *Overview); 106 107 void addLiteralOption(Option &Opt, const char *Name) { 108 if (!Opt.hasArgStr()) { 109 if (!OptionsMap.insert(std::make_pair(Name, &Opt)).second) { 110 errs() << ProgramName << ": CommandLine Error: Option '" << Name 111 << "' registered more than once!\n"; 112 report_fatal_error("inconsistency in registered CommandLine options"); 113 } 114 } 115 } 116 117 void addOption(Option *O) { 118 bool HadErrors = false; 119 if (O->ArgStr[0]) { 120 // Add argument to the argument map! 121 if (!OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) { 122 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr 123 << "' registered more than once!\n"; 124 HadErrors = true; 125 } 126 } 127 128 // Remember information about positional options. 129 if (O->getFormattingFlag() == cl::Positional) 130 PositionalOpts.push_back(O); 131 else if (O->getMiscFlags() & cl::Sink) // Remember sink options 132 SinkOpts.push_back(O); 133 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) { 134 if (ConsumeAfterOpt) { 135 O->error("Cannot specify more than one option with cl::ConsumeAfter!"); 136 HadErrors = true; 137 } 138 ConsumeAfterOpt = O; 139 } 140 141 // Fail hard if there were errors. These are strictly unrecoverable and 142 // indicate serious issues such as conflicting option names or an 143 // incorrectly 144 // linked LLVM distribution. 145 if (HadErrors) 146 report_fatal_error("inconsistency in registered CommandLine options"); 147 } 148 149 void removeOption(Option *O) { 150 SmallVector<const char *, 16> OptionNames; 151 O->getExtraOptionNames(OptionNames); 152 if (O->ArgStr[0]) 153 OptionNames.push_back(O->ArgStr); 154 for (auto Name : OptionNames) 155 OptionsMap.erase(StringRef(Name)); 156 157 if (O->getFormattingFlag() == cl::Positional) 158 for (auto Opt = PositionalOpts.begin(); Opt != PositionalOpts.end(); 159 ++Opt) { 160 if (*Opt == O) { 161 PositionalOpts.erase(Opt); 162 break; 163 } 164 } 165 else if (O->getMiscFlags() & cl::Sink) 166 for (auto Opt = SinkOpts.begin(); Opt != SinkOpts.end(); ++Opt) { 167 if (*Opt == O) { 168 SinkOpts.erase(Opt); 169 break; 170 } 171 } 172 else if (O == ConsumeAfterOpt) 173 ConsumeAfterOpt = nullptr; 174 } 175 176 bool hasOptions() { 177 return (!OptionsMap.empty() || !PositionalOpts.empty() || 178 nullptr != ConsumeAfterOpt); 179 } 180 181 void updateArgStr(Option *O, const char *NewName) { 182 if (!OptionsMap.insert(std::make_pair(NewName, O)).second) { 183 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr 184 << "' registered more than once!\n"; 185 report_fatal_error("inconsistency in registered CommandLine options"); 186 } 187 OptionsMap.erase(StringRef(O->ArgStr)); 188 } 189 190 void printOptionValues(); 191 }; 192 193 static ManagedStatic<CommandLineParser> GlobalParser; 194 195 void cl::AddLiteralOption(Option &O, const char *Name) { 196 GlobalParser->addLiteralOption(O, Name); 197 } 198 199 extrahelp::extrahelp(const char *Help) : morehelp(Help) { 200 GlobalParser->MoreHelp.push_back(Help); 201 } 202 203 void Option::addArgument() { 204 GlobalParser->addOption(this); 205 FullyInitialized = true; 206 } 207 208 void Option::removeArgument() { GlobalParser->removeOption(this); } 209 210 void Option::setArgStr(const char *S) { 211 if (FullyInitialized) 212 GlobalParser->updateArgStr(this, S); 213 ArgStr = S; 214 } 215 216 // This collects the different option categories that have been registered. 217 typedef SmallPtrSet<OptionCategory *, 16> OptionCatSet; 218 static ManagedStatic<OptionCatSet> RegisteredOptionCategories; 219 220 // Initialise the general option category. 221 OptionCategory llvm::cl::GeneralCategory("General options"); 222 223 void OptionCategory::registerCategory() { 224 assert(std::count_if(RegisteredOptionCategories->begin(), 225 RegisteredOptionCategories->end(), 226 [this](const OptionCategory *Category) { 227 return getName() == Category->getName(); 228 }) == 0 && 229 "Duplicate option categories"); 230 231 RegisteredOptionCategories->insert(this); 232 } 233 234 //===----------------------------------------------------------------------===// 235 // Basic, shared command line option processing machinery. 236 // 237 238 /// LookupOption - Lookup the option specified by the specified option on the 239 /// command line. If there is a value specified (after an equal sign) return 240 /// that as well. This assumes that leading dashes have already been stripped. 241 static Option *LookupOption(StringRef &Arg, StringRef &Value, 242 const StringMap<Option *> &OptionsMap) { 243 // Reject all dashes. 244 if (Arg.empty()) 245 return nullptr; 246 247 size_t EqualPos = Arg.find('='); 248 249 // If we have an equals sign, remember the value. 250 if (EqualPos == StringRef::npos) { 251 // Look up the option. 252 StringMap<Option *>::const_iterator I = OptionsMap.find(Arg); 253 return I != OptionsMap.end() ? I->second : nullptr; 254 } 255 256 // If the argument before the = is a valid option name, we match. If not, 257 // return Arg unmolested. 258 StringMap<Option *>::const_iterator I = 259 OptionsMap.find(Arg.substr(0, EqualPos)); 260 if (I == OptionsMap.end()) 261 return nullptr; 262 263 Value = Arg.substr(EqualPos + 1); 264 Arg = Arg.substr(0, EqualPos); 265 return I->second; 266 } 267 268 /// LookupNearestOption - Lookup the closest match to the option specified by 269 /// the specified option on the command line. If there is a value specified 270 /// (after an equal sign) return that as well. This assumes that leading dashes 271 /// have already been stripped. 272 static Option *LookupNearestOption(StringRef Arg, 273 const StringMap<Option *> &OptionsMap, 274 std::string &NearestString) { 275 // Reject all dashes. 276 if (Arg.empty()) 277 return nullptr; 278 279 // Split on any equal sign. 280 std::pair<StringRef, StringRef> SplitArg = Arg.split('='); 281 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present. 282 StringRef &RHS = SplitArg.second; 283 284 // Find the closest match. 285 Option *Best = nullptr; 286 unsigned BestDistance = 0; 287 for (StringMap<Option *>::const_iterator it = OptionsMap.begin(), 288 ie = OptionsMap.end(); 289 it != ie; ++it) { 290 Option *O = it->second; 291 SmallVector<const char *, 16> OptionNames; 292 O->getExtraOptionNames(OptionNames); 293 if (O->ArgStr[0]) 294 OptionNames.push_back(O->ArgStr); 295 296 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed; 297 StringRef Flag = PermitValue ? LHS : Arg; 298 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) { 299 StringRef Name = OptionNames[i]; 300 unsigned Distance = StringRef(Name).edit_distance( 301 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance); 302 if (!Best || Distance < BestDistance) { 303 Best = O; 304 BestDistance = Distance; 305 if (RHS.empty() || !PermitValue) 306 NearestString = OptionNames[i]; 307 else 308 NearestString = std::string(OptionNames[i]) + "=" + RHS.str(); 309 } 310 } 311 } 312 313 return Best; 314 } 315 316 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence() 317 /// that does special handling of cl::CommaSeparated options. 318 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos, 319 StringRef ArgName, StringRef Value, 320 bool MultiArg = false) { 321 // Check to see if this option accepts a comma separated list of values. If 322 // it does, we have to split up the value into multiple values. 323 if (Handler->getMiscFlags() & CommaSeparated) { 324 StringRef Val(Value); 325 StringRef::size_type Pos = Val.find(','); 326 327 while (Pos != StringRef::npos) { 328 // Process the portion before the comma. 329 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg)) 330 return true; 331 // Erase the portion before the comma, AND the comma. 332 Val = Val.substr(Pos + 1); 333 Value.substr(Pos + 1); // Increment the original value pointer as well. 334 // Check for another comma. 335 Pos = Val.find(','); 336 } 337 338 Value = Val; 339 } 340 341 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg)) 342 return true; 343 344 return false; 345 } 346 347 /// ProvideOption - For Value, this differentiates between an empty value ("") 348 /// and a null value (StringRef()). The later is accepted for arguments that 349 /// don't allow a value (-foo) the former is rejected (-foo=). 350 static inline bool ProvideOption(Option *Handler, StringRef ArgName, 351 StringRef Value, int argc, 352 const char *const *argv, int &i) { 353 // Is this a multi-argument option? 354 unsigned NumAdditionalVals = Handler->getNumAdditionalVals(); 355 356 // Enforce value requirements 357 switch (Handler->getValueExpectedFlag()) { 358 case ValueRequired: 359 if (!Value.data()) { // No value specified? 360 if (i + 1 >= argc) 361 return Handler->error("requires a value!"); 362 // Steal the next argument, like for '-o filename' 363 assert(argv && "null check"); 364 Value = argv[++i]; 365 } 366 break; 367 case ValueDisallowed: 368 if (NumAdditionalVals > 0) 369 return Handler->error("multi-valued option specified" 370 " with ValueDisallowed modifier!"); 371 372 if (Value.data()) 373 return Handler->error("does not allow a value! '" + Twine(Value) + 374 "' specified."); 375 break; 376 case ValueOptional: 377 break; 378 } 379 380 // If this isn't a multi-arg option, just run the handler. 381 if (NumAdditionalVals == 0) 382 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value); 383 384 // If it is, run the handle several times. 385 bool MultiArg = false; 386 387 if (Value.data()) { 388 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg)) 389 return true; 390 --NumAdditionalVals; 391 MultiArg = true; 392 } 393 394 while (NumAdditionalVals > 0) { 395 if (i + 1 >= argc) 396 return Handler->error("not enough values!"); 397 assert(argv && "null check"); 398 Value = argv[++i]; 399 400 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg)) 401 return true; 402 MultiArg = true; 403 --NumAdditionalVals; 404 } 405 return false; 406 } 407 408 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) { 409 int Dummy = i; 410 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy); 411 } 412 413 // Option predicates... 414 static inline bool isGrouping(const Option *O) { 415 return O->getFormattingFlag() == cl::Grouping; 416 } 417 static inline bool isPrefixedOrGrouping(const Option *O) { 418 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix; 419 } 420 421 // getOptionPred - Check to see if there are any options that satisfy the 422 // specified predicate with names that are the prefixes in Name. This is 423 // checked by progressively stripping characters off of the name, checking to 424 // see if there options that satisfy the predicate. If we find one, return it, 425 // otherwise return null. 426 // 427 static Option *getOptionPred(StringRef Name, size_t &Length, 428 bool (*Pred)(const Option *), 429 const StringMap<Option *> &OptionsMap) { 430 431 StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name); 432 433 // Loop while we haven't found an option and Name still has at least two 434 // characters in it (so that the next iteration will not be the empty 435 // string. 436 while (OMI == OptionsMap.end() && Name.size() > 1) { 437 Name = Name.substr(0, Name.size() - 1); // Chop off the last character. 438 OMI = OptionsMap.find(Name); 439 } 440 441 if (OMI != OptionsMap.end() && Pred(OMI->second)) { 442 Length = Name.size(); 443 return OMI->second; // Found one! 444 } 445 return nullptr; // No option found! 446 } 447 448 /// HandlePrefixedOrGroupedOption - The specified argument string (which started 449 /// with at least one '-') does not fully match an available option. Check to 450 /// see if this is a prefix or grouped option. If so, split arg into output an 451 /// Arg/Value pair and return the Option to parse it with. 452 static Option * 453 HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value, 454 bool &ErrorParsing, 455 const StringMap<Option *> &OptionsMap) { 456 if (Arg.size() == 1) 457 return nullptr; 458 459 // Do the lookup! 460 size_t Length = 0; 461 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap); 462 if (!PGOpt) 463 return nullptr; 464 465 // If the option is a prefixed option, then the value is simply the 466 // rest of the name... so fall through to later processing, by 467 // setting up the argument name flags and value fields. 468 if (PGOpt->getFormattingFlag() == cl::Prefix) { 469 Value = Arg.substr(Length); 470 Arg = Arg.substr(0, Length); 471 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt); 472 return PGOpt; 473 } 474 475 // This must be a grouped option... handle them now. Grouping options can't 476 // have values. 477 assert(isGrouping(PGOpt) && "Broken getOptionPred!"); 478 479 do { 480 // Move current arg name out of Arg into OneArgName. 481 StringRef OneArgName = Arg.substr(0, Length); 482 Arg = Arg.substr(Length); 483 484 // Because ValueRequired is an invalid flag for grouped arguments, 485 // we don't need to pass argc/argv in. 486 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired && 487 "Option can not be cl::Grouping AND cl::ValueRequired!"); 488 int Dummy = 0; 489 ErrorParsing |= 490 ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy); 491 492 // Get the next grouping option. 493 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap); 494 } while (PGOpt && Length != Arg.size()); 495 496 // Return the last option with Arg cut down to just the last one. 497 return PGOpt; 498 } 499 500 static bool RequiresValue(const Option *O) { 501 return O->getNumOccurrencesFlag() == cl::Required || 502 O->getNumOccurrencesFlag() == cl::OneOrMore; 503 } 504 505 static bool EatsUnboundedNumberOfValues(const Option *O) { 506 return O->getNumOccurrencesFlag() == cl::ZeroOrMore || 507 O->getNumOccurrencesFlag() == cl::OneOrMore; 508 } 509 510 static bool isWhitespace(char C) { return strchr(" \t\n\r\f\v", C); } 511 512 static bool isQuote(char C) { return C == '\"' || C == '\''; } 513 514 static bool isGNUSpecial(char C) { return strchr("\\\"\' ", C); } 515 516 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver, 517 SmallVectorImpl<const char *> &NewArgv, 518 bool MarkEOLs) { 519 SmallString<128> Token; 520 for (size_t I = 0, E = Src.size(); I != E; ++I) { 521 // Consume runs of whitespace. 522 if (Token.empty()) { 523 while (I != E && isWhitespace(Src[I])) { 524 // Mark the end of lines in response files 525 if (MarkEOLs && Src[I] == '\n') 526 NewArgv.push_back(nullptr); 527 ++I; 528 } 529 if (I == E) 530 break; 531 } 532 533 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise 534 // they are literal. This makes it much easier to read Windows file paths. 535 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) { 536 ++I; // Skip the escape. 537 Token.push_back(Src[I]); 538 continue; 539 } 540 541 // Consume a quoted string. 542 if (isQuote(Src[I])) { 543 char Quote = Src[I++]; 544 while (I != E && Src[I] != Quote) { 545 // Backslashes are literal, unless they escape a special character. 546 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1])) 547 ++I; 548 Token.push_back(Src[I]); 549 ++I; 550 } 551 if (I == E) 552 break; 553 continue; 554 } 555 556 // End the token if this is whitespace. 557 if (isWhitespace(Src[I])) { 558 if (!Token.empty()) 559 NewArgv.push_back(Saver.SaveString(Token.c_str())); 560 Token.clear(); 561 continue; 562 } 563 564 // This is a normal character. Append it. 565 Token.push_back(Src[I]); 566 } 567 568 // Append the last token after hitting EOF with no whitespace. 569 if (!Token.empty()) 570 NewArgv.push_back(Saver.SaveString(Token.c_str())); 571 // Mark the end of response files 572 if (MarkEOLs) 573 NewArgv.push_back(nullptr); 574 } 575 576 /// Backslashes are interpreted in a rather complicated way in the Windows-style 577 /// command line, because backslashes are used both to separate path and to 578 /// escape double quote. This method consumes runs of backslashes as well as the 579 /// following double quote if it's escaped. 580 /// 581 /// * If an even number of backslashes is followed by a double quote, one 582 /// backslash is output for every pair of backslashes, and the last double 583 /// quote remains unconsumed. The double quote will later be interpreted as 584 /// the start or end of a quoted string in the main loop outside of this 585 /// function. 586 /// 587 /// * If an odd number of backslashes is followed by a double quote, one 588 /// backslash is output for every pair of backslashes, and a double quote is 589 /// output for the last pair of backslash-double quote. The double quote is 590 /// consumed in this case. 591 /// 592 /// * Otherwise, backslashes are interpreted literally. 593 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) { 594 size_t E = Src.size(); 595 int BackslashCount = 0; 596 // Skip the backslashes. 597 do { 598 ++I; 599 ++BackslashCount; 600 } while (I != E && Src[I] == '\\'); 601 602 bool FollowedByDoubleQuote = (I != E && Src[I] == '"'); 603 if (FollowedByDoubleQuote) { 604 Token.append(BackslashCount / 2, '\\'); 605 if (BackslashCount % 2 == 0) 606 return I - 1; 607 Token.push_back('"'); 608 return I; 609 } 610 Token.append(BackslashCount, '\\'); 611 return I - 1; 612 } 613 614 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver, 615 SmallVectorImpl<const char *> &NewArgv, 616 bool MarkEOLs) { 617 SmallString<128> Token; 618 619 // This is a small state machine to consume characters until it reaches the 620 // end of the source string. 621 enum { INIT, UNQUOTED, QUOTED } State = INIT; 622 for (size_t I = 0, E = Src.size(); I != E; ++I) { 623 // INIT state indicates that the current input index is at the start of 624 // the string or between tokens. 625 if (State == INIT) { 626 if (isWhitespace(Src[I])) { 627 // Mark the end of lines in response files 628 if (MarkEOLs && Src[I] == '\n') 629 NewArgv.push_back(nullptr); 630 continue; 631 } 632 if (Src[I] == '"') { 633 State = QUOTED; 634 continue; 635 } 636 if (Src[I] == '\\') { 637 I = parseBackslash(Src, I, Token); 638 State = UNQUOTED; 639 continue; 640 } 641 Token.push_back(Src[I]); 642 State = UNQUOTED; 643 continue; 644 } 645 646 // UNQUOTED state means that it's reading a token not quoted by double 647 // quotes. 648 if (State == UNQUOTED) { 649 // Whitespace means the end of the token. 650 if (isWhitespace(Src[I])) { 651 NewArgv.push_back(Saver.SaveString(Token.c_str())); 652 Token.clear(); 653 State = INIT; 654 // Mark the end of lines in response files 655 if (MarkEOLs && Src[I] == '\n') 656 NewArgv.push_back(nullptr); 657 continue; 658 } 659 if (Src[I] == '"') { 660 State = QUOTED; 661 continue; 662 } 663 if (Src[I] == '\\') { 664 I = parseBackslash(Src, I, Token); 665 continue; 666 } 667 Token.push_back(Src[I]); 668 continue; 669 } 670 671 // QUOTED state means that it's reading a token quoted by double quotes. 672 if (State == QUOTED) { 673 if (Src[I] == '"') { 674 State = UNQUOTED; 675 continue; 676 } 677 if (Src[I] == '\\') { 678 I = parseBackslash(Src, I, Token); 679 continue; 680 } 681 Token.push_back(Src[I]); 682 } 683 } 684 // Append the last token after hitting EOF with no whitespace. 685 if (!Token.empty()) 686 NewArgv.push_back(Saver.SaveString(Token.c_str())); 687 // Mark the end of response files 688 if (MarkEOLs) 689 NewArgv.push_back(nullptr); 690 } 691 692 // It is called byte order marker but the UTF-8 BOM is actually not affected 693 // by the host system's endianness. 694 static bool hasUTF8ByteOrderMark(ArrayRef<char> S) { 695 return (S.size() >= 3 && 696 S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf'); 697 } 698 699 static bool ExpandResponseFile(const char *FName, StringSaver &Saver, 700 TokenizerCallback Tokenizer, 701 SmallVectorImpl<const char *> &NewArgv, 702 bool MarkEOLs = false) { 703 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr = 704 MemoryBuffer::getFile(FName); 705 if (!MemBufOrErr) 706 return false; 707 MemoryBuffer &MemBuf = *MemBufOrErr.get(); 708 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize()); 709 710 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing. 711 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd()); 712 std::string UTF8Buf; 713 if (hasUTF16ByteOrderMark(BufRef)) { 714 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf)) 715 return false; 716 Str = StringRef(UTF8Buf); 717 } 718 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove 719 // these bytes before parsing. 720 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark 721 else if (hasUTF8ByteOrderMark(BufRef)) 722 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3); 723 724 // Tokenize the contents into NewArgv. 725 Tokenizer(Str, Saver, NewArgv, MarkEOLs); 726 727 return true; 728 } 729 730 /// \brief Expand response files on a command line recursively using the given 731 /// StringSaver and tokenization strategy. 732 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer, 733 SmallVectorImpl<const char *> &Argv, 734 bool MarkEOLs) { 735 unsigned RspFiles = 0; 736 bool AllExpanded = true; 737 738 // Don't cache Argv.size() because it can change. 739 for (unsigned I = 0; I != Argv.size();) { 740 const char *Arg = Argv[I]; 741 // Check if it is an EOL marker 742 if (Arg == nullptr) { 743 ++I; 744 continue; 745 } 746 if (Arg[0] != '@') { 747 ++I; 748 continue; 749 } 750 751 // If we have too many response files, leave some unexpanded. This avoids 752 // crashing on self-referential response files. 753 if (RspFiles++ > 20) 754 return false; 755 756 // Replace this response file argument with the tokenization of its 757 // contents. Nested response files are expanded in subsequent iterations. 758 // FIXME: If a nested response file uses a relative path, is it relative to 759 // the cwd of the process or the response file? 760 SmallVector<const char *, 0> ExpandedArgv; 761 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv, 762 MarkEOLs)) { 763 // We couldn't read this file, so we leave it in the argument stream and 764 // move on. 765 AllExpanded = false; 766 ++I; 767 continue; 768 } 769 Argv.erase(Argv.begin() + I); 770 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end()); 771 } 772 return AllExpanded; 773 } 774 775 namespace { 776 class StrDupSaver : public StringSaver { 777 std::vector<char *> Dups; 778 779 public: 780 ~StrDupSaver() { 781 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end(); I != E; 782 ++I) { 783 char *Dup = *I; 784 free(Dup); 785 } 786 } 787 const char *SaveString(const char *Str) override { 788 char *Dup = strdup(Str); 789 Dups.push_back(Dup); 790 return Dup; 791 } 792 }; 793 } 794 795 /// ParseEnvironmentOptions - An alternative entry point to the 796 /// CommandLine library, which allows you to read the program's name 797 /// from the caller (as PROGNAME) and its command-line arguments from 798 /// an environment variable (whose name is given in ENVVAR). 799 /// 800 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar, 801 const char *Overview) { 802 // Check args. 803 assert(progName && "Program name not specified"); 804 assert(envVar && "Environment variable name missing"); 805 806 // Get the environment variable they want us to parse options out of. 807 const char *envValue = getenv(envVar); 808 if (!envValue) 809 return; 810 811 // Get program's "name", which we wouldn't know without the caller 812 // telling us. 813 SmallVector<const char *, 20> newArgv; 814 StrDupSaver Saver; 815 newArgv.push_back(Saver.SaveString(progName)); 816 817 // Parse the value of the environment variable into a "command line" 818 // and hand it off to ParseCommandLineOptions(). 819 TokenizeGNUCommandLine(envValue, Saver, newArgv); 820 int newArgc = static_cast<int>(newArgv.size()); 821 ParseCommandLineOptions(newArgc, &newArgv[0], Overview); 822 } 823 824 void cl::ParseCommandLineOptions(int argc, const char *const *argv, 825 const char *Overview) { 826 GlobalParser->ParseCommandLineOptions(argc, argv, Overview); 827 } 828 829 void CommandLineParser::ParseCommandLineOptions(int argc, 830 const char *const *argv, 831 const char *Overview) { 832 assert(hasOptions() && "No options specified!"); 833 834 // Expand response files. 835 SmallVector<const char *, 20> newArgv; 836 for (int i = 0; i != argc; ++i) 837 newArgv.push_back(argv[i]); 838 StrDupSaver Saver; 839 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv); 840 argv = &newArgv[0]; 841 argc = static_cast<int>(newArgv.size()); 842 843 // Copy the program name into ProgName, making sure not to overflow it. 844 ProgramName = sys::path::filename(argv[0]); 845 846 ProgramOverview = Overview; 847 bool ErrorParsing = false; 848 849 // Check out the positional arguments to collect information about them. 850 unsigned NumPositionalRequired = 0; 851 852 // Determine whether or not there are an unlimited number of positionals 853 bool HasUnlimitedPositionals = false; 854 855 if (ConsumeAfterOpt) { 856 assert(PositionalOpts.size() > 0 && 857 "Cannot specify cl::ConsumeAfter without a positional argument!"); 858 } 859 if (!PositionalOpts.empty()) { 860 861 // Calculate how many positional values are _required_. 862 bool UnboundedFound = false; 863 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) { 864 Option *Opt = PositionalOpts[i]; 865 if (RequiresValue(Opt)) 866 ++NumPositionalRequired; 867 else if (ConsumeAfterOpt) { 868 // ConsumeAfter cannot be combined with "optional" positional options 869 // unless there is only one positional argument... 870 if (PositionalOpts.size() > 1) 871 ErrorParsing |= Opt->error( 872 "error - this positional option will never be matched, " 873 "because it does not Require a value, and a " 874 "cl::ConsumeAfter option is active!"); 875 } else if (UnboundedFound && !Opt->ArgStr[0]) { 876 // This option does not "require" a value... Make sure this option is 877 // not specified after an option that eats all extra arguments, or this 878 // one will never get any! 879 // 880 ErrorParsing |= Opt->error("error - option can never match, because " 881 "another positional argument will match an " 882 "unbounded number of values, and this option" 883 " does not require a value!"); 884 errs() << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr 885 << "' is all messed up!\n"; 886 errs() << PositionalOpts.size(); 887 } 888 UnboundedFound |= EatsUnboundedNumberOfValues(Opt); 889 } 890 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt; 891 } 892 893 // PositionalVals - A vector of "positional" arguments we accumulate into 894 // the process at the end. 895 // 896 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals; 897 898 // If the program has named positional arguments, and the name has been run 899 // across, keep track of which positional argument was named. Otherwise put 900 // the positional args into the PositionalVals list... 901 Option *ActivePositionalArg = nullptr; 902 903 // Loop over all of the arguments... processing them. 904 bool DashDashFound = false; // Have we read '--'? 905 for (int i = 1; i < argc; ++i) { 906 Option *Handler = nullptr; 907 Option *NearestHandler = nullptr; 908 std::string NearestHandlerString; 909 StringRef Value; 910 StringRef ArgName = ""; 911 912 // Check to see if this is a positional argument. This argument is 913 // considered to be positional if it doesn't start with '-', if it is "-" 914 // itself, or if we have seen "--" already. 915 // 916 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) { 917 // Positional argument! 918 if (ActivePositionalArg) { 919 ProvidePositionalOption(ActivePositionalArg, argv[i], i); 920 continue; // We are done! 921 } 922 923 if (!PositionalOpts.empty()) { 924 PositionalVals.push_back(std::make_pair(argv[i], i)); 925 926 // All of the positional arguments have been fulfulled, give the rest to 927 // the consume after option... if it's specified... 928 // 929 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) { 930 for (++i; i < argc; ++i) 931 PositionalVals.push_back(std::make_pair(argv[i], i)); 932 break; // Handle outside of the argument processing loop... 933 } 934 935 // Delay processing positional arguments until the end... 936 continue; 937 } 938 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 && 939 !DashDashFound) { 940 DashDashFound = true; // This is the mythical "--"? 941 continue; // Don't try to process it as an argument itself. 942 } else if (ActivePositionalArg && 943 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) { 944 // If there is a positional argument eating options, check to see if this 945 // option is another positional argument. If so, treat it as an argument, 946 // otherwise feed it to the eating positional. 947 ArgName = argv[i] + 1; 948 // Eat leading dashes. 949 while (!ArgName.empty() && ArgName[0] == '-') 950 ArgName = ArgName.substr(1); 951 952 Handler = LookupOption(ArgName, Value, OptionsMap); 953 if (!Handler || Handler->getFormattingFlag() != cl::Positional) { 954 ProvidePositionalOption(ActivePositionalArg, argv[i], i); 955 continue; // We are done! 956 } 957 958 } else { // We start with a '-', must be an argument. 959 ArgName = argv[i] + 1; 960 // Eat leading dashes. 961 while (!ArgName.empty() && ArgName[0] == '-') 962 ArgName = ArgName.substr(1); 963 964 Handler = LookupOption(ArgName, Value, OptionsMap); 965 966 // Check to see if this "option" is really a prefixed or grouped argument. 967 if (!Handler) 968 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing, 969 OptionsMap); 970 971 // Otherwise, look for the closest available option to report to the user 972 // in the upcoming error. 973 if (!Handler && SinkOpts.empty()) 974 NearestHandler = 975 LookupNearestOption(ArgName, OptionsMap, NearestHandlerString); 976 } 977 978 if (!Handler) { 979 if (SinkOpts.empty()) { 980 errs() << ProgramName << ": Unknown command line argument '" << argv[i] 981 << "'. Try: '" << argv[0] << " -help'\n"; 982 983 if (NearestHandler) { 984 // If we know a near match, report it as well. 985 errs() << ProgramName << ": Did you mean '-" << NearestHandlerString 986 << "'?\n"; 987 } 988 989 ErrorParsing = true; 990 } else { 991 for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(), 992 E = SinkOpts.end(); 993 I != E; ++I) 994 (*I)->addOccurrence(i, "", argv[i]); 995 } 996 continue; 997 } 998 999 // If this is a named positional argument, just remember that it is the 1000 // active one... 1001 if (Handler->getFormattingFlag() == cl::Positional) 1002 ActivePositionalArg = Handler; 1003 else 1004 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i); 1005 } 1006 1007 // Check and handle positional arguments now... 1008 if (NumPositionalRequired > PositionalVals.size()) { 1009 errs() << ProgramName 1010 << ": Not enough positional command line arguments specified!\n" 1011 << "Must specify at least " << NumPositionalRequired 1012 << " positional arguments: See: " << argv[0] << " -help\n"; 1013 1014 ErrorParsing = true; 1015 } else if (!HasUnlimitedPositionals && 1016 PositionalVals.size() > PositionalOpts.size()) { 1017 errs() << ProgramName << ": Too many positional arguments specified!\n" 1018 << "Can specify at most " << PositionalOpts.size() 1019 << " positional arguments: See: " << argv[0] << " -help\n"; 1020 ErrorParsing = true; 1021 1022 } else if (!ConsumeAfterOpt) { 1023 // Positional args have already been handled if ConsumeAfter is specified. 1024 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size()); 1025 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) { 1026 if (RequiresValue(PositionalOpts[i])) { 1027 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first, 1028 PositionalVals[ValNo].second); 1029 ValNo++; 1030 --NumPositionalRequired; // We fulfilled our duty... 1031 } 1032 1033 // If we _can_ give this option more arguments, do so now, as long as we 1034 // do not give it values that others need. 'Done' controls whether the 1035 // option even _WANTS_ any more. 1036 // 1037 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required; 1038 while (NumVals - ValNo > NumPositionalRequired && !Done) { 1039 switch (PositionalOpts[i]->getNumOccurrencesFlag()) { 1040 case cl::Optional: 1041 Done = true; // Optional arguments want _at most_ one value 1042 // FALL THROUGH 1043 case cl::ZeroOrMore: // Zero or more will take all they can get... 1044 case cl::OneOrMore: // One or more will take all they can get... 1045 ProvidePositionalOption(PositionalOpts[i], 1046 PositionalVals[ValNo].first, 1047 PositionalVals[ValNo].second); 1048 ValNo++; 1049 break; 1050 default: 1051 llvm_unreachable("Internal error, unexpected NumOccurrences flag in " 1052 "positional argument processing!"); 1053 } 1054 } 1055 } 1056 } else { 1057 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size()); 1058 unsigned ValNo = 0; 1059 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j) 1060 if (RequiresValue(PositionalOpts[j])) { 1061 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j], 1062 PositionalVals[ValNo].first, 1063 PositionalVals[ValNo].second); 1064 ValNo++; 1065 } 1066 1067 // Handle the case where there is just one positional option, and it's 1068 // optional. In this case, we want to give JUST THE FIRST option to the 1069 // positional option and keep the rest for the consume after. The above 1070 // loop would have assigned no values to positional options in this case. 1071 // 1072 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) { 1073 ErrorParsing |= ProvidePositionalOption(PositionalOpts[0], 1074 PositionalVals[ValNo].first, 1075 PositionalVals[ValNo].second); 1076 ValNo++; 1077 } 1078 1079 // Handle over all of the rest of the arguments to the 1080 // cl::ConsumeAfter command line option... 1081 for (; ValNo != PositionalVals.size(); ++ValNo) 1082 ErrorParsing |= 1083 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first, 1084 PositionalVals[ValNo].second); 1085 } 1086 1087 // Loop over args and make sure all required args are specified! 1088 for (const auto &Opt : OptionsMap) { 1089 switch (Opt.second->getNumOccurrencesFlag()) { 1090 case Required: 1091 case OneOrMore: 1092 if (Opt.second->getNumOccurrences() == 0) { 1093 Opt.second->error("must be specified at least once!"); 1094 ErrorParsing = true; 1095 } 1096 // Fall through 1097 default: 1098 break; 1099 } 1100 } 1101 1102 // Now that we know if -debug is specified, we can use it. 1103 // Note that if ReadResponseFiles == true, this must be done before the 1104 // memory allocated for the expanded command line is free()d below. 1105 DEBUG(dbgs() << "Args: "; 1106 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' '; 1107 dbgs() << '\n';); 1108 1109 // Free all of the memory allocated to the map. Command line options may only 1110 // be processed once! 1111 MoreHelp.clear(); 1112 1113 // If we had an error processing our arguments, don't let the program execute 1114 if (ErrorParsing) 1115 exit(1); 1116 } 1117 1118 //===----------------------------------------------------------------------===// 1119 // Option Base class implementation 1120 // 1121 1122 bool Option::error(const Twine &Message, StringRef ArgName) { 1123 if (!ArgName.data()) 1124 ArgName = ArgStr; 1125 if (ArgName.empty()) 1126 errs() << HelpStr; // Be nice for positional arguments 1127 else 1128 errs() << GlobalParser->ProgramName << ": for the -" << ArgName; 1129 1130 errs() << " option: " << Message << "\n"; 1131 return true; 1132 } 1133 1134 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value, 1135 bool MultiArg) { 1136 if (!MultiArg) 1137 NumOccurrences++; // Increment the number of times we have been seen 1138 1139 switch (getNumOccurrencesFlag()) { 1140 case Optional: 1141 if (NumOccurrences > 1) 1142 return error("may only occur zero or one times!", ArgName); 1143 break; 1144 case Required: 1145 if (NumOccurrences > 1) 1146 return error("must occur exactly one time!", ArgName); 1147 // Fall through 1148 case OneOrMore: 1149 case ZeroOrMore: 1150 case ConsumeAfter: 1151 break; 1152 } 1153 1154 return handleOccurrence(pos, ArgName, Value); 1155 } 1156 1157 // getValueStr - Get the value description string, using "DefaultMsg" if nothing 1158 // has been specified yet. 1159 // 1160 static const char *getValueStr(const Option &O, const char *DefaultMsg) { 1161 if (O.ValueStr[0] == 0) 1162 return DefaultMsg; 1163 return O.ValueStr; 1164 } 1165 1166 //===----------------------------------------------------------------------===// 1167 // cl::alias class implementation 1168 // 1169 1170 // Return the width of the option tag for printing... 1171 size_t alias::getOptionWidth() const { return std::strlen(ArgStr) + 6; } 1172 1173 static void printHelpStr(StringRef HelpStr, size_t Indent, 1174 size_t FirstLineIndentedBy) { 1175 std::pair<StringRef, StringRef> Split = HelpStr.split('\n'); 1176 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n"; 1177 while (!Split.second.empty()) { 1178 Split = Split.second.split('\n'); 1179 outs().indent(Indent) << Split.first << "\n"; 1180 } 1181 } 1182 1183 // Print out the option for the alias. 1184 void alias::printOptionInfo(size_t GlobalWidth) const { 1185 outs() << " -" << ArgStr; 1186 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6); 1187 } 1188 1189 //===----------------------------------------------------------------------===// 1190 // Parser Implementation code... 1191 // 1192 1193 // basic_parser implementation 1194 // 1195 1196 // Return the width of the option tag for printing... 1197 size_t basic_parser_impl::getOptionWidth(const Option &O) const { 1198 size_t Len = std::strlen(O.ArgStr); 1199 if (const char *ValName = getValueName()) 1200 Len += std::strlen(getValueStr(O, ValName)) + 3; 1201 1202 return Len + 6; 1203 } 1204 1205 // printOptionInfo - Print out information about this option. The 1206 // to-be-maintained width is specified. 1207 // 1208 void basic_parser_impl::printOptionInfo(const Option &O, 1209 size_t GlobalWidth) const { 1210 outs() << " -" << O.ArgStr; 1211 1212 if (const char *ValName = getValueName()) 1213 outs() << "=<" << getValueStr(O, ValName) << '>'; 1214 1215 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O)); 1216 } 1217 1218 void basic_parser_impl::printOptionName(const Option &O, 1219 size_t GlobalWidth) const { 1220 outs() << " -" << O.ArgStr; 1221 outs().indent(GlobalWidth - std::strlen(O.ArgStr)); 1222 } 1223 1224 // parser<bool> implementation 1225 // 1226 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg, 1227 bool &Value) { 1228 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 1229 Arg == "1") { 1230 Value = true; 1231 return false; 1232 } 1233 1234 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") { 1235 Value = false; 1236 return false; 1237 } 1238 return O.error("'" + Arg + 1239 "' is invalid value for boolean argument! Try 0 or 1"); 1240 } 1241 1242 // parser<boolOrDefault> implementation 1243 // 1244 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg, 1245 boolOrDefault &Value) { 1246 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 1247 Arg == "1") { 1248 Value = BOU_TRUE; 1249 return false; 1250 } 1251 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") { 1252 Value = BOU_FALSE; 1253 return false; 1254 } 1255 1256 return O.error("'" + Arg + 1257 "' is invalid value for boolean argument! Try 0 or 1"); 1258 } 1259 1260 // parser<int> implementation 1261 // 1262 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg, 1263 int &Value) { 1264 if (Arg.getAsInteger(0, Value)) 1265 return O.error("'" + Arg + "' value invalid for integer argument!"); 1266 return false; 1267 } 1268 1269 // parser<unsigned> implementation 1270 // 1271 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg, 1272 unsigned &Value) { 1273 1274 if (Arg.getAsInteger(0, Value)) 1275 return O.error("'" + Arg + "' value invalid for uint argument!"); 1276 return false; 1277 } 1278 1279 // parser<unsigned long long> implementation 1280 // 1281 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName, 1282 StringRef Arg, 1283 unsigned long long &Value) { 1284 1285 if (Arg.getAsInteger(0, Value)) 1286 return O.error("'" + Arg + "' value invalid for uint argument!"); 1287 return false; 1288 } 1289 1290 // parser<double>/parser<float> implementation 1291 // 1292 static bool parseDouble(Option &O, StringRef Arg, double &Value) { 1293 SmallString<32> TmpStr(Arg.begin(), Arg.end()); 1294 const char *ArgStart = TmpStr.c_str(); 1295 char *End; 1296 Value = strtod(ArgStart, &End); 1297 if (*End != 0) 1298 return O.error("'" + Arg + "' value invalid for floating point argument!"); 1299 return false; 1300 } 1301 1302 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg, 1303 double &Val) { 1304 return parseDouble(O, Arg, Val); 1305 } 1306 1307 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg, 1308 float &Val) { 1309 double dVal; 1310 if (parseDouble(O, Arg, dVal)) 1311 return true; 1312 Val = (float)dVal; 1313 return false; 1314 } 1315 1316 // generic_parser_base implementation 1317 // 1318 1319 // findOption - Return the option number corresponding to the specified 1320 // argument string. If the option is not found, getNumOptions() is returned. 1321 // 1322 unsigned generic_parser_base::findOption(const char *Name) { 1323 unsigned e = getNumOptions(); 1324 1325 for (unsigned i = 0; i != e; ++i) { 1326 if (strcmp(getOption(i), Name) == 0) 1327 return i; 1328 } 1329 return e; 1330 } 1331 1332 // Return the width of the option tag for printing... 1333 size_t generic_parser_base::getOptionWidth(const Option &O) const { 1334 if (O.hasArgStr()) { 1335 size_t Size = std::strlen(O.ArgStr) + 6; 1336 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) 1337 Size = std::max(Size, std::strlen(getOption(i)) + 8); 1338 return Size; 1339 } else { 1340 size_t BaseSize = 0; 1341 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) 1342 BaseSize = std::max(BaseSize, std::strlen(getOption(i)) + 8); 1343 return BaseSize; 1344 } 1345 } 1346 1347 // printOptionInfo - Print out information about this option. The 1348 // to-be-maintained width is specified. 1349 // 1350 void generic_parser_base::printOptionInfo(const Option &O, 1351 size_t GlobalWidth) const { 1352 if (O.hasArgStr()) { 1353 outs() << " -" << O.ArgStr; 1354 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6); 1355 1356 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 1357 size_t NumSpaces = GlobalWidth - strlen(getOption(i)) - 8; 1358 outs() << " =" << getOption(i); 1359 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n'; 1360 } 1361 } else { 1362 if (O.HelpStr[0]) 1363 outs() << " " << O.HelpStr << '\n'; 1364 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 1365 const char *Option = getOption(i); 1366 outs() << " -" << Option; 1367 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8); 1368 } 1369 } 1370 } 1371 1372 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff 1373 1374 // printGenericOptionDiff - Print the value of this option and it's default. 1375 // 1376 // "Generic" options have each value mapped to a name. 1377 void generic_parser_base::printGenericOptionDiff( 1378 const Option &O, const GenericOptionValue &Value, 1379 const GenericOptionValue &Default, size_t GlobalWidth) const { 1380 outs() << " -" << O.ArgStr; 1381 outs().indent(GlobalWidth - std::strlen(O.ArgStr)); 1382 1383 unsigned NumOpts = getNumOptions(); 1384 for (unsigned i = 0; i != NumOpts; ++i) { 1385 if (Value.compare(getOptionValue(i))) 1386 continue; 1387 1388 outs() << "= " << getOption(i); 1389 size_t L = std::strlen(getOption(i)); 1390 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0; 1391 outs().indent(NumSpaces) << " (default: "; 1392 for (unsigned j = 0; j != NumOpts; ++j) { 1393 if (Default.compare(getOptionValue(j))) 1394 continue; 1395 outs() << getOption(j); 1396 break; 1397 } 1398 outs() << ")\n"; 1399 return; 1400 } 1401 outs() << "= *unknown option value*\n"; 1402 } 1403 1404 // printOptionDiff - Specializations for printing basic value types. 1405 // 1406 #define PRINT_OPT_DIFF(T) \ 1407 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \ 1408 size_t GlobalWidth) const { \ 1409 printOptionName(O, GlobalWidth); \ 1410 std::string Str; \ 1411 { \ 1412 raw_string_ostream SS(Str); \ 1413 SS << V; \ 1414 } \ 1415 outs() << "= " << Str; \ 1416 size_t NumSpaces = \ 1417 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \ 1418 outs().indent(NumSpaces) << " (default: "; \ 1419 if (D.hasValue()) \ 1420 outs() << D.getValue(); \ 1421 else \ 1422 outs() << "*no default*"; \ 1423 outs() << ")\n"; \ 1424 } 1425 1426 PRINT_OPT_DIFF(bool) 1427 PRINT_OPT_DIFF(boolOrDefault) 1428 PRINT_OPT_DIFF(int) 1429 PRINT_OPT_DIFF(unsigned) 1430 PRINT_OPT_DIFF(unsigned long long) 1431 PRINT_OPT_DIFF(double) 1432 PRINT_OPT_DIFF(float) 1433 PRINT_OPT_DIFF(char) 1434 1435 void parser<std::string>::printOptionDiff(const Option &O, StringRef V, 1436 OptionValue<std::string> D, 1437 size_t GlobalWidth) const { 1438 printOptionName(O, GlobalWidth); 1439 outs() << "= " << V; 1440 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0; 1441 outs().indent(NumSpaces) << " (default: "; 1442 if (D.hasValue()) 1443 outs() << D.getValue(); 1444 else 1445 outs() << "*no default*"; 1446 outs() << ")\n"; 1447 } 1448 1449 // Print a placeholder for options that don't yet support printOptionDiff(). 1450 void basic_parser_impl::printOptionNoValue(const Option &O, 1451 size_t GlobalWidth) const { 1452 printOptionName(O, GlobalWidth); 1453 outs() << "= *cannot print option value*\n"; 1454 } 1455 1456 //===----------------------------------------------------------------------===// 1457 // -help and -help-hidden option implementation 1458 // 1459 1460 static int OptNameCompare(const void *LHS, const void *RHS) { 1461 typedef std::pair<const char *, Option *> pair_ty; 1462 1463 return strcmp(((const pair_ty *)LHS)->first, ((const pair_ty *)RHS)->first); 1464 } 1465 1466 // Copy Options into a vector so we can sort them as we like. 1467 static void sortOpts(StringMap<Option *> &OptMap, 1468 SmallVectorImpl<std::pair<const char *, Option *>> &Opts, 1469 bool ShowHidden) { 1470 SmallPtrSet<Option *, 128> OptionSet; // Duplicate option detection. 1471 1472 for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end(); 1473 I != E; ++I) { 1474 // Ignore really-hidden options. 1475 if (I->second->getOptionHiddenFlag() == ReallyHidden) 1476 continue; 1477 1478 // Unless showhidden is set, ignore hidden flags. 1479 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden) 1480 continue; 1481 1482 // If we've already seen this option, don't add it to the list again. 1483 if (!OptionSet.insert(I->second).second) 1484 continue; 1485 1486 Opts.push_back( 1487 std::pair<const char *, Option *>(I->getKey().data(), I->second)); 1488 } 1489 1490 // Sort the options list alphabetically. 1491 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare); 1492 } 1493 1494 namespace { 1495 1496 class HelpPrinter { 1497 protected: 1498 const bool ShowHidden; 1499 typedef SmallVector<std::pair<const char *, Option *>, 128> 1500 StrOptionPairVector; 1501 // Print the options. Opts is assumed to be alphabetically sorted. 1502 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) { 1503 for (size_t i = 0, e = Opts.size(); i != e; ++i) 1504 Opts[i].second->printOptionInfo(MaxArgLen); 1505 } 1506 1507 public: 1508 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {} 1509 virtual ~HelpPrinter() {} 1510 1511 // Invoke the printer. 1512 void operator=(bool Value) { 1513 if (Value == false) 1514 return; 1515 1516 StrOptionPairVector Opts; 1517 sortOpts(GlobalParser->OptionsMap, Opts, ShowHidden); 1518 1519 if (GlobalParser->ProgramOverview) 1520 outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n"; 1521 1522 outs() << "USAGE: " << GlobalParser->ProgramName << " [options]"; 1523 1524 for (auto Opt : GlobalParser->PositionalOpts) { 1525 if (Opt->ArgStr[0]) 1526 outs() << " --" << Opt->ArgStr; 1527 outs() << " " << Opt->HelpStr; 1528 } 1529 1530 // Print the consume after option info if it exists... 1531 if (GlobalParser->ConsumeAfterOpt) 1532 outs() << " " << GlobalParser->ConsumeAfterOpt->HelpStr; 1533 1534 outs() << "\n\n"; 1535 1536 // Compute the maximum argument length... 1537 size_t MaxArgLen = 0; 1538 for (size_t i = 0, e = Opts.size(); i != e; ++i) 1539 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth()); 1540 1541 outs() << "OPTIONS:\n"; 1542 printOptions(Opts, MaxArgLen); 1543 1544 // Print any extra help the user has declared. 1545 for (auto I : GlobalParser->MoreHelp) 1546 outs() << I; 1547 GlobalParser->MoreHelp.clear(); 1548 1549 // Halt the program since help information was printed 1550 exit(0); 1551 } 1552 }; 1553 1554 class CategorizedHelpPrinter : public HelpPrinter { 1555 public: 1556 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {} 1557 1558 // Helper function for printOptions(). 1559 // It shall return true if A's name should be lexographically 1560 // ordered before B's name. It returns false otherwise. 1561 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) { 1562 return strcmp(A->getName(), B->getName()) < 0; 1563 } 1564 1565 // Make sure we inherit our base class's operator=() 1566 using HelpPrinter::operator=; 1567 1568 protected: 1569 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override { 1570 std::vector<OptionCategory *> SortedCategories; 1571 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions; 1572 1573 // Collect registered option categories into vector in preparation for 1574 // sorting. 1575 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(), 1576 E = RegisteredOptionCategories->end(); 1577 I != E; ++I) { 1578 SortedCategories.push_back(*I); 1579 } 1580 1581 // Sort the different option categories alphabetically. 1582 assert(SortedCategories.size() > 0 && "No option categories registered!"); 1583 std::sort(SortedCategories.begin(), SortedCategories.end(), 1584 OptionCategoryCompare); 1585 1586 // Create map to empty vectors. 1587 for (std::vector<OptionCategory *>::const_iterator 1588 I = SortedCategories.begin(), 1589 E = SortedCategories.end(); 1590 I != E; ++I) 1591 CategorizedOptions[*I] = std::vector<Option *>(); 1592 1593 // Walk through pre-sorted options and assign into categories. 1594 // Because the options are already alphabetically sorted the 1595 // options within categories will also be alphabetically sorted. 1596 for (size_t I = 0, E = Opts.size(); I != E; ++I) { 1597 Option *Opt = Opts[I].second; 1598 assert(CategorizedOptions.count(Opt->Category) > 0 && 1599 "Option has an unregistered category"); 1600 CategorizedOptions[Opt->Category].push_back(Opt); 1601 } 1602 1603 // Now do printing. 1604 for (std::vector<OptionCategory *>::const_iterator 1605 Category = SortedCategories.begin(), 1606 E = SortedCategories.end(); 1607 Category != E; ++Category) { 1608 // Hide empty categories for -help, but show for -help-hidden. 1609 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0; 1610 if (!ShowHidden && IsEmptyCategory) 1611 continue; 1612 1613 // Print category information. 1614 outs() << "\n"; 1615 outs() << (*Category)->getName() << ":\n"; 1616 1617 // Check if description is set. 1618 if ((*Category)->getDescription() != nullptr) 1619 outs() << (*Category)->getDescription() << "\n\n"; 1620 else 1621 outs() << "\n"; 1622 1623 // When using -help-hidden explicitly state if the category has no 1624 // options associated with it. 1625 if (IsEmptyCategory) { 1626 outs() << " This option category has no options.\n"; 1627 continue; 1628 } 1629 // Loop over the options in the category and print. 1630 for (std::vector<Option *>::const_iterator 1631 Opt = CategorizedOptions[*Category].begin(), 1632 E = CategorizedOptions[*Category].end(); 1633 Opt != E; ++Opt) 1634 (*Opt)->printOptionInfo(MaxArgLen); 1635 } 1636 } 1637 }; 1638 1639 // This wraps the Uncategorizing and Categorizing printers and decides 1640 // at run time which should be invoked. 1641 class HelpPrinterWrapper { 1642 private: 1643 HelpPrinter &UncategorizedPrinter; 1644 CategorizedHelpPrinter &CategorizedPrinter; 1645 1646 public: 1647 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter, 1648 CategorizedHelpPrinter &CategorizedPrinter) 1649 : UncategorizedPrinter(UncategorizedPrinter), 1650 CategorizedPrinter(CategorizedPrinter) {} 1651 1652 // Invoke the printer. 1653 void operator=(bool Value); 1654 }; 1655 1656 } // End anonymous namespace 1657 1658 // Declare the four HelpPrinter instances that are used to print out help, or 1659 // help-hidden as an uncategorized list or in categories. 1660 static HelpPrinter UncategorizedNormalPrinter(false); 1661 static HelpPrinter UncategorizedHiddenPrinter(true); 1662 static CategorizedHelpPrinter CategorizedNormalPrinter(false); 1663 static CategorizedHelpPrinter CategorizedHiddenPrinter(true); 1664 1665 // Declare HelpPrinter wrappers that will decide whether or not to invoke 1666 // a categorizing help printer 1667 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter, 1668 CategorizedNormalPrinter); 1669 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter, 1670 CategorizedHiddenPrinter); 1671 1672 // Define a category for generic options that all tools should have. 1673 static cl::OptionCategory GenericCategory("Generic Options"); 1674 1675 // Define uncategorized help printers. 1676 // -help-list is hidden by default because if Option categories are being used 1677 // then -help behaves the same as -help-list. 1678 static cl::opt<HelpPrinter, true, parser<bool>> HLOp( 1679 "help-list", 1680 cl::desc("Display list of available options (-help-list-hidden for more)"), 1681 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed, 1682 cl::cat(GenericCategory)); 1683 1684 static cl::opt<HelpPrinter, true, parser<bool>> 1685 HLHOp("help-list-hidden", cl::desc("Display list of all available options"), 1686 cl::location(UncategorizedHiddenPrinter), cl::Hidden, 1687 cl::ValueDisallowed, cl::cat(GenericCategory)); 1688 1689 // Define uncategorized/categorized help printers. These printers change their 1690 // behaviour at runtime depending on whether one or more Option categories have 1691 // been declared. 1692 static cl::opt<HelpPrinterWrapper, true, parser<bool>> 1693 HOp("help", cl::desc("Display available options (-help-hidden for more)"), 1694 cl::location(WrappedNormalPrinter), cl::ValueDisallowed, 1695 cl::cat(GenericCategory)); 1696 1697 static cl::opt<HelpPrinterWrapper, true, parser<bool>> 1698 HHOp("help-hidden", cl::desc("Display all available options"), 1699 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed, 1700 cl::cat(GenericCategory)); 1701 1702 static cl::opt<bool> PrintOptions( 1703 "print-options", 1704 cl::desc("Print non-default options after command line parsing"), 1705 cl::Hidden, cl::init(false), cl::cat(GenericCategory)); 1706 1707 static cl::opt<bool> PrintAllOptions( 1708 "print-all-options", 1709 cl::desc("Print all option values after command line parsing"), cl::Hidden, 1710 cl::init(false), cl::cat(GenericCategory)); 1711 1712 void HelpPrinterWrapper::operator=(bool Value) { 1713 if (Value == false) 1714 return; 1715 1716 // Decide which printer to invoke. If more than one option category is 1717 // registered then it is useful to show the categorized help instead of 1718 // uncategorized help. 1719 if (RegisteredOptionCategories->size() > 1) { 1720 // unhide -help-list option so user can have uncategorized output if they 1721 // want it. 1722 HLOp.setHiddenFlag(NotHidden); 1723 1724 CategorizedPrinter = true; // Invoke categorized printer 1725 } else 1726 UncategorizedPrinter = true; // Invoke uncategorized printer 1727 } 1728 1729 // Print the value of each option. 1730 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); } 1731 1732 void CommandLineParser::printOptionValues() { 1733 if (!PrintOptions && !PrintAllOptions) 1734 return; 1735 1736 SmallVector<std::pair<const char *, Option *>, 128> Opts; 1737 sortOpts(OptionsMap, Opts, /*ShowHidden*/ true); 1738 1739 // Compute the maximum argument length... 1740 size_t MaxArgLen = 0; 1741 for (size_t i = 0, e = Opts.size(); i != e; ++i) 1742 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth()); 1743 1744 for (size_t i = 0, e = Opts.size(); i != e; ++i) 1745 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions); 1746 } 1747 1748 static void (*OverrideVersionPrinter)() = nullptr; 1749 1750 static std::vector<void (*)()> *ExtraVersionPrinters = nullptr; 1751 1752 namespace { 1753 class VersionPrinter { 1754 public: 1755 void print() { 1756 raw_ostream &OS = outs(); 1757 OS << "LLVM (http://llvm.org/):\n" 1758 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION; 1759 #ifdef LLVM_VERSION_INFO 1760 OS << " " << LLVM_VERSION_INFO; 1761 #endif 1762 OS << "\n "; 1763 #ifndef __OPTIMIZE__ 1764 OS << "DEBUG build"; 1765 #else 1766 OS << "Optimized build"; 1767 #endif 1768 #ifndef NDEBUG 1769 OS << " with assertions"; 1770 #endif 1771 std::string CPU = sys::getHostCPUName(); 1772 if (CPU == "generic") 1773 CPU = "(unknown)"; 1774 OS << ".\n" 1775 #if (ENABLE_TIMESTAMPS == 1) 1776 << " Built " << __DATE__ << " (" << __TIME__ << ").\n" 1777 #endif 1778 << " Default target: " << sys::getDefaultTargetTriple() << '\n' 1779 << " Host CPU: " << CPU << '\n'; 1780 } 1781 void operator=(bool OptionWasSpecified) { 1782 if (!OptionWasSpecified) 1783 return; 1784 1785 if (OverrideVersionPrinter != nullptr) { 1786 (*OverrideVersionPrinter)(); 1787 exit(0); 1788 } 1789 print(); 1790 1791 // Iterate over any registered extra printers and call them to add further 1792 // information. 1793 if (ExtraVersionPrinters != nullptr) { 1794 outs() << '\n'; 1795 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(), 1796 E = ExtraVersionPrinters->end(); 1797 I != E; ++I) 1798 (*I)(); 1799 } 1800 1801 exit(0); 1802 } 1803 }; 1804 } // End anonymous namespace 1805 1806 // Define the --version option that prints out the LLVM version for the tool 1807 static VersionPrinter VersionPrinterInstance; 1808 1809 static cl::opt<VersionPrinter, true, parser<bool>> 1810 VersOp("version", cl::desc("Display the version of this program"), 1811 cl::location(VersionPrinterInstance), cl::ValueDisallowed, 1812 cl::cat(GenericCategory)); 1813 1814 // Utility function for printing the help message. 1815 void cl::PrintHelpMessage(bool Hidden, bool Categorized) { 1816 // This looks weird, but it actually prints the help message. The Printers are 1817 // types of HelpPrinter and the help gets printed when its operator= is 1818 // invoked. That's because the "normal" usages of the help printer is to be 1819 // assigned true/false depending on whether -help or -help-hidden was given or 1820 // not. Since we're circumventing that we have to make it look like -help or 1821 // -help-hidden were given, so we assign true. 1822 1823 if (!Hidden && !Categorized) 1824 UncategorizedNormalPrinter = true; 1825 else if (!Hidden && Categorized) 1826 CategorizedNormalPrinter = true; 1827 else if (Hidden && !Categorized) 1828 UncategorizedHiddenPrinter = true; 1829 else 1830 CategorizedHiddenPrinter = true; 1831 } 1832 1833 /// Utility function for printing version number. 1834 void cl::PrintVersionMessage() { VersionPrinterInstance.print(); } 1835 1836 void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; } 1837 1838 void cl::AddExtraVersionPrinter(void (*func)()) { 1839 if (!ExtraVersionPrinters) 1840 ExtraVersionPrinters = new std::vector<void (*)()>; 1841 1842 ExtraVersionPrinters->push_back(func); 1843 } 1844 1845 StringMap<Option *> &cl::getRegisteredOptions() { 1846 return GlobalParser->OptionsMap; 1847 } 1848 1849 void cl::HideUnrelatedOptions(cl::OptionCategory &Category) { 1850 for (auto &I : GlobalParser->OptionsMap) { 1851 if (I.second->Category != &Category && 1852 I.second->Category != &GenericCategory) 1853 I.second->setHiddenFlag(cl::ReallyHidden); 1854 } 1855 } 1856 1857 void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories) { 1858 auto CategoriesBegin = Categories.begin(); 1859 auto CategoriesEnd = Categories.end(); 1860 for (auto &I : GlobalParser->OptionsMap) { 1861 if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) == 1862 CategoriesEnd && 1863 I.second->Category != &GenericCategory) 1864 I.second->setHiddenFlag(cl::ReallyHidden); 1865 } 1866 } 1867 1868 void LLVMParseCommandLineOptions(int argc, const char *const *argv, 1869 const char *Overview) { 1870 llvm::cl::ParseCommandLineOptions(argc, argv, Overview); 1871 } 1872