blob: 6f1c74fde9e7d7a182275ea0b4eb0d49fc025c66 [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"
Greg Claytonb1888f22011-03-19 01:12:21 +000028#include "../Commands/CommandObjectPlatform.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000029#include "../Commands/CommandObjectProcess.h"
30#include "../Commands/CommandObjectQuit.h"
Eli Friedmanb34d2a22010-06-09 22:08:29 +000031#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000032#include "../Commands/CommandObjectRegister.h"
Chris Lattner24943d22010-06-08 16:52:24 +000033#include "CommandObjectScript.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000034#include "../Commands/CommandObjectSettings.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000035#include "../Commands/CommandObjectSource.h"
Jim Ingham767af882010-07-07 03:36:20 +000036#include "../Commands/CommandObjectCommands.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000037#include "../Commands/CommandObjectSyntax.h"
38#include "../Commands/CommandObjectTarget.h"
39#include "../Commands/CommandObjectThread.h"
Johnny Chen902e0182010-12-23 20:21:44 +000040#include "../Commands/CommandObjectVersion.h"
Chris Lattner24943d22010-06-08 16:52:24 +000041
Jim Ingham84cdc152010-06-15 19:49:27 +000042#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000043#include "lldb/Core/Debugger.h"
Jim Ingham5e16ef52010-10-04 19:49:29 +000044#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000045#include "lldb/Core/Stream.h"
46#include "lldb/Core/Timer.h"
Greg Claytoncd548032011-02-01 01:31:41 +000047#include "lldb/Host/Host.h"
Chris Lattner24943d22010-06-08 16:52:24 +000048#include "lldb/Target/Process.h"
49#include "lldb/Target/Thread.h"
50#include "lldb/Target/TargetList.h"
Greg Claytone98ac252010-11-10 04:57:04 +000051#include "lldb/Utility/CleanUp.h"
Chris Lattner24943d22010-06-08 16:52:24 +000052
53#include "lldb/Interpreter/CommandReturnObject.h"
54#include "lldb/Interpreter/CommandInterpreter.h"
Caroline Tice0aa2e552011-01-14 00:29:16 +000055#include "lldb/Interpreter/ScriptInterpreterNone.h"
56#include "lldb/Interpreter/ScriptInterpreterPython.h"
Chris Lattner24943d22010-06-08 16:52:24 +000057
58using namespace lldb;
59using namespace lldb_private;
60
61CommandInterpreter::CommandInterpreter
62(
Greg Clayton63094e02010-06-23 01:19:29 +000063 Debugger &debugger,
Chris Lattner24943d22010-06-08 16:52:24 +000064 ScriptLanguage script_language,
Greg Clayton63094e02010-06-23 01:19:29 +000065 bool synchronous_execution
Chris Lattner24943d22010-06-08 16:52:24 +000066) :
Greg Clayton49ce6822010-10-31 03:01:06 +000067 Broadcaster ("lldb.command-interpreter"),
Greg Clayton63094e02010-06-23 01:19:29 +000068 m_debugger (debugger),
Greg Clayton887aa282010-10-11 01:05:37 +000069 m_synchronous_execution (synchronous_execution),
Caroline Tice0aa2e552011-01-14 00:29:16 +000070 m_skip_lldbinit_files (false),
Jim Ingham949d5ac2011-02-18 00:54:25 +000071 m_script_interpreter_ap (),
72 m_comment_char ('#')
Chris Lattner24943d22010-06-08 16:52:24 +000073{
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000074 const char *dbg_name = debugger.GetInstanceName().AsCString();
75 std::string lang_name = ScriptInterpreter::LanguageToString (script_language);
76 StreamString var_name;
77 var_name.Printf ("[%s].script-lang", dbg_name);
Caroline Tice1d2aefd2010-09-09 06:25:08 +000078 debugger.GetSettingsController()->SetVariable (var_name.GetData(), lang_name.c_str(),
79 lldb::eVarSetOperationAssign, false,
Greg Clayton49ce6822010-10-31 03:01:06 +000080 m_debugger.GetInstanceName().AsCString());
81 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
82 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
83 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Chris Lattner24943d22010-06-08 16:52:24 +000084}
85
86void
87CommandInterpreter::Initialize ()
88{
89 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
90
91 CommandReturnObject result;
92
93 LoadCommandDictionary ();
94
Chris Lattner24943d22010-06-08 16:52:24 +000095 // Set up some initial aliases.
Greg Claytonaa378b12011-02-20 02:15:07 +000096 HandleCommand ("command alias q quit", false, result);
97 HandleCommand ("command alias run process launch --", false, result);
98 HandleCommand ("command alias r process launch --", false, result);
99 HandleCommand ("command alias c process continue", false, result);
100 HandleCommand ("command alias continue process continue", false, result);
101 HandleCommand ("command alias expr expression", false, result);
102 HandleCommand ("command alias exit quit", false, result);
103 HandleCommand ("command alias b regexp-break", false, result);
104 HandleCommand ("command alias bt thread backtrace", false, result);
105 HandleCommand ("command alias si thread step-inst", false, result);
106 HandleCommand ("command alias step thread step-in", false, result);
107 HandleCommand ("command alias s thread step-in", false, result);
108 HandleCommand ("command alias next thread step-over", false, result);
109 HandleCommand ("command alias n thread step-over", false, result);
110 HandleCommand ("command alias finish thread step-out", false, result);
111 HandleCommand ("command alias x memory read", false, result);
112 HandleCommand ("command alias l source list", false, result);
113 HandleCommand ("command alias list source list", false, result);
114 HandleCommand ("command alias p frame variable", false, result);
115 HandleCommand ("command alias print frame variable", false, result);
116 HandleCommand ("command alias po expression -o --", false, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000117}
118
Chris Lattner24943d22010-06-08 16:52:24 +0000119const char *
120CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
121{
122 // This function has not yet been implemented.
123
124 // Look for any embedded script command
125 // If found,
126 // get interpreter object from the command dictionary,
127 // call execute_one_command on it,
128 // get the results as a string,
129 // substitute that string for current stuff.
130
131 return arg;
132}
133
134
135void
136CommandInterpreter::LoadCommandDictionary ()
137{
138 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
139
140 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
141 //
142 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
143 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
144 // the cross-referencing stuff) are created!!!
145 //
146 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
147
148
149 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
150 // are created. This is so that when another command is created that needs to go into a crossref object,
151 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
152 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
153
Chris Lattner24943d22010-06-08 16:52:24 +0000154 // Non-CommandObjectCrossref commands can now be created.
155
Caroline Tice5bc8c972010-09-20 20:44:43 +0000156 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000157
Greg Clayton238c0a12010-09-18 01:14:36 +0000158 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000159 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000160 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000161 m_command_dict["commands"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000162 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
163 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
164 m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000165 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000166 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000167 m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
168 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
169 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonb1888f22011-03-19 01:12:21 +0000170 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000171 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000172 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000173 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000174 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000175 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000176 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000177 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
178 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000179 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000180
181 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000182 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
183 "regexp-break",
Caroline Ticec1ad82e2010-09-07 22:38:08 +0000184 "Set a breakpoint using a regular expression to specify the location.",
Caroline Tice43b014a2010-10-04 22:28:36 +0000185 "regexp-break [<filename>:<linenum>]\nregexp-break [<address>]\nregexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000186 if (break_regex_cmd_ap.get())
187 {
188 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
189 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
190 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
191 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list") &&
192 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
Greg Claytonb01000f2011-01-17 03:46:26 +0000193 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000194 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
195 {
196 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
197 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
198 }
199 }
200}
201
202int
203CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
204 StringList &matches)
205{
206 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
207
208 if (include_aliases)
209 {
210 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
211 }
212
213 return matches.GetSize();
214}
215
216CommandObjectSP
217CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
218{
219 CommandObject::CommandMap::iterator pos;
220 CommandObjectSP ret_val;
221
222 std::string cmd(cmd_cstr);
223
224 if (HasCommands())
225 {
226 pos = m_command_dict.find(cmd);
227 if (pos != m_command_dict.end())
228 ret_val = pos->second;
229 }
230
231 if (include_aliases && HasAliases())
232 {
233 pos = m_alias_dict.find(cmd);
234 if (pos != m_alias_dict.end())
235 ret_val = pos->second;
236 }
237
238 if (HasUserCommands())
239 {
240 pos = m_user_dict.find(cmd);
241 if (pos != m_user_dict.end())
242 ret_val = pos->second;
243 }
244
245 if (!exact && ret_val == NULL)
246 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000247 // We will only get into here if we didn't find any exact matches.
248
249 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
250
Chris Lattner24943d22010-06-08 16:52:24 +0000251 StringList local_matches;
252 if (matches == NULL)
253 matches = &local_matches;
254
Jim Inghamd40f8a62010-07-06 22:46:59 +0000255 unsigned int num_cmd_matches = 0;
256 unsigned int num_alias_matches = 0;
257 unsigned int num_user_matches = 0;
258
259 // Look through the command dictionaries one by one, and if we get only one match from any of
260 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
261
Chris Lattner24943d22010-06-08 16:52:24 +0000262 if (HasCommands())
263 {
264 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
265 }
266
267 if (num_cmd_matches == 1)
268 {
269 cmd.assign(matches->GetStringAtIndex(0));
270 pos = m_command_dict.find(cmd);
271 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000272 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000273 }
274
Jim Ingham9a574172010-06-24 20:28:42 +0000275 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000276 {
277 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
278
279 }
280
Jim Inghamd40f8a62010-07-06 22:46:59 +0000281 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000282 {
283 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
284 pos = m_alias_dict.find(cmd);
285 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000286 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000287 }
288
Jim Ingham9a574172010-06-24 20:28:42 +0000289 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000290 {
291 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
292 }
293
Jim Inghamd40f8a62010-07-06 22:46:59 +0000294 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000295 {
296 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
297
298 pos = m_user_dict.find (cmd);
299 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000300 user_match_sp = pos->second;
301 }
302
303 // If we got exactly one match, return that, otherwise return the match list.
304
305 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
306 {
307 if (num_cmd_matches)
308 return real_match_sp;
309 else if (num_alias_matches)
310 return alias_match_sp;
311 else
312 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000313 }
314 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000315 else if (matches && ret_val != NULL)
316 {
317 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000318 }
319
320
321 return ret_val;
322}
323
Jim Inghamd40f8a62010-07-06 22:46:59 +0000324CommandObjectSP
325CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000326{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000327 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
328 CommandObjectSP ret_val; // Possibly empty return value.
329
330 if (cmd_cstr == NULL)
331 return ret_val;
332
333 if (cmd_words.GetArgumentCount() == 1)
334 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
335 else
336 {
337 // We have a multi-word command (seemingly), so we need to do more work.
338 // First, get the cmd_obj_sp for the first word in the command.
339 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
340 if (cmd_obj_sp.get() != NULL)
341 {
342 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
343 // command name), and find the appropriate sub-command SP for each command word....
344 size_t end = cmd_words.GetArgumentCount();
345 for (size_t j= 1; j < end; ++j)
346 {
347 if (cmd_obj_sp->IsMultiwordObject())
348 {
349 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
350 (cmd_words.GetArgumentAtIndex (j));
351 if (cmd_obj_sp.get() == NULL)
352 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
353 return ret_val;
354 }
355 else
356 // We have more words in the command name, but we don't have a multiword object. Fail and return
357 // empty 'ret_val'.
358 return ret_val;
359 }
360 // We successfully looped through all the command words and got valid command objects for them. Assign the
361 // last object retrieved to 'ret_val'.
362 ret_val = cmd_obj_sp;
363 }
364 }
365 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000366}
367
368CommandObject *
369CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
370{
371 return GetCommandSPExact (cmd_cstr, include_aliases).get();
372}
373
374CommandObject *
375CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
376{
377 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
378
379 // If we didn't find an exact match to the command string in the commands, look in
380 // the aliases.
381
382 if (command_obj == NULL)
383 {
384 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
385 }
386
387 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
388 // in both the commands and the aliases.
389
390 if (command_obj == NULL)
391 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
392
393 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000394}
395
396bool
397CommandInterpreter::CommandExists (const char *cmd)
398{
399 return m_command_dict.find(cmd) != m_command_dict.end();
400}
401
402bool
403CommandInterpreter::AliasExists (const char *cmd)
404{
405 return m_alias_dict.find(cmd) != m_alias_dict.end();
406}
407
408bool
409CommandInterpreter::UserCommandExists (const char *cmd)
410{
411 return m_user_dict.find(cmd) != m_user_dict.end();
412}
413
414void
415CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
416{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000417 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000418 m_alias_dict[alias_name] = command_obj_sp;
419}
420
421bool
422CommandInterpreter::RemoveAlias (const char *alias_name)
423{
424 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
425 if (pos != m_alias_dict.end())
426 {
427 m_alias_dict.erase(pos);
428 return true;
429 }
430 return false;
431}
432bool
433CommandInterpreter::RemoveUser (const char *alias_name)
434{
435 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
436 if (pos != m_user_dict.end())
437 {
438 m_user_dict.erase(pos);
439 return true;
440 }
441 return false;
442}
443
Chris Lattner24943d22010-06-08 16:52:24 +0000444void
445CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
446{
447 help_string.Printf ("'%s", command_name);
448 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
449
450 if (option_arg_vector_sp != NULL)
451 {
452 OptionArgVector *options = option_arg_vector_sp.get();
453 for (int i = 0; i < options->size(); ++i)
454 {
455 OptionArgPair cur_option = (*options)[i];
456 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000457 OptionArgValue value_pair = cur_option.second;
458 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000459 if (opt.compare("<argument>") == 0)
460 {
461 help_string.Printf (" %s", value.c_str());
462 }
463 else
464 {
465 help_string.Printf (" %s", opt.c_str());
466 if ((value.compare ("<no-argument>") != 0)
467 && (value.compare ("<need-argument") != 0))
468 {
469 help_string.Printf (" %s", value.c_str());
470 }
471 }
472 }
473 }
474
475 help_string.Printf ("'");
476}
477
Greg Clayton65124ea2010-08-26 22:05:43 +0000478size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000479CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
480{
481 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000482 CommandObject::CommandMap::const_iterator end = dict.end();
483 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000484
Greg Clayton65124ea2010-08-26 22:05:43 +0000485 for (pos = dict.begin(); pos != end; ++pos)
486 {
487 size_t len = pos->first.size();
488 if (max_len < len)
489 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000490 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000491 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000492}
493
494void
495CommandInterpreter::GetHelp (CommandReturnObject &result)
496{
497 CommandObject::CommandMap::const_iterator pos;
498 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
499 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000500 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000501
502 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
503 {
504 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
505 max_len);
506 }
507 result.AppendMessage("");
508
509 if (m_alias_dict.size() > 0)
510 {
Jim Inghame3663e82010-10-22 18:47:16 +0000511 result.AppendMessage("The following is a list of your current command abbreviations "
512 "(see 'help commands alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000513 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000514 max_len = FindLongestCommandWord (m_alias_dict);
515
Chris Lattner24943d22010-06-08 16:52:24 +0000516 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
517 {
518 StreamString sstr;
519 StreamString translation_and_help;
520 std::string entry_name = pos->first;
521 std::string second_entry = pos->second.get()->GetCommandName();
522 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
523
524 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
525 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
526 translation_and_help.GetData(), max_len);
527 }
528 result.AppendMessage("");
529 }
530
531 if (m_user_dict.size() > 0)
532 {
533 result.AppendMessage ("The following is a list of your current user-defined commands:");
534 result.AppendMessage("");
535 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
536 {
537 result.AppendMessageWithFormat ("%s -- %s\n", pos->first.c_str(), pos->second->GetHelp());
538 }
539 result.AppendMessage("");
540 }
541
542 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
543}
544
Caroline Ticee0da7a52010-12-09 22:52:49 +0000545CommandObject *
546CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000547{
Caroline Ticee0da7a52010-12-09 22:52:49 +0000548 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
549 // eventually be invoked by the given command line.
550
551 CommandObject *cmd_obj = NULL;
552 std::string white_space (" \t\v");
553 size_t start = command_string.find_first_not_of (white_space);
554 size_t end = 0;
555 bool done = false;
556 while (!done)
557 {
558 if (start != std::string::npos)
559 {
560 // Get the next word from command_string.
561 end = command_string.find_first_of (white_space, start);
562 if (end == std::string::npos)
563 end = command_string.size();
564 std::string cmd_word = command_string.substr (start, end - start);
565
566 if (cmd_obj == NULL)
567 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
568 // command or alias.
569 cmd_obj = GetCommandObject (cmd_word.c_str());
570 else if (cmd_obj->IsMultiwordObject ())
571 {
572 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
573 CommandObject *sub_cmd_obj =
574 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
575 if (sub_cmd_obj)
576 cmd_obj = sub_cmd_obj;
577 else // cmd_word was not a valid sub-command word, so we are donee
578 done = true;
579 }
580 else
581 // We have a cmd_obj and it is not a multi-word object, so we are done.
582 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000583
Caroline Ticee0da7a52010-12-09 22:52:49 +0000584 // If we didn't find a valid command object, or our command object is not a multi-word object, or
585 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
586 // next word.
587
588 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
589 done = true;
590 else
591 start = command_string.find_first_not_of (white_space, end);
592 }
593 else
594 // Unable to find any more words.
595 done = true;
596 }
597
598 if (end == command_string.size())
599 command_string.clear();
600 else
601 command_string = command_string.substr(end);
602
603 return cmd_obj;
604}
605
606bool
607CommandInterpreter::StripFirstWord (std::string &command_string, std::string &word)
608{
609 std::string white_space (" \t\v");
610 size_t start;
611 size_t end;
612
613 start = command_string.find_first_not_of (white_space);
614 if (start != std::string::npos)
615 {
616 end = command_string.find_first_of (white_space, start);
617 if (end != std::string::npos)
618 {
619 word = command_string.substr (start, end - start);
620 command_string = command_string.substr (end);
621 size_t pos = command_string.find_first_not_of (white_space);
622 if ((pos != 0) && (pos != std::string::npos))
623 command_string = command_string.substr (pos);
624 }
625 else
626 {
627 word = command_string.substr (start);
628 command_string.erase();
629 }
630
631 }
632 return true;
633}
634
635void
636CommandInterpreter::BuildAliasResult (const char *alias_name, std::string &raw_input_string, std::string &alias_result,
637 CommandObject *&alias_cmd_obj, CommandReturnObject &result)
638{
639 Args cmd_args (raw_input_string.c_str());
640 alias_cmd_obj = GetCommandObject (alias_name);
641 StreamString result_str;
642
643 if (alias_cmd_obj)
644 {
645 std::string alias_name_str = alias_name;
646 if ((cmd_args.GetArgumentCount() == 0)
647 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
648 cmd_args.Unshift (alias_name);
649
650 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
651 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
652
653 if (option_arg_vector_sp.get())
654 {
655 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
656
657 for (int i = 0; i < option_arg_vector->size(); ++i)
658 {
659 OptionArgPair option_pair = (*option_arg_vector)[i];
660 OptionArgValue value_pair = option_pair.second;
661 int value_type = value_pair.first;
662 std::string option = option_pair.first;
663 std::string value = value_pair.second;
664 if (option.compare ("<argument>") == 0)
665 result_str.Printf (" %s", value.c_str());
666 else
667 {
668 result_str.Printf (" %s", option.c_str());
669 if (value_type != optional_argument)
670 result_str.Printf (" ");
671 if (value.compare ("<no_argument>") != 0)
672 {
673 int index = GetOptionArgumentPosition (value.c_str());
674 if (index == 0)
675 result_str.Printf ("%s", value.c_str());
676 else if (index >= cmd_args.GetArgumentCount())
677 {
678
679 result.AppendErrorWithFormat
680 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
681 index);
682 result.SetStatus (eReturnStatusFailed);
683 return;
684 }
685 else
686 {
687 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
688 if (strpos != std::string::npos)
689 raw_input_string = raw_input_string.erase (strpos,
690 strlen (cmd_args.GetArgumentAtIndex (index)));
691 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
692 }
693 }
694 }
695 }
696 }
697
698 alias_result = result_str.GetData();
699 }
700}
701
702bool
703CommandInterpreter::HandleCommand (const char *command_line,
704 bool add_to_history,
705 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +0000706 ExecutionContext *override_context,
707 bool repeat_on_empty_command)
708
Caroline Ticee0da7a52010-12-09 22:52:49 +0000709{
Jim Ingham949d5ac2011-02-18 00:54:25 +0000710
Caroline Ticee0da7a52010-12-09 22:52:49 +0000711 bool done = false;
712 CommandObject *cmd_obj = NULL;
713 std::string next_word;
714 bool wants_raw_input = false;
715 std::string command_string (command_line);
716
717 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +0000718 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
719
720 // Make a scoped cleanup object that will clear the crash description string
721 // on exit of this function.
722 lldb_utility::CleanUp <const char *, void> crash_description_cleanup(NULL, Host::SetCrashDescription);
723
Caroline Ticee0da7a52010-12-09 22:52:49 +0000724 if (log)
725 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +0000726
Jim Inghamabab14b2010-11-04 23:08:45 +0000727 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
728
Greg Clayton63094e02010-06-23 01:19:29 +0000729 m_debugger.UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +0000730
Jim Ingham949d5ac2011-02-18 00:54:25 +0000731 bool empty_command = false;
732 bool comment_command = false;
733 if (command_string.empty())
734 empty_command = true;
735 else
Chris Lattner24943d22010-06-08 16:52:24 +0000736 {
Jim Ingham949d5ac2011-02-18 00:54:25 +0000737 const char *k_space_characters = "\t\n\v\f\r ";
738
739 size_t non_space = command_string.find_first_not_of (k_space_characters);
740 // Check for empty line or comment line (lines whose first
741 // non-space character is the comment character for this interpreter)
742 if (non_space == std::string::npos)
743 empty_command = true;
744 else if (command_string[non_space] == m_comment_char)
745 comment_command = true;
746 }
747
748 if (empty_command)
749 {
750 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +0000751 {
Jim Ingham949d5ac2011-02-18 00:54:25 +0000752 if (m_command_history.empty())
753 {
754 result.AppendError ("empty command");
755 result.SetStatus(eReturnStatusFailed);
756 return false;
757 }
758 else
759 {
760 command_line = m_repeat_command.c_str();
761 command_string = command_line;
762 if (m_repeat_command.empty())
763 {
764 result.AppendErrorWithFormat("No auto repeat.\n");
765 result.SetStatus (eReturnStatusFailed);
766 return false;
767 }
768 }
769 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000770 }
771 else
772 {
Jim Ingham949d5ac2011-02-18 00:54:25 +0000773 result.SetStatus (eReturnStatusSuccessFinishNoResult);
774 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000775 }
Jim Ingham949d5ac2011-02-18 00:54:25 +0000776 }
777 else if (comment_command)
778 {
779 result.SetStatus (eReturnStatusSuccessFinishNoResult);
780 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000781 }
782
Caroline Ticee0da7a52010-12-09 22:52:49 +0000783 // Phase 1.
784
785 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
786 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
787 // the user could have specified an alias, and in translating the alias there may also be command options and/or
788 // even data (including raw text strings) that need to be found and inserted into the command line as part of
789 // 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 +0000790 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +0000791 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +0000792
Caroline Ticee0da7a52010-12-09 22:52:49 +0000793 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000794 size_t actual_cmd_name_len = 0;
Caroline Ticee0da7a52010-12-09 22:52:49 +0000795 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +0000796 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000797 StripFirstWord (command_string, next_word);
798 if (!cmd_obj && AliasExists (next_word.c_str()))
Chris Lattner24943d22010-06-08 16:52:24 +0000799 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000800 std::string alias_result;
801 BuildAliasResult (next_word.c_str(), command_string, alias_result, cmd_obj, result);
802 revised_command_line.Printf ("%s", alias_result.c_str());
803 if (cmd_obj)
Caroline Tice56d2fc42010-12-14 18:51:39 +0000804 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000805 wants_raw_input = cmd_obj->WantsRawCommandString ();
Caroline Tice56d2fc42010-12-14 18:51:39 +0000806 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
807 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000808 }
809 else if (!cmd_obj)
810 {
811 cmd_obj = GetCommandObject (next_word.c_str());
812 if (cmd_obj)
Chris Lattner24943d22010-06-08 16:52:24 +0000813 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000814 actual_cmd_name_len += next_word.length();
Caroline Ticee0da7a52010-12-09 22:52:49 +0000815 revised_command_line.Printf ("%s", next_word.c_str());
816 wants_raw_input = cmd_obj->WantsRawCommandString ();
Chris Lattner24943d22010-06-08 16:52:24 +0000817 }
818 else
819 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000820 revised_command_line.Printf ("%s", next_word.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000821 }
822 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000823 else if (cmd_obj->IsMultiwordObject ())
824 {
825 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
826 if (sub_cmd_obj)
827 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000828 actual_cmd_name_len += next_word.length() + 1;
Caroline Ticee0da7a52010-12-09 22:52:49 +0000829 revised_command_line.Printf (" %s", next_word.c_str());
830 cmd_obj = sub_cmd_obj;
831 wants_raw_input = cmd_obj->WantsRawCommandString ();
832 }
833 else
834 {
835 revised_command_line.Printf (" %s", next_word.c_str());
836 done = true;
837 }
838 }
839 else
840 {
841 revised_command_line.Printf (" %s", next_word.c_str());
842 done = true;
843 }
844
845 if (cmd_obj == NULL)
846 {
847 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
848 result.SetStatus (eReturnStatusFailed);
849 return false;
850 }
851
852 next_word.erase ();
853 if (command_string.length() == 0)
854 done = true;
855
Chris Lattner24943d22010-06-08 16:52:24 +0000856 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000857
858 if (command_string.size() > 0)
859 revised_command_line.Printf (" %s", command_string.c_str());
860
861 // End of Phase 1.
862 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
863 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
864 // fully translated with all substitutions & translations taken care of (still in raw text format); and
865 // wants_raw_input specifies whether the Execute method expects raw input or not.
866
867
868 if (log)
869 {
870 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
871 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
872 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
873 }
874
875 // Phase 2.
876 // Take care of things like setting up the history command & calling the appropriate Execute method on the
877 // CommandObject, with the appropriate arguments.
878
879 if (cmd_obj != NULL)
880 {
881 if (add_to_history)
882 {
883 Args command_args (revised_command_line.GetData());
884 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
885 if (repeat_command != NULL)
886 m_repeat_command.assign(repeat_command);
887 else
888 m_repeat_command.assign(command_line);
889
890 m_command_history.push_back (command_line);
891 }
892
893 command_string = revised_command_line.GetData();
894 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000895 std::string remainder;
896 if (actual_cmd_name_len < command_string.length())
897 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
898 // than cmd_obj->GetCommandName(), because name completion
899 // allows users to enter short versions of the names,
900 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +0000901
902 // Remove any initial spaces
903 std::string white_space (" \t\v");
904 size_t pos = remainder.find_first_not_of (white_space);
905 if (pos != 0 && pos != std::string::npos)
906 remainder = remainder.substr (pos);
907
908 if (log)
909 log->Printf ("HandleCommand, command line after removing command name(s): '%s'\n", remainder.c_str());
910
911
912 if (wants_raw_input)
913 cmd_obj->ExecuteRawCommandString (remainder.c_str(), result);
914 else
915 {
916 Args cmd_args (remainder.c_str());
917 cmd_obj->ExecuteWithOptions (cmd_args, result);
918 }
919 }
920 else
921 {
922 // We didn't find the first command object, so complete the first argument.
923 Args command_args (revised_command_line.GetData());
924 StringList matches;
925 int num_matches;
926 int cursor_index = 0;
927 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
928 bool word_complete;
929 num_matches = HandleCompletionMatches (command_args,
930 cursor_index,
931 cursor_char_position,
932 0,
933 -1,
934 word_complete,
935 matches);
936
937 if (num_matches > 0)
938 {
939 std::string error_msg;
940 error_msg.assign ("ambiguous command '");
941 error_msg.append(command_args.GetArgumentAtIndex(0));
942 error_msg.append ("'.");
943
944 error_msg.append (" Possible completions:");
945 for (int i = 0; i < num_matches; i++)
946 {
947 error_msg.append ("\n\t");
948 error_msg.append (matches.GetStringAtIndex (i));
949 }
950 error_msg.append ("\n");
951 result.AppendRawError (error_msg.c_str(), error_msg.size());
952 }
953 else
954 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
955
956 result.SetStatus (eReturnStatusFailed);
957 }
958
Chris Lattner24943d22010-06-08 16:52:24 +0000959 return result.Succeeded();
960}
961
962int
963CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
964 int &cursor_index,
965 int &cursor_char_position,
966 int match_start_point,
967 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +0000968 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000969 StringList &matches)
970{
971 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000972 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +0000973
974 // For any of the command completions a unique match will be a complete word.
975 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000976
977 if (cursor_index == -1)
978 {
979 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +0000980 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000981 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
982 }
983 else if (cursor_index == 0)
984 {
985 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000986 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000987 num_command_matches = matches.GetSize();
988
989 if (num_command_matches == 1
990 && cmd_obj && cmd_obj->IsMultiwordObject()
991 && matches.GetStringAtIndex(0) != NULL
992 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
993 {
994 look_for_subcommand = true;
995 num_command_matches = 0;
996 matches.DeleteStringAtIndex(0);
997 parsed_line.AppendArgument ("");
998 cursor_index++;
999 cursor_char_position = 0;
1000 }
1001 }
1002
1003 if (cursor_index > 0 || look_for_subcommand)
1004 {
1005 // We are completing further on into a commands arguments, so find the command and tell it
1006 // to complete the command.
1007 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001008 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001009 if (command_object == NULL)
1010 {
1011 return 0;
1012 }
1013 else
1014 {
1015 parsed_line.Shift();
1016 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001017 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001018 cursor_index,
1019 cursor_char_position,
1020 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001021 max_return_elements,
1022 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001023 matches);
1024 }
1025 }
1026
1027 return num_command_matches;
1028
1029}
1030
1031int
1032CommandInterpreter::HandleCompletion (const char *current_line,
1033 const char *cursor,
1034 const char *last_char,
1035 int match_start_point,
1036 int max_return_elements,
1037 StringList &matches)
1038{
1039 // We parse the argument up to the cursor, so the last argument in parsed_line is
1040 // the one containing the cursor, and the cursor is after the last character.
1041
1042 Args parsed_line(current_line, last_char - current_line);
1043 Args partial_parsed_line(current_line, cursor - current_line);
1044
1045 int num_args = partial_parsed_line.GetArgumentCount();
1046 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1047 int cursor_char_position;
1048
1049 if (cursor_index == -1)
1050 cursor_char_position = 0;
1051 else
1052 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001053
1054 if (cursor > current_line && cursor[-1] == ' ')
1055 {
1056 // We are just after a space. If we are in an argument, then we will continue
1057 // parsing, but if we are between arguments, then we have to complete whatever the next
1058 // element would be.
1059 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1060 // protected by a quote) then the space will also be in the parsed argument...
1061
1062 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1063 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1064 {
1065 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1066 cursor_index++;
1067 cursor_char_position = 0;
1068 }
1069 }
Chris Lattner24943d22010-06-08 16:52:24 +00001070
1071 int num_command_matches;
1072
1073 matches.Clear();
1074
1075 // Only max_return_elements == -1 is supported at present:
1076 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001077 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001078 num_command_matches = HandleCompletionMatches (parsed_line,
1079 cursor_index,
1080 cursor_char_position,
1081 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001082 max_return_elements,
1083 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001084 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001085
1086 if (num_command_matches <= 0)
1087 return num_command_matches;
1088
1089 if (num_args == 0)
1090 {
1091 // If we got an empty string, insert nothing.
1092 matches.InsertStringAtIndex(0, "");
1093 }
1094 else
1095 {
1096 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1097 // put an empty string in element 0.
1098 std::string command_partial_str;
1099 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001100 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1101 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001102
1103 std::string common_prefix;
1104 matches.LongestCommonPrefix (common_prefix);
1105 int partial_name_len = command_partial_str.size();
1106
1107 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001108 // Only do this if the completer told us this was a complete word, however...
1109 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001110 {
1111 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1112 if (quote_char != '\0')
1113 common_prefix.push_back(quote_char);
1114
1115 common_prefix.push_back(' ');
1116 }
1117 common_prefix.erase (0, partial_name_len);
1118 matches.InsertStringAtIndex(0, common_prefix.c_str());
1119 }
1120 return num_command_matches;
1121}
1122
Chris Lattner24943d22010-06-08 16:52:24 +00001123
1124CommandInterpreter::~CommandInterpreter ()
1125{
1126}
1127
1128const char *
1129CommandInterpreter::GetPrompt ()
1130{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001131 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001132}
1133
1134void
1135CommandInterpreter::SetPrompt (const char *new_prompt)
1136{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001137 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001138}
1139
Jim Ingham5e16ef52010-10-04 19:49:29 +00001140size_t
Greg Clayton58928562011-02-09 01:08:52 +00001141CommandInterpreter::GetConfirmationInputReaderCallback
1142(
1143 void *baton,
1144 InputReader &reader,
1145 lldb::InputReaderAction action,
1146 const char *bytes,
1147 size_t bytes_len
1148)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001149{
Greg Clayton58928562011-02-09 01:08:52 +00001150 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001151 bool *response_ptr = (bool *) baton;
1152
1153 switch (action)
1154 {
1155 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001156 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001157 {
1158 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001159 {
Greg Clayton58928562011-02-09 01:08:52 +00001160 out_file.Printf ("%s", reader.GetPrompt());
1161 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001162 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001163 }
1164 break;
1165
1166 case eInputReaderDeactivate:
1167 break;
1168
1169 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001170 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001171 {
Greg Clayton58928562011-02-09 01:08:52 +00001172 out_file.Printf ("%s", reader.GetPrompt());
1173 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001174 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001175 break;
1176
1177 case eInputReaderGotToken:
1178 if (bytes_len == 0)
1179 {
1180 reader.SetIsDone(true);
1181 }
1182 else if (bytes[0] == 'y')
1183 {
1184 *response_ptr = true;
1185 reader.SetIsDone(true);
1186 }
1187 else if (bytes[0] == 'n')
1188 {
1189 *response_ptr = false;
1190 reader.SetIsDone(true);
1191 }
1192 else
1193 {
Greg Clayton58928562011-02-09 01:08:52 +00001194 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001195 {
Greg Clayton58928562011-02-09 01:08:52 +00001196 out_file.Printf ("Please answer \"y\" or \"n\"\n%s", reader.GetPrompt());
1197 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001198 }
1199 }
1200 break;
1201
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001202 case eInputReaderInterrupt:
1203 case eInputReaderEndOfFile:
1204 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1205 reader.SetIsDone (true);
1206 break;
1207
Jim Ingham5e16ef52010-10-04 19:49:29 +00001208 case eInputReaderDone:
1209 break;
1210 }
1211
1212 return bytes_len;
1213
1214}
1215
1216bool
1217CommandInterpreter::Confirm (const char *message, bool default_answer)
1218{
Jim Ingham93057472010-10-04 22:44:14 +00001219 // Check AutoConfirm first:
1220 if (m_debugger.GetAutoConfirm())
1221 return default_answer;
1222
Jim Ingham5e16ef52010-10-04 19:49:29 +00001223 InputReaderSP reader_sp (new InputReader(GetDebugger()));
1224 bool response = default_answer;
1225 if (reader_sp)
1226 {
1227 std::string prompt(message);
1228 prompt.append(": [");
1229 if (default_answer)
1230 prompt.append ("Y/n] ");
1231 else
1232 prompt.append ("y/N] ");
1233
1234 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1235 &response, // baton
1236 eInputReaderGranularityLine, // token size, to pass to callback function
1237 NULL, // end token
1238 prompt.c_str(), // prompt
1239 true)); // echo input
1240 if (err.Success())
1241 {
1242 GetDebugger().PushInputReader (reader_sp);
1243 }
1244 reader_sp->WaitOnReaderIsDone();
1245 }
1246 return response;
1247}
1248
1249
Chris Lattner24943d22010-06-08 16:52:24 +00001250void
1251CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1252{
Jim Inghamd40f8a62010-07-06 22:46:59 +00001253 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001254
1255 if (cmd_obj_sp != NULL)
1256 {
1257 CommandObject *cmd_obj = cmd_obj_sp.get();
1258 if (cmd_obj->IsCrossRefObject ())
1259 cmd_obj->AddObject (object_type);
1260 }
1261}
1262
Chris Lattner24943d22010-06-08 16:52:24 +00001263OptionArgVectorSP
1264CommandInterpreter::GetAliasOptions (const char *alias_name)
1265{
1266 OptionArgMap::iterator pos;
1267 OptionArgVectorSP ret_val;
1268
1269 std::string alias (alias_name);
1270
1271 if (HasAliasOptions())
1272 {
1273 pos = m_alias_options.find (alias);
1274 if (pos != m_alias_options.end())
1275 ret_val = pos->second;
1276 }
1277
1278 return ret_val;
1279}
1280
1281void
1282CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1283{
1284 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1285 if (pos != m_alias_options.end())
1286 {
1287 m_alias_options.erase (pos);
1288 }
1289}
1290
1291void
1292CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1293{
1294 m_alias_options[alias_name] = option_arg_vector_sp;
1295}
1296
1297bool
1298CommandInterpreter::HasCommands ()
1299{
1300 return (!m_command_dict.empty());
1301}
1302
1303bool
1304CommandInterpreter::HasAliases ()
1305{
1306 return (!m_alias_dict.empty());
1307}
1308
1309bool
1310CommandInterpreter::HasUserCommands ()
1311{
1312 return (!m_user_dict.empty());
1313}
1314
1315bool
1316CommandInterpreter::HasAliasOptions ()
1317{
1318 return (!m_alias_options.empty());
1319}
1320
Chris Lattner24943d22010-06-08 16:52:24 +00001321void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001322CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
1323 const char *alias_name,
1324 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00001325 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001326 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00001327{
1328 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00001329
1330 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00001331
Caroline Tice44c841d2010-12-07 19:58:26 +00001332 // Make sure that the alias name is the 0th element in cmd_args
1333 std::string alias_name_str = alias_name;
1334 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1335 cmd_args.Unshift (alias_name);
1336
1337 Args new_args (alias_cmd_obj->GetCommandName());
1338 if (new_args.GetArgumentCount() == 2)
1339 new_args.Shift();
1340
Chris Lattner24943d22010-06-08 16:52:24 +00001341 if (option_arg_vector_sp.get())
1342 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001343 if (wants_raw_input)
1344 {
1345 // We have a command that both has command options and takes raw input. Make *sure* it has a
1346 // " -- " in the right place in the raw_input_string.
1347 size_t pos = raw_input_string.find(" -- ");
1348 if (pos == std::string::npos)
1349 {
1350 // None found; assume it goes at the beginning of the raw input string
1351 raw_input_string.insert (0, " -- ");
1352 }
1353 }
Chris Lattner24943d22010-06-08 16:52:24 +00001354
1355 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1356 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001357 std::vector<bool> used (old_size + 1, false);
1358
1359 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001360
1361 for (int i = 0; i < option_arg_vector->size(); ++i)
1362 {
1363 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00001364 OptionArgValue value_pair = option_pair.second;
1365 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00001366 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00001367 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00001368 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001369 {
1370 if (!wants_raw_input
1371 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
1372 new_args.AppendArgument (value.c_str());
1373 }
Chris Lattner24943d22010-06-08 16:52:24 +00001374 else
1375 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001376 if (value_type != optional_argument)
1377 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001378 if (value.compare ("<no-argument>") != 0)
1379 {
1380 int index = GetOptionArgumentPosition (value.c_str());
1381 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001382 {
Chris Lattner24943d22010-06-08 16:52:24 +00001383 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00001384 if (value_type != optional_argument)
1385 new_args.AppendArgument (value.c_str());
1386 else
1387 {
1388 char buffer[255];
1389 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
1390 new_args.AppendArgument (buffer);
1391 }
1392
1393 }
Chris Lattner24943d22010-06-08 16:52:24 +00001394 else if (index >= cmd_args.GetArgumentCount())
1395 {
1396 result.AppendErrorWithFormat
1397 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1398 index);
1399 result.SetStatus (eReturnStatusFailed);
1400 return;
1401 }
1402 else
1403 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001404 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
1405 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1406 if (strpos != std::string::npos)
1407 {
1408 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
1409 }
1410
1411 if (value_type != optional_argument)
1412 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
1413 else
1414 {
1415 char buffer[255];
1416 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
1417 cmd_args.GetArgumentAtIndex (index));
1418 new_args.AppendArgument (buffer);
1419 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001420 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001421 }
1422 }
1423 }
1424 }
1425
1426 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1427 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001428 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00001429 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1430 }
1431
1432 cmd_args.Clear();
1433 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1434 }
1435 else
1436 {
1437 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00001438 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
1439 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
1440 // input string.
1441 if (wants_raw_input)
1442 {
1443 cmd_args.Clear();
1444 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1445 }
Chris Lattner24943d22010-06-08 16:52:24 +00001446 return;
1447 }
1448
1449 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1450 return;
1451}
1452
1453
1454int
1455CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1456{
1457 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1458 // of zero.
1459
1460 char *cptr = (char *) in_string;
1461
1462 // Does it start with '%'
1463 if (cptr[0] == '%')
1464 {
1465 ++cptr;
1466
1467 // Is the rest of it entirely digits?
1468 if (isdigit (cptr[0]))
1469 {
1470 const char *start = cptr;
1471 while (isdigit (cptr[0]))
1472 ++cptr;
1473
1474 // We've gotten to the end of the digits; are we at the end of the string?
1475 if (cptr[0] == '\0')
1476 position = atoi (start);
1477 }
1478 }
1479
1480 return position;
1481}
1482
1483void
1484CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1485{
Greg Clayton887aa282010-10-11 01:05:37 +00001486 // Don't parse any .lldbinit files if we were asked not to
1487 if (m_skip_lldbinit_files)
1488 return;
1489
Chris Lattner24943d22010-06-08 16:52:24 +00001490 const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit";
Greg Clayton537a7a82010-10-20 20:54:39 +00001491 FileSpec init_file (init_file_path, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001492 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
1493 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
1494
1495 if (init_file.Exists())
1496 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001497 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
1498 bool stop_on_continue = true;
1499 bool stop_on_error = false;
1500 bool echo_commands = false;
1501 bool print_results = false;
1502
1503 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, result);
Chris Lattner24943d22010-06-08 16:52:24 +00001504 }
1505 else
1506 {
1507 // nothing to be done if the file doesn't exist
1508 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1509 }
1510}
1511
Jim Ingham949d5ac2011-02-18 00:54:25 +00001512void
Jim Inghama4fede32011-03-11 01:51:49 +00001513CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001514 ExecutionContext *override_context,
1515 bool stop_on_continue,
1516 bool stop_on_error,
1517 bool echo_commands,
1518 bool print_results,
1519 CommandReturnObject &result)
1520{
1521 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00001522
1523 // If we are going to continue past a "continue" then we need to run the commands synchronously.
1524 // Make sure you reset this value anywhere you return from the function.
1525
1526 bool old_async_execution = m_debugger.GetAsyncExecution();
1527
1528 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
1529 // cause series of commands that change the context, then do an operation that relies on that context to fail.
1530
1531 if (override_context != NULL)
1532 m_debugger.UpdateExecutionContext (override_context);
1533
1534 if (!stop_on_continue)
1535 {
1536 m_debugger.SetAsyncExecution (false);
1537 }
1538
1539 for (int idx = 0; idx < num_lines; idx++)
1540 {
1541 const char *cmd = commands.GetStringAtIndex(idx);
1542 if (cmd[0] == '\0')
1543 continue;
1544
Jim Ingham949d5ac2011-02-18 00:54:25 +00001545 if (echo_commands)
1546 {
1547 result.AppendMessageWithFormat ("%s %s\n",
1548 GetPrompt(),
1549 cmd);
1550 }
1551
Greg Claytonaa378b12011-02-20 02:15:07 +00001552 CommandReturnObject tmp_result;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001553 bool success = HandleCommand(cmd, false, tmp_result, NULL);
1554
1555 if (print_results)
1556 {
1557 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00001558 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00001559 }
1560
1561 if (!success || !tmp_result.Succeeded())
1562 {
1563 if (stop_on_error)
1564 {
1565 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed.\n",
1566 idx, cmd);
1567 result.SetStatus (eReturnStatusFailed);
1568 m_debugger.SetAsyncExecution (old_async_execution);
1569 return;
1570 }
1571 else if (print_results)
1572 {
1573 result.AppendMessageWithFormat ("Command #%d '%s' failed with error: %s.\n",
1574 idx + 1,
1575 cmd,
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00001576 tmp_result.GetErrorData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00001577 }
1578 }
1579
1580 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
1581 // could be running (for instance in Breakpoint Commands.
1582 // So we check the return value to see if it is has running in it.
1583 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
1584 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
1585 {
1586 if (stop_on_continue)
1587 {
1588 // If we caused the target to proceed, and we're going to stop in that case, set the
1589 // status in our real result before returning. This is an error if the continue was not the
1590 // last command in the set of commands to be run.
1591 if (idx != num_lines - 1)
1592 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
1593 idx + 1, cmd);
1594 else
1595 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
1596
1597 result.SetStatus(tmp_result.GetStatus());
1598 m_debugger.SetAsyncExecution (old_async_execution);
1599
1600 return;
1601 }
1602 }
1603
1604 }
1605
1606 result.SetStatus (eReturnStatusSuccessFinishResult);
1607 m_debugger.SetAsyncExecution (old_async_execution);
1608
1609 return;
1610}
1611
1612void
1613CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
1614 ExecutionContext *context,
1615 bool stop_on_continue,
1616 bool stop_on_error,
1617 bool echo_command,
1618 bool print_result,
1619 CommandReturnObject &result)
1620{
1621 if (cmd_file.Exists())
1622 {
1623 bool success;
1624 StringList commands;
1625 success = commands.ReadFileLines(cmd_file);
1626 if (!success)
1627 {
1628 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
1629 result.SetStatus (eReturnStatusFailed);
1630 return;
1631 }
1632 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, result);
1633 }
1634 else
1635 {
1636 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
1637 cmd_file.GetFilename().AsCString());
1638 result.SetStatus (eReturnStatusFailed);
1639 return;
1640 }
1641}
1642
Chris Lattner24943d22010-06-08 16:52:24 +00001643ScriptInterpreter *
1644CommandInterpreter::GetScriptInterpreter ()
1645{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001646 if (m_script_interpreter_ap.get() != NULL)
1647 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00001648
Caroline Tice0aa2e552011-01-14 00:29:16 +00001649 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
1650 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00001651 {
Caroline Tice0aa2e552011-01-14 00:29:16 +00001652 case eScriptLanguageNone:
1653 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
1654 break;
1655 case eScriptLanguagePython:
1656 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
1657 break;
1658 default:
1659 break;
1660 };
1661
1662 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00001663}
1664
1665
1666
1667bool
1668CommandInterpreter::GetSynchronous ()
1669{
1670 return m_synchronous_execution;
1671}
1672
1673void
1674CommandInterpreter::SetSynchronous (bool value)
1675{
Johnny Chend7a4eb02010-10-14 01:22:03 +00001676 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00001677}
1678
1679void
1680CommandInterpreter::OutputFormattedHelpText (Stream &strm,
1681 const char *word_text,
1682 const char *separator,
1683 const char *help_text,
1684 uint32_t max_word_len)
1685{
Greg Clayton238c0a12010-09-18 01:14:36 +00001686 const uint32_t max_columns = m_debugger.GetTerminalWidth();
1687
Chris Lattner24943d22010-06-08 16:52:24 +00001688 int indent_size = max_word_len + strlen (separator) + 2;
1689
1690 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00001691
1692 StreamString text_strm;
1693 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
1694
1695 size_t len = text_strm.GetSize();
1696 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00001697 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00001698 {
1699 text_strm.EOL();
1700 len = text_strm.GetSize();
1701 }
Chris Lattner24943d22010-06-08 16:52:24 +00001702
1703 if (len < max_columns)
1704 {
1705 // Output it as a single line.
1706 strm.Printf ("%s", text);
1707 }
1708 else
1709 {
1710 // We need to break it up into multiple lines.
1711 bool first_line = true;
1712 int text_width;
1713 int start = 0;
1714 int end = start;
1715 int final_end = strlen (text);
1716 int sub_len;
1717
1718 while (end < final_end)
1719 {
1720 if (first_line)
1721 text_width = max_columns - 1;
1722 else
1723 text_width = max_columns - indent_size - 1;
1724
1725 // Don't start the 'text' on a space, since we're already outputting the indentation.
1726 if (!first_line)
1727 {
1728 while ((start < final_end) && (text[start] == ' '))
1729 start++;
1730 }
1731
1732 end = start + text_width;
1733 if (end > final_end)
1734 end = final_end;
1735 else
1736 {
1737 // If we're not at the end of the text, make sure we break the line on white space.
1738 while (end > start
1739 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
1740 end--;
1741 }
1742
1743 sub_len = end - start;
1744 if (start != 0)
1745 strm.EOL();
1746 if (!first_line)
1747 strm.Indent();
1748 else
1749 first_line = false;
1750 assert (start <= final_end);
1751 assert (start + sub_len <= final_end);
1752 if (sub_len > 0)
1753 strm.Write (text + start, sub_len);
1754 start = end + 1;
1755 }
1756 }
1757 strm.EOL();
1758 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001759}
1760
1761void
1762CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
1763 StringList &commands_found, StringList &commands_help)
1764{
1765 CommandObject::CommandMap::const_iterator pos;
1766 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
1767 CommandObject *sub_cmd_obj;
1768
1769 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
1770 {
1771 const char * command_name = pos->first.c_str();
1772 sub_cmd_obj = pos->second.get();
1773 StreamString complete_command_name;
1774
1775 complete_command_name.Printf ("%s %s", prefix, command_name);
1776
Greg Clayton238c0a12010-09-18 01:14:36 +00001777 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001778 {
1779 commands_found.AppendString (complete_command_name.GetData());
1780 commands_help.AppendString (sub_cmd_obj->GetHelp());
1781 }
1782
1783 if (sub_cmd_obj->IsMultiwordObject())
1784 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
1785 commands_help);
1786 }
1787
1788}
1789
1790void
1791CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
1792 StringList &commands_help)
1793{
1794 CommandObject::CommandMap::const_iterator pos;
1795
1796 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1797 {
1798 const char *command_name = pos->first.c_str();
1799 CommandObject *cmd_obj = pos->second.get();
1800
Greg Clayton238c0a12010-09-18 01:14:36 +00001801 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001802 {
1803 commands_found.AppendString (command_name);
1804 commands_help.AppendString (cmd_obj->GetHelp());
1805 }
1806
1807 if (cmd_obj->IsMultiwordObject())
1808 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
1809
1810 }
1811}