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