blob: feb496332c1bdbd716e2ace60a01aa29f0547c57 [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
Chris Lattner24943d22010-06-08 16:52:24 +0000497bool
Greg Clayton63094e02010-06-23 01:19:29 +0000498CommandInterpreter::HandleCommand
499(
500 const char *command_line,
501 bool add_to_history,
502 CommandReturnObject &result,
503 ExecutionContext *override_context
504)
Chris Lattner24943d22010-06-08 16:52:24 +0000505{
Caroline Tice44c841d2010-12-07 19:58:26 +0000506 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Chris Lattner24943d22010-06-08 16:52:24 +0000507 // FIXME: there should probably be a mutex to make sure only one thread can
508 // run the interpreter at a time.
509
Greg Claytone98ac252010-11-10 04:57:04 +0000510 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
511
512 // Make a scoped cleanup object that will clear the crash description string
513 // on exit of this function.
514 lldb_utility::CleanUp <const char *, void> crash_description_cleanup(NULL, Host::SetCrashDescription);
515
Chris Lattner24943d22010-06-08 16:52:24 +0000516 // TODO: this should be a logging channel in lldb.
517// if (DebugSelf())
518// {
519// result.AppendMessageWithFormat ("Processing command: %s\n", command_line);
520// }
521
Jim Inghamabab14b2010-11-04 23:08:45 +0000522 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
523
Greg Clayton63094e02010-06-23 01:19:29 +0000524 m_debugger.UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +0000525
526 if (command_line == NULL || command_line[0] == '\0')
527 {
528 if (m_command_history.empty())
529 {
530 result.AppendError ("empty command");
531 result.SetStatus(eReturnStatusFailed);
532 return false;
533 }
534 else
535 {
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000536 command_line = m_repeat_command.c_str();
537 if (m_repeat_command.empty())
538 {
Jim Ingham767af882010-07-07 03:36:20 +0000539 result.AppendErrorWithFormat("No auto repeat.\n");
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000540 result.SetStatus (eReturnStatusFailed);
541 return false;
542 }
Chris Lattner24943d22010-06-08 16:52:24 +0000543 }
544 add_to_history = false;
545 }
546
Caroline Tice44c841d2010-12-07 19:58:26 +0000547 if (log)
548 log->Printf ("CommandInterpreter::HandleCommand, command_line = '%s'", command_line);
549
Chris Lattner24943d22010-06-08 16:52:24 +0000550 Args command_args(command_line);
551
552 if (command_args.GetArgumentCount() > 0)
553 {
Caroline Tice44c841d2010-12-07 19:58:26 +0000554 std::string raw_command_string (command_line); // For commands that take raw input but may be aliased or
555 // have command options.
556
Chris Lattner24943d22010-06-08 16:52:24 +0000557 const char *command_cstr = command_args.GetArgumentAtIndex(0);
558 if (command_cstr)
559 {
560
561 // We're looking up the command object here. So first find an exact match to the
562 // command in the commands.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000563 CommandObject *command_obj = GetCommandObject(command_cstr);
564
565 if (command_obj != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000566 {
Caroline Tice44c841d2010-12-07 19:58:26 +0000567 // Strip command name from the raw_command_string.
568 if (raw_command_string.find (command_cstr) == 0)
569 {
570 // The command name is at the front of the string (where it should be) so strip it off.
571 raw_command_string = raw_command_string.substr (strlen (command_cstr));
572 }
573
574
Caroline Tice0fb069d2010-10-18 19:18:31 +0000575 std::string aliased_cmd_str;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000576 if (command_obj->IsAlias())
Chris Lattner24943d22010-06-08 16:52:24 +0000577 {
Caroline Tice44c841d2010-12-07 19:58:26 +0000578 if (log)
579 log->Printf ("Command '%s' is an alias. Building alias command args.", command_cstr);
580 BuildAliasCommandArgs (command_obj, command_cstr, command_args, raw_command_string, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000581 if (!result.Succeeded())
Caroline Tice44c841d2010-12-07 19:58:26 +0000582 {
583 if (log)
584 log->Printf ("Building alias command args failed.");
Chris Lattner24943d22010-06-08 16:52:24 +0000585 return false;
Caroline Tice44c841d2010-12-07 19:58:26 +0000586 }
Caroline Tice0fb069d2010-10-18 19:18:31 +0000587 else
588 {
589 // We need to transfer the newly constructed args back into the command_line, in case
590 // this happens to be an alias for a command that takes raw input.
591 if (command_args.GetCommandString (aliased_cmd_str))
592 {
Caroline Tice44c841d2010-12-07 19:58:26 +0000593 if (log)
594 log->Printf ("Result string from BuildAliasCommandArgs is '%s'", aliased_cmd_str.c_str());
595 if (command_obj->WantsRawCommandString())
596 {
597 if (log)
598 {
599 log->Printf ("This command takes raw input.");
600 }
601 aliased_cmd_str.append (" ");
602 aliased_cmd_str.append (raw_command_string);
603 }
604 else
605 {
606 if (log)
607 log->Printf ("This command does NOT take raw input.");
608 }
Caroline Tice0fb069d2010-10-18 19:18:31 +0000609 command_line = aliased_cmd_str.c_str();
Caroline Tice8b5a0772010-10-18 22:38:05 +0000610 command_cstr = command_args.GetArgumentAtIndex (0);
Caroline Tice44c841d2010-12-07 19:58:26 +0000611 if (log)
612 {
613 log->Printf ("Final command line, after resolving aliases is '%s'", command_line);
614 }
Caroline Tice0fb069d2010-10-18 19:18:31 +0000615 }
616 }
Chris Lattner24943d22010-06-08 16:52:24 +0000617 }
Chris Lattner24943d22010-06-08 16:52:24 +0000618
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000619 if (add_to_history)
620 {
Jim Ingham767af882010-07-07 03:36:20 +0000621 const char *repeat_command = command_obj->GetRepeatCommand(command_args, 0);
622 if (repeat_command != NULL)
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000623 m_repeat_command.assign(repeat_command);
624 else
Jim Ingham767af882010-07-07 03:36:20 +0000625 m_repeat_command.assign(command_line);
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000626
627 m_command_history.push_back (command_line);
628 }
629
630
Chris Lattner24943d22010-06-08 16:52:24 +0000631 if (command_obj->WantsRawCommandString())
632 {
633 const char *stripped_command = ::strstr (command_line, command_cstr);
634 if (stripped_command)
635 {
636 stripped_command += strlen(command_cstr);
637 while (isspace(*stripped_command))
638 ++stripped_command;
Caroline Tice44c841d2010-12-07 19:58:26 +0000639 if (log)
640 log->Printf ("Input string being passed to ExecuteRawCommandString for '%s' command is '%s'",
641 command_obj->GetCommandName(), stripped_command);
Greg Clayton238c0a12010-09-18 01:14:36 +0000642 command_obj->ExecuteRawCommandString (stripped_command, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000643 }
644 }
645 else
646 {
Chris Lattner24943d22010-06-08 16:52:24 +0000647 // Remove the command from the args.
648 command_args.Shift();
Caroline Tice44c841d2010-12-07 19:58:26 +0000649 if (log)
650 {
651 size_t count = command_args.GetArgumentCount();
652 log->Printf ("ExecuteWithOptions for '%s' command is being called with %d args:",
653 command_obj->GetCommandName(), count);
654 for (size_t k = 0; k < count; ++k)
655 log->Printf (" arg[%d]='%s'", k, command_args.GetArgumentAtIndex (k));
656 }
Greg Clayton238c0a12010-09-18 01:14:36 +0000657 command_obj->ExecuteWithOptions (command_args, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000658 }
659 }
660 else
661 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000662 // We didn't find the first command object, so complete the first argument.
Chris Lattner24943d22010-06-08 16:52:24 +0000663 StringList matches;
664 int num_matches;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000665 int cursor_index = 0;
666 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
Jim Ingham802f8b02010-06-30 05:02:46 +0000667 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +0000668 num_matches = HandleCompletionMatches (command_args,
669 cursor_index,
670 cursor_char_position,
671 0,
672 -1,
Jim Ingham802f8b02010-06-30 05:02:46 +0000673 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +0000674 matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000675
676 if (num_matches > 0)
677 {
678 std::string error_msg;
679 error_msg.assign ("ambiguous command '");
680 error_msg.append(command_cstr);
681 error_msg.append ("'.");
682
683 error_msg.append (" Possible completions:");
684 for (int i = 0; i < num_matches; i++)
685 {
686 error_msg.append ("\n\t");
687 error_msg.append (matches.GetStringAtIndex (i));
688 }
689 error_msg.append ("\n");
690 result.AppendRawError (error_msg.c_str(), error_msg.size());
691 }
692 else
693 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_cstr);
694
695 result.SetStatus (eReturnStatusFailed);
696 }
697 }
698 }
699 return result.Succeeded();
700}
701
702int
703CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
704 int &cursor_index,
705 int &cursor_char_position,
706 int match_start_point,
707 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +0000708 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000709 StringList &matches)
710{
711 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000712 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +0000713
714 // For any of the command completions a unique match will be a complete word.
715 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000716
717 if (cursor_index == -1)
718 {
719 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +0000720 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000721 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
722 }
723 else if (cursor_index == 0)
724 {
725 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000726 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000727 num_command_matches = matches.GetSize();
728
729 if (num_command_matches == 1
730 && cmd_obj && cmd_obj->IsMultiwordObject()
731 && matches.GetStringAtIndex(0) != NULL
732 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
733 {
734 look_for_subcommand = true;
735 num_command_matches = 0;
736 matches.DeleteStringAtIndex(0);
737 parsed_line.AppendArgument ("");
738 cursor_index++;
739 cursor_char_position = 0;
740 }
741 }
742
743 if (cursor_index > 0 || look_for_subcommand)
744 {
745 // We are completing further on into a commands arguments, so find the command and tell it
746 // to complete the command.
747 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +0000748 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +0000749 if (command_object == NULL)
750 {
751 return 0;
752 }
753 else
754 {
755 parsed_line.Shift();
756 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +0000757 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +0000758 cursor_index,
759 cursor_char_position,
760 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000761 max_return_elements,
762 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000763 matches);
764 }
765 }
766
767 return num_command_matches;
768
769}
770
771int
772CommandInterpreter::HandleCompletion (const char *current_line,
773 const char *cursor,
774 const char *last_char,
775 int match_start_point,
776 int max_return_elements,
777 StringList &matches)
778{
779 // We parse the argument up to the cursor, so the last argument in parsed_line is
780 // the one containing the cursor, and the cursor is after the last character.
781
782 Args parsed_line(current_line, last_char - current_line);
783 Args partial_parsed_line(current_line, cursor - current_line);
784
785 int num_args = partial_parsed_line.GetArgumentCount();
786 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
787 int cursor_char_position;
788
789 if (cursor_index == -1)
790 cursor_char_position = 0;
791 else
792 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
793
794 int num_command_matches;
795
796 matches.Clear();
797
798 // Only max_return_elements == -1 is supported at present:
799 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +0000800 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +0000801 num_command_matches = HandleCompletionMatches (parsed_line,
802 cursor_index,
803 cursor_char_position,
804 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000805 max_return_elements,
806 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +0000807 matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000808
809 if (num_command_matches <= 0)
810 return num_command_matches;
811
812 if (num_args == 0)
813 {
814 // If we got an empty string, insert nothing.
815 matches.InsertStringAtIndex(0, "");
816 }
817 else
818 {
819 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
820 // put an empty string in element 0.
821 std::string command_partial_str;
822 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +0000823 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
824 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +0000825
826 std::string common_prefix;
827 matches.LongestCommonPrefix (common_prefix);
828 int partial_name_len = command_partial_str.size();
829
830 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +0000831 // Only do this if the completer told us this was a complete word, however...
832 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +0000833 {
834 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
835 if (quote_char != '\0')
836 common_prefix.push_back(quote_char);
837
838 common_prefix.push_back(' ');
839 }
840 common_prefix.erase (0, partial_name_len);
841 matches.InsertStringAtIndex(0, common_prefix.c_str());
842 }
843 return num_command_matches;
844}
845
Chris Lattner24943d22010-06-08 16:52:24 +0000846
847CommandInterpreter::~CommandInterpreter ()
848{
849}
850
851const char *
852CommandInterpreter::GetPrompt ()
853{
Caroline Tice5bc8c972010-09-20 20:44:43 +0000854 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +0000855}
856
857void
858CommandInterpreter::SetPrompt (const char *new_prompt)
859{
Caroline Tice5bc8c972010-09-20 20:44:43 +0000860 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +0000861}
862
Jim Ingham5e16ef52010-10-04 19:49:29 +0000863size_t
864CommandInterpreter::GetConfirmationInputReaderCallback (void *baton,
865 InputReader &reader,
866 lldb::InputReaderAction action,
867 const char *bytes,
868 size_t bytes_len)
869{
870 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle();
871 bool *response_ptr = (bool *) baton;
872
873 switch (action)
874 {
875 case eInputReaderActivate:
876 if (out_fh)
877 {
878 if (reader.GetPrompt())
879 ::fprintf (out_fh, "%s", reader.GetPrompt());
880 }
881 break;
882
883 case eInputReaderDeactivate:
884 break;
885
886 case eInputReaderReactivate:
887 if (out_fh && reader.GetPrompt())
888 ::fprintf (out_fh, "%s", reader.GetPrompt());
889 break;
890
891 case eInputReaderGotToken:
892 if (bytes_len == 0)
893 {
894 reader.SetIsDone(true);
895 }
896 else if (bytes[0] == 'y')
897 {
898 *response_ptr = true;
899 reader.SetIsDone(true);
900 }
901 else if (bytes[0] == 'n')
902 {
903 *response_ptr = false;
904 reader.SetIsDone(true);
905 }
906 else
907 {
908 if (out_fh && !reader.IsDone() && reader.GetPrompt())
909 {
910 ::fprintf (out_fh, "Please answer \"y\" or \"n\"\n");
911 ::fprintf (out_fh, "%s", reader.GetPrompt());
912 }
913 }
914 break;
915
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000916 case eInputReaderInterrupt:
917 case eInputReaderEndOfFile:
918 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
919 reader.SetIsDone (true);
920 break;
921
Jim Ingham5e16ef52010-10-04 19:49:29 +0000922 case eInputReaderDone:
923 break;
924 }
925
926 return bytes_len;
927
928}
929
930bool
931CommandInterpreter::Confirm (const char *message, bool default_answer)
932{
Jim Ingham93057472010-10-04 22:44:14 +0000933 // Check AutoConfirm first:
934 if (m_debugger.GetAutoConfirm())
935 return default_answer;
936
Jim Ingham5e16ef52010-10-04 19:49:29 +0000937 InputReaderSP reader_sp (new InputReader(GetDebugger()));
938 bool response = default_answer;
939 if (reader_sp)
940 {
941 std::string prompt(message);
942 prompt.append(": [");
943 if (default_answer)
944 prompt.append ("Y/n] ");
945 else
946 prompt.append ("y/N] ");
947
948 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
949 &response, // baton
950 eInputReaderGranularityLine, // token size, to pass to callback function
951 NULL, // end token
952 prompt.c_str(), // prompt
953 true)); // echo input
954 if (err.Success())
955 {
956 GetDebugger().PushInputReader (reader_sp);
957 }
958 reader_sp->WaitOnReaderIsDone();
959 }
960 return response;
961}
962
963
Chris Lattner24943d22010-06-08 16:52:24 +0000964void
965CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
966{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000967 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +0000968
969 if (cmd_obj_sp != NULL)
970 {
971 CommandObject *cmd_obj = cmd_obj_sp.get();
972 if (cmd_obj->IsCrossRefObject ())
973 cmd_obj->AddObject (object_type);
974 }
975}
976
Chris Lattner24943d22010-06-08 16:52:24 +0000977OptionArgVectorSP
978CommandInterpreter::GetAliasOptions (const char *alias_name)
979{
980 OptionArgMap::iterator pos;
981 OptionArgVectorSP ret_val;
982
983 std::string alias (alias_name);
984
985 if (HasAliasOptions())
986 {
987 pos = m_alias_options.find (alias);
988 if (pos != m_alias_options.end())
989 ret_val = pos->second;
990 }
991
992 return ret_val;
993}
994
995void
996CommandInterpreter::RemoveAliasOptions (const char *alias_name)
997{
998 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
999 if (pos != m_alias_options.end())
1000 {
1001 m_alias_options.erase (pos);
1002 }
1003}
1004
1005void
1006CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1007{
1008 m_alias_options[alias_name] = option_arg_vector_sp;
1009}
1010
1011bool
1012CommandInterpreter::HasCommands ()
1013{
1014 return (!m_command_dict.empty());
1015}
1016
1017bool
1018CommandInterpreter::HasAliases ()
1019{
1020 return (!m_alias_dict.empty());
1021}
1022
1023bool
1024CommandInterpreter::HasUserCommands ()
1025{
1026 return (!m_user_dict.empty());
1027}
1028
1029bool
1030CommandInterpreter::HasAliasOptions ()
1031{
1032 return (!m_alias_options.empty());
1033}
1034
Chris Lattner24943d22010-06-08 16:52:24 +00001035void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001036CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
1037 const char *alias_name,
1038 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00001039 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001040 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00001041{
1042 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00001043
1044 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00001045
Caroline Tice44c841d2010-12-07 19:58:26 +00001046 // Make sure that the alias name is the 0th element in cmd_args
1047 std::string alias_name_str = alias_name;
1048 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1049 cmd_args.Unshift (alias_name);
1050
1051 Args new_args (alias_cmd_obj->GetCommandName());
1052 if (new_args.GetArgumentCount() == 2)
1053 new_args.Shift();
1054
Chris Lattner24943d22010-06-08 16:52:24 +00001055 if (option_arg_vector_sp.get())
1056 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001057 if (wants_raw_input)
1058 {
1059 // We have a command that both has command options and takes raw input. Make *sure* it has a
1060 // " -- " in the right place in the raw_input_string.
1061 size_t pos = raw_input_string.find(" -- ");
1062 if (pos == std::string::npos)
1063 {
1064 // None found; assume it goes at the beginning of the raw input string
1065 raw_input_string.insert (0, " -- ");
1066 }
1067 }
Chris Lattner24943d22010-06-08 16:52:24 +00001068
1069 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1070 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001071 std::vector<bool> used (old_size + 1, false);
1072
1073 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001074
1075 for (int i = 0; i < option_arg_vector->size(); ++i)
1076 {
1077 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00001078 OptionArgValue value_pair = option_pair.second;
1079 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00001080 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00001081 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00001082 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001083 {
1084 if (!wants_raw_input
1085 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
1086 new_args.AppendArgument (value.c_str());
1087 }
Chris Lattner24943d22010-06-08 16:52:24 +00001088 else
1089 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001090 if (value_type != optional_argument)
1091 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001092 if (value.compare ("<no-argument>") != 0)
1093 {
1094 int index = GetOptionArgumentPosition (value.c_str());
1095 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001096 {
Chris Lattner24943d22010-06-08 16:52:24 +00001097 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00001098 if (value_type != optional_argument)
1099 new_args.AppendArgument (value.c_str());
1100 else
1101 {
1102 char buffer[255];
1103 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
1104 new_args.AppendArgument (buffer);
1105 }
1106
1107 }
Chris Lattner24943d22010-06-08 16:52:24 +00001108 else if (index >= cmd_args.GetArgumentCount())
1109 {
1110 result.AppendErrorWithFormat
1111 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1112 index);
1113 result.SetStatus (eReturnStatusFailed);
1114 return;
1115 }
1116 else
1117 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001118 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
1119 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1120 if (strpos != std::string::npos)
1121 {
1122 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
1123 }
1124
1125 if (value_type != optional_argument)
1126 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
1127 else
1128 {
1129 char buffer[255];
1130 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
1131 cmd_args.GetArgumentAtIndex (index));
1132 new_args.AppendArgument (buffer);
1133 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001134 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001135 }
1136 }
1137 }
1138 }
1139
1140 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1141 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001142 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00001143 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1144 }
1145
1146 cmd_args.Clear();
1147 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1148 }
1149 else
1150 {
1151 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00001152 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
1153 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
1154 // input string.
1155 if (wants_raw_input)
1156 {
1157 cmd_args.Clear();
1158 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1159 }
Chris Lattner24943d22010-06-08 16:52:24 +00001160 return;
1161 }
1162
1163 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1164 return;
1165}
1166
1167
1168int
1169CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1170{
1171 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1172 // of zero.
1173
1174 char *cptr = (char *) in_string;
1175
1176 // Does it start with '%'
1177 if (cptr[0] == '%')
1178 {
1179 ++cptr;
1180
1181 // Is the rest of it entirely digits?
1182 if (isdigit (cptr[0]))
1183 {
1184 const char *start = cptr;
1185 while (isdigit (cptr[0]))
1186 ++cptr;
1187
1188 // We've gotten to the end of the digits; are we at the end of the string?
1189 if (cptr[0] == '\0')
1190 position = atoi (start);
1191 }
1192 }
1193
1194 return position;
1195}
1196
1197void
1198CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1199{
Greg Clayton887aa282010-10-11 01:05:37 +00001200 // Don't parse any .lldbinit files if we were asked not to
1201 if (m_skip_lldbinit_files)
1202 return;
1203
Chris Lattner24943d22010-06-08 16:52:24 +00001204 const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit";
Greg Clayton537a7a82010-10-20 20:54:39 +00001205 FileSpec init_file (init_file_path, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001206 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
1207 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
1208
1209 if (init_file.Exists())
1210 {
1211 char path[PATH_MAX];
1212 init_file.GetPath(path, sizeof(path));
1213 StreamString source_command;
Johnny Chen7c984242010-07-28 21:16:11 +00001214 source_command.Printf ("command source '%s'", path);
Chris Lattner24943d22010-06-08 16:52:24 +00001215 HandleCommand (source_command.GetData(), false, result);
1216 }
1217 else
1218 {
1219 // nothing to be done if the file doesn't exist
1220 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1221 }
1222}
1223
1224ScriptInterpreter *
1225CommandInterpreter::GetScriptInterpreter ()
1226{
Greg Clayton63094e02010-06-23 01:19:29 +00001227 CommandObject::CommandMap::iterator pos;
1228
1229 pos = m_command_dict.find ("script");
1230 if (pos != m_command_dict.end())
Chris Lattner24943d22010-06-08 16:52:24 +00001231 {
Greg Clayton63094e02010-06-23 01:19:29 +00001232 CommandObject *script_cmd_obj = pos->second.get();
Greg Clayton238c0a12010-09-18 01:14:36 +00001233 return ((CommandObjectScript *) script_cmd_obj)->GetInterpreter ();
Chris Lattner24943d22010-06-08 16:52:24 +00001234 }
Greg Clayton63094e02010-06-23 01:19:29 +00001235 return NULL;
Chris Lattner24943d22010-06-08 16:52:24 +00001236}
1237
1238
1239
1240bool
1241CommandInterpreter::GetSynchronous ()
1242{
1243 return m_synchronous_execution;
1244}
1245
1246void
1247CommandInterpreter::SetSynchronous (bool value)
1248{
Johnny Chend7a4eb02010-10-14 01:22:03 +00001249 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00001250}
1251
1252void
1253CommandInterpreter::OutputFormattedHelpText (Stream &strm,
1254 const char *word_text,
1255 const char *separator,
1256 const char *help_text,
1257 uint32_t max_word_len)
1258{
Greg Clayton238c0a12010-09-18 01:14:36 +00001259 const uint32_t max_columns = m_debugger.GetTerminalWidth();
1260
Chris Lattner24943d22010-06-08 16:52:24 +00001261 int indent_size = max_word_len + strlen (separator) + 2;
1262
1263 strm.IndentMore (indent_size);
1264
1265 int len = indent_size + strlen (help_text) + 1;
1266 char *text = (char *) malloc (len);
1267 sprintf (text, "%-*s %s %s", max_word_len, word_text, separator, help_text);
1268 if (text[len - 1] == '\n')
1269 text[--len] = '\0';
1270
1271 if (len < max_columns)
1272 {
1273 // Output it as a single line.
1274 strm.Printf ("%s", text);
1275 }
1276 else
1277 {
1278 // We need to break it up into multiple lines.
1279 bool first_line = true;
1280 int text_width;
1281 int start = 0;
1282 int end = start;
1283 int final_end = strlen (text);
1284 int sub_len;
1285
1286 while (end < final_end)
1287 {
1288 if (first_line)
1289 text_width = max_columns - 1;
1290 else
1291 text_width = max_columns - indent_size - 1;
1292
1293 // Don't start the 'text' on a space, since we're already outputting the indentation.
1294 if (!first_line)
1295 {
1296 while ((start < final_end) && (text[start] == ' '))
1297 start++;
1298 }
1299
1300 end = start + text_width;
1301 if (end > final_end)
1302 end = final_end;
1303 else
1304 {
1305 // If we're not at the end of the text, make sure we break the line on white space.
1306 while (end > start
1307 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
1308 end--;
1309 }
1310
1311 sub_len = end - start;
1312 if (start != 0)
1313 strm.EOL();
1314 if (!first_line)
1315 strm.Indent();
1316 else
1317 first_line = false;
1318 assert (start <= final_end);
1319 assert (start + sub_len <= final_end);
1320 if (sub_len > 0)
1321 strm.Write (text + start, sub_len);
1322 start = end + 1;
1323 }
1324 }
1325 strm.EOL();
1326 strm.IndentLess(indent_size);
1327 free (text);
1328}
1329
1330void
1331CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
1332 StringList &commands_found, StringList &commands_help)
1333{
1334 CommandObject::CommandMap::const_iterator pos;
1335 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
1336 CommandObject *sub_cmd_obj;
1337
1338 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
1339 {
1340 const char * command_name = pos->first.c_str();
1341 sub_cmd_obj = pos->second.get();
1342 StreamString complete_command_name;
1343
1344 complete_command_name.Printf ("%s %s", prefix, command_name);
1345
Greg Clayton238c0a12010-09-18 01:14:36 +00001346 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001347 {
1348 commands_found.AppendString (complete_command_name.GetData());
1349 commands_help.AppendString (sub_cmd_obj->GetHelp());
1350 }
1351
1352 if (sub_cmd_obj->IsMultiwordObject())
1353 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
1354 commands_help);
1355 }
1356
1357}
1358
1359void
1360CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
1361 StringList &commands_help)
1362{
1363 CommandObject::CommandMap::const_iterator pos;
1364
1365 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1366 {
1367 const char *command_name = pos->first.c_str();
1368 CommandObject *cmd_obj = pos->second.get();
1369
Greg Clayton238c0a12010-09-18 01:14:36 +00001370 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001371 {
1372 commands_found.AppendString (command_name);
1373 commands_help.AppendString (cmd_obj->GetHelp());
1374 }
1375
1376 if (cmd_obj->IsMultiwordObject())
1377 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
1378
1379 }
1380}