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"
15 // Other libraries and framework includes
17 #include "lldb/Interpreter/Args.h"
18 #include "lldb/Core/Stream.h"
19 #include "lldb/Core/StreamFile.h"
20 #include "lldb/Core/StreamString.h"
21 #include "lldb/DataFormatters/FormatManager.h"
22 #include "lldb/Interpreter/Options.h"
23 #include "lldb/Interpreter/CommandReturnObject.h"
24 #include "lldb/Target/Process.h"
25 //#include "lldb/Target/RegisterContext.h"
26 #include "lldb/Target/StackFrame.h"
27 #include "lldb/Target/Target.h"
28 //#include "lldb/Target/Thread.h"
31 using namespace lldb_private;
33 //----------------------------------------------------------------------
35 //----------------------------------------------------------------------
36 Args::Args (const char *command) :
42 SetCommandString (command);
46 Args::Args (const char *command, size_t len) :
52 SetCommandString (command, len);
55 //----------------------------------------------------------------------
56 // We have to be very careful on the copy constructor of this class
57 // to make sure we copy all of the string values, but we can't copy the
58 // rhs.m_argv into m_argv since it will point to the "const char *" c
59 // strings in rhs.m_args. We need to copy the string list and update our
60 // own m_argv appropriately.
61 //----------------------------------------------------------------------
62 Args::Args (const Args &rhs) :
65 m_args_quote_char(rhs.m_args_quote_char)
70 //----------------------------------------------------------------------
71 // We have to be very careful on the copy constructor of this class
72 // to make sure we copy all of the string values, but we can't copy the
73 // rhs.m_argv into m_argv since it will point to the "const char *" c
74 // strings in rhs.m_args. We need to copy the string list and update our
75 // own m_argv appropriately.
76 //----------------------------------------------------------------------
78 Args::operator= (const Args &rhs)
80 // Make sure we aren't assigning to self
84 m_args_quote_char = rhs.m_args_quote_char;
90 //----------------------------------------------------------------------
92 //----------------------------------------------------------------------
98 Args::Dump (Stream *s)
100 const size_t argc = m_argv.size();
101 for (size_t i=0; i<argc; ++i)
104 const char *arg_cstr = m_argv[i];
106 s->Printf("argv[%zi]=\"%s\"\n", i, arg_cstr);
108 s->Printf("argv[%zi]=NULL\n", i);
114 Args::GetCommandString (std::string &command) const
117 const size_t argc = GetArgumentCount();
118 for (size_t i=0; i<argc; ++i)
122 command += m_argv[i];
128 Args::GetQuotedCommandString (std::string &command) const
131 const size_t argc = GetArgumentCount();
132 for (size_t i = 0; i < argc; ++i)
135 command.append (1, ' ');
136 char quote_char = GetArgumentQuoteCharAtIndex(i);
139 command.append (1, quote_char);
140 command.append (m_argv[i]);
141 command.append (1, quote_char);
144 command.append (m_argv[i]);
150 Args::SetCommandString (const char *command, size_t len)
152 // Use std::string to make sure we get a NULL terminated string we can use
153 // as "command" could point to a string within a large string....
154 std::string null_terminated_command(command, len);
155 SetCommandString(null_terminated_command.c_str());
159 Args::SetCommandString (const char *command)
163 m_args_quote_char.clear();
165 if (command && command[0])
167 static const char *k_space_separators = " \t";
168 static const char *k_space_separators_with_slash_and_quotes = " \t \\'\"";
169 const char *arg_end = NULL;
171 for (arg_pos = command;
172 arg_pos && arg_pos[0];
175 // Skip any leading space separators
176 const char *arg_start = ::strspn (arg_pos, k_space_separators) + arg_pos;
178 // If there were only space separators to the end of the line, then
180 if (*arg_start == '\0')
183 // Arguments can be split into multiple discontiguous pieces,
186 // this would result in a single argument "Hello World" (without/
187 // the quotes) since the quotes would be removed and there is
188 // not space between the strings. So we need to keep track of the
189 // current start of each argument piece in "arg_piece_start"
190 const char *arg_piece_start = arg_start;
191 arg_pos = arg_piece_start;
194 // Since we can have multiple quotes that form a single command
195 // in a command like: "Hello "world'!' (which will make a single
196 // argument "Hello world!") we remember the first quote character
197 // we encounter and use that for the quote character.
198 char first_quote_char = '\0';
199 char quote_char = '\0';
200 bool arg_complete = false;
204 arg_end = ::strcspn (arg_pos, k_space_separators_with_slash_and_quotes) + arg_pos;
209 assert (!"Unhandled case statement, we must handle this...");
214 if (arg_piece_start && arg_piece_start[0])
215 arg.append (arg_piece_start);
220 // Backslash character
224 arg.append (arg_piece_start);
230 if (quote_char == '\0')
232 arg.append (arg_piece_start, arg_end - arg_piece_start);
233 if (arg_end[1] != '\0')
235 arg.append (arg_end + 1, 1);
236 arg_pos = arg_end + 2;
237 arg_piece_start = arg_pos;
241 arg_pos = arg_end + 2;
252 // We found a quote character while inside a quoted
253 // character argument. If it matches our current quote
254 // character, this ends the effect of the quotes. If it
255 // doesn't we ignore it.
256 if (quote_char == arg_end[0])
258 arg.append (arg_piece_start, arg_end - arg_piece_start);
259 // Clear the quote character and let parsing
260 // continue (we need to watch for things like:
264 // All of which will result in a single argument "Hello World"
265 quote_char = '\0'; // Note that we are no longer inside quotes
266 arg_pos = arg_end + 1; // Skip the quote character
267 arg_piece_start = arg_pos; // Note we are starting from later in the string
271 // different quote, skip it and keep going
272 arg_pos = arg_end + 1;
277 // We found the start of a quote scope.
278 // Make sure there isn't a string that precedes
279 // the start of a quote scope like:
281 // If so, then add the "Hello" to the arg
282 if (arg_end > arg_piece_start)
283 arg.append (arg_piece_start, arg_end - arg_piece_start);
285 // Enter into a quote scope
286 quote_char = arg_end[0];
288 if (first_quote_char == '\0')
289 first_quote_char = quote_char;
292 ++arg_pos; // Skip the quote character
293 arg_piece_start = arg_pos; // Note we are starting from later in the string
295 // Skip till the next quote character
296 const char *end_quote = ::strchr (arg_piece_start, quote_char);
297 while (end_quote && end_quote[-1] == '\\')
299 // Don't skip the quote character if it is
300 // preceded by a '\' character
301 end_quote = ::strchr (end_quote + 1, quote_char);
306 if (end_quote > arg_piece_start)
307 arg.append (arg_piece_start, end_quote - arg_piece_start);
309 // If the next character is a space or the end of
310 // string, this argument is complete...
311 if (end_quote[1] == ' ' || end_quote[1] == '\t' || end_quote[1] == '\0')
314 arg_end = end_quote + 1;
318 arg_pos = end_quote + 1;
319 arg_piece_start = arg_pos;
325 // Consume the rest of the string as there was no terminating quote
326 arg.append(arg_piece_start);
327 arg_end = arg_piece_start + strlen(arg_piece_start);
337 // We are currently processing a quoted character and found
338 // a space character, skip any spaces and keep trying to find
339 // the end of the argument.
340 arg_pos = ::strspn (arg_end, k_space_separators) + arg_end;
344 // We are not inside any quotes, we just found a space after an
346 if (arg_end > arg_piece_start)
347 arg.append (arg_piece_start, arg_end - arg_piece_start);
352 } while (!arg_complete);
354 m_args.push_back(arg);
355 m_args_quote_char.push_back (first_quote_char);
357 UpdateArgvFromArgs();
362 Args::UpdateArgsAfterOptionParsing()
364 // Now m_argv might be out of date with m_args, so we need to fix that
365 arg_cstr_collection::const_iterator argv_pos, argv_end = m_argv.end();
366 arg_sstr_collection::iterator args_pos;
367 arg_quote_char_collection::iterator quotes_pos;
369 for (argv_pos = m_argv.begin(), args_pos = m_args.begin(), quotes_pos = m_args_quote_char.begin();
370 argv_pos != argv_end && args_pos != m_args.end();
373 const char *argv_cstr = *argv_pos;
374 if (argv_cstr == NULL)
377 while (args_pos != m_args.end())
379 const char *args_cstr = args_pos->c_str();
380 if (args_cstr == argv_cstr)
382 // We found the argument that matches the C string in the
383 // vector, so we can now look for the next one
390 quotes_pos = m_args_quote_char.erase (quotes_pos);
391 args_pos = m_args.erase (args_pos);
396 if (args_pos != m_args.end())
397 m_args.erase (args_pos, m_args.end());
399 if (quotes_pos != m_args_quote_char.end())
400 m_args_quote_char.erase (quotes_pos, m_args_quote_char.end());
404 Args::UpdateArgvFromArgs()
407 arg_sstr_collection::const_iterator pos, end = m_args.end();
408 for (pos = m_args.begin(); pos != end; ++pos)
409 m_argv.push_back(pos->c_str());
410 m_argv.push_back(NULL);
411 // Make sure we have enough arg quote chars in the array
412 if (m_args_quote_char.size() < m_args.size())
413 m_args_quote_char.resize (m_argv.size());
417 Args::GetArgumentCount() const
421 return m_argv.size() - 1;
425 Args::GetArgumentAtIndex (size_t idx) const
427 if (idx < m_argv.size())
433 Args::GetArgumentQuoteCharAtIndex (size_t idx) const
435 if (idx < m_args_quote_char.size())
436 return m_args_quote_char[idx];
441 Args::GetArgumentVector()
444 return (char **)&m_argv[0];
449 Args::GetConstArgumentVector() const
452 return (const char **)&m_argv[0];
459 // Don't pop the last NULL terminator from the argv array
460 if (m_argv.size() > 1)
462 m_argv.erase(m_argv.begin());
464 if (!m_args_quote_char.empty())
465 m_args_quote_char.erase(m_args_quote_char.begin());
470 Args::Unshift (const char *arg_cstr, char quote_char)
472 m_args.push_front(arg_cstr);
473 m_argv.insert(m_argv.begin(), m_args.front().c_str());
474 m_args_quote_char.insert(m_args_quote_char.begin(), quote_char);
475 return GetArgumentAtIndex (0);
479 Args::AppendArguments (const Args &rhs)
481 const size_t rhs_argc = rhs.GetArgumentCount();
482 for (size_t i=0; i<rhs_argc; ++i)
483 AppendArgument(rhs.GetArgumentAtIndex(i));
487 Args::AppendArguments (const char **argv)
491 for (uint32_t i=0; argv[i]; ++i)
492 AppendArgument(argv[i]);
497 Args::AppendArgument (const char *arg_cstr, char quote_char)
499 return InsertArgumentAtIndex (GetArgumentCount(), arg_cstr, quote_char);
503 Args::InsertArgumentAtIndex (size_t idx, const char *arg_cstr, char quote_char)
505 // Since we are using a std::list to hold onto the copied C string and
506 // we don't have direct access to the elements, we have to iterate to
508 arg_sstr_collection::iterator pos, end = m_args.end();
510 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
513 pos = m_args.insert(pos, arg_cstr);
515 if (idx >= m_args_quote_char.size())
517 m_args_quote_char.resize(idx + 1);
518 m_args_quote_char[idx] = quote_char;
521 m_args_quote_char.insert(m_args_quote_char.begin() + idx, quote_char);
523 UpdateArgvFromArgs();
524 return GetArgumentAtIndex(idx);
528 Args::ReplaceArgumentAtIndex (size_t idx, const char *arg_cstr, char quote_char)
530 // Since we are using a std::list to hold onto the copied C string and
531 // we don't have direct access to the elements, we have to iterate to
533 arg_sstr_collection::iterator pos, end = m_args.end();
535 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
540 pos->assign(arg_cstr);
541 assert(idx < m_argv.size() - 1);
542 m_argv[idx] = pos->c_str();
543 if (idx >= m_args_quote_char.size())
544 m_args_quote_char.resize(idx + 1);
545 m_args_quote_char[idx] = quote_char;
546 return GetArgumentAtIndex(idx);
552 Args::DeleteArgumentAtIndex (size_t idx)
554 // Since we are using a std::list to hold onto the copied C string and
555 // we don't have direct access to the elements, we have to iterate to
557 arg_sstr_collection::iterator pos, end = m_args.end();
559 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
565 assert(idx < m_argv.size() - 1);
566 m_argv.erase(m_argv.begin() + idx);
567 if (idx < m_args_quote_char.size())
568 m_args_quote_char.erase(m_args_quote_char.begin() + idx);
573 Args::SetArguments (size_t argc, const char **argv)
575 // m_argv will be rebuilt in UpdateArgvFromArgs() below, so there is
576 // no need to clear it here.
578 m_args_quote_char.clear();
580 // First copy each string
581 for (size_t i=0; i<argc; ++i)
583 m_args.push_back (argv[i]);
584 if ((argv[i][0] == '\'') || (argv[i][0] == '"') || (argv[i][0] == '`'))
585 m_args_quote_char.push_back (argv[i][0]);
587 m_args_quote_char.push_back ('\0');
590 UpdateArgvFromArgs();
594 Args::SetArguments (const char **argv)
596 // m_argv will be rebuilt in UpdateArgvFromArgs() below, so there is
597 // no need to clear it here.
599 m_args_quote_char.clear();
603 // First copy each string
604 for (size_t i=0; argv[i]; ++i)
606 m_args.push_back (argv[i]);
607 if ((argv[i][0] == '\'') || (argv[i][0] == '"') || (argv[i][0] == '`'))
608 m_args_quote_char.push_back (argv[i][0]);
610 m_args_quote_char.push_back ('\0');
614 UpdateArgvFromArgs();
619 Args::ParseOptions (Options &options)
623 Option *long_options = options.GetLongOptions();
624 if (long_options == NULL)
626 error.SetErrorStringWithFormat("invalid long options");
630 for (int i=0; long_options[i].name != NULL; ++i)
632 if (long_options[i].flag == NULL)
634 if (isprint8(long_options[i].val))
636 sstr << (char)long_options[i].val;
637 switch (long_options[i].has_arg)
640 case OptionParser::eNoArgument: break;
641 case OptionParser::eRequiredArgument: sstr << ':'; break;
642 case OptionParser::eOptionalArgument: sstr << "::"; break;
647 OptionParser::Prepare();
651 int long_options_index = -1;
652 val = OptionParser::Parse(GetArgumentCount(),
656 &long_options_index);
660 // Did we get an error?
663 error.SetErrorStringWithFormat("unknown or ambiguous option");
666 // The option auto-set itself
670 ((Options *) &options)->OptionSeen (val);
672 // Lookup the long option index
673 if (long_options_index == -1)
676 long_options[i].name || long_options[i].has_arg || long_options[i].flag || long_options[i].val;
679 if (long_options[i].val == val)
681 long_options_index = i;
686 // Call the callback with the option
687 if (long_options_index >= 0)
689 error = options.SetOptionValue(long_options_index,
690 long_options[long_options_index].has_arg == OptionParser::eNoArgument ? NULL : OptionParser::GetOptionArgument());
694 error.SetErrorStringWithFormat("invalid option with value '%i'", val);
700 // Update our ARGV now that get options has consumed all the options
701 m_argv.erase(m_argv.begin(), m_argv.begin() + OptionParser::GetOptionIndex());
702 UpdateArgsAfterOptionParsing ();
711 m_args_quote_char.clear();
715 Args::StringToSInt32 (const char *s, int32_t fail_value, int base, bool *success_ptr)
720 const long sval = ::strtol (s, &end, base);
724 *success_ptr = ((sval <= INT32_MAX) && (sval >= INT32_MIN));
725 return (int32_t)sval; // All characters were used, return the result
728 if (success_ptr) *success_ptr = false;
733 Args::StringToUInt32 (const char *s, uint32_t fail_value, int base, bool *success_ptr)
738 const unsigned long uval = ::strtoul (s, &end, base);
742 *success_ptr = (uval <= UINT32_MAX);
743 return (uint32_t)uval; // All characters were used, return the result
746 if (success_ptr) *success_ptr = false;
752 Args::StringToSInt64 (const char *s, int64_t fail_value, int base, bool *success_ptr)
757 int64_t uval = ::strtoll (s, &end, base);
760 if (success_ptr) *success_ptr = true;
761 return uval; // All characters were used, return the result
764 if (success_ptr) *success_ptr = false;
769 Args::StringToUInt64 (const char *s, uint64_t fail_value, int base, bool *success_ptr)
774 uint64_t uval = ::strtoull (s, &end, base);
777 if (success_ptr) *success_ptr = true;
778 return uval; // All characters were used, return the result
781 if (success_ptr) *success_ptr = false;
786 Args::StringToAddress (const ExecutionContext *exe_ctx, const char *s, lldb::addr_t fail_value, Error *error_ptr)
788 bool error_set = false;
792 lldb::addr_t addr = ::strtoull (s, &end, 0);
797 return addr; // All characters were used, return the result
799 // Try base 16 with no prefix...
800 addr = ::strtoull (s, &end, 16);
805 return addr; // All characters were used, return the result
810 Target *target = exe_ctx->GetTargetPtr();
813 lldb::ValueObjectSP valobj_sp;
814 EvaluateExpressionOptions options;
815 options.SetCoerceToId(false);
816 options.SetUnwindOnError(true);
817 options.SetKeepInMemory(false);
818 options.SetTryAllThreads(true);
820 ExecutionResults expr_result = target->EvaluateExpression(s,
821 exe_ctx->GetFramePtr(),
825 bool success = false;
826 if (expr_result == eExecutionCompleted)
828 // Get the address to watch.
829 addr = valobj_sp->GetValueAsUnsigned(fail_value, &success);
841 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());
848 // Since the compiler can't handle things like "main + 12" we should
849 // try to do this for now. The compliler doesn't like adding offsets
850 // to function pointer types.
851 static RegularExpression g_symbol_plus_offset_regex("^(.*)([-\\+])[[:space:]]*(0x[0-9A-Fa-f]+|[0-9]+)[[:space:]]*$");
852 RegularExpression::Match regex_match(3);
853 if (g_symbol_plus_offset_regex.Execute(s, ®ex_match))
859 if (regex_match.GetMatchAtIndex(s, 1, name))
861 if (regex_match.GetMatchAtIndex(s, 2, str))
865 if (regex_match.GetMatchAtIndex(s, 3, str))
867 offset = Args::StringToUInt64(str.c_str(), 0, 0, &success);
872 addr = StringToAddress (exe_ctx, name.c_str(), LLDB_INVALID_ADDRESS, &error);
873 if (addr != LLDB_INVALID_ADDRESS)
876 return addr + offset;
878 return addr - offset;
889 error_ptr->SetErrorStringWithFormat("address expression \"%s\" evaluation failed", s);
898 error_ptr->SetErrorStringWithFormat("invalid address expression \"%s\"", s);
904 Args::StripSpaces (std::string &s, bool leading, bool trailing, bool return_null_if_empty)
906 static const char *k_white_space = " \t\v";
911 size_t pos = s.find_first_not_of (k_white_space);
912 if (pos == std::string::npos)
920 size_t rpos = s.find_last_not_of(k_white_space);
921 if (rpos != std::string::npos && rpos + 1 < s.size())
925 if (return_null_if_empty && s.empty())
931 Args::StringToBoolean (const char *s, bool fail_value, bool *success_ptr)
935 if (::strcasecmp (s, "false") == 0 ||
936 ::strcasecmp (s, "off") == 0 ||
937 ::strcasecmp (s, "no") == 0 ||
938 ::strcmp (s, "0") == 0)
945 if (::strcasecmp (s, "true") == 0 ||
946 ::strcasecmp (s, "on") == 0 ||
947 ::strcasecmp (s, "yes") == 0 ||
948 ::strcmp (s, "1") == 0)
950 if (success_ptr) *success_ptr = true;
954 if (success_ptr) *success_ptr = false;
959 Args::StringToVersion (const char *s, uint32_t &major, uint32_t &minor, uint32_t &update)
968 unsigned long uval32 = ::strtoul (s, &pos, 0);
974 return pos; // Decoded major and got end of string
976 else if (*pos == '.')
978 const char *minor_cstr = pos + 1;
979 uval32 = ::strtoul (minor_cstr, &pos, 0);
980 if (pos == minor_cstr)
981 return pos; // Didn't get any digits for the minor version...
985 const char *update_cstr = pos + 1;
986 uval32 = ::strtoul (update_cstr, &pos, 0);
987 if (pos == update_cstr)
998 Args::GetShellSafeArgument (const char *unsafe_arg, std::string &safe_arg)
1000 safe_arg.assign (unsafe_arg);
1001 size_t prev_pos = 0;
1002 while (prev_pos < safe_arg.size())
1004 // Escape spaces and quotes
1005 size_t pos = safe_arg.find_first_of(" '\"", prev_pos);
1006 if (pos != std::string::npos)
1008 safe_arg.insert (pos, 1, '\\');
1014 return safe_arg.c_str();
1019 Args::StringToOptionEnum (const char *s, OptionEnumValueElement *enum_values, int32_t fail_value, Error &error)
1025 for (int i = 0; enum_values[i].string_value != NULL ; i++)
1027 if (strstr(enum_values[i].string_value, s) == enum_values[i].string_value)
1030 return enum_values[i].value;
1036 strm.PutCString ("invalid enumeration value, valid values are: ");
1037 for (int i = 0; enum_values[i].string_value != NULL; i++)
1039 strm.Printf ("%s\"%s\"",
1041 enum_values[i].string_value);
1043 error.SetErrorString(strm.GetData());
1047 error.SetErrorString ("invalid enumeration argument");
1053 Args::StringToScriptLanguage (const char *s, ScriptLanguage fail_value, bool *success_ptr)
1057 if ((::strcasecmp (s, "python") == 0) ||
1058 (::strcasecmp (s, "default") == 0 && eScriptLanguagePython == eScriptLanguageDefault))
1060 if (success_ptr) *success_ptr = true;
1061 return eScriptLanguagePython;
1063 if (::strcasecmp (s, "none"))
1065 if (success_ptr) *success_ptr = true;
1066 return eScriptLanguageNone;
1069 if (success_ptr) *success_ptr = false;
1074 Args::StringToFormat
1077 lldb::Format &format,
1078 size_t *byte_size_ptr
1081 format = eFormatInvalid;
1090 char *format_char = NULL;
1091 unsigned long byte_size = ::strtoul (s, &format_char, 0);
1092 if (byte_size != ULONG_MAX)
1093 *byte_size_ptr = byte_size;
1100 const bool partial_match_ok = true;
1101 if (!FormatManager::GetFormatFromCString (s, partial_match_ok, format))
1103 StreamString error_strm;
1104 error_strm.Printf ("Invalid format character or name '%s'. Valid values are:\n", s);
1105 for (Format f = eFormatDefault; f < kNumFormats; f = Format(f+1))
1107 char format_char = FormatManager::GetFormatAsFormatChar(f);
1109 error_strm.Printf ("'%c' or ", format_char);
1111 error_strm.Printf ("\"%s\"", FormatManager::GetFormatAsCString(f));
1116 error_strm.PutCString ("An optional byte size can precede the format character.\n");
1117 error.SetErrorString(error_strm.GetString().c_str());
1125 error.SetErrorStringWithFormat("%s option string", s ? "empty" : "invalid");
1131 Args::StringToEncoding (const char *s, lldb::Encoding fail_value)
1135 if (strcmp(s, "uint") == 0)
1136 return eEncodingUint;
1137 else if (strcmp(s, "sint") == 0)
1138 return eEncodingSint;
1139 else if (strcmp(s, "ieee754") == 0)
1140 return eEncodingIEEE754;
1141 else if (strcmp(s, "vector") == 0)
1142 return eEncodingVector;
1148 Args::StringToGenericRegister (const char *s)
1152 if (strcmp(s, "pc") == 0)
1153 return LLDB_REGNUM_GENERIC_PC;
1154 else if (strcmp(s, "sp") == 0)
1155 return LLDB_REGNUM_GENERIC_SP;
1156 else if (strcmp(s, "fp") == 0)
1157 return LLDB_REGNUM_GENERIC_FP;
1158 else if (strcmp(s, "ra") == 0)
1159 return LLDB_REGNUM_GENERIC_RA;
1160 else if (strcmp(s, "flags") == 0)
1161 return LLDB_REGNUM_GENERIC_FLAGS;
1162 else if (strncmp(s, "arg", 3) == 0)
1164 if (s[3] && s[4] == '\0')
1168 case '1': return LLDB_REGNUM_GENERIC_ARG1;
1169 case '2': return LLDB_REGNUM_GENERIC_ARG2;
1170 case '3': return LLDB_REGNUM_GENERIC_ARG3;
1171 case '4': return LLDB_REGNUM_GENERIC_ARG4;
1172 case '5': return LLDB_REGNUM_GENERIC_ARG5;
1173 case '6': return LLDB_REGNUM_GENERIC_ARG6;
1174 case '7': return LLDB_REGNUM_GENERIC_ARG7;
1175 case '8': return LLDB_REGNUM_GENERIC_ARG8;
1180 return LLDB_INVALID_REGNUM;
1185 Args::LongestCommonPrefix (std::string &common_prefix)
1187 arg_sstr_collection::iterator pos, end = m_args.end();
1188 pos = m_args.begin();
1190 common_prefix.clear();
1192 common_prefix = (*pos);
1194 for (++pos; pos != end; ++pos)
1196 size_t new_size = (*pos).size();
1198 // First trim common_prefix if it is longer than the current element:
1199 if (common_prefix.size() > new_size)
1200 common_prefix.erase (new_size);
1202 // Then trim it at the first disparity:
1204 for (size_t i = 0; i < common_prefix.size(); i++)
1206 if ((*pos)[i] != common_prefix[i])
1208 common_prefix.erase(i);
1213 // If we've emptied the common prefix, we're done.
1214 if (common_prefix.empty())
1220 Args::FindArgumentIndexForOption (Option *long_options, int long_options_index)
1222 char short_buffer[3];
1223 char long_buffer[255];
1224 ::snprintf (short_buffer, sizeof (short_buffer), "-%c", long_options[long_options_index].val);
1225 ::snprintf (long_buffer, sizeof (long_buffer), "--%s", long_options[long_options_index].name);
1226 size_t end = GetArgumentCount ();
1230 if ((::strncmp (GetArgumentAtIndex (idx), short_buffer, strlen (short_buffer)) == 0)
1231 || (::strncmp (GetArgumentAtIndex (idx), long_buffer, strlen (long_buffer)) == 0))
1242 Args::IsPositionalArgument (const char *arg)
1247 bool is_positional = true;
1248 char *cptr = (char *) arg;
1253 while (isdigit (cptr[0]))
1255 if (cptr[0] != '\0')
1256 is_positional = false;
1259 is_positional = false;
1261 return is_positional;
1265 Args::ParseAliasOptions (Options &options,
1266 CommandReturnObject &result,
1267 OptionArgVector *option_arg_vector,
1268 std::string &raw_input_string)
1272 Option *long_options = options.GetLongOptions();
1274 if (long_options == NULL)
1276 result.AppendError ("invalid long options");
1277 result.SetStatus (eReturnStatusFailed);
1281 for (i = 0; long_options[i].name != NULL; ++i)
1283 if (long_options[i].flag == NULL)
1285 sstr << (char) long_options[i].val;
1286 switch (long_options[i].has_arg)
1289 case OptionParser::eNoArgument:
1291 case OptionParser::eRequiredArgument:
1294 case OptionParser::eOptionalArgument:
1301 OptionParser::Prepare();
1305 int long_options_index = -1;
1306 val = OptionParser::Parse (GetArgumentCount(),
1307 GetArgumentVector(),
1310 &long_options_index);
1317 result.AppendError ("unknown or ambiguous option");
1318 result.SetStatus (eReturnStatusFailed);
1325 ((Options *) &options)->OptionSeen (val);
1327 // Look up the long option index
1328 if (long_options_index == -1)
1331 long_options[j].name || long_options[j].has_arg || long_options[j].flag || long_options[j].val;
1334 if (long_options[j].val == val)
1336 long_options_index = j;
1342 // See if the option takes an argument, and see if one was supplied.
1343 if (long_options_index >= 0)
1345 StreamString option_str;
1346 option_str.Printf ("-%c", val);
1348 switch (long_options[long_options_index].has_arg)
1350 case OptionParser::eNoArgument:
1351 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
1352 OptionArgValue (OptionParser::eNoArgument, "<no-argument>")));
1353 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1355 case OptionParser::eRequiredArgument:
1356 if (OptionParser::GetOptionArgument() != NULL)
1358 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
1359 OptionArgValue (OptionParser::eRequiredArgument,
1360 std::string (OptionParser::GetOptionArgument()))));
1361 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1365 result.AppendErrorWithFormat ("Option '%s' is missing argument specifier.\n",
1366 option_str.GetData());
1367 result.SetStatus (eReturnStatusFailed);
1370 case OptionParser::eOptionalArgument:
1371 if (OptionParser::GetOptionArgument() != NULL)
1373 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
1374 OptionArgValue (OptionParser::eOptionalArgument,
1375 std::string (OptionParser::GetOptionArgument()))));
1376 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1380 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
1381 OptionArgValue (OptionParser::eOptionalArgument, "<no-argument>")));
1382 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1386 result.AppendErrorWithFormat ("error with options table; invalid value in has_arg field for option '%c'.\n", val);
1387 result.SetStatus (eReturnStatusFailed);
1393 result.AppendErrorWithFormat ("Invalid option with value '%c'.\n", val);
1394 result.SetStatus (eReturnStatusFailed);
1397 if (long_options_index >= 0)
1399 // Find option in the argument list; also see if it was supposed to take an argument and if one was
1400 // supplied. Remove option (and argument, if given) from the argument list. Also remove them from
1401 // the raw_input_string, if one was passed in.
1402 size_t idx = FindArgumentIndexForOption (long_options, long_options_index);
1403 if (idx < GetArgumentCount())
1405 if (raw_input_string.size() > 0)
1407 const char *tmp_arg = GetArgumentAtIndex (idx);
1408 size_t pos = raw_input_string.find (tmp_arg);
1409 if (pos != std::string::npos)
1410 raw_input_string.erase (pos, strlen (tmp_arg));
1412 ReplaceArgumentAtIndex (idx, "");
1413 if ((long_options[long_options_index].has_arg != OptionParser::eNoArgument)
1414 && (OptionParser::GetOptionArgument() != NULL)
1415 && (idx+1 < GetArgumentCount())
1416 && (strcmp (OptionParser::GetOptionArgument(), GetArgumentAtIndex(idx+1)) == 0))
1418 if (raw_input_string.size() > 0)
1420 const char *tmp_arg = GetArgumentAtIndex (idx+1);
1421 size_t pos = raw_input_string.find (tmp_arg);
1422 if (pos != std::string::npos)
1423 raw_input_string.erase (pos, strlen (tmp_arg));
1425 ReplaceArgumentAtIndex (idx+1, "");
1430 if (!result.Succeeded())
1436 Args::ParseArgsForCompletion
1439 OptionElementVector &option_element_vector,
1440 uint32_t cursor_index
1444 Option *long_options = options.GetLongOptions();
1445 option_element_vector.clear();
1447 if (long_options == NULL)
1452 // Leading : tells getopt to return a : for a missing option argument AND
1453 // to suppress error messages.
1456 for (int i = 0; long_options[i].name != NULL; ++i)
1458 if (long_options[i].flag == NULL)
1460 sstr << (char) long_options[i].val;
1461 switch (long_options[i].has_arg)
1464 case OptionParser::eNoArgument:
1466 case OptionParser::eRequiredArgument:
1469 case OptionParser::eOptionalArgument:
1476 OptionParser::Prepare();
1477 OptionParser::EnableError(false);
1480 const OptionDefinition *opt_defs = options.GetDefinitions();
1482 // Fooey... OptionParser::Parse permutes the GetArgumentVector to move the options to the front.
1483 // So we have to build another Arg and pass that to OptionParser::Parse so it doesn't
1484 // change the one we have.
1486 std::vector<const char *> dummy_vec (GetArgumentVector(), GetArgumentVector() + GetArgumentCount() + 1);
1488 bool failed_once = false;
1489 uint32_t dash_dash_pos = -1;
1493 bool missing_argument = false;
1494 int long_options_index = -1;
1496 val = OptionParser::Parse (dummy_vec.size() - 1,
1497 (char *const *) &dummy_vec.front(),
1500 &long_options_index);
1504 // When we're completing a "--" which is the last option on line,
1510 // If this is a bare "--" we mark it as such so we can complete it successfully later.
1511 // Handling the "--" is a little tricky, since that may mean end of options or arguments, or the
1512 // user might want to complete options by long name. I make this work by checking whether the
1513 // cursor is in the "--" argument, and if so I assume we're completing the long option, otherwise
1514 // I let it pass to OptionParser::Parse which will terminate the option parsing.
1515 // Note, in either case we continue parsing the line so we can figure out what other options
1516 // were passed. This will be useful when we come to restricting completions based on what other
1517 // options we've seen on the line.
1519 if (OptionParser::GetOptionIndex() < dummy_vec.size() - 1
1520 && (strcmp (dummy_vec[OptionParser::GetOptionIndex()-1], "--") == 0))
1522 dash_dash_pos = OptionParser::GetOptionIndex() - 1;
1523 if (OptionParser::GetOptionIndex() - 1 == cursor_index)
1525 option_element_vector.push_back (OptionArgElement (OptionArgElement::eBareDoubleDash, OptionParser::GetOptionIndex() - 1,
1526 OptionArgElement::eBareDoubleDash));
1535 else if (val == '?')
1537 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, OptionParser::GetOptionIndex() - 1,
1538 OptionArgElement::eUnrecognizedArg));
1545 else if (val == ':')
1547 // This is a missing argument.
1548 val = OptionParser::GetOptionErrorCause();
1549 missing_argument = true;
1552 ((Options *) &options)->OptionSeen (val);
1554 // Look up the long option index
1555 if (long_options_index == -1)
1558 long_options[j].name || long_options[j].has_arg || long_options[j].flag || long_options[j].val;
1561 if (long_options[j].val == val)
1563 long_options_index = j;
1569 // See if the option takes an argument, and see if one was supplied.
1570 if (long_options_index >= 0)
1572 int opt_defs_index = -1;
1573 for (int i = 0; ; i++)
1575 if (opt_defs[i].short_option == 0)
1577 else if (opt_defs[i].short_option == val)
1584 switch (long_options[long_options_index].has_arg)
1586 case OptionParser::eNoArgument:
1587 option_element_vector.push_back (OptionArgElement (opt_defs_index, OptionParser::GetOptionIndex() - 1, 0));
1589 case OptionParser::eRequiredArgument:
1590 if (OptionParser::GetOptionArgument() != NULL)
1593 if (missing_argument)
1596 arg_index = OptionParser::GetOptionIndex() - 1;
1598 option_element_vector.push_back (OptionArgElement (opt_defs_index, OptionParser::GetOptionIndex() - 2, arg_index));
1602 option_element_vector.push_back (OptionArgElement (opt_defs_index, OptionParser::GetOptionIndex() - 1, -1));
1605 case OptionParser::eOptionalArgument:
1606 if (OptionParser::GetOptionArgument() != NULL)
1608 option_element_vector.push_back (OptionArgElement (opt_defs_index, OptionParser::GetOptionIndex() - 2, OptionParser::GetOptionIndex() - 1));
1612 option_element_vector.push_back (OptionArgElement (opt_defs_index, OptionParser::GetOptionIndex() - 2, OptionParser::GetOptionIndex() - 1));
1616 // The options table is messed up. Here we'll just continue
1617 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, OptionParser::GetOptionIndex() - 1,
1618 OptionArgElement::eUnrecognizedArg));
1624 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, OptionParser::GetOptionIndex() - 1,
1625 OptionArgElement::eUnrecognizedArg));
1629 // Finally we have to handle the case where the cursor index points at a single "-". We want to mark that in
1630 // the option_element_vector, but only if it is not after the "--". But it turns out that OptionParser::Parse just ignores
1631 // an isolated "-". So we have to look it up by hand here. We only care if it is AT the cursor position.
1633 if ((dash_dash_pos == -1 || cursor_index < dash_dash_pos)
1634 && strcmp (GetArgumentAtIndex(cursor_index), "-") == 0)
1636 option_element_vector.push_back (OptionArgElement (OptionArgElement::eBareDash, cursor_index,
1637 OptionArgElement::eBareDash));
1643 Args::EncodeEscapeSequences (const char *src, std::string &dst)
1648 for (const char *p = src; *p != '\0'; ++p)
1650 size_t non_special_chars = ::strcspn (p, "\\");
1651 if (non_special_chars > 0)
1653 dst.append(p, non_special_chars);
1654 p += non_special_chars;
1661 ++p; // skip the slash
1664 case 'a' : dst.append(1, '\a'); break;
1665 case 'b' : dst.append(1, '\b'); break;
1666 case 'f' : dst.append(1, '\f'); break;
1667 case 'n' : dst.append(1, '\n'); break;
1668 case 'r' : dst.append(1, '\r'); break;
1669 case 't' : dst.append(1, '\t'); break;
1670 case 'v' : dst.append(1, '\v'); break;
1671 case '\\': dst.append(1, '\\'); break;
1672 case '\'': dst.append(1, '\''); break;
1673 case '"' : dst.append(1, '"'); break;
1675 // 1 to 3 octal chars
1677 // Make a string that can hold onto the initial zero char,
1678 // up to 3 octal digits, and a terminating NULL.
1679 char oct_str[5] = { '\0', '\0', '\0', '\0', '\0' };
1682 for (i=0; (p[i] >= '0' && p[i] <= '7') && i<4; ++i)
1685 // We don't want to consume the last octal character since
1686 // the main for loop will do this for us, so we advance p by
1687 // one less than i (even if i is zero)
1689 unsigned long octal_value = ::strtoul (oct_str, NULL, 8);
1690 if (octal_value <= UINT8_MAX)
1692 dst.append(1, (char)octal_value);
1698 // hex number in the format
1701 ++p; // Skip the 'x'
1703 // Make a string that can hold onto two hex chars plus a
1705 char hex_str[3] = { *p, '\0', '\0' };
1708 ++p; // Skip the first of the two hex chars
1712 unsigned long hex_value = strtoul (hex_str, NULL, 16);
1713 if (hex_value <= UINT8_MAX)
1714 dst.append (1, (char)hex_value);
1723 // Just desensitize any other character by just printing what
1724 // came after the '\'
1736 Args::ExpandEscapedCharacters (const char *src, std::string &dst)
1741 for (const char *p = src; *p != '\0'; ++p)
1749 case '\a': dst.append("\\a"); break;
1750 case '\b': dst.append("\\b"); break;
1751 case '\f': dst.append("\\f"); break;
1752 case '\n': dst.append("\\n"); break;
1753 case '\r': dst.append("\\r"); break;
1754 case '\t': dst.append("\\t"); break;
1755 case '\v': dst.append("\\v"); break;
1756 case '\'': dst.append("\\'"); break;
1757 case '"': dst.append("\\\""); break;
1758 case '\\': dst.append("\\\\"); break;
1761 // Just encode as octal
1764 snprintf(octal_str, sizeof(octal_str), "%o", *p);
1765 dst.append(octal_str);