1 //===-- CommandInterpreter.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 <string>
11 #include <vector>
12 
13 #include <getopt.h>
14 #include <stdlib.h>
15 
16 #include "../Commands/CommandObjectApropos.h"
17 #include "../Commands/CommandObjectArgs.h"
18 #include "../Commands/CommandObjectBreakpoint.h"
19 //#include "../Commands/CommandObjectCall.h"
20 #include "../Commands/CommandObjectDisassemble.h"
21 #include "../Commands/CommandObjectExpression.h"
22 //#include "../Commands/CommandObjectFile.h"
23 #include "../Commands/CommandObjectFrame.h"
24 #include "../Commands/CommandObjectHelp.h"
25 #include "../Commands/CommandObjectLog.h"
26 #include "../Commands/CommandObjectMemory.h"
27 #include "../Commands/CommandObjectPlatform.h"
28 #include "../Commands/CommandObjectProcess.h"
29 #include "../Commands/CommandObjectQuit.h"
30 #include "lldb/Interpreter/CommandObjectRegexCommand.h"
31 #include "../Commands/CommandObjectRegister.h"
32 #include "CommandObjectScript.h"
33 #include "../Commands/CommandObjectSettings.h"
34 #include "../Commands/CommandObjectSource.h"
35 #include "../Commands/CommandObjectCommands.h"
36 #include "../Commands/CommandObjectSyntax.h"
37 #include "../Commands/CommandObjectTarget.h"
38 #include "../Commands/CommandObjectThread.h"
39 #include "../Commands/CommandObjectVersion.h"
40 
41 #include "lldb/Interpreter/Args.h"
42 #include "lldb/Interpreter/Options.h"
43 #include "lldb/Core/Debugger.h"
44 #include "lldb/Core/InputReader.h"
45 #include "lldb/Core/Stream.h"
46 #include "lldb/Core/Timer.h"
47 #include "lldb/Host/Host.h"
48 #include "lldb/Target/Process.h"
49 #include "lldb/Target/Thread.h"
50 #include "lldb/Target/TargetList.h"
51 #include "lldb/Utility/CleanUp.h"
52 
53 #include "lldb/Interpreter/CommandReturnObject.h"
54 #include "lldb/Interpreter/CommandInterpreter.h"
55 #include "lldb/Interpreter/ScriptInterpreterNone.h"
56 #include "lldb/Interpreter/ScriptInterpreterPython.h"
57 
58 using namespace lldb;
59 using namespace lldb_private;
60 
61 CommandInterpreter::CommandInterpreter
62 (
63     Debugger &debugger,
64     ScriptLanguage script_language,
65     bool synchronous_execution
66 ) :
67     Broadcaster ("lldb.command-interpreter"),
68     m_debugger (debugger),
69     m_synchronous_execution (synchronous_execution),
70     m_skip_lldbinit_files (false),
71     m_script_interpreter_ap (),
72     m_comment_char ('#')
73 {
74     const char *dbg_name = debugger.GetInstanceName().AsCString();
75     std::string lang_name = ScriptInterpreter::LanguageToString (script_language);
76     StreamString var_name;
77     var_name.Printf ("[%s].script-lang", dbg_name);
78     debugger.GetSettingsController()->SetVariable (var_name.GetData(), lang_name.c_str(),
79                                                    eVarSetOperationAssign, false,
80                                                    m_debugger.GetInstanceName().AsCString());
81     SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
82     SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
83     SetEventName (eBroadcastBitQuitCommandReceived, "quit");
84 }
85 
86 void
87 CommandInterpreter::Initialize ()
88 {
89     Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
90 
91     CommandReturnObject result;
92 
93     LoadCommandDictionary ();
94 
95     // Set up some initial aliases.
96     CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
97     if (cmd_obj_sp)
98     {
99         AddAlias ("q", cmd_obj_sp);
100         AddAlias ("exit", cmd_obj_sp);
101     }
102 
103     cmd_obj_sp = GetCommandSPExact ("process continue", false);
104     if (cmd_obj_sp)
105     {
106         AddAlias ("c", cmd_obj_sp);
107         AddAlias ("continue", cmd_obj_sp);
108     }
109 
110     cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
111     if (cmd_obj_sp)
112         AddAlias ("b", cmd_obj_sp);
113 
114     cmd_obj_sp = GetCommandSPExact ("thread backtrace", false);
115     if (cmd_obj_sp)
116         AddAlias ("bt", cmd_obj_sp);
117 
118     cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
119     if (cmd_obj_sp)
120         AddAlias ("si", cmd_obj_sp);
121 
122     cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
123     if (cmd_obj_sp)
124     {
125         AddAlias ("s", cmd_obj_sp);
126         AddAlias ("step", cmd_obj_sp);
127     }
128 
129     cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
130     if (cmd_obj_sp)
131     {
132         AddAlias ("n", cmd_obj_sp);
133         AddAlias ("next", cmd_obj_sp);
134     }
135 
136     cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
137     if (cmd_obj_sp)
138     {
139         AddAlias ("f", cmd_obj_sp);
140         AddAlias ("finish", cmd_obj_sp);
141     }
142 
143     cmd_obj_sp = GetCommandSPExact ("source list", false);
144     if (cmd_obj_sp)
145     {
146         AddAlias ("l", cmd_obj_sp);
147         AddAlias ("list", cmd_obj_sp);
148     }
149 
150     cmd_obj_sp = GetCommandSPExact ("memory read", false);
151     if (cmd_obj_sp)
152         AddAlias ("x", cmd_obj_sp);
153 
154     cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
155     if (cmd_obj_sp)
156         AddAlias ("up", cmd_obj_sp);
157 
158     cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
159     if (cmd_obj_sp)
160         AddAlias ("down", cmd_obj_sp);
161 
162     cmd_obj_sp = GetCommandSPExact ("target create", false);
163     if (cmd_obj_sp)
164         AddAlias ("file", cmd_obj_sp);
165 
166     cmd_obj_sp = GetCommandSPExact ("target modules", false);
167     if (cmd_obj_sp)
168         AddAlias ("image", cmd_obj_sp);
169 
170 
171     OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
172 
173     cmd_obj_sp = GetCommandSPExact ("expression", false);
174     if (cmd_obj_sp)
175     {
176         AddAlias ("expr", cmd_obj_sp);
177 
178         ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
179         AddAlias ("p", cmd_obj_sp);
180         AddAlias ("print", cmd_obj_sp);
181         AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
182         AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
183 
184         alias_arguments_vector_sp.reset (new OptionArgVector);
185         ProcessAliasOptionsArgs (cmd_obj_sp, "-o --", alias_arguments_vector_sp);
186         AddAlias ("po", cmd_obj_sp);
187         AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
188     }
189 
190     cmd_obj_sp = GetCommandSPExact ("process launch", false);
191     if (cmd_obj_sp)
192     {
193         alias_arguments_vector_sp.reset (new OptionArgVector);
194         ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
195         AddAlias ("r", cmd_obj_sp);
196         AddAlias ("run", cmd_obj_sp);
197         AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
198         AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
199     }
200 
201 }
202 
203 const char *
204 CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
205 {
206     // This function has not yet been implemented.
207 
208     // Look for any embedded script command
209     // If found,
210     //    get interpreter object from the command dictionary,
211     //    call execute_one_command on it,
212     //    get the results as a string,
213     //    substitute that string for current stuff.
214 
215     return arg;
216 }
217 
218 
219 void
220 CommandInterpreter::LoadCommandDictionary ()
221 {
222     Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
223 
224     // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
225     //
226     // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
227     // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
228     // the cross-referencing stuff) are created!!!
229     //
230     // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
231 
232 
233     // Command objects that inherit from CommandObjectCrossref must be created before other command objects
234     // are created.  This is so that when another command is created that needs to go into a crossref object,
235     // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
236     // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
237 
238     // Non-CommandObjectCrossref commands can now be created.
239 
240     lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
241 
242     m_command_dict["apropos"]   = CommandObjectSP (new CommandObjectApropos (*this));
243     m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
244     //m_command_dict["call"]      = CommandObjectSP (new CommandObjectCall (*this));
245     m_command_dict["command"]   = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
246     m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
247     m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
248 //    m_command_dict["file"]      = CommandObjectSP (new CommandObjectFile (*this));
249     m_command_dict["frame"]     = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
250     m_command_dict["help"]      = CommandObjectSP (new CommandObjectHelp (*this));
251     ///    m_command_dict["image"]     = CommandObjectSP (new CommandObjectImage (*this));
252     m_command_dict["log"]       = CommandObjectSP (new CommandObjectLog (*this));
253     m_command_dict["memory"]    = CommandObjectSP (new CommandObjectMemory (*this));
254     m_command_dict["platform"]  = CommandObjectSP (new CommandObjectPlatform (*this));
255     m_command_dict["process"]   = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
256     m_command_dict["quit"]      = CommandObjectSP (new CommandObjectQuit (*this));
257     m_command_dict["register"]  = CommandObjectSP (new CommandObjectRegister (*this));
258     m_command_dict["script"]    = CommandObjectSP (new CommandObjectScript (*this, script_language));
259     m_command_dict["settings"]  = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
260     m_command_dict["source"]    = CommandObjectSP (new CommandObjectMultiwordSource (*this));
261     m_command_dict["target"]    = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
262     m_command_dict["thread"]    = CommandObjectSP (new CommandObjectMultiwordThread (*this));
263     m_command_dict["version"]   = CommandObjectSP (new CommandObjectVersion (*this));
264 
265     std::auto_ptr<CommandObjectRegexCommand>
266     break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
267                                                       "_regexp-break",
268                                                       "Set a breakpoint using a regular expression to specify the location.",
269                                                       "_regexp-break [<filename>:<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
270     if (break_regex_cmd_ap.get())
271     {
272         if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
273             break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
274             break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
275             break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full") &&
276             break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
277             break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'") &&
278             break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
279         {
280             CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
281             m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
282         }
283     }
284 
285     std::auto_ptr<CommandObjectRegexCommand>
286     down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
287                                                      "_regexp-down",
288                                                      "Go down \"n\" frames in the stack (1 frame by default).",
289                                                      "_regexp-down [n]", 2));
290     if (down_regex_cmd_ap.get())
291     {
292         if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
293             down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
294         {
295             CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
296             m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
297         }
298     }
299 
300     std::auto_ptr<CommandObjectRegexCommand>
301     up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
302                                                    "_regexp-up",
303                                                    "Go up \"n\" frames in the stack (1 frame by default).",
304                                                    "_regexp-up [n]", 2));
305     if (up_regex_cmd_ap.get())
306     {
307         if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
308             up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
309         {
310             CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
311             m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
312         }
313     }
314 }
315 
316 int
317 CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
318                                                           StringList &matches)
319 {
320     CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
321 
322     if (include_aliases)
323     {
324         CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
325     }
326 
327     return matches.GetSize();
328 }
329 
330 CommandObjectSP
331 CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
332 {
333     CommandObject::CommandMap::iterator pos;
334     CommandObjectSP ret_val;
335 
336     std::string cmd(cmd_cstr);
337 
338     if (HasCommands())
339     {
340         pos = m_command_dict.find(cmd);
341         if (pos != m_command_dict.end())
342             ret_val = pos->second;
343     }
344 
345     if (include_aliases && HasAliases())
346     {
347         pos = m_alias_dict.find(cmd);
348         if (pos != m_alias_dict.end())
349             ret_val = pos->second;
350     }
351 
352     if (HasUserCommands())
353     {
354         pos = m_user_dict.find(cmd);
355         if (pos != m_user_dict.end())
356             ret_val = pos->second;
357     }
358 
359     if (!exact && ret_val == NULL)
360     {
361         // We will only get into here if we didn't find any exact matches.
362 
363         CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
364 
365         StringList local_matches;
366         if (matches == NULL)
367             matches = &local_matches;
368 
369         unsigned int num_cmd_matches = 0;
370         unsigned int num_alias_matches = 0;
371         unsigned int num_user_matches = 0;
372 
373         // Look through the command dictionaries one by one, and if we get only one match from any of
374         // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
375 
376         if (HasCommands())
377         {
378             num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
379         }
380 
381         if (num_cmd_matches == 1)
382         {
383             cmd.assign(matches->GetStringAtIndex(0));
384             pos = m_command_dict.find(cmd);
385             if (pos != m_command_dict.end())
386                 real_match_sp = pos->second;
387         }
388 
389         if (include_aliases && HasAliases())
390         {
391             num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
392 
393         }
394 
395         if (num_alias_matches == 1)
396         {
397             cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
398             pos = m_alias_dict.find(cmd);
399             if (pos != m_alias_dict.end())
400                 alias_match_sp = pos->second;
401         }
402 
403         if (HasUserCommands())
404         {
405             num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
406         }
407 
408         if (num_user_matches == 1)
409         {
410             cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
411 
412             pos = m_user_dict.find (cmd);
413             if (pos != m_user_dict.end())
414                 user_match_sp = pos->second;
415         }
416 
417         // If we got exactly one match, return that, otherwise return the match list.
418 
419         if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
420         {
421             if (num_cmd_matches)
422                 return real_match_sp;
423             else if (num_alias_matches)
424                 return alias_match_sp;
425             else
426                 return user_match_sp;
427         }
428     }
429     else if (matches && ret_val != NULL)
430     {
431         matches->AppendString (cmd_cstr);
432     }
433 
434 
435     return ret_val;
436 }
437 
438 bool
439 CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
440 {
441     if (name && name[0])
442     {
443         std::string name_sstr(name);
444         if (!can_replace)
445         {
446             if (m_command_dict.find (name_sstr) != m_command_dict.end())
447                 return false;
448         }
449         m_command_dict[name_sstr] = cmd_sp;
450         return true;
451     }
452     return false;
453 }
454 
455 
456 CommandObjectSP
457 CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
458 {
459     Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
460     CommandObjectSP ret_val;   // Possibly empty return value.
461 
462     if (cmd_cstr == NULL)
463         return ret_val;
464 
465     if (cmd_words.GetArgumentCount() == 1)
466         return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
467     else
468     {
469         // We have a multi-word command (seemingly), so we need to do more work.
470         // First, get the cmd_obj_sp for the first word in the command.
471         CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
472         if (cmd_obj_sp.get() != NULL)
473         {
474             // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
475             // command name), and find the appropriate sub-command SP for each command word....
476             size_t end = cmd_words.GetArgumentCount();
477             for (size_t j= 1; j < end; ++j)
478             {
479                 if (cmd_obj_sp->IsMultiwordObject())
480                 {
481                     cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
482                     (cmd_words.GetArgumentAtIndex (j));
483                     if (cmd_obj_sp.get() == NULL)
484                         // The sub-command name was invalid.  Fail and return the empty 'ret_val'.
485                         return ret_val;
486                 }
487                 else
488                     // We have more words in the command name, but we don't have a multiword object. Fail and return
489                     // empty 'ret_val'.
490                     return ret_val;
491             }
492             // We successfully looped through all the command words and got valid command objects for them.  Assign the
493             // last object retrieved to 'ret_val'.
494             ret_val = cmd_obj_sp;
495         }
496     }
497     return ret_val;
498 }
499 
500 CommandObject *
501 CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
502 {
503     return GetCommandSPExact (cmd_cstr, include_aliases).get();
504 }
505 
506 CommandObject *
507 CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
508 {
509     CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
510 
511     // If we didn't find an exact match to the command string in the commands, look in
512     // the aliases.
513 
514     if (command_obj == NULL)
515     {
516         command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
517     }
518 
519     // Finally, if there wasn't an exact match among the aliases, look for an inexact match
520     // in both the commands and the aliases.
521 
522     if (command_obj == NULL)
523         command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
524 
525     return command_obj;
526 }
527 
528 bool
529 CommandInterpreter::CommandExists (const char *cmd)
530 {
531     return m_command_dict.find(cmd) != m_command_dict.end();
532 }
533 
534 bool
535 CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
536                                             const char *options_args,
537                                             OptionArgVectorSP &option_arg_vector_sp)
538 {
539     bool success = true;
540     OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
541 
542     if (!options_args || (strlen (options_args) < 1))
543         return true;
544 
545     std::string options_string (options_args);
546     Args args (options_args);
547     CommandReturnObject result;
548     // Check to see if the command being aliased can take any command options.
549     Options *options = cmd_obj_sp->GetOptions ();
550     if (options)
551     {
552         // See if any options were specified as part of the alias;  if so, handle them appropriately.
553         options->NotifyOptionParsingStarting ();
554         args.Unshift ("dummy_arg");
555         args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
556         args.Shift ();
557         if (result.Succeeded())
558             options->VerifyPartialOptions (result);
559         if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
560         {
561             result.AppendError ("Unable to create requested alias.\n");
562             return false;
563         }
564     }
565 
566     if (options_string.size() > 0)
567     {
568         if (cmd_obj_sp->WantsRawCommandString ())
569             option_arg_vector->push_back (OptionArgPair ("<argument>",
570                                                           OptionArgValue (-1,
571                                                                           options_string)));
572         else
573         {
574             int argc = args.GetArgumentCount();
575             for (size_t i = 0; i < argc; ++i)
576                 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
577                     option_arg_vector->push_back
578                                 (OptionArgPair ("<argument>",
579                                                 OptionArgValue (-1,
580                                                                 std::string (args.GetArgumentAtIndex (i)))));
581         }
582     }
583 
584     return success;
585 }
586 
587 bool
588 CommandInterpreter::AliasExists (const char *cmd)
589 {
590     return m_alias_dict.find(cmd) != m_alias_dict.end();
591 }
592 
593 bool
594 CommandInterpreter::UserCommandExists (const char *cmd)
595 {
596     return m_user_dict.find(cmd) != m_user_dict.end();
597 }
598 
599 void
600 CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
601 {
602     command_obj_sp->SetIsAlias (true);
603     m_alias_dict[alias_name] = command_obj_sp;
604 }
605 
606 bool
607 CommandInterpreter::RemoveAlias (const char *alias_name)
608 {
609     CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
610     if (pos != m_alias_dict.end())
611     {
612         m_alias_dict.erase(pos);
613         return true;
614     }
615     return false;
616 }
617 bool
618 CommandInterpreter::RemoveUser (const char *alias_name)
619 {
620     CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
621     if (pos != m_user_dict.end())
622     {
623         m_user_dict.erase(pos);
624         return true;
625     }
626     return false;
627 }
628 
629 void
630 CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
631 {
632     help_string.Printf ("'%s", command_name);
633     OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
634 
635     if (option_arg_vector_sp != NULL)
636     {
637         OptionArgVector *options = option_arg_vector_sp.get();
638         for (int i = 0; i < options->size(); ++i)
639         {
640             OptionArgPair cur_option = (*options)[i];
641             std::string opt = cur_option.first;
642             OptionArgValue value_pair = cur_option.second;
643             std::string value = value_pair.second;
644             if (opt.compare("<argument>") == 0)
645             {
646                 help_string.Printf (" %s", value.c_str());
647             }
648             else
649             {
650                 help_string.Printf (" %s", opt.c_str());
651                 if ((value.compare ("<no-argument>") != 0)
652                     && (value.compare ("<need-argument") != 0))
653                 {
654                     help_string.Printf (" %s", value.c_str());
655                 }
656             }
657         }
658     }
659 
660     help_string.Printf ("'");
661 }
662 
663 size_t
664 CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
665 {
666     CommandObject::CommandMap::const_iterator pos;
667     CommandObject::CommandMap::const_iterator end = dict.end();
668     size_t max_len = 0;
669 
670     for (pos = dict.begin(); pos != end; ++pos)
671     {
672         size_t len = pos->first.size();
673         if (max_len < len)
674             max_len = len;
675     }
676     return max_len;
677 }
678 
679 void
680 CommandInterpreter::GetHelp (CommandReturnObject &result)
681 {
682     CommandObject::CommandMap::const_iterator pos;
683     result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
684     result.AppendMessage("");
685     uint32_t max_len = FindLongestCommandWord (m_command_dict);
686 
687     for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
688     {
689         OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
690                                  max_len);
691     }
692     result.AppendMessage("");
693 
694     if (m_alias_dict.size() > 0)
695     {
696         result.AppendMessage("The following is a list of your current command abbreviations "
697                              "(see 'help command alias' for more info):");
698         result.AppendMessage("");
699         max_len = FindLongestCommandWord (m_alias_dict);
700 
701         for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
702         {
703             StreamString sstr;
704             StreamString translation_and_help;
705             std::string entry_name = pos->first;
706             std::string second_entry = pos->second.get()->GetCommandName();
707             GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
708 
709             translation_and_help.Printf ("(%s)  %s", sstr.GetData(), pos->second->GetHelp());
710             OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
711                                      translation_and_help.GetData(), max_len);
712         }
713         result.AppendMessage("");
714     }
715 
716     if (m_user_dict.size() > 0)
717     {
718         result.AppendMessage ("The following is a list of your current user-defined commands:");
719         result.AppendMessage("");
720         for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
721         {
722             result.AppendMessageWithFormat ("%s  --  %s\n", pos->first.c_str(), pos->second->GetHelp());
723         }
724         result.AppendMessage("");
725     }
726 
727     result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
728 }
729 
730 CommandObject *
731 CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
732 {
733     // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
734     // eventually be invoked by the given command line.
735 
736     CommandObject *cmd_obj = NULL;
737     std::string white_space (" \t\v");
738     size_t start = command_string.find_first_not_of (white_space);
739     size_t end = 0;
740     bool done = false;
741     while (!done)
742     {
743         if (start != std::string::npos)
744         {
745             // Get the next word from command_string.
746             end = command_string.find_first_of (white_space, start);
747             if (end == std::string::npos)
748                 end = command_string.size();
749             std::string cmd_word = command_string.substr (start, end - start);
750 
751             if (cmd_obj == NULL)
752                 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
753                 // command or alias.
754                 cmd_obj = GetCommandObject (cmd_word.c_str());
755             else if (cmd_obj->IsMultiwordObject ())
756             {
757                 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
758                 CommandObject *sub_cmd_obj =
759                                          ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
760                 if (sub_cmd_obj)
761                     cmd_obj = sub_cmd_obj;
762                 else // cmd_word was not a valid sub-command word, so we are donee
763                     done = true;
764             }
765             else
766                 // We have a cmd_obj and it is not a multi-word object, so we are done.
767                 done = true;
768 
769             // If we didn't find a valid command object, or our command object is not a multi-word object, or
770             // we are at the end of the command_string, then we are done.  Otherwise, find the start of the
771             // next word.
772 
773             if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
774                 done = true;
775             else
776                 start = command_string.find_first_not_of (white_space, end);
777         }
778         else
779             // Unable to find any more words.
780             done = true;
781     }
782 
783     if (end == command_string.size())
784         command_string.clear();
785     else
786         command_string = command_string.substr(end);
787 
788     return cmd_obj;
789 }
790 
791 bool
792 CommandInterpreter::StripFirstWord (std::string &command_string, std::string &word, bool &was_quoted, char &quote_char)
793 {
794     std::string white_space (" \t\v");
795     size_t start;
796     size_t end;
797 
798     start = command_string.find_first_not_of (white_space);
799     if (start != std::string::npos)
800     {
801         size_t len = command_string.size() - start;
802         if (len >= 2
803                 && ((command_string[start] == '\'') || (command_string[start] == '"')))
804         {
805             was_quoted = true;
806             quote_char = command_string[start];
807             std::string quote_string = command_string.substr (start, 1);
808             start = start + 1;
809             end = command_string.find (quote_string, start);
810             if (end != std::string::npos)
811             {
812                 word = command_string.substr (start, end - start);
813                 if (end + 1 < len)
814                     command_string = command_string.substr (end+1);
815                 else
816                     command_string.erase ();
817                 size_t pos = command_string.find_first_not_of (white_space);
818                 if ((pos != 0) && (pos != std::string::npos))
819                     command_string = command_string.substr (pos);
820             }
821             else
822             {
823                 word = command_string.substr (start - 1);
824                 command_string.erase ();
825             }
826         }
827         else
828         {
829             end = command_string.find_first_of (white_space, start);
830             if (end != std::string::npos)
831             {
832                 word = command_string.substr (start, end - start);
833                 command_string = command_string.substr (end);
834                 size_t pos = command_string.find_first_not_of (white_space);
835                 if ((pos != 0) && (pos != std::string::npos))
836                     command_string = command_string.substr (pos);
837             }
838             else
839             {
840                 word = command_string.substr (start);
841                 command_string.erase();
842             }
843         }
844 
845     }
846     return true;
847 }
848 
849 void
850 CommandInterpreter::BuildAliasResult (const char *alias_name, std::string &raw_input_string, std::string &alias_result,
851                                       CommandObject *&alias_cmd_obj, CommandReturnObject &result)
852 {
853     Args cmd_args (raw_input_string.c_str());
854     alias_cmd_obj = GetCommandObject (alias_name);
855     StreamString result_str;
856 
857     if (alias_cmd_obj)
858     {
859         std::string alias_name_str = alias_name;
860         if ((cmd_args.GetArgumentCount() == 0)
861             || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
862             cmd_args.Unshift (alias_name);
863 
864         result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
865         OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
866 
867         if (option_arg_vector_sp.get())
868         {
869             OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
870 
871             for (int i = 0; i < option_arg_vector->size(); ++i)
872             {
873                 OptionArgPair option_pair = (*option_arg_vector)[i];
874                 OptionArgValue value_pair = option_pair.second;
875                 int value_type = value_pair.first;
876                 std::string option = option_pair.first;
877                 std::string value = value_pair.second;
878                 if (option.compare ("<argument>") == 0)
879                     result_str.Printf (" %s", value.c_str());
880                 else
881                 {
882                     result_str.Printf (" %s", option.c_str());
883                     if (value_type != optional_argument)
884                         result_str.Printf (" ");
885                     if (value.compare ("<no_argument>") != 0)
886                     {
887                         int index = GetOptionArgumentPosition (value.c_str());
888                         if (index == 0)
889                             result_str.Printf ("%s", value.c_str());
890                         else if (index >= cmd_args.GetArgumentCount())
891                         {
892 
893                             result.AppendErrorWithFormat
894                             ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
895                              index);
896                             result.SetStatus (eReturnStatusFailed);
897                             return;
898                         }
899                         else
900                         {
901                             size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
902                             if (strpos != std::string::npos)
903                                 raw_input_string = raw_input_string.erase (strpos,
904                                                                           strlen (cmd_args.GetArgumentAtIndex (index)));
905                             result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
906                         }
907                     }
908                 }
909             }
910         }
911 
912         alias_result = result_str.GetData();
913     }
914 }
915 
916 bool
917 CommandInterpreter::HandleCommand (const char *command_line,
918                                    bool add_to_history,
919                                    CommandReturnObject &result,
920                                    ExecutionContext *override_context,
921                                    bool repeat_on_empty_command)
922 
923 {
924 
925     bool done = false;
926     CommandObject *cmd_obj = NULL;
927     std::string next_word;
928     bool wants_raw_input = false;
929     std::string command_string (command_line);
930 
931     LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
932     Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
933 
934     // Make a scoped cleanup object that will clear the crash description string
935     // on exit of this function.
936     lldb_utility::CleanUp <const char *, void> crash_description_cleanup(NULL, Host::SetCrashDescription);
937 
938     if (log)
939         log->Printf ("Processing command: %s", command_line);
940 
941     Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
942 
943     UpdateExecutionContext (override_context);
944 
945     bool empty_command = false;
946     bool comment_command = false;
947     if (command_string.empty())
948         empty_command = true;
949     else
950     {
951         const char *k_space_characters = "\t\n\v\f\r ";
952 
953         size_t non_space = command_string.find_first_not_of (k_space_characters);
954         // Check for empty line or comment line (lines whose first
955         // non-space character is the comment character for this interpreter)
956         if (non_space == std::string::npos)
957             empty_command = true;
958         else if (command_string[non_space] == m_comment_char)
959              comment_command = true;
960     }
961 
962     if (empty_command)
963     {
964         if (repeat_on_empty_command)
965         {
966             if (m_command_history.empty())
967             {
968                 result.AppendError ("empty command");
969                 result.SetStatus(eReturnStatusFailed);
970                 return false;
971             }
972             else
973             {
974                 command_line = m_repeat_command.c_str();
975                 command_string = command_line;
976                 if (m_repeat_command.empty())
977                 {
978                     result.AppendErrorWithFormat("No auto repeat.\n");
979                     result.SetStatus (eReturnStatusFailed);
980                     return false;
981                 }
982             }
983             add_to_history = false;
984         }
985         else
986         {
987             result.SetStatus (eReturnStatusSuccessFinishNoResult);
988             return true;
989         }
990     }
991     else if (comment_command)
992     {
993         result.SetStatus (eReturnStatusSuccessFinishNoResult);
994         return true;
995     }
996 
997     // Phase 1.
998 
999     // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1000     // is for the specified command, and whether or not it wants raw input.  This gets complicated by the fact that
1001     // the user could have specified an alias, and in translating the alias there may also be command options and/or
1002     // even data (including raw text strings) that need to be found and inserted into the command line as part of
1003     // the translation.  So this first step is plain look-up & replacement, resulting in three things:  1). the command
1004     // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
1005     // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
1006 
1007     StreamString revised_command_line;
1008     size_t actual_cmd_name_len = 0;
1009     while (!done)
1010     {
1011         bool was_quoted = false;
1012         char quote_char = '\0';
1013         StripFirstWord (command_string, next_word, was_quoted, quote_char);
1014         if (!cmd_obj && AliasExists (next_word.c_str()))
1015         {
1016             std::string alias_result;
1017             BuildAliasResult (next_word.c_str(), command_string, alias_result, cmd_obj, result);
1018             revised_command_line.Printf ("%s", alias_result.c_str());
1019             if (cmd_obj)
1020             {
1021                 wants_raw_input = cmd_obj->WantsRawCommandString ();
1022                 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1023             }
1024         }
1025         else if (!cmd_obj)
1026         {
1027             cmd_obj = GetCommandObject (next_word.c_str());
1028             if (cmd_obj)
1029             {
1030                 actual_cmd_name_len += next_word.length();
1031                 revised_command_line.Printf ("%s", next_word.c_str());
1032                 wants_raw_input = cmd_obj->WantsRawCommandString ();
1033             }
1034             else
1035             {
1036                 revised_command_line.Printf ("%s", next_word.c_str());
1037             }
1038         }
1039         else if (cmd_obj->IsMultiwordObject ())
1040         {
1041             CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
1042             if (sub_cmd_obj)
1043             {
1044                 actual_cmd_name_len += next_word.length() + 1;
1045                 revised_command_line.Printf (" %s", next_word.c_str());
1046                 cmd_obj = sub_cmd_obj;
1047                 wants_raw_input = cmd_obj->WantsRawCommandString ();
1048             }
1049             else
1050             {
1051                 if (was_quoted)
1052                 {
1053                     if (quote_char == '"')
1054                         revised_command_line.Printf (" \"%s\"", next_word.c_str());
1055                     else
1056                         revised_command_line.Printf (" '%s'", next_word.c_str());
1057                 }
1058                 else
1059                     revised_command_line.Printf (" %s", next_word.c_str());
1060                 done = true;
1061             }
1062         }
1063         else
1064         {
1065             if (was_quoted)
1066             {
1067                 if (quote_char == '"')
1068                     revised_command_line.Printf (" \"%s\"", next_word.c_str());
1069                 else
1070                     revised_command_line.Printf (" '%s'", next_word.c_str());
1071             }
1072             else
1073                 revised_command_line.Printf (" %s", next_word.c_str());
1074             done = true;
1075         }
1076 
1077         if (cmd_obj == NULL)
1078         {
1079             result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1080             result.SetStatus (eReturnStatusFailed);
1081             return false;
1082         }
1083 
1084         next_word.erase ();
1085         if (command_string.length() == 0)
1086             done = true;
1087 
1088     }
1089 
1090     if (command_string.size() > 0)
1091         revised_command_line.Printf (" %s", command_string.c_str());
1092 
1093     // End of Phase 1.
1094     // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1095     // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1096     // fully translated with all substitutions & translations taken care of (still in raw text format); and
1097     // wants_raw_input specifies whether the Execute method expects raw input or not.
1098 
1099 
1100     if (log)
1101     {
1102         log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1103         log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1104         log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1105     }
1106 
1107     // Phase 2.
1108     // Take care of things like setting up the history command & calling the appropriate Execute method on the
1109     // CommandObject, with the appropriate arguments.
1110 
1111     if (cmd_obj != NULL)
1112     {
1113         if (add_to_history)
1114         {
1115             Args command_args (revised_command_line.GetData());
1116             const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1117             if (repeat_command != NULL)
1118                 m_repeat_command.assign(repeat_command);
1119             else
1120                 m_repeat_command.assign(command_line);
1121 
1122             m_command_history.push_back (command_line);
1123         }
1124 
1125         command_string = revised_command_line.GetData();
1126         std::string command_name (cmd_obj->GetCommandName());
1127         std::string remainder;
1128         if (actual_cmd_name_len < command_string.length())
1129             remainder = command_string.substr (actual_cmd_name_len);  // Note: 'actual_cmd_name_len' may be considerably shorter
1130                                                            // than cmd_obj->GetCommandName(), because name completion
1131                                                            // allows users to enter short versions of the names,
1132                                                            // e.g. 'br s' for 'breakpoint set'.
1133 
1134         // Remove any initial spaces
1135         std::string white_space (" \t\v");
1136         size_t pos = remainder.find_first_not_of (white_space);
1137         if (pos != 0 && pos != std::string::npos)
1138             remainder.erase(0, pos);
1139 
1140         if (log)
1141             log->Printf ("HandleCommand, command line after removing command name(s): '%s'\n", remainder.c_str());
1142 
1143 
1144         if (wants_raw_input)
1145             cmd_obj->ExecuteRawCommandString (remainder.c_str(), result);
1146         else
1147         {
1148             Args cmd_args (remainder.c_str());
1149             cmd_obj->ExecuteWithOptions (cmd_args, result);
1150         }
1151     }
1152     else
1153     {
1154         // We didn't find the first command object, so complete the first argument.
1155         Args command_args (revised_command_line.GetData());
1156         StringList matches;
1157         int num_matches;
1158         int cursor_index = 0;
1159         int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1160         bool word_complete;
1161         num_matches = HandleCompletionMatches (command_args,
1162                                                cursor_index,
1163                                                cursor_char_position,
1164                                                0,
1165                                                -1,
1166                                                word_complete,
1167                                                matches);
1168 
1169         if (num_matches > 0)
1170         {
1171             std::string error_msg;
1172             error_msg.assign ("ambiguous command '");
1173             error_msg.append(command_args.GetArgumentAtIndex(0));
1174             error_msg.append ("'.");
1175 
1176             error_msg.append (" Possible completions:");
1177             for (int i = 0; i < num_matches; i++)
1178             {
1179                 error_msg.append ("\n\t");
1180                 error_msg.append (matches.GetStringAtIndex (i));
1181             }
1182             error_msg.append ("\n");
1183             result.AppendRawError (error_msg.c_str(), error_msg.size());
1184         }
1185         else
1186             result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1187 
1188         result.SetStatus (eReturnStatusFailed);
1189     }
1190 
1191     return result.Succeeded();
1192 }
1193 
1194 int
1195 CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1196                                              int &cursor_index,
1197                                              int &cursor_char_position,
1198                                              int match_start_point,
1199                                              int max_return_elements,
1200                                              bool &word_complete,
1201                                              StringList &matches)
1202 {
1203     int num_command_matches = 0;
1204     bool look_for_subcommand = false;
1205 
1206     // For any of the command completions a unique match will be a complete word.
1207     word_complete = true;
1208 
1209     if (cursor_index == -1)
1210     {
1211         // We got nothing on the command line, so return the list of commands
1212         bool include_aliases = true;
1213         num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1214     }
1215     else if (cursor_index == 0)
1216     {
1217         // The cursor is in the first argument, so just do a lookup in the dictionary.
1218         CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
1219         num_command_matches = matches.GetSize();
1220 
1221         if (num_command_matches == 1
1222             && cmd_obj && cmd_obj->IsMultiwordObject()
1223             && matches.GetStringAtIndex(0) != NULL
1224             && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1225         {
1226             look_for_subcommand = true;
1227             num_command_matches = 0;
1228             matches.DeleteStringAtIndex(0);
1229             parsed_line.AppendArgument ("");
1230             cursor_index++;
1231             cursor_char_position = 0;
1232         }
1233     }
1234 
1235     if (cursor_index > 0 || look_for_subcommand)
1236     {
1237         // We are completing further on into a commands arguments, so find the command and tell it
1238         // to complete the command.
1239         // First see if there is a matching initial command:
1240         CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
1241         if (command_object == NULL)
1242         {
1243             return 0;
1244         }
1245         else
1246         {
1247             parsed_line.Shift();
1248             cursor_index--;
1249             num_command_matches = command_object->HandleCompletion (parsed_line,
1250                                                                     cursor_index,
1251                                                                     cursor_char_position,
1252                                                                     match_start_point,
1253                                                                     max_return_elements,
1254                                                                     word_complete,
1255                                                                     matches);
1256         }
1257     }
1258 
1259     return num_command_matches;
1260 
1261 }
1262 
1263 int
1264 CommandInterpreter::HandleCompletion (const char *current_line,
1265                                       const char *cursor,
1266                                       const char *last_char,
1267                                       int match_start_point,
1268                                       int max_return_elements,
1269                                       StringList &matches)
1270 {
1271     // We parse the argument up to the cursor, so the last argument in parsed_line is
1272     // the one containing the cursor, and the cursor is after the last character.
1273 
1274     Args parsed_line(current_line, last_char - current_line);
1275     Args partial_parsed_line(current_line, cursor - current_line);
1276 
1277     int num_args = partial_parsed_line.GetArgumentCount();
1278     int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1279     int cursor_char_position;
1280 
1281     if (cursor_index == -1)
1282         cursor_char_position = 0;
1283     else
1284         cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
1285 
1286     if (cursor > current_line && cursor[-1] == ' ')
1287     {
1288         // We are just after a space.  If we are in an argument, then we will continue
1289         // parsing, but if we are between arguments, then we have to complete whatever the next
1290         // element would be.
1291         // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1292         // protected by a quote) then the space will also be in the parsed argument...
1293 
1294         const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1295         if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1296         {
1297             parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1298             cursor_index++;
1299             cursor_char_position = 0;
1300         }
1301     }
1302 
1303     int num_command_matches;
1304 
1305     matches.Clear();
1306 
1307     // Only max_return_elements == -1 is supported at present:
1308     assert (max_return_elements == -1);
1309     bool word_complete;
1310     num_command_matches = HandleCompletionMatches (parsed_line,
1311                                                    cursor_index,
1312                                                    cursor_char_position,
1313                                                    match_start_point,
1314                                                    max_return_elements,
1315                                                    word_complete,
1316                                                    matches);
1317 
1318     if (num_command_matches <= 0)
1319             return num_command_matches;
1320 
1321     if (num_args == 0)
1322     {
1323         // If we got an empty string, insert nothing.
1324         matches.InsertStringAtIndex(0, "");
1325     }
1326     else
1327     {
1328         // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1329         // put an empty string in element 0.
1330         std::string command_partial_str;
1331         if (cursor_index >= 0)
1332             command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1333                                        parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
1334 
1335         std::string common_prefix;
1336         matches.LongestCommonPrefix (common_prefix);
1337         int partial_name_len = command_partial_str.size();
1338 
1339         // If we matched a unique single command, add a space...
1340         // Only do this if the completer told us this was a complete word, however...
1341         if (num_command_matches == 1 && word_complete)
1342         {
1343             char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1344             if (quote_char != '\0')
1345                 common_prefix.push_back(quote_char);
1346 
1347             common_prefix.push_back(' ');
1348         }
1349         common_prefix.erase (0, partial_name_len);
1350         matches.InsertStringAtIndex(0, common_prefix.c_str());
1351     }
1352     return num_command_matches;
1353 }
1354 
1355 
1356 CommandInterpreter::~CommandInterpreter ()
1357 {
1358 }
1359 
1360 const char *
1361 CommandInterpreter::GetPrompt ()
1362 {
1363     return m_debugger.GetPrompt();
1364 }
1365 
1366 void
1367 CommandInterpreter::SetPrompt (const char *new_prompt)
1368 {
1369     m_debugger.SetPrompt (new_prompt);
1370 }
1371 
1372 size_t
1373 CommandInterpreter::GetConfirmationInputReaderCallback
1374 (
1375     void *baton,
1376     InputReader &reader,
1377     lldb::InputReaderAction action,
1378     const char *bytes,
1379     size_t bytes_len
1380 )
1381 {
1382     File &out_file = reader.GetDebugger().GetOutputFile();
1383     bool *response_ptr = (bool *) baton;
1384 
1385     switch (action)
1386     {
1387     case eInputReaderActivate:
1388         if (out_file.IsValid())
1389         {
1390             if (reader.GetPrompt())
1391             {
1392                 out_file.Printf ("%s", reader.GetPrompt());
1393                 out_file.Flush ();
1394             }
1395         }
1396         break;
1397 
1398     case eInputReaderDeactivate:
1399         break;
1400 
1401     case eInputReaderReactivate:
1402         if (out_file.IsValid() && reader.GetPrompt())
1403         {
1404             out_file.Printf ("%s", reader.GetPrompt());
1405             out_file.Flush ();
1406         }
1407         break;
1408 
1409     case eInputReaderAsynchronousOutputWritten:
1410         break;
1411 
1412     case eInputReaderGotToken:
1413         if (bytes_len == 0)
1414         {
1415             reader.SetIsDone(true);
1416         }
1417         else if (bytes[0] == 'y')
1418         {
1419             *response_ptr = true;
1420             reader.SetIsDone(true);
1421         }
1422         else if (bytes[0] == 'n')
1423         {
1424             *response_ptr = false;
1425             reader.SetIsDone(true);
1426         }
1427         else
1428         {
1429             if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
1430             {
1431                 out_file.Printf ("Please answer \"y\" or \"n\"\n%s", reader.GetPrompt());
1432                 out_file.Flush ();
1433             }
1434         }
1435         break;
1436 
1437     case eInputReaderInterrupt:
1438     case eInputReaderEndOfFile:
1439         *response_ptr = false;  // Assume ^C or ^D means cancel the proposed action
1440         reader.SetIsDone (true);
1441         break;
1442 
1443     case eInputReaderDone:
1444         break;
1445     }
1446 
1447     return bytes_len;
1448 
1449 }
1450 
1451 bool
1452 CommandInterpreter::Confirm (const char *message, bool default_answer)
1453 {
1454     // Check AutoConfirm first:
1455     if (m_debugger.GetAutoConfirm())
1456         return default_answer;
1457 
1458     InputReaderSP reader_sp (new InputReader(GetDebugger()));
1459     bool response = default_answer;
1460     if (reader_sp)
1461     {
1462         std::string prompt(message);
1463         prompt.append(": [");
1464         if (default_answer)
1465             prompt.append ("Y/n] ");
1466         else
1467             prompt.append ("y/N] ");
1468 
1469         Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1470                                           &response,                    // baton
1471                                           eInputReaderGranularityLine,  // token size, to pass to callback function
1472                                           NULL,                         // end token
1473                                           prompt.c_str(),               // prompt
1474                                           true));                       // echo input
1475         if (err.Success())
1476         {
1477             GetDebugger().PushInputReader (reader_sp);
1478         }
1479         reader_sp->WaitOnReaderIsDone();
1480     }
1481     return response;
1482 }
1483 
1484 
1485 void
1486 CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1487 {
1488     CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
1489 
1490     if (cmd_obj_sp != NULL)
1491     {
1492         CommandObject *cmd_obj = cmd_obj_sp.get();
1493         if (cmd_obj->IsCrossRefObject ())
1494             cmd_obj->AddObject (object_type);
1495     }
1496 }
1497 
1498 OptionArgVectorSP
1499 CommandInterpreter::GetAliasOptions (const char *alias_name)
1500 {
1501     OptionArgMap::iterator pos;
1502     OptionArgVectorSP ret_val;
1503 
1504     std::string alias (alias_name);
1505 
1506     if (HasAliasOptions())
1507     {
1508         pos = m_alias_options.find (alias);
1509         if (pos != m_alias_options.end())
1510           ret_val = pos->second;
1511     }
1512 
1513     return ret_val;
1514 }
1515 
1516 void
1517 CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1518 {
1519     OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1520     if (pos != m_alias_options.end())
1521     {
1522         m_alias_options.erase (pos);
1523     }
1524 }
1525 
1526 void
1527 CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1528 {
1529     m_alias_options[alias_name] = option_arg_vector_sp;
1530 }
1531 
1532 bool
1533 CommandInterpreter::HasCommands ()
1534 {
1535     return (!m_command_dict.empty());
1536 }
1537 
1538 bool
1539 CommandInterpreter::HasAliases ()
1540 {
1541     return (!m_alias_dict.empty());
1542 }
1543 
1544 bool
1545 CommandInterpreter::HasUserCommands ()
1546 {
1547     return (!m_user_dict.empty());
1548 }
1549 
1550 bool
1551 CommandInterpreter::HasAliasOptions ()
1552 {
1553     return (!m_alias_options.empty());
1554 }
1555 
1556 void
1557 CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
1558                                            const char *alias_name,
1559                                            Args &cmd_args,
1560                                            std::string &raw_input_string,
1561                                            CommandReturnObject &result)
1562 {
1563     OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1564 
1565     bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
1566 
1567     // Make sure that the alias name is the 0th element in cmd_args
1568     std::string alias_name_str = alias_name;
1569     if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1570         cmd_args.Unshift (alias_name);
1571 
1572     Args new_args (alias_cmd_obj->GetCommandName());
1573     if (new_args.GetArgumentCount() == 2)
1574         new_args.Shift();
1575 
1576     if (option_arg_vector_sp.get())
1577     {
1578         if (wants_raw_input)
1579         {
1580             // We have a command that both has command options and takes raw input.  Make *sure* it has a
1581             // " -- " in the right place in the raw_input_string.
1582             size_t pos = raw_input_string.find(" -- ");
1583             if (pos == std::string::npos)
1584             {
1585                 // None found; assume it goes at the beginning of the raw input string
1586                 raw_input_string.insert (0, " -- ");
1587             }
1588         }
1589 
1590         OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1591         int old_size = cmd_args.GetArgumentCount();
1592         std::vector<bool> used (old_size + 1, false);
1593 
1594         used[0] = true;
1595 
1596         for (int i = 0; i < option_arg_vector->size(); ++i)
1597         {
1598             OptionArgPair option_pair = (*option_arg_vector)[i];
1599             OptionArgValue value_pair = option_pair.second;
1600             int value_type = value_pair.first;
1601             std::string option = option_pair.first;
1602             std::string value = value_pair.second;
1603             if (option.compare ("<argument>") == 0)
1604             {
1605                 if (!wants_raw_input
1606                     || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
1607                     new_args.AppendArgument (value.c_str());
1608             }
1609             else
1610             {
1611                 if (value_type != optional_argument)
1612                     new_args.AppendArgument (option.c_str());
1613                 if (value.compare ("<no-argument>") != 0)
1614                 {
1615                     int index = GetOptionArgumentPosition (value.c_str());
1616                     if (index == 0)
1617                     {
1618                         // value was NOT a positional argument; must be a real value
1619                         if (value_type != optional_argument)
1620                             new_args.AppendArgument (value.c_str());
1621                         else
1622                         {
1623                             char buffer[255];
1624                             ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
1625                             new_args.AppendArgument (buffer);
1626                         }
1627 
1628                     }
1629                     else if (index >= cmd_args.GetArgumentCount())
1630                     {
1631                         result.AppendErrorWithFormat
1632                                     ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1633                                      index);
1634                         result.SetStatus (eReturnStatusFailed);
1635                         return;
1636                     }
1637                     else
1638                     {
1639                         // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
1640                         size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1641                         if (strpos != std::string::npos)
1642                         {
1643                             raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
1644                         }
1645 
1646                         if (value_type != optional_argument)
1647                             new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
1648                         else
1649                         {
1650                             char buffer[255];
1651                             ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
1652                                         cmd_args.GetArgumentAtIndex (index));
1653                             new_args.AppendArgument (buffer);
1654                         }
1655                         used[index] = true;
1656                     }
1657                 }
1658             }
1659         }
1660 
1661         for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1662         {
1663             if (!used[j] && !wants_raw_input)
1664                 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1665         }
1666 
1667         cmd_args.Clear();
1668         cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1669     }
1670     else
1671     {
1672         result.SetStatus (eReturnStatusSuccessFinishNoResult);
1673         // This alias was not created with any options; nothing further needs to be done, unless it is a command that
1674         // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
1675         // input string.
1676         if (wants_raw_input)
1677         {
1678             cmd_args.Clear();
1679             cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1680         }
1681         return;
1682     }
1683 
1684     result.SetStatus (eReturnStatusSuccessFinishNoResult);
1685     return;
1686 }
1687 
1688 
1689 int
1690 CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1691 {
1692     int position = 0;   // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1693                         // of zero.
1694 
1695     char *cptr = (char *) in_string;
1696 
1697     // Does it start with '%'
1698     if (cptr[0] == '%')
1699     {
1700         ++cptr;
1701 
1702         // Is the rest of it entirely digits?
1703         if (isdigit (cptr[0]))
1704         {
1705             const char *start = cptr;
1706             while (isdigit (cptr[0]))
1707                 ++cptr;
1708 
1709             // We've gotten to the end of the digits; are we at the end of the string?
1710             if (cptr[0] == '\0')
1711                 position = atoi (start);
1712         }
1713     }
1714 
1715     return position;
1716 }
1717 
1718 void
1719 CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1720 {
1721     // Don't parse any .lldbinit files if we were asked not to
1722     if (m_skip_lldbinit_files)
1723         return;
1724 
1725     const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit";
1726     FileSpec init_file (init_file_path, true);
1727     // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
1728     // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
1729 
1730     if (init_file.Exists())
1731     {
1732         ExecutionContext *exe_ctx = NULL;  // We don't have any context yet.
1733         bool stop_on_continue = true;
1734         bool stop_on_error    = false;
1735         bool echo_commands    = false;
1736         bool print_results    = false;
1737 
1738         HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, result);
1739     }
1740     else
1741     {
1742         // nothing to be done if the file doesn't exist
1743         result.SetStatus(eReturnStatusSuccessFinishNoResult);
1744     }
1745 }
1746 
1747 PlatformSP
1748 CommandInterpreter::GetPlatform (bool prefer_target_platform)
1749 {
1750     PlatformSP platform_sp;
1751     if (prefer_target_platform && m_exe_ctx.target)
1752         platform_sp = m_exe_ctx.target->GetPlatform();
1753 
1754     if (!platform_sp)
1755         platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
1756     return platform_sp;
1757 }
1758 
1759 void
1760 CommandInterpreter::HandleCommands (const StringList &commands,
1761                                     ExecutionContext *override_context,
1762                                     bool stop_on_continue,
1763                                     bool stop_on_error,
1764                                     bool echo_commands,
1765                                     bool print_results,
1766                                     CommandReturnObject &result)
1767 {
1768     size_t num_lines = commands.GetSize();
1769 
1770     // If we are going to continue past a "continue" then we need to run the commands synchronously.
1771     // Make sure you reset this value anywhere you return from the function.
1772 
1773     bool old_async_execution = m_debugger.GetAsyncExecution();
1774 
1775     // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
1776     // cause series of commands that change the context, then do an operation that relies on that context to fail.
1777 
1778     if (override_context != NULL)
1779         UpdateExecutionContext (override_context);
1780 
1781     if (!stop_on_continue)
1782     {
1783         m_debugger.SetAsyncExecution (false);
1784     }
1785 
1786     for (int idx = 0; idx < num_lines; idx++)
1787     {
1788         const char *cmd = commands.GetStringAtIndex(idx);
1789         if (cmd[0] == '\0')
1790             continue;
1791 
1792         if (echo_commands)
1793         {
1794             result.AppendMessageWithFormat ("%s %s\n",
1795                                              GetPrompt(),
1796                                              cmd);
1797         }
1798 
1799         CommandReturnObject tmp_result;
1800         bool success = HandleCommand(cmd, false, tmp_result, NULL);
1801 
1802         if (print_results)
1803         {
1804             if (tmp_result.Succeeded())
1805               result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
1806         }
1807 
1808         if (!success || !tmp_result.Succeeded())
1809         {
1810             if (stop_on_error)
1811             {
1812                 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed.\n",
1813                                          idx, cmd);
1814                 result.SetStatus (eReturnStatusFailed);
1815                 m_debugger.SetAsyncExecution (old_async_execution);
1816                 return;
1817             }
1818             else if (print_results)
1819             {
1820                 result.AppendMessageWithFormat ("Command #%d '%s' failed with error: %s.\n",
1821                                                 idx + 1,
1822                                                 cmd,
1823                                                 tmp_result.GetErrorData());
1824             }
1825         }
1826 
1827         if (result.GetImmediateOutputStream())
1828             result.GetImmediateOutputStream()->Flush();
1829 
1830         if (result.GetImmediateErrorStream())
1831             result.GetImmediateErrorStream()->Flush();
1832 
1833         // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
1834         // could be running (for instance in Breakpoint Commands.
1835         // So we check the return value to see if it is has running in it.
1836         if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
1837                 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
1838         {
1839             if (stop_on_continue)
1840             {
1841                 // If we caused the target to proceed, and we're going to stop in that case, set the
1842                 // status in our real result before returning.  This is an error if the continue was not the
1843                 // last command in the set of commands to be run.
1844                 if (idx != num_lines - 1)
1845                     result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
1846                                                  idx + 1, cmd);
1847                 else
1848                     result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
1849 
1850                 result.SetStatus(tmp_result.GetStatus());
1851                 m_debugger.SetAsyncExecution (old_async_execution);
1852 
1853                 return;
1854             }
1855         }
1856 
1857     }
1858 
1859     result.SetStatus (eReturnStatusSuccessFinishResult);
1860     m_debugger.SetAsyncExecution (old_async_execution);
1861 
1862     return;
1863 }
1864 
1865 void
1866 CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
1867                                             ExecutionContext *context,
1868                                             bool stop_on_continue,
1869                                             bool stop_on_error,
1870                                             bool echo_command,
1871                                             bool print_result,
1872                                             CommandReturnObject &result)
1873 {
1874     if (cmd_file.Exists())
1875     {
1876         bool success;
1877         StringList commands;
1878         success = commands.ReadFileLines(cmd_file);
1879         if (!success)
1880         {
1881             result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
1882             result.SetStatus (eReturnStatusFailed);
1883             return;
1884         }
1885         HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, result);
1886     }
1887     else
1888     {
1889         result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
1890                                       cmd_file.GetFilename().AsCString());
1891         result.SetStatus (eReturnStatusFailed);
1892         return;
1893     }
1894 }
1895 
1896 ScriptInterpreter *
1897 CommandInterpreter::GetScriptInterpreter ()
1898 {
1899     if (m_script_interpreter_ap.get() != NULL)
1900         return m_script_interpreter_ap.get();
1901 
1902     lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
1903     switch (script_lang)
1904     {
1905         case eScriptLanguageNone:
1906             m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
1907             break;
1908         case eScriptLanguagePython:
1909             m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
1910             break;
1911         default:
1912             break;
1913     };
1914 
1915     return m_script_interpreter_ap.get();
1916 }
1917 
1918 
1919 
1920 bool
1921 CommandInterpreter::GetSynchronous ()
1922 {
1923     return m_synchronous_execution;
1924 }
1925 
1926 void
1927 CommandInterpreter::SetSynchronous (bool value)
1928 {
1929     m_synchronous_execution  = value;
1930 }
1931 
1932 void
1933 CommandInterpreter::OutputFormattedHelpText (Stream &strm,
1934                                              const char *word_text,
1935                                              const char *separator,
1936                                              const char *help_text,
1937                                              uint32_t max_word_len)
1938 {
1939     const uint32_t max_columns = m_debugger.GetTerminalWidth();
1940 
1941     int indent_size = max_word_len + strlen (separator) + 2;
1942 
1943     strm.IndentMore (indent_size);
1944 
1945     StreamString text_strm;
1946     text_strm.Printf ("%-*s %s %s",  max_word_len, word_text, separator, help_text);
1947 
1948     size_t len = text_strm.GetSize();
1949     const char *text = text_strm.GetData();
1950     if (text[len - 1] == '\n')
1951     {
1952         text_strm.EOL();
1953         len = text_strm.GetSize();
1954     }
1955 
1956     if (len  < max_columns)
1957     {
1958         // Output it as a single line.
1959         strm.Printf ("%s", text);
1960     }
1961     else
1962     {
1963         // We need to break it up into multiple lines.
1964         bool first_line = true;
1965         int text_width;
1966         int start = 0;
1967         int end = start;
1968         int final_end = strlen (text);
1969         int sub_len;
1970 
1971         while (end < final_end)
1972         {
1973             if (first_line)
1974                 text_width = max_columns - 1;
1975             else
1976                 text_width = max_columns - indent_size - 1;
1977 
1978             // Don't start the 'text' on a space, since we're already outputting the indentation.
1979             if (!first_line)
1980             {
1981                 while ((start < final_end) && (text[start] == ' '))
1982                   start++;
1983             }
1984 
1985             end = start + text_width;
1986             if (end > final_end)
1987                 end = final_end;
1988             else
1989             {
1990                 // If we're not at the end of the text, make sure we break the line on white space.
1991                 while (end > start
1992                        && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
1993                     end--;
1994             }
1995 
1996             sub_len = end - start;
1997             if (start != 0)
1998               strm.EOL();
1999             if (!first_line)
2000                 strm.Indent();
2001             else
2002                 first_line = false;
2003             assert (start <= final_end);
2004             assert (start + sub_len <= final_end);
2005             if (sub_len > 0)
2006                 strm.Write (text + start, sub_len);
2007             start = end + 1;
2008         }
2009     }
2010     strm.EOL();
2011     strm.IndentLess(indent_size);
2012 }
2013 
2014 void
2015 CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
2016                                            StringList &commands_found, StringList &commands_help)
2017 {
2018     CommandObject::CommandMap::const_iterator pos;
2019     CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
2020     CommandObject *sub_cmd_obj;
2021 
2022     for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
2023     {
2024           const char * command_name = pos->first.c_str();
2025           sub_cmd_obj = pos->second.get();
2026           StreamString complete_command_name;
2027 
2028           complete_command_name.Printf ("%s %s", prefix, command_name);
2029 
2030           if (sub_cmd_obj->HelpTextContainsWord (search_word))
2031           {
2032               commands_found.AppendString (complete_command_name.GetData());
2033               commands_help.AppendString (sub_cmd_obj->GetHelp());
2034           }
2035 
2036           if (sub_cmd_obj->IsMultiwordObject())
2037               AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
2038                                      commands_help);
2039     }
2040 
2041 }
2042 
2043 void
2044 CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2045                                             StringList &commands_help)
2046 {
2047     CommandObject::CommandMap::const_iterator pos;
2048 
2049     for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2050     {
2051         const char *command_name = pos->first.c_str();
2052         CommandObject *cmd_obj = pos->second.get();
2053 
2054         if (cmd_obj->HelpTextContainsWord (search_word))
2055         {
2056             commands_found.AppendString (command_name);
2057             commands_help.AppendString (cmd_obj->GetHelp());
2058         }
2059 
2060         if (cmd_obj->IsMultiwordObject())
2061           AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
2062 
2063     }
2064 }
2065 
2066 
2067 void
2068 CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2069 {
2070     m_exe_ctx.Clear();
2071 
2072     if (override_context != NULL)
2073     {
2074         m_exe_ctx.target = override_context->target;
2075         m_exe_ctx.process = override_context->process;
2076         m_exe_ctx.thread = override_context->thread;
2077         m_exe_ctx.frame = override_context->frame;
2078     }
2079     else
2080     {
2081         TargetSP target_sp (m_debugger.GetSelectedTarget());
2082         if (target_sp)
2083         {
2084             m_exe_ctx.target = target_sp.get();
2085             m_exe_ctx.process = target_sp->GetProcessSP().get();
2086             if (m_exe_ctx.process && m_exe_ctx.process->IsAlive() && !m_exe_ctx.process->IsRunning())
2087             {
2088                 m_exe_ctx.thread = m_exe_ctx.process->GetThreadList().GetSelectedThread().get();
2089                 if (m_exe_ctx.thread == NULL)
2090                 {
2091                     m_exe_ctx.thread = m_exe_ctx.process->GetThreadList().GetThreadAtIndex(0).get();
2092                     // If we didn't have a selected thread, select one here.
2093                     if (m_exe_ctx.thread != NULL)
2094                         m_exe_ctx.process->GetThreadList().SetSelectedThreadByID(m_exe_ctx.thread->GetID());
2095                 }
2096                 if (m_exe_ctx.thread)
2097                 {
2098                     m_exe_ctx.frame = m_exe_ctx.thread->GetSelectedFrame().get();
2099                     if (m_exe_ctx.frame == NULL)
2100                     {
2101                         m_exe_ctx.frame = m_exe_ctx.thread->GetStackFrameAtIndex (0).get();
2102                         // If we didn't have a selected frame select one here.
2103                         if (m_exe_ctx.frame != NULL)
2104                             m_exe_ctx.thread->SetSelectedFrame(m_exe_ctx.frame);
2105                     }
2106                 }
2107             }
2108         }
2109     }
2110 }
2111 
2112