blob: 4a87ba0359d6e9f9fe6bd7f6afc69cdef1b55d51 [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);
86 result.Clear(); HandleCommand ("command alias run process launch", false, result);
87 result.Clear(); HandleCommand ("command alias r process launch", false, result);
88 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);
Chris Lattner24943d22010-06-08 16:52:24 +0000105}
106
Chris Lattner24943d22010-06-08 16:52:24 +0000107const char *
108CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
109{
110 // This function has not yet been implemented.
111
112 // Look for any embedded script command
113 // If found,
114 // get interpreter object from the command dictionary,
115 // call execute_one_command on it,
116 // get the results as a string,
117 // substitute that string for current stuff.
118
119 return arg;
120}
121
122
123void
124CommandInterpreter::LoadCommandDictionary ()
125{
126 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
127
128 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
129 //
130 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
131 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
132 // the cross-referencing stuff) are created!!!
133 //
134 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
135
136
137 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
138 // are created. This is so that when another command is created that needs to go into a crossref object,
139 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
140 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
141
Chris Lattner24943d22010-06-08 16:52:24 +0000142 // Non-CommandObjectCrossref commands can now be created.
143
Caroline Tice5bc8c972010-09-20 20:44:43 +0000144 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000145
Greg Clayton238c0a12010-09-18 01:14:36 +0000146 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000147 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000148 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000149 m_command_dict["commands"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000150 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
151 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
152 m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000153 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000154 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000155 m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
156 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
157 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
158 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000159 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000160 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000161 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000162 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000163 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000164 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
165 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000166
167 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000168 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
169 "regexp-break",
Caroline Ticec1ad82e2010-09-07 22:38:08 +0000170 "Set a breakpoint using a regular expression to specify the location.",
Caroline Tice43b014a2010-10-04 22:28:36 +0000171 "regexp-break [<filename>:<linenum>]\nregexp-break [<address>]\nregexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000172 if (break_regex_cmd_ap.get())
173 {
174 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
175 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
176 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
177 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list") &&
178 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
179 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
180 {
181 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
182 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
183 }
184 }
185}
186
187int
188CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
189 StringList &matches)
190{
191 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
192
193 if (include_aliases)
194 {
195 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
196 }
197
198 return matches.GetSize();
199}
200
201CommandObjectSP
202CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
203{
204 CommandObject::CommandMap::iterator pos;
205 CommandObjectSP ret_val;
206
207 std::string cmd(cmd_cstr);
208
209 if (HasCommands())
210 {
211 pos = m_command_dict.find(cmd);
212 if (pos != m_command_dict.end())
213 ret_val = pos->second;
214 }
215
216 if (include_aliases && HasAliases())
217 {
218 pos = m_alias_dict.find(cmd);
219 if (pos != m_alias_dict.end())
220 ret_val = pos->second;
221 }
222
223 if (HasUserCommands())
224 {
225 pos = m_user_dict.find(cmd);
226 if (pos != m_user_dict.end())
227 ret_val = pos->second;
228 }
229
230 if (!exact && ret_val == NULL)
231 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000232 // We will only get into here if we didn't find any exact matches.
233
234 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
235
Chris Lattner24943d22010-06-08 16:52:24 +0000236 StringList local_matches;
237 if (matches == NULL)
238 matches = &local_matches;
239
Jim Inghamd40f8a62010-07-06 22:46:59 +0000240 unsigned int num_cmd_matches = 0;
241 unsigned int num_alias_matches = 0;
242 unsigned int num_user_matches = 0;
243
244 // Look through the command dictionaries one by one, and if we get only one match from any of
245 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
246
Chris Lattner24943d22010-06-08 16:52:24 +0000247 if (HasCommands())
248 {
249 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
250 }
251
252 if (num_cmd_matches == 1)
253 {
254 cmd.assign(matches->GetStringAtIndex(0));
255 pos = m_command_dict.find(cmd);
256 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000257 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000258 }
259
Jim Ingham9a574172010-06-24 20:28:42 +0000260 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000261 {
262 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
263
264 }
265
Jim Inghamd40f8a62010-07-06 22:46:59 +0000266 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000267 {
268 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
269 pos = m_alias_dict.find(cmd);
270 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000271 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000272 }
273
Jim Ingham9a574172010-06-24 20:28:42 +0000274 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000275 {
276 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
277 }
278
Jim Inghamd40f8a62010-07-06 22:46:59 +0000279 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000280 {
281 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
282
283 pos = m_user_dict.find (cmd);
284 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000285 user_match_sp = pos->second;
286 }
287
288 // If we got exactly one match, return that, otherwise return the match list.
289
290 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
291 {
292 if (num_cmd_matches)
293 return real_match_sp;
294 else if (num_alias_matches)
295 return alias_match_sp;
296 else
297 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000298 }
299 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000300 else if (matches && ret_val != NULL)
301 {
302 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000303 }
304
305
306 return ret_val;
307}
308
Jim Inghamd40f8a62010-07-06 22:46:59 +0000309CommandObjectSP
310CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000311{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000312 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
313}
314
315CommandObject *
316CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
317{
318 return GetCommandSPExact (cmd_cstr, include_aliases).get();
319}
320
321CommandObject *
322CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
323{
324 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
325
326 // If we didn't find an exact match to the command string in the commands, look in
327 // the aliases.
328
329 if (command_obj == NULL)
330 {
331 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
332 }
333
334 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
335 // in both the commands and the aliases.
336
337 if (command_obj == NULL)
338 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
339
340 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000341}
342
343bool
344CommandInterpreter::CommandExists (const char *cmd)
345{
346 return m_command_dict.find(cmd) != m_command_dict.end();
347}
348
349bool
350CommandInterpreter::AliasExists (const char *cmd)
351{
352 return m_alias_dict.find(cmd) != m_alias_dict.end();
353}
354
355bool
356CommandInterpreter::UserCommandExists (const char *cmd)
357{
358 return m_user_dict.find(cmd) != m_user_dict.end();
359}
360
361void
362CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
363{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000364 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000365 m_alias_dict[alias_name] = command_obj_sp;
366}
367
368bool
369CommandInterpreter::RemoveAlias (const char *alias_name)
370{
371 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
372 if (pos != m_alias_dict.end())
373 {
374 m_alias_dict.erase(pos);
375 return true;
376 }
377 return false;
378}
379bool
380CommandInterpreter::RemoveUser (const char *alias_name)
381{
382 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
383 if (pos != m_user_dict.end())
384 {
385 m_user_dict.erase(pos);
386 return true;
387 }
388 return false;
389}
390
Chris Lattner24943d22010-06-08 16:52:24 +0000391void
392CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
393{
394 help_string.Printf ("'%s", command_name);
395 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
396
397 if (option_arg_vector_sp != NULL)
398 {
399 OptionArgVector *options = option_arg_vector_sp.get();
400 for (int i = 0; i < options->size(); ++i)
401 {
402 OptionArgPair cur_option = (*options)[i];
403 std::string opt = cur_option.first;
404 std::string value = cur_option.second;
405 if (opt.compare("<argument>") == 0)
406 {
407 help_string.Printf (" %s", value.c_str());
408 }
409 else
410 {
411 help_string.Printf (" %s", opt.c_str());
412 if ((value.compare ("<no-argument>") != 0)
413 && (value.compare ("<need-argument") != 0))
414 {
415 help_string.Printf (" %s", value.c_str());
416 }
417 }
418 }
419 }
420
421 help_string.Printf ("'");
422}
423
Greg Clayton65124ea2010-08-26 22:05:43 +0000424size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000425CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
426{
427 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000428 CommandObject::CommandMap::const_iterator end = dict.end();
429 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000430
Greg Clayton65124ea2010-08-26 22:05:43 +0000431 for (pos = dict.begin(); pos != end; ++pos)
432 {
433 size_t len = pos->first.size();
434 if (max_len < len)
435 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000436 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000437 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000438}
439
440void
441CommandInterpreter::GetHelp (CommandReturnObject &result)
442{
443 CommandObject::CommandMap::const_iterator pos;
444 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
445 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000446 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000447
448 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
449 {
450 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
451 max_len);
452 }
453 result.AppendMessage("");
454
455 if (m_alias_dict.size() > 0)
456 {
Caroline Tice00edd3a2010-09-13 05:27:16 +0000457 result.AppendMessage("The following is a list of your current command abbreviations (see 'help commands alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000458 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000459 max_len = FindLongestCommandWord (m_alias_dict);
460
Chris Lattner24943d22010-06-08 16:52:24 +0000461 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
462 {
463 StreamString sstr;
464 StreamString translation_and_help;
465 std::string entry_name = pos->first;
466 std::string second_entry = pos->second.get()->GetCommandName();
467 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
468
469 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
470 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
471 translation_and_help.GetData(), max_len);
472 }
473 result.AppendMessage("");
474 }
475
476 if (m_user_dict.size() > 0)
477 {
478 result.AppendMessage ("The following is a list of your current user-defined commands:");
479 result.AppendMessage("");
480 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
481 {
482 result.AppendMessageWithFormat ("%s -- %s\n", pos->first.c_str(), pos->second->GetHelp());
483 }
484 result.AppendMessage("");
485 }
486
487 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
488}
489
Chris Lattner24943d22010-06-08 16:52:24 +0000490bool
Greg Clayton63094e02010-06-23 01:19:29 +0000491CommandInterpreter::HandleCommand
492(
493 const char *command_line,
494 bool add_to_history,
495 CommandReturnObject &result,
496 ExecutionContext *override_context
497)
Chris Lattner24943d22010-06-08 16:52:24 +0000498{
499 // FIXME: there should probably be a mutex to make sure only one thread can
500 // run the interpreter at a time.
501
502 // TODO: this should be a logging channel in lldb.
503// if (DebugSelf())
504// {
505// result.AppendMessageWithFormat ("Processing command: %s\n", command_line);
506// }
507
Greg Clayton63094e02010-06-23 01:19:29 +0000508 m_debugger.UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +0000509
510 if (command_line == NULL || command_line[0] == '\0')
511 {
512 if (m_command_history.empty())
513 {
514 result.AppendError ("empty command");
515 result.SetStatus(eReturnStatusFailed);
516 return false;
517 }
518 else
519 {
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000520 command_line = m_repeat_command.c_str();
521 if (m_repeat_command.empty())
522 {
Jim Ingham767af882010-07-07 03:36:20 +0000523 result.AppendErrorWithFormat("No auto repeat.\n");
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000524 result.SetStatus (eReturnStatusFailed);
525 return false;
526 }
Chris Lattner24943d22010-06-08 16:52:24 +0000527 }
528 add_to_history = false;
529 }
530
531 Args command_args(command_line);
532
533 if (command_args.GetArgumentCount() > 0)
534 {
535 const char *command_cstr = command_args.GetArgumentAtIndex(0);
536 if (command_cstr)
537 {
538
539 // We're looking up the command object here. So first find an exact match to the
540 // command in the commands.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000541 CommandObject *command_obj = GetCommandObject(command_cstr);
542
543 if (command_obj != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000544 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000545 if (command_obj->IsAlias())
Chris Lattner24943d22010-06-08 16:52:24 +0000546 {
547 BuildAliasCommandArgs (command_obj, command_cstr, command_args, result);
548 if (!result.Succeeded())
549 return false;
550 }
Chris Lattner24943d22010-06-08 16:52:24 +0000551
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000552 if (add_to_history)
553 {
Jim Ingham767af882010-07-07 03:36:20 +0000554 const char *repeat_command = command_obj->GetRepeatCommand(command_args, 0);
555 if (repeat_command != NULL)
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000556 m_repeat_command.assign(repeat_command);
557 else
Jim Ingham767af882010-07-07 03:36:20 +0000558 m_repeat_command.assign(command_line);
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000559
560 m_command_history.push_back (command_line);
561 }
562
563
Chris Lattner24943d22010-06-08 16:52:24 +0000564 if (command_obj->WantsRawCommandString())
565 {
566 const char *stripped_command = ::strstr (command_line, command_cstr);
567 if (stripped_command)
568 {
569 stripped_command += strlen(command_cstr);
570 while (isspace(*stripped_command))
571 ++stripped_command;
Greg Clayton238c0a12010-09-18 01:14:36 +0000572 command_obj->ExecuteRawCommandString (stripped_command, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000573 }
574 }
575 else
576 {
Chris Lattner24943d22010-06-08 16:52:24 +0000577 // Remove the command from the args.
578 command_args.Shift();
Greg Clayton238c0a12010-09-18 01:14:36 +0000579 command_obj->ExecuteWithOptions (command_args, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000580 }
581 }
582 else
583 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000584 // We didn't find the first command object, so complete the first argument.
Chris Lattner24943d22010-06-08 16:52:24 +0000585 StringList matches;
586 int num_matches;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000587 int cursor_index = 0;
588 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
Jim Ingham802f8b02010-06-30 05:02:46 +0000589 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +0000590 num_matches = HandleCompletionMatches (command_args,
591 cursor_index,
592 cursor_char_position,
593 0,
594 -1,
Jim Ingham802f8b02010-06-30 05:02:46 +0000595 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +0000596 matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000597
598 if (num_matches > 0)
599 {
600 std::string error_msg;
601 error_msg.assign ("ambiguous command '");
602 error_msg.append(command_cstr);
603 error_msg.append ("'.");
604
605 error_msg.append (" Possible completions:");
606 for (int i = 0; i < num_matches; i++)
607 {
608 error_msg.append ("\n\t");
609 error_msg.append (matches.GetStringAtIndex (i));
610 }
611 error_msg.append ("\n");
612 result.AppendRawError (error_msg.c_str(), error_msg.size());
613 }
614 else
615 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_cstr);
616
617 result.SetStatus (eReturnStatusFailed);
618 }
619 }
620 }
621 return result.Succeeded();
622}
623
624int
625CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
626 int &cursor_index,
627 int &cursor_char_position,
628 int match_start_point,
629 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +0000630 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000631 StringList &matches)
632{
633 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000634 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +0000635
636 // For any of the command completions a unique match will be a complete word.
637 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000638
639 if (cursor_index == -1)
640 {
641 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +0000642 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000643 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
644 }
645 else if (cursor_index == 0)
646 {
647 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000648 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000649 num_command_matches = matches.GetSize();
650
651 if (num_command_matches == 1
652 && cmd_obj && cmd_obj->IsMultiwordObject()
653 && matches.GetStringAtIndex(0) != NULL
654 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
655 {
656 look_for_subcommand = true;
657 num_command_matches = 0;
658 matches.DeleteStringAtIndex(0);
659 parsed_line.AppendArgument ("");
660 cursor_index++;
661 cursor_char_position = 0;
662 }
663 }
664
665 if (cursor_index > 0 || look_for_subcommand)
666 {
667 // We are completing further on into a commands arguments, so find the command and tell it
668 // to complete the command.
669 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +0000670 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +0000671 if (command_object == NULL)
672 {
673 return 0;
674 }
675 else
676 {
677 parsed_line.Shift();
678 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +0000679 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +0000680 cursor_index,
681 cursor_char_position,
682 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000683 max_return_elements,
684 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000685 matches);
686 }
687 }
688
689 return num_command_matches;
690
691}
692
693int
694CommandInterpreter::HandleCompletion (const char *current_line,
695 const char *cursor,
696 const char *last_char,
697 int match_start_point,
698 int max_return_elements,
699 StringList &matches)
700{
701 // We parse the argument up to the cursor, so the last argument in parsed_line is
702 // the one containing the cursor, and the cursor is after the last character.
703
704 Args parsed_line(current_line, last_char - current_line);
705 Args partial_parsed_line(current_line, cursor - current_line);
706
707 int num_args = partial_parsed_line.GetArgumentCount();
708 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
709 int cursor_char_position;
710
711 if (cursor_index == -1)
712 cursor_char_position = 0;
713 else
714 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
715
716 int num_command_matches;
717
718 matches.Clear();
719
720 // Only max_return_elements == -1 is supported at present:
721 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +0000722 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +0000723 num_command_matches = HandleCompletionMatches (parsed_line,
724 cursor_index,
725 cursor_char_position,
726 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000727 max_return_elements,
728 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +0000729 matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000730
731 if (num_command_matches <= 0)
732 return num_command_matches;
733
734 if (num_args == 0)
735 {
736 // If we got an empty string, insert nothing.
737 matches.InsertStringAtIndex(0, "");
738 }
739 else
740 {
741 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
742 // put an empty string in element 0.
743 std::string command_partial_str;
744 if (cursor_index >= 0)
745 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index), parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
746
747 std::string common_prefix;
748 matches.LongestCommonPrefix (common_prefix);
749 int partial_name_len = command_partial_str.size();
750
751 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +0000752 // Only do this if the completer told us this was a complete word, however...
753 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +0000754 {
755 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
756 if (quote_char != '\0')
757 common_prefix.push_back(quote_char);
758
759 common_prefix.push_back(' ');
760 }
761 common_prefix.erase (0, partial_name_len);
762 matches.InsertStringAtIndex(0, common_prefix.c_str());
763 }
764 return num_command_matches;
765}
766
Chris Lattner24943d22010-06-08 16:52:24 +0000767
768CommandInterpreter::~CommandInterpreter ()
769{
770}
771
772const char *
773CommandInterpreter::GetPrompt ()
774{
Caroline Tice5bc8c972010-09-20 20:44:43 +0000775 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +0000776}
777
778void
779CommandInterpreter::SetPrompt (const char *new_prompt)
780{
Caroline Tice5bc8c972010-09-20 20:44:43 +0000781 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +0000782}
783
Jim Ingham5e16ef52010-10-04 19:49:29 +0000784size_t
785CommandInterpreter::GetConfirmationInputReaderCallback (void *baton,
786 InputReader &reader,
787 lldb::InputReaderAction action,
788 const char *bytes,
789 size_t bytes_len)
790{
791 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle();
792 bool *response_ptr = (bool *) baton;
793
794 switch (action)
795 {
796 case eInputReaderActivate:
797 if (out_fh)
798 {
799 if (reader.GetPrompt())
800 ::fprintf (out_fh, "%s", reader.GetPrompt());
801 }
802 break;
803
804 case eInputReaderDeactivate:
805 break;
806
807 case eInputReaderReactivate:
808 if (out_fh && reader.GetPrompt())
809 ::fprintf (out_fh, "%s", reader.GetPrompt());
810 break;
811
812 case eInputReaderGotToken:
813 if (bytes_len == 0)
814 {
815 reader.SetIsDone(true);
816 }
817 else if (bytes[0] == 'y')
818 {
819 *response_ptr = true;
820 reader.SetIsDone(true);
821 }
822 else if (bytes[0] == 'n')
823 {
824 *response_ptr = false;
825 reader.SetIsDone(true);
826 }
827 else
828 {
829 if (out_fh && !reader.IsDone() && reader.GetPrompt())
830 {
831 ::fprintf (out_fh, "Please answer \"y\" or \"n\"\n");
832 ::fprintf (out_fh, "%s", reader.GetPrompt());
833 }
834 }
835 break;
836
837 case eInputReaderDone:
838 break;
839 }
840
841 return bytes_len;
842
843}
844
845bool
846CommandInterpreter::Confirm (const char *message, bool default_answer)
847{
Jim Ingham93057472010-10-04 22:44:14 +0000848 // Check AutoConfirm first:
849 if (m_debugger.GetAutoConfirm())
850 return default_answer;
851
Jim Ingham5e16ef52010-10-04 19:49:29 +0000852 InputReaderSP reader_sp (new InputReader(GetDebugger()));
853 bool response = default_answer;
854 if (reader_sp)
855 {
856 std::string prompt(message);
857 prompt.append(": [");
858 if (default_answer)
859 prompt.append ("Y/n] ");
860 else
861 prompt.append ("y/N] ");
862
863 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
864 &response, // baton
865 eInputReaderGranularityLine, // token size, to pass to callback function
866 NULL, // end token
867 prompt.c_str(), // prompt
868 true)); // echo input
869 if (err.Success())
870 {
871 GetDebugger().PushInputReader (reader_sp);
872 }
873 reader_sp->WaitOnReaderIsDone();
874 }
875 return response;
876}
877
878
Chris Lattner24943d22010-06-08 16:52:24 +0000879void
880CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
881{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000882 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +0000883
884 if (cmd_obj_sp != NULL)
885 {
886 CommandObject *cmd_obj = cmd_obj_sp.get();
887 if (cmd_obj->IsCrossRefObject ())
888 cmd_obj->AddObject (object_type);
889 }
890}
891
Chris Lattner24943d22010-06-08 16:52:24 +0000892OptionArgVectorSP
893CommandInterpreter::GetAliasOptions (const char *alias_name)
894{
895 OptionArgMap::iterator pos;
896 OptionArgVectorSP ret_val;
897
898 std::string alias (alias_name);
899
900 if (HasAliasOptions())
901 {
902 pos = m_alias_options.find (alias);
903 if (pos != m_alias_options.end())
904 ret_val = pos->second;
905 }
906
907 return ret_val;
908}
909
910void
911CommandInterpreter::RemoveAliasOptions (const char *alias_name)
912{
913 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
914 if (pos != m_alias_options.end())
915 {
916 m_alias_options.erase (pos);
917 }
918}
919
920void
921CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
922{
923 m_alias_options[alias_name] = option_arg_vector_sp;
924}
925
926bool
927CommandInterpreter::HasCommands ()
928{
929 return (!m_command_dict.empty());
930}
931
932bool
933CommandInterpreter::HasAliases ()
934{
935 return (!m_alias_dict.empty());
936}
937
938bool
939CommandInterpreter::HasUserCommands ()
940{
941 return (!m_user_dict.empty());
942}
943
944bool
945CommandInterpreter::HasAliasOptions ()
946{
947 return (!m_alias_options.empty());
948}
949
Chris Lattner24943d22010-06-08 16:52:24 +0000950void
Caroline Ticebd5c63e2010-10-12 21:57:09 +0000951CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
952 const char *alias_name,
953 Args &cmd_args,
954 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +0000955{
956 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
957
958 if (option_arg_vector_sp.get())
959 {
960 // Make sure that the alias name is the 0th element in cmd_args
961 std::string alias_name_str = alias_name;
962 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
963 cmd_args.Unshift (alias_name);
964
965 Args new_args (alias_cmd_obj->GetCommandName());
966 if (new_args.GetArgumentCount() == 2)
967 new_args.Shift();
968
969 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
970 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +0000971 std::vector<bool> used (old_size + 1, false);
972
973 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000974
975 for (int i = 0; i < option_arg_vector->size(); ++i)
976 {
977 OptionArgPair option_pair = (*option_arg_vector)[i];
978 std::string option = option_pair.first;
979 std::string value = option_pair.second;
980 if (option.compare ("<argument>") == 0)
981 new_args.AppendArgument (value.c_str());
982 else
983 {
984 new_args.AppendArgument (option.c_str());
985 if (value.compare ("<no-argument>") != 0)
986 {
987 int index = GetOptionArgumentPosition (value.c_str());
988 if (index == 0)
989 // value was NOT a positional argument; must be a real value
990 new_args.AppendArgument (value.c_str());
991 else if (index >= cmd_args.GetArgumentCount())
992 {
993 result.AppendErrorWithFormat
994 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
995 index);
996 result.SetStatus (eReturnStatusFailed);
997 return;
998 }
999 else
1000 {
1001 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001002 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001003 }
1004 }
1005 }
1006 }
1007
1008 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1009 {
1010 if (!used[j])
1011 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1012 }
1013
1014 cmd_args.Clear();
1015 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1016 }
1017 else
1018 {
1019 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1020 // This alias was not created with any options; nothing further needs to be done.
1021 return;
1022 }
1023
1024 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1025 return;
1026}
1027
1028
1029int
1030CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1031{
1032 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1033 // of zero.
1034
1035 char *cptr = (char *) in_string;
1036
1037 // Does it start with '%'
1038 if (cptr[0] == '%')
1039 {
1040 ++cptr;
1041
1042 // Is the rest of it entirely digits?
1043 if (isdigit (cptr[0]))
1044 {
1045 const char *start = cptr;
1046 while (isdigit (cptr[0]))
1047 ++cptr;
1048
1049 // We've gotten to the end of the digits; are we at the end of the string?
1050 if (cptr[0] == '\0')
1051 position = atoi (start);
1052 }
1053 }
1054
1055 return position;
1056}
1057
1058void
1059CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1060{
Greg Clayton887aa282010-10-11 01:05:37 +00001061 // Don't parse any .lldbinit files if we were asked not to
1062 if (m_skip_lldbinit_files)
1063 return;
1064
Chris Lattner24943d22010-06-08 16:52:24 +00001065 const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit";
1066 FileSpec init_file (init_file_path);
1067 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
1068 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
1069
1070 if (init_file.Exists())
1071 {
1072 char path[PATH_MAX];
1073 init_file.GetPath(path, sizeof(path));
1074 StreamString source_command;
Johnny Chen7c984242010-07-28 21:16:11 +00001075 source_command.Printf ("command source '%s'", path);
Chris Lattner24943d22010-06-08 16:52:24 +00001076 HandleCommand (source_command.GetData(), false, result);
1077 }
1078 else
1079 {
1080 // nothing to be done if the file doesn't exist
1081 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1082 }
1083}
1084
1085ScriptInterpreter *
1086CommandInterpreter::GetScriptInterpreter ()
1087{
Greg Clayton63094e02010-06-23 01:19:29 +00001088 CommandObject::CommandMap::iterator pos;
1089
1090 pos = m_command_dict.find ("script");
1091 if (pos != m_command_dict.end())
Chris Lattner24943d22010-06-08 16:52:24 +00001092 {
Greg Clayton63094e02010-06-23 01:19:29 +00001093 CommandObject *script_cmd_obj = pos->second.get();
Greg Clayton238c0a12010-09-18 01:14:36 +00001094 return ((CommandObjectScript *) script_cmd_obj)->GetInterpreter ();
Chris Lattner24943d22010-06-08 16:52:24 +00001095 }
Greg Clayton63094e02010-06-23 01:19:29 +00001096 return NULL;
Chris Lattner24943d22010-06-08 16:52:24 +00001097}
1098
1099
1100
1101bool
1102CommandInterpreter::GetSynchronous ()
1103{
1104 return m_synchronous_execution;
1105}
1106
1107void
1108CommandInterpreter::SetSynchronous (bool value)
1109{
1110 static bool value_set_once = false;
1111 if (!value_set_once)
1112 {
1113 value_set_once = true;
1114 m_synchronous_execution = value;
1115 }
1116}
1117
1118void
1119CommandInterpreter::OutputFormattedHelpText (Stream &strm,
1120 const char *word_text,
1121 const char *separator,
1122 const char *help_text,
1123 uint32_t max_word_len)
1124{
Greg Clayton238c0a12010-09-18 01:14:36 +00001125 const uint32_t max_columns = m_debugger.GetTerminalWidth();
1126
Chris Lattner24943d22010-06-08 16:52:24 +00001127 int indent_size = max_word_len + strlen (separator) + 2;
1128
1129 strm.IndentMore (indent_size);
1130
1131 int len = indent_size + strlen (help_text) + 1;
1132 char *text = (char *) malloc (len);
1133 sprintf (text, "%-*s %s %s", max_word_len, word_text, separator, help_text);
1134 if (text[len - 1] == '\n')
1135 text[--len] = '\0';
1136
1137 if (len < max_columns)
1138 {
1139 // Output it as a single line.
1140 strm.Printf ("%s", text);
1141 }
1142 else
1143 {
1144 // We need to break it up into multiple lines.
1145 bool first_line = true;
1146 int text_width;
1147 int start = 0;
1148 int end = start;
1149 int final_end = strlen (text);
1150 int sub_len;
1151
1152 while (end < final_end)
1153 {
1154 if (first_line)
1155 text_width = max_columns - 1;
1156 else
1157 text_width = max_columns - indent_size - 1;
1158
1159 // Don't start the 'text' on a space, since we're already outputting the indentation.
1160 if (!first_line)
1161 {
1162 while ((start < final_end) && (text[start] == ' '))
1163 start++;
1164 }
1165
1166 end = start + text_width;
1167 if (end > final_end)
1168 end = final_end;
1169 else
1170 {
1171 // If we're not at the end of the text, make sure we break the line on white space.
1172 while (end > start
1173 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
1174 end--;
1175 }
1176
1177 sub_len = end - start;
1178 if (start != 0)
1179 strm.EOL();
1180 if (!first_line)
1181 strm.Indent();
1182 else
1183 first_line = false;
1184 assert (start <= final_end);
1185 assert (start + sub_len <= final_end);
1186 if (sub_len > 0)
1187 strm.Write (text + start, sub_len);
1188 start = end + 1;
1189 }
1190 }
1191 strm.EOL();
1192 strm.IndentLess(indent_size);
1193 free (text);
1194}
1195
1196void
1197CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
1198 StringList &commands_found, StringList &commands_help)
1199{
1200 CommandObject::CommandMap::const_iterator pos;
1201 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
1202 CommandObject *sub_cmd_obj;
1203
1204 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
1205 {
1206 const char * command_name = pos->first.c_str();
1207 sub_cmd_obj = pos->second.get();
1208 StreamString complete_command_name;
1209
1210 complete_command_name.Printf ("%s %s", prefix, command_name);
1211
Greg Clayton238c0a12010-09-18 01:14:36 +00001212 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001213 {
1214 commands_found.AppendString (complete_command_name.GetData());
1215 commands_help.AppendString (sub_cmd_obj->GetHelp());
1216 }
1217
1218 if (sub_cmd_obj->IsMultiwordObject())
1219 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
1220 commands_help);
1221 }
1222
1223}
1224
1225void
1226CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
1227 StringList &commands_help)
1228{
1229 CommandObject::CommandMap::const_iterator pos;
1230
1231 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1232 {
1233 const char *command_name = pos->first.c_str();
1234 CommandObject *cmd_obj = pos->second.get();
1235
Greg Clayton238c0a12010-09-18 01:14:36 +00001236 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001237 {
1238 commands_found.AppendString (command_name);
1239 commands_help.AppendString (cmd_obj->GetHelp());
1240 }
1241
1242 if (cmd_obj->IsMultiwordObject())
1243 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
1244
1245 }
1246}