blob: 6c90854c297290aac6431884b992aabf46da73ae [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
Greg Clayton63094e02010-06-23 01:19:29 +0000513 m_debugger.UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +0000514
515 if (command_line == NULL || command_line[0] == '\0')
516 {
517 if (m_command_history.empty())
518 {
519 result.AppendError ("empty command");
520 result.SetStatus(eReturnStatusFailed);
521 return false;
522 }
523 else
524 {
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000525 command_line = m_repeat_command.c_str();
526 if (m_repeat_command.empty())
527 {
Jim Ingham767af882010-07-07 03:36:20 +0000528 result.AppendErrorWithFormat("No auto repeat.\n");
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000529 result.SetStatus (eReturnStatusFailed);
530 return false;
531 }
Chris Lattner24943d22010-06-08 16:52:24 +0000532 }
533 add_to_history = false;
534 }
535
536 Args command_args(command_line);
537
538 if (command_args.GetArgumentCount() > 0)
539 {
540 const char *command_cstr = command_args.GetArgumentAtIndex(0);
541 if (command_cstr)
542 {
543
544 // We're looking up the command object here. So first find an exact match to the
545 // command in the commands.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000546 CommandObject *command_obj = GetCommandObject(command_cstr);
547
548 if (command_obj != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000549 {
Caroline Tice0fb069d2010-10-18 19:18:31 +0000550 std::string aliased_cmd_str;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000551 if (command_obj->IsAlias())
Chris Lattner24943d22010-06-08 16:52:24 +0000552 {
553 BuildAliasCommandArgs (command_obj, command_cstr, command_args, result);
554 if (!result.Succeeded())
555 return false;
Caroline Tice0fb069d2010-10-18 19:18:31 +0000556 else
557 {
558 // We need to transfer the newly constructed args back into the command_line, in case
559 // this happens to be an alias for a command that takes raw input.
560 if (command_args.GetCommandString (aliased_cmd_str))
561 {
562 command_line = aliased_cmd_str.c_str();
Caroline Tice8b5a0772010-10-18 22:38:05 +0000563 command_cstr = command_args.GetArgumentAtIndex (0);
Caroline Tice0fb069d2010-10-18 19:18:31 +0000564 }
565 }
Chris Lattner24943d22010-06-08 16:52:24 +0000566 }
Chris Lattner24943d22010-06-08 16:52:24 +0000567
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000568 if (add_to_history)
569 {
Jim Ingham767af882010-07-07 03:36:20 +0000570 const char *repeat_command = command_obj->GetRepeatCommand(command_args, 0);
571 if (repeat_command != NULL)
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000572 m_repeat_command.assign(repeat_command);
573 else
Jim Ingham767af882010-07-07 03:36:20 +0000574 m_repeat_command.assign(command_line);
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000575
576 m_command_history.push_back (command_line);
577 }
578
579
Chris Lattner24943d22010-06-08 16:52:24 +0000580 if (command_obj->WantsRawCommandString())
581 {
582 const char *stripped_command = ::strstr (command_line, command_cstr);
583 if (stripped_command)
584 {
585 stripped_command += strlen(command_cstr);
586 while (isspace(*stripped_command))
587 ++stripped_command;
Greg Clayton238c0a12010-09-18 01:14:36 +0000588 command_obj->ExecuteRawCommandString (stripped_command, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000589 }
590 }
591 else
592 {
Chris Lattner24943d22010-06-08 16:52:24 +0000593 // Remove the command from the args.
594 command_args.Shift();
Greg Clayton238c0a12010-09-18 01:14:36 +0000595 command_obj->ExecuteWithOptions (command_args, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000596 }
597 }
598 else
599 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000600 // We didn't find the first command object, so complete the first argument.
Chris Lattner24943d22010-06-08 16:52:24 +0000601 StringList matches;
602 int num_matches;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000603 int cursor_index = 0;
604 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
Jim Ingham802f8b02010-06-30 05:02:46 +0000605 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +0000606 num_matches = HandleCompletionMatches (command_args,
607 cursor_index,
608 cursor_char_position,
609 0,
610 -1,
Jim Ingham802f8b02010-06-30 05:02:46 +0000611 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +0000612 matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000613
614 if (num_matches > 0)
615 {
616 std::string error_msg;
617 error_msg.assign ("ambiguous command '");
618 error_msg.append(command_cstr);
619 error_msg.append ("'.");
620
621 error_msg.append (" Possible completions:");
622 for (int i = 0; i < num_matches; i++)
623 {
624 error_msg.append ("\n\t");
625 error_msg.append (matches.GetStringAtIndex (i));
626 }
627 error_msg.append ("\n");
628 result.AppendRawError (error_msg.c_str(), error_msg.size());
629 }
630 else
631 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_cstr);
632
633 result.SetStatus (eReturnStatusFailed);
634 }
635 }
636 }
637 return result.Succeeded();
638}
639
640int
641CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
642 int &cursor_index,
643 int &cursor_char_position,
644 int match_start_point,
645 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +0000646 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000647 StringList &matches)
648{
649 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000650 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +0000651
652 // For any of the command completions a unique match will be a complete word.
653 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000654
655 if (cursor_index == -1)
656 {
657 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +0000658 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000659 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
660 }
661 else if (cursor_index == 0)
662 {
663 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000664 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000665 num_command_matches = matches.GetSize();
666
667 if (num_command_matches == 1
668 && cmd_obj && cmd_obj->IsMultiwordObject()
669 && matches.GetStringAtIndex(0) != NULL
670 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
671 {
672 look_for_subcommand = true;
673 num_command_matches = 0;
674 matches.DeleteStringAtIndex(0);
675 parsed_line.AppendArgument ("");
676 cursor_index++;
677 cursor_char_position = 0;
678 }
679 }
680
681 if (cursor_index > 0 || look_for_subcommand)
682 {
683 // We are completing further on into a commands arguments, so find the command and tell it
684 // to complete the command.
685 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +0000686 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +0000687 if (command_object == NULL)
688 {
689 return 0;
690 }
691 else
692 {
693 parsed_line.Shift();
694 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +0000695 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +0000696 cursor_index,
697 cursor_char_position,
698 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000699 max_return_elements,
700 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000701 matches);
702 }
703 }
704
705 return num_command_matches;
706
707}
708
709int
710CommandInterpreter::HandleCompletion (const char *current_line,
711 const char *cursor,
712 const char *last_char,
713 int match_start_point,
714 int max_return_elements,
715 StringList &matches)
716{
717 // We parse the argument up to the cursor, so the last argument in parsed_line is
718 // the one containing the cursor, and the cursor is after the last character.
719
720 Args parsed_line(current_line, last_char - current_line);
721 Args partial_parsed_line(current_line, cursor - current_line);
722
723 int num_args = partial_parsed_line.GetArgumentCount();
724 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
725 int cursor_char_position;
726
727 if (cursor_index == -1)
728 cursor_char_position = 0;
729 else
730 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
731
732 int num_command_matches;
733
734 matches.Clear();
735
736 // Only max_return_elements == -1 is supported at present:
737 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +0000738 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +0000739 num_command_matches = HandleCompletionMatches (parsed_line,
740 cursor_index,
741 cursor_char_position,
742 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000743 max_return_elements,
744 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +0000745 matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000746
747 if (num_command_matches <= 0)
748 return num_command_matches;
749
750 if (num_args == 0)
751 {
752 // If we got an empty string, insert nothing.
753 matches.InsertStringAtIndex(0, "");
754 }
755 else
756 {
757 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
758 // put an empty string in element 0.
759 std::string command_partial_str;
760 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +0000761 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
762 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +0000763
764 std::string common_prefix;
765 matches.LongestCommonPrefix (common_prefix);
766 int partial_name_len = command_partial_str.size();
767
768 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +0000769 // Only do this if the completer told us this was a complete word, however...
770 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +0000771 {
772 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
773 if (quote_char != '\0')
774 common_prefix.push_back(quote_char);
775
776 common_prefix.push_back(' ');
777 }
778 common_prefix.erase (0, partial_name_len);
779 matches.InsertStringAtIndex(0, common_prefix.c_str());
780 }
781 return num_command_matches;
782}
783
Chris Lattner24943d22010-06-08 16:52:24 +0000784
785CommandInterpreter::~CommandInterpreter ()
786{
787}
788
789const char *
790CommandInterpreter::GetPrompt ()
791{
Caroline Tice5bc8c972010-09-20 20:44:43 +0000792 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +0000793}
794
795void
796CommandInterpreter::SetPrompt (const char *new_prompt)
797{
Caroline Tice5bc8c972010-09-20 20:44:43 +0000798 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +0000799}
800
Jim Ingham5e16ef52010-10-04 19:49:29 +0000801size_t
802CommandInterpreter::GetConfirmationInputReaderCallback (void *baton,
803 InputReader &reader,
804 lldb::InputReaderAction action,
805 const char *bytes,
806 size_t bytes_len)
807{
808 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle();
809 bool *response_ptr = (bool *) baton;
810
811 switch (action)
812 {
813 case eInputReaderActivate:
814 if (out_fh)
815 {
816 if (reader.GetPrompt())
817 ::fprintf (out_fh, "%s", reader.GetPrompt());
818 }
819 break;
820
821 case eInputReaderDeactivate:
822 break;
823
824 case eInputReaderReactivate:
825 if (out_fh && reader.GetPrompt())
826 ::fprintf (out_fh, "%s", reader.GetPrompt());
827 break;
828
829 case eInputReaderGotToken:
830 if (bytes_len == 0)
831 {
832 reader.SetIsDone(true);
833 }
834 else if (bytes[0] == 'y')
835 {
836 *response_ptr = true;
837 reader.SetIsDone(true);
838 }
839 else if (bytes[0] == 'n')
840 {
841 *response_ptr = false;
842 reader.SetIsDone(true);
843 }
844 else
845 {
846 if (out_fh && !reader.IsDone() && reader.GetPrompt())
847 {
848 ::fprintf (out_fh, "Please answer \"y\" or \"n\"\n");
849 ::fprintf (out_fh, "%s", reader.GetPrompt());
850 }
851 }
852 break;
853
854 case eInputReaderDone:
855 break;
856 }
857
858 return bytes_len;
859
860}
861
862bool
863CommandInterpreter::Confirm (const char *message, bool default_answer)
864{
Jim Ingham93057472010-10-04 22:44:14 +0000865 // Check AutoConfirm first:
866 if (m_debugger.GetAutoConfirm())
867 return default_answer;
868
Jim Ingham5e16ef52010-10-04 19:49:29 +0000869 InputReaderSP reader_sp (new InputReader(GetDebugger()));
870 bool response = default_answer;
871 if (reader_sp)
872 {
873 std::string prompt(message);
874 prompt.append(": [");
875 if (default_answer)
876 prompt.append ("Y/n] ");
877 else
878 prompt.append ("y/N] ");
879
880 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
881 &response, // baton
882 eInputReaderGranularityLine, // token size, to pass to callback function
883 NULL, // end token
884 prompt.c_str(), // prompt
885 true)); // echo input
886 if (err.Success())
887 {
888 GetDebugger().PushInputReader (reader_sp);
889 }
890 reader_sp->WaitOnReaderIsDone();
891 }
892 return response;
893}
894
895
Chris Lattner24943d22010-06-08 16:52:24 +0000896void
897CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
898{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000899 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +0000900
901 if (cmd_obj_sp != NULL)
902 {
903 CommandObject *cmd_obj = cmd_obj_sp.get();
904 if (cmd_obj->IsCrossRefObject ())
905 cmd_obj->AddObject (object_type);
906 }
907}
908
Chris Lattner24943d22010-06-08 16:52:24 +0000909OptionArgVectorSP
910CommandInterpreter::GetAliasOptions (const char *alias_name)
911{
912 OptionArgMap::iterator pos;
913 OptionArgVectorSP ret_val;
914
915 std::string alias (alias_name);
916
917 if (HasAliasOptions())
918 {
919 pos = m_alias_options.find (alias);
920 if (pos != m_alias_options.end())
921 ret_val = pos->second;
922 }
923
924 return ret_val;
925}
926
927void
928CommandInterpreter::RemoveAliasOptions (const char *alias_name)
929{
930 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
931 if (pos != m_alias_options.end())
932 {
933 m_alias_options.erase (pos);
934 }
935}
936
937void
938CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
939{
940 m_alias_options[alias_name] = option_arg_vector_sp;
941}
942
943bool
944CommandInterpreter::HasCommands ()
945{
946 return (!m_command_dict.empty());
947}
948
949bool
950CommandInterpreter::HasAliases ()
951{
952 return (!m_alias_dict.empty());
953}
954
955bool
956CommandInterpreter::HasUserCommands ()
957{
958 return (!m_user_dict.empty());
959}
960
961bool
962CommandInterpreter::HasAliasOptions ()
963{
964 return (!m_alias_options.empty());
965}
966
Chris Lattner24943d22010-06-08 16:52:24 +0000967void
Caroline Ticebd5c63e2010-10-12 21:57:09 +0000968CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
969 const char *alias_name,
970 Args &cmd_args,
971 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +0000972{
973 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
974
975 if (option_arg_vector_sp.get())
976 {
977 // Make sure that the alias name is the 0th element in cmd_args
978 std::string alias_name_str = alias_name;
979 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
980 cmd_args.Unshift (alias_name);
981
982 Args new_args (alias_cmd_obj->GetCommandName());
983 if (new_args.GetArgumentCount() == 2)
984 new_args.Shift();
985
986 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
987 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +0000988 std::vector<bool> used (old_size + 1, false);
989
990 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000991
992 for (int i = 0; i < option_arg_vector->size(); ++i)
993 {
994 OptionArgPair option_pair = (*option_arg_vector)[i];
995 std::string option = option_pair.first;
996 std::string value = option_pair.second;
997 if (option.compare ("<argument>") == 0)
998 new_args.AppendArgument (value.c_str());
999 else
1000 {
1001 new_args.AppendArgument (option.c_str());
1002 if (value.compare ("<no-argument>") != 0)
1003 {
1004 int index = GetOptionArgumentPosition (value.c_str());
1005 if (index == 0)
1006 // value was NOT a positional argument; must be a real value
1007 new_args.AppendArgument (value.c_str());
1008 else if (index >= cmd_args.GetArgumentCount())
1009 {
1010 result.AppendErrorWithFormat
1011 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1012 index);
1013 result.SetStatus (eReturnStatusFailed);
1014 return;
1015 }
1016 else
1017 {
1018 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001019 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001020 }
1021 }
1022 }
1023 }
1024
1025 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1026 {
1027 if (!used[j])
1028 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1029 }
1030
1031 cmd_args.Clear();
1032 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1033 }
1034 else
1035 {
1036 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1037 // This alias was not created with any options; nothing further needs to be done.
1038 return;
1039 }
1040
1041 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1042 return;
1043}
1044
1045
1046int
1047CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1048{
1049 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1050 // of zero.
1051
1052 char *cptr = (char *) in_string;
1053
1054 // Does it start with '%'
1055 if (cptr[0] == '%')
1056 {
1057 ++cptr;
1058
1059 // Is the rest of it entirely digits?
1060 if (isdigit (cptr[0]))
1061 {
1062 const char *start = cptr;
1063 while (isdigit (cptr[0]))
1064 ++cptr;
1065
1066 // We've gotten to the end of the digits; are we at the end of the string?
1067 if (cptr[0] == '\0')
1068 position = atoi (start);
1069 }
1070 }
1071
1072 return position;
1073}
1074
1075void
1076CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1077{
Greg Clayton887aa282010-10-11 01:05:37 +00001078 // Don't parse any .lldbinit files if we were asked not to
1079 if (m_skip_lldbinit_files)
1080 return;
1081
Chris Lattner24943d22010-06-08 16:52:24 +00001082 const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit";
Greg Clayton537a7a82010-10-20 20:54:39 +00001083 FileSpec init_file (init_file_path, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001084 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
1085 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
1086
1087 if (init_file.Exists())
1088 {
1089 char path[PATH_MAX];
1090 init_file.GetPath(path, sizeof(path));
1091 StreamString source_command;
Johnny Chen7c984242010-07-28 21:16:11 +00001092 source_command.Printf ("command source '%s'", path);
Chris Lattner24943d22010-06-08 16:52:24 +00001093 HandleCommand (source_command.GetData(), false, result);
1094 }
1095 else
1096 {
1097 // nothing to be done if the file doesn't exist
1098 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1099 }
1100}
1101
1102ScriptInterpreter *
1103CommandInterpreter::GetScriptInterpreter ()
1104{
Greg Clayton63094e02010-06-23 01:19:29 +00001105 CommandObject::CommandMap::iterator pos;
1106
1107 pos = m_command_dict.find ("script");
1108 if (pos != m_command_dict.end())
Chris Lattner24943d22010-06-08 16:52:24 +00001109 {
Greg Clayton63094e02010-06-23 01:19:29 +00001110 CommandObject *script_cmd_obj = pos->second.get();
Greg Clayton238c0a12010-09-18 01:14:36 +00001111 return ((CommandObjectScript *) script_cmd_obj)->GetInterpreter ();
Chris Lattner24943d22010-06-08 16:52:24 +00001112 }
Greg Clayton63094e02010-06-23 01:19:29 +00001113 return NULL;
Chris Lattner24943d22010-06-08 16:52:24 +00001114}
1115
1116
1117
1118bool
1119CommandInterpreter::GetSynchronous ()
1120{
1121 return m_synchronous_execution;
1122}
1123
1124void
1125CommandInterpreter::SetSynchronous (bool value)
1126{
Johnny Chend7a4eb02010-10-14 01:22:03 +00001127 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00001128}
1129
1130void
1131CommandInterpreter::OutputFormattedHelpText (Stream &strm,
1132 const char *word_text,
1133 const char *separator,
1134 const char *help_text,
1135 uint32_t max_word_len)
1136{
Greg Clayton238c0a12010-09-18 01:14:36 +00001137 const uint32_t max_columns = m_debugger.GetTerminalWidth();
1138
Chris Lattner24943d22010-06-08 16:52:24 +00001139 int indent_size = max_word_len + strlen (separator) + 2;
1140
1141 strm.IndentMore (indent_size);
1142
1143 int len = indent_size + strlen (help_text) + 1;
1144 char *text = (char *) malloc (len);
1145 sprintf (text, "%-*s %s %s", max_word_len, word_text, separator, help_text);
1146 if (text[len - 1] == '\n')
1147 text[--len] = '\0';
1148
1149 if (len < max_columns)
1150 {
1151 // Output it as a single line.
1152 strm.Printf ("%s", text);
1153 }
1154 else
1155 {
1156 // We need to break it up into multiple lines.
1157 bool first_line = true;
1158 int text_width;
1159 int start = 0;
1160 int end = start;
1161 int final_end = strlen (text);
1162 int sub_len;
1163
1164 while (end < final_end)
1165 {
1166 if (first_line)
1167 text_width = max_columns - 1;
1168 else
1169 text_width = max_columns - indent_size - 1;
1170
1171 // Don't start the 'text' on a space, since we're already outputting the indentation.
1172 if (!first_line)
1173 {
1174 while ((start < final_end) && (text[start] == ' '))
1175 start++;
1176 }
1177
1178 end = start + text_width;
1179 if (end > final_end)
1180 end = final_end;
1181 else
1182 {
1183 // If we're not at the end of the text, make sure we break the line on white space.
1184 while (end > start
1185 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
1186 end--;
1187 }
1188
1189 sub_len = end - start;
1190 if (start != 0)
1191 strm.EOL();
1192 if (!first_line)
1193 strm.Indent();
1194 else
1195 first_line = false;
1196 assert (start <= final_end);
1197 assert (start + sub_len <= final_end);
1198 if (sub_len > 0)
1199 strm.Write (text + start, sub_len);
1200 start = end + 1;
1201 }
1202 }
1203 strm.EOL();
1204 strm.IndentLess(indent_size);
1205 free (text);
1206}
1207
1208void
1209CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
1210 StringList &commands_found, StringList &commands_help)
1211{
1212 CommandObject::CommandMap::const_iterator pos;
1213 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
1214 CommandObject *sub_cmd_obj;
1215
1216 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
1217 {
1218 const char * command_name = pos->first.c_str();
1219 sub_cmd_obj = pos->second.get();
1220 StreamString complete_command_name;
1221
1222 complete_command_name.Printf ("%s %s", prefix, command_name);
1223
Greg Clayton238c0a12010-09-18 01:14:36 +00001224 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001225 {
1226 commands_found.AppendString (complete_command_name.GetData());
1227 commands_help.AppendString (sub_cmd_obj->GetHelp());
1228 }
1229
1230 if (sub_cmd_obj->IsMultiwordObject())
1231 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
1232 commands_help);
1233 }
1234
1235}
1236
1237void
1238CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
1239 StringList &commands_help)
1240{
1241 CommandObject::CommandMap::const_iterator pos;
1242
1243 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1244 {
1245 const char *command_name = pos->first.c_str();
1246 CommandObject *cmd_obj = pos->second.get();
1247
Greg Clayton238c0a12010-09-18 01:14:36 +00001248 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001249 {
1250 commands_found.AppendString (command_name);
1251 commands_help.AppendString (cmd_obj->GetHelp());
1252 }
1253
1254 if (cmd_obj->IsMultiwordObject())
1255 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
1256
1257 }
1258}