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