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