blob: 1027f94457f912d29495db0ff3a3f8549890b95e [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/CommandObjectAppend.h"
16#include "../Commands/CommandObjectApropos.h"
17#include "../Commands/CommandObjectArgs.h"
18#include "../Commands/CommandObjectBreakpoint.h"
19#include "../Commands/CommandObjectCall.h"
20#include "../Commands/CommandObjectDelete.h"
21#include "../Commands/CommandObjectDisassemble.h"
22#include "../Commands/CommandObjectExpression.h"
23#include "../Commands/CommandObjectFile.h"
24#include "../Commands/CommandObjectFrame.h"
25#include "../Commands/CommandObjectHelp.h"
26#include "../Commands/CommandObjectImage.h"
27#include "../Commands/CommandObjectInfo.h"
28#include "../Commands/CommandObjectLog.h"
29#include "../Commands/CommandObjectMemory.h"
30#include "../Commands/CommandObjectProcess.h"
31#include "../Commands/CommandObjectQuit.h"
Eli Friedmanb34d2a22010-06-09 22:08:29 +000032#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000033#include "../Commands/CommandObjectRegister.h"
Chris Lattner24943d22010-06-08 16:52:24 +000034#include "CommandObjectScript.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000035#include "../Commands/CommandObjectSelect.h"
36#include "../Commands/CommandObjectSet.h"
37#include "../Commands/CommandObjectSettings.h"
38#include "../Commands/CommandObjectShow.h"
39#include "../Commands/CommandObjectSource.h"
Jim Ingham767af882010-07-07 03:36:20 +000040#include "../Commands/CommandObjectCommands.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000041#include "../Commands/CommandObjectSyntax.h"
42#include "../Commands/CommandObjectTarget.h"
43#include "../Commands/CommandObjectThread.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000044#include "../Commands/CommandObjectVariable.h"
Chris Lattner24943d22010-06-08 16:52:24 +000045
Jim Ingham84cdc152010-06-15 19:49:27 +000046#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000047#include "lldb/Core/Debugger.h"
48#include "lldb/Core/Stream.h"
49#include "lldb/Core/Timer.h"
50#include "lldb/Target/Process.h"
51#include "lldb/Target/Thread.h"
52#include "lldb/Target/TargetList.h"
53
54#include "lldb/Interpreter/CommandReturnObject.h"
55#include "lldb/Interpreter/CommandInterpreter.h"
56
57using namespace lldb;
58using namespace lldb_private;
59
60CommandInterpreter::CommandInterpreter
61(
Greg Clayton63094e02010-06-23 01:19:29 +000062 Debugger &debugger,
Chris Lattner24943d22010-06-08 16:52:24 +000063 ScriptLanguage script_language,
Greg Clayton63094e02010-06-23 01:19:29 +000064 bool synchronous_execution
Chris Lattner24943d22010-06-08 16:52:24 +000065) :
66 Broadcaster ("CommandInterpreter"),
Greg Clayton63094e02010-06-23 01:19:29 +000067 m_debugger (debugger),
Chris Lattner24943d22010-06-08 16:52:24 +000068 m_script_language (script_language),
Greg Clayton63094e02010-06-23 01:19:29 +000069 m_synchronous_execution (synchronous_execution)
Chris Lattner24943d22010-06-08 16:52:24 +000070{
71}
72
73void
74CommandInterpreter::Initialize ()
75{
76 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
77
78 CommandReturnObject result;
79
80 LoadCommandDictionary ();
81
82 InitializeVariables ();
83
84 // Set up some initial aliases.
Jim Ingham767af882010-07-07 03:36:20 +000085 result.Clear(); HandleCommand ("command alias q quit", false, result);
86 result.Clear(); HandleCommand ("command alias run process launch", false, result);
87 result.Clear(); HandleCommand ("command alias r process launch", false, result);
88 result.Clear(); HandleCommand ("command alias c process continue", false, result);
89 result.Clear(); HandleCommand ("command alias continue process continue", false, result);
90 result.Clear(); HandleCommand ("command alias expr expression", false, result);
91 result.Clear(); HandleCommand ("command alias exit quit", false, result);
92 result.Clear(); HandleCommand ("command alias b breakpoint", false, result);
93 result.Clear(); HandleCommand ("command alias bt thread backtrace", false, result);
94 result.Clear(); HandleCommand ("command alias si thread step-inst", false, result);
95 result.Clear(); HandleCommand ("command alias step thread step-in", false, result);
96 result.Clear(); HandleCommand ("command alias s thread step-in", false, result);
97 result.Clear(); HandleCommand ("command alias next thread step-over", false, result);
98 result.Clear(); HandleCommand ("command alias n thread step-over", false, result);
99 result.Clear(); HandleCommand ("command alias finish thread step-out", false, result);
100 result.Clear(); HandleCommand ("command alias x memory read", false, result);
101 result.Clear(); HandleCommand ("command alias l source list", false, result);
102 result.Clear(); HandleCommand ("command alias list source list", false, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000103}
104
105void
106CommandInterpreter::InitializeVariables ()
107{
108 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
109
110 m_variables["prompt"] =
111 StateVariableSP (new StateVariable ("prompt",
112 "(lldb) ",
113 false,
114 "The debugger prompt displayed for the user.",
115 StateVariable::BroadcastPromptChange));
116
117 m_variables["run-args"] =
118 StateVariableSP (new StateVariable ("run-args",
119 (Args*)NULL,
120 "An argument list containing the arguments to be passed to the executable when it is launched."));
121
122
123 m_variables["env-vars"] =
124 StateVariableSP (new StateVariable ("env-vars",
125 (Args*)NULL,
126 "A list of strings containing the environment variables to be passed to the executable's environment."));
127
128 m_variables["input-path"] =
129 StateVariableSP (new StateVariable ("input-path",
130 "/dev/stdin",
131 false,
132 "The file/path to be used by the executable program for reading its input."));
133
134 m_variables["output-path"] =
135 StateVariableSP (new StateVariable ( "output-path",
136 "/dev/stdout",
137 false,
138 "The file/path to be used by the executable program for writing its output."));
139
140 m_variables["error-path"] =
141 StateVariableSP (new StateVariable ("error-path",
142 "/dev/stderr",
143 false,
144 "The file/path to be used by the executable program for writing its error messages."));
145
146 m_variables["arch"] =
147 StateVariableSP (new StateVariable ("arch",
148 "",
149 false,
150 "The architecture to be used for running the executable (e.g. i386, x86_64, etc)."));
151
152 m_variables["script-lang"] =
153 StateVariableSP (new StateVariable ("script-lang",
154 "Python",
155 false,
156 "The script language to be used for evaluating user-written scripts.",
157 StateVariable::VerifyScriptLanguage));
158
159 m_variables["term-width"] =
160 StateVariableSP (new StateVariable ("term-width",
161 80,
162 "The maximum number of columns to use for displaying text."));
163
164}
165
166const char *
167CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
168{
169 // This function has not yet been implemented.
170
171 // Look for any embedded script command
172 // If found,
173 // get interpreter object from the command dictionary,
174 // call execute_one_command on it,
175 // get the results as a string,
176 // substitute that string for current stuff.
177
178 return arg;
179}
180
181
182void
183CommandInterpreter::LoadCommandDictionary ()
184{
185 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
186
187 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
188 //
189 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
190 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
191 // the cross-referencing stuff) are created!!!
192 //
193 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
194
195
196 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
197 // are created. This is so that when another command is created that needs to go into a crossref object,
198 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
199 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
200
Greg Clayton63094e02010-06-23 01:19:29 +0000201 m_command_dict["select"] = CommandObjectSP (new CommandObjectSelect ());
202 m_command_dict["info"] = CommandObjectSP (new CommandObjectInfo ());
203 m_command_dict["delete"] = CommandObjectSP (new CommandObjectDelete ());
Chris Lattner24943d22010-06-08 16:52:24 +0000204
205 // Non-CommandObjectCrossref commands can now be created.
206
Chris Lattner24943d22010-06-08 16:52:24 +0000207 m_command_dict["append"] = CommandObjectSP (new CommandObjectAppend ());
208 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos ());
Greg Clayton63094e02010-06-23 01:19:29 +0000209 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000210 m_command_dict["call"] = CommandObjectSP (new CommandObjectCall ());
Jim Ingham767af882010-07-07 03:36:20 +0000211 m_command_dict["commands"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000212 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble ());
213 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression ());
214 m_command_dict["file"] = CommandObjectSP (new CommandObjectFile ());
Greg Clayton63094e02010-06-23 01:19:29 +0000215 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000216 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp ());
Greg Clayton63094e02010-06-23 01:19:29 +0000217 m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
218 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
219 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
220 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000221 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit ());
Greg Clayton63094e02010-06-23 01:19:29 +0000222 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000223 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (m_script_language));
224 m_command_dict["set"] = CommandObjectSP (new CommandObjectSet ());
225 m_command_dict["settings"] = CommandObjectSP (new CommandObjectSettings ());
226 m_command_dict["show"] = CommandObjectSP (new CommandObjectShow ());
Jim Ingham767af882010-07-07 03:36:20 +0000227 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000228 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
229 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000230 m_command_dict["variable"] = CommandObjectSP (new CommandObjectVariable (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000231
232 std::auto_ptr<CommandObjectRegexCommand>
233 break_regex_cmd_ap(new CommandObjectRegexCommand ("regexp-break",
234 "Smart breakpoint command (using regular expressions).",
235 "regexp-break [<file>:<line>]\nregexp-break [<address>]\nregexp-break <...>", 2));
236 if (break_regex_cmd_ap.get())
237 {
238 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
239 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
240 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
241 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list") &&
242 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
243 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
244 {
245 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
246 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
247 }
248 }
249}
250
251int
252CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
253 StringList &matches)
254{
255 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
256
257 if (include_aliases)
258 {
259 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
260 }
261
262 return matches.GetSize();
263}
264
265CommandObjectSP
266CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
267{
268 CommandObject::CommandMap::iterator pos;
269 CommandObjectSP ret_val;
270
271 std::string cmd(cmd_cstr);
272
273 if (HasCommands())
274 {
275 pos = m_command_dict.find(cmd);
276 if (pos != m_command_dict.end())
277 ret_val = pos->second;
278 }
279
280 if (include_aliases && HasAliases())
281 {
282 pos = m_alias_dict.find(cmd);
283 if (pos != m_alias_dict.end())
284 ret_val = pos->second;
285 }
286
287 if (HasUserCommands())
288 {
289 pos = m_user_dict.find(cmd);
290 if (pos != m_user_dict.end())
291 ret_val = pos->second;
292 }
293
294 if (!exact && ret_val == NULL)
295 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000296 // We will only get into here if we didn't find any exact matches.
297
298 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
299
Chris Lattner24943d22010-06-08 16:52:24 +0000300 StringList local_matches;
301 if (matches == NULL)
302 matches = &local_matches;
303
Jim Inghamd40f8a62010-07-06 22:46:59 +0000304 unsigned int num_cmd_matches = 0;
305 unsigned int num_alias_matches = 0;
306 unsigned int num_user_matches = 0;
307
308 // Look through the command dictionaries one by one, and if we get only one match from any of
309 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
310
Chris Lattner24943d22010-06-08 16:52:24 +0000311 if (HasCommands())
312 {
313 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
314 }
315
316 if (num_cmd_matches == 1)
317 {
318 cmd.assign(matches->GetStringAtIndex(0));
319 pos = m_command_dict.find(cmd);
320 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000321 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000322 }
323
Jim Ingham9a574172010-06-24 20:28:42 +0000324 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000325 {
326 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
327
328 }
329
Jim Inghamd40f8a62010-07-06 22:46:59 +0000330 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000331 {
332 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
333 pos = m_alias_dict.find(cmd);
334 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000335 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000336 }
337
Jim Ingham9a574172010-06-24 20:28:42 +0000338 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000339 {
340 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
341 }
342
Jim Inghamd40f8a62010-07-06 22:46:59 +0000343 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000344 {
345 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
346
347 pos = m_user_dict.find (cmd);
348 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000349 user_match_sp = pos->second;
350 }
351
352 // If we got exactly one match, return that, otherwise return the match list.
353
354 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
355 {
356 if (num_cmd_matches)
357 return real_match_sp;
358 else if (num_alias_matches)
359 return alias_match_sp;
360 else
361 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000362 }
363 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000364 else if (matches && ret_val != NULL)
365 {
366 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000367 }
368
369
370 return ret_val;
371}
372
Jim Inghamd40f8a62010-07-06 22:46:59 +0000373CommandObjectSP
374CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000375{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000376 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
377}
378
379CommandObject *
380CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
381{
382 return GetCommandSPExact (cmd_cstr, include_aliases).get();
383}
384
385CommandObject *
386CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
387{
388 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
389
390 // If we didn't find an exact match to the command string in the commands, look in
391 // the aliases.
392
393 if (command_obj == NULL)
394 {
395 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
396 }
397
398 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
399 // in both the commands and the aliases.
400
401 if (command_obj == NULL)
402 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
403
404 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000405}
406
407bool
408CommandInterpreter::CommandExists (const char *cmd)
409{
410 return m_command_dict.find(cmd) != m_command_dict.end();
411}
412
413bool
414CommandInterpreter::AliasExists (const char *cmd)
415{
416 return m_alias_dict.find(cmd) != m_alias_dict.end();
417}
418
419bool
420CommandInterpreter::UserCommandExists (const char *cmd)
421{
422 return m_user_dict.find(cmd) != m_user_dict.end();
423}
424
425void
426CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
427{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000428 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000429 m_alias_dict[alias_name] = command_obj_sp;
430}
431
432bool
433CommandInterpreter::RemoveAlias (const char *alias_name)
434{
435 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
436 if (pos != m_alias_dict.end())
437 {
438 m_alias_dict.erase(pos);
439 return true;
440 }
441 return false;
442}
443bool
444CommandInterpreter::RemoveUser (const char *alias_name)
445{
446 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
447 if (pos != m_user_dict.end())
448 {
449 m_user_dict.erase(pos);
450 return true;
451 }
452 return false;
453}
454
455StateVariable *
456CommandInterpreter::GetStateVariable(const char *name)
457{
458 VariableMap::const_iterator pos = m_variables.find(name);
459 if (pos != m_variables.end())
460 return pos->second.get();
461 return NULL;
462}
463
464void
465CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
466{
467 help_string.Printf ("'%s", command_name);
468 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
469
470 if (option_arg_vector_sp != NULL)
471 {
472 OptionArgVector *options = option_arg_vector_sp.get();
473 for (int i = 0; i < options->size(); ++i)
474 {
475 OptionArgPair cur_option = (*options)[i];
476 std::string opt = cur_option.first;
477 std::string value = cur_option.second;
478 if (opt.compare("<argument>") == 0)
479 {
480 help_string.Printf (" %s", value.c_str());
481 }
482 else
483 {
484 help_string.Printf (" %s", opt.c_str());
485 if ((value.compare ("<no-argument>") != 0)
486 && (value.compare ("<need-argument") != 0))
487 {
488 help_string.Printf (" %s", value.c_str());
489 }
490 }
491 }
492 }
493
494 help_string.Printf ("'");
495}
496
497std::string
498CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
499{
500 CommandObject::CommandMap::const_iterator pos;
501 int max_len = 0;
502 CommandObjectSP cmd_sp;
503 std::string longest_word;
504
505 for (pos = dict.begin(); pos != dict.end(); ++pos)
506 {
507 if ((max_len == 0)
508 || (strlen (pos->first.c_str()) > max_len))
509 {
510 longest_word = pos->first;
511 max_len = strlen (longest_word.c_str());
512 }
513 }
514
515 return longest_word;
516}
517
518void
519CommandInterpreter::GetHelp (CommandReturnObject &result)
520{
521 CommandObject::CommandMap::const_iterator pos;
522 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
523 result.AppendMessage("");
524 std::string longest_word = FindLongestCommandWord (m_command_dict);
525 uint32_t max_len = strlen (longest_word.c_str());
526
527 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
528 {
529 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
530 max_len);
531 }
532 result.AppendMessage("");
533
534 if (m_alias_dict.size() > 0)
535 {
536 result.AppendMessage("The following is a list of your current command abbreviations (see 'alias' for more info):");
537 result.AppendMessage("");
538 longest_word = FindLongestCommandWord (m_alias_dict);
539 max_len = strlen (longest_word.c_str());
540 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
541 {
542 StreamString sstr;
543 StreamString translation_and_help;
544 std::string entry_name = pos->first;
545 std::string second_entry = pos->second.get()->GetCommandName();
546 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
547
548 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
549 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
550 translation_and_help.GetData(), max_len);
551 }
552 result.AppendMessage("");
553 }
554
555 if (m_user_dict.size() > 0)
556 {
557 result.AppendMessage ("The following is a list of your current user-defined commands:");
558 result.AppendMessage("");
559 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
560 {
561 result.AppendMessageWithFormat ("%s -- %s\n", pos->first.c_str(), pos->second->GetHelp());
562 }
563 result.AppendMessage("");
564 }
565
566 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
567}
568
569void
570CommandInterpreter::ShowVariableValues (CommandReturnObject &result)
571{
572 result.AppendMessage ("Below is a list of all the debugger setting variables and their values:");
573
574 for (VariableMap::const_iterator pos = m_variables.begin(); pos != m_variables.end(); ++pos)
575 {
576 StateVariable *var = pos->second.get();
577 var->AppendVariableInformation (result);
578 }
579}
580
581void
582CommandInterpreter::ShowVariableHelp (CommandReturnObject &result)
583{
584 result.AppendMessage ("Below is a list of all the internal debugger variables that are settable:");
585 for (VariableMap::const_iterator pos = m_variables.begin(); pos != m_variables.end(); ++pos)
586 {
587 StateVariable *var = pos->second.get();
588 result.AppendMessageWithFormat (" %s -- %s \n", var->GetName(), var->GetHelp());
589 }
590}
591
592// Main entry point into the command_interpreter; this function takes a text
593// line containing a debugger command, with all its flags, options, etc,
594// parses the line and takes the appropriate actions.
595
596bool
Greg Clayton63094e02010-06-23 01:19:29 +0000597CommandInterpreter::HandleCommand
598(
599 const char *command_line,
600 bool add_to_history,
601 CommandReturnObject &result,
602 ExecutionContext *override_context
603)
Chris Lattner24943d22010-06-08 16:52:24 +0000604{
605 // FIXME: there should probably be a mutex to make sure only one thread can
606 // run the interpreter at a time.
607
608 // TODO: this should be a logging channel in lldb.
609// if (DebugSelf())
610// {
611// result.AppendMessageWithFormat ("Processing command: %s\n", command_line);
612// }
613
Greg Clayton63094e02010-06-23 01:19:29 +0000614 m_debugger.UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +0000615
616 if (command_line == NULL || command_line[0] == '\0')
617 {
618 if (m_command_history.empty())
619 {
620 result.AppendError ("empty command");
621 result.SetStatus(eReturnStatusFailed);
622 return false;
623 }
624 else
625 {
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000626 command_line = m_repeat_command.c_str();
627 if (m_repeat_command.empty())
628 {
Jim Ingham767af882010-07-07 03:36:20 +0000629 result.AppendErrorWithFormat("No auto repeat.\n");
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000630 result.SetStatus (eReturnStatusFailed);
631 return false;
632 }
Chris Lattner24943d22010-06-08 16:52:24 +0000633 }
634 add_to_history = false;
635 }
636
637 Args command_args(command_line);
638
639 if (command_args.GetArgumentCount() > 0)
640 {
641 const char *command_cstr = command_args.GetArgumentAtIndex(0);
642 if (command_cstr)
643 {
644
645 // We're looking up the command object here. So first find an exact match to the
646 // command in the commands.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000647 CommandObject *command_obj = GetCommandObject(command_cstr);
648
649 if (command_obj != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000650 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000651 if (command_obj->IsAlias())
Chris Lattner24943d22010-06-08 16:52:24 +0000652 {
653 BuildAliasCommandArgs (command_obj, command_cstr, command_args, result);
654 if (!result.Succeeded())
655 return false;
656 }
Chris Lattner24943d22010-06-08 16:52:24 +0000657
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000658 if (add_to_history)
659 {
Jim Ingham767af882010-07-07 03:36:20 +0000660 const char *repeat_command = command_obj->GetRepeatCommand(command_args, 0);
661 if (repeat_command != NULL)
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000662 m_repeat_command.assign(repeat_command);
663 else
Jim Ingham767af882010-07-07 03:36:20 +0000664 m_repeat_command.assign(command_line);
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000665
666 m_command_history.push_back (command_line);
667 }
668
669
Chris Lattner24943d22010-06-08 16:52:24 +0000670 if (command_obj->WantsRawCommandString())
671 {
672 const char *stripped_command = ::strstr (command_line, command_cstr);
673 if (stripped_command)
674 {
675 stripped_command += strlen(command_cstr);
676 while (isspace(*stripped_command))
677 ++stripped_command;
Greg Clayton63094e02010-06-23 01:19:29 +0000678 command_obj->ExecuteRawCommandString (*this, stripped_command, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000679 }
680 }
681 else
682 {
Chris Lattner24943d22010-06-08 16:52:24 +0000683 // Remove the command from the args.
684 command_args.Shift();
Greg Clayton63094e02010-06-23 01:19:29 +0000685 command_obj->ExecuteWithOptions (*this, command_args, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000686 }
687 }
688 else
689 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000690 // We didn't find the first command object, so complete the first argument.
Chris Lattner24943d22010-06-08 16:52:24 +0000691 StringList matches;
692 int num_matches;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000693 int cursor_index = 0;
694 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
Jim Ingham802f8b02010-06-30 05:02:46 +0000695 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +0000696 num_matches = HandleCompletionMatches (command_args,
697 cursor_index,
698 cursor_char_position,
699 0,
700 -1,
Jim Ingham802f8b02010-06-30 05:02:46 +0000701 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +0000702 matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000703
704 if (num_matches > 0)
705 {
706 std::string error_msg;
707 error_msg.assign ("ambiguous command '");
708 error_msg.append(command_cstr);
709 error_msg.append ("'.");
710
711 error_msg.append (" Possible completions:");
712 for (int i = 0; i < num_matches; i++)
713 {
714 error_msg.append ("\n\t");
715 error_msg.append (matches.GetStringAtIndex (i));
716 }
717 error_msg.append ("\n");
718 result.AppendRawError (error_msg.c_str(), error_msg.size());
719 }
720 else
721 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_cstr);
722
723 result.SetStatus (eReturnStatusFailed);
724 }
725 }
726 }
727 return result.Succeeded();
728}
729
730int
731CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
732 int &cursor_index,
733 int &cursor_char_position,
734 int match_start_point,
735 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +0000736 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000737 StringList &matches)
738{
739 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000740 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +0000741
742 // For any of the command completions a unique match will be a complete word.
743 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000744
745 if (cursor_index == -1)
746 {
747 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +0000748 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000749 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
750 }
751 else if (cursor_index == 0)
752 {
753 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000754 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000755 num_command_matches = matches.GetSize();
756
757 if (num_command_matches == 1
758 && cmd_obj && cmd_obj->IsMultiwordObject()
759 && matches.GetStringAtIndex(0) != NULL
760 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
761 {
762 look_for_subcommand = true;
763 num_command_matches = 0;
764 matches.DeleteStringAtIndex(0);
765 parsed_line.AppendArgument ("");
766 cursor_index++;
767 cursor_char_position = 0;
768 }
769 }
770
771 if (cursor_index > 0 || look_for_subcommand)
772 {
773 // We are completing further on into a commands arguments, so find the command and tell it
774 // to complete the command.
775 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +0000776 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +0000777 if (command_object == NULL)
778 {
779 return 0;
780 }
781 else
782 {
783 parsed_line.Shift();
784 cursor_index--;
Greg Clayton63094e02010-06-23 01:19:29 +0000785 num_command_matches = command_object->HandleCompletion (*this,
786 parsed_line,
787 cursor_index,
788 cursor_char_position,
789 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000790 max_return_elements,
791 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000792 matches);
793 }
794 }
795
796 return num_command_matches;
797
798}
799
800int
801CommandInterpreter::HandleCompletion (const char *current_line,
802 const char *cursor,
803 const char *last_char,
804 int match_start_point,
805 int max_return_elements,
806 StringList &matches)
807{
808 // We parse the argument up to the cursor, so the last argument in parsed_line is
809 // the one containing the cursor, and the cursor is after the last character.
810
811 Args parsed_line(current_line, last_char - current_line);
812 Args partial_parsed_line(current_line, cursor - current_line);
813
814 int num_args = partial_parsed_line.GetArgumentCount();
815 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
816 int cursor_char_position;
817
818 if (cursor_index == -1)
819 cursor_char_position = 0;
820 else
821 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
822
823 int num_command_matches;
824
825 matches.Clear();
826
827 // Only max_return_elements == -1 is supported at present:
828 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +0000829 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +0000830 num_command_matches = HandleCompletionMatches (parsed_line,
831 cursor_index,
832 cursor_char_position,
833 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000834 max_return_elements,
835 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +0000836 matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000837
838 if (num_command_matches <= 0)
839 return num_command_matches;
840
841 if (num_args == 0)
842 {
843 // If we got an empty string, insert nothing.
844 matches.InsertStringAtIndex(0, "");
845 }
846 else
847 {
848 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
849 // put an empty string in element 0.
850 std::string command_partial_str;
851 if (cursor_index >= 0)
852 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index), parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
853
854 std::string common_prefix;
855 matches.LongestCommonPrefix (common_prefix);
856 int partial_name_len = command_partial_str.size();
857
858 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +0000859 // Only do this if the completer told us this was a complete word, however...
860 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +0000861 {
862 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
863 if (quote_char != '\0')
864 common_prefix.push_back(quote_char);
865
866 common_prefix.push_back(' ');
867 }
868 common_prefix.erase (0, partial_name_len);
869 matches.InsertStringAtIndex(0, common_prefix.c_str());
870 }
871 return num_command_matches;
872}
873
Chris Lattner24943d22010-06-08 16:52:24 +0000874const Args *
875CommandInterpreter::GetProgramArguments ()
876{
877 if (! HasInterpreterVariables())
878 return NULL;
879
880 VariableMap::const_iterator pos = m_variables.find("run-args");
881 if (pos == m_variables.end())
882 return NULL;
883
884 StateVariable *var = pos->second.get();
885
886 if (var)
887 return &var->GetArgs();
888 return NULL;
889}
890
891const Args *
892CommandInterpreter::GetEnvironmentVariables ()
893{
894 if (! HasInterpreterVariables())
895 return NULL;
896
897 VariableMap::const_iterator pos = m_variables.find("env-vars");
898 if (pos == m_variables.end())
899 return NULL;
900
901 StateVariable *var = pos->second.get();
902 if (var)
903 return &var->GetArgs();
904 return NULL;
905}
906
907
908CommandInterpreter::~CommandInterpreter ()
909{
910}
911
912const char *
913CommandInterpreter::GetPrompt ()
914{
915 VariableMap::iterator pos;
916
917 if (! HasInterpreterVariables())
918 return NULL;
919
920 pos = m_variables.find("prompt");
921 if (pos == m_variables.end())
922 return NULL;
923
924 StateVariable *var = pos->second.get();
925
926 return ((char *) var->GetStringValue());
927}
928
929void
930CommandInterpreter::SetPrompt (const char *new_prompt)
931{
932 VariableMap::iterator pos;
933 CommandReturnObject result;
934
935 if (! HasInterpreterVariables())
936 return;
937
938 pos = m_variables.find ("prompt");
939 if (pos == m_variables.end())
940 return;
941
942 StateVariable *var = pos->second.get();
943
944 if (var->VerifyValue (this, (void *) new_prompt, result))
945 var->SetStringValue (new_prompt);
946}
947
948void
949CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
950{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000951 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +0000952
953 if (cmd_obj_sp != NULL)
954 {
955 CommandObject *cmd_obj = cmd_obj_sp.get();
956 if (cmd_obj->IsCrossRefObject ())
957 cmd_obj->AddObject (object_type);
958 }
959}
960
961void
962CommandInterpreter::SetScriptLanguage (ScriptLanguage lang)
963{
964 m_script_language = lang;
965}
966
Chris Lattner24943d22010-06-08 16:52:24 +0000967OptionArgVectorSP
968CommandInterpreter::GetAliasOptions (const char *alias_name)
969{
970 OptionArgMap::iterator pos;
971 OptionArgVectorSP ret_val;
972
973 std::string alias (alias_name);
974
975 if (HasAliasOptions())
976 {
977 pos = m_alias_options.find (alias);
978 if (pos != m_alias_options.end())
979 ret_val = pos->second;
980 }
981
982 return ret_val;
983}
984
985void
986CommandInterpreter::RemoveAliasOptions (const char *alias_name)
987{
988 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
989 if (pos != m_alias_options.end())
990 {
991 m_alias_options.erase (pos);
992 }
993}
994
995void
996CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
997{
998 m_alias_options[alias_name] = option_arg_vector_sp;
999}
1000
1001bool
1002CommandInterpreter::HasCommands ()
1003{
1004 return (!m_command_dict.empty());
1005}
1006
1007bool
1008CommandInterpreter::HasAliases ()
1009{
1010 return (!m_alias_dict.empty());
1011}
1012
1013bool
1014CommandInterpreter::HasUserCommands ()
1015{
1016 return (!m_user_dict.empty());
1017}
1018
1019bool
1020CommandInterpreter::HasAliasOptions ()
1021{
1022 return (!m_alias_options.empty());
1023}
1024
1025bool
1026CommandInterpreter::HasInterpreterVariables ()
1027{
1028 return (!m_variables.empty());
1029}
1030
1031void
1032CommandInterpreter::BuildAliasCommandArgs
1033(
1034 CommandObject *alias_cmd_obj,
1035 const char *alias_name,
1036 Args &cmd_args,
1037 CommandReturnObject &result
1038)
1039{
1040 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1041
1042 if (option_arg_vector_sp.get())
1043 {
1044 // Make sure that the alias name is the 0th element in cmd_args
1045 std::string alias_name_str = alias_name;
1046 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1047 cmd_args.Unshift (alias_name);
1048
1049 Args new_args (alias_cmd_obj->GetCommandName());
1050 if (new_args.GetArgumentCount() == 2)
1051 new_args.Shift();
1052
1053 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1054 int old_size = cmd_args.GetArgumentCount();
1055 int *used = (int *) malloc ((old_size + 1) * sizeof (int));
1056
1057 memset (used, 0, (old_size + 1) * sizeof (int));
1058 used[0] = 1;
1059
1060 for (int i = 0; i < option_arg_vector->size(); ++i)
1061 {
1062 OptionArgPair option_pair = (*option_arg_vector)[i];
1063 std::string option = option_pair.first;
1064 std::string value = option_pair.second;
1065 if (option.compare ("<argument>") == 0)
1066 new_args.AppendArgument (value.c_str());
1067 else
1068 {
1069 new_args.AppendArgument (option.c_str());
1070 if (value.compare ("<no-argument>") != 0)
1071 {
1072 int index = GetOptionArgumentPosition (value.c_str());
1073 if (index == 0)
1074 // value was NOT a positional argument; must be a real value
1075 new_args.AppendArgument (value.c_str());
1076 else if (index >= cmd_args.GetArgumentCount())
1077 {
1078 result.AppendErrorWithFormat
1079 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1080 index);
1081 result.SetStatus (eReturnStatusFailed);
1082 return;
1083 }
1084 else
1085 {
1086 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
1087 used[index] = 1;
1088 }
1089 }
1090 }
1091 }
1092
1093 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1094 {
1095 if (!used[j])
1096 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1097 }
1098
1099 cmd_args.Clear();
1100 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1101 }
1102 else
1103 {
1104 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1105 // This alias was not created with any options; nothing further needs to be done.
1106 return;
1107 }
1108
1109 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1110 return;
1111}
1112
1113
1114int
1115CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1116{
1117 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1118 // of zero.
1119
1120 char *cptr = (char *) in_string;
1121
1122 // Does it start with '%'
1123 if (cptr[0] == '%')
1124 {
1125 ++cptr;
1126
1127 // Is the rest of it entirely digits?
1128 if (isdigit (cptr[0]))
1129 {
1130 const char *start = cptr;
1131 while (isdigit (cptr[0]))
1132 ++cptr;
1133
1134 // We've gotten to the end of the digits; are we at the end of the string?
1135 if (cptr[0] == '\0')
1136 position = atoi (start);
1137 }
1138 }
1139
1140 return position;
1141}
1142
1143void
1144CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1145{
1146 const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit";
1147 FileSpec init_file (init_file_path);
1148 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
1149 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
1150
1151 if (init_file.Exists())
1152 {
1153 char path[PATH_MAX];
1154 init_file.GetPath(path, sizeof(path));
1155 StreamString source_command;
1156 source_command.Printf ("source '%s'", path);
1157 HandleCommand (source_command.GetData(), false, result);
1158 }
1159 else
1160 {
1161 // nothing to be done if the file doesn't exist
1162 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1163 }
1164}
1165
1166ScriptInterpreter *
1167CommandInterpreter::GetScriptInterpreter ()
1168{
Greg Clayton63094e02010-06-23 01:19:29 +00001169 CommandObject::CommandMap::iterator pos;
1170
1171 pos = m_command_dict.find ("script");
1172 if (pos != m_command_dict.end())
Chris Lattner24943d22010-06-08 16:52:24 +00001173 {
Greg Clayton63094e02010-06-23 01:19:29 +00001174 CommandObject *script_cmd_obj = pos->second.get();
1175 return ((CommandObjectScript *) script_cmd_obj)->GetInterpreter (*this);
Chris Lattner24943d22010-06-08 16:52:24 +00001176 }
Greg Clayton63094e02010-06-23 01:19:29 +00001177 return NULL;
Chris Lattner24943d22010-06-08 16:52:24 +00001178}
1179
1180
1181
1182bool
1183CommandInterpreter::GetSynchronous ()
1184{
1185 return m_synchronous_execution;
1186}
1187
1188void
1189CommandInterpreter::SetSynchronous (bool value)
1190{
1191 static bool value_set_once = false;
1192 if (!value_set_once)
1193 {
1194 value_set_once = true;
1195 m_synchronous_execution = value;
1196 }
1197}
1198
1199void
1200CommandInterpreter::OutputFormattedHelpText (Stream &strm,
1201 const char *word_text,
1202 const char *separator,
1203 const char *help_text,
1204 uint32_t max_word_len)
1205{
1206 StateVariable *var = GetStateVariable ("term-width");
1207 int max_columns = var->GetIntValue();
1208 // Sanity check max_columns, to cope with emacs shell mode with TERM=dumb
1209 // (0 rows; 0 columns;).
1210 if (max_columns <= 0) max_columns = 80;
1211
1212 int indent_size = max_word_len + strlen (separator) + 2;
1213
1214 strm.IndentMore (indent_size);
1215
1216 int len = indent_size + strlen (help_text) + 1;
1217 char *text = (char *) malloc (len);
1218 sprintf (text, "%-*s %s %s", max_word_len, word_text, separator, help_text);
1219 if (text[len - 1] == '\n')
1220 text[--len] = '\0';
1221
1222 if (len < max_columns)
1223 {
1224 // Output it as a single line.
1225 strm.Printf ("%s", text);
1226 }
1227 else
1228 {
1229 // We need to break it up into multiple lines.
1230 bool first_line = true;
1231 int text_width;
1232 int start = 0;
1233 int end = start;
1234 int final_end = strlen (text);
1235 int sub_len;
1236
1237 while (end < final_end)
1238 {
1239 if (first_line)
1240 text_width = max_columns - 1;
1241 else
1242 text_width = max_columns - indent_size - 1;
1243
1244 // Don't start the 'text' on a space, since we're already outputting the indentation.
1245 if (!first_line)
1246 {
1247 while ((start < final_end) && (text[start] == ' '))
1248 start++;
1249 }
1250
1251 end = start + text_width;
1252 if (end > final_end)
1253 end = final_end;
1254 else
1255 {
1256 // If we're not at the end of the text, make sure we break the line on white space.
1257 while (end > start
1258 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
1259 end--;
1260 }
1261
1262 sub_len = end - start;
1263 if (start != 0)
1264 strm.EOL();
1265 if (!first_line)
1266 strm.Indent();
1267 else
1268 first_line = false;
1269 assert (start <= final_end);
1270 assert (start + sub_len <= final_end);
1271 if (sub_len > 0)
1272 strm.Write (text + start, sub_len);
1273 start = end + 1;
1274 }
1275 }
1276 strm.EOL();
1277 strm.IndentLess(indent_size);
1278 free (text);
1279}
1280
1281void
1282CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
1283 StringList &commands_found, StringList &commands_help)
1284{
1285 CommandObject::CommandMap::const_iterator pos;
1286 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
1287 CommandObject *sub_cmd_obj;
1288
1289 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
1290 {
1291 const char * command_name = pos->first.c_str();
1292 sub_cmd_obj = pos->second.get();
1293 StreamString complete_command_name;
1294
1295 complete_command_name.Printf ("%s %s", prefix, command_name);
1296
1297 if (sub_cmd_obj->HelpTextContainsWord (search_word))
1298 {
1299 commands_found.AppendString (complete_command_name.GetData());
1300 commands_help.AppendString (sub_cmd_obj->GetHelp());
1301 }
1302
1303 if (sub_cmd_obj->IsMultiwordObject())
1304 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
1305 commands_help);
1306 }
1307
1308}
1309
1310void
1311CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
1312 StringList &commands_help)
1313{
1314 CommandObject::CommandMap::const_iterator pos;
1315
1316 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1317 {
1318 const char *command_name = pos->first.c_str();
1319 CommandObject *cmd_obj = pos->second.get();
1320
1321 if (cmd_obj->HelpTextContainsWord (search_word))
1322 {
1323 commands_found.AppendString (command_name);
1324 commands_help.AppendString (cmd_obj->GetHelp());
1325 }
1326
1327 if (cmd_obj->IsMultiwordObject())
1328 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
1329
1330 }
1331}