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