blob: b65cb1988a494ac13e84a1047eb2593488c78d6b [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"
Johnny Chen902e0182010-12-23 20:21:44 +000039#include "../Commands/CommandObjectVersion.h"
Chris Lattner24943d22010-06-08 16:52:24 +000040
Jim Ingham84cdc152010-06-15 19:49:27 +000041#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000042#include "lldb/Core/Debugger.h"
Jim Ingham5e16ef52010-10-04 19:49:29 +000043#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000044#include "lldb/Core/Stream.h"
45#include "lldb/Core/Timer.h"
46#include "lldb/Target/Process.h"
47#include "lldb/Target/Thread.h"
48#include "lldb/Target/TargetList.h"
Greg Claytone98ac252010-11-10 04:57:04 +000049#include "lldb/Utility/CleanUp.h"
Chris Lattner24943d22010-06-08 16:52:24 +000050
51#include "lldb/Interpreter/CommandReturnObject.h"
52#include "lldb/Interpreter/CommandInterpreter.h"
53
54using namespace lldb;
55using namespace lldb_private;
56
57CommandInterpreter::CommandInterpreter
58(
Greg Clayton63094e02010-06-23 01:19:29 +000059 Debugger &debugger,
Chris Lattner24943d22010-06-08 16:52:24 +000060 ScriptLanguage script_language,
Greg Clayton63094e02010-06-23 01:19:29 +000061 bool synchronous_execution
Chris Lattner24943d22010-06-08 16:52:24 +000062) :
Greg Clayton49ce6822010-10-31 03:01:06 +000063 Broadcaster ("lldb.command-interpreter"),
Greg Clayton63094e02010-06-23 01:19:29 +000064 m_debugger (debugger),
Greg Clayton887aa282010-10-11 01:05:37 +000065 m_synchronous_execution (synchronous_execution),
66 m_skip_lldbinit_files (false)
Chris Lattner24943d22010-06-08 16:52:24 +000067{
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000068 const char *dbg_name = debugger.GetInstanceName().AsCString();
69 std::string lang_name = ScriptInterpreter::LanguageToString (script_language);
70 StreamString var_name;
71 var_name.Printf ("[%s].script-lang", dbg_name);
Caroline Tice1d2aefd2010-09-09 06:25:08 +000072 debugger.GetSettingsController()->SetVariable (var_name.GetData(), lang_name.c_str(),
73 lldb::eVarSetOperationAssign, false,
Greg Clayton49ce6822010-10-31 03:01:06 +000074 m_debugger.GetInstanceName().AsCString());
75 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
76 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
77 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Chris Lattner24943d22010-06-08 16:52:24 +000078}
79
80void
81CommandInterpreter::Initialize ()
82{
83 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
84
85 CommandReturnObject result;
86
87 LoadCommandDictionary ();
88
Chris Lattner24943d22010-06-08 16:52:24 +000089 // Set up some initial aliases.
Jim Ingham767af882010-07-07 03:36:20 +000090 result.Clear(); HandleCommand ("command alias q quit", false, result);
Jim Inghame3663e82010-10-22 18:47:16 +000091 result.Clear(); HandleCommand ("command alias run process launch --", false, result);
92 result.Clear(); HandleCommand ("command alias r process launch --", false, result);
Jim Ingham767af882010-07-07 03:36:20 +000093 result.Clear(); HandleCommand ("command alias c process continue", false, result);
94 result.Clear(); HandleCommand ("command alias continue process continue", false, result);
95 result.Clear(); HandleCommand ("command alias expr expression", false, result);
96 result.Clear(); HandleCommand ("command alias exit quit", false, result);
Greg Clayton0f3a8eb2010-09-16 17:09:23 +000097 result.Clear(); HandleCommand ("command alias b regexp-break", false, result);
Jim Ingham767af882010-07-07 03:36:20 +000098 result.Clear(); HandleCommand ("command alias bt thread backtrace", false, result);
99 result.Clear(); HandleCommand ("command alias si thread step-inst", false, result);
100 result.Clear(); HandleCommand ("command alias step thread step-in", false, result);
101 result.Clear(); HandleCommand ("command alias s thread step-in", false, result);
102 result.Clear(); HandleCommand ("command alias next thread step-over", false, result);
103 result.Clear(); HandleCommand ("command alias n thread step-over", false, result);
104 result.Clear(); HandleCommand ("command alias finish thread step-out", false, result);
105 result.Clear(); HandleCommand ("command alias x memory read", false, result);
106 result.Clear(); HandleCommand ("command alias l source list", false, result);
107 result.Clear(); HandleCommand ("command alias list source list", false, result);
Greg Clayton0f3a8eb2010-09-16 17:09:23 +0000108 result.Clear(); HandleCommand ("command alias p frame variable", false, result);
109 result.Clear(); HandleCommand ("command alias print frame variable", false, result);
Jim Inghame3663e82010-10-22 18:47:16 +0000110 result.Clear(); HandleCommand ("command alias po expression -o --", false, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000111}
112
Chris Lattner24943d22010-06-08 16:52:24 +0000113const char *
114CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
115{
116 // This function has not yet been implemented.
117
118 // Look for any embedded script command
119 // If found,
120 // get interpreter object from the command dictionary,
121 // call execute_one_command on it,
122 // get the results as a string,
123 // substitute that string for current stuff.
124
125 return arg;
126}
127
128
129void
130CommandInterpreter::LoadCommandDictionary ()
131{
132 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
133
134 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
135 //
136 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
137 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
138 // the cross-referencing stuff) are created!!!
139 //
140 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
141
142
143 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
144 // are created. This is so that when another command is created that needs to go into a crossref object,
145 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
146 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
147
Chris Lattner24943d22010-06-08 16:52:24 +0000148 // Non-CommandObjectCrossref commands can now be created.
149
Caroline Tice5bc8c972010-09-20 20:44:43 +0000150 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000151
Greg Clayton238c0a12010-09-18 01:14:36 +0000152 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000153 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000154 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000155 m_command_dict["commands"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000156 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
157 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
158 m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000159 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000160 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000161 m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
162 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
163 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
164 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000165 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000166 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000167 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000168 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000169 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000170 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
171 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000172 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000173
174 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000175 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
176 "regexp-break",
Caroline Ticec1ad82e2010-09-07 22:38:08 +0000177 "Set a breakpoint using a regular expression to specify the location.",
Caroline Tice43b014a2010-10-04 22:28:36 +0000178 "regexp-break [<filename>:<linenum>]\nregexp-break [<address>]\nregexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000179 if (break_regex_cmd_ap.get())
180 {
181 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
182 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
183 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
184 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list") &&
185 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
186 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
187 {
188 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
189 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
190 }
191 }
192}
193
194int
195CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
196 StringList &matches)
197{
198 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
199
200 if (include_aliases)
201 {
202 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
203 }
204
205 return matches.GetSize();
206}
207
208CommandObjectSP
209CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
210{
211 CommandObject::CommandMap::iterator pos;
212 CommandObjectSP ret_val;
213
214 std::string cmd(cmd_cstr);
215
216 if (HasCommands())
217 {
218 pos = m_command_dict.find(cmd);
219 if (pos != m_command_dict.end())
220 ret_val = pos->second;
221 }
222
223 if (include_aliases && HasAliases())
224 {
225 pos = m_alias_dict.find(cmd);
226 if (pos != m_alias_dict.end())
227 ret_val = pos->second;
228 }
229
230 if (HasUserCommands())
231 {
232 pos = m_user_dict.find(cmd);
233 if (pos != m_user_dict.end())
234 ret_val = pos->second;
235 }
236
237 if (!exact && ret_val == NULL)
238 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000239 // We will only get into here if we didn't find any exact matches.
240
241 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
242
Chris Lattner24943d22010-06-08 16:52:24 +0000243 StringList local_matches;
244 if (matches == NULL)
245 matches = &local_matches;
246
Jim Inghamd40f8a62010-07-06 22:46:59 +0000247 unsigned int num_cmd_matches = 0;
248 unsigned int num_alias_matches = 0;
249 unsigned int num_user_matches = 0;
250
251 // Look through the command dictionaries one by one, and if we get only one match from any of
252 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
253
Chris Lattner24943d22010-06-08 16:52:24 +0000254 if (HasCommands())
255 {
256 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
257 }
258
259 if (num_cmd_matches == 1)
260 {
261 cmd.assign(matches->GetStringAtIndex(0));
262 pos = m_command_dict.find(cmd);
263 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000264 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000265 }
266
Jim Ingham9a574172010-06-24 20:28:42 +0000267 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000268 {
269 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
270
271 }
272
Jim Inghamd40f8a62010-07-06 22:46:59 +0000273 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000274 {
275 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
276 pos = m_alias_dict.find(cmd);
277 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000278 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000279 }
280
Jim Ingham9a574172010-06-24 20:28:42 +0000281 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000282 {
283 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
284 }
285
Jim Inghamd40f8a62010-07-06 22:46:59 +0000286 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000287 {
288 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
289
290 pos = m_user_dict.find (cmd);
291 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000292 user_match_sp = pos->second;
293 }
294
295 // If we got exactly one match, return that, otherwise return the match list.
296
297 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
298 {
299 if (num_cmd_matches)
300 return real_match_sp;
301 else if (num_alias_matches)
302 return alias_match_sp;
303 else
304 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000305 }
306 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000307 else if (matches && ret_val != NULL)
308 {
309 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000310 }
311
312
313 return ret_val;
314}
315
Jim Inghamd40f8a62010-07-06 22:46:59 +0000316CommandObjectSP
317CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000318{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000319 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
320 CommandObjectSP ret_val; // Possibly empty return value.
321
322 if (cmd_cstr == NULL)
323 return ret_val;
324
325 if (cmd_words.GetArgumentCount() == 1)
326 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
327 else
328 {
329 // We have a multi-word command (seemingly), so we need to do more work.
330 // First, get the cmd_obj_sp for the first word in the command.
331 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
332 if (cmd_obj_sp.get() != NULL)
333 {
334 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
335 // command name), and find the appropriate sub-command SP for each command word....
336 size_t end = cmd_words.GetArgumentCount();
337 for (size_t j= 1; j < end; ++j)
338 {
339 if (cmd_obj_sp->IsMultiwordObject())
340 {
341 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
342 (cmd_words.GetArgumentAtIndex (j));
343 if (cmd_obj_sp.get() == NULL)
344 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
345 return ret_val;
346 }
347 else
348 // We have more words in the command name, but we don't have a multiword object. Fail and return
349 // empty 'ret_val'.
350 return ret_val;
351 }
352 // We successfully looped through all the command words and got valid command objects for them. Assign the
353 // last object retrieved to 'ret_val'.
354 ret_val = cmd_obj_sp;
355 }
356 }
357 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000358}
359
360CommandObject *
361CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
362{
363 return GetCommandSPExact (cmd_cstr, include_aliases).get();
364}
365
366CommandObject *
367CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
368{
369 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
370
371 // If we didn't find an exact match to the command string in the commands, look in
372 // the aliases.
373
374 if (command_obj == NULL)
375 {
376 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
377 }
378
379 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
380 // in both the commands and the aliases.
381
382 if (command_obj == NULL)
383 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
384
385 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000386}
387
388bool
389CommandInterpreter::CommandExists (const char *cmd)
390{
391 return m_command_dict.find(cmd) != m_command_dict.end();
392}
393
394bool
395CommandInterpreter::AliasExists (const char *cmd)
396{
397 return m_alias_dict.find(cmd) != m_alias_dict.end();
398}
399
400bool
401CommandInterpreter::UserCommandExists (const char *cmd)
402{
403 return m_user_dict.find(cmd) != m_user_dict.end();
404}
405
406void
407CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
408{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000409 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000410 m_alias_dict[alias_name] = command_obj_sp;
411}
412
413bool
414CommandInterpreter::RemoveAlias (const char *alias_name)
415{
416 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
417 if (pos != m_alias_dict.end())
418 {
419 m_alias_dict.erase(pos);
420 return true;
421 }
422 return false;
423}
424bool
425CommandInterpreter::RemoveUser (const char *alias_name)
426{
427 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
428 if (pos != m_user_dict.end())
429 {
430 m_user_dict.erase(pos);
431 return true;
432 }
433 return false;
434}
435
Chris Lattner24943d22010-06-08 16:52:24 +0000436void
437CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
438{
439 help_string.Printf ("'%s", command_name);
440 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
441
442 if (option_arg_vector_sp != NULL)
443 {
444 OptionArgVector *options = option_arg_vector_sp.get();
445 for (int i = 0; i < options->size(); ++i)
446 {
447 OptionArgPair cur_option = (*options)[i];
448 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000449 OptionArgValue value_pair = cur_option.second;
450 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000451 if (opt.compare("<argument>") == 0)
452 {
453 help_string.Printf (" %s", value.c_str());
454 }
455 else
456 {
457 help_string.Printf (" %s", opt.c_str());
458 if ((value.compare ("<no-argument>") != 0)
459 && (value.compare ("<need-argument") != 0))
460 {
461 help_string.Printf (" %s", value.c_str());
462 }
463 }
464 }
465 }
466
467 help_string.Printf ("'");
468}
469
Greg Clayton65124ea2010-08-26 22:05:43 +0000470size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000471CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
472{
473 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000474 CommandObject::CommandMap::const_iterator end = dict.end();
475 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000476
Greg Clayton65124ea2010-08-26 22:05:43 +0000477 for (pos = dict.begin(); pos != end; ++pos)
478 {
479 size_t len = pos->first.size();
480 if (max_len < len)
481 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000482 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000483 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000484}
485
486void
487CommandInterpreter::GetHelp (CommandReturnObject &result)
488{
489 CommandObject::CommandMap::const_iterator pos;
490 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
491 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000492 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000493
494 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
495 {
496 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
497 max_len);
498 }
499 result.AppendMessage("");
500
501 if (m_alias_dict.size() > 0)
502 {
Jim Inghame3663e82010-10-22 18:47:16 +0000503 result.AppendMessage("The following is a list of your current command abbreviations "
504 "(see 'help commands alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000505 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000506 max_len = FindLongestCommandWord (m_alias_dict);
507
Chris Lattner24943d22010-06-08 16:52:24 +0000508 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
509 {
510 StreamString sstr;
511 StreamString translation_and_help;
512 std::string entry_name = pos->first;
513 std::string second_entry = pos->second.get()->GetCommandName();
514 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
515
516 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
517 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
518 translation_and_help.GetData(), max_len);
519 }
520 result.AppendMessage("");
521 }
522
523 if (m_user_dict.size() > 0)
524 {
525 result.AppendMessage ("The following is a list of your current user-defined commands:");
526 result.AppendMessage("");
527 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
528 {
529 result.AppendMessageWithFormat ("%s -- %s\n", pos->first.c_str(), pos->second->GetHelp());
530 }
531 result.AppendMessage("");
532 }
533
534 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
535}
536
Caroline Ticee0da7a52010-12-09 22:52:49 +0000537CommandObject *
538CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000539{
Caroline Ticee0da7a52010-12-09 22:52:49 +0000540 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
541 // eventually be invoked by the given command line.
542
543 CommandObject *cmd_obj = NULL;
544 std::string white_space (" \t\v");
545 size_t start = command_string.find_first_not_of (white_space);
546 size_t end = 0;
547 bool done = false;
548 while (!done)
549 {
550 if (start != std::string::npos)
551 {
552 // Get the next word from command_string.
553 end = command_string.find_first_of (white_space, start);
554 if (end == std::string::npos)
555 end = command_string.size();
556 std::string cmd_word = command_string.substr (start, end - start);
557
558 if (cmd_obj == NULL)
559 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
560 // command or alias.
561 cmd_obj = GetCommandObject (cmd_word.c_str());
562 else if (cmd_obj->IsMultiwordObject ())
563 {
564 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
565 CommandObject *sub_cmd_obj =
566 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
567 if (sub_cmd_obj)
568 cmd_obj = sub_cmd_obj;
569 else // cmd_word was not a valid sub-command word, so we are donee
570 done = true;
571 }
572 else
573 // We have a cmd_obj and it is not a multi-word object, so we are done.
574 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000575
Caroline Ticee0da7a52010-12-09 22:52:49 +0000576 // If we didn't find a valid command object, or our command object is not a multi-word object, or
577 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
578 // next word.
579
580 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
581 done = true;
582 else
583 start = command_string.find_first_not_of (white_space, end);
584 }
585 else
586 // Unable to find any more words.
587 done = true;
588 }
589
590 if (end == command_string.size())
591 command_string.clear();
592 else
593 command_string = command_string.substr(end);
594
595 return cmd_obj;
596}
597
598bool
599CommandInterpreter::StripFirstWord (std::string &command_string, std::string &word)
600{
601 std::string white_space (" \t\v");
602 size_t start;
603 size_t end;
604
605 start = command_string.find_first_not_of (white_space);
606 if (start != std::string::npos)
607 {
608 end = command_string.find_first_of (white_space, start);
609 if (end != std::string::npos)
610 {
611 word = command_string.substr (start, end - start);
612 command_string = command_string.substr (end);
613 size_t pos = command_string.find_first_not_of (white_space);
614 if ((pos != 0) && (pos != std::string::npos))
615 command_string = command_string.substr (pos);
616 }
617 else
618 {
619 word = command_string.substr (start);
620 command_string.erase();
621 }
622
623 }
624 return true;
625}
626
627void
628CommandInterpreter::BuildAliasResult (const char *alias_name, std::string &raw_input_string, std::string &alias_result,
629 CommandObject *&alias_cmd_obj, CommandReturnObject &result)
630{
631 Args cmd_args (raw_input_string.c_str());
632 alias_cmd_obj = GetCommandObject (alias_name);
633 StreamString result_str;
634
635 if (alias_cmd_obj)
636 {
637 std::string alias_name_str = alias_name;
638 if ((cmd_args.GetArgumentCount() == 0)
639 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
640 cmd_args.Unshift (alias_name);
641
642 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
643 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
644
645 if (option_arg_vector_sp.get())
646 {
647 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
648
649 for (int i = 0; i < option_arg_vector->size(); ++i)
650 {
651 OptionArgPair option_pair = (*option_arg_vector)[i];
652 OptionArgValue value_pair = option_pair.second;
653 int value_type = value_pair.first;
654 std::string option = option_pair.first;
655 std::string value = value_pair.second;
656 if (option.compare ("<argument>") == 0)
657 result_str.Printf (" %s", value.c_str());
658 else
659 {
660 result_str.Printf (" %s", option.c_str());
661 if (value_type != optional_argument)
662 result_str.Printf (" ");
663 if (value.compare ("<no_argument>") != 0)
664 {
665 int index = GetOptionArgumentPosition (value.c_str());
666 if (index == 0)
667 result_str.Printf ("%s", value.c_str());
668 else if (index >= cmd_args.GetArgumentCount())
669 {
670
671 result.AppendErrorWithFormat
672 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
673 index);
674 result.SetStatus (eReturnStatusFailed);
675 return;
676 }
677 else
678 {
679 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
680 if (strpos != std::string::npos)
681 raw_input_string = raw_input_string.erase (strpos,
682 strlen (cmd_args.GetArgumentAtIndex (index)));
683 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
684 }
685 }
686 }
687 }
688 }
689
690 alias_result = result_str.GetData();
691 }
692}
693
694bool
695CommandInterpreter::HandleCommand (const char *command_line,
696 bool add_to_history,
697 CommandReturnObject &result,
698 ExecutionContext *override_context)
699{
700 bool done = false;
701 CommandObject *cmd_obj = NULL;
702 std::string next_word;
703 bool wants_raw_input = false;
704 std::string command_string (command_line);
705
706 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +0000707 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
708
709 // Make a scoped cleanup object that will clear the crash description string
710 // on exit of this function.
711 lldb_utility::CleanUp <const char *, void> crash_description_cleanup(NULL, Host::SetCrashDescription);
712
Caroline Ticee0da7a52010-12-09 22:52:49 +0000713 if (log)
714 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +0000715
Jim Inghamabab14b2010-11-04 23:08:45 +0000716 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
717
Greg Clayton63094e02010-06-23 01:19:29 +0000718 m_debugger.UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +0000719
720 if (command_line == NULL || command_line[0] == '\0')
721 {
722 if (m_command_history.empty())
723 {
724 result.AppendError ("empty command");
725 result.SetStatus(eReturnStatusFailed);
726 return false;
727 }
728 else
729 {
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000730 command_line = m_repeat_command.c_str();
Caroline Ticee0da7a52010-12-09 22:52:49 +0000731 command_string = command_line;
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000732 if (m_repeat_command.empty())
733 {
Jim Ingham767af882010-07-07 03:36:20 +0000734 result.AppendErrorWithFormat("No auto repeat.\n");
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000735 result.SetStatus (eReturnStatusFailed);
736 return false;
737 }
Chris Lattner24943d22010-06-08 16:52:24 +0000738 }
739 add_to_history = false;
740 }
741
Caroline Ticee0da7a52010-12-09 22:52:49 +0000742 // Phase 1.
743
744 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
745 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
746 // the user could have specified an alias, and in translating the alias there may also be command options and/or
747 // even data (including raw text strings) that need to be found and inserted into the command line as part of
748 // the translation. So this first step is plain look-up & replacement, resulting in three things: 1). the command
749 // object whose Execute method will actually be called; 2). a revised command string, with all substituitions &
750 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +0000751
Caroline Ticee0da7a52010-12-09 22:52:49 +0000752 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000753 size_t actual_cmd_name_len = 0;
Caroline Ticee0da7a52010-12-09 22:52:49 +0000754 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +0000755 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000756 StripFirstWord (command_string, next_word);
757 if (!cmd_obj && AliasExists (next_word.c_str()))
Chris Lattner24943d22010-06-08 16:52:24 +0000758 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000759 std::string alias_result;
760 BuildAliasResult (next_word.c_str(), command_string, alias_result, cmd_obj, result);
761 revised_command_line.Printf ("%s", alias_result.c_str());
762 if (cmd_obj)
Caroline Tice56d2fc42010-12-14 18:51:39 +0000763 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000764 wants_raw_input = cmd_obj->WantsRawCommandString ();
Caroline Tice56d2fc42010-12-14 18:51:39 +0000765 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
766 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000767 }
768 else if (!cmd_obj)
769 {
770 cmd_obj = GetCommandObject (next_word.c_str());
771 if (cmd_obj)
Chris Lattner24943d22010-06-08 16:52:24 +0000772 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000773 actual_cmd_name_len += next_word.length();
Caroline Ticee0da7a52010-12-09 22:52:49 +0000774 revised_command_line.Printf ("%s", next_word.c_str());
775 wants_raw_input = cmd_obj->WantsRawCommandString ();
Chris Lattner24943d22010-06-08 16:52:24 +0000776 }
777 else
778 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000779 revised_command_line.Printf ("%s", next_word.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000780 }
781 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000782 else if (cmd_obj->IsMultiwordObject ())
783 {
784 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
785 if (sub_cmd_obj)
786 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000787 actual_cmd_name_len += next_word.length() + 1;
Caroline Ticee0da7a52010-12-09 22:52:49 +0000788 revised_command_line.Printf (" %s", next_word.c_str());
789 cmd_obj = sub_cmd_obj;
790 wants_raw_input = cmd_obj->WantsRawCommandString ();
791 }
792 else
793 {
794 revised_command_line.Printf (" %s", next_word.c_str());
795 done = true;
796 }
797 }
798 else
799 {
800 revised_command_line.Printf (" %s", next_word.c_str());
801 done = true;
802 }
803
804 if (cmd_obj == NULL)
805 {
806 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
807 result.SetStatus (eReturnStatusFailed);
808 return false;
809 }
810
811 next_word.erase ();
812 if (command_string.length() == 0)
813 done = true;
814
Chris Lattner24943d22010-06-08 16:52:24 +0000815 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000816
817 if (command_string.size() > 0)
818 revised_command_line.Printf (" %s", command_string.c_str());
819
820 // End of Phase 1.
821 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
822 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
823 // fully translated with all substitutions & translations taken care of (still in raw text format); and
824 // wants_raw_input specifies whether the Execute method expects raw input or not.
825
826
827 if (log)
828 {
829 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
830 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
831 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
832 }
833
834 // Phase 2.
835 // Take care of things like setting up the history command & calling the appropriate Execute method on the
836 // CommandObject, with the appropriate arguments.
837
838 if (cmd_obj != NULL)
839 {
840 if (add_to_history)
841 {
842 Args command_args (revised_command_line.GetData());
843 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
844 if (repeat_command != NULL)
845 m_repeat_command.assign(repeat_command);
846 else
847 m_repeat_command.assign(command_line);
848
849 m_command_history.push_back (command_line);
850 }
851
852 command_string = revised_command_line.GetData();
853 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000854 std::string remainder;
855 if (actual_cmd_name_len < command_string.length())
856 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
857 // than cmd_obj->GetCommandName(), because name completion
858 // allows users to enter short versions of the names,
859 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +0000860
861 // Remove any initial spaces
862 std::string white_space (" \t\v");
863 size_t pos = remainder.find_first_not_of (white_space);
864 if (pos != 0 && pos != std::string::npos)
865 remainder = remainder.substr (pos);
866
867 if (log)
868 log->Printf ("HandleCommand, command line after removing command name(s): '%s'\n", remainder.c_str());
869
870
871 if (wants_raw_input)
872 cmd_obj->ExecuteRawCommandString (remainder.c_str(), result);
873 else
874 {
875 Args cmd_args (remainder.c_str());
876 cmd_obj->ExecuteWithOptions (cmd_args, result);
877 }
878 }
879 else
880 {
881 // We didn't find the first command object, so complete the first argument.
882 Args command_args (revised_command_line.GetData());
883 StringList matches;
884 int num_matches;
885 int cursor_index = 0;
886 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
887 bool word_complete;
888 num_matches = HandleCompletionMatches (command_args,
889 cursor_index,
890 cursor_char_position,
891 0,
892 -1,
893 word_complete,
894 matches);
895
896 if (num_matches > 0)
897 {
898 std::string error_msg;
899 error_msg.assign ("ambiguous command '");
900 error_msg.append(command_args.GetArgumentAtIndex(0));
901 error_msg.append ("'.");
902
903 error_msg.append (" Possible completions:");
904 for (int i = 0; i < num_matches; i++)
905 {
906 error_msg.append ("\n\t");
907 error_msg.append (matches.GetStringAtIndex (i));
908 }
909 error_msg.append ("\n");
910 result.AppendRawError (error_msg.c_str(), error_msg.size());
911 }
912 else
913 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
914
915 result.SetStatus (eReturnStatusFailed);
916 }
917
Chris Lattner24943d22010-06-08 16:52:24 +0000918 return result.Succeeded();
919}
920
921int
922CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
923 int &cursor_index,
924 int &cursor_char_position,
925 int match_start_point,
926 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +0000927 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000928 StringList &matches)
929{
930 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000931 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +0000932
933 // For any of the command completions a unique match will be a complete word.
934 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000935
936 if (cursor_index == -1)
937 {
938 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +0000939 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000940 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
941 }
942 else if (cursor_index == 0)
943 {
944 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000945 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000946 num_command_matches = matches.GetSize();
947
948 if (num_command_matches == 1
949 && cmd_obj && cmd_obj->IsMultiwordObject()
950 && matches.GetStringAtIndex(0) != NULL
951 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
952 {
953 look_for_subcommand = true;
954 num_command_matches = 0;
955 matches.DeleteStringAtIndex(0);
956 parsed_line.AppendArgument ("");
957 cursor_index++;
958 cursor_char_position = 0;
959 }
960 }
961
962 if (cursor_index > 0 || look_for_subcommand)
963 {
964 // We are completing further on into a commands arguments, so find the command and tell it
965 // to complete the command.
966 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +0000967 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +0000968 if (command_object == NULL)
969 {
970 return 0;
971 }
972 else
973 {
974 parsed_line.Shift();
975 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +0000976 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +0000977 cursor_index,
978 cursor_char_position,
979 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000980 max_return_elements,
981 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000982 matches);
983 }
984 }
985
986 return num_command_matches;
987
988}
989
990int
991CommandInterpreter::HandleCompletion (const char *current_line,
992 const char *cursor,
993 const char *last_char,
994 int match_start_point,
995 int max_return_elements,
996 StringList &matches)
997{
998 // We parse the argument up to the cursor, so the last argument in parsed_line is
999 // the one containing the cursor, and the cursor is after the last character.
1000
1001 Args parsed_line(current_line, last_char - current_line);
1002 Args partial_parsed_line(current_line, cursor - current_line);
1003
1004 int num_args = partial_parsed_line.GetArgumentCount();
1005 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1006 int cursor_char_position;
1007
1008 if (cursor_index == -1)
1009 cursor_char_position = 0;
1010 else
1011 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001012
1013 if (cursor > current_line && cursor[-1] == ' ')
1014 {
1015 // We are just after a space. If we are in an argument, then we will continue
1016 // parsing, but if we are between arguments, then we have to complete whatever the next
1017 // element would be.
1018 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1019 // protected by a quote) then the space will also be in the parsed argument...
1020
1021 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1022 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1023 {
1024 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1025 cursor_index++;
1026 cursor_char_position = 0;
1027 }
1028 }
Chris Lattner24943d22010-06-08 16:52:24 +00001029
1030 int num_command_matches;
1031
1032 matches.Clear();
1033
1034 // Only max_return_elements == -1 is supported at present:
1035 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001036 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001037 num_command_matches = HandleCompletionMatches (parsed_line,
1038 cursor_index,
1039 cursor_char_position,
1040 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001041 max_return_elements,
1042 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001043 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001044
1045 if (num_command_matches <= 0)
1046 return num_command_matches;
1047
1048 if (num_args == 0)
1049 {
1050 // If we got an empty string, insert nothing.
1051 matches.InsertStringAtIndex(0, "");
1052 }
1053 else
1054 {
1055 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1056 // put an empty string in element 0.
1057 std::string command_partial_str;
1058 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001059 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1060 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001061
1062 std::string common_prefix;
1063 matches.LongestCommonPrefix (common_prefix);
1064 int partial_name_len = command_partial_str.size();
1065
1066 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001067 // Only do this if the completer told us this was a complete word, however...
1068 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001069 {
1070 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1071 if (quote_char != '\0')
1072 common_prefix.push_back(quote_char);
1073
1074 common_prefix.push_back(' ');
1075 }
1076 common_prefix.erase (0, partial_name_len);
1077 matches.InsertStringAtIndex(0, common_prefix.c_str());
1078 }
1079 return num_command_matches;
1080}
1081
Chris Lattner24943d22010-06-08 16:52:24 +00001082
1083CommandInterpreter::~CommandInterpreter ()
1084{
1085}
1086
1087const char *
1088CommandInterpreter::GetPrompt ()
1089{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001090 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001091}
1092
1093void
1094CommandInterpreter::SetPrompt (const char *new_prompt)
1095{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001096 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001097}
1098
Jim Ingham5e16ef52010-10-04 19:49:29 +00001099size_t
1100CommandInterpreter::GetConfirmationInputReaderCallback (void *baton,
1101 InputReader &reader,
1102 lldb::InputReaderAction action,
1103 const char *bytes,
1104 size_t bytes_len)
1105{
1106 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle();
1107 bool *response_ptr = (bool *) baton;
1108
1109 switch (action)
1110 {
1111 case eInputReaderActivate:
1112 if (out_fh)
1113 {
1114 if (reader.GetPrompt())
1115 ::fprintf (out_fh, "%s", reader.GetPrompt());
1116 }
1117 break;
1118
1119 case eInputReaderDeactivate:
1120 break;
1121
1122 case eInputReaderReactivate:
1123 if (out_fh && reader.GetPrompt())
1124 ::fprintf (out_fh, "%s", reader.GetPrompt());
1125 break;
1126
1127 case eInputReaderGotToken:
1128 if (bytes_len == 0)
1129 {
1130 reader.SetIsDone(true);
1131 }
1132 else if (bytes[0] == 'y')
1133 {
1134 *response_ptr = true;
1135 reader.SetIsDone(true);
1136 }
1137 else if (bytes[0] == 'n')
1138 {
1139 *response_ptr = false;
1140 reader.SetIsDone(true);
1141 }
1142 else
1143 {
1144 if (out_fh && !reader.IsDone() && reader.GetPrompt())
1145 {
1146 ::fprintf (out_fh, "Please answer \"y\" or \"n\"\n");
1147 ::fprintf (out_fh, "%s", reader.GetPrompt());
1148 }
1149 }
1150 break;
1151
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001152 case eInputReaderInterrupt:
1153 case eInputReaderEndOfFile:
1154 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1155 reader.SetIsDone (true);
1156 break;
1157
Jim Ingham5e16ef52010-10-04 19:49:29 +00001158 case eInputReaderDone:
1159 break;
1160 }
1161
1162 return bytes_len;
1163
1164}
1165
1166bool
1167CommandInterpreter::Confirm (const char *message, bool default_answer)
1168{
Jim Ingham93057472010-10-04 22:44:14 +00001169 // Check AutoConfirm first:
1170 if (m_debugger.GetAutoConfirm())
1171 return default_answer;
1172
Jim Ingham5e16ef52010-10-04 19:49:29 +00001173 InputReaderSP reader_sp (new InputReader(GetDebugger()));
1174 bool response = default_answer;
1175 if (reader_sp)
1176 {
1177 std::string prompt(message);
1178 prompt.append(": [");
1179 if (default_answer)
1180 prompt.append ("Y/n] ");
1181 else
1182 prompt.append ("y/N] ");
1183
1184 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1185 &response, // baton
1186 eInputReaderGranularityLine, // token size, to pass to callback function
1187 NULL, // end token
1188 prompt.c_str(), // prompt
1189 true)); // echo input
1190 if (err.Success())
1191 {
1192 GetDebugger().PushInputReader (reader_sp);
1193 }
1194 reader_sp->WaitOnReaderIsDone();
1195 }
1196 return response;
1197}
1198
1199
Chris Lattner24943d22010-06-08 16:52:24 +00001200void
1201CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1202{
Jim Inghamd40f8a62010-07-06 22:46:59 +00001203 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001204
1205 if (cmd_obj_sp != NULL)
1206 {
1207 CommandObject *cmd_obj = cmd_obj_sp.get();
1208 if (cmd_obj->IsCrossRefObject ())
1209 cmd_obj->AddObject (object_type);
1210 }
1211}
1212
Chris Lattner24943d22010-06-08 16:52:24 +00001213OptionArgVectorSP
1214CommandInterpreter::GetAliasOptions (const char *alias_name)
1215{
1216 OptionArgMap::iterator pos;
1217 OptionArgVectorSP ret_val;
1218
1219 std::string alias (alias_name);
1220
1221 if (HasAliasOptions())
1222 {
1223 pos = m_alias_options.find (alias);
1224 if (pos != m_alias_options.end())
1225 ret_val = pos->second;
1226 }
1227
1228 return ret_val;
1229}
1230
1231void
1232CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1233{
1234 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1235 if (pos != m_alias_options.end())
1236 {
1237 m_alias_options.erase (pos);
1238 }
1239}
1240
1241void
1242CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1243{
1244 m_alias_options[alias_name] = option_arg_vector_sp;
1245}
1246
1247bool
1248CommandInterpreter::HasCommands ()
1249{
1250 return (!m_command_dict.empty());
1251}
1252
1253bool
1254CommandInterpreter::HasAliases ()
1255{
1256 return (!m_alias_dict.empty());
1257}
1258
1259bool
1260CommandInterpreter::HasUserCommands ()
1261{
1262 return (!m_user_dict.empty());
1263}
1264
1265bool
1266CommandInterpreter::HasAliasOptions ()
1267{
1268 return (!m_alias_options.empty());
1269}
1270
Chris Lattner24943d22010-06-08 16:52:24 +00001271void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001272CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
1273 const char *alias_name,
1274 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00001275 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001276 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00001277{
1278 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00001279
1280 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00001281
Caroline Tice44c841d2010-12-07 19:58:26 +00001282 // Make sure that the alias name is the 0th element in cmd_args
1283 std::string alias_name_str = alias_name;
1284 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1285 cmd_args.Unshift (alias_name);
1286
1287 Args new_args (alias_cmd_obj->GetCommandName());
1288 if (new_args.GetArgumentCount() == 2)
1289 new_args.Shift();
1290
Chris Lattner24943d22010-06-08 16:52:24 +00001291 if (option_arg_vector_sp.get())
1292 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001293 if (wants_raw_input)
1294 {
1295 // We have a command that both has command options and takes raw input. Make *sure* it has a
1296 // " -- " in the right place in the raw_input_string.
1297 size_t pos = raw_input_string.find(" -- ");
1298 if (pos == std::string::npos)
1299 {
1300 // None found; assume it goes at the beginning of the raw input string
1301 raw_input_string.insert (0, " -- ");
1302 }
1303 }
Chris Lattner24943d22010-06-08 16:52:24 +00001304
1305 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1306 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001307 std::vector<bool> used (old_size + 1, false);
1308
1309 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001310
1311 for (int i = 0; i < option_arg_vector->size(); ++i)
1312 {
1313 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00001314 OptionArgValue value_pair = option_pair.second;
1315 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00001316 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00001317 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00001318 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001319 {
1320 if (!wants_raw_input
1321 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
1322 new_args.AppendArgument (value.c_str());
1323 }
Chris Lattner24943d22010-06-08 16:52:24 +00001324 else
1325 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001326 if (value_type != optional_argument)
1327 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001328 if (value.compare ("<no-argument>") != 0)
1329 {
1330 int index = GetOptionArgumentPosition (value.c_str());
1331 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001332 {
Chris Lattner24943d22010-06-08 16:52:24 +00001333 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00001334 if (value_type != optional_argument)
1335 new_args.AppendArgument (value.c_str());
1336 else
1337 {
1338 char buffer[255];
1339 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
1340 new_args.AppendArgument (buffer);
1341 }
1342
1343 }
Chris Lattner24943d22010-06-08 16:52:24 +00001344 else if (index >= cmd_args.GetArgumentCount())
1345 {
1346 result.AppendErrorWithFormat
1347 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1348 index);
1349 result.SetStatus (eReturnStatusFailed);
1350 return;
1351 }
1352 else
1353 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001354 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
1355 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1356 if (strpos != std::string::npos)
1357 {
1358 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
1359 }
1360
1361 if (value_type != optional_argument)
1362 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
1363 else
1364 {
1365 char buffer[255];
1366 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
1367 cmd_args.GetArgumentAtIndex (index));
1368 new_args.AppendArgument (buffer);
1369 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001370 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001371 }
1372 }
1373 }
1374 }
1375
1376 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1377 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001378 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00001379 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1380 }
1381
1382 cmd_args.Clear();
1383 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1384 }
1385 else
1386 {
1387 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00001388 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
1389 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
1390 // input string.
1391 if (wants_raw_input)
1392 {
1393 cmd_args.Clear();
1394 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1395 }
Chris Lattner24943d22010-06-08 16:52:24 +00001396 return;
1397 }
1398
1399 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1400 return;
1401}
1402
1403
1404int
1405CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1406{
1407 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1408 // of zero.
1409
1410 char *cptr = (char *) in_string;
1411
1412 // Does it start with '%'
1413 if (cptr[0] == '%')
1414 {
1415 ++cptr;
1416
1417 // Is the rest of it entirely digits?
1418 if (isdigit (cptr[0]))
1419 {
1420 const char *start = cptr;
1421 while (isdigit (cptr[0]))
1422 ++cptr;
1423
1424 // We've gotten to the end of the digits; are we at the end of the string?
1425 if (cptr[0] == '\0')
1426 position = atoi (start);
1427 }
1428 }
1429
1430 return position;
1431}
1432
1433void
1434CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1435{
Greg Clayton887aa282010-10-11 01:05:37 +00001436 // Don't parse any .lldbinit files if we were asked not to
1437 if (m_skip_lldbinit_files)
1438 return;
1439
Chris Lattner24943d22010-06-08 16:52:24 +00001440 const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit";
Greg Clayton537a7a82010-10-20 20:54:39 +00001441 FileSpec init_file (init_file_path, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001442 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
1443 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
1444
1445 if (init_file.Exists())
1446 {
1447 char path[PATH_MAX];
1448 init_file.GetPath(path, sizeof(path));
1449 StreamString source_command;
Johnny Chen7c984242010-07-28 21:16:11 +00001450 source_command.Printf ("command source '%s'", path);
Chris Lattner24943d22010-06-08 16:52:24 +00001451 HandleCommand (source_command.GetData(), false, result);
1452 }
1453 else
1454 {
1455 // nothing to be done if the file doesn't exist
1456 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1457 }
1458}
1459
1460ScriptInterpreter *
1461CommandInterpreter::GetScriptInterpreter ()
1462{
Greg Clayton63094e02010-06-23 01:19:29 +00001463 CommandObject::CommandMap::iterator pos;
1464
1465 pos = m_command_dict.find ("script");
1466 if (pos != m_command_dict.end())
Chris Lattner24943d22010-06-08 16:52:24 +00001467 {
Greg Clayton63094e02010-06-23 01:19:29 +00001468 CommandObject *script_cmd_obj = pos->second.get();
Greg Clayton238c0a12010-09-18 01:14:36 +00001469 return ((CommandObjectScript *) script_cmd_obj)->GetInterpreter ();
Chris Lattner24943d22010-06-08 16:52:24 +00001470 }
Greg Clayton63094e02010-06-23 01:19:29 +00001471 return NULL;
Chris Lattner24943d22010-06-08 16:52:24 +00001472}
1473
1474
1475
1476bool
1477CommandInterpreter::GetSynchronous ()
1478{
1479 return m_synchronous_execution;
1480}
1481
1482void
1483CommandInterpreter::SetSynchronous (bool value)
1484{
Johnny Chend7a4eb02010-10-14 01:22:03 +00001485 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00001486}
1487
1488void
1489CommandInterpreter::OutputFormattedHelpText (Stream &strm,
1490 const char *word_text,
1491 const char *separator,
1492 const char *help_text,
1493 uint32_t max_word_len)
1494{
Greg Clayton238c0a12010-09-18 01:14:36 +00001495 const uint32_t max_columns = m_debugger.GetTerminalWidth();
1496
Chris Lattner24943d22010-06-08 16:52:24 +00001497 int indent_size = max_word_len + strlen (separator) + 2;
1498
1499 strm.IndentMore (indent_size);
1500
1501 int len = indent_size + strlen (help_text) + 1;
1502 char *text = (char *) malloc (len);
1503 sprintf (text, "%-*s %s %s", max_word_len, word_text, separator, help_text);
1504 if (text[len - 1] == '\n')
1505 text[--len] = '\0';
1506
1507 if (len < max_columns)
1508 {
1509 // Output it as a single line.
1510 strm.Printf ("%s", text);
1511 }
1512 else
1513 {
1514 // We need to break it up into multiple lines.
1515 bool first_line = true;
1516 int text_width;
1517 int start = 0;
1518 int end = start;
1519 int final_end = strlen (text);
1520 int sub_len;
1521
1522 while (end < final_end)
1523 {
1524 if (first_line)
1525 text_width = max_columns - 1;
1526 else
1527 text_width = max_columns - indent_size - 1;
1528
1529 // Don't start the 'text' on a space, since we're already outputting the indentation.
1530 if (!first_line)
1531 {
1532 while ((start < final_end) && (text[start] == ' '))
1533 start++;
1534 }
1535
1536 end = start + text_width;
1537 if (end > final_end)
1538 end = final_end;
1539 else
1540 {
1541 // If we're not at the end of the text, make sure we break the line on white space.
1542 while (end > start
1543 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
1544 end--;
1545 }
1546
1547 sub_len = end - start;
1548 if (start != 0)
1549 strm.EOL();
1550 if (!first_line)
1551 strm.Indent();
1552 else
1553 first_line = false;
1554 assert (start <= final_end);
1555 assert (start + sub_len <= final_end);
1556 if (sub_len > 0)
1557 strm.Write (text + start, sub_len);
1558 start = end + 1;
1559 }
1560 }
1561 strm.EOL();
1562 strm.IndentLess(indent_size);
1563 free (text);
1564}
1565
1566void
1567CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
1568 StringList &commands_found, StringList &commands_help)
1569{
1570 CommandObject::CommandMap::const_iterator pos;
1571 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
1572 CommandObject *sub_cmd_obj;
1573
1574 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
1575 {
1576 const char * command_name = pos->first.c_str();
1577 sub_cmd_obj = pos->second.get();
1578 StreamString complete_command_name;
1579
1580 complete_command_name.Printf ("%s %s", prefix, command_name);
1581
Greg Clayton238c0a12010-09-18 01:14:36 +00001582 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001583 {
1584 commands_found.AppendString (complete_command_name.GetData());
1585 commands_help.AppendString (sub_cmd_obj->GetHelp());
1586 }
1587
1588 if (sub_cmd_obj->IsMultiwordObject())
1589 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
1590 commands_help);
1591 }
1592
1593}
1594
1595void
1596CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
1597 StringList &commands_help)
1598{
1599 CommandObject::CommandMap::const_iterator pos;
1600
1601 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1602 {
1603 const char *command_name = pos->first.c_str();
1604 CommandObject *cmd_obj = pos->second.get();
1605
Greg Clayton238c0a12010-09-18 01:14:36 +00001606 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001607 {
1608 commands_found.AppendString (command_name);
1609 commands_help.AppendString (cmd_obj->GetHelp());
1610 }
1611
1612 if (cmd_obj->IsMultiwordObject())
1613 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
1614
1615 }
1616}