blob: f127fde251fcecb83fe1d14d3f5bdc23baadb0b5 [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
Greg Clayton452bf612010-08-31 18:35:14 +0000164 m_variables["disable-aslr"] =
165 StateVariableSP (new StateVariable ("disable-aslr",
166 1,
167 "Disable Address Space Layout Randomization (ASLR)."));
168
Chris Lattner24943d22010-06-08 16:52:24 +0000169}
170
171const char *
172CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
173{
174 // This function has not yet been implemented.
175
176 // Look for any embedded script command
177 // If found,
178 // get interpreter object from the command dictionary,
179 // call execute_one_command on it,
180 // get the results as a string,
181 // substitute that string for current stuff.
182
183 return arg;
184}
185
186
187void
188CommandInterpreter::LoadCommandDictionary ()
189{
190 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
191
192 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
193 //
194 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
195 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
196 // the cross-referencing stuff) are created!!!
197 //
198 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
199
200
201 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
202 // are created. This is so that when another command is created that needs to go into a crossref object,
203 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
204 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
205
Greg Clayton63094e02010-06-23 01:19:29 +0000206 m_command_dict["select"] = CommandObjectSP (new CommandObjectSelect ());
207 m_command_dict["info"] = CommandObjectSP (new CommandObjectInfo ());
208 m_command_dict["delete"] = CommandObjectSP (new CommandObjectDelete ());
Chris Lattner24943d22010-06-08 16:52:24 +0000209
210 // Non-CommandObjectCrossref commands can now be created.
211
Chris Lattner24943d22010-06-08 16:52:24 +0000212 m_command_dict["append"] = CommandObjectSP (new CommandObjectAppend ());
213 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos ());
Greg Clayton63094e02010-06-23 01:19:29 +0000214 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Sean Callanan65dafa82010-08-27 01:01:44 +0000215 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall ());
Jim Ingham767af882010-07-07 03:36:20 +0000216 m_command_dict["commands"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000217 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble ());
218 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression ());
219 m_command_dict["file"] = CommandObjectSP (new CommandObjectFile ());
Greg Clayton63094e02010-06-23 01:19:29 +0000220 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000221 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp ());
Greg Clayton63094e02010-06-23 01:19:29 +0000222 m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
223 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
224 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
225 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000226 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit ());
Greg Clayton63094e02010-06-23 01:19:29 +0000227 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000228 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (m_script_language));
229 m_command_dict["set"] = CommandObjectSP (new CommandObjectSet ());
230 m_command_dict["settings"] = CommandObjectSP (new CommandObjectSettings ());
231 m_command_dict["show"] = CommandObjectSP (new CommandObjectShow ());
Jim Ingham767af882010-07-07 03:36:20 +0000232 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000233 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
234 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000235 m_command_dict["variable"] = CommandObjectSP (new CommandObjectVariable (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000236
237 std::auto_ptr<CommandObjectRegexCommand>
238 break_regex_cmd_ap(new CommandObjectRegexCommand ("regexp-break",
239 "Smart breakpoint command (using regular expressions).",
240 "regexp-break [<file>:<line>]\nregexp-break [<address>]\nregexp-break <...>", 2));
241 if (break_regex_cmd_ap.get())
242 {
243 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
244 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
245 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
246 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list") &&
247 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
248 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
249 {
250 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
251 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
252 }
253 }
254}
255
256int
257CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
258 StringList &matches)
259{
260 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
261
262 if (include_aliases)
263 {
264 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
265 }
266
267 return matches.GetSize();
268}
269
270CommandObjectSP
271CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
272{
273 CommandObject::CommandMap::iterator pos;
274 CommandObjectSP ret_val;
275
276 std::string cmd(cmd_cstr);
277
278 if (HasCommands())
279 {
280 pos = m_command_dict.find(cmd);
281 if (pos != m_command_dict.end())
282 ret_val = pos->second;
283 }
284
285 if (include_aliases && HasAliases())
286 {
287 pos = m_alias_dict.find(cmd);
288 if (pos != m_alias_dict.end())
289 ret_val = pos->second;
290 }
291
292 if (HasUserCommands())
293 {
294 pos = m_user_dict.find(cmd);
295 if (pos != m_user_dict.end())
296 ret_val = pos->second;
297 }
298
299 if (!exact && ret_val == NULL)
300 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000301 // We will only get into here if we didn't find any exact matches.
302
303 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
304
Chris Lattner24943d22010-06-08 16:52:24 +0000305 StringList local_matches;
306 if (matches == NULL)
307 matches = &local_matches;
308
Jim Inghamd40f8a62010-07-06 22:46:59 +0000309 unsigned int num_cmd_matches = 0;
310 unsigned int num_alias_matches = 0;
311 unsigned int num_user_matches = 0;
312
313 // Look through the command dictionaries one by one, and if we get only one match from any of
314 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
315
Chris Lattner24943d22010-06-08 16:52:24 +0000316 if (HasCommands())
317 {
318 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
319 }
320
321 if (num_cmd_matches == 1)
322 {
323 cmd.assign(matches->GetStringAtIndex(0));
324 pos = m_command_dict.find(cmd);
325 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000326 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000327 }
328
Jim Ingham9a574172010-06-24 20:28:42 +0000329 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000330 {
331 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
332
333 }
334
Jim Inghamd40f8a62010-07-06 22:46:59 +0000335 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000336 {
337 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
338 pos = m_alias_dict.find(cmd);
339 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000340 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000341 }
342
Jim Ingham9a574172010-06-24 20:28:42 +0000343 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000344 {
345 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
346 }
347
Jim Inghamd40f8a62010-07-06 22:46:59 +0000348 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000349 {
350 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
351
352 pos = m_user_dict.find (cmd);
353 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000354 user_match_sp = pos->second;
355 }
356
357 // If we got exactly one match, return that, otherwise return the match list.
358
359 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
360 {
361 if (num_cmd_matches)
362 return real_match_sp;
363 else if (num_alias_matches)
364 return alias_match_sp;
365 else
366 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000367 }
368 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000369 else if (matches && ret_val != NULL)
370 {
371 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000372 }
373
374
375 return ret_val;
376}
377
Jim Inghamd40f8a62010-07-06 22:46:59 +0000378CommandObjectSP
379CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000380{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000381 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
382}
383
384CommandObject *
385CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
386{
387 return GetCommandSPExact (cmd_cstr, include_aliases).get();
388}
389
390CommandObject *
391CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
392{
393 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
394
395 // If we didn't find an exact match to the command string in the commands, look in
396 // the aliases.
397
398 if (command_obj == NULL)
399 {
400 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
401 }
402
403 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
404 // in both the commands and the aliases.
405
406 if (command_obj == NULL)
407 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
408
409 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000410}
411
412bool
413CommandInterpreter::CommandExists (const char *cmd)
414{
415 return m_command_dict.find(cmd) != m_command_dict.end();
416}
417
418bool
419CommandInterpreter::AliasExists (const char *cmd)
420{
421 return m_alias_dict.find(cmd) != m_alias_dict.end();
422}
423
424bool
425CommandInterpreter::UserCommandExists (const char *cmd)
426{
427 return m_user_dict.find(cmd) != m_user_dict.end();
428}
429
430void
431CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
432{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000433 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000434 m_alias_dict[alias_name] = command_obj_sp;
435}
436
437bool
438CommandInterpreter::RemoveAlias (const char *alias_name)
439{
440 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
441 if (pos != m_alias_dict.end())
442 {
443 m_alias_dict.erase(pos);
444 return true;
445 }
446 return false;
447}
448bool
449CommandInterpreter::RemoveUser (const char *alias_name)
450{
451 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
452 if (pos != m_user_dict.end())
453 {
454 m_user_dict.erase(pos);
455 return true;
456 }
457 return false;
458}
459
460StateVariable *
461CommandInterpreter::GetStateVariable(const char *name)
462{
463 VariableMap::const_iterator pos = m_variables.find(name);
464 if (pos != m_variables.end())
465 return pos->second.get();
466 return NULL;
467}
468
469void
470CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
471{
472 help_string.Printf ("'%s", command_name);
473 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
474
475 if (option_arg_vector_sp != NULL)
476 {
477 OptionArgVector *options = option_arg_vector_sp.get();
478 for (int i = 0; i < options->size(); ++i)
479 {
480 OptionArgPair cur_option = (*options)[i];
481 std::string opt = cur_option.first;
482 std::string value = cur_option.second;
483 if (opt.compare("<argument>") == 0)
484 {
485 help_string.Printf (" %s", value.c_str());
486 }
487 else
488 {
489 help_string.Printf (" %s", opt.c_str());
490 if ((value.compare ("<no-argument>") != 0)
491 && (value.compare ("<need-argument") != 0))
492 {
493 help_string.Printf (" %s", value.c_str());
494 }
495 }
496 }
497 }
498
499 help_string.Printf ("'");
500}
501
Greg Clayton65124ea2010-08-26 22:05:43 +0000502size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000503CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
504{
505 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000506 CommandObject::CommandMap::const_iterator end = dict.end();
507 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000508
Greg Clayton65124ea2010-08-26 22:05:43 +0000509 for (pos = dict.begin(); pos != end; ++pos)
510 {
511 size_t len = pos->first.size();
512 if (max_len < len)
513 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000514 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000515 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000516}
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("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000524 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000525
526 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
527 {
528 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
529 max_len);
530 }
531 result.AppendMessage("");
532
533 if (m_alias_dict.size() > 0)
534 {
Sean Callanana3aff732010-08-09 18:50:15 +0000535 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 +0000536 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000537 max_len = FindLongestCommandWord (m_alias_dict);
538
Chris Lattner24943d22010-06-08 16:52:24 +0000539 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
540 {
541 StreamString sstr;
542 StreamString translation_and_help;
543 std::string entry_name = pos->first;
544 std::string second_entry = pos->second.get()->GetCommandName();
545 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
546
547 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
548 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
549 translation_and_help.GetData(), max_len);
550 }
551 result.AppendMessage("");
552 }
553
554 if (m_user_dict.size() > 0)
555 {
556 result.AppendMessage ("The following is a list of your current user-defined commands:");
557 result.AppendMessage("");
558 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
559 {
560 result.AppendMessageWithFormat ("%s -- %s\n", pos->first.c_str(), pos->second->GetHelp());
561 }
562 result.AppendMessage("");
563 }
564
565 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
566}
567
568void
569CommandInterpreter::ShowVariableValues (CommandReturnObject &result)
570{
571 result.AppendMessage ("Below is a list of all the debugger setting variables and their values:");
572
573 for (VariableMap::const_iterator pos = m_variables.begin(); pos != m_variables.end(); ++pos)
574 {
575 StateVariable *var = pos->second.get();
576 var->AppendVariableInformation (result);
577 }
578}
579
580void
581CommandInterpreter::ShowVariableHelp (CommandReturnObject &result)
582{
583 result.AppendMessage ("Below is a list of all the internal debugger variables that are settable:");
584 for (VariableMap::const_iterator pos = m_variables.begin(); pos != m_variables.end(); ++pos)
585 {
586 StateVariable *var = pos->second.get();
587 result.AppendMessageWithFormat (" %s -- %s \n", var->GetName(), var->GetHelp());
588 }
589}
590
591// Main entry point into the command_interpreter; this function takes a text
592// line containing a debugger command, with all its flags, options, etc,
593// parses the line and takes the appropriate actions.
594
595bool
Greg Clayton63094e02010-06-23 01:19:29 +0000596CommandInterpreter::HandleCommand
597(
598 const char *command_line,
599 bool add_to_history,
600 CommandReturnObject &result,
601 ExecutionContext *override_context
602)
Chris Lattner24943d22010-06-08 16:52:24 +0000603{
604 // FIXME: there should probably be a mutex to make sure only one thread can
605 // run the interpreter at a time.
606
607 // TODO: this should be a logging channel in lldb.
608// if (DebugSelf())
609// {
610// result.AppendMessageWithFormat ("Processing command: %s\n", command_line);
611// }
612
Greg Clayton63094e02010-06-23 01:19:29 +0000613 m_debugger.UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +0000614
615 if (command_line == NULL || command_line[0] == '\0')
616 {
617 if (m_command_history.empty())
618 {
619 result.AppendError ("empty command");
620 result.SetStatus(eReturnStatusFailed);
621 return false;
622 }
623 else
624 {
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000625 command_line = m_repeat_command.c_str();
626 if (m_repeat_command.empty())
627 {
Jim Ingham767af882010-07-07 03:36:20 +0000628 result.AppendErrorWithFormat("No auto repeat.\n");
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000629 result.SetStatus (eReturnStatusFailed);
630 return false;
631 }
Chris Lattner24943d22010-06-08 16:52:24 +0000632 }
633 add_to_history = false;
634 }
635
636 Args command_args(command_line);
637
638 if (command_args.GetArgumentCount() > 0)
639 {
640 const char *command_cstr = command_args.GetArgumentAtIndex(0);
641 if (command_cstr)
642 {
643
644 // We're looking up the command object here. So first find an exact match to the
645 // command in the commands.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000646 CommandObject *command_obj = GetCommandObject(command_cstr);
647
648 if (command_obj != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000649 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000650 if (command_obj->IsAlias())
Chris Lattner24943d22010-06-08 16:52:24 +0000651 {
652 BuildAliasCommandArgs (command_obj, command_cstr, command_args, result);
653 if (!result.Succeeded())
654 return false;
655 }
Chris Lattner24943d22010-06-08 16:52:24 +0000656
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000657 if (add_to_history)
658 {
Jim Ingham767af882010-07-07 03:36:20 +0000659 const char *repeat_command = command_obj->GetRepeatCommand(command_args, 0);
660 if (repeat_command != NULL)
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000661 m_repeat_command.assign(repeat_command);
662 else
Jim Ingham767af882010-07-07 03:36:20 +0000663 m_repeat_command.assign(command_line);
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000664
665 m_command_history.push_back (command_line);
666 }
667
668
Chris Lattner24943d22010-06-08 16:52:24 +0000669 if (command_obj->WantsRawCommandString())
670 {
671 const char *stripped_command = ::strstr (command_line, command_cstr);
672 if (stripped_command)
673 {
674 stripped_command += strlen(command_cstr);
675 while (isspace(*stripped_command))
676 ++stripped_command;
Greg Clayton63094e02010-06-23 01:19:29 +0000677 command_obj->ExecuteRawCommandString (*this, stripped_command, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000678 }
679 }
680 else
681 {
Chris Lattner24943d22010-06-08 16:52:24 +0000682 // Remove the command from the args.
683 command_args.Shift();
Greg Clayton63094e02010-06-23 01:19:29 +0000684 command_obj->ExecuteWithOptions (*this, command_args, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000685 }
686 }
687 else
688 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000689 // We didn't find the first command object, so complete the first argument.
Chris Lattner24943d22010-06-08 16:52:24 +0000690 StringList matches;
691 int num_matches;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000692 int cursor_index = 0;
693 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
Jim Ingham802f8b02010-06-30 05:02:46 +0000694 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +0000695 num_matches = HandleCompletionMatches (command_args,
696 cursor_index,
697 cursor_char_position,
698 0,
699 -1,
Jim Ingham802f8b02010-06-30 05:02:46 +0000700 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +0000701 matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000702
703 if (num_matches > 0)
704 {
705 std::string error_msg;
706 error_msg.assign ("ambiguous command '");
707 error_msg.append(command_cstr);
708 error_msg.append ("'.");
709
710 error_msg.append (" Possible completions:");
711 for (int i = 0; i < num_matches; i++)
712 {
713 error_msg.append ("\n\t");
714 error_msg.append (matches.GetStringAtIndex (i));
715 }
716 error_msg.append ("\n");
717 result.AppendRawError (error_msg.c_str(), error_msg.size());
718 }
719 else
720 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_cstr);
721
722 result.SetStatus (eReturnStatusFailed);
723 }
724 }
725 }
726 return result.Succeeded();
727}
728
729int
730CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
731 int &cursor_index,
732 int &cursor_char_position,
733 int match_start_point,
734 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +0000735 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000736 StringList &matches)
737{
738 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000739 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +0000740
741 // For any of the command completions a unique match will be a complete word.
742 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000743
744 if (cursor_index == -1)
745 {
746 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +0000747 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000748 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
749 }
750 else if (cursor_index == 0)
751 {
752 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000753 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000754 num_command_matches = matches.GetSize();
755
756 if (num_command_matches == 1
757 && cmd_obj && cmd_obj->IsMultiwordObject()
758 && matches.GetStringAtIndex(0) != NULL
759 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
760 {
761 look_for_subcommand = true;
762 num_command_matches = 0;
763 matches.DeleteStringAtIndex(0);
764 parsed_line.AppendArgument ("");
765 cursor_index++;
766 cursor_char_position = 0;
767 }
768 }
769
770 if (cursor_index > 0 || look_for_subcommand)
771 {
772 // We are completing further on into a commands arguments, so find the command and tell it
773 // to complete the command.
774 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +0000775 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +0000776 if (command_object == NULL)
777 {
778 return 0;
779 }
780 else
781 {
782 parsed_line.Shift();
783 cursor_index--;
Greg Clayton63094e02010-06-23 01:19:29 +0000784 num_command_matches = command_object->HandleCompletion (*this,
785 parsed_line,
786 cursor_index,
787 cursor_char_position,
788 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000789 max_return_elements,
790 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000791 matches);
792 }
793 }
794
795 return num_command_matches;
796
797}
798
799int
800CommandInterpreter::HandleCompletion (const char *current_line,
801 const char *cursor,
802 const char *last_char,
803 int match_start_point,
804 int max_return_elements,
805 StringList &matches)
806{
807 // We parse the argument up to the cursor, so the last argument in parsed_line is
808 // the one containing the cursor, and the cursor is after the last character.
809
810 Args parsed_line(current_line, last_char - current_line);
811 Args partial_parsed_line(current_line, cursor - current_line);
812
813 int num_args = partial_parsed_line.GetArgumentCount();
814 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
815 int cursor_char_position;
816
817 if (cursor_index == -1)
818 cursor_char_position = 0;
819 else
820 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
821
822 int num_command_matches;
823
824 matches.Clear();
825
826 // Only max_return_elements == -1 is supported at present:
827 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +0000828 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +0000829 num_command_matches = HandleCompletionMatches (parsed_line,
830 cursor_index,
831 cursor_char_position,
832 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000833 max_return_elements,
834 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +0000835 matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000836
837 if (num_command_matches <= 0)
838 return num_command_matches;
839
840 if (num_args == 0)
841 {
842 // If we got an empty string, insert nothing.
843 matches.InsertStringAtIndex(0, "");
844 }
845 else
846 {
847 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
848 // put an empty string in element 0.
849 std::string command_partial_str;
850 if (cursor_index >= 0)
851 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index), parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
852
853 std::string common_prefix;
854 matches.LongestCommonPrefix (common_prefix);
855 int partial_name_len = command_partial_str.size();
856
857 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +0000858 // Only do this if the completer told us this was a complete word, however...
859 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +0000860 {
861 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
862 if (quote_char != '\0')
863 common_prefix.push_back(quote_char);
864
865 common_prefix.push_back(' ');
866 }
867 common_prefix.erase (0, partial_name_len);
868 matches.InsertStringAtIndex(0, common_prefix.c_str());
869 }
870 return num_command_matches;
871}
872
Chris Lattner24943d22010-06-08 16:52:24 +0000873const Args *
874CommandInterpreter::GetProgramArguments ()
875{
876 if (! HasInterpreterVariables())
877 return NULL;
878
879 VariableMap::const_iterator pos = m_variables.find("run-args");
880 if (pos == m_variables.end())
881 return NULL;
882
883 StateVariable *var = pos->second.get();
884
885 if (var)
886 return &var->GetArgs();
887 return NULL;
888}
889
890const Args *
891CommandInterpreter::GetEnvironmentVariables ()
892{
893 if (! HasInterpreterVariables())
894 return NULL;
895
896 VariableMap::const_iterator pos = m_variables.find("env-vars");
897 if (pos == m_variables.end())
898 return NULL;
899
900 StateVariable *var = pos->second.get();
901 if (var)
902 return &var->GetArgs();
903 return NULL;
904}
905
Greg Clayton452bf612010-08-31 18:35:14 +0000906int
907CommandInterpreter::GetDisableASLR ()
908{
909 StateVariable *var = GetStateVariable ("disable-aslr");
910 int disable_aslr = var->GetIntValue();
911
912 return disable_aslr;
913}
Chris Lattner24943d22010-06-08 16:52:24 +0000914
915CommandInterpreter::~CommandInterpreter ()
916{
917}
918
919const char *
920CommandInterpreter::GetPrompt ()
921{
922 VariableMap::iterator pos;
923
924 if (! HasInterpreterVariables())
925 return NULL;
926
927 pos = m_variables.find("prompt");
928 if (pos == m_variables.end())
929 return NULL;
930
931 StateVariable *var = pos->second.get();
932
933 return ((char *) var->GetStringValue());
934}
935
936void
937CommandInterpreter::SetPrompt (const char *new_prompt)
938{
939 VariableMap::iterator pos;
940 CommandReturnObject result;
941
942 if (! HasInterpreterVariables())
943 return;
944
945 pos = m_variables.find ("prompt");
946 if (pos == m_variables.end())
947 return;
948
949 StateVariable *var = pos->second.get();
950
951 if (var->VerifyValue (this, (void *) new_prompt, result))
952 var->SetStringValue (new_prompt);
953}
954
955void
956CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
957{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000958 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +0000959
960 if (cmd_obj_sp != NULL)
961 {
962 CommandObject *cmd_obj = cmd_obj_sp.get();
963 if (cmd_obj->IsCrossRefObject ())
964 cmd_obj->AddObject (object_type);
965 }
966}
967
968void
969CommandInterpreter::SetScriptLanguage (ScriptLanguage lang)
970{
971 m_script_language = lang;
972}
973
Chris Lattner24943d22010-06-08 16:52:24 +0000974OptionArgVectorSP
975CommandInterpreter::GetAliasOptions (const char *alias_name)
976{
977 OptionArgMap::iterator pos;
978 OptionArgVectorSP ret_val;
979
980 std::string alias (alias_name);
981
982 if (HasAliasOptions())
983 {
984 pos = m_alias_options.find (alias);
985 if (pos != m_alias_options.end())
986 ret_val = pos->second;
987 }
988
989 return ret_val;
990}
991
992void
993CommandInterpreter::RemoveAliasOptions (const char *alias_name)
994{
995 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
996 if (pos != m_alias_options.end())
997 {
998 m_alias_options.erase (pos);
999 }
1000}
1001
1002void
1003CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1004{
1005 m_alias_options[alias_name] = option_arg_vector_sp;
1006}
1007
1008bool
1009CommandInterpreter::HasCommands ()
1010{
1011 return (!m_command_dict.empty());
1012}
1013
1014bool
1015CommandInterpreter::HasAliases ()
1016{
1017 return (!m_alias_dict.empty());
1018}
1019
1020bool
1021CommandInterpreter::HasUserCommands ()
1022{
1023 return (!m_user_dict.empty());
1024}
1025
1026bool
1027CommandInterpreter::HasAliasOptions ()
1028{
1029 return (!m_alias_options.empty());
1030}
1031
1032bool
1033CommandInterpreter::HasInterpreterVariables ()
1034{
1035 return (!m_variables.empty());
1036}
1037
1038void
1039CommandInterpreter::BuildAliasCommandArgs
1040(
1041 CommandObject *alias_cmd_obj,
1042 const char *alias_name,
1043 Args &cmd_args,
1044 CommandReturnObject &result
1045)
1046{
1047 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1048
1049 if (option_arg_vector_sp.get())
1050 {
1051 // Make sure that the alias name is the 0th element in cmd_args
1052 std::string alias_name_str = alias_name;
1053 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1054 cmd_args.Unshift (alias_name);
1055
1056 Args new_args (alias_cmd_obj->GetCommandName());
1057 if (new_args.GetArgumentCount() == 2)
1058 new_args.Shift();
1059
1060 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1061 int old_size = cmd_args.GetArgumentCount();
1062 int *used = (int *) malloc ((old_size + 1) * sizeof (int));
1063
1064 memset (used, 0, (old_size + 1) * sizeof (int));
1065 used[0] = 1;
1066
1067 for (int i = 0; i < option_arg_vector->size(); ++i)
1068 {
1069 OptionArgPair option_pair = (*option_arg_vector)[i];
1070 std::string option = option_pair.first;
1071 std::string value = option_pair.second;
1072 if (option.compare ("<argument>") == 0)
1073 new_args.AppendArgument (value.c_str());
1074 else
1075 {
1076 new_args.AppendArgument (option.c_str());
1077 if (value.compare ("<no-argument>") != 0)
1078 {
1079 int index = GetOptionArgumentPosition (value.c_str());
1080 if (index == 0)
1081 // value was NOT a positional argument; must be a real value
1082 new_args.AppendArgument (value.c_str());
1083 else if (index >= cmd_args.GetArgumentCount())
1084 {
1085 result.AppendErrorWithFormat
1086 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1087 index);
1088 result.SetStatus (eReturnStatusFailed);
1089 return;
1090 }
1091 else
1092 {
1093 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
1094 used[index] = 1;
1095 }
1096 }
1097 }
1098 }
1099
1100 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1101 {
1102 if (!used[j])
1103 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1104 }
1105
1106 cmd_args.Clear();
1107 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1108 }
1109 else
1110 {
1111 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1112 // This alias was not created with any options; nothing further needs to be done.
1113 return;
1114 }
1115
1116 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1117 return;
1118}
1119
1120
1121int
1122CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1123{
1124 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1125 // of zero.
1126
1127 char *cptr = (char *) in_string;
1128
1129 // Does it start with '%'
1130 if (cptr[0] == '%')
1131 {
1132 ++cptr;
1133
1134 // Is the rest of it entirely digits?
1135 if (isdigit (cptr[0]))
1136 {
1137 const char *start = cptr;
1138 while (isdigit (cptr[0]))
1139 ++cptr;
1140
1141 // We've gotten to the end of the digits; are we at the end of the string?
1142 if (cptr[0] == '\0')
1143 position = atoi (start);
1144 }
1145 }
1146
1147 return position;
1148}
1149
1150void
1151CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1152{
1153 const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit";
1154 FileSpec init_file (init_file_path);
1155 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
1156 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
1157
1158 if (init_file.Exists())
1159 {
1160 char path[PATH_MAX];
1161 init_file.GetPath(path, sizeof(path));
1162 StreamString source_command;
Johnny Chen7c984242010-07-28 21:16:11 +00001163 source_command.Printf ("command source '%s'", path);
Chris Lattner24943d22010-06-08 16:52:24 +00001164 HandleCommand (source_command.GetData(), false, result);
1165 }
1166 else
1167 {
1168 // nothing to be done if the file doesn't exist
1169 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1170 }
1171}
1172
1173ScriptInterpreter *
1174CommandInterpreter::GetScriptInterpreter ()
1175{
Greg Clayton63094e02010-06-23 01:19:29 +00001176 CommandObject::CommandMap::iterator pos;
1177
1178 pos = m_command_dict.find ("script");
1179 if (pos != m_command_dict.end())
Chris Lattner24943d22010-06-08 16:52:24 +00001180 {
Greg Clayton63094e02010-06-23 01:19:29 +00001181 CommandObject *script_cmd_obj = pos->second.get();
1182 return ((CommandObjectScript *) script_cmd_obj)->GetInterpreter (*this);
Chris Lattner24943d22010-06-08 16:52:24 +00001183 }
Greg Clayton63094e02010-06-23 01:19:29 +00001184 return NULL;
Chris Lattner24943d22010-06-08 16:52:24 +00001185}
1186
1187
1188
1189bool
1190CommandInterpreter::GetSynchronous ()
1191{
1192 return m_synchronous_execution;
1193}
1194
1195void
1196CommandInterpreter::SetSynchronous (bool value)
1197{
1198 static bool value_set_once = false;
1199 if (!value_set_once)
1200 {
1201 value_set_once = true;
1202 m_synchronous_execution = value;
1203 }
1204}
1205
1206void
1207CommandInterpreter::OutputFormattedHelpText (Stream &strm,
1208 const char *word_text,
1209 const char *separator,
1210 const char *help_text,
1211 uint32_t max_word_len)
1212{
1213 StateVariable *var = GetStateVariable ("term-width");
1214 int max_columns = var->GetIntValue();
1215 // Sanity check max_columns, to cope with emacs shell mode with TERM=dumb
1216 // (0 rows; 0 columns;).
1217 if (max_columns <= 0) max_columns = 80;
1218
1219 int indent_size = max_word_len + strlen (separator) + 2;
1220
1221 strm.IndentMore (indent_size);
1222
1223 int len = indent_size + strlen (help_text) + 1;
1224 char *text = (char *) malloc (len);
1225 sprintf (text, "%-*s %s %s", max_word_len, word_text, separator, help_text);
1226 if (text[len - 1] == '\n')
1227 text[--len] = '\0';
1228
1229 if (len < max_columns)
1230 {
1231 // Output it as a single line.
1232 strm.Printf ("%s", text);
1233 }
1234 else
1235 {
1236 // We need to break it up into multiple lines.
1237 bool first_line = true;
1238 int text_width;
1239 int start = 0;
1240 int end = start;
1241 int final_end = strlen (text);
1242 int sub_len;
1243
1244 while (end < final_end)
1245 {
1246 if (first_line)
1247 text_width = max_columns - 1;
1248 else
1249 text_width = max_columns - indent_size - 1;
1250
1251 // Don't start the 'text' on a space, since we're already outputting the indentation.
1252 if (!first_line)
1253 {
1254 while ((start < final_end) && (text[start] == ' '))
1255 start++;
1256 }
1257
1258 end = start + text_width;
1259 if (end > final_end)
1260 end = final_end;
1261 else
1262 {
1263 // If we're not at the end of the text, make sure we break the line on white space.
1264 while (end > start
1265 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
1266 end--;
1267 }
1268
1269 sub_len = end - start;
1270 if (start != 0)
1271 strm.EOL();
1272 if (!first_line)
1273 strm.Indent();
1274 else
1275 first_line = false;
1276 assert (start <= final_end);
1277 assert (start + sub_len <= final_end);
1278 if (sub_len > 0)
1279 strm.Write (text + start, sub_len);
1280 start = end + 1;
1281 }
1282 }
1283 strm.EOL();
1284 strm.IndentLess(indent_size);
1285 free (text);
1286}
1287
1288void
1289CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
1290 StringList &commands_found, StringList &commands_help)
1291{
1292 CommandObject::CommandMap::const_iterator pos;
1293 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
1294 CommandObject *sub_cmd_obj;
1295
1296 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
1297 {
1298 const char * command_name = pos->first.c_str();
1299 sub_cmd_obj = pos->second.get();
1300 StreamString complete_command_name;
1301
1302 complete_command_name.Printf ("%s %s", prefix, command_name);
1303
1304 if (sub_cmd_obj->HelpTextContainsWord (search_word))
1305 {
1306 commands_found.AppendString (complete_command_name.GetData());
1307 commands_help.AppendString (sub_cmd_obj->GetHelp());
1308 }
1309
1310 if (sub_cmd_obj->IsMultiwordObject())
1311 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
1312 commands_help);
1313 }
1314
1315}
1316
1317void
1318CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
1319 StringList &commands_help)
1320{
1321 CommandObject::CommandMap::const_iterator pos;
1322
1323 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1324 {
1325 const char *command_name = pos->first.c_str();
1326 CommandObject *cmd_obj = pos->second.get();
1327
1328 if (cmd_obj->HelpTextContainsWord (search_word))
1329 {
1330 commands_found.AppendString (command_name);
1331 commands_help.AppendString (cmd_obj->GetHelp());
1332 }
1333
1334 if (cmd_obj->IsMultiwordObject())
1335 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
1336
1337 }
1338}