blob: 95061523bf4dee1c77514a38dc991879f037d63b [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));
Jim Ingham767af882010-07-07 03:36:20 +0000166 m_command_dict["commands"] = 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
Jim Inghamd40f8a62010-07-06 22:46:59 +0000359CommandObjectSP
360CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000361{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000362 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
363 CommandObjectSP ret_val; // Possibly empty return value.
364
365 if (cmd_cstr == NULL)
366 return ret_val;
367
368 if (cmd_words.GetArgumentCount() == 1)
369 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
370 else
371 {
372 // We have a multi-word command (seemingly), so we need to do more work.
373 // First, get the cmd_obj_sp for the first word in the command.
374 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
375 if (cmd_obj_sp.get() != NULL)
376 {
377 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
378 // command name), and find the appropriate sub-command SP for each command word....
379 size_t end = cmd_words.GetArgumentCount();
380 for (size_t j= 1; j < end; ++j)
381 {
382 if (cmd_obj_sp->IsMultiwordObject())
383 {
384 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
385 (cmd_words.GetArgumentAtIndex (j));
386 if (cmd_obj_sp.get() == NULL)
387 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
388 return ret_val;
389 }
390 else
391 // We have more words in the command name, but we don't have a multiword object. Fail and return
392 // empty 'ret_val'.
393 return ret_val;
394 }
395 // We successfully looped through all the command words and got valid command objects for them. Assign the
396 // last object retrieved to 'ret_val'.
397 ret_val = cmd_obj_sp;
398 }
399 }
400 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000401}
402
403CommandObject *
404CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
405{
406 return GetCommandSPExact (cmd_cstr, include_aliases).get();
407}
408
409CommandObject *
410CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
411{
412 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
413
414 // If we didn't find an exact match to the command string in the commands, look in
415 // the aliases.
416
417 if (command_obj == NULL)
418 {
419 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
420 }
421
422 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
423 // in both the commands and the aliases.
424
425 if (command_obj == NULL)
426 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
427
428 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000429}
430
431bool
432CommandInterpreter::CommandExists (const char *cmd)
433{
434 return m_command_dict.find(cmd) != m_command_dict.end();
435}
436
437bool
438CommandInterpreter::AliasExists (const char *cmd)
439{
440 return m_alias_dict.find(cmd) != m_alias_dict.end();
441}
442
443bool
444CommandInterpreter::UserCommandExists (const char *cmd)
445{
446 return m_user_dict.find(cmd) != m_user_dict.end();
447}
448
449void
450CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
451{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000452 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000453 m_alias_dict[alias_name] = command_obj_sp;
454}
455
456bool
457CommandInterpreter::RemoveAlias (const char *alias_name)
458{
459 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
460 if (pos != m_alias_dict.end())
461 {
462 m_alias_dict.erase(pos);
463 return true;
464 }
465 return false;
466}
467bool
468CommandInterpreter::RemoveUser (const char *alias_name)
469{
470 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
471 if (pos != m_user_dict.end())
472 {
473 m_user_dict.erase(pos);
474 return true;
475 }
476 return false;
477}
478
Chris Lattner24943d22010-06-08 16:52:24 +0000479void
480CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
481{
482 help_string.Printf ("'%s", command_name);
483 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
484
485 if (option_arg_vector_sp != NULL)
486 {
487 OptionArgVector *options = option_arg_vector_sp.get();
488 for (int i = 0; i < options->size(); ++i)
489 {
490 OptionArgPair cur_option = (*options)[i];
491 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000492 OptionArgValue value_pair = cur_option.second;
493 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000494 if (opt.compare("<argument>") == 0)
495 {
496 help_string.Printf (" %s", value.c_str());
497 }
498 else
499 {
500 help_string.Printf (" %s", opt.c_str());
501 if ((value.compare ("<no-argument>") != 0)
502 && (value.compare ("<need-argument") != 0))
503 {
504 help_string.Printf (" %s", value.c_str());
505 }
506 }
507 }
508 }
509
510 help_string.Printf ("'");
511}
512
Greg Clayton65124ea2010-08-26 22:05:43 +0000513size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000514CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
515{
516 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000517 CommandObject::CommandMap::const_iterator end = dict.end();
518 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000519
Greg Clayton65124ea2010-08-26 22:05:43 +0000520 for (pos = dict.begin(); pos != end; ++pos)
521 {
522 size_t len = pos->first.size();
523 if (max_len < len)
524 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000525 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000526 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000527}
528
529void
530CommandInterpreter::GetHelp (CommandReturnObject &result)
531{
532 CommandObject::CommandMap::const_iterator pos;
533 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
534 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000535 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000536
537 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
538 {
539 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
540 max_len);
541 }
542 result.AppendMessage("");
543
544 if (m_alias_dict.size() > 0)
545 {
Jim Inghame3663e82010-10-22 18:47:16 +0000546 result.AppendMessage("The following is a list of your current command abbreviations "
547 "(see 'help commands alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000548 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000549 max_len = FindLongestCommandWord (m_alias_dict);
550
Chris Lattner24943d22010-06-08 16:52:24 +0000551 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
552 {
553 StreamString sstr;
554 StreamString translation_and_help;
555 std::string entry_name = pos->first;
556 std::string second_entry = pos->second.get()->GetCommandName();
557 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
558
559 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
560 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
561 translation_and_help.GetData(), max_len);
562 }
563 result.AppendMessage("");
564 }
565
566 if (m_user_dict.size() > 0)
567 {
568 result.AppendMessage ("The following is a list of your current user-defined commands:");
569 result.AppendMessage("");
570 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
571 {
572 result.AppendMessageWithFormat ("%s -- %s\n", pos->first.c_str(), pos->second->GetHelp());
573 }
574 result.AppendMessage("");
575 }
576
577 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
578}
579
Caroline Ticee0da7a52010-12-09 22:52:49 +0000580CommandObject *
581CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000582{
Caroline Ticee0da7a52010-12-09 22:52:49 +0000583 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
584 // eventually be invoked by the given command line.
585
586 CommandObject *cmd_obj = NULL;
587 std::string white_space (" \t\v");
588 size_t start = command_string.find_first_not_of (white_space);
589 size_t end = 0;
590 bool done = false;
591 while (!done)
592 {
593 if (start != std::string::npos)
594 {
595 // Get the next word from command_string.
596 end = command_string.find_first_of (white_space, start);
597 if (end == std::string::npos)
598 end = command_string.size();
599 std::string cmd_word = command_string.substr (start, end - start);
600
601 if (cmd_obj == NULL)
602 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
603 // command or alias.
604 cmd_obj = GetCommandObject (cmd_word.c_str());
605 else if (cmd_obj->IsMultiwordObject ())
606 {
607 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
608 CommandObject *sub_cmd_obj =
609 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
610 if (sub_cmd_obj)
611 cmd_obj = sub_cmd_obj;
612 else // cmd_word was not a valid sub-command word, so we are donee
613 done = true;
614 }
615 else
616 // We have a cmd_obj and it is not a multi-word object, so we are done.
617 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000618
Caroline Ticee0da7a52010-12-09 22:52:49 +0000619 // If we didn't find a valid command object, or our command object is not a multi-word object, or
620 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
621 // next word.
622
623 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
624 done = true;
625 else
626 start = command_string.find_first_not_of (white_space, end);
627 }
628 else
629 // Unable to find any more words.
630 done = true;
631 }
632
633 if (end == command_string.size())
634 command_string.clear();
635 else
636 command_string = command_string.substr(end);
637
638 return cmd_obj;
639}
640
641bool
642CommandInterpreter::StripFirstWord (std::string &command_string, std::string &word)
643{
644 std::string white_space (" \t\v");
645 size_t start;
646 size_t end;
647
648 start = command_string.find_first_not_of (white_space);
649 if (start != std::string::npos)
650 {
651 end = command_string.find_first_of (white_space, start);
652 if (end != std::string::npos)
653 {
654 word = command_string.substr (start, end - start);
655 command_string = command_string.substr (end);
656 size_t pos = command_string.find_first_not_of (white_space);
657 if ((pos != 0) && (pos != std::string::npos))
658 command_string = command_string.substr (pos);
659 }
660 else
661 {
662 word = command_string.substr (start);
663 command_string.erase();
664 }
665
666 }
667 return true;
668}
669
670void
671CommandInterpreter::BuildAliasResult (const char *alias_name, std::string &raw_input_string, std::string &alias_result,
672 CommandObject *&alias_cmd_obj, CommandReturnObject &result)
673{
674 Args cmd_args (raw_input_string.c_str());
675 alias_cmd_obj = GetCommandObject (alias_name);
676 StreamString result_str;
677
678 if (alias_cmd_obj)
679 {
680 std::string alias_name_str = alias_name;
681 if ((cmd_args.GetArgumentCount() == 0)
682 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
683 cmd_args.Unshift (alias_name);
684
685 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
686 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
687
688 if (option_arg_vector_sp.get())
689 {
690 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
691
692 for (int i = 0; i < option_arg_vector->size(); ++i)
693 {
694 OptionArgPair option_pair = (*option_arg_vector)[i];
695 OptionArgValue value_pair = option_pair.second;
696 int value_type = value_pair.first;
697 std::string option = option_pair.first;
698 std::string value = value_pair.second;
699 if (option.compare ("<argument>") == 0)
700 result_str.Printf (" %s", value.c_str());
701 else
702 {
703 result_str.Printf (" %s", option.c_str());
704 if (value_type != optional_argument)
705 result_str.Printf (" ");
706 if (value.compare ("<no_argument>") != 0)
707 {
708 int index = GetOptionArgumentPosition (value.c_str());
709 if (index == 0)
710 result_str.Printf ("%s", value.c_str());
711 else if (index >= cmd_args.GetArgumentCount())
712 {
713
714 result.AppendErrorWithFormat
715 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
716 index);
717 result.SetStatus (eReturnStatusFailed);
718 return;
719 }
720 else
721 {
722 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
723 if (strpos != std::string::npos)
724 raw_input_string = raw_input_string.erase (strpos,
725 strlen (cmd_args.GetArgumentAtIndex (index)));
726 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
727 }
728 }
729 }
730 }
731 }
732
733 alias_result = result_str.GetData();
734 }
735}
736
737bool
738CommandInterpreter::HandleCommand (const char *command_line,
739 bool add_to_history,
740 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +0000741 ExecutionContext *override_context,
742 bool repeat_on_empty_command)
743
Caroline Ticee0da7a52010-12-09 22:52:49 +0000744{
Jim Ingham949d5ac2011-02-18 00:54:25 +0000745
Caroline Ticee0da7a52010-12-09 22:52:49 +0000746 bool done = false;
747 CommandObject *cmd_obj = NULL;
748 std::string next_word;
749 bool wants_raw_input = false;
750 std::string command_string (command_line);
751
752 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +0000753 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
754
755 // Make a scoped cleanup object that will clear the crash description string
756 // on exit of this function.
757 lldb_utility::CleanUp <const char *, void> crash_description_cleanup(NULL, Host::SetCrashDescription);
758
Caroline Ticee0da7a52010-12-09 22:52:49 +0000759 if (log)
760 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +0000761
Jim Inghamabab14b2010-11-04 23:08:45 +0000762 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
763
Greg Claytonb72d0f02011-04-12 05:54:46 +0000764 UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +0000765
Jim Ingham949d5ac2011-02-18 00:54:25 +0000766 bool empty_command = false;
767 bool comment_command = false;
768 if (command_string.empty())
769 empty_command = true;
770 else
Chris Lattner24943d22010-06-08 16:52:24 +0000771 {
Jim Ingham949d5ac2011-02-18 00:54:25 +0000772 const char *k_space_characters = "\t\n\v\f\r ";
773
774 size_t non_space = command_string.find_first_not_of (k_space_characters);
775 // Check for empty line or comment line (lines whose first
776 // non-space character is the comment character for this interpreter)
777 if (non_space == std::string::npos)
778 empty_command = true;
779 else if (command_string[non_space] == m_comment_char)
780 comment_command = true;
781 }
782
783 if (empty_command)
784 {
785 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +0000786 {
Jim Ingham949d5ac2011-02-18 00:54:25 +0000787 if (m_command_history.empty())
788 {
789 result.AppendError ("empty command");
790 result.SetStatus(eReturnStatusFailed);
791 return false;
792 }
793 else
794 {
795 command_line = m_repeat_command.c_str();
796 command_string = command_line;
797 if (m_repeat_command.empty())
798 {
799 result.AppendErrorWithFormat("No auto repeat.\n");
800 result.SetStatus (eReturnStatusFailed);
801 return false;
802 }
803 }
804 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000805 }
806 else
807 {
Jim Ingham949d5ac2011-02-18 00:54:25 +0000808 result.SetStatus (eReturnStatusSuccessFinishNoResult);
809 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000810 }
Jim Ingham949d5ac2011-02-18 00:54:25 +0000811 }
812 else if (comment_command)
813 {
814 result.SetStatus (eReturnStatusSuccessFinishNoResult);
815 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000816 }
817
Caroline Ticee0da7a52010-12-09 22:52:49 +0000818 // Phase 1.
819
820 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
821 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
822 // the user could have specified an alias, and in translating the alias there may also be command options and/or
823 // even data (including raw text strings) that need to be found and inserted into the command line as part of
824 // 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 +0000825 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +0000826 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +0000827
Caroline Ticee0da7a52010-12-09 22:52:49 +0000828 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000829 size_t actual_cmd_name_len = 0;
Caroline Ticee0da7a52010-12-09 22:52:49 +0000830 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +0000831 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000832 StripFirstWord (command_string, next_word);
833 if (!cmd_obj && AliasExists (next_word.c_str()))
Chris Lattner24943d22010-06-08 16:52:24 +0000834 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000835 std::string alias_result;
836 BuildAliasResult (next_word.c_str(), command_string, alias_result, cmd_obj, result);
837 revised_command_line.Printf ("%s", alias_result.c_str());
838 if (cmd_obj)
Caroline Tice56d2fc42010-12-14 18:51:39 +0000839 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000840 wants_raw_input = cmd_obj->WantsRawCommandString ();
Caroline Tice56d2fc42010-12-14 18:51:39 +0000841 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
842 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000843 }
844 else if (!cmd_obj)
845 {
846 cmd_obj = GetCommandObject (next_word.c_str());
847 if (cmd_obj)
Chris Lattner24943d22010-06-08 16:52:24 +0000848 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000849 actual_cmd_name_len += next_word.length();
Caroline Ticee0da7a52010-12-09 22:52:49 +0000850 revised_command_line.Printf ("%s", next_word.c_str());
851 wants_raw_input = cmd_obj->WantsRawCommandString ();
Chris Lattner24943d22010-06-08 16:52:24 +0000852 }
853 else
854 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000855 revised_command_line.Printf ("%s", next_word.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000856 }
857 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000858 else if (cmd_obj->IsMultiwordObject ())
859 {
860 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
861 if (sub_cmd_obj)
862 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000863 actual_cmd_name_len += next_word.length() + 1;
Caroline Ticee0da7a52010-12-09 22:52:49 +0000864 revised_command_line.Printf (" %s", next_word.c_str());
865 cmd_obj = sub_cmd_obj;
866 wants_raw_input = cmd_obj->WantsRawCommandString ();
867 }
868 else
869 {
870 revised_command_line.Printf (" %s", next_word.c_str());
871 done = true;
872 }
873 }
874 else
875 {
876 revised_command_line.Printf (" %s", next_word.c_str());
877 done = true;
878 }
879
880 if (cmd_obj == NULL)
881 {
882 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
883 result.SetStatus (eReturnStatusFailed);
884 return false;
885 }
886
887 next_word.erase ();
888 if (command_string.length() == 0)
889 done = true;
890
Chris Lattner24943d22010-06-08 16:52:24 +0000891 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000892
893 if (command_string.size() > 0)
894 revised_command_line.Printf (" %s", command_string.c_str());
895
896 // End of Phase 1.
897 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
898 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
899 // fully translated with all substitutions & translations taken care of (still in raw text format); and
900 // wants_raw_input specifies whether the Execute method expects raw input or not.
901
902
903 if (log)
904 {
905 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
906 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
907 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
908 }
909
910 // Phase 2.
911 // Take care of things like setting up the history command & calling the appropriate Execute method on the
912 // CommandObject, with the appropriate arguments.
913
914 if (cmd_obj != NULL)
915 {
916 if (add_to_history)
917 {
918 Args command_args (revised_command_line.GetData());
919 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
920 if (repeat_command != NULL)
921 m_repeat_command.assign(repeat_command);
922 else
923 m_repeat_command.assign(command_line);
924
925 m_command_history.push_back (command_line);
926 }
927
928 command_string = revised_command_line.GetData();
929 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000930 std::string remainder;
931 if (actual_cmd_name_len < command_string.length())
932 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
933 // than cmd_obj->GetCommandName(), because name completion
934 // allows users to enter short versions of the names,
935 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +0000936
937 // Remove any initial spaces
938 std::string white_space (" \t\v");
939 size_t pos = remainder.find_first_not_of (white_space);
940 if (pos != 0 && pos != std::string::npos)
941 remainder = remainder.substr (pos);
942
943 if (log)
944 log->Printf ("HandleCommand, command line after removing command name(s): '%s'\n", remainder.c_str());
945
946
947 if (wants_raw_input)
948 cmd_obj->ExecuteRawCommandString (remainder.c_str(), result);
949 else
950 {
951 Args cmd_args (remainder.c_str());
952 cmd_obj->ExecuteWithOptions (cmd_args, result);
953 }
954 }
955 else
956 {
957 // We didn't find the first command object, so complete the first argument.
958 Args command_args (revised_command_line.GetData());
959 StringList matches;
960 int num_matches;
961 int cursor_index = 0;
962 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
963 bool word_complete;
964 num_matches = HandleCompletionMatches (command_args,
965 cursor_index,
966 cursor_char_position,
967 0,
968 -1,
969 word_complete,
970 matches);
971
972 if (num_matches > 0)
973 {
974 std::string error_msg;
975 error_msg.assign ("ambiguous command '");
976 error_msg.append(command_args.GetArgumentAtIndex(0));
977 error_msg.append ("'.");
978
979 error_msg.append (" Possible completions:");
980 for (int i = 0; i < num_matches; i++)
981 {
982 error_msg.append ("\n\t");
983 error_msg.append (matches.GetStringAtIndex (i));
984 }
985 error_msg.append ("\n");
986 result.AppendRawError (error_msg.c_str(), error_msg.size());
987 }
988 else
989 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
990
991 result.SetStatus (eReturnStatusFailed);
992 }
993
Chris Lattner24943d22010-06-08 16:52:24 +0000994 return result.Succeeded();
995}
996
997int
998CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
999 int &cursor_index,
1000 int &cursor_char_position,
1001 int match_start_point,
1002 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001003 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001004 StringList &matches)
1005{
1006 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001007 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001008
1009 // For any of the command completions a unique match will be a complete word.
1010 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001011
1012 if (cursor_index == -1)
1013 {
1014 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001015 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001016 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1017 }
1018 else if (cursor_index == 0)
1019 {
1020 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001021 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001022 num_command_matches = matches.GetSize();
1023
1024 if (num_command_matches == 1
1025 && cmd_obj && cmd_obj->IsMultiwordObject()
1026 && matches.GetStringAtIndex(0) != NULL
1027 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1028 {
1029 look_for_subcommand = true;
1030 num_command_matches = 0;
1031 matches.DeleteStringAtIndex(0);
1032 parsed_line.AppendArgument ("");
1033 cursor_index++;
1034 cursor_char_position = 0;
1035 }
1036 }
1037
1038 if (cursor_index > 0 || look_for_subcommand)
1039 {
1040 // We are completing further on into a commands arguments, so find the command and tell it
1041 // to complete the command.
1042 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001043 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001044 if (command_object == NULL)
1045 {
1046 return 0;
1047 }
1048 else
1049 {
1050 parsed_line.Shift();
1051 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001052 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001053 cursor_index,
1054 cursor_char_position,
1055 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001056 max_return_elements,
1057 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001058 matches);
1059 }
1060 }
1061
1062 return num_command_matches;
1063
1064}
1065
1066int
1067CommandInterpreter::HandleCompletion (const char *current_line,
1068 const char *cursor,
1069 const char *last_char,
1070 int match_start_point,
1071 int max_return_elements,
1072 StringList &matches)
1073{
1074 // We parse the argument up to the cursor, so the last argument in parsed_line is
1075 // the one containing the cursor, and the cursor is after the last character.
1076
1077 Args parsed_line(current_line, last_char - current_line);
1078 Args partial_parsed_line(current_line, cursor - current_line);
1079
1080 int num_args = partial_parsed_line.GetArgumentCount();
1081 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1082 int cursor_char_position;
1083
1084 if (cursor_index == -1)
1085 cursor_char_position = 0;
1086 else
1087 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001088
1089 if (cursor > current_line && cursor[-1] == ' ')
1090 {
1091 // We are just after a space. If we are in an argument, then we will continue
1092 // parsing, but if we are between arguments, then we have to complete whatever the next
1093 // element would be.
1094 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1095 // protected by a quote) then the space will also be in the parsed argument...
1096
1097 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1098 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1099 {
1100 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1101 cursor_index++;
1102 cursor_char_position = 0;
1103 }
1104 }
Chris Lattner24943d22010-06-08 16:52:24 +00001105
1106 int num_command_matches;
1107
1108 matches.Clear();
1109
1110 // Only max_return_elements == -1 is supported at present:
1111 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001112 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001113 num_command_matches = HandleCompletionMatches (parsed_line,
1114 cursor_index,
1115 cursor_char_position,
1116 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001117 max_return_elements,
1118 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001119 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001120
1121 if (num_command_matches <= 0)
1122 return num_command_matches;
1123
1124 if (num_args == 0)
1125 {
1126 // If we got an empty string, insert nothing.
1127 matches.InsertStringAtIndex(0, "");
1128 }
1129 else
1130 {
1131 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1132 // put an empty string in element 0.
1133 std::string command_partial_str;
1134 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001135 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1136 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001137
1138 std::string common_prefix;
1139 matches.LongestCommonPrefix (common_prefix);
1140 int partial_name_len = command_partial_str.size();
1141
1142 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001143 // Only do this if the completer told us this was a complete word, however...
1144 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001145 {
1146 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1147 if (quote_char != '\0')
1148 common_prefix.push_back(quote_char);
1149
1150 common_prefix.push_back(' ');
1151 }
1152 common_prefix.erase (0, partial_name_len);
1153 matches.InsertStringAtIndex(0, common_prefix.c_str());
1154 }
1155 return num_command_matches;
1156}
1157
Chris Lattner24943d22010-06-08 16:52:24 +00001158
1159CommandInterpreter::~CommandInterpreter ()
1160{
1161}
1162
1163const char *
1164CommandInterpreter::GetPrompt ()
1165{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001166 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001167}
1168
1169void
1170CommandInterpreter::SetPrompt (const char *new_prompt)
1171{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001172 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001173}
1174
Jim Ingham5e16ef52010-10-04 19:49:29 +00001175size_t
Greg Clayton58928562011-02-09 01:08:52 +00001176CommandInterpreter::GetConfirmationInputReaderCallback
1177(
1178 void *baton,
1179 InputReader &reader,
1180 lldb::InputReaderAction action,
1181 const char *bytes,
1182 size_t bytes_len
1183)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001184{
Greg Clayton58928562011-02-09 01:08:52 +00001185 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001186 bool *response_ptr = (bool *) baton;
1187
1188 switch (action)
1189 {
1190 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001191 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001192 {
1193 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001194 {
Greg Clayton58928562011-02-09 01:08:52 +00001195 out_file.Printf ("%s", reader.GetPrompt());
1196 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001197 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001198 }
1199 break;
1200
1201 case eInputReaderDeactivate:
1202 break;
1203
1204 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001205 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001206 {
Greg Clayton58928562011-02-09 01:08:52 +00001207 out_file.Printf ("%s", reader.GetPrompt());
1208 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001209 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001210 break;
1211
1212 case eInputReaderGotToken:
1213 if (bytes_len == 0)
1214 {
1215 reader.SetIsDone(true);
1216 }
1217 else if (bytes[0] == 'y')
1218 {
1219 *response_ptr = true;
1220 reader.SetIsDone(true);
1221 }
1222 else if (bytes[0] == 'n')
1223 {
1224 *response_ptr = false;
1225 reader.SetIsDone(true);
1226 }
1227 else
1228 {
Greg Clayton58928562011-02-09 01:08:52 +00001229 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001230 {
Greg Clayton58928562011-02-09 01:08:52 +00001231 out_file.Printf ("Please answer \"y\" or \"n\"\n%s", reader.GetPrompt());
1232 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001233 }
1234 }
1235 break;
1236
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001237 case eInputReaderInterrupt:
1238 case eInputReaderEndOfFile:
1239 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1240 reader.SetIsDone (true);
1241 break;
1242
Jim Ingham5e16ef52010-10-04 19:49:29 +00001243 case eInputReaderDone:
1244 break;
1245 }
1246
1247 return bytes_len;
1248
1249}
1250
1251bool
1252CommandInterpreter::Confirm (const char *message, bool default_answer)
1253{
Jim Ingham93057472010-10-04 22:44:14 +00001254 // Check AutoConfirm first:
1255 if (m_debugger.GetAutoConfirm())
1256 return default_answer;
1257
Jim Ingham5e16ef52010-10-04 19:49:29 +00001258 InputReaderSP reader_sp (new InputReader(GetDebugger()));
1259 bool response = default_answer;
1260 if (reader_sp)
1261 {
1262 std::string prompt(message);
1263 prompt.append(": [");
1264 if (default_answer)
1265 prompt.append ("Y/n] ");
1266 else
1267 prompt.append ("y/N] ");
1268
1269 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1270 &response, // baton
1271 eInputReaderGranularityLine, // token size, to pass to callback function
1272 NULL, // end token
1273 prompt.c_str(), // prompt
1274 true)); // echo input
1275 if (err.Success())
1276 {
1277 GetDebugger().PushInputReader (reader_sp);
1278 }
1279 reader_sp->WaitOnReaderIsDone();
1280 }
1281 return response;
1282}
1283
1284
Chris Lattner24943d22010-06-08 16:52:24 +00001285void
1286CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1287{
Jim Inghamd40f8a62010-07-06 22:46:59 +00001288 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001289
1290 if (cmd_obj_sp != NULL)
1291 {
1292 CommandObject *cmd_obj = cmd_obj_sp.get();
1293 if (cmd_obj->IsCrossRefObject ())
1294 cmd_obj->AddObject (object_type);
1295 }
1296}
1297
Chris Lattner24943d22010-06-08 16:52:24 +00001298OptionArgVectorSP
1299CommandInterpreter::GetAliasOptions (const char *alias_name)
1300{
1301 OptionArgMap::iterator pos;
1302 OptionArgVectorSP ret_val;
1303
1304 std::string alias (alias_name);
1305
1306 if (HasAliasOptions())
1307 {
1308 pos = m_alias_options.find (alias);
1309 if (pos != m_alias_options.end())
1310 ret_val = pos->second;
1311 }
1312
1313 return ret_val;
1314}
1315
1316void
1317CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1318{
1319 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1320 if (pos != m_alias_options.end())
1321 {
1322 m_alias_options.erase (pos);
1323 }
1324}
1325
1326void
1327CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1328{
1329 m_alias_options[alias_name] = option_arg_vector_sp;
1330}
1331
1332bool
1333CommandInterpreter::HasCommands ()
1334{
1335 return (!m_command_dict.empty());
1336}
1337
1338bool
1339CommandInterpreter::HasAliases ()
1340{
1341 return (!m_alias_dict.empty());
1342}
1343
1344bool
1345CommandInterpreter::HasUserCommands ()
1346{
1347 return (!m_user_dict.empty());
1348}
1349
1350bool
1351CommandInterpreter::HasAliasOptions ()
1352{
1353 return (!m_alias_options.empty());
1354}
1355
Chris Lattner24943d22010-06-08 16:52:24 +00001356void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001357CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
1358 const char *alias_name,
1359 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00001360 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001361 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00001362{
1363 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00001364
1365 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00001366
Caroline Tice44c841d2010-12-07 19:58:26 +00001367 // Make sure that the alias name is the 0th element in cmd_args
1368 std::string alias_name_str = alias_name;
1369 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1370 cmd_args.Unshift (alias_name);
1371
1372 Args new_args (alias_cmd_obj->GetCommandName());
1373 if (new_args.GetArgumentCount() == 2)
1374 new_args.Shift();
1375
Chris Lattner24943d22010-06-08 16:52:24 +00001376 if (option_arg_vector_sp.get())
1377 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001378 if (wants_raw_input)
1379 {
1380 // We have a command that both has command options and takes raw input. Make *sure* it has a
1381 // " -- " in the right place in the raw_input_string.
1382 size_t pos = raw_input_string.find(" -- ");
1383 if (pos == std::string::npos)
1384 {
1385 // None found; assume it goes at the beginning of the raw input string
1386 raw_input_string.insert (0, " -- ");
1387 }
1388 }
Chris Lattner24943d22010-06-08 16:52:24 +00001389
1390 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1391 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001392 std::vector<bool> used (old_size + 1, false);
1393
1394 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001395
1396 for (int i = 0; i < option_arg_vector->size(); ++i)
1397 {
1398 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00001399 OptionArgValue value_pair = option_pair.second;
1400 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00001401 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00001402 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00001403 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001404 {
1405 if (!wants_raw_input
1406 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
1407 new_args.AppendArgument (value.c_str());
1408 }
Chris Lattner24943d22010-06-08 16:52:24 +00001409 else
1410 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001411 if (value_type != optional_argument)
1412 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001413 if (value.compare ("<no-argument>") != 0)
1414 {
1415 int index = GetOptionArgumentPosition (value.c_str());
1416 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001417 {
Chris Lattner24943d22010-06-08 16:52:24 +00001418 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00001419 if (value_type != optional_argument)
1420 new_args.AppendArgument (value.c_str());
1421 else
1422 {
1423 char buffer[255];
1424 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
1425 new_args.AppendArgument (buffer);
1426 }
1427
1428 }
Chris Lattner24943d22010-06-08 16:52:24 +00001429 else if (index >= cmd_args.GetArgumentCount())
1430 {
1431 result.AppendErrorWithFormat
1432 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1433 index);
1434 result.SetStatus (eReturnStatusFailed);
1435 return;
1436 }
1437 else
1438 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001439 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
1440 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1441 if (strpos != std::string::npos)
1442 {
1443 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
1444 }
1445
1446 if (value_type != optional_argument)
1447 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
1448 else
1449 {
1450 char buffer[255];
1451 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
1452 cmd_args.GetArgumentAtIndex (index));
1453 new_args.AppendArgument (buffer);
1454 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001455 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001456 }
1457 }
1458 }
1459 }
1460
1461 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1462 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001463 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00001464 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1465 }
1466
1467 cmd_args.Clear();
1468 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1469 }
1470 else
1471 {
1472 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00001473 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
1474 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
1475 // input string.
1476 if (wants_raw_input)
1477 {
1478 cmd_args.Clear();
1479 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1480 }
Chris Lattner24943d22010-06-08 16:52:24 +00001481 return;
1482 }
1483
1484 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1485 return;
1486}
1487
1488
1489int
1490CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1491{
1492 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1493 // of zero.
1494
1495 char *cptr = (char *) in_string;
1496
1497 // Does it start with '%'
1498 if (cptr[0] == '%')
1499 {
1500 ++cptr;
1501
1502 // Is the rest of it entirely digits?
1503 if (isdigit (cptr[0]))
1504 {
1505 const char *start = cptr;
1506 while (isdigit (cptr[0]))
1507 ++cptr;
1508
1509 // We've gotten to the end of the digits; are we at the end of the string?
1510 if (cptr[0] == '\0')
1511 position = atoi (start);
1512 }
1513 }
1514
1515 return position;
1516}
1517
1518void
1519CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1520{
Greg Clayton887aa282010-10-11 01:05:37 +00001521 // Don't parse any .lldbinit files if we were asked not to
1522 if (m_skip_lldbinit_files)
1523 return;
1524
Chris Lattner24943d22010-06-08 16:52:24 +00001525 const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit";
Greg Clayton537a7a82010-10-20 20:54:39 +00001526 FileSpec init_file (init_file_path, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001527 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
1528 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
1529
1530 if (init_file.Exists())
1531 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001532 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
1533 bool stop_on_continue = true;
1534 bool stop_on_error = false;
1535 bool echo_commands = false;
1536 bool print_results = false;
1537
1538 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, result);
Chris Lattner24943d22010-06-08 16:52:24 +00001539 }
1540 else
1541 {
1542 // nothing to be done if the file doesn't exist
1543 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1544 }
1545}
1546
Greg Claytonb72d0f02011-04-12 05:54:46 +00001547PlatformSP
1548CommandInterpreter::GetPlatform (bool prefer_target_platform)
1549{
1550 PlatformSP platform_sp;
1551 if (prefer_target_platform && m_exe_ctx.target)
1552 platform_sp = m_exe_ctx.target->GetPlatform();
1553
1554 if (!platform_sp)
1555 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
1556 return platform_sp;
1557}
1558
Jim Ingham949d5ac2011-02-18 00:54:25 +00001559void
Jim Inghama4fede32011-03-11 01:51:49 +00001560CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001561 ExecutionContext *override_context,
1562 bool stop_on_continue,
1563 bool stop_on_error,
1564 bool echo_commands,
1565 bool print_results,
1566 CommandReturnObject &result)
1567{
1568 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00001569
1570 // If we are going to continue past a "continue" then we need to run the commands synchronously.
1571 // Make sure you reset this value anywhere you return from the function.
1572
1573 bool old_async_execution = m_debugger.GetAsyncExecution();
1574
1575 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
1576 // cause series of commands that change the context, then do an operation that relies on that context to fail.
1577
1578 if (override_context != NULL)
Greg Claytonb72d0f02011-04-12 05:54:46 +00001579 UpdateExecutionContext (override_context);
Jim Ingham949d5ac2011-02-18 00:54:25 +00001580
1581 if (!stop_on_continue)
1582 {
1583 m_debugger.SetAsyncExecution (false);
1584 }
1585
1586 for (int idx = 0; idx < num_lines; idx++)
1587 {
1588 const char *cmd = commands.GetStringAtIndex(idx);
1589 if (cmd[0] == '\0')
1590 continue;
1591
Jim Ingham949d5ac2011-02-18 00:54:25 +00001592 if (echo_commands)
1593 {
1594 result.AppendMessageWithFormat ("%s %s\n",
1595 GetPrompt(),
1596 cmd);
1597 }
1598
Greg Claytonaa378b12011-02-20 02:15:07 +00001599 CommandReturnObject tmp_result;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001600 bool success = HandleCommand(cmd, false, tmp_result, NULL);
1601
1602 if (print_results)
1603 {
1604 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00001605 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00001606 }
1607
1608 if (!success || !tmp_result.Succeeded())
1609 {
1610 if (stop_on_error)
1611 {
1612 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed.\n",
1613 idx, cmd);
1614 result.SetStatus (eReturnStatusFailed);
1615 m_debugger.SetAsyncExecution (old_async_execution);
1616 return;
1617 }
1618 else if (print_results)
1619 {
1620 result.AppendMessageWithFormat ("Command #%d '%s' failed with error: %s.\n",
1621 idx + 1,
1622 cmd,
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00001623 tmp_result.GetErrorData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00001624 }
1625 }
1626
1627 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
1628 // could be running (for instance in Breakpoint Commands.
1629 // So we check the return value to see if it is has running in it.
1630 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
1631 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
1632 {
1633 if (stop_on_continue)
1634 {
1635 // If we caused the target to proceed, and we're going to stop in that case, set the
1636 // status in our real result before returning. This is an error if the continue was not the
1637 // last command in the set of commands to be run.
1638 if (idx != num_lines - 1)
1639 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
1640 idx + 1, cmd);
1641 else
1642 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
1643
1644 result.SetStatus(tmp_result.GetStatus());
1645 m_debugger.SetAsyncExecution (old_async_execution);
1646
1647 return;
1648 }
1649 }
1650
1651 }
1652
1653 result.SetStatus (eReturnStatusSuccessFinishResult);
1654 m_debugger.SetAsyncExecution (old_async_execution);
1655
1656 return;
1657}
1658
1659void
1660CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
1661 ExecutionContext *context,
1662 bool stop_on_continue,
1663 bool stop_on_error,
1664 bool echo_command,
1665 bool print_result,
1666 CommandReturnObject &result)
1667{
1668 if (cmd_file.Exists())
1669 {
1670 bool success;
1671 StringList commands;
1672 success = commands.ReadFileLines(cmd_file);
1673 if (!success)
1674 {
1675 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
1676 result.SetStatus (eReturnStatusFailed);
1677 return;
1678 }
1679 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, result);
1680 }
1681 else
1682 {
1683 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
1684 cmd_file.GetFilename().AsCString());
1685 result.SetStatus (eReturnStatusFailed);
1686 return;
1687 }
1688}
1689
Chris Lattner24943d22010-06-08 16:52:24 +00001690ScriptInterpreter *
1691CommandInterpreter::GetScriptInterpreter ()
1692{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001693 if (m_script_interpreter_ap.get() != NULL)
1694 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00001695
Caroline Tice0aa2e552011-01-14 00:29:16 +00001696 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
1697 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00001698 {
Caroline Tice0aa2e552011-01-14 00:29:16 +00001699 case eScriptLanguageNone:
1700 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
1701 break;
1702 case eScriptLanguagePython:
1703 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
1704 break;
1705 default:
1706 break;
1707 };
1708
1709 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00001710}
1711
1712
1713
1714bool
1715CommandInterpreter::GetSynchronous ()
1716{
1717 return m_synchronous_execution;
1718}
1719
1720void
1721CommandInterpreter::SetSynchronous (bool value)
1722{
Johnny Chend7a4eb02010-10-14 01:22:03 +00001723 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00001724}
1725
1726void
1727CommandInterpreter::OutputFormattedHelpText (Stream &strm,
1728 const char *word_text,
1729 const char *separator,
1730 const char *help_text,
1731 uint32_t max_word_len)
1732{
Greg Clayton238c0a12010-09-18 01:14:36 +00001733 const uint32_t max_columns = m_debugger.GetTerminalWidth();
1734
Chris Lattner24943d22010-06-08 16:52:24 +00001735 int indent_size = max_word_len + strlen (separator) + 2;
1736
1737 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00001738
1739 StreamString text_strm;
1740 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
1741
1742 size_t len = text_strm.GetSize();
1743 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00001744 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00001745 {
1746 text_strm.EOL();
1747 len = text_strm.GetSize();
1748 }
Chris Lattner24943d22010-06-08 16:52:24 +00001749
1750 if (len < max_columns)
1751 {
1752 // Output it as a single line.
1753 strm.Printf ("%s", text);
1754 }
1755 else
1756 {
1757 // We need to break it up into multiple lines.
1758 bool first_line = true;
1759 int text_width;
1760 int start = 0;
1761 int end = start;
1762 int final_end = strlen (text);
1763 int sub_len;
1764
1765 while (end < final_end)
1766 {
1767 if (first_line)
1768 text_width = max_columns - 1;
1769 else
1770 text_width = max_columns - indent_size - 1;
1771
1772 // Don't start the 'text' on a space, since we're already outputting the indentation.
1773 if (!first_line)
1774 {
1775 while ((start < final_end) && (text[start] == ' '))
1776 start++;
1777 }
1778
1779 end = start + text_width;
1780 if (end > final_end)
1781 end = final_end;
1782 else
1783 {
1784 // If we're not at the end of the text, make sure we break the line on white space.
1785 while (end > start
1786 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
1787 end--;
1788 }
1789
1790 sub_len = end - start;
1791 if (start != 0)
1792 strm.EOL();
1793 if (!first_line)
1794 strm.Indent();
1795 else
1796 first_line = false;
1797 assert (start <= final_end);
1798 assert (start + sub_len <= final_end);
1799 if (sub_len > 0)
1800 strm.Write (text + start, sub_len);
1801 start = end + 1;
1802 }
1803 }
1804 strm.EOL();
1805 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001806}
1807
1808void
1809CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
1810 StringList &commands_found, StringList &commands_help)
1811{
1812 CommandObject::CommandMap::const_iterator pos;
1813 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
1814 CommandObject *sub_cmd_obj;
1815
1816 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
1817 {
1818 const char * command_name = pos->first.c_str();
1819 sub_cmd_obj = pos->second.get();
1820 StreamString complete_command_name;
1821
1822 complete_command_name.Printf ("%s %s", prefix, command_name);
1823
Greg Clayton238c0a12010-09-18 01:14:36 +00001824 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001825 {
1826 commands_found.AppendString (complete_command_name.GetData());
1827 commands_help.AppendString (sub_cmd_obj->GetHelp());
1828 }
1829
1830 if (sub_cmd_obj->IsMultiwordObject())
1831 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
1832 commands_help);
1833 }
1834
1835}
1836
1837void
1838CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
1839 StringList &commands_help)
1840{
1841 CommandObject::CommandMap::const_iterator pos;
1842
1843 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1844 {
1845 const char *command_name = pos->first.c_str();
1846 CommandObject *cmd_obj = pos->second.get();
1847
Greg Clayton238c0a12010-09-18 01:14:36 +00001848 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001849 {
1850 commands_found.AppendString (command_name);
1851 commands_help.AppendString (cmd_obj->GetHelp());
1852 }
1853
1854 if (cmd_obj->IsMultiwordObject())
1855 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
1856
1857 }
1858}
Greg Claytonb72d0f02011-04-12 05:54:46 +00001859
1860
1861void
1862CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
1863{
1864 m_exe_ctx.Clear();
1865
1866 if (override_context != NULL)
1867 {
1868 m_exe_ctx.target = override_context->target;
1869 m_exe_ctx.process = override_context->process;
1870 m_exe_ctx.thread = override_context->thread;
1871 m_exe_ctx.frame = override_context->frame;
1872 }
1873 else
1874 {
1875 TargetSP target_sp (m_debugger.GetSelectedTarget());
1876 if (target_sp)
1877 {
1878 m_exe_ctx.target = target_sp.get();
1879 m_exe_ctx.process = target_sp->GetProcessSP().get();
1880 if (m_exe_ctx.process && m_exe_ctx.process->IsAlive() && !m_exe_ctx.process->IsRunning())
1881 {
1882 m_exe_ctx.thread = m_exe_ctx.process->GetThreadList().GetSelectedThread().get();
1883 if (m_exe_ctx.thread == NULL)
1884 {
1885 m_exe_ctx.thread = m_exe_ctx.process->GetThreadList().GetThreadAtIndex(0).get();
1886 // If we didn't have a selected thread, select one here.
1887 if (m_exe_ctx.thread != NULL)
1888 m_exe_ctx.process->GetThreadList().SetSelectedThreadByID(m_exe_ctx.thread->GetID());
1889 }
1890 if (m_exe_ctx.thread)
1891 {
1892 m_exe_ctx.frame = m_exe_ctx.thread->GetSelectedFrame().get();
1893 if (m_exe_ctx.frame == NULL)
1894 {
1895 m_exe_ctx.frame = m_exe_ctx.thread->GetStackFrameAtIndex (0).get();
1896 // If we didn't have a selected frame select one here.
1897 if (m_exe_ctx.frame != NULL)
1898 m_exe_ctx.thread->SetSelectedFrame(m_exe_ctx.frame);
1899 }
1900 }
1901 }
1902 }
1903 }
1904}
1905