blob: 0dc4a34aa7b2a5080b3be54088b2542b04cbf7d7 [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>
Caroline Ticebd5c63e2010-10-12 21:57:09 +000011#include <vector>
Chris Lattner24943d22010-06-08 16:52:24 +000012
13#include <getopt.h>
14#include <stdlib.h>
15
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000016#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/CommandObjectDisassemble.h"
21#include "../Commands/CommandObjectExpression.h"
22#include "../Commands/CommandObjectFile.h"
23#include "../Commands/CommandObjectFrame.h"
24#include "../Commands/CommandObjectHelp.h"
25#include "../Commands/CommandObjectImage.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000026#include "../Commands/CommandObjectLog.h"
27#include "../Commands/CommandObjectMemory.h"
28#include "../Commands/CommandObjectProcess.h"
29#include "../Commands/CommandObjectQuit.h"
Eli Friedmanb34d2a22010-06-09 22:08:29 +000030#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000031#include "../Commands/CommandObjectRegister.h"
Chris Lattner24943d22010-06-08 16:52:24 +000032#include "CommandObjectScript.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000033#include "../Commands/CommandObjectSettings.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000034#include "../Commands/CommandObjectSource.h"
Jim Ingham767af882010-07-07 03:36:20 +000035#include "../Commands/CommandObjectCommands.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000036#include "../Commands/CommandObjectSyntax.h"
37#include "../Commands/CommandObjectTarget.h"
38#include "../Commands/CommandObjectThread.h"
Chris Lattner24943d22010-06-08 16:52:24 +000039
Jim Ingham84cdc152010-06-15 19:49:27 +000040#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000041#include "lldb/Core/Debugger.h"
Jim Ingham5e16ef52010-10-04 19:49:29 +000042#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000043#include "lldb/Core/Stream.h"
44#include "lldb/Core/Timer.h"
45#include "lldb/Target/Process.h"
46#include "lldb/Target/Thread.h"
47#include "lldb/Target/TargetList.h"
Greg Claytone98ac252010-11-10 04:57:04 +000048#include "lldb/Utility/CleanUp.h"
Chris Lattner24943d22010-06-08 16:52:24 +000049
50#include "lldb/Interpreter/CommandReturnObject.h"
51#include "lldb/Interpreter/CommandInterpreter.h"
52
53using namespace lldb;
54using namespace lldb_private;
55
56CommandInterpreter::CommandInterpreter
57(
Greg Clayton63094e02010-06-23 01:19:29 +000058 Debugger &debugger,
Chris Lattner24943d22010-06-08 16:52:24 +000059 ScriptLanguage script_language,
Greg Clayton63094e02010-06-23 01:19:29 +000060 bool synchronous_execution
Chris Lattner24943d22010-06-08 16:52:24 +000061) :
Greg Clayton49ce6822010-10-31 03:01:06 +000062 Broadcaster ("lldb.command-interpreter"),
Greg Clayton63094e02010-06-23 01:19:29 +000063 m_debugger (debugger),
Greg Clayton887aa282010-10-11 01:05:37 +000064 m_synchronous_execution (synchronous_execution),
65 m_skip_lldbinit_files (false)
Chris Lattner24943d22010-06-08 16:52:24 +000066{
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000067 const char *dbg_name = debugger.GetInstanceName().AsCString();
68 std::string lang_name = ScriptInterpreter::LanguageToString (script_language);
69 StreamString var_name;
70 var_name.Printf ("[%s].script-lang", dbg_name);
Caroline Tice1d2aefd2010-09-09 06:25:08 +000071 debugger.GetSettingsController()->SetVariable (var_name.GetData(), lang_name.c_str(),
72 lldb::eVarSetOperationAssign, false,
Greg Clayton49ce6822010-10-31 03:01:06 +000073 m_debugger.GetInstanceName().AsCString());
74 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
75 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
76 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Chris Lattner24943d22010-06-08 16:52:24 +000077}
78
79void
80CommandInterpreter::Initialize ()
81{
82 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
83
84 CommandReturnObject result;
85
86 LoadCommandDictionary ();
87
Chris Lattner24943d22010-06-08 16:52:24 +000088 // Set up some initial aliases.
Jim Ingham767af882010-07-07 03:36:20 +000089 result.Clear(); HandleCommand ("command alias q quit", false, result);
Jim Inghame3663e82010-10-22 18:47:16 +000090 result.Clear(); HandleCommand ("command alias run process launch --", false, result);
91 result.Clear(); HandleCommand ("command alias r process launch --", false, result);
Jim Ingham767af882010-07-07 03:36:20 +000092 result.Clear(); HandleCommand ("command alias c process continue", false, result);
93 result.Clear(); HandleCommand ("command alias continue process continue", false, result);
94 result.Clear(); HandleCommand ("command alias expr expression", false, result);
95 result.Clear(); HandleCommand ("command alias exit quit", false, result);
Greg Clayton0f3a8eb2010-09-16 17:09:23 +000096 result.Clear(); HandleCommand ("command alias b regexp-break", false, result);
Jim Ingham767af882010-07-07 03:36:20 +000097 result.Clear(); HandleCommand ("command alias bt thread backtrace", false, result);
98 result.Clear(); HandleCommand ("command alias si thread step-inst", false, result);
99 result.Clear(); HandleCommand ("command alias step thread step-in", false, result);
100 result.Clear(); HandleCommand ("command alias s thread step-in", false, result);
101 result.Clear(); HandleCommand ("command alias next thread step-over", false, result);
102 result.Clear(); HandleCommand ("command alias n thread step-over", false, result);
103 result.Clear(); HandleCommand ("command alias finish thread step-out", false, result);
104 result.Clear(); HandleCommand ("command alias x memory read", false, result);
105 result.Clear(); HandleCommand ("command alias l source list", false, result);
106 result.Clear(); HandleCommand ("command alias list source list", false, result);
Greg Clayton0f3a8eb2010-09-16 17:09:23 +0000107 result.Clear(); HandleCommand ("command alias p frame variable", false, result);
108 result.Clear(); HandleCommand ("command alias print frame variable", false, result);
Jim Inghame3663e82010-10-22 18:47:16 +0000109 result.Clear(); HandleCommand ("command alias po expression -o --", false, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000110}
111
Chris Lattner24943d22010-06-08 16:52:24 +0000112const char *
113CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
114{
115 // This function has not yet been implemented.
116
117 // Look for any embedded script command
118 // If found,
119 // get interpreter object from the command dictionary,
120 // call execute_one_command on it,
121 // get the results as a string,
122 // substitute that string for current stuff.
123
124 return arg;
125}
126
127
128void
129CommandInterpreter::LoadCommandDictionary ()
130{
131 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
132
133 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
134 //
135 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
136 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
137 // the cross-referencing stuff) are created!!!
138 //
139 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
140
141
142 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
143 // are created. This is so that when another command is created that needs to go into a crossref object,
144 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
145 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
146
Chris Lattner24943d22010-06-08 16:52:24 +0000147 // Non-CommandObjectCrossref commands can now be created.
148
Caroline Tice5bc8c972010-09-20 20:44:43 +0000149 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000150
Greg Clayton238c0a12010-09-18 01:14:36 +0000151 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000152 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000153 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000154 m_command_dict["commands"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000155 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
156 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
157 m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000158 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000159 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000160 m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
161 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
162 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
163 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000164 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000165 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000166 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000167 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000168 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000169 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
170 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000171
172 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000173 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
174 "regexp-break",
Caroline Ticec1ad82e2010-09-07 22:38:08 +0000175 "Set a breakpoint using a regular expression to specify the location.",
Caroline Tice43b014a2010-10-04 22:28:36 +0000176 "regexp-break [<filename>:<linenum>]\nregexp-break [<address>]\nregexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000177 if (break_regex_cmd_ap.get())
178 {
179 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
180 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
181 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
182 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list") &&
183 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
184 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
185 {
186 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
187 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
188 }
189 }
190}
191
192int
193CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
194 StringList &matches)
195{
196 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
197
198 if (include_aliases)
199 {
200 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
201 }
202
203 return matches.GetSize();
204}
205
206CommandObjectSP
207CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
208{
209 CommandObject::CommandMap::iterator pos;
210 CommandObjectSP ret_val;
211
212 std::string cmd(cmd_cstr);
213
214 if (HasCommands())
215 {
216 pos = m_command_dict.find(cmd);
217 if (pos != m_command_dict.end())
218 ret_val = pos->second;
219 }
220
221 if (include_aliases && HasAliases())
222 {
223 pos = m_alias_dict.find(cmd);
224 if (pos != m_alias_dict.end())
225 ret_val = pos->second;
226 }
227
228 if (HasUserCommands())
229 {
230 pos = m_user_dict.find(cmd);
231 if (pos != m_user_dict.end())
232 ret_val = pos->second;
233 }
234
235 if (!exact && ret_val == NULL)
236 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000237 // We will only get into here if we didn't find any exact matches.
238
239 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
240
Chris Lattner24943d22010-06-08 16:52:24 +0000241 StringList local_matches;
242 if (matches == NULL)
243 matches = &local_matches;
244
Jim Inghamd40f8a62010-07-06 22:46:59 +0000245 unsigned int num_cmd_matches = 0;
246 unsigned int num_alias_matches = 0;
247 unsigned int num_user_matches = 0;
248
249 // Look through the command dictionaries one by one, and if we get only one match from any of
250 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
251
Chris Lattner24943d22010-06-08 16:52:24 +0000252 if (HasCommands())
253 {
254 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
255 }
256
257 if (num_cmd_matches == 1)
258 {
259 cmd.assign(matches->GetStringAtIndex(0));
260 pos = m_command_dict.find(cmd);
261 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000262 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000263 }
264
Jim Ingham9a574172010-06-24 20:28:42 +0000265 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000266 {
267 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
268
269 }
270
Jim Inghamd40f8a62010-07-06 22:46:59 +0000271 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000272 {
273 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
274 pos = m_alias_dict.find(cmd);
275 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000276 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000277 }
278
Jim Ingham9a574172010-06-24 20:28:42 +0000279 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000280 {
281 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
282 }
283
Jim Inghamd40f8a62010-07-06 22:46:59 +0000284 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000285 {
286 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
287
288 pos = m_user_dict.find (cmd);
289 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000290 user_match_sp = pos->second;
291 }
292
293 // If we got exactly one match, return that, otherwise return the match list.
294
295 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
296 {
297 if (num_cmd_matches)
298 return real_match_sp;
299 else if (num_alias_matches)
300 return alias_match_sp;
301 else
302 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000303 }
304 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000305 else if (matches && ret_val != NULL)
306 {
307 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000308 }
309
310
311 return ret_val;
312}
313
Jim Inghamd40f8a62010-07-06 22:46:59 +0000314CommandObjectSP
315CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000316{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000317 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
318}
319
320CommandObject *
321CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
322{
323 return GetCommandSPExact (cmd_cstr, include_aliases).get();
324}
325
326CommandObject *
327CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
328{
329 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
330
331 // If we didn't find an exact match to the command string in the commands, look in
332 // the aliases.
333
334 if (command_obj == NULL)
335 {
336 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
337 }
338
339 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
340 // in both the commands and the aliases.
341
342 if (command_obj == NULL)
343 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
344
345 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000346}
347
348bool
349CommandInterpreter::CommandExists (const char *cmd)
350{
351 return m_command_dict.find(cmd) != m_command_dict.end();
352}
353
354bool
355CommandInterpreter::AliasExists (const char *cmd)
356{
357 return m_alias_dict.find(cmd) != m_alias_dict.end();
358}
359
360bool
361CommandInterpreter::UserCommandExists (const char *cmd)
362{
363 return m_user_dict.find(cmd) != m_user_dict.end();
364}
365
366void
367CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
368{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000369 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000370 m_alias_dict[alias_name] = command_obj_sp;
371}
372
373bool
374CommandInterpreter::RemoveAlias (const char *alias_name)
375{
376 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
377 if (pos != m_alias_dict.end())
378 {
379 m_alias_dict.erase(pos);
380 return true;
381 }
382 return false;
383}
384bool
385CommandInterpreter::RemoveUser (const char *alias_name)
386{
387 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
388 if (pos != m_user_dict.end())
389 {
390 m_user_dict.erase(pos);
391 return true;
392 }
393 return false;
394}
395
Chris Lattner24943d22010-06-08 16:52:24 +0000396void
397CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
398{
399 help_string.Printf ("'%s", command_name);
400 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
401
402 if (option_arg_vector_sp != NULL)
403 {
404 OptionArgVector *options = option_arg_vector_sp.get();
405 for (int i = 0; i < options->size(); ++i)
406 {
407 OptionArgPair cur_option = (*options)[i];
408 std::string opt = cur_option.first;
409 std::string value = cur_option.second;
410 if (opt.compare("<argument>") == 0)
411 {
412 help_string.Printf (" %s", value.c_str());
413 }
414 else
415 {
416 help_string.Printf (" %s", opt.c_str());
417 if ((value.compare ("<no-argument>") != 0)
418 && (value.compare ("<need-argument") != 0))
419 {
420 help_string.Printf (" %s", value.c_str());
421 }
422 }
423 }
424 }
425
426 help_string.Printf ("'");
427}
428
Greg Clayton65124ea2010-08-26 22:05:43 +0000429size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000430CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
431{
432 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000433 CommandObject::CommandMap::const_iterator end = dict.end();
434 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000435
Greg Clayton65124ea2010-08-26 22:05:43 +0000436 for (pos = dict.begin(); pos != end; ++pos)
437 {
438 size_t len = pos->first.size();
439 if (max_len < len)
440 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000441 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000442 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000443}
444
445void
446CommandInterpreter::GetHelp (CommandReturnObject &result)
447{
448 CommandObject::CommandMap::const_iterator pos;
449 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
450 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000451 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000452
453 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
454 {
455 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
456 max_len);
457 }
458 result.AppendMessage("");
459
460 if (m_alias_dict.size() > 0)
461 {
Jim Inghame3663e82010-10-22 18:47:16 +0000462 result.AppendMessage("The following is a list of your current command abbreviations "
463 "(see 'help commands alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000464 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000465 max_len = FindLongestCommandWord (m_alias_dict);
466
Chris Lattner24943d22010-06-08 16:52:24 +0000467 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
468 {
469 StreamString sstr;
470 StreamString translation_and_help;
471 std::string entry_name = pos->first;
472 std::string second_entry = pos->second.get()->GetCommandName();
473 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
474
475 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
476 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
477 translation_and_help.GetData(), max_len);
478 }
479 result.AppendMessage("");
480 }
481
482 if (m_user_dict.size() > 0)
483 {
484 result.AppendMessage ("The following is a list of your current user-defined commands:");
485 result.AppendMessage("");
486 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
487 {
488 result.AppendMessageWithFormat ("%s -- %s\n", pos->first.c_str(), pos->second->GetHelp());
489 }
490 result.AppendMessage("");
491 }
492
493 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
494}
495
Chris Lattner24943d22010-06-08 16:52:24 +0000496bool
Greg Clayton63094e02010-06-23 01:19:29 +0000497CommandInterpreter::HandleCommand
498(
499 const char *command_line,
500 bool add_to_history,
501 CommandReturnObject &result,
502 ExecutionContext *override_context
503)
Chris Lattner24943d22010-06-08 16:52:24 +0000504{
505 // FIXME: there should probably be a mutex to make sure only one thread can
506 // run the interpreter at a time.
507
Greg Claytone98ac252010-11-10 04:57:04 +0000508 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
509
510 // Make a scoped cleanup object that will clear the crash description string
511 // on exit of this function.
512 lldb_utility::CleanUp <const char *, void> crash_description_cleanup(NULL, Host::SetCrashDescription);
513
Chris Lattner24943d22010-06-08 16:52:24 +0000514 // TODO: this should be a logging channel in lldb.
515// if (DebugSelf())
516// {
517// result.AppendMessageWithFormat ("Processing command: %s\n", command_line);
518// }
519
Jim Inghamabab14b2010-11-04 23:08:45 +0000520 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
521
Greg Clayton63094e02010-06-23 01:19:29 +0000522 m_debugger.UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +0000523
524 if (command_line == NULL || command_line[0] == '\0')
525 {
526 if (m_command_history.empty())
527 {
528 result.AppendError ("empty command");
529 result.SetStatus(eReturnStatusFailed);
530 return false;
531 }
532 else
533 {
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000534 command_line = m_repeat_command.c_str();
535 if (m_repeat_command.empty())
536 {
Jim Ingham767af882010-07-07 03:36:20 +0000537 result.AppendErrorWithFormat("No auto repeat.\n");
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000538 result.SetStatus (eReturnStatusFailed);
539 return false;
540 }
Chris Lattner24943d22010-06-08 16:52:24 +0000541 }
542 add_to_history = false;
543 }
544
545 Args command_args(command_line);
546
547 if (command_args.GetArgumentCount() > 0)
548 {
549 const char *command_cstr = command_args.GetArgumentAtIndex(0);
550 if (command_cstr)
551 {
552
553 // We're looking up the command object here. So first find an exact match to the
554 // command in the commands.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000555 CommandObject *command_obj = GetCommandObject(command_cstr);
556
557 if (command_obj != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000558 {
Caroline Tice0fb069d2010-10-18 19:18:31 +0000559 std::string aliased_cmd_str;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000560 if (command_obj->IsAlias())
Chris Lattner24943d22010-06-08 16:52:24 +0000561 {
562 BuildAliasCommandArgs (command_obj, command_cstr, command_args, result);
563 if (!result.Succeeded())
564 return false;
Caroline Tice0fb069d2010-10-18 19:18:31 +0000565 else
566 {
567 // We need to transfer the newly constructed args back into the command_line, in case
568 // this happens to be an alias for a command that takes raw input.
569 if (command_args.GetCommandString (aliased_cmd_str))
570 {
571 command_line = aliased_cmd_str.c_str();
Caroline Tice8b5a0772010-10-18 22:38:05 +0000572 command_cstr = command_args.GetArgumentAtIndex (0);
Caroline Tice0fb069d2010-10-18 19:18:31 +0000573 }
574 }
Chris Lattner24943d22010-06-08 16:52:24 +0000575 }
Chris Lattner24943d22010-06-08 16:52:24 +0000576
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000577 if (add_to_history)
578 {
Jim Ingham767af882010-07-07 03:36:20 +0000579 const char *repeat_command = command_obj->GetRepeatCommand(command_args, 0);
580 if (repeat_command != NULL)
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000581 m_repeat_command.assign(repeat_command);
582 else
Jim Ingham767af882010-07-07 03:36:20 +0000583 m_repeat_command.assign(command_line);
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000584
585 m_command_history.push_back (command_line);
586 }
587
588
Chris Lattner24943d22010-06-08 16:52:24 +0000589 if (command_obj->WantsRawCommandString())
590 {
591 const char *stripped_command = ::strstr (command_line, command_cstr);
592 if (stripped_command)
593 {
594 stripped_command += strlen(command_cstr);
595 while (isspace(*stripped_command))
596 ++stripped_command;
Greg Clayton238c0a12010-09-18 01:14:36 +0000597 command_obj->ExecuteRawCommandString (stripped_command, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000598 }
599 }
600 else
601 {
Chris Lattner24943d22010-06-08 16:52:24 +0000602 // Remove the command from the args.
603 command_args.Shift();
Greg Clayton238c0a12010-09-18 01:14:36 +0000604 command_obj->ExecuteWithOptions (command_args, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000605 }
606 }
607 else
608 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000609 // We didn't find the first command object, so complete the first argument.
Chris Lattner24943d22010-06-08 16:52:24 +0000610 StringList matches;
611 int num_matches;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000612 int cursor_index = 0;
613 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
Jim Ingham802f8b02010-06-30 05:02:46 +0000614 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +0000615 num_matches = HandleCompletionMatches (command_args,
616 cursor_index,
617 cursor_char_position,
618 0,
619 -1,
Jim Ingham802f8b02010-06-30 05:02:46 +0000620 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +0000621 matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000622
623 if (num_matches > 0)
624 {
625 std::string error_msg;
626 error_msg.assign ("ambiguous command '");
627 error_msg.append(command_cstr);
628 error_msg.append ("'.");
629
630 error_msg.append (" Possible completions:");
631 for (int i = 0; i < num_matches; i++)
632 {
633 error_msg.append ("\n\t");
634 error_msg.append (matches.GetStringAtIndex (i));
635 }
636 error_msg.append ("\n");
637 result.AppendRawError (error_msg.c_str(), error_msg.size());
638 }
639 else
640 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_cstr);
641
642 result.SetStatus (eReturnStatusFailed);
643 }
644 }
645 }
646 return result.Succeeded();
647}
648
649int
650CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
651 int &cursor_index,
652 int &cursor_char_position,
653 int match_start_point,
654 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +0000655 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000656 StringList &matches)
657{
658 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000659 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +0000660
661 // For any of the command completions a unique match will be a complete word.
662 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000663
664 if (cursor_index == -1)
665 {
666 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +0000667 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000668 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
669 }
670 else if (cursor_index == 0)
671 {
672 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000673 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000674 num_command_matches = matches.GetSize();
675
676 if (num_command_matches == 1
677 && cmd_obj && cmd_obj->IsMultiwordObject()
678 && matches.GetStringAtIndex(0) != NULL
679 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
680 {
681 look_for_subcommand = true;
682 num_command_matches = 0;
683 matches.DeleteStringAtIndex(0);
684 parsed_line.AppendArgument ("");
685 cursor_index++;
686 cursor_char_position = 0;
687 }
688 }
689
690 if (cursor_index > 0 || look_for_subcommand)
691 {
692 // We are completing further on into a commands arguments, so find the command and tell it
693 // to complete the command.
694 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +0000695 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +0000696 if (command_object == NULL)
697 {
698 return 0;
699 }
700 else
701 {
702 parsed_line.Shift();
703 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +0000704 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +0000705 cursor_index,
706 cursor_char_position,
707 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000708 max_return_elements,
709 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000710 matches);
711 }
712 }
713
714 return num_command_matches;
715
716}
717
718int
719CommandInterpreter::HandleCompletion (const char *current_line,
720 const char *cursor,
721 const char *last_char,
722 int match_start_point,
723 int max_return_elements,
724 StringList &matches)
725{
726 // We parse the argument up to the cursor, so the last argument in parsed_line is
727 // the one containing the cursor, and the cursor is after the last character.
728
729 Args parsed_line(current_line, last_char - current_line);
730 Args partial_parsed_line(current_line, cursor - current_line);
731
732 int num_args = partial_parsed_line.GetArgumentCount();
733 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
734 int cursor_char_position;
735
736 if (cursor_index == -1)
737 cursor_char_position = 0;
738 else
739 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
740
741 int num_command_matches;
742
743 matches.Clear();
744
745 // Only max_return_elements == -1 is supported at present:
746 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +0000747 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +0000748 num_command_matches = HandleCompletionMatches (parsed_line,
749 cursor_index,
750 cursor_char_position,
751 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000752 max_return_elements,
753 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +0000754 matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000755
756 if (num_command_matches <= 0)
757 return num_command_matches;
758
759 if (num_args == 0)
760 {
761 // If we got an empty string, insert nothing.
762 matches.InsertStringAtIndex(0, "");
763 }
764 else
765 {
766 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
767 // put an empty string in element 0.
768 std::string command_partial_str;
769 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +0000770 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
771 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +0000772
773 std::string common_prefix;
774 matches.LongestCommonPrefix (common_prefix);
775 int partial_name_len = command_partial_str.size();
776
777 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +0000778 // Only do this if the completer told us this was a complete word, however...
779 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +0000780 {
781 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
782 if (quote_char != '\0')
783 common_prefix.push_back(quote_char);
784
785 common_prefix.push_back(' ');
786 }
787 common_prefix.erase (0, partial_name_len);
788 matches.InsertStringAtIndex(0, common_prefix.c_str());
789 }
790 return num_command_matches;
791}
792
Chris Lattner24943d22010-06-08 16:52:24 +0000793
794CommandInterpreter::~CommandInterpreter ()
795{
796}
797
798const char *
799CommandInterpreter::GetPrompt ()
800{
Caroline Tice5bc8c972010-09-20 20:44:43 +0000801 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +0000802}
803
804void
805CommandInterpreter::SetPrompt (const char *new_prompt)
806{
Caroline Tice5bc8c972010-09-20 20:44:43 +0000807 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +0000808}
809
Jim Ingham5e16ef52010-10-04 19:49:29 +0000810size_t
811CommandInterpreter::GetConfirmationInputReaderCallback (void *baton,
812 InputReader &reader,
813 lldb::InputReaderAction action,
814 const char *bytes,
815 size_t bytes_len)
816{
817 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle();
818 bool *response_ptr = (bool *) baton;
819
820 switch (action)
821 {
822 case eInputReaderActivate:
823 if (out_fh)
824 {
825 if (reader.GetPrompt())
826 ::fprintf (out_fh, "%s", reader.GetPrompt());
827 }
828 break;
829
830 case eInputReaderDeactivate:
831 break;
832
833 case eInputReaderReactivate:
834 if (out_fh && reader.GetPrompt())
835 ::fprintf (out_fh, "%s", reader.GetPrompt());
836 break;
837
838 case eInputReaderGotToken:
839 if (bytes_len == 0)
840 {
841 reader.SetIsDone(true);
842 }
843 else if (bytes[0] == 'y')
844 {
845 *response_ptr = true;
846 reader.SetIsDone(true);
847 }
848 else if (bytes[0] == 'n')
849 {
850 *response_ptr = false;
851 reader.SetIsDone(true);
852 }
853 else
854 {
855 if (out_fh && !reader.IsDone() && reader.GetPrompt())
856 {
857 ::fprintf (out_fh, "Please answer \"y\" or \"n\"\n");
858 ::fprintf (out_fh, "%s", reader.GetPrompt());
859 }
860 }
861 break;
862
863 case eInputReaderDone:
864 break;
865 }
866
867 return bytes_len;
868
869}
870
871bool
872CommandInterpreter::Confirm (const char *message, bool default_answer)
873{
Jim Ingham93057472010-10-04 22:44:14 +0000874 // Check AutoConfirm first:
875 if (m_debugger.GetAutoConfirm())
876 return default_answer;
877
Jim Ingham5e16ef52010-10-04 19:49:29 +0000878 InputReaderSP reader_sp (new InputReader(GetDebugger()));
879 bool response = default_answer;
880 if (reader_sp)
881 {
882 std::string prompt(message);
883 prompt.append(": [");
884 if (default_answer)
885 prompt.append ("Y/n] ");
886 else
887 prompt.append ("y/N] ");
888
889 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
890 &response, // baton
891 eInputReaderGranularityLine, // token size, to pass to callback function
892 NULL, // end token
893 prompt.c_str(), // prompt
894 true)); // echo input
895 if (err.Success())
896 {
897 GetDebugger().PushInputReader (reader_sp);
898 }
899 reader_sp->WaitOnReaderIsDone();
900 }
901 return response;
902}
903
904
Chris Lattner24943d22010-06-08 16:52:24 +0000905void
906CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
907{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000908 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +0000909
910 if (cmd_obj_sp != NULL)
911 {
912 CommandObject *cmd_obj = cmd_obj_sp.get();
913 if (cmd_obj->IsCrossRefObject ())
914 cmd_obj->AddObject (object_type);
915 }
916}
917
Chris Lattner24943d22010-06-08 16:52:24 +0000918OptionArgVectorSP
919CommandInterpreter::GetAliasOptions (const char *alias_name)
920{
921 OptionArgMap::iterator pos;
922 OptionArgVectorSP ret_val;
923
924 std::string alias (alias_name);
925
926 if (HasAliasOptions())
927 {
928 pos = m_alias_options.find (alias);
929 if (pos != m_alias_options.end())
930 ret_val = pos->second;
931 }
932
933 return ret_val;
934}
935
936void
937CommandInterpreter::RemoveAliasOptions (const char *alias_name)
938{
939 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
940 if (pos != m_alias_options.end())
941 {
942 m_alias_options.erase (pos);
943 }
944}
945
946void
947CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
948{
949 m_alias_options[alias_name] = option_arg_vector_sp;
950}
951
952bool
953CommandInterpreter::HasCommands ()
954{
955 return (!m_command_dict.empty());
956}
957
958bool
959CommandInterpreter::HasAliases ()
960{
961 return (!m_alias_dict.empty());
962}
963
964bool
965CommandInterpreter::HasUserCommands ()
966{
967 return (!m_user_dict.empty());
968}
969
970bool
971CommandInterpreter::HasAliasOptions ()
972{
973 return (!m_alias_options.empty());
974}
975
Chris Lattner24943d22010-06-08 16:52:24 +0000976void
Caroline Ticebd5c63e2010-10-12 21:57:09 +0000977CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
978 const char *alias_name,
979 Args &cmd_args,
980 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +0000981{
982 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
983
984 if (option_arg_vector_sp.get())
985 {
986 // Make sure that the alias name is the 0th element in cmd_args
987 std::string alias_name_str = alias_name;
988 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
989 cmd_args.Unshift (alias_name);
990
991 Args new_args (alias_cmd_obj->GetCommandName());
992 if (new_args.GetArgumentCount() == 2)
993 new_args.Shift();
994
995 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
996 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +0000997 std::vector<bool> used (old_size + 1, false);
998
999 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001000
1001 for (int i = 0; i < option_arg_vector->size(); ++i)
1002 {
1003 OptionArgPair option_pair = (*option_arg_vector)[i];
1004 std::string option = option_pair.first;
1005 std::string value = option_pair.second;
1006 if (option.compare ("<argument>") == 0)
1007 new_args.AppendArgument (value.c_str());
1008 else
1009 {
1010 new_args.AppendArgument (option.c_str());
1011 if (value.compare ("<no-argument>") != 0)
1012 {
1013 int index = GetOptionArgumentPosition (value.c_str());
1014 if (index == 0)
1015 // value was NOT a positional argument; must be a real value
1016 new_args.AppendArgument (value.c_str());
1017 else if (index >= cmd_args.GetArgumentCount())
1018 {
1019 result.AppendErrorWithFormat
1020 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1021 index);
1022 result.SetStatus (eReturnStatusFailed);
1023 return;
1024 }
1025 else
1026 {
1027 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001028 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001029 }
1030 }
1031 }
1032 }
1033
1034 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1035 {
1036 if (!used[j])
1037 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1038 }
1039
1040 cmd_args.Clear();
1041 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1042 }
1043 else
1044 {
1045 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1046 // This alias was not created with any options; nothing further needs to be done.
1047 return;
1048 }
1049
1050 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1051 return;
1052}
1053
1054
1055int
1056CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1057{
1058 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1059 // of zero.
1060
1061 char *cptr = (char *) in_string;
1062
1063 // Does it start with '%'
1064 if (cptr[0] == '%')
1065 {
1066 ++cptr;
1067
1068 // Is the rest of it entirely digits?
1069 if (isdigit (cptr[0]))
1070 {
1071 const char *start = cptr;
1072 while (isdigit (cptr[0]))
1073 ++cptr;
1074
1075 // We've gotten to the end of the digits; are we at the end of the string?
1076 if (cptr[0] == '\0')
1077 position = atoi (start);
1078 }
1079 }
1080
1081 return position;
1082}
1083
1084void
1085CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1086{
Greg Clayton887aa282010-10-11 01:05:37 +00001087 // Don't parse any .lldbinit files if we were asked not to
1088 if (m_skip_lldbinit_files)
1089 return;
1090
Chris Lattner24943d22010-06-08 16:52:24 +00001091 const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit";
Greg Clayton537a7a82010-10-20 20:54:39 +00001092 FileSpec init_file (init_file_path, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001093 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
1094 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
1095
1096 if (init_file.Exists())
1097 {
1098 char path[PATH_MAX];
1099 init_file.GetPath(path, sizeof(path));
1100 StreamString source_command;
Johnny Chen7c984242010-07-28 21:16:11 +00001101 source_command.Printf ("command source '%s'", path);
Chris Lattner24943d22010-06-08 16:52:24 +00001102 HandleCommand (source_command.GetData(), false, result);
1103 }
1104 else
1105 {
1106 // nothing to be done if the file doesn't exist
1107 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1108 }
1109}
1110
1111ScriptInterpreter *
1112CommandInterpreter::GetScriptInterpreter ()
1113{
Greg Clayton63094e02010-06-23 01:19:29 +00001114 CommandObject::CommandMap::iterator pos;
1115
1116 pos = m_command_dict.find ("script");
1117 if (pos != m_command_dict.end())
Chris Lattner24943d22010-06-08 16:52:24 +00001118 {
Greg Clayton63094e02010-06-23 01:19:29 +00001119 CommandObject *script_cmd_obj = pos->second.get();
Greg Clayton238c0a12010-09-18 01:14:36 +00001120 return ((CommandObjectScript *) script_cmd_obj)->GetInterpreter ();
Chris Lattner24943d22010-06-08 16:52:24 +00001121 }
Greg Clayton63094e02010-06-23 01:19:29 +00001122 return NULL;
Chris Lattner24943d22010-06-08 16:52:24 +00001123}
1124
1125
1126
1127bool
1128CommandInterpreter::GetSynchronous ()
1129{
1130 return m_synchronous_execution;
1131}
1132
1133void
1134CommandInterpreter::SetSynchronous (bool value)
1135{
Johnny Chend7a4eb02010-10-14 01:22:03 +00001136 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00001137}
1138
1139void
1140CommandInterpreter::OutputFormattedHelpText (Stream &strm,
1141 const char *word_text,
1142 const char *separator,
1143 const char *help_text,
1144 uint32_t max_word_len)
1145{
Greg Clayton238c0a12010-09-18 01:14:36 +00001146 const uint32_t max_columns = m_debugger.GetTerminalWidth();
1147
Chris Lattner24943d22010-06-08 16:52:24 +00001148 int indent_size = max_word_len + strlen (separator) + 2;
1149
1150 strm.IndentMore (indent_size);
1151
1152 int len = indent_size + strlen (help_text) + 1;
1153 char *text = (char *) malloc (len);
1154 sprintf (text, "%-*s %s %s", max_word_len, word_text, separator, help_text);
1155 if (text[len - 1] == '\n')
1156 text[--len] = '\0';
1157
1158 if (len < max_columns)
1159 {
1160 // Output it as a single line.
1161 strm.Printf ("%s", text);
1162 }
1163 else
1164 {
1165 // We need to break it up into multiple lines.
1166 bool first_line = true;
1167 int text_width;
1168 int start = 0;
1169 int end = start;
1170 int final_end = strlen (text);
1171 int sub_len;
1172
1173 while (end < final_end)
1174 {
1175 if (first_line)
1176 text_width = max_columns - 1;
1177 else
1178 text_width = max_columns - indent_size - 1;
1179
1180 // Don't start the 'text' on a space, since we're already outputting the indentation.
1181 if (!first_line)
1182 {
1183 while ((start < final_end) && (text[start] == ' '))
1184 start++;
1185 }
1186
1187 end = start + text_width;
1188 if (end > final_end)
1189 end = final_end;
1190 else
1191 {
1192 // If we're not at the end of the text, make sure we break the line on white space.
1193 while (end > start
1194 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
1195 end--;
1196 }
1197
1198 sub_len = end - start;
1199 if (start != 0)
1200 strm.EOL();
1201 if (!first_line)
1202 strm.Indent();
1203 else
1204 first_line = false;
1205 assert (start <= final_end);
1206 assert (start + sub_len <= final_end);
1207 if (sub_len > 0)
1208 strm.Write (text + start, sub_len);
1209 start = end + 1;
1210 }
1211 }
1212 strm.EOL();
1213 strm.IndentLess(indent_size);
1214 free (text);
1215}
1216
1217void
1218CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
1219 StringList &commands_found, StringList &commands_help)
1220{
1221 CommandObject::CommandMap::const_iterator pos;
1222 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
1223 CommandObject *sub_cmd_obj;
1224
1225 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
1226 {
1227 const char * command_name = pos->first.c_str();
1228 sub_cmd_obj = pos->second.get();
1229 StreamString complete_command_name;
1230
1231 complete_command_name.Printf ("%s %s", prefix, command_name);
1232
Greg Clayton238c0a12010-09-18 01:14:36 +00001233 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001234 {
1235 commands_found.AppendString (complete_command_name.GetData());
1236 commands_help.AppendString (sub_cmd_obj->GetHelp());
1237 }
1238
1239 if (sub_cmd_obj->IsMultiwordObject())
1240 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
1241 commands_help);
1242 }
1243
1244}
1245
1246void
1247CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
1248 StringList &commands_help)
1249{
1250 CommandObject::CommandMap::const_iterator pos;
1251
1252 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1253 {
1254 const char *command_name = pos->first.c_str();
1255 CommandObject *cmd_obj = pos->second.get();
1256
Greg Clayton238c0a12010-09-18 01:14:36 +00001257 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001258 {
1259 commands_found.AppendString (command_name);
1260 commands_help.AppendString (cmd_obj->GetHelp());
1261 }
1262
1263 if (cmd_obj->IsMultiwordObject())
1264 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
1265
1266 }
1267}