blob: 64bdfcd5b80ec32d3da897cd2eaeae6a51c668f1 [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>
11
12#include <getopt.h>
13#include <stdlib.h>
14
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000015#include "../Commands/CommandObjectApropos.h"
16#include "../Commands/CommandObjectArgs.h"
17#include "../Commands/CommandObjectBreakpoint.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000018//#include "../Commands/CommandObjectCall.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000019#include "../Commands/CommandObjectDisassemble.h"
20#include "../Commands/CommandObjectExpression.h"
21#include "../Commands/CommandObjectFile.h"
22#include "../Commands/CommandObjectFrame.h"
23#include "../Commands/CommandObjectHelp.h"
24#include "../Commands/CommandObjectImage.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000025#include "../Commands/CommandObjectLog.h"
26#include "../Commands/CommandObjectMemory.h"
27#include "../Commands/CommandObjectProcess.h"
28#include "../Commands/CommandObjectQuit.h"
Eli Friedmanb34d2a22010-06-09 22:08:29 +000029#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000030#include "../Commands/CommandObjectRegister.h"
Chris Lattner24943d22010-06-08 16:52:24 +000031#include "CommandObjectScript.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000032#include "../Commands/CommandObjectSettings.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000033#include "../Commands/CommandObjectSource.h"
Jim Ingham767af882010-07-07 03:36:20 +000034#include "../Commands/CommandObjectCommands.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000035#include "../Commands/CommandObjectSyntax.h"
36#include "../Commands/CommandObjectTarget.h"
37#include "../Commands/CommandObjectThread.h"
Chris Lattner24943d22010-06-08 16:52:24 +000038
Jim Ingham84cdc152010-06-15 19:49:27 +000039#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000040#include "lldb/Core/Debugger.h"
Jim Ingham5e16ef52010-10-04 19:49:29 +000041#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000042#include "lldb/Core/Stream.h"
43#include "lldb/Core/Timer.h"
44#include "lldb/Target/Process.h"
45#include "lldb/Target/Thread.h"
46#include "lldb/Target/TargetList.h"
47
48#include "lldb/Interpreter/CommandReturnObject.h"
49#include "lldb/Interpreter/CommandInterpreter.h"
50
51using namespace lldb;
52using namespace lldb_private;
53
54CommandInterpreter::CommandInterpreter
55(
Greg Clayton63094e02010-06-23 01:19:29 +000056 Debugger &debugger,
Chris Lattner24943d22010-06-08 16:52:24 +000057 ScriptLanguage script_language,
Greg Clayton63094e02010-06-23 01:19:29 +000058 bool synchronous_execution
Chris Lattner24943d22010-06-08 16:52:24 +000059) :
60 Broadcaster ("CommandInterpreter"),
Greg Clayton63094e02010-06-23 01:19:29 +000061 m_debugger (debugger),
Greg Clayton887aa282010-10-11 01:05:37 +000062 m_synchronous_execution (synchronous_execution),
63 m_skip_lldbinit_files (false)
Chris Lattner24943d22010-06-08 16:52:24 +000064{
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000065 const char *dbg_name = debugger.GetInstanceName().AsCString();
66 std::string lang_name = ScriptInterpreter::LanguageToString (script_language);
67 StreamString var_name;
68 var_name.Printf ("[%s].script-lang", dbg_name);
Caroline Tice1d2aefd2010-09-09 06:25:08 +000069 debugger.GetSettingsController()->SetVariable (var_name.GetData(), lang_name.c_str(),
70 lldb::eVarSetOperationAssign, false,
71 m_debugger.GetInstanceName().AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +000072}
73
74void
75CommandInterpreter::Initialize ()
76{
77 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
78
79 CommandReturnObject result;
80
81 LoadCommandDictionary ();
82
Chris Lattner24943d22010-06-08 16:52:24 +000083 // Set up some initial aliases.
Jim Ingham767af882010-07-07 03:36:20 +000084 result.Clear(); HandleCommand ("command alias q quit", false, result);
85 result.Clear(); HandleCommand ("command alias run process launch", false, result);
86 result.Clear(); HandleCommand ("command alias r process launch", false, result);
87 result.Clear(); HandleCommand ("command alias c process continue", false, result);
88 result.Clear(); HandleCommand ("command alias continue process continue", false, result);
89 result.Clear(); HandleCommand ("command alias expr expression", false, result);
90 result.Clear(); HandleCommand ("command alias exit quit", false, result);
Greg Clayton0f3a8eb2010-09-16 17:09:23 +000091 result.Clear(); HandleCommand ("command alias b regexp-break", false, result);
Jim Ingham767af882010-07-07 03:36:20 +000092 result.Clear(); HandleCommand ("command alias bt thread backtrace", false, result);
93 result.Clear(); HandleCommand ("command alias si thread step-inst", false, result);
94 result.Clear(); HandleCommand ("command alias step thread step-in", false, result);
95 result.Clear(); HandleCommand ("command alias s thread step-in", false, result);
96 result.Clear(); HandleCommand ("command alias next thread step-over", false, result);
97 result.Clear(); HandleCommand ("command alias n thread step-over", false, result);
98 result.Clear(); HandleCommand ("command alias finish thread step-out", false, result);
99 result.Clear(); HandleCommand ("command alias x memory read", false, result);
100 result.Clear(); HandleCommand ("command alias l source list", false, result);
101 result.Clear(); HandleCommand ("command alias list source list", false, result);
Greg Clayton0f3a8eb2010-09-16 17:09:23 +0000102 result.Clear(); HandleCommand ("command alias p frame variable", false, result);
103 result.Clear(); HandleCommand ("command alias print frame variable", false, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000104}
105
Chris Lattner24943d22010-06-08 16:52:24 +0000106const char *
107CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
108{
109 // This function has not yet been implemented.
110
111 // Look for any embedded script command
112 // If found,
113 // get interpreter object from the command dictionary,
114 // call execute_one_command on it,
115 // get the results as a string,
116 // substitute that string for current stuff.
117
118 return arg;
119}
120
121
122void
123CommandInterpreter::LoadCommandDictionary ()
124{
125 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
126
127 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
128 //
129 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
130 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
131 // the cross-referencing stuff) are created!!!
132 //
133 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
134
135
136 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
137 // are created. This is so that when another command is created that needs to go into a crossref object,
138 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
139 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
140
Chris Lattner24943d22010-06-08 16:52:24 +0000141 // Non-CommandObjectCrossref commands can now be created.
142
Caroline Tice5bc8c972010-09-20 20:44:43 +0000143 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000144
Greg Clayton238c0a12010-09-18 01:14:36 +0000145 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000146 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000147 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000148 m_command_dict["commands"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000149 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
150 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
151 m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000152 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000153 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000154 m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
155 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
156 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
157 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000158 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000159 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000160 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000161 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000162 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000163 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
164 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000165
166 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000167 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
168 "regexp-break",
Caroline Ticec1ad82e2010-09-07 22:38:08 +0000169 "Set a breakpoint using a regular expression to specify the location.",
Caroline Tice43b014a2010-10-04 22:28:36 +0000170 "regexp-break [<filename>:<linenum>]\nregexp-break [<address>]\nregexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000171 if (break_regex_cmd_ap.get())
172 {
173 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
174 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
175 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
176 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list") &&
177 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
178 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
179 {
180 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
181 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
182 }
183 }
184}
185
186int
187CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
188 StringList &matches)
189{
190 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
191
192 if (include_aliases)
193 {
194 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
195 }
196
197 return matches.GetSize();
198}
199
200CommandObjectSP
201CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
202{
203 CommandObject::CommandMap::iterator pos;
204 CommandObjectSP ret_val;
205
206 std::string cmd(cmd_cstr);
207
208 if (HasCommands())
209 {
210 pos = m_command_dict.find(cmd);
211 if (pos != m_command_dict.end())
212 ret_val = pos->second;
213 }
214
215 if (include_aliases && HasAliases())
216 {
217 pos = m_alias_dict.find(cmd);
218 if (pos != m_alias_dict.end())
219 ret_val = pos->second;
220 }
221
222 if (HasUserCommands())
223 {
224 pos = m_user_dict.find(cmd);
225 if (pos != m_user_dict.end())
226 ret_val = pos->second;
227 }
228
229 if (!exact && ret_val == NULL)
230 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000231 // We will only get into here if we didn't find any exact matches.
232
233 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
234
Chris Lattner24943d22010-06-08 16:52:24 +0000235 StringList local_matches;
236 if (matches == NULL)
237 matches = &local_matches;
238
Jim Inghamd40f8a62010-07-06 22:46:59 +0000239 unsigned int num_cmd_matches = 0;
240 unsigned int num_alias_matches = 0;
241 unsigned int num_user_matches = 0;
242
243 // Look through the command dictionaries one by one, and if we get only one match from any of
244 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
245
Chris Lattner24943d22010-06-08 16:52:24 +0000246 if (HasCommands())
247 {
248 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
249 }
250
251 if (num_cmd_matches == 1)
252 {
253 cmd.assign(matches->GetStringAtIndex(0));
254 pos = m_command_dict.find(cmd);
255 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000256 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000257 }
258
Jim Ingham9a574172010-06-24 20:28:42 +0000259 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000260 {
261 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
262
263 }
264
Jim Inghamd40f8a62010-07-06 22:46:59 +0000265 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000266 {
267 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
268 pos = m_alias_dict.find(cmd);
269 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000270 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000271 }
272
Jim Ingham9a574172010-06-24 20:28:42 +0000273 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000274 {
275 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
276 }
277
Jim Inghamd40f8a62010-07-06 22:46:59 +0000278 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000279 {
280 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
281
282 pos = m_user_dict.find (cmd);
283 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000284 user_match_sp = pos->second;
285 }
286
287 // If we got exactly one match, return that, otherwise return the match list.
288
289 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
290 {
291 if (num_cmd_matches)
292 return real_match_sp;
293 else if (num_alias_matches)
294 return alias_match_sp;
295 else
296 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000297 }
298 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000299 else if (matches && ret_val != NULL)
300 {
301 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000302 }
303
304
305 return ret_val;
306}
307
Jim Inghamd40f8a62010-07-06 22:46:59 +0000308CommandObjectSP
309CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000310{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000311 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
312}
313
314CommandObject *
315CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
316{
317 return GetCommandSPExact (cmd_cstr, include_aliases).get();
318}
319
320CommandObject *
321CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
322{
323 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
324
325 // If we didn't find an exact match to the command string in the commands, look in
326 // the aliases.
327
328 if (command_obj == NULL)
329 {
330 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
331 }
332
333 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
334 // in both the commands and the aliases.
335
336 if (command_obj == NULL)
337 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
338
339 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000340}
341
342bool
343CommandInterpreter::CommandExists (const char *cmd)
344{
345 return m_command_dict.find(cmd) != m_command_dict.end();
346}
347
348bool
349CommandInterpreter::AliasExists (const char *cmd)
350{
351 return m_alias_dict.find(cmd) != m_alias_dict.end();
352}
353
354bool
355CommandInterpreter::UserCommandExists (const char *cmd)
356{
357 return m_user_dict.find(cmd) != m_user_dict.end();
358}
359
360void
361CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
362{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000363 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000364 m_alias_dict[alias_name] = command_obj_sp;
365}
366
367bool
368CommandInterpreter::RemoveAlias (const char *alias_name)
369{
370 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
371 if (pos != m_alias_dict.end())
372 {
373 m_alias_dict.erase(pos);
374 return true;
375 }
376 return false;
377}
378bool
379CommandInterpreter::RemoveUser (const char *alias_name)
380{
381 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
382 if (pos != m_user_dict.end())
383 {
384 m_user_dict.erase(pos);
385 return true;
386 }
387 return false;
388}
389
Chris Lattner24943d22010-06-08 16:52:24 +0000390void
391CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
392{
393 help_string.Printf ("'%s", command_name);
394 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
395
396 if (option_arg_vector_sp != NULL)
397 {
398 OptionArgVector *options = option_arg_vector_sp.get();
399 for (int i = 0; i < options->size(); ++i)
400 {
401 OptionArgPair cur_option = (*options)[i];
402 std::string opt = cur_option.first;
403 std::string value = cur_option.second;
404 if (opt.compare("<argument>") == 0)
405 {
406 help_string.Printf (" %s", value.c_str());
407 }
408 else
409 {
410 help_string.Printf (" %s", opt.c_str());
411 if ((value.compare ("<no-argument>") != 0)
412 && (value.compare ("<need-argument") != 0))
413 {
414 help_string.Printf (" %s", value.c_str());
415 }
416 }
417 }
418 }
419
420 help_string.Printf ("'");
421}
422
Greg Clayton65124ea2010-08-26 22:05:43 +0000423size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000424CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
425{
426 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000427 CommandObject::CommandMap::const_iterator end = dict.end();
428 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000429
Greg Clayton65124ea2010-08-26 22:05:43 +0000430 for (pos = dict.begin(); pos != end; ++pos)
431 {
432 size_t len = pos->first.size();
433 if (max_len < len)
434 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000435 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000436 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000437}
438
439void
440CommandInterpreter::GetHelp (CommandReturnObject &result)
441{
442 CommandObject::CommandMap::const_iterator pos;
443 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
444 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000445 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000446
447 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
448 {
449 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
450 max_len);
451 }
452 result.AppendMessage("");
453
454 if (m_alias_dict.size() > 0)
455 {
Caroline Tice00edd3a2010-09-13 05:27:16 +0000456 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 +0000457 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000458 max_len = FindLongestCommandWord (m_alias_dict);
459
Chris Lattner24943d22010-06-08 16:52:24 +0000460 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
461 {
462 StreamString sstr;
463 StreamString translation_and_help;
464 std::string entry_name = pos->first;
465 std::string second_entry = pos->second.get()->GetCommandName();
466 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
467
468 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
469 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
470 translation_and_help.GetData(), max_len);
471 }
472 result.AppendMessage("");
473 }
474
475 if (m_user_dict.size() > 0)
476 {
477 result.AppendMessage ("The following is a list of your current user-defined commands:");
478 result.AppendMessage("");
479 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
480 {
481 result.AppendMessageWithFormat ("%s -- %s\n", pos->first.c_str(), pos->second->GetHelp());
482 }
483 result.AppendMessage("");
484 }
485
486 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
487}
488
Chris Lattner24943d22010-06-08 16:52:24 +0000489bool
Greg Clayton63094e02010-06-23 01:19:29 +0000490CommandInterpreter::HandleCommand
491(
492 const char *command_line,
493 bool add_to_history,
494 CommandReturnObject &result,
495 ExecutionContext *override_context
496)
Chris Lattner24943d22010-06-08 16:52:24 +0000497{
498 // FIXME: there should probably be a mutex to make sure only one thread can
499 // run the interpreter at a time.
500
501 // TODO: this should be a logging channel in lldb.
502// if (DebugSelf())
503// {
504// result.AppendMessageWithFormat ("Processing command: %s\n", command_line);
505// }
506
Greg Clayton63094e02010-06-23 01:19:29 +0000507 m_debugger.UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +0000508
509 if (command_line == NULL || command_line[0] == '\0')
510 {
511 if (m_command_history.empty())
512 {
513 result.AppendError ("empty command");
514 result.SetStatus(eReturnStatusFailed);
515 return false;
516 }
517 else
518 {
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000519 command_line = m_repeat_command.c_str();
520 if (m_repeat_command.empty())
521 {
Jim Ingham767af882010-07-07 03:36:20 +0000522 result.AppendErrorWithFormat("No auto repeat.\n");
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000523 result.SetStatus (eReturnStatusFailed);
524 return false;
525 }
Chris Lattner24943d22010-06-08 16:52:24 +0000526 }
527 add_to_history = false;
528 }
529
530 Args command_args(command_line);
531
532 if (command_args.GetArgumentCount() > 0)
533 {
534 const char *command_cstr = command_args.GetArgumentAtIndex(0);
535 if (command_cstr)
536 {
537
538 // We're looking up the command object here. So first find an exact match to the
539 // command in the commands.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000540 CommandObject *command_obj = GetCommandObject(command_cstr);
541
542 if (command_obj != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000543 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000544 if (command_obj->IsAlias())
Chris Lattner24943d22010-06-08 16:52:24 +0000545 {
546 BuildAliasCommandArgs (command_obj, command_cstr, command_args, result);
547 if (!result.Succeeded())
548 return false;
549 }
Chris Lattner24943d22010-06-08 16:52:24 +0000550
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000551 if (add_to_history)
552 {
Jim Ingham767af882010-07-07 03:36:20 +0000553 const char *repeat_command = command_obj->GetRepeatCommand(command_args, 0);
554 if (repeat_command != NULL)
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000555 m_repeat_command.assign(repeat_command);
556 else
Jim Ingham767af882010-07-07 03:36:20 +0000557 m_repeat_command.assign(command_line);
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000558
559 m_command_history.push_back (command_line);
560 }
561
562
Chris Lattner24943d22010-06-08 16:52:24 +0000563 if (command_obj->WantsRawCommandString())
564 {
565 const char *stripped_command = ::strstr (command_line, command_cstr);
566 if (stripped_command)
567 {
568 stripped_command += strlen(command_cstr);
569 while (isspace(*stripped_command))
570 ++stripped_command;
Greg Clayton238c0a12010-09-18 01:14:36 +0000571 command_obj->ExecuteRawCommandString (stripped_command, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000572 }
573 }
574 else
575 {
Chris Lattner24943d22010-06-08 16:52:24 +0000576 // Remove the command from the args.
577 command_args.Shift();
Greg Clayton238c0a12010-09-18 01:14:36 +0000578 command_obj->ExecuteWithOptions (command_args, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000579 }
580 }
581 else
582 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000583 // We didn't find the first command object, so complete the first argument.
Chris Lattner24943d22010-06-08 16:52:24 +0000584 StringList matches;
585 int num_matches;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000586 int cursor_index = 0;
587 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
Jim Ingham802f8b02010-06-30 05:02:46 +0000588 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +0000589 num_matches = HandleCompletionMatches (command_args,
590 cursor_index,
591 cursor_char_position,
592 0,
593 -1,
Jim Ingham802f8b02010-06-30 05:02:46 +0000594 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +0000595 matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000596
597 if (num_matches > 0)
598 {
599 std::string error_msg;
600 error_msg.assign ("ambiguous command '");
601 error_msg.append(command_cstr);
602 error_msg.append ("'.");
603
604 error_msg.append (" Possible completions:");
605 for (int i = 0; i < num_matches; i++)
606 {
607 error_msg.append ("\n\t");
608 error_msg.append (matches.GetStringAtIndex (i));
609 }
610 error_msg.append ("\n");
611 result.AppendRawError (error_msg.c_str(), error_msg.size());
612 }
613 else
614 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_cstr);
615
616 result.SetStatus (eReturnStatusFailed);
617 }
618 }
619 }
620 return result.Succeeded();
621}
622
623int
624CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
625 int &cursor_index,
626 int &cursor_char_position,
627 int match_start_point,
628 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +0000629 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000630 StringList &matches)
631{
632 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000633 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +0000634
635 // For any of the command completions a unique match will be a complete word.
636 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000637
638 if (cursor_index == -1)
639 {
640 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +0000641 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000642 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
643 }
644 else if (cursor_index == 0)
645 {
646 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000647 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000648 num_command_matches = matches.GetSize();
649
650 if (num_command_matches == 1
651 && cmd_obj && cmd_obj->IsMultiwordObject()
652 && matches.GetStringAtIndex(0) != NULL
653 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
654 {
655 look_for_subcommand = true;
656 num_command_matches = 0;
657 matches.DeleteStringAtIndex(0);
658 parsed_line.AppendArgument ("");
659 cursor_index++;
660 cursor_char_position = 0;
661 }
662 }
663
664 if (cursor_index > 0 || look_for_subcommand)
665 {
666 // We are completing further on into a commands arguments, so find the command and tell it
667 // to complete the command.
668 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +0000669 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +0000670 if (command_object == NULL)
671 {
672 return 0;
673 }
674 else
675 {
676 parsed_line.Shift();
677 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +0000678 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +0000679 cursor_index,
680 cursor_char_position,
681 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000682 max_return_elements,
683 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000684 matches);
685 }
686 }
687
688 return num_command_matches;
689
690}
691
692int
693CommandInterpreter::HandleCompletion (const char *current_line,
694 const char *cursor,
695 const char *last_char,
696 int match_start_point,
697 int max_return_elements,
698 StringList &matches)
699{
700 // We parse the argument up to the cursor, so the last argument in parsed_line is
701 // the one containing the cursor, and the cursor is after the last character.
702
703 Args parsed_line(current_line, last_char - current_line);
704 Args partial_parsed_line(current_line, cursor - current_line);
705
706 int num_args = partial_parsed_line.GetArgumentCount();
707 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
708 int cursor_char_position;
709
710 if (cursor_index == -1)
711 cursor_char_position = 0;
712 else
713 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
714
715 int num_command_matches;
716
717 matches.Clear();
718
719 // Only max_return_elements == -1 is supported at present:
720 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +0000721 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +0000722 num_command_matches = HandleCompletionMatches (parsed_line,
723 cursor_index,
724 cursor_char_position,
725 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000726 max_return_elements,
727 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +0000728 matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000729
730 if (num_command_matches <= 0)
731 return num_command_matches;
732
733 if (num_args == 0)
734 {
735 // If we got an empty string, insert nothing.
736 matches.InsertStringAtIndex(0, "");
737 }
738 else
739 {
740 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
741 // put an empty string in element 0.
742 std::string command_partial_str;
743 if (cursor_index >= 0)
744 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index), parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
745
746 std::string common_prefix;
747 matches.LongestCommonPrefix (common_prefix);
748 int partial_name_len = command_partial_str.size();
749
750 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +0000751 // Only do this if the completer told us this was a complete word, however...
752 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +0000753 {
754 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
755 if (quote_char != '\0')
756 common_prefix.push_back(quote_char);
757
758 common_prefix.push_back(' ');
759 }
760 common_prefix.erase (0, partial_name_len);
761 matches.InsertStringAtIndex(0, common_prefix.c_str());
762 }
763 return num_command_matches;
764}
765
Chris Lattner24943d22010-06-08 16:52:24 +0000766
767CommandInterpreter::~CommandInterpreter ()
768{
769}
770
771const char *
772CommandInterpreter::GetPrompt ()
773{
Caroline Tice5bc8c972010-09-20 20:44:43 +0000774 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +0000775}
776
777void
778CommandInterpreter::SetPrompt (const char *new_prompt)
779{
Caroline Tice5bc8c972010-09-20 20:44:43 +0000780 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +0000781}
782
Jim Ingham5e16ef52010-10-04 19:49:29 +0000783size_t
784CommandInterpreter::GetConfirmationInputReaderCallback (void *baton,
785 InputReader &reader,
786 lldb::InputReaderAction action,
787 const char *bytes,
788 size_t bytes_len)
789{
790 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle();
791 bool *response_ptr = (bool *) baton;
792
793 switch (action)
794 {
795 case eInputReaderActivate:
796 if (out_fh)
797 {
798 if (reader.GetPrompt())
799 ::fprintf (out_fh, "%s", reader.GetPrompt());
800 }
801 break;
802
803 case eInputReaderDeactivate:
804 break;
805
806 case eInputReaderReactivate:
807 if (out_fh && reader.GetPrompt())
808 ::fprintf (out_fh, "%s", reader.GetPrompt());
809 break;
810
811 case eInputReaderGotToken:
812 if (bytes_len == 0)
813 {
814 reader.SetIsDone(true);
815 }
816 else if (bytes[0] == 'y')
817 {
818 *response_ptr = true;
819 reader.SetIsDone(true);
820 }
821 else if (bytes[0] == 'n')
822 {
823 *response_ptr = false;
824 reader.SetIsDone(true);
825 }
826 else
827 {
828 if (out_fh && !reader.IsDone() && reader.GetPrompt())
829 {
830 ::fprintf (out_fh, "Please answer \"y\" or \"n\"\n");
831 ::fprintf (out_fh, "%s", reader.GetPrompt());
832 }
833 }
834 break;
835
836 case eInputReaderDone:
837 break;
838 }
839
840 return bytes_len;
841
842}
843
844bool
845CommandInterpreter::Confirm (const char *message, bool default_answer)
846{
Jim Ingham93057472010-10-04 22:44:14 +0000847 // Check AutoConfirm first:
848 if (m_debugger.GetAutoConfirm())
849 return default_answer;
850
Jim Ingham5e16ef52010-10-04 19:49:29 +0000851 InputReaderSP reader_sp (new InputReader(GetDebugger()));
852 bool response = default_answer;
853 if (reader_sp)
854 {
855 std::string prompt(message);
856 prompt.append(": [");
857 if (default_answer)
858 prompt.append ("Y/n] ");
859 else
860 prompt.append ("y/N] ");
861
862 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
863 &response, // baton
864 eInputReaderGranularityLine, // token size, to pass to callback function
865 NULL, // end token
866 prompt.c_str(), // prompt
867 true)); // echo input
868 if (err.Success())
869 {
870 GetDebugger().PushInputReader (reader_sp);
871 }
872 reader_sp->WaitOnReaderIsDone();
873 }
874 return response;
875}
876
877
Chris Lattner24943d22010-06-08 16:52:24 +0000878void
879CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
880{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000881 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +0000882
883 if (cmd_obj_sp != NULL)
884 {
885 CommandObject *cmd_obj = cmd_obj_sp.get();
886 if (cmd_obj->IsCrossRefObject ())
887 cmd_obj->AddObject (object_type);
888 }
889}
890
Chris Lattner24943d22010-06-08 16:52:24 +0000891OptionArgVectorSP
892CommandInterpreter::GetAliasOptions (const char *alias_name)
893{
894 OptionArgMap::iterator pos;
895 OptionArgVectorSP ret_val;
896
897 std::string alias (alias_name);
898
899 if (HasAliasOptions())
900 {
901 pos = m_alias_options.find (alias);
902 if (pos != m_alias_options.end())
903 ret_val = pos->second;
904 }
905
906 return ret_val;
907}
908
909void
910CommandInterpreter::RemoveAliasOptions (const char *alias_name)
911{
912 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
913 if (pos != m_alias_options.end())
914 {
915 m_alias_options.erase (pos);
916 }
917}
918
919void
920CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
921{
922 m_alias_options[alias_name] = option_arg_vector_sp;
923}
924
925bool
926CommandInterpreter::HasCommands ()
927{
928 return (!m_command_dict.empty());
929}
930
931bool
932CommandInterpreter::HasAliases ()
933{
934 return (!m_alias_dict.empty());
935}
936
937bool
938CommandInterpreter::HasUserCommands ()
939{
940 return (!m_user_dict.empty());
941}
942
943bool
944CommandInterpreter::HasAliasOptions ()
945{
946 return (!m_alias_options.empty());
947}
948
Chris Lattner24943d22010-06-08 16:52:24 +0000949void
950CommandInterpreter::BuildAliasCommandArgs
951(
952 CommandObject *alias_cmd_obj,
953 const char *alias_name,
954 Args &cmd_args,
955 CommandReturnObject &result
956)
957{
958 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
959
960 if (option_arg_vector_sp.get())
961 {
962 // Make sure that the alias name is the 0th element in cmd_args
963 std::string alias_name_str = alias_name;
964 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
965 cmd_args.Unshift (alias_name);
966
967 Args new_args (alias_cmd_obj->GetCommandName());
968 if (new_args.GetArgumentCount() == 2)
969 new_args.Shift();
970
971 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
972 int old_size = cmd_args.GetArgumentCount();
973 int *used = (int *) malloc ((old_size + 1) * sizeof (int));
974
975 memset (used, 0, (old_size + 1) * sizeof (int));
976 used[0] = 1;
977
978 for (int i = 0; i < option_arg_vector->size(); ++i)
979 {
980 OptionArgPair option_pair = (*option_arg_vector)[i];
981 std::string option = option_pair.first;
982 std::string value = option_pair.second;
983 if (option.compare ("<argument>") == 0)
984 new_args.AppendArgument (value.c_str());
985 else
986 {
987 new_args.AppendArgument (option.c_str());
988 if (value.compare ("<no-argument>") != 0)
989 {
990 int index = GetOptionArgumentPosition (value.c_str());
991 if (index == 0)
992 // value was NOT a positional argument; must be a real value
993 new_args.AppendArgument (value.c_str());
994 else if (index >= cmd_args.GetArgumentCount())
995 {
996 result.AppendErrorWithFormat
997 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
998 index);
999 result.SetStatus (eReturnStatusFailed);
1000 return;
1001 }
1002 else
1003 {
1004 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
1005 used[index] = 1;
1006 }
1007 }
1008 }
1009 }
1010
1011 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1012 {
1013 if (!used[j])
1014 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1015 }
1016
1017 cmd_args.Clear();
1018 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1019 }
1020 else
1021 {
1022 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1023 // This alias was not created with any options; nothing further needs to be done.
1024 return;
1025 }
1026
1027 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1028 return;
1029}
1030
1031
1032int
1033CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1034{
1035 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1036 // of zero.
1037
1038 char *cptr = (char *) in_string;
1039
1040 // Does it start with '%'
1041 if (cptr[0] == '%')
1042 {
1043 ++cptr;
1044
1045 // Is the rest of it entirely digits?
1046 if (isdigit (cptr[0]))
1047 {
1048 const char *start = cptr;
1049 while (isdigit (cptr[0]))
1050 ++cptr;
1051
1052 // We've gotten to the end of the digits; are we at the end of the string?
1053 if (cptr[0] == '\0')
1054 position = atoi (start);
1055 }
1056 }
1057
1058 return position;
1059}
1060
1061void
1062CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1063{
Greg Clayton887aa282010-10-11 01:05:37 +00001064 // Don't parse any .lldbinit files if we were asked not to
1065 if (m_skip_lldbinit_files)
1066 return;
1067
Chris Lattner24943d22010-06-08 16:52:24 +00001068 const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit";
1069 FileSpec init_file (init_file_path);
1070 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
1071 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
1072
1073 if (init_file.Exists())
1074 {
1075 char path[PATH_MAX];
1076 init_file.GetPath(path, sizeof(path));
1077 StreamString source_command;
Johnny Chen7c984242010-07-28 21:16:11 +00001078 source_command.Printf ("command source '%s'", path);
Chris Lattner24943d22010-06-08 16:52:24 +00001079 HandleCommand (source_command.GetData(), false, result);
1080 }
1081 else
1082 {
1083 // nothing to be done if the file doesn't exist
1084 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1085 }
1086}
1087
1088ScriptInterpreter *
1089CommandInterpreter::GetScriptInterpreter ()
1090{
Greg Clayton63094e02010-06-23 01:19:29 +00001091 CommandObject::CommandMap::iterator pos;
1092
1093 pos = m_command_dict.find ("script");
1094 if (pos != m_command_dict.end())
Chris Lattner24943d22010-06-08 16:52:24 +00001095 {
Greg Clayton63094e02010-06-23 01:19:29 +00001096 CommandObject *script_cmd_obj = pos->second.get();
Greg Clayton238c0a12010-09-18 01:14:36 +00001097 return ((CommandObjectScript *) script_cmd_obj)->GetInterpreter ();
Chris Lattner24943d22010-06-08 16:52:24 +00001098 }
Greg Clayton63094e02010-06-23 01:19:29 +00001099 return NULL;
Chris Lattner24943d22010-06-08 16:52:24 +00001100}
1101
1102
1103
1104bool
1105CommandInterpreter::GetSynchronous ()
1106{
1107 return m_synchronous_execution;
1108}
1109
1110void
1111CommandInterpreter::SetSynchronous (bool value)
1112{
1113 static bool value_set_once = false;
1114 if (!value_set_once)
1115 {
1116 value_set_once = true;
1117 m_synchronous_execution = value;
1118 }
1119}
1120
1121void
1122CommandInterpreter::OutputFormattedHelpText (Stream &strm,
1123 const char *word_text,
1124 const char *separator,
1125 const char *help_text,
1126 uint32_t max_word_len)
1127{
Greg Clayton238c0a12010-09-18 01:14:36 +00001128 const uint32_t max_columns = m_debugger.GetTerminalWidth();
1129
Chris Lattner24943d22010-06-08 16:52:24 +00001130 int indent_size = max_word_len + strlen (separator) + 2;
1131
1132 strm.IndentMore (indent_size);
1133
1134 int len = indent_size + strlen (help_text) + 1;
1135 char *text = (char *) malloc (len);
1136 sprintf (text, "%-*s %s %s", max_word_len, word_text, separator, help_text);
1137 if (text[len - 1] == '\n')
1138 text[--len] = '\0';
1139
1140 if (len < max_columns)
1141 {
1142 // Output it as a single line.
1143 strm.Printf ("%s", text);
1144 }
1145 else
1146 {
1147 // We need to break it up into multiple lines.
1148 bool first_line = true;
1149 int text_width;
1150 int start = 0;
1151 int end = start;
1152 int final_end = strlen (text);
1153 int sub_len;
1154
1155 while (end < final_end)
1156 {
1157 if (first_line)
1158 text_width = max_columns - 1;
1159 else
1160 text_width = max_columns - indent_size - 1;
1161
1162 // Don't start the 'text' on a space, since we're already outputting the indentation.
1163 if (!first_line)
1164 {
1165 while ((start < final_end) && (text[start] == ' '))
1166 start++;
1167 }
1168
1169 end = start + text_width;
1170 if (end > final_end)
1171 end = final_end;
1172 else
1173 {
1174 // If we're not at the end of the text, make sure we break the line on white space.
1175 while (end > start
1176 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
1177 end--;
1178 }
1179
1180 sub_len = end - start;
1181 if (start != 0)
1182 strm.EOL();
1183 if (!first_line)
1184 strm.Indent();
1185 else
1186 first_line = false;
1187 assert (start <= final_end);
1188 assert (start + sub_len <= final_end);
1189 if (sub_len > 0)
1190 strm.Write (text + start, sub_len);
1191 start = end + 1;
1192 }
1193 }
1194 strm.EOL();
1195 strm.IndentLess(indent_size);
1196 free (text);
1197}
1198
1199void
1200CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
1201 StringList &commands_found, StringList &commands_help)
1202{
1203 CommandObject::CommandMap::const_iterator pos;
1204 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
1205 CommandObject *sub_cmd_obj;
1206
1207 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
1208 {
1209 const char * command_name = pos->first.c_str();
1210 sub_cmd_obj = pos->second.get();
1211 StreamString complete_command_name;
1212
1213 complete_command_name.Printf ("%s %s", prefix, command_name);
1214
Greg Clayton238c0a12010-09-18 01:14:36 +00001215 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001216 {
1217 commands_found.AppendString (complete_command_name.GetData());
1218 commands_help.AppendString (sub_cmd_obj->GetHelp());
1219 }
1220
1221 if (sub_cmd_obj->IsMultiwordObject())
1222 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
1223 commands_help);
1224 }
1225
1226}
1227
1228void
1229CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
1230 StringList &commands_help)
1231{
1232 CommandObject::CommandMap::const_iterator pos;
1233
1234 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1235 {
1236 const char *command_name = pos->first.c_str();
1237 CommandObject *cmd_obj = pos->second.get();
1238
Greg Clayton238c0a12010-09-18 01:14:36 +00001239 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001240 {
1241 commands_found.AppendString (command_name);
1242 commands_help.AppendString (cmd_obj->GetHelp());
1243 }
1244
1245 if (cmd_obj->IsMultiwordObject())
1246 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
1247
1248 }
1249}