blob: 465575694a55af8832c63786b8c5cc42c8a5df49 [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
792CommandInterpreter::StripFirstWord (std::string &command_string, std::string &word)
793{
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 {
801 end = command_string.find_first_of (white_space, start);
802 if (end != std::string::npos)
803 {
804 word = command_string.substr (start, end - start);
805 command_string = command_string.substr (end);
806 size_t pos = command_string.find_first_not_of (white_space);
807 if ((pos != 0) && (pos != std::string::npos))
808 command_string = command_string.substr (pos);
809 }
810 else
811 {
812 word = command_string.substr (start);
813 command_string.erase();
814 }
815
816 }
817 return true;
818}
819
820void
821CommandInterpreter::BuildAliasResult (const char *alias_name, std::string &raw_input_string, std::string &alias_result,
822 CommandObject *&alias_cmd_obj, CommandReturnObject &result)
823{
824 Args cmd_args (raw_input_string.c_str());
825 alias_cmd_obj = GetCommandObject (alias_name);
826 StreamString result_str;
827
828 if (alias_cmd_obj)
829 {
830 std::string alias_name_str = alias_name;
831 if ((cmd_args.GetArgumentCount() == 0)
832 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
833 cmd_args.Unshift (alias_name);
834
835 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
836 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
837
838 if (option_arg_vector_sp.get())
839 {
840 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
841
842 for (int i = 0; i < option_arg_vector->size(); ++i)
843 {
844 OptionArgPair option_pair = (*option_arg_vector)[i];
845 OptionArgValue value_pair = option_pair.second;
846 int value_type = value_pair.first;
847 std::string option = option_pair.first;
848 std::string value = value_pair.second;
849 if (option.compare ("<argument>") == 0)
850 result_str.Printf (" %s", value.c_str());
851 else
852 {
853 result_str.Printf (" %s", option.c_str());
854 if (value_type != optional_argument)
855 result_str.Printf (" ");
856 if (value.compare ("<no_argument>") != 0)
857 {
858 int index = GetOptionArgumentPosition (value.c_str());
859 if (index == 0)
860 result_str.Printf ("%s", value.c_str());
861 else if (index >= cmd_args.GetArgumentCount())
862 {
863
864 result.AppendErrorWithFormat
865 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
866 index);
867 result.SetStatus (eReturnStatusFailed);
868 return;
869 }
870 else
871 {
872 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
873 if (strpos != std::string::npos)
874 raw_input_string = raw_input_string.erase (strpos,
875 strlen (cmd_args.GetArgumentAtIndex (index)));
876 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
877 }
878 }
879 }
880 }
881 }
882
883 alias_result = result_str.GetData();
884 }
885}
886
887bool
888CommandInterpreter::HandleCommand (const char *command_line,
889 bool add_to_history,
890 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +0000891 ExecutionContext *override_context,
892 bool repeat_on_empty_command)
893
Caroline Ticee0da7a52010-12-09 22:52:49 +0000894{
Jim Ingham949d5ac2011-02-18 00:54:25 +0000895
Caroline Ticee0da7a52010-12-09 22:52:49 +0000896 bool done = false;
897 CommandObject *cmd_obj = NULL;
898 std::string next_word;
899 bool wants_raw_input = false;
900 std::string command_string (command_line);
901
902 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +0000903 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
904
905 // Make a scoped cleanup object that will clear the crash description string
906 // on exit of this function.
907 lldb_utility::CleanUp <const char *, void> crash_description_cleanup(NULL, Host::SetCrashDescription);
908
Caroline Ticee0da7a52010-12-09 22:52:49 +0000909 if (log)
910 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +0000911
Jim Inghamabab14b2010-11-04 23:08:45 +0000912 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
913
Greg Claytonb72d0f02011-04-12 05:54:46 +0000914 UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +0000915
Jim Ingham949d5ac2011-02-18 00:54:25 +0000916 bool empty_command = false;
917 bool comment_command = false;
918 if (command_string.empty())
919 empty_command = true;
920 else
Chris Lattner24943d22010-06-08 16:52:24 +0000921 {
Jim Ingham949d5ac2011-02-18 00:54:25 +0000922 const char *k_space_characters = "\t\n\v\f\r ";
923
924 size_t non_space = command_string.find_first_not_of (k_space_characters);
925 // Check for empty line or comment line (lines whose first
926 // non-space character is the comment character for this interpreter)
927 if (non_space == std::string::npos)
928 empty_command = true;
929 else if (command_string[non_space] == m_comment_char)
930 comment_command = true;
931 }
932
933 if (empty_command)
934 {
935 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +0000936 {
Jim Ingham949d5ac2011-02-18 00:54:25 +0000937 if (m_command_history.empty())
938 {
939 result.AppendError ("empty command");
940 result.SetStatus(eReturnStatusFailed);
941 return false;
942 }
943 else
944 {
945 command_line = m_repeat_command.c_str();
946 command_string = command_line;
947 if (m_repeat_command.empty())
948 {
949 result.AppendErrorWithFormat("No auto repeat.\n");
950 result.SetStatus (eReturnStatusFailed);
951 return false;
952 }
953 }
954 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000955 }
956 else
957 {
Jim Ingham949d5ac2011-02-18 00:54:25 +0000958 result.SetStatus (eReturnStatusSuccessFinishNoResult);
959 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000960 }
Jim Ingham949d5ac2011-02-18 00:54:25 +0000961 }
962 else if (comment_command)
963 {
964 result.SetStatus (eReturnStatusSuccessFinishNoResult);
965 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000966 }
967
Caroline Ticee0da7a52010-12-09 22:52:49 +0000968 // Phase 1.
969
970 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
971 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
972 // the user could have specified an alias, and in translating the alias there may also be command options and/or
973 // even data (including raw text strings) that need to be found and inserted into the command line as part of
974 // 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 +0000975 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +0000976 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +0000977
Caroline Ticee0da7a52010-12-09 22:52:49 +0000978 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000979 size_t actual_cmd_name_len = 0;
Caroline Ticee0da7a52010-12-09 22:52:49 +0000980 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +0000981 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000982 StripFirstWord (command_string, next_word);
983 if (!cmd_obj && AliasExists (next_word.c_str()))
Chris Lattner24943d22010-06-08 16:52:24 +0000984 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000985 std::string alias_result;
986 BuildAliasResult (next_word.c_str(), command_string, alias_result, cmd_obj, result);
987 revised_command_line.Printf ("%s", alias_result.c_str());
988 if (cmd_obj)
Caroline Tice56d2fc42010-12-14 18:51:39 +0000989 {
Caroline Ticee0da7a52010-12-09 22:52:49 +0000990 wants_raw_input = cmd_obj->WantsRawCommandString ();
Caroline Tice56d2fc42010-12-14 18:51:39 +0000991 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
992 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000993 }
994 else if (!cmd_obj)
995 {
996 cmd_obj = GetCommandObject (next_word.c_str());
997 if (cmd_obj)
Chris Lattner24943d22010-06-08 16:52:24 +0000998 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +0000999 actual_cmd_name_len += next_word.length();
Caroline Ticee0da7a52010-12-09 22:52:49 +00001000 revised_command_line.Printf ("%s", next_word.c_str());
1001 wants_raw_input = cmd_obj->WantsRawCommandString ();
Chris Lattner24943d22010-06-08 16:52:24 +00001002 }
1003 else
1004 {
Caroline Ticee0da7a52010-12-09 22:52:49 +00001005 revised_command_line.Printf ("%s", next_word.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001006 }
1007 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001008 else if (cmd_obj->IsMultiwordObject ())
1009 {
1010 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
1011 if (sub_cmd_obj)
1012 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001013 actual_cmd_name_len += next_word.length() + 1;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001014 revised_command_line.Printf (" %s", next_word.c_str());
1015 cmd_obj = sub_cmd_obj;
1016 wants_raw_input = cmd_obj->WantsRawCommandString ();
1017 }
1018 else
1019 {
1020 revised_command_line.Printf (" %s", next_word.c_str());
1021 done = true;
1022 }
1023 }
1024 else
1025 {
1026 revised_command_line.Printf (" %s", next_word.c_str());
1027 done = true;
1028 }
1029
1030 if (cmd_obj == NULL)
1031 {
1032 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1033 result.SetStatus (eReturnStatusFailed);
1034 return false;
1035 }
1036
1037 next_word.erase ();
1038 if (command_string.length() == 0)
1039 done = true;
1040
Chris Lattner24943d22010-06-08 16:52:24 +00001041 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001042
1043 if (command_string.size() > 0)
1044 revised_command_line.Printf (" %s", command_string.c_str());
1045
1046 // End of Phase 1.
1047 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1048 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1049 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1050 // wants_raw_input specifies whether the Execute method expects raw input or not.
1051
1052
1053 if (log)
1054 {
1055 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1056 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1057 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1058 }
1059
1060 // Phase 2.
1061 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1062 // CommandObject, with the appropriate arguments.
1063
1064 if (cmd_obj != NULL)
1065 {
1066 if (add_to_history)
1067 {
1068 Args command_args (revised_command_line.GetData());
1069 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1070 if (repeat_command != NULL)
1071 m_repeat_command.assign(repeat_command);
1072 else
1073 m_repeat_command.assign(command_line);
1074
1075 m_command_history.push_back (command_line);
1076 }
1077
1078 command_string = revised_command_line.GetData();
1079 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001080 std::string remainder;
1081 if (actual_cmd_name_len < command_string.length())
1082 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1083 // than cmd_obj->GetCommandName(), because name completion
1084 // allows users to enter short versions of the names,
1085 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +00001086
1087 // Remove any initial spaces
1088 std::string white_space (" \t\v");
1089 size_t pos = remainder.find_first_not_of (white_space);
1090 if (pos != 0 && pos != std::string::npos)
Greg Clayton91c9dcf2011-04-22 20:58:45 +00001091 remainder.erase(0, pos);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001092
1093 if (log)
1094 log->Printf ("HandleCommand, command line after removing command name(s): '%s'\n", remainder.c_str());
1095
1096
1097 if (wants_raw_input)
1098 cmd_obj->ExecuteRawCommandString (remainder.c_str(), result);
1099 else
1100 {
1101 Args cmd_args (remainder.c_str());
1102 cmd_obj->ExecuteWithOptions (cmd_args, result);
1103 }
1104 }
1105 else
1106 {
1107 // We didn't find the first command object, so complete the first argument.
1108 Args command_args (revised_command_line.GetData());
1109 StringList matches;
1110 int num_matches;
1111 int cursor_index = 0;
1112 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1113 bool word_complete;
1114 num_matches = HandleCompletionMatches (command_args,
1115 cursor_index,
1116 cursor_char_position,
1117 0,
1118 -1,
1119 word_complete,
1120 matches);
1121
1122 if (num_matches > 0)
1123 {
1124 std::string error_msg;
1125 error_msg.assign ("ambiguous command '");
1126 error_msg.append(command_args.GetArgumentAtIndex(0));
1127 error_msg.append ("'.");
1128
1129 error_msg.append (" Possible completions:");
1130 for (int i = 0; i < num_matches; i++)
1131 {
1132 error_msg.append ("\n\t");
1133 error_msg.append (matches.GetStringAtIndex (i));
1134 }
1135 error_msg.append ("\n");
1136 result.AppendRawError (error_msg.c_str(), error_msg.size());
1137 }
1138 else
1139 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1140
1141 result.SetStatus (eReturnStatusFailed);
1142 }
1143
Chris Lattner24943d22010-06-08 16:52:24 +00001144 return result.Succeeded();
1145}
1146
1147int
1148CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1149 int &cursor_index,
1150 int &cursor_char_position,
1151 int match_start_point,
1152 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001153 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001154 StringList &matches)
1155{
1156 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001157 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001158
1159 // For any of the command completions a unique match will be a complete word.
1160 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001161
1162 if (cursor_index == -1)
1163 {
1164 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001165 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001166 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1167 }
1168 else if (cursor_index == 0)
1169 {
1170 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001171 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001172 num_command_matches = matches.GetSize();
1173
1174 if (num_command_matches == 1
1175 && cmd_obj && cmd_obj->IsMultiwordObject()
1176 && matches.GetStringAtIndex(0) != NULL
1177 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1178 {
1179 look_for_subcommand = true;
1180 num_command_matches = 0;
1181 matches.DeleteStringAtIndex(0);
1182 parsed_line.AppendArgument ("");
1183 cursor_index++;
1184 cursor_char_position = 0;
1185 }
1186 }
1187
1188 if (cursor_index > 0 || look_for_subcommand)
1189 {
1190 // We are completing further on into a commands arguments, so find the command and tell it
1191 // to complete the command.
1192 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001193 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001194 if (command_object == NULL)
1195 {
1196 return 0;
1197 }
1198 else
1199 {
1200 parsed_line.Shift();
1201 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001202 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001203 cursor_index,
1204 cursor_char_position,
1205 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001206 max_return_elements,
1207 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001208 matches);
1209 }
1210 }
1211
1212 return num_command_matches;
1213
1214}
1215
1216int
1217CommandInterpreter::HandleCompletion (const char *current_line,
1218 const char *cursor,
1219 const char *last_char,
1220 int match_start_point,
1221 int max_return_elements,
1222 StringList &matches)
1223{
1224 // We parse the argument up to the cursor, so the last argument in parsed_line is
1225 // the one containing the cursor, and the cursor is after the last character.
1226
1227 Args parsed_line(current_line, last_char - current_line);
1228 Args partial_parsed_line(current_line, cursor - current_line);
1229
1230 int num_args = partial_parsed_line.GetArgumentCount();
1231 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1232 int cursor_char_position;
1233
1234 if (cursor_index == -1)
1235 cursor_char_position = 0;
1236 else
1237 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001238
1239 if (cursor > current_line && cursor[-1] == ' ')
1240 {
1241 // We are just after a space. If we are in an argument, then we will continue
1242 // parsing, but if we are between arguments, then we have to complete whatever the next
1243 // element would be.
1244 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1245 // protected by a quote) then the space will also be in the parsed argument...
1246
1247 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1248 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1249 {
1250 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1251 cursor_index++;
1252 cursor_char_position = 0;
1253 }
1254 }
Chris Lattner24943d22010-06-08 16:52:24 +00001255
1256 int num_command_matches;
1257
1258 matches.Clear();
1259
1260 // Only max_return_elements == -1 is supported at present:
1261 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001262 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001263 num_command_matches = HandleCompletionMatches (parsed_line,
1264 cursor_index,
1265 cursor_char_position,
1266 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001267 max_return_elements,
1268 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001269 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001270
1271 if (num_command_matches <= 0)
1272 return num_command_matches;
1273
1274 if (num_args == 0)
1275 {
1276 // If we got an empty string, insert nothing.
1277 matches.InsertStringAtIndex(0, "");
1278 }
1279 else
1280 {
1281 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1282 // put an empty string in element 0.
1283 std::string command_partial_str;
1284 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001285 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1286 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001287
1288 std::string common_prefix;
1289 matches.LongestCommonPrefix (common_prefix);
1290 int partial_name_len = command_partial_str.size();
1291
1292 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001293 // Only do this if the completer told us this was a complete word, however...
1294 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001295 {
1296 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1297 if (quote_char != '\0')
1298 common_prefix.push_back(quote_char);
1299
1300 common_prefix.push_back(' ');
1301 }
1302 common_prefix.erase (0, partial_name_len);
1303 matches.InsertStringAtIndex(0, common_prefix.c_str());
1304 }
1305 return num_command_matches;
1306}
1307
Chris Lattner24943d22010-06-08 16:52:24 +00001308
1309CommandInterpreter::~CommandInterpreter ()
1310{
1311}
1312
1313const char *
1314CommandInterpreter::GetPrompt ()
1315{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001316 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001317}
1318
1319void
1320CommandInterpreter::SetPrompt (const char *new_prompt)
1321{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001322 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001323}
1324
Jim Ingham5e16ef52010-10-04 19:49:29 +00001325size_t
Greg Clayton58928562011-02-09 01:08:52 +00001326CommandInterpreter::GetConfirmationInputReaderCallback
1327(
1328 void *baton,
1329 InputReader &reader,
1330 lldb::InputReaderAction action,
1331 const char *bytes,
1332 size_t bytes_len
1333)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001334{
Greg Clayton58928562011-02-09 01:08:52 +00001335 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001336 bool *response_ptr = (bool *) baton;
1337
1338 switch (action)
1339 {
1340 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001341 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001342 {
1343 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001344 {
Greg Clayton58928562011-02-09 01:08:52 +00001345 out_file.Printf ("%s", reader.GetPrompt());
1346 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001347 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001348 }
1349 break;
1350
1351 case eInputReaderDeactivate:
1352 break;
1353
1354 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001355 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001356 {
Greg Clayton58928562011-02-09 01:08:52 +00001357 out_file.Printf ("%s", reader.GetPrompt());
1358 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001359 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001360 break;
Caroline Tice4a348082011-05-02 20:41:46 +00001361
1362 case eInputReaderAsynchronousOutputWritten:
1363 break;
1364
Jim Ingham5e16ef52010-10-04 19:49:29 +00001365 case eInputReaderGotToken:
1366 if (bytes_len == 0)
1367 {
1368 reader.SetIsDone(true);
1369 }
1370 else if (bytes[0] == 'y')
1371 {
1372 *response_ptr = true;
1373 reader.SetIsDone(true);
1374 }
1375 else if (bytes[0] == 'n')
1376 {
1377 *response_ptr = false;
1378 reader.SetIsDone(true);
1379 }
1380 else
1381 {
Greg Clayton58928562011-02-09 01:08:52 +00001382 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001383 {
Greg Clayton58928562011-02-09 01:08:52 +00001384 out_file.Printf ("Please answer \"y\" or \"n\"\n%s", reader.GetPrompt());
1385 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001386 }
1387 }
1388 break;
1389
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001390 case eInputReaderInterrupt:
1391 case eInputReaderEndOfFile:
1392 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1393 reader.SetIsDone (true);
1394 break;
1395
Jim Ingham5e16ef52010-10-04 19:49:29 +00001396 case eInputReaderDone:
1397 break;
1398 }
1399
1400 return bytes_len;
1401
1402}
1403
1404bool
1405CommandInterpreter::Confirm (const char *message, bool default_answer)
1406{
Jim Ingham93057472010-10-04 22:44:14 +00001407 // Check AutoConfirm first:
1408 if (m_debugger.GetAutoConfirm())
1409 return default_answer;
1410
Jim Ingham5e16ef52010-10-04 19:49:29 +00001411 InputReaderSP reader_sp (new InputReader(GetDebugger()));
1412 bool response = default_answer;
1413 if (reader_sp)
1414 {
1415 std::string prompt(message);
1416 prompt.append(": [");
1417 if (default_answer)
1418 prompt.append ("Y/n] ");
1419 else
1420 prompt.append ("y/N] ");
1421
1422 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1423 &response, // baton
1424 eInputReaderGranularityLine, // token size, to pass to callback function
1425 NULL, // end token
1426 prompt.c_str(), // prompt
1427 true)); // echo input
1428 if (err.Success())
1429 {
1430 GetDebugger().PushInputReader (reader_sp);
1431 }
1432 reader_sp->WaitOnReaderIsDone();
1433 }
1434 return response;
1435}
1436
1437
Chris Lattner24943d22010-06-08 16:52:24 +00001438void
1439CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1440{
Jim Inghamd40f8a62010-07-06 22:46:59 +00001441 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001442
1443 if (cmd_obj_sp != NULL)
1444 {
1445 CommandObject *cmd_obj = cmd_obj_sp.get();
1446 if (cmd_obj->IsCrossRefObject ())
1447 cmd_obj->AddObject (object_type);
1448 }
1449}
1450
Chris Lattner24943d22010-06-08 16:52:24 +00001451OptionArgVectorSP
1452CommandInterpreter::GetAliasOptions (const char *alias_name)
1453{
1454 OptionArgMap::iterator pos;
1455 OptionArgVectorSP ret_val;
1456
1457 std::string alias (alias_name);
1458
1459 if (HasAliasOptions())
1460 {
1461 pos = m_alias_options.find (alias);
1462 if (pos != m_alias_options.end())
1463 ret_val = pos->second;
1464 }
1465
1466 return ret_val;
1467}
1468
1469void
1470CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1471{
1472 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1473 if (pos != m_alias_options.end())
1474 {
1475 m_alias_options.erase (pos);
1476 }
1477}
1478
1479void
1480CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1481{
1482 m_alias_options[alias_name] = option_arg_vector_sp;
1483}
1484
1485bool
1486CommandInterpreter::HasCommands ()
1487{
1488 return (!m_command_dict.empty());
1489}
1490
1491bool
1492CommandInterpreter::HasAliases ()
1493{
1494 return (!m_alias_dict.empty());
1495}
1496
1497bool
1498CommandInterpreter::HasUserCommands ()
1499{
1500 return (!m_user_dict.empty());
1501}
1502
1503bool
1504CommandInterpreter::HasAliasOptions ()
1505{
1506 return (!m_alias_options.empty());
1507}
1508
Chris Lattner24943d22010-06-08 16:52:24 +00001509void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001510CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
1511 const char *alias_name,
1512 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00001513 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001514 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00001515{
1516 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00001517
1518 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00001519
Caroline Tice44c841d2010-12-07 19:58:26 +00001520 // Make sure that the alias name is the 0th element in cmd_args
1521 std::string alias_name_str = alias_name;
1522 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1523 cmd_args.Unshift (alias_name);
1524
1525 Args new_args (alias_cmd_obj->GetCommandName());
1526 if (new_args.GetArgumentCount() == 2)
1527 new_args.Shift();
1528
Chris Lattner24943d22010-06-08 16:52:24 +00001529 if (option_arg_vector_sp.get())
1530 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001531 if (wants_raw_input)
1532 {
1533 // We have a command that both has command options and takes raw input. Make *sure* it has a
1534 // " -- " in the right place in the raw_input_string.
1535 size_t pos = raw_input_string.find(" -- ");
1536 if (pos == std::string::npos)
1537 {
1538 // None found; assume it goes at the beginning of the raw input string
1539 raw_input_string.insert (0, " -- ");
1540 }
1541 }
Chris Lattner24943d22010-06-08 16:52:24 +00001542
1543 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1544 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001545 std::vector<bool> used (old_size + 1, false);
1546
1547 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001548
1549 for (int i = 0; i < option_arg_vector->size(); ++i)
1550 {
1551 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00001552 OptionArgValue value_pair = option_pair.second;
1553 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00001554 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00001555 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00001556 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001557 {
1558 if (!wants_raw_input
1559 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
1560 new_args.AppendArgument (value.c_str());
1561 }
Chris Lattner24943d22010-06-08 16:52:24 +00001562 else
1563 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001564 if (value_type != optional_argument)
1565 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001566 if (value.compare ("<no-argument>") != 0)
1567 {
1568 int index = GetOptionArgumentPosition (value.c_str());
1569 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001570 {
Chris Lattner24943d22010-06-08 16:52:24 +00001571 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00001572 if (value_type != optional_argument)
1573 new_args.AppendArgument (value.c_str());
1574 else
1575 {
1576 char buffer[255];
1577 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
1578 new_args.AppendArgument (buffer);
1579 }
1580
1581 }
Chris Lattner24943d22010-06-08 16:52:24 +00001582 else if (index >= cmd_args.GetArgumentCount())
1583 {
1584 result.AppendErrorWithFormat
1585 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1586 index);
1587 result.SetStatus (eReturnStatusFailed);
1588 return;
1589 }
1590 else
1591 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001592 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
1593 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1594 if (strpos != std::string::npos)
1595 {
1596 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
1597 }
1598
1599 if (value_type != optional_argument)
1600 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
1601 else
1602 {
1603 char buffer[255];
1604 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
1605 cmd_args.GetArgumentAtIndex (index));
1606 new_args.AppendArgument (buffer);
1607 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001608 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001609 }
1610 }
1611 }
1612 }
1613
1614 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1615 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001616 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00001617 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1618 }
1619
1620 cmd_args.Clear();
1621 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1622 }
1623 else
1624 {
1625 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00001626 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
1627 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
1628 // input string.
1629 if (wants_raw_input)
1630 {
1631 cmd_args.Clear();
1632 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1633 }
Chris Lattner24943d22010-06-08 16:52:24 +00001634 return;
1635 }
1636
1637 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1638 return;
1639}
1640
1641
1642int
1643CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1644{
1645 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1646 // of zero.
1647
1648 char *cptr = (char *) in_string;
1649
1650 // Does it start with '%'
1651 if (cptr[0] == '%')
1652 {
1653 ++cptr;
1654
1655 // Is the rest of it entirely digits?
1656 if (isdigit (cptr[0]))
1657 {
1658 const char *start = cptr;
1659 while (isdigit (cptr[0]))
1660 ++cptr;
1661
1662 // We've gotten to the end of the digits; are we at the end of the string?
1663 if (cptr[0] == '\0')
1664 position = atoi (start);
1665 }
1666 }
1667
1668 return position;
1669}
1670
1671void
1672CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1673{
Greg Clayton887aa282010-10-11 01:05:37 +00001674 // Don't parse any .lldbinit files if we were asked not to
1675 if (m_skip_lldbinit_files)
1676 return;
1677
Chris Lattner24943d22010-06-08 16:52:24 +00001678 const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit";
Greg Clayton537a7a82010-10-20 20:54:39 +00001679 FileSpec init_file (init_file_path, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001680 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
1681 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
1682
1683 if (init_file.Exists())
1684 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001685 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
1686 bool stop_on_continue = true;
1687 bool stop_on_error = false;
1688 bool echo_commands = false;
1689 bool print_results = false;
1690
1691 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, result);
Chris Lattner24943d22010-06-08 16:52:24 +00001692 }
1693 else
1694 {
1695 // nothing to be done if the file doesn't exist
1696 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1697 }
1698}
1699
Greg Claytonb72d0f02011-04-12 05:54:46 +00001700PlatformSP
1701CommandInterpreter::GetPlatform (bool prefer_target_platform)
1702{
1703 PlatformSP platform_sp;
1704 if (prefer_target_platform && m_exe_ctx.target)
1705 platform_sp = m_exe_ctx.target->GetPlatform();
1706
1707 if (!platform_sp)
1708 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
1709 return platform_sp;
1710}
1711
Jim Ingham949d5ac2011-02-18 00:54:25 +00001712void
Jim Inghama4fede32011-03-11 01:51:49 +00001713CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001714 ExecutionContext *override_context,
1715 bool stop_on_continue,
1716 bool stop_on_error,
1717 bool echo_commands,
1718 bool print_results,
1719 CommandReturnObject &result)
1720{
1721 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00001722
1723 // If we are going to continue past a "continue" then we need to run the commands synchronously.
1724 // Make sure you reset this value anywhere you return from the function.
1725
1726 bool old_async_execution = m_debugger.GetAsyncExecution();
1727
1728 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
1729 // cause series of commands that change the context, then do an operation that relies on that context to fail.
1730
1731 if (override_context != NULL)
Greg Claytonb72d0f02011-04-12 05:54:46 +00001732 UpdateExecutionContext (override_context);
Jim Ingham949d5ac2011-02-18 00:54:25 +00001733
1734 if (!stop_on_continue)
1735 {
1736 m_debugger.SetAsyncExecution (false);
1737 }
1738
1739 for (int idx = 0; idx < num_lines; idx++)
1740 {
1741 const char *cmd = commands.GetStringAtIndex(idx);
1742 if (cmd[0] == '\0')
1743 continue;
1744
Jim Ingham949d5ac2011-02-18 00:54:25 +00001745 if (echo_commands)
1746 {
1747 result.AppendMessageWithFormat ("%s %s\n",
1748 GetPrompt(),
1749 cmd);
1750 }
1751
Greg Claytonaa378b12011-02-20 02:15:07 +00001752 CommandReturnObject tmp_result;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001753 bool success = HandleCommand(cmd, false, tmp_result, NULL);
1754
1755 if (print_results)
1756 {
1757 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00001758 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00001759 }
1760
1761 if (!success || !tmp_result.Succeeded())
1762 {
1763 if (stop_on_error)
1764 {
1765 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed.\n",
1766 idx, cmd);
1767 result.SetStatus (eReturnStatusFailed);
1768 m_debugger.SetAsyncExecution (old_async_execution);
1769 return;
1770 }
1771 else if (print_results)
1772 {
1773 result.AppendMessageWithFormat ("Command #%d '%s' failed with error: %s.\n",
1774 idx + 1,
1775 cmd,
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00001776 tmp_result.GetErrorData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00001777 }
1778 }
1779
Caroline Tice4a348082011-05-02 20:41:46 +00001780 if (result.GetImmediateOutputStream())
1781 result.GetImmediateOutputStream()->Flush();
1782
1783 if (result.GetImmediateErrorStream())
1784 result.GetImmediateErrorStream()->Flush();
1785
Jim Ingham949d5ac2011-02-18 00:54:25 +00001786 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
1787 // could be running (for instance in Breakpoint Commands.
1788 // So we check the return value to see if it is has running in it.
1789 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
1790 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
1791 {
1792 if (stop_on_continue)
1793 {
1794 // If we caused the target to proceed, and we're going to stop in that case, set the
1795 // status in our real result before returning. This is an error if the continue was not the
1796 // last command in the set of commands to be run.
1797 if (idx != num_lines - 1)
1798 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
1799 idx + 1, cmd);
1800 else
1801 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
1802
1803 result.SetStatus(tmp_result.GetStatus());
1804 m_debugger.SetAsyncExecution (old_async_execution);
1805
1806 return;
1807 }
1808 }
1809
1810 }
1811
1812 result.SetStatus (eReturnStatusSuccessFinishResult);
1813 m_debugger.SetAsyncExecution (old_async_execution);
1814
1815 return;
1816}
1817
1818void
1819CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
1820 ExecutionContext *context,
1821 bool stop_on_continue,
1822 bool stop_on_error,
1823 bool echo_command,
1824 bool print_result,
1825 CommandReturnObject &result)
1826{
1827 if (cmd_file.Exists())
1828 {
1829 bool success;
1830 StringList commands;
1831 success = commands.ReadFileLines(cmd_file);
1832 if (!success)
1833 {
1834 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
1835 result.SetStatus (eReturnStatusFailed);
1836 return;
1837 }
1838 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, result);
1839 }
1840 else
1841 {
1842 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
1843 cmd_file.GetFilename().AsCString());
1844 result.SetStatus (eReturnStatusFailed);
1845 return;
1846 }
1847}
1848
Chris Lattner24943d22010-06-08 16:52:24 +00001849ScriptInterpreter *
1850CommandInterpreter::GetScriptInterpreter ()
1851{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001852 if (m_script_interpreter_ap.get() != NULL)
1853 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00001854
Caroline Tice0aa2e552011-01-14 00:29:16 +00001855 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
1856 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00001857 {
Caroline Tice0aa2e552011-01-14 00:29:16 +00001858 case eScriptLanguageNone:
1859 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
1860 break;
1861 case eScriptLanguagePython:
1862 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
1863 break;
1864 default:
1865 break;
1866 };
1867
1868 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00001869}
1870
1871
1872
1873bool
1874CommandInterpreter::GetSynchronous ()
1875{
1876 return m_synchronous_execution;
1877}
1878
1879void
1880CommandInterpreter::SetSynchronous (bool value)
1881{
Johnny Chend7a4eb02010-10-14 01:22:03 +00001882 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00001883}
1884
1885void
1886CommandInterpreter::OutputFormattedHelpText (Stream &strm,
1887 const char *word_text,
1888 const char *separator,
1889 const char *help_text,
1890 uint32_t max_word_len)
1891{
Greg Clayton238c0a12010-09-18 01:14:36 +00001892 const uint32_t max_columns = m_debugger.GetTerminalWidth();
1893
Chris Lattner24943d22010-06-08 16:52:24 +00001894 int indent_size = max_word_len + strlen (separator) + 2;
1895
1896 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00001897
1898 StreamString text_strm;
1899 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
1900
1901 size_t len = text_strm.GetSize();
1902 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00001903 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00001904 {
1905 text_strm.EOL();
1906 len = text_strm.GetSize();
1907 }
Chris Lattner24943d22010-06-08 16:52:24 +00001908
1909 if (len < max_columns)
1910 {
1911 // Output it as a single line.
1912 strm.Printf ("%s", text);
1913 }
1914 else
1915 {
1916 // We need to break it up into multiple lines.
1917 bool first_line = true;
1918 int text_width;
1919 int start = 0;
1920 int end = start;
1921 int final_end = strlen (text);
1922 int sub_len;
1923
1924 while (end < final_end)
1925 {
1926 if (first_line)
1927 text_width = max_columns - 1;
1928 else
1929 text_width = max_columns - indent_size - 1;
1930
1931 // Don't start the 'text' on a space, since we're already outputting the indentation.
1932 if (!first_line)
1933 {
1934 while ((start < final_end) && (text[start] == ' '))
1935 start++;
1936 }
1937
1938 end = start + text_width;
1939 if (end > final_end)
1940 end = final_end;
1941 else
1942 {
1943 // If we're not at the end of the text, make sure we break the line on white space.
1944 while (end > start
1945 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
1946 end--;
1947 }
1948
1949 sub_len = end - start;
1950 if (start != 0)
1951 strm.EOL();
1952 if (!first_line)
1953 strm.Indent();
1954 else
1955 first_line = false;
1956 assert (start <= final_end);
1957 assert (start + sub_len <= final_end);
1958 if (sub_len > 0)
1959 strm.Write (text + start, sub_len);
1960 start = end + 1;
1961 }
1962 }
1963 strm.EOL();
1964 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001965}
1966
1967void
1968CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
1969 StringList &commands_found, StringList &commands_help)
1970{
1971 CommandObject::CommandMap::const_iterator pos;
1972 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
1973 CommandObject *sub_cmd_obj;
1974
1975 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
1976 {
1977 const char * command_name = pos->first.c_str();
1978 sub_cmd_obj = pos->second.get();
1979 StreamString complete_command_name;
1980
1981 complete_command_name.Printf ("%s %s", prefix, command_name);
1982
Greg Clayton238c0a12010-09-18 01:14:36 +00001983 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00001984 {
1985 commands_found.AppendString (complete_command_name.GetData());
1986 commands_help.AppendString (sub_cmd_obj->GetHelp());
1987 }
1988
1989 if (sub_cmd_obj->IsMultiwordObject())
1990 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
1991 commands_help);
1992 }
1993
1994}
1995
1996void
1997CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
1998 StringList &commands_help)
1999{
2000 CommandObject::CommandMap::const_iterator pos;
2001
2002 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2003 {
2004 const char *command_name = pos->first.c_str();
2005 CommandObject *cmd_obj = pos->second.get();
2006
Greg Clayton238c0a12010-09-18 01:14:36 +00002007 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002008 {
2009 commands_found.AppendString (command_name);
2010 commands_help.AppendString (cmd_obj->GetHelp());
2011 }
2012
2013 if (cmd_obj->IsMultiwordObject())
2014 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
2015
2016 }
2017}
Greg Claytonb72d0f02011-04-12 05:54:46 +00002018
2019
2020void
2021CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2022{
2023 m_exe_ctx.Clear();
2024
2025 if (override_context != NULL)
2026 {
2027 m_exe_ctx.target = override_context->target;
2028 m_exe_ctx.process = override_context->process;
2029 m_exe_ctx.thread = override_context->thread;
2030 m_exe_ctx.frame = override_context->frame;
2031 }
2032 else
2033 {
2034 TargetSP target_sp (m_debugger.GetSelectedTarget());
2035 if (target_sp)
2036 {
2037 m_exe_ctx.target = target_sp.get();
2038 m_exe_ctx.process = target_sp->GetProcessSP().get();
2039 if (m_exe_ctx.process && m_exe_ctx.process->IsAlive() && !m_exe_ctx.process->IsRunning())
2040 {
2041 m_exe_ctx.thread = m_exe_ctx.process->GetThreadList().GetSelectedThread().get();
2042 if (m_exe_ctx.thread == NULL)
2043 {
2044 m_exe_ctx.thread = m_exe_ctx.process->GetThreadList().GetThreadAtIndex(0).get();
2045 // If we didn't have a selected thread, select one here.
2046 if (m_exe_ctx.thread != NULL)
2047 m_exe_ctx.process->GetThreadList().SetSelectedThreadByID(m_exe_ctx.thread->GetID());
2048 }
2049 if (m_exe_ctx.thread)
2050 {
2051 m_exe_ctx.frame = m_exe_ctx.thread->GetSelectedFrame().get();
2052 if (m_exe_ctx.frame == NULL)
2053 {
2054 m_exe_ctx.frame = m_exe_ctx.thread->GetStackFrameAtIndex (0).get();
2055 // If we didn't have a selected frame select one here.
2056 if (m_exe_ctx.frame != NULL)
2057 m_exe_ctx.thread->SetSelectedFrame(m_exe_ctx.frame);
2058 }
2059 }
2060 }
2061 }
2062 }
2063}
2064