blob: 8c4c884f0c8d816570221dbea93184fb7d5e6f52 [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{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000317 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
318 CommandObjectSP ret_val; // Possibly empty return value.
319
320 if (cmd_cstr == NULL)
321 return ret_val;
322
323 if (cmd_words.GetArgumentCount() == 1)
324 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
325 else
326 {
327 // We have a multi-word command (seemingly), so we need to do more work.
328 // First, get the cmd_obj_sp for the first word in the command.
329 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
330 if (cmd_obj_sp.get() != NULL)
331 {
332 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
333 // command name), and find the appropriate sub-command SP for each command word....
334 size_t end = cmd_words.GetArgumentCount();
335 for (size_t j= 1; j < end; ++j)
336 {
337 if (cmd_obj_sp->IsMultiwordObject())
338 {
339 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
340 (cmd_words.GetArgumentAtIndex (j));
341 if (cmd_obj_sp.get() == NULL)
342 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
343 return ret_val;
344 }
345 else
346 // We have more words in the command name, but we don't have a multiword object. Fail and return
347 // empty 'ret_val'.
348 return ret_val;
349 }
350 // We successfully looped through all the command words and got valid command objects for them. Assign the
351 // last object retrieved to 'ret_val'.
352 ret_val = cmd_obj_sp;
353 }
354 }
355 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000356}
357
358CommandObject *
359CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
360{
361 return GetCommandSPExact (cmd_cstr, include_aliases).get();
362}
363
364CommandObject *
365CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
366{
367 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
368
369 // If we didn't find an exact match to the command string in the commands, look in
370 // the aliases.
371
372 if (command_obj == NULL)
373 {
374 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
375 }
376
377 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
378 // in both the commands and the aliases.
379
380 if (command_obj == NULL)
381 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
382
383 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000384}
385
386bool
387CommandInterpreter::CommandExists (const char *cmd)
388{
389 return m_command_dict.find(cmd) != m_command_dict.end();
390}
391
392bool
393CommandInterpreter::AliasExists (const char *cmd)
394{
395 return m_alias_dict.find(cmd) != m_alias_dict.end();
396}
397
398bool
399CommandInterpreter::UserCommandExists (const char *cmd)
400{
401 return m_user_dict.find(cmd) != m_user_dict.end();
402}
403
404void
405CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
406{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000407 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000408 m_alias_dict[alias_name] = command_obj_sp;
409}
410
411bool
412CommandInterpreter::RemoveAlias (const char *alias_name)
413{
414 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
415 if (pos != m_alias_dict.end())
416 {
417 m_alias_dict.erase(pos);
418 return true;
419 }
420 return false;
421}
422bool
423CommandInterpreter::RemoveUser (const char *alias_name)
424{
425 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
426 if (pos != m_user_dict.end())
427 {
428 m_user_dict.erase(pos);
429 return true;
430 }
431 return false;
432}
433
Chris Lattner24943d22010-06-08 16:52:24 +0000434void
435CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
436{
437 help_string.Printf ("'%s", command_name);
438 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
439
440 if (option_arg_vector_sp != NULL)
441 {
442 OptionArgVector *options = option_arg_vector_sp.get();
443 for (int i = 0; i < options->size(); ++i)
444 {
445 OptionArgPair cur_option = (*options)[i];
446 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000447 OptionArgValue value_pair = cur_option.second;
448 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000449 if (opt.compare("<argument>") == 0)
450 {
451 help_string.Printf (" %s", value.c_str());
452 }
453 else
454 {
455 help_string.Printf (" %s", opt.c_str());
456 if ((value.compare ("<no-argument>") != 0)
457 && (value.compare ("<need-argument") != 0))
458 {
459 help_string.Printf (" %s", value.c_str());
460 }
461 }
462 }
463 }
464
465 help_string.Printf ("'");
466}
467
Greg Clayton65124ea2010-08-26 22:05:43 +0000468size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000469CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
470{
471 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000472 CommandObject::CommandMap::const_iterator end = dict.end();
473 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000474
Greg Clayton65124ea2010-08-26 22:05:43 +0000475 for (pos = dict.begin(); pos != end; ++pos)
476 {
477 size_t len = pos->first.size();
478 if (max_len < len)
479 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000480 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000481 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000482}
483
484void
485CommandInterpreter::GetHelp (CommandReturnObject &result)
486{
487 CommandObject::CommandMap::const_iterator pos;
488 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
489 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000490 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000491
492 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
493 {
494 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
495 max_len);
496 }
497 result.AppendMessage("");
498
499 if (m_alias_dict.size() > 0)
500 {
Jim Inghame3663e82010-10-22 18:47:16 +0000501 result.AppendMessage("The following is a list of your current command abbreviations "
502 "(see 'help commands alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000503 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000504 max_len = FindLongestCommandWord (m_alias_dict);
505
Chris Lattner24943d22010-06-08 16:52:24 +0000506 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
507 {
508 StreamString sstr;
509 StreamString translation_and_help;
510 std::string entry_name = pos->first;
511 std::string second_entry = pos->second.get()->GetCommandName();
512 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
513
514 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
515 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
516 translation_and_help.GetData(), max_len);
517 }
518 result.AppendMessage("");
519 }
520
521 if (m_user_dict.size() > 0)
522 {
523 result.AppendMessage ("The following is a list of your current user-defined commands:");
524 result.AppendMessage("");
525 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
526 {
527 result.AppendMessageWithFormat ("%s -- %s\n", pos->first.c_str(), pos->second->GetHelp());
528 }
529 result.AppendMessage("");
530 }
531
532 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
533}
534
Caroline Ticee0da7a52010-12-09 22:52:49 +0000535CommandObject *
536CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000537{
Caroline Ticee0da7a52010-12-09 22:52:49 +0000538 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
539 // eventually be invoked by the given command line.
540
541 CommandObject *cmd_obj = NULL;
542 std::string white_space (" \t\v");
543 size_t start = command_string.find_first_not_of (white_space);
544 size_t end = 0;
545 bool done = false;
546 while (!done)
547 {
548 if (start != std::string::npos)
549 {
550 // Get the next word from command_string.
551 end = command_string.find_first_of (white_space, start);
552 if (end == std::string::npos)
553 end = command_string.size();
554 std::string cmd_word = command_string.substr (start, end - start);
555
556 if (cmd_obj == NULL)
557 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
558 // command or alias.
559 cmd_obj = GetCommandObject (cmd_word.c_str());
560 else if (cmd_obj->IsMultiwordObject ())
561 {
562 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
563 CommandObject *sub_cmd_obj =
564 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
565 if (sub_cmd_obj)
566 cmd_obj = sub_cmd_obj;
567 else // cmd_word was not a valid sub-command word, so we are donee
568 done = true;
569 }
570 else
571 // We have a cmd_obj and it is not a multi-word object, so we are done.
572 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000573
Caroline Ticee0da7a52010-12-09 22:52:49 +0000574 // If we didn't find a valid command object, or our command object is not a multi-word object, or
575 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
576 // next word.
577
578 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
579 done = true;
580 else
581 start = command_string.find_first_not_of (white_space, end);
582 }
583 else
584 // Unable to find any more words.
585 done = true;
586 }
587
588 if (end == command_string.size())
589 command_string.clear();
590 else
591 command_string = command_string.substr(end);
592
593 return cmd_obj;
594}
595
596bool
597CommandInterpreter::StripFirstWord (std::string &command_string, std::string &word)
598{
599 std::string white_space (" \t\v");
600 size_t start;
601 size_t end;
602
603 start = command_string.find_first_not_of (white_space);
604 if (start != std::string::npos)
605 {
606 end = command_string.find_first_of (white_space, start);
607 if (end != std::string::npos)
608 {
609 word = command_string.substr (start, end - start);
610 command_string = command_string.substr (end);
611 size_t pos = command_string.find_first_not_of (white_space);
612 if ((pos != 0) && (pos != std::string::npos))
613 command_string = command_string.substr (pos);
614 }
615 else
616 {
617 word = command_string.substr (start);
618 command_string.erase();
619 }
620
621 }
622 return true;
623}
624
625void
626CommandInterpreter::BuildAliasResult (const char *alias_name, std::string &raw_input_string, std::string &alias_result,
627 CommandObject *&alias_cmd_obj, CommandReturnObject &result)
628{
629 Args cmd_args (raw_input_string.c_str());
630 alias_cmd_obj = GetCommandObject (alias_name);
631 StreamString result_str;
632
633 if (alias_cmd_obj)
634 {
635 std::string alias_name_str = alias_name;
636 if ((cmd_args.GetArgumentCount() == 0)
637 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
638 cmd_args.Unshift (alias_name);
639
640 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
641 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
642
643 if (option_arg_vector_sp.get())
644 {
645 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
646
647 for (int i = 0; i < option_arg_vector->size(); ++i)
648 {
649 OptionArgPair option_pair = (*option_arg_vector)[i];
650 OptionArgValue value_pair = option_pair.second;
651 int value_type = value_pair.first;
652 std::string option = option_pair.first;
653 std::string value = value_pair.second;
654 if (option.compare ("<argument>") == 0)
655 result_str.Printf (" %s", value.c_str());
656 else
657 {
658 result_str.Printf (" %s", option.c_str());
659 if (value_type != optional_argument)
660 result_str.Printf (" ");
661 if (value.compare ("<no_argument>") != 0)
662 {
663 int index = GetOptionArgumentPosition (value.c_str());
664 if (index == 0)
665 result_str.Printf ("%s", value.c_str());
666 else if (index >= cmd_args.GetArgumentCount())
667 {
668
669 result.AppendErrorWithFormat
670 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
671 index);
672 result.SetStatus (eReturnStatusFailed);
673 return;
674 }
675 else
676 {
677 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
678 if (strpos != std::string::npos)
679 raw_input_string = raw_input_string.erase (strpos,
680 strlen (cmd_args.GetArgumentAtIndex (index)));
681 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
682 }
683 }
684 }
685 }
686 }
687
688 alias_result = result_str.GetData();
689 }
690}
691
692bool
693CommandInterpreter::HandleCommand (const char *command_line,
694 bool add_to_history,
695 CommandReturnObject &result,
696 ExecutionContext *override_context)
697{
698 bool done = false;
699 CommandObject *cmd_obj = NULL;
700 std::string next_word;
701 bool wants_raw_input = false;
702 std::string command_string (command_line);
703
704 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +0000705 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
706
707 // Make a scoped cleanup object that will clear the crash description string
708 // on exit of this function.
709 lldb_utility::CleanUp <const char *, void> crash_description_cleanup(NULL, Host::SetCrashDescription);
710
Caroline Ticee0da7a52010-12-09 22:52:49 +0000711 if (log)
712 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +0000713
Jim Inghamabab14b2010-11-04 23:08:45 +0000714 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
715
Greg Clayton63094e02010-06-23 01:19:29 +0000716 m_debugger.UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +0000717
718 if (command_line == NULL || command_line[0] == '\0')
719 {
720 if (m_command_history.empty())
721 {
722 result.AppendError ("empty command");
723 result.SetStatus(eReturnStatusFailed);
724 return false;
725 }
726 else
727 {
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000728 command_line = m_repeat_command.c_str();
Caroline Ticee0da7a52010-12-09 22:52:49 +0000729 command_string = command_line;
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000730 if (m_repeat_command.empty())
731 {
Jim Ingham767af882010-07-07 03:36:20 +0000732 result.AppendErrorWithFormat("No auto repeat.\n");
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000733 result.SetStatus (eReturnStatusFailed);
734 return false;
735 }
Chris Lattner24943d22010-06-08 16:52:24 +0000736 }
737 add_to_history = false;
738 }
739
Caroline Ticee0da7a52010-12-09 22:52:49 +0000740 // Phase 1.
741
742 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
743 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
744 // the user could have specified an alias, and in translating the alias there may also be command options and/or
745 // even data (including raw text strings) that need to be found and inserted into the command line as part of
746 // the translation. So this first step is plain look-up & replacement, resulting in three things: 1). the command
747 // object whose Execute method will actually be called; 2). a revised command string, with all substituitions &
748 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +0000749
Caroline Ticee0da7a52010-12-09 22:52:49 +0000750 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000751 size_t actual_cmd_name_len = 0;
Caroline Ticee0da7a52010-12-09 22:52:49 +0000752 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +0000753 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000754 StripFirstWord (command_string, next_word);
755 if (!cmd_obj && AliasExists (next_word.c_str()))
Chris Lattner24943d22010-06-08 16:52:24 +0000756 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000757 std::string alias_result;
758 BuildAliasResult (next_word.c_str(), command_string, alias_result, cmd_obj, result);
759 revised_command_line.Printf ("%s", alias_result.c_str());
760 if (cmd_obj)
Caroline Tice56d2fc42010-12-14 18:51:39 +0000761 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000762 wants_raw_input = cmd_obj->WantsRawCommandString ();
Caroline Tice56d2fc42010-12-14 18:51:39 +0000763 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
764 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000765 }
766 else if (!cmd_obj)
767 {
768 cmd_obj = GetCommandObject (next_word.c_str());
769 if (cmd_obj)
Chris Lattner24943d22010-06-08 16:52:24 +0000770 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000771 actual_cmd_name_len += next_word.length();
Caroline Ticee0da7a52010-12-09 22:52:49 +0000772 revised_command_line.Printf ("%s", next_word.c_str());
773 wants_raw_input = cmd_obj->WantsRawCommandString ();
Chris Lattner24943d22010-06-08 16:52:24 +0000774 }
775 else
776 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000777 revised_command_line.Printf ("%s", next_word.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000778 }
779 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000780 else if (cmd_obj->IsMultiwordObject ())
781 {
782 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
783 if (sub_cmd_obj)
784 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000785 actual_cmd_name_len += next_word.length() + 1;
Caroline Ticee0da7a52010-12-09 22:52:49 +0000786 revised_command_line.Printf (" %s", next_word.c_str());
787 cmd_obj = sub_cmd_obj;
788 wants_raw_input = cmd_obj->WantsRawCommandString ();
789 }
790 else
791 {
792 revised_command_line.Printf (" %s", next_word.c_str());
793 done = true;
794 }
795 }
796 else
797 {
798 revised_command_line.Printf (" %s", next_word.c_str());
799 done = true;
800 }
801
802 if (cmd_obj == NULL)
803 {
804 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
805 result.SetStatus (eReturnStatusFailed);
806 return false;
807 }
808
809 next_word.erase ();
810 if (command_string.length() == 0)
811 done = true;
812
Chris Lattner24943d22010-06-08 16:52:24 +0000813 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000814
815 if (command_string.size() > 0)
816 revised_command_line.Printf (" %s", command_string.c_str());
817
818 // End of Phase 1.
819 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
820 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
821 // fully translated with all substitutions & translations taken care of (still in raw text format); and
822 // wants_raw_input specifies whether the Execute method expects raw input or not.
823
824
825 if (log)
826 {
827 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
828 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
829 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
830 }
831
832 // Phase 2.
833 // Take care of things like setting up the history command & calling the appropriate Execute method on the
834 // CommandObject, with the appropriate arguments.
835
836 if (cmd_obj != NULL)
837 {
838 if (add_to_history)
839 {
840 Args command_args (revised_command_line.GetData());
841 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
842 if (repeat_command != NULL)
843 m_repeat_command.assign(repeat_command);
844 else
845 m_repeat_command.assign(command_line);
846
847 m_command_history.push_back (command_line);
848 }
849
850 command_string = revised_command_line.GetData();
851 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000852 std::string remainder;
853 if (actual_cmd_name_len < command_string.length())
854 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
855 // than cmd_obj->GetCommandName(), because name completion
856 // allows users to enter short versions of the names,
857 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +0000858
859 // Remove any initial spaces
860 std::string white_space (" \t\v");
861 size_t pos = remainder.find_first_not_of (white_space);
862 if (pos != 0 && pos != std::string::npos)
863 remainder = remainder.substr (pos);
864
865 if (log)
866 log->Printf ("HandleCommand, command line after removing command name(s): '%s'\n", remainder.c_str());
867
868
869 if (wants_raw_input)
870 cmd_obj->ExecuteRawCommandString (remainder.c_str(), result);
871 else
872 {
873 Args cmd_args (remainder.c_str());
874 cmd_obj->ExecuteWithOptions (cmd_args, result);
875 }
876 }
877 else
878 {
879 // We didn't find the first command object, so complete the first argument.
880 Args command_args (revised_command_line.GetData());
881 StringList matches;
882 int num_matches;
883 int cursor_index = 0;
884 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
885 bool word_complete;
886 num_matches = HandleCompletionMatches (command_args,
887 cursor_index,
888 cursor_char_position,
889 0,
890 -1,
891 word_complete,
892 matches);
893
894 if (num_matches > 0)
895 {
896 std::string error_msg;
897 error_msg.assign ("ambiguous command '");
898 error_msg.append(command_args.GetArgumentAtIndex(0));
899 error_msg.append ("'.");
900
901 error_msg.append (" Possible completions:");
902 for (int i = 0; i < num_matches; i++)
903 {
904 error_msg.append ("\n\t");
905 error_msg.append (matches.GetStringAtIndex (i));
906 }
907 error_msg.append ("\n");
908 result.AppendRawError (error_msg.c_str(), error_msg.size());
909 }
910 else
911 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
912
913 result.SetStatus (eReturnStatusFailed);
914 }
915
Chris Lattner24943d22010-06-08 16:52:24 +0000916 return result.Succeeded();
917}
918
919int
920CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
921 int &cursor_index,
922 int &cursor_char_position,
923 int match_start_point,
924 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +0000925 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000926 StringList &matches)
927{
928 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000929 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +0000930
931 // For any of the command completions a unique match will be a complete word.
932 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000933
934 if (cursor_index == -1)
935 {
936 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +0000937 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000938 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
939 }
940 else if (cursor_index == 0)
941 {
942 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000943 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000944 num_command_matches = matches.GetSize();
945
946 if (num_command_matches == 1
947 && cmd_obj && cmd_obj->IsMultiwordObject()
948 && matches.GetStringAtIndex(0) != NULL
949 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
950 {
951 look_for_subcommand = true;
952 num_command_matches = 0;
953 matches.DeleteStringAtIndex(0);
954 parsed_line.AppendArgument ("");
955 cursor_index++;
956 cursor_char_position = 0;
957 }
958 }
959
960 if (cursor_index > 0 || look_for_subcommand)
961 {
962 // We are completing further on into a commands arguments, so find the command and tell it
963 // to complete the command.
964 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +0000965 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +0000966 if (command_object == NULL)
967 {
968 return 0;
969 }
970 else
971 {
972 parsed_line.Shift();
973 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +0000974 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +0000975 cursor_index,
976 cursor_char_position,
977 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000978 max_return_elements,
979 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000980 matches);
981 }
982 }
983
984 return num_command_matches;
985
986}
987
988int
989CommandInterpreter::HandleCompletion (const char *current_line,
990 const char *cursor,
991 const char *last_char,
992 int match_start_point,
993 int max_return_elements,
994 StringList &matches)
995{
996 // We parse the argument up to the cursor, so the last argument in parsed_line is
997 // the one containing the cursor, and the cursor is after the last character.
998
999 Args parsed_line(current_line, last_char - current_line);
1000 Args partial_parsed_line(current_line, cursor - current_line);
1001
1002 int num_args = partial_parsed_line.GetArgumentCount();
1003 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1004 int cursor_char_position;
1005
1006 if (cursor_index == -1)
1007 cursor_char_position = 0;
1008 else
1009 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
1010
1011 int num_command_matches;
1012
1013 matches.Clear();
1014
1015 // Only max_return_elements == -1 is supported at present:
1016 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001017 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001018 num_command_matches = HandleCompletionMatches (parsed_line,
1019 cursor_index,
1020 cursor_char_position,
1021 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001022 max_return_elements,
1023 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001024 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001025
1026 if (num_command_matches <= 0)
1027 return num_command_matches;
1028
1029 if (num_args == 0)
1030 {
1031 // If we got an empty string, insert nothing.
1032 matches.InsertStringAtIndex(0, "");
1033 }
1034 else
1035 {
1036 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1037 // put an empty string in element 0.
1038 std::string command_partial_str;
1039 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001040 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1041 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001042
1043 std::string common_prefix;
1044 matches.LongestCommonPrefix (common_prefix);
1045 int partial_name_len = command_partial_str.size();
1046
1047 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001048 // Only do this if the completer told us this was a complete word, however...
1049 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001050 {
1051 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1052 if (quote_char != '\0')
1053 common_prefix.push_back(quote_char);
1054
1055 common_prefix.push_back(' ');
1056 }
1057 common_prefix.erase (0, partial_name_len);
1058 matches.InsertStringAtIndex(0, common_prefix.c_str());
1059 }
1060 return num_command_matches;
1061}
1062
Chris Lattner24943d22010-06-08 16:52:24 +00001063
1064CommandInterpreter::~CommandInterpreter ()
1065{
1066}
1067
1068const char *
1069CommandInterpreter::GetPrompt ()
1070{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001071 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001072}
1073
1074void
1075CommandInterpreter::SetPrompt (const char *new_prompt)
1076{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001077 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001078}
1079
Jim Ingham5e16ef52010-10-04 19:49:29 +00001080size_t
1081CommandInterpreter::GetConfirmationInputReaderCallback (void *baton,
1082 InputReader &reader,
1083 lldb::InputReaderAction action,
1084 const char *bytes,
1085 size_t bytes_len)
1086{
1087 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle();
1088 bool *response_ptr = (bool *) baton;
1089
1090 switch (action)
1091 {
1092 case eInputReaderActivate:
1093 if (out_fh)
1094 {
1095 if (reader.GetPrompt())
1096 ::fprintf (out_fh, "%s", reader.GetPrompt());
1097 }
1098 break;
1099
1100 case eInputReaderDeactivate:
1101 break;
1102
1103 case eInputReaderReactivate:
1104 if (out_fh && reader.GetPrompt())
1105 ::fprintf (out_fh, "%s", reader.GetPrompt());
1106 break;
1107
1108 case eInputReaderGotToken:
1109 if (bytes_len == 0)
1110 {
1111 reader.SetIsDone(true);
1112 }
1113 else if (bytes[0] == 'y')
1114 {
1115 *response_ptr = true;
1116 reader.SetIsDone(true);
1117 }
1118 else if (bytes[0] == 'n')
1119 {
1120 *response_ptr = false;
1121 reader.SetIsDone(true);
1122 }
1123 else
1124 {
1125 if (out_fh && !reader.IsDone() && reader.GetPrompt())
1126 {
1127 ::fprintf (out_fh, "Please answer \"y\" or \"n\"\n");
1128 ::fprintf (out_fh, "%s", reader.GetPrompt());
1129 }
1130 }
1131 break;
1132
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001133 case eInputReaderInterrupt:
1134 case eInputReaderEndOfFile:
1135 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1136 reader.SetIsDone (true);
1137 break;
1138
Jim Ingham5e16ef52010-10-04 19:49:29 +00001139 case eInputReaderDone:
1140 break;
1141 }
1142
1143 return bytes_len;
1144
1145}
1146
1147bool
1148CommandInterpreter::Confirm (const char *message, bool default_answer)
1149{
Jim Ingham93057472010-10-04 22:44:14 +00001150 // Check AutoConfirm first:
1151 if (m_debugger.GetAutoConfirm())
1152 return default_answer;
1153
Jim Ingham5e16ef52010-10-04 19:49:29 +00001154 InputReaderSP reader_sp (new InputReader(GetDebugger()));
1155 bool response = default_answer;
1156 if (reader_sp)
1157 {
1158 std::string prompt(message);
1159 prompt.append(": [");
1160 if (default_answer)
1161 prompt.append ("Y/n] ");
1162 else
1163 prompt.append ("y/N] ");
1164
1165 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1166 &response, // baton
1167 eInputReaderGranularityLine, // token size, to pass to callback function
1168 NULL, // end token
1169 prompt.c_str(), // prompt
1170 true)); // echo input
1171 if (err.Success())
1172 {
1173 GetDebugger().PushInputReader (reader_sp);
1174 }
1175 reader_sp->WaitOnReaderIsDone();
1176 }
1177 return response;
1178}
1179
1180
Chris Lattner24943d22010-06-08 16:52:24 +00001181void
1182CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1183{
Jim Inghamd40f8a62010-07-06 22:46:59 +00001184 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001185
1186 if (cmd_obj_sp != NULL)
1187 {
1188 CommandObject *cmd_obj = cmd_obj_sp.get();
1189 if (cmd_obj->IsCrossRefObject ())
1190 cmd_obj->AddObject (object_type);
1191 }
1192}
1193
Chris Lattner24943d22010-06-08 16:52:24 +00001194OptionArgVectorSP
1195CommandInterpreter::GetAliasOptions (const char *alias_name)
1196{
1197 OptionArgMap::iterator pos;
1198 OptionArgVectorSP ret_val;
1199
1200 std::string alias (alias_name);
1201
1202 if (HasAliasOptions())
1203 {
1204 pos = m_alias_options.find (alias);
1205 if (pos != m_alias_options.end())
1206 ret_val = pos->second;
1207 }
1208
1209 return ret_val;
1210}
1211
1212void
1213CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1214{
1215 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1216 if (pos != m_alias_options.end())
1217 {
1218 m_alias_options.erase (pos);
1219 }
1220}
1221
1222void
1223CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1224{
1225 m_alias_options[alias_name] = option_arg_vector_sp;
1226}
1227
1228bool
1229CommandInterpreter::HasCommands ()
1230{
1231 return (!m_command_dict.empty());
1232}
1233
1234bool
1235CommandInterpreter::HasAliases ()
1236{
1237 return (!m_alias_dict.empty());
1238}
1239
1240bool
1241CommandInterpreter::HasUserCommands ()
1242{
1243 return (!m_user_dict.empty());
1244}
1245
1246bool
1247CommandInterpreter::HasAliasOptions ()
1248{
1249 return (!m_alias_options.empty());
1250}
1251
Chris Lattner24943d22010-06-08 16:52:24 +00001252void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001253CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
1254 const char *alias_name,
1255 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00001256 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001257 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00001258{
1259 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00001260
1261 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00001262
Caroline Tice44c841d2010-12-07 19:58:26 +00001263 // Make sure that the alias name is the 0th element in cmd_args
1264 std::string alias_name_str = alias_name;
1265 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1266 cmd_args.Unshift (alias_name);
1267
1268 Args new_args (alias_cmd_obj->GetCommandName());
1269 if (new_args.GetArgumentCount() == 2)
1270 new_args.Shift();
1271
Chris Lattner24943d22010-06-08 16:52:24 +00001272 if (option_arg_vector_sp.get())
1273 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001274 if (wants_raw_input)
1275 {
1276 // We have a command that both has command options and takes raw input. Make *sure* it has a
1277 // " -- " in the right place in the raw_input_string.
1278 size_t pos = raw_input_string.find(" -- ");
1279 if (pos == std::string::npos)
1280 {
1281 // None found; assume it goes at the beginning of the raw input string
1282 raw_input_string.insert (0, " -- ");
1283 }
1284 }
Chris Lattner24943d22010-06-08 16:52:24 +00001285
1286 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1287 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001288 std::vector<bool> used (old_size + 1, false);
1289
1290 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001291
1292 for (int i = 0; i < option_arg_vector->size(); ++i)
1293 {
1294 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00001295 OptionArgValue value_pair = option_pair.second;
1296 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00001297 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00001298 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00001299 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001300 {
1301 if (!wants_raw_input
1302 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
1303 new_args.AppendArgument (value.c_str());
1304 }
Chris Lattner24943d22010-06-08 16:52:24 +00001305 else
1306 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001307 if (value_type != optional_argument)
1308 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001309 if (value.compare ("<no-argument>") != 0)
1310 {
1311 int index = GetOptionArgumentPosition (value.c_str());
1312 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001313 {
Chris Lattner24943d22010-06-08 16:52:24 +00001314 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00001315 if (value_type != optional_argument)
1316 new_args.AppendArgument (value.c_str());
1317 else
1318 {
1319 char buffer[255];
1320 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
1321 new_args.AppendArgument (buffer);
1322 }
1323
1324 }
Chris Lattner24943d22010-06-08 16:52:24 +00001325 else if (index >= cmd_args.GetArgumentCount())
1326 {
1327 result.AppendErrorWithFormat
1328 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1329 index);
1330 result.SetStatus (eReturnStatusFailed);
1331 return;
1332 }
1333 else
1334 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001335 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
1336 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1337 if (strpos != std::string::npos)
1338 {
1339 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
1340 }
1341
1342 if (value_type != optional_argument)
1343 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
1344 else
1345 {
1346 char buffer[255];
1347 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
1348 cmd_args.GetArgumentAtIndex (index));
1349 new_args.AppendArgument (buffer);
1350 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001351 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001352 }
1353 }
1354 }
1355 }
1356
1357 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1358 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001359 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00001360 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1361 }
1362
1363 cmd_args.Clear();
1364 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1365 }
1366 else
1367 {
1368 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00001369 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
1370 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
1371 // input string.
1372 if (wants_raw_input)
1373 {
1374 cmd_args.Clear();
1375 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1376 }
Chris Lattner24943d22010-06-08 16:52:24 +00001377 return;
1378 }
1379
1380 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1381 return;
1382}
1383
1384
1385int
1386CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1387{
1388 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1389 // of zero.
1390
1391 char *cptr = (char *) in_string;
1392
1393 // Does it start with '%'
1394 if (cptr[0] == '%')
1395 {
1396 ++cptr;
1397
1398 // Is the rest of it entirely digits?
1399 if (isdigit (cptr[0]))
1400 {
1401 const char *start = cptr;
1402 while (isdigit (cptr[0]))
1403 ++cptr;
1404
1405 // We've gotten to the end of the digits; are we at the end of the string?
1406 if (cptr[0] == '\0')
1407 position = atoi (start);
1408 }
1409 }
1410
1411 return position;
1412}
1413
1414void
1415CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1416{
Greg Clayton887aa282010-10-11 01:05:37 +00001417 // Don't parse any .lldbinit files if we were asked not to
1418 if (m_skip_lldbinit_files)
1419 return;
1420
Chris Lattner24943d22010-06-08 16:52:24 +00001421 const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit";
Greg Clayton537a7a82010-10-20 20:54:39 +00001422 FileSpec init_file (init_file_path, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001423 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
1424 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
1425
1426 if (init_file.Exists())
1427 {
1428 char path[PATH_MAX];
1429 init_file.GetPath(path, sizeof(path));
1430 StreamString source_command;
Johnny Chen7c984242010-07-28 21:16:11 +00001431 source_command.Printf ("command source '%s'", path);
Chris Lattner24943d22010-06-08 16:52:24 +00001432 HandleCommand (source_command.GetData(), false, result);
1433 }
1434 else
1435 {
1436 // nothing to be done if the file doesn't exist
1437 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1438 }
1439}
1440
1441ScriptInterpreter *
1442CommandInterpreter::GetScriptInterpreter ()
1443{
Greg Clayton63094e02010-06-23 01:19:29 +00001444 CommandObject::CommandMap::iterator pos;
1445
1446 pos = m_command_dict.find ("script");
1447 if (pos != m_command_dict.end())
Chris Lattner24943d22010-06-08 16:52:24 +00001448 {
Greg Clayton63094e02010-06-23 01:19:29 +00001449 CommandObject *script_cmd_obj = pos->second.get();
Greg Clayton238c0a12010-09-18 01:14:36 +00001450 return ((CommandObjectScript *) script_cmd_obj)->GetInterpreter ();
Chris Lattner24943d22010-06-08 16:52:24 +00001451 }
Greg Clayton63094e02010-06-23 01:19:29 +00001452 return NULL;
Chris Lattner24943d22010-06-08 16:52:24 +00001453}
1454
1455
1456
1457bool
1458CommandInterpreter::GetSynchronous ()
1459{
1460 return m_synchronous_execution;
1461}
1462
1463void
1464CommandInterpreter::SetSynchronous (bool value)
1465{
Johnny Chend7a4eb02010-10-14 01:22:03 +00001466 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00001467}
1468
1469void
1470CommandInterpreter::OutputFormattedHelpText (Stream &strm,
1471 const char *word_text,
1472 const char *separator,
1473 const char *help_text,
1474 uint32_t max_word_len)
1475{
Greg Clayton238c0a12010-09-18 01:14:36 +00001476 const uint32_t max_columns = m_debugger.GetTerminalWidth();
1477
Chris Lattner24943d22010-06-08 16:52:24 +00001478 int indent_size = max_word_len + strlen (separator) + 2;
1479
1480 strm.IndentMore (indent_size);
1481
1482 int len = indent_size + strlen (help_text) + 1;
1483 char *text = (char *) malloc (len);
1484 sprintf (text, "%-*s %s %s", max_word_len, word_text, separator, help_text);
1485 if (text[len - 1] == '\n')
1486 text[--len] = '\0';
1487
1488 if (len < max_columns)
1489 {
1490 // Output it as a single line.
1491 strm.Printf ("%s", text);
1492 }
1493 else
1494 {
1495 // We need to break it up into multiple lines.
1496 bool first_line = true;
1497 int text_width;
1498 int start = 0;
1499 int end = start;
1500 int final_end = strlen (text);
1501 int sub_len;
1502
1503 while (end < final_end)
1504 {
1505 if (first_line)
1506 text_width = max_columns - 1;
1507 else
1508 text_width = max_columns - indent_size - 1;
1509
1510 // Don't start the 'text' on a space, since we're already outputting the indentation.
1511 if (!first_line)
1512 {
1513 while ((start < final_end) && (text[start] == ' '))
1514 start++;
1515 }
1516
1517 end = start + text_width;
1518 if (end > final_end)
1519 end = final_end;
1520 else
1521 {
1522 // If we're not at the end of the text, make sure we break the line on white space.
1523 while (end > start
1524 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
1525 end--;
1526 }
1527
1528 sub_len = end - start;
1529 if (start != 0)
1530 strm.EOL();
1531 if (!first_line)
1532 strm.Indent();
1533 else
1534 first_line = false;
1535 assert (start <= final_end);
1536 assert (start + sub_len <= final_end);
1537 if (sub_len > 0)
1538 strm.Write (text + start, sub_len);
1539 start = end + 1;
1540 }
1541 }
1542 strm.EOL();
1543 strm.IndentLess(indent_size);
1544 free (text);
1545}
1546
1547void
1548CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
1549 StringList &commands_found, StringList &commands_help)
1550{
1551 CommandObject::CommandMap::const_iterator pos;
1552 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
1553 CommandObject *sub_cmd_obj;
1554
1555 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
1556 {
1557 const char * command_name = pos->first.c_str();
1558 sub_cmd_obj = pos->second.get();
1559 StreamString complete_command_name;
1560
1561 complete_command_name.Printf ("%s %s", prefix, command_name);
1562
Greg Clayton238c0a12010-09-18 01:14:36 +00001563 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001564 {
1565 commands_found.AppendString (complete_command_name.GetData());
1566 commands_help.AppendString (sub_cmd_obj->GetHelp());
1567 }
1568
1569 if (sub_cmd_obj->IsMultiwordObject())
1570 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
1571 commands_help);
1572 }
1573
1574}
1575
1576void
1577CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
1578 StringList &commands_help)
1579{
1580 CommandObject::CommandMap::const_iterator pos;
1581
1582 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1583 {
1584 const char *command_name = pos->first.c_str();
1585 CommandObject *cmd_obj = pos->second.get();
1586
Greg Clayton238c0a12010-09-18 01:14:36 +00001587 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001588 {
1589 commands_found.AppendString (command_name);
1590 commands_help.AppendString (cmd_obj->GetHelp());
1591 }
1592
1593 if (cmd_obj->IsMultiwordObject())
1594 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
1595
1596 }
1597}