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