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