blob: 9fde66e4dbaca3a4917616315556071a9e7415bf [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"
Enrico Granata6d101882012-09-28 23:57:51 +000029#include "../Commands/CommandObjectPlugin.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000030#include "../Commands/CommandObjectProcess.h"
31#include "../Commands/CommandObjectQuit.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000032#include "../Commands/CommandObjectRegister.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000033#include "../Commands/CommandObjectSettings.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000034#include "../Commands/CommandObjectSource.h"
Jim Ingham767af882010-07-07 03:36:20 +000035#include "../Commands/CommandObjectCommands.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000036#include "../Commands/CommandObjectSyntax.h"
37#include "../Commands/CommandObjectTarget.h"
38#include "../Commands/CommandObjectThread.h"
Greg Clayton5c28dd12011-06-23 17:59:56 +000039#include "../Commands/CommandObjectType.h"
Johnny Chen902e0182010-12-23 20:21:44 +000040#include "../Commands/CommandObjectVersion.h"
Johnny Chen01acfa72011-09-22 18:04:58 +000041#include "../Commands/CommandObjectWatchpoint.h"
Chris Lattner24943d22010-06-08 16:52:24 +000042
Chris Lattner24943d22010-06-08 16:52:24 +000043#include "lldb/Core/Debugger.h"
Jim Ingham5e16ef52010-10-04 19:49:29 +000044#include "lldb/Core/InputReader.h"
Enrico Granatadb054912012-10-29 21:18:03 +000045#include "lldb/Core/Log.h"
Chris Lattner24943d22010-06-08 16:52:24 +000046#include "lldb/Core/Stream.h"
47#include "lldb/Core/Timer.h"
Enrico Granatadb054912012-10-29 21:18:03 +000048
Greg Claytoncd548032011-02-01 01:31:41 +000049#include "lldb/Host/Host.h"
Enrico Granatadb054912012-10-29 21:18:03 +000050
51#include "lldb/Interpreter/Args.h"
52#include "lldb/Interpreter/CommandReturnObject.h"
53#include "lldb/Interpreter/CommandInterpreter.h"
54#include "lldb/Interpreter/Options.h"
55#include "lldb/Interpreter/ScriptInterpreterNone.h"
56#include "lldb/Interpreter/ScriptInterpreterPython.h"
57
58
Chris Lattner24943d22010-06-08 16:52:24 +000059#include "lldb/Target/Process.h"
60#include "lldb/Target/Thread.h"
61#include "lldb/Target/TargetList.h"
62
Enrico Granatadb054912012-10-29 21:18:03 +000063#include "lldb/Utility/CleanUp.h"
Chris Lattner24943d22010-06-08 16:52:24 +000064
65using namespace lldb;
66using namespace lldb_private;
67
Greg Clayton9f282852012-08-23 00:22:02 +000068
69static PropertyDefinition
70g_properties[] =
71{
72 { "expand-regex-aliases", OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, regular expression alias commands will show the expanded command that will be executed. This can be used to debug new regular expression alias commands." },
73 { NULL , OptionValue::eTypeInvalid, true, 0 , NULL, NULL, NULL }
74};
75
76enum
77{
78 ePropertyExpandRegexAliases = 0
79};
80
Jim Ingham5a15e692012-02-16 06:50:00 +000081ConstString &
82CommandInterpreter::GetStaticBroadcasterClass ()
83{
84 static ConstString class_name ("lldb.commandInterpreter");
85 return class_name;
86}
87
Chris Lattner24943d22010-06-08 16:52:24 +000088CommandInterpreter::CommandInterpreter
89(
Greg Clayton63094e02010-06-23 01:19:29 +000090 Debugger &debugger,
Chris Lattner24943d22010-06-08 16:52:24 +000091 ScriptLanguage script_language,
Greg Clayton63094e02010-06-23 01:19:29 +000092 bool synchronous_execution
Chris Lattner24943d22010-06-08 16:52:24 +000093) :
Jim Ingham5a15e692012-02-16 06:50:00 +000094 Broadcaster (&debugger, "lldb.command-interpreter"),
Greg Clayton9f282852012-08-23 00:22:02 +000095 Properties(OptionValuePropertiesSP(new OptionValueProperties(ConstString("interpreter")))),
Greg Clayton63094e02010-06-23 01:19:29 +000096 m_debugger (debugger),
Greg Clayton887aa282010-10-11 01:05:37 +000097 m_synchronous_execution (synchronous_execution),
Caroline Tice0aa2e552011-01-14 00:29:16 +000098 m_skip_lldbinit_files (false),
Jim Ingham574c3d62011-08-12 23:34:31 +000099 m_skip_app_init_files (false),
Jim Ingham949d5ac2011-02-18 00:54:25 +0000100 m_script_interpreter_ap (),
Caroline Tice892fadd2011-06-16 16:27:19 +0000101 m_comment_char ('#'),
Jim Ingham6247dbe2011-07-12 03:12:18 +0000102 m_repeat_char ('!'),
Johnny Chen3908bb12012-08-09 22:06:10 +0000103 m_batch_command_mode (false),
Enrico Granata01bc2d42012-05-31 01:09:06 +0000104 m_truncation_warning(eNoTruncation),
105 m_command_source_depth (0)
Chris Lattner24943d22010-06-08 16:52:24 +0000106{
Greg Clayton73844aa2012-08-22 17:17:09 +0000107 debugger.SetScriptLanguage (script_language);
Greg Clayton49ce6822010-10-31 03:01:06 +0000108 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
109 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
Greg Clayton73844aa2012-08-22 17:17:09 +0000110 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Jim Ingham5a15e692012-02-16 06:50:00 +0000111 CheckInWithManager ();
Greg Clayton9f282852012-08-23 00:22:02 +0000112 m_collection_sp->Initialize (g_properties);
Chris Lattner24943d22010-06-08 16:52:24 +0000113}
114
Greg Clayton9f282852012-08-23 00:22:02 +0000115bool
116CommandInterpreter::GetExpandRegexAliases () const
117{
118 const uint32_t idx = ePropertyExpandRegexAliases;
119 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
120}
121
122
123
Chris Lattner24943d22010-06-08 16:52:24 +0000124void
125CommandInterpreter::Initialize ()
126{
127 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
128
129 CommandReturnObject result;
130
131 LoadCommandDictionary ();
132
Chris Lattner24943d22010-06-08 16:52:24 +0000133 // Set up some initial aliases.
Caroline Tice5ddbe212011-05-06 21:37:15 +0000134 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
135 if (cmd_obj_sp)
136 {
137 AddAlias ("q", cmd_obj_sp);
138 AddAlias ("exit", cmd_obj_sp);
139 }
Sean Callananfc58af22012-05-04 23:15:02 +0000140
Johnny Chena47e44b2012-08-24 18:15:45 +0000141 cmd_obj_sp = GetCommandSPExact ("_regexp-attach",false);
Sean Callananfc58af22012-05-04 23:15:02 +0000142 if (cmd_obj_sp)
143 {
144 AddAlias ("attach", cmd_obj_sp);
145 }
Caroline Tice5ddbe212011-05-06 21:37:15 +0000146
Johnny Chena47e44b2012-08-24 18:15:45 +0000147 cmd_obj_sp = GetCommandSPExact ("process detach",false);
148 if (cmd_obj_sp)
149 {
150 AddAlias ("detach", cmd_obj_sp);
151 }
152
Caroline Tice5ddbe212011-05-06 21:37:15 +0000153 cmd_obj_sp = GetCommandSPExact ("process continue", false);
154 if (cmd_obj_sp)
155 {
156 AddAlias ("c", cmd_obj_sp);
157 AddAlias ("continue", cmd_obj_sp);
158 }
159
160 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
161 if (cmd_obj_sp)
162 AddAlias ("b", cmd_obj_sp);
163
Jim Ingham2753a022012-10-05 19:16:31 +0000164 cmd_obj_sp = GetCommandSPExact ("_regexp-tbreak",false);
165 if (cmd_obj_sp)
166 AddAlias ("tbreak", cmd_obj_sp);
167
Caroline Tice5ddbe212011-05-06 21:37:15 +0000168 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
169 if (cmd_obj_sp)
Jason Molenda47eb00e2011-10-22 00:47:41 +0000170 {
171 AddAlias ("stepi", cmd_obj_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000172 AddAlias ("si", cmd_obj_sp);
Jason Molenda47eb00e2011-10-22 00:47:41 +0000173 }
174
175 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
176 if (cmd_obj_sp)
177 {
178 AddAlias ("nexti", cmd_obj_sp);
179 AddAlias ("ni", cmd_obj_sp);
180 }
Caroline Tice5ddbe212011-05-06 21:37:15 +0000181
182 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
183 if (cmd_obj_sp)
184 {
185 AddAlias ("s", cmd_obj_sp);
186 AddAlias ("step", cmd_obj_sp);
187 }
188
189 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
190 if (cmd_obj_sp)
191 {
192 AddAlias ("n", cmd_obj_sp);
193 AddAlias ("next", cmd_obj_sp);
194 }
195
196 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
197 if (cmd_obj_sp)
198 {
Caroline Tice5ddbe212011-05-06 21:37:15 +0000199 AddAlias ("finish", cmd_obj_sp);
200 }
201
Jim Ingham59355252011-12-02 01:12:59 +0000202 cmd_obj_sp = GetCommandSPExact ("frame select", false);
203 if (cmd_obj_sp)
204 {
205 AddAlias ("f", cmd_obj_sp);
206 }
207
Jim Ingham2753a022012-10-05 19:16:31 +0000208 cmd_obj_sp = GetCommandSPExact ("thread select", false);
209 if (cmd_obj_sp)
210 {
211 AddAlias ("t", cmd_obj_sp);
212 }
213
Caroline Tice5ddbe212011-05-06 21:37:15 +0000214 cmd_obj_sp = GetCommandSPExact ("source list", false);
215 if (cmd_obj_sp)
216 {
217 AddAlias ("l", cmd_obj_sp);
218 AddAlias ("list", cmd_obj_sp);
219 }
220
221 cmd_obj_sp = GetCommandSPExact ("memory read", false);
222 if (cmd_obj_sp)
223 AddAlias ("x", cmd_obj_sp);
224
225 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
226 if (cmd_obj_sp)
227 AddAlias ("up", cmd_obj_sp);
228
229 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
230 if (cmd_obj_sp)
231 AddAlias ("down", cmd_obj_sp);
232
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000233 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000234 if (cmd_obj_sp)
235 AddAlias ("display", cmd_obj_sp);
Jim Ingham9d1acc12011-10-24 18:37:00 +0000236
237 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
238 if (cmd_obj_sp)
239 AddAlias ("dis", cmd_obj_sp);
240
241 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
242 if (cmd_obj_sp)
243 AddAlias ("di", cmd_obj_sp);
244
245
Jason Molenda730cae02011-10-22 01:30:52 +0000246
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000247 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000248 if (cmd_obj_sp)
249 AddAlias ("undisplay", cmd_obj_sp);
250
Jim Inghamf190a412012-10-10 16:51:31 +0000251 cmd_obj_sp = GetCommandSPExact ("_regexp-bt", false);
252 if (cmd_obj_sp)
253 AddAlias ("bt", cmd_obj_sp);
254
Caroline Tice5ddbe212011-05-06 21:37:15 +0000255 cmd_obj_sp = GetCommandSPExact ("target create", false);
256 if (cmd_obj_sp)
257 AddAlias ("file", cmd_obj_sp);
258
259 cmd_obj_sp = GetCommandSPExact ("target modules", false);
260 if (cmd_obj_sp)
261 AddAlias ("image", cmd_obj_sp);
262
263
264 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghame56493f2011-03-22 02:29:32 +0000265
Caroline Tice5ddbe212011-05-06 21:37:15 +0000266 cmd_obj_sp = GetCommandSPExact ("expression", false);
267 if (cmd_obj_sp)
268 {
269 AddAlias ("expr", cmd_obj_sp);
270
271 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
272 AddAlias ("p", cmd_obj_sp);
273 AddAlias ("print", cmd_obj_sp);
Sean Callanan59959eb2012-08-08 01:30:34 +0000274 AddAlias ("call", cmd_obj_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000275 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
276 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
Sean Callanan59959eb2012-08-08 01:30:34 +0000277 AddOrReplaceAliasOptions ("call", alias_arguments_vector_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000278
279 alias_arguments_vector_sp.reset (new OptionArgVector);
280 ProcessAliasOptionsArgs (cmd_obj_sp, "-o --", alias_arguments_vector_sp);
281 AddAlias ("po", cmd_obj_sp);
282 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
283 }
284
Sean Callananee301fa2012-06-01 23:29:32 +0000285 cmd_obj_sp = GetCommandSPExact ("process kill", false);
286 if (cmd_obj_sp)
Greg Claytonf2e53a52012-09-27 00:02:27 +0000287 {
Sean Callananee301fa2012-06-01 23:29:32 +0000288 AddAlias ("kill", cmd_obj_sp);
Greg Claytonf2e53a52012-09-27 00:02:27 +0000289 }
Sean Callananee301fa2012-06-01 23:29:32 +0000290
Caroline Tice5ddbe212011-05-06 21:37:15 +0000291 cmd_obj_sp = GetCommandSPExact ("process launch", false);
292 if (cmd_obj_sp)
293 {
294 alias_arguments_vector_sp.reset (new OptionArgVector);
Jason Molenda36eb7c02012-07-06 02:46:23 +0000295#if defined (__arm__)
296 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
297#else
Greg Clayton86c50d72012-05-18 00:04:38 +0000298 ProcessAliasOptionsArgs (cmd_obj_sp, "--shell=/bin/bash --", alias_arguments_vector_sp);
Jason Molenda36eb7c02012-07-06 02:46:23 +0000299#endif
Caroline Tice5ddbe212011-05-06 21:37:15 +0000300 AddAlias ("r", cmd_obj_sp);
301 AddAlias ("run", cmd_obj_sp);
302 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
303 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
304 }
Greg Claytonc84623f2012-03-29 21:47:51 +0000305
306 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
307 if (cmd_obj_sp)
308 {
309 AddAlias ("add-dsym", cmd_obj_sp);
310 }
Sean Callanan7b71b172012-05-21 18:25:19 +0000311
312 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
313 if (cmd_obj_sp)
314 {
315 alias_arguments_vector_sp.reset (new OptionArgVector);
316 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
Jim Ingham2657b6b2012-10-18 23:24:12 +0000317 AddAlias ("rbreak", cmd_obj_sp);
318 AddOrReplaceAliasOptions("rbreak", alias_arguments_vector_sp);
Sean Callanan7b71b172012-05-21 18:25:19 +0000319 }
Chris Lattner24943d22010-06-08 16:52:24 +0000320}
321
Chris Lattner24943d22010-06-08 16:52:24 +0000322const char *
323CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
324{
325 // This function has not yet been implemented.
326
327 // Look for any embedded script command
328 // If found,
329 // get interpreter object from the command dictionary,
330 // call execute_one_command on it,
331 // get the results as a string,
332 // substitute that string for current stuff.
333
334 return arg;
335}
336
337
338void
339CommandInterpreter::LoadCommandDictionary ()
340{
341 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
342
343 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
344 //
345 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
346 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
347 // the cross-referencing stuff) are created!!!
348 //
349 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
350
351
352 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
353 // are created. This is so that when another command is created that needs to go into a crossref object,
354 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
355 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
356
Chris Lattner24943d22010-06-08 16:52:24 +0000357 // Non-CommandObjectCrossref commands can now be created.
358
Caroline Tice5bc8c972010-09-20 20:44:43 +0000359 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000360
Greg Clayton238c0a12010-09-18 01:14:36 +0000361 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000362 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000363 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000364 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000365 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
366 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Claytonabe0fed2011-04-18 08:33:37 +0000367// m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000368 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000369 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Claytone1f50b92011-05-03 22:09:39 +0000370 /// m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000371 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
372 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonb1888f22011-03-19 01:12:21 +0000373 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Enrico Granata6d101882012-09-28 23:57:51 +0000374 m_command_dict["plugin"] = CommandObjectSP (new CommandObjectPlugin (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000375 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000376 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000377 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000378 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000379 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000380 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000381 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
382 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata6b1596d2011-08-16 23:24:13 +0000383 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000384 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chen01acfa72011-09-22 18:04:58 +0000385 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000386
Jim Ingham2753a022012-10-05 19:16:31 +0000387 const char *break_regexes[][2] = {{"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2"},
388 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
389 {"^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
390 {"^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"},
391 {"^(-.*)$", "breakpoint set %1"},
392 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'"},
393 {"^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"}};
394
395 size_t num_regexes = sizeof break_regexes/sizeof(char *[2]);
396
Chris Lattner24943d22010-06-08 16:52:24 +0000397 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000398 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000399 "_regexp-break",
Johnny Chen58edac32012-08-23 00:32:22 +0000400 "Set a breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
401 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
Jim Ingham2753a022012-10-05 19:16:31 +0000402
Chris Lattner24943d22010-06-08 16:52:24 +0000403 if (break_regex_cmd_ap.get())
404 {
Jim Ingham2753a022012-10-05 19:16:31 +0000405 bool success = true;
406 for (size_t i = 0; i < num_regexes; i++)
407 {
408 success = break_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], break_regexes[i][1]);
409 if (!success)
410 break;
411 }
412 success = break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
413
414 if (success)
Chris Lattner24943d22010-06-08 16:52:24 +0000415 {
416 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
417 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
418 }
419 }
Jim Inghame56493f2011-03-22 02:29:32 +0000420
421 std::auto_ptr<CommandObjectRegexCommand>
Jim Ingham2753a022012-10-05 19:16:31 +0000422 tbreak_regex_cmd_ap(new CommandObjectRegexCommand (*this,
423 "_regexp-tbreak",
424 "Set a one shot breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
425 "_regexp-tbreak [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
426
427 if (tbreak_regex_cmd_ap.get())
428 {
429 bool success = true;
430 for (size_t i = 0; i < num_regexes; i++)
431 {
432 // If you add a resultant command string longer than 1024 characters be sure to increase the size of this buffer.
433 char buffer[1024];
434 int num_printed = snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o");
435 assert (num_printed < 1024);
436 success = tbreak_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], buffer);
437 if (!success)
438 break;
439 }
440 success = tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
441
442 if (success)
443 {
444 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
445 m_command_dict[tbreak_regex_cmd_sp->GetCommandName ()] = tbreak_regex_cmd_sp;
446 }
447 }
448
449 std::auto_ptr<CommandObjectRegexCommand>
Johnny Chena47e44b2012-08-24 18:15:45 +0000450 attach_regex_cmd_ap(new CommandObjectRegexCommand (*this,
451 "_regexp-attach",
452 "Attach to a process id if in decimal, otherwise treat the argument as a process name to attach to.",
453 "_regexp-attach [<pid>]\n_regexp-attach [<process-name>]", 2));
454 if (attach_regex_cmd_ap.get())
455 {
456 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "process attach --pid %1") &&
457 attach_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "process attach --name '%1'"))
458 {
459 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
460 m_command_dict[attach_regex_cmd_sp->GetCommandName ()] = attach_regex_cmd_sp;
461 }
462 }
463
464 std::auto_ptr<CommandObjectRegexCommand>
Jim Inghame56493f2011-03-22 02:29:32 +0000465 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000466 "_regexp-down",
467 "Go down \"n\" frames in the stack (1 frame by default).",
468 "_regexp-down [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000469 if (down_regex_cmd_ap.get())
470 {
471 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
472 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
473 {
474 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
475 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
476 }
477 }
478
479 std::auto_ptr<CommandObjectRegexCommand>
480 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000481 "_regexp-up",
482 "Go up \"n\" frames in the stack (1 frame by default).",
483 "_regexp-up [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000484 if (up_regex_cmd_ap.get())
485 {
486 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
487 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
488 {
489 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
490 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
491 }
492 }
Jason Molenda730cae02011-10-22 01:30:52 +0000493
494 std::auto_ptr<CommandObjectRegexCommand>
495 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000496 "_regexp-display",
Jason Molenda730cae02011-10-22 01:30:52 +0000497 "Add an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000498 "_regexp-display expression", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000499 if (display_regex_cmd_ap.get())
500 {
501 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
502 {
503 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
504 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
505 }
506 }
507
508 std::auto_ptr<CommandObjectRegexCommand>
509 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000510 "_regexp-undisplay",
Jason Molenda730cae02011-10-22 01:30:52 +0000511 "Remove an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000512 "_regexp-undisplay stop-hook-number", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000513 if (undisplay_regex_cmd_ap.get())
514 {
515 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
516 {
517 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
518 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
519 }
520 }
521
Greg Claytonc3750432012-09-26 22:26:47 +0000522 std::auto_ptr<CommandObjectRegexCommand>
523 connect_gdb_remote_cmd_ap(new CommandObjectRegexCommand (*this,
524 "gdb-remote",
Jason Molendade1edce2012-10-23 03:05:16 +0000525 "Connect to a remote GDB server. If no hostname is provided, localhost is assumed.",
526 "gdb-remote [<hostname>:]<portnum>", 2));
Greg Claytonc3750432012-09-26 22:26:47 +0000527 if (connect_gdb_remote_cmd_ap.get())
528 {
529 if (connect_gdb_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin gdb-remote connect://%1") &&
530 connect_gdb_remote_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "process connect --plugin gdb-remote connect://localhost:%1"))
531 {
532 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
533 m_command_dict[command_sp->GetCommandName ()] = command_sp;
534 }
535 }
536
537 std::auto_ptr<CommandObjectRegexCommand>
538 connect_kdp_remote_cmd_ap(new CommandObjectRegexCommand (*this,
539 "kdp-remote",
Jason Molendade1edce2012-10-23 03:05:16 +0000540 "Connect to a remote KDP server. udp port 41139 is the default port number.",
541 "kdp-remote <hostname>[:<portnum>]", 2));
Greg Claytonc3750432012-09-26 22:26:47 +0000542 if (connect_kdp_remote_cmd_ap.get())
543 {
544 if (connect_kdp_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin kdp-remote udp://%1") &&
Jason Molenda73feea42012-09-27 02:47:55 +0000545 connect_kdp_remote_cmd_ap->AddRegexCommand("^(.+)$", "process connect --plugin kdp-remote udp://%1:41139"))
Greg Claytonc3750432012-09-26 22:26:47 +0000546 {
547 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
548 m_command_dict[command_sp->GetCommandName ()] = command_sp;
549 }
550 }
551
Jason Molenda1a48cb72012-10-05 05:29:32 +0000552 std::auto_ptr<CommandObjectRegexCommand>
553 bt_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jim Inghamf190a412012-10-10 16:51:31 +0000554 "_regexp-bt",
Jason Molenda1a48cb72012-10-05 05:29:32 +0000555 "Show a backtrace. An optional argument is accepted; if that argument is a number, it specifies the number of frames to display. If that argument is 'all', full backtraces of all threads are displayed.",
556 "bt [<digit>|all]", 2));
557 if (bt_regex_cmd_ap.get())
558 {
559 // accept but don't document "bt -c <number>" -- before bt was a regex command if you wanted to backtrace
560 // three frames you would do "bt -c 3" but the intention is to have this emulate the gdb "bt" command and
561 // so now "bt 3" is the preferred form, in line with gdb.
562 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "thread backtrace -c %1") &&
563 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$", "thread backtrace -c %1") &&
564 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
565 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace"))
566 {
567 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
568 m_command_dict[command_sp->GetCommandName ()] = command_sp;
569 }
570 }
571
Chris Lattner24943d22010-06-08 16:52:24 +0000572}
573
574int
575CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
576 StringList &matches)
577{
578 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
579
580 if (include_aliases)
581 {
582 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
583 }
584
585 return matches.GetSize();
586}
587
588CommandObjectSP
589CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
590{
591 CommandObject::CommandMap::iterator pos;
592 CommandObjectSP ret_val;
593
594 std::string cmd(cmd_cstr);
595
596 if (HasCommands())
597 {
598 pos = m_command_dict.find(cmd);
599 if (pos != m_command_dict.end())
600 ret_val = pos->second;
601 }
602
603 if (include_aliases && HasAliases())
604 {
605 pos = m_alias_dict.find(cmd);
606 if (pos != m_alias_dict.end())
607 ret_val = pos->second;
608 }
609
610 if (HasUserCommands())
611 {
612 pos = m_user_dict.find(cmd);
613 if (pos != m_user_dict.end())
614 ret_val = pos->second;
615 }
616
Sean Callananb386d822012-08-09 00:50:26 +0000617 if (!exact && !ret_val)
Chris Lattner24943d22010-06-08 16:52:24 +0000618 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000619 // We will only get into here if we didn't find any exact matches.
620
621 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
622
Chris Lattner24943d22010-06-08 16:52:24 +0000623 StringList local_matches;
624 if (matches == NULL)
625 matches = &local_matches;
626
Jim Inghamd40f8a62010-07-06 22:46:59 +0000627 unsigned int num_cmd_matches = 0;
628 unsigned int num_alias_matches = 0;
629 unsigned int num_user_matches = 0;
630
631 // Look through the command dictionaries one by one, and if we get only one match from any of
632 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
633
Chris Lattner24943d22010-06-08 16:52:24 +0000634 if (HasCommands())
635 {
636 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
637 }
638
639 if (num_cmd_matches == 1)
640 {
641 cmd.assign(matches->GetStringAtIndex(0));
642 pos = m_command_dict.find(cmd);
643 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000644 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000645 }
646
Jim Ingham9a574172010-06-24 20:28:42 +0000647 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000648 {
649 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
650
651 }
652
Jim Inghamd40f8a62010-07-06 22:46:59 +0000653 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000654 {
655 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
656 pos = m_alias_dict.find(cmd);
657 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000658 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000659 }
660
Jim Ingham9a574172010-06-24 20:28:42 +0000661 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000662 {
663 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
664 }
665
Jim Inghamd40f8a62010-07-06 22:46:59 +0000666 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000667 {
668 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
669
670 pos = m_user_dict.find (cmd);
671 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000672 user_match_sp = pos->second;
673 }
674
675 // If we got exactly one match, return that, otherwise return the match list.
676
677 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
678 {
679 if (num_cmd_matches)
680 return real_match_sp;
681 else if (num_alias_matches)
682 return alias_match_sp;
683 else
684 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000685 }
686 }
Sean Callananb386d822012-08-09 00:50:26 +0000687 else if (matches && ret_val)
Jim Inghamd40f8a62010-07-06 22:46:59 +0000688 {
689 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000690 }
691
692
693 return ret_val;
694}
695
Greg Claytond12aeab2011-04-20 16:37:46 +0000696bool
697CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
698{
699 if (name && name[0])
700 {
701 std::string name_sstr(name);
Enrico Granata2f1014b2012-10-01 17:19:37 +0000702 bool found = (m_command_dict.find (name_sstr) != m_command_dict.end());
703 if (found && !can_replace)
704 return false;
705 if (found && m_command_dict[name_sstr]->IsRemovable() == false)
Enrico Granata6d101882012-09-28 23:57:51 +0000706 return false;
Greg Claytond12aeab2011-04-20 16:37:46 +0000707 m_command_dict[name_sstr] = cmd_sp;
708 return true;
709 }
710 return false;
711}
712
Enrico Granata6b1596d2011-08-16 23:24:13 +0000713bool
Enrico Granata6010ace2011-11-07 22:57:04 +0000714CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata6b1596d2011-08-16 23:24:13 +0000715 const lldb::CommandObjectSP &cmd_sp,
716 bool can_replace)
717{
Enrico Granata6010ace2011-11-07 22:57:04 +0000718 if (!name.empty())
Enrico Granata6b1596d2011-08-16 23:24:13 +0000719 {
Enrico Granata6010ace2011-11-07 22:57:04 +0000720
721 const char* name_cstr = name.c_str();
722
723 // do not allow replacement of internal commands
724 if (CommandExists(name_cstr))
Enrico Granata6d101882012-09-28 23:57:51 +0000725 {
726 if (can_replace == false)
727 return false;
728 if (m_command_dict[name]->IsRemovable() == false)
729 return false;
730 }
Enrico Granata6010ace2011-11-07 22:57:04 +0000731
Enrico Granata6d101882012-09-28 23:57:51 +0000732 if (UserCommandExists(name_cstr))
733 {
734 if (can_replace == false)
735 return false;
736 if (m_user_dict[name]->IsRemovable() == false)
737 return false;
738 }
739
Enrico Granata6010ace2011-11-07 22:57:04 +0000740 m_user_dict[name] = cmd_sp;
Enrico Granata6b1596d2011-08-16 23:24:13 +0000741 return true;
742 }
743 return false;
744}
Greg Claytond12aeab2011-04-20 16:37:46 +0000745
Jim Inghamd40f8a62010-07-06 22:46:59 +0000746CommandObjectSP
747CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000748{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000749 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
750 CommandObjectSP ret_val; // Possibly empty return value.
751
752 if (cmd_cstr == NULL)
753 return ret_val;
754
755 if (cmd_words.GetArgumentCount() == 1)
756 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
757 else
758 {
759 // We have a multi-word command (seemingly), so we need to do more work.
760 // First, get the cmd_obj_sp for the first word in the command.
761 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
762 if (cmd_obj_sp.get() != NULL)
763 {
764 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
765 // command name), and find the appropriate sub-command SP for each command word....
766 size_t end = cmd_words.GetArgumentCount();
767 for (size_t j= 1; j < end; ++j)
768 {
769 if (cmd_obj_sp->IsMultiwordObject())
770 {
Greg Clayton13193d52012-10-13 02:07:45 +0000771 cmd_obj_sp = cmd_obj_sp->GetSubcommandSP (cmd_words.GetArgumentAtIndex (j));
Caroline Tice56d2fc42010-12-14 18:51:39 +0000772 if (cmd_obj_sp.get() == NULL)
773 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
774 return ret_val;
775 }
776 else
777 // We have more words in the command name, but we don't have a multiword object. Fail and return
778 // empty 'ret_val'.
779 return ret_val;
780 }
781 // We successfully looped through all the command words and got valid command objects for them. Assign the
782 // last object retrieved to 'ret_val'.
783 ret_val = cmd_obj_sp;
784 }
785 }
786 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000787}
788
789CommandObject *
790CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
791{
792 return GetCommandSPExact (cmd_cstr, include_aliases).get();
793}
794
795CommandObject *
796CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
797{
798 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
799
800 // If we didn't find an exact match to the command string in the commands, look in
801 // the aliases.
802
803 if (command_obj == NULL)
804 {
805 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
806 }
807
808 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
809 // in both the commands and the aliases.
810
811 if (command_obj == NULL)
812 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
813
814 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000815}
816
817bool
818CommandInterpreter::CommandExists (const char *cmd)
819{
820 return m_command_dict.find(cmd) != m_command_dict.end();
821}
822
823bool
Caroline Tice5ddbe212011-05-06 21:37:15 +0000824CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
825 const char *options_args,
826 OptionArgVectorSP &option_arg_vector_sp)
827{
828 bool success = true;
829 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
830
831 if (!options_args || (strlen (options_args) < 1))
832 return true;
833
834 std::string options_string (options_args);
835 Args args (options_args);
836 CommandReturnObject result;
837 // Check to see if the command being aliased can take any command options.
838 Options *options = cmd_obj_sp->GetOptions ();
839 if (options)
840 {
841 // See if any options were specified as part of the alias; if so, handle them appropriately.
842 options->NotifyOptionParsingStarting ();
843 args.Unshift ("dummy_arg");
844 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
845 args.Shift ();
846 if (result.Succeeded())
847 options->VerifyPartialOptions (result);
848 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
849 {
850 result.AppendError ("Unable to create requested alias.\n");
851 return false;
852 }
853 }
854
Greg Clayton7268b4c2011-10-28 21:38:01 +0000855 if (!options_string.empty())
Caroline Tice5ddbe212011-05-06 21:37:15 +0000856 {
857 if (cmd_obj_sp->WantsRawCommandString ())
858 option_arg_vector->push_back (OptionArgPair ("<argument>",
859 OptionArgValue (-1,
860 options_string)));
861 else
862 {
863 int argc = args.GetArgumentCount();
864 for (size_t i = 0; i < argc; ++i)
865 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
866 option_arg_vector->push_back
867 (OptionArgPair ("<argument>",
868 OptionArgValue (-1,
869 std::string (args.GetArgumentAtIndex (i)))));
870 }
871 }
872
873 return success;
874}
875
876bool
Chris Lattner24943d22010-06-08 16:52:24 +0000877CommandInterpreter::AliasExists (const char *cmd)
878{
879 return m_alias_dict.find(cmd) != m_alias_dict.end();
880}
881
882bool
883CommandInterpreter::UserCommandExists (const char *cmd)
884{
885 return m_user_dict.find(cmd) != m_user_dict.end();
886}
887
888void
889CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
890{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000891 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000892 m_alias_dict[alias_name] = command_obj_sp;
893}
894
895bool
896CommandInterpreter::RemoveAlias (const char *alias_name)
897{
898 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
899 if (pos != m_alias_dict.end())
900 {
901 m_alias_dict.erase(pos);
902 return true;
903 }
904 return false;
905}
906bool
907CommandInterpreter::RemoveUser (const char *alias_name)
908{
909 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
910 if (pos != m_user_dict.end())
911 {
912 m_user_dict.erase(pos);
913 return true;
914 }
915 return false;
916}
917
Chris Lattner24943d22010-06-08 16:52:24 +0000918void
919CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
920{
921 help_string.Printf ("'%s", command_name);
922 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
923
Sean Callananb386d822012-08-09 00:50:26 +0000924 if (option_arg_vector_sp)
Chris Lattner24943d22010-06-08 16:52:24 +0000925 {
926 OptionArgVector *options = option_arg_vector_sp.get();
927 for (int i = 0; i < options->size(); ++i)
928 {
929 OptionArgPair cur_option = (*options)[i];
930 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000931 OptionArgValue value_pair = cur_option.second;
932 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000933 if (opt.compare("<argument>") == 0)
934 {
935 help_string.Printf (" %s", value.c_str());
936 }
937 else
938 {
939 help_string.Printf (" %s", opt.c_str());
940 if ((value.compare ("<no-argument>") != 0)
941 && (value.compare ("<need-argument") != 0))
942 {
943 help_string.Printf (" %s", value.c_str());
944 }
945 }
946 }
947 }
948
949 help_string.Printf ("'");
950}
951
Greg Clayton65124ea2010-08-26 22:05:43 +0000952size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000953CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
954{
955 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000956 CommandObject::CommandMap::const_iterator end = dict.end();
957 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000958
Greg Clayton65124ea2010-08-26 22:05:43 +0000959 for (pos = dict.begin(); pos != end; ++pos)
960 {
961 size_t len = pos->first.size();
962 if (max_len < len)
963 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000964 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000965 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000966}
967
968void
Enrico Granata6b1596d2011-08-16 23:24:13 +0000969CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata1ac6d1f2011-09-09 17:49:36 +0000970 uint32_t cmd_types)
Chris Lattner24943d22010-06-08 16:52:24 +0000971{
972 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000973 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata6b1596d2011-08-16 23:24:13 +0000974
975 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner24943d22010-06-08 16:52:24 +0000976 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000977
978 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
979 result.AppendMessage("");
Chris Lattner24943d22010-06-08 16:52:24 +0000980
Enrico Granata6b1596d2011-08-16 23:24:13 +0000981 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
982 {
983 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
984 max_len);
985 }
986 result.AppendMessage("");
987
988 }
989
Greg Clayton7268b4c2011-10-28 21:38:01 +0000990 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner24943d22010-06-08 16:52:24 +0000991 {
Jim Inghame3663e82010-10-22 18:47:16 +0000992 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000993 "(see 'help command alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000994 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000995 max_len = FindLongestCommandWord (m_alias_dict);
996
Chris Lattner24943d22010-06-08 16:52:24 +0000997 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
998 {
999 StreamString sstr;
1000 StreamString translation_and_help;
1001 std::string entry_name = pos->first;
1002 std::string second_entry = pos->second.get()->GetCommandName();
1003 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
1004
1005 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
1006 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
1007 translation_and_help.GetData(), max_len);
1008 }
1009 result.AppendMessage("");
1010 }
1011
Greg Clayton7268b4c2011-10-28 21:38:01 +00001012 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner24943d22010-06-08 16:52:24 +00001013 {
1014 result.AppendMessage ("The following is a list of your current user-defined commands:");
1015 result.AppendMessage("");
Enrico Granata6b1596d2011-08-16 23:24:13 +00001016 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner24943d22010-06-08 16:52:24 +00001017 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
1018 {
Enrico Granata6b1596d2011-08-16 23:24:13 +00001019 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1020 max_len);
Chris Lattner24943d22010-06-08 16:52:24 +00001021 }
1022 result.AppendMessage("");
1023 }
1024
1025 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
1026}
1027
Caroline Ticee0da7a52010-12-09 22:52:49 +00001028CommandObject *
1029CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +00001030{
Caroline Ticee0da7a52010-12-09 22:52:49 +00001031 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
1032 // eventually be invoked by the given command line.
1033
1034 CommandObject *cmd_obj = NULL;
1035 std::string white_space (" \t\v");
1036 size_t start = command_string.find_first_not_of (white_space);
1037 size_t end = 0;
1038 bool done = false;
1039 while (!done)
1040 {
1041 if (start != std::string::npos)
1042 {
1043 // Get the next word from command_string.
1044 end = command_string.find_first_of (white_space, start);
1045 if (end == std::string::npos)
1046 end = command_string.size();
1047 std::string cmd_word = command_string.substr (start, end - start);
1048
1049 if (cmd_obj == NULL)
1050 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
1051 // command or alias.
1052 cmd_obj = GetCommandObject (cmd_word.c_str());
1053 else if (cmd_obj->IsMultiwordObject ())
1054 {
1055 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
Greg Clayton13193d52012-10-13 02:07:45 +00001056 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (cmd_word.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001057 if (sub_cmd_obj)
1058 cmd_obj = sub_cmd_obj;
1059 else // cmd_word was not a valid sub-command word, so we are donee
1060 done = true;
1061 }
1062 else
1063 // We have a cmd_obj and it is not a multi-word object, so we are done.
1064 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001065
Caroline Ticee0da7a52010-12-09 22:52:49 +00001066 // If we didn't find a valid command object, or our command object is not a multi-word object, or
1067 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
1068 // next word.
1069
1070 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
1071 done = true;
1072 else
1073 start = command_string.find_first_not_of (white_space, end);
1074 }
1075 else
1076 // Unable to find any more words.
1077 done = true;
1078 }
1079
1080 if (end == command_string.size())
1081 command_string.clear();
1082 else
1083 command_string = command_string.substr(end);
1084
1085 return cmd_obj;
1086}
1087
Greg Clayton9d855c62011-10-25 00:36:27 +00001088static const char *k_white_space = " \t\v";
Greg Clayton7268b4c2011-10-28 21:38:01 +00001089static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton9d855c62011-10-25 00:36:27 +00001090static void
1091StripLeadingSpaces (std::string &s)
Caroline Ticee0da7a52010-12-09 22:52:49 +00001092{
Greg Clayton9d855c62011-10-25 00:36:27 +00001093 if (!s.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +00001094 {
Greg Clayton9d855c62011-10-25 00:36:27 +00001095 size_t pos = s.find_first_not_of (k_white_space);
1096 if (pos == std::string::npos)
1097 s.clear();
1098 else if (pos == 0)
1099 return;
1100 s.erase (0, pos);
1101 }
1102}
1103
Greg Clayton3840cd72011-11-09 23:25:03 +00001104static size_t
1105FindArgumentTerminator (const std::string &s)
1106{
Greg Clayton3840cd72011-11-09 23:25:03 +00001107 const size_t s_len = s.size();
1108 size_t offset = 0;
1109 while (offset < s_len)
1110 {
1111 size_t pos = s.find ("--", offset);
1112 if (pos == std::string::npos)
1113 break;
1114 if (pos > 0)
1115 {
1116 if (isspace(s[pos-1]))
1117 {
1118 // Check if the string ends "\s--" (where \s is a space character)
1119 // or if we have "\s--\s".
1120 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
1121 {
Greg Clayton3840cd72011-11-09 23:25:03 +00001122 return pos;
1123 }
1124 }
1125 }
1126 offset = pos + 2;
1127 }
Greg Clayton3840cd72011-11-09 23:25:03 +00001128 return std::string::npos;
1129}
1130
Greg Clayton9d855c62011-10-25 00:36:27 +00001131static bool
Greg Clayton7268b4c2011-10-28 21:38:01 +00001132ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton9d855c62011-10-25 00:36:27 +00001133{
Greg Clayton7268b4c2011-10-28 21:38:01 +00001134 command.clear();
1135 suffix.clear();
Greg Clayton9d855c62011-10-25 00:36:27 +00001136 StripLeadingSpaces (command_string);
1137
1138 bool result = false;
1139 quote_char = '\0';
1140
1141 if (!command_string.empty())
1142 {
1143 const char first_char = command_string[0];
1144 if (first_char == '\'' || first_char == '"')
Caroline Ticee0da7a52010-12-09 22:52:49 +00001145 {
Greg Clayton9d855c62011-10-25 00:36:27 +00001146 quote_char = first_char;
1147 const size_t end_quote_pos = command_string.find (quote_char, 1);
1148 if (end_quote_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +00001149 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001150 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +00001151 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +00001152 }
1153 else
1154 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001155 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton9d855c62011-10-25 00:36:27 +00001156 if (end_quote_pos + 1 < command_string.size())
1157 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
1158 else
1159 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +00001160 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001161 }
1162 else
1163 {
Greg Clayton9d855c62011-10-25 00:36:27 +00001164 const size_t first_space_pos = command_string.find_first_of (k_white_space);
1165 if (first_space_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +00001166 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001167 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +00001168 command_string.erase();
Caroline Tice649116c2011-05-11 16:07:06 +00001169 }
1170 else
1171 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001172 command.assign (command_string, 0, first_space_pos);
1173 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice649116c2011-05-11 16:07:06 +00001174 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001175 }
Greg Clayton9d855c62011-10-25 00:36:27 +00001176 result = true;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001177 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001178
1179
1180 if (!command.empty())
1181 {
1182 // actual commands can't start with '-' or '_'
1183 if (command[0] != '-' && command[0] != '_')
1184 {
1185 size_t pos = command.find_first_not_of(k_valid_command_chars);
1186 if (pos > 0 && pos != std::string::npos)
1187 {
1188 suffix.assign (command.begin() + pos, command.end());
1189 command.erase (pos);
1190 }
1191 }
1192 }
Greg Clayton9d855c62011-10-25 00:36:27 +00001193
1194 return result;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001195}
1196
Greg Clayton7268b4c2011-10-28 21:38:01 +00001197CommandObject *
1198CommandInterpreter::BuildAliasResult (const char *alias_name,
1199 std::string &raw_input_string,
1200 std::string &alias_result,
1201 CommandReturnObject &result)
Caroline Ticee0da7a52010-12-09 22:52:49 +00001202{
Greg Clayton7268b4c2011-10-28 21:38:01 +00001203 CommandObject *alias_cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001204 Args cmd_args (raw_input_string.c_str());
1205 alias_cmd_obj = GetCommandObject (alias_name);
1206 StreamString result_str;
1207
1208 if (alias_cmd_obj)
1209 {
1210 std::string alias_name_str = alias_name;
1211 if ((cmd_args.GetArgumentCount() == 0)
1212 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1213 cmd_args.Unshift (alias_name);
1214
1215 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1216 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1217
1218 if (option_arg_vector_sp.get())
1219 {
1220 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1221
1222 for (int i = 0; i < option_arg_vector->size(); ++i)
1223 {
1224 OptionArgPair option_pair = (*option_arg_vector)[i];
1225 OptionArgValue value_pair = option_pair.second;
1226 int value_type = value_pair.first;
1227 std::string option = option_pair.first;
1228 std::string value = value_pair.second;
1229 if (option.compare ("<argument>") == 0)
1230 result_str.Printf (" %s", value.c_str());
1231 else
1232 {
1233 result_str.Printf (" %s", option.c_str());
1234 if (value_type != optional_argument)
1235 result_str.Printf (" ");
1236 if (value.compare ("<no_argument>") != 0)
1237 {
1238 int index = GetOptionArgumentPosition (value.c_str());
1239 if (index == 0)
1240 result_str.Printf ("%s", value.c_str());
1241 else if (index >= cmd_args.GetArgumentCount())
1242 {
1243
1244 result.AppendErrorWithFormat
1245 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1246 index);
1247 result.SetStatus (eReturnStatusFailed);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001248 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001249 }
1250 else
1251 {
1252 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1253 if (strpos != std::string::npos)
1254 raw_input_string = raw_input_string.erase (strpos,
1255 strlen (cmd_args.GetArgumentAtIndex (index)));
1256 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1257 }
1258 }
1259 }
1260 }
1261 }
1262
1263 alias_result = result_str.GetData();
1264 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001265 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001266}
1267
Greg Claytonf5c0c722011-10-14 07:41:33 +00001268Error
1269CommandInterpreter::PreprocessCommand (std::string &command)
1270{
1271 // The command preprocessor needs to do things to the command
1272 // line before any parsing of arguments or anything else is done.
1273 // The only current stuff that gets proprocessed is anyting enclosed
1274 // in backtick ('`') characters is evaluated as an expression and
1275 // the result of the expression must be a scalar that can be substituted
1276 // into the command. An example would be:
1277 // (lldb) memory read `$rsp + 20`
1278 Error error; // Error for any expressions that might not evaluate
1279 size_t start_backtick;
1280 size_t pos = 0;
1281 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1282 {
1283 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1284 {
1285 // The backtick was preceeded by a '\' character, remove the slash
1286 // and don't treat the backtick as the start of an expression
1287 command.erase(start_backtick-1, 1);
1288 // No need to add one to start_backtick since we just deleted a char
1289 pos = start_backtick;
1290 }
1291 else
1292 {
1293 const size_t expr_content_start = start_backtick + 1;
1294 const size_t end_backtick = command.find ('`', expr_content_start);
1295 if (end_backtick == std::string::npos)
1296 return error;
1297 else if (end_backtick == expr_content_start)
1298 {
1299 // Empty expression (two backticks in a row)
1300 command.erase (start_backtick, 2);
1301 }
1302 else
1303 {
1304 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1305
Greg Claytonbcaf99a2012-07-12 20:32:19 +00001306 ExecutionContext exe_ctx(GetExecutionContext());
1307 Target *target = exe_ctx.GetTargetPtr();
Johnny Chenb09f8472011-10-29 00:21:50 +00001308 // Get a dummy target to allow for calculator mode while processing backticks.
1309 // This also helps break the infinite loop caused when target is null.
1310 if (!target)
1311 target = Host::GetDummyTarget(GetDebugger()).get();
Greg Claytonf5c0c722011-10-14 07:41:33 +00001312 if (target)
1313 {
Greg Claytonf5c0c722011-10-14 07:41:33 +00001314 ValueObjectSP expr_result_valobj_sp;
Enrico Granatad27026e2012-09-05 20:41:26 +00001315
Jim Ingham47beabb2012-10-16 21:41:58 +00001316 EvaluateExpressionOptions options;
Enrico Granatad27026e2012-09-05 20:41:26 +00001317 options.SetCoerceToId(false)
1318 .SetUnwindOnError(true)
1319 .SetKeepInMemory(false)
Jim Ingham47beabb2012-10-16 21:41:58 +00001320 .SetRunOthers(true)
1321 .SetTimeoutUsec(0);
Enrico Granatad27026e2012-09-05 20:41:26 +00001322
Greg Claytonf5c0c722011-10-14 07:41:33 +00001323 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
Enrico Granatad27026e2012-09-05 20:41:26 +00001324 exe_ctx.GetFramePtr(),
Enrico Granata6cca9692012-07-16 23:10:35 +00001325 expr_result_valobj_sp,
Enrico Granatad27026e2012-09-05 20:41:26 +00001326 options);
1327
Greg Claytonf5c0c722011-10-14 07:41:33 +00001328 if (expr_result == eExecutionCompleted)
1329 {
1330 Scalar scalar;
1331 if (expr_result_valobj_sp->ResolveValue (scalar))
1332 {
1333 command.erase (start_backtick, end_backtick - start_backtick + 1);
1334 StreamString value_strm;
1335 const bool show_type = false;
1336 scalar.GetValue (&value_strm, show_type);
1337 size_t value_string_size = value_strm.GetSize();
1338 if (value_string_size)
1339 {
1340 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1341 pos = start_backtick + value_string_size;
1342 continue;
1343 }
1344 else
1345 {
1346 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1347 }
1348 }
1349 else
1350 {
1351 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1352 }
1353 }
1354 else
1355 {
1356 if (expr_result_valobj_sp)
1357 error = expr_result_valobj_sp->GetError();
1358 if (error.Success())
1359 {
1360
1361 switch (expr_result)
1362 {
1363 case eExecutionSetupError:
1364 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1365 break;
1366 case eExecutionCompleted:
1367 break;
1368 case eExecutionDiscarded:
1369 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1370 break;
1371 case eExecutionInterrupted:
1372 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1373 break;
1374 case eExecutionTimedOut:
1375 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1376 break;
1377 }
1378 }
1379 }
1380 }
1381 }
1382 if (error.Fail())
1383 break;
1384 }
1385 }
1386 return error;
1387}
1388
1389
Caroline Ticee0da7a52010-12-09 22:52:49 +00001390bool
1391CommandInterpreter::HandleCommand (const char *command_line,
Enrico Granata01bc2d42012-05-31 01:09:06 +00001392 LazyBool lazy_add_to_history,
Caroline Ticee0da7a52010-12-09 22:52:49 +00001393 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001394 ExecutionContext *override_context,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001395 bool repeat_on_empty_command,
1396 bool no_context_switching)
Jim Ingham949d5ac2011-02-18 00:54:25 +00001397
Caroline Ticee0da7a52010-12-09 22:52:49 +00001398{
Jim Ingham949d5ac2011-02-18 00:54:25 +00001399
Caroline Ticee0da7a52010-12-09 22:52:49 +00001400 bool done = false;
1401 CommandObject *cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001402 bool wants_raw_input = false;
1403 std::string command_string (command_line);
Jim Ingham6247dbe2011-07-12 03:12:18 +00001404 std::string original_command_string (command_line);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001405
1406 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +00001407 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1408
1409 // Make a scoped cleanup object that will clear the crash description string
1410 // on exit of this function.
Enrico Granata1a102082011-07-12 00:18:11 +00001411 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Claytone98ac252010-11-10 04:57:04 +00001412
Caroline Ticee0da7a52010-12-09 22:52:49 +00001413 if (log)
1414 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +00001415
Jim Inghamabab14b2010-11-04 23:08:45 +00001416 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1417
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001418 if (!no_context_switching)
1419 UpdateExecutionContext (override_context);
Enrico Granata01bc2d42012-05-31 01:09:06 +00001420
1421 // <rdar://problem/11328896>
1422 bool add_to_history;
1423 if (lazy_add_to_history == eLazyBoolCalculate)
1424 add_to_history = (m_command_source_depth == 0);
1425 else
1426 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1427
Jim Ingham949d5ac2011-02-18 00:54:25 +00001428 bool empty_command = false;
1429 bool comment_command = false;
1430 if (command_string.empty())
1431 empty_command = true;
1432 else
Chris Lattner24943d22010-06-08 16:52:24 +00001433 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001434 const char *k_space_characters = "\t\n\v\f\r ";
1435
1436 size_t non_space = command_string.find_first_not_of (k_space_characters);
1437 // Check for empty line or comment line (lines whose first
1438 // non-space character is the comment character for this interpreter)
1439 if (non_space == std::string::npos)
1440 empty_command = true;
1441 else if (command_string[non_space] == m_comment_char)
1442 comment_command = true;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001443 else if (command_string[non_space] == m_repeat_char)
1444 {
1445 const char *history_string = FindHistoryString (command_string.c_str() + non_space);
1446 if (history_string == NULL)
1447 {
1448 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1449 result.SetStatus(eReturnStatusFailed);
1450 return false;
1451 }
1452 add_to_history = false;
1453 command_string = history_string;
1454 original_command_string = history_string;
1455 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001456 }
1457
1458 if (empty_command)
1459 {
1460 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +00001461 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001462 if (m_command_history.empty())
1463 {
1464 result.AppendError ("empty command");
1465 result.SetStatus(eReturnStatusFailed);
1466 return false;
1467 }
1468 else
1469 {
1470 command_line = m_repeat_command.c_str();
1471 command_string = command_line;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001472 original_command_string = command_line;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001473 if (m_repeat_command.empty())
1474 {
1475 result.AppendErrorWithFormat("No auto repeat.\n");
1476 result.SetStatus (eReturnStatusFailed);
1477 return false;
1478 }
1479 }
1480 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001481 }
1482 else
1483 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001484 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1485 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001486 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001487 }
1488 else if (comment_command)
1489 {
1490 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1491 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001492 }
Caroline Tice649116c2011-05-11 16:07:06 +00001493
Greg Claytonf5c0c722011-10-14 07:41:33 +00001494
1495 Error error (PreprocessCommand (command_string));
1496
1497 if (error.Fail())
1498 {
1499 result.AppendError (error.AsCString());
1500 result.SetStatus(eReturnStatusFailed);
1501 return false;
1502 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001503 // Phase 1.
1504
1505 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1506 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1507 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1508 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1509 // 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 +00001510 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +00001511 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +00001512
Caroline Ticee0da7a52010-12-09 22:52:49 +00001513 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001514 size_t actual_cmd_name_len = 0;
Greg Clayton7268b4c2011-10-28 21:38:01 +00001515 std::string next_word;
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001516 StringList matches;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001517 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +00001518 {
Caroline Tice649116c2011-05-11 16:07:06 +00001519 char quote_char = '\0';
Greg Clayton7268b4c2011-10-28 21:38:01 +00001520 std::string suffix;
1521 ExtractCommand (command_string, next_word, suffix, quote_char);
1522 if (cmd_obj == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +00001523 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001524 if (AliasExists (next_word.c_str()))
Caroline Tice56d2fc42010-12-14 18:51:39 +00001525 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001526 std::string alias_result;
1527 cmd_obj = BuildAliasResult (next_word.c_str(), command_string, alias_result, result);
1528 revised_command_line.Printf ("%s", alias_result.c_str());
1529 if (cmd_obj)
1530 {
1531 wants_raw_input = cmd_obj->WantsRawCommandString ();
1532 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1533 }
Chris Lattner24943d22010-06-08 16:52:24 +00001534 }
1535 else
1536 {
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001537 cmd_obj = GetCommandObject (next_word.c_str(), &matches);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001538 if (cmd_obj)
1539 {
1540 actual_cmd_name_len += next_word.length();
1541 revised_command_line.Printf ("%s", next_word.c_str());
1542 wants_raw_input = cmd_obj->WantsRawCommandString ();
1543 }
Caroline Tice649116c2011-05-11 16:07:06 +00001544 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001545 {
1546 revised_command_line.Printf ("%s", next_word.c_str());
1547 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001548 }
1549 }
1550 else
1551 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001552 if (cmd_obj->IsMultiwordObject ())
1553 {
Greg Clayton13193d52012-10-13 02:07:45 +00001554 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (next_word.c_str());
Greg Clayton7268b4c2011-10-28 21:38:01 +00001555 if (sub_cmd_obj)
1556 {
1557 actual_cmd_name_len += next_word.length() + 1;
1558 revised_command_line.Printf (" %s", next_word.c_str());
1559 cmd_obj = sub_cmd_obj;
1560 wants_raw_input = cmd_obj->WantsRawCommandString ();
1561 }
1562 else
1563 {
1564 if (quote_char)
1565 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1566 else
1567 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1568 done = true;
1569 }
1570 }
Caroline Tice649116c2011-05-11 16:07:06 +00001571 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001572 {
1573 if (quote_char)
1574 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1575 else
1576 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1577 done = true;
1578 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001579 }
1580
1581 if (cmd_obj == NULL)
1582 {
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001583 uint32_t num_matches = matches.GetSize();
1584 if (matches.GetSize() > 1) {
1585 std::string error_msg;
1586 error_msg.assign ("Ambiguous command '");
1587 error_msg.append(next_word.c_str());
1588 error_msg.append ("'.");
1589
1590 error_msg.append (" Possible matches:");
1591
1592 for (uint32_t i = 0; i < num_matches; ++i) {
1593 error_msg.append ("\n\t");
1594 error_msg.append (matches.GetStringAtIndex(i));
1595 }
1596 error_msg.append ("\n");
1597 result.AppendRawError (error_msg.c_str(), error_msg.size());
1598 } else {
1599 // We didn't have only one match, otherwise we wouldn't get here.
1600 assert(num_matches == 0);
1601 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1602 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001603 result.SetStatus (eReturnStatusFailed);
1604 return false;
1605 }
1606
Greg Clayton7268b4c2011-10-28 21:38:01 +00001607 if (cmd_obj->IsMultiwordObject ())
1608 {
1609 if (!suffix.empty())
1610 {
1611
1612 result.AppendErrorWithFormat ("multi-word commands ('%s') can't have shorthand suffixes: '%s'\n",
1613 next_word.c_str(),
1614 suffix.c_str());
1615 result.SetStatus (eReturnStatusFailed);
1616 return false;
1617 }
1618 }
1619 else
1620 {
1621 // If we found a normal command, we are done
1622 done = true;
1623 if (!suffix.empty())
1624 {
1625 switch (suffix[0])
1626 {
1627 case '/':
1628 // GDB format suffixes
Greg Claytond8a218d2011-10-29 00:57:28 +00001629 {
1630 Options *command_options = cmd_obj->GetOptions();
1631 if (command_options && command_options->SupportsLongOption("gdb-format"))
1632 {
Greg Clayton3840cd72011-11-09 23:25:03 +00001633 std::string gdb_format_option ("--gdb-format=");
1634 gdb_format_option += (suffix.c_str() + 1);
1635
1636 bool inserted = false;
1637 std::string &cmd = revised_command_line.GetString();
1638 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1639 if (arg_terminator_idx != std::string::npos)
1640 {
1641 // Insert the gdb format option before the "--" that terminates options
1642 gdb_format_option.append(1,' ');
1643 cmd.insert(arg_terminator_idx, gdb_format_option);
1644 inserted = true;
1645 }
1646
1647 if (!inserted)
1648 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1649
1650 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1651 revised_command_line.PutCString (" --");
Greg Claytond8a218d2011-10-29 00:57:28 +00001652 }
1653 else
1654 {
1655 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1656 cmd_obj->GetCommandName());
1657 result.SetStatus (eReturnStatusFailed);
1658 return false;
1659 }
1660 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001661 break;
Johnny Chen8ca450b2011-10-31 22:22:06 +00001662
1663 default:
1664 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1665 suffix.c_str());
1666 result.SetStatus (eReturnStatusFailed);
1667 return false;
1668
Greg Clayton7268b4c2011-10-28 21:38:01 +00001669 }
1670 }
1671 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001672 if (command_string.length() == 0)
1673 done = true;
1674
Chris Lattner24943d22010-06-08 16:52:24 +00001675 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001676
Greg Clayton7268b4c2011-10-28 21:38:01 +00001677 if (!command_string.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +00001678 revised_command_line.Printf (" %s", command_string.c_str());
1679
1680 // End of Phase 1.
1681 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1682 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1683 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1684 // wants_raw_input specifies whether the Execute method expects raw input or not.
1685
1686
1687 if (log)
1688 {
1689 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1690 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1691 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1692 }
1693
1694 // Phase 2.
1695 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1696 // CommandObject, with the appropriate arguments.
1697
1698 if (cmd_obj != NULL)
1699 {
1700 if (add_to_history)
1701 {
1702 Args command_args (revised_command_line.GetData());
1703 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1704 if (repeat_command != NULL)
1705 m_repeat_command.assign(repeat_command);
1706 else
Jim Ingham6247dbe2011-07-12 03:12:18 +00001707 m_repeat_command.assign(original_command_string.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001708
Jim Ingham6247dbe2011-07-12 03:12:18 +00001709 // Don't keep pushing the same command onto the history...
Greg Clayton7268b4c2011-10-28 21:38:01 +00001710 if (m_command_history.empty() || m_command_history.back() != original_command_string)
Jim Ingham6247dbe2011-07-12 03:12:18 +00001711 m_command_history.push_back (original_command_string);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001712 }
1713
1714 command_string = revised_command_line.GetData();
1715 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001716 std::string remainder;
1717 if (actual_cmd_name_len < command_string.length())
1718 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1719 // than cmd_obj->GetCommandName(), because name completion
1720 // allows users to enter short versions of the names,
1721 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +00001722
1723 // Remove any initial spaces
1724 std::string white_space (" \t\v");
1725 size_t pos = remainder.find_first_not_of (white_space);
1726 if (pos != 0 && pos != std::string::npos)
Greg Clayton91c9dcf2011-04-22 20:58:45 +00001727 remainder.erase(0, pos);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001728
1729 if (log)
Jason Molenda24c991c2011-08-25 00:20:04 +00001730 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001731
Jim Inghamda26bd22012-06-08 21:56:10 +00001732 cmd_obj->Execute (remainder.c_str(), result);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001733 }
1734 else
1735 {
1736 // We didn't find the first command object, so complete the first argument.
1737 Args command_args (revised_command_line.GetData());
1738 StringList matches;
1739 int num_matches;
1740 int cursor_index = 0;
1741 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1742 bool word_complete;
1743 num_matches = HandleCompletionMatches (command_args,
1744 cursor_index,
1745 cursor_char_position,
1746 0,
1747 -1,
1748 word_complete,
1749 matches);
1750
1751 if (num_matches > 0)
1752 {
1753 std::string error_msg;
1754 error_msg.assign ("ambiguous command '");
1755 error_msg.append(command_args.GetArgumentAtIndex(0));
1756 error_msg.append ("'.");
1757
1758 error_msg.append (" Possible completions:");
1759 for (int i = 0; i < num_matches; i++)
1760 {
1761 error_msg.append ("\n\t");
1762 error_msg.append (matches.GetStringAtIndex (i));
1763 }
1764 error_msg.append ("\n");
1765 result.AppendRawError (error_msg.c_str(), error_msg.size());
1766 }
1767 else
1768 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1769
1770 result.SetStatus (eReturnStatusFailed);
1771 }
1772
Jason Molenda24c991c2011-08-25 00:20:04 +00001773 if (log)
1774 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1775
Chris Lattner24943d22010-06-08 16:52:24 +00001776 return result.Succeeded();
1777}
1778
1779int
1780CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1781 int &cursor_index,
1782 int &cursor_char_position,
1783 int match_start_point,
1784 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001785 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001786 StringList &matches)
1787{
1788 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001789 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001790
1791 // For any of the command completions a unique match will be a complete word.
1792 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001793
1794 if (cursor_index == -1)
1795 {
1796 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001797 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001798 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1799 }
1800 else if (cursor_index == 0)
1801 {
1802 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001803 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001804 num_command_matches = matches.GetSize();
1805
1806 if (num_command_matches == 1
1807 && cmd_obj && cmd_obj->IsMultiwordObject()
1808 && matches.GetStringAtIndex(0) != NULL
1809 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1810 {
1811 look_for_subcommand = true;
1812 num_command_matches = 0;
1813 matches.DeleteStringAtIndex(0);
1814 parsed_line.AppendArgument ("");
1815 cursor_index++;
1816 cursor_char_position = 0;
1817 }
1818 }
1819
1820 if (cursor_index > 0 || look_for_subcommand)
1821 {
1822 // We are completing further on into a commands arguments, so find the command and tell it
1823 // to complete the command.
1824 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001825 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001826 if (command_object == NULL)
1827 {
1828 return 0;
1829 }
1830 else
1831 {
1832 parsed_line.Shift();
1833 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001834 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001835 cursor_index,
1836 cursor_char_position,
1837 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001838 max_return_elements,
1839 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001840 matches);
1841 }
1842 }
1843
1844 return num_command_matches;
1845
1846}
1847
1848int
1849CommandInterpreter::HandleCompletion (const char *current_line,
1850 const char *cursor,
1851 const char *last_char,
1852 int match_start_point,
1853 int max_return_elements,
1854 StringList &matches)
1855{
1856 // We parse the argument up to the cursor, so the last argument in parsed_line is
1857 // the one containing the cursor, and the cursor is after the last character.
1858
1859 Args parsed_line(current_line, last_char - current_line);
1860 Args partial_parsed_line(current_line, cursor - current_line);
1861
Jim Ingham6247dbe2011-07-12 03:12:18 +00001862 // Don't complete comments, and if the line we are completing is just the history repeat character,
1863 // substitute the appropriate history line.
1864 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1865 if (first_arg)
1866 {
1867 if (first_arg[0] == m_comment_char)
1868 return 0;
1869 else if (first_arg[0] == m_repeat_char)
1870 {
1871 const char *history_string = FindHistoryString (first_arg);
1872 if (history_string != NULL)
1873 {
1874 matches.Clear();
1875 matches.InsertStringAtIndex(0, history_string);
1876 return -2;
1877 }
1878 else
1879 return 0;
1880
1881 }
1882 }
1883
1884
Chris Lattner24943d22010-06-08 16:52:24 +00001885 int num_args = partial_parsed_line.GetArgumentCount();
1886 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1887 int cursor_char_position;
1888
1889 if (cursor_index == -1)
1890 cursor_char_position = 0;
1891 else
1892 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001893
1894 if (cursor > current_line && cursor[-1] == ' ')
1895 {
1896 // We are just after a space. If we are in an argument, then we will continue
1897 // parsing, but if we are between arguments, then we have to complete whatever the next
1898 // element would be.
1899 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1900 // protected by a quote) then the space will also be in the parsed argument...
1901
1902 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1903 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1904 {
1905 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1906 cursor_index++;
1907 cursor_char_position = 0;
1908 }
1909 }
Chris Lattner24943d22010-06-08 16:52:24 +00001910
1911 int num_command_matches;
1912
1913 matches.Clear();
1914
1915 // Only max_return_elements == -1 is supported at present:
1916 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001917 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001918 num_command_matches = HandleCompletionMatches (parsed_line,
1919 cursor_index,
1920 cursor_char_position,
1921 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001922 max_return_elements,
1923 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001924 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001925
1926 if (num_command_matches <= 0)
1927 return num_command_matches;
1928
1929 if (num_args == 0)
1930 {
1931 // If we got an empty string, insert nothing.
1932 matches.InsertStringAtIndex(0, "");
1933 }
1934 else
1935 {
1936 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1937 // put an empty string in element 0.
1938 std::string command_partial_str;
1939 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001940 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1941 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001942
1943 std::string common_prefix;
1944 matches.LongestCommonPrefix (common_prefix);
1945 int partial_name_len = command_partial_str.size();
1946
1947 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001948 // Only do this if the completer told us this was a complete word, however...
1949 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001950 {
1951 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1952 if (quote_char != '\0')
1953 common_prefix.push_back(quote_char);
1954
1955 common_prefix.push_back(' ');
1956 }
1957 common_prefix.erase (0, partial_name_len);
1958 matches.InsertStringAtIndex(0, common_prefix.c_str());
1959 }
1960 return num_command_matches;
1961}
1962
Chris Lattner24943d22010-06-08 16:52:24 +00001963
1964CommandInterpreter::~CommandInterpreter ()
1965{
1966}
1967
1968const char *
1969CommandInterpreter::GetPrompt ()
1970{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001971 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001972}
1973
1974void
1975CommandInterpreter::SetPrompt (const char *new_prompt)
1976{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001977 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001978}
1979
Jim Ingham5e16ef52010-10-04 19:49:29 +00001980size_t
Greg Clayton58928562011-02-09 01:08:52 +00001981CommandInterpreter::GetConfirmationInputReaderCallback
1982(
1983 void *baton,
1984 InputReader &reader,
1985 lldb::InputReaderAction action,
1986 const char *bytes,
1987 size_t bytes_len
1988)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001989{
Greg Clayton58928562011-02-09 01:08:52 +00001990 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001991 bool *response_ptr = (bool *) baton;
1992
1993 switch (action)
1994 {
1995 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001996 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001997 {
1998 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001999 {
Greg Clayton58928562011-02-09 01:08:52 +00002000 out_file.Printf ("%s", reader.GetPrompt());
2001 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00002002 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00002003 }
2004 break;
2005
2006 case eInputReaderDeactivate:
2007 break;
2008
2009 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00002010 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00002011 {
Greg Clayton58928562011-02-09 01:08:52 +00002012 out_file.Printf ("%s", reader.GetPrompt());
2013 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00002014 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00002015 break;
Caroline Tice4a348082011-05-02 20:41:46 +00002016
2017 case eInputReaderAsynchronousOutputWritten:
2018 break;
2019
Jim Ingham5e16ef52010-10-04 19:49:29 +00002020 case eInputReaderGotToken:
2021 if (bytes_len == 0)
2022 {
2023 reader.SetIsDone(true);
2024 }
Jim Ingham36fe9912011-11-14 20:02:01 +00002025 else if (bytes[0] == 'y' || bytes[0] == 'Y')
Jim Ingham5e16ef52010-10-04 19:49:29 +00002026 {
2027 *response_ptr = true;
2028 reader.SetIsDone(true);
2029 }
Jim Ingham36fe9912011-11-14 20:02:01 +00002030 else if (bytes[0] == 'n' || bytes[0] == 'N')
Jim Ingham5e16ef52010-10-04 19:49:29 +00002031 {
2032 *response_ptr = false;
2033 reader.SetIsDone(true);
2034 }
2035 else
2036 {
Greg Clayton58928562011-02-09 01:08:52 +00002037 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00002038 {
Jim Ingham26183802011-11-17 01:22:00 +00002039 out_file.Printf ("Please answer \"y\" or \"n\".\n%s", reader.GetPrompt());
Greg Clayton58928562011-02-09 01:08:52 +00002040 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00002041 }
2042 }
2043 break;
2044
Caroline Ticec4f55fe2010-11-19 20:47:54 +00002045 case eInputReaderInterrupt:
2046 case eInputReaderEndOfFile:
2047 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
2048 reader.SetIsDone (true);
2049 break;
2050
Jim Ingham5e16ef52010-10-04 19:49:29 +00002051 case eInputReaderDone:
2052 break;
2053 }
2054
2055 return bytes_len;
2056
2057}
2058
2059bool
2060CommandInterpreter::Confirm (const char *message, bool default_answer)
2061{
Jim Ingham93057472010-10-04 22:44:14 +00002062 // Check AutoConfirm first:
2063 if (m_debugger.GetAutoConfirm())
2064 return default_answer;
2065
Jim Ingham5e16ef52010-10-04 19:49:29 +00002066 InputReaderSP reader_sp (new InputReader(GetDebugger()));
2067 bool response = default_answer;
2068 if (reader_sp)
2069 {
2070 std::string prompt(message);
2071 prompt.append(": [");
2072 if (default_answer)
2073 prompt.append ("Y/n] ");
2074 else
2075 prompt.append ("y/N] ");
2076
2077 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
2078 &response, // baton
2079 eInputReaderGranularityLine, // token size, to pass to callback function
2080 NULL, // end token
2081 prompt.c_str(), // prompt
2082 true)); // echo input
2083 if (err.Success())
2084 {
2085 GetDebugger().PushInputReader (reader_sp);
2086 }
2087 reader_sp->WaitOnReaderIsDone();
2088 }
2089 return response;
2090}
2091
2092
Chris Lattner24943d22010-06-08 16:52:24 +00002093void
2094CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
2095{
Jim Inghamd40f8a62010-07-06 22:46:59 +00002096 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00002097
Sean Callananb386d822012-08-09 00:50:26 +00002098 if (cmd_obj_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002099 {
2100 CommandObject *cmd_obj = cmd_obj_sp.get();
2101 if (cmd_obj->IsCrossRefObject ())
2102 cmd_obj->AddObject (object_type);
2103 }
2104}
2105
Chris Lattner24943d22010-06-08 16:52:24 +00002106OptionArgVectorSP
2107CommandInterpreter::GetAliasOptions (const char *alias_name)
2108{
2109 OptionArgMap::iterator pos;
2110 OptionArgVectorSP ret_val;
2111
2112 std::string alias (alias_name);
2113
2114 if (HasAliasOptions())
2115 {
2116 pos = m_alias_options.find (alias);
2117 if (pos != m_alias_options.end())
2118 ret_val = pos->second;
2119 }
2120
2121 return ret_val;
2122}
2123
2124void
2125CommandInterpreter::RemoveAliasOptions (const char *alias_name)
2126{
2127 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
2128 if (pos != m_alias_options.end())
2129 {
2130 m_alias_options.erase (pos);
2131 }
2132}
2133
2134void
2135CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
2136{
2137 m_alias_options[alias_name] = option_arg_vector_sp;
2138}
2139
2140bool
2141CommandInterpreter::HasCommands ()
2142{
2143 return (!m_command_dict.empty());
2144}
2145
2146bool
2147CommandInterpreter::HasAliases ()
2148{
2149 return (!m_alias_dict.empty());
2150}
2151
2152bool
2153CommandInterpreter::HasUserCommands ()
2154{
2155 return (!m_user_dict.empty());
2156}
2157
2158bool
2159CommandInterpreter::HasAliasOptions ()
2160{
2161 return (!m_alias_options.empty());
2162}
2163
Chris Lattner24943d22010-06-08 16:52:24 +00002164void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002165CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2166 const char *alias_name,
2167 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00002168 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002169 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00002170{
2171 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00002172
2173 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00002174
Caroline Tice44c841d2010-12-07 19:58:26 +00002175 // Make sure that the alias name is the 0th element in cmd_args
2176 std::string alias_name_str = alias_name;
2177 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2178 cmd_args.Unshift (alias_name);
2179
2180 Args new_args (alias_cmd_obj->GetCommandName());
2181 if (new_args.GetArgumentCount() == 2)
2182 new_args.Shift();
2183
Chris Lattner24943d22010-06-08 16:52:24 +00002184 if (option_arg_vector_sp.get())
2185 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002186 if (wants_raw_input)
2187 {
2188 // We have a command that both has command options and takes raw input. Make *sure* it has a
2189 // " -- " in the right place in the raw_input_string.
2190 size_t pos = raw_input_string.find(" -- ");
2191 if (pos == std::string::npos)
2192 {
2193 // None found; assume it goes at the beginning of the raw input string
2194 raw_input_string.insert (0, " -- ");
2195 }
2196 }
Chris Lattner24943d22010-06-08 16:52:24 +00002197
2198 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
2199 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002200 std::vector<bool> used (old_size + 1, false);
2201
2202 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002203
2204 for (int i = 0; i < option_arg_vector->size(); ++i)
2205 {
2206 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00002207 OptionArgValue value_pair = option_pair.second;
2208 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00002209 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00002210 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00002211 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002212 {
2213 if (!wants_raw_input
2214 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2215 new_args.AppendArgument (value.c_str());
2216 }
Chris Lattner24943d22010-06-08 16:52:24 +00002217 else
2218 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002219 if (value_type != optional_argument)
2220 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00002221 if (value.compare ("<no-argument>") != 0)
2222 {
2223 int index = GetOptionArgumentPosition (value.c_str());
2224 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002225 {
Chris Lattner24943d22010-06-08 16:52:24 +00002226 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00002227 if (value_type != optional_argument)
2228 new_args.AppendArgument (value.c_str());
2229 else
2230 {
2231 char buffer[255];
2232 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2233 new_args.AppendArgument (buffer);
2234 }
2235
2236 }
Chris Lattner24943d22010-06-08 16:52:24 +00002237 else if (index >= cmd_args.GetArgumentCount())
2238 {
2239 result.AppendErrorWithFormat
2240 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2241 index);
2242 result.SetStatus (eReturnStatusFailed);
2243 return;
2244 }
2245 else
2246 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002247 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2248 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2249 if (strpos != std::string::npos)
2250 {
2251 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2252 }
2253
2254 if (value_type != optional_argument)
2255 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2256 else
2257 {
2258 char buffer[255];
2259 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2260 cmd_args.GetArgumentAtIndex (index));
2261 new_args.AppendArgument (buffer);
2262 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002263 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002264 }
2265 }
2266 }
2267 }
2268
2269 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
2270 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002271 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00002272 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2273 }
2274
2275 cmd_args.Clear();
2276 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2277 }
2278 else
2279 {
2280 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00002281 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2282 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2283 // input string.
2284 if (wants_raw_input)
2285 {
2286 cmd_args.Clear();
2287 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2288 }
Chris Lattner24943d22010-06-08 16:52:24 +00002289 return;
2290 }
2291
2292 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2293 return;
2294}
2295
2296
2297int
2298CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2299{
2300 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2301 // of zero.
2302
2303 char *cptr = (char *) in_string;
2304
2305 // Does it start with '%'
2306 if (cptr[0] == '%')
2307 {
2308 ++cptr;
2309
2310 // Is the rest of it entirely digits?
2311 if (isdigit (cptr[0]))
2312 {
2313 const char *start = cptr;
2314 while (isdigit (cptr[0]))
2315 ++cptr;
2316
2317 // We've gotten to the end of the digits; are we at the end of the string?
2318 if (cptr[0] == '\0')
2319 position = atoi (start);
2320 }
2321 }
2322
2323 return position;
2324}
2325
2326void
2327CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2328{
Jim Ingham574c3d62011-08-12 23:34:31 +00002329 FileSpec init_file;
Greg Claytond6edcb52011-09-11 00:01:44 +00002330 if (in_cwd)
Jim Ingham574c3d62011-08-12 23:34:31 +00002331 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002332 // In the current working directory we don't load any program specific
2333 // .lldbinit files, we only look for a "./.lldbinit" file.
2334 if (m_skip_lldbinit_files)
2335 return;
2336
2337 init_file.SetFile ("./.lldbinit", true);
Jim Ingham574c3d62011-08-12 23:34:31 +00002338 }
Greg Claytond6edcb52011-09-11 00:01:44 +00002339 else
Jim Ingham574c3d62011-08-12 23:34:31 +00002340 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002341 // If we aren't looking in the current working directory we are looking
2342 // in the home directory. We will first see if there is an application
2343 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2344 // "-" and the name of the program. If this file doesn't exist, we fall
2345 // back to just the "~/.lldbinit" file. We also obey any requests to not
2346 // load the init files.
2347 const char *init_file_path = "~/.lldbinit";
2348
2349 if (m_skip_app_init_files == false)
2350 {
2351 FileSpec program_file_spec (Host::GetProgramFileSpec());
2352 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham574c3d62011-08-12 23:34:31 +00002353
Greg Claytond6edcb52011-09-11 00:01:44 +00002354 if (program_name)
2355 {
2356 char program_init_file_name[PATH_MAX];
2357 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2358 init_file.SetFile (program_init_file_name, true);
2359 if (!init_file.Exists())
2360 init_file.Clear();
2361 }
2362 }
2363
2364 if (!init_file && !m_skip_lldbinit_files)
2365 init_file.SetFile (init_file_path, true);
2366 }
2367
Chris Lattner24943d22010-06-08 16:52:24 +00002368 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2369 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2370
2371 if (init_file.Exists())
2372 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00002373 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
2374 bool stop_on_continue = true;
2375 bool stop_on_error = false;
2376 bool echo_commands = false;
2377 bool print_results = false;
2378
Enrico Granata01bc2d42012-05-31 01:09:06 +00002379 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, eLazyBoolNo, result);
Chris Lattner24943d22010-06-08 16:52:24 +00002380 }
2381 else
2382 {
2383 // nothing to be done if the file doesn't exist
2384 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2385 }
2386}
2387
Greg Claytonb72d0f02011-04-12 05:54:46 +00002388PlatformSP
2389CommandInterpreter::GetPlatform (bool prefer_target_platform)
2390{
2391 PlatformSP platform_sp;
Greg Clayton567e7f32011-09-22 04:58:26 +00002392 if (prefer_target_platform)
2393 {
Greg Claytonbcaf99a2012-07-12 20:32:19 +00002394 ExecutionContext exe_ctx(GetExecutionContext());
2395 Target *target = exe_ctx.GetTargetPtr();
Greg Clayton567e7f32011-09-22 04:58:26 +00002396 if (target)
2397 platform_sp = target->GetPlatform();
2398 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002399
2400 if (!platform_sp)
2401 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2402 return platform_sp;
2403}
2404
Jim Ingham949d5ac2011-02-18 00:54:25 +00002405void
Jim Inghama4fede32011-03-11 01:51:49 +00002406CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002407 ExecutionContext *override_context,
2408 bool stop_on_continue,
2409 bool stop_on_error,
2410 bool echo_commands,
2411 bool print_results,
Enrico Granata01bc2d42012-05-31 01:09:06 +00002412 LazyBool add_to_history,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002413 CommandReturnObject &result)
2414{
2415 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00002416
2417 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2418 // Make sure you reset this value anywhere you return from the function.
2419
2420 bool old_async_execution = m_debugger.GetAsyncExecution();
2421
2422 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2423 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2424
2425 if (override_context != NULL)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002426 UpdateExecutionContext (override_context);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002427
2428 if (!stop_on_continue)
2429 {
2430 m_debugger.SetAsyncExecution (false);
2431 }
2432
2433 for (int idx = 0; idx < num_lines; idx++)
2434 {
2435 const char *cmd = commands.GetStringAtIndex(idx);
2436 if (cmd[0] == '\0')
2437 continue;
2438
Jim Ingham949d5ac2011-02-18 00:54:25 +00002439 if (echo_commands)
2440 {
2441 result.AppendMessageWithFormat ("%s %s\n",
2442 GetPrompt(),
2443 cmd);
2444 }
2445
Greg Claytonaa378b12011-02-20 02:15:07 +00002446 CommandReturnObject tmp_result;
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002447 // If override_context is not NULL, pass no_context_switching = true for
2448 // HandleCommand() since we updated our context already.
Enrico Granata01bc2d42012-05-31 01:09:06 +00002449 bool success = HandleCommand(cmd, add_to_history, tmp_result,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002450 NULL, /* override_context */
2451 true, /* repeat_on_empty_command */
2452 override_context != NULL /* no_context_switching */);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002453
2454 if (print_results)
2455 {
2456 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002457 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002458 }
2459
2460 if (!success || !tmp_result.Succeeded())
2461 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002462 const char *error_msg = tmp_result.GetErrorData();
2463 if (error_msg == NULL || error_msg[0] == '\0')
2464 error_msg = "<unknown error>.\n";
Jim Ingham949d5ac2011-02-18 00:54:25 +00002465 if (stop_on_error)
2466 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002467 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed with %s",
2468 idx, cmd, error_msg);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002469 result.SetStatus (eReturnStatusFailed);
2470 m_debugger.SetAsyncExecution (old_async_execution);
2471 return;
2472 }
2473 else if (print_results)
2474 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002475 result.AppendMessageWithFormat ("Command #%d '%s' failed with %s",
Jim Ingham949d5ac2011-02-18 00:54:25 +00002476 idx + 1,
2477 cmd,
Jim Ingham862fd5c2012-04-24 02:25:07 +00002478 error_msg);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002479 }
2480 }
2481
Caroline Tice4a348082011-05-02 20:41:46 +00002482 if (result.GetImmediateOutputStream())
2483 result.GetImmediateOutputStream()->Flush();
2484
2485 if (result.GetImmediateErrorStream())
2486 result.GetImmediateErrorStream()->Flush();
2487
Jim Ingham949d5ac2011-02-18 00:54:25 +00002488 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2489 // could be running (for instance in Breakpoint Commands.
2490 // So we check the return value to see if it is has running in it.
2491 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2492 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2493 {
2494 if (stop_on_continue)
2495 {
2496 // If we caused the target to proceed, and we're going to stop in that case, set the
2497 // status in our real result before returning. This is an error if the continue was not the
2498 // last command in the set of commands to be run.
2499 if (idx != num_lines - 1)
2500 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
2501 idx + 1, cmd);
2502 else
2503 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
2504
2505 result.SetStatus(tmp_result.GetStatus());
2506 m_debugger.SetAsyncExecution (old_async_execution);
2507
2508 return;
2509 }
2510 }
2511
2512 }
2513
2514 result.SetStatus (eReturnStatusSuccessFinishResult);
2515 m_debugger.SetAsyncExecution (old_async_execution);
2516
2517 return;
2518}
2519
2520void
2521CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2522 ExecutionContext *context,
2523 bool stop_on_continue,
2524 bool stop_on_error,
2525 bool echo_command,
2526 bool print_result,
Enrico Granata01bc2d42012-05-31 01:09:06 +00002527 LazyBool add_to_history,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002528 CommandReturnObject &result)
2529{
2530 if (cmd_file.Exists())
2531 {
2532 bool success;
2533 StringList commands;
2534 success = commands.ReadFileLines(cmd_file);
2535 if (!success)
2536 {
2537 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2538 result.SetStatus (eReturnStatusFailed);
2539 return;
2540 }
Enrico Granata01bc2d42012-05-31 01:09:06 +00002541 m_command_source_depth++;
2542 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, add_to_history, result);
2543 m_command_source_depth--;
Jim Ingham949d5ac2011-02-18 00:54:25 +00002544 }
2545 else
2546 {
2547 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2548 cmd_file.GetFilename().AsCString());
2549 result.SetStatus (eReturnStatusFailed);
2550 return;
2551 }
2552}
2553
Chris Lattner24943d22010-06-08 16:52:24 +00002554ScriptInterpreter *
Enrico Granatadb054912012-10-29 21:18:03 +00002555CommandInterpreter::GetScriptInterpreter (bool can_create)
Chris Lattner24943d22010-06-08 16:52:24 +00002556{
Enrico Granatadb054912012-10-29 21:18:03 +00002557 if (m_script_interpreter_ap.get() != NULL)
2558 return m_script_interpreter_ap.get();
2559
2560 if (!can_create)
2561 return NULL;
2562
Enrico Granatac5c10a42012-07-10 18:23:48 +00002563 // <rdar://problem/11751427>
2564 // we need to protect the initialization of the script interpreter
2565 // otherwise we could end up with two threads both trying to create
2566 // their instance of it, and for some languages (e.g. Python)
2567 // this is a bulletproof recipe for disaster!
2568 // this needs to be a function-level static because multiple Debugger instances living in the same process
2569 // still need to be isolated and not try to initialize Python concurrently
Enrico Granatab88c0a92012-07-10 19:04:14 +00002570 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive);
2571 Mutex::Locker interpreter_lock(g_interpreter_mutex);
Enrico Granatac5c10a42012-07-10 18:23:48 +00002572
Enrico Granatadb054912012-10-29 21:18:03 +00002573 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
2574 if (log)
2575 log->Printf("Initializing the ScriptInterpreter now\n");
Greg Clayton63094e02010-06-23 01:19:29 +00002576
Caroline Tice0aa2e552011-01-14 00:29:16 +00002577 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2578 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00002579 {
Greg Clayton3e4238d2011-11-04 03:34:56 +00002580 case eScriptLanguagePython:
2581#ifndef LLDB_DISABLE_PYTHON
2582 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2583 break;
2584#else
2585 // Fall through to the None case when python is disabled
2586#endif
Caroline Tice0aa2e552011-01-14 00:29:16 +00002587 case eScriptLanguageNone:
2588 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2589 break;
Caroline Tice0aa2e552011-01-14 00:29:16 +00002590 default:
2591 break;
2592 };
2593
2594 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00002595}
2596
2597
2598
2599bool
2600CommandInterpreter::GetSynchronous ()
2601{
2602 return m_synchronous_execution;
2603}
2604
2605void
2606CommandInterpreter::SetSynchronous (bool value)
2607{
Johnny Chend7a4eb02010-10-14 01:22:03 +00002608 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00002609}
2610
2611void
2612CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2613 const char *word_text,
2614 const char *separator,
2615 const char *help_text,
2616 uint32_t max_word_len)
2617{
Greg Clayton238c0a12010-09-18 01:14:36 +00002618 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2619
Chris Lattner24943d22010-06-08 16:52:24 +00002620 int indent_size = max_word_len + strlen (separator) + 2;
2621
2622 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00002623
2624 StreamString text_strm;
2625 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2626
2627 size_t len = text_strm.GetSize();
2628 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00002629 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00002630 {
2631 text_strm.EOL();
2632 len = text_strm.GetSize();
2633 }
Chris Lattner24943d22010-06-08 16:52:24 +00002634
2635 if (len < max_columns)
2636 {
2637 // Output it as a single line.
2638 strm.Printf ("%s", text);
2639 }
2640 else
2641 {
2642 // We need to break it up into multiple lines.
2643 bool first_line = true;
2644 int text_width;
2645 int start = 0;
2646 int end = start;
2647 int final_end = strlen (text);
2648 int sub_len;
2649
2650 while (end < final_end)
2651 {
2652 if (first_line)
2653 text_width = max_columns - 1;
2654 else
2655 text_width = max_columns - indent_size - 1;
2656
2657 // Don't start the 'text' on a space, since we're already outputting the indentation.
2658 if (!first_line)
2659 {
2660 while ((start < final_end) && (text[start] == ' '))
2661 start++;
2662 }
2663
2664 end = start + text_width;
2665 if (end > final_end)
2666 end = final_end;
2667 else
2668 {
2669 // If we're not at the end of the text, make sure we break the line on white space.
2670 while (end > start
2671 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2672 end--;
Greg Clayton73844aa2012-08-22 17:17:09 +00002673 assert (end > 0);
Chris Lattner24943d22010-06-08 16:52:24 +00002674 }
2675
2676 sub_len = end - start;
2677 if (start != 0)
2678 strm.EOL();
2679 if (!first_line)
2680 strm.Indent();
2681 else
2682 first_line = false;
2683 assert (start <= final_end);
2684 assert (start + sub_len <= final_end);
2685 if (sub_len > 0)
2686 strm.Write (text + start, sub_len);
2687 start = end + 1;
2688 }
2689 }
2690 strm.EOL();
2691 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00002692}
2693
2694void
Enrico Granata1bba6e52011-07-07 00:38:40 +00002695CommandInterpreter::OutputHelpText (Stream &strm,
2696 const char *word_text,
2697 const char *separator,
2698 const char *help_text,
2699 uint32_t max_word_len)
2700{
2701 int indent_size = max_word_len + strlen (separator) + 2;
2702
2703 strm.IndentMore (indent_size);
2704
2705 StreamString text_strm;
2706 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2707
2708 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Enrico Granata1bba6e52011-07-07 00:38:40 +00002709
2710 size_t len = text_strm.GetSize();
2711 const char *text = text_strm.GetData();
2712
2713 uint32_t chars_left = max_columns;
2714
2715 for (uint32_t i = 0; i < len; i++)
2716 {
2717 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2718 {
Enrico Granata1bba6e52011-07-07 00:38:40 +00002719 chars_left = max_columns - indent_size;
2720 strm.EOL();
2721 strm.Indent();
2722 }
2723 else
2724 {
2725 strm.PutChar(text[i]);
2726 chars_left--;
2727 }
2728
2729 }
2730
2731 strm.EOL();
2732 strm.IndentLess(indent_size);
2733}
2734
2735void
Chris Lattner24943d22010-06-08 16:52:24 +00002736CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2737 StringList &commands_help)
2738{
2739 CommandObject::CommandMap::const_iterator pos;
2740
2741 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2742 {
2743 const char *command_name = pos->first.c_str();
2744 CommandObject *cmd_obj = pos->second.get();
2745
Greg Clayton238c0a12010-09-18 01:14:36 +00002746 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002747 {
2748 commands_found.AppendString (command_name);
2749 commands_help.AppendString (cmd_obj->GetHelp());
2750 }
2751
2752 if (cmd_obj->IsMultiwordObject())
Greg Clayton13193d52012-10-13 02:07:45 +00002753 cmd_obj->AproposAllSubCommands (command_name,
2754 search_word,
2755 commands_found,
2756 commands_help);
Chris Lattner24943d22010-06-08 16:52:24 +00002757
2758 }
2759}
Greg Claytonb72d0f02011-04-12 05:54:46 +00002760
2761
2762void
2763CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2764{
Greg Claytonb72d0f02011-04-12 05:54:46 +00002765 if (override_context != NULL)
2766 {
Greg Claytonbcaf99a2012-07-12 20:32:19 +00002767 m_exe_ctx_ref = *override_context;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002768 }
2769 else
2770 {
Greg Claytonbcaf99a2012-07-12 20:32:19 +00002771 const bool adopt_selected = true;
2772 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002773 }
2774}
2775
Jim Ingham6247dbe2011-07-12 03:12:18 +00002776void
2777CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2778{
2779 DumpHistory (stream, 0, count - 1);
2780}
2781
2782void
2783CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2784{
Greg Clayton7268b4c2011-10-28 21:38:01 +00002785 const size_t last_idx = std::min<size_t>(m_command_history.size(), end + 1);
2786 for (size_t i = start; i < last_idx; i++)
Jim Ingham6247dbe2011-07-12 03:12:18 +00002787 {
2788 if (!m_command_history[i].empty())
2789 {
2790 stream.Indent();
Greg Clayton7268b4c2011-10-28 21:38:01 +00002791 stream.Printf ("%4zu: %s\n", i, m_command_history[i].c_str());
Jim Ingham6247dbe2011-07-12 03:12:18 +00002792 }
2793 }
2794}
2795
2796const char *
2797CommandInterpreter::FindHistoryString (const char *input_str) const
2798{
2799 if (input_str[0] != m_repeat_char)
2800 return NULL;
2801 if (input_str[1] == '-')
2802 {
2803 bool success;
2804 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
2805 if (!success)
2806 return NULL;
2807 if (idx > m_command_history.size())
2808 return NULL;
2809 idx = m_command_history.size() - idx;
2810 return m_command_history[idx].c_str();
2811
2812 }
2813 else if (input_str[1] == m_repeat_char)
2814 {
2815 if (m_command_history.empty())
2816 return NULL;
2817 else
2818 return m_command_history.back().c_str();
2819 }
2820 else
2821 {
2822 bool success;
2823 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2824 if (!success)
2825 return NULL;
2826 if (idx >= m_command_history.size())
2827 return NULL;
2828 return m_command_history[idx].c_str();
2829 }
2830}