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