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