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