blob: abd0943bf418906f6c94bd5df6907b1689d0b037 [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"
22#include "../Commands/CommandObjectFile.h"
23#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"
28#include "../Commands/CommandObjectProcess.h"
29#include "../Commands/CommandObjectQuit.h"
Eli Friedmanb34d2a22010-06-09 22:08:29 +000030#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000031#include "../Commands/CommandObjectRegister.h"
Chris Lattner24943d22010-06-08 16:52:24 +000032#include "CommandObjectScript.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000033#include "../Commands/CommandObjectSettings.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000034#include "../Commands/CommandObjectSource.h"
Jim Ingham767af882010-07-07 03:36:20 +000035#include "../Commands/CommandObjectCommands.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000036#include "../Commands/CommandObjectSyntax.h"
37#include "../Commands/CommandObjectTarget.h"
38#include "../Commands/CommandObjectThread.h"
Chris Lattner24943d22010-06-08 16:52:24 +000039
Jim Ingham84cdc152010-06-15 19:49:27 +000040#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000041#include "lldb/Core/Debugger.h"
Jim Ingham5e16ef52010-10-04 19:49:29 +000042#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000043#include "lldb/Core/Stream.h"
44#include "lldb/Core/Timer.h"
45#include "lldb/Target/Process.h"
46#include "lldb/Target/Thread.h"
47#include "lldb/Target/TargetList.h"
Greg Claytone98ac252010-11-10 04:57:04 +000048#include "lldb/Utility/CleanUp.h"
Chris Lattner24943d22010-06-08 16:52:24 +000049
50#include "lldb/Interpreter/CommandReturnObject.h"
51#include "lldb/Interpreter/CommandInterpreter.h"
52
53using namespace lldb;
54using namespace lldb_private;
55
56CommandInterpreter::CommandInterpreter
57(
Greg Clayton63094e02010-06-23 01:19:29 +000058 Debugger &debugger,
Chris Lattner24943d22010-06-08 16:52:24 +000059 ScriptLanguage script_language,
Greg Clayton63094e02010-06-23 01:19:29 +000060 bool synchronous_execution
Chris Lattner24943d22010-06-08 16:52:24 +000061) :
Greg Clayton49ce6822010-10-31 03:01:06 +000062 Broadcaster ("lldb.command-interpreter"),
Greg Clayton63094e02010-06-23 01:19:29 +000063 m_debugger (debugger),
Greg Clayton887aa282010-10-11 01:05:37 +000064 m_synchronous_execution (synchronous_execution),
65 m_skip_lldbinit_files (false)
Chris Lattner24943d22010-06-08 16:52:24 +000066{
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000067 const char *dbg_name = debugger.GetInstanceName().AsCString();
68 std::string lang_name = ScriptInterpreter::LanguageToString (script_language);
69 StreamString var_name;
70 var_name.Printf ("[%s].script-lang", dbg_name);
Caroline Tice1d2aefd2010-09-09 06:25:08 +000071 debugger.GetSettingsController()->SetVariable (var_name.GetData(), lang_name.c_str(),
72 lldb::eVarSetOperationAssign, false,
Greg Clayton49ce6822010-10-31 03:01:06 +000073 m_debugger.GetInstanceName().AsCString());
74 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
75 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
76 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Chris Lattner24943d22010-06-08 16:52:24 +000077}
78
79void
80CommandInterpreter::Initialize ()
81{
82 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
83
84 CommandReturnObject result;
85
86 LoadCommandDictionary ();
87
Chris Lattner24943d22010-06-08 16:52:24 +000088 // Set up some initial aliases.
Jim Ingham767af882010-07-07 03:36:20 +000089 result.Clear(); HandleCommand ("command alias q quit", false, result);
Jim Inghame3663e82010-10-22 18:47:16 +000090 result.Clear(); HandleCommand ("command alias run process launch --", false, result);
91 result.Clear(); HandleCommand ("command alias r process launch --", false, result);
Jim Ingham767af882010-07-07 03:36:20 +000092 result.Clear(); HandleCommand ("command alias c process continue", false, result);
93 result.Clear(); HandleCommand ("command alias continue process continue", false, result);
94 result.Clear(); HandleCommand ("command alias expr expression", false, result);
95 result.Clear(); HandleCommand ("command alias exit quit", false, result);
Greg Clayton0f3a8eb2010-09-16 17:09:23 +000096 result.Clear(); HandleCommand ("command alias b regexp-break", false, result);
Jim Ingham767af882010-07-07 03:36:20 +000097 result.Clear(); HandleCommand ("command alias bt thread backtrace", false, result);
98 result.Clear(); HandleCommand ("command alias si thread step-inst", false, result);
99 result.Clear(); HandleCommand ("command alias step thread step-in", false, result);
100 result.Clear(); HandleCommand ("command alias s thread step-in", false, result);
101 result.Clear(); HandleCommand ("command alias next thread step-over", false, result);
102 result.Clear(); HandleCommand ("command alias n thread step-over", false, result);
103 result.Clear(); HandleCommand ("command alias finish thread step-out", false, result);
104 result.Clear(); HandleCommand ("command alias x memory read", false, result);
105 result.Clear(); HandleCommand ("command alias l source list", false, result);
106 result.Clear(); HandleCommand ("command alias list source list", false, result);
Greg Clayton0f3a8eb2010-09-16 17:09:23 +0000107 result.Clear(); HandleCommand ("command alias p frame variable", false, result);
108 result.Clear(); HandleCommand ("command alias print frame variable", false, result);
Jim Inghame3663e82010-10-22 18:47:16 +0000109 result.Clear(); HandleCommand ("command alias po expression -o --", false, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000110}
111
Chris Lattner24943d22010-06-08 16:52:24 +0000112const char *
113CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
114{
115 // This function has not yet been implemented.
116
117 // Look for any embedded script command
118 // If found,
119 // get interpreter object from the command dictionary,
120 // call execute_one_command on it,
121 // get the results as a string,
122 // substitute that string for current stuff.
123
124 return arg;
125}
126
127
128void
129CommandInterpreter::LoadCommandDictionary ()
130{
131 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
132
133 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
134 //
135 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
136 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
137 // the cross-referencing stuff) are created!!!
138 //
139 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
140
141
142 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
143 // are created. This is so that when another command is created that needs to go into a crossref object,
144 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
145 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
146
Chris Lattner24943d22010-06-08 16:52:24 +0000147 // Non-CommandObjectCrossref commands can now be created.
148
Caroline Tice5bc8c972010-09-20 20:44:43 +0000149 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000150
Greg Clayton238c0a12010-09-18 01:14:36 +0000151 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000152 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000153 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000154 m_command_dict["commands"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000155 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
156 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
157 m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000158 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000159 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000160 m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
161 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
162 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
163 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000164 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000165 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000166 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000167 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000168 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000169 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
170 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000171
172 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000173 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
174 "regexp-break",
Caroline Ticec1ad82e2010-09-07 22:38:08 +0000175 "Set a breakpoint using a regular expression to specify the location.",
Caroline Tice43b014a2010-10-04 22:28:36 +0000176 "regexp-break [<filename>:<linenum>]\nregexp-break [<address>]\nregexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000177 if (break_regex_cmd_ap.get())
178 {
179 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
180 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
181 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
182 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list") &&
183 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
184 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
185 {
186 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
187 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
188 }
189 }
190}
191
192int
193CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
194 StringList &matches)
195{
196 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
197
198 if (include_aliases)
199 {
200 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
201 }
202
203 return matches.GetSize();
204}
205
206CommandObjectSP
207CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
208{
209 CommandObject::CommandMap::iterator pos;
210 CommandObjectSP ret_val;
211
212 std::string cmd(cmd_cstr);
213
214 if (HasCommands())
215 {
216 pos = m_command_dict.find(cmd);
217 if (pos != m_command_dict.end())
218 ret_val = pos->second;
219 }
220
221 if (include_aliases && HasAliases())
222 {
223 pos = m_alias_dict.find(cmd);
224 if (pos != m_alias_dict.end())
225 ret_val = pos->second;
226 }
227
228 if (HasUserCommands())
229 {
230 pos = m_user_dict.find(cmd);
231 if (pos != m_user_dict.end())
232 ret_val = pos->second;
233 }
234
235 if (!exact && ret_val == NULL)
236 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000237 // We will only get into here if we didn't find any exact matches.
238
239 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
240
Chris Lattner24943d22010-06-08 16:52:24 +0000241 StringList local_matches;
242 if (matches == NULL)
243 matches = &local_matches;
244
Jim Inghamd40f8a62010-07-06 22:46:59 +0000245 unsigned int num_cmd_matches = 0;
246 unsigned int num_alias_matches = 0;
247 unsigned int num_user_matches = 0;
248
249 // Look through the command dictionaries one by one, and if we get only one match from any of
250 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
251
Chris Lattner24943d22010-06-08 16:52:24 +0000252 if (HasCommands())
253 {
254 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
255 }
256
257 if (num_cmd_matches == 1)
258 {
259 cmd.assign(matches->GetStringAtIndex(0));
260 pos = m_command_dict.find(cmd);
261 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000262 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000263 }
264
Jim Ingham9a574172010-06-24 20:28:42 +0000265 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000266 {
267 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
268
269 }
270
Jim Inghamd40f8a62010-07-06 22:46:59 +0000271 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000272 {
273 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
274 pos = m_alias_dict.find(cmd);
275 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000276 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000277 }
278
Jim Ingham9a574172010-06-24 20:28:42 +0000279 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000280 {
281 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
282 }
283
Jim Inghamd40f8a62010-07-06 22:46:59 +0000284 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000285 {
286 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
287
288 pos = m_user_dict.find (cmd);
289 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000290 user_match_sp = pos->second;
291 }
292
293 // If we got exactly one match, return that, otherwise return the match list.
294
295 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
296 {
297 if (num_cmd_matches)
298 return real_match_sp;
299 else if (num_alias_matches)
300 return alias_match_sp;
301 else
302 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000303 }
304 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000305 else if (matches && ret_val != NULL)
306 {
307 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000308 }
309
310
311 return ret_val;
312}
313
Jim Inghamd40f8a62010-07-06 22:46:59 +0000314CommandObjectSP
315CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000316{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000317 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
318}
319
320CommandObject *
321CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
322{
323 return GetCommandSPExact (cmd_cstr, include_aliases).get();
324}
325
326CommandObject *
327CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
328{
329 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
330
331 // If we didn't find an exact match to the command string in the commands, look in
332 // the aliases.
333
334 if (command_obj == NULL)
335 {
336 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
337 }
338
339 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
340 // in both the commands and the aliases.
341
342 if (command_obj == NULL)
343 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
344
345 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000346}
347
348bool
349CommandInterpreter::CommandExists (const char *cmd)
350{
351 return m_command_dict.find(cmd) != m_command_dict.end();
352}
353
354bool
355CommandInterpreter::AliasExists (const char *cmd)
356{
357 return m_alias_dict.find(cmd) != m_alias_dict.end();
358}
359
360bool
361CommandInterpreter::UserCommandExists (const char *cmd)
362{
363 return m_user_dict.find(cmd) != m_user_dict.end();
364}
365
366void
367CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
368{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000369 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000370 m_alias_dict[alias_name] = command_obj_sp;
371}
372
373bool
374CommandInterpreter::RemoveAlias (const char *alias_name)
375{
376 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
377 if (pos != m_alias_dict.end())
378 {
379 m_alias_dict.erase(pos);
380 return true;
381 }
382 return false;
383}
384bool
385CommandInterpreter::RemoveUser (const char *alias_name)
386{
387 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
388 if (pos != m_user_dict.end())
389 {
390 m_user_dict.erase(pos);
391 return true;
392 }
393 return false;
394}
395
Chris Lattner24943d22010-06-08 16:52:24 +0000396void
397CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
398{
399 help_string.Printf ("'%s", command_name);
400 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
401
402 if (option_arg_vector_sp != NULL)
403 {
404 OptionArgVector *options = option_arg_vector_sp.get();
405 for (int i = 0; i < options->size(); ++i)
406 {
407 OptionArgPair cur_option = (*options)[i];
408 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000409 OptionArgValue value_pair = cur_option.second;
410 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000411 if (opt.compare("<argument>") == 0)
412 {
413 help_string.Printf (" %s", value.c_str());
414 }
415 else
416 {
417 help_string.Printf (" %s", opt.c_str());
418 if ((value.compare ("<no-argument>") != 0)
419 && (value.compare ("<need-argument") != 0))
420 {
421 help_string.Printf (" %s", value.c_str());
422 }
423 }
424 }
425 }
426
427 help_string.Printf ("'");
428}
429
Greg Clayton65124ea2010-08-26 22:05:43 +0000430size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000431CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
432{
433 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000434 CommandObject::CommandMap::const_iterator end = dict.end();
435 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000436
Greg Clayton65124ea2010-08-26 22:05:43 +0000437 for (pos = dict.begin(); pos != end; ++pos)
438 {
439 size_t len = pos->first.size();
440 if (max_len < len)
441 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000442 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000443 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000444}
445
446void
447CommandInterpreter::GetHelp (CommandReturnObject &result)
448{
449 CommandObject::CommandMap::const_iterator pos;
450 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
451 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000452 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000453
454 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
455 {
456 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
457 max_len);
458 }
459 result.AppendMessage("");
460
461 if (m_alias_dict.size() > 0)
462 {
Jim Inghame3663e82010-10-22 18:47:16 +0000463 result.AppendMessage("The following is a list of your current command abbreviations "
464 "(see 'help commands alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000465 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000466 max_len = FindLongestCommandWord (m_alias_dict);
467
Chris Lattner24943d22010-06-08 16:52:24 +0000468 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
469 {
470 StreamString sstr;
471 StreamString translation_and_help;
472 std::string entry_name = pos->first;
473 std::string second_entry = pos->second.get()->GetCommandName();
474 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
475
476 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
477 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
478 translation_and_help.GetData(), max_len);
479 }
480 result.AppendMessage("");
481 }
482
483 if (m_user_dict.size() > 0)
484 {
485 result.AppendMessage ("The following is a list of your current user-defined commands:");
486 result.AppendMessage("");
487 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
488 {
489 result.AppendMessageWithFormat ("%s -- %s\n", pos->first.c_str(), pos->second->GetHelp());
490 }
491 result.AppendMessage("");
492 }
493
494 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
495}
496
Caroline Ticee0da7a52010-12-09 22:52:49 +0000497CommandObject *
498CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000499{
Caroline Ticee0da7a52010-12-09 22:52:49 +0000500 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
501 // eventually be invoked by the given command line.
502
503 CommandObject *cmd_obj = NULL;
504 std::string white_space (" \t\v");
505 size_t start = command_string.find_first_not_of (white_space);
506 size_t end = 0;
507 bool done = false;
508 while (!done)
509 {
510 if (start != std::string::npos)
511 {
512 // Get the next word from command_string.
513 end = command_string.find_first_of (white_space, start);
514 if (end == std::string::npos)
515 end = command_string.size();
516 std::string cmd_word = command_string.substr (start, end - start);
517
518 if (cmd_obj == NULL)
519 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
520 // command or alias.
521 cmd_obj = GetCommandObject (cmd_word.c_str());
522 else if (cmd_obj->IsMultiwordObject ())
523 {
524 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
525 CommandObject *sub_cmd_obj =
526 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
527 if (sub_cmd_obj)
528 cmd_obj = sub_cmd_obj;
529 else // cmd_word was not a valid sub-command word, so we are donee
530 done = true;
531 }
532 else
533 // We have a cmd_obj and it is not a multi-word object, so we are done.
534 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000535
Caroline Ticee0da7a52010-12-09 22:52:49 +0000536 // If we didn't find a valid command object, or our command object is not a multi-word object, or
537 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
538 // next word.
539
540 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
541 done = true;
542 else
543 start = command_string.find_first_not_of (white_space, end);
544 }
545 else
546 // Unable to find any more words.
547 done = true;
548 }
549
550 if (end == command_string.size())
551 command_string.clear();
552 else
553 command_string = command_string.substr(end);
554
555 return cmd_obj;
556}
557
558bool
559CommandInterpreter::StripFirstWord (std::string &command_string, std::string &word)
560{
561 std::string white_space (" \t\v");
562 size_t start;
563 size_t end;
564
565 start = command_string.find_first_not_of (white_space);
566 if (start != std::string::npos)
567 {
568 end = command_string.find_first_of (white_space, start);
569 if (end != std::string::npos)
570 {
571 word = command_string.substr (start, end - start);
572 command_string = command_string.substr (end);
573 size_t pos = command_string.find_first_not_of (white_space);
574 if ((pos != 0) && (pos != std::string::npos))
575 command_string = command_string.substr (pos);
576 }
577 else
578 {
579 word = command_string.substr (start);
580 command_string.erase();
581 }
582
583 }
584 return true;
585}
586
587void
588CommandInterpreter::BuildAliasResult (const char *alias_name, std::string &raw_input_string, std::string &alias_result,
589 CommandObject *&alias_cmd_obj, CommandReturnObject &result)
590{
591 Args cmd_args (raw_input_string.c_str());
592 alias_cmd_obj = GetCommandObject (alias_name);
593 StreamString result_str;
594
595 if (alias_cmd_obj)
596 {
597 std::string alias_name_str = alias_name;
598 if ((cmd_args.GetArgumentCount() == 0)
599 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
600 cmd_args.Unshift (alias_name);
601
602 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
603 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
604
605 if (option_arg_vector_sp.get())
606 {
607 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
608
609 for (int i = 0; i < option_arg_vector->size(); ++i)
610 {
611 OptionArgPair option_pair = (*option_arg_vector)[i];
612 OptionArgValue value_pair = option_pair.second;
613 int value_type = value_pair.first;
614 std::string option = option_pair.first;
615 std::string value = value_pair.second;
616 if (option.compare ("<argument>") == 0)
617 result_str.Printf (" %s", value.c_str());
618 else
619 {
620 result_str.Printf (" %s", option.c_str());
621 if (value_type != optional_argument)
622 result_str.Printf (" ");
623 if (value.compare ("<no_argument>") != 0)
624 {
625 int index = GetOptionArgumentPosition (value.c_str());
626 if (index == 0)
627 result_str.Printf ("%s", value.c_str());
628 else if (index >= cmd_args.GetArgumentCount())
629 {
630
631 result.AppendErrorWithFormat
632 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
633 index);
634 result.SetStatus (eReturnStatusFailed);
635 return;
636 }
637 else
638 {
639 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
640 if (strpos != std::string::npos)
641 raw_input_string = raw_input_string.erase (strpos,
642 strlen (cmd_args.GetArgumentAtIndex (index)));
643 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
644 }
645 }
646 }
647 }
648 }
649
650 alias_result = result_str.GetData();
651 }
652}
653
654bool
655CommandInterpreter::HandleCommand (const char *command_line,
656 bool add_to_history,
657 CommandReturnObject &result,
658 ExecutionContext *override_context)
659{
660 bool done = false;
661 CommandObject *cmd_obj = NULL;
662 std::string next_word;
663 bool wants_raw_input = false;
664 std::string command_string (command_line);
665
666 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +0000667 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
668
669 // Make a scoped cleanup object that will clear the crash description string
670 // on exit of this function.
671 lldb_utility::CleanUp <const char *, void> crash_description_cleanup(NULL, Host::SetCrashDescription);
672
Caroline Ticee0da7a52010-12-09 22:52:49 +0000673 if (log)
674 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +0000675
Jim Inghamabab14b2010-11-04 23:08:45 +0000676 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
677
Greg Clayton63094e02010-06-23 01:19:29 +0000678 m_debugger.UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +0000679
680 if (command_line == NULL || command_line[0] == '\0')
681 {
682 if (m_command_history.empty())
683 {
684 result.AppendError ("empty command");
685 result.SetStatus(eReturnStatusFailed);
686 return false;
687 }
688 else
689 {
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000690 command_line = m_repeat_command.c_str();
Caroline Ticee0da7a52010-12-09 22:52:49 +0000691 command_string = command_line;
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000692 if (m_repeat_command.empty())
693 {
Jim Ingham767af882010-07-07 03:36:20 +0000694 result.AppendErrorWithFormat("No auto repeat.\n");
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000695 result.SetStatus (eReturnStatusFailed);
696 return false;
697 }
Chris Lattner24943d22010-06-08 16:52:24 +0000698 }
699 add_to_history = false;
700 }
701
Caroline Ticee0da7a52010-12-09 22:52:49 +0000702 // Phase 1.
703
704 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
705 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
706 // the user could have specified an alias, and in translating the alias there may also be command options and/or
707 // even data (including raw text strings) that need to be found and inserted into the command line as part of
708 // the translation. So this first step is plain look-up & replacement, resulting in three things: 1). the command
709 // object whose Execute method will actually be called; 2). a revised command string, with all substituitions &
710 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +0000711
Caroline Ticee0da7a52010-12-09 22:52:49 +0000712 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000713 size_t actual_cmd_name_len = 0;
Caroline Ticee0da7a52010-12-09 22:52:49 +0000714 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +0000715 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000716 StripFirstWord (command_string, next_word);
717 if (!cmd_obj && AliasExists (next_word.c_str()))
Chris Lattner24943d22010-06-08 16:52:24 +0000718 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000719 std::string alias_result;
720 BuildAliasResult (next_word.c_str(), command_string, alias_result, cmd_obj, result);
721 revised_command_line.Printf ("%s", alias_result.c_str());
722 if (cmd_obj)
723 wants_raw_input = cmd_obj->WantsRawCommandString ();
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000724 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
Caroline Ticee0da7a52010-12-09 22:52:49 +0000725 }
726 else if (!cmd_obj)
727 {
728 cmd_obj = GetCommandObject (next_word.c_str());
729 if (cmd_obj)
Chris Lattner24943d22010-06-08 16:52:24 +0000730 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000731 actual_cmd_name_len += next_word.length();
Caroline Ticee0da7a52010-12-09 22:52:49 +0000732 revised_command_line.Printf ("%s", next_word.c_str());
733 wants_raw_input = cmd_obj->WantsRawCommandString ();
Chris Lattner24943d22010-06-08 16:52:24 +0000734 }
735 else
736 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000737 revised_command_line.Printf ("%s", next_word.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000738 }
739 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000740 else if (cmd_obj->IsMultiwordObject ())
741 {
742 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
743 if (sub_cmd_obj)
744 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000745 actual_cmd_name_len += next_word.length() + 1;
Caroline Ticee0da7a52010-12-09 22:52:49 +0000746 revised_command_line.Printf (" %s", next_word.c_str());
747 cmd_obj = sub_cmd_obj;
748 wants_raw_input = cmd_obj->WantsRawCommandString ();
749 }
750 else
751 {
752 revised_command_line.Printf (" %s", next_word.c_str());
753 done = true;
754 }
755 }
756 else
757 {
758 revised_command_line.Printf (" %s", next_word.c_str());
759 done = true;
760 }
761
762 if (cmd_obj == NULL)
763 {
764 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
765 result.SetStatus (eReturnStatusFailed);
766 return false;
767 }
768
769 next_word.erase ();
770 if (command_string.length() == 0)
771 done = true;
772
Chris Lattner24943d22010-06-08 16:52:24 +0000773 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000774
775 if (command_string.size() > 0)
776 revised_command_line.Printf (" %s", command_string.c_str());
777
778 // End of Phase 1.
779 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
780 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
781 // fully translated with all substitutions & translations taken care of (still in raw text format); and
782 // wants_raw_input specifies whether the Execute method expects raw input or not.
783
784
785 if (log)
786 {
787 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
788 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
789 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
790 }
791
792 // Phase 2.
793 // Take care of things like setting up the history command & calling the appropriate Execute method on the
794 // CommandObject, with the appropriate arguments.
795
796 if (cmd_obj != NULL)
797 {
798 if (add_to_history)
799 {
800 Args command_args (revised_command_line.GetData());
801 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
802 if (repeat_command != NULL)
803 m_repeat_command.assign(repeat_command);
804 else
805 m_repeat_command.assign(command_line);
806
807 m_command_history.push_back (command_line);
808 }
809
810 command_string = revised_command_line.GetData();
811 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000812 std::string remainder;
813 if (actual_cmd_name_len < command_string.length())
814 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
815 // than cmd_obj->GetCommandName(), because name completion
816 // allows users to enter short versions of the names,
817 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +0000818
819 // Remove any initial spaces
820 std::string white_space (" \t\v");
821 size_t pos = remainder.find_first_not_of (white_space);
822 if (pos != 0 && pos != std::string::npos)
823 remainder = remainder.substr (pos);
824
825 if (log)
826 log->Printf ("HandleCommand, command line after removing command name(s): '%s'\n", remainder.c_str());
827
828
829 if (wants_raw_input)
830 cmd_obj->ExecuteRawCommandString (remainder.c_str(), result);
831 else
832 {
833 Args cmd_args (remainder.c_str());
834 cmd_obj->ExecuteWithOptions (cmd_args, result);
835 }
836 }
837 else
838 {
839 // We didn't find the first command object, so complete the first argument.
840 Args command_args (revised_command_line.GetData());
841 StringList matches;
842 int num_matches;
843 int cursor_index = 0;
844 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
845 bool word_complete;
846 num_matches = HandleCompletionMatches (command_args,
847 cursor_index,
848 cursor_char_position,
849 0,
850 -1,
851 word_complete,
852 matches);
853
854 if (num_matches > 0)
855 {
856 std::string error_msg;
857 error_msg.assign ("ambiguous command '");
858 error_msg.append(command_args.GetArgumentAtIndex(0));
859 error_msg.append ("'.");
860
861 error_msg.append (" Possible completions:");
862 for (int i = 0; i < num_matches; i++)
863 {
864 error_msg.append ("\n\t");
865 error_msg.append (matches.GetStringAtIndex (i));
866 }
867 error_msg.append ("\n");
868 result.AppendRawError (error_msg.c_str(), error_msg.size());
869 }
870 else
871 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
872
873 result.SetStatus (eReturnStatusFailed);
874 }
875
Chris Lattner24943d22010-06-08 16:52:24 +0000876 return result.Succeeded();
877}
878
879int
880CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
881 int &cursor_index,
882 int &cursor_char_position,
883 int match_start_point,
884 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +0000885 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000886 StringList &matches)
887{
888 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000889 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +0000890
891 // For any of the command completions a unique match will be a complete word.
892 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000893
894 if (cursor_index == -1)
895 {
896 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +0000897 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000898 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
899 }
900 else if (cursor_index == 0)
901 {
902 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000903 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000904 num_command_matches = matches.GetSize();
905
906 if (num_command_matches == 1
907 && cmd_obj && cmd_obj->IsMultiwordObject()
908 && matches.GetStringAtIndex(0) != NULL
909 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
910 {
911 look_for_subcommand = true;
912 num_command_matches = 0;
913 matches.DeleteStringAtIndex(0);
914 parsed_line.AppendArgument ("");
915 cursor_index++;
916 cursor_char_position = 0;
917 }
918 }
919
920 if (cursor_index > 0 || look_for_subcommand)
921 {
922 // We are completing further on into a commands arguments, so find the command and tell it
923 // to complete the command.
924 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +0000925 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +0000926 if (command_object == NULL)
927 {
928 return 0;
929 }
930 else
931 {
932 parsed_line.Shift();
933 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +0000934 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +0000935 cursor_index,
936 cursor_char_position,
937 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000938 max_return_elements,
939 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000940 matches);
941 }
942 }
943
944 return num_command_matches;
945
946}
947
948int
949CommandInterpreter::HandleCompletion (const char *current_line,
950 const char *cursor,
951 const char *last_char,
952 int match_start_point,
953 int max_return_elements,
954 StringList &matches)
955{
956 // We parse the argument up to the cursor, so the last argument in parsed_line is
957 // the one containing the cursor, and the cursor is after the last character.
958
959 Args parsed_line(current_line, last_char - current_line);
960 Args partial_parsed_line(current_line, cursor - current_line);
961
962 int num_args = partial_parsed_line.GetArgumentCount();
963 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
964 int cursor_char_position;
965
966 if (cursor_index == -1)
967 cursor_char_position = 0;
968 else
969 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
970
971 int num_command_matches;
972
973 matches.Clear();
974
975 // Only max_return_elements == -1 is supported at present:
976 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +0000977 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +0000978 num_command_matches = HandleCompletionMatches (parsed_line,
979 cursor_index,
980 cursor_char_position,
981 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000982 max_return_elements,
983 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +0000984 matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000985
986 if (num_command_matches <= 0)
987 return num_command_matches;
988
989 if (num_args == 0)
990 {
991 // If we got an empty string, insert nothing.
992 matches.InsertStringAtIndex(0, "");
993 }
994 else
995 {
996 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
997 // put an empty string in element 0.
998 std::string command_partial_str;
999 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001000 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1001 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001002
1003 std::string common_prefix;
1004 matches.LongestCommonPrefix (common_prefix);
1005 int partial_name_len = command_partial_str.size();
1006
1007 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001008 // Only do this if the completer told us this was a complete word, however...
1009 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001010 {
1011 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1012 if (quote_char != '\0')
1013 common_prefix.push_back(quote_char);
1014
1015 common_prefix.push_back(' ');
1016 }
1017 common_prefix.erase (0, partial_name_len);
1018 matches.InsertStringAtIndex(0, common_prefix.c_str());
1019 }
1020 return num_command_matches;
1021}
1022
Chris Lattner24943d22010-06-08 16:52:24 +00001023
1024CommandInterpreter::~CommandInterpreter ()
1025{
1026}
1027
1028const char *
1029CommandInterpreter::GetPrompt ()
1030{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001031 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001032}
1033
1034void
1035CommandInterpreter::SetPrompt (const char *new_prompt)
1036{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001037 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001038}
1039
Jim Ingham5e16ef52010-10-04 19:49:29 +00001040size_t
1041CommandInterpreter::GetConfirmationInputReaderCallback (void *baton,
1042 InputReader &reader,
1043 lldb::InputReaderAction action,
1044 const char *bytes,
1045 size_t bytes_len)
1046{
1047 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle();
1048 bool *response_ptr = (bool *) baton;
1049
1050 switch (action)
1051 {
1052 case eInputReaderActivate:
1053 if (out_fh)
1054 {
1055 if (reader.GetPrompt())
1056 ::fprintf (out_fh, "%s", reader.GetPrompt());
1057 }
1058 break;
1059
1060 case eInputReaderDeactivate:
1061 break;
1062
1063 case eInputReaderReactivate:
1064 if (out_fh && reader.GetPrompt())
1065 ::fprintf (out_fh, "%s", reader.GetPrompt());
1066 break;
1067
1068 case eInputReaderGotToken:
1069 if (bytes_len == 0)
1070 {
1071 reader.SetIsDone(true);
1072 }
1073 else if (bytes[0] == 'y')
1074 {
1075 *response_ptr = true;
1076 reader.SetIsDone(true);
1077 }
1078 else if (bytes[0] == 'n')
1079 {
1080 *response_ptr = false;
1081 reader.SetIsDone(true);
1082 }
1083 else
1084 {
1085 if (out_fh && !reader.IsDone() && reader.GetPrompt())
1086 {
1087 ::fprintf (out_fh, "Please answer \"y\" or \"n\"\n");
1088 ::fprintf (out_fh, "%s", reader.GetPrompt());
1089 }
1090 }
1091 break;
1092
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001093 case eInputReaderInterrupt:
1094 case eInputReaderEndOfFile:
1095 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1096 reader.SetIsDone (true);
1097 break;
1098
Jim Ingham5e16ef52010-10-04 19:49:29 +00001099 case eInputReaderDone:
1100 break;
1101 }
1102
1103 return bytes_len;
1104
1105}
1106
1107bool
1108CommandInterpreter::Confirm (const char *message, bool default_answer)
1109{
Jim Ingham93057472010-10-04 22:44:14 +00001110 // Check AutoConfirm first:
1111 if (m_debugger.GetAutoConfirm())
1112 return default_answer;
1113
Jim Ingham5e16ef52010-10-04 19:49:29 +00001114 InputReaderSP reader_sp (new InputReader(GetDebugger()));
1115 bool response = default_answer;
1116 if (reader_sp)
1117 {
1118 std::string prompt(message);
1119 prompt.append(": [");
1120 if (default_answer)
1121 prompt.append ("Y/n] ");
1122 else
1123 prompt.append ("y/N] ");
1124
1125 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1126 &response, // baton
1127 eInputReaderGranularityLine, // token size, to pass to callback function
1128 NULL, // end token
1129 prompt.c_str(), // prompt
1130 true)); // echo input
1131 if (err.Success())
1132 {
1133 GetDebugger().PushInputReader (reader_sp);
1134 }
1135 reader_sp->WaitOnReaderIsDone();
1136 }
1137 return response;
1138}
1139
1140
Chris Lattner24943d22010-06-08 16:52:24 +00001141void
1142CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1143{
Jim Inghamd40f8a62010-07-06 22:46:59 +00001144 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001145
1146 if (cmd_obj_sp != NULL)
1147 {
1148 CommandObject *cmd_obj = cmd_obj_sp.get();
1149 if (cmd_obj->IsCrossRefObject ())
1150 cmd_obj->AddObject (object_type);
1151 }
1152}
1153
Chris Lattner24943d22010-06-08 16:52:24 +00001154OptionArgVectorSP
1155CommandInterpreter::GetAliasOptions (const char *alias_name)
1156{
1157 OptionArgMap::iterator pos;
1158 OptionArgVectorSP ret_val;
1159
1160 std::string alias (alias_name);
1161
1162 if (HasAliasOptions())
1163 {
1164 pos = m_alias_options.find (alias);
1165 if (pos != m_alias_options.end())
1166 ret_val = pos->second;
1167 }
1168
1169 return ret_val;
1170}
1171
1172void
1173CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1174{
1175 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1176 if (pos != m_alias_options.end())
1177 {
1178 m_alias_options.erase (pos);
1179 }
1180}
1181
1182void
1183CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1184{
1185 m_alias_options[alias_name] = option_arg_vector_sp;
1186}
1187
1188bool
1189CommandInterpreter::HasCommands ()
1190{
1191 return (!m_command_dict.empty());
1192}
1193
1194bool
1195CommandInterpreter::HasAliases ()
1196{
1197 return (!m_alias_dict.empty());
1198}
1199
1200bool
1201CommandInterpreter::HasUserCommands ()
1202{
1203 return (!m_user_dict.empty());
1204}
1205
1206bool
1207CommandInterpreter::HasAliasOptions ()
1208{
1209 return (!m_alias_options.empty());
1210}
1211
Chris Lattner24943d22010-06-08 16:52:24 +00001212void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001213CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
1214 const char *alias_name,
1215 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00001216 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001217 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00001218{
1219 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00001220
1221 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00001222
Caroline Tice44c841d2010-12-07 19:58:26 +00001223 // Make sure that the alias name is the 0th element in cmd_args
1224 std::string alias_name_str = alias_name;
1225 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1226 cmd_args.Unshift (alias_name);
1227
1228 Args new_args (alias_cmd_obj->GetCommandName());
1229 if (new_args.GetArgumentCount() == 2)
1230 new_args.Shift();
1231
Chris Lattner24943d22010-06-08 16:52:24 +00001232 if (option_arg_vector_sp.get())
1233 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001234 if (wants_raw_input)
1235 {
1236 // We have a command that both has command options and takes raw input. Make *sure* it has a
1237 // " -- " in the right place in the raw_input_string.
1238 size_t pos = raw_input_string.find(" -- ");
1239 if (pos == std::string::npos)
1240 {
1241 // None found; assume it goes at the beginning of the raw input string
1242 raw_input_string.insert (0, " -- ");
1243 }
1244 }
Chris Lattner24943d22010-06-08 16:52:24 +00001245
1246 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1247 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001248 std::vector<bool> used (old_size + 1, false);
1249
1250 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001251
1252 for (int i = 0; i < option_arg_vector->size(); ++i)
1253 {
1254 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00001255 OptionArgValue value_pair = option_pair.second;
1256 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00001257 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00001258 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00001259 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001260 {
1261 if (!wants_raw_input
1262 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
1263 new_args.AppendArgument (value.c_str());
1264 }
Chris Lattner24943d22010-06-08 16:52:24 +00001265 else
1266 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001267 if (value_type != optional_argument)
1268 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001269 if (value.compare ("<no-argument>") != 0)
1270 {
1271 int index = GetOptionArgumentPosition (value.c_str());
1272 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001273 {
Chris Lattner24943d22010-06-08 16:52:24 +00001274 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00001275 if (value_type != optional_argument)
1276 new_args.AppendArgument (value.c_str());
1277 else
1278 {
1279 char buffer[255];
1280 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
1281 new_args.AppendArgument (buffer);
1282 }
1283
1284 }
Chris Lattner24943d22010-06-08 16:52:24 +00001285 else if (index >= cmd_args.GetArgumentCount())
1286 {
1287 result.AppendErrorWithFormat
1288 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1289 index);
1290 result.SetStatus (eReturnStatusFailed);
1291 return;
1292 }
1293 else
1294 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001295 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
1296 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1297 if (strpos != std::string::npos)
1298 {
1299 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
1300 }
1301
1302 if (value_type != optional_argument)
1303 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
1304 else
1305 {
1306 char buffer[255];
1307 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
1308 cmd_args.GetArgumentAtIndex (index));
1309 new_args.AppendArgument (buffer);
1310 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001311 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001312 }
1313 }
1314 }
1315 }
1316
1317 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1318 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001319 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00001320 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1321 }
1322
1323 cmd_args.Clear();
1324 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1325 }
1326 else
1327 {
1328 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00001329 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
1330 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
1331 // input string.
1332 if (wants_raw_input)
1333 {
1334 cmd_args.Clear();
1335 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1336 }
Chris Lattner24943d22010-06-08 16:52:24 +00001337 return;
1338 }
1339
1340 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1341 return;
1342}
1343
1344
1345int
1346CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1347{
1348 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1349 // of zero.
1350
1351 char *cptr = (char *) in_string;
1352
1353 // Does it start with '%'
1354 if (cptr[0] == '%')
1355 {
1356 ++cptr;
1357
1358 // Is the rest of it entirely digits?
1359 if (isdigit (cptr[0]))
1360 {
1361 const char *start = cptr;
1362 while (isdigit (cptr[0]))
1363 ++cptr;
1364
1365 // We've gotten to the end of the digits; are we at the end of the string?
1366 if (cptr[0] == '\0')
1367 position = atoi (start);
1368 }
1369 }
1370
1371 return position;
1372}
1373
1374void
1375CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1376{
Greg Clayton887aa282010-10-11 01:05:37 +00001377 // Don't parse any .lldbinit files if we were asked not to
1378 if (m_skip_lldbinit_files)
1379 return;
1380
Chris Lattner24943d22010-06-08 16:52:24 +00001381 const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit";
Greg Clayton537a7a82010-10-20 20:54:39 +00001382 FileSpec init_file (init_file_path, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001383 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
1384 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
1385
1386 if (init_file.Exists())
1387 {
1388 char path[PATH_MAX];
1389 init_file.GetPath(path, sizeof(path));
1390 StreamString source_command;
Johnny Chen7c984242010-07-28 21:16:11 +00001391 source_command.Printf ("command source '%s'", path);
Chris Lattner24943d22010-06-08 16:52:24 +00001392 HandleCommand (source_command.GetData(), false, result);
1393 }
1394 else
1395 {
1396 // nothing to be done if the file doesn't exist
1397 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1398 }
1399}
1400
1401ScriptInterpreter *
1402CommandInterpreter::GetScriptInterpreter ()
1403{
Greg Clayton63094e02010-06-23 01:19:29 +00001404 CommandObject::CommandMap::iterator pos;
1405
1406 pos = m_command_dict.find ("script");
1407 if (pos != m_command_dict.end())
Chris Lattner24943d22010-06-08 16:52:24 +00001408 {
Greg Clayton63094e02010-06-23 01:19:29 +00001409 CommandObject *script_cmd_obj = pos->second.get();
Greg Clayton238c0a12010-09-18 01:14:36 +00001410 return ((CommandObjectScript *) script_cmd_obj)->GetInterpreter ();
Chris Lattner24943d22010-06-08 16:52:24 +00001411 }
Greg Clayton63094e02010-06-23 01:19:29 +00001412 return NULL;
Chris Lattner24943d22010-06-08 16:52:24 +00001413}
1414
1415
1416
1417bool
1418CommandInterpreter::GetSynchronous ()
1419{
1420 return m_synchronous_execution;
1421}
1422
1423void
1424CommandInterpreter::SetSynchronous (bool value)
1425{
Johnny Chend7a4eb02010-10-14 01:22:03 +00001426 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00001427}
1428
1429void
1430CommandInterpreter::OutputFormattedHelpText (Stream &strm,
1431 const char *word_text,
1432 const char *separator,
1433 const char *help_text,
1434 uint32_t max_word_len)
1435{
Greg Clayton238c0a12010-09-18 01:14:36 +00001436 const uint32_t max_columns = m_debugger.GetTerminalWidth();
1437
Chris Lattner24943d22010-06-08 16:52:24 +00001438 int indent_size = max_word_len + strlen (separator) + 2;
1439
1440 strm.IndentMore (indent_size);
1441
1442 int len = indent_size + strlen (help_text) + 1;
1443 char *text = (char *) malloc (len);
1444 sprintf (text, "%-*s %s %s", max_word_len, word_text, separator, help_text);
1445 if (text[len - 1] == '\n')
1446 text[--len] = '\0';
1447
1448 if (len < max_columns)
1449 {
1450 // Output it as a single line.
1451 strm.Printf ("%s", text);
1452 }
1453 else
1454 {
1455 // We need to break it up into multiple lines.
1456 bool first_line = true;
1457 int text_width;
1458 int start = 0;
1459 int end = start;
1460 int final_end = strlen (text);
1461 int sub_len;
1462
1463 while (end < final_end)
1464 {
1465 if (first_line)
1466 text_width = max_columns - 1;
1467 else
1468 text_width = max_columns - indent_size - 1;
1469
1470 // Don't start the 'text' on a space, since we're already outputting the indentation.
1471 if (!first_line)
1472 {
1473 while ((start < final_end) && (text[start] == ' '))
1474 start++;
1475 }
1476
1477 end = start + text_width;
1478 if (end > final_end)
1479 end = final_end;
1480 else
1481 {
1482 // If we're not at the end of the text, make sure we break the line on white space.
1483 while (end > start
1484 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
1485 end--;
1486 }
1487
1488 sub_len = end - start;
1489 if (start != 0)
1490 strm.EOL();
1491 if (!first_line)
1492 strm.Indent();
1493 else
1494 first_line = false;
1495 assert (start <= final_end);
1496 assert (start + sub_len <= final_end);
1497 if (sub_len > 0)
1498 strm.Write (text + start, sub_len);
1499 start = end + 1;
1500 }
1501 }
1502 strm.EOL();
1503 strm.IndentLess(indent_size);
1504 free (text);
1505}
1506
1507void
1508CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
1509 StringList &commands_found, StringList &commands_help)
1510{
1511 CommandObject::CommandMap::const_iterator pos;
1512 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
1513 CommandObject *sub_cmd_obj;
1514
1515 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
1516 {
1517 const char * command_name = pos->first.c_str();
1518 sub_cmd_obj = pos->second.get();
1519 StreamString complete_command_name;
1520
1521 complete_command_name.Printf ("%s %s", prefix, command_name);
1522
Greg Clayton238c0a12010-09-18 01:14:36 +00001523 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001524 {
1525 commands_found.AppendString (complete_command_name.GetData());
1526 commands_help.AppendString (sub_cmd_obj->GetHelp());
1527 }
1528
1529 if (sub_cmd_obj->IsMultiwordObject())
1530 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
1531 commands_help);
1532 }
1533
1534}
1535
1536void
1537CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
1538 StringList &commands_help)
1539{
1540 CommandObject::CommandMap::const_iterator pos;
1541
1542 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1543 {
1544 const char *command_name = pos->first.c_str();
1545 CommandObject *cmd_obj = pos->second.get();
1546
Greg Clayton238c0a12010-09-18 01:14:36 +00001547 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001548 {
1549 commands_found.AppendString (command_name);
1550 commands_help.AppendString (cmd_obj->GetHelp());
1551 }
1552
1553 if (cmd_obj->IsMultiwordObject())
1554 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
1555
1556 }
1557}