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