blob: 98786f7c5cc289ae3d94279b4e4bf12fdd2ceed4 [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(),
Greg Claytonb3448432011-03-24 21:19:54 +000079 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);
Jim Ingham15f2d432011-03-24 18:23:12 +0000115 HandleCommand ("command alias print expression --", false, result);
Greg Claytonaa378b12011-02-20 02:15:07 +0000116 HandleCommand ("command alias po expression -o --", false, result);
Jim Inghame56493f2011-03-22 02:29:32 +0000117 HandleCommand ("command alias up regexp-up", false, result);
118 HandleCommand ("command alias down regexp-down", false, result);
119
Chris Lattner24943d22010-06-08 16:52:24 +0000120}
121
Chris Lattner24943d22010-06-08 16:52:24 +0000122const char *
123CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
124{
125 // This function has not yet been implemented.
126
127 // Look for any embedded script command
128 // If found,
129 // get interpreter object from the command dictionary,
130 // call execute_one_command on it,
131 // get the results as a string,
132 // substitute that string for current stuff.
133
134 return arg;
135}
136
137
138void
139CommandInterpreter::LoadCommandDictionary ()
140{
141 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
142
143 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
144 //
145 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
146 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
147 // the cross-referencing stuff) are created!!!
148 //
149 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
150
151
152 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
153 // are created. This is so that when another command is created that needs to go into a crossref object,
154 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
155 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
156
Chris Lattner24943d22010-06-08 16:52:24 +0000157 // Non-CommandObjectCrossref commands can now be created.
158
Caroline Tice5bc8c972010-09-20 20:44:43 +0000159 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000160
Greg Clayton238c0a12010-09-18 01:14:36 +0000161 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000162 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000163 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000164 m_command_dict["commands"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000165 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
166 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
167 m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000168 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000169 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000170 m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
171 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
172 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonb1888f22011-03-19 01:12:21 +0000173 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000174 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000175 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000176 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000177 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000178 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000179 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000180 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
181 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000182 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000183
184 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000185 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
186 "regexp-break",
Caroline Ticec1ad82e2010-09-07 22:38:08 +0000187 "Set a breakpoint using a regular expression to specify the location.",
Caroline Tice43b014a2010-10-04 22:28:36 +0000188 "regexp-break [<filename>:<linenum>]\nregexp-break [<address>]\nregexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000189 if (break_regex_cmd_ap.get())
190 {
191 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
192 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
193 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
194 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list") &&
195 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
Greg Claytonb01000f2011-01-17 03:46:26 +0000196 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000197 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
198 {
199 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
200 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
201 }
202 }
Jim Inghame56493f2011-03-22 02:29:32 +0000203
204 std::auto_ptr<CommandObjectRegexCommand>
205 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
206 "regexp-down",
207 "Go down \"n\" frames in the stack (1 frame by default).",
208 "down [n]", 2));
209 if (down_regex_cmd_ap.get())
210 {
211 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
212 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
213 {
214 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
215 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
216 }
217 }
218
219 std::auto_ptr<CommandObjectRegexCommand>
220 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
221 "regexp-up",
222 "Go up \"n\" frames in the stack (1 frame by default).",
223 "up [n]", 2));
224 if (up_regex_cmd_ap.get())
225 {
226 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
227 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
228 {
229 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
230 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
231 }
232 }
Chris Lattner24943d22010-06-08 16:52:24 +0000233}
234
235int
236CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
237 StringList &matches)
238{
239 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
240
241 if (include_aliases)
242 {
243 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
244 }
245
246 return matches.GetSize();
247}
248
249CommandObjectSP
250CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
251{
252 CommandObject::CommandMap::iterator pos;
253 CommandObjectSP ret_val;
254
255 std::string cmd(cmd_cstr);
256
257 if (HasCommands())
258 {
259 pos = m_command_dict.find(cmd);
260 if (pos != m_command_dict.end())
261 ret_val = pos->second;
262 }
263
264 if (include_aliases && HasAliases())
265 {
266 pos = m_alias_dict.find(cmd);
267 if (pos != m_alias_dict.end())
268 ret_val = pos->second;
269 }
270
271 if (HasUserCommands())
272 {
273 pos = m_user_dict.find(cmd);
274 if (pos != m_user_dict.end())
275 ret_val = pos->second;
276 }
277
278 if (!exact && ret_val == NULL)
279 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000280 // We will only get into here if we didn't find any exact matches.
281
282 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
283
Chris Lattner24943d22010-06-08 16:52:24 +0000284 StringList local_matches;
285 if (matches == NULL)
286 matches = &local_matches;
287
Jim Inghamd40f8a62010-07-06 22:46:59 +0000288 unsigned int num_cmd_matches = 0;
289 unsigned int num_alias_matches = 0;
290 unsigned int num_user_matches = 0;
291
292 // Look through the command dictionaries one by one, and if we get only one match from any of
293 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
294
Chris Lattner24943d22010-06-08 16:52:24 +0000295 if (HasCommands())
296 {
297 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
298 }
299
300 if (num_cmd_matches == 1)
301 {
302 cmd.assign(matches->GetStringAtIndex(0));
303 pos = m_command_dict.find(cmd);
304 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000305 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000306 }
307
Jim Ingham9a574172010-06-24 20:28:42 +0000308 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000309 {
310 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
311
312 }
313
Jim Inghamd40f8a62010-07-06 22:46:59 +0000314 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000315 {
316 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
317 pos = m_alias_dict.find(cmd);
318 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000319 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000320 }
321
Jim Ingham9a574172010-06-24 20:28:42 +0000322 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000323 {
324 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
325 }
326
Jim Inghamd40f8a62010-07-06 22:46:59 +0000327 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000328 {
329 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
330
331 pos = m_user_dict.find (cmd);
332 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000333 user_match_sp = pos->second;
334 }
335
336 // If we got exactly one match, return that, otherwise return the match list.
337
338 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
339 {
340 if (num_cmd_matches)
341 return real_match_sp;
342 else if (num_alias_matches)
343 return alias_match_sp;
344 else
345 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000346 }
347 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000348 else if (matches && ret_val != NULL)
349 {
350 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000351 }
352
353
354 return ret_val;
355}
356
Jim Inghamd40f8a62010-07-06 22:46:59 +0000357CommandObjectSP
358CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000359{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000360 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
361 CommandObjectSP ret_val; // Possibly empty return value.
362
363 if (cmd_cstr == NULL)
364 return ret_val;
365
366 if (cmd_words.GetArgumentCount() == 1)
367 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
368 else
369 {
370 // We have a multi-word command (seemingly), so we need to do more work.
371 // First, get the cmd_obj_sp for the first word in the command.
372 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
373 if (cmd_obj_sp.get() != NULL)
374 {
375 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
376 // command name), and find the appropriate sub-command SP for each command word....
377 size_t end = cmd_words.GetArgumentCount();
378 for (size_t j= 1; j < end; ++j)
379 {
380 if (cmd_obj_sp->IsMultiwordObject())
381 {
382 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
383 (cmd_words.GetArgumentAtIndex (j));
384 if (cmd_obj_sp.get() == NULL)
385 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
386 return ret_val;
387 }
388 else
389 // We have more words in the command name, but we don't have a multiword object. Fail and return
390 // empty 'ret_val'.
391 return ret_val;
392 }
393 // We successfully looped through all the command words and got valid command objects for them. Assign the
394 // last object retrieved to 'ret_val'.
395 ret_val = cmd_obj_sp;
396 }
397 }
398 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000399}
400
401CommandObject *
402CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
403{
404 return GetCommandSPExact (cmd_cstr, include_aliases).get();
405}
406
407CommandObject *
408CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
409{
410 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
411
412 // If we didn't find an exact match to the command string in the commands, look in
413 // the aliases.
414
415 if (command_obj == NULL)
416 {
417 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
418 }
419
420 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
421 // in both the commands and the aliases.
422
423 if (command_obj == NULL)
424 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
425
426 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000427}
428
429bool
430CommandInterpreter::CommandExists (const char *cmd)
431{
432 return m_command_dict.find(cmd) != m_command_dict.end();
433}
434
435bool
436CommandInterpreter::AliasExists (const char *cmd)
437{
438 return m_alias_dict.find(cmd) != m_alias_dict.end();
439}
440
441bool
442CommandInterpreter::UserCommandExists (const char *cmd)
443{
444 return m_user_dict.find(cmd) != m_user_dict.end();
445}
446
447void
448CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
449{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000450 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000451 m_alias_dict[alias_name] = command_obj_sp;
452}
453
454bool
455CommandInterpreter::RemoveAlias (const char *alias_name)
456{
457 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
458 if (pos != m_alias_dict.end())
459 {
460 m_alias_dict.erase(pos);
461 return true;
462 }
463 return false;
464}
465bool
466CommandInterpreter::RemoveUser (const char *alias_name)
467{
468 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
469 if (pos != m_user_dict.end())
470 {
471 m_user_dict.erase(pos);
472 return true;
473 }
474 return false;
475}
476
Chris Lattner24943d22010-06-08 16:52:24 +0000477void
478CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
479{
480 help_string.Printf ("'%s", command_name);
481 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
482
483 if (option_arg_vector_sp != NULL)
484 {
485 OptionArgVector *options = option_arg_vector_sp.get();
486 for (int i = 0; i < options->size(); ++i)
487 {
488 OptionArgPair cur_option = (*options)[i];
489 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000490 OptionArgValue value_pair = cur_option.second;
491 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000492 if (opt.compare("<argument>") == 0)
493 {
494 help_string.Printf (" %s", value.c_str());
495 }
496 else
497 {
498 help_string.Printf (" %s", opt.c_str());
499 if ((value.compare ("<no-argument>") != 0)
500 && (value.compare ("<need-argument") != 0))
501 {
502 help_string.Printf (" %s", value.c_str());
503 }
504 }
505 }
506 }
507
508 help_string.Printf ("'");
509}
510
Greg Clayton65124ea2010-08-26 22:05:43 +0000511size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000512CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
513{
514 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000515 CommandObject::CommandMap::const_iterator end = dict.end();
516 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000517
Greg Clayton65124ea2010-08-26 22:05:43 +0000518 for (pos = dict.begin(); pos != end; ++pos)
519 {
520 size_t len = pos->first.size();
521 if (max_len < len)
522 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000523 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000524 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000525}
526
527void
528CommandInterpreter::GetHelp (CommandReturnObject &result)
529{
530 CommandObject::CommandMap::const_iterator pos;
531 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
532 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000533 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000534
535 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
536 {
537 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
538 max_len);
539 }
540 result.AppendMessage("");
541
542 if (m_alias_dict.size() > 0)
543 {
Jim Inghame3663e82010-10-22 18:47:16 +0000544 result.AppendMessage("The following is a list of your current command abbreviations "
545 "(see 'help commands alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000546 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000547 max_len = FindLongestCommandWord (m_alias_dict);
548
Chris Lattner24943d22010-06-08 16:52:24 +0000549 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
550 {
551 StreamString sstr;
552 StreamString translation_and_help;
553 std::string entry_name = pos->first;
554 std::string second_entry = pos->second.get()->GetCommandName();
555 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
556
557 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
558 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
559 translation_and_help.GetData(), max_len);
560 }
561 result.AppendMessage("");
562 }
563
564 if (m_user_dict.size() > 0)
565 {
566 result.AppendMessage ("The following is a list of your current user-defined commands:");
567 result.AppendMessage("");
568 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
569 {
570 result.AppendMessageWithFormat ("%s -- %s\n", pos->first.c_str(), pos->second->GetHelp());
571 }
572 result.AppendMessage("");
573 }
574
575 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
576}
577
Caroline Ticee0da7a52010-12-09 22:52:49 +0000578CommandObject *
579CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000580{
Caroline Ticee0da7a52010-12-09 22:52:49 +0000581 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
582 // eventually be invoked by the given command line.
583
584 CommandObject *cmd_obj = NULL;
585 std::string white_space (" \t\v");
586 size_t start = command_string.find_first_not_of (white_space);
587 size_t end = 0;
588 bool done = false;
589 while (!done)
590 {
591 if (start != std::string::npos)
592 {
593 // Get the next word from command_string.
594 end = command_string.find_first_of (white_space, start);
595 if (end == std::string::npos)
596 end = command_string.size();
597 std::string cmd_word = command_string.substr (start, end - start);
598
599 if (cmd_obj == NULL)
600 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
601 // command or alias.
602 cmd_obj = GetCommandObject (cmd_word.c_str());
603 else if (cmd_obj->IsMultiwordObject ())
604 {
605 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
606 CommandObject *sub_cmd_obj =
607 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
608 if (sub_cmd_obj)
609 cmd_obj = sub_cmd_obj;
610 else // cmd_word was not a valid sub-command word, so we are donee
611 done = true;
612 }
613 else
614 // We have a cmd_obj and it is not a multi-word object, so we are done.
615 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000616
Caroline Ticee0da7a52010-12-09 22:52:49 +0000617 // If we didn't find a valid command object, or our command object is not a multi-word object, or
618 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
619 // next word.
620
621 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
622 done = true;
623 else
624 start = command_string.find_first_not_of (white_space, end);
625 }
626 else
627 // Unable to find any more words.
628 done = true;
629 }
630
631 if (end == command_string.size())
632 command_string.clear();
633 else
634 command_string = command_string.substr(end);
635
636 return cmd_obj;
637}
638
639bool
640CommandInterpreter::StripFirstWord (std::string &command_string, std::string &word)
641{
642 std::string white_space (" \t\v");
643 size_t start;
644 size_t end;
645
646 start = command_string.find_first_not_of (white_space);
647 if (start != std::string::npos)
648 {
649 end = command_string.find_first_of (white_space, start);
650 if (end != std::string::npos)
651 {
652 word = command_string.substr (start, end - start);
653 command_string = command_string.substr (end);
654 size_t pos = command_string.find_first_not_of (white_space);
655 if ((pos != 0) && (pos != std::string::npos))
656 command_string = command_string.substr (pos);
657 }
658 else
659 {
660 word = command_string.substr (start);
661 command_string.erase();
662 }
663
664 }
665 return true;
666}
667
668void
669CommandInterpreter::BuildAliasResult (const char *alias_name, std::string &raw_input_string, std::string &alias_result,
670 CommandObject *&alias_cmd_obj, CommandReturnObject &result)
671{
672 Args cmd_args (raw_input_string.c_str());
673 alias_cmd_obj = GetCommandObject (alias_name);
674 StreamString result_str;
675
676 if (alias_cmd_obj)
677 {
678 std::string alias_name_str = alias_name;
679 if ((cmd_args.GetArgumentCount() == 0)
680 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
681 cmd_args.Unshift (alias_name);
682
683 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
684 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
685
686 if (option_arg_vector_sp.get())
687 {
688 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
689
690 for (int i = 0; i < option_arg_vector->size(); ++i)
691 {
692 OptionArgPair option_pair = (*option_arg_vector)[i];
693 OptionArgValue value_pair = option_pair.second;
694 int value_type = value_pair.first;
695 std::string option = option_pair.first;
696 std::string value = value_pair.second;
697 if (option.compare ("<argument>") == 0)
698 result_str.Printf (" %s", value.c_str());
699 else
700 {
701 result_str.Printf (" %s", option.c_str());
702 if (value_type != optional_argument)
703 result_str.Printf (" ");
704 if (value.compare ("<no_argument>") != 0)
705 {
706 int index = GetOptionArgumentPosition (value.c_str());
707 if (index == 0)
708 result_str.Printf ("%s", value.c_str());
709 else if (index >= cmd_args.GetArgumentCount())
710 {
711
712 result.AppendErrorWithFormat
713 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
714 index);
715 result.SetStatus (eReturnStatusFailed);
716 return;
717 }
718 else
719 {
720 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
721 if (strpos != std::string::npos)
722 raw_input_string = raw_input_string.erase (strpos,
723 strlen (cmd_args.GetArgumentAtIndex (index)));
724 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
725 }
726 }
727 }
728 }
729 }
730
731 alias_result = result_str.GetData();
732 }
733}
734
735bool
736CommandInterpreter::HandleCommand (const char *command_line,
737 bool add_to_history,
738 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +0000739 ExecutionContext *override_context,
740 bool repeat_on_empty_command)
741
Caroline Ticee0da7a52010-12-09 22:52:49 +0000742{
Jim Ingham949d5ac2011-02-18 00:54:25 +0000743
Caroline Ticee0da7a52010-12-09 22:52:49 +0000744 bool done = false;
745 CommandObject *cmd_obj = NULL;
746 std::string next_word;
747 bool wants_raw_input = false;
748 std::string command_string (command_line);
749
750 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +0000751 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
752
753 // Make a scoped cleanup object that will clear the crash description string
754 // on exit of this function.
755 lldb_utility::CleanUp <const char *, void> crash_description_cleanup(NULL, Host::SetCrashDescription);
756
Caroline Ticee0da7a52010-12-09 22:52:49 +0000757 if (log)
758 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +0000759
Jim Inghamabab14b2010-11-04 23:08:45 +0000760 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
761
Greg Clayton63094e02010-06-23 01:19:29 +0000762 m_debugger.UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +0000763
Jim Ingham949d5ac2011-02-18 00:54:25 +0000764 bool empty_command = false;
765 bool comment_command = false;
766 if (command_string.empty())
767 empty_command = true;
768 else
Chris Lattner24943d22010-06-08 16:52:24 +0000769 {
Jim Ingham949d5ac2011-02-18 00:54:25 +0000770 const char *k_space_characters = "\t\n\v\f\r ";
771
772 size_t non_space = command_string.find_first_not_of (k_space_characters);
773 // Check for empty line or comment line (lines whose first
774 // non-space character is the comment character for this interpreter)
775 if (non_space == std::string::npos)
776 empty_command = true;
777 else if (command_string[non_space] == m_comment_char)
778 comment_command = true;
779 }
780
781 if (empty_command)
782 {
783 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +0000784 {
Jim Ingham949d5ac2011-02-18 00:54:25 +0000785 if (m_command_history.empty())
786 {
787 result.AppendError ("empty command");
788 result.SetStatus(eReturnStatusFailed);
789 return false;
790 }
791 else
792 {
793 command_line = m_repeat_command.c_str();
794 command_string = command_line;
795 if (m_repeat_command.empty())
796 {
797 result.AppendErrorWithFormat("No auto repeat.\n");
798 result.SetStatus (eReturnStatusFailed);
799 return false;
800 }
801 }
802 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000803 }
804 else
805 {
Jim Ingham949d5ac2011-02-18 00:54:25 +0000806 result.SetStatus (eReturnStatusSuccessFinishNoResult);
807 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000808 }
Jim Ingham949d5ac2011-02-18 00:54:25 +0000809 }
810 else if (comment_command)
811 {
812 result.SetStatus (eReturnStatusSuccessFinishNoResult);
813 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000814 }
815
Caroline Ticee0da7a52010-12-09 22:52:49 +0000816 // Phase 1.
817
818 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
819 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
820 // the user could have specified an alias, and in translating the alias there may also be command options and/or
821 // even data (including raw text strings) that need to be found and inserted into the command line as part of
822 // 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 +0000823 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +0000824 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +0000825
Caroline Ticee0da7a52010-12-09 22:52:49 +0000826 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000827 size_t actual_cmd_name_len = 0;
Caroline Ticee0da7a52010-12-09 22:52:49 +0000828 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +0000829 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000830 StripFirstWord (command_string, next_word);
831 if (!cmd_obj && AliasExists (next_word.c_str()))
Chris Lattner24943d22010-06-08 16:52:24 +0000832 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000833 std::string alias_result;
834 BuildAliasResult (next_word.c_str(), command_string, alias_result, cmd_obj, result);
835 revised_command_line.Printf ("%s", alias_result.c_str());
836 if (cmd_obj)
Caroline Tice56d2fc42010-12-14 18:51:39 +0000837 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000838 wants_raw_input = cmd_obj->WantsRawCommandString ();
Caroline Tice56d2fc42010-12-14 18:51:39 +0000839 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
840 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000841 }
842 else if (!cmd_obj)
843 {
844 cmd_obj = GetCommandObject (next_word.c_str());
845 if (cmd_obj)
Chris Lattner24943d22010-06-08 16:52:24 +0000846 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000847 actual_cmd_name_len += next_word.length();
Caroline Ticee0da7a52010-12-09 22:52:49 +0000848 revised_command_line.Printf ("%s", next_word.c_str());
849 wants_raw_input = cmd_obj->WantsRawCommandString ();
Chris Lattner24943d22010-06-08 16:52:24 +0000850 }
851 else
852 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000853 revised_command_line.Printf ("%s", next_word.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000854 }
855 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000856 else if (cmd_obj->IsMultiwordObject ())
857 {
858 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
859 if (sub_cmd_obj)
860 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000861 actual_cmd_name_len += next_word.length() + 1;
Caroline Ticee0da7a52010-12-09 22:52:49 +0000862 revised_command_line.Printf (" %s", next_word.c_str());
863 cmd_obj = sub_cmd_obj;
864 wants_raw_input = cmd_obj->WantsRawCommandString ();
865 }
866 else
867 {
868 revised_command_line.Printf (" %s", next_word.c_str());
869 done = true;
870 }
871 }
872 else
873 {
874 revised_command_line.Printf (" %s", next_word.c_str());
875 done = true;
876 }
877
878 if (cmd_obj == NULL)
879 {
880 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
881 result.SetStatus (eReturnStatusFailed);
882 return false;
883 }
884
885 next_word.erase ();
886 if (command_string.length() == 0)
887 done = true;
888
Chris Lattner24943d22010-06-08 16:52:24 +0000889 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000890
891 if (command_string.size() > 0)
892 revised_command_line.Printf (" %s", command_string.c_str());
893
894 // End of Phase 1.
895 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
896 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
897 // fully translated with all substitutions & translations taken care of (still in raw text format); and
898 // wants_raw_input specifies whether the Execute method expects raw input or not.
899
900
901 if (log)
902 {
903 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
904 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
905 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
906 }
907
908 // Phase 2.
909 // Take care of things like setting up the history command & calling the appropriate Execute method on the
910 // CommandObject, with the appropriate arguments.
911
912 if (cmd_obj != NULL)
913 {
914 if (add_to_history)
915 {
916 Args command_args (revised_command_line.GetData());
917 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
918 if (repeat_command != NULL)
919 m_repeat_command.assign(repeat_command);
920 else
921 m_repeat_command.assign(command_line);
922
923 m_command_history.push_back (command_line);
924 }
925
926 command_string = revised_command_line.GetData();
927 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000928 std::string remainder;
929 if (actual_cmd_name_len < command_string.length())
930 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
931 // than cmd_obj->GetCommandName(), because name completion
932 // allows users to enter short versions of the names,
933 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +0000934
935 // Remove any initial spaces
936 std::string white_space (" \t\v");
937 size_t pos = remainder.find_first_not_of (white_space);
938 if (pos != 0 && pos != std::string::npos)
939 remainder = remainder.substr (pos);
940
941 if (log)
942 log->Printf ("HandleCommand, command line after removing command name(s): '%s'\n", remainder.c_str());
943
944
945 if (wants_raw_input)
946 cmd_obj->ExecuteRawCommandString (remainder.c_str(), result);
947 else
948 {
949 Args cmd_args (remainder.c_str());
950 cmd_obj->ExecuteWithOptions (cmd_args, result);
951 }
952 }
953 else
954 {
955 // We didn't find the first command object, so complete the first argument.
956 Args command_args (revised_command_line.GetData());
957 StringList matches;
958 int num_matches;
959 int cursor_index = 0;
960 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
961 bool word_complete;
962 num_matches = HandleCompletionMatches (command_args,
963 cursor_index,
964 cursor_char_position,
965 0,
966 -1,
967 word_complete,
968 matches);
969
970 if (num_matches > 0)
971 {
972 std::string error_msg;
973 error_msg.assign ("ambiguous command '");
974 error_msg.append(command_args.GetArgumentAtIndex(0));
975 error_msg.append ("'.");
976
977 error_msg.append (" Possible completions:");
978 for (int i = 0; i < num_matches; i++)
979 {
980 error_msg.append ("\n\t");
981 error_msg.append (matches.GetStringAtIndex (i));
982 }
983 error_msg.append ("\n");
984 result.AppendRawError (error_msg.c_str(), error_msg.size());
985 }
986 else
987 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
988
989 result.SetStatus (eReturnStatusFailed);
990 }
991
Chris Lattner24943d22010-06-08 16:52:24 +0000992 return result.Succeeded();
993}
994
995int
996CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
997 int &cursor_index,
998 int &cursor_char_position,
999 int match_start_point,
1000 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001001 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001002 StringList &matches)
1003{
1004 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001005 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001006
1007 // For any of the command completions a unique match will be a complete word.
1008 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001009
1010 if (cursor_index == -1)
1011 {
1012 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001013 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001014 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1015 }
1016 else if (cursor_index == 0)
1017 {
1018 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001019 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001020 num_command_matches = matches.GetSize();
1021
1022 if (num_command_matches == 1
1023 && cmd_obj && cmd_obj->IsMultiwordObject()
1024 && matches.GetStringAtIndex(0) != NULL
1025 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1026 {
1027 look_for_subcommand = true;
1028 num_command_matches = 0;
1029 matches.DeleteStringAtIndex(0);
1030 parsed_line.AppendArgument ("");
1031 cursor_index++;
1032 cursor_char_position = 0;
1033 }
1034 }
1035
1036 if (cursor_index > 0 || look_for_subcommand)
1037 {
1038 // We are completing further on into a commands arguments, so find the command and tell it
1039 // to complete the command.
1040 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001041 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001042 if (command_object == NULL)
1043 {
1044 return 0;
1045 }
1046 else
1047 {
1048 parsed_line.Shift();
1049 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001050 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001051 cursor_index,
1052 cursor_char_position,
1053 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001054 max_return_elements,
1055 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001056 matches);
1057 }
1058 }
1059
1060 return num_command_matches;
1061
1062}
1063
1064int
1065CommandInterpreter::HandleCompletion (const char *current_line,
1066 const char *cursor,
1067 const char *last_char,
1068 int match_start_point,
1069 int max_return_elements,
1070 StringList &matches)
1071{
1072 // We parse the argument up to the cursor, so the last argument in parsed_line is
1073 // the one containing the cursor, and the cursor is after the last character.
1074
1075 Args parsed_line(current_line, last_char - current_line);
1076 Args partial_parsed_line(current_line, cursor - current_line);
1077
1078 int num_args = partial_parsed_line.GetArgumentCount();
1079 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1080 int cursor_char_position;
1081
1082 if (cursor_index == -1)
1083 cursor_char_position = 0;
1084 else
1085 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001086
1087 if (cursor > current_line && cursor[-1] == ' ')
1088 {
1089 // We are just after a space. If we are in an argument, then we will continue
1090 // parsing, but if we are between arguments, then we have to complete whatever the next
1091 // element would be.
1092 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1093 // protected by a quote) then the space will also be in the parsed argument...
1094
1095 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1096 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1097 {
1098 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1099 cursor_index++;
1100 cursor_char_position = 0;
1101 }
1102 }
Chris Lattner24943d22010-06-08 16:52:24 +00001103
1104 int num_command_matches;
1105
1106 matches.Clear();
1107
1108 // Only max_return_elements == -1 is supported at present:
1109 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001110 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001111 num_command_matches = HandleCompletionMatches (parsed_line,
1112 cursor_index,
1113 cursor_char_position,
1114 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001115 max_return_elements,
1116 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001117 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001118
1119 if (num_command_matches <= 0)
1120 return num_command_matches;
1121
1122 if (num_args == 0)
1123 {
1124 // If we got an empty string, insert nothing.
1125 matches.InsertStringAtIndex(0, "");
1126 }
1127 else
1128 {
1129 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1130 // put an empty string in element 0.
1131 std::string command_partial_str;
1132 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001133 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1134 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001135
1136 std::string common_prefix;
1137 matches.LongestCommonPrefix (common_prefix);
1138 int partial_name_len = command_partial_str.size();
1139
1140 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001141 // Only do this if the completer told us this was a complete word, however...
1142 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001143 {
1144 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1145 if (quote_char != '\0')
1146 common_prefix.push_back(quote_char);
1147
1148 common_prefix.push_back(' ');
1149 }
1150 common_prefix.erase (0, partial_name_len);
1151 matches.InsertStringAtIndex(0, common_prefix.c_str());
1152 }
1153 return num_command_matches;
1154}
1155
Chris Lattner24943d22010-06-08 16:52:24 +00001156
1157CommandInterpreter::~CommandInterpreter ()
1158{
1159}
1160
1161const char *
1162CommandInterpreter::GetPrompt ()
1163{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001164 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001165}
1166
1167void
1168CommandInterpreter::SetPrompt (const char *new_prompt)
1169{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001170 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001171}
1172
Jim Ingham5e16ef52010-10-04 19:49:29 +00001173size_t
Greg Clayton58928562011-02-09 01:08:52 +00001174CommandInterpreter::GetConfirmationInputReaderCallback
1175(
1176 void *baton,
1177 InputReader &reader,
1178 lldb::InputReaderAction action,
1179 const char *bytes,
1180 size_t bytes_len
1181)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001182{
Greg Clayton58928562011-02-09 01:08:52 +00001183 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001184 bool *response_ptr = (bool *) baton;
1185
1186 switch (action)
1187 {
1188 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001189 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001190 {
1191 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001192 {
Greg Clayton58928562011-02-09 01:08:52 +00001193 out_file.Printf ("%s", reader.GetPrompt());
1194 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001195 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001196 }
1197 break;
1198
1199 case eInputReaderDeactivate:
1200 break;
1201
1202 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001203 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001204 {
Greg Clayton58928562011-02-09 01:08:52 +00001205 out_file.Printf ("%s", reader.GetPrompt());
1206 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001207 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001208 break;
1209
1210 case eInputReaderGotToken:
1211 if (bytes_len == 0)
1212 {
1213 reader.SetIsDone(true);
1214 }
1215 else if (bytes[0] == 'y')
1216 {
1217 *response_ptr = true;
1218 reader.SetIsDone(true);
1219 }
1220 else if (bytes[0] == 'n')
1221 {
1222 *response_ptr = false;
1223 reader.SetIsDone(true);
1224 }
1225 else
1226 {
Greg Clayton58928562011-02-09 01:08:52 +00001227 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001228 {
Greg Clayton58928562011-02-09 01:08:52 +00001229 out_file.Printf ("Please answer \"y\" or \"n\"\n%s", reader.GetPrompt());
1230 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001231 }
1232 }
1233 break;
1234
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001235 case eInputReaderInterrupt:
1236 case eInputReaderEndOfFile:
1237 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1238 reader.SetIsDone (true);
1239 break;
1240
Jim Ingham5e16ef52010-10-04 19:49:29 +00001241 case eInputReaderDone:
1242 break;
1243 }
1244
1245 return bytes_len;
1246
1247}
1248
1249bool
1250CommandInterpreter::Confirm (const char *message, bool default_answer)
1251{
Jim Ingham93057472010-10-04 22:44:14 +00001252 // Check AutoConfirm first:
1253 if (m_debugger.GetAutoConfirm())
1254 return default_answer;
1255
Jim Ingham5e16ef52010-10-04 19:49:29 +00001256 InputReaderSP reader_sp (new InputReader(GetDebugger()));
1257 bool response = default_answer;
1258 if (reader_sp)
1259 {
1260 std::string prompt(message);
1261 prompt.append(": [");
1262 if (default_answer)
1263 prompt.append ("Y/n] ");
1264 else
1265 prompt.append ("y/N] ");
1266
1267 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1268 &response, // baton
1269 eInputReaderGranularityLine, // token size, to pass to callback function
1270 NULL, // end token
1271 prompt.c_str(), // prompt
1272 true)); // echo input
1273 if (err.Success())
1274 {
1275 GetDebugger().PushInputReader (reader_sp);
1276 }
1277 reader_sp->WaitOnReaderIsDone();
1278 }
1279 return response;
1280}
1281
1282
Chris Lattner24943d22010-06-08 16:52:24 +00001283void
1284CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1285{
Jim Inghamd40f8a62010-07-06 22:46:59 +00001286 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001287
1288 if (cmd_obj_sp != NULL)
1289 {
1290 CommandObject *cmd_obj = cmd_obj_sp.get();
1291 if (cmd_obj->IsCrossRefObject ())
1292 cmd_obj->AddObject (object_type);
1293 }
1294}
1295
Chris Lattner24943d22010-06-08 16:52:24 +00001296OptionArgVectorSP
1297CommandInterpreter::GetAliasOptions (const char *alias_name)
1298{
1299 OptionArgMap::iterator pos;
1300 OptionArgVectorSP ret_val;
1301
1302 std::string alias (alias_name);
1303
1304 if (HasAliasOptions())
1305 {
1306 pos = m_alias_options.find (alias);
1307 if (pos != m_alias_options.end())
1308 ret_val = pos->second;
1309 }
1310
1311 return ret_val;
1312}
1313
1314void
1315CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1316{
1317 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1318 if (pos != m_alias_options.end())
1319 {
1320 m_alias_options.erase (pos);
1321 }
1322}
1323
1324void
1325CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1326{
1327 m_alias_options[alias_name] = option_arg_vector_sp;
1328}
1329
1330bool
1331CommandInterpreter::HasCommands ()
1332{
1333 return (!m_command_dict.empty());
1334}
1335
1336bool
1337CommandInterpreter::HasAliases ()
1338{
1339 return (!m_alias_dict.empty());
1340}
1341
1342bool
1343CommandInterpreter::HasUserCommands ()
1344{
1345 return (!m_user_dict.empty());
1346}
1347
1348bool
1349CommandInterpreter::HasAliasOptions ()
1350{
1351 return (!m_alias_options.empty());
1352}
1353
Chris Lattner24943d22010-06-08 16:52:24 +00001354void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001355CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
1356 const char *alias_name,
1357 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00001358 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001359 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00001360{
1361 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00001362
1363 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00001364
Caroline Tice44c841d2010-12-07 19:58:26 +00001365 // Make sure that the alias name is the 0th element in cmd_args
1366 std::string alias_name_str = alias_name;
1367 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1368 cmd_args.Unshift (alias_name);
1369
1370 Args new_args (alias_cmd_obj->GetCommandName());
1371 if (new_args.GetArgumentCount() == 2)
1372 new_args.Shift();
1373
Chris Lattner24943d22010-06-08 16:52:24 +00001374 if (option_arg_vector_sp.get())
1375 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001376 if (wants_raw_input)
1377 {
1378 // We have a command that both has command options and takes raw input. Make *sure* it has a
1379 // " -- " in the right place in the raw_input_string.
1380 size_t pos = raw_input_string.find(" -- ");
1381 if (pos == std::string::npos)
1382 {
1383 // None found; assume it goes at the beginning of the raw input string
1384 raw_input_string.insert (0, " -- ");
1385 }
1386 }
Chris Lattner24943d22010-06-08 16:52:24 +00001387
1388 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1389 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001390 std::vector<bool> used (old_size + 1, false);
1391
1392 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001393
1394 for (int i = 0; i < option_arg_vector->size(); ++i)
1395 {
1396 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00001397 OptionArgValue value_pair = option_pair.second;
1398 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00001399 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00001400 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00001401 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001402 {
1403 if (!wants_raw_input
1404 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
1405 new_args.AppendArgument (value.c_str());
1406 }
Chris Lattner24943d22010-06-08 16:52:24 +00001407 else
1408 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001409 if (value_type != optional_argument)
1410 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001411 if (value.compare ("<no-argument>") != 0)
1412 {
1413 int index = GetOptionArgumentPosition (value.c_str());
1414 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001415 {
Chris Lattner24943d22010-06-08 16:52:24 +00001416 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00001417 if (value_type != optional_argument)
1418 new_args.AppendArgument (value.c_str());
1419 else
1420 {
1421 char buffer[255];
1422 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
1423 new_args.AppendArgument (buffer);
1424 }
1425
1426 }
Chris Lattner24943d22010-06-08 16:52:24 +00001427 else if (index >= cmd_args.GetArgumentCount())
1428 {
1429 result.AppendErrorWithFormat
1430 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1431 index);
1432 result.SetStatus (eReturnStatusFailed);
1433 return;
1434 }
1435 else
1436 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001437 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
1438 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1439 if (strpos != std::string::npos)
1440 {
1441 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
1442 }
1443
1444 if (value_type != optional_argument)
1445 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
1446 else
1447 {
1448 char buffer[255];
1449 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
1450 cmd_args.GetArgumentAtIndex (index));
1451 new_args.AppendArgument (buffer);
1452 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001453 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001454 }
1455 }
1456 }
1457 }
1458
1459 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1460 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001461 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00001462 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1463 }
1464
1465 cmd_args.Clear();
1466 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1467 }
1468 else
1469 {
1470 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00001471 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
1472 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
1473 // input string.
1474 if (wants_raw_input)
1475 {
1476 cmd_args.Clear();
1477 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1478 }
Chris Lattner24943d22010-06-08 16:52:24 +00001479 return;
1480 }
1481
1482 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1483 return;
1484}
1485
1486
1487int
1488CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1489{
1490 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1491 // of zero.
1492
1493 char *cptr = (char *) in_string;
1494
1495 // Does it start with '%'
1496 if (cptr[0] == '%')
1497 {
1498 ++cptr;
1499
1500 // Is the rest of it entirely digits?
1501 if (isdigit (cptr[0]))
1502 {
1503 const char *start = cptr;
1504 while (isdigit (cptr[0]))
1505 ++cptr;
1506
1507 // We've gotten to the end of the digits; are we at the end of the string?
1508 if (cptr[0] == '\0')
1509 position = atoi (start);
1510 }
1511 }
1512
1513 return position;
1514}
1515
1516void
1517CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1518{
Greg Clayton887aa282010-10-11 01:05:37 +00001519 // Don't parse any .lldbinit files if we were asked not to
1520 if (m_skip_lldbinit_files)
1521 return;
1522
Chris Lattner24943d22010-06-08 16:52:24 +00001523 const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit";
Greg Clayton537a7a82010-10-20 20:54:39 +00001524 FileSpec init_file (init_file_path, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001525 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
1526 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
1527
1528 if (init_file.Exists())
1529 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001530 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
1531 bool stop_on_continue = true;
1532 bool stop_on_error = false;
1533 bool echo_commands = false;
1534 bool print_results = false;
1535
1536 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, result);
Chris Lattner24943d22010-06-08 16:52:24 +00001537 }
1538 else
1539 {
1540 // nothing to be done if the file doesn't exist
1541 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1542 }
1543}
1544
Jim Ingham949d5ac2011-02-18 00:54:25 +00001545void
Jim Inghama4fede32011-03-11 01:51:49 +00001546CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001547 ExecutionContext *override_context,
1548 bool stop_on_continue,
1549 bool stop_on_error,
1550 bool echo_commands,
1551 bool print_results,
1552 CommandReturnObject &result)
1553{
1554 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00001555
1556 // If we are going to continue past a "continue" then we need to run the commands synchronously.
1557 // Make sure you reset this value anywhere you return from the function.
1558
1559 bool old_async_execution = m_debugger.GetAsyncExecution();
1560
1561 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
1562 // cause series of commands that change the context, then do an operation that relies on that context to fail.
1563
1564 if (override_context != NULL)
1565 m_debugger.UpdateExecutionContext (override_context);
1566
1567 if (!stop_on_continue)
1568 {
1569 m_debugger.SetAsyncExecution (false);
1570 }
1571
1572 for (int idx = 0; idx < num_lines; idx++)
1573 {
1574 const char *cmd = commands.GetStringAtIndex(idx);
1575 if (cmd[0] == '\0')
1576 continue;
1577
Jim Ingham949d5ac2011-02-18 00:54:25 +00001578 if (echo_commands)
1579 {
1580 result.AppendMessageWithFormat ("%s %s\n",
1581 GetPrompt(),
1582 cmd);
1583 }
1584
Greg Claytonaa378b12011-02-20 02:15:07 +00001585 CommandReturnObject tmp_result;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001586 bool success = HandleCommand(cmd, false, tmp_result, NULL);
1587
1588 if (print_results)
1589 {
1590 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00001591 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00001592 }
1593
1594 if (!success || !tmp_result.Succeeded())
1595 {
1596 if (stop_on_error)
1597 {
1598 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed.\n",
1599 idx, cmd);
1600 result.SetStatus (eReturnStatusFailed);
1601 m_debugger.SetAsyncExecution (old_async_execution);
1602 return;
1603 }
1604 else if (print_results)
1605 {
1606 result.AppendMessageWithFormat ("Command #%d '%s' failed with error: %s.\n",
1607 idx + 1,
1608 cmd,
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00001609 tmp_result.GetErrorData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00001610 }
1611 }
1612
1613 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
1614 // could be running (for instance in Breakpoint Commands.
1615 // So we check the return value to see if it is has running in it.
1616 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
1617 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
1618 {
1619 if (stop_on_continue)
1620 {
1621 // If we caused the target to proceed, and we're going to stop in that case, set the
1622 // status in our real result before returning. This is an error if the continue was not the
1623 // last command in the set of commands to be run.
1624 if (idx != num_lines - 1)
1625 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
1626 idx + 1, cmd);
1627 else
1628 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
1629
1630 result.SetStatus(tmp_result.GetStatus());
1631 m_debugger.SetAsyncExecution (old_async_execution);
1632
1633 return;
1634 }
1635 }
1636
1637 }
1638
1639 result.SetStatus (eReturnStatusSuccessFinishResult);
1640 m_debugger.SetAsyncExecution (old_async_execution);
1641
1642 return;
1643}
1644
1645void
1646CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
1647 ExecutionContext *context,
1648 bool stop_on_continue,
1649 bool stop_on_error,
1650 bool echo_command,
1651 bool print_result,
1652 CommandReturnObject &result)
1653{
1654 if (cmd_file.Exists())
1655 {
1656 bool success;
1657 StringList commands;
1658 success = commands.ReadFileLines(cmd_file);
1659 if (!success)
1660 {
1661 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
1662 result.SetStatus (eReturnStatusFailed);
1663 return;
1664 }
1665 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, result);
1666 }
1667 else
1668 {
1669 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
1670 cmd_file.GetFilename().AsCString());
1671 result.SetStatus (eReturnStatusFailed);
1672 return;
1673 }
1674}
1675
Chris Lattner24943d22010-06-08 16:52:24 +00001676ScriptInterpreter *
1677CommandInterpreter::GetScriptInterpreter ()
1678{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001679 if (m_script_interpreter_ap.get() != NULL)
1680 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00001681
Caroline Tice0aa2e552011-01-14 00:29:16 +00001682 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
1683 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00001684 {
Caroline Tice0aa2e552011-01-14 00:29:16 +00001685 case eScriptLanguageNone:
1686 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
1687 break;
1688 case eScriptLanguagePython:
1689 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
1690 break;
1691 default:
1692 break;
1693 };
1694
1695 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00001696}
1697
1698
1699
1700bool
1701CommandInterpreter::GetSynchronous ()
1702{
1703 return m_synchronous_execution;
1704}
1705
1706void
1707CommandInterpreter::SetSynchronous (bool value)
1708{
Johnny Chend7a4eb02010-10-14 01:22:03 +00001709 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00001710}
1711
1712void
1713CommandInterpreter::OutputFormattedHelpText (Stream &strm,
1714 const char *word_text,
1715 const char *separator,
1716 const char *help_text,
1717 uint32_t max_word_len)
1718{
Greg Clayton238c0a12010-09-18 01:14:36 +00001719 const uint32_t max_columns = m_debugger.GetTerminalWidth();
1720
Chris Lattner24943d22010-06-08 16:52:24 +00001721 int indent_size = max_word_len + strlen (separator) + 2;
1722
1723 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00001724
1725 StreamString text_strm;
1726 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
1727
1728 size_t len = text_strm.GetSize();
1729 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00001730 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00001731 {
1732 text_strm.EOL();
1733 len = text_strm.GetSize();
1734 }
Chris Lattner24943d22010-06-08 16:52:24 +00001735
1736 if (len < max_columns)
1737 {
1738 // Output it as a single line.
1739 strm.Printf ("%s", text);
1740 }
1741 else
1742 {
1743 // We need to break it up into multiple lines.
1744 bool first_line = true;
1745 int text_width;
1746 int start = 0;
1747 int end = start;
1748 int final_end = strlen (text);
1749 int sub_len;
1750
1751 while (end < final_end)
1752 {
1753 if (first_line)
1754 text_width = max_columns - 1;
1755 else
1756 text_width = max_columns - indent_size - 1;
1757
1758 // Don't start the 'text' on a space, since we're already outputting the indentation.
1759 if (!first_line)
1760 {
1761 while ((start < final_end) && (text[start] == ' '))
1762 start++;
1763 }
1764
1765 end = start + text_width;
1766 if (end > final_end)
1767 end = final_end;
1768 else
1769 {
1770 // If we're not at the end of the text, make sure we break the line on white space.
1771 while (end > start
1772 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
1773 end--;
1774 }
1775
1776 sub_len = end - start;
1777 if (start != 0)
1778 strm.EOL();
1779 if (!first_line)
1780 strm.Indent();
1781 else
1782 first_line = false;
1783 assert (start <= final_end);
1784 assert (start + sub_len <= final_end);
1785 if (sub_len > 0)
1786 strm.Write (text + start, sub_len);
1787 start = end + 1;
1788 }
1789 }
1790 strm.EOL();
1791 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001792}
1793
1794void
1795CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
1796 StringList &commands_found, StringList &commands_help)
1797{
1798 CommandObject::CommandMap::const_iterator pos;
1799 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
1800 CommandObject *sub_cmd_obj;
1801
1802 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
1803 {
1804 const char * command_name = pos->first.c_str();
1805 sub_cmd_obj = pos->second.get();
1806 StreamString complete_command_name;
1807
1808 complete_command_name.Printf ("%s %s", prefix, command_name);
1809
Greg Clayton238c0a12010-09-18 01:14:36 +00001810 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001811 {
1812 commands_found.AppendString (complete_command_name.GetData());
1813 commands_help.AppendString (sub_cmd_obj->GetHelp());
1814 }
1815
1816 if (sub_cmd_obj->IsMultiwordObject())
1817 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
1818 commands_help);
1819 }
1820
1821}
1822
1823void
1824CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
1825 StringList &commands_help)
1826{
1827 CommandObject::CommandMap::const_iterator pos;
1828
1829 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1830 {
1831 const char *command_name = pos->first.c_str();
1832 CommandObject *cmd_obj = pos->second.get();
1833
Greg Clayton238c0a12010-09-18 01:14:36 +00001834 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001835 {
1836 commands_found.AppendString (command_name);
1837 commands_help.AppendString (cmd_obj->GetHelp());
1838 }
1839
1840 if (cmd_obj->IsMultiwordObject())
1841 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
1842
1843 }
1844}