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