1 //===-- Args.cpp ------------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
13 // Other libraries and framework includes
15 #include "lldb/DataFormatters/FormatManager.h"
16 #include "lldb/Host/OptionParser.h"
17 #include "lldb/Interpreter/Args.h"
18 #include "lldb/Interpreter/CommandInterpreter.h"
19 #include "lldb/Interpreter/CommandReturnObject.h"
20 #include "lldb/Interpreter/Options.h"
21 #include "lldb/Target/Target.h"
22 #include "lldb/Utility/Stream.h"
23 #include "lldb/Utility/StreamString.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
30 using namespace lldb_private;
33 // A helper function for argument parsing.
34 // Parses the initial part of the first argument using normal double quote
36 // backslash escapes the double quote and itself. The parsed string is appended
38 // argument. The function returns the unparsed portion of the string, starting
41 static llvm::StringRef ParseDoubleQuotes(llvm::StringRef quoted,
42 std::string &result) {
43 // Inside double quotes, '\' and '"' are special.
44 static const char *k_escapable_characters = "\"\\";
46 // Skip over over regular characters and append them.
47 size_t regular = quoted.find_first_of(k_escapable_characters);
48 result += quoted.substr(0, regular);
49 quoted = quoted.substr(regular);
51 // If we have reached the end of string or the closing quote, we're done.
52 if (quoted.empty() || quoted.front() == '"')
55 // We have found a backslash.
56 quoted = quoted.drop_front();
59 // A lone backslash at the end of string, let's just append it.
64 // If the character after the backslash is not a whitelisted escapable
66 // leave the character sequence untouched.
67 if (strchr(k_escapable_characters, quoted.front()) == nullptr)
70 result += quoted.front();
71 quoted = quoted.drop_front();
77 static size_t ArgvToArgc(const char **argv) {
86 // A helper function for SetCommandString. Parses a single argument from the
87 // command string, processing quotes and backslashes in a shell-like manner.
88 // The function returns a tuple consisting of the parsed argument, the quote
89 // char used, and the unparsed portion of the string starting at the first
90 // unqouted, unescaped whitespace character.
91 static std::tuple<std::string, char, llvm::StringRef>
92 ParseSingleArgument(llvm::StringRef command) {
93 // Argument can be split into multiple discontiguous pieces, for example:
95 // this would result in a single argument "Hello World" (without the quotes)
96 // since the quotes would be removed and there is not space between the
100 // Since we can have multiple quotes that form a single command
101 // in a command like: "Hello "world'!' (which will make a single
102 // argument "Hello world!") we remember the first quote character
103 // we encounter and use that for the quote character.
104 char first_quote_char = '\0';
106 bool arg_complete = false;
108 // Skip over over regular characters and append them.
109 size_t regular = command.find_first_of(" \t\"'`\\");
110 arg += command.substr(0, regular);
111 command = command.substr(regular);
116 char special = command.front();
117 command = command.drop_front();
120 if (command.empty()) {
125 // If the character after the backslash is not a whitelisted escapable
127 // leave the character sequence untouched.
128 if (strchr(" \t\\'\"`", command.front()) == nullptr)
131 arg += command.front();
132 command = command.drop_front();
138 // We are not inside any quotes, we just found a space after an
139 // argument. We are done.
146 // We found the start of a quote scope.
147 if (first_quote_char == '\0')
148 first_quote_char = special;
151 command = ParseDoubleQuotes(command, arg);
153 // For single quotes, we simply skip ahead to the matching quote
155 // (or the end of the string).
156 size_t quoted = command.find(special);
157 arg += command.substr(0, quoted);
158 command = command.substr(quoted);
161 // If we found a closing quote, skip it.
162 if (!command.empty())
163 command = command.drop_front();
167 } while (!arg_complete);
169 return std::make_tuple(arg, first_quote_char, command);
172 Args::ArgEntry::ArgEntry(llvm::StringRef str, char quote) : quote(quote) {
173 size_t size = str.size();
174 ptr.reset(new char[size + 1]);
176 ::memcpy(data(), str.data() ? str.data() : "", size);
178 ref = llvm::StringRef(c_str(), size);
181 //----------------------------------------------------------------------
183 //----------------------------------------------------------------------
184 Args::Args(llvm::StringRef command) { SetCommandString(command); }
186 Args::Args(const Args &rhs) { *this = rhs; }
188 Args::Args(const StringList &list) : Args() {
189 for(size_t i = 0; i < list.GetSize(); ++i)
190 AppendArgument(list[i]);
193 Args &Args::operator=(const Args &rhs) {
198 for (auto &entry : rhs.m_entries) {
199 m_entries.emplace_back(entry.ref, entry.quote);
200 m_argv.push_back(m_entries.back().data());
202 m_argv.push_back(nullptr);
206 //----------------------------------------------------------------------
208 //----------------------------------------------------------------------
211 void Args::Dump(Stream &s, const char *label_name) const {
216 for (auto &entry : m_entries) {
218 s.Format("{0}[{1}]=\"{2}\"\n", label_name, i++, entry.ref);
220 s.Format("{0}[{1}]=NULL\n", label_name, i);
224 bool Args::GetCommandString(std::string &command) const {
227 for (size_t i = 0; i < m_entries.size(); ++i) {
230 command += m_entries[i].ref;
233 return !m_entries.empty();
236 bool Args::GetQuotedCommandString(std::string &command) const {
239 for (size_t i = 0; i < m_entries.size(); ++i) {
243 if (m_entries[i].quote) {
244 command += m_entries[i].quote;
245 command += m_entries[i].ref;
246 command += m_entries[i].quote;
248 command += m_entries[i].ref;
252 return !m_entries.empty();
255 void Args::SetCommandString(llvm::StringRef command) {
259 static const char *k_space_separators = " \t";
260 command = command.ltrim(k_space_separators);
263 while (!command.empty()) {
264 std::tie(arg, quote, command) = ParseSingleArgument(command);
265 m_entries.emplace_back(arg, quote);
266 m_argv.push_back(m_entries.back().data());
267 command = command.ltrim(k_space_separators);
269 m_argv.push_back(nullptr);
272 void Args::UpdateArgsAfterOptionParsing() {
273 assert(!m_argv.empty());
274 assert(m_argv.back() == nullptr);
276 // Now m_argv might be out of date with m_entries, so we need to fix that.
277 // This happens because getopt_long_only may permute the order of the
278 // arguments in argv, so we need to re-order the quotes and the refs array
280 for (size_t i = 0; i < m_argv.size() - 1; ++i) {
281 const char *argv = m_argv[i];
283 std::find_if(m_entries.begin() + i, m_entries.end(),
284 [argv](const ArgEntry &D) { return D.c_str() == argv; });
285 assert(pos != m_entries.end());
286 size_t distance = std::distance(m_entries.begin(), pos);
290 assert(distance > i);
292 std::swap(m_entries[i], m_entries[distance]);
293 assert(m_entries[i].ref.data() == m_argv[i]);
295 m_entries.resize(m_argv.size() - 1);
298 size_t Args::GetArgumentCount() const { return m_entries.size(); }
300 const char *Args::GetArgumentAtIndex(size_t idx) const {
301 if (idx < m_argv.size())
306 char Args::GetArgumentQuoteCharAtIndex(size_t idx) const {
307 if (idx < m_entries.size())
308 return m_entries[idx].quote;
312 char **Args::GetArgumentVector() {
313 assert(!m_argv.empty());
314 // TODO: functions like execve and posix_spawnp exhibit undefined behavior
315 // when argv or envp is null. So the code below is actually wrong. However,
316 // other code in LLDB depends on it being null. The code has been acting this
317 // way for some time, so it makes sense to leave it this way until someone
318 // has the time to come along and fix it.
319 return (m_argv.size() > 1) ? m_argv.data() : nullptr;
322 const char **Args::GetConstArgumentVector() const {
323 assert(!m_argv.empty());
324 return (m_argv.size() > 1) ? const_cast<const char **>(m_argv.data())
329 // Don't pop the last NULL terminator from the argv array
330 if (m_entries.empty())
332 m_argv.erase(m_argv.begin());
333 m_entries.erase(m_entries.begin());
336 void Args::Unshift(llvm::StringRef arg_str, char quote_char) {
337 InsertArgumentAtIndex(0, arg_str, quote_char);
340 void Args::AppendArguments(const Args &rhs) {
341 assert(m_argv.size() == m_entries.size() + 1);
342 assert(m_argv.back() == nullptr);
344 for (auto &entry : rhs.m_entries) {
345 m_entries.emplace_back(entry.ref, entry.quote);
346 m_argv.push_back(m_entries.back().data());
348 m_argv.push_back(nullptr);
351 void Args::AppendArguments(const char **argv) {
352 size_t argc = ArgvToArgc(argv);
354 assert(m_argv.size() == m_entries.size() + 1);
355 assert(m_argv.back() == nullptr);
357 for (auto arg : llvm::makeArrayRef(argv, argc)) {
358 m_entries.emplace_back(arg, '\0');
359 m_argv.push_back(m_entries.back().data());
362 m_argv.push_back(nullptr);
365 void Args::AppendArgument(llvm::StringRef arg_str, char quote_char) {
366 InsertArgumentAtIndex(GetArgumentCount(), arg_str, quote_char);
369 void Args::InsertArgumentAtIndex(size_t idx, llvm::StringRef arg_str,
371 assert(m_argv.size() == m_entries.size() + 1);
372 assert(m_argv.back() == nullptr);
374 if (idx > m_entries.size())
376 m_entries.emplace(m_entries.begin() + idx, arg_str, quote_char);
377 m_argv.insert(m_argv.begin() + idx, m_entries[idx].data());
380 void Args::ReplaceArgumentAtIndex(size_t idx, llvm::StringRef arg_str,
382 assert(m_argv.size() == m_entries.size() + 1);
383 assert(m_argv.back() == nullptr);
385 if (idx >= m_entries.size())
388 if (arg_str.size() > m_entries[idx].ref.size()) {
389 m_entries[idx] = ArgEntry(arg_str, quote_char);
390 m_argv[idx] = m_entries[idx].data();
392 const char *src_data = arg_str.data() ? arg_str.data() : "";
393 ::memcpy(m_entries[idx].data(), src_data, arg_str.size());
394 m_entries[idx].ptr[arg_str.size()] = 0;
395 m_entries[idx].ref = m_entries[idx].ref.take_front(arg_str.size());
399 void Args::DeleteArgumentAtIndex(size_t idx) {
400 if (idx >= m_entries.size())
403 m_argv.erase(m_argv.begin() + idx);
404 m_entries.erase(m_entries.begin() + idx);
407 void Args::SetArguments(size_t argc, const char **argv) {
410 auto args = llvm::makeArrayRef(argv, argc);
411 m_entries.resize(argc);
412 m_argv.resize(argc + 1);
413 for (size_t i = 0; i < args.size(); ++i) {
415 ((args[i][0] == '\'') || (args[i][0] == '"') || (args[i][0] == '`'))
419 m_entries[i] = ArgEntry(args[i], quote);
420 m_argv[i] = m_entries[i].data();
424 void Args::SetArguments(const char **argv) {
425 SetArguments(ArgvToArgc(argv), argv);
428 Status Args::ParseOptions(Options &options, ExecutionContext *execution_context,
429 PlatformSP platform_sp, bool require_validation) {
432 Option *long_options = options.GetLongOptions();
433 if (long_options == nullptr) {
434 error.SetErrorStringWithFormat("invalid long options");
438 for (int i = 0; long_options[i].definition != nullptr; ++i) {
439 if (long_options[i].flag == nullptr) {
440 if (isprint8(long_options[i].val)) {
441 sstr << (char)long_options[i].val;
442 switch (long_options[i].definition->option_has_arg) {
444 case OptionParser::eNoArgument:
446 case OptionParser::eRequiredArgument:
449 case OptionParser::eOptionalArgument:
456 std::unique_lock<std::mutex> lock;
457 OptionParser::Prepare(lock);
460 int long_options_index = -1;
461 val = OptionParser::Parse(GetArgumentCount(), GetArgumentVector(),
462 sstr.GetString(), long_options,
463 &long_options_index);
467 // Did we get an error?
469 error.SetErrorStringWithFormat("unknown or ambiguous option");
472 // The option auto-set itself
476 ((Options *)&options)->OptionSeen(val);
478 // Lookup the long option index
479 if (long_options_index == -1) {
480 for (int i = 0; long_options[i].definition || long_options[i].flag ||
483 if (long_options[i].val == val) {
484 long_options_index = i;
489 // Call the callback with the option
490 if (long_options_index >= 0 &&
491 long_options[long_options_index].definition) {
492 const OptionDefinition *def = long_options[long_options_index].definition;
495 // User did not pass in an explicit platform. Try to grab
496 // from the execution context.
498 execution_context ? execution_context->GetTargetSP() : TargetSP();
499 platform_sp = target_sp ? target_sp->GetPlatform() : PlatformSP();
501 OptionValidator *validator = def->validator;
503 if (!platform_sp && require_validation) {
504 // Caller requires validation but we cannot validate as we
505 // don't have the mandatory platform against which to
507 error.SetErrorString("cannot validate options: "
508 "no platform available");
512 bool validation_failed = false;
514 // Ensure we have an execution context, empty or not.
515 ExecutionContext dummy_context;
516 ExecutionContext *exe_ctx_p =
517 execution_context ? execution_context : &dummy_context;
518 if (validator && !validator->IsValid(*platform_sp, *exe_ctx_p)) {
519 validation_failed = true;
520 error.SetErrorStringWithFormat("Option \"%s\" invalid. %s",
522 def->validator->LongConditionString());
526 // As long as validation didn't fail, we set the option value.
527 if (!validation_failed)
528 error = options.SetOptionValue(
530 (def->option_has_arg == OptionParser::eNoArgument)
532 : OptionParser::GetOptionArgument(),
535 error.SetErrorStringWithFormat("invalid option with value '%i'", val);
541 // Update our ARGV now that get options has consumed all the options
542 m_argv.erase(m_argv.begin(), m_argv.begin() + OptionParser::GetOptionIndex());
543 UpdateArgsAfterOptionParsing();
550 m_argv.push_back(nullptr);
553 lldb::addr_t Args::StringToAddress(const ExecutionContext *exe_ctx,
554 llvm::StringRef s, lldb::addr_t fail_value,
556 bool error_set = false;
559 error_ptr->SetErrorStringWithFormat("invalid address expression \"%s\"",
564 llvm::StringRef sref = s;
566 lldb::addr_t addr = LLDB_INVALID_ADDRESS;
567 if (!s.getAsInteger(0, addr)) {
573 // Try base 16 with no prefix...
574 if (!s.getAsInteger(16, addr)) {
580 Target *target = nullptr;
581 if (!exe_ctx || !(target = exe_ctx->GetTargetPtr())) {
583 error_ptr->SetErrorStringWithFormat("invalid address expression \"%s\"",
588 lldb::ValueObjectSP valobj_sp;
589 EvaluateExpressionOptions options;
590 options.SetCoerceToId(false);
591 options.SetUnwindOnError(true);
592 options.SetKeepInMemory(false);
593 options.SetTryAllThreads(true);
595 ExpressionResults expr_result =
596 target->EvaluateExpression(s, exe_ctx->GetFramePtr(), valobj_sp, options);
598 bool success = false;
599 if (expr_result == eExpressionCompleted) {
601 valobj_sp = valobj_sp->GetQualifiedRepresentationIfAvailable(
602 valobj_sp->GetDynamicValueType(), true);
603 // Get the address to watch.
605 addr = valobj_sp->GetValueAsUnsigned(fail_value, &success);
613 error_ptr->SetErrorStringWithFormat(
614 "address expression \"%s\" resulted in a value whose type "
615 "can't be converted to an address: %s",
616 s.str().c_str(), valobj_sp->GetTypeName().GetCString());
621 // Since the compiler can't handle things like "main + 12" we should
622 // try to do this for now. The compiler doesn't like adding offsets
623 // to function pointer types.
624 static RegularExpression g_symbol_plus_offset_regex(
625 "^(.*)([-\\+])[[:space:]]*(0x[0-9A-Fa-f]+|[0-9]+)[[:space:]]*$");
626 RegularExpression::Match regex_match(3);
627 if (g_symbol_plus_offset_regex.Execute(sref, ®ex_match)) {
632 if (regex_match.GetMatchAtIndex(s, 1, name)) {
633 if (regex_match.GetMatchAtIndex(s, 2, str)) {
636 if (regex_match.GetMatchAtIndex(s, 3, str)) {
637 if (!llvm::StringRef(str).getAsInteger(0, offset)) {
639 addr = StringToAddress(exe_ctx, name.c_str(),
640 LLDB_INVALID_ADDRESS, &error);
641 if (addr != LLDB_INVALID_ADDRESS) {
643 return addr + offset;
645 return addr - offset;
655 error_ptr->SetErrorStringWithFormat(
656 "address expression \"%s\" evaluation failed", s.str().c_str());
662 error_ptr->SetErrorStringWithFormat("invalid address expression \"%s\"",
668 const char *Args::StripSpaces(std::string &s, bool leading, bool trailing,
669 bool return_null_if_empty) {
670 static const char *k_white_space = " \t\v";
673 size_t pos = s.find_first_not_of(k_white_space);
674 if (pos == std::string::npos)
681 size_t rpos = s.find_last_not_of(k_white_space);
682 if (rpos != std::string::npos && rpos + 1 < s.size())
686 if (return_null_if_empty && s.empty())
691 bool Args::StringToBoolean(llvm::StringRef ref, bool fail_value,
696 if (ref.equals_lower("false") || ref.equals_lower("off") ||
697 ref.equals_lower("no") || ref.equals_lower("0")) {
699 } else if (ref.equals_lower("true") || ref.equals_lower("on") ||
700 ref.equals_lower("yes") || ref.equals_lower("1")) {
704 *success_ptr = false;
708 char Args::StringToChar(llvm::StringRef s, char fail_value, bool *success_ptr) {
710 *success_ptr = false;
719 bool Args::StringToVersion(llvm::StringRef string, uint32_t &major,
720 uint32_t &minor, uint32_t &update) {
728 llvm::StringRef major_str, minor_str, update_str;
730 std::tie(major_str, minor_str) = string.split('.');
731 std::tie(minor_str, update_str) = minor_str.split('.');
732 if (major_str.getAsInteger(10, major))
734 if (!minor_str.empty() && minor_str.getAsInteger(10, minor))
736 if (!update_str.empty() && update_str.getAsInteger(10, update))
742 const char *Args::GetShellSafeArgument(const FileSpec &shell,
743 const char *unsafe_arg,
744 std::string &safe_arg) {
745 struct ShellDescriptor {
746 ConstString m_basename;
747 const char *m_escapables;
750 static ShellDescriptor g_Shells[] = {{ConstString("bash"), " '\"<>()&"},
751 {ConstString("tcsh"), " '\"<>()&$"},
752 {ConstString("sh"), " '\"<>()&"}};
755 const char *escapables = " '\"";
757 if (auto basename = shell.GetFilename()) {
758 for (const auto &Shell : g_Shells) {
759 if (Shell.m_basename == basename) {
760 escapables = Shell.m_escapables;
766 safe_arg.assign(unsafe_arg);
768 while (prev_pos < safe_arg.size()) {
769 // Escape spaces and quotes
770 size_t pos = safe_arg.find_first_of(escapables, prev_pos);
771 if (pos != std::string::npos) {
772 safe_arg.insert(pos, 1, '\\');
777 return safe_arg.c_str();
780 int64_t Args::StringToOptionEnum(llvm::StringRef s,
781 OptionEnumValueElement *enum_values,
782 int32_t fail_value, Status &error) {
785 error.SetErrorString("invalid enumeration argument");
790 error.SetErrorString("empty enumeration string");
794 for (int i = 0; enum_values[i].string_value != nullptr; i++) {
795 llvm::StringRef this_enum(enum_values[i].string_value);
796 if (this_enum.startswith(s))
797 return enum_values[i].value;
801 strm.PutCString("invalid enumeration value, valid values are: ");
802 for (int i = 0; enum_values[i].string_value != nullptr; i++) {
803 strm.Printf("%s\"%s\"", i > 0 ? ", " : "", enum_values[i].string_value);
805 error.SetErrorString(strm.GetString());
810 Args::StringToScriptLanguage(llvm::StringRef s, lldb::ScriptLanguage fail_value,
815 if (s.equals_lower("python"))
816 return eScriptLanguagePython;
817 if (s.equals_lower("default"))
818 return eScriptLanguageDefault;
819 if (s.equals_lower("none"))
820 return eScriptLanguageNone;
823 *success_ptr = false;
827 Status Args::StringToFormat(const char *s, lldb::Format &format,
828 size_t *byte_size_ptr) {
829 format = eFormatInvalid;
835 char *format_char = nullptr;
836 unsigned long byte_size = ::strtoul(s, &format_char, 0);
837 if (byte_size != ULONG_MAX)
838 *byte_size_ptr = byte_size;
844 const bool partial_match_ok = true;
845 if (!FormatManager::GetFormatFromCString(s, partial_match_ok, format)) {
846 StreamString error_strm;
848 "Invalid format character or name '%s'. Valid values are:\n", s);
849 for (Format f = eFormatDefault; f < kNumFormats; f = Format(f + 1)) {
850 char format_char = FormatManager::GetFormatAsFormatChar(f);
852 error_strm.Printf("'%c' or ", format_char);
854 error_strm.Printf("\"%s\"", FormatManager::GetFormatAsCString(f));
859 error_strm.PutCString(
860 "An optional byte size can precede the format character.\n");
861 error.SetErrorString(error_strm.GetString());
867 error.SetErrorStringWithFormat("%s option string", s ? "empty" : "invalid");
872 lldb::Encoding Args::StringToEncoding(llvm::StringRef s,
873 lldb::Encoding fail_value) {
874 return llvm::StringSwitch<lldb::Encoding>(s)
875 .Case("uint", eEncodingUint)
876 .Case("sint", eEncodingSint)
877 .Case("ieee754", eEncodingIEEE754)
878 .Case("vector", eEncodingVector)
879 .Default(fail_value);
882 uint32_t Args::StringToGenericRegister(llvm::StringRef s) {
884 return LLDB_INVALID_REGNUM;
885 uint32_t result = llvm::StringSwitch<uint32_t>(s)
886 .Case("pc", LLDB_REGNUM_GENERIC_PC)
887 .Case("sp", LLDB_REGNUM_GENERIC_SP)
888 .Case("fp", LLDB_REGNUM_GENERIC_FP)
889 .Cases("ra", "lr", LLDB_REGNUM_GENERIC_RA)
890 .Case("flags", LLDB_REGNUM_GENERIC_FLAGS)
891 .Case("arg1", LLDB_REGNUM_GENERIC_ARG1)
892 .Case("arg2", LLDB_REGNUM_GENERIC_ARG2)
893 .Case("arg3", LLDB_REGNUM_GENERIC_ARG3)
894 .Case("arg4", LLDB_REGNUM_GENERIC_ARG4)
895 .Case("arg5", LLDB_REGNUM_GENERIC_ARG5)
896 .Case("arg6", LLDB_REGNUM_GENERIC_ARG6)
897 .Case("arg7", LLDB_REGNUM_GENERIC_ARG7)
898 .Case("arg8", LLDB_REGNUM_GENERIC_ARG8)
899 .Default(LLDB_INVALID_REGNUM);
903 void Args::AddOrReplaceEnvironmentVariable(llvm::StringRef env_var_name,
904 llvm::StringRef new_value) {
905 if (env_var_name.empty())
908 // Build the new entry.
909 std::string var_string(env_var_name);
910 if (!new_value.empty()) {
912 var_string += new_value;
916 if (ContainsEnvironmentVariable(env_var_name, &index)) {
917 ReplaceArgumentAtIndex(index, var_string);
921 // We didn't find it. Append it instead.
922 AppendArgument(var_string);
925 bool Args::ContainsEnvironmentVariable(llvm::StringRef env_var_name,
926 size_t *argument_index) const {
928 if (env_var_name.empty())
931 // Check each arg to see if it matches the env var name.
932 for (auto arg : llvm::enumerate(m_entries)) {
933 llvm::StringRef name, value;
934 std::tie(name, value) = arg.value().ref.split('=');
935 if (name != env_var_name)
939 *argument_index = arg.index();
943 // We didn't find a match.
947 size_t Args::FindArgumentIndexForOption(Option *long_options,
948 int long_options_index) const {
949 char short_buffer[3];
950 char long_buffer[255];
951 ::snprintf(short_buffer, sizeof(short_buffer), "-%c",
952 long_options[long_options_index].val);
953 ::snprintf(long_buffer, sizeof(long_buffer), "--%s",
954 long_options[long_options_index].definition->long_option);
956 for (auto entry : llvm::enumerate(m_entries)) {
957 if (entry.value().ref.startswith(short_buffer) ||
958 entry.value().ref.startswith(long_buffer))
959 return entry.index();
965 bool Args::IsPositionalArgument(const char *arg) {
969 bool is_positional = true;
970 const char *cptr = arg;
972 if (cptr[0] == '%') {
974 while (isdigit(cptr[0]))
977 is_positional = false;
979 is_positional = false;
981 return is_positional;
984 std::string Args::ParseAliasOptions(Options &options,
985 CommandReturnObject &result,
986 OptionArgVector *option_arg_vector,
987 llvm::StringRef raw_input_string) {
988 std::string result_string(raw_input_string);
991 Option *long_options = options.GetLongOptions();
993 if (long_options == nullptr) {
994 result.AppendError("invalid long options");
995 result.SetStatus(eReturnStatusFailed);
996 return result_string;
999 for (i = 0; long_options[i].definition != nullptr; ++i) {
1000 if (long_options[i].flag == nullptr) {
1001 sstr << (char)long_options[i].val;
1002 switch (long_options[i].definition->option_has_arg) {
1004 case OptionParser::eNoArgument:
1006 case OptionParser::eRequiredArgument:
1009 case OptionParser::eOptionalArgument:
1016 std::unique_lock<std::mutex> lock;
1017 OptionParser::Prepare(lock);
1018 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1021 int long_options_index = -1;
1022 val = OptionParser::Parse(GetArgumentCount(), GetArgumentVector(),
1023 sstr.GetString(), long_options,
1024 &long_options_index);
1030 result.AppendError("unknown or ambiguous option");
1031 result.SetStatus(eReturnStatusFailed);
1038 options.OptionSeen(val);
1040 // Look up the long option index
1041 if (long_options_index == -1) {
1042 for (int j = 0; long_options[j].definition || long_options[j].flag ||
1043 long_options[j].val;
1045 if (long_options[j].val == val) {
1046 long_options_index = j;
1052 // See if the option takes an argument, and see if one was supplied.
1053 if (long_options_index == -1) {
1054 result.AppendErrorWithFormat("Invalid option with value '%c'.\n", val);
1055 result.SetStatus(eReturnStatusFailed);
1056 return result_string;
1059 StreamString option_str;
1060 option_str.Printf("-%c", val);
1061 const OptionDefinition *def = long_options[long_options_index].definition;
1063 (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg;
1065 const char *option_arg = nullptr;
1067 case OptionParser::eRequiredArgument:
1068 if (OptionParser::GetOptionArgument() == nullptr) {
1069 result.AppendErrorWithFormat(
1070 "Option '%s' is missing argument specifier.\n",
1071 option_str.GetData());
1072 result.SetStatus(eReturnStatusFailed);
1073 return result_string;
1076 case OptionParser::eOptionalArgument:
1077 option_arg = OptionParser::GetOptionArgument();
1079 case OptionParser::eNoArgument:
1082 result.AppendErrorWithFormat("error with options table; invalid value "
1083 "in has_arg field for option '%c'.\n",
1085 result.SetStatus(eReturnStatusFailed);
1086 return result_string;
1089 option_arg = "<no-argument>";
1090 option_arg_vector->emplace_back(option_str.GetString(), has_arg,
1093 // Find option in the argument list; also see if it was supposed to take
1094 // an argument and if one was supplied. Remove option (and argument, if
1095 // given) from the argument list. Also remove them from the
1096 // raw_input_string, if one was passed in.
1097 size_t idx = FindArgumentIndexForOption(long_options, long_options_index);
1098 if (idx == size_t(-1))
1101 if (!result_string.empty()) {
1102 auto tmp_arg = m_entries[idx].ref;
1103 size_t pos = result_string.find(tmp_arg);
1104 if (pos != std::string::npos)
1105 result_string.erase(pos, tmp_arg.size());
1107 ReplaceArgumentAtIndex(idx, llvm::StringRef());
1108 if ((long_options[long_options_index].definition->option_has_arg !=
1109 OptionParser::eNoArgument) &&
1110 (OptionParser::GetOptionArgument() != nullptr) &&
1111 (idx + 1 < GetArgumentCount()) &&
1112 (m_entries[idx + 1].ref == OptionParser::GetOptionArgument())) {
1113 if (result_string.size() > 0) {
1114 auto tmp_arg = m_entries[idx + 1].ref;
1115 size_t pos = result_string.find(tmp_arg);
1116 if (pos != std::string::npos)
1117 result_string.erase(pos, tmp_arg.size());
1119 ReplaceArgumentAtIndex(idx + 1, llvm::StringRef());
1122 return result_string;
1125 void Args::ParseArgsForCompletion(Options &options,
1126 OptionElementVector &option_element_vector,
1127 uint32_t cursor_index) {
1129 Option *long_options = options.GetLongOptions();
1130 option_element_vector.clear();
1132 if (long_options == nullptr) {
1136 // Leading : tells getopt to return a : for a missing option argument AND
1137 // to suppress error messages.
1140 for (int i = 0; long_options[i].definition != nullptr; ++i) {
1141 if (long_options[i].flag == nullptr) {
1142 sstr << (char)long_options[i].val;
1143 switch (long_options[i].definition->option_has_arg) {
1145 case OptionParser::eNoArgument:
1147 case OptionParser::eRequiredArgument:
1150 case OptionParser::eOptionalArgument:
1157 std::unique_lock<std::mutex> lock;
1158 OptionParser::Prepare(lock);
1159 OptionParser::EnableError(false);
1162 auto opt_defs = options.GetDefinitions();
1164 // Fooey... OptionParser::Parse permutes the GetArgumentVector to move the
1165 // options to the front. So we have to build another Arg and pass that to
1166 // OptionParser::Parse so it doesn't change the one we have.
1168 std::vector<char *> dummy_vec = m_argv;
1170 bool failed_once = false;
1171 uint32_t dash_dash_pos = -1;
1174 bool missing_argument = false;
1175 int long_options_index = -1;
1177 val = OptionParser::Parse(dummy_vec.size() - 1, &dummy_vec[0],
1178 sstr.GetString(), long_options,
1179 &long_options_index);
1182 // When we're completing a "--" which is the last option on line,
1188 // If this is a bare "--" we mark it as such so we can complete it
1189 // successfully later.
1190 // Handling the "--" is a little tricky, since that may mean end of
1191 // options or arguments, or the
1192 // user might want to complete options by long name. I make this work by
1193 // checking whether the
1194 // cursor is in the "--" argument, and if so I assume we're completing the
1195 // long option, otherwise
1196 // I let it pass to OptionParser::Parse which will terminate the option
1198 // Note, in either case we continue parsing the line so we can figure out
1199 // what other options
1200 // were passed. This will be useful when we come to restricting
1201 // completions based on what other
1202 // options we've seen on the line.
1204 if (static_cast<size_t>(OptionParser::GetOptionIndex()) <
1205 dummy_vec.size() - 1 &&
1206 (strcmp(dummy_vec[OptionParser::GetOptionIndex() - 1], "--") == 0)) {
1207 dash_dash_pos = OptionParser::GetOptionIndex() - 1;
1208 if (static_cast<size_t>(OptionParser::GetOptionIndex() - 1) ==
1210 option_element_vector.push_back(
1211 OptionArgElement(OptionArgElement::eBareDoubleDash,
1212 OptionParser::GetOptionIndex() - 1,
1213 OptionArgElement::eBareDoubleDash));
1219 } else if (val == '?') {
1220 option_element_vector.push_back(
1221 OptionArgElement(OptionArgElement::eUnrecognizedArg,
1222 OptionParser::GetOptionIndex() - 1,
1223 OptionArgElement::eUnrecognizedArg));
1225 } else if (val == 0) {
1227 } else if (val == ':') {
1228 // This is a missing argument.
1229 val = OptionParser::GetOptionErrorCause();
1230 missing_argument = true;
1233 ((Options *)&options)->OptionSeen(val);
1235 // Look up the long option index
1236 if (long_options_index == -1) {
1237 for (int j = 0; long_options[j].definition || long_options[j].flag ||
1238 long_options[j].val;
1240 if (long_options[j].val == val) {
1241 long_options_index = j;
1247 // See if the option takes an argument, and see if one was supplied.
1248 if (long_options_index >= 0) {
1249 int opt_defs_index = -1;
1250 for (size_t i = 0; i < opt_defs.size(); i++) {
1251 if (opt_defs[i].short_option != val)
1257 const OptionDefinition *def = long_options[long_options_index].definition;
1259 (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg;
1261 case OptionParser::eNoArgument:
1262 option_element_vector.push_back(OptionArgElement(
1263 opt_defs_index, OptionParser::GetOptionIndex() - 1, 0));
1265 case OptionParser::eRequiredArgument:
1266 if (OptionParser::GetOptionArgument() != nullptr) {
1268 if (missing_argument)
1271 arg_index = OptionParser::GetOptionIndex() - 1;
1273 option_element_vector.push_back(OptionArgElement(
1274 opt_defs_index, OptionParser::GetOptionIndex() - 2, arg_index));
1276 option_element_vector.push_back(OptionArgElement(
1277 opt_defs_index, OptionParser::GetOptionIndex() - 1, -1));
1280 case OptionParser::eOptionalArgument:
1281 if (OptionParser::GetOptionArgument() != nullptr) {
1282 option_element_vector.push_back(OptionArgElement(
1283 opt_defs_index, OptionParser::GetOptionIndex() - 2,
1284 OptionParser::GetOptionIndex() - 1));
1286 option_element_vector.push_back(OptionArgElement(
1287 opt_defs_index, OptionParser::GetOptionIndex() - 2,
1288 OptionParser::GetOptionIndex() - 1));
1292 // The options table is messed up. Here we'll just continue
1293 option_element_vector.push_back(
1294 OptionArgElement(OptionArgElement::eUnrecognizedArg,
1295 OptionParser::GetOptionIndex() - 1,
1296 OptionArgElement::eUnrecognizedArg));
1300 option_element_vector.push_back(
1301 OptionArgElement(OptionArgElement::eUnrecognizedArg,
1302 OptionParser::GetOptionIndex() - 1,
1303 OptionArgElement::eUnrecognizedArg));
1307 // Finally we have to handle the case where the cursor index points at a
1308 // single "-". We want to mark that in
1309 // the option_element_vector, but only if it is not after the "--". But it
1310 // turns out that OptionParser::Parse just ignores
1311 // an isolated "-". So we have to look it up by hand here. We only care if
1312 // it is AT the cursor position.
1313 // Note, a single quoted dash is not the same as a single dash...
1315 const ArgEntry &cursor = m_entries[cursor_index];
1316 if ((static_cast<int32_t>(dash_dash_pos) == -1 ||
1317 cursor_index < dash_dash_pos) &&
1318 cursor.quote == '\0' && cursor.ref == "-") {
1319 option_element_vector.push_back(
1320 OptionArgElement(OptionArgElement::eBareDash, cursor_index,
1321 OptionArgElement::eBareDash));
1325 void Args::EncodeEscapeSequences(const char *src, std::string &dst) {
1328 for (const char *p = src; *p != '\0'; ++p) {
1329 size_t non_special_chars = ::strcspn(p, "\\");
1330 if (non_special_chars > 0) {
1331 dst.append(p, non_special_chars);
1332 p += non_special_chars;
1338 ++p; // skip the slash
1341 dst.append(1, '\a');
1344 dst.append(1, '\b');
1347 dst.append(1, '\f');
1350 dst.append(1, '\n');
1353 dst.append(1, '\r');
1356 dst.append(1, '\t');
1359 dst.append(1, '\v');
1362 dst.append(1, '\\');
1365 dst.append(1, '\'');
1371 // 1 to 3 octal chars
1373 // Make a string that can hold onto the initial zero char,
1374 // up to 3 octal digits, and a terminating NULL.
1375 char oct_str[5] = {'\0', '\0', '\0', '\0', '\0'};
1378 for (i = 0; (p[i] >= '0' && p[i] <= '7') && i < 4; ++i)
1381 // We don't want to consume the last octal character since
1382 // the main for loop will do this for us, so we advance p by
1383 // one less than i (even if i is zero)
1385 unsigned long octal_value = ::strtoul(oct_str, nullptr, 8);
1386 if (octal_value <= UINT8_MAX) {
1387 dst.append(1, (char)octal_value);
1393 // hex number in the format
1394 if (isxdigit(p[1])) {
1395 ++p; // Skip the 'x'
1397 // Make a string that can hold onto two hex chars plus a
1399 char hex_str[3] = {*p, '\0', '\0'};
1400 if (isxdigit(p[1])) {
1401 ++p; // Skip the first of the two hex chars
1405 unsigned long hex_value = strtoul(hex_str, nullptr, 16);
1406 if (hex_value <= UINT8_MAX)
1407 dst.append(1, (char)hex_value);
1414 // Just desensitize any other character by just printing what
1415 // came after the '\'
1424 void Args::ExpandEscapedCharacters(const char *src, std::string &dst) {
1427 for (const char *p = src; *p != '\0'; ++p) {
1463 // Just encode as octal
1466 snprintf(octal_str, sizeof(octal_str), "%o", *p);
1467 dst.append(octal_str);
1475 std::string Args::EscapeLLDBCommandArgument(const std::string &arg,
1477 const char *chars_to_escape = nullptr;
1478 switch (quote_char) {
1480 chars_to_escape = " \t\\'\"`";
1483 chars_to_escape = "";
1486 chars_to_escape = "$\"`\\";
1489 assert(false && "Unhandled quote character");
1493 res.reserve(arg.size());
1494 for (char c : arg) {
1495 if (::strchr(chars_to_escape, c))
1496 res.push_back('\\');