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