blob: eaf886f76ad239321ae3927ff013cfb968295d3a [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"
Sean Callanan65dafa82010-08-27 01:01:44 +000019//#include "../Commands/CommandObjectCall.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000020#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));
Sean Callanan65dafa82010-08-27 01:01:44 +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
Greg Clayton65124ea2010-08-26 22:05:43 +0000497size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000498CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
499{
500 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000501 CommandObject::CommandMap::const_iterator end = dict.end();
502 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000503
Greg Clayton65124ea2010-08-26 22:05:43 +0000504 for (pos = dict.begin(); pos != end; ++pos)
505 {
506 size_t len = pos->first.size();
507 if (max_len < len)
508 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000509 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000510 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000511}
512
513void
514CommandInterpreter::GetHelp (CommandReturnObject &result)
515{
516 CommandObject::CommandMap::const_iterator pos;
517 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
518 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000519 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000520
521 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
522 {
523 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
524 max_len);
525 }
526 result.AppendMessage("");
527
528 if (m_alias_dict.size() > 0)
529 {
Sean Callanana3aff732010-08-09 18:50:15 +0000530 result.AppendMessage("The following is a list of your current command abbreviations (see 'commands alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000531 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000532 max_len = FindLongestCommandWord (m_alias_dict);
533
Chris Lattner24943d22010-06-08 16:52:24 +0000534 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
535 {
536 StreamString sstr;
537 StreamString translation_and_help;
538 std::string entry_name = pos->first;
539 std::string second_entry = pos->second.get()->GetCommandName();
540 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
541
542 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
543 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
544 translation_and_help.GetData(), max_len);
545 }
546 result.AppendMessage("");
547 }
548
549 if (m_user_dict.size() > 0)
550 {
551 result.AppendMessage ("The following is a list of your current user-defined commands:");
552 result.AppendMessage("");
553 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
554 {
555 result.AppendMessageWithFormat ("%s -- %s\n", pos->first.c_str(), pos->second->GetHelp());
556 }
557 result.AppendMessage("");
558 }
559
560 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
561}
562
563void
564CommandInterpreter::ShowVariableValues (CommandReturnObject &result)
565{
566 result.AppendMessage ("Below is a list of all the debugger setting variables and their values:");
567
568 for (VariableMap::const_iterator pos = m_variables.begin(); pos != m_variables.end(); ++pos)
569 {
570 StateVariable *var = pos->second.get();
571 var->AppendVariableInformation (result);
572 }
573}
574
575void
576CommandInterpreter::ShowVariableHelp (CommandReturnObject &result)
577{
578 result.AppendMessage ("Below is a list of all the internal debugger variables that are settable:");
579 for (VariableMap::const_iterator pos = m_variables.begin(); pos != m_variables.end(); ++pos)
580 {
581 StateVariable *var = pos->second.get();
582 result.AppendMessageWithFormat (" %s -- %s \n", var->GetName(), var->GetHelp());
583 }
584}
585
586// Main entry point into the command_interpreter; this function takes a text
587// line containing a debugger command, with all its flags, options, etc,
588// parses the line and takes the appropriate actions.
589
590bool
Greg Clayton63094e02010-06-23 01:19:29 +0000591CommandInterpreter::HandleCommand
592(
593 const char *command_line,
594 bool add_to_history,
595 CommandReturnObject &result,
596 ExecutionContext *override_context
597)
Chris Lattner24943d22010-06-08 16:52:24 +0000598{
599 // FIXME: there should probably be a mutex to make sure only one thread can
600 // run the interpreter at a time.
601
602 // TODO: this should be a logging channel in lldb.
603// if (DebugSelf())
604// {
605// result.AppendMessageWithFormat ("Processing command: %s\n", command_line);
606// }
607
Greg Clayton63094e02010-06-23 01:19:29 +0000608 m_debugger.UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +0000609
610 if (command_line == NULL || command_line[0] == '\0')
611 {
612 if (m_command_history.empty())
613 {
614 result.AppendError ("empty command");
615 result.SetStatus(eReturnStatusFailed);
616 return false;
617 }
618 else
619 {
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000620 command_line = m_repeat_command.c_str();
621 if (m_repeat_command.empty())
622 {
Jim Ingham767af882010-07-07 03:36:20 +0000623 result.AppendErrorWithFormat("No auto repeat.\n");
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000624 result.SetStatus (eReturnStatusFailed);
625 return false;
626 }
Chris Lattner24943d22010-06-08 16:52:24 +0000627 }
628 add_to_history = false;
629 }
630
631 Args command_args(command_line);
632
633 if (command_args.GetArgumentCount() > 0)
634 {
635 const char *command_cstr = command_args.GetArgumentAtIndex(0);
636 if (command_cstr)
637 {
638
639 // We're looking up the command object here. So first find an exact match to the
640 // command in the commands.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000641 CommandObject *command_obj = GetCommandObject(command_cstr);
642
643 if (command_obj != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000644 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000645 if (command_obj->IsAlias())
Chris Lattner24943d22010-06-08 16:52:24 +0000646 {
647 BuildAliasCommandArgs (command_obj, command_cstr, command_args, result);
648 if (!result.Succeeded())
649 return false;
650 }
Chris Lattner24943d22010-06-08 16:52:24 +0000651
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000652 if (add_to_history)
653 {
Jim Ingham767af882010-07-07 03:36:20 +0000654 const char *repeat_command = command_obj->GetRepeatCommand(command_args, 0);
655 if (repeat_command != NULL)
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000656 m_repeat_command.assign(repeat_command);
657 else
Jim Ingham767af882010-07-07 03:36:20 +0000658 m_repeat_command.assign(command_line);
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000659
660 m_command_history.push_back (command_line);
661 }
662
663
Chris Lattner24943d22010-06-08 16:52:24 +0000664 if (command_obj->WantsRawCommandString())
665 {
666 const char *stripped_command = ::strstr (command_line, command_cstr);
667 if (stripped_command)
668 {
669 stripped_command += strlen(command_cstr);
670 while (isspace(*stripped_command))
671 ++stripped_command;
Greg Clayton63094e02010-06-23 01:19:29 +0000672 command_obj->ExecuteRawCommandString (*this, stripped_command, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000673 }
674 }
675 else
676 {
Chris Lattner24943d22010-06-08 16:52:24 +0000677 // Remove the command from the args.
678 command_args.Shift();
Greg Clayton63094e02010-06-23 01:19:29 +0000679 command_obj->ExecuteWithOptions (*this, command_args, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000680 }
681 }
682 else
683 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000684 // We didn't find the first command object, so complete the first argument.
Chris Lattner24943d22010-06-08 16:52:24 +0000685 StringList matches;
686 int num_matches;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000687 int cursor_index = 0;
688 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
Jim Ingham802f8b02010-06-30 05:02:46 +0000689 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +0000690 num_matches = HandleCompletionMatches (command_args,
691 cursor_index,
692 cursor_char_position,
693 0,
694 -1,
Jim Ingham802f8b02010-06-30 05:02:46 +0000695 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +0000696 matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000697
698 if (num_matches > 0)
699 {
700 std::string error_msg;
701 error_msg.assign ("ambiguous command '");
702 error_msg.append(command_cstr);
703 error_msg.append ("'.");
704
705 error_msg.append (" Possible completions:");
706 for (int i = 0; i < num_matches; i++)
707 {
708 error_msg.append ("\n\t");
709 error_msg.append (matches.GetStringAtIndex (i));
710 }
711 error_msg.append ("\n");
712 result.AppendRawError (error_msg.c_str(), error_msg.size());
713 }
714 else
715 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_cstr);
716
717 result.SetStatus (eReturnStatusFailed);
718 }
719 }
720 }
721 return result.Succeeded();
722}
723
724int
725CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
726 int &cursor_index,
727 int &cursor_char_position,
728 int match_start_point,
729 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +0000730 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000731 StringList &matches)
732{
733 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000734 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +0000735
736 // For any of the command completions a unique match will be a complete word.
737 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000738
739 if (cursor_index == -1)
740 {
741 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +0000742 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000743 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
744 }
745 else if (cursor_index == 0)
746 {
747 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000748 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000749 num_command_matches = matches.GetSize();
750
751 if (num_command_matches == 1
752 && cmd_obj && cmd_obj->IsMultiwordObject()
753 && matches.GetStringAtIndex(0) != NULL
754 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
755 {
756 look_for_subcommand = true;
757 num_command_matches = 0;
758 matches.DeleteStringAtIndex(0);
759 parsed_line.AppendArgument ("");
760 cursor_index++;
761 cursor_char_position = 0;
762 }
763 }
764
765 if (cursor_index > 0 || look_for_subcommand)
766 {
767 // We are completing further on into a commands arguments, so find the command and tell it
768 // to complete the command.
769 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +0000770 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +0000771 if (command_object == NULL)
772 {
773 return 0;
774 }
775 else
776 {
777 parsed_line.Shift();
778 cursor_index--;
Greg Clayton63094e02010-06-23 01:19:29 +0000779 num_command_matches = command_object->HandleCompletion (*this,
780 parsed_line,
781 cursor_index,
782 cursor_char_position,
783 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000784 max_return_elements,
785 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000786 matches);
787 }
788 }
789
790 return num_command_matches;
791
792}
793
794int
795CommandInterpreter::HandleCompletion (const char *current_line,
796 const char *cursor,
797 const char *last_char,
798 int match_start_point,
799 int max_return_elements,
800 StringList &matches)
801{
802 // We parse the argument up to the cursor, so the last argument in parsed_line is
803 // the one containing the cursor, and the cursor is after the last character.
804
805 Args parsed_line(current_line, last_char - current_line);
806 Args partial_parsed_line(current_line, cursor - current_line);
807
808 int num_args = partial_parsed_line.GetArgumentCount();
809 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
810 int cursor_char_position;
811
812 if (cursor_index == -1)
813 cursor_char_position = 0;
814 else
815 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
816
817 int num_command_matches;
818
819 matches.Clear();
820
821 // Only max_return_elements == -1 is supported at present:
822 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +0000823 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +0000824 num_command_matches = HandleCompletionMatches (parsed_line,
825 cursor_index,
826 cursor_char_position,
827 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000828 max_return_elements,
829 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +0000830 matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000831
832 if (num_command_matches <= 0)
833 return num_command_matches;
834
835 if (num_args == 0)
836 {
837 // If we got an empty string, insert nothing.
838 matches.InsertStringAtIndex(0, "");
839 }
840 else
841 {
842 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
843 // put an empty string in element 0.
844 std::string command_partial_str;
845 if (cursor_index >= 0)
846 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index), parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
847
848 std::string common_prefix;
849 matches.LongestCommonPrefix (common_prefix);
850 int partial_name_len = command_partial_str.size();
851
852 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +0000853 // Only do this if the completer told us this was a complete word, however...
854 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +0000855 {
856 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
857 if (quote_char != '\0')
858 common_prefix.push_back(quote_char);
859
860 common_prefix.push_back(' ');
861 }
862 common_prefix.erase (0, partial_name_len);
863 matches.InsertStringAtIndex(0, common_prefix.c_str());
864 }
865 return num_command_matches;
866}
867
Chris Lattner24943d22010-06-08 16:52:24 +0000868const Args *
869CommandInterpreter::GetProgramArguments ()
870{
871 if (! HasInterpreterVariables())
872 return NULL;
873
874 VariableMap::const_iterator pos = m_variables.find("run-args");
875 if (pos == m_variables.end())
876 return NULL;
877
878 StateVariable *var = pos->second.get();
879
880 if (var)
881 return &var->GetArgs();
882 return NULL;
883}
884
885const Args *
886CommandInterpreter::GetEnvironmentVariables ()
887{
888 if (! HasInterpreterVariables())
889 return NULL;
890
891 VariableMap::const_iterator pos = m_variables.find("env-vars");
892 if (pos == m_variables.end())
893 return NULL;
894
895 StateVariable *var = pos->second.get();
896 if (var)
897 return &var->GetArgs();
898 return NULL;
899}
900
901
902CommandInterpreter::~CommandInterpreter ()
903{
904}
905
906const char *
907CommandInterpreter::GetPrompt ()
908{
909 VariableMap::iterator pos;
910
911 if (! HasInterpreterVariables())
912 return NULL;
913
914 pos = m_variables.find("prompt");
915 if (pos == m_variables.end())
916 return NULL;
917
918 StateVariable *var = pos->second.get();
919
920 return ((char *) var->GetStringValue());
921}
922
923void
924CommandInterpreter::SetPrompt (const char *new_prompt)
925{
926 VariableMap::iterator pos;
927 CommandReturnObject result;
928
929 if (! HasInterpreterVariables())
930 return;
931
932 pos = m_variables.find ("prompt");
933 if (pos == m_variables.end())
934 return;
935
936 StateVariable *var = pos->second.get();
937
938 if (var->VerifyValue (this, (void *) new_prompt, result))
939 var->SetStringValue (new_prompt);
940}
941
942void
943CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
944{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000945 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +0000946
947 if (cmd_obj_sp != NULL)
948 {
949 CommandObject *cmd_obj = cmd_obj_sp.get();
950 if (cmd_obj->IsCrossRefObject ())
951 cmd_obj->AddObject (object_type);
952 }
953}
954
955void
956CommandInterpreter::SetScriptLanguage (ScriptLanguage lang)
957{
958 m_script_language = lang;
959}
960
Chris Lattner24943d22010-06-08 16:52:24 +0000961OptionArgVectorSP
962CommandInterpreter::GetAliasOptions (const char *alias_name)
963{
964 OptionArgMap::iterator pos;
965 OptionArgVectorSP ret_val;
966
967 std::string alias (alias_name);
968
969 if (HasAliasOptions())
970 {
971 pos = m_alias_options.find (alias);
972 if (pos != m_alias_options.end())
973 ret_val = pos->second;
974 }
975
976 return ret_val;
977}
978
979void
980CommandInterpreter::RemoveAliasOptions (const char *alias_name)
981{
982 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
983 if (pos != m_alias_options.end())
984 {
985 m_alias_options.erase (pos);
986 }
987}
988
989void
990CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
991{
992 m_alias_options[alias_name] = option_arg_vector_sp;
993}
994
995bool
996CommandInterpreter::HasCommands ()
997{
998 return (!m_command_dict.empty());
999}
1000
1001bool
1002CommandInterpreter::HasAliases ()
1003{
1004 return (!m_alias_dict.empty());
1005}
1006
1007bool
1008CommandInterpreter::HasUserCommands ()
1009{
1010 return (!m_user_dict.empty());
1011}
1012
1013bool
1014CommandInterpreter::HasAliasOptions ()
1015{
1016 return (!m_alias_options.empty());
1017}
1018
1019bool
1020CommandInterpreter::HasInterpreterVariables ()
1021{
1022 return (!m_variables.empty());
1023}
1024
1025void
1026CommandInterpreter::BuildAliasCommandArgs
1027(
1028 CommandObject *alias_cmd_obj,
1029 const char *alias_name,
1030 Args &cmd_args,
1031 CommandReturnObject &result
1032)
1033{
1034 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1035
1036 if (option_arg_vector_sp.get())
1037 {
1038 // Make sure that the alias name is the 0th element in cmd_args
1039 std::string alias_name_str = alias_name;
1040 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1041 cmd_args.Unshift (alias_name);
1042
1043 Args new_args (alias_cmd_obj->GetCommandName());
1044 if (new_args.GetArgumentCount() == 2)
1045 new_args.Shift();
1046
1047 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1048 int old_size = cmd_args.GetArgumentCount();
1049 int *used = (int *) malloc ((old_size + 1) * sizeof (int));
1050
1051 memset (used, 0, (old_size + 1) * sizeof (int));
1052 used[0] = 1;
1053
1054 for (int i = 0; i < option_arg_vector->size(); ++i)
1055 {
1056 OptionArgPair option_pair = (*option_arg_vector)[i];
1057 std::string option = option_pair.first;
1058 std::string value = option_pair.second;
1059 if (option.compare ("<argument>") == 0)
1060 new_args.AppendArgument (value.c_str());
1061 else
1062 {
1063 new_args.AppendArgument (option.c_str());
1064 if (value.compare ("<no-argument>") != 0)
1065 {
1066 int index = GetOptionArgumentPosition (value.c_str());
1067 if (index == 0)
1068 // value was NOT a positional argument; must be a real value
1069 new_args.AppendArgument (value.c_str());
1070 else if (index >= cmd_args.GetArgumentCount())
1071 {
1072 result.AppendErrorWithFormat
1073 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1074 index);
1075 result.SetStatus (eReturnStatusFailed);
1076 return;
1077 }
1078 else
1079 {
1080 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
1081 used[index] = 1;
1082 }
1083 }
1084 }
1085 }
1086
1087 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1088 {
1089 if (!used[j])
1090 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1091 }
1092
1093 cmd_args.Clear();
1094 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1095 }
1096 else
1097 {
1098 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1099 // This alias was not created with any options; nothing further needs to be done.
1100 return;
1101 }
1102
1103 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1104 return;
1105}
1106
1107
1108int
1109CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1110{
1111 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1112 // of zero.
1113
1114 char *cptr = (char *) in_string;
1115
1116 // Does it start with '%'
1117 if (cptr[0] == '%')
1118 {
1119 ++cptr;
1120
1121 // Is the rest of it entirely digits?
1122 if (isdigit (cptr[0]))
1123 {
1124 const char *start = cptr;
1125 while (isdigit (cptr[0]))
1126 ++cptr;
1127
1128 // We've gotten to the end of the digits; are we at the end of the string?
1129 if (cptr[0] == '\0')
1130 position = atoi (start);
1131 }
1132 }
1133
1134 return position;
1135}
1136
1137void
1138CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1139{
1140 const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit";
1141 FileSpec init_file (init_file_path);
1142 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
1143 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
1144
1145 if (init_file.Exists())
1146 {
1147 char path[PATH_MAX];
1148 init_file.GetPath(path, sizeof(path));
1149 StreamString source_command;
Johnny Chen7c984242010-07-28 21:16:11 +00001150 source_command.Printf ("command source '%s'", path);
Chris Lattner24943d22010-06-08 16:52:24 +00001151 HandleCommand (source_command.GetData(), false, result);
1152 }
1153 else
1154 {
1155 // nothing to be done if the file doesn't exist
1156 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1157 }
1158}
1159
1160ScriptInterpreter *
1161CommandInterpreter::GetScriptInterpreter ()
1162{
Greg Clayton63094e02010-06-23 01:19:29 +00001163 CommandObject::CommandMap::iterator pos;
1164
1165 pos = m_command_dict.find ("script");
1166 if (pos != m_command_dict.end())
Chris Lattner24943d22010-06-08 16:52:24 +00001167 {
Greg Clayton63094e02010-06-23 01:19:29 +00001168 CommandObject *script_cmd_obj = pos->second.get();
1169 return ((CommandObjectScript *) script_cmd_obj)->GetInterpreter (*this);
Chris Lattner24943d22010-06-08 16:52:24 +00001170 }
Greg Clayton63094e02010-06-23 01:19:29 +00001171 return NULL;
Chris Lattner24943d22010-06-08 16:52:24 +00001172}
1173
1174
1175
1176bool
1177CommandInterpreter::GetSynchronous ()
1178{
1179 return m_synchronous_execution;
1180}
1181
1182void
1183CommandInterpreter::SetSynchronous (bool value)
1184{
1185 static bool value_set_once = false;
1186 if (!value_set_once)
1187 {
1188 value_set_once = true;
1189 m_synchronous_execution = value;
1190 }
1191}
1192
1193void
1194CommandInterpreter::OutputFormattedHelpText (Stream &strm,
1195 const char *word_text,
1196 const char *separator,
1197 const char *help_text,
1198 uint32_t max_word_len)
1199{
1200 StateVariable *var = GetStateVariable ("term-width");
1201 int max_columns = var->GetIntValue();
1202 // Sanity check max_columns, to cope with emacs shell mode with TERM=dumb
1203 // (0 rows; 0 columns;).
1204 if (max_columns <= 0) max_columns = 80;
1205
1206 int indent_size = max_word_len + strlen (separator) + 2;
1207
1208 strm.IndentMore (indent_size);
1209
1210 int len = indent_size + strlen (help_text) + 1;
1211 char *text = (char *) malloc (len);
1212 sprintf (text, "%-*s %s %s", max_word_len, word_text, separator, help_text);
1213 if (text[len - 1] == '\n')
1214 text[--len] = '\0';
1215
1216 if (len < max_columns)
1217 {
1218 // Output it as a single line.
1219 strm.Printf ("%s", text);
1220 }
1221 else
1222 {
1223 // We need to break it up into multiple lines.
1224 bool first_line = true;
1225 int text_width;
1226 int start = 0;
1227 int end = start;
1228 int final_end = strlen (text);
1229 int sub_len;
1230
1231 while (end < final_end)
1232 {
1233 if (first_line)
1234 text_width = max_columns - 1;
1235 else
1236 text_width = max_columns - indent_size - 1;
1237
1238 // Don't start the 'text' on a space, since we're already outputting the indentation.
1239 if (!first_line)
1240 {
1241 while ((start < final_end) && (text[start] == ' '))
1242 start++;
1243 }
1244
1245 end = start + text_width;
1246 if (end > final_end)
1247 end = final_end;
1248 else
1249 {
1250 // If we're not at the end of the text, make sure we break the line on white space.
1251 while (end > start
1252 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
1253 end--;
1254 }
1255
1256 sub_len = end - start;
1257 if (start != 0)
1258 strm.EOL();
1259 if (!first_line)
1260 strm.Indent();
1261 else
1262 first_line = false;
1263 assert (start <= final_end);
1264 assert (start + sub_len <= final_end);
1265 if (sub_len > 0)
1266 strm.Write (text + start, sub_len);
1267 start = end + 1;
1268 }
1269 }
1270 strm.EOL();
1271 strm.IndentLess(indent_size);
1272 free (text);
1273}
1274
1275void
1276CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
1277 StringList &commands_found, StringList &commands_help)
1278{
1279 CommandObject::CommandMap::const_iterator pos;
1280 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
1281 CommandObject *sub_cmd_obj;
1282
1283 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
1284 {
1285 const char * command_name = pos->first.c_str();
1286 sub_cmd_obj = pos->second.get();
1287 StreamString complete_command_name;
1288
1289 complete_command_name.Printf ("%s %s", prefix, command_name);
1290
1291 if (sub_cmd_obj->HelpTextContainsWord (search_word))
1292 {
1293 commands_found.AppendString (complete_command_name.GetData());
1294 commands_help.AppendString (sub_cmd_obj->GetHelp());
1295 }
1296
1297 if (sub_cmd_obj->IsMultiwordObject())
1298 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
1299 commands_help);
1300 }
1301
1302}
1303
1304void
1305CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
1306 StringList &commands_help)
1307{
1308 CommandObject::CommandMap::const_iterator pos;
1309
1310 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1311 {
1312 const char *command_name = pos->first.c_str();
1313 CommandObject *cmd_obj = pos->second.get();
1314
1315 if (cmd_obj->HelpTextContainsWord (search_word))
1316 {
1317 commands_found.AppendString (command_name);
1318 commands_help.AppendString (cmd_obj->GetHelp());
1319 }
1320
1321 if (cmd_obj->IsMultiwordObject())
1322 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
1323
1324 }
1325}