blob: 38c3d7e21073cba44dce6ff7fdb3ca5e6198b5c7 [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
Greg Clayton5c28dd12011-06-23 17:59:56 +000016#include "CommandObjectScript.h"
Peter Collingbourne921fac02011-06-23 20:37:26 +000017#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Greg Clayton5c28dd12011-06-23 17:59:56 +000018
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000019#include "../Commands/CommandObjectApropos.h"
20#include "../Commands/CommandObjectArgs.h"
21#include "../Commands/CommandObjectBreakpoint.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000022#include "../Commands/CommandObjectDisassemble.h"
23#include "../Commands/CommandObjectExpression.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000024#include "../Commands/CommandObjectFrame.h"
25#include "../Commands/CommandObjectHelp.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000026#include "../Commands/CommandObjectLog.h"
27#include "../Commands/CommandObjectMemory.h"
Greg Claytonb1888f22011-03-19 01:12:21 +000028#include "../Commands/CommandObjectPlatform.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000029#include "../Commands/CommandObjectProcess.h"
30#include "../Commands/CommandObjectQuit.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000031#include "../Commands/CommandObjectRegister.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000032#include "../Commands/CommandObjectSettings.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000033#include "../Commands/CommandObjectSource.h"
Jim Ingham767af882010-07-07 03:36:20 +000034#include "../Commands/CommandObjectCommands.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000035#include "../Commands/CommandObjectSyntax.h"
36#include "../Commands/CommandObjectTarget.h"
37#include "../Commands/CommandObjectThread.h"
Greg Clayton5c28dd12011-06-23 17:59:56 +000038#include "../Commands/CommandObjectType.h"
Johnny Chen902e0182010-12-23 20:21:44 +000039#include "../Commands/CommandObjectVersion.h"
Johnny Chen01acfa72011-09-22 18:04:58 +000040#include "../Commands/CommandObjectWatchpoint.h"
Chris Lattner24943d22010-06-08 16:52:24 +000041
Jim Ingham84cdc152010-06-15 19:49:27 +000042#include "lldb/Interpreter/Args.h"
Caroline Tice5ddbe212011-05-06 21:37:15 +000043#include "lldb/Interpreter/Options.h"
Chris Lattner24943d22010-06-08 16:52:24 +000044#include "lldb/Core/Debugger.h"
Jim Ingham5e16ef52010-10-04 19:49:29 +000045#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000046#include "lldb/Core/Stream.h"
47#include "lldb/Core/Timer.h"
Greg Claytoncd548032011-02-01 01:31:41 +000048#include "lldb/Host/Host.h"
Chris Lattner24943d22010-06-08 16:52:24 +000049#include "lldb/Target/Process.h"
50#include "lldb/Target/Thread.h"
51#include "lldb/Target/TargetList.h"
Greg Claytone98ac252010-11-10 04:57:04 +000052#include "lldb/Utility/CleanUp.h"
Chris Lattner24943d22010-06-08 16:52:24 +000053
54#include "lldb/Interpreter/CommandReturnObject.h"
55#include "lldb/Interpreter/CommandInterpreter.h"
Caroline Tice0aa2e552011-01-14 00:29:16 +000056#include "lldb/Interpreter/ScriptInterpreterNone.h"
57#include "lldb/Interpreter/ScriptInterpreterPython.h"
Chris Lattner24943d22010-06-08 16:52:24 +000058
59using namespace lldb;
60using namespace lldb_private;
61
62CommandInterpreter::CommandInterpreter
63(
Greg Clayton63094e02010-06-23 01:19:29 +000064 Debugger &debugger,
Chris Lattner24943d22010-06-08 16:52:24 +000065 ScriptLanguage script_language,
Greg Clayton63094e02010-06-23 01:19:29 +000066 bool synchronous_execution
Chris Lattner24943d22010-06-08 16:52:24 +000067) :
Greg Clayton49ce6822010-10-31 03:01:06 +000068 Broadcaster ("lldb.command-interpreter"),
Greg Clayton63094e02010-06-23 01:19:29 +000069 m_debugger (debugger),
Greg Clayton887aa282010-10-11 01:05:37 +000070 m_synchronous_execution (synchronous_execution),
Caroline Tice0aa2e552011-01-14 00:29:16 +000071 m_skip_lldbinit_files (false),
Jim Ingham574c3d62011-08-12 23:34:31 +000072 m_skip_app_init_files (false),
Jim Ingham949d5ac2011-02-18 00:54:25 +000073 m_script_interpreter_ap (),
Caroline Tice892fadd2011-06-16 16:27:19 +000074 m_comment_char ('#'),
Jim Ingham6247dbe2011-07-12 03:12:18 +000075 m_repeat_char ('!'),
Enrico Granata293a7b32011-08-15 19:24:02 +000076 m_batch_command_mode (false),
77 m_truncation_warning(eNoTruncation)
Chris Lattner24943d22010-06-08 16:52:24 +000078{
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000079 const char *dbg_name = debugger.GetInstanceName().AsCString();
80 std::string lang_name = ScriptInterpreter::LanguageToString (script_language);
81 StreamString var_name;
82 var_name.Printf ("[%s].script-lang", dbg_name);
Caroline Tice1d2aefd2010-09-09 06:25:08 +000083 debugger.GetSettingsController()->SetVariable (var_name.GetData(), lang_name.c_str(),
Greg Claytonb3448432011-03-24 21:19:54 +000084 eVarSetOperationAssign, false,
Greg Clayton49ce6822010-10-31 03:01:06 +000085 m_debugger.GetInstanceName().AsCString());
86 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
87 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
88 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Chris Lattner24943d22010-06-08 16:52:24 +000089}
90
91void
92CommandInterpreter::Initialize ()
93{
94 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
95
96 CommandReturnObject result;
97
98 LoadCommandDictionary ();
99
Chris Lattner24943d22010-06-08 16:52:24 +0000100 // Set up some initial aliases.
Caroline Tice5ddbe212011-05-06 21:37:15 +0000101 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
102 if (cmd_obj_sp)
103 {
104 AddAlias ("q", cmd_obj_sp);
105 AddAlias ("exit", cmd_obj_sp);
106 }
107
108 cmd_obj_sp = GetCommandSPExact ("process continue", false);
109 if (cmd_obj_sp)
110 {
111 AddAlias ("c", cmd_obj_sp);
112 AddAlias ("continue", cmd_obj_sp);
113 }
114
115 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
116 if (cmd_obj_sp)
117 AddAlias ("b", cmd_obj_sp);
118
119 cmd_obj_sp = GetCommandSPExact ("thread backtrace", false);
120 if (cmd_obj_sp)
121 AddAlias ("bt", cmd_obj_sp);
122
123 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
124 if (cmd_obj_sp)
125 AddAlias ("si", cmd_obj_sp);
126
127 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
128 if (cmd_obj_sp)
129 {
130 AddAlias ("s", cmd_obj_sp);
131 AddAlias ("step", cmd_obj_sp);
132 }
133
134 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
135 if (cmd_obj_sp)
136 {
137 AddAlias ("n", cmd_obj_sp);
138 AddAlias ("next", cmd_obj_sp);
139 }
140
141 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
142 if (cmd_obj_sp)
143 {
144 AddAlias ("f", cmd_obj_sp);
145 AddAlias ("finish", cmd_obj_sp);
146 }
147
148 cmd_obj_sp = GetCommandSPExact ("source list", false);
149 if (cmd_obj_sp)
150 {
151 AddAlias ("l", cmd_obj_sp);
152 AddAlias ("list", cmd_obj_sp);
153 }
154
155 cmd_obj_sp = GetCommandSPExact ("memory read", false);
156 if (cmd_obj_sp)
157 AddAlias ("x", cmd_obj_sp);
158
159 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
160 if (cmd_obj_sp)
161 AddAlias ("up", cmd_obj_sp);
162
163 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
164 if (cmd_obj_sp)
165 AddAlias ("down", cmd_obj_sp);
166
167 cmd_obj_sp = GetCommandSPExact ("target create", false);
168 if (cmd_obj_sp)
169 AddAlias ("file", cmd_obj_sp);
170
171 cmd_obj_sp = GetCommandSPExact ("target modules", false);
172 if (cmd_obj_sp)
173 AddAlias ("image", cmd_obj_sp);
174
175
176 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghame56493f2011-03-22 02:29:32 +0000177
Caroline Tice5ddbe212011-05-06 21:37:15 +0000178 cmd_obj_sp = GetCommandSPExact ("expression", false);
179 if (cmd_obj_sp)
180 {
181 AddAlias ("expr", cmd_obj_sp);
182
183 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
184 AddAlias ("p", cmd_obj_sp);
185 AddAlias ("print", cmd_obj_sp);
186 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
187 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
188
189 alias_arguments_vector_sp.reset (new OptionArgVector);
190 ProcessAliasOptionsArgs (cmd_obj_sp, "-o --", alias_arguments_vector_sp);
191 AddAlias ("po", cmd_obj_sp);
192 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
193 }
194
195 cmd_obj_sp = GetCommandSPExact ("process launch", false);
196 if (cmd_obj_sp)
197 {
198 alias_arguments_vector_sp.reset (new OptionArgVector);
199 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
200 AddAlias ("r", cmd_obj_sp);
201 AddAlias ("run", cmd_obj_sp);
202 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
203 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
204 }
205
Chris Lattner24943d22010-06-08 16:52:24 +0000206}
207
Chris Lattner24943d22010-06-08 16:52:24 +0000208const char *
209CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
210{
211 // This function has not yet been implemented.
212
213 // Look for any embedded script command
214 // If found,
215 // get interpreter object from the command dictionary,
216 // call execute_one_command on it,
217 // get the results as a string,
218 // substitute that string for current stuff.
219
220 return arg;
221}
222
223
224void
225CommandInterpreter::LoadCommandDictionary ()
226{
227 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
228
229 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
230 //
231 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
232 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
233 // the cross-referencing stuff) are created!!!
234 //
235 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
236
237
238 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
239 // are created. This is so that when another command is created that needs to go into a crossref object,
240 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
241 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
242
Chris Lattner24943d22010-06-08 16:52:24 +0000243 // Non-CommandObjectCrossref commands can now be created.
244
Caroline Tice5bc8c972010-09-20 20:44:43 +0000245 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000246
Greg Clayton238c0a12010-09-18 01:14:36 +0000247 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000248 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000249 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000250 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000251 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
252 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Claytonabe0fed2011-04-18 08:33:37 +0000253// m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000254 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000255 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Claytone1f50b92011-05-03 22:09:39 +0000256 /// m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000257 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
258 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonb1888f22011-03-19 01:12:21 +0000259 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000260 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000261 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000262 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000263 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000264 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000265 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000266 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
267 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata6b1596d2011-08-16 23:24:13 +0000268 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000269 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chen01acfa72011-09-22 18:04:58 +0000270 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000271
272 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000273 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000274 "_regexp-break",
Caroline Ticec1ad82e2010-09-07 22:38:08 +0000275 "Set a breakpoint using a regular expression to specify the location.",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000276 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000277 if (break_regex_cmd_ap.get())
278 {
279 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
280 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
281 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
Greg Claytonb72d0f02011-04-12 05:54:46 +0000282 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000283 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
Greg Claytonb01000f2011-01-17 03:46:26 +0000284 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000285 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
286 {
287 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
288 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
289 }
290 }
Jim Inghame56493f2011-03-22 02:29:32 +0000291
292 std::auto_ptr<CommandObjectRegexCommand>
293 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000294 "_regexp-down",
295 "Go down \"n\" frames in the stack (1 frame by default).",
296 "_regexp-down [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000297 if (down_regex_cmd_ap.get())
298 {
299 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
300 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
301 {
302 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
303 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
304 }
305 }
306
307 std::auto_ptr<CommandObjectRegexCommand>
308 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000309 "_regexp-up",
310 "Go up \"n\" frames in the stack (1 frame by default).",
311 "_regexp-up [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000312 if (up_regex_cmd_ap.get())
313 {
314 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
315 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
316 {
317 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
318 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
319 }
320 }
Chris Lattner24943d22010-06-08 16:52:24 +0000321}
322
323int
324CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
325 StringList &matches)
326{
327 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
328
329 if (include_aliases)
330 {
331 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
332 }
333
334 return matches.GetSize();
335}
336
337CommandObjectSP
338CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
339{
340 CommandObject::CommandMap::iterator pos;
341 CommandObjectSP ret_val;
342
343 std::string cmd(cmd_cstr);
344
345 if (HasCommands())
346 {
347 pos = m_command_dict.find(cmd);
348 if (pos != m_command_dict.end())
349 ret_val = pos->second;
350 }
351
352 if (include_aliases && HasAliases())
353 {
354 pos = m_alias_dict.find(cmd);
355 if (pos != m_alias_dict.end())
356 ret_val = pos->second;
357 }
358
359 if (HasUserCommands())
360 {
361 pos = m_user_dict.find(cmd);
362 if (pos != m_user_dict.end())
363 ret_val = pos->second;
364 }
365
366 if (!exact && ret_val == NULL)
367 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000368 // We will only get into here if we didn't find any exact matches.
369
370 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
371
Chris Lattner24943d22010-06-08 16:52:24 +0000372 StringList local_matches;
373 if (matches == NULL)
374 matches = &local_matches;
375
Jim Inghamd40f8a62010-07-06 22:46:59 +0000376 unsigned int num_cmd_matches = 0;
377 unsigned int num_alias_matches = 0;
378 unsigned int num_user_matches = 0;
379
380 // Look through the command dictionaries one by one, and if we get only one match from any of
381 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
382
Chris Lattner24943d22010-06-08 16:52:24 +0000383 if (HasCommands())
384 {
385 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
386 }
387
388 if (num_cmd_matches == 1)
389 {
390 cmd.assign(matches->GetStringAtIndex(0));
391 pos = m_command_dict.find(cmd);
392 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000393 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000394 }
395
Jim Ingham9a574172010-06-24 20:28:42 +0000396 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000397 {
398 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
399
400 }
401
Jim Inghamd40f8a62010-07-06 22:46:59 +0000402 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000403 {
404 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
405 pos = m_alias_dict.find(cmd);
406 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000407 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000408 }
409
Jim Ingham9a574172010-06-24 20:28:42 +0000410 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000411 {
412 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
413 }
414
Jim Inghamd40f8a62010-07-06 22:46:59 +0000415 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000416 {
417 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
418
419 pos = m_user_dict.find (cmd);
420 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000421 user_match_sp = pos->second;
422 }
423
424 // If we got exactly one match, return that, otherwise return the match list.
425
426 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
427 {
428 if (num_cmd_matches)
429 return real_match_sp;
430 else if (num_alias_matches)
431 return alias_match_sp;
432 else
433 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000434 }
435 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000436 else if (matches && ret_val != NULL)
437 {
438 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000439 }
440
441
442 return ret_val;
443}
444
Greg Claytond12aeab2011-04-20 16:37:46 +0000445bool
446CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
447{
448 if (name && name[0])
449 {
450 std::string name_sstr(name);
451 if (!can_replace)
452 {
453 if (m_command_dict.find (name_sstr) != m_command_dict.end())
454 return false;
455 }
456 m_command_dict[name_sstr] = cmd_sp;
457 return true;
458 }
459 return false;
460}
461
Enrico Granata6b1596d2011-08-16 23:24:13 +0000462bool
463CommandInterpreter::AddUserCommand (const char *name,
464 const lldb::CommandObjectSP &cmd_sp,
465 bool can_replace)
466{
467 if (name && name[0])
468 {
469 std::string name_sstr(name);
470 if (!can_replace)
471 {
472 if (m_user_dict.find (name_sstr) != m_user_dict.end())
473 return false;
474 }
475 m_user_dict[name_sstr] = cmd_sp;
476 return true;
477 }
478 return false;
479}
Greg Claytond12aeab2011-04-20 16:37:46 +0000480
Jim Inghamd40f8a62010-07-06 22:46:59 +0000481CommandObjectSP
482CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000483{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000484 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
485 CommandObjectSP ret_val; // Possibly empty return value.
486
487 if (cmd_cstr == NULL)
488 return ret_val;
489
490 if (cmd_words.GetArgumentCount() == 1)
491 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
492 else
493 {
494 // We have a multi-word command (seemingly), so we need to do more work.
495 // First, get the cmd_obj_sp for the first word in the command.
496 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
497 if (cmd_obj_sp.get() != NULL)
498 {
499 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
500 // command name), and find the appropriate sub-command SP for each command word....
501 size_t end = cmd_words.GetArgumentCount();
502 for (size_t j= 1; j < end; ++j)
503 {
504 if (cmd_obj_sp->IsMultiwordObject())
505 {
506 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
507 (cmd_words.GetArgumentAtIndex (j));
508 if (cmd_obj_sp.get() == NULL)
509 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
510 return ret_val;
511 }
512 else
513 // We have more words in the command name, but we don't have a multiword object. Fail and return
514 // empty 'ret_val'.
515 return ret_val;
516 }
517 // We successfully looped through all the command words and got valid command objects for them. Assign the
518 // last object retrieved to 'ret_val'.
519 ret_val = cmd_obj_sp;
520 }
521 }
522 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000523}
524
525CommandObject *
526CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
527{
528 return GetCommandSPExact (cmd_cstr, include_aliases).get();
529}
530
531CommandObject *
532CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
533{
534 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
535
536 // If we didn't find an exact match to the command string in the commands, look in
537 // the aliases.
538
539 if (command_obj == NULL)
540 {
541 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
542 }
543
544 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
545 // in both the commands and the aliases.
546
547 if (command_obj == NULL)
548 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
549
550 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000551}
552
553bool
554CommandInterpreter::CommandExists (const char *cmd)
555{
556 return m_command_dict.find(cmd) != m_command_dict.end();
557}
558
559bool
Caroline Tice5ddbe212011-05-06 21:37:15 +0000560CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
561 const char *options_args,
562 OptionArgVectorSP &option_arg_vector_sp)
563{
564 bool success = true;
565 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
566
567 if (!options_args || (strlen (options_args) < 1))
568 return true;
569
570 std::string options_string (options_args);
571 Args args (options_args);
572 CommandReturnObject result;
573 // Check to see if the command being aliased can take any command options.
574 Options *options = cmd_obj_sp->GetOptions ();
575 if (options)
576 {
577 // See if any options were specified as part of the alias; if so, handle them appropriately.
578 options->NotifyOptionParsingStarting ();
579 args.Unshift ("dummy_arg");
580 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
581 args.Shift ();
582 if (result.Succeeded())
583 options->VerifyPartialOptions (result);
584 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
585 {
586 result.AppendError ("Unable to create requested alias.\n");
587 return false;
588 }
589 }
590
591 if (options_string.size() > 0)
592 {
593 if (cmd_obj_sp->WantsRawCommandString ())
594 option_arg_vector->push_back (OptionArgPair ("<argument>",
595 OptionArgValue (-1,
596 options_string)));
597 else
598 {
599 int argc = args.GetArgumentCount();
600 for (size_t i = 0; i < argc; ++i)
601 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
602 option_arg_vector->push_back
603 (OptionArgPair ("<argument>",
604 OptionArgValue (-1,
605 std::string (args.GetArgumentAtIndex (i)))));
606 }
607 }
608
609 return success;
610}
611
612bool
Chris Lattner24943d22010-06-08 16:52:24 +0000613CommandInterpreter::AliasExists (const char *cmd)
614{
615 return m_alias_dict.find(cmd) != m_alias_dict.end();
616}
617
618bool
619CommandInterpreter::UserCommandExists (const char *cmd)
620{
621 return m_user_dict.find(cmd) != m_user_dict.end();
622}
623
624void
625CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
626{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000627 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000628 m_alias_dict[alias_name] = command_obj_sp;
629}
630
631bool
632CommandInterpreter::RemoveAlias (const char *alias_name)
633{
634 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
635 if (pos != m_alias_dict.end())
636 {
637 m_alias_dict.erase(pos);
638 return true;
639 }
640 return false;
641}
642bool
643CommandInterpreter::RemoveUser (const char *alias_name)
644{
645 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
646 if (pos != m_user_dict.end())
647 {
648 m_user_dict.erase(pos);
649 return true;
650 }
651 return false;
652}
653
Chris Lattner24943d22010-06-08 16:52:24 +0000654void
655CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
656{
657 help_string.Printf ("'%s", command_name);
658 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
659
660 if (option_arg_vector_sp != NULL)
661 {
662 OptionArgVector *options = option_arg_vector_sp.get();
663 for (int i = 0; i < options->size(); ++i)
664 {
665 OptionArgPair cur_option = (*options)[i];
666 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000667 OptionArgValue value_pair = cur_option.second;
668 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000669 if (opt.compare("<argument>") == 0)
670 {
671 help_string.Printf (" %s", value.c_str());
672 }
673 else
674 {
675 help_string.Printf (" %s", opt.c_str());
676 if ((value.compare ("<no-argument>") != 0)
677 && (value.compare ("<need-argument") != 0))
678 {
679 help_string.Printf (" %s", value.c_str());
680 }
681 }
682 }
683 }
684
685 help_string.Printf ("'");
686}
687
Greg Clayton65124ea2010-08-26 22:05:43 +0000688size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000689CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
690{
691 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000692 CommandObject::CommandMap::const_iterator end = dict.end();
693 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000694
Greg Clayton65124ea2010-08-26 22:05:43 +0000695 for (pos = dict.begin(); pos != end; ++pos)
696 {
697 size_t len = pos->first.size();
698 if (max_len < len)
699 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000700 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000701 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000702}
703
704void
Enrico Granata6b1596d2011-08-16 23:24:13 +0000705CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata1ac6d1f2011-09-09 17:49:36 +0000706 uint32_t cmd_types)
Chris Lattner24943d22010-06-08 16:52:24 +0000707{
708 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000709 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata6b1596d2011-08-16 23:24:13 +0000710
711 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner24943d22010-06-08 16:52:24 +0000712 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000713
714 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
715 result.AppendMessage("");
Chris Lattner24943d22010-06-08 16:52:24 +0000716
Enrico Granata6b1596d2011-08-16 23:24:13 +0000717 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
718 {
719 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
720 max_len);
721 }
722 result.AppendMessage("");
723
724 }
725
726 if (m_alias_dict.size() > 0 && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner24943d22010-06-08 16:52:24 +0000727 {
Jim Inghame3663e82010-10-22 18:47:16 +0000728 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000729 "(see 'help command alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000730 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000731 max_len = FindLongestCommandWord (m_alias_dict);
732
Chris Lattner24943d22010-06-08 16:52:24 +0000733 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
734 {
735 StreamString sstr;
736 StreamString translation_and_help;
737 std::string entry_name = pos->first;
738 std::string second_entry = pos->second.get()->GetCommandName();
739 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
740
741 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
742 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
743 translation_and_help.GetData(), max_len);
744 }
745 result.AppendMessage("");
746 }
747
Enrico Granata6b1596d2011-08-16 23:24:13 +0000748 if (m_user_dict.size() > 0 && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner24943d22010-06-08 16:52:24 +0000749 {
750 result.AppendMessage ("The following is a list of your current user-defined commands:");
751 result.AppendMessage("");
Enrico Granata6b1596d2011-08-16 23:24:13 +0000752 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000753 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
754 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000755 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
756 max_len);
Chris Lattner24943d22010-06-08 16:52:24 +0000757 }
758 result.AppendMessage("");
759 }
760
761 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
762}
763
Caroline Ticee0da7a52010-12-09 22:52:49 +0000764CommandObject *
765CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000766{
Caroline Ticee0da7a52010-12-09 22:52:49 +0000767 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
768 // eventually be invoked by the given command line.
769
770 CommandObject *cmd_obj = NULL;
771 std::string white_space (" \t\v");
772 size_t start = command_string.find_first_not_of (white_space);
773 size_t end = 0;
774 bool done = false;
775 while (!done)
776 {
777 if (start != std::string::npos)
778 {
779 // Get the next word from command_string.
780 end = command_string.find_first_of (white_space, start);
781 if (end == std::string::npos)
782 end = command_string.size();
783 std::string cmd_word = command_string.substr (start, end - start);
784
785 if (cmd_obj == NULL)
786 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
787 // command or alias.
788 cmd_obj = GetCommandObject (cmd_word.c_str());
789 else if (cmd_obj->IsMultiwordObject ())
790 {
791 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
792 CommandObject *sub_cmd_obj =
793 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
794 if (sub_cmd_obj)
795 cmd_obj = sub_cmd_obj;
796 else // cmd_word was not a valid sub-command word, so we are donee
797 done = true;
798 }
799 else
800 // We have a cmd_obj and it is not a multi-word object, so we are done.
801 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000802
Caroline Ticee0da7a52010-12-09 22:52:49 +0000803 // If we didn't find a valid command object, or our command object is not a multi-word object, or
804 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
805 // next word.
806
807 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
808 done = true;
809 else
810 start = command_string.find_first_not_of (white_space, end);
811 }
812 else
813 // Unable to find any more words.
814 done = true;
815 }
816
817 if (end == command_string.size())
818 command_string.clear();
819 else
820 command_string = command_string.substr(end);
821
822 return cmd_obj;
823}
824
825bool
Caroline Tice649116c2011-05-11 16:07:06 +0000826CommandInterpreter::StripFirstWord (std::string &command_string, std::string &word, bool &was_quoted, char &quote_char)
Caroline Ticee0da7a52010-12-09 22:52:49 +0000827{
828 std::string white_space (" \t\v");
829 size_t start;
830 size_t end;
831
832 start = command_string.find_first_not_of (white_space);
833 if (start != std::string::npos)
834 {
Caroline Tice649116c2011-05-11 16:07:06 +0000835 size_t len = command_string.size() - start;
836 if (len >= 2
837 && ((command_string[start] == '\'') || (command_string[start] == '"')))
Caroline Ticee0da7a52010-12-09 22:52:49 +0000838 {
Caroline Tice649116c2011-05-11 16:07:06 +0000839 was_quoted = true;
840 quote_char = command_string[start];
841 std::string quote_string = command_string.substr (start, 1);
842 start = start + 1;
843 end = command_string.find (quote_string, start);
844 if (end != std::string::npos)
845 {
846 word = command_string.substr (start, end - start);
847 if (end + 1 < len)
848 command_string = command_string.substr (end+1);
849 else
850 command_string.erase ();
851 size_t pos = command_string.find_first_not_of (white_space);
852 if ((pos != 0) && (pos != std::string::npos))
853 command_string = command_string.substr (pos);
854 }
855 else
856 {
857 word = command_string.substr (start - 1);
858 command_string.erase ();
859 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000860 }
861 else
862 {
Caroline Tice649116c2011-05-11 16:07:06 +0000863 end = command_string.find_first_of (white_space, start);
864 if (end != std::string::npos)
865 {
866 word = command_string.substr (start, end - start);
867 command_string = command_string.substr (end);
868 size_t pos = command_string.find_first_not_of (white_space);
869 if ((pos != 0) && (pos != std::string::npos))
870 command_string = command_string.substr (pos);
871 }
872 else
873 {
874 word = command_string.substr (start);
875 command_string.erase();
876 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000877 }
878
879 }
880 return true;
881}
882
883void
884CommandInterpreter::BuildAliasResult (const char *alias_name, std::string &raw_input_string, std::string &alias_result,
885 CommandObject *&alias_cmd_obj, CommandReturnObject &result)
886{
887 Args cmd_args (raw_input_string.c_str());
888 alias_cmd_obj = GetCommandObject (alias_name);
889 StreamString result_str;
890
891 if (alias_cmd_obj)
892 {
893 std::string alias_name_str = alias_name;
894 if ((cmd_args.GetArgumentCount() == 0)
895 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
896 cmd_args.Unshift (alias_name);
897
898 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
899 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
900
901 if (option_arg_vector_sp.get())
902 {
903 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
904
905 for (int i = 0; i < option_arg_vector->size(); ++i)
906 {
907 OptionArgPair option_pair = (*option_arg_vector)[i];
908 OptionArgValue value_pair = option_pair.second;
909 int value_type = value_pair.first;
910 std::string option = option_pair.first;
911 std::string value = value_pair.second;
912 if (option.compare ("<argument>") == 0)
913 result_str.Printf (" %s", value.c_str());
914 else
915 {
916 result_str.Printf (" %s", option.c_str());
917 if (value_type != optional_argument)
918 result_str.Printf (" ");
919 if (value.compare ("<no_argument>") != 0)
920 {
921 int index = GetOptionArgumentPosition (value.c_str());
922 if (index == 0)
923 result_str.Printf ("%s", value.c_str());
924 else if (index >= cmd_args.GetArgumentCount())
925 {
926
927 result.AppendErrorWithFormat
928 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
929 index);
930 result.SetStatus (eReturnStatusFailed);
931 return;
932 }
933 else
934 {
935 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
936 if (strpos != std::string::npos)
937 raw_input_string = raw_input_string.erase (strpos,
938 strlen (cmd_args.GetArgumentAtIndex (index)));
939 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
940 }
941 }
942 }
943 }
944 }
945
946 alias_result = result_str.GetData();
947 }
948}
949
Greg Claytonf5c0c722011-10-14 07:41:33 +0000950Error
951CommandInterpreter::PreprocessCommand (std::string &command)
952{
953 // The command preprocessor needs to do things to the command
954 // line before any parsing of arguments or anything else is done.
955 // The only current stuff that gets proprocessed is anyting enclosed
956 // in backtick ('`') characters is evaluated as an expression and
957 // the result of the expression must be a scalar that can be substituted
958 // into the command. An example would be:
959 // (lldb) memory read `$rsp + 20`
960 Error error; // Error for any expressions that might not evaluate
961 size_t start_backtick;
962 size_t pos = 0;
963 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
964 {
965 if (start_backtick > 0 && command[start_backtick-1] == '\\')
966 {
967 // The backtick was preceeded by a '\' character, remove the slash
968 // and don't treat the backtick as the start of an expression
969 command.erase(start_backtick-1, 1);
970 // No need to add one to start_backtick since we just deleted a char
971 pos = start_backtick;
972 }
973 else
974 {
975 const size_t expr_content_start = start_backtick + 1;
976 const size_t end_backtick = command.find ('`', expr_content_start);
977 if (end_backtick == std::string::npos)
978 return error;
979 else if (end_backtick == expr_content_start)
980 {
981 // Empty expression (two backticks in a row)
982 command.erase (start_backtick, 2);
983 }
984 else
985 {
986 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
987
988 Target *target = m_exe_ctx.GetTargetPtr();
989 if (target)
990 {
991 const bool unwind_on_error = true;
992 const bool keep_in_memory = false;
993 ValueObjectSP expr_result_valobj_sp;
994 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
995 m_exe_ctx.GetFramePtr(),
996 eExecutionPolicyOnlyWhenNeeded,
997 unwind_on_error, keep_in_memory,
998 eNoDynamicValues,
999 expr_result_valobj_sp);
1000 if (expr_result == eExecutionCompleted)
1001 {
1002 Scalar scalar;
1003 if (expr_result_valobj_sp->ResolveValue (scalar))
1004 {
1005 command.erase (start_backtick, end_backtick - start_backtick + 1);
1006 StreamString value_strm;
1007 const bool show_type = false;
1008 scalar.GetValue (&value_strm, show_type);
1009 size_t value_string_size = value_strm.GetSize();
1010 if (value_string_size)
1011 {
1012 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1013 pos = start_backtick + value_string_size;
1014 continue;
1015 }
1016 else
1017 {
1018 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1019 }
1020 }
1021 else
1022 {
1023 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1024 }
1025 }
1026 else
1027 {
1028 if (expr_result_valobj_sp)
1029 error = expr_result_valobj_sp->GetError();
1030 if (error.Success())
1031 {
1032
1033 switch (expr_result)
1034 {
1035 case eExecutionSetupError:
1036 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1037 break;
1038 case eExecutionCompleted:
1039 break;
1040 case eExecutionDiscarded:
1041 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1042 break;
1043 case eExecutionInterrupted:
1044 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1045 break;
1046 case eExecutionTimedOut:
1047 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1048 break;
1049 }
1050 }
1051 }
1052 }
1053 }
1054 if (error.Fail())
1055 break;
1056 }
1057 }
1058 return error;
1059}
1060
1061
Caroline Ticee0da7a52010-12-09 22:52:49 +00001062bool
1063CommandInterpreter::HandleCommand (const char *command_line,
1064 bool add_to_history,
1065 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001066 ExecutionContext *override_context,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001067 bool repeat_on_empty_command,
1068 bool no_context_switching)
Jim Ingham949d5ac2011-02-18 00:54:25 +00001069
Caroline Ticee0da7a52010-12-09 22:52:49 +00001070{
Jim Ingham949d5ac2011-02-18 00:54:25 +00001071
Caroline Ticee0da7a52010-12-09 22:52:49 +00001072 bool done = false;
1073 CommandObject *cmd_obj = NULL;
1074 std::string next_word;
1075 bool wants_raw_input = false;
1076 std::string command_string (command_line);
Jim Ingham6247dbe2011-07-12 03:12:18 +00001077 std::string original_command_string (command_line);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001078
1079 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +00001080 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1081
1082 // Make a scoped cleanup object that will clear the crash description string
1083 // on exit of this function.
Enrico Granata1a102082011-07-12 00:18:11 +00001084 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Claytone98ac252010-11-10 04:57:04 +00001085
Caroline Ticee0da7a52010-12-09 22:52:49 +00001086 if (log)
1087 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +00001088
Jim Inghamabab14b2010-11-04 23:08:45 +00001089 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1090
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001091 if (!no_context_switching)
1092 UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +00001093
Jim Ingham949d5ac2011-02-18 00:54:25 +00001094 bool empty_command = false;
1095 bool comment_command = false;
1096 if (command_string.empty())
1097 empty_command = true;
1098 else
Chris Lattner24943d22010-06-08 16:52:24 +00001099 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001100 const char *k_space_characters = "\t\n\v\f\r ";
1101
1102 size_t non_space = command_string.find_first_not_of (k_space_characters);
1103 // Check for empty line or comment line (lines whose first
1104 // non-space character is the comment character for this interpreter)
1105 if (non_space == std::string::npos)
1106 empty_command = true;
1107 else if (command_string[non_space] == m_comment_char)
1108 comment_command = true;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001109 else if (command_string[non_space] == m_repeat_char)
1110 {
1111 const char *history_string = FindHistoryString (command_string.c_str() + non_space);
1112 if (history_string == NULL)
1113 {
1114 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1115 result.SetStatus(eReturnStatusFailed);
1116 return false;
1117 }
1118 add_to_history = false;
1119 command_string = history_string;
1120 original_command_string = history_string;
1121 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001122 }
1123
1124 if (empty_command)
1125 {
1126 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +00001127 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001128 if (m_command_history.empty())
1129 {
1130 result.AppendError ("empty command");
1131 result.SetStatus(eReturnStatusFailed);
1132 return false;
1133 }
1134 else
1135 {
1136 command_line = m_repeat_command.c_str();
1137 command_string = command_line;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001138 original_command_string = command_line;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001139 if (m_repeat_command.empty())
1140 {
1141 result.AppendErrorWithFormat("No auto repeat.\n");
1142 result.SetStatus (eReturnStatusFailed);
1143 return false;
1144 }
1145 }
1146 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001147 }
1148 else
1149 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001150 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1151 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001152 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001153 }
1154 else if (comment_command)
1155 {
1156 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1157 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001158 }
Caroline Tice649116c2011-05-11 16:07:06 +00001159
Greg Claytonf5c0c722011-10-14 07:41:33 +00001160
1161 Error error (PreprocessCommand (command_string));
1162
1163 if (error.Fail())
1164 {
1165 result.AppendError (error.AsCString());
1166 result.SetStatus(eReturnStatusFailed);
1167 return false;
1168 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001169 // Phase 1.
1170
1171 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1172 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1173 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1174 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1175 // 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 +00001176 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +00001177 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +00001178
Caroline Ticee0da7a52010-12-09 22:52:49 +00001179 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001180 size_t actual_cmd_name_len = 0;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001181 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +00001182 {
Caroline Tice649116c2011-05-11 16:07:06 +00001183 bool was_quoted = false;
1184 char quote_char = '\0';
1185 StripFirstWord (command_string, next_word, was_quoted, quote_char);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001186 if (!cmd_obj && AliasExists (next_word.c_str()))
Chris Lattner24943d22010-06-08 16:52:24 +00001187 {
Caroline Ticee0da7a52010-12-09 22:52:49 +00001188 std::string alias_result;
1189 BuildAliasResult (next_word.c_str(), command_string, alias_result, cmd_obj, result);
1190 revised_command_line.Printf ("%s", alias_result.c_str());
1191 if (cmd_obj)
Caroline Tice56d2fc42010-12-14 18:51:39 +00001192 {
Caroline Ticee0da7a52010-12-09 22:52:49 +00001193 wants_raw_input = cmd_obj->WantsRawCommandString ();
Caroline Tice56d2fc42010-12-14 18:51:39 +00001194 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1195 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001196 }
1197 else if (!cmd_obj)
1198 {
1199 cmd_obj = GetCommandObject (next_word.c_str());
1200 if (cmd_obj)
Chris Lattner24943d22010-06-08 16:52:24 +00001201 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001202 actual_cmd_name_len += next_word.length();
Caroline Ticee0da7a52010-12-09 22:52:49 +00001203 revised_command_line.Printf ("%s", next_word.c_str());
1204 wants_raw_input = cmd_obj->WantsRawCommandString ();
Chris Lattner24943d22010-06-08 16:52:24 +00001205 }
1206 else
1207 {
Caroline Ticee0da7a52010-12-09 22:52:49 +00001208 revised_command_line.Printf ("%s", next_word.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001209 }
1210 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001211 else if (cmd_obj->IsMultiwordObject ())
1212 {
1213 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
1214 if (sub_cmd_obj)
1215 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001216 actual_cmd_name_len += next_word.length() + 1;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001217 revised_command_line.Printf (" %s", next_word.c_str());
1218 cmd_obj = sub_cmd_obj;
1219 wants_raw_input = cmd_obj->WantsRawCommandString ();
1220 }
1221 else
1222 {
Caroline Tice649116c2011-05-11 16:07:06 +00001223 if (was_quoted)
1224 {
1225 if (quote_char == '"')
1226 revised_command_line.Printf (" \"%s\"", next_word.c_str());
1227 else
1228 revised_command_line.Printf (" '%s'", next_word.c_str());
1229 }
1230 else
1231 revised_command_line.Printf (" %s", next_word.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001232 done = true;
1233 }
1234 }
1235 else
1236 {
Caroline Tice649116c2011-05-11 16:07:06 +00001237 if (was_quoted)
1238 {
1239 if (quote_char == '"')
1240 revised_command_line.Printf (" \"%s\"", next_word.c_str());
1241 else
1242 revised_command_line.Printf (" '%s'", next_word.c_str());
1243 }
1244 else
1245 revised_command_line.Printf (" %s", next_word.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001246 done = true;
1247 }
1248
1249 if (cmd_obj == NULL)
1250 {
1251 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1252 result.SetStatus (eReturnStatusFailed);
1253 return false;
1254 }
1255
1256 next_word.erase ();
1257 if (command_string.length() == 0)
1258 done = true;
1259
Chris Lattner24943d22010-06-08 16:52:24 +00001260 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001261
1262 if (command_string.size() > 0)
1263 revised_command_line.Printf (" %s", command_string.c_str());
1264
1265 // End of Phase 1.
1266 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1267 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1268 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1269 // wants_raw_input specifies whether the Execute method expects raw input or not.
1270
1271
1272 if (log)
1273 {
1274 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1275 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1276 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1277 }
1278
1279 // Phase 2.
1280 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1281 // CommandObject, with the appropriate arguments.
1282
1283 if (cmd_obj != NULL)
1284 {
1285 if (add_to_history)
1286 {
1287 Args command_args (revised_command_line.GetData());
1288 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1289 if (repeat_command != NULL)
1290 m_repeat_command.assign(repeat_command);
1291 else
Jim Ingham6247dbe2011-07-12 03:12:18 +00001292 m_repeat_command.assign(original_command_string.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001293
Jim Ingham6247dbe2011-07-12 03:12:18 +00001294 // Don't keep pushing the same command onto the history...
1295 if (m_command_history.size() == 0 || m_command_history.back() != original_command_string)
1296 m_command_history.push_back (original_command_string);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001297 }
1298
1299 command_string = revised_command_line.GetData();
1300 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001301 std::string remainder;
1302 if (actual_cmd_name_len < command_string.length())
1303 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1304 // than cmd_obj->GetCommandName(), because name completion
1305 // allows users to enter short versions of the names,
1306 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +00001307
1308 // Remove any initial spaces
1309 std::string white_space (" \t\v");
1310 size_t pos = remainder.find_first_not_of (white_space);
1311 if (pos != 0 && pos != std::string::npos)
Greg Clayton91c9dcf2011-04-22 20:58:45 +00001312 remainder.erase(0, pos);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001313
1314 if (log)
Jason Molenda24c991c2011-08-25 00:20:04 +00001315 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001316
1317
1318 if (wants_raw_input)
1319 cmd_obj->ExecuteRawCommandString (remainder.c_str(), result);
1320 else
1321 {
1322 Args cmd_args (remainder.c_str());
1323 cmd_obj->ExecuteWithOptions (cmd_args, result);
1324 }
1325 }
1326 else
1327 {
1328 // We didn't find the first command object, so complete the first argument.
1329 Args command_args (revised_command_line.GetData());
1330 StringList matches;
1331 int num_matches;
1332 int cursor_index = 0;
1333 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1334 bool word_complete;
1335 num_matches = HandleCompletionMatches (command_args,
1336 cursor_index,
1337 cursor_char_position,
1338 0,
1339 -1,
1340 word_complete,
1341 matches);
1342
1343 if (num_matches > 0)
1344 {
1345 std::string error_msg;
1346 error_msg.assign ("ambiguous command '");
1347 error_msg.append(command_args.GetArgumentAtIndex(0));
1348 error_msg.append ("'.");
1349
1350 error_msg.append (" Possible completions:");
1351 for (int i = 0; i < num_matches; i++)
1352 {
1353 error_msg.append ("\n\t");
1354 error_msg.append (matches.GetStringAtIndex (i));
1355 }
1356 error_msg.append ("\n");
1357 result.AppendRawError (error_msg.c_str(), error_msg.size());
1358 }
1359 else
1360 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1361
1362 result.SetStatus (eReturnStatusFailed);
1363 }
1364
Jason Molenda24c991c2011-08-25 00:20:04 +00001365 if (log)
1366 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1367
Chris Lattner24943d22010-06-08 16:52:24 +00001368 return result.Succeeded();
1369}
1370
1371int
1372CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1373 int &cursor_index,
1374 int &cursor_char_position,
1375 int match_start_point,
1376 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001377 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001378 StringList &matches)
1379{
1380 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001381 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001382
1383 // For any of the command completions a unique match will be a complete word.
1384 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001385
1386 if (cursor_index == -1)
1387 {
1388 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001389 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001390 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1391 }
1392 else if (cursor_index == 0)
1393 {
1394 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001395 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001396 num_command_matches = matches.GetSize();
1397
1398 if (num_command_matches == 1
1399 && cmd_obj && cmd_obj->IsMultiwordObject()
1400 && matches.GetStringAtIndex(0) != NULL
1401 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1402 {
1403 look_for_subcommand = true;
1404 num_command_matches = 0;
1405 matches.DeleteStringAtIndex(0);
1406 parsed_line.AppendArgument ("");
1407 cursor_index++;
1408 cursor_char_position = 0;
1409 }
1410 }
1411
1412 if (cursor_index > 0 || look_for_subcommand)
1413 {
1414 // We are completing further on into a commands arguments, so find the command and tell it
1415 // to complete the command.
1416 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001417 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001418 if (command_object == NULL)
1419 {
1420 return 0;
1421 }
1422 else
1423 {
1424 parsed_line.Shift();
1425 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001426 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001427 cursor_index,
1428 cursor_char_position,
1429 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001430 max_return_elements,
1431 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001432 matches);
1433 }
1434 }
1435
1436 return num_command_matches;
1437
1438}
1439
1440int
1441CommandInterpreter::HandleCompletion (const char *current_line,
1442 const char *cursor,
1443 const char *last_char,
1444 int match_start_point,
1445 int max_return_elements,
1446 StringList &matches)
1447{
1448 // We parse the argument up to the cursor, so the last argument in parsed_line is
1449 // the one containing the cursor, and the cursor is after the last character.
1450
1451 Args parsed_line(current_line, last_char - current_line);
1452 Args partial_parsed_line(current_line, cursor - current_line);
1453
Jim Ingham6247dbe2011-07-12 03:12:18 +00001454 // Don't complete comments, and if the line we are completing is just the history repeat character,
1455 // substitute the appropriate history line.
1456 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1457 if (first_arg)
1458 {
1459 if (first_arg[0] == m_comment_char)
1460 return 0;
1461 else if (first_arg[0] == m_repeat_char)
1462 {
1463 const char *history_string = FindHistoryString (first_arg);
1464 if (history_string != NULL)
1465 {
1466 matches.Clear();
1467 matches.InsertStringAtIndex(0, history_string);
1468 return -2;
1469 }
1470 else
1471 return 0;
1472
1473 }
1474 }
1475
1476
Chris Lattner24943d22010-06-08 16:52:24 +00001477 int num_args = partial_parsed_line.GetArgumentCount();
1478 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1479 int cursor_char_position;
1480
1481 if (cursor_index == -1)
1482 cursor_char_position = 0;
1483 else
1484 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001485
1486 if (cursor > current_line && cursor[-1] == ' ')
1487 {
1488 // We are just after a space. If we are in an argument, then we will continue
1489 // parsing, but if we are between arguments, then we have to complete whatever the next
1490 // element would be.
1491 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1492 // protected by a quote) then the space will also be in the parsed argument...
1493
1494 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1495 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1496 {
1497 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1498 cursor_index++;
1499 cursor_char_position = 0;
1500 }
1501 }
Chris Lattner24943d22010-06-08 16:52:24 +00001502
1503 int num_command_matches;
1504
1505 matches.Clear();
1506
1507 // Only max_return_elements == -1 is supported at present:
1508 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001509 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001510 num_command_matches = HandleCompletionMatches (parsed_line,
1511 cursor_index,
1512 cursor_char_position,
1513 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001514 max_return_elements,
1515 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001516 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001517
1518 if (num_command_matches <= 0)
1519 return num_command_matches;
1520
1521 if (num_args == 0)
1522 {
1523 // If we got an empty string, insert nothing.
1524 matches.InsertStringAtIndex(0, "");
1525 }
1526 else
1527 {
1528 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1529 // put an empty string in element 0.
1530 std::string command_partial_str;
1531 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001532 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1533 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001534
1535 std::string common_prefix;
1536 matches.LongestCommonPrefix (common_prefix);
1537 int partial_name_len = command_partial_str.size();
1538
1539 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001540 // Only do this if the completer told us this was a complete word, however...
1541 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001542 {
1543 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1544 if (quote_char != '\0')
1545 common_prefix.push_back(quote_char);
1546
1547 common_prefix.push_back(' ');
1548 }
1549 common_prefix.erase (0, partial_name_len);
1550 matches.InsertStringAtIndex(0, common_prefix.c_str());
1551 }
1552 return num_command_matches;
1553}
1554
Chris Lattner24943d22010-06-08 16:52:24 +00001555
1556CommandInterpreter::~CommandInterpreter ()
1557{
1558}
1559
1560const char *
1561CommandInterpreter::GetPrompt ()
1562{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001563 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001564}
1565
1566void
1567CommandInterpreter::SetPrompt (const char *new_prompt)
1568{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001569 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001570}
1571
Jim Ingham5e16ef52010-10-04 19:49:29 +00001572size_t
Greg Clayton58928562011-02-09 01:08:52 +00001573CommandInterpreter::GetConfirmationInputReaderCallback
1574(
1575 void *baton,
1576 InputReader &reader,
1577 lldb::InputReaderAction action,
1578 const char *bytes,
1579 size_t bytes_len
1580)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001581{
Greg Clayton58928562011-02-09 01:08:52 +00001582 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001583 bool *response_ptr = (bool *) baton;
1584
1585 switch (action)
1586 {
1587 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001588 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001589 {
1590 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001591 {
Greg Clayton58928562011-02-09 01:08:52 +00001592 out_file.Printf ("%s", reader.GetPrompt());
1593 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001594 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001595 }
1596 break;
1597
1598 case eInputReaderDeactivate:
1599 break;
1600
1601 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001602 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001603 {
Greg Clayton58928562011-02-09 01:08:52 +00001604 out_file.Printf ("%s", reader.GetPrompt());
1605 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001606 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001607 break;
Caroline Tice4a348082011-05-02 20:41:46 +00001608
1609 case eInputReaderAsynchronousOutputWritten:
1610 break;
1611
Jim Ingham5e16ef52010-10-04 19:49:29 +00001612 case eInputReaderGotToken:
1613 if (bytes_len == 0)
1614 {
1615 reader.SetIsDone(true);
1616 }
1617 else if (bytes[0] == 'y')
1618 {
1619 *response_ptr = true;
1620 reader.SetIsDone(true);
1621 }
1622 else if (bytes[0] == 'n')
1623 {
1624 *response_ptr = false;
1625 reader.SetIsDone(true);
1626 }
1627 else
1628 {
Greg Clayton58928562011-02-09 01:08:52 +00001629 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001630 {
Greg Clayton58928562011-02-09 01:08:52 +00001631 out_file.Printf ("Please answer \"y\" or \"n\"\n%s", reader.GetPrompt());
1632 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001633 }
1634 }
1635 break;
1636
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001637 case eInputReaderInterrupt:
1638 case eInputReaderEndOfFile:
1639 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1640 reader.SetIsDone (true);
1641 break;
1642
Jim Ingham5e16ef52010-10-04 19:49:29 +00001643 case eInputReaderDone:
1644 break;
1645 }
1646
1647 return bytes_len;
1648
1649}
1650
1651bool
1652CommandInterpreter::Confirm (const char *message, bool default_answer)
1653{
Jim Ingham93057472010-10-04 22:44:14 +00001654 // Check AutoConfirm first:
1655 if (m_debugger.GetAutoConfirm())
1656 return default_answer;
1657
Jim Ingham5e16ef52010-10-04 19:49:29 +00001658 InputReaderSP reader_sp (new InputReader(GetDebugger()));
1659 bool response = default_answer;
1660 if (reader_sp)
1661 {
1662 std::string prompt(message);
1663 prompt.append(": [");
1664 if (default_answer)
1665 prompt.append ("Y/n] ");
1666 else
1667 prompt.append ("y/N] ");
1668
1669 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1670 &response, // baton
1671 eInputReaderGranularityLine, // token size, to pass to callback function
1672 NULL, // end token
1673 prompt.c_str(), // prompt
1674 true)); // echo input
1675 if (err.Success())
1676 {
1677 GetDebugger().PushInputReader (reader_sp);
1678 }
1679 reader_sp->WaitOnReaderIsDone();
1680 }
1681 return response;
1682}
1683
1684
Chris Lattner24943d22010-06-08 16:52:24 +00001685void
1686CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1687{
Jim Inghamd40f8a62010-07-06 22:46:59 +00001688 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001689
1690 if (cmd_obj_sp != NULL)
1691 {
1692 CommandObject *cmd_obj = cmd_obj_sp.get();
1693 if (cmd_obj->IsCrossRefObject ())
1694 cmd_obj->AddObject (object_type);
1695 }
1696}
1697
Chris Lattner24943d22010-06-08 16:52:24 +00001698OptionArgVectorSP
1699CommandInterpreter::GetAliasOptions (const char *alias_name)
1700{
1701 OptionArgMap::iterator pos;
1702 OptionArgVectorSP ret_val;
1703
1704 std::string alias (alias_name);
1705
1706 if (HasAliasOptions())
1707 {
1708 pos = m_alias_options.find (alias);
1709 if (pos != m_alias_options.end())
1710 ret_val = pos->second;
1711 }
1712
1713 return ret_val;
1714}
1715
1716void
1717CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1718{
1719 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1720 if (pos != m_alias_options.end())
1721 {
1722 m_alias_options.erase (pos);
1723 }
1724}
1725
1726void
1727CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1728{
1729 m_alias_options[alias_name] = option_arg_vector_sp;
1730}
1731
1732bool
1733CommandInterpreter::HasCommands ()
1734{
1735 return (!m_command_dict.empty());
1736}
1737
1738bool
1739CommandInterpreter::HasAliases ()
1740{
1741 return (!m_alias_dict.empty());
1742}
1743
1744bool
1745CommandInterpreter::HasUserCommands ()
1746{
1747 return (!m_user_dict.empty());
1748}
1749
1750bool
1751CommandInterpreter::HasAliasOptions ()
1752{
1753 return (!m_alias_options.empty());
1754}
1755
Chris Lattner24943d22010-06-08 16:52:24 +00001756void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001757CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
1758 const char *alias_name,
1759 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00001760 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001761 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00001762{
1763 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00001764
1765 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00001766
Caroline Tice44c841d2010-12-07 19:58:26 +00001767 // Make sure that the alias name is the 0th element in cmd_args
1768 std::string alias_name_str = alias_name;
1769 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1770 cmd_args.Unshift (alias_name);
1771
1772 Args new_args (alias_cmd_obj->GetCommandName());
1773 if (new_args.GetArgumentCount() == 2)
1774 new_args.Shift();
1775
Chris Lattner24943d22010-06-08 16:52:24 +00001776 if (option_arg_vector_sp.get())
1777 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001778 if (wants_raw_input)
1779 {
1780 // We have a command that both has command options and takes raw input. Make *sure* it has a
1781 // " -- " in the right place in the raw_input_string.
1782 size_t pos = raw_input_string.find(" -- ");
1783 if (pos == std::string::npos)
1784 {
1785 // None found; assume it goes at the beginning of the raw input string
1786 raw_input_string.insert (0, " -- ");
1787 }
1788 }
Chris Lattner24943d22010-06-08 16:52:24 +00001789
1790 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1791 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001792 std::vector<bool> used (old_size + 1, false);
1793
1794 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001795
1796 for (int i = 0; i < option_arg_vector->size(); ++i)
1797 {
1798 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00001799 OptionArgValue value_pair = option_pair.second;
1800 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00001801 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00001802 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00001803 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001804 {
1805 if (!wants_raw_input
1806 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
1807 new_args.AppendArgument (value.c_str());
1808 }
Chris Lattner24943d22010-06-08 16:52:24 +00001809 else
1810 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001811 if (value_type != optional_argument)
1812 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001813 if (value.compare ("<no-argument>") != 0)
1814 {
1815 int index = GetOptionArgumentPosition (value.c_str());
1816 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001817 {
Chris Lattner24943d22010-06-08 16:52:24 +00001818 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00001819 if (value_type != optional_argument)
1820 new_args.AppendArgument (value.c_str());
1821 else
1822 {
1823 char buffer[255];
1824 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
1825 new_args.AppendArgument (buffer);
1826 }
1827
1828 }
Chris Lattner24943d22010-06-08 16:52:24 +00001829 else if (index >= cmd_args.GetArgumentCount())
1830 {
1831 result.AppendErrorWithFormat
1832 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1833 index);
1834 result.SetStatus (eReturnStatusFailed);
1835 return;
1836 }
1837 else
1838 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001839 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
1840 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1841 if (strpos != std::string::npos)
1842 {
1843 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
1844 }
1845
1846 if (value_type != optional_argument)
1847 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
1848 else
1849 {
1850 char buffer[255];
1851 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
1852 cmd_args.GetArgumentAtIndex (index));
1853 new_args.AppendArgument (buffer);
1854 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001855 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001856 }
1857 }
1858 }
1859 }
1860
1861 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1862 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001863 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00001864 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1865 }
1866
1867 cmd_args.Clear();
1868 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1869 }
1870 else
1871 {
1872 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00001873 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
1874 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
1875 // input string.
1876 if (wants_raw_input)
1877 {
1878 cmd_args.Clear();
1879 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1880 }
Chris Lattner24943d22010-06-08 16:52:24 +00001881 return;
1882 }
1883
1884 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1885 return;
1886}
1887
1888
1889int
1890CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1891{
1892 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1893 // of zero.
1894
1895 char *cptr = (char *) in_string;
1896
1897 // Does it start with '%'
1898 if (cptr[0] == '%')
1899 {
1900 ++cptr;
1901
1902 // Is the rest of it entirely digits?
1903 if (isdigit (cptr[0]))
1904 {
1905 const char *start = cptr;
1906 while (isdigit (cptr[0]))
1907 ++cptr;
1908
1909 // We've gotten to the end of the digits; are we at the end of the string?
1910 if (cptr[0] == '\0')
1911 position = atoi (start);
1912 }
1913 }
1914
1915 return position;
1916}
1917
1918void
1919CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1920{
Jim Ingham574c3d62011-08-12 23:34:31 +00001921 FileSpec init_file;
Greg Claytond6edcb52011-09-11 00:01:44 +00001922 if (in_cwd)
Jim Ingham574c3d62011-08-12 23:34:31 +00001923 {
Greg Claytond6edcb52011-09-11 00:01:44 +00001924 // In the current working directory we don't load any program specific
1925 // .lldbinit files, we only look for a "./.lldbinit" file.
1926 if (m_skip_lldbinit_files)
1927 return;
1928
1929 init_file.SetFile ("./.lldbinit", true);
Jim Ingham574c3d62011-08-12 23:34:31 +00001930 }
Greg Claytond6edcb52011-09-11 00:01:44 +00001931 else
Jim Ingham574c3d62011-08-12 23:34:31 +00001932 {
Greg Claytond6edcb52011-09-11 00:01:44 +00001933 // If we aren't looking in the current working directory we are looking
1934 // in the home directory. We will first see if there is an application
1935 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
1936 // "-" and the name of the program. If this file doesn't exist, we fall
1937 // back to just the "~/.lldbinit" file. We also obey any requests to not
1938 // load the init files.
1939 const char *init_file_path = "~/.lldbinit";
1940
1941 if (m_skip_app_init_files == false)
1942 {
1943 FileSpec program_file_spec (Host::GetProgramFileSpec());
1944 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham574c3d62011-08-12 23:34:31 +00001945
Greg Claytond6edcb52011-09-11 00:01:44 +00001946 if (program_name)
1947 {
1948 char program_init_file_name[PATH_MAX];
1949 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
1950 init_file.SetFile (program_init_file_name, true);
1951 if (!init_file.Exists())
1952 init_file.Clear();
1953 }
1954 }
1955
1956 if (!init_file && !m_skip_lldbinit_files)
1957 init_file.SetFile (init_file_path, true);
1958 }
1959
Chris Lattner24943d22010-06-08 16:52:24 +00001960 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
1961 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
1962
1963 if (init_file.Exists())
1964 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001965 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
1966 bool stop_on_continue = true;
1967 bool stop_on_error = false;
1968 bool echo_commands = false;
1969 bool print_results = false;
1970
1971 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, result);
Chris Lattner24943d22010-06-08 16:52:24 +00001972 }
1973 else
1974 {
1975 // nothing to be done if the file doesn't exist
1976 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1977 }
1978}
1979
Greg Claytonb72d0f02011-04-12 05:54:46 +00001980PlatformSP
1981CommandInterpreter::GetPlatform (bool prefer_target_platform)
1982{
1983 PlatformSP platform_sp;
Greg Clayton567e7f32011-09-22 04:58:26 +00001984 if (prefer_target_platform)
1985 {
1986 Target *target = m_exe_ctx.GetTargetPtr();
1987 if (target)
1988 platform_sp = target->GetPlatform();
1989 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001990
1991 if (!platform_sp)
1992 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
1993 return platform_sp;
1994}
1995
Jim Ingham949d5ac2011-02-18 00:54:25 +00001996void
Jim Inghama4fede32011-03-11 01:51:49 +00001997CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001998 ExecutionContext *override_context,
1999 bool stop_on_continue,
2000 bool stop_on_error,
2001 bool echo_commands,
2002 bool print_results,
2003 CommandReturnObject &result)
2004{
2005 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00002006
2007 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2008 // Make sure you reset this value anywhere you return from the function.
2009
2010 bool old_async_execution = m_debugger.GetAsyncExecution();
2011
2012 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2013 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2014
2015 if (override_context != NULL)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002016 UpdateExecutionContext (override_context);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002017
2018 if (!stop_on_continue)
2019 {
2020 m_debugger.SetAsyncExecution (false);
2021 }
2022
2023 for (int idx = 0; idx < num_lines; idx++)
2024 {
2025 const char *cmd = commands.GetStringAtIndex(idx);
2026 if (cmd[0] == '\0')
2027 continue;
2028
Jim Ingham949d5ac2011-02-18 00:54:25 +00002029 if (echo_commands)
2030 {
2031 result.AppendMessageWithFormat ("%s %s\n",
2032 GetPrompt(),
2033 cmd);
2034 }
2035
Greg Claytonaa378b12011-02-20 02:15:07 +00002036 CommandReturnObject tmp_result;
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002037 // If override_context is not NULL, pass no_context_switching = true for
2038 // HandleCommand() since we updated our context already.
2039 bool success = HandleCommand(cmd, false, tmp_result,
2040 NULL, /* override_context */
2041 true, /* repeat_on_empty_command */
2042 override_context != NULL /* no_context_switching */);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002043
2044 if (print_results)
2045 {
2046 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002047 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002048 }
2049
2050 if (!success || !tmp_result.Succeeded())
2051 {
2052 if (stop_on_error)
2053 {
2054 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed.\n",
2055 idx, cmd);
2056 result.SetStatus (eReturnStatusFailed);
2057 m_debugger.SetAsyncExecution (old_async_execution);
2058 return;
2059 }
2060 else if (print_results)
2061 {
2062 result.AppendMessageWithFormat ("Command #%d '%s' failed with error: %s.\n",
2063 idx + 1,
2064 cmd,
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002065 tmp_result.GetErrorData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002066 }
2067 }
2068
Caroline Tice4a348082011-05-02 20:41:46 +00002069 if (result.GetImmediateOutputStream())
2070 result.GetImmediateOutputStream()->Flush();
2071
2072 if (result.GetImmediateErrorStream())
2073 result.GetImmediateErrorStream()->Flush();
2074
Jim Ingham949d5ac2011-02-18 00:54:25 +00002075 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2076 // could be running (for instance in Breakpoint Commands.
2077 // So we check the return value to see if it is has running in it.
2078 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2079 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2080 {
2081 if (stop_on_continue)
2082 {
2083 // If we caused the target to proceed, and we're going to stop in that case, set the
2084 // status in our real result before returning. This is an error if the continue was not the
2085 // last command in the set of commands to be run.
2086 if (idx != num_lines - 1)
2087 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
2088 idx + 1, cmd);
2089 else
2090 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
2091
2092 result.SetStatus(tmp_result.GetStatus());
2093 m_debugger.SetAsyncExecution (old_async_execution);
2094
2095 return;
2096 }
2097 }
2098
2099 }
2100
2101 result.SetStatus (eReturnStatusSuccessFinishResult);
2102 m_debugger.SetAsyncExecution (old_async_execution);
2103
2104 return;
2105}
2106
2107void
2108CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2109 ExecutionContext *context,
2110 bool stop_on_continue,
2111 bool stop_on_error,
2112 bool echo_command,
2113 bool print_result,
2114 CommandReturnObject &result)
2115{
2116 if (cmd_file.Exists())
2117 {
2118 bool success;
2119 StringList commands;
2120 success = commands.ReadFileLines(cmd_file);
2121 if (!success)
2122 {
2123 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2124 result.SetStatus (eReturnStatusFailed);
2125 return;
2126 }
2127 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, result);
2128 }
2129 else
2130 {
2131 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2132 cmd_file.GetFilename().AsCString());
2133 result.SetStatus (eReturnStatusFailed);
2134 return;
2135 }
2136}
2137
Chris Lattner24943d22010-06-08 16:52:24 +00002138ScriptInterpreter *
2139CommandInterpreter::GetScriptInterpreter ()
2140{
Caroline Tice0aa2e552011-01-14 00:29:16 +00002141 if (m_script_interpreter_ap.get() != NULL)
2142 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00002143
Caroline Tice0aa2e552011-01-14 00:29:16 +00002144 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2145 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00002146 {
Caroline Tice0aa2e552011-01-14 00:29:16 +00002147 case eScriptLanguageNone:
2148 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2149 break;
2150 case eScriptLanguagePython:
2151 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2152 break;
2153 default:
2154 break;
2155 };
2156
2157 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00002158}
2159
2160
2161
2162bool
2163CommandInterpreter::GetSynchronous ()
2164{
2165 return m_synchronous_execution;
2166}
2167
2168void
2169CommandInterpreter::SetSynchronous (bool value)
2170{
Johnny Chend7a4eb02010-10-14 01:22:03 +00002171 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00002172}
2173
2174void
2175CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2176 const char *word_text,
2177 const char *separator,
2178 const char *help_text,
2179 uint32_t max_word_len)
2180{
Greg Clayton238c0a12010-09-18 01:14:36 +00002181 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2182
Chris Lattner24943d22010-06-08 16:52:24 +00002183 int indent_size = max_word_len + strlen (separator) + 2;
2184
2185 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00002186
2187 StreamString text_strm;
2188 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2189
2190 size_t len = text_strm.GetSize();
2191 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00002192 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00002193 {
2194 text_strm.EOL();
2195 len = text_strm.GetSize();
2196 }
Chris Lattner24943d22010-06-08 16:52:24 +00002197
2198 if (len < max_columns)
2199 {
2200 // Output it as a single line.
2201 strm.Printf ("%s", text);
2202 }
2203 else
2204 {
2205 // We need to break it up into multiple lines.
2206 bool first_line = true;
2207 int text_width;
2208 int start = 0;
2209 int end = start;
2210 int final_end = strlen (text);
2211 int sub_len;
2212
2213 while (end < final_end)
2214 {
2215 if (first_line)
2216 text_width = max_columns - 1;
2217 else
2218 text_width = max_columns - indent_size - 1;
2219
2220 // Don't start the 'text' on a space, since we're already outputting the indentation.
2221 if (!first_line)
2222 {
2223 while ((start < final_end) && (text[start] == ' '))
2224 start++;
2225 }
2226
2227 end = start + text_width;
2228 if (end > final_end)
2229 end = final_end;
2230 else
2231 {
2232 // If we're not at the end of the text, make sure we break the line on white space.
2233 while (end > start
2234 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2235 end--;
2236 }
2237
2238 sub_len = end - start;
2239 if (start != 0)
2240 strm.EOL();
2241 if (!first_line)
2242 strm.Indent();
2243 else
2244 first_line = false;
2245 assert (start <= final_end);
2246 assert (start + sub_len <= final_end);
2247 if (sub_len > 0)
2248 strm.Write (text + start, sub_len);
2249 start = end + 1;
2250 }
2251 }
2252 strm.EOL();
2253 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00002254}
2255
2256void
Enrico Granata1bba6e52011-07-07 00:38:40 +00002257CommandInterpreter::OutputHelpText (Stream &strm,
2258 const char *word_text,
2259 const char *separator,
2260 const char *help_text,
2261 uint32_t max_word_len)
2262{
2263 int indent_size = max_word_len + strlen (separator) + 2;
2264
2265 strm.IndentMore (indent_size);
2266
2267 StreamString text_strm;
2268 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2269
2270 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2271 bool first_line = true;
2272
2273 size_t len = text_strm.GetSize();
2274 const char *text = text_strm.GetData();
2275
2276 uint32_t chars_left = max_columns;
2277
2278 for (uint32_t i = 0; i < len; i++)
2279 {
2280 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2281 {
2282 first_line = false;
2283 chars_left = max_columns - indent_size;
2284 strm.EOL();
2285 strm.Indent();
2286 }
2287 else
2288 {
2289 strm.PutChar(text[i]);
2290 chars_left--;
2291 }
2292
2293 }
2294
2295 strm.EOL();
2296 strm.IndentLess(indent_size);
2297}
2298
2299void
Chris Lattner24943d22010-06-08 16:52:24 +00002300CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
2301 StringList &commands_found, StringList &commands_help)
2302{
2303 CommandObject::CommandMap::const_iterator pos;
2304 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
2305 CommandObject *sub_cmd_obj;
2306
2307 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
2308 {
2309 const char * command_name = pos->first.c_str();
2310 sub_cmd_obj = pos->second.get();
2311 StreamString complete_command_name;
2312
2313 complete_command_name.Printf ("%s %s", prefix, command_name);
2314
Greg Clayton238c0a12010-09-18 01:14:36 +00002315 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002316 {
2317 commands_found.AppendString (complete_command_name.GetData());
2318 commands_help.AppendString (sub_cmd_obj->GetHelp());
2319 }
2320
2321 if (sub_cmd_obj->IsMultiwordObject())
2322 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
2323 commands_help);
2324 }
2325
2326}
2327
2328void
2329CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2330 StringList &commands_help)
2331{
2332 CommandObject::CommandMap::const_iterator pos;
2333
2334 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2335 {
2336 const char *command_name = pos->first.c_str();
2337 CommandObject *cmd_obj = pos->second.get();
2338
Greg Clayton238c0a12010-09-18 01:14:36 +00002339 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002340 {
2341 commands_found.AppendString (command_name);
2342 commands_help.AppendString (cmd_obj->GetHelp());
2343 }
2344
2345 if (cmd_obj->IsMultiwordObject())
2346 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
2347
2348 }
2349}
Greg Claytonb72d0f02011-04-12 05:54:46 +00002350
2351
2352void
2353CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2354{
2355 m_exe_ctx.Clear();
2356
2357 if (override_context != NULL)
2358 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002359 m_exe_ctx = *override_context;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002360 }
2361 else
2362 {
2363 TargetSP target_sp (m_debugger.GetSelectedTarget());
2364 if (target_sp)
2365 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002366 m_exe_ctx.SetTargetSP (target_sp);
2367 ProcessSP process_sp (target_sp->GetProcessSP());
2368 m_exe_ctx.SetProcessSP (process_sp);
2369 if (process_sp && process_sp->IsAlive() && !process_sp->IsRunning())
Greg Claytonb72d0f02011-04-12 05:54:46 +00002370 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002371 ThreadSP thread_sp (process_sp->GetThreadList().GetSelectedThread().get());
2372 if (thread_sp)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002373 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002374 m_exe_ctx.SetThreadSP (thread_sp);
2375 StackFrameSP frame_sp (thread_sp->GetSelectedFrame());
2376 if (!frame_sp)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002377 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002378 frame_sp = thread_sp->GetStackFrameAtIndex (0);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002379 // If we didn't have a selected frame select one here.
Greg Clayton567e7f32011-09-22 04:58:26 +00002380 if (frame_sp)
2381 thread_sp->SetSelectedFrame(frame_sp.get());
Greg Claytonb72d0f02011-04-12 05:54:46 +00002382 }
Greg Clayton567e7f32011-09-22 04:58:26 +00002383 if (frame_sp)
2384 m_exe_ctx.SetFrameSP (frame_sp);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002385 }
2386 }
2387 }
2388 }
2389}
2390
Jim Ingham6247dbe2011-07-12 03:12:18 +00002391void
2392CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2393{
2394 DumpHistory (stream, 0, count - 1);
2395}
2396
2397void
2398CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2399{
2400 size_t num_history_elements = m_command_history.size();
2401 if (start > num_history_elements)
2402 return;
2403 for (uint32_t i = start; i < num_history_elements && i <= end; i++)
2404 {
2405 if (!m_command_history[i].empty())
2406 {
2407 stream.Indent();
2408 stream.Printf ("%4d: %s\n", i, m_command_history[i].c_str());
2409 }
2410 }
2411}
2412
2413const char *
2414CommandInterpreter::FindHistoryString (const char *input_str) const
2415{
2416 if (input_str[0] != m_repeat_char)
2417 return NULL;
2418 if (input_str[1] == '-')
2419 {
2420 bool success;
2421 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
2422 if (!success)
2423 return NULL;
2424 if (idx > m_command_history.size())
2425 return NULL;
2426 idx = m_command_history.size() - idx;
2427 return m_command_history[idx].c_str();
2428
2429 }
2430 else if (input_str[1] == m_repeat_char)
2431 {
2432 if (m_command_history.empty())
2433 return NULL;
2434 else
2435 return m_command_history.back().c_str();
2436 }
2437 else
2438 {
2439 bool success;
2440 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2441 if (!success)
2442 return NULL;
2443 if (idx >= m_command_history.size())
2444 return NULL;
2445 return m_command_history[idx].c_str();
2446 }
2447}