blob: 461c54383acb6a5792cea8f9fd24eb35d701464b [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"
Johnny Chen902e0182010-12-23 20:21:44 +000039#include "../Commands/CommandObjectVersion.h"
Chris Lattner24943d22010-06-08 16:52:24 +000040
Jim Ingham84cdc152010-06-15 19:49:27 +000041#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000042#include "lldb/Core/Debugger.h"
Jim Ingham5e16ef52010-10-04 19:49:29 +000043#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000044#include "lldb/Core/Stream.h"
45#include "lldb/Core/Timer.h"
Greg Claytoncd548032011-02-01 01:31:41 +000046#include "lldb/Host/Host.h"
Chris Lattner24943d22010-06-08 16:52:24 +000047#include "lldb/Target/Process.h"
48#include "lldb/Target/Thread.h"
49#include "lldb/Target/TargetList.h"
Greg Claytone98ac252010-11-10 04:57:04 +000050#include "lldb/Utility/CleanUp.h"
Chris Lattner24943d22010-06-08 16:52:24 +000051
52#include "lldb/Interpreter/CommandReturnObject.h"
53#include "lldb/Interpreter/CommandInterpreter.h"
Caroline Tice0aa2e552011-01-14 00:29:16 +000054#include "lldb/Interpreter/ScriptInterpreterNone.h"
55#include "lldb/Interpreter/ScriptInterpreterPython.h"
Chris Lattner24943d22010-06-08 16:52:24 +000056
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) :
Greg Clayton49ce6822010-10-31 03:01:06 +000066 Broadcaster ("lldb.command-interpreter"),
Greg Clayton63094e02010-06-23 01:19:29 +000067 m_debugger (debugger),
Greg Clayton887aa282010-10-11 01:05:37 +000068 m_synchronous_execution (synchronous_execution),
Caroline Tice0aa2e552011-01-14 00:29:16 +000069 m_skip_lldbinit_files (false),
Jim Ingham949d5ac2011-02-18 00:54:25 +000070 m_script_interpreter_ap (),
71 m_comment_char ('#')
Chris Lattner24943d22010-06-08 16:52:24 +000072{
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000073 const char *dbg_name = debugger.GetInstanceName().AsCString();
74 std::string lang_name = ScriptInterpreter::LanguageToString (script_language);
75 StreamString var_name;
76 var_name.Printf ("[%s].script-lang", dbg_name);
Caroline Tice1d2aefd2010-09-09 06:25:08 +000077 debugger.GetSettingsController()->SetVariable (var_name.GetData(), lang_name.c_str(),
78 lldb::eVarSetOperationAssign, false,
Greg Clayton49ce6822010-10-31 03:01:06 +000079 m_debugger.GetInstanceName().AsCString());
80 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
81 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
82 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Chris Lattner24943d22010-06-08 16:52:24 +000083}
84
85void
86CommandInterpreter::Initialize ()
87{
88 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
89
90 CommandReturnObject result;
91
92 LoadCommandDictionary ();
93
Chris Lattner24943d22010-06-08 16:52:24 +000094 // Set up some initial aliases.
Greg Claytonaa378b12011-02-20 02:15:07 +000095 HandleCommand ("command alias q quit", false, result);
96 HandleCommand ("command alias run process launch --", false, result);
97 HandleCommand ("command alias r process launch --", false, result);
98 HandleCommand ("command alias c process continue", false, result);
99 HandleCommand ("command alias continue process continue", false, result);
100 HandleCommand ("command alias expr expression", false, result);
101 HandleCommand ("command alias exit quit", false, result);
102 HandleCommand ("command alias b regexp-break", false, result);
103 HandleCommand ("command alias bt thread backtrace", false, result);
104 HandleCommand ("command alias si thread step-inst", false, result);
105 HandleCommand ("command alias step thread step-in", false, result);
106 HandleCommand ("command alias s thread step-in", false, result);
107 HandleCommand ("command alias next thread step-over", false, result);
108 HandleCommand ("command alias n thread step-over", false, result);
109 HandleCommand ("command alias finish thread step-out", false, result);
110 HandleCommand ("command alias x memory read", false, result);
111 HandleCommand ("command alias l source list", false, result);
112 HandleCommand ("command alias list source list", false, result);
113 HandleCommand ("command alias p frame variable", false, result);
114 HandleCommand ("command alias print frame variable", false, result);
115 HandleCommand ("command alias po expression -o --", false, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000116}
117
Chris Lattner24943d22010-06-08 16:52:24 +0000118const char *
119CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
120{
121 // This function has not yet been implemented.
122
123 // Look for any embedded script command
124 // If found,
125 // get interpreter object from the command dictionary,
126 // call execute_one_command on it,
127 // get the results as a string,
128 // substitute that string for current stuff.
129
130 return arg;
131}
132
133
134void
135CommandInterpreter::LoadCommandDictionary ()
136{
137 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
138
139 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
140 //
141 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
142 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
143 // the cross-referencing stuff) are created!!!
144 //
145 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
146
147
148 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
149 // are created. This is so that when another command is created that needs to go into a crossref object,
150 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
151 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
152
Chris Lattner24943d22010-06-08 16:52:24 +0000153 // Non-CommandObjectCrossref commands can now be created.
154
Caroline Tice5bc8c972010-09-20 20:44:43 +0000155 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000156
Greg Clayton238c0a12010-09-18 01:14:36 +0000157 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000158 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000159 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000160 m_command_dict["commands"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000161 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
162 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
163 m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000164 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000165 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000166 m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
167 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
168 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
169 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000170 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000171 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000172 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000173 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000174 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000175 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
176 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000177 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000178
179 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000180 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
181 "regexp-break",
Caroline Ticec1ad82e2010-09-07 22:38:08 +0000182 "Set a breakpoint using a regular expression to specify the location.",
Caroline Tice43b014a2010-10-04 22:28:36 +0000183 "regexp-break [<filename>:<linenum>]\nregexp-break [<address>]\nregexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000184 if (break_regex_cmd_ap.get())
185 {
186 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
187 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
188 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
189 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list") &&
190 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
Greg Claytonb01000f2011-01-17 03:46:26 +0000191 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000192 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
193 {
194 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
195 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
196 }
197 }
198}
199
200int
201CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
202 StringList &matches)
203{
204 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
205
206 if (include_aliases)
207 {
208 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
209 }
210
211 return matches.GetSize();
212}
213
214CommandObjectSP
215CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
216{
217 CommandObject::CommandMap::iterator pos;
218 CommandObjectSP ret_val;
219
220 std::string cmd(cmd_cstr);
221
222 if (HasCommands())
223 {
224 pos = m_command_dict.find(cmd);
225 if (pos != m_command_dict.end())
226 ret_val = pos->second;
227 }
228
229 if (include_aliases && HasAliases())
230 {
231 pos = m_alias_dict.find(cmd);
232 if (pos != m_alias_dict.end())
233 ret_val = pos->second;
234 }
235
236 if (HasUserCommands())
237 {
238 pos = m_user_dict.find(cmd);
239 if (pos != m_user_dict.end())
240 ret_val = pos->second;
241 }
242
243 if (!exact && ret_val == NULL)
244 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000245 // We will only get into here if we didn't find any exact matches.
246
247 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
248
Chris Lattner24943d22010-06-08 16:52:24 +0000249 StringList local_matches;
250 if (matches == NULL)
251 matches = &local_matches;
252
Jim Inghamd40f8a62010-07-06 22:46:59 +0000253 unsigned int num_cmd_matches = 0;
254 unsigned int num_alias_matches = 0;
255 unsigned int num_user_matches = 0;
256
257 // Look through the command dictionaries one by one, and if we get only one match from any of
258 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
259
Chris Lattner24943d22010-06-08 16:52:24 +0000260 if (HasCommands())
261 {
262 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
263 }
264
265 if (num_cmd_matches == 1)
266 {
267 cmd.assign(matches->GetStringAtIndex(0));
268 pos = m_command_dict.find(cmd);
269 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000270 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000271 }
272
Jim Ingham9a574172010-06-24 20:28:42 +0000273 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000274 {
275 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
276
277 }
278
Jim Inghamd40f8a62010-07-06 22:46:59 +0000279 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000280 {
281 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
282 pos = m_alias_dict.find(cmd);
283 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000284 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000285 }
286
Jim Ingham9a574172010-06-24 20:28:42 +0000287 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000288 {
289 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
290 }
291
Jim Inghamd40f8a62010-07-06 22:46:59 +0000292 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000293 {
294 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
295
296 pos = m_user_dict.find (cmd);
297 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000298 user_match_sp = pos->second;
299 }
300
301 // If we got exactly one match, return that, otherwise return the match list.
302
303 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
304 {
305 if (num_cmd_matches)
306 return real_match_sp;
307 else if (num_alias_matches)
308 return alias_match_sp;
309 else
310 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000311 }
312 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000313 else if (matches && ret_val != NULL)
314 {
315 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000316 }
317
318
319 return ret_val;
320}
321
Jim Inghamd40f8a62010-07-06 22:46:59 +0000322CommandObjectSP
323CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000324{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000325 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
326 CommandObjectSP ret_val; // Possibly empty return value.
327
328 if (cmd_cstr == NULL)
329 return ret_val;
330
331 if (cmd_words.GetArgumentCount() == 1)
332 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
333 else
334 {
335 // We have a multi-word command (seemingly), so we need to do more work.
336 // First, get the cmd_obj_sp for the first word in the command.
337 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
338 if (cmd_obj_sp.get() != NULL)
339 {
340 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
341 // command name), and find the appropriate sub-command SP for each command word....
342 size_t end = cmd_words.GetArgumentCount();
343 for (size_t j= 1; j < end; ++j)
344 {
345 if (cmd_obj_sp->IsMultiwordObject())
346 {
347 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
348 (cmd_words.GetArgumentAtIndex (j));
349 if (cmd_obj_sp.get() == NULL)
350 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
351 return ret_val;
352 }
353 else
354 // We have more words in the command name, but we don't have a multiword object. Fail and return
355 // empty 'ret_val'.
356 return ret_val;
357 }
358 // We successfully looped through all the command words and got valid command objects for them. Assign the
359 // last object retrieved to 'ret_val'.
360 ret_val = cmd_obj_sp;
361 }
362 }
363 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000364}
365
366CommandObject *
367CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
368{
369 return GetCommandSPExact (cmd_cstr, include_aliases).get();
370}
371
372CommandObject *
373CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
374{
375 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
376
377 // If we didn't find an exact match to the command string in the commands, look in
378 // the aliases.
379
380 if (command_obj == NULL)
381 {
382 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
383 }
384
385 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
386 // in both the commands and the aliases.
387
388 if (command_obj == NULL)
389 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
390
391 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000392}
393
394bool
395CommandInterpreter::CommandExists (const char *cmd)
396{
397 return m_command_dict.find(cmd) != m_command_dict.end();
398}
399
400bool
401CommandInterpreter::AliasExists (const char *cmd)
402{
403 return m_alias_dict.find(cmd) != m_alias_dict.end();
404}
405
406bool
407CommandInterpreter::UserCommandExists (const char *cmd)
408{
409 return m_user_dict.find(cmd) != m_user_dict.end();
410}
411
412void
413CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
414{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000415 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000416 m_alias_dict[alias_name] = command_obj_sp;
417}
418
419bool
420CommandInterpreter::RemoveAlias (const char *alias_name)
421{
422 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
423 if (pos != m_alias_dict.end())
424 {
425 m_alias_dict.erase(pos);
426 return true;
427 }
428 return false;
429}
430bool
431CommandInterpreter::RemoveUser (const char *alias_name)
432{
433 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
434 if (pos != m_user_dict.end())
435 {
436 m_user_dict.erase(pos);
437 return true;
438 }
439 return false;
440}
441
Chris Lattner24943d22010-06-08 16:52:24 +0000442void
443CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
444{
445 help_string.Printf ("'%s", command_name);
446 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
447
448 if (option_arg_vector_sp != NULL)
449 {
450 OptionArgVector *options = option_arg_vector_sp.get();
451 for (int i = 0; i < options->size(); ++i)
452 {
453 OptionArgPair cur_option = (*options)[i];
454 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000455 OptionArgValue value_pair = cur_option.second;
456 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000457 if (opt.compare("<argument>") == 0)
458 {
459 help_string.Printf (" %s", value.c_str());
460 }
461 else
462 {
463 help_string.Printf (" %s", opt.c_str());
464 if ((value.compare ("<no-argument>") != 0)
465 && (value.compare ("<need-argument") != 0))
466 {
467 help_string.Printf (" %s", value.c_str());
468 }
469 }
470 }
471 }
472
473 help_string.Printf ("'");
474}
475
Greg Clayton65124ea2010-08-26 22:05:43 +0000476size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000477CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
478{
479 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000480 CommandObject::CommandMap::const_iterator end = dict.end();
481 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000482
Greg Clayton65124ea2010-08-26 22:05:43 +0000483 for (pos = dict.begin(); pos != end; ++pos)
484 {
485 size_t len = pos->first.size();
486 if (max_len < len)
487 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000488 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000489 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000490}
491
492void
493CommandInterpreter::GetHelp (CommandReturnObject &result)
494{
495 CommandObject::CommandMap::const_iterator pos;
496 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
497 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000498 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000499
500 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
501 {
502 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
503 max_len);
504 }
505 result.AppendMessage("");
506
507 if (m_alias_dict.size() > 0)
508 {
Jim Inghame3663e82010-10-22 18:47:16 +0000509 result.AppendMessage("The following is a list of your current command abbreviations "
510 "(see 'help commands alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000511 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000512 max_len = FindLongestCommandWord (m_alias_dict);
513
Chris Lattner24943d22010-06-08 16:52:24 +0000514 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
515 {
516 StreamString sstr;
517 StreamString translation_and_help;
518 std::string entry_name = pos->first;
519 std::string second_entry = pos->second.get()->GetCommandName();
520 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
521
522 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
523 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
524 translation_and_help.GetData(), max_len);
525 }
526 result.AppendMessage("");
527 }
528
529 if (m_user_dict.size() > 0)
530 {
531 result.AppendMessage ("The following is a list of your current user-defined commands:");
532 result.AppendMessage("");
533 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
534 {
535 result.AppendMessageWithFormat ("%s -- %s\n", pos->first.c_str(), pos->second->GetHelp());
536 }
537 result.AppendMessage("");
538 }
539
540 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
541}
542
Caroline Ticee0da7a52010-12-09 22:52:49 +0000543CommandObject *
544CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000545{
Caroline Ticee0da7a52010-12-09 22:52:49 +0000546 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
547 // eventually be invoked by the given command line.
548
549 CommandObject *cmd_obj = NULL;
550 std::string white_space (" \t\v");
551 size_t start = command_string.find_first_not_of (white_space);
552 size_t end = 0;
553 bool done = false;
554 while (!done)
555 {
556 if (start != std::string::npos)
557 {
558 // Get the next word from command_string.
559 end = command_string.find_first_of (white_space, start);
560 if (end == std::string::npos)
561 end = command_string.size();
562 std::string cmd_word = command_string.substr (start, end - start);
563
564 if (cmd_obj == NULL)
565 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
566 // command or alias.
567 cmd_obj = GetCommandObject (cmd_word.c_str());
568 else if (cmd_obj->IsMultiwordObject ())
569 {
570 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
571 CommandObject *sub_cmd_obj =
572 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
573 if (sub_cmd_obj)
574 cmd_obj = sub_cmd_obj;
575 else // cmd_word was not a valid sub-command word, so we are donee
576 done = true;
577 }
578 else
579 // We have a cmd_obj and it is not a multi-word object, so we are done.
580 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000581
Caroline Ticee0da7a52010-12-09 22:52:49 +0000582 // If we didn't find a valid command object, or our command object is not a multi-word object, or
583 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
584 // next word.
585
586 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
587 done = true;
588 else
589 start = command_string.find_first_not_of (white_space, end);
590 }
591 else
592 // Unable to find any more words.
593 done = true;
594 }
595
596 if (end == command_string.size())
597 command_string.clear();
598 else
599 command_string = command_string.substr(end);
600
601 return cmd_obj;
602}
603
604bool
605CommandInterpreter::StripFirstWord (std::string &command_string, std::string &word)
606{
607 std::string white_space (" \t\v");
608 size_t start;
609 size_t end;
610
611 start = command_string.find_first_not_of (white_space);
612 if (start != std::string::npos)
613 {
614 end = command_string.find_first_of (white_space, start);
615 if (end != std::string::npos)
616 {
617 word = command_string.substr (start, end - start);
618 command_string = command_string.substr (end);
619 size_t pos = command_string.find_first_not_of (white_space);
620 if ((pos != 0) && (pos != std::string::npos))
621 command_string = command_string.substr (pos);
622 }
623 else
624 {
625 word = command_string.substr (start);
626 command_string.erase();
627 }
628
629 }
630 return true;
631}
632
633void
634CommandInterpreter::BuildAliasResult (const char *alias_name, std::string &raw_input_string, std::string &alias_result,
635 CommandObject *&alias_cmd_obj, CommandReturnObject &result)
636{
637 Args cmd_args (raw_input_string.c_str());
638 alias_cmd_obj = GetCommandObject (alias_name);
639 StreamString result_str;
640
641 if (alias_cmd_obj)
642 {
643 std::string alias_name_str = alias_name;
644 if ((cmd_args.GetArgumentCount() == 0)
645 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
646 cmd_args.Unshift (alias_name);
647
648 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
649 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
650
651 if (option_arg_vector_sp.get())
652 {
653 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
654
655 for (int i = 0; i < option_arg_vector->size(); ++i)
656 {
657 OptionArgPair option_pair = (*option_arg_vector)[i];
658 OptionArgValue value_pair = option_pair.second;
659 int value_type = value_pair.first;
660 std::string option = option_pair.first;
661 std::string value = value_pair.second;
662 if (option.compare ("<argument>") == 0)
663 result_str.Printf (" %s", value.c_str());
664 else
665 {
666 result_str.Printf (" %s", option.c_str());
667 if (value_type != optional_argument)
668 result_str.Printf (" ");
669 if (value.compare ("<no_argument>") != 0)
670 {
671 int index = GetOptionArgumentPosition (value.c_str());
672 if (index == 0)
673 result_str.Printf ("%s", value.c_str());
674 else if (index >= cmd_args.GetArgumentCount())
675 {
676
677 result.AppendErrorWithFormat
678 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
679 index);
680 result.SetStatus (eReturnStatusFailed);
681 return;
682 }
683 else
684 {
685 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
686 if (strpos != std::string::npos)
687 raw_input_string = raw_input_string.erase (strpos,
688 strlen (cmd_args.GetArgumentAtIndex (index)));
689 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
690 }
691 }
692 }
693 }
694 }
695
696 alias_result = result_str.GetData();
697 }
698}
699
700bool
701CommandInterpreter::HandleCommand (const char *command_line,
702 bool add_to_history,
703 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +0000704 ExecutionContext *override_context,
705 bool repeat_on_empty_command)
706
Caroline Ticee0da7a52010-12-09 22:52:49 +0000707{
Jim Ingham949d5ac2011-02-18 00:54:25 +0000708
Caroline Ticee0da7a52010-12-09 22:52:49 +0000709 bool done = false;
710 CommandObject *cmd_obj = NULL;
711 std::string next_word;
712 bool wants_raw_input = false;
713 std::string command_string (command_line);
714
715 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +0000716 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
717
718 // Make a scoped cleanup object that will clear the crash description string
719 // on exit of this function.
720 lldb_utility::CleanUp <const char *, void> crash_description_cleanup(NULL, Host::SetCrashDescription);
721
Caroline Ticee0da7a52010-12-09 22:52:49 +0000722 if (log)
723 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +0000724
Jim Inghamabab14b2010-11-04 23:08:45 +0000725 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
726
Greg Clayton63094e02010-06-23 01:19:29 +0000727 m_debugger.UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +0000728
Jim Ingham949d5ac2011-02-18 00:54:25 +0000729 bool empty_command = false;
730 bool comment_command = false;
731 if (command_string.empty())
732 empty_command = true;
733 else
Chris Lattner24943d22010-06-08 16:52:24 +0000734 {
Jim Ingham949d5ac2011-02-18 00:54:25 +0000735 const char *k_space_characters = "\t\n\v\f\r ";
736
737 size_t non_space = command_string.find_first_not_of (k_space_characters);
738 // Check for empty line or comment line (lines whose first
739 // non-space character is the comment character for this interpreter)
740 if (non_space == std::string::npos)
741 empty_command = true;
742 else if (command_string[non_space] == m_comment_char)
743 comment_command = true;
744 }
745
746 if (empty_command)
747 {
748 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +0000749 {
Jim Ingham949d5ac2011-02-18 00:54:25 +0000750 if (m_command_history.empty())
751 {
752 result.AppendError ("empty command");
753 result.SetStatus(eReturnStatusFailed);
754 return false;
755 }
756 else
757 {
758 command_line = m_repeat_command.c_str();
759 command_string = command_line;
760 if (m_repeat_command.empty())
761 {
762 result.AppendErrorWithFormat("No auto repeat.\n");
763 result.SetStatus (eReturnStatusFailed);
764 return false;
765 }
766 }
767 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000768 }
769 else
770 {
Jim Ingham949d5ac2011-02-18 00:54:25 +0000771 result.SetStatus (eReturnStatusSuccessFinishNoResult);
772 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000773 }
Jim Ingham949d5ac2011-02-18 00:54:25 +0000774 }
775 else if (comment_command)
776 {
777 result.SetStatus (eReturnStatusSuccessFinishNoResult);
778 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000779 }
780
Caroline Ticee0da7a52010-12-09 22:52:49 +0000781 // Phase 1.
782
783 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
784 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
785 // the user could have specified an alias, and in translating the alias there may also be command options and/or
786 // even data (including raw text strings) that need to be found and inserted into the command line as part of
787 // the translation. So this first step is plain look-up & replacement, resulting in three things: 1). the command
Greg Clayton5d187e52011-01-08 20:28:42 +0000788 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +0000789 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +0000790
Caroline Ticee0da7a52010-12-09 22:52:49 +0000791 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000792 size_t actual_cmd_name_len = 0;
Caroline Ticee0da7a52010-12-09 22:52:49 +0000793 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +0000794 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000795 StripFirstWord (command_string, next_word);
796 if (!cmd_obj && AliasExists (next_word.c_str()))
Chris Lattner24943d22010-06-08 16:52:24 +0000797 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000798 std::string alias_result;
799 BuildAliasResult (next_word.c_str(), command_string, alias_result, cmd_obj, result);
800 revised_command_line.Printf ("%s", alias_result.c_str());
801 if (cmd_obj)
Caroline Tice56d2fc42010-12-14 18:51:39 +0000802 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000803 wants_raw_input = cmd_obj->WantsRawCommandString ();
Caroline Tice56d2fc42010-12-14 18:51:39 +0000804 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
805 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000806 }
807 else if (!cmd_obj)
808 {
809 cmd_obj = GetCommandObject (next_word.c_str());
810 if (cmd_obj)
Chris Lattner24943d22010-06-08 16:52:24 +0000811 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000812 actual_cmd_name_len += next_word.length();
Caroline Ticee0da7a52010-12-09 22:52:49 +0000813 revised_command_line.Printf ("%s", next_word.c_str());
814 wants_raw_input = cmd_obj->WantsRawCommandString ();
Chris Lattner24943d22010-06-08 16:52:24 +0000815 }
816 else
817 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000818 revised_command_line.Printf ("%s", next_word.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000819 }
820 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000821 else if (cmd_obj->IsMultiwordObject ())
822 {
823 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
824 if (sub_cmd_obj)
825 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000826 actual_cmd_name_len += next_word.length() + 1;
Caroline Ticee0da7a52010-12-09 22:52:49 +0000827 revised_command_line.Printf (" %s", next_word.c_str());
828 cmd_obj = sub_cmd_obj;
829 wants_raw_input = cmd_obj->WantsRawCommandString ();
830 }
831 else
832 {
833 revised_command_line.Printf (" %s", next_word.c_str());
834 done = true;
835 }
836 }
837 else
838 {
839 revised_command_line.Printf (" %s", next_word.c_str());
840 done = true;
841 }
842
843 if (cmd_obj == NULL)
844 {
845 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
846 result.SetStatus (eReturnStatusFailed);
847 return false;
848 }
849
850 next_word.erase ();
851 if (command_string.length() == 0)
852 done = true;
853
Chris Lattner24943d22010-06-08 16:52:24 +0000854 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000855
856 if (command_string.size() > 0)
857 revised_command_line.Printf (" %s", command_string.c_str());
858
859 // End of Phase 1.
860 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
861 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
862 // fully translated with all substitutions & translations taken care of (still in raw text format); and
863 // wants_raw_input specifies whether the Execute method expects raw input or not.
864
865
866 if (log)
867 {
868 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
869 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
870 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
871 }
872
873 // Phase 2.
874 // Take care of things like setting up the history command & calling the appropriate Execute method on the
875 // CommandObject, with the appropriate arguments.
876
877 if (cmd_obj != NULL)
878 {
879 if (add_to_history)
880 {
881 Args command_args (revised_command_line.GetData());
882 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
883 if (repeat_command != NULL)
884 m_repeat_command.assign(repeat_command);
885 else
886 m_repeat_command.assign(command_line);
887
888 m_command_history.push_back (command_line);
889 }
890
891 command_string = revised_command_line.GetData();
892 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000893 std::string remainder;
894 if (actual_cmd_name_len < command_string.length())
895 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
896 // than cmd_obj->GetCommandName(), because name completion
897 // allows users to enter short versions of the names,
898 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +0000899
900 // Remove any initial spaces
901 std::string white_space (" \t\v");
902 size_t pos = remainder.find_first_not_of (white_space);
903 if (pos != 0 && pos != std::string::npos)
904 remainder = remainder.substr (pos);
905
906 if (log)
907 log->Printf ("HandleCommand, command line after removing command name(s): '%s'\n", remainder.c_str());
908
909
910 if (wants_raw_input)
911 cmd_obj->ExecuteRawCommandString (remainder.c_str(), result);
912 else
913 {
914 Args cmd_args (remainder.c_str());
915 cmd_obj->ExecuteWithOptions (cmd_args, result);
916 }
917 }
918 else
919 {
920 // We didn't find the first command object, so complete the first argument.
921 Args command_args (revised_command_line.GetData());
922 StringList matches;
923 int num_matches;
924 int cursor_index = 0;
925 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
926 bool word_complete;
927 num_matches = HandleCompletionMatches (command_args,
928 cursor_index,
929 cursor_char_position,
930 0,
931 -1,
932 word_complete,
933 matches);
934
935 if (num_matches > 0)
936 {
937 std::string error_msg;
938 error_msg.assign ("ambiguous command '");
939 error_msg.append(command_args.GetArgumentAtIndex(0));
940 error_msg.append ("'.");
941
942 error_msg.append (" Possible completions:");
943 for (int i = 0; i < num_matches; i++)
944 {
945 error_msg.append ("\n\t");
946 error_msg.append (matches.GetStringAtIndex (i));
947 }
948 error_msg.append ("\n");
949 result.AppendRawError (error_msg.c_str(), error_msg.size());
950 }
951 else
952 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
953
954 result.SetStatus (eReturnStatusFailed);
955 }
956
Chris Lattner24943d22010-06-08 16:52:24 +0000957 return result.Succeeded();
958}
959
960int
961CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
962 int &cursor_index,
963 int &cursor_char_position,
964 int match_start_point,
965 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +0000966 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000967 StringList &matches)
968{
969 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000970 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +0000971
972 // For any of the command completions a unique match will be a complete word.
973 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000974
975 if (cursor_index == -1)
976 {
977 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +0000978 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000979 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
980 }
981 else if (cursor_index == 0)
982 {
983 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000984 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000985 num_command_matches = matches.GetSize();
986
987 if (num_command_matches == 1
988 && cmd_obj && cmd_obj->IsMultiwordObject()
989 && matches.GetStringAtIndex(0) != NULL
990 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
991 {
992 look_for_subcommand = true;
993 num_command_matches = 0;
994 matches.DeleteStringAtIndex(0);
995 parsed_line.AppendArgument ("");
996 cursor_index++;
997 cursor_char_position = 0;
998 }
999 }
1000
1001 if (cursor_index > 0 || look_for_subcommand)
1002 {
1003 // We are completing further on into a commands arguments, so find the command and tell it
1004 // to complete the command.
1005 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001006 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001007 if (command_object == NULL)
1008 {
1009 return 0;
1010 }
1011 else
1012 {
1013 parsed_line.Shift();
1014 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001015 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001016 cursor_index,
1017 cursor_char_position,
1018 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001019 max_return_elements,
1020 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001021 matches);
1022 }
1023 }
1024
1025 return num_command_matches;
1026
1027}
1028
1029int
1030CommandInterpreter::HandleCompletion (const char *current_line,
1031 const char *cursor,
1032 const char *last_char,
1033 int match_start_point,
1034 int max_return_elements,
1035 StringList &matches)
1036{
1037 // We parse the argument up to the cursor, so the last argument in parsed_line is
1038 // the one containing the cursor, and the cursor is after the last character.
1039
1040 Args parsed_line(current_line, last_char - current_line);
1041 Args partial_parsed_line(current_line, cursor - current_line);
1042
1043 int num_args = partial_parsed_line.GetArgumentCount();
1044 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1045 int cursor_char_position;
1046
1047 if (cursor_index == -1)
1048 cursor_char_position = 0;
1049 else
1050 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001051
1052 if (cursor > current_line && cursor[-1] == ' ')
1053 {
1054 // We are just after a space. If we are in an argument, then we will continue
1055 // parsing, but if we are between arguments, then we have to complete whatever the next
1056 // element would be.
1057 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1058 // protected by a quote) then the space will also be in the parsed argument...
1059
1060 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1061 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1062 {
1063 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1064 cursor_index++;
1065 cursor_char_position = 0;
1066 }
1067 }
Chris Lattner24943d22010-06-08 16:52:24 +00001068
1069 int num_command_matches;
1070
1071 matches.Clear();
1072
1073 // Only max_return_elements == -1 is supported at present:
1074 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001075 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001076 num_command_matches = HandleCompletionMatches (parsed_line,
1077 cursor_index,
1078 cursor_char_position,
1079 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001080 max_return_elements,
1081 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001082 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001083
1084 if (num_command_matches <= 0)
1085 return num_command_matches;
1086
1087 if (num_args == 0)
1088 {
1089 // If we got an empty string, insert nothing.
1090 matches.InsertStringAtIndex(0, "");
1091 }
1092 else
1093 {
1094 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1095 // put an empty string in element 0.
1096 std::string command_partial_str;
1097 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001098 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1099 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001100
1101 std::string common_prefix;
1102 matches.LongestCommonPrefix (common_prefix);
1103 int partial_name_len = command_partial_str.size();
1104
1105 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001106 // Only do this if the completer told us this was a complete word, however...
1107 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001108 {
1109 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1110 if (quote_char != '\0')
1111 common_prefix.push_back(quote_char);
1112
1113 common_prefix.push_back(' ');
1114 }
1115 common_prefix.erase (0, partial_name_len);
1116 matches.InsertStringAtIndex(0, common_prefix.c_str());
1117 }
1118 return num_command_matches;
1119}
1120
Chris Lattner24943d22010-06-08 16:52:24 +00001121
1122CommandInterpreter::~CommandInterpreter ()
1123{
1124}
1125
1126const char *
1127CommandInterpreter::GetPrompt ()
1128{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001129 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001130}
1131
1132void
1133CommandInterpreter::SetPrompt (const char *new_prompt)
1134{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001135 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001136}
1137
Jim Ingham5e16ef52010-10-04 19:49:29 +00001138size_t
Greg Clayton58928562011-02-09 01:08:52 +00001139CommandInterpreter::GetConfirmationInputReaderCallback
1140(
1141 void *baton,
1142 InputReader &reader,
1143 lldb::InputReaderAction action,
1144 const char *bytes,
1145 size_t bytes_len
1146)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001147{
Greg Clayton58928562011-02-09 01:08:52 +00001148 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001149 bool *response_ptr = (bool *) baton;
1150
1151 switch (action)
1152 {
1153 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001154 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001155 {
1156 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001157 {
Greg Clayton58928562011-02-09 01:08:52 +00001158 out_file.Printf ("%s", reader.GetPrompt());
1159 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001160 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001161 }
1162 break;
1163
1164 case eInputReaderDeactivate:
1165 break;
1166
1167 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001168 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001169 {
Greg Clayton58928562011-02-09 01:08:52 +00001170 out_file.Printf ("%s", reader.GetPrompt());
1171 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001172 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001173 break;
1174
1175 case eInputReaderGotToken:
1176 if (bytes_len == 0)
1177 {
1178 reader.SetIsDone(true);
1179 }
1180 else if (bytes[0] == 'y')
1181 {
1182 *response_ptr = true;
1183 reader.SetIsDone(true);
1184 }
1185 else if (bytes[0] == 'n')
1186 {
1187 *response_ptr = false;
1188 reader.SetIsDone(true);
1189 }
1190 else
1191 {
Greg Clayton58928562011-02-09 01:08:52 +00001192 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001193 {
Greg Clayton58928562011-02-09 01:08:52 +00001194 out_file.Printf ("Please answer \"y\" or \"n\"\n%s", reader.GetPrompt());
1195 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001196 }
1197 }
1198 break;
1199
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001200 case eInputReaderInterrupt:
1201 case eInputReaderEndOfFile:
1202 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1203 reader.SetIsDone (true);
1204 break;
1205
Jim Ingham5e16ef52010-10-04 19:49:29 +00001206 case eInputReaderDone:
1207 break;
1208 }
1209
1210 return bytes_len;
1211
1212}
1213
1214bool
1215CommandInterpreter::Confirm (const char *message, bool default_answer)
1216{
Jim Ingham93057472010-10-04 22:44:14 +00001217 // Check AutoConfirm first:
1218 if (m_debugger.GetAutoConfirm())
1219 return default_answer;
1220
Jim Ingham5e16ef52010-10-04 19:49:29 +00001221 InputReaderSP reader_sp (new InputReader(GetDebugger()));
1222 bool response = default_answer;
1223 if (reader_sp)
1224 {
1225 std::string prompt(message);
1226 prompt.append(": [");
1227 if (default_answer)
1228 prompt.append ("Y/n] ");
1229 else
1230 prompt.append ("y/N] ");
1231
1232 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1233 &response, // baton
1234 eInputReaderGranularityLine, // token size, to pass to callback function
1235 NULL, // end token
1236 prompt.c_str(), // prompt
1237 true)); // echo input
1238 if (err.Success())
1239 {
1240 GetDebugger().PushInputReader (reader_sp);
1241 }
1242 reader_sp->WaitOnReaderIsDone();
1243 }
1244 return response;
1245}
1246
1247
Chris Lattner24943d22010-06-08 16:52:24 +00001248void
1249CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1250{
Jim Inghamd40f8a62010-07-06 22:46:59 +00001251 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001252
1253 if (cmd_obj_sp != NULL)
1254 {
1255 CommandObject *cmd_obj = cmd_obj_sp.get();
1256 if (cmd_obj->IsCrossRefObject ())
1257 cmd_obj->AddObject (object_type);
1258 }
1259}
1260
Chris Lattner24943d22010-06-08 16:52:24 +00001261OptionArgVectorSP
1262CommandInterpreter::GetAliasOptions (const char *alias_name)
1263{
1264 OptionArgMap::iterator pos;
1265 OptionArgVectorSP ret_val;
1266
1267 std::string alias (alias_name);
1268
1269 if (HasAliasOptions())
1270 {
1271 pos = m_alias_options.find (alias);
1272 if (pos != m_alias_options.end())
1273 ret_val = pos->second;
1274 }
1275
1276 return ret_val;
1277}
1278
1279void
1280CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1281{
1282 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1283 if (pos != m_alias_options.end())
1284 {
1285 m_alias_options.erase (pos);
1286 }
1287}
1288
1289void
1290CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1291{
1292 m_alias_options[alias_name] = option_arg_vector_sp;
1293}
1294
1295bool
1296CommandInterpreter::HasCommands ()
1297{
1298 return (!m_command_dict.empty());
1299}
1300
1301bool
1302CommandInterpreter::HasAliases ()
1303{
1304 return (!m_alias_dict.empty());
1305}
1306
1307bool
1308CommandInterpreter::HasUserCommands ()
1309{
1310 return (!m_user_dict.empty());
1311}
1312
1313bool
1314CommandInterpreter::HasAliasOptions ()
1315{
1316 return (!m_alias_options.empty());
1317}
1318
Chris Lattner24943d22010-06-08 16:52:24 +00001319void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001320CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
1321 const char *alias_name,
1322 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00001323 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001324 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00001325{
1326 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00001327
1328 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00001329
Caroline Tice44c841d2010-12-07 19:58:26 +00001330 // Make sure that the alias name is the 0th element in cmd_args
1331 std::string alias_name_str = alias_name;
1332 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1333 cmd_args.Unshift (alias_name);
1334
1335 Args new_args (alias_cmd_obj->GetCommandName());
1336 if (new_args.GetArgumentCount() == 2)
1337 new_args.Shift();
1338
Chris Lattner24943d22010-06-08 16:52:24 +00001339 if (option_arg_vector_sp.get())
1340 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001341 if (wants_raw_input)
1342 {
1343 // We have a command that both has command options and takes raw input. Make *sure* it has a
1344 // " -- " in the right place in the raw_input_string.
1345 size_t pos = raw_input_string.find(" -- ");
1346 if (pos == std::string::npos)
1347 {
1348 // None found; assume it goes at the beginning of the raw input string
1349 raw_input_string.insert (0, " -- ");
1350 }
1351 }
Chris Lattner24943d22010-06-08 16:52:24 +00001352
1353 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1354 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001355 std::vector<bool> used (old_size + 1, false);
1356
1357 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001358
1359 for (int i = 0; i < option_arg_vector->size(); ++i)
1360 {
1361 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00001362 OptionArgValue value_pair = option_pair.second;
1363 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00001364 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00001365 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00001366 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001367 {
1368 if (!wants_raw_input
1369 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
1370 new_args.AppendArgument (value.c_str());
1371 }
Chris Lattner24943d22010-06-08 16:52:24 +00001372 else
1373 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001374 if (value_type != optional_argument)
1375 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001376 if (value.compare ("<no-argument>") != 0)
1377 {
1378 int index = GetOptionArgumentPosition (value.c_str());
1379 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001380 {
Chris Lattner24943d22010-06-08 16:52:24 +00001381 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00001382 if (value_type != optional_argument)
1383 new_args.AppendArgument (value.c_str());
1384 else
1385 {
1386 char buffer[255];
1387 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
1388 new_args.AppendArgument (buffer);
1389 }
1390
1391 }
Chris Lattner24943d22010-06-08 16:52:24 +00001392 else if (index >= cmd_args.GetArgumentCount())
1393 {
1394 result.AppendErrorWithFormat
1395 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1396 index);
1397 result.SetStatus (eReturnStatusFailed);
1398 return;
1399 }
1400 else
1401 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001402 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
1403 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1404 if (strpos != std::string::npos)
1405 {
1406 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
1407 }
1408
1409 if (value_type != optional_argument)
1410 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
1411 else
1412 {
1413 char buffer[255];
1414 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
1415 cmd_args.GetArgumentAtIndex (index));
1416 new_args.AppendArgument (buffer);
1417 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001418 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001419 }
1420 }
1421 }
1422 }
1423
1424 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1425 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001426 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00001427 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1428 }
1429
1430 cmd_args.Clear();
1431 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1432 }
1433 else
1434 {
1435 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00001436 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
1437 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
1438 // input string.
1439 if (wants_raw_input)
1440 {
1441 cmd_args.Clear();
1442 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1443 }
Chris Lattner24943d22010-06-08 16:52:24 +00001444 return;
1445 }
1446
1447 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1448 return;
1449}
1450
1451
1452int
1453CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1454{
1455 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1456 // of zero.
1457
1458 char *cptr = (char *) in_string;
1459
1460 // Does it start with '%'
1461 if (cptr[0] == '%')
1462 {
1463 ++cptr;
1464
1465 // Is the rest of it entirely digits?
1466 if (isdigit (cptr[0]))
1467 {
1468 const char *start = cptr;
1469 while (isdigit (cptr[0]))
1470 ++cptr;
1471
1472 // We've gotten to the end of the digits; are we at the end of the string?
1473 if (cptr[0] == '\0')
1474 position = atoi (start);
1475 }
1476 }
1477
1478 return position;
1479}
1480
1481void
1482CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1483{
Greg Clayton887aa282010-10-11 01:05:37 +00001484 // Don't parse any .lldbinit files if we were asked not to
1485 if (m_skip_lldbinit_files)
1486 return;
1487
Chris Lattner24943d22010-06-08 16:52:24 +00001488 const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit";
Greg Clayton537a7a82010-10-20 20:54:39 +00001489 FileSpec init_file (init_file_path, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001490 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
1491 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
1492
1493 if (init_file.Exists())
1494 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001495 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
1496 bool stop_on_continue = true;
1497 bool stop_on_error = false;
1498 bool echo_commands = false;
1499 bool print_results = false;
1500
1501 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, result);
Chris Lattner24943d22010-06-08 16:52:24 +00001502 }
1503 else
1504 {
1505 // nothing to be done if the file doesn't exist
1506 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1507 }
1508}
1509
Jim Ingham949d5ac2011-02-18 00:54:25 +00001510void
Jim Inghama4fede32011-03-11 01:51:49 +00001511CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001512 ExecutionContext *override_context,
1513 bool stop_on_continue,
1514 bool stop_on_error,
1515 bool echo_commands,
1516 bool print_results,
1517 CommandReturnObject &result)
1518{
1519 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00001520
1521 // If we are going to continue past a "continue" then we need to run the commands synchronously.
1522 // Make sure you reset this value anywhere you return from the function.
1523
1524 bool old_async_execution = m_debugger.GetAsyncExecution();
1525
1526 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
1527 // cause series of commands that change the context, then do an operation that relies on that context to fail.
1528
1529 if (override_context != NULL)
1530 m_debugger.UpdateExecutionContext (override_context);
1531
1532 if (!stop_on_continue)
1533 {
1534 m_debugger.SetAsyncExecution (false);
1535 }
1536
1537 for (int idx = 0; idx < num_lines; idx++)
1538 {
1539 const char *cmd = commands.GetStringAtIndex(idx);
1540 if (cmd[0] == '\0')
1541 continue;
1542
Jim Ingham949d5ac2011-02-18 00:54:25 +00001543 if (echo_commands)
1544 {
1545 result.AppendMessageWithFormat ("%s %s\n",
1546 GetPrompt(),
1547 cmd);
1548 }
1549
Greg Claytonaa378b12011-02-20 02:15:07 +00001550 CommandReturnObject tmp_result;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001551 bool success = HandleCommand(cmd, false, tmp_result, NULL);
1552
1553 if (print_results)
1554 {
1555 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00001556 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00001557 }
1558
1559 if (!success || !tmp_result.Succeeded())
1560 {
1561 if (stop_on_error)
1562 {
1563 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed.\n",
1564 idx, cmd);
1565 result.SetStatus (eReturnStatusFailed);
1566 m_debugger.SetAsyncExecution (old_async_execution);
1567 return;
1568 }
1569 else if (print_results)
1570 {
1571 result.AppendMessageWithFormat ("Command #%d '%s' failed with error: %s.\n",
1572 idx + 1,
1573 cmd,
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00001574 tmp_result.GetErrorData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00001575 }
1576 }
1577
1578 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
1579 // could be running (for instance in Breakpoint Commands.
1580 // So we check the return value to see if it is has running in it.
1581 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
1582 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
1583 {
1584 if (stop_on_continue)
1585 {
1586 // If we caused the target to proceed, and we're going to stop in that case, set the
1587 // status in our real result before returning. This is an error if the continue was not the
1588 // last command in the set of commands to be run.
1589 if (idx != num_lines - 1)
1590 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
1591 idx + 1, cmd);
1592 else
1593 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
1594
1595 result.SetStatus(tmp_result.GetStatus());
1596 m_debugger.SetAsyncExecution (old_async_execution);
1597
1598 return;
1599 }
1600 }
1601
1602 }
1603
1604 result.SetStatus (eReturnStatusSuccessFinishResult);
1605 m_debugger.SetAsyncExecution (old_async_execution);
1606
1607 return;
1608}
1609
1610void
1611CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
1612 ExecutionContext *context,
1613 bool stop_on_continue,
1614 bool stop_on_error,
1615 bool echo_command,
1616 bool print_result,
1617 CommandReturnObject &result)
1618{
1619 if (cmd_file.Exists())
1620 {
1621 bool success;
1622 StringList commands;
1623 success = commands.ReadFileLines(cmd_file);
1624 if (!success)
1625 {
1626 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
1627 result.SetStatus (eReturnStatusFailed);
1628 return;
1629 }
1630 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, result);
1631 }
1632 else
1633 {
1634 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
1635 cmd_file.GetFilename().AsCString());
1636 result.SetStatus (eReturnStatusFailed);
1637 return;
1638 }
1639}
1640
Chris Lattner24943d22010-06-08 16:52:24 +00001641ScriptInterpreter *
1642CommandInterpreter::GetScriptInterpreter ()
1643{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001644 if (m_script_interpreter_ap.get() != NULL)
1645 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00001646
Caroline Tice0aa2e552011-01-14 00:29:16 +00001647 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
1648 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00001649 {
Caroline Tice0aa2e552011-01-14 00:29:16 +00001650 case eScriptLanguageNone:
1651 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
1652 break;
1653 case eScriptLanguagePython:
1654 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
1655 break;
1656 default:
1657 break;
1658 };
1659
1660 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00001661}
1662
1663
1664
1665bool
1666CommandInterpreter::GetSynchronous ()
1667{
1668 return m_synchronous_execution;
1669}
1670
1671void
1672CommandInterpreter::SetSynchronous (bool value)
1673{
Johnny Chend7a4eb02010-10-14 01:22:03 +00001674 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00001675}
1676
1677void
1678CommandInterpreter::OutputFormattedHelpText (Stream &strm,
1679 const char *word_text,
1680 const char *separator,
1681 const char *help_text,
1682 uint32_t max_word_len)
1683{
Greg Clayton238c0a12010-09-18 01:14:36 +00001684 const uint32_t max_columns = m_debugger.GetTerminalWidth();
1685
Chris Lattner24943d22010-06-08 16:52:24 +00001686 int indent_size = max_word_len + strlen (separator) + 2;
1687
1688 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00001689
1690 StreamString text_strm;
1691 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
1692
1693 size_t len = text_strm.GetSize();
1694 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00001695 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00001696 {
1697 text_strm.EOL();
1698 len = text_strm.GetSize();
1699 }
Chris Lattner24943d22010-06-08 16:52:24 +00001700
1701 if (len < max_columns)
1702 {
1703 // Output it as a single line.
1704 strm.Printf ("%s", text);
1705 }
1706 else
1707 {
1708 // We need to break it up into multiple lines.
1709 bool first_line = true;
1710 int text_width;
1711 int start = 0;
1712 int end = start;
1713 int final_end = strlen (text);
1714 int sub_len;
1715
1716 while (end < final_end)
1717 {
1718 if (first_line)
1719 text_width = max_columns - 1;
1720 else
1721 text_width = max_columns - indent_size - 1;
1722
1723 // Don't start the 'text' on a space, since we're already outputting the indentation.
1724 if (!first_line)
1725 {
1726 while ((start < final_end) && (text[start] == ' '))
1727 start++;
1728 }
1729
1730 end = start + text_width;
1731 if (end > final_end)
1732 end = final_end;
1733 else
1734 {
1735 // If we're not at the end of the text, make sure we break the line on white space.
1736 while (end > start
1737 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
1738 end--;
1739 }
1740
1741 sub_len = end - start;
1742 if (start != 0)
1743 strm.EOL();
1744 if (!first_line)
1745 strm.Indent();
1746 else
1747 first_line = false;
1748 assert (start <= final_end);
1749 assert (start + sub_len <= final_end);
1750 if (sub_len > 0)
1751 strm.Write (text + start, sub_len);
1752 start = end + 1;
1753 }
1754 }
1755 strm.EOL();
1756 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001757}
1758
1759void
1760CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
1761 StringList &commands_found, StringList &commands_help)
1762{
1763 CommandObject::CommandMap::const_iterator pos;
1764 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
1765 CommandObject *sub_cmd_obj;
1766
1767 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
1768 {
1769 const char * command_name = pos->first.c_str();
1770 sub_cmd_obj = pos->second.get();
1771 StreamString complete_command_name;
1772
1773 complete_command_name.Printf ("%s %s", prefix, command_name);
1774
Greg Clayton238c0a12010-09-18 01:14:36 +00001775 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001776 {
1777 commands_found.AppendString (complete_command_name.GetData());
1778 commands_help.AppendString (sub_cmd_obj->GetHelp());
1779 }
1780
1781 if (sub_cmd_obj->IsMultiwordObject())
1782 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
1783 commands_help);
1784 }
1785
1786}
1787
1788void
1789CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
1790 StringList &commands_help)
1791{
1792 CommandObject::CommandMap::const_iterator pos;
1793
1794 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1795 {
1796 const char *command_name = pos->first.c_str();
1797 CommandObject *cmd_obj = pos->second.get();
1798
Greg Clayton238c0a12010-09-18 01:14:36 +00001799 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001800 {
1801 commands_found.AppendString (command_name);
1802 commands_help.AppendString (cmd_obj->GetHelp());
1803 }
1804
1805 if (cmd_obj->IsMultiwordObject())
1806 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
1807
1808 }
1809}