blob: 3f9e902de4700d7f994e0b58a0604ddbc243073c [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) :
61 Broadcaster ("CommandInterpreter"),
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,
72 m_debugger.GetInstanceName().AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +000073}
74
75void
76CommandInterpreter::Initialize ()
77{
78 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
79
80 CommandReturnObject result;
81
82 LoadCommandDictionary ();
83
Chris Lattner24943d22010-06-08 16:52:24 +000084 // Set up some initial aliases.
Jim Ingham767af882010-07-07 03:36:20 +000085 result.Clear(); HandleCommand ("command alias q quit", false, result);
Jim Inghame3663e82010-10-22 18:47:16 +000086 result.Clear(); HandleCommand ("command alias run process launch --", false, result);
87 result.Clear(); HandleCommand ("command alias r process launch --", false, result);
Jim Ingham767af882010-07-07 03:36:20 +000088 result.Clear(); HandleCommand ("command alias c process continue", false, result);
89 result.Clear(); HandleCommand ("command alias continue process continue", false, result);
90 result.Clear(); HandleCommand ("command alias expr expression", false, result);
91 result.Clear(); HandleCommand ("command alias exit quit", false, result);
Greg Clayton0f3a8eb2010-09-16 17:09:23 +000092 result.Clear(); HandleCommand ("command alias b regexp-break", false, result);
Jim Ingham767af882010-07-07 03:36:20 +000093 result.Clear(); HandleCommand ("command alias bt thread backtrace", false, result);
94 result.Clear(); HandleCommand ("command alias si thread step-inst", false, result);
95 result.Clear(); HandleCommand ("command alias step thread step-in", false, result);
96 result.Clear(); HandleCommand ("command alias s thread step-in", false, result);
97 result.Clear(); HandleCommand ("command alias next thread step-over", false, result);
98 result.Clear(); HandleCommand ("command alias n thread step-over", false, result);
99 result.Clear(); HandleCommand ("command alias finish thread step-out", false, result);
100 result.Clear(); HandleCommand ("command alias x memory read", false, result);
101 result.Clear(); HandleCommand ("command alias l source list", false, result);
102 result.Clear(); HandleCommand ("command alias list source list", false, result);
Greg Clayton0f3a8eb2010-09-16 17:09:23 +0000103 result.Clear(); HandleCommand ("command alias p frame variable", false, result);
104 result.Clear(); HandleCommand ("command alias print frame variable", false, result);
Jim Inghame3663e82010-10-22 18:47:16 +0000105 result.Clear(); HandleCommand ("command alias po expression -o --", false, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000106}
107
Chris Lattner24943d22010-06-08 16:52:24 +0000108const char *
109CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
110{
111 // This function has not yet been implemented.
112
113 // Look for any embedded script command
114 // If found,
115 // get interpreter object from the command dictionary,
116 // call execute_one_command on it,
117 // get the results as a string,
118 // substitute that string for current stuff.
119
120 return arg;
121}
122
123
124void
125CommandInterpreter::LoadCommandDictionary ()
126{
127 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
128
129 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
130 //
131 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
132 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
133 // the cross-referencing stuff) are created!!!
134 //
135 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
136
137
138 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
139 // are created. This is so that when another command is created that needs to go into a crossref object,
140 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
141 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
142
Chris Lattner24943d22010-06-08 16:52:24 +0000143 // Non-CommandObjectCrossref commands can now be created.
144
Caroline Tice5bc8c972010-09-20 20:44:43 +0000145 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000146
Greg Clayton238c0a12010-09-18 01:14:36 +0000147 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000148 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000149 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000150 m_command_dict["commands"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000151 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
152 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
153 m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000154 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000155 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000156 m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
157 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
158 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
159 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000160 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000161 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000162 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000163 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000164 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000165 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
166 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000167
168 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000169 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
170 "regexp-break",
Caroline Ticec1ad82e2010-09-07 22:38:08 +0000171 "Set a breakpoint using a regular expression to specify the location.",
Caroline Tice43b014a2010-10-04 22:28:36 +0000172 "regexp-break [<filename>:<linenum>]\nregexp-break [<address>]\nregexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000173 if (break_regex_cmd_ap.get())
174 {
175 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
176 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
177 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
178 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list") &&
179 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
180 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
181 {
182 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
183 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
184 }
185 }
186}
187
188int
189CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
190 StringList &matches)
191{
192 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
193
194 if (include_aliases)
195 {
196 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
197 }
198
199 return matches.GetSize();
200}
201
202CommandObjectSP
203CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
204{
205 CommandObject::CommandMap::iterator pos;
206 CommandObjectSP ret_val;
207
208 std::string cmd(cmd_cstr);
209
210 if (HasCommands())
211 {
212 pos = m_command_dict.find(cmd);
213 if (pos != m_command_dict.end())
214 ret_val = pos->second;
215 }
216
217 if (include_aliases && HasAliases())
218 {
219 pos = m_alias_dict.find(cmd);
220 if (pos != m_alias_dict.end())
221 ret_val = pos->second;
222 }
223
224 if (HasUserCommands())
225 {
226 pos = m_user_dict.find(cmd);
227 if (pos != m_user_dict.end())
228 ret_val = pos->second;
229 }
230
231 if (!exact && ret_val == NULL)
232 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000233 // We will only get into here if we didn't find any exact matches.
234
235 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
236
Chris Lattner24943d22010-06-08 16:52:24 +0000237 StringList local_matches;
238 if (matches == NULL)
239 matches = &local_matches;
240
Jim Inghamd40f8a62010-07-06 22:46:59 +0000241 unsigned int num_cmd_matches = 0;
242 unsigned int num_alias_matches = 0;
243 unsigned int num_user_matches = 0;
244
245 // Look through the command dictionaries one by one, and if we get only one match from any of
246 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
247
Chris Lattner24943d22010-06-08 16:52:24 +0000248 if (HasCommands())
249 {
250 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
251 }
252
253 if (num_cmd_matches == 1)
254 {
255 cmd.assign(matches->GetStringAtIndex(0));
256 pos = m_command_dict.find(cmd);
257 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000258 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000259 }
260
Jim Ingham9a574172010-06-24 20:28:42 +0000261 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000262 {
263 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
264
265 }
266
Jim Inghamd40f8a62010-07-06 22:46:59 +0000267 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000268 {
269 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
270 pos = m_alias_dict.find(cmd);
271 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000272 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000273 }
274
Jim Ingham9a574172010-06-24 20:28:42 +0000275 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000276 {
277 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
278 }
279
Jim Inghamd40f8a62010-07-06 22:46:59 +0000280 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000281 {
282 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
283
284 pos = m_user_dict.find (cmd);
285 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000286 user_match_sp = pos->second;
287 }
288
289 // If we got exactly one match, return that, otherwise return the match list.
290
291 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
292 {
293 if (num_cmd_matches)
294 return real_match_sp;
295 else if (num_alias_matches)
296 return alias_match_sp;
297 else
298 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000299 }
300 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000301 else if (matches && ret_val != NULL)
302 {
303 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000304 }
305
306
307 return ret_val;
308}
309
Jim Inghamd40f8a62010-07-06 22:46:59 +0000310CommandObjectSP
311CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000312{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000313 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
314}
315
316CommandObject *
317CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
318{
319 return GetCommandSPExact (cmd_cstr, include_aliases).get();
320}
321
322CommandObject *
323CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
324{
325 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
326
327 // If we didn't find an exact match to the command string in the commands, look in
328 // the aliases.
329
330 if (command_obj == NULL)
331 {
332 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
333 }
334
335 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
336 // in both the commands and the aliases.
337
338 if (command_obj == NULL)
339 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
340
341 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000342}
343
344bool
345CommandInterpreter::CommandExists (const char *cmd)
346{
347 return m_command_dict.find(cmd) != m_command_dict.end();
348}
349
350bool
351CommandInterpreter::AliasExists (const char *cmd)
352{
353 return m_alias_dict.find(cmd) != m_alias_dict.end();
354}
355
356bool
357CommandInterpreter::UserCommandExists (const char *cmd)
358{
359 return m_user_dict.find(cmd) != m_user_dict.end();
360}
361
362void
363CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
364{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000365 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000366 m_alias_dict[alias_name] = command_obj_sp;
367}
368
369bool
370CommandInterpreter::RemoveAlias (const char *alias_name)
371{
372 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
373 if (pos != m_alias_dict.end())
374 {
375 m_alias_dict.erase(pos);
376 return true;
377 }
378 return false;
379}
380bool
381CommandInterpreter::RemoveUser (const char *alias_name)
382{
383 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
384 if (pos != m_user_dict.end())
385 {
386 m_user_dict.erase(pos);
387 return true;
388 }
389 return false;
390}
391
Chris Lattner24943d22010-06-08 16:52:24 +0000392void
393CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
394{
395 help_string.Printf ("'%s", command_name);
396 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
397
398 if (option_arg_vector_sp != NULL)
399 {
400 OptionArgVector *options = option_arg_vector_sp.get();
401 for (int i = 0; i < options->size(); ++i)
402 {
403 OptionArgPair cur_option = (*options)[i];
404 std::string opt = cur_option.first;
405 std::string value = cur_option.second;
406 if (opt.compare("<argument>") == 0)
407 {
408 help_string.Printf (" %s", value.c_str());
409 }
410 else
411 {
412 help_string.Printf (" %s", opt.c_str());
413 if ((value.compare ("<no-argument>") != 0)
414 && (value.compare ("<need-argument") != 0))
415 {
416 help_string.Printf (" %s", value.c_str());
417 }
418 }
419 }
420 }
421
422 help_string.Printf ("'");
423}
424
Greg Clayton65124ea2010-08-26 22:05:43 +0000425size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000426CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
427{
428 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000429 CommandObject::CommandMap::const_iterator end = dict.end();
430 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000431
Greg Clayton65124ea2010-08-26 22:05:43 +0000432 for (pos = dict.begin(); pos != end; ++pos)
433 {
434 size_t len = pos->first.size();
435 if (max_len < len)
436 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000437 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000438 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000439}
440
441void
442CommandInterpreter::GetHelp (CommandReturnObject &result)
443{
444 CommandObject::CommandMap::const_iterator pos;
445 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
446 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000447 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000448
449 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
450 {
451 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
452 max_len);
453 }
454 result.AppendMessage("");
455
456 if (m_alias_dict.size() > 0)
457 {
Jim Inghame3663e82010-10-22 18:47:16 +0000458 result.AppendMessage("The following is a list of your current command abbreviations "
459 "(see 'help commands alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000460 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000461 max_len = FindLongestCommandWord (m_alias_dict);
462
Chris Lattner24943d22010-06-08 16:52:24 +0000463 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
464 {
465 StreamString sstr;
466 StreamString translation_and_help;
467 std::string entry_name = pos->first;
468 std::string second_entry = pos->second.get()->GetCommandName();
469 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
470
471 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
472 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
473 translation_and_help.GetData(), max_len);
474 }
475 result.AppendMessage("");
476 }
477
478 if (m_user_dict.size() > 0)
479 {
480 result.AppendMessage ("The following is a list of your current user-defined commands:");
481 result.AppendMessage("");
482 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
483 {
484 result.AppendMessageWithFormat ("%s -- %s\n", pos->first.c_str(), pos->second->GetHelp());
485 }
486 result.AppendMessage("");
487 }
488
489 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
490}
491
Chris Lattner24943d22010-06-08 16:52:24 +0000492bool
Greg Clayton63094e02010-06-23 01:19:29 +0000493CommandInterpreter::HandleCommand
494(
495 const char *command_line,
496 bool add_to_history,
497 CommandReturnObject &result,
498 ExecutionContext *override_context
499)
Chris Lattner24943d22010-06-08 16:52:24 +0000500{
501 // FIXME: there should probably be a mutex to make sure only one thread can
502 // run the interpreter at a time.
503
504 // TODO: this should be a logging channel in lldb.
505// if (DebugSelf())
506// {
507// result.AppendMessageWithFormat ("Processing command: %s\n", command_line);
508// }
509
Greg Clayton63094e02010-06-23 01:19:29 +0000510 m_debugger.UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +0000511
512 if (command_line == NULL || command_line[0] == '\0')
513 {
514 if (m_command_history.empty())
515 {
516 result.AppendError ("empty command");
517 result.SetStatus(eReturnStatusFailed);
518 return false;
519 }
520 else
521 {
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000522 command_line = m_repeat_command.c_str();
523 if (m_repeat_command.empty())
524 {
Jim Ingham767af882010-07-07 03:36:20 +0000525 result.AppendErrorWithFormat("No auto repeat.\n");
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000526 result.SetStatus (eReturnStatusFailed);
527 return false;
528 }
Chris Lattner24943d22010-06-08 16:52:24 +0000529 }
530 add_to_history = false;
531 }
532
533 Args command_args(command_line);
534
535 if (command_args.GetArgumentCount() > 0)
536 {
537 const char *command_cstr = command_args.GetArgumentAtIndex(0);
538 if (command_cstr)
539 {
540
541 // We're looking up the command object here. So first find an exact match to the
542 // command in the commands.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000543 CommandObject *command_obj = GetCommandObject(command_cstr);
544
545 if (command_obj != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000546 {
Caroline Tice0fb069d2010-10-18 19:18:31 +0000547 std::string aliased_cmd_str;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000548 if (command_obj->IsAlias())
Chris Lattner24943d22010-06-08 16:52:24 +0000549 {
550 BuildAliasCommandArgs (command_obj, command_cstr, command_args, result);
551 if (!result.Succeeded())
552 return false;
Caroline Tice0fb069d2010-10-18 19:18:31 +0000553 else
554 {
555 // We need to transfer the newly constructed args back into the command_line, in case
556 // this happens to be an alias for a command that takes raw input.
557 if (command_args.GetCommandString (aliased_cmd_str))
558 {
559 command_line = aliased_cmd_str.c_str();
Caroline Tice8b5a0772010-10-18 22:38:05 +0000560 command_cstr = command_args.GetArgumentAtIndex (0);
Caroline Tice0fb069d2010-10-18 19:18:31 +0000561 }
562 }
Chris Lattner24943d22010-06-08 16:52:24 +0000563 }
Chris Lattner24943d22010-06-08 16:52:24 +0000564
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000565 if (add_to_history)
566 {
Jim Ingham767af882010-07-07 03:36:20 +0000567 const char *repeat_command = command_obj->GetRepeatCommand(command_args, 0);
568 if (repeat_command != NULL)
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000569 m_repeat_command.assign(repeat_command);
570 else
Jim Ingham767af882010-07-07 03:36:20 +0000571 m_repeat_command.assign(command_line);
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000572
573 m_command_history.push_back (command_line);
574 }
575
576
Chris Lattner24943d22010-06-08 16:52:24 +0000577 if (command_obj->WantsRawCommandString())
578 {
579 const char *stripped_command = ::strstr (command_line, command_cstr);
580 if (stripped_command)
581 {
582 stripped_command += strlen(command_cstr);
583 while (isspace(*stripped_command))
584 ++stripped_command;
Greg Clayton238c0a12010-09-18 01:14:36 +0000585 command_obj->ExecuteRawCommandString (stripped_command, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000586 }
587 }
588 else
589 {
Chris Lattner24943d22010-06-08 16:52:24 +0000590 // Remove the command from the args.
591 command_args.Shift();
Greg Clayton238c0a12010-09-18 01:14:36 +0000592 command_obj->ExecuteWithOptions (command_args, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000593 }
594 }
595 else
596 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000597 // We didn't find the first command object, so complete the first argument.
Chris Lattner24943d22010-06-08 16:52:24 +0000598 StringList matches;
599 int num_matches;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000600 int cursor_index = 0;
601 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
Jim Ingham802f8b02010-06-30 05:02:46 +0000602 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +0000603 num_matches = HandleCompletionMatches (command_args,
604 cursor_index,
605 cursor_char_position,
606 0,
607 -1,
Jim Ingham802f8b02010-06-30 05:02:46 +0000608 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +0000609 matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000610
611 if (num_matches > 0)
612 {
613 std::string error_msg;
614 error_msg.assign ("ambiguous command '");
615 error_msg.append(command_cstr);
616 error_msg.append ("'.");
617
618 error_msg.append (" Possible completions:");
619 for (int i = 0; i < num_matches; i++)
620 {
621 error_msg.append ("\n\t");
622 error_msg.append (matches.GetStringAtIndex (i));
623 }
624 error_msg.append ("\n");
625 result.AppendRawError (error_msg.c_str(), error_msg.size());
626 }
627 else
628 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_cstr);
629
630 result.SetStatus (eReturnStatusFailed);
631 }
632 }
633 }
634 return result.Succeeded();
635}
636
637int
638CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
639 int &cursor_index,
640 int &cursor_char_position,
641 int match_start_point,
642 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +0000643 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000644 StringList &matches)
645{
646 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000647 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +0000648
649 // For any of the command completions a unique match will be a complete word.
650 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000651
652 if (cursor_index == -1)
653 {
654 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +0000655 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000656 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
657 }
658 else if (cursor_index == 0)
659 {
660 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000661 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000662 num_command_matches = matches.GetSize();
663
664 if (num_command_matches == 1
665 && cmd_obj && cmd_obj->IsMultiwordObject()
666 && matches.GetStringAtIndex(0) != NULL
667 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
668 {
669 look_for_subcommand = true;
670 num_command_matches = 0;
671 matches.DeleteStringAtIndex(0);
672 parsed_line.AppendArgument ("");
673 cursor_index++;
674 cursor_char_position = 0;
675 }
676 }
677
678 if (cursor_index > 0 || look_for_subcommand)
679 {
680 // We are completing further on into a commands arguments, so find the command and tell it
681 // to complete the command.
682 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +0000683 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +0000684 if (command_object == NULL)
685 {
686 return 0;
687 }
688 else
689 {
690 parsed_line.Shift();
691 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +0000692 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +0000693 cursor_index,
694 cursor_char_position,
695 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000696 max_return_elements,
697 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000698 matches);
699 }
700 }
701
702 return num_command_matches;
703
704}
705
706int
707CommandInterpreter::HandleCompletion (const char *current_line,
708 const char *cursor,
709 const char *last_char,
710 int match_start_point,
711 int max_return_elements,
712 StringList &matches)
713{
714 // We parse the argument up to the cursor, so the last argument in parsed_line is
715 // the one containing the cursor, and the cursor is after the last character.
716
717 Args parsed_line(current_line, last_char - current_line);
718 Args partial_parsed_line(current_line, cursor - current_line);
719
720 int num_args = partial_parsed_line.GetArgumentCount();
721 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
722 int cursor_char_position;
723
724 if (cursor_index == -1)
725 cursor_char_position = 0;
726 else
727 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
728
729 int num_command_matches;
730
731 matches.Clear();
732
733 // Only max_return_elements == -1 is supported at present:
734 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +0000735 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +0000736 num_command_matches = HandleCompletionMatches (parsed_line,
737 cursor_index,
738 cursor_char_position,
739 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000740 max_return_elements,
741 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +0000742 matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000743
744 if (num_command_matches <= 0)
745 return num_command_matches;
746
747 if (num_args == 0)
748 {
749 // If we got an empty string, insert nothing.
750 matches.InsertStringAtIndex(0, "");
751 }
752 else
753 {
754 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
755 // put an empty string in element 0.
756 std::string command_partial_str;
757 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +0000758 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
759 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +0000760
761 std::string common_prefix;
762 matches.LongestCommonPrefix (common_prefix);
763 int partial_name_len = command_partial_str.size();
764
765 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +0000766 // Only do this if the completer told us this was a complete word, however...
767 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +0000768 {
769 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
770 if (quote_char != '\0')
771 common_prefix.push_back(quote_char);
772
773 common_prefix.push_back(' ');
774 }
775 common_prefix.erase (0, partial_name_len);
776 matches.InsertStringAtIndex(0, common_prefix.c_str());
777 }
778 return num_command_matches;
779}
780
Chris Lattner24943d22010-06-08 16:52:24 +0000781
782CommandInterpreter::~CommandInterpreter ()
783{
784}
785
786const char *
787CommandInterpreter::GetPrompt ()
788{
Caroline Tice5bc8c972010-09-20 20:44:43 +0000789 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +0000790}
791
792void
793CommandInterpreter::SetPrompt (const char *new_prompt)
794{
Caroline Tice5bc8c972010-09-20 20:44:43 +0000795 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +0000796}
797
Jim Ingham5e16ef52010-10-04 19:49:29 +0000798size_t
799CommandInterpreter::GetConfirmationInputReaderCallback (void *baton,
800 InputReader &reader,
801 lldb::InputReaderAction action,
802 const char *bytes,
803 size_t bytes_len)
804{
805 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle();
806 bool *response_ptr = (bool *) baton;
807
808 switch (action)
809 {
810 case eInputReaderActivate:
811 if (out_fh)
812 {
813 if (reader.GetPrompt())
814 ::fprintf (out_fh, "%s", reader.GetPrompt());
815 }
816 break;
817
818 case eInputReaderDeactivate:
819 break;
820
821 case eInputReaderReactivate:
822 if (out_fh && reader.GetPrompt())
823 ::fprintf (out_fh, "%s", reader.GetPrompt());
824 break;
825
826 case eInputReaderGotToken:
827 if (bytes_len == 0)
828 {
829 reader.SetIsDone(true);
830 }
831 else if (bytes[0] == 'y')
832 {
833 *response_ptr = true;
834 reader.SetIsDone(true);
835 }
836 else if (bytes[0] == 'n')
837 {
838 *response_ptr = false;
839 reader.SetIsDone(true);
840 }
841 else
842 {
843 if (out_fh && !reader.IsDone() && reader.GetPrompt())
844 {
845 ::fprintf (out_fh, "Please answer \"y\" or \"n\"\n");
846 ::fprintf (out_fh, "%s", reader.GetPrompt());
847 }
848 }
849 break;
850
851 case eInputReaderDone:
852 break;
853 }
854
855 return bytes_len;
856
857}
858
859bool
860CommandInterpreter::Confirm (const char *message, bool default_answer)
861{
Jim Ingham93057472010-10-04 22:44:14 +0000862 // Check AutoConfirm first:
863 if (m_debugger.GetAutoConfirm())
864 return default_answer;
865
Jim Ingham5e16ef52010-10-04 19:49:29 +0000866 InputReaderSP reader_sp (new InputReader(GetDebugger()));
867 bool response = default_answer;
868 if (reader_sp)
869 {
870 std::string prompt(message);
871 prompt.append(": [");
872 if (default_answer)
873 prompt.append ("Y/n] ");
874 else
875 prompt.append ("y/N] ");
876
877 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
878 &response, // baton
879 eInputReaderGranularityLine, // token size, to pass to callback function
880 NULL, // end token
881 prompt.c_str(), // prompt
882 true)); // echo input
883 if (err.Success())
884 {
885 GetDebugger().PushInputReader (reader_sp);
886 }
887 reader_sp->WaitOnReaderIsDone();
888 }
889 return response;
890}
891
892
Chris Lattner24943d22010-06-08 16:52:24 +0000893void
894CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
895{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000896 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +0000897
898 if (cmd_obj_sp != NULL)
899 {
900 CommandObject *cmd_obj = cmd_obj_sp.get();
901 if (cmd_obj->IsCrossRefObject ())
902 cmd_obj->AddObject (object_type);
903 }
904}
905
Chris Lattner24943d22010-06-08 16:52:24 +0000906OptionArgVectorSP
907CommandInterpreter::GetAliasOptions (const char *alias_name)
908{
909 OptionArgMap::iterator pos;
910 OptionArgVectorSP ret_val;
911
912 std::string alias (alias_name);
913
914 if (HasAliasOptions())
915 {
916 pos = m_alias_options.find (alias);
917 if (pos != m_alias_options.end())
918 ret_val = pos->second;
919 }
920
921 return ret_val;
922}
923
924void
925CommandInterpreter::RemoveAliasOptions (const char *alias_name)
926{
927 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
928 if (pos != m_alias_options.end())
929 {
930 m_alias_options.erase (pos);
931 }
932}
933
934void
935CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
936{
937 m_alias_options[alias_name] = option_arg_vector_sp;
938}
939
940bool
941CommandInterpreter::HasCommands ()
942{
943 return (!m_command_dict.empty());
944}
945
946bool
947CommandInterpreter::HasAliases ()
948{
949 return (!m_alias_dict.empty());
950}
951
952bool
953CommandInterpreter::HasUserCommands ()
954{
955 return (!m_user_dict.empty());
956}
957
958bool
959CommandInterpreter::HasAliasOptions ()
960{
961 return (!m_alias_options.empty());
962}
963
Chris Lattner24943d22010-06-08 16:52:24 +0000964void
Caroline Ticebd5c63e2010-10-12 21:57:09 +0000965CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
966 const char *alias_name,
967 Args &cmd_args,
968 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +0000969{
970 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
971
972 if (option_arg_vector_sp.get())
973 {
974 // Make sure that the alias name is the 0th element in cmd_args
975 std::string alias_name_str = alias_name;
976 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
977 cmd_args.Unshift (alias_name);
978
979 Args new_args (alias_cmd_obj->GetCommandName());
980 if (new_args.GetArgumentCount() == 2)
981 new_args.Shift();
982
983 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
984 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +0000985 std::vector<bool> used (old_size + 1, false);
986
987 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000988
989 for (int i = 0; i < option_arg_vector->size(); ++i)
990 {
991 OptionArgPair option_pair = (*option_arg_vector)[i];
992 std::string option = option_pair.first;
993 std::string value = option_pair.second;
994 if (option.compare ("<argument>") == 0)
995 new_args.AppendArgument (value.c_str());
996 else
997 {
998 new_args.AppendArgument (option.c_str());
999 if (value.compare ("<no-argument>") != 0)
1000 {
1001 int index = GetOptionArgumentPosition (value.c_str());
1002 if (index == 0)
1003 // value was NOT a positional argument; must be a real value
1004 new_args.AppendArgument (value.c_str());
1005 else if (index >= cmd_args.GetArgumentCount())
1006 {
1007 result.AppendErrorWithFormat
1008 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1009 index);
1010 result.SetStatus (eReturnStatusFailed);
1011 return;
1012 }
1013 else
1014 {
1015 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001016 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001017 }
1018 }
1019 }
1020 }
1021
1022 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1023 {
1024 if (!used[j])
1025 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1026 }
1027
1028 cmd_args.Clear();
1029 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1030 }
1031 else
1032 {
1033 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1034 // This alias was not created with any options; nothing further needs to be done.
1035 return;
1036 }
1037
1038 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1039 return;
1040}
1041
1042
1043int
1044CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1045{
1046 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1047 // of zero.
1048
1049 char *cptr = (char *) in_string;
1050
1051 // Does it start with '%'
1052 if (cptr[0] == '%')
1053 {
1054 ++cptr;
1055
1056 // Is the rest of it entirely digits?
1057 if (isdigit (cptr[0]))
1058 {
1059 const char *start = cptr;
1060 while (isdigit (cptr[0]))
1061 ++cptr;
1062
1063 // We've gotten to the end of the digits; are we at the end of the string?
1064 if (cptr[0] == '\0')
1065 position = atoi (start);
1066 }
1067 }
1068
1069 return position;
1070}
1071
1072void
1073CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1074{
Greg Clayton887aa282010-10-11 01:05:37 +00001075 // Don't parse any .lldbinit files if we were asked not to
1076 if (m_skip_lldbinit_files)
1077 return;
1078
Chris Lattner24943d22010-06-08 16:52:24 +00001079 const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit";
Greg Clayton537a7a82010-10-20 20:54:39 +00001080 FileSpec init_file (init_file_path, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001081 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
1082 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
1083
1084 if (init_file.Exists())
1085 {
1086 char path[PATH_MAX];
1087 init_file.GetPath(path, sizeof(path));
1088 StreamString source_command;
Johnny Chen7c984242010-07-28 21:16:11 +00001089 source_command.Printf ("command source '%s'", path);
Chris Lattner24943d22010-06-08 16:52:24 +00001090 HandleCommand (source_command.GetData(), false, result);
1091 }
1092 else
1093 {
1094 // nothing to be done if the file doesn't exist
1095 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1096 }
1097}
1098
1099ScriptInterpreter *
1100CommandInterpreter::GetScriptInterpreter ()
1101{
Greg Clayton63094e02010-06-23 01:19:29 +00001102 CommandObject::CommandMap::iterator pos;
1103
1104 pos = m_command_dict.find ("script");
1105 if (pos != m_command_dict.end())
Chris Lattner24943d22010-06-08 16:52:24 +00001106 {
Greg Clayton63094e02010-06-23 01:19:29 +00001107 CommandObject *script_cmd_obj = pos->second.get();
Greg Clayton238c0a12010-09-18 01:14:36 +00001108 return ((CommandObjectScript *) script_cmd_obj)->GetInterpreter ();
Chris Lattner24943d22010-06-08 16:52:24 +00001109 }
Greg Clayton63094e02010-06-23 01:19:29 +00001110 return NULL;
Chris Lattner24943d22010-06-08 16:52:24 +00001111}
1112
1113
1114
1115bool
1116CommandInterpreter::GetSynchronous ()
1117{
1118 return m_synchronous_execution;
1119}
1120
1121void
1122CommandInterpreter::SetSynchronous (bool value)
1123{
Johnny Chend7a4eb02010-10-14 01:22:03 +00001124 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00001125}
1126
1127void
1128CommandInterpreter::OutputFormattedHelpText (Stream &strm,
1129 const char *word_text,
1130 const char *separator,
1131 const char *help_text,
1132 uint32_t max_word_len)
1133{
Greg Clayton238c0a12010-09-18 01:14:36 +00001134 const uint32_t max_columns = m_debugger.GetTerminalWidth();
1135
Chris Lattner24943d22010-06-08 16:52:24 +00001136 int indent_size = max_word_len + strlen (separator) + 2;
1137
1138 strm.IndentMore (indent_size);
1139
1140 int len = indent_size + strlen (help_text) + 1;
1141 char *text = (char *) malloc (len);
1142 sprintf (text, "%-*s %s %s", max_word_len, word_text, separator, help_text);
1143 if (text[len - 1] == '\n')
1144 text[--len] = '\0';
1145
1146 if (len < max_columns)
1147 {
1148 // Output it as a single line.
1149 strm.Printf ("%s", text);
1150 }
1151 else
1152 {
1153 // We need to break it up into multiple lines.
1154 bool first_line = true;
1155 int text_width;
1156 int start = 0;
1157 int end = start;
1158 int final_end = strlen (text);
1159 int sub_len;
1160
1161 while (end < final_end)
1162 {
1163 if (first_line)
1164 text_width = max_columns - 1;
1165 else
1166 text_width = max_columns - indent_size - 1;
1167
1168 // Don't start the 'text' on a space, since we're already outputting the indentation.
1169 if (!first_line)
1170 {
1171 while ((start < final_end) && (text[start] == ' '))
1172 start++;
1173 }
1174
1175 end = start + text_width;
1176 if (end > final_end)
1177 end = final_end;
1178 else
1179 {
1180 // If we're not at the end of the text, make sure we break the line on white space.
1181 while (end > start
1182 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
1183 end--;
1184 }
1185
1186 sub_len = end - start;
1187 if (start != 0)
1188 strm.EOL();
1189 if (!first_line)
1190 strm.Indent();
1191 else
1192 first_line = false;
1193 assert (start <= final_end);
1194 assert (start + sub_len <= final_end);
1195 if (sub_len > 0)
1196 strm.Write (text + start, sub_len);
1197 start = end + 1;
1198 }
1199 }
1200 strm.EOL();
1201 strm.IndentLess(indent_size);
1202 free (text);
1203}
1204
1205void
1206CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
1207 StringList &commands_found, StringList &commands_help)
1208{
1209 CommandObject::CommandMap::const_iterator pos;
1210 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
1211 CommandObject *sub_cmd_obj;
1212
1213 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
1214 {
1215 const char * command_name = pos->first.c_str();
1216 sub_cmd_obj = pos->second.get();
1217 StreamString complete_command_name;
1218
1219 complete_command_name.Printf ("%s %s", prefix, command_name);
1220
Greg Clayton238c0a12010-09-18 01:14:36 +00001221 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001222 {
1223 commands_found.AppendString (complete_command_name.GetData());
1224 commands_help.AppendString (sub_cmd_obj->GetHelp());
1225 }
1226
1227 if (sub_cmd_obj->IsMultiwordObject())
1228 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
1229 commands_help);
1230 }
1231
1232}
1233
1234void
1235CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
1236 StringList &commands_help)
1237{
1238 CommandObject::CommandMap::const_iterator pos;
1239
1240 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1241 {
1242 const char *command_name = pos->first.c_str();
1243 CommandObject *cmd_obj = pos->second.get();
1244
Greg Clayton238c0a12010-09-18 01:14:36 +00001245 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001246 {
1247 commands_found.AppendString (command_name);
1248 commands_help.AppendString (cmd_obj->GetHelp());
1249 }
1250
1251 if (cmd_obj->IsMultiwordObject())
1252 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
1253
1254 }
1255}