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 //===----------------------------------------------------------------------===//
10 #include "lldb/lldb-python.h"
16 // Other libraries and framework includes
18 #include "lldb/Interpreter/Args.h"
19 #include "lldb/Core/Stream.h"
20 #include "lldb/Core/StreamFile.h"
21 #include "lldb/Core/StreamString.h"
22 #include "lldb/DataFormatters/FormatManager.h"
23 #include "lldb/Interpreter/Options.h"
24 #include "lldb/Interpreter/CommandReturnObject.h"
25 #include "lldb/Target/Process.h"
26 //#include "lldb/Target/RegisterContext.h"
27 #include "lldb/Target/StackFrame.h"
28 #include "lldb/Target/Target.h"
29 //#include "lldb/Target/Thread.h"
32 using namespace lldb_private;
34 //----------------------------------------------------------------------
36 //----------------------------------------------------------------------
37 Args::Args (const char *command) :
43 SetCommandString (command);
47 Args::Args (const char *command, size_t len) :
53 SetCommandString (command, len);
56 //----------------------------------------------------------------------
57 // We have to be very careful on the copy constructor of this class
58 // to make sure we copy all of the string values, but we can't copy the
59 // rhs.m_argv into m_argv since it will point to the "const char *" c
60 // strings in rhs.m_args. We need to copy the string list and update our
61 // own m_argv appropriately.
62 //----------------------------------------------------------------------
63 Args::Args (const Args &rhs) :
66 m_args_quote_char(rhs.m_args_quote_char)
71 //----------------------------------------------------------------------
72 // We have to be very careful on the copy constructor of this class
73 // to make sure we copy all of the string values, but we can't copy the
74 // rhs.m_argv into m_argv since it will point to the "const char *" c
75 // strings in rhs.m_args. We need to copy the string list and update our
76 // own m_argv appropriately.
77 //----------------------------------------------------------------------
79 Args::operator= (const Args &rhs)
81 // Make sure we aren't assigning to self
85 m_args_quote_char = rhs.m_args_quote_char;
91 //----------------------------------------------------------------------
93 //----------------------------------------------------------------------
99 Args::Dump (Stream *s)
101 const size_t argc = m_argv.size();
102 for (size_t i=0; i<argc; ++i)
105 const char *arg_cstr = m_argv[i];
107 s->Printf("argv[%zi]=\"%s\"\n", i, arg_cstr);
109 s->Printf("argv[%zi]=NULL\n", i);
115 Args::GetCommandString (std::string &command) const
118 const size_t argc = GetArgumentCount();
119 for (size_t i=0; i<argc; ++i)
123 command += m_argv[i];
129 Args::GetQuotedCommandString (std::string &command) const
132 const size_t argc = GetArgumentCount();
133 for (size_t i = 0; i < argc; ++i)
136 command.append (1, ' ');
137 char quote_char = GetArgumentQuoteCharAtIndex(i);
140 command.append (1, quote_char);
141 command.append (m_argv[i]);
142 command.append (1, quote_char);
145 command.append (m_argv[i]);
151 Args::SetCommandString (const char *command, size_t len)
153 // Use std::string to make sure we get a NULL terminated string we can use
154 // as "command" could point to a string within a large string....
155 std::string null_terminated_command(command, len);
156 SetCommandString(null_terminated_command.c_str());
160 Args::SetCommandString (const char *command)
164 m_args_quote_char.clear();
166 if (command && command[0])
168 static const char *k_space_separators = " \t";
169 static const char *k_space_separators_with_slash_and_quotes = " \t \\'\"";
170 const char *arg_end = NULL;
172 for (arg_pos = command;
173 arg_pos && arg_pos[0];
176 // Skip any leading space separators
177 const char *arg_start = ::strspn (arg_pos, k_space_separators) + arg_pos;
179 // If there were only space separators to the end of the line, then
181 if (*arg_start == '\0')
184 // Arguments can be split into multiple discontiguous pieces,
187 // this would result in a single argument "Hello World" (without/
188 // the quotes) since the quotes would be removed and there is
189 // not space between the strings. So we need to keep track of the
190 // current start of each argument piece in "arg_piece_start"
191 const char *arg_piece_start = arg_start;
192 arg_pos = arg_piece_start;
195 // Since we can have multiple quotes that form a single command
196 // in a command like: "Hello "world'!' (which will make a single
197 // argument "Hello world!") we remember the first quote character
198 // we encounter and use that for the quote character.
199 char first_quote_char = '\0';
200 char quote_char = '\0';
201 bool arg_complete = false;
205 arg_end = ::strcspn (arg_pos, k_space_separators_with_slash_and_quotes) + arg_pos;
210 assert (!"Unhandled case statement, we must handle this...");
215 if (arg_piece_start && arg_piece_start[0])
216 arg.append (arg_piece_start);
221 // Backslash character
225 arg.append (arg_piece_start);
231 if (quote_char == '\0')
233 arg.append (arg_piece_start, arg_end - arg_piece_start);
234 if (arg_end[1] != '\0')
236 arg.append (arg_end + 1, 1);
237 arg_pos = arg_end + 2;
238 arg_piece_start = arg_pos;
242 arg_pos = arg_end + 2;
253 // We found a quote character while inside a quoted
254 // character argument. If it matches our current quote
255 // character, this ends the effect of the quotes. If it
256 // doesn't we ignore it.
257 if (quote_char == arg_end[0])
259 arg.append (arg_piece_start, arg_end - arg_piece_start);
260 // Clear the quote character and let parsing
261 // continue (we need to watch for things like:
265 // All of which will result in a single argument "Hello World"
266 quote_char = '\0'; // Note that we are no longer inside quotes
267 arg_pos = arg_end + 1; // Skip the quote character
268 arg_piece_start = arg_pos; // Note we are starting from later in the string
272 // different quote, skip it and keep going
273 arg_pos = arg_end + 1;
278 // We found the start of a quote scope.
279 // Make sure there isn't a string that precedes
280 // the start of a quote scope like:
282 // If so, then add the "Hello" to the arg
283 if (arg_end > arg_piece_start)
284 arg.append (arg_piece_start, arg_end - arg_piece_start);
286 // Enter into a quote scope
287 quote_char = arg_end[0];
289 if (first_quote_char == '\0')
290 first_quote_char = quote_char;
293 ++arg_pos; // Skip the quote character
294 arg_piece_start = arg_pos; // Note we are starting from later in the string
296 // Skip till the next quote character
297 const char *end_quote = ::strchr (arg_piece_start, quote_char);
298 while (end_quote && end_quote[-1] == '\\')
300 // Don't skip the quote character if it is
301 // preceded by a '\' character
302 end_quote = ::strchr (end_quote + 1, quote_char);
307 if (end_quote > arg_piece_start)
308 arg.append (arg_piece_start, end_quote - arg_piece_start);
310 // If the next character is a space or the end of
311 // string, this argument is complete...
312 if (end_quote[1] == ' ' || end_quote[1] == '\t' || end_quote[1] == '\0')
315 arg_end = end_quote + 1;
319 arg_pos = end_quote + 1;
320 arg_piece_start = arg_pos;
326 // Consume the rest of the string as there was no terminating quote
327 arg.append(arg_piece_start);
328 arg_end = arg_piece_start + strlen(arg_piece_start);
338 // We are currently processing a quoted character and found
339 // a space character, skip any spaces and keep trying to find
340 // the end of the argument.
341 arg_pos = ::strspn (arg_end, k_space_separators) + arg_end;
345 // We are not inside any quotes, we just found a space after an
347 if (arg_end > arg_piece_start)
348 arg.append (arg_piece_start, arg_end - arg_piece_start);
353 } while (!arg_complete);
355 m_args.push_back(arg);
356 m_args_quote_char.push_back (first_quote_char);
358 UpdateArgvFromArgs();
363 Args::UpdateArgsAfterOptionParsing()
365 // Now m_argv might be out of date with m_args, so we need to fix that
366 arg_cstr_collection::const_iterator argv_pos, argv_end = m_argv.end();
367 arg_sstr_collection::iterator args_pos;
368 arg_quote_char_collection::iterator quotes_pos;
370 for (argv_pos = m_argv.begin(), args_pos = m_args.begin(), quotes_pos = m_args_quote_char.begin();
371 argv_pos != argv_end && args_pos != m_args.end();
374 const char *argv_cstr = *argv_pos;
375 if (argv_cstr == NULL)
378 while (args_pos != m_args.end())
380 const char *args_cstr = args_pos->c_str();
381 if (args_cstr == argv_cstr)
383 // We found the argument that matches the C string in the
384 // vector, so we can now look for the next one
391 quotes_pos = m_args_quote_char.erase (quotes_pos);
392 args_pos = m_args.erase (args_pos);
397 if (args_pos != m_args.end())
398 m_args.erase (args_pos, m_args.end());
400 if (quotes_pos != m_args_quote_char.end())
401 m_args_quote_char.erase (quotes_pos, m_args_quote_char.end());
405 Args::UpdateArgvFromArgs()
408 arg_sstr_collection::const_iterator pos, end = m_args.end();
409 for (pos = m_args.begin(); pos != end; ++pos)
410 m_argv.push_back(pos->c_str());
411 m_argv.push_back(NULL);
412 // Make sure we have enough arg quote chars in the array
413 if (m_args_quote_char.size() < m_args.size())
414 m_args_quote_char.resize (m_argv.size());
418 Args::GetArgumentCount() const
422 return m_argv.size() - 1;
426 Args::GetArgumentAtIndex (size_t idx) const
428 if (idx < m_argv.size())
434 Args::GetArgumentQuoteCharAtIndex (size_t idx) const
436 if (idx < m_args_quote_char.size())
437 return m_args_quote_char[idx];
442 Args::GetArgumentVector()
445 return (char **)&m_argv[0];
450 Args::GetConstArgumentVector() const
453 return (const char **)&m_argv[0];
460 // Don't pop the last NULL terminator from the argv array
461 if (m_argv.size() > 1)
463 m_argv.erase(m_argv.begin());
465 if (!m_args_quote_char.empty())
466 m_args_quote_char.erase(m_args_quote_char.begin());
471 Args::Unshift (const char *arg_cstr, char quote_char)
473 m_args.push_front(arg_cstr);
474 m_argv.insert(m_argv.begin(), m_args.front().c_str());
475 m_args_quote_char.insert(m_args_quote_char.begin(), quote_char);
476 return GetArgumentAtIndex (0);
480 Args::AppendArguments (const Args &rhs)
482 const size_t rhs_argc = rhs.GetArgumentCount();
483 for (size_t i=0; i<rhs_argc; ++i)
484 AppendArgument(rhs.GetArgumentAtIndex(i));
488 Args::AppendArguments (const char **argv)
492 for (uint32_t i=0; argv[i]; ++i)
493 AppendArgument(argv[i]);
498 Args::AppendArgument (const char *arg_cstr, char quote_char)
500 return InsertArgumentAtIndex (GetArgumentCount(), arg_cstr, quote_char);
504 Args::InsertArgumentAtIndex (size_t idx, const char *arg_cstr, char quote_char)
506 // Since we are using a std::list to hold onto the copied C string and
507 // we don't have direct access to the elements, we have to iterate to
509 arg_sstr_collection::iterator pos, end = m_args.end();
511 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
514 pos = m_args.insert(pos, arg_cstr);
516 if (idx >= m_args_quote_char.size())
518 m_args_quote_char.resize(idx + 1);
519 m_args_quote_char[idx] = quote_char;
522 m_args_quote_char.insert(m_args_quote_char.begin() + idx, quote_char);
524 UpdateArgvFromArgs();
525 return GetArgumentAtIndex(idx);
529 Args::ReplaceArgumentAtIndex (size_t idx, const char *arg_cstr, char quote_char)
531 // Since we are using a std::list to hold onto the copied C string and
532 // we don't have direct access to the elements, we have to iterate to
534 arg_sstr_collection::iterator pos, end = m_args.end();
536 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
541 pos->assign(arg_cstr);
542 assert(idx < m_argv.size() - 1);
543 m_argv[idx] = pos->c_str();
544 if (idx >= m_args_quote_char.size())
545 m_args_quote_char.resize(idx + 1);
546 m_args_quote_char[idx] = quote_char;
547 return GetArgumentAtIndex(idx);
553 Args::DeleteArgumentAtIndex (size_t idx)
555 // Since we are using a std::list to hold onto the copied C string and
556 // we don't have direct access to the elements, we have to iterate to
558 arg_sstr_collection::iterator pos, end = m_args.end();
560 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
566 assert(idx < m_argv.size() - 1);
567 m_argv.erase(m_argv.begin() + idx);
568 if (idx < m_args_quote_char.size())
569 m_args_quote_char.erase(m_args_quote_char.begin() + idx);
574 Args::SetArguments (size_t argc, const char **argv)
576 // m_argv will be rebuilt in UpdateArgvFromArgs() below, so there is
577 // no need to clear it here.
579 m_args_quote_char.clear();
581 // First copy each string
582 for (size_t i=0; i<argc; ++i)
584 m_args.push_back (argv[i]);
585 if ((argv[i][0] == '\'') || (argv[i][0] == '"') || (argv[i][0] == '`'))
586 m_args_quote_char.push_back (argv[i][0]);
588 m_args_quote_char.push_back ('\0');
591 UpdateArgvFromArgs();
595 Args::SetArguments (const char **argv)
597 // m_argv will be rebuilt in UpdateArgvFromArgs() below, so there is
598 // no need to clear it here.
600 m_args_quote_char.clear();
604 // First copy each string
605 for (size_t i=0; argv[i]; ++i)
607 m_args.push_back (argv[i]);
608 if ((argv[i][0] == '\'') || (argv[i][0] == '"') || (argv[i][0] == '`'))
609 m_args_quote_char.push_back (argv[i][0]);
611 m_args_quote_char.push_back ('\0');
615 UpdateArgvFromArgs();
620 Args::ParseOptions (Options &options)
624 struct option *long_options = options.GetLongOptions();
625 if (long_options == NULL)
627 error.SetErrorStringWithFormat("invalid long options");
631 for (int i=0; long_options[i].name != NULL; ++i)
633 if (long_options[i].flag == NULL)
635 if (isprint8(long_options[i].val))
637 sstr << (char)long_options[i].val;
638 switch (long_options[i].has_arg)
641 case no_argument: break;
642 case required_argument: sstr << ':'; break;
643 case optional_argument: sstr << "::"; break;
657 int long_options_index = -1;
658 val = ::getopt_long_only(GetArgumentCount(),
662 &long_options_index);
666 // Did we get an error?
669 error.SetErrorStringWithFormat("unknown or ambiguous option");
672 // The option auto-set itself
676 ((Options *) &options)->OptionSeen (val);
678 // Lookup the long option index
679 if (long_options_index == -1)
682 long_options[i].name || long_options[i].has_arg || long_options[i].flag || long_options[i].val;
685 if (long_options[i].val == val)
687 long_options_index = i;
692 // Call the callback with the option
693 if (long_options_index >= 0)
695 error = options.SetOptionValue(long_options_index,
696 long_options[long_options_index].has_arg == no_argument ? NULL : optarg);
700 error.SetErrorStringWithFormat("invalid option with value '%i'", val);
706 // Update our ARGV now that get options has consumed all the options
707 m_argv.erase(m_argv.begin(), m_argv.begin() + optind);
708 UpdateArgsAfterOptionParsing ();
717 m_args_quote_char.clear();
721 Args::StringToSInt32 (const char *s, int32_t fail_value, int base, bool *success_ptr)
726 const long sval = ::strtol (s, &end, base);
730 *success_ptr = ((sval <= INT32_MAX) && (sval >= INT32_MIN));
731 return (int32_t)sval; // All characters were used, return the result
734 if (success_ptr) *success_ptr = false;
739 Args::StringToUInt32 (const char *s, uint32_t fail_value, int base, bool *success_ptr)
744 const unsigned long uval = ::strtoul (s, &end, base);
748 *success_ptr = (uval <= UINT32_MAX);
749 return (uint32_t)uval; // All characters were used, return the result
752 if (success_ptr) *success_ptr = false;
758 Args::StringToSInt64 (const char *s, int64_t fail_value, int base, bool *success_ptr)
763 int64_t uval = ::strtoll (s, &end, base);
766 if (success_ptr) *success_ptr = true;
767 return uval; // All characters were used, return the result
770 if (success_ptr) *success_ptr = false;
775 Args::StringToUInt64 (const char *s, uint64_t fail_value, int base, bool *success_ptr)
780 uint64_t uval = ::strtoull (s, &end, base);
783 if (success_ptr) *success_ptr = true;
784 return uval; // All characters were used, return the result
787 if (success_ptr) *success_ptr = false;
792 Args::StringToAddress (const ExecutionContext *exe_ctx, const char *s, lldb::addr_t fail_value, Error *error_ptr)
794 bool error_set = false;
798 lldb::addr_t addr = ::strtoull (s, &end, 0);
803 return addr; // All characters were used, return the result
805 // Try base 16 with no prefix...
806 addr = ::strtoull (s, &end, 16);
811 return addr; // All characters were used, return the result
816 Target *target = exe_ctx->GetTargetPtr();
819 lldb::ValueObjectSP valobj_sp;
820 EvaluateExpressionOptions options;
821 options.SetCoerceToId(false);
822 options.SetUnwindOnError(true);
823 options.SetKeepInMemory(false);
824 options.SetRunOthers(true);
826 ExecutionResults expr_result = target->EvaluateExpression(s,
827 exe_ctx->GetFramePtr(),
831 bool success = false;
832 if (expr_result == eExecutionCompleted)
834 // Get the address to watch.
835 addr = valobj_sp->GetValueAsUnsigned(fail_value, &success);
847 error_ptr->SetErrorStringWithFormat("address expression \"%s\" resulted in a value whose type can't be converted to an address: %s", s, valobj_sp->GetTypeName().GetCString());
854 // Since the compiler can't handle things like "main + 12" we should
855 // try to do this for now. The compliler doesn't like adding offsets
856 // to function pointer types.
857 static RegularExpression g_symbol_plus_offset_regex("^(.*)([-\\+])[[:space:]]*(0x[0-9A-Fa-f]+|[0-9]+)[[:space:]]*$");
858 RegularExpression::Match regex_match(3);
859 if (g_symbol_plus_offset_regex.Execute(s, ®ex_match))
865 if (regex_match.GetMatchAtIndex(s, 1, name))
867 if (regex_match.GetMatchAtIndex(s, 2, str))
871 if (regex_match.GetMatchAtIndex(s, 3, str))
873 offset = Args::StringToUInt64(str.c_str(), 0, 0, &success);
878 addr = StringToAddress (exe_ctx, name.c_str(), LLDB_INVALID_ADDRESS, &error);
879 if (addr != LLDB_INVALID_ADDRESS)
882 return addr + offset;
884 return addr - offset;
895 error_ptr->SetErrorStringWithFormat("address expression \"%s\" evaluation failed", s);
904 error_ptr->SetErrorStringWithFormat("invalid address expression \"%s\"", s);
910 Args::StripSpaces (std::string &s, bool leading, bool trailing, bool return_null_if_empty)
912 static const char *k_white_space = " \t\v";
917 size_t pos = s.find_first_not_of (k_white_space);
918 if (pos == std::string::npos)
926 size_t rpos = s.find_last_not_of(k_white_space);
927 if (rpos != std::string::npos && rpos + 1 < s.size())
931 if (return_null_if_empty && s.empty())
937 Args::StringToBoolean (const char *s, bool fail_value, bool *success_ptr)
941 if (::strcasecmp (s, "false") == 0 ||
942 ::strcasecmp (s, "off") == 0 ||
943 ::strcasecmp (s, "no") == 0 ||
944 ::strcmp (s, "0") == 0)
951 if (::strcasecmp (s, "true") == 0 ||
952 ::strcasecmp (s, "on") == 0 ||
953 ::strcasecmp (s, "yes") == 0 ||
954 ::strcmp (s, "1") == 0)
956 if (success_ptr) *success_ptr = true;
960 if (success_ptr) *success_ptr = false;
965 Args::StringToVersion (const char *s, uint32_t &major, uint32_t &minor, uint32_t &update)
974 unsigned long uval32 = ::strtoul (s, &pos, 0);
980 return pos; // Decoded major and got end of string
982 else if (*pos == '.')
984 const char *minor_cstr = pos + 1;
985 uval32 = ::strtoul (minor_cstr, &pos, 0);
986 if (pos == minor_cstr)
987 return pos; // Didn't get any digits for the minor version...
991 const char *update_cstr = pos + 1;
992 uval32 = ::strtoul (update_cstr, &pos, 0);
993 if (pos == update_cstr)
1004 Args::GetShellSafeArgument (const char *unsafe_arg, std::string &safe_arg)
1006 safe_arg.assign (unsafe_arg);
1007 size_t prev_pos = 0;
1008 while (prev_pos < safe_arg.size())
1010 // Escape spaces and quotes
1011 size_t pos = safe_arg.find_first_of(" '\"", prev_pos);
1012 if (pos != std::string::npos)
1014 safe_arg.insert (pos, 1, '\\');
1020 return safe_arg.c_str();
1025 Args::StringToOptionEnum (const char *s, OptionEnumValueElement *enum_values, int32_t fail_value, Error &error)
1031 for (int i = 0; enum_values[i].string_value != NULL ; i++)
1033 if (strstr(enum_values[i].string_value, s) == enum_values[i].string_value)
1036 return enum_values[i].value;
1042 strm.PutCString ("invalid enumeration value, valid values are: ");
1043 for (int i = 0; enum_values[i].string_value != NULL; i++)
1045 strm.Printf ("%s\"%s\"",
1047 enum_values[i].string_value);
1049 error.SetErrorString(strm.GetData());
1053 error.SetErrorString ("invalid enumeration argument");
1059 Args::StringToScriptLanguage (const char *s, ScriptLanguage fail_value, bool *success_ptr)
1063 if ((::strcasecmp (s, "python") == 0) ||
1064 (::strcasecmp (s, "default") == 0 && eScriptLanguagePython == eScriptLanguageDefault))
1066 if (success_ptr) *success_ptr = true;
1067 return eScriptLanguagePython;
1069 if (::strcasecmp (s, "none"))
1071 if (success_ptr) *success_ptr = true;
1072 return eScriptLanguageNone;
1075 if (success_ptr) *success_ptr = false;
1080 Args::StringToFormat
1083 lldb::Format &format,
1084 size_t *byte_size_ptr
1087 format = eFormatInvalid;
1096 char *format_char = NULL;
1097 unsigned long byte_size = ::strtoul (s, &format_char, 0);
1098 if (byte_size != ULONG_MAX)
1099 *byte_size_ptr = byte_size;
1106 const bool partial_match_ok = true;
1107 if (!FormatManager::GetFormatFromCString (s, partial_match_ok, format))
1109 StreamString error_strm;
1110 error_strm.Printf ("Invalid format character or name '%s'. Valid values are:\n", s);
1111 for (Format f = eFormatDefault; f < kNumFormats; f = Format(f+1))
1113 char format_char = FormatManager::GetFormatAsFormatChar(f);
1115 error_strm.Printf ("'%c' or ", format_char);
1117 error_strm.Printf ("\"%s\"", FormatManager::GetFormatAsCString(f));
1122 error_strm.PutCString ("An optional byte size can precede the format character.\n");
1123 error.SetErrorString(error_strm.GetString().c_str());
1131 error.SetErrorStringWithFormat("%s option string", s ? "empty" : "invalid");
1137 Args::StringToEncoding (const char *s, lldb::Encoding fail_value)
1141 if (strcmp(s, "uint") == 0)
1142 return eEncodingUint;
1143 else if (strcmp(s, "sint") == 0)
1144 return eEncodingSint;
1145 else if (strcmp(s, "ieee754") == 0)
1146 return eEncodingIEEE754;
1147 else if (strcmp(s, "vector") == 0)
1148 return eEncodingVector;
1154 Args::StringToGenericRegister (const char *s)
1158 if (strcmp(s, "pc") == 0)
1159 return LLDB_REGNUM_GENERIC_PC;
1160 else if (strcmp(s, "sp") == 0)
1161 return LLDB_REGNUM_GENERIC_SP;
1162 else if (strcmp(s, "fp") == 0)
1163 return LLDB_REGNUM_GENERIC_FP;
1164 else if (strcmp(s, "ra") == 0)
1165 return LLDB_REGNUM_GENERIC_RA;
1166 else if (strcmp(s, "flags") == 0)
1167 return LLDB_REGNUM_GENERIC_FLAGS;
1168 else if (strncmp(s, "arg", 3) == 0)
1170 if (s[3] && s[4] == '\0')
1174 case '1': return LLDB_REGNUM_GENERIC_ARG1;
1175 case '2': return LLDB_REGNUM_GENERIC_ARG2;
1176 case '3': return LLDB_REGNUM_GENERIC_ARG3;
1177 case '4': return LLDB_REGNUM_GENERIC_ARG4;
1178 case '5': return LLDB_REGNUM_GENERIC_ARG5;
1179 case '6': return LLDB_REGNUM_GENERIC_ARG6;
1180 case '7': return LLDB_REGNUM_GENERIC_ARG7;
1181 case '8': return LLDB_REGNUM_GENERIC_ARG8;
1186 return LLDB_INVALID_REGNUM;
1191 Args::LongestCommonPrefix (std::string &common_prefix)
1193 arg_sstr_collection::iterator pos, end = m_args.end();
1194 pos = m_args.begin();
1196 common_prefix.clear();
1198 common_prefix = (*pos);
1200 for (++pos; pos != end; ++pos)
1202 size_t new_size = (*pos).size();
1204 // First trim common_prefix if it is longer than the current element:
1205 if (common_prefix.size() > new_size)
1206 common_prefix.erase (new_size);
1208 // Then trim it at the first disparity:
1210 for (size_t i = 0; i < common_prefix.size(); i++)
1212 if ((*pos)[i] != common_prefix[i])
1214 common_prefix.erase(i);
1219 // If we've emptied the common prefix, we're done.
1220 if (common_prefix.empty())
1226 Args::FindArgumentIndexForOption (struct option *long_options, int long_options_index)
1228 char short_buffer[3];
1229 char long_buffer[255];
1230 ::snprintf (short_buffer, sizeof (short_buffer), "-%c", long_options[long_options_index].val);
1231 ::snprintf (long_buffer, sizeof (long_buffer), "--%s", long_options[long_options_index].name);
1232 size_t end = GetArgumentCount ();
1236 if ((::strncmp (GetArgumentAtIndex (idx), short_buffer, strlen (short_buffer)) == 0)
1237 || (::strncmp (GetArgumentAtIndex (idx), long_buffer, strlen (long_buffer)) == 0))
1248 Args::IsPositionalArgument (const char *arg)
1253 bool is_positional = true;
1254 char *cptr = (char *) arg;
1259 while (isdigit (cptr[0]))
1261 if (cptr[0] != '\0')
1262 is_positional = false;
1265 is_positional = false;
1267 return is_positional;
1271 Args::ParseAliasOptions (Options &options,
1272 CommandReturnObject &result,
1273 OptionArgVector *option_arg_vector,
1274 std::string &raw_input_string)
1278 struct option *long_options = options.GetLongOptions();
1280 if (long_options == NULL)
1282 result.AppendError ("invalid long options");
1283 result.SetStatus (eReturnStatusFailed);
1287 for (i = 0; long_options[i].name != NULL; ++i)
1289 if (long_options[i].flag == NULL)
1291 sstr << (char) long_options[i].val;
1292 switch (long_options[i].has_arg)
1297 case required_argument:
1300 case optional_argument:
1316 int long_options_index = -1;
1317 val = ::getopt_long_only (GetArgumentCount(),
1318 GetArgumentVector(),
1321 &long_options_index);
1328 result.AppendError ("unknown or ambiguous option");
1329 result.SetStatus (eReturnStatusFailed);
1336 ((Options *) &options)->OptionSeen (val);
1338 // Look up the long option index
1339 if (long_options_index == -1)
1342 long_options[j].name || long_options[j].has_arg || long_options[j].flag || long_options[j].val;
1345 if (long_options[j].val == val)
1347 long_options_index = j;
1353 // See if the option takes an argument, and see if one was supplied.
1354 if (long_options_index >= 0)
1356 StreamString option_str;
1357 option_str.Printf ("-%c", val);
1359 switch (long_options[long_options_index].has_arg)
1362 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
1363 OptionArgValue (no_argument, "<no-argument>")));
1364 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1366 case required_argument:
1369 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
1370 OptionArgValue (required_argument,
1371 std::string (optarg))));
1372 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1376 result.AppendErrorWithFormat ("Option '%s' is missing argument specifier.\n",
1377 option_str.GetData());
1378 result.SetStatus (eReturnStatusFailed);
1381 case optional_argument:
1384 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
1385 OptionArgValue (optional_argument,
1386 std::string (optarg))));
1387 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1391 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
1392 OptionArgValue (optional_argument, "<no-argument>")));
1393 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1397 result.AppendErrorWithFormat ("error with options table; invalid value in has_arg field for option '%c'.\n", val);
1398 result.SetStatus (eReturnStatusFailed);
1404 result.AppendErrorWithFormat ("Invalid option with value '%c'.\n", val);
1405 result.SetStatus (eReturnStatusFailed);
1408 if (long_options_index >= 0)
1410 // Find option in the argument list; also see if it was supposed to take an argument and if one was
1411 // supplied. Remove option (and argument, if given) from the argument list. Also remove them from
1412 // the raw_input_string, if one was passed in.
1413 size_t idx = FindArgumentIndexForOption (long_options, long_options_index);
1414 if (idx < GetArgumentCount())
1416 if (raw_input_string.size() > 0)
1418 const char *tmp_arg = GetArgumentAtIndex (idx);
1419 size_t pos = raw_input_string.find (tmp_arg);
1420 if (pos != std::string::npos)
1421 raw_input_string.erase (pos, strlen (tmp_arg));
1423 ReplaceArgumentAtIndex (idx, "");
1424 if ((long_options[long_options_index].has_arg != no_argument)
1426 && (idx+1 < GetArgumentCount())
1427 && (strcmp (optarg, GetArgumentAtIndex(idx+1)) == 0))
1429 if (raw_input_string.size() > 0)
1431 const char *tmp_arg = GetArgumentAtIndex (idx+1);
1432 size_t pos = raw_input_string.find (tmp_arg);
1433 if (pos != std::string::npos)
1434 raw_input_string.erase (pos, strlen (tmp_arg));
1436 ReplaceArgumentAtIndex (idx+1, "");
1441 if (!result.Succeeded())
1447 Args::ParseArgsForCompletion
1450 OptionElementVector &option_element_vector,
1451 uint32_t cursor_index
1455 struct option *long_options = options.GetLongOptions();
1456 option_element_vector.clear();
1458 if (long_options == NULL)
1463 // Leading : tells getopt to return a : for a missing option argument AND
1464 // to suppress error messages.
1467 for (int i = 0; long_options[i].name != NULL; ++i)
1469 if (long_options[i].flag == NULL)
1471 sstr << (char) long_options[i].val;
1472 switch (long_options[i].has_arg)
1477 case required_argument:
1480 case optional_argument:
1496 const OptionDefinition *opt_defs = options.GetDefinitions();
1498 // Fooey... getopt_long_only permutes the GetArgumentVector to move the options to the front.
1499 // So we have to build another Arg and pass that to getopt_long_only so it doesn't
1500 // change the one we have.
1502 std::vector<const char *> dummy_vec (GetArgumentVector(), GetArgumentVector() + GetArgumentCount() + 1);
1504 bool failed_once = false;
1505 uint32_t dash_dash_pos = -1;
1509 bool missing_argument = false;
1510 int long_options_index = -1;
1512 val = ::getopt_long_only (dummy_vec.size() - 1,
1513 (char *const *) &dummy_vec.front(),
1516 &long_options_index);
1520 // When we're completing a "--" which is the last option on line,
1526 // If this is a bare "--" we mark it as such so we can complete it successfully later.
1527 // Handling the "--" is a little tricky, since that may mean end of options or arguments, or the
1528 // user might want to complete options by long name. I make this work by checking whether the
1529 // cursor is in the "--" argument, and if so I assume we're completing the long option, otherwise
1530 // I let it pass to getopt_long_only which will terminate the option parsing.
1531 // Note, in either case we continue parsing the line so we can figure out what other options
1532 // were passed. This will be useful when we come to restricting completions based on what other
1533 // options we've seen on the line.
1535 if (optind < dummy_vec.size() - 1
1536 && (strcmp (dummy_vec[optind-1], "--") == 0))
1538 dash_dash_pos = optind - 1;
1539 if (optind - 1 == cursor_index)
1541 option_element_vector.push_back (OptionArgElement (OptionArgElement::eBareDoubleDash, optind - 1,
1542 OptionArgElement::eBareDoubleDash));
1551 else if (val == '?')
1553 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1554 OptionArgElement::eUnrecognizedArg));
1561 else if (val == ':')
1563 // This is a missing argument.
1565 missing_argument = true;
1568 ((Options *) &options)->OptionSeen (val);
1570 // Look up the long option index
1571 if (long_options_index == -1)
1574 long_options[j].name || long_options[j].has_arg || long_options[j].flag || long_options[j].val;
1577 if (long_options[j].val == val)
1579 long_options_index = j;
1585 // See if the option takes an argument, and see if one was supplied.
1586 if (long_options_index >= 0)
1588 int opt_defs_index = -1;
1589 for (int i = 0; ; i++)
1591 if (opt_defs[i].short_option == 0)
1593 else if (opt_defs[i].short_option == val)
1600 switch (long_options[long_options_index].has_arg)
1603 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 1, 0));
1605 case required_argument:
1609 if (missing_argument)
1612 arg_index = optind - 1;
1614 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, arg_index));
1618 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 1, -1));
1621 case optional_argument:
1624 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, optind - 1));
1628 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, optind - 1));
1632 // The options table is messed up. Here we'll just continue
1633 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1634 OptionArgElement::eUnrecognizedArg));
1640 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1641 OptionArgElement::eUnrecognizedArg));
1645 // Finally we have to handle the case where the cursor index points at a single "-". We want to mark that in
1646 // the option_element_vector, but only if it is not after the "--". But it turns out that getopt_long_only just ignores
1647 // an isolated "-". So we have to look it up by hand here. We only care if it is AT the cursor position.
1649 if ((dash_dash_pos == -1 || cursor_index < dash_dash_pos)
1650 && strcmp (GetArgumentAtIndex(cursor_index), "-") == 0)
1652 option_element_vector.push_back (OptionArgElement (OptionArgElement::eBareDash, cursor_index,
1653 OptionArgElement::eBareDash));
1659 Args::EncodeEscapeSequences (const char *src, std::string &dst)
1664 for (const char *p = src; *p != '\0'; ++p)
1666 size_t non_special_chars = ::strcspn (p, "\\");
1667 if (non_special_chars > 0)
1669 dst.append(p, non_special_chars);
1670 p += non_special_chars;
1677 ++p; // skip the slash
1680 case 'a' : dst.append(1, '\a'); break;
1681 case 'b' : dst.append(1, '\b'); break;
1682 case 'f' : dst.append(1, '\f'); break;
1683 case 'n' : dst.append(1, '\n'); break;
1684 case 'r' : dst.append(1, '\r'); break;
1685 case 't' : dst.append(1, '\t'); break;
1686 case 'v' : dst.append(1, '\v'); break;
1687 case '\\': dst.append(1, '\\'); break;
1688 case '\'': dst.append(1, '\''); break;
1689 case '"' : dst.append(1, '"'); break;
1691 // 1 to 3 octal chars
1693 // Make a string that can hold onto the initial zero char,
1694 // up to 3 octal digits, and a terminating NULL.
1695 char oct_str[5] = { '\0', '\0', '\0', '\0', '\0' };
1698 for (i=0; (p[i] >= '0' && p[i] <= '7') && i<4; ++i)
1701 // We don't want to consume the last octal character since
1702 // the main for loop will do this for us, so we advance p by
1703 // one less than i (even if i is zero)
1705 unsigned long octal_value = ::strtoul (oct_str, NULL, 8);
1706 if (octal_value <= UINT8_MAX)
1708 dst.append(1, (char)octal_value);
1714 // hex number in the format
1717 ++p; // Skip the 'x'
1719 // Make a string that can hold onto two hex chars plus a
1721 char hex_str[3] = { *p, '\0', '\0' };
1724 ++p; // Skip the first of the two hex chars
1728 unsigned long hex_value = strtoul (hex_str, NULL, 16);
1729 if (hex_value <= UINT8_MAX)
1730 dst.append (1, (char)hex_value);
1739 // Just desensitize any other character by just printing what
1740 // came after the '\'
1752 Args::ExpandEscapedCharacters (const char *src, std::string &dst)
1757 for (const char *p = src; *p != '\0'; ++p)
1765 case '\a': dst.append("\\a"); break;
1766 case '\b': dst.append("\\b"); break;
1767 case '\f': dst.append("\\f"); break;
1768 case '\n': dst.append("\\n"); break;
1769 case '\r': dst.append("\\r"); break;
1770 case '\t': dst.append("\\t"); break;
1771 case '\v': dst.append("\\v"); break;
1772 case '\'': dst.append("\\'"); break;
1773 case '"': dst.append("\\\""); break;
1774 case '\\': dst.append("\\\\"); break;
1777 // Just encode as octal
1780 snprintf(octal_str, sizeof(octal_str), "%o", *p);
1781 dst.append(octal_str);