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::CheckRequirements (CommandReturnObject &result)
212 {
213 #ifdef LLDB_CONFIGURATION_DEBUG
214     // Nothing should be stored in m_exe_ctx between running commands as m_exe_ctx
215     // has shared pointers to the target, process, thread and frame and we don't
216     // want any CommandObject instances to keep any of these objects around
217     // longer than for a single command. Every command should call
218     // CommandObject::Cleanup() after it has completed
219     assert (m_exe_ctx.GetTargetPtr() == NULL);
220     assert (m_exe_ctx.GetProcessPtr() == NULL);
221     assert (m_exe_ctx.GetThreadPtr() == NULL);
222     assert (m_exe_ctx.GetFramePtr() == NULL);
223 #endif
224 
225     // Lock down the interpreter's execution context prior to running the
226     // command so we guarantee the selected target, process, thread and frame
227     // can't go away during the execution
228     m_exe_ctx = m_interpreter.GetExecutionContext();
229 
230     const uint32_t flags = GetFlags().Get();
231     if (flags & (eFlagRequiresTarget   |
232                  eFlagRequiresProcess  |
233                  eFlagRequiresThread   |
234                  eFlagRequiresFrame    |
235                  eFlagTryTargetAPILock ))
236     {
237 
238         if ((flags & eFlagRequiresTarget) && !m_exe_ctx.HasTargetScope())
239         {
240             result.AppendError (GetInvalidTargetDescription());
241             return false;
242         }
243 
244         if ((flags & eFlagRequiresProcess) && !m_exe_ctx.HasProcessScope())
245         {
246             result.AppendError (GetInvalidProcessDescription());
247             return false;
248         }
249 
250         if ((flags & eFlagRequiresThread) && !m_exe_ctx.HasThreadScope())
251         {
252             result.AppendError (GetInvalidThreadDescription());
253             return false;
254         }
255 
256         if ((flags & eFlagRequiresFrame) && !m_exe_ctx.HasFrameScope())
257         {
258             result.AppendError (GetInvalidFrameDescription());
259             return false;
260         }
261 
262         if ((flags & eFlagRequiresRegContext) && (m_exe_ctx.GetRegisterContext() == NULL))
263         {
264             result.AppendError (GetInvalidRegContextDescription());
265             return false;
266         }
267 
268         if (flags & eFlagTryTargetAPILock)
269         {
270             Target *target = m_exe_ctx.GetTargetPtr();
271             if (target)
272             {
273                 if (m_api_locker.TryLock (target->GetAPIMutex(), NULL) == false)
274                 {
275                     result.AppendError ("failed to get API lock");
276                     return false;
277                 }
278             }
279         }
280     }
281 
282     if (GetFlags().AnySet (CommandObject::eFlagProcessMustBeLaunched | CommandObject::eFlagProcessMustBePaused))
283     {
284         Process *process = m_interpreter.GetExecutionContext().GetProcessPtr();
285         if (process == NULL)
286         {
287             // A process that is not running is considered paused.
288             if (GetFlags().Test(CommandObject::eFlagProcessMustBeLaunched))
289             {
290                 result.AppendError ("Process must exist.");
291                 result.SetStatus (eReturnStatusFailed);
292                 return false;
293             }
294         }
295         else
296         {
297             StateType state = process->GetState();
298 
299             switch (state)
300             {
301             case eStateInvalid:
302             case eStateSuspended:
303             case eStateCrashed:
304             case eStateStopped:
305                 break;
306 
307             case eStateConnected:
308             case eStateAttaching:
309             case eStateLaunching:
310             case eStateDetached:
311             case eStateExited:
312             case eStateUnloaded:
313                 if (GetFlags().Test(CommandObject::eFlagProcessMustBeLaunched))
314                 {
315                     result.AppendError ("Process must be launched.");
316                     result.SetStatus (eReturnStatusFailed);
317                     return false;
318                 }
319                 break;
320 
321             case eStateRunning:
322             case eStateStepping:
323                 if (GetFlags().Test(CommandObject::eFlagProcessMustBePaused))
324                 {
325                     result.AppendError ("Process is running.  Use 'process interrupt' to pause execution.");
326                     result.SetStatus (eReturnStatusFailed);
327                     return false;
328                 }
329             }
330         }
331     }
332     return true;
333 }
334 
335 void
336 CommandObject::Cleanup ()
337 {
338     m_exe_ctx.Clear();
339     m_api_locker.Unlock();
340 }
341 
342 
343 class CommandDictCommandPartialMatch
344 {
345     public:
346         CommandDictCommandPartialMatch (const char *match_str)
347         {
348             m_match_str = match_str;
349         }
350         bool operator() (const std::pair<std::string, lldb::CommandObjectSP> map_element) const
351         {
352             // A NULL or empty string matches everything.
353             if (m_match_str == NULL || *m_match_str == '\0')
354                 return true;
355 
356             return map_element.first.find (m_match_str, 0) == 0;
357         }
358 
359     private:
360         const char *m_match_str;
361 };
362 
363 int
364 CommandObject::AddNamesMatchingPartialString (CommandObject::CommandMap &in_map, const char *cmd_str,
365                                               StringList &matches)
366 {
367     int number_added = 0;
368     CommandDictCommandPartialMatch matcher(cmd_str);
369 
370     CommandObject::CommandMap::iterator matching_cmds = std::find_if (in_map.begin(), in_map.end(), matcher);
371 
372     while (matching_cmds != in_map.end())
373     {
374         ++number_added;
375         matches.AppendString((*matching_cmds).first.c_str());
376         matching_cmds = std::find_if (++matching_cmds, in_map.end(), matcher);;
377     }
378     return number_added;
379 }
380 
381 int
382 CommandObject::HandleCompletion
383 (
384     Args &input,
385     int &cursor_index,
386     int &cursor_char_position,
387     int match_start_point,
388     int max_return_elements,
389     bool &word_complete,
390     StringList &matches
391 )
392 {
393     // Default implmentation of WantsCompletion() is !WantsRawCommandString().
394     // Subclasses who want raw command string but desire, for example,
395     // argument completion should override WantsCompletion() to return true,
396     // instead.
397     if (WantsRawCommandString() && !WantsCompletion())
398     {
399         // FIXME: Abstract telling the completion to insert the completion character.
400         matches.Clear();
401         return -1;
402     }
403     else
404     {
405         // Can we do anything generic with the options?
406         Options *cur_options = GetOptions();
407         CommandReturnObject result;
408         OptionElementVector opt_element_vector;
409 
410         if (cur_options != NULL)
411         {
412             // Re-insert the dummy command name string which will have been
413             // stripped off:
414             input.Unshift ("dummy-string");
415             cursor_index++;
416 
417 
418             // I stick an element on the end of the input, because if the last element is
419             // option that requires an argument, getopt_long will freak out.
420 
421             input.AppendArgument ("<FAKE-VALUE>");
422 
423             input.ParseArgsForCompletion (*cur_options, opt_element_vector, cursor_index);
424 
425             input.DeleteArgumentAtIndex(input.GetArgumentCount() - 1);
426 
427             bool handled_by_options;
428             handled_by_options = cur_options->HandleOptionCompletion (input,
429                                                                       opt_element_vector,
430                                                                       cursor_index,
431                                                                       cursor_char_position,
432                                                                       match_start_point,
433                                                                       max_return_elements,
434                                                                       word_complete,
435                                                                       matches);
436             if (handled_by_options)
437                 return matches.GetSize();
438         }
439 
440         // If we got here, the last word is not an option or an option argument.
441         return HandleArgumentCompletion (input,
442                                          cursor_index,
443                                          cursor_char_position,
444                                          opt_element_vector,
445                                          match_start_point,
446                                          max_return_elements,
447                                          word_complete,
448                                          matches);
449     }
450 }
451 
452 bool
453 CommandObject::HelpTextContainsWord (const char *search_word)
454 {
455     std::string options_usage_help;
456 
457     bool found_word = false;
458 
459     const char *short_help = GetHelp();
460     const char *long_help = GetHelpLong();
461     const char *syntax_help = GetSyntax();
462 
463     if (short_help && strcasestr (short_help, search_word))
464         found_word = true;
465     else if (long_help && strcasestr (long_help, search_word))
466         found_word = true;
467     else if (syntax_help && strcasestr (syntax_help, search_word))
468         found_word = true;
469 
470     if (!found_word
471         && GetOptions() != NULL)
472     {
473         StreamString usage_help;
474         GetOptions()->GenerateOptionUsage (usage_help, this);
475         if (usage_help.GetSize() > 0)
476         {
477             const char *usage_text = usage_help.GetData();
478             if (strcasestr (usage_text, search_word))
479               found_word = true;
480         }
481     }
482 
483     return found_word;
484 }
485 
486 int
487 CommandObject::GetNumArgumentEntries  ()
488 {
489     return m_arguments.size();
490 }
491 
492 CommandObject::CommandArgumentEntry *
493 CommandObject::GetArgumentEntryAtIndex (int idx)
494 {
495     if (idx < m_arguments.size())
496         return &(m_arguments[idx]);
497 
498     return NULL;
499 }
500 
501 CommandObject::ArgumentTableEntry *
502 CommandObject::FindArgumentDataByType (CommandArgumentType arg_type)
503 {
504     const ArgumentTableEntry *table = CommandObject::GetArgumentTable();
505 
506     for (int i = 0; i < eArgTypeLastArg; ++i)
507         if (table[i].arg_type == arg_type)
508             return (ArgumentTableEntry *) &(table[i]);
509 
510     return NULL;
511 }
512 
513 void
514 CommandObject::GetArgumentHelp (Stream &str, CommandArgumentType arg_type, CommandInterpreter &interpreter)
515 {
516     const ArgumentTableEntry* table = CommandObject::GetArgumentTable();
517     ArgumentTableEntry *entry = (ArgumentTableEntry *) &(table[arg_type]);
518 
519     // The table is *supposed* to be kept in arg_type order, but someone *could* have messed it up...
520 
521     if (entry->arg_type != arg_type)
522         entry = CommandObject::FindArgumentDataByType (arg_type);
523 
524     if (!entry)
525         return;
526 
527     StreamString name_str;
528     name_str.Printf ("<%s>", entry->arg_name);
529 
530     if (entry->help_function)
531     {
532         const char* help_text = entry->help_function();
533         if (!entry->help_function.self_formatting)
534         {
535             interpreter.OutputFormattedHelpText (str, name_str.GetData(), "--", help_text,
536                                                  name_str.GetSize());
537         }
538         else
539         {
540             interpreter.OutputHelpText(str, name_str.GetData(), "--", help_text,
541                                        name_str.GetSize());
542         }
543     }
544     else
545         interpreter.OutputFormattedHelpText (str, name_str.GetData(), "--", entry->help_text, name_str.GetSize());
546 }
547 
548 const char *
549 CommandObject::GetArgumentName (CommandArgumentType arg_type)
550 {
551     ArgumentTableEntry *entry = (ArgumentTableEntry *) &(CommandObject::GetArgumentTable()[arg_type]);
552 
553     // The table is *supposed* to be kept in arg_type order, but someone *could* have messed it up...
554 
555     if (entry->arg_type != arg_type)
556         entry = CommandObject::FindArgumentDataByType (arg_type);
557 
558     if (entry)
559         return entry->arg_name;
560 
561     StreamString str;
562     str << "Arg name for type (" << arg_type << ") not in arg table!";
563     return str.GetData();
564 }
565 
566 bool
567 CommandObject::IsPairType (ArgumentRepetitionType arg_repeat_type)
568 {
569     if ((arg_repeat_type == eArgRepeatPairPlain)
570         ||  (arg_repeat_type == eArgRepeatPairOptional)
571         ||  (arg_repeat_type == eArgRepeatPairPlus)
572         ||  (arg_repeat_type == eArgRepeatPairStar)
573         ||  (arg_repeat_type == eArgRepeatPairRange)
574         ||  (arg_repeat_type == eArgRepeatPairRangeOptional))
575         return true;
576 
577     return false;
578 }
579 
580 static CommandObject::CommandArgumentEntry
581 OptSetFiltered(uint32_t opt_set_mask, CommandObject::CommandArgumentEntry &cmd_arg_entry)
582 {
583     CommandObject::CommandArgumentEntry ret_val;
584     for (unsigned i = 0; i < cmd_arg_entry.size(); ++i)
585         if (opt_set_mask & cmd_arg_entry[i].arg_opt_set_association)
586             ret_val.push_back(cmd_arg_entry[i]);
587     return ret_val;
588 }
589 
590 // Default parameter value of opt_set_mask is LLDB_OPT_SET_ALL, which means take
591 // all the argument data into account.  On rare cases where some argument sticks
592 // with certain option sets, this function returns the option set filtered args.
593 void
594 CommandObject::GetFormattedCommandArguments (Stream &str, uint32_t opt_set_mask)
595 {
596     int num_args = m_arguments.size();
597     for (int i = 0; i < num_args; ++i)
598     {
599         if (i > 0)
600             str.Printf (" ");
601         CommandArgumentEntry arg_entry =
602             opt_set_mask == LLDB_OPT_SET_ALL ? m_arguments[i]
603                                              : OptSetFiltered(opt_set_mask, m_arguments[i]);
604         int num_alternatives = arg_entry.size();
605 
606         if ((num_alternatives == 2)
607             && IsPairType (arg_entry[0].arg_repetition))
608         {
609             const char *first_name = GetArgumentName (arg_entry[0].arg_type);
610             const char *second_name = GetArgumentName (arg_entry[1].arg_type);
611             switch (arg_entry[0].arg_repetition)
612             {
613                 case eArgRepeatPairPlain:
614                     str.Printf ("<%s> <%s>", first_name, second_name);
615                     break;
616                 case eArgRepeatPairOptional:
617                     str.Printf ("[<%s> <%s>]", first_name, second_name);
618                     break;
619                 case eArgRepeatPairPlus:
620                     str.Printf ("<%s> <%s> [<%s> <%s> [...]]", first_name, second_name, first_name, second_name);
621                     break;
622                 case eArgRepeatPairStar:
623                     str.Printf ("[<%s> <%s> [<%s> <%s> [...]]]", first_name, second_name, first_name, second_name);
624                     break;
625                 case eArgRepeatPairRange:
626                     str.Printf ("<%s_1> <%s_1> ... <%s_n> <%s_n>", first_name, second_name, first_name, second_name);
627                     break;
628                 case eArgRepeatPairRangeOptional:
629                     str.Printf ("[<%s_1> <%s_1> ... <%s_n> <%s_n>]", first_name, second_name, first_name, second_name);
630                     break;
631                 // Explicitly test for all the rest of the cases, so if new types get added we will notice the
632                 // missing case statement(s).
633                 case eArgRepeatPlain:
634                 case eArgRepeatOptional:
635                 case eArgRepeatPlus:
636                 case eArgRepeatStar:
637                 case eArgRepeatRange:
638                     // These should not be reached, as they should fail the IsPairType test above.
639                     break;
640             }
641         }
642         else
643         {
644             StreamString names;
645             for (int j = 0; j < num_alternatives; ++j)
646             {
647                 if (j > 0)
648                     names.Printf (" | ");
649                 names.Printf ("%s", GetArgumentName (arg_entry[j].arg_type));
650             }
651             switch (arg_entry[0].arg_repetition)
652             {
653                 case eArgRepeatPlain:
654                     str.Printf ("<%s>", names.GetData());
655                     break;
656                 case eArgRepeatPlus:
657                     str.Printf ("<%s> [<%s> [...]]", names.GetData(), names.GetData());
658                     break;
659                 case eArgRepeatStar:
660                     str.Printf ("[<%s> [<%s> [...]]]", names.GetData(), names.GetData());
661                     break;
662                 case eArgRepeatOptional:
663                     str.Printf ("[<%s>]", names.GetData());
664                     break;
665                 case eArgRepeatRange:
666                     str.Printf ("<%s_1> .. <%s_n>", names.GetData(), names.GetData());
667                     break;
668                 // Explicitly test for all the rest of the cases, so if new types get added we will notice the
669                 // missing case statement(s).
670                 case eArgRepeatPairPlain:
671                 case eArgRepeatPairOptional:
672                 case eArgRepeatPairPlus:
673                 case eArgRepeatPairStar:
674                 case eArgRepeatPairRange:
675                 case eArgRepeatPairRangeOptional:
676                     // These should not be hit, as they should pass the IsPairType test above, and control should
677                     // have gone into the other branch of the if statement.
678                     break;
679             }
680         }
681     }
682 }
683 
684 CommandArgumentType
685 CommandObject::LookupArgumentName (const char *arg_name)
686 {
687     CommandArgumentType return_type = eArgTypeLastArg;
688 
689     std::string arg_name_str (arg_name);
690     size_t len = arg_name_str.length();
691     if (arg_name[0] == '<'
692         && arg_name[len-1] == '>')
693         arg_name_str = arg_name_str.substr (1, len-2);
694 
695     const ArgumentTableEntry *table = GetArgumentTable();
696     for (int i = 0; i < eArgTypeLastArg; ++i)
697         if (arg_name_str.compare (table[i].arg_name) == 0)
698             return_type = g_arguments_data[i].arg_type;
699 
700     return return_type;
701 }
702 
703 static const char *
704 RegisterNameHelpTextCallback ()
705 {
706     return "Register names can be specified using the architecture specific names.  "
707     "They can also be specified using generic names.  Not all generic entities have "
708     "registers backing them on all architectures.  When they don't the generic name "
709     "will return an error.\n"
710     "The generic names defined in lldb are:\n"
711     "\n"
712     "pc       - program counter register\n"
713     "ra       - return address register\n"
714     "fp       - frame pointer register\n"
715     "sp       - stack pointer register\n"
716     "flags    - the flags register\n"
717     "arg{1-6} - integer argument passing registers.\n";
718 }
719 
720 static const char *
721 BreakpointIDHelpTextCallback ()
722 {
723     return "Breakpoint ID's consist major and minor numbers;  the major number "
724     "corresponds to the single entity that was created with a 'breakpoint set' "
725     "command; the minor numbers correspond to all the locations that were actually "
726     "found/set based on the major breakpoint.  A full breakpoint ID might look like "
727     "3.14, meaning the 14th location set for the 3rd breakpoint.  You can specify "
728     "all the locations of a breakpoint by just indicating the major breakpoint "
729     "number. A valid breakpoint id consists either of just the major id number, "
730     "or the major number, a dot, and the location number (e.g. 3 or 3.2 could "
731     "both be valid breakpoint ids).";
732 }
733 
734 static const char *
735 BreakpointIDRangeHelpTextCallback ()
736 {
737     return "A 'breakpoint id list' is a manner of specifying multiple breakpoints. "
738     "This can be done  through several mechanisms.  The easiest way is to just "
739     "enter a space-separated list of breakpoint ids.  To specify all the "
740     "breakpoint locations under a major breakpoint, you can use the major "
741     "breakpoint number followed by '.*', eg. '5.*' means all the locations under "
742     "breakpoint 5.  You can also indicate a range of breakpoints by using "
743     "<start-bp-id> - <end-bp-id>.  The start-bp-id and end-bp-id for a range can "
744     "be any valid breakpoint ids.  It is not legal, however, to specify a range "
745     "using specific locations that cross major breakpoint numbers.  I.e. 3.2 - 3.7"
746     " is legal; 2 - 5 is legal; but 3.2 - 4.4 is not legal.";
747 }
748 
749 static const char *
750 GDBFormatHelpTextCallback ()
751 {
752     return "A GDB format consists of a repeat count, a format letter and a size letter. "
753     "The repeat count is optional and defaults to 1. The format letter is optional "
754     "and defaults to the previous format that was used. The size letter is optional "
755     "and defaults to the previous size that was used.\n"
756     "\n"
757     "Format letters include:\n"
758     "o - octal\n"
759     "x - hexadecimal\n"
760     "d - decimal\n"
761     "u - unsigned decimal\n"
762     "t - binary\n"
763     "f - float\n"
764     "a - address\n"
765     "i - instruction\n"
766     "c - char\n"
767     "s - string\n"
768     "T - OSType\n"
769     "A - float as hex\n"
770     "\n"
771     "Size letters include:\n"
772     "b - 1 byte  (byte)\n"
773     "h - 2 bytes (halfword)\n"
774     "w - 4 bytes (word)\n"
775     "g - 8 bytes (giant)\n"
776     "\n"
777     "Example formats:\n"
778     "32xb - show 32 1 byte hexadecimal integer values\n"
779     "16xh - show 16 2 byte hexadecimal integer values\n"
780     "64   - show 64 2 byte hexadecimal integer values (format and size from the last format)\n"
781     "dw   - show 1 4 byte decimal integer value\n"
782     ;
783 }
784 
785 static const char *
786 FormatHelpTextCallback ()
787 {
788 
789     static char* help_text_ptr = NULL;
790 
791     if (help_text_ptr)
792         return help_text_ptr;
793 
794     StreamString sstr;
795     sstr << "One of the format names (or one-character names) that can be used to show a variable's value:\n";
796     for (Format f = eFormatDefault; f < kNumFormats; f = Format(f+1))
797     {
798         if (f != eFormatDefault)
799             sstr.PutChar('\n');
800 
801         char format_char = FormatManager::GetFormatAsFormatChar(f);
802         if (format_char)
803             sstr.Printf("'%c' or ", format_char);
804 
805         sstr.Printf ("\"%s\"", FormatManager::GetFormatAsCString(f));
806     }
807 
808     sstr.Flush();
809 
810     std::string data = sstr.GetString();
811 
812     help_text_ptr = new char[data.length()+1];
813 
814     data.copy(help_text_ptr, data.length());
815 
816     return help_text_ptr;
817 }
818 
819 static const char *
820 LanguageTypeHelpTextCallback ()
821 {
822     static char* help_text_ptr = NULL;
823 
824     if (help_text_ptr)
825         return help_text_ptr;
826 
827     StreamString sstr;
828     sstr << "One of the following languages:\n";
829 
830     for (unsigned int l = eLanguageTypeUnknown; l < eNumLanguageTypes; ++l)
831     {
832         sstr << "  " << LanguageRuntime::GetNameForLanguageType(static_cast<LanguageType>(l)) << "\n";
833     }
834 
835     sstr.Flush();
836 
837     std::string data = sstr.GetString();
838 
839     help_text_ptr = new char[data.length()+1];
840 
841     data.copy(help_text_ptr, data.length());
842 
843     return help_text_ptr;
844 }
845 
846 static const char *
847 SummaryStringHelpTextCallback()
848 {
849     return
850         "A summary string is a way to extract information from variables in order to present them using a summary.\n"
851         "Summary strings contain static text, variables, scopes and control sequences:\n"
852         "  - Static text can be any sequence of non-special characters, i.e. anything but '{', '}', '$', or '\\'.\n"
853         "  - Variables are sequences of characters beginning with ${, ending with } and that contain symbols in the format described below.\n"
854         "  - 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"
855         "  - Control sequences are the usual C/C++ '\\a', '\\n', ..., plus '\\$', '\\{' and '\\}'.\n"
856         "A summary string works by copying static text verbatim, turning control sequences into their character counterpart, expanding variables and trying to expand scopes.\n"
857         "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"
858         "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"
859         " (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"
860         " ${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."
861         " 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"
862         "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."
863         "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"
864         " path refers to:\n"
865         "  - 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"
866         " and displayed as an individual variable\n"
867         "  - 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"
868         " 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"
869         "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"
870         "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"
871         " special symbols only allowed as part of a variable:\n"
872         "    %V: show the value of the object by default\n"
873         "    %S: show the summary of the object by default\n"
874         "    %@: show the runtime-provided object description (for Objective-C, it calls NSPrintForDebugger; for C/C++ it does nothing)\n"
875         "    %L: show the location of the object (memory address or a register name)\n"
876         "    %#: show the number of children of the object\n"
877         "    %T: show the type of the object\n"
878         "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"
879         " 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"
880         " count the number of actual elements stored in an std::list:\n"
881         "type summary add -s \"${svar%#}\" -x \"std::list<\"";
882 }
883 
884 static const char *
885 ExprPathHelpTextCallback()
886 {
887     return
888     "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"
889     "For instance, given a class:\n"
890     "  class foo {\n"
891     "      int a;\n"
892     "      int b; .\n"
893     "      foo* next;\n"
894     "  };\n"
895     "the expression to read item b in the item pointed to by next for foo aFoo would be aFoo.next->b.\n"
896     "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"
897     "Expression paths in LLDB include dot (.) and arrow (->) operators, and most commands using expression paths have ways to also accept the star (*) operator.\n"
898     "The meaning of these operators is the same as the usual one given to them by the C/C++ standards.\n"
899     "LLDB also has support for indexing ([ ]) in expression paths, and extends the traditional meaning of the square brackets operator to allow bitfield extraction:\n"
900     "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"
901     " 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"
902     " 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"
903     " meaning of array slicing (taking elements n thru m inside the array or pointed-to memory).";
904 }
905 
906 void
907 CommandObject::AddIDsArgumentData(CommandArgumentEntry &arg, CommandArgumentType ID, CommandArgumentType IDRange)
908 {
909     CommandArgumentData id_arg;
910     CommandArgumentData id_range_arg;
911 
912     // Create the first variant for the first (and only) argument for this command.
913     id_arg.arg_type = ID;
914     id_arg.arg_repetition = eArgRepeatOptional;
915 
916     // Create the second variant for the first (and only) argument for this command.
917     id_range_arg.arg_type = IDRange;
918     id_range_arg.arg_repetition = eArgRepeatOptional;
919 
920     // The first (and only) argument for this command could be either an id or an id_range.
921     // Push both variants into the entry for the first argument for this command.
922     arg.push_back(id_arg);
923     arg.push_back(id_range_arg);
924 }
925 
926 const char *
927 CommandObject::GetArgumentTypeAsCString (const lldb::CommandArgumentType arg_type)
928 {
929     if (arg_type >=0 && arg_type < eArgTypeLastArg)
930         return g_arguments_data[arg_type].arg_name;
931     return NULL;
932 
933 }
934 
935 const char *
936 CommandObject::GetArgumentDescriptionAsCString (const lldb::CommandArgumentType arg_type)
937 {
938     if (arg_type >=0 && arg_type < eArgTypeLastArg)
939         return g_arguments_data[arg_type].help_text;
940     return NULL;
941 }
942 
943 bool
944 CommandObjectParsed::Execute (const char *args_string, CommandReturnObject &result)
945 {
946     CommandOverrideCallback command_callback = GetOverrideCallback();
947     bool handled = false;
948     Args cmd_args (args_string);
949     if (command_callback)
950     {
951         Args full_args (GetCommandName ());
952         full_args.AppendArguments(cmd_args);
953         handled = command_callback (GetOverrideCallbackBaton(), full_args.GetConstArgumentVector());
954     }
955     if (!handled)
956     {
957         for (size_t i = 0; i < cmd_args.GetArgumentCount();  ++i)
958         {
959             const char *tmp_str = cmd_args.GetArgumentAtIndex (i);
960             if (tmp_str[0] == '`')  // back-quote
961                 cmd_args.ReplaceArgumentAtIndex (i, m_interpreter.ProcessEmbeddedScriptCommands (tmp_str));
962         }
963 
964         if (CheckRequirements(result))
965         {
966             if (ParseOptions (cmd_args, result))
967             {
968                 // Call the command-specific version of 'Execute', passing it the already processed arguments.
969                 handled = DoExecute (cmd_args, result);
970             }
971         }
972 
973         Cleanup();
974     }
975     return handled;
976 }
977 
978 bool
979 CommandObjectRaw::Execute (const char *args_string, CommandReturnObject &result)
980 {
981     CommandOverrideCallback command_callback = GetOverrideCallback();
982     bool handled = false;
983     if (command_callback)
984     {
985         std::string full_command (GetCommandName ());
986         full_command += ' ';
987         full_command += args_string;
988         const char *argv[2] = { NULL, NULL };
989         argv[0] = full_command.c_str();
990         handled = command_callback (GetOverrideCallbackBaton(), argv);
991     }
992     if (!handled)
993     {
994         if (CheckRequirements(result))
995             handled = DoExecute (args_string, result);
996 
997         Cleanup();
998     }
999     return handled;
1000 }
1001 
1002 static
1003 const char *arch_helper()
1004 {
1005     static StreamString g_archs_help;
1006     if (g_archs_help.Empty())
1007     {
1008         StringList archs;
1009         ArchSpec::AutoComplete(NULL, archs);
1010         g_archs_help.Printf("These are the supported architecture names:\n");
1011         archs.Join("\n", g_archs_help);
1012     }
1013     return g_archs_help.GetData();
1014 }
1015 
1016 CommandObject::ArgumentTableEntry
1017 CommandObject::g_arguments_data[] =
1018 {
1019     { eArgTypeAddress, "address", CommandCompletions::eNoCompletion, { NULL, false }, "A valid address in the target program's execution space." },
1020     { eArgTypeAddressOrExpression, "address-expression", CommandCompletions::eNoCompletion, { NULL, false }, "An expression that resolves to an address." },
1021     { eArgTypeAliasName, "alias-name", CommandCompletions::eNoCompletion, { NULL, false }, "The name of an abbreviation (alias) for a debugger command." },
1022     { 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.)" },
1023     { eArgTypeArchitecture, "arch", CommandCompletions::eArchitectureCompletion, { arch_helper, true }, "The architecture name, e.g. i386 or x86_64." },
1024     { eArgTypeBoolean, "boolean", CommandCompletions::eNoCompletion, { NULL, false }, "A Boolean value: 'true' or 'false'" },
1025     { eArgTypeBreakpointID, "breakpt-id", CommandCompletions::eNoCompletion, { BreakpointIDHelpTextCallback, false }, NULL },
1026     { eArgTypeBreakpointIDRange, "breakpt-id-list", CommandCompletions::eNoCompletion, { BreakpointIDRangeHelpTextCallback, false }, NULL },
1027     { eArgTypeByteSize, "byte-size", CommandCompletions::eNoCompletion, { NULL, false }, "Number of bytes to use." },
1028     { eArgTypeClassName, "class-name", CommandCompletions::eNoCompletion, { NULL, false }, "Then name of a class from the debug information in the program." },
1029     { eArgTypeCommandName, "cmd-name", CommandCompletions::eNoCompletion, { NULL, false }, "A debugger command (may be multiple words), without any options or arguments." },
1030     { eArgTypeCount, "count", CommandCompletions::eNoCompletion, { NULL, false }, "An unsigned integer." },
1031     { eArgTypeDirectoryName, "directory", CommandCompletions::eDiskDirectoryCompletion, { NULL, false }, "A directory name." },
1032     { eArgTypeDisassemblyFlavor, "disassembly-flavor", CommandCompletions::eNoCompletion, { NULL, false }, "A disassembly flavor recognized by your disassembly plugin.  Currently the only valid options are \"att\" and \"intel\" for Intel targets" },
1033     { eArgTypeEndAddress, "end-address", CommandCompletions::eNoCompletion, { NULL, false }, "Help text goes here." },
1034     { eArgTypeExpression, "expr", CommandCompletions::eNoCompletion, { NULL, false }, "Help text goes here." },
1035     { eArgTypeExpressionPath, "expr-path", CommandCompletions::eNoCompletion, { ExprPathHelpTextCallback, true }, NULL },
1036     { eArgTypeExprFormat, "expression-format", CommandCompletions::eNoCompletion, { NULL, false }, "[ [bool|b] | [bin] | [char|c] | [oct|o] | [dec|i|d|u] | [hex|x] | [float|f] | [cstr|s] ]" },
1037     { eArgTypeFilename, "filename", CommandCompletions::eDiskFileCompletion, { NULL, false }, "The name of a file (can include path)." },
1038     { eArgTypeFormat, "format", CommandCompletions::eNoCompletion, { FormatHelpTextCallback, true }, NULL },
1039     { eArgTypeFrameIndex, "frame-index", CommandCompletions::eNoCompletion, { NULL, false }, "Index into a thread's list of frames." },
1040     { eArgTypeFullName, "fullname", CommandCompletions::eNoCompletion, { NULL, false }, "Help text goes here." },
1041     { eArgTypeFunctionName, "function-name", CommandCompletions::eNoCompletion, { NULL, false }, "The name of a function." },
1042     { eArgTypeFunctionOrSymbol, "function-or-symbol", CommandCompletions::eNoCompletion, { NULL, false }, "The name of a function or symbol." },
1043     { eArgTypeGDBFormat, "gdb-format", CommandCompletions::eNoCompletion, { GDBFormatHelpTextCallback, true }, NULL },
1044     { eArgTypeIndex, "index", CommandCompletions::eNoCompletion, { NULL, false }, "An index into a list." },
1045     { eArgTypeLanguage, "language", CommandCompletions::eNoCompletion, { LanguageTypeHelpTextCallback, true }, NULL },
1046     { eArgTypeLineNum, "linenum", CommandCompletions::eNoCompletion, { NULL, false }, "Line number in a source file." },
1047     { 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." },
1048     { 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)." },
1049     { eArgTypeMethod, "method", CommandCompletions::eNoCompletion, { NULL, false }, "A C++ method name." },
1050     { eArgTypeName, "name", CommandCompletions::eNoCompletion, { NULL, false }, "Help text goes here." },
1051     { eArgTypeNewPathPrefix, "new-path-prefix", CommandCompletions::eNoCompletion, { NULL, false }, "Help text goes here." },
1052     { eArgTypeNumLines, "num-lines", CommandCompletions::eNoCompletion, { NULL, false }, "The number of lines to use." },
1053     { eArgTypeNumberPerLine, "number-per-line", CommandCompletions::eNoCompletion, { NULL, false }, "The number of items per line to display." },
1054     { eArgTypeOffset, "offset", CommandCompletions::eNoCompletion, { NULL, false }, "Help text goes here." },
1055     { eArgTypeOldPathPrefix, "old-path-prefix", CommandCompletions::eNoCompletion, { NULL, false }, "Help text goes here." },
1056     { eArgTypeOneLiner, "one-line-command", CommandCompletions::eNoCompletion, { NULL, false }, "A command that is entered as a single line of text." },
1057     { eArgTypePid, "pid", CommandCompletions::eNoCompletion, { NULL, false }, "The process ID number." },
1058     { eArgTypePlugin, "plugin", CommandCompletions::eNoCompletion, { NULL, false }, "Help text goes here." },
1059     { eArgTypeProcessName, "process-name", CommandCompletions::eNoCompletion, { NULL, false }, "The name of the process." },
1060     { eArgTypePythonClass, "python-class", CommandCompletions::eNoCompletion, { NULL, false }, "The name of a Python class." },
1061     { eArgTypePythonFunction, "python-function", CommandCompletions::eNoCompletion, { NULL, false }, "The name of a Python function." },
1062     { eArgTypePythonScript, "python-script", CommandCompletions::eNoCompletion, { NULL, false }, "Source code written in Python." },
1063     { eArgTypeQueueName, "queue-name", CommandCompletions::eNoCompletion, { NULL, false }, "The name of the thread queue." },
1064     { eArgTypeRegisterName, "register-name", CommandCompletions::eNoCompletion, { RegisterNameHelpTextCallback, true }, NULL },
1065     { eArgTypeRegularExpression, "regular-expression", CommandCompletions::eNoCompletion, { NULL, false }, "A regular expression." },
1066     { eArgTypeRunArgs, "run-args", CommandCompletions::eNoCompletion, { NULL, false }, "Arguments to be passed to the target program when it starts executing." },
1067     { eArgTypeRunMode, "run-mode", CommandCompletions::eNoCompletion, { NULL, false }, "Help text goes here." },
1068     { eArgTypeScriptedCommandSynchronicity, "script-cmd-synchronicity", CommandCompletions::eNoCompletion, { NULL, false }, "The synchronicity to use to run scripted commands with regard to LLDB event system." },
1069     { eArgTypeScriptLang, "script-language", CommandCompletions::eNoCompletion, { NULL, false }, "The scripting language to be used for script-based commands.  Currently only Python is valid." },
1070     { eArgTypeSearchWord, "search-word", CommandCompletions::eNoCompletion, { NULL, false }, "The word for which you wish to search for information about." },
1071     { eArgTypeSelector, "selector", CommandCompletions::eNoCompletion, { NULL, false }, "An Objective-C selector name." },
1072     { 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)." },
1073     { 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)." },
1074     { eArgTypeSettingPrefix, "setting-prefix", CommandCompletions::eNoCompletion, { NULL, false }, "The name of a settable internal debugger variable up to a dot ('.'), e.g. 'target.process.'" },
1075     { 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." },
1076     { eArgTypeShlibName, "shlib-name", CommandCompletions::eNoCompletion, { NULL, false }, "The name of a shared library." },
1077     { eArgTypeSourceFile, "source-file", CommandCompletions::eSourceFileCompletion, { NULL, false }, "The name of a source file.." },
1078     { eArgTypeSortOrder, "sort-order", CommandCompletions::eNoCompletion, { NULL, false }, "Specify a sort order when dumping lists." },
1079     { eArgTypeStartAddress, "start-address", CommandCompletions::eNoCompletion, { NULL, false }, "Help text goes here." },
1080     { eArgTypeSummaryString, "summary-string", CommandCompletions::eNoCompletion, { SummaryStringHelpTextCallback, true }, NULL },
1081     { eArgTypeSymbol, "symbol", CommandCompletions::eSymbolCompletion, { NULL, false }, "Any symbol name (function name, variable, argument, etc.)" },
1082     { eArgTypeThreadID, "thread-id", CommandCompletions::eNoCompletion, { NULL, false }, "Thread ID number." },
1083     { eArgTypeThreadIndex, "thread-index", CommandCompletions::eNoCompletion, { NULL, false }, "Index into the process' list of threads." },
1084     { eArgTypeThreadName, "thread-name", CommandCompletions::eNoCompletion, { NULL, false }, "The thread's name." },
1085     { eArgTypeUnsignedInteger, "unsigned-integer", CommandCompletions::eNoCompletion, { NULL, false }, "An unsigned integer." },
1086     { eArgTypeUnixSignal, "unix-signal", CommandCompletions::eNoCompletion, { NULL, false }, "A valid Unix signal name or number (e.g. SIGKILL, KILL or 9)." },
1087     { eArgTypeVarName, "variable-name", CommandCompletions::eNoCompletion, { NULL, false }, "The name of a variable in your program." },
1088     { eArgTypeValue, "value", CommandCompletions::eNoCompletion, { NULL, false }, "A value could be anything, depending on where and how it is used." },
1089     { eArgTypeWidth, "width", CommandCompletions::eNoCompletion, { NULL, false }, "Help text goes here." },
1090     { eArgTypeNone, "none", CommandCompletions::eNoCompletion, { NULL, false }, "No help available for this." },
1091     { 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." },
1092     { eArgTypeWatchpointID, "watchpt-id", CommandCompletions::eNoCompletion, { NULL, false }, "Watchpoint IDs are positive integers." },
1093     { eArgTypeWatchpointIDRange, "watchpt-id-list", CommandCompletions::eNoCompletion, { NULL, false }, "For example, '1-3' or '1 to 3'." },
1094     { eArgTypeWatchType, "watch-type", CommandCompletions::eNoCompletion, { NULL, false }, "Specify the type for a watchpoint." }
1095 };
1096 
1097 const CommandObject::ArgumentTableEntry*
1098 CommandObject::GetArgumentTable ()
1099 {
1100     // If this assertion fires, then the table above is out of date with the CommandArgumentType enumeration
1101     assert ((sizeof (CommandObject::g_arguments_data) / sizeof (CommandObject::ArgumentTableEntry)) == eArgTypeLastArg);
1102     return CommandObject::g_arguments_data;
1103 }
1104 
1105 
1106