blob: 5a3ad183af5a0e50625b74bf495d94794e9c6cb1 [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"
48
49#include "lldb/Interpreter/CommandReturnObject.h"
50#include "lldb/Interpreter/CommandInterpreter.h"
51
52using namespace lldb;
53using namespace lldb_private;
54
55CommandInterpreter::CommandInterpreter
56(
Greg Clayton63094e02010-06-23 01:19:29 +000057 Debugger &debugger,
Chris Lattner24943d22010-06-08 16:52:24 +000058 ScriptLanguage script_language,
Greg Clayton63094e02010-06-23 01:19:29 +000059 bool synchronous_execution
Chris Lattner24943d22010-06-08 16:52:24 +000060) :
Greg Clayton49ce6822010-10-31 03:01:06 +000061 Broadcaster ("lldb.command-interpreter"),
Greg Clayton63094e02010-06-23 01:19:29 +000062 m_debugger (debugger),
Greg Clayton887aa282010-10-11 01:05:37 +000063 m_synchronous_execution (synchronous_execution),
64 m_skip_lldbinit_files (false)
Chris Lattner24943d22010-06-08 16:52:24 +000065{
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000066 const char *dbg_name = debugger.GetInstanceName().AsCString();
67 std::string lang_name = ScriptInterpreter::LanguageToString (script_language);
68 StreamString var_name;
69 var_name.Printf ("[%s].script-lang", dbg_name);
Caroline Tice1d2aefd2010-09-09 06:25:08 +000070 debugger.GetSettingsController()->SetVariable (var_name.GetData(), lang_name.c_str(),
71 lldb::eVarSetOperationAssign, false,
Greg Clayton49ce6822010-10-31 03:01:06 +000072 m_debugger.GetInstanceName().AsCString());
73 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
74 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
75 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Chris Lattner24943d22010-06-08 16:52:24 +000076}
77
78void
79CommandInterpreter::Initialize ()
80{
81 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
82
83 CommandReturnObject result;
84
85 LoadCommandDictionary ();
86
Chris Lattner24943d22010-06-08 16:52:24 +000087 // Set up some initial aliases.
Jim Ingham767af882010-07-07 03:36:20 +000088 result.Clear(); HandleCommand ("command alias q quit", false, result);
Jim Inghame3663e82010-10-22 18:47:16 +000089 result.Clear(); HandleCommand ("command alias run process launch --", false, result);
90 result.Clear(); HandleCommand ("command alias r process launch --", false, result);
Jim Ingham767af882010-07-07 03:36:20 +000091 result.Clear(); HandleCommand ("command alias c process continue", false, result);
92 result.Clear(); HandleCommand ("command alias continue process continue", false, result);
93 result.Clear(); HandleCommand ("command alias expr expression", false, result);
94 result.Clear(); HandleCommand ("command alias exit quit", false, result);
Greg Clayton0f3a8eb2010-09-16 17:09:23 +000095 result.Clear(); HandleCommand ("command alias b regexp-break", false, result);
Jim Ingham767af882010-07-07 03:36:20 +000096 result.Clear(); HandleCommand ("command alias bt thread backtrace", false, result);
97 result.Clear(); HandleCommand ("command alias si thread step-inst", false, result);
98 result.Clear(); HandleCommand ("command alias step thread step-in", false, result);
99 result.Clear(); HandleCommand ("command alias s thread step-in", false, result);
100 result.Clear(); HandleCommand ("command alias next thread step-over", false, result);
101 result.Clear(); HandleCommand ("command alias n thread step-over", false, result);
102 result.Clear(); HandleCommand ("command alias finish thread step-out", false, result);
103 result.Clear(); HandleCommand ("command alias x memory read", false, result);
104 result.Clear(); HandleCommand ("command alias l source list", false, result);
105 result.Clear(); HandleCommand ("command alias list source list", false, result);
Greg Clayton0f3a8eb2010-09-16 17:09:23 +0000106 result.Clear(); HandleCommand ("command alias p frame variable", false, result);
107 result.Clear(); HandleCommand ("command alias print frame variable", false, result);
Jim Inghame3663e82010-10-22 18:47:16 +0000108 result.Clear(); HandleCommand ("command alias po expression -o --", false, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000109}
110
Chris Lattner24943d22010-06-08 16:52:24 +0000111const char *
112CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
113{
114 // This function has not yet been implemented.
115
116 // Look for any embedded script command
117 // If found,
118 // get interpreter object from the command dictionary,
119 // call execute_one_command on it,
120 // get the results as a string,
121 // substitute that string for current stuff.
122
123 return arg;
124}
125
126
127void
128CommandInterpreter::LoadCommandDictionary ()
129{
130 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
131
132 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
133 //
134 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
135 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
136 // the cross-referencing stuff) are created!!!
137 //
138 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
139
140
141 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
142 // are created. This is so that when another command is created that needs to go into a crossref object,
143 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
144 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
145
Chris Lattner24943d22010-06-08 16:52:24 +0000146 // Non-CommandObjectCrossref commands can now be created.
147
Caroline Tice5bc8c972010-09-20 20:44:43 +0000148 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000149
Greg Clayton238c0a12010-09-18 01:14:36 +0000150 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000151 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000152 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000153 m_command_dict["commands"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000154 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
155 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
156 m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000157 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000158 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000159 m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
160 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
161 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
162 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000163 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000164 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000165 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000166 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000167 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000168 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
169 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000170
171 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000172 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
173 "regexp-break",
Caroline Ticec1ad82e2010-09-07 22:38:08 +0000174 "Set a breakpoint using a regular expression to specify the location.",
Caroline Tice43b014a2010-10-04 22:28:36 +0000175 "regexp-break [<filename>:<linenum>]\nregexp-break [<address>]\nregexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000176 if (break_regex_cmd_ap.get())
177 {
178 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
179 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
180 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
181 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list") &&
182 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
183 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
184 {
185 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
186 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
187 }
188 }
189}
190
191int
192CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
193 StringList &matches)
194{
195 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
196
197 if (include_aliases)
198 {
199 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
200 }
201
202 return matches.GetSize();
203}
204
205CommandObjectSP
206CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
207{
208 CommandObject::CommandMap::iterator pos;
209 CommandObjectSP ret_val;
210
211 std::string cmd(cmd_cstr);
212
213 if (HasCommands())
214 {
215 pos = m_command_dict.find(cmd);
216 if (pos != m_command_dict.end())
217 ret_val = pos->second;
218 }
219
220 if (include_aliases && HasAliases())
221 {
222 pos = m_alias_dict.find(cmd);
223 if (pos != m_alias_dict.end())
224 ret_val = pos->second;
225 }
226
227 if (HasUserCommands())
228 {
229 pos = m_user_dict.find(cmd);
230 if (pos != m_user_dict.end())
231 ret_val = pos->second;
232 }
233
234 if (!exact && ret_val == NULL)
235 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000236 // We will only get into here if we didn't find any exact matches.
237
238 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
239
Chris Lattner24943d22010-06-08 16:52:24 +0000240 StringList local_matches;
241 if (matches == NULL)
242 matches = &local_matches;
243
Jim Inghamd40f8a62010-07-06 22:46:59 +0000244 unsigned int num_cmd_matches = 0;
245 unsigned int num_alias_matches = 0;
246 unsigned int num_user_matches = 0;
247
248 // Look through the command dictionaries one by one, and if we get only one match from any of
249 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
250
Chris Lattner24943d22010-06-08 16:52:24 +0000251 if (HasCommands())
252 {
253 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
254 }
255
256 if (num_cmd_matches == 1)
257 {
258 cmd.assign(matches->GetStringAtIndex(0));
259 pos = m_command_dict.find(cmd);
260 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000261 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000262 }
263
Jim Ingham9a574172010-06-24 20:28:42 +0000264 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000265 {
266 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
267
268 }
269
Jim Inghamd40f8a62010-07-06 22:46:59 +0000270 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000271 {
272 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
273 pos = m_alias_dict.find(cmd);
274 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000275 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000276 }
277
Jim Ingham9a574172010-06-24 20:28:42 +0000278 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000279 {
280 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
281 }
282
Jim Inghamd40f8a62010-07-06 22:46:59 +0000283 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000284 {
285 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
286
287 pos = m_user_dict.find (cmd);
288 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000289 user_match_sp = pos->second;
290 }
291
292 // If we got exactly one match, return that, otherwise return the match list.
293
294 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
295 {
296 if (num_cmd_matches)
297 return real_match_sp;
298 else if (num_alias_matches)
299 return alias_match_sp;
300 else
301 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000302 }
303 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000304 else if (matches && ret_val != NULL)
305 {
306 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000307 }
308
309
310 return ret_val;
311}
312
Jim Inghamd40f8a62010-07-06 22:46:59 +0000313CommandObjectSP
314CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000315{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000316 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
317}
318
319CommandObject *
320CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
321{
322 return GetCommandSPExact (cmd_cstr, include_aliases).get();
323}
324
325CommandObject *
326CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
327{
328 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
329
330 // If we didn't find an exact match to the command string in the commands, look in
331 // the aliases.
332
333 if (command_obj == NULL)
334 {
335 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
336 }
337
338 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
339 // in both the commands and the aliases.
340
341 if (command_obj == NULL)
342 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
343
344 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000345}
346
347bool
348CommandInterpreter::CommandExists (const char *cmd)
349{
350 return m_command_dict.find(cmd) != m_command_dict.end();
351}
352
353bool
354CommandInterpreter::AliasExists (const char *cmd)
355{
356 return m_alias_dict.find(cmd) != m_alias_dict.end();
357}
358
359bool
360CommandInterpreter::UserCommandExists (const char *cmd)
361{
362 return m_user_dict.find(cmd) != m_user_dict.end();
363}
364
365void
366CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
367{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000368 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000369 m_alias_dict[alias_name] = command_obj_sp;
370}
371
372bool
373CommandInterpreter::RemoveAlias (const char *alias_name)
374{
375 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
376 if (pos != m_alias_dict.end())
377 {
378 m_alias_dict.erase(pos);
379 return true;
380 }
381 return false;
382}
383bool
384CommandInterpreter::RemoveUser (const char *alias_name)
385{
386 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
387 if (pos != m_user_dict.end())
388 {
389 m_user_dict.erase(pos);
390 return true;
391 }
392 return false;
393}
394
Chris Lattner24943d22010-06-08 16:52:24 +0000395void
396CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
397{
398 help_string.Printf ("'%s", command_name);
399 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
400
401 if (option_arg_vector_sp != NULL)
402 {
403 OptionArgVector *options = option_arg_vector_sp.get();
404 for (int i = 0; i < options->size(); ++i)
405 {
406 OptionArgPair cur_option = (*options)[i];
407 std::string opt = cur_option.first;
408 std::string value = cur_option.second;
409 if (opt.compare("<argument>") == 0)
410 {
411 help_string.Printf (" %s", value.c_str());
412 }
413 else
414 {
415 help_string.Printf (" %s", opt.c_str());
416 if ((value.compare ("<no-argument>") != 0)
417 && (value.compare ("<need-argument") != 0))
418 {
419 help_string.Printf (" %s", value.c_str());
420 }
421 }
422 }
423 }
424
425 help_string.Printf ("'");
426}
427
Greg Clayton65124ea2010-08-26 22:05:43 +0000428size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000429CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
430{
431 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000432 CommandObject::CommandMap::const_iterator end = dict.end();
433 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000434
Greg Clayton65124ea2010-08-26 22:05:43 +0000435 for (pos = dict.begin(); pos != end; ++pos)
436 {
437 size_t len = pos->first.size();
438 if (max_len < len)
439 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000440 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000441 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000442}
443
444void
445CommandInterpreter::GetHelp (CommandReturnObject &result)
446{
447 CommandObject::CommandMap::const_iterator pos;
448 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
449 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000450 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000451
452 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
453 {
454 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
455 max_len);
456 }
457 result.AppendMessage("");
458
459 if (m_alias_dict.size() > 0)
460 {
Jim Inghame3663e82010-10-22 18:47:16 +0000461 result.AppendMessage("The following is a list of your current command abbreviations "
462 "(see 'help commands alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000463 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000464 max_len = FindLongestCommandWord (m_alias_dict);
465
Chris Lattner24943d22010-06-08 16:52:24 +0000466 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
467 {
468 StreamString sstr;
469 StreamString translation_and_help;
470 std::string entry_name = pos->first;
471 std::string second_entry = pos->second.get()->GetCommandName();
472 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
473
474 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
475 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
476 translation_and_help.GetData(), max_len);
477 }
478 result.AppendMessage("");
479 }
480
481 if (m_user_dict.size() > 0)
482 {
483 result.AppendMessage ("The following is a list of your current user-defined commands:");
484 result.AppendMessage("");
485 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
486 {
487 result.AppendMessageWithFormat ("%s -- %s\n", pos->first.c_str(), pos->second->GetHelp());
488 }
489 result.AppendMessage("");
490 }
491
492 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
493}
494
Chris Lattner24943d22010-06-08 16:52:24 +0000495bool
Greg Clayton63094e02010-06-23 01:19:29 +0000496CommandInterpreter::HandleCommand
497(
498 const char *command_line,
499 bool add_to_history,
500 CommandReturnObject &result,
501 ExecutionContext *override_context
502)
Chris Lattner24943d22010-06-08 16:52:24 +0000503{
504 // FIXME: there should probably be a mutex to make sure only one thread can
505 // run the interpreter at a time.
506
507 // TODO: this should be a logging channel in lldb.
508// if (DebugSelf())
509// {
510// result.AppendMessageWithFormat ("Processing command: %s\n", command_line);
511// }
512
Jim Inghamabab14b2010-11-04 23:08:45 +0000513 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
514
Greg Clayton63094e02010-06-23 01:19:29 +0000515 m_debugger.UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +0000516
517 if (command_line == NULL || command_line[0] == '\0')
518 {
519 if (m_command_history.empty())
520 {
521 result.AppendError ("empty command");
522 result.SetStatus(eReturnStatusFailed);
523 return false;
524 }
525 else
526 {
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000527 command_line = m_repeat_command.c_str();
528 if (m_repeat_command.empty())
529 {
Jim Ingham767af882010-07-07 03:36:20 +0000530 result.AppendErrorWithFormat("No auto repeat.\n");
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000531 result.SetStatus (eReturnStatusFailed);
532 return false;
533 }
Chris Lattner24943d22010-06-08 16:52:24 +0000534 }
535 add_to_history = false;
536 }
537
538 Args command_args(command_line);
539
540 if (command_args.GetArgumentCount() > 0)
541 {
542 const char *command_cstr = command_args.GetArgumentAtIndex(0);
543 if (command_cstr)
544 {
545
546 // We're looking up the command object here. So first find an exact match to the
547 // command in the commands.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000548 CommandObject *command_obj = GetCommandObject(command_cstr);
549
550 if (command_obj != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000551 {
Caroline Tice0fb069d2010-10-18 19:18:31 +0000552 std::string aliased_cmd_str;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000553 if (command_obj->IsAlias())
Chris Lattner24943d22010-06-08 16:52:24 +0000554 {
555 BuildAliasCommandArgs (command_obj, command_cstr, command_args, result);
556 if (!result.Succeeded())
557 return false;
Caroline Tice0fb069d2010-10-18 19:18:31 +0000558 else
559 {
560 // We need to transfer the newly constructed args back into the command_line, in case
561 // this happens to be an alias for a command that takes raw input.
562 if (command_args.GetCommandString (aliased_cmd_str))
563 {
564 command_line = aliased_cmd_str.c_str();
Caroline Tice8b5a0772010-10-18 22:38:05 +0000565 command_cstr = command_args.GetArgumentAtIndex (0);
Caroline Tice0fb069d2010-10-18 19:18:31 +0000566 }
567 }
Chris Lattner24943d22010-06-08 16:52:24 +0000568 }
Chris Lattner24943d22010-06-08 16:52:24 +0000569
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000570 if (add_to_history)
571 {
Jim Ingham767af882010-07-07 03:36:20 +0000572 const char *repeat_command = command_obj->GetRepeatCommand(command_args, 0);
573 if (repeat_command != NULL)
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000574 m_repeat_command.assign(repeat_command);
575 else
Jim Ingham767af882010-07-07 03:36:20 +0000576 m_repeat_command.assign(command_line);
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000577
578 m_command_history.push_back (command_line);
579 }
580
581
Chris Lattner24943d22010-06-08 16:52:24 +0000582 if (command_obj->WantsRawCommandString())
583 {
584 const char *stripped_command = ::strstr (command_line, command_cstr);
585 if (stripped_command)
586 {
587 stripped_command += strlen(command_cstr);
588 while (isspace(*stripped_command))
589 ++stripped_command;
Greg Clayton238c0a12010-09-18 01:14:36 +0000590 command_obj->ExecuteRawCommandString (stripped_command, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000591 }
592 }
593 else
594 {
Chris Lattner24943d22010-06-08 16:52:24 +0000595 // Remove the command from the args.
596 command_args.Shift();
Greg Clayton238c0a12010-09-18 01:14:36 +0000597 command_obj->ExecuteWithOptions (command_args, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000598 }
599 }
600 else
601 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000602 // We didn't find the first command object, so complete the first argument.
Chris Lattner24943d22010-06-08 16:52:24 +0000603 StringList matches;
604 int num_matches;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000605 int cursor_index = 0;
606 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
Jim Ingham802f8b02010-06-30 05:02:46 +0000607 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +0000608 num_matches = HandleCompletionMatches (command_args,
609 cursor_index,
610 cursor_char_position,
611 0,
612 -1,
Jim Ingham802f8b02010-06-30 05:02:46 +0000613 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +0000614 matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000615
616 if (num_matches > 0)
617 {
618 std::string error_msg;
619 error_msg.assign ("ambiguous command '");
620 error_msg.append(command_cstr);
621 error_msg.append ("'.");
622
623 error_msg.append (" Possible completions:");
624 for (int i = 0; i < num_matches; i++)
625 {
626 error_msg.append ("\n\t");
627 error_msg.append (matches.GetStringAtIndex (i));
628 }
629 error_msg.append ("\n");
630 result.AppendRawError (error_msg.c_str(), error_msg.size());
631 }
632 else
633 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_cstr);
634
635 result.SetStatus (eReturnStatusFailed);
636 }
637 }
638 }
639 return result.Succeeded();
640}
641
642int
643CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
644 int &cursor_index,
645 int &cursor_char_position,
646 int match_start_point,
647 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +0000648 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000649 StringList &matches)
650{
651 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000652 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +0000653
654 // For any of the command completions a unique match will be a complete word.
655 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000656
657 if (cursor_index == -1)
658 {
659 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +0000660 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000661 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
662 }
663 else if (cursor_index == 0)
664 {
665 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000666 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000667 num_command_matches = matches.GetSize();
668
669 if (num_command_matches == 1
670 && cmd_obj && cmd_obj->IsMultiwordObject()
671 && matches.GetStringAtIndex(0) != NULL
672 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
673 {
674 look_for_subcommand = true;
675 num_command_matches = 0;
676 matches.DeleteStringAtIndex(0);
677 parsed_line.AppendArgument ("");
678 cursor_index++;
679 cursor_char_position = 0;
680 }
681 }
682
683 if (cursor_index > 0 || look_for_subcommand)
684 {
685 // We are completing further on into a commands arguments, so find the command and tell it
686 // to complete the command.
687 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +0000688 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +0000689 if (command_object == NULL)
690 {
691 return 0;
692 }
693 else
694 {
695 parsed_line.Shift();
696 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +0000697 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +0000698 cursor_index,
699 cursor_char_position,
700 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000701 max_return_elements,
702 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000703 matches);
704 }
705 }
706
707 return num_command_matches;
708
709}
710
711int
712CommandInterpreter::HandleCompletion (const char *current_line,
713 const char *cursor,
714 const char *last_char,
715 int match_start_point,
716 int max_return_elements,
717 StringList &matches)
718{
719 // We parse the argument up to the cursor, so the last argument in parsed_line is
720 // the one containing the cursor, and the cursor is after the last character.
721
722 Args parsed_line(current_line, last_char - current_line);
723 Args partial_parsed_line(current_line, cursor - current_line);
724
725 int num_args = partial_parsed_line.GetArgumentCount();
726 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
727 int cursor_char_position;
728
729 if (cursor_index == -1)
730 cursor_char_position = 0;
731 else
732 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
733
734 int num_command_matches;
735
736 matches.Clear();
737
738 // Only max_return_elements == -1 is supported at present:
739 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +0000740 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +0000741 num_command_matches = HandleCompletionMatches (parsed_line,
742 cursor_index,
743 cursor_char_position,
744 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000745 max_return_elements,
746 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +0000747 matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000748
749 if (num_command_matches <= 0)
750 return num_command_matches;
751
752 if (num_args == 0)
753 {
754 // If we got an empty string, insert nothing.
755 matches.InsertStringAtIndex(0, "");
756 }
757 else
758 {
759 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
760 // put an empty string in element 0.
761 std::string command_partial_str;
762 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +0000763 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
764 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +0000765
766 std::string common_prefix;
767 matches.LongestCommonPrefix (common_prefix);
768 int partial_name_len = command_partial_str.size();
769
770 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +0000771 // Only do this if the completer told us this was a complete word, however...
772 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +0000773 {
774 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
775 if (quote_char != '\0')
776 common_prefix.push_back(quote_char);
777
778 common_prefix.push_back(' ');
779 }
780 common_prefix.erase (0, partial_name_len);
781 matches.InsertStringAtIndex(0, common_prefix.c_str());
782 }
783 return num_command_matches;
784}
785
Chris Lattner24943d22010-06-08 16:52:24 +0000786
787CommandInterpreter::~CommandInterpreter ()
788{
789}
790
791const char *
792CommandInterpreter::GetPrompt ()
793{
Caroline Tice5bc8c972010-09-20 20:44:43 +0000794 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +0000795}
796
797void
798CommandInterpreter::SetPrompt (const char *new_prompt)
799{
Caroline Tice5bc8c972010-09-20 20:44:43 +0000800 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +0000801}
802
Jim Ingham5e16ef52010-10-04 19:49:29 +0000803size_t
804CommandInterpreter::GetConfirmationInputReaderCallback (void *baton,
805 InputReader &reader,
806 lldb::InputReaderAction action,
807 const char *bytes,
808 size_t bytes_len)
809{
810 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle();
811 bool *response_ptr = (bool *) baton;
812
813 switch (action)
814 {
815 case eInputReaderActivate:
816 if (out_fh)
817 {
818 if (reader.GetPrompt())
819 ::fprintf (out_fh, "%s", reader.GetPrompt());
820 }
821 break;
822
823 case eInputReaderDeactivate:
824 break;
825
826 case eInputReaderReactivate:
827 if (out_fh && reader.GetPrompt())
828 ::fprintf (out_fh, "%s", reader.GetPrompt());
829 break;
830
831 case eInputReaderGotToken:
832 if (bytes_len == 0)
833 {
834 reader.SetIsDone(true);
835 }
836 else if (bytes[0] == 'y')
837 {
838 *response_ptr = true;
839 reader.SetIsDone(true);
840 }
841 else if (bytes[0] == 'n')
842 {
843 *response_ptr = false;
844 reader.SetIsDone(true);
845 }
846 else
847 {
848 if (out_fh && !reader.IsDone() && reader.GetPrompt())
849 {
850 ::fprintf (out_fh, "Please answer \"y\" or \"n\"\n");
851 ::fprintf (out_fh, "%s", reader.GetPrompt());
852 }
853 }
854 break;
855
856 case eInputReaderDone:
857 break;
858 }
859
860 return bytes_len;
861
862}
863
864bool
865CommandInterpreter::Confirm (const char *message, bool default_answer)
866{
Jim Ingham93057472010-10-04 22:44:14 +0000867 // Check AutoConfirm first:
868 if (m_debugger.GetAutoConfirm())
869 return default_answer;
870
Jim Ingham5e16ef52010-10-04 19:49:29 +0000871 InputReaderSP reader_sp (new InputReader(GetDebugger()));
872 bool response = default_answer;
873 if (reader_sp)
874 {
875 std::string prompt(message);
876 prompt.append(": [");
877 if (default_answer)
878 prompt.append ("Y/n] ");
879 else
880 prompt.append ("y/N] ");
881
882 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
883 &response, // baton
884 eInputReaderGranularityLine, // token size, to pass to callback function
885 NULL, // end token
886 prompt.c_str(), // prompt
887 true)); // echo input
888 if (err.Success())
889 {
890 GetDebugger().PushInputReader (reader_sp);
891 }
892 reader_sp->WaitOnReaderIsDone();
893 }
894 return response;
895}
896
897
Chris Lattner24943d22010-06-08 16:52:24 +0000898void
899CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
900{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000901 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +0000902
903 if (cmd_obj_sp != NULL)
904 {
905 CommandObject *cmd_obj = cmd_obj_sp.get();
906 if (cmd_obj->IsCrossRefObject ())
907 cmd_obj->AddObject (object_type);
908 }
909}
910
Chris Lattner24943d22010-06-08 16:52:24 +0000911OptionArgVectorSP
912CommandInterpreter::GetAliasOptions (const char *alias_name)
913{
914 OptionArgMap::iterator pos;
915 OptionArgVectorSP ret_val;
916
917 std::string alias (alias_name);
918
919 if (HasAliasOptions())
920 {
921 pos = m_alias_options.find (alias);
922 if (pos != m_alias_options.end())
923 ret_val = pos->second;
924 }
925
926 return ret_val;
927}
928
929void
930CommandInterpreter::RemoveAliasOptions (const char *alias_name)
931{
932 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
933 if (pos != m_alias_options.end())
934 {
935 m_alias_options.erase (pos);
936 }
937}
938
939void
940CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
941{
942 m_alias_options[alias_name] = option_arg_vector_sp;
943}
944
945bool
946CommandInterpreter::HasCommands ()
947{
948 return (!m_command_dict.empty());
949}
950
951bool
952CommandInterpreter::HasAliases ()
953{
954 return (!m_alias_dict.empty());
955}
956
957bool
958CommandInterpreter::HasUserCommands ()
959{
960 return (!m_user_dict.empty());
961}
962
963bool
964CommandInterpreter::HasAliasOptions ()
965{
966 return (!m_alias_options.empty());
967}
968
Chris Lattner24943d22010-06-08 16:52:24 +0000969void
Caroline Ticebd5c63e2010-10-12 21:57:09 +0000970CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
971 const char *alias_name,
972 Args &cmd_args,
973 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +0000974{
975 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
976
977 if (option_arg_vector_sp.get())
978 {
979 // Make sure that the alias name is the 0th element in cmd_args
980 std::string alias_name_str = alias_name;
981 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
982 cmd_args.Unshift (alias_name);
983
984 Args new_args (alias_cmd_obj->GetCommandName());
985 if (new_args.GetArgumentCount() == 2)
986 new_args.Shift();
987
988 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
989 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +0000990 std::vector<bool> used (old_size + 1, false);
991
992 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000993
994 for (int i = 0; i < option_arg_vector->size(); ++i)
995 {
996 OptionArgPair option_pair = (*option_arg_vector)[i];
997 std::string option = option_pair.first;
998 std::string value = option_pair.second;
999 if (option.compare ("<argument>") == 0)
1000 new_args.AppendArgument (value.c_str());
1001 else
1002 {
1003 new_args.AppendArgument (option.c_str());
1004 if (value.compare ("<no-argument>") != 0)
1005 {
1006 int index = GetOptionArgumentPosition (value.c_str());
1007 if (index == 0)
1008 // value was NOT a positional argument; must be a real value
1009 new_args.AppendArgument (value.c_str());
1010 else if (index >= cmd_args.GetArgumentCount())
1011 {
1012 result.AppendErrorWithFormat
1013 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1014 index);
1015 result.SetStatus (eReturnStatusFailed);
1016 return;
1017 }
1018 else
1019 {
1020 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001021 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001022 }
1023 }
1024 }
1025 }
1026
1027 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1028 {
1029 if (!used[j])
1030 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1031 }
1032
1033 cmd_args.Clear();
1034 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1035 }
1036 else
1037 {
1038 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1039 // This alias was not created with any options; nothing further needs to be done.
1040 return;
1041 }
1042
1043 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1044 return;
1045}
1046
1047
1048int
1049CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1050{
1051 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1052 // of zero.
1053
1054 char *cptr = (char *) in_string;
1055
1056 // Does it start with '%'
1057 if (cptr[0] == '%')
1058 {
1059 ++cptr;
1060
1061 // Is the rest of it entirely digits?
1062 if (isdigit (cptr[0]))
1063 {
1064 const char *start = cptr;
1065 while (isdigit (cptr[0]))
1066 ++cptr;
1067
1068 // We've gotten to the end of the digits; are we at the end of the string?
1069 if (cptr[0] == '\0')
1070 position = atoi (start);
1071 }
1072 }
1073
1074 return position;
1075}
1076
1077void
1078CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1079{
Greg Clayton887aa282010-10-11 01:05:37 +00001080 // Don't parse any .lldbinit files if we were asked not to
1081 if (m_skip_lldbinit_files)
1082 return;
1083
Chris Lattner24943d22010-06-08 16:52:24 +00001084 const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit";
Greg Clayton537a7a82010-10-20 20:54:39 +00001085 FileSpec init_file (init_file_path, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001086 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
1087 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
1088
1089 if (init_file.Exists())
1090 {
1091 char path[PATH_MAX];
1092 init_file.GetPath(path, sizeof(path));
1093 StreamString source_command;
Johnny Chen7c984242010-07-28 21:16:11 +00001094 source_command.Printf ("command source '%s'", path);
Chris Lattner24943d22010-06-08 16:52:24 +00001095 HandleCommand (source_command.GetData(), false, result);
1096 }
1097 else
1098 {
1099 // nothing to be done if the file doesn't exist
1100 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1101 }
1102}
1103
1104ScriptInterpreter *
1105CommandInterpreter::GetScriptInterpreter ()
1106{
Greg Clayton63094e02010-06-23 01:19:29 +00001107 CommandObject::CommandMap::iterator pos;
1108
1109 pos = m_command_dict.find ("script");
1110 if (pos != m_command_dict.end())
Chris Lattner24943d22010-06-08 16:52:24 +00001111 {
Greg Clayton63094e02010-06-23 01:19:29 +00001112 CommandObject *script_cmd_obj = pos->second.get();
Greg Clayton238c0a12010-09-18 01:14:36 +00001113 return ((CommandObjectScript *) script_cmd_obj)->GetInterpreter ();
Chris Lattner24943d22010-06-08 16:52:24 +00001114 }
Greg Clayton63094e02010-06-23 01:19:29 +00001115 return NULL;
Chris Lattner24943d22010-06-08 16:52:24 +00001116}
1117
1118
1119
1120bool
1121CommandInterpreter::GetSynchronous ()
1122{
1123 return m_synchronous_execution;
1124}
1125
1126void
1127CommandInterpreter::SetSynchronous (bool value)
1128{
Johnny Chend7a4eb02010-10-14 01:22:03 +00001129 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00001130}
1131
1132void
1133CommandInterpreter::OutputFormattedHelpText (Stream &strm,
1134 const char *word_text,
1135 const char *separator,
1136 const char *help_text,
1137 uint32_t max_word_len)
1138{
Greg Clayton238c0a12010-09-18 01:14:36 +00001139 const uint32_t max_columns = m_debugger.GetTerminalWidth();
1140
Chris Lattner24943d22010-06-08 16:52:24 +00001141 int indent_size = max_word_len + strlen (separator) + 2;
1142
1143 strm.IndentMore (indent_size);
1144
1145 int len = indent_size + strlen (help_text) + 1;
1146 char *text = (char *) malloc (len);
1147 sprintf (text, "%-*s %s %s", max_word_len, word_text, separator, help_text);
1148 if (text[len - 1] == '\n')
1149 text[--len] = '\0';
1150
1151 if (len < max_columns)
1152 {
1153 // Output it as a single line.
1154 strm.Printf ("%s", text);
1155 }
1156 else
1157 {
1158 // We need to break it up into multiple lines.
1159 bool first_line = true;
1160 int text_width;
1161 int start = 0;
1162 int end = start;
1163 int final_end = strlen (text);
1164 int sub_len;
1165
1166 while (end < final_end)
1167 {
1168 if (first_line)
1169 text_width = max_columns - 1;
1170 else
1171 text_width = max_columns - indent_size - 1;
1172
1173 // Don't start the 'text' on a space, since we're already outputting the indentation.
1174 if (!first_line)
1175 {
1176 while ((start < final_end) && (text[start] == ' '))
1177 start++;
1178 }
1179
1180 end = start + text_width;
1181 if (end > final_end)
1182 end = final_end;
1183 else
1184 {
1185 // If we're not at the end of the text, make sure we break the line on white space.
1186 while (end > start
1187 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
1188 end--;
1189 }
1190
1191 sub_len = end - start;
1192 if (start != 0)
1193 strm.EOL();
1194 if (!first_line)
1195 strm.Indent();
1196 else
1197 first_line = false;
1198 assert (start <= final_end);
1199 assert (start + sub_len <= final_end);
1200 if (sub_len > 0)
1201 strm.Write (text + start, sub_len);
1202 start = end + 1;
1203 }
1204 }
1205 strm.EOL();
1206 strm.IndentLess(indent_size);
1207 free (text);
1208}
1209
1210void
1211CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
1212 StringList &commands_found, StringList &commands_help)
1213{
1214 CommandObject::CommandMap::const_iterator pos;
1215 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
1216 CommandObject *sub_cmd_obj;
1217
1218 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
1219 {
1220 const char * command_name = pos->first.c_str();
1221 sub_cmd_obj = pos->second.get();
1222 StreamString complete_command_name;
1223
1224 complete_command_name.Printf ("%s %s", prefix, command_name);
1225
Greg Clayton238c0a12010-09-18 01:14:36 +00001226 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001227 {
1228 commands_found.AppendString (complete_command_name.GetData());
1229 commands_help.AppendString (sub_cmd_obj->GetHelp());
1230 }
1231
1232 if (sub_cmd_obj->IsMultiwordObject())
1233 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
1234 commands_help);
1235 }
1236
1237}
1238
1239void
1240CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
1241 StringList &commands_help)
1242{
1243 CommandObject::CommandMap::const_iterator pos;
1244
1245 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1246 {
1247 const char *command_name = pos->first.c_str();
1248 CommandObject *cmd_obj = pos->second.get();
1249
Greg Clayton238c0a12010-09-18 01:14:36 +00001250 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001251 {
1252 commands_found.AppendString (command_name);
1253 commands_help.AppendString (cmd_obj->GetHelp());
1254 }
1255
1256 if (cmd_obj->IsMultiwordObject())
1257 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
1258
1259 }
1260}