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