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 "CommandObjectScript.h"
17 #include "lldb/Interpreter/CommandObjectRegexCommand.h"
18 
19 #include "../Commands/CommandObjectApropos.h"
20 #include "../Commands/CommandObjectArgs.h"
21 #include "../Commands/CommandObjectBreakpoint.h"
22 #include "../Commands/CommandObjectDisassemble.h"
23 #include "../Commands/CommandObjectExpression.h"
24 #include "../Commands/CommandObjectFrame.h"
25 #include "../Commands/CommandObjectHelp.h"
26 #include "../Commands/CommandObjectLog.h"
27 #include "../Commands/CommandObjectMemory.h"
28 #include "../Commands/CommandObjectPlatform.h"
29 #include "../Commands/CommandObjectProcess.h"
30 #include "../Commands/CommandObjectQuit.h"
31 #include "../Commands/CommandObjectRegister.h"
32 #include "../Commands/CommandObjectSettings.h"
33 #include "../Commands/CommandObjectSource.h"
34 #include "../Commands/CommandObjectCommands.h"
35 #include "../Commands/CommandObjectSyntax.h"
36 #include "../Commands/CommandObjectTarget.h"
37 #include "../Commands/CommandObjectThread.h"
38 #include "../Commands/CommandObjectType.h"
39 #include "../Commands/CommandObjectVersion.h"
40 #include "../Commands/CommandObjectWatchpoint.h"
41 
42 #include "lldb/Interpreter/Args.h"
43 #include "lldb/Interpreter/Options.h"
44 #include "lldb/Core/Debugger.h"
45 #include "lldb/Core/InputReader.h"
46 #include "lldb/Core/Stream.h"
47 #include "lldb/Core/Timer.h"
48 #include "lldb/Host/Host.h"
49 #include "lldb/Target/Process.h"
50 #include "lldb/Target/Thread.h"
51 #include "lldb/Target/TargetList.h"
52 #include "lldb/Utility/CleanUp.h"
53 
54 #include "lldb/Interpreter/CommandReturnObject.h"
55 #include "lldb/Interpreter/CommandInterpreter.h"
56 #include "lldb/Interpreter/ScriptInterpreterNone.h"
57 #include "lldb/Interpreter/ScriptInterpreterPython.h"
58 
59 using namespace lldb;
60 using namespace lldb_private;
61 
62 ConstString &
63 CommandInterpreter::GetStaticBroadcasterClass ()
64 {
65     static ConstString class_name ("lldb.commandInterpreter");
66     return class_name;
67 }
68 
69 CommandInterpreter::CommandInterpreter
70 (
71     Debugger &debugger,
72     ScriptLanguage script_language,
73     bool synchronous_execution
74 ) :
75     Broadcaster (&debugger, "lldb.command-interpreter"),
76     m_debugger (debugger),
77     m_synchronous_execution (synchronous_execution),
78     m_skip_lldbinit_files (false),
79     m_skip_app_init_files (false),
80     m_script_interpreter_ap (),
81     m_comment_char ('#'),
82     m_repeat_char ('!'),
83     m_truncation_warning(eNoTruncation),
84     m_command_source_depth (0)
85 {
86     const char *dbg_name = debugger.GetInstanceName().AsCString();
87     std::string lang_name = ScriptInterpreter::LanguageToString (script_language);
88     StreamString var_name;
89     var_name.Printf ("[%s].script-lang", dbg_name);
90     debugger.GetSettingsController()->SetVariable (var_name.GetData(), lang_name.c_str(),
91                                                    eVarSetOperationAssign, false,
92                                                    m_debugger.GetInstanceName().AsCString());
93     SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
94     SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
95     SetEventName (eBroadcastBitQuitCommandReceived, "quit");
96 
97     CheckInWithManager ();
98 }
99 
100 void
101 CommandInterpreter::Initialize ()
102 {
103     Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
104 
105     CommandReturnObject result;
106 
107     LoadCommandDictionary ();
108 
109     // Set up some initial aliases.
110     CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
111     if (cmd_obj_sp)
112     {
113         AddAlias ("q", cmd_obj_sp);
114         AddAlias ("exit", cmd_obj_sp);
115     }
116 
117     cmd_obj_sp = GetCommandSPExact ("process attach", false);
118     if (cmd_obj_sp)
119     {
120         AddAlias ("attach", cmd_obj_sp);
121     }
122 
123     cmd_obj_sp = GetCommandSPExact ("process continue", false);
124     if (cmd_obj_sp)
125     {
126         AddAlias ("c", cmd_obj_sp);
127         AddAlias ("continue", cmd_obj_sp);
128     }
129 
130     cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
131     if (cmd_obj_sp)
132         AddAlias ("b", cmd_obj_sp);
133 
134     cmd_obj_sp = GetCommandSPExact ("thread backtrace", false);
135     if (cmd_obj_sp)
136         AddAlias ("bt", cmd_obj_sp);
137 
138     cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
139     if (cmd_obj_sp)
140     {
141         AddAlias ("stepi", cmd_obj_sp);
142         AddAlias ("si", cmd_obj_sp);
143     }
144 
145     cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
146     if (cmd_obj_sp)
147     {
148         AddAlias ("nexti", cmd_obj_sp);
149         AddAlias ("ni", cmd_obj_sp);
150     }
151 
152     cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
153     if (cmd_obj_sp)
154     {
155         AddAlias ("s", cmd_obj_sp);
156         AddAlias ("step", cmd_obj_sp);
157     }
158 
159     cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
160     if (cmd_obj_sp)
161     {
162         AddAlias ("n", cmd_obj_sp);
163         AddAlias ("next", cmd_obj_sp);
164     }
165 
166     cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
167     if (cmd_obj_sp)
168     {
169         AddAlias ("finish", cmd_obj_sp);
170     }
171 
172     cmd_obj_sp = GetCommandSPExact ("frame select", false);
173     if (cmd_obj_sp)
174     {
175         AddAlias ("f", cmd_obj_sp);
176     }
177 
178     cmd_obj_sp = GetCommandSPExact ("source list", false);
179     if (cmd_obj_sp)
180     {
181         AddAlias ("l", cmd_obj_sp);
182         AddAlias ("list", cmd_obj_sp);
183     }
184 
185     cmd_obj_sp = GetCommandSPExact ("memory read", false);
186     if (cmd_obj_sp)
187         AddAlias ("x", cmd_obj_sp);
188 
189     cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
190     if (cmd_obj_sp)
191         AddAlias ("up", cmd_obj_sp);
192 
193     cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
194     if (cmd_obj_sp)
195         AddAlias ("down", cmd_obj_sp);
196 
197     cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
198     if (cmd_obj_sp)
199         AddAlias ("display", cmd_obj_sp);
200 
201     cmd_obj_sp = GetCommandSPExact ("disassemble", false);
202     if (cmd_obj_sp)
203         AddAlias ("dis", cmd_obj_sp);
204 
205     cmd_obj_sp = GetCommandSPExact ("disassemble", false);
206     if (cmd_obj_sp)
207         AddAlias ("di", cmd_obj_sp);
208 
209 
210 
211     cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
212     if (cmd_obj_sp)
213         AddAlias ("undisplay", cmd_obj_sp);
214 
215     cmd_obj_sp = GetCommandSPExact ("target create", false);
216     if (cmd_obj_sp)
217         AddAlias ("file", cmd_obj_sp);
218 
219     cmd_obj_sp = GetCommandSPExact ("target modules", false);
220     if (cmd_obj_sp)
221         AddAlias ("image", cmd_obj_sp);
222 
223 
224     OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
225 
226     cmd_obj_sp = GetCommandSPExact ("expression", false);
227     if (cmd_obj_sp)
228     {
229         AddAlias ("expr", cmd_obj_sp);
230 
231         ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
232         AddAlias ("p", cmd_obj_sp);
233         AddAlias ("print", cmd_obj_sp);
234         AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
235         AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
236 
237         alias_arguments_vector_sp.reset (new OptionArgVector);
238         ProcessAliasOptionsArgs (cmd_obj_sp, "-o --", alias_arguments_vector_sp);
239         AddAlias ("po", cmd_obj_sp);
240         AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
241     }
242 
243     cmd_obj_sp = GetCommandSPExact ("process kill", false);
244     if (cmd_obj_sp)
245         AddAlias ("kill", cmd_obj_sp);
246 
247     cmd_obj_sp = GetCommandSPExact ("process launch", false);
248     if (cmd_obj_sp)
249     {
250         alias_arguments_vector_sp.reset (new OptionArgVector);
251 #if defined (__arm__)
252         ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
253 #else
254         ProcessAliasOptionsArgs (cmd_obj_sp, "--shell=/bin/bash --", alias_arguments_vector_sp);
255 #endif
256         AddAlias ("r", cmd_obj_sp);
257         AddAlias ("run", cmd_obj_sp);
258         AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
259         AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
260     }
261 
262     cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
263     if (cmd_obj_sp)
264     {
265         AddAlias ("add-dsym", cmd_obj_sp);
266     }
267 
268     cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
269     if (cmd_obj_sp)
270     {
271         alias_arguments_vector_sp.reset (new OptionArgVector);
272         ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
273         AddAlias ("rb", cmd_obj_sp);
274         AddOrReplaceAliasOptions("rb", alias_arguments_vector_sp);
275     }
276 }
277 
278 const char *
279 CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
280 {
281     // This function has not yet been implemented.
282 
283     // Look for any embedded script command
284     // If found,
285     //    get interpreter object from the command dictionary,
286     //    call execute_one_command on it,
287     //    get the results as a string,
288     //    substitute that string for current stuff.
289 
290     return arg;
291 }
292 
293 
294 void
295 CommandInterpreter::LoadCommandDictionary ()
296 {
297     Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
298 
299     // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
300     //
301     // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
302     // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
303     // the cross-referencing stuff) are created!!!
304     //
305     // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
306 
307 
308     // Command objects that inherit from CommandObjectCrossref must be created before other command objects
309     // are created.  This is so that when another command is created that needs to go into a crossref object,
310     // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
311     // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
312 
313     // Non-CommandObjectCrossref commands can now be created.
314 
315     lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
316 
317     m_command_dict["apropos"]   = CommandObjectSP (new CommandObjectApropos (*this));
318     m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
319     //m_command_dict["call"]      = CommandObjectSP (new CommandObjectCall (*this));
320     m_command_dict["command"]   = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
321     m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
322     m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
323 //    m_command_dict["file"]      = CommandObjectSP (new CommandObjectFile (*this));
324     m_command_dict["frame"]     = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
325     m_command_dict["help"]      = CommandObjectSP (new CommandObjectHelp (*this));
326     ///    m_command_dict["image"]     = CommandObjectSP (new CommandObjectImage (*this));
327     m_command_dict["log"]       = CommandObjectSP (new CommandObjectLog (*this));
328     m_command_dict["memory"]    = CommandObjectSP (new CommandObjectMemory (*this));
329     m_command_dict["platform"]  = CommandObjectSP (new CommandObjectPlatform (*this));
330     m_command_dict["process"]   = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
331     m_command_dict["quit"]      = CommandObjectSP (new CommandObjectQuit (*this));
332     m_command_dict["register"]  = CommandObjectSP (new CommandObjectRegister (*this));
333     m_command_dict["script"]    = CommandObjectSP (new CommandObjectScript (*this, script_language));
334     m_command_dict["settings"]  = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
335     m_command_dict["source"]    = CommandObjectSP (new CommandObjectMultiwordSource (*this));
336     m_command_dict["target"]    = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
337     m_command_dict["thread"]    = CommandObjectSP (new CommandObjectMultiwordThread (*this));
338     m_command_dict["type"]      = CommandObjectSP (new CommandObjectType (*this));
339     m_command_dict["version"]   = CommandObjectSP (new CommandObjectVersion (*this));
340     m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
341 
342     std::auto_ptr<CommandObjectRegexCommand>
343     break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
344                                                       "_regexp-break",
345                                                       "Set a breakpoint using a regular expression to specify the location.",
346                                                       "_regexp-break [<filename>:<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
347     if (break_regex_cmd_ap.get())
348     {
349         if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
350             break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
351             break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
352             break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full") &&
353             break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
354             break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'") &&
355             break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
356         {
357             CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
358             m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
359         }
360     }
361 
362     std::auto_ptr<CommandObjectRegexCommand>
363     down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
364                                                      "_regexp-down",
365                                                      "Go down \"n\" frames in the stack (1 frame by default).",
366                                                      "_regexp-down [n]", 2));
367     if (down_regex_cmd_ap.get())
368     {
369         if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
370             down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
371         {
372             CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
373             m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
374         }
375     }
376 
377     std::auto_ptr<CommandObjectRegexCommand>
378     up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
379                                                    "_regexp-up",
380                                                    "Go up \"n\" frames in the stack (1 frame by default).",
381                                                    "_regexp-up [n]", 2));
382     if (up_regex_cmd_ap.get())
383     {
384         if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
385             up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
386         {
387             CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
388             m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
389         }
390     }
391 
392     std::auto_ptr<CommandObjectRegexCommand>
393     display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
394                                                    "_regexp-display",
395                                                    "Add an expression evaluation stop-hook.",
396                                                    "_regexp-display expression", 2));
397     if (display_regex_cmd_ap.get())
398     {
399         if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
400         {
401             CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
402             m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
403         }
404     }
405 
406     std::auto_ptr<CommandObjectRegexCommand>
407     undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
408                                                    "_regexp-undisplay",
409                                                    "Remove an expression evaluation stop-hook.",
410                                                    "_regexp-undisplay stop-hook-number", 2));
411     if (undisplay_regex_cmd_ap.get())
412     {
413         if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
414         {
415             CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
416             m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
417         }
418     }
419 
420 }
421 
422 int
423 CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
424                                                           StringList &matches)
425 {
426     CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
427 
428     if (include_aliases)
429     {
430         CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
431     }
432 
433     return matches.GetSize();
434 }
435 
436 CommandObjectSP
437 CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
438 {
439     CommandObject::CommandMap::iterator pos;
440     CommandObjectSP ret_val;
441 
442     std::string cmd(cmd_cstr);
443 
444     if (HasCommands())
445     {
446         pos = m_command_dict.find(cmd);
447         if (pos != m_command_dict.end())
448             ret_val = pos->second;
449     }
450 
451     if (include_aliases && HasAliases())
452     {
453         pos = m_alias_dict.find(cmd);
454         if (pos != m_alias_dict.end())
455             ret_val = pos->second;
456     }
457 
458     if (HasUserCommands())
459     {
460         pos = m_user_dict.find(cmd);
461         if (pos != m_user_dict.end())
462             ret_val = pos->second;
463     }
464 
465     if (!exact && ret_val == NULL)
466     {
467         // We will only get into here if we didn't find any exact matches.
468 
469         CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
470 
471         StringList local_matches;
472         if (matches == NULL)
473             matches = &local_matches;
474 
475         unsigned int num_cmd_matches = 0;
476         unsigned int num_alias_matches = 0;
477         unsigned int num_user_matches = 0;
478 
479         // Look through the command dictionaries one by one, and if we get only one match from any of
480         // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
481 
482         if (HasCommands())
483         {
484             num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
485         }
486 
487         if (num_cmd_matches == 1)
488         {
489             cmd.assign(matches->GetStringAtIndex(0));
490             pos = m_command_dict.find(cmd);
491             if (pos != m_command_dict.end())
492                 real_match_sp = pos->second;
493         }
494 
495         if (include_aliases && HasAliases())
496         {
497             num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
498 
499         }
500 
501         if (num_alias_matches == 1)
502         {
503             cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
504             pos = m_alias_dict.find(cmd);
505             if (pos != m_alias_dict.end())
506                 alias_match_sp = pos->second;
507         }
508 
509         if (HasUserCommands())
510         {
511             num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
512         }
513 
514         if (num_user_matches == 1)
515         {
516             cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
517 
518             pos = m_user_dict.find (cmd);
519             if (pos != m_user_dict.end())
520                 user_match_sp = pos->second;
521         }
522 
523         // If we got exactly one match, return that, otherwise return the match list.
524 
525         if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
526         {
527             if (num_cmd_matches)
528                 return real_match_sp;
529             else if (num_alias_matches)
530                 return alias_match_sp;
531             else
532                 return user_match_sp;
533         }
534     }
535     else if (matches && ret_val != NULL)
536     {
537         matches->AppendString (cmd_cstr);
538     }
539 
540 
541     return ret_val;
542 }
543 
544 bool
545 CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
546 {
547     if (name && name[0])
548     {
549         std::string name_sstr(name);
550         if (!can_replace)
551         {
552             if (m_command_dict.find (name_sstr) != m_command_dict.end())
553                 return false;
554         }
555         m_command_dict[name_sstr] = cmd_sp;
556         return true;
557     }
558     return false;
559 }
560 
561 bool
562 CommandInterpreter::AddUserCommand (std::string name,
563                                     const lldb::CommandObjectSP &cmd_sp,
564                                     bool can_replace)
565 {
566     if (!name.empty())
567     {
568 
569         const char* name_cstr = name.c_str();
570 
571         // do not allow replacement of internal commands
572         if (CommandExists(name_cstr))
573             return false;
574 
575         if (can_replace == false && UserCommandExists(name_cstr))
576             return false;
577 
578         m_user_dict[name] = cmd_sp;
579         return true;
580     }
581     return false;
582 }
583 
584 CommandObjectSP
585 CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
586 {
587     Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
588     CommandObjectSP ret_val;   // Possibly empty return value.
589 
590     if (cmd_cstr == NULL)
591         return ret_val;
592 
593     if (cmd_words.GetArgumentCount() == 1)
594         return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
595     else
596     {
597         // We have a multi-word command (seemingly), so we need to do more work.
598         // First, get the cmd_obj_sp for the first word in the command.
599         CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
600         if (cmd_obj_sp.get() != NULL)
601         {
602             // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
603             // command name), and find the appropriate sub-command SP for each command word....
604             size_t end = cmd_words.GetArgumentCount();
605             for (size_t j= 1; j < end; ++j)
606             {
607                 if (cmd_obj_sp->IsMultiwordObject())
608                 {
609                     cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
610                     (cmd_words.GetArgumentAtIndex (j));
611                     if (cmd_obj_sp.get() == NULL)
612                         // The sub-command name was invalid.  Fail and return the empty 'ret_val'.
613                         return ret_val;
614                 }
615                 else
616                     // We have more words in the command name, but we don't have a multiword object. Fail and return
617                     // empty 'ret_val'.
618                     return ret_val;
619             }
620             // We successfully looped through all the command words and got valid command objects for them.  Assign the
621             // last object retrieved to 'ret_val'.
622             ret_val = cmd_obj_sp;
623         }
624     }
625     return ret_val;
626 }
627 
628 CommandObject *
629 CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
630 {
631     return GetCommandSPExact (cmd_cstr, include_aliases).get();
632 }
633 
634 CommandObject *
635 CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
636 {
637     CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
638 
639     // If we didn't find an exact match to the command string in the commands, look in
640     // the aliases.
641 
642     if (command_obj == NULL)
643     {
644         command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
645     }
646 
647     // Finally, if there wasn't an exact match among the aliases, look for an inexact match
648     // in both the commands and the aliases.
649 
650     if (command_obj == NULL)
651         command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
652 
653     return command_obj;
654 }
655 
656 bool
657 CommandInterpreter::CommandExists (const char *cmd)
658 {
659     return m_command_dict.find(cmd) != m_command_dict.end();
660 }
661 
662 bool
663 CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
664                                             const char *options_args,
665                                             OptionArgVectorSP &option_arg_vector_sp)
666 {
667     bool success = true;
668     OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
669 
670     if (!options_args || (strlen (options_args) < 1))
671         return true;
672 
673     std::string options_string (options_args);
674     Args args (options_args);
675     CommandReturnObject result;
676     // Check to see if the command being aliased can take any command options.
677     Options *options = cmd_obj_sp->GetOptions ();
678     if (options)
679     {
680         // See if any options were specified as part of the alias;  if so, handle them appropriately.
681         options->NotifyOptionParsingStarting ();
682         args.Unshift ("dummy_arg");
683         args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
684         args.Shift ();
685         if (result.Succeeded())
686             options->VerifyPartialOptions (result);
687         if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
688         {
689             result.AppendError ("Unable to create requested alias.\n");
690             return false;
691         }
692     }
693 
694     if (!options_string.empty())
695     {
696         if (cmd_obj_sp->WantsRawCommandString ())
697             option_arg_vector->push_back (OptionArgPair ("<argument>",
698                                                           OptionArgValue (-1,
699                                                                           options_string)));
700         else
701         {
702             int argc = args.GetArgumentCount();
703             for (size_t i = 0; i < argc; ++i)
704                 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
705                     option_arg_vector->push_back
706                                 (OptionArgPair ("<argument>",
707                                                 OptionArgValue (-1,
708                                                                 std::string (args.GetArgumentAtIndex (i)))));
709         }
710     }
711 
712     return success;
713 }
714 
715 bool
716 CommandInterpreter::AliasExists (const char *cmd)
717 {
718     return m_alias_dict.find(cmd) != m_alias_dict.end();
719 }
720 
721 bool
722 CommandInterpreter::UserCommandExists (const char *cmd)
723 {
724     return m_user_dict.find(cmd) != m_user_dict.end();
725 }
726 
727 void
728 CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
729 {
730     command_obj_sp->SetIsAlias (true);
731     m_alias_dict[alias_name] = command_obj_sp;
732 }
733 
734 bool
735 CommandInterpreter::RemoveAlias (const char *alias_name)
736 {
737     CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
738     if (pos != m_alias_dict.end())
739     {
740         m_alias_dict.erase(pos);
741         return true;
742     }
743     return false;
744 }
745 bool
746 CommandInterpreter::RemoveUser (const char *alias_name)
747 {
748     CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
749     if (pos != m_user_dict.end())
750     {
751         m_user_dict.erase(pos);
752         return true;
753     }
754     return false;
755 }
756 
757 void
758 CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
759 {
760     help_string.Printf ("'%s", command_name);
761     OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
762 
763     if (option_arg_vector_sp != NULL)
764     {
765         OptionArgVector *options = option_arg_vector_sp.get();
766         for (int i = 0; i < options->size(); ++i)
767         {
768             OptionArgPair cur_option = (*options)[i];
769             std::string opt = cur_option.first;
770             OptionArgValue value_pair = cur_option.second;
771             std::string value = value_pair.second;
772             if (opt.compare("<argument>") == 0)
773             {
774                 help_string.Printf (" %s", value.c_str());
775             }
776             else
777             {
778                 help_string.Printf (" %s", opt.c_str());
779                 if ((value.compare ("<no-argument>") != 0)
780                     && (value.compare ("<need-argument") != 0))
781                 {
782                     help_string.Printf (" %s", value.c_str());
783                 }
784             }
785         }
786     }
787 
788     help_string.Printf ("'");
789 }
790 
791 size_t
792 CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
793 {
794     CommandObject::CommandMap::const_iterator pos;
795     CommandObject::CommandMap::const_iterator end = dict.end();
796     size_t max_len = 0;
797 
798     for (pos = dict.begin(); pos != end; ++pos)
799     {
800         size_t len = pos->first.size();
801         if (max_len < len)
802             max_len = len;
803     }
804     return max_len;
805 }
806 
807 void
808 CommandInterpreter::GetHelp (CommandReturnObject &result,
809                              uint32_t cmd_types)
810 {
811     CommandObject::CommandMap::const_iterator pos;
812     uint32_t max_len = FindLongestCommandWord (m_command_dict);
813 
814     if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
815     {
816 
817         result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
818         result.AppendMessage("");
819 
820         for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
821         {
822             OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
823                                      max_len);
824         }
825         result.AppendMessage("");
826 
827     }
828 
829     if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
830     {
831         result.AppendMessage("The following is a list of your current command abbreviations "
832                              "(see 'help command alias' for more info):");
833         result.AppendMessage("");
834         max_len = FindLongestCommandWord (m_alias_dict);
835 
836         for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
837         {
838             StreamString sstr;
839             StreamString translation_and_help;
840             std::string entry_name = pos->first;
841             std::string second_entry = pos->second.get()->GetCommandName();
842             GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
843 
844             translation_and_help.Printf ("(%s)  %s", sstr.GetData(), pos->second->GetHelp());
845             OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
846                                      translation_and_help.GetData(), max_len);
847         }
848         result.AppendMessage("");
849     }
850 
851     if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
852     {
853         result.AppendMessage ("The following is a list of your current user-defined commands:");
854         result.AppendMessage("");
855         max_len = FindLongestCommandWord (m_user_dict);
856         for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
857         {
858             OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
859                                      max_len);
860         }
861         result.AppendMessage("");
862     }
863 
864     result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
865 }
866 
867 CommandObject *
868 CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
869 {
870     // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
871     // eventually be invoked by the given command line.
872 
873     CommandObject *cmd_obj = NULL;
874     std::string white_space (" \t\v");
875     size_t start = command_string.find_first_not_of (white_space);
876     size_t end = 0;
877     bool done = false;
878     while (!done)
879     {
880         if (start != std::string::npos)
881         {
882             // Get the next word from command_string.
883             end = command_string.find_first_of (white_space, start);
884             if (end == std::string::npos)
885                 end = command_string.size();
886             std::string cmd_word = command_string.substr (start, end - start);
887 
888             if (cmd_obj == NULL)
889                 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
890                 // command or alias.
891                 cmd_obj = GetCommandObject (cmd_word.c_str());
892             else if (cmd_obj->IsMultiwordObject ())
893             {
894                 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
895                 CommandObject *sub_cmd_obj =
896                                          ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
897                 if (sub_cmd_obj)
898                     cmd_obj = sub_cmd_obj;
899                 else // cmd_word was not a valid sub-command word, so we are donee
900                     done = true;
901             }
902             else
903                 // We have a cmd_obj and it is not a multi-word object, so we are done.
904                 done = true;
905 
906             // If we didn't find a valid command object, or our command object is not a multi-word object, or
907             // we are at the end of the command_string, then we are done.  Otherwise, find the start of the
908             // next word.
909 
910             if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
911                 done = true;
912             else
913                 start = command_string.find_first_not_of (white_space, end);
914         }
915         else
916             // Unable to find any more words.
917             done = true;
918     }
919 
920     if (end == command_string.size())
921         command_string.clear();
922     else
923         command_string = command_string.substr(end);
924 
925     return cmd_obj;
926 }
927 
928 static const char *k_white_space = " \t\v";
929 static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
930 static void
931 StripLeadingSpaces (std::string &s)
932 {
933     if (!s.empty())
934     {
935         size_t pos = s.find_first_not_of (k_white_space);
936         if (pos == std::string::npos)
937             s.clear();
938         else if (pos == 0)
939             return;
940         s.erase (0, pos);
941     }
942 }
943 
944 static size_t
945 FindArgumentTerminator (const std::string &s)
946 {
947     const size_t s_len = s.size();
948     size_t offset = 0;
949     while (offset < s_len)
950     {
951         size_t pos = s.find ("--", offset);
952         if (pos == std::string::npos)
953             break;
954         if (pos > 0)
955         {
956             if (isspace(s[pos-1]))
957             {
958                 // Check if the string ends "\s--" (where \s is a space character)
959                 // or if we have "\s--\s".
960                 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
961                 {
962                     return pos;
963                 }
964             }
965         }
966         offset = pos + 2;
967     }
968     return std::string::npos;
969 }
970 
971 static bool
972 ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
973 {
974     command.clear();
975     suffix.clear();
976     StripLeadingSpaces (command_string);
977 
978     bool result = false;
979     quote_char = '\0';
980 
981     if (!command_string.empty())
982     {
983         const char first_char = command_string[0];
984         if (first_char == '\'' || first_char == '"')
985         {
986             quote_char = first_char;
987             const size_t end_quote_pos = command_string.find (quote_char, 1);
988             if (end_quote_pos == std::string::npos)
989             {
990                 command.swap (command_string);
991                 command_string.erase ();
992             }
993             else
994             {
995                 command.assign (command_string, 1, end_quote_pos - 1);
996                 if (end_quote_pos + 1 < command_string.size())
997                     command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
998                 else
999                     command_string.erase ();
1000             }
1001         }
1002         else
1003         {
1004             const size_t first_space_pos = command_string.find_first_of (k_white_space);
1005             if (first_space_pos == std::string::npos)
1006             {
1007                 command.swap (command_string);
1008                 command_string.erase();
1009             }
1010             else
1011             {
1012                 command.assign (command_string, 0, first_space_pos);
1013                 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
1014             }
1015         }
1016         result = true;
1017     }
1018 
1019 
1020     if (!command.empty())
1021     {
1022         // actual commands can't start with '-' or '_'
1023         if (command[0] != '-' && command[0] != '_')
1024         {
1025             size_t pos = command.find_first_not_of(k_valid_command_chars);
1026             if (pos > 0 && pos != std::string::npos)
1027             {
1028                 suffix.assign (command.begin() + pos, command.end());
1029                 command.erase (pos);
1030             }
1031         }
1032     }
1033 
1034     return result;
1035 }
1036 
1037 CommandObject *
1038 CommandInterpreter::BuildAliasResult (const char *alias_name,
1039                                       std::string &raw_input_string,
1040                                       std::string &alias_result,
1041                                       CommandReturnObject &result)
1042 {
1043     CommandObject *alias_cmd_obj = NULL;
1044     Args cmd_args (raw_input_string.c_str());
1045     alias_cmd_obj = GetCommandObject (alias_name);
1046     StreamString result_str;
1047 
1048     if (alias_cmd_obj)
1049     {
1050         std::string alias_name_str = alias_name;
1051         if ((cmd_args.GetArgumentCount() == 0)
1052             || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1053             cmd_args.Unshift (alias_name);
1054 
1055         result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1056         OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1057 
1058         if (option_arg_vector_sp.get())
1059         {
1060             OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1061 
1062             for (int i = 0; i < option_arg_vector->size(); ++i)
1063             {
1064                 OptionArgPair option_pair = (*option_arg_vector)[i];
1065                 OptionArgValue value_pair = option_pair.second;
1066                 int value_type = value_pair.first;
1067                 std::string option = option_pair.first;
1068                 std::string value = value_pair.second;
1069                 if (option.compare ("<argument>") == 0)
1070                     result_str.Printf (" %s", value.c_str());
1071                 else
1072                 {
1073                     result_str.Printf (" %s", option.c_str());
1074                     if (value_type != optional_argument)
1075                         result_str.Printf (" ");
1076                     if (value.compare ("<no_argument>") != 0)
1077                     {
1078                         int index = GetOptionArgumentPosition (value.c_str());
1079                         if (index == 0)
1080                             result_str.Printf ("%s", value.c_str());
1081                         else if (index >= cmd_args.GetArgumentCount())
1082                         {
1083 
1084                             result.AppendErrorWithFormat
1085                             ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1086                              index);
1087                             result.SetStatus (eReturnStatusFailed);
1088                             return alias_cmd_obj;
1089                         }
1090                         else
1091                         {
1092                             size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1093                             if (strpos != std::string::npos)
1094                                 raw_input_string = raw_input_string.erase (strpos,
1095                                                                           strlen (cmd_args.GetArgumentAtIndex (index)));
1096                             result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1097                         }
1098                     }
1099                 }
1100             }
1101         }
1102 
1103         alias_result = result_str.GetData();
1104     }
1105     return alias_cmd_obj;
1106 }
1107 
1108 Error
1109 CommandInterpreter::PreprocessCommand (std::string &command)
1110 {
1111     // The command preprocessor needs to do things to the command
1112     // line before any parsing of arguments or anything else is done.
1113     // The only current stuff that gets proprocessed is anyting enclosed
1114     // in backtick ('`') characters is evaluated as an expression and
1115     // the result of the expression must be a scalar that can be substituted
1116     // into the command. An example would be:
1117     // (lldb) memory read `$rsp + 20`
1118     Error error; // Error for any expressions that might not evaluate
1119     size_t start_backtick;
1120     size_t pos = 0;
1121     while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1122     {
1123         if (start_backtick > 0 && command[start_backtick-1] == '\\')
1124         {
1125             // The backtick was preceeded by a '\' character, remove the slash
1126             // and don't treat the backtick as the start of an expression
1127             command.erase(start_backtick-1, 1);
1128             // No need to add one to start_backtick since we just deleted a char
1129             pos = start_backtick;
1130         }
1131         else
1132         {
1133             const size_t expr_content_start = start_backtick + 1;
1134             const size_t end_backtick = command.find ('`', expr_content_start);
1135             if (end_backtick == std::string::npos)
1136                 return error;
1137             else if (end_backtick == expr_content_start)
1138             {
1139                 // Empty expression (two backticks in a row)
1140                 command.erase (start_backtick, 2);
1141             }
1142             else
1143             {
1144                 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1145 
1146                 Target *target = m_exe_ctx.GetTargetPtr();
1147                 // Get a dummy target to allow for calculator mode while processing backticks.
1148                 // This also helps break the infinite loop caused when target is null.
1149                 if (!target)
1150                     target = Host::GetDummyTarget(GetDebugger()).get();
1151                 if (target)
1152                 {
1153                     const bool coerce_to_id = false;
1154                     const bool unwind_on_error = true;
1155                     const bool keep_in_memory = false;
1156                     ValueObjectSP expr_result_valobj_sp;
1157                     ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
1158                                                                                m_exe_ctx.GetFramePtr(),
1159                                                                                eExecutionPolicyOnlyWhenNeeded,
1160                                                                                coerce_to_id,
1161                                                                                unwind_on_error,
1162                                                                                keep_in_memory,
1163                                                                                eNoDynamicValues,
1164                                                                                expr_result_valobj_sp);
1165                     if (expr_result == eExecutionCompleted)
1166                     {
1167                         Scalar scalar;
1168                         if (expr_result_valobj_sp->ResolveValue (scalar))
1169                         {
1170                             command.erase (start_backtick, end_backtick - start_backtick + 1);
1171                             StreamString value_strm;
1172                             const bool show_type = false;
1173                             scalar.GetValue (&value_strm, show_type);
1174                             size_t value_string_size = value_strm.GetSize();
1175                             if (value_string_size)
1176                             {
1177                                 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1178                                 pos = start_backtick + value_string_size;
1179                                 continue;
1180                             }
1181                             else
1182                             {
1183                                 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1184                             }
1185                         }
1186                         else
1187                         {
1188                             error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1189                         }
1190                     }
1191                     else
1192                     {
1193                         if (expr_result_valobj_sp)
1194                             error = expr_result_valobj_sp->GetError();
1195                         if (error.Success())
1196                         {
1197 
1198                             switch (expr_result)
1199                             {
1200                                 case eExecutionSetupError:
1201                                     error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1202                                     break;
1203                                 case eExecutionCompleted:
1204                                     break;
1205                                 case eExecutionDiscarded:
1206                                     error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1207                                     break;
1208                                 case eExecutionInterrupted:
1209                                     error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1210                                     break;
1211                                 case eExecutionTimedOut:
1212                                     error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1213                                     break;
1214                             }
1215                         }
1216                     }
1217                 }
1218             }
1219             if (error.Fail())
1220                 break;
1221         }
1222     }
1223     return error;
1224 }
1225 
1226 
1227 bool
1228 CommandInterpreter::HandleCommand (const char *command_line,
1229                                    LazyBool lazy_add_to_history,
1230                                    CommandReturnObject &result,
1231                                    ExecutionContext *override_context,
1232                                    bool repeat_on_empty_command,
1233                                    bool no_context_switching)
1234 
1235 {
1236 
1237     bool done = false;
1238     CommandObject *cmd_obj = NULL;
1239     bool wants_raw_input = false;
1240     std::string command_string (command_line);
1241     std::string original_command_string (command_line);
1242 
1243     LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
1244     Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1245 
1246     // Make a scoped cleanup object that will clear the crash description string
1247     // on exit of this function.
1248     lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
1249 
1250     if (log)
1251         log->Printf ("Processing command: %s", command_line);
1252 
1253     Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1254 
1255     if (!no_context_switching)
1256         UpdateExecutionContext (override_context);
1257 
1258     // <rdar://problem/11328896>
1259     bool add_to_history;
1260     if (lazy_add_to_history == eLazyBoolCalculate)
1261         add_to_history = (m_command_source_depth == 0);
1262     else
1263         add_to_history = (lazy_add_to_history == eLazyBoolYes);
1264 
1265     bool empty_command = false;
1266     bool comment_command = false;
1267     if (command_string.empty())
1268         empty_command = true;
1269     else
1270     {
1271         const char *k_space_characters = "\t\n\v\f\r ";
1272 
1273         size_t non_space = command_string.find_first_not_of (k_space_characters);
1274         // Check for empty line or comment line (lines whose first
1275         // non-space character is the comment character for this interpreter)
1276         if (non_space == std::string::npos)
1277             empty_command = true;
1278         else if (command_string[non_space] == m_comment_char)
1279              comment_command = true;
1280         else if (command_string[non_space] == m_repeat_char)
1281         {
1282             const char *history_string = FindHistoryString (command_string.c_str() + non_space);
1283             if (history_string == NULL)
1284             {
1285                 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1286                 result.SetStatus(eReturnStatusFailed);
1287                 return false;
1288             }
1289             add_to_history = false;
1290             command_string = history_string;
1291             original_command_string = history_string;
1292         }
1293     }
1294 
1295     if (empty_command)
1296     {
1297         if (repeat_on_empty_command)
1298         {
1299             if (m_command_history.empty())
1300             {
1301                 result.AppendError ("empty command");
1302                 result.SetStatus(eReturnStatusFailed);
1303                 return false;
1304             }
1305             else
1306             {
1307                 command_line = m_repeat_command.c_str();
1308                 command_string = command_line;
1309                 original_command_string = command_line;
1310                 if (m_repeat_command.empty())
1311                 {
1312                     result.AppendErrorWithFormat("No auto repeat.\n");
1313                     result.SetStatus (eReturnStatusFailed);
1314                     return false;
1315                 }
1316             }
1317             add_to_history = false;
1318         }
1319         else
1320         {
1321             result.SetStatus (eReturnStatusSuccessFinishNoResult);
1322             return true;
1323         }
1324     }
1325     else if (comment_command)
1326     {
1327         result.SetStatus (eReturnStatusSuccessFinishNoResult);
1328         return true;
1329     }
1330 
1331 
1332     Error error (PreprocessCommand (command_string));
1333 
1334     if (error.Fail())
1335     {
1336         result.AppendError (error.AsCString());
1337         result.SetStatus(eReturnStatusFailed);
1338         return false;
1339     }
1340     // Phase 1.
1341 
1342     // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1343     // is for the specified command, and whether or not it wants raw input.  This gets complicated by the fact that
1344     // the user could have specified an alias, and in translating the alias there may also be command options and/or
1345     // even data (including raw text strings) that need to be found and inserted into the command line as part of
1346     // the translation.  So this first step is plain look-up & replacement, resulting in three things:  1). the command
1347     // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
1348     // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
1349 
1350     StreamString revised_command_line;
1351     size_t actual_cmd_name_len = 0;
1352     std::string next_word;
1353     StringList matches;
1354     while (!done)
1355     {
1356         char quote_char = '\0';
1357         std::string suffix;
1358         ExtractCommand (command_string, next_word, suffix, quote_char);
1359         if (cmd_obj == NULL)
1360         {
1361             if (AliasExists (next_word.c_str()))
1362             {
1363                 std::string alias_result;
1364                 cmd_obj = BuildAliasResult (next_word.c_str(), command_string, alias_result, result);
1365                 revised_command_line.Printf ("%s", alias_result.c_str());
1366                 if (cmd_obj)
1367                 {
1368                     wants_raw_input = cmd_obj->WantsRawCommandString ();
1369                     actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1370                 }
1371             }
1372             else
1373             {
1374                 cmd_obj = GetCommandObject (next_word.c_str(), &matches);
1375                 if (cmd_obj)
1376                 {
1377                     actual_cmd_name_len += next_word.length();
1378                     revised_command_line.Printf ("%s", next_word.c_str());
1379                     wants_raw_input = cmd_obj->WantsRawCommandString ();
1380                 }
1381                 else
1382                 {
1383                     revised_command_line.Printf ("%s", next_word.c_str());
1384                 }
1385             }
1386         }
1387         else
1388         {
1389             if (cmd_obj->IsMultiwordObject ())
1390             {
1391                 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
1392                 if (sub_cmd_obj)
1393                 {
1394                     actual_cmd_name_len += next_word.length() + 1;
1395                     revised_command_line.Printf (" %s", next_word.c_str());
1396                     cmd_obj = sub_cmd_obj;
1397                     wants_raw_input = cmd_obj->WantsRawCommandString ();
1398                 }
1399                 else
1400                 {
1401                     if (quote_char)
1402                         revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1403                     else
1404                         revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1405                     done = true;
1406                 }
1407             }
1408             else
1409             {
1410                 if (quote_char)
1411                     revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1412                 else
1413                     revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1414                 done = true;
1415             }
1416         }
1417 
1418         if (cmd_obj == NULL)
1419         {
1420             uint32_t num_matches = matches.GetSize();
1421             if (matches.GetSize() > 1) {
1422                 std::string error_msg;
1423                 error_msg.assign ("Ambiguous command '");
1424                 error_msg.append(next_word.c_str());
1425                 error_msg.append ("'.");
1426 
1427                 error_msg.append (" Possible matches:");
1428 
1429                 for (uint32_t i = 0; i < num_matches; ++i) {
1430                     error_msg.append ("\n\t");
1431                     error_msg.append (matches.GetStringAtIndex(i));
1432                 }
1433                 error_msg.append ("\n");
1434                 result.AppendRawError (error_msg.c_str(), error_msg.size());
1435             } else {
1436                 // We didn't have only one match, otherwise we wouldn't get here.
1437                 assert(num_matches == 0);
1438                 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1439             }
1440             result.SetStatus (eReturnStatusFailed);
1441             return false;
1442         }
1443 
1444         if (cmd_obj->IsMultiwordObject ())
1445         {
1446             if (!suffix.empty())
1447             {
1448 
1449                 result.AppendErrorWithFormat ("multi-word commands ('%s') can't have shorthand suffixes: '%s'\n",
1450                                               next_word.c_str(),
1451                                               suffix.c_str());
1452                 result.SetStatus (eReturnStatusFailed);
1453                 return false;
1454             }
1455         }
1456         else
1457         {
1458             // If we found a normal command, we are done
1459             done = true;
1460             if (!suffix.empty())
1461             {
1462                 switch (suffix[0])
1463                 {
1464                 case '/':
1465                     // GDB format suffixes
1466                     {
1467                         Options *command_options = cmd_obj->GetOptions();
1468                         if (command_options && command_options->SupportsLongOption("gdb-format"))
1469                         {
1470                             std::string gdb_format_option ("--gdb-format=");
1471                             gdb_format_option += (suffix.c_str() + 1);
1472 
1473                             bool inserted = false;
1474                             std::string &cmd = revised_command_line.GetString();
1475                             size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1476                             if (arg_terminator_idx != std::string::npos)
1477                             {
1478                                 // Insert the gdb format option before the "--" that terminates options
1479                                 gdb_format_option.append(1,' ');
1480                                 cmd.insert(arg_terminator_idx, gdb_format_option);
1481                                 inserted = true;
1482                             }
1483 
1484                             if (!inserted)
1485                                 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1486 
1487                             if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1488                                 revised_command_line.PutCString (" --");
1489                         }
1490                         else
1491                         {
1492                             result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1493                                                           cmd_obj->GetCommandName());
1494                             result.SetStatus (eReturnStatusFailed);
1495                             return false;
1496                         }
1497                     }
1498                     break;
1499 
1500                 default:
1501                     result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1502                                                   suffix.c_str());
1503                     result.SetStatus (eReturnStatusFailed);
1504                     return false;
1505 
1506                 }
1507             }
1508         }
1509         if (command_string.length() == 0)
1510             done = true;
1511 
1512     }
1513 
1514     if (!command_string.empty())
1515         revised_command_line.Printf (" %s", command_string.c_str());
1516 
1517     // End of Phase 1.
1518     // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1519     // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1520     // fully translated with all substitutions & translations taken care of (still in raw text format); and
1521     // wants_raw_input specifies whether the Execute method expects raw input or not.
1522 
1523 
1524     if (log)
1525     {
1526         log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1527         log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1528         log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1529     }
1530 
1531     // Phase 2.
1532     // Take care of things like setting up the history command & calling the appropriate Execute method on the
1533     // CommandObject, with the appropriate arguments.
1534 
1535     if (cmd_obj != NULL)
1536     {
1537         if (add_to_history)
1538         {
1539             Args command_args (revised_command_line.GetData());
1540             const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1541             if (repeat_command != NULL)
1542                 m_repeat_command.assign(repeat_command);
1543             else
1544                 m_repeat_command.assign(original_command_string.c_str());
1545 
1546             // Don't keep pushing the same command onto the history...
1547             if (m_command_history.empty() || m_command_history.back() != original_command_string)
1548                 m_command_history.push_back (original_command_string);
1549         }
1550 
1551         command_string = revised_command_line.GetData();
1552         std::string command_name (cmd_obj->GetCommandName());
1553         std::string remainder;
1554         if (actual_cmd_name_len < command_string.length())
1555             remainder = command_string.substr (actual_cmd_name_len);  // Note: 'actual_cmd_name_len' may be considerably shorter
1556                                                            // than cmd_obj->GetCommandName(), because name completion
1557                                                            // allows users to enter short versions of the names,
1558                                                            // e.g. 'br s' for 'breakpoint set'.
1559 
1560         // Remove any initial spaces
1561         std::string white_space (" \t\v");
1562         size_t pos = remainder.find_first_not_of (white_space);
1563         if (pos != 0 && pos != std::string::npos)
1564             remainder.erase(0, pos);
1565 
1566         if (log)
1567             log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
1568 
1569         cmd_obj->Execute (remainder.c_str(), result);
1570     }
1571     else
1572     {
1573         // We didn't find the first command object, so complete the first argument.
1574         Args command_args (revised_command_line.GetData());
1575         StringList matches;
1576         int num_matches;
1577         int cursor_index = 0;
1578         int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1579         bool word_complete;
1580         num_matches = HandleCompletionMatches (command_args,
1581                                                cursor_index,
1582                                                cursor_char_position,
1583                                                0,
1584                                                -1,
1585                                                word_complete,
1586                                                matches);
1587 
1588         if (num_matches > 0)
1589         {
1590             std::string error_msg;
1591             error_msg.assign ("ambiguous command '");
1592             error_msg.append(command_args.GetArgumentAtIndex(0));
1593             error_msg.append ("'.");
1594 
1595             error_msg.append (" Possible completions:");
1596             for (int i = 0; i < num_matches; i++)
1597             {
1598                 error_msg.append ("\n\t");
1599                 error_msg.append (matches.GetStringAtIndex (i));
1600             }
1601             error_msg.append ("\n");
1602             result.AppendRawError (error_msg.c_str(), error_msg.size());
1603         }
1604         else
1605             result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1606 
1607         result.SetStatus (eReturnStatusFailed);
1608     }
1609 
1610     if (log)
1611       log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1612 
1613     return result.Succeeded();
1614 }
1615 
1616 int
1617 CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1618                                              int &cursor_index,
1619                                              int &cursor_char_position,
1620                                              int match_start_point,
1621                                              int max_return_elements,
1622                                              bool &word_complete,
1623                                              StringList &matches)
1624 {
1625     int num_command_matches = 0;
1626     bool look_for_subcommand = false;
1627 
1628     // For any of the command completions a unique match will be a complete word.
1629     word_complete = true;
1630 
1631     if (cursor_index == -1)
1632     {
1633         // We got nothing on the command line, so return the list of commands
1634         bool include_aliases = true;
1635         num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1636     }
1637     else if (cursor_index == 0)
1638     {
1639         // The cursor is in the first argument, so just do a lookup in the dictionary.
1640         CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
1641         num_command_matches = matches.GetSize();
1642 
1643         if (num_command_matches == 1
1644             && cmd_obj && cmd_obj->IsMultiwordObject()
1645             && matches.GetStringAtIndex(0) != NULL
1646             && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1647         {
1648             look_for_subcommand = true;
1649             num_command_matches = 0;
1650             matches.DeleteStringAtIndex(0);
1651             parsed_line.AppendArgument ("");
1652             cursor_index++;
1653             cursor_char_position = 0;
1654         }
1655     }
1656 
1657     if (cursor_index > 0 || look_for_subcommand)
1658     {
1659         // We are completing further on into a commands arguments, so find the command and tell it
1660         // to complete the command.
1661         // First see if there is a matching initial command:
1662         CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
1663         if (command_object == NULL)
1664         {
1665             return 0;
1666         }
1667         else
1668         {
1669             parsed_line.Shift();
1670             cursor_index--;
1671             num_command_matches = command_object->HandleCompletion (parsed_line,
1672                                                                     cursor_index,
1673                                                                     cursor_char_position,
1674                                                                     match_start_point,
1675                                                                     max_return_elements,
1676                                                                     word_complete,
1677                                                                     matches);
1678         }
1679     }
1680 
1681     return num_command_matches;
1682 
1683 }
1684 
1685 int
1686 CommandInterpreter::HandleCompletion (const char *current_line,
1687                                       const char *cursor,
1688                                       const char *last_char,
1689                                       int match_start_point,
1690                                       int max_return_elements,
1691                                       StringList &matches)
1692 {
1693     // We parse the argument up to the cursor, so the last argument in parsed_line is
1694     // the one containing the cursor, and the cursor is after the last character.
1695 
1696     Args parsed_line(current_line, last_char - current_line);
1697     Args partial_parsed_line(current_line, cursor - current_line);
1698 
1699     // Don't complete comments, and if the line we are completing is just the history repeat character,
1700     // substitute the appropriate history line.
1701     const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1702     if (first_arg)
1703     {
1704         if (first_arg[0] == m_comment_char)
1705             return 0;
1706         else if (first_arg[0] == m_repeat_char)
1707         {
1708             const char *history_string = FindHistoryString (first_arg);
1709             if (history_string != NULL)
1710             {
1711                 matches.Clear();
1712                 matches.InsertStringAtIndex(0, history_string);
1713                 return -2;
1714             }
1715             else
1716                 return 0;
1717 
1718         }
1719     }
1720 
1721 
1722     int num_args = partial_parsed_line.GetArgumentCount();
1723     int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1724     int cursor_char_position;
1725 
1726     if (cursor_index == -1)
1727         cursor_char_position = 0;
1728     else
1729         cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
1730 
1731     if (cursor > current_line && cursor[-1] == ' ')
1732     {
1733         // We are just after a space.  If we are in an argument, then we will continue
1734         // parsing, but if we are between arguments, then we have to complete whatever the next
1735         // element would be.
1736         // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1737         // protected by a quote) then the space will also be in the parsed argument...
1738 
1739         const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1740         if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1741         {
1742             parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1743             cursor_index++;
1744             cursor_char_position = 0;
1745         }
1746     }
1747 
1748     int num_command_matches;
1749 
1750     matches.Clear();
1751 
1752     // Only max_return_elements == -1 is supported at present:
1753     assert (max_return_elements == -1);
1754     bool word_complete;
1755     num_command_matches = HandleCompletionMatches (parsed_line,
1756                                                    cursor_index,
1757                                                    cursor_char_position,
1758                                                    match_start_point,
1759                                                    max_return_elements,
1760                                                    word_complete,
1761                                                    matches);
1762 
1763     if (num_command_matches <= 0)
1764             return num_command_matches;
1765 
1766     if (num_args == 0)
1767     {
1768         // If we got an empty string, insert nothing.
1769         matches.InsertStringAtIndex(0, "");
1770     }
1771     else
1772     {
1773         // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1774         // put an empty string in element 0.
1775         std::string command_partial_str;
1776         if (cursor_index >= 0)
1777             command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1778                                        parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
1779 
1780         std::string common_prefix;
1781         matches.LongestCommonPrefix (common_prefix);
1782         int partial_name_len = command_partial_str.size();
1783 
1784         // If we matched a unique single command, add a space...
1785         // Only do this if the completer told us this was a complete word, however...
1786         if (num_command_matches == 1 && word_complete)
1787         {
1788             char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1789             if (quote_char != '\0')
1790                 common_prefix.push_back(quote_char);
1791 
1792             common_prefix.push_back(' ');
1793         }
1794         common_prefix.erase (0, partial_name_len);
1795         matches.InsertStringAtIndex(0, common_prefix.c_str());
1796     }
1797     return num_command_matches;
1798 }
1799 
1800 
1801 CommandInterpreter::~CommandInterpreter ()
1802 {
1803 }
1804 
1805 const char *
1806 CommandInterpreter::GetPrompt ()
1807 {
1808     return m_debugger.GetPrompt();
1809 }
1810 
1811 void
1812 CommandInterpreter::SetPrompt (const char *new_prompt)
1813 {
1814     m_debugger.SetPrompt (new_prompt);
1815 }
1816 
1817 size_t
1818 CommandInterpreter::GetConfirmationInputReaderCallback
1819 (
1820     void *baton,
1821     InputReader &reader,
1822     lldb::InputReaderAction action,
1823     const char *bytes,
1824     size_t bytes_len
1825 )
1826 {
1827     File &out_file = reader.GetDebugger().GetOutputFile();
1828     bool *response_ptr = (bool *) baton;
1829 
1830     switch (action)
1831     {
1832     case eInputReaderActivate:
1833         if (out_file.IsValid())
1834         {
1835             if (reader.GetPrompt())
1836             {
1837                 out_file.Printf ("%s", reader.GetPrompt());
1838                 out_file.Flush ();
1839             }
1840         }
1841         break;
1842 
1843     case eInputReaderDeactivate:
1844         break;
1845 
1846     case eInputReaderReactivate:
1847         if (out_file.IsValid() && reader.GetPrompt())
1848         {
1849             out_file.Printf ("%s", reader.GetPrompt());
1850             out_file.Flush ();
1851         }
1852         break;
1853 
1854     case eInputReaderAsynchronousOutputWritten:
1855         break;
1856 
1857     case eInputReaderGotToken:
1858         if (bytes_len == 0)
1859         {
1860             reader.SetIsDone(true);
1861         }
1862         else if (bytes[0] == 'y' || bytes[0] == 'Y')
1863         {
1864             *response_ptr = true;
1865             reader.SetIsDone(true);
1866         }
1867         else if (bytes[0] == 'n' || bytes[0] == 'N')
1868         {
1869             *response_ptr = false;
1870             reader.SetIsDone(true);
1871         }
1872         else
1873         {
1874             if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
1875             {
1876                 out_file.Printf ("Please answer \"y\" or \"n\".\n%s", reader.GetPrompt());
1877                 out_file.Flush ();
1878             }
1879         }
1880         break;
1881 
1882     case eInputReaderInterrupt:
1883     case eInputReaderEndOfFile:
1884         *response_ptr = false;  // Assume ^C or ^D means cancel the proposed action
1885         reader.SetIsDone (true);
1886         break;
1887 
1888     case eInputReaderDone:
1889         break;
1890     }
1891 
1892     return bytes_len;
1893 
1894 }
1895 
1896 bool
1897 CommandInterpreter::Confirm (const char *message, bool default_answer)
1898 {
1899     // Check AutoConfirm first:
1900     if (m_debugger.GetAutoConfirm())
1901         return default_answer;
1902 
1903     InputReaderSP reader_sp (new InputReader(GetDebugger()));
1904     bool response = default_answer;
1905     if (reader_sp)
1906     {
1907         std::string prompt(message);
1908         prompt.append(": [");
1909         if (default_answer)
1910             prompt.append ("Y/n] ");
1911         else
1912             prompt.append ("y/N] ");
1913 
1914         Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1915                                           &response,                    // baton
1916                                           eInputReaderGranularityLine,  // token size, to pass to callback function
1917                                           NULL,                         // end token
1918                                           prompt.c_str(),               // prompt
1919                                           true));                       // echo input
1920         if (err.Success())
1921         {
1922             GetDebugger().PushInputReader (reader_sp);
1923         }
1924         reader_sp->WaitOnReaderIsDone();
1925     }
1926     return response;
1927 }
1928 
1929 
1930 void
1931 CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1932 {
1933     CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
1934 
1935     if (cmd_obj_sp != NULL)
1936     {
1937         CommandObject *cmd_obj = cmd_obj_sp.get();
1938         if (cmd_obj->IsCrossRefObject ())
1939             cmd_obj->AddObject (object_type);
1940     }
1941 }
1942 
1943 OptionArgVectorSP
1944 CommandInterpreter::GetAliasOptions (const char *alias_name)
1945 {
1946     OptionArgMap::iterator pos;
1947     OptionArgVectorSP ret_val;
1948 
1949     std::string alias (alias_name);
1950 
1951     if (HasAliasOptions())
1952     {
1953         pos = m_alias_options.find (alias);
1954         if (pos != m_alias_options.end())
1955           ret_val = pos->second;
1956     }
1957 
1958     return ret_val;
1959 }
1960 
1961 void
1962 CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1963 {
1964     OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1965     if (pos != m_alias_options.end())
1966     {
1967         m_alias_options.erase (pos);
1968     }
1969 }
1970 
1971 void
1972 CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1973 {
1974     m_alias_options[alias_name] = option_arg_vector_sp;
1975 }
1976 
1977 bool
1978 CommandInterpreter::HasCommands ()
1979 {
1980     return (!m_command_dict.empty());
1981 }
1982 
1983 bool
1984 CommandInterpreter::HasAliases ()
1985 {
1986     return (!m_alias_dict.empty());
1987 }
1988 
1989 bool
1990 CommandInterpreter::HasUserCommands ()
1991 {
1992     return (!m_user_dict.empty());
1993 }
1994 
1995 bool
1996 CommandInterpreter::HasAliasOptions ()
1997 {
1998     return (!m_alias_options.empty());
1999 }
2000 
2001 void
2002 CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2003                                            const char *alias_name,
2004                                            Args &cmd_args,
2005                                            std::string &raw_input_string,
2006                                            CommandReturnObject &result)
2007 {
2008     OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
2009 
2010     bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
2011 
2012     // Make sure that the alias name is the 0th element in cmd_args
2013     std::string alias_name_str = alias_name;
2014     if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2015         cmd_args.Unshift (alias_name);
2016 
2017     Args new_args (alias_cmd_obj->GetCommandName());
2018     if (new_args.GetArgumentCount() == 2)
2019         new_args.Shift();
2020 
2021     if (option_arg_vector_sp.get())
2022     {
2023         if (wants_raw_input)
2024         {
2025             // We have a command that both has command options and takes raw input.  Make *sure* it has a
2026             // " -- " in the right place in the raw_input_string.
2027             size_t pos = raw_input_string.find(" -- ");
2028             if (pos == std::string::npos)
2029             {
2030                 // None found; assume it goes at the beginning of the raw input string
2031                 raw_input_string.insert (0, " -- ");
2032             }
2033         }
2034 
2035         OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
2036         int old_size = cmd_args.GetArgumentCount();
2037         std::vector<bool> used (old_size + 1, false);
2038 
2039         used[0] = true;
2040 
2041         for (int i = 0; i < option_arg_vector->size(); ++i)
2042         {
2043             OptionArgPair option_pair = (*option_arg_vector)[i];
2044             OptionArgValue value_pair = option_pair.second;
2045             int value_type = value_pair.first;
2046             std::string option = option_pair.first;
2047             std::string value = value_pair.second;
2048             if (option.compare ("<argument>") == 0)
2049             {
2050                 if (!wants_raw_input
2051                     || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2052                     new_args.AppendArgument (value.c_str());
2053             }
2054             else
2055             {
2056                 if (value_type != optional_argument)
2057                     new_args.AppendArgument (option.c_str());
2058                 if (value.compare ("<no-argument>") != 0)
2059                 {
2060                     int index = GetOptionArgumentPosition (value.c_str());
2061                     if (index == 0)
2062                     {
2063                         // value was NOT a positional argument; must be a real value
2064                         if (value_type != optional_argument)
2065                             new_args.AppendArgument (value.c_str());
2066                         else
2067                         {
2068                             char buffer[255];
2069                             ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2070                             new_args.AppendArgument (buffer);
2071                         }
2072 
2073                     }
2074                     else if (index >= cmd_args.GetArgumentCount())
2075                     {
2076                         result.AppendErrorWithFormat
2077                                     ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2078                                      index);
2079                         result.SetStatus (eReturnStatusFailed);
2080                         return;
2081                     }
2082                     else
2083                     {
2084                         // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2085                         size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2086                         if (strpos != std::string::npos)
2087                         {
2088                             raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2089                         }
2090 
2091                         if (value_type != optional_argument)
2092                             new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2093                         else
2094                         {
2095                             char buffer[255];
2096                             ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2097                                         cmd_args.GetArgumentAtIndex (index));
2098                             new_args.AppendArgument (buffer);
2099                         }
2100                         used[index] = true;
2101                     }
2102                 }
2103             }
2104         }
2105 
2106         for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
2107         {
2108             if (!used[j] && !wants_raw_input)
2109                 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2110         }
2111 
2112         cmd_args.Clear();
2113         cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2114     }
2115     else
2116     {
2117         result.SetStatus (eReturnStatusSuccessFinishNoResult);
2118         // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2119         // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2120         // input string.
2121         if (wants_raw_input)
2122         {
2123             cmd_args.Clear();
2124             cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2125         }
2126         return;
2127     }
2128 
2129     result.SetStatus (eReturnStatusSuccessFinishNoResult);
2130     return;
2131 }
2132 
2133 
2134 int
2135 CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2136 {
2137     int position = 0;   // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2138                         // of zero.
2139 
2140     char *cptr = (char *) in_string;
2141 
2142     // Does it start with '%'
2143     if (cptr[0] == '%')
2144     {
2145         ++cptr;
2146 
2147         // Is the rest of it entirely digits?
2148         if (isdigit (cptr[0]))
2149         {
2150             const char *start = cptr;
2151             while (isdigit (cptr[0]))
2152                 ++cptr;
2153 
2154             // We've gotten to the end of the digits; are we at the end of the string?
2155             if (cptr[0] == '\0')
2156                 position = atoi (start);
2157         }
2158     }
2159 
2160     return position;
2161 }
2162 
2163 void
2164 CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2165 {
2166     FileSpec init_file;
2167     if (in_cwd)
2168     {
2169         // In the current working directory we don't load any program specific
2170         // .lldbinit files, we only look for a "./.lldbinit" file.
2171         if (m_skip_lldbinit_files)
2172             return;
2173 
2174         init_file.SetFile ("./.lldbinit", true);
2175     }
2176     else
2177     {
2178         // If we aren't looking in the current working directory we are looking
2179         // in the home directory. We will first see if there is an application
2180         // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2181         // "-" and the name of the program. If this file doesn't exist, we fall
2182         // back to just the "~/.lldbinit" file. We also obey any requests to not
2183         // load the init files.
2184         const char *init_file_path = "~/.lldbinit";
2185 
2186         if (m_skip_app_init_files == false)
2187         {
2188             FileSpec program_file_spec (Host::GetProgramFileSpec());
2189             const char *program_name = program_file_spec.GetFilename().AsCString();
2190 
2191             if (program_name)
2192             {
2193                 char program_init_file_name[PATH_MAX];
2194                 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2195                 init_file.SetFile (program_init_file_name, true);
2196                 if (!init_file.Exists())
2197                     init_file.Clear();
2198             }
2199         }
2200 
2201         if (!init_file && !m_skip_lldbinit_files)
2202 			init_file.SetFile (init_file_path, true);
2203     }
2204 
2205     // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2206     // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2207 
2208     if (init_file.Exists())
2209     {
2210         ExecutionContext *exe_ctx = NULL;  // We don't have any context yet.
2211         bool stop_on_continue = true;
2212         bool stop_on_error    = false;
2213         bool echo_commands    = false;
2214         bool print_results    = false;
2215 
2216         HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, eLazyBoolNo, result);
2217     }
2218     else
2219     {
2220         // nothing to be done if the file doesn't exist
2221         result.SetStatus(eReturnStatusSuccessFinishNoResult);
2222     }
2223 }
2224 
2225 PlatformSP
2226 CommandInterpreter::GetPlatform (bool prefer_target_platform)
2227 {
2228     PlatformSP platform_sp;
2229     if (prefer_target_platform)
2230     {
2231         Target *target = m_exe_ctx.GetTargetPtr();
2232         if (target)
2233             platform_sp = target->GetPlatform();
2234     }
2235 
2236     if (!platform_sp)
2237         platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2238     return platform_sp;
2239 }
2240 
2241 void
2242 CommandInterpreter::HandleCommands (const StringList &commands,
2243                                     ExecutionContext *override_context,
2244                                     bool stop_on_continue,
2245                                     bool stop_on_error,
2246                                     bool echo_commands,
2247                                     bool print_results,
2248                                     LazyBool add_to_history,
2249                                     CommandReturnObject &result)
2250 {
2251     size_t num_lines = commands.GetSize();
2252 
2253     // If we are going to continue past a "continue" then we need to run the commands synchronously.
2254     // Make sure you reset this value anywhere you return from the function.
2255 
2256     bool old_async_execution = m_debugger.GetAsyncExecution();
2257 
2258     // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2259     // cause series of commands that change the context, then do an operation that relies on that context to fail.
2260 
2261     if (override_context != NULL)
2262         UpdateExecutionContext (override_context);
2263 
2264     if (!stop_on_continue)
2265     {
2266         m_debugger.SetAsyncExecution (false);
2267     }
2268 
2269     for (int idx = 0; idx < num_lines; idx++)
2270     {
2271         const char *cmd = commands.GetStringAtIndex(idx);
2272         if (cmd[0] == '\0')
2273             continue;
2274 
2275         if (echo_commands)
2276         {
2277             result.AppendMessageWithFormat ("%s %s\n",
2278                                              GetPrompt(),
2279                                              cmd);
2280         }
2281 
2282         CommandReturnObject tmp_result;
2283         // If override_context is not NULL, pass no_context_switching = true for
2284         // HandleCommand() since we updated our context already.
2285         bool success = HandleCommand(cmd, add_to_history, tmp_result,
2286                                      NULL, /* override_context */
2287                                      true, /* repeat_on_empty_command */
2288                                      override_context != NULL /* no_context_switching */);
2289 
2290         if (print_results)
2291         {
2292             if (tmp_result.Succeeded())
2293               result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
2294         }
2295 
2296         if (!success || !tmp_result.Succeeded())
2297         {
2298             const char *error_msg = tmp_result.GetErrorData();
2299             if (error_msg == NULL || error_msg[0] == '\0')
2300                 error_msg = "<unknown error>.\n";
2301             if (stop_on_error)
2302             {
2303                 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed with %s",
2304                                          idx, cmd, error_msg);
2305                 result.SetStatus (eReturnStatusFailed);
2306                 m_debugger.SetAsyncExecution (old_async_execution);
2307                 return;
2308             }
2309             else if (print_results)
2310             {
2311                 result.AppendMessageWithFormat ("Command #%d '%s' failed with %s",
2312                                                 idx + 1,
2313                                                 cmd,
2314                                                 error_msg);
2315             }
2316         }
2317 
2318         if (result.GetImmediateOutputStream())
2319             result.GetImmediateOutputStream()->Flush();
2320 
2321         if (result.GetImmediateErrorStream())
2322             result.GetImmediateErrorStream()->Flush();
2323 
2324         // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2325         // could be running (for instance in Breakpoint Commands.
2326         // So we check the return value to see if it is has running in it.
2327         if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2328                 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2329         {
2330             if (stop_on_continue)
2331             {
2332                 // If we caused the target to proceed, and we're going to stop in that case, set the
2333                 // status in our real result before returning.  This is an error if the continue was not the
2334                 // last command in the set of commands to be run.
2335                 if (idx != num_lines - 1)
2336                     result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
2337                                                  idx + 1, cmd);
2338                 else
2339                     result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
2340 
2341                 result.SetStatus(tmp_result.GetStatus());
2342                 m_debugger.SetAsyncExecution (old_async_execution);
2343 
2344                 return;
2345             }
2346         }
2347 
2348     }
2349 
2350     result.SetStatus (eReturnStatusSuccessFinishResult);
2351     m_debugger.SetAsyncExecution (old_async_execution);
2352 
2353     return;
2354 }
2355 
2356 void
2357 CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2358                                             ExecutionContext *context,
2359                                             bool stop_on_continue,
2360                                             bool stop_on_error,
2361                                             bool echo_command,
2362                                             bool print_result,
2363                                             LazyBool add_to_history,
2364                                             CommandReturnObject &result)
2365 {
2366     if (cmd_file.Exists())
2367     {
2368         bool success;
2369         StringList commands;
2370         success = commands.ReadFileLines(cmd_file);
2371         if (!success)
2372         {
2373             result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2374             result.SetStatus (eReturnStatusFailed);
2375             return;
2376         }
2377         m_command_source_depth++;
2378         HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, add_to_history, result);
2379         m_command_source_depth--;
2380     }
2381     else
2382     {
2383         result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2384                                       cmd_file.GetFilename().AsCString());
2385         result.SetStatus (eReturnStatusFailed);
2386         return;
2387     }
2388 }
2389 
2390 ScriptInterpreter *
2391 CommandInterpreter::GetScriptInterpreter ()
2392 {
2393     // <rdar://problem/11751427>
2394     // we need to protect the initialization of the script interpreter
2395     // otherwise we could end up with two threads both trying to create
2396     // their instance of it, and for some languages (e.g. Python)
2397     // this is a bulletproof recipe for disaster!
2398     // this needs to be a function-level static because multiple Debugger instances living in the same process
2399     // still need to be isolated and not try to initialize Python concurrently
2400     static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive);
2401     Mutex::Locker interpreter_lock(g_interpreter_mutex);
2402 
2403     if (m_script_interpreter_ap.get() != NULL)
2404         return m_script_interpreter_ap.get();
2405 
2406     lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2407     switch (script_lang)
2408     {
2409         case eScriptLanguagePython:
2410 #ifndef LLDB_DISABLE_PYTHON
2411             m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2412             break;
2413 #else
2414             // Fall through to the None case when python is disabled
2415 #endif
2416         case eScriptLanguageNone:
2417             m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2418             break;
2419         default:
2420             break;
2421     };
2422 
2423     return m_script_interpreter_ap.get();
2424 }
2425 
2426 
2427 
2428 bool
2429 CommandInterpreter::GetSynchronous ()
2430 {
2431     return m_synchronous_execution;
2432 }
2433 
2434 void
2435 CommandInterpreter::SetSynchronous (bool value)
2436 {
2437     m_synchronous_execution  = value;
2438 }
2439 
2440 void
2441 CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2442                                              const char *word_text,
2443                                              const char *separator,
2444                                              const char *help_text,
2445                                              uint32_t max_word_len)
2446 {
2447     const uint32_t max_columns = m_debugger.GetTerminalWidth();
2448 
2449     int indent_size = max_word_len + strlen (separator) + 2;
2450 
2451     strm.IndentMore (indent_size);
2452 
2453     StreamString text_strm;
2454     text_strm.Printf ("%-*s %s %s",  max_word_len, word_text, separator, help_text);
2455 
2456     size_t len = text_strm.GetSize();
2457     const char *text = text_strm.GetData();
2458     if (text[len - 1] == '\n')
2459     {
2460         text_strm.EOL();
2461         len = text_strm.GetSize();
2462     }
2463 
2464     if (len  < max_columns)
2465     {
2466         // Output it as a single line.
2467         strm.Printf ("%s", text);
2468     }
2469     else
2470     {
2471         // We need to break it up into multiple lines.
2472         bool first_line = true;
2473         int text_width;
2474         int start = 0;
2475         int end = start;
2476         int final_end = strlen (text);
2477         int sub_len;
2478 
2479         while (end < final_end)
2480         {
2481             if (first_line)
2482                 text_width = max_columns - 1;
2483             else
2484                 text_width = max_columns - indent_size - 1;
2485 
2486             // Don't start the 'text' on a space, since we're already outputting the indentation.
2487             if (!first_line)
2488             {
2489                 while ((start < final_end) && (text[start] == ' '))
2490                   start++;
2491             }
2492 
2493             end = start + text_width;
2494             if (end > final_end)
2495                 end = final_end;
2496             else
2497             {
2498                 // If we're not at the end of the text, make sure we break the line on white space.
2499                 while (end > start
2500                        && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2501                     end--;
2502             }
2503 
2504             sub_len = end - start;
2505             if (start != 0)
2506               strm.EOL();
2507             if (!first_line)
2508                 strm.Indent();
2509             else
2510                 first_line = false;
2511             assert (start <= final_end);
2512             assert (start + sub_len <= final_end);
2513             if (sub_len > 0)
2514                 strm.Write (text + start, sub_len);
2515             start = end + 1;
2516         }
2517     }
2518     strm.EOL();
2519     strm.IndentLess(indent_size);
2520 }
2521 
2522 void
2523 CommandInterpreter::OutputHelpText (Stream &strm,
2524                                     const char *word_text,
2525                                     const char *separator,
2526                                     const char *help_text,
2527                                     uint32_t max_word_len)
2528 {
2529     int indent_size = max_word_len + strlen (separator) + 2;
2530 
2531     strm.IndentMore (indent_size);
2532 
2533     StreamString text_strm;
2534     text_strm.Printf ("%-*s %s %s",  max_word_len, word_text, separator, help_text);
2535 
2536     const uint32_t max_columns = m_debugger.GetTerminalWidth();
2537     bool first_line = true;
2538 
2539     size_t len = text_strm.GetSize();
2540     const char *text = text_strm.GetData();
2541 
2542     uint32_t chars_left = max_columns;
2543 
2544     for (uint32_t i = 0; i < len; i++)
2545     {
2546         if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2547         {
2548             first_line = false;
2549             chars_left = max_columns - indent_size;
2550             strm.EOL();
2551             strm.Indent();
2552         }
2553         else
2554         {
2555             strm.PutChar(text[i]);
2556             chars_left--;
2557         }
2558 
2559     }
2560 
2561     strm.EOL();
2562     strm.IndentLess(indent_size);
2563 }
2564 
2565 void
2566 CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
2567                                            StringList &commands_found, StringList &commands_help)
2568 {
2569     CommandObject::CommandMap::const_iterator pos;
2570     CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
2571     CommandObject *sub_cmd_obj;
2572 
2573     for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
2574     {
2575           const char * command_name = pos->first.c_str();
2576           sub_cmd_obj = pos->second.get();
2577           StreamString complete_command_name;
2578 
2579           complete_command_name.Printf ("%s %s", prefix, command_name);
2580 
2581           if (sub_cmd_obj->HelpTextContainsWord (search_word))
2582           {
2583               commands_found.AppendString (complete_command_name.GetData());
2584               commands_help.AppendString (sub_cmd_obj->GetHelp());
2585           }
2586 
2587           if (sub_cmd_obj->IsMultiwordObject())
2588               AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
2589                                      commands_help);
2590     }
2591 
2592 }
2593 
2594 void
2595 CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2596                                             StringList &commands_help)
2597 {
2598     CommandObject::CommandMap::const_iterator pos;
2599 
2600     for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2601     {
2602         const char *command_name = pos->first.c_str();
2603         CommandObject *cmd_obj = pos->second.get();
2604 
2605         if (cmd_obj->HelpTextContainsWord (search_word))
2606         {
2607             commands_found.AppendString (command_name);
2608             commands_help.AppendString (cmd_obj->GetHelp());
2609         }
2610 
2611         if (cmd_obj->IsMultiwordObject())
2612           AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
2613 
2614     }
2615 }
2616 
2617 
2618 void
2619 CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2620 {
2621     m_exe_ctx.Clear();
2622 
2623     if (override_context != NULL)
2624     {
2625         m_exe_ctx = *override_context;
2626     }
2627     else
2628     {
2629         TargetSP target_sp (m_debugger.GetSelectedTarget());
2630         if (target_sp)
2631         {
2632             m_exe_ctx.SetTargetSP (target_sp);
2633             ProcessSP process_sp (target_sp->GetProcessSP());
2634             m_exe_ctx.SetProcessSP (process_sp);
2635             if (process_sp && process_sp->IsAlive() && !process_sp->IsRunning())
2636             {
2637                 ThreadSP thread_sp (process_sp->GetThreadList().GetSelectedThread());
2638                 if (thread_sp)
2639                 {
2640                     m_exe_ctx.SetThreadSP (thread_sp);
2641                     StackFrameSP frame_sp (thread_sp->GetSelectedFrame());
2642                     if (!frame_sp)
2643                     {
2644                         frame_sp = thread_sp->GetStackFrameAtIndex (0);
2645                         // If we didn't have a selected frame select one here.
2646                         if (frame_sp)
2647                             thread_sp->SetSelectedFrame(frame_sp.get());
2648                     }
2649                     if (frame_sp)
2650                         m_exe_ctx.SetFrameSP (frame_sp);
2651                 }
2652             }
2653         }
2654     }
2655 }
2656 
2657 void
2658 CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2659 {
2660     DumpHistory (stream, 0, count - 1);
2661 }
2662 
2663 void
2664 CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2665 {
2666     const size_t last_idx = std::min<size_t>(m_command_history.size(), end + 1);
2667     for (size_t i = start; i < last_idx; i++)
2668     {
2669         if (!m_command_history[i].empty())
2670         {
2671             stream.Indent();
2672             stream.Printf ("%4zu: %s\n", i, m_command_history[i].c_str());
2673         }
2674     }
2675 }
2676 
2677 const char *
2678 CommandInterpreter::FindHistoryString (const char *input_str) const
2679 {
2680     if (input_str[0] != m_repeat_char)
2681         return NULL;
2682     if (input_str[1] == '-')
2683     {
2684         bool success;
2685         uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
2686         if (!success)
2687             return NULL;
2688         if (idx > m_command_history.size())
2689             return NULL;
2690         idx = m_command_history.size() - idx;
2691         return m_command_history[idx].c_str();
2692 
2693     }
2694     else if (input_str[1] == m_repeat_char)
2695     {
2696         if (m_command_history.empty())
2697             return NULL;
2698         else
2699             return m_command_history.back().c_str();
2700     }
2701     else
2702     {
2703         bool success;
2704         uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2705         if (!success)
2706             return NULL;
2707         if (idx >= m_command_history.size())
2708             return NULL;
2709         return m_command_history[idx].c_str();
2710     }
2711 }
2712