blob: a3c2921eefe510604322cf5990c09c16acf1c2b7 [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 Clayton63094e02010-06-23 01:19:29 +000062 m_synchronous_execution (synchronous_execution)
Chris Lattner24943d22010-06-08 16:52:24 +000063{
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000064 const char *dbg_name = debugger.GetInstanceName().AsCString();
65 std::string lang_name = ScriptInterpreter::LanguageToString (script_language);
66 StreamString var_name;
67 var_name.Printf ("[%s].script-lang", dbg_name);
Caroline Tice1d2aefd2010-09-09 06:25:08 +000068 debugger.GetSettingsController()->SetVariable (var_name.GetData(), lang_name.c_str(),
69 lldb::eVarSetOperationAssign, false,
70 m_debugger.GetInstanceName().AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +000071}
72
73void
74CommandInterpreter::Initialize ()
75{
76 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
77
78 CommandReturnObject result;
79
80 LoadCommandDictionary ();
81
Chris Lattner24943d22010-06-08 16:52:24 +000082 // Set up some initial aliases.
Jim Ingham767af882010-07-07 03:36:20 +000083 result.Clear(); HandleCommand ("command alias q quit", false, result);
84 result.Clear(); HandleCommand ("command alias run process launch", false, result);
85 result.Clear(); HandleCommand ("command alias r process launch", false, result);
86 result.Clear(); HandleCommand ("command alias c process continue", false, result);
87 result.Clear(); HandleCommand ("command alias continue process continue", false, result);
88 result.Clear(); HandleCommand ("command alias expr expression", false, result);
89 result.Clear(); HandleCommand ("command alias exit quit", false, result);
Greg Clayton0f3a8eb2010-09-16 17:09:23 +000090 result.Clear(); HandleCommand ("command alias b regexp-break", false, result);
Jim Ingham767af882010-07-07 03:36:20 +000091 result.Clear(); HandleCommand ("command alias bt thread backtrace", false, result);
92 result.Clear(); HandleCommand ("command alias si thread step-inst", false, result);
93 result.Clear(); HandleCommand ("command alias step thread step-in", false, result);
94 result.Clear(); HandleCommand ("command alias s thread step-in", false, result);
95 result.Clear(); HandleCommand ("command alias next thread step-over", false, result);
96 result.Clear(); HandleCommand ("command alias n thread step-over", false, result);
97 result.Clear(); HandleCommand ("command alias finish thread step-out", false, result);
98 result.Clear(); HandleCommand ("command alias x memory read", false, result);
99 result.Clear(); HandleCommand ("command alias l source list", false, result);
100 result.Clear(); HandleCommand ("command alias list source list", false, result);
Greg Clayton0f3a8eb2010-09-16 17:09:23 +0000101 result.Clear(); HandleCommand ("command alias p frame variable", false, result);
102 result.Clear(); HandleCommand ("command alias print frame variable", false, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000103}
104
Chris Lattner24943d22010-06-08 16:52:24 +0000105const char *
106CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
107{
108 // This function has not yet been implemented.
109
110 // Look for any embedded script command
111 // If found,
112 // get interpreter object from the command dictionary,
113 // call execute_one_command on it,
114 // get the results as a string,
115 // substitute that string for current stuff.
116
117 return arg;
118}
119
120
121void
122CommandInterpreter::LoadCommandDictionary ()
123{
124 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
125
126 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
127 //
128 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
129 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
130 // the cross-referencing stuff) are created!!!
131 //
132 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
133
134
135 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
136 // are created. This is so that when another command is created that needs to go into a crossref object,
137 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
138 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
139
Chris Lattner24943d22010-06-08 16:52:24 +0000140 // Non-CommandObjectCrossref commands can now be created.
141
Caroline Tice5bc8c972010-09-20 20:44:43 +0000142 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000143
Greg Clayton238c0a12010-09-18 01:14:36 +0000144 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000145 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000146 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000147 m_command_dict["commands"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000148 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
149 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
150 m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000151 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000152 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000153 m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
154 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
155 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
156 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000157 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000158 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000159 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000160 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000161 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000162 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
163 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000164
165 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000166 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
167 "regexp-break",
Caroline Ticec1ad82e2010-09-07 22:38:08 +0000168 "Set a breakpoint using a regular expression to specify the location.",
Chris Lattner24943d22010-06-08 16:52:24 +0000169 "regexp-break [<file>:<line>]\nregexp-break [<address>]\nregexp-break <...>", 2));
170 if (break_regex_cmd_ap.get())
171 {
172 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
173 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
174 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
175 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list") &&
176 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
177 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
178 {
179 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
180 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
181 }
182 }
183}
184
185int
186CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
187 StringList &matches)
188{
189 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
190
191 if (include_aliases)
192 {
193 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
194 }
195
196 return matches.GetSize();
197}
198
199CommandObjectSP
200CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
201{
202 CommandObject::CommandMap::iterator pos;
203 CommandObjectSP ret_val;
204
205 std::string cmd(cmd_cstr);
206
207 if (HasCommands())
208 {
209 pos = m_command_dict.find(cmd);
210 if (pos != m_command_dict.end())
211 ret_val = pos->second;
212 }
213
214 if (include_aliases && HasAliases())
215 {
216 pos = m_alias_dict.find(cmd);
217 if (pos != m_alias_dict.end())
218 ret_val = pos->second;
219 }
220
221 if (HasUserCommands())
222 {
223 pos = m_user_dict.find(cmd);
224 if (pos != m_user_dict.end())
225 ret_val = pos->second;
226 }
227
228 if (!exact && ret_val == NULL)
229 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000230 // We will only get into here if we didn't find any exact matches.
231
232 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
233
Chris Lattner24943d22010-06-08 16:52:24 +0000234 StringList local_matches;
235 if (matches == NULL)
236 matches = &local_matches;
237
Jim Inghamd40f8a62010-07-06 22:46:59 +0000238 unsigned int num_cmd_matches = 0;
239 unsigned int num_alias_matches = 0;
240 unsigned int num_user_matches = 0;
241
242 // Look through the command dictionaries one by one, and if we get only one match from any of
243 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
244
Chris Lattner24943d22010-06-08 16:52:24 +0000245 if (HasCommands())
246 {
247 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
248 }
249
250 if (num_cmd_matches == 1)
251 {
252 cmd.assign(matches->GetStringAtIndex(0));
253 pos = m_command_dict.find(cmd);
254 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000255 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000256 }
257
Jim Ingham9a574172010-06-24 20:28:42 +0000258 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000259 {
260 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
261
262 }
263
Jim Inghamd40f8a62010-07-06 22:46:59 +0000264 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000265 {
266 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
267 pos = m_alias_dict.find(cmd);
268 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000269 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000270 }
271
Jim Ingham9a574172010-06-24 20:28:42 +0000272 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000273 {
274 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
275 }
276
Jim Inghamd40f8a62010-07-06 22:46:59 +0000277 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000278 {
279 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
280
281 pos = m_user_dict.find (cmd);
282 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000283 user_match_sp = pos->second;
284 }
285
286 // If we got exactly one match, return that, otherwise return the match list.
287
288 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
289 {
290 if (num_cmd_matches)
291 return real_match_sp;
292 else if (num_alias_matches)
293 return alias_match_sp;
294 else
295 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000296 }
297 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000298 else if (matches && ret_val != NULL)
299 {
300 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000301 }
302
303
304 return ret_val;
305}
306
Jim Inghamd40f8a62010-07-06 22:46:59 +0000307CommandObjectSP
308CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000309{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000310 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
311}
312
313CommandObject *
314CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
315{
316 return GetCommandSPExact (cmd_cstr, include_aliases).get();
317}
318
319CommandObject *
320CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
321{
322 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
323
324 // If we didn't find an exact match to the command string in the commands, look in
325 // the aliases.
326
327 if (command_obj == NULL)
328 {
329 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
330 }
331
332 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
333 // in both the commands and the aliases.
334
335 if (command_obj == NULL)
336 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
337
338 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000339}
340
341bool
342CommandInterpreter::CommandExists (const char *cmd)
343{
344 return m_command_dict.find(cmd) != m_command_dict.end();
345}
346
347bool
348CommandInterpreter::AliasExists (const char *cmd)
349{
350 return m_alias_dict.find(cmd) != m_alias_dict.end();
351}
352
353bool
354CommandInterpreter::UserCommandExists (const char *cmd)
355{
356 return m_user_dict.find(cmd) != m_user_dict.end();
357}
358
359void
360CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
361{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000362 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000363 m_alias_dict[alias_name] = command_obj_sp;
364}
365
366bool
367CommandInterpreter::RemoveAlias (const char *alias_name)
368{
369 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
370 if (pos != m_alias_dict.end())
371 {
372 m_alias_dict.erase(pos);
373 return true;
374 }
375 return false;
376}
377bool
378CommandInterpreter::RemoveUser (const char *alias_name)
379{
380 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
381 if (pos != m_user_dict.end())
382 {
383 m_user_dict.erase(pos);
384 return true;
385 }
386 return false;
387}
388
Chris Lattner24943d22010-06-08 16:52:24 +0000389void
390CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
391{
392 help_string.Printf ("'%s", command_name);
393 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
394
395 if (option_arg_vector_sp != NULL)
396 {
397 OptionArgVector *options = option_arg_vector_sp.get();
398 for (int i = 0; i < options->size(); ++i)
399 {
400 OptionArgPair cur_option = (*options)[i];
401 std::string opt = cur_option.first;
402 std::string value = cur_option.second;
403 if (opt.compare("<argument>") == 0)
404 {
405 help_string.Printf (" %s", value.c_str());
406 }
407 else
408 {
409 help_string.Printf (" %s", opt.c_str());
410 if ((value.compare ("<no-argument>") != 0)
411 && (value.compare ("<need-argument") != 0))
412 {
413 help_string.Printf (" %s", value.c_str());
414 }
415 }
416 }
417 }
418
419 help_string.Printf ("'");
420}
421
Greg Clayton65124ea2010-08-26 22:05:43 +0000422size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000423CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
424{
425 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000426 CommandObject::CommandMap::const_iterator end = dict.end();
427 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000428
Greg Clayton65124ea2010-08-26 22:05:43 +0000429 for (pos = dict.begin(); pos != end; ++pos)
430 {
431 size_t len = pos->first.size();
432 if (max_len < len)
433 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000434 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000435 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000436}
437
438void
439CommandInterpreter::GetHelp (CommandReturnObject &result)
440{
441 CommandObject::CommandMap::const_iterator pos;
442 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
443 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000444 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000445
446 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
447 {
448 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
449 max_len);
450 }
451 result.AppendMessage("");
452
453 if (m_alias_dict.size() > 0)
454 {
Caroline Tice00edd3a2010-09-13 05:27:16 +0000455 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 +0000456 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000457 max_len = FindLongestCommandWord (m_alias_dict);
458
Chris Lattner24943d22010-06-08 16:52:24 +0000459 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
460 {
461 StreamString sstr;
462 StreamString translation_and_help;
463 std::string entry_name = pos->first;
464 std::string second_entry = pos->second.get()->GetCommandName();
465 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
466
467 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
468 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
469 translation_and_help.GetData(), max_len);
470 }
471 result.AppendMessage("");
472 }
473
474 if (m_user_dict.size() > 0)
475 {
476 result.AppendMessage ("The following is a list of your current user-defined commands:");
477 result.AppendMessage("");
478 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
479 {
480 result.AppendMessageWithFormat ("%s -- %s\n", pos->first.c_str(), pos->second->GetHelp());
481 }
482 result.AppendMessage("");
483 }
484
485 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
486}
487
Chris Lattner24943d22010-06-08 16:52:24 +0000488bool
Greg Clayton63094e02010-06-23 01:19:29 +0000489CommandInterpreter::HandleCommand
490(
491 const char *command_line,
492 bool add_to_history,
493 CommandReturnObject &result,
494 ExecutionContext *override_context
495)
Chris Lattner24943d22010-06-08 16:52:24 +0000496{
497 // FIXME: there should probably be a mutex to make sure only one thread can
498 // run the interpreter at a time.
499
500 // TODO: this should be a logging channel in lldb.
501// if (DebugSelf())
502// {
503// result.AppendMessageWithFormat ("Processing command: %s\n", command_line);
504// }
505
Greg Clayton63094e02010-06-23 01:19:29 +0000506 m_debugger.UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +0000507
508 if (command_line == NULL || command_line[0] == '\0')
509 {
510 if (m_command_history.empty())
511 {
512 result.AppendError ("empty command");
513 result.SetStatus(eReturnStatusFailed);
514 return false;
515 }
516 else
517 {
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000518 command_line = m_repeat_command.c_str();
519 if (m_repeat_command.empty())
520 {
Jim Ingham767af882010-07-07 03:36:20 +0000521 result.AppendErrorWithFormat("No auto repeat.\n");
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000522 result.SetStatus (eReturnStatusFailed);
523 return false;
524 }
Chris Lattner24943d22010-06-08 16:52:24 +0000525 }
526 add_to_history = false;
527 }
528
529 Args command_args(command_line);
530
531 if (command_args.GetArgumentCount() > 0)
532 {
533 const char *command_cstr = command_args.GetArgumentAtIndex(0);
534 if (command_cstr)
535 {
536
537 // We're looking up the command object here. So first find an exact match to the
538 // command in the commands.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000539 CommandObject *command_obj = GetCommandObject(command_cstr);
540
541 if (command_obj != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000542 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000543 if (command_obj->IsAlias())
Chris Lattner24943d22010-06-08 16:52:24 +0000544 {
545 BuildAliasCommandArgs (command_obj, command_cstr, command_args, result);
546 if (!result.Succeeded())
547 return false;
548 }
Chris Lattner24943d22010-06-08 16:52:24 +0000549
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000550 if (add_to_history)
551 {
Jim Ingham767af882010-07-07 03:36:20 +0000552 const char *repeat_command = command_obj->GetRepeatCommand(command_args, 0);
553 if (repeat_command != NULL)
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000554 m_repeat_command.assign(repeat_command);
555 else
Jim Ingham767af882010-07-07 03:36:20 +0000556 m_repeat_command.assign(command_line);
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000557
558 m_command_history.push_back (command_line);
559 }
560
561
Chris Lattner24943d22010-06-08 16:52:24 +0000562 if (command_obj->WantsRawCommandString())
563 {
564 const char *stripped_command = ::strstr (command_line, command_cstr);
565 if (stripped_command)
566 {
567 stripped_command += strlen(command_cstr);
568 while (isspace(*stripped_command))
569 ++stripped_command;
Greg Clayton238c0a12010-09-18 01:14:36 +0000570 command_obj->ExecuteRawCommandString (stripped_command, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000571 }
572 }
573 else
574 {
Chris Lattner24943d22010-06-08 16:52:24 +0000575 // Remove the command from the args.
576 command_args.Shift();
Greg Clayton238c0a12010-09-18 01:14:36 +0000577 command_obj->ExecuteWithOptions (command_args, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000578 }
579 }
580 else
581 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000582 // We didn't find the first command object, so complete the first argument.
Chris Lattner24943d22010-06-08 16:52:24 +0000583 StringList matches;
584 int num_matches;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000585 int cursor_index = 0;
586 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
Jim Ingham802f8b02010-06-30 05:02:46 +0000587 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +0000588 num_matches = HandleCompletionMatches (command_args,
589 cursor_index,
590 cursor_char_position,
591 0,
592 -1,
Jim Ingham802f8b02010-06-30 05:02:46 +0000593 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +0000594 matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000595
596 if (num_matches > 0)
597 {
598 std::string error_msg;
599 error_msg.assign ("ambiguous command '");
600 error_msg.append(command_cstr);
601 error_msg.append ("'.");
602
603 error_msg.append (" Possible completions:");
604 for (int i = 0; i < num_matches; i++)
605 {
606 error_msg.append ("\n\t");
607 error_msg.append (matches.GetStringAtIndex (i));
608 }
609 error_msg.append ("\n");
610 result.AppendRawError (error_msg.c_str(), error_msg.size());
611 }
612 else
613 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_cstr);
614
615 result.SetStatus (eReturnStatusFailed);
616 }
617 }
618 }
619 return result.Succeeded();
620}
621
622int
623CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
624 int &cursor_index,
625 int &cursor_char_position,
626 int match_start_point,
627 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +0000628 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000629 StringList &matches)
630{
631 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000632 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +0000633
634 // For any of the command completions a unique match will be a complete word.
635 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000636
637 if (cursor_index == -1)
638 {
639 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +0000640 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000641 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
642 }
643 else if (cursor_index == 0)
644 {
645 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000646 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000647 num_command_matches = matches.GetSize();
648
649 if (num_command_matches == 1
650 && cmd_obj && cmd_obj->IsMultiwordObject()
651 && matches.GetStringAtIndex(0) != NULL
652 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
653 {
654 look_for_subcommand = true;
655 num_command_matches = 0;
656 matches.DeleteStringAtIndex(0);
657 parsed_line.AppendArgument ("");
658 cursor_index++;
659 cursor_char_position = 0;
660 }
661 }
662
663 if (cursor_index > 0 || look_for_subcommand)
664 {
665 // We are completing further on into a commands arguments, so find the command and tell it
666 // to complete the command.
667 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +0000668 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +0000669 if (command_object == NULL)
670 {
671 return 0;
672 }
673 else
674 {
675 parsed_line.Shift();
676 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +0000677 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +0000678 cursor_index,
679 cursor_char_position,
680 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000681 max_return_elements,
682 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000683 matches);
684 }
685 }
686
687 return num_command_matches;
688
689}
690
691int
692CommandInterpreter::HandleCompletion (const char *current_line,
693 const char *cursor,
694 const char *last_char,
695 int match_start_point,
696 int max_return_elements,
697 StringList &matches)
698{
699 // We parse the argument up to the cursor, so the last argument in parsed_line is
700 // the one containing the cursor, and the cursor is after the last character.
701
702 Args parsed_line(current_line, last_char - current_line);
703 Args partial_parsed_line(current_line, cursor - current_line);
704
705 int num_args = partial_parsed_line.GetArgumentCount();
706 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
707 int cursor_char_position;
708
709 if (cursor_index == -1)
710 cursor_char_position = 0;
711 else
712 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
713
714 int num_command_matches;
715
716 matches.Clear();
717
718 // Only max_return_elements == -1 is supported at present:
719 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +0000720 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +0000721 num_command_matches = HandleCompletionMatches (parsed_line,
722 cursor_index,
723 cursor_char_position,
724 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000725 max_return_elements,
726 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +0000727 matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000728
729 if (num_command_matches <= 0)
730 return num_command_matches;
731
732 if (num_args == 0)
733 {
734 // If we got an empty string, insert nothing.
735 matches.InsertStringAtIndex(0, "");
736 }
737 else
738 {
739 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
740 // put an empty string in element 0.
741 std::string command_partial_str;
742 if (cursor_index >= 0)
743 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index), parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
744
745 std::string common_prefix;
746 matches.LongestCommonPrefix (common_prefix);
747 int partial_name_len = command_partial_str.size();
748
749 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +0000750 // Only do this if the completer told us this was a complete word, however...
751 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +0000752 {
753 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
754 if (quote_char != '\0')
755 common_prefix.push_back(quote_char);
756
757 common_prefix.push_back(' ');
758 }
759 common_prefix.erase (0, partial_name_len);
760 matches.InsertStringAtIndex(0, common_prefix.c_str());
761 }
762 return num_command_matches;
763}
764
Chris Lattner24943d22010-06-08 16:52:24 +0000765
766CommandInterpreter::~CommandInterpreter ()
767{
768}
769
770const char *
771CommandInterpreter::GetPrompt ()
772{
Caroline Tice5bc8c972010-09-20 20:44:43 +0000773 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +0000774}
775
776void
777CommandInterpreter::SetPrompt (const char *new_prompt)
778{
Caroline Tice5bc8c972010-09-20 20:44:43 +0000779 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +0000780}
781
Jim Ingham5e16ef52010-10-04 19:49:29 +0000782size_t
783CommandInterpreter::GetConfirmationInputReaderCallback (void *baton,
784 InputReader &reader,
785 lldb::InputReaderAction action,
786 const char *bytes,
787 size_t bytes_len)
788{
789 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle();
790 bool *response_ptr = (bool *) baton;
791
792 switch (action)
793 {
794 case eInputReaderActivate:
795 if (out_fh)
796 {
797 if (reader.GetPrompt())
798 ::fprintf (out_fh, "%s", reader.GetPrompt());
799 }
800 break;
801
802 case eInputReaderDeactivate:
803 break;
804
805 case eInputReaderReactivate:
806 if (out_fh && reader.GetPrompt())
807 ::fprintf (out_fh, "%s", reader.GetPrompt());
808 break;
809
810 case eInputReaderGotToken:
811 if (bytes_len == 0)
812 {
813 reader.SetIsDone(true);
814 }
815 else if (bytes[0] == 'y')
816 {
817 *response_ptr = true;
818 reader.SetIsDone(true);
819 }
820 else if (bytes[0] == 'n')
821 {
822 *response_ptr = false;
823 reader.SetIsDone(true);
824 }
825 else
826 {
827 if (out_fh && !reader.IsDone() && reader.GetPrompt())
828 {
829 ::fprintf (out_fh, "Please answer \"y\" or \"n\"\n");
830 ::fprintf (out_fh, "%s", reader.GetPrompt());
831 }
832 }
833 break;
834
835 case eInputReaderDone:
836 break;
837 }
838
839 return bytes_len;
840
841}
842
843bool
844CommandInterpreter::Confirm (const char *message, bool default_answer)
845{
846 // The default interpretation just pushes a new input reader and lets it get the answer:
847 InputReaderSP reader_sp (new InputReader(GetDebugger()));
848 bool response = default_answer;
849 if (reader_sp)
850 {
851 std::string prompt(message);
852 prompt.append(": [");
853 if (default_answer)
854 prompt.append ("Y/n] ");
855 else
856 prompt.append ("y/N] ");
857
858 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
859 &response, // baton
860 eInputReaderGranularityLine, // token size, to pass to callback function
861 NULL, // end token
862 prompt.c_str(), // prompt
863 true)); // echo input
864 if (err.Success())
865 {
866 GetDebugger().PushInputReader (reader_sp);
867 }
868 reader_sp->WaitOnReaderIsDone();
869 }
870 return response;
871}
872
873
Chris Lattner24943d22010-06-08 16:52:24 +0000874void
875CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
876{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000877 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +0000878
879 if (cmd_obj_sp != NULL)
880 {
881 CommandObject *cmd_obj = cmd_obj_sp.get();
882 if (cmd_obj->IsCrossRefObject ())
883 cmd_obj->AddObject (object_type);
884 }
885}
886
Chris Lattner24943d22010-06-08 16:52:24 +0000887OptionArgVectorSP
888CommandInterpreter::GetAliasOptions (const char *alias_name)
889{
890 OptionArgMap::iterator pos;
891 OptionArgVectorSP ret_val;
892
893 std::string alias (alias_name);
894
895 if (HasAliasOptions())
896 {
897 pos = m_alias_options.find (alias);
898 if (pos != m_alias_options.end())
899 ret_val = pos->second;
900 }
901
902 return ret_val;
903}
904
905void
906CommandInterpreter::RemoveAliasOptions (const char *alias_name)
907{
908 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
909 if (pos != m_alias_options.end())
910 {
911 m_alias_options.erase (pos);
912 }
913}
914
915void
916CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
917{
918 m_alias_options[alias_name] = option_arg_vector_sp;
919}
920
921bool
922CommandInterpreter::HasCommands ()
923{
924 return (!m_command_dict.empty());
925}
926
927bool
928CommandInterpreter::HasAliases ()
929{
930 return (!m_alias_dict.empty());
931}
932
933bool
934CommandInterpreter::HasUserCommands ()
935{
936 return (!m_user_dict.empty());
937}
938
939bool
940CommandInterpreter::HasAliasOptions ()
941{
942 return (!m_alias_options.empty());
943}
944
Chris Lattner24943d22010-06-08 16:52:24 +0000945void
946CommandInterpreter::BuildAliasCommandArgs
947(
948 CommandObject *alias_cmd_obj,
949 const char *alias_name,
950 Args &cmd_args,
951 CommandReturnObject &result
952)
953{
954 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
955
956 if (option_arg_vector_sp.get())
957 {
958 // Make sure that the alias name is the 0th element in cmd_args
959 std::string alias_name_str = alias_name;
960 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
961 cmd_args.Unshift (alias_name);
962
963 Args new_args (alias_cmd_obj->GetCommandName());
964 if (new_args.GetArgumentCount() == 2)
965 new_args.Shift();
966
967 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
968 int old_size = cmd_args.GetArgumentCount();
969 int *used = (int *) malloc ((old_size + 1) * sizeof (int));
970
971 memset (used, 0, (old_size + 1) * sizeof (int));
972 used[0] = 1;
973
974 for (int i = 0; i < option_arg_vector->size(); ++i)
975 {
976 OptionArgPair option_pair = (*option_arg_vector)[i];
977 std::string option = option_pair.first;
978 std::string value = option_pair.second;
979 if (option.compare ("<argument>") == 0)
980 new_args.AppendArgument (value.c_str());
981 else
982 {
983 new_args.AppendArgument (option.c_str());
984 if (value.compare ("<no-argument>") != 0)
985 {
986 int index = GetOptionArgumentPosition (value.c_str());
987 if (index == 0)
988 // value was NOT a positional argument; must be a real value
989 new_args.AppendArgument (value.c_str());
990 else if (index >= cmd_args.GetArgumentCount())
991 {
992 result.AppendErrorWithFormat
993 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
994 index);
995 result.SetStatus (eReturnStatusFailed);
996 return;
997 }
998 else
999 {
1000 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
1001 used[index] = 1;
1002 }
1003 }
1004 }
1005 }
1006
1007 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1008 {
1009 if (!used[j])
1010 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1011 }
1012
1013 cmd_args.Clear();
1014 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1015 }
1016 else
1017 {
1018 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1019 // This alias was not created with any options; nothing further needs to be done.
1020 return;
1021 }
1022
1023 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1024 return;
1025}
1026
1027
1028int
1029CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1030{
1031 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1032 // of zero.
1033
1034 char *cptr = (char *) in_string;
1035
1036 // Does it start with '%'
1037 if (cptr[0] == '%')
1038 {
1039 ++cptr;
1040
1041 // Is the rest of it entirely digits?
1042 if (isdigit (cptr[0]))
1043 {
1044 const char *start = cptr;
1045 while (isdigit (cptr[0]))
1046 ++cptr;
1047
1048 // We've gotten to the end of the digits; are we at the end of the string?
1049 if (cptr[0] == '\0')
1050 position = atoi (start);
1051 }
1052 }
1053
1054 return position;
1055}
1056
1057void
1058CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1059{
1060 const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit";
1061 FileSpec init_file (init_file_path);
1062 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
1063 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
1064
1065 if (init_file.Exists())
1066 {
1067 char path[PATH_MAX];
1068 init_file.GetPath(path, sizeof(path));
1069 StreamString source_command;
Johnny Chen7c984242010-07-28 21:16:11 +00001070 source_command.Printf ("command source '%s'", path);
Chris Lattner24943d22010-06-08 16:52:24 +00001071 HandleCommand (source_command.GetData(), false, result);
1072 }
1073 else
1074 {
1075 // nothing to be done if the file doesn't exist
1076 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1077 }
1078}
1079
1080ScriptInterpreter *
1081CommandInterpreter::GetScriptInterpreter ()
1082{
Greg Clayton63094e02010-06-23 01:19:29 +00001083 CommandObject::CommandMap::iterator pos;
1084
1085 pos = m_command_dict.find ("script");
1086 if (pos != m_command_dict.end())
Chris Lattner24943d22010-06-08 16:52:24 +00001087 {
Greg Clayton63094e02010-06-23 01:19:29 +00001088 CommandObject *script_cmd_obj = pos->second.get();
Greg Clayton238c0a12010-09-18 01:14:36 +00001089 return ((CommandObjectScript *) script_cmd_obj)->GetInterpreter ();
Chris Lattner24943d22010-06-08 16:52:24 +00001090 }
Greg Clayton63094e02010-06-23 01:19:29 +00001091 return NULL;
Chris Lattner24943d22010-06-08 16:52:24 +00001092}
1093
1094
1095
1096bool
1097CommandInterpreter::GetSynchronous ()
1098{
1099 return m_synchronous_execution;
1100}
1101
1102void
1103CommandInterpreter::SetSynchronous (bool value)
1104{
1105 static bool value_set_once = false;
1106 if (!value_set_once)
1107 {
1108 value_set_once = true;
1109 m_synchronous_execution = value;
1110 }
1111}
1112
1113void
1114CommandInterpreter::OutputFormattedHelpText (Stream &strm,
1115 const char *word_text,
1116 const char *separator,
1117 const char *help_text,
1118 uint32_t max_word_len)
1119{
Greg Clayton238c0a12010-09-18 01:14:36 +00001120 const uint32_t max_columns = m_debugger.GetTerminalWidth();
1121
Chris Lattner24943d22010-06-08 16:52:24 +00001122 int indent_size = max_word_len + strlen (separator) + 2;
1123
1124 strm.IndentMore (indent_size);
1125
1126 int len = indent_size + strlen (help_text) + 1;
1127 char *text = (char *) malloc (len);
1128 sprintf (text, "%-*s %s %s", max_word_len, word_text, separator, help_text);
1129 if (text[len - 1] == '\n')
1130 text[--len] = '\0';
1131
1132 if (len < max_columns)
1133 {
1134 // Output it as a single line.
1135 strm.Printf ("%s", text);
1136 }
1137 else
1138 {
1139 // We need to break it up into multiple lines.
1140 bool first_line = true;
1141 int text_width;
1142 int start = 0;
1143 int end = start;
1144 int final_end = strlen (text);
1145 int sub_len;
1146
1147 while (end < final_end)
1148 {
1149 if (first_line)
1150 text_width = max_columns - 1;
1151 else
1152 text_width = max_columns - indent_size - 1;
1153
1154 // Don't start the 'text' on a space, since we're already outputting the indentation.
1155 if (!first_line)
1156 {
1157 while ((start < final_end) && (text[start] == ' '))
1158 start++;
1159 }
1160
1161 end = start + text_width;
1162 if (end > final_end)
1163 end = final_end;
1164 else
1165 {
1166 // If we're not at the end of the text, make sure we break the line on white space.
1167 while (end > start
1168 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
1169 end--;
1170 }
1171
1172 sub_len = end - start;
1173 if (start != 0)
1174 strm.EOL();
1175 if (!first_line)
1176 strm.Indent();
1177 else
1178 first_line = false;
1179 assert (start <= final_end);
1180 assert (start + sub_len <= final_end);
1181 if (sub_len > 0)
1182 strm.Write (text + start, sub_len);
1183 start = end + 1;
1184 }
1185 }
1186 strm.EOL();
1187 strm.IndentLess(indent_size);
1188 free (text);
1189}
1190
1191void
1192CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
1193 StringList &commands_found, StringList &commands_help)
1194{
1195 CommandObject::CommandMap::const_iterator pos;
1196 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
1197 CommandObject *sub_cmd_obj;
1198
1199 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
1200 {
1201 const char * command_name = pos->first.c_str();
1202 sub_cmd_obj = pos->second.get();
1203 StreamString complete_command_name;
1204
1205 complete_command_name.Printf ("%s %s", prefix, command_name);
1206
Greg Clayton238c0a12010-09-18 01:14:36 +00001207 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001208 {
1209 commands_found.AppendString (complete_command_name.GetData());
1210 commands_help.AppendString (sub_cmd_obj->GetHelp());
1211 }
1212
1213 if (sub_cmd_obj->IsMultiwordObject())
1214 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
1215 commands_help);
1216 }
1217
1218}
1219
1220void
1221CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
1222 StringList &commands_help)
1223{
1224 CommandObject::CommandMap::const_iterator pos;
1225
1226 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1227 {
1228 const char *command_name = pos->first.c_str();
1229 CommandObject *cmd_obj = pos->second.get();
1230
Greg Clayton238c0a12010-09-18 01:14:36 +00001231 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001232 {
1233 commands_found.AppendString (command_name);
1234 commands_help.AppendString (cmd_obj->GetHelp());
1235 }
1236
1237 if (cmd_obj->IsMultiwordObject())
1238 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
1239
1240 }
1241}