1 //===-- CommandObject.cpp ---------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "lldb/lldb-python.h"
11 
12 #include "lldb/Interpreter/CommandObject.h"
13 
14 #include <string>
15 #include <map>
16 
17 #include <getopt.h>
18 #include <stdlib.h>
19 #include <ctype.h>
20 
21 #include "lldb/Core/Address.h"
22 #include "lldb/Core/ArchSpec.h"
23 #include "lldb/Interpreter/Options.h"
24 
25 // These are for the Sourcename completers.
26 // FIXME: Make a separate file for the completers.
27 #include "lldb/Host/FileSpec.h"
28 #include "lldb/Core/FileSpecList.h"
29 #include "lldb/Target/Process.h"
30 #include "lldb/Target/Target.h"
31 
32 #include "lldb/Interpreter/CommandInterpreter.h"
33 #include "lldb/Interpreter/CommandReturnObject.h"
34 #include "lldb/Interpreter/ScriptInterpreter.h"
35 #include "lldb/Interpreter/ScriptInterpreterPython.h"
36 
37 using namespace lldb;
38 using namespace lldb_private;
39 
40 //-------------------------------------------------------------------------
41 // CommandObject
42 //-------------------------------------------------------------------------
43 
44 CommandObject::CommandObject
45 (
46     CommandInterpreter &interpreter,
47     const char *name,
48     const char *help,
49     const char *syntax,
50     uint32_t flags
51 ) :
52     m_interpreter (interpreter),
53     m_cmd_name (name),
54     m_cmd_help_short (),
55     m_cmd_help_long (),
56     m_cmd_syntax (),
57     m_is_alias (false),
58     m_flags (flags),
59     m_arguments(),
60     m_command_override_callback (NULL),
61     m_command_override_baton (NULL)
62 {
63     if (help && help[0])
64         m_cmd_help_short = help;
65     if (syntax && syntax[0])
66         m_cmd_syntax = syntax;
67 }
68 
69 CommandObject::~CommandObject ()
70 {
71 }
72 
73 const char *
74 CommandObject::GetHelp ()
75 {
76     return m_cmd_help_short.c_str();
77 }
78 
79 const char *
80 CommandObject::GetHelpLong ()
81 {
82     return m_cmd_help_long.c_str();
83 }
84 
85 const char *
86 CommandObject::GetSyntax ()
87 {
88     if (m_cmd_syntax.length() == 0)
89     {
90         StreamString syntax_str;
91         syntax_str.Printf ("%s", GetCommandName());
92         if (GetOptions() != NULL)
93             syntax_str.Printf (" <cmd-options>");
94         if (m_arguments.size() > 0)
95         {
96             syntax_str.Printf (" ");
97             if (WantsRawCommandString())
98                 syntax_str.Printf("-- ");
99             GetFormattedCommandArguments (syntax_str);
100         }
101         m_cmd_syntax = syntax_str.GetData ();
102     }
103 
104     return m_cmd_syntax.c_str();
105 }
106 
107 const char *
108 CommandObject::Translate ()
109 {
110     //return m_cmd_func_name.c_str();
111     return "This function is currently not implemented.";
112 }
113 
114 const char *
115 CommandObject::GetCommandName ()
116 {
117     return m_cmd_name.c_str();
118 }
119 
120 void
121 CommandObject::SetCommandName (const char *name)
122 {
123     m_cmd_name = name;
124 }
125 
126 void
127 CommandObject::SetHelp (const char *cstr)
128 {
129     m_cmd_help_short = cstr;
130 }
131 
132 void
133 CommandObject::SetHelpLong (const char *cstr)
134 {
135     m_cmd_help_long = cstr;
136 }
137 
138 void
139 CommandObject::SetHelpLong (std::string str)
140 {
141     m_cmd_help_long = str;
142 }
143 
144 void
145 CommandObject::SetSyntax (const char *cstr)
146 {
147     m_cmd_syntax = cstr;
148 }
149 
150 Options *
151 CommandObject::GetOptions ()
152 {
153     // By default commands don't have options unless this virtual function
154     // is overridden by base classes.
155     return NULL;
156 }
157 
158 bool
159 CommandObject::ParseOptions
160 (
161     Args& args,
162     CommandReturnObject &result
163 )
164 {
165     // See if the subclass has options?
166     Options *options = GetOptions();
167     if (options != NULL)
168     {
169         Error error;
170         options->NotifyOptionParsingStarting();
171 
172         // ParseOptions calls getopt_long, which always skips the zero'th item in the array and starts at position 1,
173         // so we need to push a dummy value into position zero.
174         args.Unshift("dummy_string");
175         error = args.ParseOptions (*options);
176 
177         // The "dummy_string" will have already been removed by ParseOptions,
178         // so no need to remove it.
179 
180         if (error.Success())
181             error = options->NotifyOptionParsingFinished();
182 
183         if (error.Success())
184         {
185             if (options->VerifyOptions (result))
186                 return true;
187         }
188         else
189         {
190             const char *error_cstr = error.AsCString();
191             if (error_cstr)
192             {
193                 // We got an error string, lets use that
194                 result.AppendError(error_cstr);
195             }
196             else
197             {
198                 // No error string, output the usage information into result
199                 options->GenerateOptionUsage (result.GetErrorStream(), this);
200             }
201         }
202         result.SetStatus (eReturnStatusFailed);
203         return false;
204     }
205     return true;
206 }
207 
208 
209 
210 bool
211 CommandObject::CheckFlags (CommandReturnObject &result)
212 {
213     if (GetFlags().AnySet (CommandObject::eFlagProcessMustBeLaunched | CommandObject::eFlagProcessMustBePaused))
214     {
215         Process *process = m_interpreter.GetExecutionContext().GetProcessPtr();
216         if (process == NULL)
217         {
218             // A process that is not running is considered paused.
219             if (GetFlags().Test(CommandObject::eFlagProcessMustBeLaunched))
220             {
221                 result.AppendError ("Process must exist.");
222                 result.SetStatus (eReturnStatusFailed);
223                 return false;
224             }
225         }
226         else
227         {
228             StateType state = process->GetState();
229 
230             switch (state)
231             {
232             case eStateInvalid:
233             case eStateSuspended:
234             case eStateCrashed:
235             case eStateStopped:
236                 break;
237 
238             case eStateConnected:
239             case eStateAttaching:
240             case eStateLaunching:
241             case eStateDetached:
242             case eStateExited:
243             case eStateUnloaded:
244                 if (GetFlags().Test(CommandObject::eFlagProcessMustBeLaunched))
245                 {
246                     result.AppendError ("Process must be launched.");
247                     result.SetStatus (eReturnStatusFailed);
248                     return false;
249                 }
250                 break;
251 
252             case eStateRunning:
253             case eStateStepping:
254                 if (GetFlags().Test(CommandObject::eFlagProcessMustBePaused))
255                 {
256                     result.AppendError ("Process is running.  Use 'process interrupt' to pause execution.");
257                     result.SetStatus (eReturnStatusFailed);
258                     return false;
259                 }
260             }
261         }
262     }
263     return true;
264 }
265 
266 class CommandDictCommandPartialMatch
267 {
268     public:
269         CommandDictCommandPartialMatch (const char *match_str)
270         {
271             m_match_str = match_str;
272         }
273         bool operator() (const std::pair<std::string, lldb::CommandObjectSP> map_element) const
274         {
275             // A NULL or empty string matches everything.
276             if (m_match_str == NULL || *m_match_str == '\0')
277                 return 1;
278 
279             size_t found = map_element.first.find (m_match_str, 0);
280             if (found == std::string::npos)
281                 return 0;
282             else
283                 return found == 0;
284         }
285 
286     private:
287         const char *m_match_str;
288 };
289 
290 int
291 CommandObject::AddNamesMatchingPartialString (CommandObject::CommandMap &in_map, const char *cmd_str,
292                                               StringList &matches)
293 {
294     int number_added = 0;
295     CommandDictCommandPartialMatch matcher(cmd_str);
296 
297     CommandObject::CommandMap::iterator matching_cmds = std::find_if (in_map.begin(), in_map.end(), matcher);
298 
299     while (matching_cmds != in_map.end())
300     {
301         ++number_added;
302         matches.AppendString((*matching_cmds).first.c_str());
303         matching_cmds = std::find_if (++matching_cmds, in_map.end(), matcher);;
304     }
305     return number_added;
306 }
307 
308 int
309 CommandObject::HandleCompletion
310 (
311     Args &input,
312     int &cursor_index,
313     int &cursor_char_position,
314     int match_start_point,
315     int max_return_elements,
316     bool &word_complete,
317     StringList &matches
318 )
319 {
320     // Default implmentation of WantsCompletion() is !WantsRawCommandString().
321     // Subclasses who want raw command string but desire, for example,
322     // argument completion should override WantsCompletion() to return true,
323     // instead.
324     if (WantsRawCommandString() && !WantsCompletion())
325     {
326         // FIXME: Abstract telling the completion to insert the completion character.
327         matches.Clear();
328         return -1;
329     }
330     else
331     {
332         // Can we do anything generic with the options?
333         Options *cur_options = GetOptions();
334         CommandReturnObject result;
335         OptionElementVector opt_element_vector;
336 
337         if (cur_options != NULL)
338         {
339             // Re-insert the dummy command name string which will have been
340             // stripped off:
341             input.Unshift ("dummy-string");
342             cursor_index++;
343 
344 
345             // I stick an element on the end of the input, because if the last element is
346             // option that requires an argument, getopt_long will freak out.
347 
348             input.AppendArgument ("<FAKE-VALUE>");
349 
350             input.ParseArgsForCompletion (*cur_options, opt_element_vector, cursor_index);
351 
352             input.DeleteArgumentAtIndex(input.GetArgumentCount() - 1);
353 
354             bool handled_by_options;
355             handled_by_options = cur_options->HandleOptionCompletion (input,
356                                                                       opt_element_vector,
357                                                                       cursor_index,
358                                                                       cursor_char_position,
359                                                                       match_start_point,
360                                                                       max_return_elements,
361                                                                       word_complete,
362                                                                       matches);
363             if (handled_by_options)
364                 return matches.GetSize();
365         }
366 
367         // If we got here, the last word is not an option or an option argument.
368         return HandleArgumentCompletion (input,
369                                          cursor_index,
370                                          cursor_char_position,
371                                          opt_element_vector,
372                                          match_start_point,
373                                          max_return_elements,
374                                          word_complete,
375                                          matches);
376     }
377 }
378 
379 bool
380 CommandObject::HelpTextContainsWord (const char *search_word)
381 {
382     std::string options_usage_help;
383 
384     bool found_word = false;
385 
386     const char *short_help = GetHelp();
387     const char *long_help = GetHelpLong();
388     const char *syntax_help = GetSyntax();
389 
390     if (short_help && strcasestr (short_help, search_word))
391         found_word = true;
392     else if (long_help && strcasestr (long_help, search_word))
393         found_word = true;
394     else if (syntax_help && strcasestr (syntax_help, search_word))
395         found_word = true;
396 
397     if (!found_word
398         && GetOptions() != NULL)
399     {
400         StreamString usage_help;
401         GetOptions()->GenerateOptionUsage (usage_help, this);
402         if (usage_help.GetSize() > 0)
403         {
404             const char *usage_text = usage_help.GetData();
405             if (strcasestr (usage_text, search_word))
406               found_word = true;
407         }
408     }
409 
410     return found_word;
411 }
412 
413 int
414 CommandObject::GetNumArgumentEntries  ()
415 {
416     return m_arguments.size();
417 }
418 
419 CommandObject::CommandArgumentEntry *
420 CommandObject::GetArgumentEntryAtIndex (int idx)
421 {
422     if (idx < m_arguments.size())
423         return &(m_arguments[idx]);
424 
425     return NULL;
426 }
427 
428 CommandObject::ArgumentTableEntry *
429 CommandObject::FindArgumentDataByType (CommandArgumentType arg_type)
430 {
431     const ArgumentTableEntry *table = CommandObject::GetArgumentTable();
432 
433     for (int i = 0; i < eArgTypeLastArg; ++i)
434         if (table[i].arg_type == arg_type)
435             return (ArgumentTableEntry *) &(table[i]);
436 
437     return NULL;
438 }
439 
440 void
441 CommandObject::GetArgumentHelp (Stream &str, CommandArgumentType arg_type, CommandInterpreter &interpreter)
442 {
443     const ArgumentTableEntry* table = CommandObject::GetArgumentTable();
444     ArgumentTableEntry *entry = (ArgumentTableEntry *) &(table[arg_type]);
445 
446     // The table is *supposed* to be kept in arg_type order, but someone *could* have messed it up...
447 
448     if (entry->arg_type != arg_type)
449         entry = CommandObject::FindArgumentDataByType (arg_type);
450 
451     if (!entry)
452         return;
453 
454     StreamString name_str;
455     name_str.Printf ("<%s>", entry->arg_name);
456 
457     if (entry->help_function)
458     {
459         const char* help_text = entry->help_function();
460         if (!entry->help_function.self_formatting)
461         {
462             interpreter.OutputFormattedHelpText (str, name_str.GetData(), "--", help_text,
463                                                  name_str.GetSize());
464         }
465         else
466         {
467             interpreter.OutputHelpText(str, name_str.GetData(), "--", help_text,
468                                        name_str.GetSize());
469         }
470     }
471     else
472         interpreter.OutputFormattedHelpText (str, name_str.GetData(), "--", entry->help_text, name_str.GetSize());
473 }
474 
475 const char *
476 CommandObject::GetArgumentName (CommandArgumentType arg_type)
477 {
478     ArgumentTableEntry *entry = (ArgumentTableEntry *) &(CommandObject::GetArgumentTable()[arg_type]);
479 
480     // The table is *supposed* to be kept in arg_type order, but someone *could* have messed it up...
481 
482     if (entry->arg_type != arg_type)
483         entry = CommandObject::FindArgumentDataByType (arg_type);
484 
485     if (entry)
486         return entry->arg_name;
487 
488     StreamString str;
489     str << "Arg name for type (" << arg_type << ") not in arg table!";
490     return str.GetData();
491 }
492 
493 bool
494 CommandObject::IsPairType (ArgumentRepetitionType arg_repeat_type)
495 {
496     if ((arg_repeat_type == eArgRepeatPairPlain)
497         ||  (arg_repeat_type == eArgRepeatPairOptional)
498         ||  (arg_repeat_type == eArgRepeatPairPlus)
499         ||  (arg_repeat_type == eArgRepeatPairStar)
500         ||  (arg_repeat_type == eArgRepeatPairRange)
501         ||  (arg_repeat_type == eArgRepeatPairRangeOptional))
502         return true;
503 
504     return false;
505 }
506 
507 static CommandObject::CommandArgumentEntry
508 OptSetFiltered(uint32_t opt_set_mask, CommandObject::CommandArgumentEntry &cmd_arg_entry)
509 {
510     CommandObject::CommandArgumentEntry ret_val;
511     for (unsigned i = 0; i < cmd_arg_entry.size(); ++i)
512         if (opt_set_mask & cmd_arg_entry[i].arg_opt_set_association)
513             ret_val.push_back(cmd_arg_entry[i]);
514     return ret_val;
515 }
516 
517 // Default parameter value of opt_set_mask is LLDB_OPT_SET_ALL, which means take
518 // all the argument data into account.  On rare cases where some argument sticks
519 // with certain option sets, this function returns the option set filtered args.
520 void
521 CommandObject::GetFormattedCommandArguments (Stream &str, uint32_t opt_set_mask)
522 {
523     int num_args = m_arguments.size();
524     for (int i = 0; i < num_args; ++i)
525     {
526         if (i > 0)
527             str.Printf (" ");
528         CommandArgumentEntry arg_entry =
529             opt_set_mask == LLDB_OPT_SET_ALL ? m_arguments[i]
530                                              : OptSetFiltered(opt_set_mask, m_arguments[i]);
531         int num_alternatives = arg_entry.size();
532 
533         if ((num_alternatives == 2)
534             && IsPairType (arg_entry[0].arg_repetition))
535         {
536             const char *first_name = GetArgumentName (arg_entry[0].arg_type);
537             const char *second_name = GetArgumentName (arg_entry[1].arg_type);
538             switch (arg_entry[0].arg_repetition)
539             {
540                 case eArgRepeatPairPlain:
541                     str.Printf ("<%s> <%s>", first_name, second_name);
542                     break;
543                 case eArgRepeatPairOptional:
544                     str.Printf ("[<%s> <%s>]", first_name, second_name);
545                     break;
546                 case eArgRepeatPairPlus:
547                     str.Printf ("<%s> <%s> [<%s> <%s> [...]]", first_name, second_name, first_name, second_name);
548                     break;
549                 case eArgRepeatPairStar:
550                     str.Printf ("[<%s> <%s> [<%s> <%s> [...]]]", first_name, second_name, first_name, second_name);
551                     break;
552                 case eArgRepeatPairRange:
553                     str.Printf ("<%s_1> <%s_1> ... <%s_n> <%s_n>", first_name, second_name, first_name, second_name);
554                     break;
555                 case eArgRepeatPairRangeOptional:
556                     str.Printf ("[<%s_1> <%s_1> ... <%s_n> <%s_n>]", first_name, second_name, first_name, second_name);
557                     break;
558                 // Explicitly test for all the rest of the cases, so if new types get added we will notice the
559                 // missing case statement(s).
560                 case eArgRepeatPlain:
561                 case eArgRepeatOptional:
562                 case eArgRepeatPlus:
563                 case eArgRepeatStar:
564                 case eArgRepeatRange:
565                     // These should not be reached, as they should fail the IsPairType test above.
566                     break;
567             }
568         }
569         else
570         {
571             StreamString names;
572             for (int j = 0; j < num_alternatives; ++j)
573             {
574                 if (j > 0)
575                     names.Printf (" | ");
576                 names.Printf ("%s", GetArgumentName (arg_entry[j].arg_type));
577             }
578             switch (arg_entry[0].arg_repetition)
579             {
580                 case eArgRepeatPlain:
581                     str.Printf ("<%s>", names.GetData());
582                     break;
583                 case eArgRepeatPlus:
584                     str.Printf ("<%s> [<%s> [...]]", names.GetData(), names.GetData());
585                     break;
586                 case eArgRepeatStar:
587                     str.Printf ("[<%s> [<%s> [...]]]", names.GetData(), names.GetData());
588                     break;
589                 case eArgRepeatOptional:
590                     str.Printf ("[<%s>]", names.GetData());
591                     break;
592                 case eArgRepeatRange:
593                     str.Printf ("<%s_1> .. <%s_n>", names.GetData(), names.GetData());
594                     break;
595                 // Explicitly test for all the rest of the cases, so if new types get added we will notice the
596                 // missing case statement(s).
597                 case eArgRepeatPairPlain:
598                 case eArgRepeatPairOptional:
599                 case eArgRepeatPairPlus:
600                 case eArgRepeatPairStar:
601                 case eArgRepeatPairRange:
602                 case eArgRepeatPairRangeOptional:
603                     // These should not be hit, as they should pass the IsPairType test above, and control should
604                     // have gone into the other branch of the if statement.
605                     break;
606             }
607         }
608     }
609 }
610 
611 CommandArgumentType
612 CommandObject::LookupArgumentName (const char *arg_name)
613 {
614     CommandArgumentType return_type = eArgTypeLastArg;
615 
616     std::string arg_name_str (arg_name);
617     size_t len = arg_name_str.length();
618     if (arg_name[0] == '<'
619         && arg_name[len-1] == '>')
620         arg_name_str = arg_name_str.substr (1, len-2);
621 
622     const ArgumentTableEntry *table = GetArgumentTable();
623     for (int i = 0; i < eArgTypeLastArg; ++i)
624         if (arg_name_str.compare (table[i].arg_name) == 0)
625             return_type = g_arguments_data[i].arg_type;
626 
627     return return_type;
628 }
629 
630 static const char *
631 RegisterNameHelpTextCallback ()
632 {
633     return "Register names can be specified using the architecture specific names.  "
634     "They can also be specified using generic names.  Not all generic entities have "
635     "registers backing them on all architectures.  When they don't the generic name "
636     "will return an error.\n"
637     "The generic names defined in lldb are:\n"
638     "\n"
639     "pc       - program counter register\n"
640     "ra       - return address register\n"
641     "fp       - frame pointer register\n"
642     "sp       - stack pointer register\n"
643     "flags    - the flags register\n"
644     "arg{1-6} - integer argument passing registers.\n";
645 }
646 
647 static const char *
648 BreakpointIDHelpTextCallback ()
649 {
650     return "Breakpoint ID's consist major and minor numbers;  the major number "
651     "corresponds to the single entity that was created with a 'breakpoint set' "
652     "command; the minor numbers correspond to all the locations that were actually "
653     "found/set based on the major breakpoint.  A full breakpoint ID might look like "
654     "3.14, meaning the 14th location set for the 3rd breakpoint.  You can specify "
655     "all the locations of a breakpoint by just indicating the major breakpoint "
656     "number. A valid breakpoint id consists either of just the major id number, "
657     "or the major number, a dot, and the location number (e.g. 3 or 3.2 could "
658     "both be valid breakpoint ids).";
659 }
660 
661 static const char *
662 BreakpointIDRangeHelpTextCallback ()
663 {
664     return "A 'breakpoint id list' is a manner of specifying multiple breakpoints. "
665     "This can be done  through several mechanisms.  The easiest way is to just "
666     "enter a space-separated list of breakpoint ids.  To specify all the "
667     "breakpoint locations under a major breakpoint, you can use the major "
668     "breakpoint number followed by '.*', eg. '5.*' means all the locations under "
669     "breakpoint 5.  You can also indicate a range of breakpoints by using "
670     "<start-bp-id> - <end-bp-id>.  The start-bp-id and end-bp-id for a range can "
671     "be any valid breakpoint ids.  It is not legal, however, to specify a range "
672     "using specific locations that cross major breakpoint numbers.  I.e. 3.2 - 3.7"
673     " is legal; 2 - 5 is legal; but 3.2 - 4.4 is not legal.";
674 }
675 
676 static const char *
677 GDBFormatHelpTextCallback ()
678 {
679     return "A GDB format consists of a repeat count, a format letter and a size letter. "
680     "The repeat count is optional and defaults to 1. The format letter is optional "
681     "and defaults to the previous format that was used. The size letter is optional "
682     "and defaults to the previous size that was used.\n"
683     "\n"
684     "Format letters include:\n"
685     "o - octal\n"
686     "x - hexadecimal\n"
687     "d - decimal\n"
688     "u - unsigned decimal\n"
689     "t - binary\n"
690     "f - float\n"
691     "a - address\n"
692     "i - instruction\n"
693     "c - char\n"
694     "s - string\n"
695     "T - OSType\n"
696     "A - float as hex\n"
697     "\n"
698     "Size letters include:\n"
699     "b - 1 byte  (byte)\n"
700     "h - 2 bytes (halfword)\n"
701     "w - 4 bytes (word)\n"
702     "g - 8 bytes (giant)\n"
703     "\n"
704     "Example formats:\n"
705     "32xb - show 32 1 byte hexadecimal integer values\n"
706     "16xh - show 16 2 byte hexadecimal integer values\n"
707     "64   - show 64 2 byte hexadecimal integer values (format and size from the last format)\n"
708     "dw   - show 1 4 byte decimal integer value\n"
709     ;
710 }
711 
712 static const char *
713 FormatHelpTextCallback ()
714 {
715 
716     static char* help_text_ptr = NULL;
717 
718     if (help_text_ptr)
719         return help_text_ptr;
720 
721     StreamString sstr;
722     sstr << "One of the format names (or one-character names) that can be used to show a variable's value:\n";
723     for (Format f = eFormatDefault; f < kNumFormats; f = Format(f+1))
724     {
725         if (f != eFormatDefault)
726             sstr.PutChar('\n');
727 
728         char format_char = FormatManager::GetFormatAsFormatChar(f);
729         if (format_char)
730             sstr.Printf("'%c' or ", format_char);
731 
732         sstr.Printf ("\"%s\"", FormatManager::GetFormatAsCString(f));
733     }
734 
735     sstr.Flush();
736 
737     std::string data = sstr.GetString();
738 
739     help_text_ptr = new char[data.length()+1];
740 
741     data.copy(help_text_ptr, data.length());
742 
743     return help_text_ptr;
744 }
745 
746 static const char *
747 LanguageTypeHelpTextCallback ()
748 {
749     static char* help_text_ptr = NULL;
750 
751     if (help_text_ptr)
752         return help_text_ptr;
753 
754     StreamString sstr;
755     sstr << "One of the following languages:\n";
756 
757     for (unsigned int l = eLanguageTypeUnknown; l < eNumLanguageTypes; ++l)
758     {
759         sstr << "  " << LanguageRuntime::GetNameForLanguageType(static_cast<LanguageType>(l)) << "\n";
760     }
761 
762     sstr.Flush();
763 
764     std::string data = sstr.GetString();
765 
766     help_text_ptr = new char[data.length()+1];
767 
768     data.copy(help_text_ptr, data.length());
769 
770     return help_text_ptr;
771 }
772 
773 static const char *
774 SummaryStringHelpTextCallback()
775 {
776     return
777         "A summary string is a way to extract information from variables in order to present them using a summary.\n"
778         "Summary strings contain static text, variables, scopes and control sequences:\n"
779         "  - Static text can be any sequence of non-special characters, i.e. anything but '{', '}', '$', or '\\'.\n"
780         "  - Variables are sequences of characters beginning with ${, ending with } and that contain symbols in the format described below.\n"
781         "  - Scopes are any sequence of text between { and }. Anything included in a scope will only appear in the output summary if there were no errors.\n"
782         "  - Control sequences are the usual C/C++ '\\a', '\\n', ..., plus '\\$', '\\{' and '\\}'.\n"
783         "A summary string works by copying static text verbatim, turning control sequences into their character counterpart, expanding variables and trying to expand scopes.\n"
784         "A variable is expanded by giving it a value other than its textual representation, and the way this is done depends on what comes after the ${ marker.\n"
785         "The most common sequence if ${var followed by an expression path, which is the text one would type to access a member of an aggregate types, given a variable of that type"
786         " (e.g. if type T has a member named x, which has a member named y, and if t is of type T, the expression path would be .x.y and the way to fit that into a summary string would be"
787         " ${var.x.y}). You can also use ${*var followed by an expression path and in that case the object referred by the path will be dereferenced before being displayed."
788         " If the object is not a pointer, doing so will cause an error. For additional details on expression paths, you can type 'help expr-path'. \n"
789         "By default, summary strings attempt to display the summary for any variable they reference, and if that fails the value. If neither can be shown, nothing is displayed."
790         "In a summary string, you can also use an array index [n], or a slice-like range [n-m]. This can have two different meanings depending on what kind of object the expression"
791         " path refers to:\n"
792         "  - if it is a scalar type (any basic type like int, float, ...) the expression is a bitfield, i.e. the bits indicated by the indexing operator are extracted out of the number"
793         " and displayed as an individual variable\n"
794         "  - if it is an array or pointer the array items indicated by the indexing operator are shown as the result of the variable. if the expression is an array, real array items are"
795         " printed; if it is a pointer, the pointer-as-array syntax is used to obtain the values (this means, the latter case can have no range checking)\n"
796         "If you are trying to display an array for which the size is known, you can also use [] instead of giving an exact range. This has the effect of showing items 0 thru size - 1.\n"
797         "Additionally, a variable can contain an (optional) format code, as in ${var.x.y%code}, where code can be any of the valid formats described in 'help format', or one of the"
798         " special symbols only allowed as part of a variable:\n"
799         "    %V: show the value of the object by default\n"
800         "    %S: show the summary of the object by default\n"
801         "    %@: show the runtime-provided object description (for Objective-C, it calls NSPrintForDebugger; for C/C++ it does nothing)\n"
802         "    %L: show the location of the object (memory address or a register name)\n"
803         "    %#: show the number of children of the object\n"
804         "    %T: show the type of the object\n"
805         "Another variable that you can use in summary strings is ${svar . This sequence works exactly like ${var, including the fact that ${*svar is an allowed sequence, but uses"
806         " the object's synthetic children provider instead of the actual objects. For instance, if you are using STL synthetic children providers, the following summary string would"
807         " count the number of actual elements stored in an std::list:\n"
808         "type summary add -s \"${svar%#}\" -x \"std::list<\"";
809 }
810 
811 static const char *
812 ExprPathHelpTextCallback()
813 {
814     return
815     "An expression path is the sequence of symbols that is used in C/C++ to access a member variable of an aggregate object (class).\n"
816     "For instance, given a class:\n"
817     "  class foo {\n"
818     "      int a;\n"
819     "      int b; .\n"
820     "      foo* next;\n"
821     "  };\n"
822     "the expression to read item b in the item pointed to by next for foo aFoo would be aFoo.next->b.\n"
823     "Given that aFoo could just be any object of type foo, the string '.next->b' is the expression path, because it can be attached to any foo instance to achieve the effect.\n"
824     "Expression paths in LLDB include dot (.) and arrow (->) operators, and most commands using expression paths have ways to also accept the star (*) operator.\n"
825     "The meaning of these operators is the same as the usual one given to them by the C/C++ standards.\n"
826     "LLDB also has support for indexing ([ ]) in expression paths, and extends the traditional meaning of the square brackets operator to allow bitfield extraction:\n"
827     "for objects of native types (int, float, char, ...) saying '[n-m]' as an expression path (where n and m are any positive integers, e.g. [3-5]) causes LLDB to extract"
828     " bits n thru m from the value of the variable. If n == m, [n] is also allowed as a shortcut syntax. For arrays and pointers, expression paths can only contain one index"
829     " and the meaning of the operation is the same as the one defined by C/C++ (item extraction). Some commands extend bitfield-like syntax for arrays and pointers with the"
830     " meaning of array slicing (taking elements n thru m inside the array or pointed-to memory).";
831 }
832 
833 void
834 CommandObject::AddIDsArgumentData(CommandArgumentEntry &arg, CommandArgumentType ID, CommandArgumentType IDRange)
835 {
836     CommandArgumentData id_arg;
837     CommandArgumentData id_range_arg;
838 
839     // Create the first variant for the first (and only) argument for this command.
840     id_arg.arg_type = ID;
841     id_arg.arg_repetition = eArgRepeatOptional;
842 
843     // Create the second variant for the first (and only) argument for this command.
844     id_range_arg.arg_type = IDRange;
845     id_range_arg.arg_repetition = eArgRepeatOptional;
846 
847     // The first (and only) argument for this command could be either an id or an id_range.
848     // Push both variants into the entry for the first argument for this command.
849     arg.push_back(id_arg);
850     arg.push_back(id_range_arg);
851 }
852 
853 const char *
854 CommandObject::GetArgumentTypeAsCString (const lldb::CommandArgumentType arg_type)
855 {
856     if (arg_type >=0 && arg_type < eArgTypeLastArg)
857         return g_arguments_data[arg_type].arg_name;
858     return NULL;
859 
860 }
861 
862 const char *
863 CommandObject::GetArgumentDescriptionAsCString (const lldb::CommandArgumentType arg_type)
864 {
865     if (arg_type >=0 && arg_type < eArgTypeLastArg)
866         return g_arguments_data[arg_type].help_text;
867     return NULL;
868 }
869 
870 bool
871 CommandObjectParsed::Execute (const char *args_string, CommandReturnObject &result)
872 {
873     CommandOverrideCallback command_callback = GetOverrideCallback();
874     bool handled = false;
875     Args cmd_args (args_string);
876     if (command_callback)
877     {
878         Args full_args (GetCommandName ());
879         full_args.AppendArguments(cmd_args);
880         handled = command_callback (GetOverrideCallbackBaton(), full_args.GetConstArgumentVector());
881     }
882     if (!handled)
883     {
884         for (size_t i = 0; i < cmd_args.GetArgumentCount();  ++i)
885         {
886             const char *tmp_str = cmd_args.GetArgumentAtIndex (i);
887             if (tmp_str[0] == '`')  // back-quote
888                 cmd_args.ReplaceArgumentAtIndex (i, m_interpreter.ProcessEmbeddedScriptCommands (tmp_str));
889         }
890 
891         if (!CheckFlags(result))
892             return false;
893 
894         if (!ParseOptions (cmd_args, result))
895             return false;
896 
897         // Call the command-specific version of 'Execute', passing it the already processed arguments.
898         handled = DoExecute (cmd_args, result);
899     }
900     return handled;
901 }
902 
903 bool
904 CommandObjectRaw::Execute (const char *args_string, CommandReturnObject &result)
905 {
906     CommandOverrideCallback command_callback = GetOverrideCallback();
907     bool handled = false;
908     if (command_callback)
909     {
910         std::string full_command (GetCommandName ());
911         full_command += ' ';
912         full_command += args_string;
913         const char *argv[2] = { NULL, NULL };
914         argv[0] = full_command.c_str();
915         handled = command_callback (GetOverrideCallbackBaton(), argv);
916     }
917     if (!handled)
918     {
919         if (!CheckFlags(result))
920             return false;
921         else
922             handled = DoExecute (args_string, result);
923     }
924     return handled;
925 }
926 
927 static
928 const char *arch_helper()
929 {
930     static StreamString g_archs_help;
931     if (g_archs_help.Empty())
932     {
933         StringList archs;
934         ArchSpec::AutoComplete(NULL, archs);
935         g_archs_help.Printf("These are the supported architecture names:\n");
936         archs.Join("\n", g_archs_help);
937     }
938     return g_archs_help.GetData();
939 }
940 
941 CommandObject::ArgumentTableEntry
942 CommandObject::g_arguments_data[] =
943 {
944     { eArgTypeAddress, "address", CommandCompletions::eNoCompletion, { NULL, false }, "A valid address in the target program's execution space." },
945     { eArgTypeAliasName, "alias-name", CommandCompletions::eNoCompletion, { NULL, false }, "The name of an abbreviation (alias) for a debugger command." },
946     { eArgTypeAliasOptions, "options-for-aliased-command", CommandCompletions::eNoCompletion, { NULL, false }, "Command options to be used as part of an alias (abbreviation) definition.  (See 'help commands alias' for more information.)" },
947     { eArgTypeArchitecture, "arch", CommandCompletions::eArchitectureCompletion, { arch_helper, true }, "The architecture name, e.g. i386 or x86_64." },
948     { eArgTypeBoolean, "boolean", CommandCompletions::eNoCompletion, { NULL, false }, "A Boolean value: 'true' or 'false'" },
949     { eArgTypeBreakpointID, "breakpt-id", CommandCompletions::eNoCompletion, { BreakpointIDHelpTextCallback, false }, NULL },
950     { eArgTypeBreakpointIDRange, "breakpt-id-list", CommandCompletions::eNoCompletion, { BreakpointIDRangeHelpTextCallback, false }, NULL },
951     { eArgTypeByteSize, "byte-size", CommandCompletions::eNoCompletion, { NULL, false }, "Number of bytes to use." },
952     { eArgTypeClassName, "class-name", CommandCompletions::eNoCompletion, { NULL, false }, "Then name of a class from the debug information in the program." },
953     { eArgTypeCommandName, "cmd-name", CommandCompletions::eNoCompletion, { NULL, false }, "A debugger command (may be multiple words), without any options or arguments." },
954     { eArgTypeCount, "count", CommandCompletions::eNoCompletion, { NULL, false }, "An unsigned integer." },
955     { eArgTypeDirectoryName, "directory", CommandCompletions::eDiskDirectoryCompletion, { NULL, false }, "A directory name." },
956     { eArgTypeEndAddress, "end-address", CommandCompletions::eNoCompletion, { NULL, false }, "Help text goes here." },
957     { eArgTypeExpression, "expr", CommandCompletions::eNoCompletion, { NULL, false }, "Help text goes here." },
958     { eArgTypeExpressionPath, "expr-path", CommandCompletions::eNoCompletion, { ExprPathHelpTextCallback, true }, NULL },
959     { eArgTypeExprFormat, "expression-format", CommandCompletions::eNoCompletion, { NULL, false }, "[ [bool|b] | [bin] | [char|c] | [oct|o] | [dec|i|d|u] | [hex|x] | [float|f] | [cstr|s] ]" },
960     { eArgTypeFilename, "filename", CommandCompletions::eDiskFileCompletion, { NULL, false }, "The name of a file (can include path)." },
961     { eArgTypeFormat, "format", CommandCompletions::eNoCompletion, { FormatHelpTextCallback, true }, NULL },
962     { eArgTypeFrameIndex, "frame-index", CommandCompletions::eNoCompletion, { NULL, false }, "Index into a thread's list of frames." },
963     { eArgTypeFullName, "fullname", CommandCompletions::eNoCompletion, { NULL, false }, "Help text goes here." },
964     { eArgTypeFunctionName, "function-name", CommandCompletions::eNoCompletion, { NULL, false }, "The name of a function." },
965     { eArgTypeFunctionOrSymbol, "function-or-symbol", CommandCompletions::eNoCompletion, { NULL, false }, "The name of a function or symbol." },
966     { eArgTypeGDBFormat, "gdb-format", CommandCompletions::eNoCompletion, { GDBFormatHelpTextCallback, true }, NULL },
967     { eArgTypeIndex, "index", CommandCompletions::eNoCompletion, { NULL, false }, "An index into a list." },
968     { eArgTypeLanguage, "language", CommandCompletions::eNoCompletion, { LanguageTypeHelpTextCallback, true }, NULL },
969     { eArgTypeLineNum, "linenum", CommandCompletions::eNoCompletion, { NULL, false }, "Line number in a source file." },
970     { eArgTypeLogCategory, "log-category", CommandCompletions::eNoCompletion, { NULL, false }, "The name of a category within a log channel, e.g. all (try \"log list\" to see a list of all channels and their categories." },
971     { eArgTypeLogChannel, "log-channel", CommandCompletions::eNoCompletion, { NULL, false }, "The name of a log channel, e.g. process.gdb-remote (try \"log list\" to see a list of all channels and their categories)." },
972     { eArgTypeMethod, "method", CommandCompletions::eNoCompletion, { NULL, false }, "A C++ method name." },
973     { eArgTypeName, "name", CommandCompletions::eNoCompletion, { NULL, false }, "Help text goes here." },
974     { eArgTypeNewPathPrefix, "new-path-prefix", CommandCompletions::eNoCompletion, { NULL, false }, "Help text goes here." },
975     { eArgTypeNumLines, "num-lines", CommandCompletions::eNoCompletion, { NULL, false }, "The number of lines to use." },
976     { eArgTypeNumberPerLine, "number-per-line", CommandCompletions::eNoCompletion, { NULL, false }, "The number of items per line to display." },
977     { eArgTypeOffset, "offset", CommandCompletions::eNoCompletion, { NULL, false }, "Help text goes here." },
978     { eArgTypeOldPathPrefix, "old-path-prefix", CommandCompletions::eNoCompletion, { NULL, false }, "Help text goes here." },
979     { eArgTypeOneLiner, "one-line-command", CommandCompletions::eNoCompletion, { NULL, false }, "A command that is entered as a single line of text." },
980     { eArgTypePid, "pid", CommandCompletions::eNoCompletion, { NULL, false }, "The process ID number." },
981     { eArgTypePlugin, "plugin", CommandCompletions::eNoCompletion, { NULL, false }, "Help text goes here." },
982     { eArgTypeProcessName, "process-name", CommandCompletions::eNoCompletion, { NULL, false }, "The name of the process." },
983     { eArgTypePythonClass, "python-class", CommandCompletions::eNoCompletion, { NULL, false }, "The name of a Python class." },
984     { eArgTypePythonFunction, "python-function", CommandCompletions::eNoCompletion, { NULL, false }, "The name of a Python function." },
985     { eArgTypePythonScript, "python-script", CommandCompletions::eNoCompletion, { NULL, false }, "Source code written in Python." },
986     { eArgTypeQueueName, "queue-name", CommandCompletions::eNoCompletion, { NULL, false }, "The name of the thread queue." },
987     { eArgTypeRegisterName, "register-name", CommandCompletions::eNoCompletion, { RegisterNameHelpTextCallback, true }, NULL },
988     { eArgTypeRegularExpression, "regular-expression", CommandCompletions::eNoCompletion, { NULL, false }, "A regular expression." },
989     { eArgTypeRunArgs, "run-args", CommandCompletions::eNoCompletion, { NULL, false }, "Arguments to be passed to the target program when it starts executing." },
990     { eArgTypeRunMode, "run-mode", CommandCompletions::eNoCompletion, { NULL, false }, "Help text goes here." },
991     { eArgTypeScriptedCommandSynchronicity, "script-cmd-synchronicity", CommandCompletions::eNoCompletion, { NULL, false }, "The synchronicity to use to run scripted commands with regard to LLDB event system." },
992     { eArgTypeScriptLang, "script-language", CommandCompletions::eNoCompletion, { NULL, false }, "The scripting language to be used for script-based commands.  Currently only Python is valid." },
993     { eArgTypeSearchWord, "search-word", CommandCompletions::eNoCompletion, { NULL, false }, "The word for which you wish to search for information about." },
994     { eArgTypeSelector, "selector", CommandCompletions::eNoCompletion, { NULL, false }, "An Objective-C selector name." },
995     { eArgTypeSettingIndex, "setting-index", CommandCompletions::eNoCompletion, { NULL, false }, "An index into a settings variable that is an array (try 'settings list' to see all the possible settings variables and their types)." },
996     { eArgTypeSettingKey, "setting-key", CommandCompletions::eNoCompletion, { NULL, false }, "A key into a settings variables that is a dictionary (try 'settings list' to see all the possible settings variables and their types)." },
997     { eArgTypeSettingPrefix, "setting-prefix", CommandCompletions::eNoCompletion, { NULL, false }, "The name of a settable internal debugger variable up to a dot ('.'), e.g. 'target.process.'" },
998     { eArgTypeSettingVariableName, "setting-variable-name", CommandCompletions::eNoCompletion, { NULL, false }, "The name of a settable internal debugger variable.  Type 'settings list' to see a complete list of such variables." },
999     { eArgTypeShlibName, "shlib-name", CommandCompletions::eNoCompletion, { NULL, false }, "The name of a shared library." },
1000     { eArgTypeSourceFile, "source-file", CommandCompletions::eSourceFileCompletion, { NULL, false }, "The name of a source file.." },
1001     { eArgTypeSortOrder, "sort-order", CommandCompletions::eNoCompletion, { NULL, false }, "Specify a sort order when dumping lists." },
1002     { eArgTypeStartAddress, "start-address", CommandCompletions::eNoCompletion, { NULL, false }, "Help text goes here." },
1003     { eArgTypeSummaryString, "summary-string", CommandCompletions::eNoCompletion, { SummaryStringHelpTextCallback, true }, NULL },
1004     { eArgTypeSymbol, "symbol", CommandCompletions::eSymbolCompletion, { NULL, false }, "Any symbol name (function name, variable, argument, etc.)" },
1005     { eArgTypeThreadID, "thread-id", CommandCompletions::eNoCompletion, { NULL, false }, "Thread ID number." },
1006     { eArgTypeThreadIndex, "thread-index", CommandCompletions::eNoCompletion, { NULL, false }, "Index into the process' list of threads." },
1007     { eArgTypeThreadName, "thread-name", CommandCompletions::eNoCompletion, { NULL, false }, "The thread's name." },
1008     { eArgTypeUnsignedInteger, "unsigned-integer", CommandCompletions::eNoCompletion, { NULL, false }, "An unsigned integer." },
1009     { eArgTypeUnixSignal, "unix-signal", CommandCompletions::eNoCompletion, { NULL, false }, "A valid Unix signal name or number (e.g. SIGKILL, KILL or 9)." },
1010     { eArgTypeVarName, "variable-name", CommandCompletions::eNoCompletion, { NULL, false }, "The name of a variable in your program." },
1011     { eArgTypeValue, "value", CommandCompletions::eNoCompletion, { NULL, false }, "A value could be anything, depending on where and how it is used." },
1012     { eArgTypeWidth, "width", CommandCompletions::eNoCompletion, { NULL, false }, "Help text goes here." },
1013     { eArgTypeNone, "none", CommandCompletions::eNoCompletion, { NULL, false }, "No help available for this." },
1014     { eArgTypePlatform, "platform-name", CommandCompletions::ePlatformPluginCompletion, { NULL, false }, "The name of an installed platform plug-in . Type 'platform list' to see a complete list of installed platforms." },
1015     { eArgTypeWatchpointID, "watchpt-id", CommandCompletions::eNoCompletion, { NULL, false }, "Watchpoint IDs are positive integers." },
1016     { eArgTypeWatchpointIDRange, "watchpt-id-list", CommandCompletions::eNoCompletion, { NULL, false }, "For example, '1-3' or '1 to 3'." },
1017     { eArgTypeWatchType, "watch-type", CommandCompletions::eNoCompletion, { NULL, false }, "Specify the type for a watchpoint." }
1018 };
1019 
1020 const CommandObject::ArgumentTableEntry*
1021 CommandObject::GetArgumentTable ()
1022 {
1023     // If this assertion fires, then the table above is out of date with the CommandArgumentType enumeration
1024     assert ((sizeof (CommandObject::g_arguments_data) / sizeof (CommandObject::ArgumentTableEntry)) == eArgTypeLastArg);
1025     return CommandObject::g_arguments_data;
1026 }
1027 
1028 
1029