blob: 16e5f3b75afed10d759333b703bc43b0e4a0ac01 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- 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>
Caroline Ticebd5c63e2010-10-12 21:57:09 +000011#include <vector>
Chris Lattner24943d22010-06-08 16:52:24 +000012
13#include <getopt.h>
14#include <stdlib.h>
15
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000016#include "../Commands/CommandObjectApropos.h"
17#include "../Commands/CommandObjectArgs.h"
18#include "../Commands/CommandObjectBreakpoint.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000019//#include "../Commands/CommandObjectCall.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000020#include "../Commands/CommandObjectDisassemble.h"
21#include "../Commands/CommandObjectExpression.h"
Greg Claytonabe0fed2011-04-18 08:33:37 +000022//#include "../Commands/CommandObjectFile.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000023#include "../Commands/CommandObjectFrame.h"
24#include "../Commands/CommandObjectHelp.h"
25#include "../Commands/CommandObjectImage.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000026#include "../Commands/CommandObjectLog.h"
27#include "../Commands/CommandObjectMemory.h"
Greg Claytonb1888f22011-03-19 01:12:21 +000028#include "../Commands/CommandObjectPlatform.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000029#include "../Commands/CommandObjectProcess.h"
30#include "../Commands/CommandObjectQuit.h"
Eli Friedmanb34d2a22010-06-09 22:08:29 +000031#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000032#include "../Commands/CommandObjectRegister.h"
Chris Lattner24943d22010-06-08 16:52:24 +000033#include "CommandObjectScript.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000034#include "../Commands/CommandObjectSettings.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000035#include "../Commands/CommandObjectSource.h"
Jim Ingham767af882010-07-07 03:36:20 +000036#include "../Commands/CommandObjectCommands.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000037#include "../Commands/CommandObjectSyntax.h"
38#include "../Commands/CommandObjectTarget.h"
39#include "../Commands/CommandObjectThread.h"
Johnny Chen902e0182010-12-23 20:21:44 +000040#include "../Commands/CommandObjectVersion.h"
Chris Lattner24943d22010-06-08 16:52:24 +000041
Jim Ingham84cdc152010-06-15 19:49:27 +000042#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000043#include "lldb/Core/Debugger.h"
Jim Ingham5e16ef52010-10-04 19:49:29 +000044#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000045#include "lldb/Core/Stream.h"
46#include "lldb/Core/Timer.h"
Greg Claytoncd548032011-02-01 01:31:41 +000047#include "lldb/Host/Host.h"
Chris Lattner24943d22010-06-08 16:52:24 +000048#include "lldb/Target/Process.h"
49#include "lldb/Target/Thread.h"
50#include "lldb/Target/TargetList.h"
Greg Claytone98ac252010-11-10 04:57:04 +000051#include "lldb/Utility/CleanUp.h"
Chris Lattner24943d22010-06-08 16:52:24 +000052
53#include "lldb/Interpreter/CommandReturnObject.h"
54#include "lldb/Interpreter/CommandInterpreter.h"
Caroline Tice0aa2e552011-01-14 00:29:16 +000055#include "lldb/Interpreter/ScriptInterpreterNone.h"
56#include "lldb/Interpreter/ScriptInterpreterPython.h"
Chris Lattner24943d22010-06-08 16:52:24 +000057
58using namespace lldb;
59using namespace lldb_private;
60
61CommandInterpreter::CommandInterpreter
62(
Greg Clayton63094e02010-06-23 01:19:29 +000063 Debugger &debugger,
Chris Lattner24943d22010-06-08 16:52:24 +000064 ScriptLanguage script_language,
Greg Clayton63094e02010-06-23 01:19:29 +000065 bool synchronous_execution
Chris Lattner24943d22010-06-08 16:52:24 +000066) :
Greg Clayton49ce6822010-10-31 03:01:06 +000067 Broadcaster ("lldb.command-interpreter"),
Greg Clayton63094e02010-06-23 01:19:29 +000068 m_debugger (debugger),
Greg Clayton887aa282010-10-11 01:05:37 +000069 m_synchronous_execution (synchronous_execution),
Caroline Tice0aa2e552011-01-14 00:29:16 +000070 m_skip_lldbinit_files (false),
Jim Ingham949d5ac2011-02-18 00:54:25 +000071 m_script_interpreter_ap (),
72 m_comment_char ('#')
Chris Lattner24943d22010-06-08 16:52:24 +000073{
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000074 const char *dbg_name = debugger.GetInstanceName().AsCString();
75 std::string lang_name = ScriptInterpreter::LanguageToString (script_language);
76 StreamString var_name;
77 var_name.Printf ("[%s].script-lang", dbg_name);
Caroline Tice1d2aefd2010-09-09 06:25:08 +000078 debugger.GetSettingsController()->SetVariable (var_name.GetData(), lang_name.c_str(),
Greg Claytonb3448432011-03-24 21:19:54 +000079 eVarSetOperationAssign, false,
Greg Clayton49ce6822010-10-31 03:01:06 +000080 m_debugger.GetInstanceName().AsCString());
81 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
82 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
83 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Chris Lattner24943d22010-06-08 16:52:24 +000084}
85
86void
87CommandInterpreter::Initialize ()
88{
89 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
90
91 CommandReturnObject result;
92
93 LoadCommandDictionary ();
94
Chris Lattner24943d22010-06-08 16:52:24 +000095 // Set up some initial aliases.
Greg Claytonaa378b12011-02-20 02:15:07 +000096 HandleCommand ("command alias q quit", false, result);
97 HandleCommand ("command alias run process launch --", false, result);
98 HandleCommand ("command alias r process launch --", false, result);
99 HandleCommand ("command alias c process continue", false, result);
100 HandleCommand ("command alias continue process continue", false, result);
101 HandleCommand ("command alias expr expression", false, result);
102 HandleCommand ("command alias exit quit", false, result);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000103 HandleCommand ("command alias b _regexp-break", false, result);
Greg Claytonaa378b12011-02-20 02:15:07 +0000104 HandleCommand ("command alias bt thread backtrace", false, result);
105 HandleCommand ("command alias si thread step-inst", false, result);
106 HandleCommand ("command alias step thread step-in", false, result);
107 HandleCommand ("command alias s thread step-in", false, result);
108 HandleCommand ("command alias next thread step-over", false, result);
109 HandleCommand ("command alias n thread step-over", false, result);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000110 HandleCommand ("command alias f thread step-out", false, result);
Greg Claytonaa378b12011-02-20 02:15:07 +0000111 HandleCommand ("command alias finish thread step-out", false, result);
112 HandleCommand ("command alias x memory read", false, result);
113 HandleCommand ("command alias l source list", false, result);
114 HandleCommand ("command alias list source list", false, result);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000115 HandleCommand ("command alias p expression --", false, result);
Jim Ingham15f2d432011-03-24 18:23:12 +0000116 HandleCommand ("command alias print expression --", false, result);
Greg Claytonaa378b12011-02-20 02:15:07 +0000117 HandleCommand ("command alias po expression -o --", false, result);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000118 HandleCommand ("command alias up _regexp-up", false, result);
119 HandleCommand ("command alias down _regexp-down", false, result);
Greg Claytonabe0fed2011-04-18 08:33:37 +0000120 HandleCommand ("command alias file target create", false, result);
Jim Inghame56493f2011-03-22 02:29:32 +0000121
Chris Lattner24943d22010-06-08 16:52:24 +0000122}
123
Chris Lattner24943d22010-06-08 16:52:24 +0000124const char *
125CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
126{
127 // This function has not yet been implemented.
128
129 // Look for any embedded script command
130 // If found,
131 // get interpreter object from the command dictionary,
132 // call execute_one_command on it,
133 // get the results as a string,
134 // substitute that string for current stuff.
135
136 return arg;
137}
138
139
140void
141CommandInterpreter::LoadCommandDictionary ()
142{
143 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
144
145 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
146 //
147 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
148 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
149 // the cross-referencing stuff) are created!!!
150 //
151 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
152
153
154 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
155 // are created. This is so that when another command is created that needs to go into a crossref object,
156 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
157 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
158
Chris Lattner24943d22010-06-08 16:52:24 +0000159 // Non-CommandObjectCrossref commands can now be created.
160
Caroline Tice5bc8c972010-09-20 20:44:43 +0000161 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000162
Greg Clayton238c0a12010-09-18 01:14:36 +0000163 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000164 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000165 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000166 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000167 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
168 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Claytonabe0fed2011-04-18 08:33:37 +0000169// m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000170 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000171 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000172 m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
173 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
174 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonb1888f22011-03-19 01:12:21 +0000175 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000176 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000177 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000178 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000179 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000180 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000181 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000182 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
183 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000184 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000185
186 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000187 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000188 "_regexp-break",
Caroline Ticec1ad82e2010-09-07 22:38:08 +0000189 "Set a breakpoint using a regular expression to specify the location.",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000190 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000191 if (break_regex_cmd_ap.get())
192 {
193 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
194 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
195 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
Greg Claytonb72d0f02011-04-12 05:54:46 +0000196 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000197 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
Greg Claytonb01000f2011-01-17 03:46:26 +0000198 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000199 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
200 {
201 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
202 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
203 }
204 }
Jim Inghame56493f2011-03-22 02:29:32 +0000205
206 std::auto_ptr<CommandObjectRegexCommand>
207 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000208 "_regexp-down",
209 "Go down \"n\" frames in the stack (1 frame by default).",
210 "_regexp-down [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000211 if (down_regex_cmd_ap.get())
212 {
213 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
214 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
215 {
216 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
217 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
218 }
219 }
220
221 std::auto_ptr<CommandObjectRegexCommand>
222 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000223 "_regexp-up",
224 "Go up \"n\" frames in the stack (1 frame by default).",
225 "_regexp-up [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000226 if (up_regex_cmd_ap.get())
227 {
228 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
229 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
230 {
231 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
232 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
233 }
234 }
Chris Lattner24943d22010-06-08 16:52:24 +0000235}
236
237int
238CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
239 StringList &matches)
240{
241 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
242
243 if (include_aliases)
244 {
245 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
246 }
247
248 return matches.GetSize();
249}
250
251CommandObjectSP
252CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
253{
254 CommandObject::CommandMap::iterator pos;
255 CommandObjectSP ret_val;
256
257 std::string cmd(cmd_cstr);
258
259 if (HasCommands())
260 {
261 pos = m_command_dict.find(cmd);
262 if (pos != m_command_dict.end())
263 ret_val = pos->second;
264 }
265
266 if (include_aliases && HasAliases())
267 {
268 pos = m_alias_dict.find(cmd);
269 if (pos != m_alias_dict.end())
270 ret_val = pos->second;
271 }
272
273 if (HasUserCommands())
274 {
275 pos = m_user_dict.find(cmd);
276 if (pos != m_user_dict.end())
277 ret_val = pos->second;
278 }
279
280 if (!exact && ret_val == NULL)
281 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000282 // We will only get into here if we didn't find any exact matches.
283
284 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
285
Chris Lattner24943d22010-06-08 16:52:24 +0000286 StringList local_matches;
287 if (matches == NULL)
288 matches = &local_matches;
289
Jim Inghamd40f8a62010-07-06 22:46:59 +0000290 unsigned int num_cmd_matches = 0;
291 unsigned int num_alias_matches = 0;
292 unsigned int num_user_matches = 0;
293
294 // Look through the command dictionaries one by one, and if we get only one match from any of
295 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
296
Chris Lattner24943d22010-06-08 16:52:24 +0000297 if (HasCommands())
298 {
299 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
300 }
301
302 if (num_cmd_matches == 1)
303 {
304 cmd.assign(matches->GetStringAtIndex(0));
305 pos = m_command_dict.find(cmd);
306 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000307 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000308 }
309
Jim Ingham9a574172010-06-24 20:28:42 +0000310 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000311 {
312 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
313
314 }
315
Jim Inghamd40f8a62010-07-06 22:46:59 +0000316 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000317 {
318 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
319 pos = m_alias_dict.find(cmd);
320 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000321 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000322 }
323
Jim Ingham9a574172010-06-24 20:28:42 +0000324 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000325 {
326 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
327 }
328
Jim Inghamd40f8a62010-07-06 22:46:59 +0000329 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000330 {
331 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
332
333 pos = m_user_dict.find (cmd);
334 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000335 user_match_sp = pos->second;
336 }
337
338 // If we got exactly one match, return that, otherwise return the match list.
339
340 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
341 {
342 if (num_cmd_matches)
343 return real_match_sp;
344 else if (num_alias_matches)
345 return alias_match_sp;
346 else
347 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000348 }
349 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000350 else if (matches && ret_val != NULL)
351 {
352 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000353 }
354
355
356 return ret_val;
357}
358
Greg Claytond12aeab2011-04-20 16:37:46 +0000359bool
360CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
361{
362 if (name && name[0])
363 {
364 std::string name_sstr(name);
365 if (!can_replace)
366 {
367 if (m_command_dict.find (name_sstr) != m_command_dict.end())
368 return false;
369 }
370 m_command_dict[name_sstr] = cmd_sp;
371 return true;
372 }
373 return false;
374}
375
376
Jim Inghamd40f8a62010-07-06 22:46:59 +0000377CommandObjectSP
378CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000379{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000380 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
381 CommandObjectSP ret_val; // Possibly empty return value.
382
383 if (cmd_cstr == NULL)
384 return ret_val;
385
386 if (cmd_words.GetArgumentCount() == 1)
387 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
388 else
389 {
390 // We have a multi-word command (seemingly), so we need to do more work.
391 // First, get the cmd_obj_sp for the first word in the command.
392 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
393 if (cmd_obj_sp.get() != NULL)
394 {
395 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
396 // command name), and find the appropriate sub-command SP for each command word....
397 size_t end = cmd_words.GetArgumentCount();
398 for (size_t j= 1; j < end; ++j)
399 {
400 if (cmd_obj_sp->IsMultiwordObject())
401 {
402 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
403 (cmd_words.GetArgumentAtIndex (j));
404 if (cmd_obj_sp.get() == NULL)
405 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
406 return ret_val;
407 }
408 else
409 // We have more words in the command name, but we don't have a multiword object. Fail and return
410 // empty 'ret_val'.
411 return ret_val;
412 }
413 // We successfully looped through all the command words and got valid command objects for them. Assign the
414 // last object retrieved to 'ret_val'.
415 ret_val = cmd_obj_sp;
416 }
417 }
418 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000419}
420
421CommandObject *
422CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
423{
424 return GetCommandSPExact (cmd_cstr, include_aliases).get();
425}
426
427CommandObject *
428CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
429{
430 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
431
432 // If we didn't find an exact match to the command string in the commands, look in
433 // the aliases.
434
435 if (command_obj == NULL)
436 {
437 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
438 }
439
440 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
441 // in both the commands and the aliases.
442
443 if (command_obj == NULL)
444 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
445
446 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000447}
448
449bool
450CommandInterpreter::CommandExists (const char *cmd)
451{
452 return m_command_dict.find(cmd) != m_command_dict.end();
453}
454
455bool
456CommandInterpreter::AliasExists (const char *cmd)
457{
458 return m_alias_dict.find(cmd) != m_alias_dict.end();
459}
460
461bool
462CommandInterpreter::UserCommandExists (const char *cmd)
463{
464 return m_user_dict.find(cmd) != m_user_dict.end();
465}
466
467void
468CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
469{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000470 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000471 m_alias_dict[alias_name] = command_obj_sp;
472}
473
474bool
475CommandInterpreter::RemoveAlias (const char *alias_name)
476{
477 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
478 if (pos != m_alias_dict.end())
479 {
480 m_alias_dict.erase(pos);
481 return true;
482 }
483 return false;
484}
485bool
486CommandInterpreter::RemoveUser (const char *alias_name)
487{
488 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
489 if (pos != m_user_dict.end())
490 {
491 m_user_dict.erase(pos);
492 return true;
493 }
494 return false;
495}
496
Chris Lattner24943d22010-06-08 16:52:24 +0000497void
498CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
499{
500 help_string.Printf ("'%s", command_name);
501 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
502
503 if (option_arg_vector_sp != NULL)
504 {
505 OptionArgVector *options = option_arg_vector_sp.get();
506 for (int i = 0; i < options->size(); ++i)
507 {
508 OptionArgPair cur_option = (*options)[i];
509 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000510 OptionArgValue value_pair = cur_option.second;
511 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000512 if (opt.compare("<argument>") == 0)
513 {
514 help_string.Printf (" %s", value.c_str());
515 }
516 else
517 {
518 help_string.Printf (" %s", opt.c_str());
519 if ((value.compare ("<no-argument>") != 0)
520 && (value.compare ("<need-argument") != 0))
521 {
522 help_string.Printf (" %s", value.c_str());
523 }
524 }
525 }
526 }
527
528 help_string.Printf ("'");
529}
530
Greg Clayton65124ea2010-08-26 22:05:43 +0000531size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000532CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
533{
534 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000535 CommandObject::CommandMap::const_iterator end = dict.end();
536 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000537
Greg Clayton65124ea2010-08-26 22:05:43 +0000538 for (pos = dict.begin(); pos != end; ++pos)
539 {
540 size_t len = pos->first.size();
541 if (max_len < len)
542 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000543 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000544 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000545}
546
547void
548CommandInterpreter::GetHelp (CommandReturnObject &result)
549{
550 CommandObject::CommandMap::const_iterator pos;
551 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
552 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000553 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000554
555 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
556 {
557 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
558 max_len);
559 }
560 result.AppendMessage("");
561
562 if (m_alias_dict.size() > 0)
563 {
Jim Inghame3663e82010-10-22 18:47:16 +0000564 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000565 "(see 'help command alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000566 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000567 max_len = FindLongestCommandWord (m_alias_dict);
568
Chris Lattner24943d22010-06-08 16:52:24 +0000569 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
570 {
571 StreamString sstr;
572 StreamString translation_and_help;
573 std::string entry_name = pos->first;
574 std::string second_entry = pos->second.get()->GetCommandName();
575 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
576
577 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
578 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
579 translation_and_help.GetData(), max_len);
580 }
581 result.AppendMessage("");
582 }
583
584 if (m_user_dict.size() > 0)
585 {
586 result.AppendMessage ("The following is a list of your current user-defined commands:");
587 result.AppendMessage("");
588 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
589 {
590 result.AppendMessageWithFormat ("%s -- %s\n", pos->first.c_str(), pos->second->GetHelp());
591 }
592 result.AppendMessage("");
593 }
594
595 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
596}
597
Caroline Ticee0da7a52010-12-09 22:52:49 +0000598CommandObject *
599CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000600{
Caroline Ticee0da7a52010-12-09 22:52:49 +0000601 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
602 // eventually be invoked by the given command line.
603
604 CommandObject *cmd_obj = NULL;
605 std::string white_space (" \t\v");
606 size_t start = command_string.find_first_not_of (white_space);
607 size_t end = 0;
608 bool done = false;
609 while (!done)
610 {
611 if (start != std::string::npos)
612 {
613 // Get the next word from command_string.
614 end = command_string.find_first_of (white_space, start);
615 if (end == std::string::npos)
616 end = command_string.size();
617 std::string cmd_word = command_string.substr (start, end - start);
618
619 if (cmd_obj == NULL)
620 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
621 // command or alias.
622 cmd_obj = GetCommandObject (cmd_word.c_str());
623 else if (cmd_obj->IsMultiwordObject ())
624 {
625 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
626 CommandObject *sub_cmd_obj =
627 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
628 if (sub_cmd_obj)
629 cmd_obj = sub_cmd_obj;
630 else // cmd_word was not a valid sub-command word, so we are donee
631 done = true;
632 }
633 else
634 // We have a cmd_obj and it is not a multi-word object, so we are done.
635 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000636
Caroline Ticee0da7a52010-12-09 22:52:49 +0000637 // If we didn't find a valid command object, or our command object is not a multi-word object, or
638 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
639 // next word.
640
641 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
642 done = true;
643 else
644 start = command_string.find_first_not_of (white_space, end);
645 }
646 else
647 // Unable to find any more words.
648 done = true;
649 }
650
651 if (end == command_string.size())
652 command_string.clear();
653 else
654 command_string = command_string.substr(end);
655
656 return cmd_obj;
657}
658
659bool
660CommandInterpreter::StripFirstWord (std::string &command_string, std::string &word)
661{
662 std::string white_space (" \t\v");
663 size_t start;
664 size_t end;
665
666 start = command_string.find_first_not_of (white_space);
667 if (start != std::string::npos)
668 {
669 end = command_string.find_first_of (white_space, start);
670 if (end != std::string::npos)
671 {
672 word = command_string.substr (start, end - start);
673 command_string = command_string.substr (end);
674 size_t pos = command_string.find_first_not_of (white_space);
675 if ((pos != 0) && (pos != std::string::npos))
676 command_string = command_string.substr (pos);
677 }
678 else
679 {
680 word = command_string.substr (start);
681 command_string.erase();
682 }
683
684 }
685 return true;
686}
687
688void
689CommandInterpreter::BuildAliasResult (const char *alias_name, std::string &raw_input_string, std::string &alias_result,
690 CommandObject *&alias_cmd_obj, CommandReturnObject &result)
691{
692 Args cmd_args (raw_input_string.c_str());
693 alias_cmd_obj = GetCommandObject (alias_name);
694 StreamString result_str;
695
696 if (alias_cmd_obj)
697 {
698 std::string alias_name_str = alias_name;
699 if ((cmd_args.GetArgumentCount() == 0)
700 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
701 cmd_args.Unshift (alias_name);
702
703 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
704 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
705
706 if (option_arg_vector_sp.get())
707 {
708 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
709
710 for (int i = 0; i < option_arg_vector->size(); ++i)
711 {
712 OptionArgPair option_pair = (*option_arg_vector)[i];
713 OptionArgValue value_pair = option_pair.second;
714 int value_type = value_pair.first;
715 std::string option = option_pair.first;
716 std::string value = value_pair.second;
717 if (option.compare ("<argument>") == 0)
718 result_str.Printf (" %s", value.c_str());
719 else
720 {
721 result_str.Printf (" %s", option.c_str());
722 if (value_type != optional_argument)
723 result_str.Printf (" ");
724 if (value.compare ("<no_argument>") != 0)
725 {
726 int index = GetOptionArgumentPosition (value.c_str());
727 if (index == 0)
728 result_str.Printf ("%s", value.c_str());
729 else if (index >= cmd_args.GetArgumentCount())
730 {
731
732 result.AppendErrorWithFormat
733 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
734 index);
735 result.SetStatus (eReturnStatusFailed);
736 return;
737 }
738 else
739 {
740 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
741 if (strpos != std::string::npos)
742 raw_input_string = raw_input_string.erase (strpos,
743 strlen (cmd_args.GetArgumentAtIndex (index)));
744 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
745 }
746 }
747 }
748 }
749 }
750
751 alias_result = result_str.GetData();
752 }
753}
754
755bool
756CommandInterpreter::HandleCommand (const char *command_line,
757 bool add_to_history,
758 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +0000759 ExecutionContext *override_context,
760 bool repeat_on_empty_command)
761
Caroline Ticee0da7a52010-12-09 22:52:49 +0000762{
Jim Ingham949d5ac2011-02-18 00:54:25 +0000763
Caroline Ticee0da7a52010-12-09 22:52:49 +0000764 bool done = false;
765 CommandObject *cmd_obj = NULL;
766 std::string next_word;
767 bool wants_raw_input = false;
768 std::string command_string (command_line);
769
770 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +0000771 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
772
773 // Make a scoped cleanup object that will clear the crash description string
774 // on exit of this function.
775 lldb_utility::CleanUp <const char *, void> crash_description_cleanup(NULL, Host::SetCrashDescription);
776
Caroline Ticee0da7a52010-12-09 22:52:49 +0000777 if (log)
778 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +0000779
Jim Inghamabab14b2010-11-04 23:08:45 +0000780 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
781
Greg Claytonb72d0f02011-04-12 05:54:46 +0000782 UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +0000783
Jim Ingham949d5ac2011-02-18 00:54:25 +0000784 bool empty_command = false;
785 bool comment_command = false;
786 if (command_string.empty())
787 empty_command = true;
788 else
Chris Lattner24943d22010-06-08 16:52:24 +0000789 {
Jim Ingham949d5ac2011-02-18 00:54:25 +0000790 const char *k_space_characters = "\t\n\v\f\r ";
791
792 size_t non_space = command_string.find_first_not_of (k_space_characters);
793 // Check for empty line or comment line (lines whose first
794 // non-space character is the comment character for this interpreter)
795 if (non_space == std::string::npos)
796 empty_command = true;
797 else if (command_string[non_space] == m_comment_char)
798 comment_command = true;
799 }
800
801 if (empty_command)
802 {
803 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +0000804 {
Jim Ingham949d5ac2011-02-18 00:54:25 +0000805 if (m_command_history.empty())
806 {
807 result.AppendError ("empty command");
808 result.SetStatus(eReturnStatusFailed);
809 return false;
810 }
811 else
812 {
813 command_line = m_repeat_command.c_str();
814 command_string = command_line;
815 if (m_repeat_command.empty())
816 {
817 result.AppendErrorWithFormat("No auto repeat.\n");
818 result.SetStatus (eReturnStatusFailed);
819 return false;
820 }
821 }
822 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000823 }
824 else
825 {
Jim Ingham949d5ac2011-02-18 00:54:25 +0000826 result.SetStatus (eReturnStatusSuccessFinishNoResult);
827 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000828 }
Jim Ingham949d5ac2011-02-18 00:54:25 +0000829 }
830 else if (comment_command)
831 {
832 result.SetStatus (eReturnStatusSuccessFinishNoResult);
833 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000834 }
835
Caroline Ticee0da7a52010-12-09 22:52:49 +0000836 // Phase 1.
837
838 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
839 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
840 // the user could have specified an alias, and in translating the alias there may also be command options and/or
841 // even data (including raw text strings) that need to be found and inserted into the command line as part of
842 // the translation. So this first step is plain look-up & replacement, resulting in three things: 1). the command
Greg Clayton5d187e52011-01-08 20:28:42 +0000843 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +0000844 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +0000845
Caroline Ticee0da7a52010-12-09 22:52:49 +0000846 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000847 size_t actual_cmd_name_len = 0;
Caroline Ticee0da7a52010-12-09 22:52:49 +0000848 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +0000849 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000850 StripFirstWord (command_string, next_word);
851 if (!cmd_obj && AliasExists (next_word.c_str()))
Chris Lattner24943d22010-06-08 16:52:24 +0000852 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000853 std::string alias_result;
854 BuildAliasResult (next_word.c_str(), command_string, alias_result, cmd_obj, result);
855 revised_command_line.Printf ("%s", alias_result.c_str());
856 if (cmd_obj)
Caroline Tice56d2fc42010-12-14 18:51:39 +0000857 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000858 wants_raw_input = cmd_obj->WantsRawCommandString ();
Caroline Tice56d2fc42010-12-14 18:51:39 +0000859 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
860 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000861 }
862 else if (!cmd_obj)
863 {
864 cmd_obj = GetCommandObject (next_word.c_str());
865 if (cmd_obj)
Chris Lattner24943d22010-06-08 16:52:24 +0000866 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000867 actual_cmd_name_len += next_word.length();
Caroline Ticee0da7a52010-12-09 22:52:49 +0000868 revised_command_line.Printf ("%s", next_word.c_str());
869 wants_raw_input = cmd_obj->WantsRawCommandString ();
Chris Lattner24943d22010-06-08 16:52:24 +0000870 }
871 else
872 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000873 revised_command_line.Printf ("%s", next_word.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000874 }
875 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000876 else if (cmd_obj->IsMultiwordObject ())
877 {
878 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
879 if (sub_cmd_obj)
880 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000881 actual_cmd_name_len += next_word.length() + 1;
Caroline Ticee0da7a52010-12-09 22:52:49 +0000882 revised_command_line.Printf (" %s", next_word.c_str());
883 cmd_obj = sub_cmd_obj;
884 wants_raw_input = cmd_obj->WantsRawCommandString ();
885 }
886 else
887 {
888 revised_command_line.Printf (" %s", next_word.c_str());
889 done = true;
890 }
891 }
892 else
893 {
894 revised_command_line.Printf (" %s", next_word.c_str());
895 done = true;
896 }
897
898 if (cmd_obj == NULL)
899 {
900 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
901 result.SetStatus (eReturnStatusFailed);
902 return false;
903 }
904
905 next_word.erase ();
906 if (command_string.length() == 0)
907 done = true;
908
Chris Lattner24943d22010-06-08 16:52:24 +0000909 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000910
911 if (command_string.size() > 0)
912 revised_command_line.Printf (" %s", command_string.c_str());
913
914 // End of Phase 1.
915 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
916 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
917 // fully translated with all substitutions & translations taken care of (still in raw text format); and
918 // wants_raw_input specifies whether the Execute method expects raw input or not.
919
920
921 if (log)
922 {
923 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
924 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
925 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
926 }
927
928 // Phase 2.
929 // Take care of things like setting up the history command & calling the appropriate Execute method on the
930 // CommandObject, with the appropriate arguments.
931
932 if (cmd_obj != NULL)
933 {
934 if (add_to_history)
935 {
936 Args command_args (revised_command_line.GetData());
937 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
938 if (repeat_command != NULL)
939 m_repeat_command.assign(repeat_command);
940 else
941 m_repeat_command.assign(command_line);
942
943 m_command_history.push_back (command_line);
944 }
945
946 command_string = revised_command_line.GetData();
947 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000948 std::string remainder;
949 if (actual_cmd_name_len < command_string.length())
950 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
951 // than cmd_obj->GetCommandName(), because name completion
952 // allows users to enter short versions of the names,
953 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +0000954
955 // Remove any initial spaces
956 std::string white_space (" \t\v");
957 size_t pos = remainder.find_first_not_of (white_space);
958 if (pos != 0 && pos != std::string::npos)
Greg Clayton91c9dcf2011-04-22 20:58:45 +0000959 remainder.erase(0, pos);
Caroline Ticee0da7a52010-12-09 22:52:49 +0000960
961 if (log)
962 log->Printf ("HandleCommand, command line after removing command name(s): '%s'\n", remainder.c_str());
963
964
965 if (wants_raw_input)
966 cmd_obj->ExecuteRawCommandString (remainder.c_str(), result);
967 else
968 {
969 Args cmd_args (remainder.c_str());
970 cmd_obj->ExecuteWithOptions (cmd_args, result);
971 }
972 }
973 else
974 {
975 // We didn't find the first command object, so complete the first argument.
976 Args command_args (revised_command_line.GetData());
977 StringList matches;
978 int num_matches;
979 int cursor_index = 0;
980 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
981 bool word_complete;
982 num_matches = HandleCompletionMatches (command_args,
983 cursor_index,
984 cursor_char_position,
985 0,
986 -1,
987 word_complete,
988 matches);
989
990 if (num_matches > 0)
991 {
992 std::string error_msg;
993 error_msg.assign ("ambiguous command '");
994 error_msg.append(command_args.GetArgumentAtIndex(0));
995 error_msg.append ("'.");
996
997 error_msg.append (" Possible completions:");
998 for (int i = 0; i < num_matches; i++)
999 {
1000 error_msg.append ("\n\t");
1001 error_msg.append (matches.GetStringAtIndex (i));
1002 }
1003 error_msg.append ("\n");
1004 result.AppendRawError (error_msg.c_str(), error_msg.size());
1005 }
1006 else
1007 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1008
1009 result.SetStatus (eReturnStatusFailed);
1010 }
1011
Chris Lattner24943d22010-06-08 16:52:24 +00001012 return result.Succeeded();
1013}
1014
1015int
1016CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1017 int &cursor_index,
1018 int &cursor_char_position,
1019 int match_start_point,
1020 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001021 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001022 StringList &matches)
1023{
1024 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001025 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001026
1027 // For any of the command completions a unique match will be a complete word.
1028 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001029
1030 if (cursor_index == -1)
1031 {
1032 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001033 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001034 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1035 }
1036 else if (cursor_index == 0)
1037 {
1038 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001039 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001040 num_command_matches = matches.GetSize();
1041
1042 if (num_command_matches == 1
1043 && cmd_obj && cmd_obj->IsMultiwordObject()
1044 && matches.GetStringAtIndex(0) != NULL
1045 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1046 {
1047 look_for_subcommand = true;
1048 num_command_matches = 0;
1049 matches.DeleteStringAtIndex(0);
1050 parsed_line.AppendArgument ("");
1051 cursor_index++;
1052 cursor_char_position = 0;
1053 }
1054 }
1055
1056 if (cursor_index > 0 || look_for_subcommand)
1057 {
1058 // We are completing further on into a commands arguments, so find the command and tell it
1059 // to complete the command.
1060 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001061 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001062 if (command_object == NULL)
1063 {
1064 return 0;
1065 }
1066 else
1067 {
1068 parsed_line.Shift();
1069 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001070 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001071 cursor_index,
1072 cursor_char_position,
1073 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001074 max_return_elements,
1075 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001076 matches);
1077 }
1078 }
1079
1080 return num_command_matches;
1081
1082}
1083
1084int
1085CommandInterpreter::HandleCompletion (const char *current_line,
1086 const char *cursor,
1087 const char *last_char,
1088 int match_start_point,
1089 int max_return_elements,
1090 StringList &matches)
1091{
1092 // We parse the argument up to the cursor, so the last argument in parsed_line is
1093 // the one containing the cursor, and the cursor is after the last character.
1094
1095 Args parsed_line(current_line, last_char - current_line);
1096 Args partial_parsed_line(current_line, cursor - current_line);
1097
1098 int num_args = partial_parsed_line.GetArgumentCount();
1099 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1100 int cursor_char_position;
1101
1102 if (cursor_index == -1)
1103 cursor_char_position = 0;
1104 else
1105 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001106
1107 if (cursor > current_line && cursor[-1] == ' ')
1108 {
1109 // We are just after a space. If we are in an argument, then we will continue
1110 // parsing, but if we are between arguments, then we have to complete whatever the next
1111 // element would be.
1112 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1113 // protected by a quote) then the space will also be in the parsed argument...
1114
1115 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1116 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1117 {
1118 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1119 cursor_index++;
1120 cursor_char_position = 0;
1121 }
1122 }
Chris Lattner24943d22010-06-08 16:52:24 +00001123
1124 int num_command_matches;
1125
1126 matches.Clear();
1127
1128 // Only max_return_elements == -1 is supported at present:
1129 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001130 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001131 num_command_matches = HandleCompletionMatches (parsed_line,
1132 cursor_index,
1133 cursor_char_position,
1134 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001135 max_return_elements,
1136 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001137 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001138
1139 if (num_command_matches <= 0)
1140 return num_command_matches;
1141
1142 if (num_args == 0)
1143 {
1144 // If we got an empty string, insert nothing.
1145 matches.InsertStringAtIndex(0, "");
1146 }
1147 else
1148 {
1149 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1150 // put an empty string in element 0.
1151 std::string command_partial_str;
1152 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001153 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1154 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001155
1156 std::string common_prefix;
1157 matches.LongestCommonPrefix (common_prefix);
1158 int partial_name_len = command_partial_str.size();
1159
1160 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001161 // Only do this if the completer told us this was a complete word, however...
1162 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001163 {
1164 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1165 if (quote_char != '\0')
1166 common_prefix.push_back(quote_char);
1167
1168 common_prefix.push_back(' ');
1169 }
1170 common_prefix.erase (0, partial_name_len);
1171 matches.InsertStringAtIndex(0, common_prefix.c_str());
1172 }
1173 return num_command_matches;
1174}
1175
Chris Lattner24943d22010-06-08 16:52:24 +00001176
1177CommandInterpreter::~CommandInterpreter ()
1178{
1179}
1180
1181const char *
1182CommandInterpreter::GetPrompt ()
1183{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001184 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001185}
1186
1187void
1188CommandInterpreter::SetPrompt (const char *new_prompt)
1189{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001190 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001191}
1192
Jim Ingham5e16ef52010-10-04 19:49:29 +00001193size_t
Greg Clayton58928562011-02-09 01:08:52 +00001194CommandInterpreter::GetConfirmationInputReaderCallback
1195(
1196 void *baton,
1197 InputReader &reader,
1198 lldb::InputReaderAction action,
1199 const char *bytes,
1200 size_t bytes_len
1201)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001202{
Greg Clayton58928562011-02-09 01:08:52 +00001203 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001204 bool *response_ptr = (bool *) baton;
1205
1206 switch (action)
1207 {
1208 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001209 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001210 {
1211 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001212 {
Greg Clayton58928562011-02-09 01:08:52 +00001213 out_file.Printf ("%s", reader.GetPrompt());
1214 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001215 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001216 }
1217 break;
1218
1219 case eInputReaderDeactivate:
1220 break;
1221
1222 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001223 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001224 {
Greg Clayton58928562011-02-09 01:08:52 +00001225 out_file.Printf ("%s", reader.GetPrompt());
1226 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001227 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001228 break;
Caroline Tice4a348082011-05-02 20:41:46 +00001229
1230 case eInputReaderAsynchronousOutputWritten:
1231 break;
1232
Jim Ingham5e16ef52010-10-04 19:49:29 +00001233 case eInputReaderGotToken:
1234 if (bytes_len == 0)
1235 {
1236 reader.SetIsDone(true);
1237 }
1238 else if (bytes[0] == 'y')
1239 {
1240 *response_ptr = true;
1241 reader.SetIsDone(true);
1242 }
1243 else if (bytes[0] == 'n')
1244 {
1245 *response_ptr = false;
1246 reader.SetIsDone(true);
1247 }
1248 else
1249 {
Greg Clayton58928562011-02-09 01:08:52 +00001250 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001251 {
Greg Clayton58928562011-02-09 01:08:52 +00001252 out_file.Printf ("Please answer \"y\" or \"n\"\n%s", reader.GetPrompt());
1253 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001254 }
1255 }
1256 break;
1257
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001258 case eInputReaderInterrupt:
1259 case eInputReaderEndOfFile:
1260 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1261 reader.SetIsDone (true);
1262 break;
1263
Jim Ingham5e16ef52010-10-04 19:49:29 +00001264 case eInputReaderDone:
1265 break;
1266 }
1267
1268 return bytes_len;
1269
1270}
1271
1272bool
1273CommandInterpreter::Confirm (const char *message, bool default_answer)
1274{
Jim Ingham93057472010-10-04 22:44:14 +00001275 // Check AutoConfirm first:
1276 if (m_debugger.GetAutoConfirm())
1277 return default_answer;
1278
Jim Ingham5e16ef52010-10-04 19:49:29 +00001279 InputReaderSP reader_sp (new InputReader(GetDebugger()));
1280 bool response = default_answer;
1281 if (reader_sp)
1282 {
1283 std::string prompt(message);
1284 prompt.append(": [");
1285 if (default_answer)
1286 prompt.append ("Y/n] ");
1287 else
1288 prompt.append ("y/N] ");
1289
1290 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1291 &response, // baton
1292 eInputReaderGranularityLine, // token size, to pass to callback function
1293 NULL, // end token
1294 prompt.c_str(), // prompt
1295 true)); // echo input
1296 if (err.Success())
1297 {
1298 GetDebugger().PushInputReader (reader_sp);
1299 }
1300 reader_sp->WaitOnReaderIsDone();
1301 }
1302 return response;
1303}
1304
1305
Chris Lattner24943d22010-06-08 16:52:24 +00001306void
1307CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1308{
Jim Inghamd40f8a62010-07-06 22:46:59 +00001309 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001310
1311 if (cmd_obj_sp != NULL)
1312 {
1313 CommandObject *cmd_obj = cmd_obj_sp.get();
1314 if (cmd_obj->IsCrossRefObject ())
1315 cmd_obj->AddObject (object_type);
1316 }
1317}
1318
Chris Lattner24943d22010-06-08 16:52:24 +00001319OptionArgVectorSP
1320CommandInterpreter::GetAliasOptions (const char *alias_name)
1321{
1322 OptionArgMap::iterator pos;
1323 OptionArgVectorSP ret_val;
1324
1325 std::string alias (alias_name);
1326
1327 if (HasAliasOptions())
1328 {
1329 pos = m_alias_options.find (alias);
1330 if (pos != m_alias_options.end())
1331 ret_val = pos->second;
1332 }
1333
1334 return ret_val;
1335}
1336
1337void
1338CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1339{
1340 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1341 if (pos != m_alias_options.end())
1342 {
1343 m_alias_options.erase (pos);
1344 }
1345}
1346
1347void
1348CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1349{
1350 m_alias_options[alias_name] = option_arg_vector_sp;
1351}
1352
1353bool
1354CommandInterpreter::HasCommands ()
1355{
1356 return (!m_command_dict.empty());
1357}
1358
1359bool
1360CommandInterpreter::HasAliases ()
1361{
1362 return (!m_alias_dict.empty());
1363}
1364
1365bool
1366CommandInterpreter::HasUserCommands ()
1367{
1368 return (!m_user_dict.empty());
1369}
1370
1371bool
1372CommandInterpreter::HasAliasOptions ()
1373{
1374 return (!m_alias_options.empty());
1375}
1376
Chris Lattner24943d22010-06-08 16:52:24 +00001377void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001378CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
1379 const char *alias_name,
1380 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00001381 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001382 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00001383{
1384 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00001385
1386 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00001387
Caroline Tice44c841d2010-12-07 19:58:26 +00001388 // Make sure that the alias name is the 0th element in cmd_args
1389 std::string alias_name_str = alias_name;
1390 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1391 cmd_args.Unshift (alias_name);
1392
1393 Args new_args (alias_cmd_obj->GetCommandName());
1394 if (new_args.GetArgumentCount() == 2)
1395 new_args.Shift();
1396
Chris Lattner24943d22010-06-08 16:52:24 +00001397 if (option_arg_vector_sp.get())
1398 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001399 if (wants_raw_input)
1400 {
1401 // We have a command that both has command options and takes raw input. Make *sure* it has a
1402 // " -- " in the right place in the raw_input_string.
1403 size_t pos = raw_input_string.find(" -- ");
1404 if (pos == std::string::npos)
1405 {
1406 // None found; assume it goes at the beginning of the raw input string
1407 raw_input_string.insert (0, " -- ");
1408 }
1409 }
Chris Lattner24943d22010-06-08 16:52:24 +00001410
1411 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1412 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001413 std::vector<bool> used (old_size + 1, false);
1414
1415 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001416
1417 for (int i = 0; i < option_arg_vector->size(); ++i)
1418 {
1419 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00001420 OptionArgValue value_pair = option_pair.second;
1421 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00001422 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00001423 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00001424 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001425 {
1426 if (!wants_raw_input
1427 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
1428 new_args.AppendArgument (value.c_str());
1429 }
Chris Lattner24943d22010-06-08 16:52:24 +00001430 else
1431 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001432 if (value_type != optional_argument)
1433 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001434 if (value.compare ("<no-argument>") != 0)
1435 {
1436 int index = GetOptionArgumentPosition (value.c_str());
1437 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001438 {
Chris Lattner24943d22010-06-08 16:52:24 +00001439 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00001440 if (value_type != optional_argument)
1441 new_args.AppendArgument (value.c_str());
1442 else
1443 {
1444 char buffer[255];
1445 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
1446 new_args.AppendArgument (buffer);
1447 }
1448
1449 }
Chris Lattner24943d22010-06-08 16:52:24 +00001450 else if (index >= cmd_args.GetArgumentCount())
1451 {
1452 result.AppendErrorWithFormat
1453 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1454 index);
1455 result.SetStatus (eReturnStatusFailed);
1456 return;
1457 }
1458 else
1459 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001460 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
1461 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1462 if (strpos != std::string::npos)
1463 {
1464 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
1465 }
1466
1467 if (value_type != optional_argument)
1468 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
1469 else
1470 {
1471 char buffer[255];
1472 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
1473 cmd_args.GetArgumentAtIndex (index));
1474 new_args.AppendArgument (buffer);
1475 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001476 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001477 }
1478 }
1479 }
1480 }
1481
1482 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1483 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001484 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00001485 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1486 }
1487
1488 cmd_args.Clear();
1489 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1490 }
1491 else
1492 {
1493 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00001494 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
1495 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
1496 // input string.
1497 if (wants_raw_input)
1498 {
1499 cmd_args.Clear();
1500 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1501 }
Chris Lattner24943d22010-06-08 16:52:24 +00001502 return;
1503 }
1504
1505 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1506 return;
1507}
1508
1509
1510int
1511CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1512{
1513 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1514 // of zero.
1515
1516 char *cptr = (char *) in_string;
1517
1518 // Does it start with '%'
1519 if (cptr[0] == '%')
1520 {
1521 ++cptr;
1522
1523 // Is the rest of it entirely digits?
1524 if (isdigit (cptr[0]))
1525 {
1526 const char *start = cptr;
1527 while (isdigit (cptr[0]))
1528 ++cptr;
1529
1530 // We've gotten to the end of the digits; are we at the end of the string?
1531 if (cptr[0] == '\0')
1532 position = atoi (start);
1533 }
1534 }
1535
1536 return position;
1537}
1538
1539void
1540CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1541{
Greg Clayton887aa282010-10-11 01:05:37 +00001542 // Don't parse any .lldbinit files if we were asked not to
1543 if (m_skip_lldbinit_files)
1544 return;
1545
Chris Lattner24943d22010-06-08 16:52:24 +00001546 const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit";
Greg Clayton537a7a82010-10-20 20:54:39 +00001547 FileSpec init_file (init_file_path, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001548 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
1549 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
1550
1551 if (init_file.Exists())
1552 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001553 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
1554 bool stop_on_continue = true;
1555 bool stop_on_error = false;
1556 bool echo_commands = false;
1557 bool print_results = false;
1558
1559 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, result);
Chris Lattner24943d22010-06-08 16:52:24 +00001560 }
1561 else
1562 {
1563 // nothing to be done if the file doesn't exist
1564 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1565 }
1566}
1567
Greg Claytonb72d0f02011-04-12 05:54:46 +00001568PlatformSP
1569CommandInterpreter::GetPlatform (bool prefer_target_platform)
1570{
1571 PlatformSP platform_sp;
1572 if (prefer_target_platform && m_exe_ctx.target)
1573 platform_sp = m_exe_ctx.target->GetPlatform();
1574
1575 if (!platform_sp)
1576 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
1577 return platform_sp;
1578}
1579
Jim Ingham949d5ac2011-02-18 00:54:25 +00001580void
Jim Inghama4fede32011-03-11 01:51:49 +00001581CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001582 ExecutionContext *override_context,
1583 bool stop_on_continue,
1584 bool stop_on_error,
1585 bool echo_commands,
1586 bool print_results,
1587 CommandReturnObject &result)
1588{
1589 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00001590
1591 // If we are going to continue past a "continue" then we need to run the commands synchronously.
1592 // Make sure you reset this value anywhere you return from the function.
1593
1594 bool old_async_execution = m_debugger.GetAsyncExecution();
1595
1596 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
1597 // cause series of commands that change the context, then do an operation that relies on that context to fail.
1598
1599 if (override_context != NULL)
Greg Claytonb72d0f02011-04-12 05:54:46 +00001600 UpdateExecutionContext (override_context);
Jim Ingham949d5ac2011-02-18 00:54:25 +00001601
1602 if (!stop_on_continue)
1603 {
1604 m_debugger.SetAsyncExecution (false);
1605 }
1606
1607 for (int idx = 0; idx < num_lines; idx++)
1608 {
1609 const char *cmd = commands.GetStringAtIndex(idx);
1610 if (cmd[0] == '\0')
1611 continue;
1612
Jim Ingham949d5ac2011-02-18 00:54:25 +00001613 if (echo_commands)
1614 {
1615 result.AppendMessageWithFormat ("%s %s\n",
1616 GetPrompt(),
1617 cmd);
1618 }
1619
Greg Claytonaa378b12011-02-20 02:15:07 +00001620 CommandReturnObject tmp_result;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001621 bool success = HandleCommand(cmd, false, tmp_result, NULL);
1622
1623 if (print_results)
1624 {
1625 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00001626 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00001627 }
1628
1629 if (!success || !tmp_result.Succeeded())
1630 {
1631 if (stop_on_error)
1632 {
1633 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed.\n",
1634 idx, cmd);
1635 result.SetStatus (eReturnStatusFailed);
1636 m_debugger.SetAsyncExecution (old_async_execution);
1637 return;
1638 }
1639 else if (print_results)
1640 {
1641 result.AppendMessageWithFormat ("Command #%d '%s' failed with error: %s.\n",
1642 idx + 1,
1643 cmd,
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00001644 tmp_result.GetErrorData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00001645 }
1646 }
1647
Caroline Tice4a348082011-05-02 20:41:46 +00001648 if (result.GetImmediateOutputStream())
1649 result.GetImmediateOutputStream()->Flush();
1650
1651 if (result.GetImmediateErrorStream())
1652 result.GetImmediateErrorStream()->Flush();
1653
Jim Ingham949d5ac2011-02-18 00:54:25 +00001654 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
1655 // could be running (for instance in Breakpoint Commands.
1656 // So we check the return value to see if it is has running in it.
1657 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
1658 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
1659 {
1660 if (stop_on_continue)
1661 {
1662 // If we caused the target to proceed, and we're going to stop in that case, set the
1663 // status in our real result before returning. This is an error if the continue was not the
1664 // last command in the set of commands to be run.
1665 if (idx != num_lines - 1)
1666 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
1667 idx + 1, cmd);
1668 else
1669 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
1670
1671 result.SetStatus(tmp_result.GetStatus());
1672 m_debugger.SetAsyncExecution (old_async_execution);
1673
1674 return;
1675 }
1676 }
1677
1678 }
1679
1680 result.SetStatus (eReturnStatusSuccessFinishResult);
1681 m_debugger.SetAsyncExecution (old_async_execution);
1682
1683 return;
1684}
1685
1686void
1687CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
1688 ExecutionContext *context,
1689 bool stop_on_continue,
1690 bool stop_on_error,
1691 bool echo_command,
1692 bool print_result,
1693 CommandReturnObject &result)
1694{
1695 if (cmd_file.Exists())
1696 {
1697 bool success;
1698 StringList commands;
1699 success = commands.ReadFileLines(cmd_file);
1700 if (!success)
1701 {
1702 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
1703 result.SetStatus (eReturnStatusFailed);
1704 return;
1705 }
1706 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, result);
1707 }
1708 else
1709 {
1710 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
1711 cmd_file.GetFilename().AsCString());
1712 result.SetStatus (eReturnStatusFailed);
1713 return;
1714 }
1715}
1716
Chris Lattner24943d22010-06-08 16:52:24 +00001717ScriptInterpreter *
1718CommandInterpreter::GetScriptInterpreter ()
1719{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001720 if (m_script_interpreter_ap.get() != NULL)
1721 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00001722
Caroline Tice0aa2e552011-01-14 00:29:16 +00001723 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
1724 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00001725 {
Caroline Tice0aa2e552011-01-14 00:29:16 +00001726 case eScriptLanguageNone:
1727 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
1728 break;
1729 case eScriptLanguagePython:
1730 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
1731 break;
1732 default:
1733 break;
1734 };
1735
1736 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00001737}
1738
1739
1740
1741bool
1742CommandInterpreter::GetSynchronous ()
1743{
1744 return m_synchronous_execution;
1745}
1746
1747void
1748CommandInterpreter::SetSynchronous (bool value)
1749{
Johnny Chend7a4eb02010-10-14 01:22:03 +00001750 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00001751}
1752
1753void
1754CommandInterpreter::OutputFormattedHelpText (Stream &strm,
1755 const char *word_text,
1756 const char *separator,
1757 const char *help_text,
1758 uint32_t max_word_len)
1759{
Greg Clayton238c0a12010-09-18 01:14:36 +00001760 const uint32_t max_columns = m_debugger.GetTerminalWidth();
1761
Chris Lattner24943d22010-06-08 16:52:24 +00001762 int indent_size = max_word_len + strlen (separator) + 2;
1763
1764 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00001765
1766 StreamString text_strm;
1767 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
1768
1769 size_t len = text_strm.GetSize();
1770 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00001771 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00001772 {
1773 text_strm.EOL();
1774 len = text_strm.GetSize();
1775 }
Chris Lattner24943d22010-06-08 16:52:24 +00001776
1777 if (len < max_columns)
1778 {
1779 // Output it as a single line.
1780 strm.Printf ("%s", text);
1781 }
1782 else
1783 {
1784 // We need to break it up into multiple lines.
1785 bool first_line = true;
1786 int text_width;
1787 int start = 0;
1788 int end = start;
1789 int final_end = strlen (text);
1790 int sub_len;
1791
1792 while (end < final_end)
1793 {
1794 if (first_line)
1795 text_width = max_columns - 1;
1796 else
1797 text_width = max_columns - indent_size - 1;
1798
1799 // Don't start the 'text' on a space, since we're already outputting the indentation.
1800 if (!first_line)
1801 {
1802 while ((start < final_end) && (text[start] == ' '))
1803 start++;
1804 }
1805
1806 end = start + text_width;
1807 if (end > final_end)
1808 end = final_end;
1809 else
1810 {
1811 // If we're not at the end of the text, make sure we break the line on white space.
1812 while (end > start
1813 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
1814 end--;
1815 }
1816
1817 sub_len = end - start;
1818 if (start != 0)
1819 strm.EOL();
1820 if (!first_line)
1821 strm.Indent();
1822 else
1823 first_line = false;
1824 assert (start <= final_end);
1825 assert (start + sub_len <= final_end);
1826 if (sub_len > 0)
1827 strm.Write (text + start, sub_len);
1828 start = end + 1;
1829 }
1830 }
1831 strm.EOL();
1832 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001833}
1834
1835void
1836CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
1837 StringList &commands_found, StringList &commands_help)
1838{
1839 CommandObject::CommandMap::const_iterator pos;
1840 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
1841 CommandObject *sub_cmd_obj;
1842
1843 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
1844 {
1845 const char * command_name = pos->first.c_str();
1846 sub_cmd_obj = pos->second.get();
1847 StreamString complete_command_name;
1848
1849 complete_command_name.Printf ("%s %s", prefix, command_name);
1850
Greg Clayton238c0a12010-09-18 01:14:36 +00001851 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001852 {
1853 commands_found.AppendString (complete_command_name.GetData());
1854 commands_help.AppendString (sub_cmd_obj->GetHelp());
1855 }
1856
1857 if (sub_cmd_obj->IsMultiwordObject())
1858 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
1859 commands_help);
1860 }
1861
1862}
1863
1864void
1865CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
1866 StringList &commands_help)
1867{
1868 CommandObject::CommandMap::const_iterator pos;
1869
1870 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1871 {
1872 const char *command_name = pos->first.c_str();
1873 CommandObject *cmd_obj = pos->second.get();
1874
Greg Clayton238c0a12010-09-18 01:14:36 +00001875 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001876 {
1877 commands_found.AppendString (command_name);
1878 commands_help.AppendString (cmd_obj->GetHelp());
1879 }
1880
1881 if (cmd_obj->IsMultiwordObject())
1882 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
1883
1884 }
1885}
Greg Claytonb72d0f02011-04-12 05:54:46 +00001886
1887
1888void
1889CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
1890{
1891 m_exe_ctx.Clear();
1892
1893 if (override_context != NULL)
1894 {
1895 m_exe_ctx.target = override_context->target;
1896 m_exe_ctx.process = override_context->process;
1897 m_exe_ctx.thread = override_context->thread;
1898 m_exe_ctx.frame = override_context->frame;
1899 }
1900 else
1901 {
1902 TargetSP target_sp (m_debugger.GetSelectedTarget());
1903 if (target_sp)
1904 {
1905 m_exe_ctx.target = target_sp.get();
1906 m_exe_ctx.process = target_sp->GetProcessSP().get();
1907 if (m_exe_ctx.process && m_exe_ctx.process->IsAlive() && !m_exe_ctx.process->IsRunning())
1908 {
1909 m_exe_ctx.thread = m_exe_ctx.process->GetThreadList().GetSelectedThread().get();
1910 if (m_exe_ctx.thread == NULL)
1911 {
1912 m_exe_ctx.thread = m_exe_ctx.process->GetThreadList().GetThreadAtIndex(0).get();
1913 // If we didn't have a selected thread, select one here.
1914 if (m_exe_ctx.thread != NULL)
1915 m_exe_ctx.process->GetThreadList().SetSelectedThreadByID(m_exe_ctx.thread->GetID());
1916 }
1917 if (m_exe_ctx.thread)
1918 {
1919 m_exe_ctx.frame = m_exe_ctx.thread->GetSelectedFrame().get();
1920 if (m_exe_ctx.frame == NULL)
1921 {
1922 m_exe_ctx.frame = m_exe_ctx.thread->GetStackFrameAtIndex (0).get();
1923 // If we didn't have a selected frame select one here.
1924 if (m_exe_ctx.frame != NULL)
1925 m_exe_ctx.thread->SetSelectedFrame(m_exe_ctx.frame);
1926 }
1927 }
1928 }
1929 }
1930 }
1931}
1932