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