blob: c0f6dcd794e6d0fd16c278ee1bf91147883e6eb3 [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"
Greg Claytonabe0fed2011-04-18 08:33:37 +000022//#include "../Commands/CommandObjectFile.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000023#include "../Commands/CommandObjectFrame.h"
24#include "../Commands/CommandObjectHelp.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000025#include "../Commands/CommandObjectLog.h"
26#include "../Commands/CommandObjectMemory.h"
Greg Claytonb1888f22011-03-19 01:12:21 +000027#include "../Commands/CommandObjectPlatform.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000028#include "../Commands/CommandObjectProcess.h"
29#include "../Commands/CommandObjectQuit.h"
Eli Friedmanb34d2a22010-06-09 22:08:29 +000030#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000031#include "../Commands/CommandObjectRegister.h"
Chris Lattner24943d22010-06-08 16:52:24 +000032#include "CommandObjectScript.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000033#include "../Commands/CommandObjectSettings.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000034#include "../Commands/CommandObjectSource.h"
Jim Ingham767af882010-07-07 03:36:20 +000035#include "../Commands/CommandObjectCommands.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000036#include "../Commands/CommandObjectSyntax.h"
37#include "../Commands/CommandObjectTarget.h"
38#include "../Commands/CommandObjectThread.h"
Johnny Chen902e0182010-12-23 20:21:44 +000039#include "../Commands/CommandObjectVersion.h"
Chris Lattner24943d22010-06-08 16:52:24 +000040
Jim Ingham84cdc152010-06-15 19:49:27 +000041#include "lldb/Interpreter/Args.h"
Caroline Tice5ddbe212011-05-06 21:37:15 +000042#include "lldb/Interpreter/Options.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.
Caroline Tice5ddbe212011-05-06 21:37:15 +000096 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
97 if (cmd_obj_sp)
98 {
99 AddAlias ("q", cmd_obj_sp);
100 AddAlias ("exit", cmd_obj_sp);
101 }
102
103 cmd_obj_sp = GetCommandSPExact ("process continue", false);
104 if (cmd_obj_sp)
105 {
106 AddAlias ("c", cmd_obj_sp);
107 AddAlias ("continue", cmd_obj_sp);
108 }
109
110 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
111 if (cmd_obj_sp)
112 AddAlias ("b", cmd_obj_sp);
113
114 cmd_obj_sp = GetCommandSPExact ("thread backtrace", false);
115 if (cmd_obj_sp)
116 AddAlias ("bt", cmd_obj_sp);
117
118 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
119 if (cmd_obj_sp)
120 AddAlias ("si", cmd_obj_sp);
121
122 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
123 if (cmd_obj_sp)
124 {
125 AddAlias ("s", cmd_obj_sp);
126 AddAlias ("step", cmd_obj_sp);
127 }
128
129 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
130 if (cmd_obj_sp)
131 {
132 AddAlias ("n", cmd_obj_sp);
133 AddAlias ("next", cmd_obj_sp);
134 }
135
136 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
137 if (cmd_obj_sp)
138 {
139 AddAlias ("f", cmd_obj_sp);
140 AddAlias ("finish", cmd_obj_sp);
141 }
142
143 cmd_obj_sp = GetCommandSPExact ("source list", false);
144 if (cmd_obj_sp)
145 {
146 AddAlias ("l", cmd_obj_sp);
147 AddAlias ("list", cmd_obj_sp);
148 }
149
150 cmd_obj_sp = GetCommandSPExact ("memory read", false);
151 if (cmd_obj_sp)
152 AddAlias ("x", cmd_obj_sp);
153
154 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
155 if (cmd_obj_sp)
156 AddAlias ("up", cmd_obj_sp);
157
158 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
159 if (cmd_obj_sp)
160 AddAlias ("down", cmd_obj_sp);
161
162 cmd_obj_sp = GetCommandSPExact ("target create", false);
163 if (cmd_obj_sp)
164 AddAlias ("file", cmd_obj_sp);
165
166 cmd_obj_sp = GetCommandSPExact ("target modules", false);
167 if (cmd_obj_sp)
168 AddAlias ("image", cmd_obj_sp);
169
170
171 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghame56493f2011-03-22 02:29:32 +0000172
Caroline Tice5ddbe212011-05-06 21:37:15 +0000173 cmd_obj_sp = GetCommandSPExact ("expression", false);
174 if (cmd_obj_sp)
175 {
176 AddAlias ("expr", cmd_obj_sp);
177
178 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
179 AddAlias ("p", cmd_obj_sp);
180 AddAlias ("print", cmd_obj_sp);
181 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
182 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
183
184 alias_arguments_vector_sp.reset (new OptionArgVector);
185 ProcessAliasOptionsArgs (cmd_obj_sp, "-o --", alias_arguments_vector_sp);
186 AddAlias ("po", cmd_obj_sp);
187 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
188 }
189
190 cmd_obj_sp = GetCommandSPExact ("process launch", false);
191 if (cmd_obj_sp)
192 {
193 alias_arguments_vector_sp.reset (new OptionArgVector);
194 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
195 AddAlias ("r", cmd_obj_sp);
196 AddAlias ("run", cmd_obj_sp);
197 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
198 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
199 }
200
Chris Lattner24943d22010-06-08 16:52:24 +0000201}
202
Chris Lattner24943d22010-06-08 16:52:24 +0000203const char *
204CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
205{
206 // This function has not yet been implemented.
207
208 // Look for any embedded script command
209 // If found,
210 // get interpreter object from the command dictionary,
211 // call execute_one_command on it,
212 // get the results as a string,
213 // substitute that string for current stuff.
214
215 return arg;
216}
217
218
219void
220CommandInterpreter::LoadCommandDictionary ()
221{
222 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
223
224 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
225 //
226 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
227 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
228 // the cross-referencing stuff) are created!!!
229 //
230 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
231
232
233 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
234 // are created. This is so that when another command is created that needs to go into a crossref object,
235 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
236 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
237
Chris Lattner24943d22010-06-08 16:52:24 +0000238 // Non-CommandObjectCrossref commands can now be created.
239
Caroline Tice5bc8c972010-09-20 20:44:43 +0000240 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000241
Greg Clayton238c0a12010-09-18 01:14:36 +0000242 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000243 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000244 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000245 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000246 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
247 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Claytonabe0fed2011-04-18 08:33:37 +0000248// m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000249 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000250 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Claytone1f50b92011-05-03 22:09:39 +0000251 /// m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000252 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
253 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonb1888f22011-03-19 01:12:21 +0000254 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000255 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000256 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000257 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000258 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000259 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000260 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000261 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
262 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000263 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000264
265 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000266 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000267 "_regexp-break",
Caroline Ticec1ad82e2010-09-07 22:38:08 +0000268 "Set a breakpoint using a regular expression to specify the location.",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000269 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000270 if (break_regex_cmd_ap.get())
271 {
272 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
273 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
274 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
Greg Claytonb72d0f02011-04-12 05:54:46 +0000275 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000276 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
Greg Claytonb01000f2011-01-17 03:46:26 +0000277 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000278 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
279 {
280 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
281 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
282 }
283 }
Jim Inghame56493f2011-03-22 02:29:32 +0000284
285 std::auto_ptr<CommandObjectRegexCommand>
286 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000287 "_regexp-down",
288 "Go down \"n\" frames in the stack (1 frame by default).",
289 "_regexp-down [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000290 if (down_regex_cmd_ap.get())
291 {
292 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
293 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
294 {
295 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
296 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
297 }
298 }
299
300 std::auto_ptr<CommandObjectRegexCommand>
301 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000302 "_regexp-up",
303 "Go up \"n\" frames in the stack (1 frame by default).",
304 "_regexp-up [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000305 if (up_regex_cmd_ap.get())
306 {
307 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
308 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
309 {
310 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
311 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
312 }
313 }
Chris Lattner24943d22010-06-08 16:52:24 +0000314}
315
316int
317CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
318 StringList &matches)
319{
320 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
321
322 if (include_aliases)
323 {
324 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
325 }
326
327 return matches.GetSize();
328}
329
330CommandObjectSP
331CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
332{
333 CommandObject::CommandMap::iterator pos;
334 CommandObjectSP ret_val;
335
336 std::string cmd(cmd_cstr);
337
338 if (HasCommands())
339 {
340 pos = m_command_dict.find(cmd);
341 if (pos != m_command_dict.end())
342 ret_val = pos->second;
343 }
344
345 if (include_aliases && HasAliases())
346 {
347 pos = m_alias_dict.find(cmd);
348 if (pos != m_alias_dict.end())
349 ret_val = pos->second;
350 }
351
352 if (HasUserCommands())
353 {
354 pos = m_user_dict.find(cmd);
355 if (pos != m_user_dict.end())
356 ret_val = pos->second;
357 }
358
359 if (!exact && ret_val == NULL)
360 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000361 // We will only get into here if we didn't find any exact matches.
362
363 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
364
Chris Lattner24943d22010-06-08 16:52:24 +0000365 StringList local_matches;
366 if (matches == NULL)
367 matches = &local_matches;
368
Jim Inghamd40f8a62010-07-06 22:46:59 +0000369 unsigned int num_cmd_matches = 0;
370 unsigned int num_alias_matches = 0;
371 unsigned int num_user_matches = 0;
372
373 // Look through the command dictionaries one by one, and if we get only one match from any of
374 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
375
Chris Lattner24943d22010-06-08 16:52:24 +0000376 if (HasCommands())
377 {
378 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
379 }
380
381 if (num_cmd_matches == 1)
382 {
383 cmd.assign(matches->GetStringAtIndex(0));
384 pos = m_command_dict.find(cmd);
385 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000386 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000387 }
388
Jim Ingham9a574172010-06-24 20:28:42 +0000389 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000390 {
391 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
392
393 }
394
Jim Inghamd40f8a62010-07-06 22:46:59 +0000395 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000396 {
397 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
398 pos = m_alias_dict.find(cmd);
399 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000400 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000401 }
402
Jim Ingham9a574172010-06-24 20:28:42 +0000403 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000404 {
405 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
406 }
407
Jim Inghamd40f8a62010-07-06 22:46:59 +0000408 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000409 {
410 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
411
412 pos = m_user_dict.find (cmd);
413 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000414 user_match_sp = pos->second;
415 }
416
417 // If we got exactly one match, return that, otherwise return the match list.
418
419 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
420 {
421 if (num_cmd_matches)
422 return real_match_sp;
423 else if (num_alias_matches)
424 return alias_match_sp;
425 else
426 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000427 }
428 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000429 else if (matches && ret_val != NULL)
430 {
431 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000432 }
433
434
435 return ret_val;
436}
437
Greg Claytond12aeab2011-04-20 16:37:46 +0000438bool
439CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
440{
441 if (name && name[0])
442 {
443 std::string name_sstr(name);
444 if (!can_replace)
445 {
446 if (m_command_dict.find (name_sstr) != m_command_dict.end())
447 return false;
448 }
449 m_command_dict[name_sstr] = cmd_sp;
450 return true;
451 }
452 return false;
453}
454
455
Jim Inghamd40f8a62010-07-06 22:46:59 +0000456CommandObjectSP
457CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000458{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000459 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
460 CommandObjectSP ret_val; // Possibly empty return value.
461
462 if (cmd_cstr == NULL)
463 return ret_val;
464
465 if (cmd_words.GetArgumentCount() == 1)
466 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
467 else
468 {
469 // We have a multi-word command (seemingly), so we need to do more work.
470 // First, get the cmd_obj_sp for the first word in the command.
471 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
472 if (cmd_obj_sp.get() != NULL)
473 {
474 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
475 // command name), and find the appropriate sub-command SP for each command word....
476 size_t end = cmd_words.GetArgumentCount();
477 for (size_t j= 1; j < end; ++j)
478 {
479 if (cmd_obj_sp->IsMultiwordObject())
480 {
481 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
482 (cmd_words.GetArgumentAtIndex (j));
483 if (cmd_obj_sp.get() == NULL)
484 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
485 return ret_val;
486 }
487 else
488 // We have more words in the command name, but we don't have a multiword object. Fail and return
489 // empty 'ret_val'.
490 return ret_val;
491 }
492 // We successfully looped through all the command words and got valid command objects for them. Assign the
493 // last object retrieved to 'ret_val'.
494 ret_val = cmd_obj_sp;
495 }
496 }
497 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000498}
499
500CommandObject *
501CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
502{
503 return GetCommandSPExact (cmd_cstr, include_aliases).get();
504}
505
506CommandObject *
507CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
508{
509 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
510
511 // If we didn't find an exact match to the command string in the commands, look in
512 // the aliases.
513
514 if (command_obj == NULL)
515 {
516 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
517 }
518
519 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
520 // in both the commands and the aliases.
521
522 if (command_obj == NULL)
523 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
524
525 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000526}
527
528bool
529CommandInterpreter::CommandExists (const char *cmd)
530{
531 return m_command_dict.find(cmd) != m_command_dict.end();
532}
533
534bool
Caroline Tice5ddbe212011-05-06 21:37:15 +0000535CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
536 const char *options_args,
537 OptionArgVectorSP &option_arg_vector_sp)
538{
539 bool success = true;
540 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
541
542 if (!options_args || (strlen (options_args) < 1))
543 return true;
544
545 std::string options_string (options_args);
546 Args args (options_args);
547 CommandReturnObject result;
548 // Check to see if the command being aliased can take any command options.
549 Options *options = cmd_obj_sp->GetOptions ();
550 if (options)
551 {
552 // See if any options were specified as part of the alias; if so, handle them appropriately.
553 options->NotifyOptionParsingStarting ();
554 args.Unshift ("dummy_arg");
555 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
556 args.Shift ();
557 if (result.Succeeded())
558 options->VerifyPartialOptions (result);
559 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
560 {
561 result.AppendError ("Unable to create requested alias.\n");
562 return false;
563 }
564 }
565
566 if (options_string.size() > 0)
567 {
568 if (cmd_obj_sp->WantsRawCommandString ())
569 option_arg_vector->push_back (OptionArgPair ("<argument>",
570 OptionArgValue (-1,
571 options_string)));
572 else
573 {
574 int argc = args.GetArgumentCount();
575 for (size_t i = 0; i < argc; ++i)
576 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
577 option_arg_vector->push_back
578 (OptionArgPair ("<argument>",
579 OptionArgValue (-1,
580 std::string (args.GetArgumentAtIndex (i)))));
581 }
582 }
583
584 return success;
585}
586
587bool
Chris Lattner24943d22010-06-08 16:52:24 +0000588CommandInterpreter::AliasExists (const char *cmd)
589{
590 return m_alias_dict.find(cmd) != m_alias_dict.end();
591}
592
593bool
594CommandInterpreter::UserCommandExists (const char *cmd)
595{
596 return m_user_dict.find(cmd) != m_user_dict.end();
597}
598
599void
600CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
601{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000602 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000603 m_alias_dict[alias_name] = command_obj_sp;
604}
605
606bool
607CommandInterpreter::RemoveAlias (const char *alias_name)
608{
609 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
610 if (pos != m_alias_dict.end())
611 {
612 m_alias_dict.erase(pos);
613 return true;
614 }
615 return false;
616}
617bool
618CommandInterpreter::RemoveUser (const char *alias_name)
619{
620 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
621 if (pos != m_user_dict.end())
622 {
623 m_user_dict.erase(pos);
624 return true;
625 }
626 return false;
627}
628
Chris Lattner24943d22010-06-08 16:52:24 +0000629void
630CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
631{
632 help_string.Printf ("'%s", command_name);
633 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
634
635 if (option_arg_vector_sp != NULL)
636 {
637 OptionArgVector *options = option_arg_vector_sp.get();
638 for (int i = 0; i < options->size(); ++i)
639 {
640 OptionArgPair cur_option = (*options)[i];
641 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000642 OptionArgValue value_pair = cur_option.second;
643 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000644 if (opt.compare("<argument>") == 0)
645 {
646 help_string.Printf (" %s", value.c_str());
647 }
648 else
649 {
650 help_string.Printf (" %s", opt.c_str());
651 if ((value.compare ("<no-argument>") != 0)
652 && (value.compare ("<need-argument") != 0))
653 {
654 help_string.Printf (" %s", value.c_str());
655 }
656 }
657 }
658 }
659
660 help_string.Printf ("'");
661}
662
Greg Clayton65124ea2010-08-26 22:05:43 +0000663size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000664CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
665{
666 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000667 CommandObject::CommandMap::const_iterator end = dict.end();
668 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000669
Greg Clayton65124ea2010-08-26 22:05:43 +0000670 for (pos = dict.begin(); pos != end; ++pos)
671 {
672 size_t len = pos->first.size();
673 if (max_len < len)
674 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000675 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000676 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000677}
678
679void
680CommandInterpreter::GetHelp (CommandReturnObject &result)
681{
682 CommandObject::CommandMap::const_iterator pos;
683 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
684 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000685 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000686
687 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
688 {
689 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
690 max_len);
691 }
692 result.AppendMessage("");
693
694 if (m_alias_dict.size() > 0)
695 {
Jim Inghame3663e82010-10-22 18:47:16 +0000696 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000697 "(see 'help command alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000698 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000699 max_len = FindLongestCommandWord (m_alias_dict);
700
Chris Lattner24943d22010-06-08 16:52:24 +0000701 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
702 {
703 StreamString sstr;
704 StreamString translation_and_help;
705 std::string entry_name = pos->first;
706 std::string second_entry = pos->second.get()->GetCommandName();
707 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
708
709 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
710 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
711 translation_and_help.GetData(), max_len);
712 }
713 result.AppendMessage("");
714 }
715
716 if (m_user_dict.size() > 0)
717 {
718 result.AppendMessage ("The following is a list of your current user-defined commands:");
719 result.AppendMessage("");
720 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
721 {
722 result.AppendMessageWithFormat ("%s -- %s\n", pos->first.c_str(), pos->second->GetHelp());
723 }
724 result.AppendMessage("");
725 }
726
727 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
728}
729
Caroline Ticee0da7a52010-12-09 22:52:49 +0000730CommandObject *
731CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000732{
Caroline Ticee0da7a52010-12-09 22:52:49 +0000733 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
734 // eventually be invoked by the given command line.
735
736 CommandObject *cmd_obj = NULL;
737 std::string white_space (" \t\v");
738 size_t start = command_string.find_first_not_of (white_space);
739 size_t end = 0;
740 bool done = false;
741 while (!done)
742 {
743 if (start != std::string::npos)
744 {
745 // Get the next word from command_string.
746 end = command_string.find_first_of (white_space, start);
747 if (end == std::string::npos)
748 end = command_string.size();
749 std::string cmd_word = command_string.substr (start, end - start);
750
751 if (cmd_obj == NULL)
752 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
753 // command or alias.
754 cmd_obj = GetCommandObject (cmd_word.c_str());
755 else if (cmd_obj->IsMultiwordObject ())
756 {
757 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
758 CommandObject *sub_cmd_obj =
759 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
760 if (sub_cmd_obj)
761 cmd_obj = sub_cmd_obj;
762 else // cmd_word was not a valid sub-command word, so we are donee
763 done = true;
764 }
765 else
766 // We have a cmd_obj and it is not a multi-word object, so we are done.
767 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000768
Caroline Ticee0da7a52010-12-09 22:52:49 +0000769 // If we didn't find a valid command object, or our command object is not a multi-word object, or
770 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
771 // next word.
772
773 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
774 done = true;
775 else
776 start = command_string.find_first_not_of (white_space, end);
777 }
778 else
779 // Unable to find any more words.
780 done = true;
781 }
782
783 if (end == command_string.size())
784 command_string.clear();
785 else
786 command_string = command_string.substr(end);
787
788 return cmd_obj;
789}
790
791bool
Caroline Tice649116c2011-05-11 16:07:06 +0000792CommandInterpreter::StripFirstWord (std::string &command_string, std::string &word, bool &was_quoted, char &quote_char)
Caroline Ticee0da7a52010-12-09 22:52:49 +0000793{
794 std::string white_space (" \t\v");
795 size_t start;
796 size_t end;
797
798 start = command_string.find_first_not_of (white_space);
799 if (start != std::string::npos)
800 {
Caroline Tice649116c2011-05-11 16:07:06 +0000801 size_t len = command_string.size() - start;
802 if (len >= 2
803 && ((command_string[start] == '\'') || (command_string[start] == '"')))
Caroline Ticee0da7a52010-12-09 22:52:49 +0000804 {
Caroline Tice649116c2011-05-11 16:07:06 +0000805 was_quoted = true;
806 quote_char = command_string[start];
807 std::string quote_string = command_string.substr (start, 1);
808 start = start + 1;
809 end = command_string.find (quote_string, start);
810 if (end != std::string::npos)
811 {
812 word = command_string.substr (start, end - start);
813 if (end + 1 < len)
814 command_string = command_string.substr (end+1);
815 else
816 command_string.erase ();
817 size_t pos = command_string.find_first_not_of (white_space);
818 if ((pos != 0) && (pos != std::string::npos))
819 command_string = command_string.substr (pos);
820 }
821 else
822 {
823 word = command_string.substr (start - 1);
824 command_string.erase ();
825 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000826 }
827 else
828 {
Caroline Tice649116c2011-05-11 16:07:06 +0000829 end = command_string.find_first_of (white_space, start);
830 if (end != std::string::npos)
831 {
832 word = command_string.substr (start, end - start);
833 command_string = command_string.substr (end);
834 size_t pos = command_string.find_first_not_of (white_space);
835 if ((pos != 0) && (pos != std::string::npos))
836 command_string = command_string.substr (pos);
837 }
838 else
839 {
840 word = command_string.substr (start);
841 command_string.erase();
842 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000843 }
844
845 }
846 return true;
847}
848
849void
850CommandInterpreter::BuildAliasResult (const char *alias_name, std::string &raw_input_string, std::string &alias_result,
851 CommandObject *&alias_cmd_obj, CommandReturnObject &result)
852{
853 Args cmd_args (raw_input_string.c_str());
854 alias_cmd_obj = GetCommandObject (alias_name);
855 StreamString result_str;
856
857 if (alias_cmd_obj)
858 {
859 std::string alias_name_str = alias_name;
860 if ((cmd_args.GetArgumentCount() == 0)
861 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
862 cmd_args.Unshift (alias_name);
863
864 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
865 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
866
867 if (option_arg_vector_sp.get())
868 {
869 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
870
871 for (int i = 0; i < option_arg_vector->size(); ++i)
872 {
873 OptionArgPair option_pair = (*option_arg_vector)[i];
874 OptionArgValue value_pair = option_pair.second;
875 int value_type = value_pair.first;
876 std::string option = option_pair.first;
877 std::string value = value_pair.second;
878 if (option.compare ("<argument>") == 0)
879 result_str.Printf (" %s", value.c_str());
880 else
881 {
882 result_str.Printf (" %s", option.c_str());
883 if (value_type != optional_argument)
884 result_str.Printf (" ");
885 if (value.compare ("<no_argument>") != 0)
886 {
887 int index = GetOptionArgumentPosition (value.c_str());
888 if (index == 0)
889 result_str.Printf ("%s", value.c_str());
890 else if (index >= cmd_args.GetArgumentCount())
891 {
892
893 result.AppendErrorWithFormat
894 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
895 index);
896 result.SetStatus (eReturnStatusFailed);
897 return;
898 }
899 else
900 {
901 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
902 if (strpos != std::string::npos)
903 raw_input_string = raw_input_string.erase (strpos,
904 strlen (cmd_args.GetArgumentAtIndex (index)));
905 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
906 }
907 }
908 }
909 }
910 }
911
912 alias_result = result_str.GetData();
913 }
914}
915
916bool
917CommandInterpreter::HandleCommand (const char *command_line,
918 bool add_to_history,
919 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +0000920 ExecutionContext *override_context,
921 bool repeat_on_empty_command)
922
Caroline Ticee0da7a52010-12-09 22:52:49 +0000923{
Jim Ingham949d5ac2011-02-18 00:54:25 +0000924
Caroline Ticee0da7a52010-12-09 22:52:49 +0000925 bool done = false;
926 CommandObject *cmd_obj = NULL;
927 std::string next_word;
928 bool wants_raw_input = false;
929 std::string command_string (command_line);
930
931 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +0000932 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
933
934 // Make a scoped cleanup object that will clear the crash description string
935 // on exit of this function.
936 lldb_utility::CleanUp <const char *, void> crash_description_cleanup(NULL, Host::SetCrashDescription);
937
Caroline Ticee0da7a52010-12-09 22:52:49 +0000938 if (log)
939 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +0000940
Jim Inghamabab14b2010-11-04 23:08:45 +0000941 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
942
Greg Claytonb72d0f02011-04-12 05:54:46 +0000943 UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +0000944
Jim Ingham949d5ac2011-02-18 00:54:25 +0000945 bool empty_command = false;
946 bool comment_command = false;
947 if (command_string.empty())
948 empty_command = true;
949 else
Chris Lattner24943d22010-06-08 16:52:24 +0000950 {
Jim Ingham949d5ac2011-02-18 00:54:25 +0000951 const char *k_space_characters = "\t\n\v\f\r ";
952
953 size_t non_space = command_string.find_first_not_of (k_space_characters);
954 // Check for empty line or comment line (lines whose first
955 // non-space character is the comment character for this interpreter)
956 if (non_space == std::string::npos)
957 empty_command = true;
958 else if (command_string[non_space] == m_comment_char)
959 comment_command = true;
960 }
961
962 if (empty_command)
963 {
964 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +0000965 {
Jim Ingham949d5ac2011-02-18 00:54:25 +0000966 if (m_command_history.empty())
967 {
968 result.AppendError ("empty command");
969 result.SetStatus(eReturnStatusFailed);
970 return false;
971 }
972 else
973 {
974 command_line = m_repeat_command.c_str();
975 command_string = command_line;
976 if (m_repeat_command.empty())
977 {
978 result.AppendErrorWithFormat("No auto repeat.\n");
979 result.SetStatus (eReturnStatusFailed);
980 return false;
981 }
982 }
983 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000984 }
985 else
986 {
Jim Ingham949d5ac2011-02-18 00:54:25 +0000987 result.SetStatus (eReturnStatusSuccessFinishNoResult);
988 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000989 }
Jim Ingham949d5ac2011-02-18 00:54:25 +0000990 }
991 else if (comment_command)
992 {
993 result.SetStatus (eReturnStatusSuccessFinishNoResult);
994 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000995 }
Caroline Tice649116c2011-05-11 16:07:06 +0000996
Caroline Ticee0da7a52010-12-09 22:52:49 +0000997 // Phase 1.
998
999 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1000 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1001 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1002 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1003 // 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 +00001004 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +00001005 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +00001006
Caroline Ticee0da7a52010-12-09 22:52:49 +00001007 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001008 size_t actual_cmd_name_len = 0;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001009 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +00001010 {
Caroline Tice649116c2011-05-11 16:07:06 +00001011 bool was_quoted = false;
1012 char quote_char = '\0';
1013 StripFirstWord (command_string, next_word, was_quoted, quote_char);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001014 if (!cmd_obj && AliasExists (next_word.c_str()))
Chris Lattner24943d22010-06-08 16:52:24 +00001015 {
Caroline Ticee0da7a52010-12-09 22:52:49 +00001016 std::string alias_result;
1017 BuildAliasResult (next_word.c_str(), command_string, alias_result, cmd_obj, result);
1018 revised_command_line.Printf ("%s", alias_result.c_str());
1019 if (cmd_obj)
Caroline Tice56d2fc42010-12-14 18:51:39 +00001020 {
Caroline Ticee0da7a52010-12-09 22:52:49 +00001021 wants_raw_input = cmd_obj->WantsRawCommandString ();
Caroline Tice56d2fc42010-12-14 18:51:39 +00001022 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1023 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001024 }
1025 else if (!cmd_obj)
1026 {
1027 cmd_obj = GetCommandObject (next_word.c_str());
1028 if (cmd_obj)
Chris Lattner24943d22010-06-08 16:52:24 +00001029 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001030 actual_cmd_name_len += next_word.length();
Caroline Ticee0da7a52010-12-09 22:52:49 +00001031 revised_command_line.Printf ("%s", next_word.c_str());
1032 wants_raw_input = cmd_obj->WantsRawCommandString ();
Chris Lattner24943d22010-06-08 16:52:24 +00001033 }
1034 else
1035 {
Caroline Ticee0da7a52010-12-09 22:52:49 +00001036 revised_command_line.Printf ("%s", next_word.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001037 }
1038 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001039 else if (cmd_obj->IsMultiwordObject ())
1040 {
1041 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
1042 if (sub_cmd_obj)
1043 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001044 actual_cmd_name_len += next_word.length() + 1;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001045 revised_command_line.Printf (" %s", next_word.c_str());
1046 cmd_obj = sub_cmd_obj;
1047 wants_raw_input = cmd_obj->WantsRawCommandString ();
1048 }
1049 else
1050 {
Caroline Tice649116c2011-05-11 16:07:06 +00001051 if (was_quoted)
1052 {
1053 if (quote_char == '"')
1054 revised_command_line.Printf (" \"%s\"", next_word.c_str());
1055 else
1056 revised_command_line.Printf (" '%s'", next_word.c_str());
1057 }
1058 else
1059 revised_command_line.Printf (" %s", next_word.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001060 done = true;
1061 }
1062 }
1063 else
1064 {
Caroline Tice649116c2011-05-11 16:07:06 +00001065 if (was_quoted)
1066 {
1067 if (quote_char == '"')
1068 revised_command_line.Printf (" \"%s\"", next_word.c_str());
1069 else
1070 revised_command_line.Printf (" '%s'", next_word.c_str());
1071 }
1072 else
1073 revised_command_line.Printf (" %s", next_word.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001074 done = true;
1075 }
1076
1077 if (cmd_obj == NULL)
1078 {
1079 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1080 result.SetStatus (eReturnStatusFailed);
1081 return false;
1082 }
1083
1084 next_word.erase ();
1085 if (command_string.length() == 0)
1086 done = true;
1087
Chris Lattner24943d22010-06-08 16:52:24 +00001088 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001089
1090 if (command_string.size() > 0)
1091 revised_command_line.Printf (" %s", command_string.c_str());
1092
1093 // End of Phase 1.
1094 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1095 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1096 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1097 // wants_raw_input specifies whether the Execute method expects raw input or not.
1098
1099
1100 if (log)
1101 {
1102 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1103 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1104 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1105 }
1106
1107 // Phase 2.
1108 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1109 // CommandObject, with the appropriate arguments.
1110
1111 if (cmd_obj != NULL)
1112 {
1113 if (add_to_history)
1114 {
1115 Args command_args (revised_command_line.GetData());
1116 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1117 if (repeat_command != NULL)
1118 m_repeat_command.assign(repeat_command);
1119 else
1120 m_repeat_command.assign(command_line);
1121
1122 m_command_history.push_back (command_line);
1123 }
1124
1125 command_string = revised_command_line.GetData();
1126 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001127 std::string remainder;
1128 if (actual_cmd_name_len < command_string.length())
1129 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1130 // than cmd_obj->GetCommandName(), because name completion
1131 // allows users to enter short versions of the names,
1132 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +00001133
1134 // Remove any initial spaces
1135 std::string white_space (" \t\v");
1136 size_t pos = remainder.find_first_not_of (white_space);
1137 if (pos != 0 && pos != std::string::npos)
Greg Clayton91c9dcf2011-04-22 20:58:45 +00001138 remainder.erase(0, pos);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001139
1140 if (log)
1141 log->Printf ("HandleCommand, command line after removing command name(s): '%s'\n", remainder.c_str());
1142
1143
1144 if (wants_raw_input)
1145 cmd_obj->ExecuteRawCommandString (remainder.c_str(), result);
1146 else
1147 {
1148 Args cmd_args (remainder.c_str());
1149 cmd_obj->ExecuteWithOptions (cmd_args, result);
1150 }
1151 }
1152 else
1153 {
1154 // We didn't find the first command object, so complete the first argument.
1155 Args command_args (revised_command_line.GetData());
1156 StringList matches;
1157 int num_matches;
1158 int cursor_index = 0;
1159 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1160 bool word_complete;
1161 num_matches = HandleCompletionMatches (command_args,
1162 cursor_index,
1163 cursor_char_position,
1164 0,
1165 -1,
1166 word_complete,
1167 matches);
1168
1169 if (num_matches > 0)
1170 {
1171 std::string error_msg;
1172 error_msg.assign ("ambiguous command '");
1173 error_msg.append(command_args.GetArgumentAtIndex(0));
1174 error_msg.append ("'.");
1175
1176 error_msg.append (" Possible completions:");
1177 for (int i = 0; i < num_matches; i++)
1178 {
1179 error_msg.append ("\n\t");
1180 error_msg.append (matches.GetStringAtIndex (i));
1181 }
1182 error_msg.append ("\n");
1183 result.AppendRawError (error_msg.c_str(), error_msg.size());
1184 }
1185 else
1186 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1187
1188 result.SetStatus (eReturnStatusFailed);
1189 }
1190
Chris Lattner24943d22010-06-08 16:52:24 +00001191 return result.Succeeded();
1192}
1193
1194int
1195CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1196 int &cursor_index,
1197 int &cursor_char_position,
1198 int match_start_point,
1199 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001200 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001201 StringList &matches)
1202{
1203 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001204 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001205
1206 // For any of the command completions a unique match will be a complete word.
1207 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001208
1209 if (cursor_index == -1)
1210 {
1211 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001212 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001213 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1214 }
1215 else if (cursor_index == 0)
1216 {
1217 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001218 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001219 num_command_matches = matches.GetSize();
1220
1221 if (num_command_matches == 1
1222 && cmd_obj && cmd_obj->IsMultiwordObject()
1223 && matches.GetStringAtIndex(0) != NULL
1224 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1225 {
1226 look_for_subcommand = true;
1227 num_command_matches = 0;
1228 matches.DeleteStringAtIndex(0);
1229 parsed_line.AppendArgument ("");
1230 cursor_index++;
1231 cursor_char_position = 0;
1232 }
1233 }
1234
1235 if (cursor_index > 0 || look_for_subcommand)
1236 {
1237 // We are completing further on into a commands arguments, so find the command and tell it
1238 // to complete the command.
1239 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001240 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001241 if (command_object == NULL)
1242 {
1243 return 0;
1244 }
1245 else
1246 {
1247 parsed_line.Shift();
1248 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001249 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001250 cursor_index,
1251 cursor_char_position,
1252 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001253 max_return_elements,
1254 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001255 matches);
1256 }
1257 }
1258
1259 return num_command_matches;
1260
1261}
1262
1263int
1264CommandInterpreter::HandleCompletion (const char *current_line,
1265 const char *cursor,
1266 const char *last_char,
1267 int match_start_point,
1268 int max_return_elements,
1269 StringList &matches)
1270{
1271 // We parse the argument up to the cursor, so the last argument in parsed_line is
1272 // the one containing the cursor, and the cursor is after the last character.
1273
1274 Args parsed_line(current_line, last_char - current_line);
1275 Args partial_parsed_line(current_line, cursor - current_line);
1276
1277 int num_args = partial_parsed_line.GetArgumentCount();
1278 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1279 int cursor_char_position;
1280
1281 if (cursor_index == -1)
1282 cursor_char_position = 0;
1283 else
1284 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001285
1286 if (cursor > current_line && cursor[-1] == ' ')
1287 {
1288 // We are just after a space. If we are in an argument, then we will continue
1289 // parsing, but if we are between arguments, then we have to complete whatever the next
1290 // element would be.
1291 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1292 // protected by a quote) then the space will also be in the parsed argument...
1293
1294 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1295 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1296 {
1297 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1298 cursor_index++;
1299 cursor_char_position = 0;
1300 }
1301 }
Chris Lattner24943d22010-06-08 16:52:24 +00001302
1303 int num_command_matches;
1304
1305 matches.Clear();
1306
1307 // Only max_return_elements == -1 is supported at present:
1308 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001309 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001310 num_command_matches = HandleCompletionMatches (parsed_line,
1311 cursor_index,
1312 cursor_char_position,
1313 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001314 max_return_elements,
1315 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001316 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001317
1318 if (num_command_matches <= 0)
1319 return num_command_matches;
1320
1321 if (num_args == 0)
1322 {
1323 // If we got an empty string, insert nothing.
1324 matches.InsertStringAtIndex(0, "");
1325 }
1326 else
1327 {
1328 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1329 // put an empty string in element 0.
1330 std::string command_partial_str;
1331 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001332 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1333 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001334
1335 std::string common_prefix;
1336 matches.LongestCommonPrefix (common_prefix);
1337 int partial_name_len = command_partial_str.size();
1338
1339 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001340 // Only do this if the completer told us this was a complete word, however...
1341 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001342 {
1343 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1344 if (quote_char != '\0')
1345 common_prefix.push_back(quote_char);
1346
1347 common_prefix.push_back(' ');
1348 }
1349 common_prefix.erase (0, partial_name_len);
1350 matches.InsertStringAtIndex(0, common_prefix.c_str());
1351 }
1352 return num_command_matches;
1353}
1354
Chris Lattner24943d22010-06-08 16:52:24 +00001355
1356CommandInterpreter::~CommandInterpreter ()
1357{
1358}
1359
1360const char *
1361CommandInterpreter::GetPrompt ()
1362{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001363 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001364}
1365
1366void
1367CommandInterpreter::SetPrompt (const char *new_prompt)
1368{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001369 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001370}
1371
Jim Ingham5e16ef52010-10-04 19:49:29 +00001372size_t
Greg Clayton58928562011-02-09 01:08:52 +00001373CommandInterpreter::GetConfirmationInputReaderCallback
1374(
1375 void *baton,
1376 InputReader &reader,
1377 lldb::InputReaderAction action,
1378 const char *bytes,
1379 size_t bytes_len
1380)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001381{
Greg Clayton58928562011-02-09 01:08:52 +00001382 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001383 bool *response_ptr = (bool *) baton;
1384
1385 switch (action)
1386 {
1387 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001388 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001389 {
1390 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001391 {
Greg Clayton58928562011-02-09 01:08:52 +00001392 out_file.Printf ("%s", reader.GetPrompt());
1393 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001394 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001395 }
1396 break;
1397
1398 case eInputReaderDeactivate:
1399 break;
1400
1401 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001402 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001403 {
Greg Clayton58928562011-02-09 01:08:52 +00001404 out_file.Printf ("%s", reader.GetPrompt());
1405 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001406 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001407 break;
Caroline Tice4a348082011-05-02 20:41:46 +00001408
1409 case eInputReaderAsynchronousOutputWritten:
1410 break;
1411
Jim Ingham5e16ef52010-10-04 19:49:29 +00001412 case eInputReaderGotToken:
1413 if (bytes_len == 0)
1414 {
1415 reader.SetIsDone(true);
1416 }
1417 else if (bytes[0] == 'y')
1418 {
1419 *response_ptr = true;
1420 reader.SetIsDone(true);
1421 }
1422 else if (bytes[0] == 'n')
1423 {
1424 *response_ptr = false;
1425 reader.SetIsDone(true);
1426 }
1427 else
1428 {
Greg Clayton58928562011-02-09 01:08:52 +00001429 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001430 {
Greg Clayton58928562011-02-09 01:08:52 +00001431 out_file.Printf ("Please answer \"y\" or \"n\"\n%s", reader.GetPrompt());
1432 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001433 }
1434 }
1435 break;
1436
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001437 case eInputReaderInterrupt:
1438 case eInputReaderEndOfFile:
1439 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1440 reader.SetIsDone (true);
1441 break;
1442
Jim Ingham5e16ef52010-10-04 19:49:29 +00001443 case eInputReaderDone:
1444 break;
1445 }
1446
1447 return bytes_len;
1448
1449}
1450
1451bool
1452CommandInterpreter::Confirm (const char *message, bool default_answer)
1453{
Jim Ingham93057472010-10-04 22:44:14 +00001454 // Check AutoConfirm first:
1455 if (m_debugger.GetAutoConfirm())
1456 return default_answer;
1457
Jim Ingham5e16ef52010-10-04 19:49:29 +00001458 InputReaderSP reader_sp (new InputReader(GetDebugger()));
1459 bool response = default_answer;
1460 if (reader_sp)
1461 {
1462 std::string prompt(message);
1463 prompt.append(": [");
1464 if (default_answer)
1465 prompt.append ("Y/n] ");
1466 else
1467 prompt.append ("y/N] ");
1468
1469 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1470 &response, // baton
1471 eInputReaderGranularityLine, // token size, to pass to callback function
1472 NULL, // end token
1473 prompt.c_str(), // prompt
1474 true)); // echo input
1475 if (err.Success())
1476 {
1477 GetDebugger().PushInputReader (reader_sp);
1478 }
1479 reader_sp->WaitOnReaderIsDone();
1480 }
1481 return response;
1482}
1483
1484
Chris Lattner24943d22010-06-08 16:52:24 +00001485void
1486CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1487{
Jim Inghamd40f8a62010-07-06 22:46:59 +00001488 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001489
1490 if (cmd_obj_sp != NULL)
1491 {
1492 CommandObject *cmd_obj = cmd_obj_sp.get();
1493 if (cmd_obj->IsCrossRefObject ())
1494 cmd_obj->AddObject (object_type);
1495 }
1496}
1497
Chris Lattner24943d22010-06-08 16:52:24 +00001498OptionArgVectorSP
1499CommandInterpreter::GetAliasOptions (const char *alias_name)
1500{
1501 OptionArgMap::iterator pos;
1502 OptionArgVectorSP ret_val;
1503
1504 std::string alias (alias_name);
1505
1506 if (HasAliasOptions())
1507 {
1508 pos = m_alias_options.find (alias);
1509 if (pos != m_alias_options.end())
1510 ret_val = pos->second;
1511 }
1512
1513 return ret_val;
1514}
1515
1516void
1517CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1518{
1519 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1520 if (pos != m_alias_options.end())
1521 {
1522 m_alias_options.erase (pos);
1523 }
1524}
1525
1526void
1527CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1528{
1529 m_alias_options[alias_name] = option_arg_vector_sp;
1530}
1531
1532bool
1533CommandInterpreter::HasCommands ()
1534{
1535 return (!m_command_dict.empty());
1536}
1537
1538bool
1539CommandInterpreter::HasAliases ()
1540{
1541 return (!m_alias_dict.empty());
1542}
1543
1544bool
1545CommandInterpreter::HasUserCommands ()
1546{
1547 return (!m_user_dict.empty());
1548}
1549
1550bool
1551CommandInterpreter::HasAliasOptions ()
1552{
1553 return (!m_alias_options.empty());
1554}
1555
Chris Lattner24943d22010-06-08 16:52:24 +00001556void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001557CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
1558 const char *alias_name,
1559 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00001560 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001561 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00001562{
1563 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00001564
1565 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00001566
Caroline Tice44c841d2010-12-07 19:58:26 +00001567 // Make sure that the alias name is the 0th element in cmd_args
1568 std::string alias_name_str = alias_name;
1569 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1570 cmd_args.Unshift (alias_name);
1571
1572 Args new_args (alias_cmd_obj->GetCommandName());
1573 if (new_args.GetArgumentCount() == 2)
1574 new_args.Shift();
1575
Chris Lattner24943d22010-06-08 16:52:24 +00001576 if (option_arg_vector_sp.get())
1577 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001578 if (wants_raw_input)
1579 {
1580 // We have a command that both has command options and takes raw input. Make *sure* it has a
1581 // " -- " in the right place in the raw_input_string.
1582 size_t pos = raw_input_string.find(" -- ");
1583 if (pos == std::string::npos)
1584 {
1585 // None found; assume it goes at the beginning of the raw input string
1586 raw_input_string.insert (0, " -- ");
1587 }
1588 }
Chris Lattner24943d22010-06-08 16:52:24 +00001589
1590 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1591 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001592 std::vector<bool> used (old_size + 1, false);
1593
1594 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001595
1596 for (int i = 0; i < option_arg_vector->size(); ++i)
1597 {
1598 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00001599 OptionArgValue value_pair = option_pair.second;
1600 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00001601 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00001602 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00001603 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001604 {
1605 if (!wants_raw_input
1606 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
1607 new_args.AppendArgument (value.c_str());
1608 }
Chris Lattner24943d22010-06-08 16:52:24 +00001609 else
1610 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001611 if (value_type != optional_argument)
1612 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001613 if (value.compare ("<no-argument>") != 0)
1614 {
1615 int index = GetOptionArgumentPosition (value.c_str());
1616 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001617 {
Chris Lattner24943d22010-06-08 16:52:24 +00001618 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00001619 if (value_type != optional_argument)
1620 new_args.AppendArgument (value.c_str());
1621 else
1622 {
1623 char buffer[255];
1624 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
1625 new_args.AppendArgument (buffer);
1626 }
1627
1628 }
Chris Lattner24943d22010-06-08 16:52:24 +00001629 else if (index >= cmd_args.GetArgumentCount())
1630 {
1631 result.AppendErrorWithFormat
1632 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1633 index);
1634 result.SetStatus (eReturnStatusFailed);
1635 return;
1636 }
1637 else
1638 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001639 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
1640 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1641 if (strpos != std::string::npos)
1642 {
1643 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
1644 }
1645
1646 if (value_type != optional_argument)
1647 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
1648 else
1649 {
1650 char buffer[255];
1651 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
1652 cmd_args.GetArgumentAtIndex (index));
1653 new_args.AppendArgument (buffer);
1654 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001655 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001656 }
1657 }
1658 }
1659 }
1660
1661 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1662 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001663 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00001664 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1665 }
1666
1667 cmd_args.Clear();
1668 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1669 }
1670 else
1671 {
1672 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00001673 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
1674 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
1675 // input string.
1676 if (wants_raw_input)
1677 {
1678 cmd_args.Clear();
1679 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1680 }
Chris Lattner24943d22010-06-08 16:52:24 +00001681 return;
1682 }
1683
1684 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1685 return;
1686}
1687
1688
1689int
1690CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1691{
1692 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1693 // of zero.
1694
1695 char *cptr = (char *) in_string;
1696
1697 // Does it start with '%'
1698 if (cptr[0] == '%')
1699 {
1700 ++cptr;
1701
1702 // Is the rest of it entirely digits?
1703 if (isdigit (cptr[0]))
1704 {
1705 const char *start = cptr;
1706 while (isdigit (cptr[0]))
1707 ++cptr;
1708
1709 // We've gotten to the end of the digits; are we at the end of the string?
1710 if (cptr[0] == '\0')
1711 position = atoi (start);
1712 }
1713 }
1714
1715 return position;
1716}
1717
1718void
1719CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1720{
Greg Clayton887aa282010-10-11 01:05:37 +00001721 // Don't parse any .lldbinit files if we were asked not to
1722 if (m_skip_lldbinit_files)
1723 return;
1724
Chris Lattner24943d22010-06-08 16:52:24 +00001725 const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit";
Greg Clayton537a7a82010-10-20 20:54:39 +00001726 FileSpec init_file (init_file_path, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001727 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
1728 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
1729
1730 if (init_file.Exists())
1731 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001732 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
1733 bool stop_on_continue = true;
1734 bool stop_on_error = false;
1735 bool echo_commands = false;
1736 bool print_results = false;
1737
1738 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, result);
Chris Lattner24943d22010-06-08 16:52:24 +00001739 }
1740 else
1741 {
1742 // nothing to be done if the file doesn't exist
1743 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1744 }
1745}
1746
Greg Claytonb72d0f02011-04-12 05:54:46 +00001747PlatformSP
1748CommandInterpreter::GetPlatform (bool prefer_target_platform)
1749{
1750 PlatformSP platform_sp;
1751 if (prefer_target_platform && m_exe_ctx.target)
1752 platform_sp = m_exe_ctx.target->GetPlatform();
1753
1754 if (!platform_sp)
1755 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
1756 return platform_sp;
1757}
1758
Jim Ingham949d5ac2011-02-18 00:54:25 +00001759void
Jim Inghama4fede32011-03-11 01:51:49 +00001760CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001761 ExecutionContext *override_context,
1762 bool stop_on_continue,
1763 bool stop_on_error,
1764 bool echo_commands,
1765 bool print_results,
1766 CommandReturnObject &result)
1767{
1768 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00001769
1770 // If we are going to continue past a "continue" then we need to run the commands synchronously.
1771 // Make sure you reset this value anywhere you return from the function.
1772
1773 bool old_async_execution = m_debugger.GetAsyncExecution();
1774
1775 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
1776 // cause series of commands that change the context, then do an operation that relies on that context to fail.
1777
1778 if (override_context != NULL)
Greg Claytonb72d0f02011-04-12 05:54:46 +00001779 UpdateExecutionContext (override_context);
Jim Ingham949d5ac2011-02-18 00:54:25 +00001780
1781 if (!stop_on_continue)
1782 {
1783 m_debugger.SetAsyncExecution (false);
1784 }
1785
1786 for (int idx = 0; idx < num_lines; idx++)
1787 {
1788 const char *cmd = commands.GetStringAtIndex(idx);
1789 if (cmd[0] == '\0')
1790 continue;
1791
Jim Ingham949d5ac2011-02-18 00:54:25 +00001792 if (echo_commands)
1793 {
1794 result.AppendMessageWithFormat ("%s %s\n",
1795 GetPrompt(),
1796 cmd);
1797 }
1798
Greg Claytonaa378b12011-02-20 02:15:07 +00001799 CommandReturnObject tmp_result;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001800 bool success = HandleCommand(cmd, false, tmp_result, NULL);
1801
1802 if (print_results)
1803 {
1804 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00001805 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00001806 }
1807
1808 if (!success || !tmp_result.Succeeded())
1809 {
1810 if (stop_on_error)
1811 {
1812 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed.\n",
1813 idx, cmd);
1814 result.SetStatus (eReturnStatusFailed);
1815 m_debugger.SetAsyncExecution (old_async_execution);
1816 return;
1817 }
1818 else if (print_results)
1819 {
1820 result.AppendMessageWithFormat ("Command #%d '%s' failed with error: %s.\n",
1821 idx + 1,
1822 cmd,
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00001823 tmp_result.GetErrorData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00001824 }
1825 }
1826
Caroline Tice4a348082011-05-02 20:41:46 +00001827 if (result.GetImmediateOutputStream())
1828 result.GetImmediateOutputStream()->Flush();
1829
1830 if (result.GetImmediateErrorStream())
1831 result.GetImmediateErrorStream()->Flush();
1832
Jim Ingham949d5ac2011-02-18 00:54:25 +00001833 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
1834 // could be running (for instance in Breakpoint Commands.
1835 // So we check the return value to see if it is has running in it.
1836 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
1837 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
1838 {
1839 if (stop_on_continue)
1840 {
1841 // If we caused the target to proceed, and we're going to stop in that case, set the
1842 // status in our real result before returning. This is an error if the continue was not the
1843 // last command in the set of commands to be run.
1844 if (idx != num_lines - 1)
1845 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
1846 idx + 1, cmd);
1847 else
1848 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
1849
1850 result.SetStatus(tmp_result.GetStatus());
1851 m_debugger.SetAsyncExecution (old_async_execution);
1852
1853 return;
1854 }
1855 }
1856
1857 }
1858
1859 result.SetStatus (eReturnStatusSuccessFinishResult);
1860 m_debugger.SetAsyncExecution (old_async_execution);
1861
1862 return;
1863}
1864
1865void
1866CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
1867 ExecutionContext *context,
1868 bool stop_on_continue,
1869 bool stop_on_error,
1870 bool echo_command,
1871 bool print_result,
1872 CommandReturnObject &result)
1873{
1874 if (cmd_file.Exists())
1875 {
1876 bool success;
1877 StringList commands;
1878 success = commands.ReadFileLines(cmd_file);
1879 if (!success)
1880 {
1881 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
1882 result.SetStatus (eReturnStatusFailed);
1883 return;
1884 }
1885 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, result);
1886 }
1887 else
1888 {
1889 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
1890 cmd_file.GetFilename().AsCString());
1891 result.SetStatus (eReturnStatusFailed);
1892 return;
1893 }
1894}
1895
Chris Lattner24943d22010-06-08 16:52:24 +00001896ScriptInterpreter *
1897CommandInterpreter::GetScriptInterpreter ()
1898{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001899 if (m_script_interpreter_ap.get() != NULL)
1900 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00001901
Caroline Tice0aa2e552011-01-14 00:29:16 +00001902 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
1903 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00001904 {
Caroline Tice0aa2e552011-01-14 00:29:16 +00001905 case eScriptLanguageNone:
1906 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
1907 break;
1908 case eScriptLanguagePython:
1909 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
1910 break;
1911 default:
1912 break;
1913 };
1914
1915 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00001916}
1917
1918
1919
1920bool
1921CommandInterpreter::GetSynchronous ()
1922{
1923 return m_synchronous_execution;
1924}
1925
1926void
1927CommandInterpreter::SetSynchronous (bool value)
1928{
Johnny Chend7a4eb02010-10-14 01:22:03 +00001929 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00001930}
1931
1932void
1933CommandInterpreter::OutputFormattedHelpText (Stream &strm,
1934 const char *word_text,
1935 const char *separator,
1936 const char *help_text,
1937 uint32_t max_word_len)
1938{
Greg Clayton238c0a12010-09-18 01:14:36 +00001939 const uint32_t max_columns = m_debugger.GetTerminalWidth();
1940
Chris Lattner24943d22010-06-08 16:52:24 +00001941 int indent_size = max_word_len + strlen (separator) + 2;
1942
1943 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00001944
1945 StreamString text_strm;
1946 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
1947
1948 size_t len = text_strm.GetSize();
1949 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00001950 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00001951 {
1952 text_strm.EOL();
1953 len = text_strm.GetSize();
1954 }
Chris Lattner24943d22010-06-08 16:52:24 +00001955
1956 if (len < max_columns)
1957 {
1958 // Output it as a single line.
1959 strm.Printf ("%s", text);
1960 }
1961 else
1962 {
1963 // We need to break it up into multiple lines.
1964 bool first_line = true;
1965 int text_width;
1966 int start = 0;
1967 int end = start;
1968 int final_end = strlen (text);
1969 int sub_len;
1970
1971 while (end < final_end)
1972 {
1973 if (first_line)
1974 text_width = max_columns - 1;
1975 else
1976 text_width = max_columns - indent_size - 1;
1977
1978 // Don't start the 'text' on a space, since we're already outputting the indentation.
1979 if (!first_line)
1980 {
1981 while ((start < final_end) && (text[start] == ' '))
1982 start++;
1983 }
1984
1985 end = start + text_width;
1986 if (end > final_end)
1987 end = final_end;
1988 else
1989 {
1990 // If we're not at the end of the text, make sure we break the line on white space.
1991 while (end > start
1992 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
1993 end--;
1994 }
1995
1996 sub_len = end - start;
1997 if (start != 0)
1998 strm.EOL();
1999 if (!first_line)
2000 strm.Indent();
2001 else
2002 first_line = false;
2003 assert (start <= final_end);
2004 assert (start + sub_len <= final_end);
2005 if (sub_len > 0)
2006 strm.Write (text + start, sub_len);
2007 start = end + 1;
2008 }
2009 }
2010 strm.EOL();
2011 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00002012}
2013
2014void
2015CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
2016 StringList &commands_found, StringList &commands_help)
2017{
2018 CommandObject::CommandMap::const_iterator pos;
2019 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
2020 CommandObject *sub_cmd_obj;
2021
2022 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
2023 {
2024 const char * command_name = pos->first.c_str();
2025 sub_cmd_obj = pos->second.get();
2026 StreamString complete_command_name;
2027
2028 complete_command_name.Printf ("%s %s", prefix, command_name);
2029
Greg Clayton238c0a12010-09-18 01:14:36 +00002030 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002031 {
2032 commands_found.AppendString (complete_command_name.GetData());
2033 commands_help.AppendString (sub_cmd_obj->GetHelp());
2034 }
2035
2036 if (sub_cmd_obj->IsMultiwordObject())
2037 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
2038 commands_help);
2039 }
2040
2041}
2042
2043void
2044CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2045 StringList &commands_help)
2046{
2047 CommandObject::CommandMap::const_iterator pos;
2048
2049 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2050 {
2051 const char *command_name = pos->first.c_str();
2052 CommandObject *cmd_obj = pos->second.get();
2053
Greg Clayton238c0a12010-09-18 01:14:36 +00002054 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002055 {
2056 commands_found.AppendString (command_name);
2057 commands_help.AppendString (cmd_obj->GetHelp());
2058 }
2059
2060 if (cmd_obj->IsMultiwordObject())
2061 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
2062
2063 }
2064}
Greg Claytonb72d0f02011-04-12 05:54:46 +00002065
2066
2067void
2068CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2069{
2070 m_exe_ctx.Clear();
2071
2072 if (override_context != NULL)
2073 {
2074 m_exe_ctx.target = override_context->target;
2075 m_exe_ctx.process = override_context->process;
2076 m_exe_ctx.thread = override_context->thread;
2077 m_exe_ctx.frame = override_context->frame;
2078 }
2079 else
2080 {
2081 TargetSP target_sp (m_debugger.GetSelectedTarget());
2082 if (target_sp)
2083 {
2084 m_exe_ctx.target = target_sp.get();
2085 m_exe_ctx.process = target_sp->GetProcessSP().get();
2086 if (m_exe_ctx.process && m_exe_ctx.process->IsAlive() && !m_exe_ctx.process->IsRunning())
2087 {
2088 m_exe_ctx.thread = m_exe_ctx.process->GetThreadList().GetSelectedThread().get();
2089 if (m_exe_ctx.thread == NULL)
2090 {
2091 m_exe_ctx.thread = m_exe_ctx.process->GetThreadList().GetThreadAtIndex(0).get();
2092 // If we didn't have a selected thread, select one here.
2093 if (m_exe_ctx.thread != NULL)
2094 m_exe_ctx.process->GetThreadList().SetSelectedThreadByID(m_exe_ctx.thread->GetID());
2095 }
2096 if (m_exe_ctx.thread)
2097 {
2098 m_exe_ctx.frame = m_exe_ctx.thread->GetSelectedFrame().get();
2099 if (m_exe_ctx.frame == NULL)
2100 {
2101 m_exe_ctx.frame = m_exe_ctx.thread->GetStackFrameAtIndex (0).get();
2102 // If we didn't have a selected frame select one here.
2103 if (m_exe_ctx.frame != NULL)
2104 m_exe_ctx.thread->SetSelectedFrame(m_exe_ctx.frame);
2105 }
2106 }
2107 }
2108 }
2109 }
2110}
2111