blob: 453004d860e08dbeb3b26df1f0f65d84f473722e [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
Jim Ingham84cdc152010-06-15 19:49:27 +000043#include "lldb/Interpreter/Args.h"
Caroline Tice5ddbe212011-05-06 21:37:15 +000044#include "lldb/Interpreter/Options.h"
Chris Lattner24943d22010-06-08 16:52:24 +000045#include "lldb/Core/Debugger.h"
Jim Ingham5e16ef52010-10-04 19:49:29 +000046#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000047#include "lldb/Core/Stream.h"
48#include "lldb/Core/Timer.h"
Greg Claytoncd548032011-02-01 01:31:41 +000049#include "lldb/Host/Host.h"
Chris Lattner24943d22010-06-08 16:52:24 +000050#include "lldb/Target/Process.h"
51#include "lldb/Target/Thread.h"
52#include "lldb/Target/TargetList.h"
Greg Claytone98ac252010-11-10 04:57:04 +000053#include "lldb/Utility/CleanUp.h"
Chris Lattner24943d22010-06-08 16:52:24 +000054
55#include "lldb/Interpreter/CommandReturnObject.h"
56#include "lldb/Interpreter/CommandInterpreter.h"
Caroline Tice0aa2e552011-01-14 00:29:16 +000057#include "lldb/Interpreter/ScriptInterpreterNone.h"
58#include "lldb/Interpreter/ScriptInterpreterPython.h"
Chris Lattner24943d22010-06-08 16:52:24 +000059
60using namespace lldb;
61using namespace lldb_private;
62
Greg Clayton9f282852012-08-23 00:22:02 +000063
64static PropertyDefinition
65g_properties[] =
66{
67 { "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." },
68 { NULL , OptionValue::eTypeInvalid, true, 0 , NULL, NULL, NULL }
69};
70
71enum
72{
73 ePropertyExpandRegexAliases = 0
74};
75
Jim Ingham5a15e692012-02-16 06:50:00 +000076ConstString &
77CommandInterpreter::GetStaticBroadcasterClass ()
78{
79 static ConstString class_name ("lldb.commandInterpreter");
80 return class_name;
81}
82
Chris Lattner24943d22010-06-08 16:52:24 +000083CommandInterpreter::CommandInterpreter
84(
Greg Clayton63094e02010-06-23 01:19:29 +000085 Debugger &debugger,
Chris Lattner24943d22010-06-08 16:52:24 +000086 ScriptLanguage script_language,
Greg Clayton63094e02010-06-23 01:19:29 +000087 bool synchronous_execution
Chris Lattner24943d22010-06-08 16:52:24 +000088) :
Jim Ingham5a15e692012-02-16 06:50:00 +000089 Broadcaster (&debugger, "lldb.command-interpreter"),
Greg Clayton9f282852012-08-23 00:22:02 +000090 Properties(OptionValuePropertiesSP(new OptionValueProperties(ConstString("interpreter")))),
Greg Clayton63094e02010-06-23 01:19:29 +000091 m_debugger (debugger),
Greg Clayton887aa282010-10-11 01:05:37 +000092 m_synchronous_execution (synchronous_execution),
Caroline Tice0aa2e552011-01-14 00:29:16 +000093 m_skip_lldbinit_files (false),
Jim Ingham574c3d62011-08-12 23:34:31 +000094 m_skip_app_init_files (false),
Jim Ingham949d5ac2011-02-18 00:54:25 +000095 m_script_interpreter_ap (),
Caroline Tice892fadd2011-06-16 16:27:19 +000096 m_comment_char ('#'),
Jim Ingham6247dbe2011-07-12 03:12:18 +000097 m_repeat_char ('!'),
Johnny Chen3908bb12012-08-09 22:06:10 +000098 m_batch_command_mode (false),
Enrico Granata01bc2d42012-05-31 01:09:06 +000099 m_truncation_warning(eNoTruncation),
100 m_command_source_depth (0)
Chris Lattner24943d22010-06-08 16:52:24 +0000101{
Greg Clayton73844aa2012-08-22 17:17:09 +0000102 debugger.SetScriptLanguage (script_language);
Greg Clayton49ce6822010-10-31 03:01:06 +0000103 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
104 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
Greg Clayton73844aa2012-08-22 17:17:09 +0000105 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Jim Ingham5a15e692012-02-16 06:50:00 +0000106 CheckInWithManager ();
Greg Clayton9f282852012-08-23 00:22:02 +0000107 m_collection_sp->Initialize (g_properties);
Chris Lattner24943d22010-06-08 16:52:24 +0000108}
109
Greg Clayton9f282852012-08-23 00:22:02 +0000110bool
111CommandInterpreter::GetExpandRegexAliases () const
112{
113 const uint32_t idx = ePropertyExpandRegexAliases;
114 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
115}
116
117
118
Chris Lattner24943d22010-06-08 16:52:24 +0000119void
120CommandInterpreter::Initialize ()
121{
122 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
123
124 CommandReturnObject result;
125
126 LoadCommandDictionary ();
127
Chris Lattner24943d22010-06-08 16:52:24 +0000128 // Set up some initial aliases.
Caroline Tice5ddbe212011-05-06 21:37:15 +0000129 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
130 if (cmd_obj_sp)
131 {
132 AddAlias ("q", cmd_obj_sp);
133 AddAlias ("exit", cmd_obj_sp);
134 }
Sean Callananfc58af22012-05-04 23:15:02 +0000135
Johnny Chena47e44b2012-08-24 18:15:45 +0000136 cmd_obj_sp = GetCommandSPExact ("_regexp-attach",false);
Sean Callananfc58af22012-05-04 23:15:02 +0000137 if (cmd_obj_sp)
138 {
139 AddAlias ("attach", cmd_obj_sp);
140 }
Caroline Tice5ddbe212011-05-06 21:37:15 +0000141
Johnny Chena47e44b2012-08-24 18:15:45 +0000142 cmd_obj_sp = GetCommandSPExact ("process detach",false);
143 if (cmd_obj_sp)
144 {
145 AddAlias ("detach", cmd_obj_sp);
146 }
147
Caroline Tice5ddbe212011-05-06 21:37:15 +0000148 cmd_obj_sp = GetCommandSPExact ("process continue", false);
149 if (cmd_obj_sp)
150 {
151 AddAlias ("c", cmd_obj_sp);
152 AddAlias ("continue", cmd_obj_sp);
153 }
154
155 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
156 if (cmd_obj_sp)
157 AddAlias ("b", cmd_obj_sp);
158
Jim Ingham2753a022012-10-05 19:16:31 +0000159 cmd_obj_sp = GetCommandSPExact ("_regexp-tbreak",false);
160 if (cmd_obj_sp)
161 AddAlias ("tbreak", cmd_obj_sp);
162
Caroline Tice5ddbe212011-05-06 21:37:15 +0000163 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
164 if (cmd_obj_sp)
Jason Molenda47eb00e2011-10-22 00:47:41 +0000165 {
166 AddAlias ("stepi", cmd_obj_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000167 AddAlias ("si", cmd_obj_sp);
Jason Molenda47eb00e2011-10-22 00:47:41 +0000168 }
169
170 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
171 if (cmd_obj_sp)
172 {
173 AddAlias ("nexti", cmd_obj_sp);
174 AddAlias ("ni", cmd_obj_sp);
175 }
Caroline Tice5ddbe212011-05-06 21:37:15 +0000176
177 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
178 if (cmd_obj_sp)
179 {
180 AddAlias ("s", cmd_obj_sp);
181 AddAlias ("step", cmd_obj_sp);
182 }
183
184 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
185 if (cmd_obj_sp)
186 {
187 AddAlias ("n", cmd_obj_sp);
188 AddAlias ("next", cmd_obj_sp);
189 }
190
191 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
192 if (cmd_obj_sp)
193 {
Caroline Tice5ddbe212011-05-06 21:37:15 +0000194 AddAlias ("finish", cmd_obj_sp);
195 }
196
Jim Ingham59355252011-12-02 01:12:59 +0000197 cmd_obj_sp = GetCommandSPExact ("frame select", false);
198 if (cmd_obj_sp)
199 {
200 AddAlias ("f", cmd_obj_sp);
201 }
202
Jim Ingham2753a022012-10-05 19:16:31 +0000203 cmd_obj_sp = GetCommandSPExact ("thread select", false);
204 if (cmd_obj_sp)
205 {
206 AddAlias ("t", cmd_obj_sp);
207 }
208
Caroline Tice5ddbe212011-05-06 21:37:15 +0000209 cmd_obj_sp = GetCommandSPExact ("source list", false);
210 if (cmd_obj_sp)
211 {
212 AddAlias ("l", cmd_obj_sp);
213 AddAlias ("list", cmd_obj_sp);
214 }
215
216 cmd_obj_sp = GetCommandSPExact ("memory read", false);
217 if (cmd_obj_sp)
218 AddAlias ("x", cmd_obj_sp);
219
220 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
221 if (cmd_obj_sp)
222 AddAlias ("up", cmd_obj_sp);
223
224 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
225 if (cmd_obj_sp)
226 AddAlias ("down", cmd_obj_sp);
227
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000228 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000229 if (cmd_obj_sp)
230 AddAlias ("display", cmd_obj_sp);
Jim Ingham9d1acc12011-10-24 18:37:00 +0000231
232 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
233 if (cmd_obj_sp)
234 AddAlias ("dis", cmd_obj_sp);
235
236 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
237 if (cmd_obj_sp)
238 AddAlias ("di", cmd_obj_sp);
239
240
Jason Molenda730cae02011-10-22 01:30:52 +0000241
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000242 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000243 if (cmd_obj_sp)
244 AddAlias ("undisplay", cmd_obj_sp);
245
Jim Inghamf190a412012-10-10 16:51:31 +0000246 cmd_obj_sp = GetCommandSPExact ("_regexp-bt", false);
247 if (cmd_obj_sp)
248 AddAlias ("bt", cmd_obj_sp);
249
Caroline Tice5ddbe212011-05-06 21:37:15 +0000250 cmd_obj_sp = GetCommandSPExact ("target create", false);
251 if (cmd_obj_sp)
252 AddAlias ("file", cmd_obj_sp);
253
254 cmd_obj_sp = GetCommandSPExact ("target modules", false);
255 if (cmd_obj_sp)
256 AddAlias ("image", cmd_obj_sp);
257
258
259 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghame56493f2011-03-22 02:29:32 +0000260
Caroline Tice5ddbe212011-05-06 21:37:15 +0000261 cmd_obj_sp = GetCommandSPExact ("expression", false);
262 if (cmd_obj_sp)
263 {
264 AddAlias ("expr", cmd_obj_sp);
265
266 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
267 AddAlias ("p", cmd_obj_sp);
268 AddAlias ("print", cmd_obj_sp);
Sean Callanan59959eb2012-08-08 01:30:34 +0000269 AddAlias ("call", cmd_obj_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000270 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
271 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
Sean Callanan59959eb2012-08-08 01:30:34 +0000272 AddOrReplaceAliasOptions ("call", alias_arguments_vector_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000273
274 alias_arguments_vector_sp.reset (new OptionArgVector);
275 ProcessAliasOptionsArgs (cmd_obj_sp, "-o --", alias_arguments_vector_sp);
276 AddAlias ("po", cmd_obj_sp);
277 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
278 }
279
Sean Callananee301fa2012-06-01 23:29:32 +0000280 cmd_obj_sp = GetCommandSPExact ("process kill", false);
281 if (cmd_obj_sp)
Greg Claytonf2e53a52012-09-27 00:02:27 +0000282 {
Sean Callananee301fa2012-06-01 23:29:32 +0000283 AddAlias ("kill", cmd_obj_sp);
Greg Claytonf2e53a52012-09-27 00:02:27 +0000284 }
Sean Callananee301fa2012-06-01 23:29:32 +0000285
Caroline Tice5ddbe212011-05-06 21:37:15 +0000286 cmd_obj_sp = GetCommandSPExact ("process launch", false);
287 if (cmd_obj_sp)
288 {
289 alias_arguments_vector_sp.reset (new OptionArgVector);
Jason Molenda36eb7c02012-07-06 02:46:23 +0000290#if defined (__arm__)
291 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
292#else
Greg Clayton86c50d72012-05-18 00:04:38 +0000293 ProcessAliasOptionsArgs (cmd_obj_sp, "--shell=/bin/bash --", alias_arguments_vector_sp);
Jason Molenda36eb7c02012-07-06 02:46:23 +0000294#endif
Caroline Tice5ddbe212011-05-06 21:37:15 +0000295 AddAlias ("r", cmd_obj_sp);
296 AddAlias ("run", cmd_obj_sp);
297 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
298 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
299 }
Greg Claytonc84623f2012-03-29 21:47:51 +0000300
301 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
302 if (cmd_obj_sp)
303 {
304 AddAlias ("add-dsym", cmd_obj_sp);
305 }
Sean Callanan7b71b172012-05-21 18:25:19 +0000306
307 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
308 if (cmd_obj_sp)
309 {
310 alias_arguments_vector_sp.reset (new OptionArgVector);
311 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
312 AddAlias ("rb", cmd_obj_sp);
313 AddOrReplaceAliasOptions("rb", alias_arguments_vector_sp);
314 }
Chris Lattner24943d22010-06-08 16:52:24 +0000315}
316
Chris Lattner24943d22010-06-08 16:52:24 +0000317const char *
318CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
319{
320 // This function has not yet been implemented.
321
322 // Look for any embedded script command
323 // If found,
324 // get interpreter object from the command dictionary,
325 // call execute_one_command on it,
326 // get the results as a string,
327 // substitute that string for current stuff.
328
329 return arg;
330}
331
332
333void
334CommandInterpreter::LoadCommandDictionary ()
335{
336 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
337
338 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
339 //
340 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
341 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
342 // the cross-referencing stuff) are created!!!
343 //
344 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
345
346
347 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
348 // are created. This is so that when another command is created that needs to go into a crossref object,
349 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
350 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
351
Chris Lattner24943d22010-06-08 16:52:24 +0000352 // Non-CommandObjectCrossref commands can now be created.
353
Caroline Tice5bc8c972010-09-20 20:44:43 +0000354 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000355
Greg Clayton238c0a12010-09-18 01:14:36 +0000356 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000357 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000358 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000359 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000360 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
361 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Claytonabe0fed2011-04-18 08:33:37 +0000362// m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000363 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000364 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Claytone1f50b92011-05-03 22:09:39 +0000365 /// m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000366 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
367 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonb1888f22011-03-19 01:12:21 +0000368 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Enrico Granata6d101882012-09-28 23:57:51 +0000369 m_command_dict["plugin"] = CommandObjectSP (new CommandObjectPlugin (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000370 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000371 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000372 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000373 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000374 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000375 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000376 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
377 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata6b1596d2011-08-16 23:24:13 +0000378 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000379 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chen01acfa72011-09-22 18:04:58 +0000380 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000381
Jim Ingham2753a022012-10-05 19:16:31 +0000382 const char *break_regexes[][2] = {{"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2"},
383 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
384 {"^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
385 {"^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"},
386 {"^(-.*)$", "breakpoint set %1"},
387 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'"},
388 {"^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"}};
389
390 size_t num_regexes = sizeof break_regexes/sizeof(char *[2]);
391
Chris Lattner24943d22010-06-08 16:52:24 +0000392 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000393 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000394 "_regexp-break",
Johnny Chen58edac32012-08-23 00:32:22 +0000395 "Set a breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
396 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
Jim Ingham2753a022012-10-05 19:16:31 +0000397
Chris Lattner24943d22010-06-08 16:52:24 +0000398 if (break_regex_cmd_ap.get())
399 {
Jim Ingham2753a022012-10-05 19:16:31 +0000400 bool success = true;
401 for (size_t i = 0; i < num_regexes; i++)
402 {
403 success = break_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], break_regexes[i][1]);
404 if (!success)
405 break;
406 }
407 success = break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
408
409 if (success)
Chris Lattner24943d22010-06-08 16:52:24 +0000410 {
411 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
412 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
413 }
414 }
Jim Inghame56493f2011-03-22 02:29:32 +0000415
416 std::auto_ptr<CommandObjectRegexCommand>
Jim Ingham2753a022012-10-05 19:16:31 +0000417 tbreak_regex_cmd_ap(new CommandObjectRegexCommand (*this,
418 "_regexp-tbreak",
419 "Set a one shot breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
420 "_regexp-tbreak [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
421
422 if (tbreak_regex_cmd_ap.get())
423 {
424 bool success = true;
425 for (size_t i = 0; i < num_regexes; i++)
426 {
427 // If you add a resultant command string longer than 1024 characters be sure to increase the size of this buffer.
428 char buffer[1024];
429 int num_printed = snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o");
430 assert (num_printed < 1024);
431 success = tbreak_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], buffer);
432 if (!success)
433 break;
434 }
435 success = tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
436
437 if (success)
438 {
439 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
440 m_command_dict[tbreak_regex_cmd_sp->GetCommandName ()] = tbreak_regex_cmd_sp;
441 }
442 }
443
444 std::auto_ptr<CommandObjectRegexCommand>
Johnny Chena47e44b2012-08-24 18:15:45 +0000445 attach_regex_cmd_ap(new CommandObjectRegexCommand (*this,
446 "_regexp-attach",
447 "Attach to a process id if in decimal, otherwise treat the argument as a process name to attach to.",
448 "_regexp-attach [<pid>]\n_regexp-attach [<process-name>]", 2));
449 if (attach_regex_cmd_ap.get())
450 {
451 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "process attach --pid %1") &&
452 attach_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "process attach --name '%1'"))
453 {
454 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
455 m_command_dict[attach_regex_cmd_sp->GetCommandName ()] = attach_regex_cmd_sp;
456 }
457 }
458
459 std::auto_ptr<CommandObjectRegexCommand>
Jim Inghame56493f2011-03-22 02:29:32 +0000460 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000461 "_regexp-down",
462 "Go down \"n\" frames in the stack (1 frame by default).",
463 "_regexp-down [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000464 if (down_regex_cmd_ap.get())
465 {
466 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
467 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
468 {
469 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
470 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
471 }
472 }
473
474 std::auto_ptr<CommandObjectRegexCommand>
475 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000476 "_regexp-up",
477 "Go up \"n\" frames in the stack (1 frame by default).",
478 "_regexp-up [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000479 if (up_regex_cmd_ap.get())
480 {
481 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
482 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
483 {
484 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
485 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
486 }
487 }
Jason Molenda730cae02011-10-22 01:30:52 +0000488
489 std::auto_ptr<CommandObjectRegexCommand>
490 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000491 "_regexp-display",
Jason Molenda730cae02011-10-22 01:30:52 +0000492 "Add an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000493 "_regexp-display expression", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000494 if (display_regex_cmd_ap.get())
495 {
496 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
497 {
498 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
499 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
500 }
501 }
502
503 std::auto_ptr<CommandObjectRegexCommand>
504 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000505 "_regexp-undisplay",
Jason Molenda730cae02011-10-22 01:30:52 +0000506 "Remove an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000507 "_regexp-undisplay stop-hook-number", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000508 if (undisplay_regex_cmd_ap.get())
509 {
510 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
511 {
512 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
513 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
514 }
515 }
516
Greg Claytonc3750432012-09-26 22:26:47 +0000517 std::auto_ptr<CommandObjectRegexCommand>
518 connect_gdb_remote_cmd_ap(new CommandObjectRegexCommand (*this,
519 "gdb-remote",
520 "Connect to a remote GDB server.",
521 "gdb-remote [<host>:<port>]\ngdb-remote [<port>]", 2));
522 if (connect_gdb_remote_cmd_ap.get())
523 {
524 if (connect_gdb_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin gdb-remote connect://%1") &&
525 connect_gdb_remote_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "process connect --plugin gdb-remote connect://localhost:%1"))
526 {
527 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
528 m_command_dict[command_sp->GetCommandName ()] = command_sp;
529 }
530 }
531
532 std::auto_ptr<CommandObjectRegexCommand>
533 connect_kdp_remote_cmd_ap(new CommandObjectRegexCommand (*this,
534 "kdp-remote",
535 "Connect to a remote KDP server.",
536 "kdp-remote [<host>]\nkdp-remote [<host>:<port>]", 2));
537 if (connect_kdp_remote_cmd_ap.get())
538 {
539 if (connect_kdp_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin kdp-remote udp://%1") &&
Jason Molenda73feea42012-09-27 02:47:55 +0000540 connect_kdp_remote_cmd_ap->AddRegexCommand("^(.+)$", "process connect --plugin kdp-remote udp://%1:41139"))
Greg Claytonc3750432012-09-26 22:26:47 +0000541 {
542 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
543 m_command_dict[command_sp->GetCommandName ()] = command_sp;
544 }
545 }
546
Jason Molenda1a48cb72012-10-05 05:29:32 +0000547 std::auto_ptr<CommandObjectRegexCommand>
548 bt_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jim Inghamf190a412012-10-10 16:51:31 +0000549 "_regexp-bt",
Jason Molenda1a48cb72012-10-05 05:29:32 +0000550 "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.",
551 "bt [<digit>|all]", 2));
552 if (bt_regex_cmd_ap.get())
553 {
554 // accept but don't document "bt -c <number>" -- before bt was a regex command if you wanted to backtrace
555 // three frames you would do "bt -c 3" but the intention is to have this emulate the gdb "bt" command and
556 // so now "bt 3" is the preferred form, in line with gdb.
557 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "thread backtrace -c %1") &&
558 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$", "thread backtrace -c %1") &&
559 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
560 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace"))
561 {
562 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
563 m_command_dict[command_sp->GetCommandName ()] = command_sp;
564 }
565 }
566
Chris Lattner24943d22010-06-08 16:52:24 +0000567}
568
569int
570CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
571 StringList &matches)
572{
573 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
574
575 if (include_aliases)
576 {
577 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
578 }
579
580 return matches.GetSize();
581}
582
583CommandObjectSP
584CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
585{
586 CommandObject::CommandMap::iterator pos;
587 CommandObjectSP ret_val;
588
589 std::string cmd(cmd_cstr);
590
591 if (HasCommands())
592 {
593 pos = m_command_dict.find(cmd);
594 if (pos != m_command_dict.end())
595 ret_val = pos->second;
596 }
597
598 if (include_aliases && HasAliases())
599 {
600 pos = m_alias_dict.find(cmd);
601 if (pos != m_alias_dict.end())
602 ret_val = pos->second;
603 }
604
605 if (HasUserCommands())
606 {
607 pos = m_user_dict.find(cmd);
608 if (pos != m_user_dict.end())
609 ret_val = pos->second;
610 }
611
Sean Callananb386d822012-08-09 00:50:26 +0000612 if (!exact && !ret_val)
Chris Lattner24943d22010-06-08 16:52:24 +0000613 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000614 // We will only get into here if we didn't find any exact matches.
615
616 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
617
Chris Lattner24943d22010-06-08 16:52:24 +0000618 StringList local_matches;
619 if (matches == NULL)
620 matches = &local_matches;
621
Jim Inghamd40f8a62010-07-06 22:46:59 +0000622 unsigned int num_cmd_matches = 0;
623 unsigned int num_alias_matches = 0;
624 unsigned int num_user_matches = 0;
625
626 // Look through the command dictionaries one by one, and if we get only one match from any of
627 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
628
Chris Lattner24943d22010-06-08 16:52:24 +0000629 if (HasCommands())
630 {
631 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
632 }
633
634 if (num_cmd_matches == 1)
635 {
636 cmd.assign(matches->GetStringAtIndex(0));
637 pos = m_command_dict.find(cmd);
638 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000639 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000640 }
641
Jim Ingham9a574172010-06-24 20:28:42 +0000642 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000643 {
644 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
645
646 }
647
Jim Inghamd40f8a62010-07-06 22:46:59 +0000648 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000649 {
650 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
651 pos = m_alias_dict.find(cmd);
652 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000653 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000654 }
655
Jim Ingham9a574172010-06-24 20:28:42 +0000656 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000657 {
658 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
659 }
660
Jim Inghamd40f8a62010-07-06 22:46:59 +0000661 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000662 {
663 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
664
665 pos = m_user_dict.find (cmd);
666 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000667 user_match_sp = pos->second;
668 }
669
670 // If we got exactly one match, return that, otherwise return the match list.
671
672 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
673 {
674 if (num_cmd_matches)
675 return real_match_sp;
676 else if (num_alias_matches)
677 return alias_match_sp;
678 else
679 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000680 }
681 }
Sean Callananb386d822012-08-09 00:50:26 +0000682 else if (matches && ret_val)
Jim Inghamd40f8a62010-07-06 22:46:59 +0000683 {
684 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000685 }
686
687
688 return ret_val;
689}
690
Greg Claytond12aeab2011-04-20 16:37:46 +0000691bool
692CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
693{
694 if (name && name[0])
695 {
696 std::string name_sstr(name);
Enrico Granata2f1014b2012-10-01 17:19:37 +0000697 bool found = (m_command_dict.find (name_sstr) != m_command_dict.end());
698 if (found && !can_replace)
699 return false;
700 if (found && m_command_dict[name_sstr]->IsRemovable() == false)
Enrico Granata6d101882012-09-28 23:57:51 +0000701 return false;
Greg Claytond12aeab2011-04-20 16:37:46 +0000702 m_command_dict[name_sstr] = cmd_sp;
703 return true;
704 }
705 return false;
706}
707
Enrico Granata6b1596d2011-08-16 23:24:13 +0000708bool
Enrico Granata6010ace2011-11-07 22:57:04 +0000709CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata6b1596d2011-08-16 23:24:13 +0000710 const lldb::CommandObjectSP &cmd_sp,
711 bool can_replace)
712{
Enrico Granata6010ace2011-11-07 22:57:04 +0000713 if (!name.empty())
Enrico Granata6b1596d2011-08-16 23:24:13 +0000714 {
Enrico Granata6010ace2011-11-07 22:57:04 +0000715
716 const char* name_cstr = name.c_str();
717
718 // do not allow replacement of internal commands
719 if (CommandExists(name_cstr))
Enrico Granata6d101882012-09-28 23:57:51 +0000720 {
721 if (can_replace == false)
722 return false;
723 if (m_command_dict[name]->IsRemovable() == false)
724 return false;
725 }
Enrico Granata6010ace2011-11-07 22:57:04 +0000726
Enrico Granata6d101882012-09-28 23:57:51 +0000727 if (UserCommandExists(name_cstr))
728 {
729 if (can_replace == false)
730 return false;
731 if (m_user_dict[name]->IsRemovable() == false)
732 return false;
733 }
734
Enrico Granata6010ace2011-11-07 22:57:04 +0000735 m_user_dict[name] = cmd_sp;
Enrico Granata6b1596d2011-08-16 23:24:13 +0000736 return true;
737 }
738 return false;
739}
Greg Claytond12aeab2011-04-20 16:37:46 +0000740
Jim Inghamd40f8a62010-07-06 22:46:59 +0000741CommandObjectSP
742CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000743{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000744 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
745 CommandObjectSP ret_val; // Possibly empty return value.
746
747 if (cmd_cstr == NULL)
748 return ret_val;
749
750 if (cmd_words.GetArgumentCount() == 1)
751 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
752 else
753 {
754 // We have a multi-word command (seemingly), so we need to do more work.
755 // First, get the cmd_obj_sp for the first word in the command.
756 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
757 if (cmd_obj_sp.get() != NULL)
758 {
759 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
760 // command name), and find the appropriate sub-command SP for each command word....
761 size_t end = cmd_words.GetArgumentCount();
762 for (size_t j= 1; j < end; ++j)
763 {
764 if (cmd_obj_sp->IsMultiwordObject())
765 {
Greg Clayton13193d52012-10-13 02:07:45 +0000766 cmd_obj_sp = cmd_obj_sp->GetSubcommandSP (cmd_words.GetArgumentAtIndex (j));
Caroline Tice56d2fc42010-12-14 18:51:39 +0000767 if (cmd_obj_sp.get() == NULL)
768 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
769 return ret_val;
770 }
771 else
772 // We have more words in the command name, but we don't have a multiword object. Fail and return
773 // empty 'ret_val'.
774 return ret_val;
775 }
776 // We successfully looped through all the command words and got valid command objects for them. Assign the
777 // last object retrieved to 'ret_val'.
778 ret_val = cmd_obj_sp;
779 }
780 }
781 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000782}
783
784CommandObject *
785CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
786{
787 return GetCommandSPExact (cmd_cstr, include_aliases).get();
788}
789
790CommandObject *
791CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
792{
793 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
794
795 // If we didn't find an exact match to the command string in the commands, look in
796 // the aliases.
797
798 if (command_obj == NULL)
799 {
800 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
801 }
802
803 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
804 // in both the commands and the aliases.
805
806 if (command_obj == NULL)
807 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
808
809 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000810}
811
812bool
813CommandInterpreter::CommandExists (const char *cmd)
814{
815 return m_command_dict.find(cmd) != m_command_dict.end();
816}
817
818bool
Caroline Tice5ddbe212011-05-06 21:37:15 +0000819CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
820 const char *options_args,
821 OptionArgVectorSP &option_arg_vector_sp)
822{
823 bool success = true;
824 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
825
826 if (!options_args || (strlen (options_args) < 1))
827 return true;
828
829 std::string options_string (options_args);
830 Args args (options_args);
831 CommandReturnObject result;
832 // Check to see if the command being aliased can take any command options.
833 Options *options = cmd_obj_sp->GetOptions ();
834 if (options)
835 {
836 // See if any options were specified as part of the alias; if so, handle them appropriately.
837 options->NotifyOptionParsingStarting ();
838 args.Unshift ("dummy_arg");
839 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
840 args.Shift ();
841 if (result.Succeeded())
842 options->VerifyPartialOptions (result);
843 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
844 {
845 result.AppendError ("Unable to create requested alias.\n");
846 return false;
847 }
848 }
849
Greg Clayton7268b4c2011-10-28 21:38:01 +0000850 if (!options_string.empty())
Caroline Tice5ddbe212011-05-06 21:37:15 +0000851 {
852 if (cmd_obj_sp->WantsRawCommandString ())
853 option_arg_vector->push_back (OptionArgPair ("<argument>",
854 OptionArgValue (-1,
855 options_string)));
856 else
857 {
858 int argc = args.GetArgumentCount();
859 for (size_t i = 0; i < argc; ++i)
860 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
861 option_arg_vector->push_back
862 (OptionArgPair ("<argument>",
863 OptionArgValue (-1,
864 std::string (args.GetArgumentAtIndex (i)))));
865 }
866 }
867
868 return success;
869}
870
871bool
Chris Lattner24943d22010-06-08 16:52:24 +0000872CommandInterpreter::AliasExists (const char *cmd)
873{
874 return m_alias_dict.find(cmd) != m_alias_dict.end();
875}
876
877bool
878CommandInterpreter::UserCommandExists (const char *cmd)
879{
880 return m_user_dict.find(cmd) != m_user_dict.end();
881}
882
883void
884CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
885{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000886 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000887 m_alias_dict[alias_name] = command_obj_sp;
888}
889
890bool
891CommandInterpreter::RemoveAlias (const char *alias_name)
892{
893 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
894 if (pos != m_alias_dict.end())
895 {
896 m_alias_dict.erase(pos);
897 return true;
898 }
899 return false;
900}
901bool
902CommandInterpreter::RemoveUser (const char *alias_name)
903{
904 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
905 if (pos != m_user_dict.end())
906 {
907 m_user_dict.erase(pos);
908 return true;
909 }
910 return false;
911}
912
Chris Lattner24943d22010-06-08 16:52:24 +0000913void
914CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
915{
916 help_string.Printf ("'%s", command_name);
917 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
918
Sean Callananb386d822012-08-09 00:50:26 +0000919 if (option_arg_vector_sp)
Chris Lattner24943d22010-06-08 16:52:24 +0000920 {
921 OptionArgVector *options = option_arg_vector_sp.get();
922 for (int i = 0; i < options->size(); ++i)
923 {
924 OptionArgPair cur_option = (*options)[i];
925 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000926 OptionArgValue value_pair = cur_option.second;
927 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000928 if (opt.compare("<argument>") == 0)
929 {
930 help_string.Printf (" %s", value.c_str());
931 }
932 else
933 {
934 help_string.Printf (" %s", opt.c_str());
935 if ((value.compare ("<no-argument>") != 0)
936 && (value.compare ("<need-argument") != 0))
937 {
938 help_string.Printf (" %s", value.c_str());
939 }
940 }
941 }
942 }
943
944 help_string.Printf ("'");
945}
946
Greg Clayton65124ea2010-08-26 22:05:43 +0000947size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000948CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
949{
950 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000951 CommandObject::CommandMap::const_iterator end = dict.end();
952 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000953
Greg Clayton65124ea2010-08-26 22:05:43 +0000954 for (pos = dict.begin(); pos != end; ++pos)
955 {
956 size_t len = pos->first.size();
957 if (max_len < len)
958 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000959 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000960 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000961}
962
963void
Enrico Granata6b1596d2011-08-16 23:24:13 +0000964CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata1ac6d1f2011-09-09 17:49:36 +0000965 uint32_t cmd_types)
Chris Lattner24943d22010-06-08 16:52:24 +0000966{
967 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000968 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata6b1596d2011-08-16 23:24:13 +0000969
970 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner24943d22010-06-08 16:52:24 +0000971 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000972
973 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
974 result.AppendMessage("");
Chris Lattner24943d22010-06-08 16:52:24 +0000975
Enrico Granata6b1596d2011-08-16 23:24:13 +0000976 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
977 {
978 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
979 max_len);
980 }
981 result.AppendMessage("");
982
983 }
984
Greg Clayton7268b4c2011-10-28 21:38:01 +0000985 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner24943d22010-06-08 16:52:24 +0000986 {
Jim Inghame3663e82010-10-22 18:47:16 +0000987 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000988 "(see 'help command alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000989 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000990 max_len = FindLongestCommandWord (m_alias_dict);
991
Chris Lattner24943d22010-06-08 16:52:24 +0000992 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
993 {
994 StreamString sstr;
995 StreamString translation_and_help;
996 std::string entry_name = pos->first;
997 std::string second_entry = pos->second.get()->GetCommandName();
998 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
999
1000 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
1001 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
1002 translation_and_help.GetData(), max_len);
1003 }
1004 result.AppendMessage("");
1005 }
1006
Greg Clayton7268b4c2011-10-28 21:38:01 +00001007 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner24943d22010-06-08 16:52:24 +00001008 {
1009 result.AppendMessage ("The following is a list of your current user-defined commands:");
1010 result.AppendMessage("");
Enrico Granata6b1596d2011-08-16 23:24:13 +00001011 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner24943d22010-06-08 16:52:24 +00001012 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
1013 {
Enrico Granata6b1596d2011-08-16 23:24:13 +00001014 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1015 max_len);
Chris Lattner24943d22010-06-08 16:52:24 +00001016 }
1017 result.AppendMessage("");
1018 }
1019
1020 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
1021}
1022
Caroline Ticee0da7a52010-12-09 22:52:49 +00001023CommandObject *
1024CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +00001025{
Caroline Ticee0da7a52010-12-09 22:52:49 +00001026 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
1027 // eventually be invoked by the given command line.
1028
1029 CommandObject *cmd_obj = NULL;
1030 std::string white_space (" \t\v");
1031 size_t start = command_string.find_first_not_of (white_space);
1032 size_t end = 0;
1033 bool done = false;
1034 while (!done)
1035 {
1036 if (start != std::string::npos)
1037 {
1038 // Get the next word from command_string.
1039 end = command_string.find_first_of (white_space, start);
1040 if (end == std::string::npos)
1041 end = command_string.size();
1042 std::string cmd_word = command_string.substr (start, end - start);
1043
1044 if (cmd_obj == NULL)
1045 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
1046 // command or alias.
1047 cmd_obj = GetCommandObject (cmd_word.c_str());
1048 else if (cmd_obj->IsMultiwordObject ())
1049 {
1050 // 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 +00001051 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (cmd_word.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001052 if (sub_cmd_obj)
1053 cmd_obj = sub_cmd_obj;
1054 else // cmd_word was not a valid sub-command word, so we are donee
1055 done = true;
1056 }
1057 else
1058 // We have a cmd_obj and it is not a multi-word object, so we are done.
1059 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001060
Caroline Ticee0da7a52010-12-09 22:52:49 +00001061 // If we didn't find a valid command object, or our command object is not a multi-word object, or
1062 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
1063 // next word.
1064
1065 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
1066 done = true;
1067 else
1068 start = command_string.find_first_not_of (white_space, end);
1069 }
1070 else
1071 // Unable to find any more words.
1072 done = true;
1073 }
1074
1075 if (end == command_string.size())
1076 command_string.clear();
1077 else
1078 command_string = command_string.substr(end);
1079
1080 return cmd_obj;
1081}
1082
Greg Clayton9d855c62011-10-25 00:36:27 +00001083static const char *k_white_space = " \t\v";
Greg Clayton7268b4c2011-10-28 21:38:01 +00001084static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton9d855c62011-10-25 00:36:27 +00001085static void
1086StripLeadingSpaces (std::string &s)
Caroline Ticee0da7a52010-12-09 22:52:49 +00001087{
Greg Clayton9d855c62011-10-25 00:36:27 +00001088 if (!s.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +00001089 {
Greg Clayton9d855c62011-10-25 00:36:27 +00001090 size_t pos = s.find_first_not_of (k_white_space);
1091 if (pos == std::string::npos)
1092 s.clear();
1093 else if (pos == 0)
1094 return;
1095 s.erase (0, pos);
1096 }
1097}
1098
Greg Clayton3840cd72011-11-09 23:25:03 +00001099static size_t
1100FindArgumentTerminator (const std::string &s)
1101{
Greg Clayton3840cd72011-11-09 23:25:03 +00001102 const size_t s_len = s.size();
1103 size_t offset = 0;
1104 while (offset < s_len)
1105 {
1106 size_t pos = s.find ("--", offset);
1107 if (pos == std::string::npos)
1108 break;
1109 if (pos > 0)
1110 {
1111 if (isspace(s[pos-1]))
1112 {
1113 // Check if the string ends "\s--" (where \s is a space character)
1114 // or if we have "\s--\s".
1115 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
1116 {
Greg Clayton3840cd72011-11-09 23:25:03 +00001117 return pos;
1118 }
1119 }
1120 }
1121 offset = pos + 2;
1122 }
Greg Clayton3840cd72011-11-09 23:25:03 +00001123 return std::string::npos;
1124}
1125
Greg Clayton9d855c62011-10-25 00:36:27 +00001126static bool
Greg Clayton7268b4c2011-10-28 21:38:01 +00001127ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton9d855c62011-10-25 00:36:27 +00001128{
Greg Clayton7268b4c2011-10-28 21:38:01 +00001129 command.clear();
1130 suffix.clear();
Greg Clayton9d855c62011-10-25 00:36:27 +00001131 StripLeadingSpaces (command_string);
1132
1133 bool result = false;
1134 quote_char = '\0';
1135
1136 if (!command_string.empty())
1137 {
1138 const char first_char = command_string[0];
1139 if (first_char == '\'' || first_char == '"')
Caroline Ticee0da7a52010-12-09 22:52:49 +00001140 {
Greg Clayton9d855c62011-10-25 00:36:27 +00001141 quote_char = first_char;
1142 const size_t end_quote_pos = command_string.find (quote_char, 1);
1143 if (end_quote_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +00001144 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001145 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +00001146 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +00001147 }
1148 else
1149 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001150 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton9d855c62011-10-25 00:36:27 +00001151 if (end_quote_pos + 1 < command_string.size())
1152 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
1153 else
1154 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +00001155 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001156 }
1157 else
1158 {
Greg Clayton9d855c62011-10-25 00:36:27 +00001159 const size_t first_space_pos = command_string.find_first_of (k_white_space);
1160 if (first_space_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +00001161 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001162 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +00001163 command_string.erase();
Caroline Tice649116c2011-05-11 16:07:06 +00001164 }
1165 else
1166 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001167 command.assign (command_string, 0, first_space_pos);
1168 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice649116c2011-05-11 16:07:06 +00001169 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001170 }
Greg Clayton9d855c62011-10-25 00:36:27 +00001171 result = true;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001172 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001173
1174
1175 if (!command.empty())
1176 {
1177 // actual commands can't start with '-' or '_'
1178 if (command[0] != '-' && command[0] != '_')
1179 {
1180 size_t pos = command.find_first_not_of(k_valid_command_chars);
1181 if (pos > 0 && pos != std::string::npos)
1182 {
1183 suffix.assign (command.begin() + pos, command.end());
1184 command.erase (pos);
1185 }
1186 }
1187 }
Greg Clayton9d855c62011-10-25 00:36:27 +00001188
1189 return result;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001190}
1191
Greg Clayton7268b4c2011-10-28 21:38:01 +00001192CommandObject *
1193CommandInterpreter::BuildAliasResult (const char *alias_name,
1194 std::string &raw_input_string,
1195 std::string &alias_result,
1196 CommandReturnObject &result)
Caroline Ticee0da7a52010-12-09 22:52:49 +00001197{
Greg Clayton7268b4c2011-10-28 21:38:01 +00001198 CommandObject *alias_cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001199 Args cmd_args (raw_input_string.c_str());
1200 alias_cmd_obj = GetCommandObject (alias_name);
1201 StreamString result_str;
1202
1203 if (alias_cmd_obj)
1204 {
1205 std::string alias_name_str = alias_name;
1206 if ((cmd_args.GetArgumentCount() == 0)
1207 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1208 cmd_args.Unshift (alias_name);
1209
1210 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1211 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1212
1213 if (option_arg_vector_sp.get())
1214 {
1215 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1216
1217 for (int i = 0; i < option_arg_vector->size(); ++i)
1218 {
1219 OptionArgPair option_pair = (*option_arg_vector)[i];
1220 OptionArgValue value_pair = option_pair.second;
1221 int value_type = value_pair.first;
1222 std::string option = option_pair.first;
1223 std::string value = value_pair.second;
1224 if (option.compare ("<argument>") == 0)
1225 result_str.Printf (" %s", value.c_str());
1226 else
1227 {
1228 result_str.Printf (" %s", option.c_str());
1229 if (value_type != optional_argument)
1230 result_str.Printf (" ");
1231 if (value.compare ("<no_argument>") != 0)
1232 {
1233 int index = GetOptionArgumentPosition (value.c_str());
1234 if (index == 0)
1235 result_str.Printf ("%s", value.c_str());
1236 else if (index >= cmd_args.GetArgumentCount())
1237 {
1238
1239 result.AppendErrorWithFormat
1240 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1241 index);
1242 result.SetStatus (eReturnStatusFailed);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001243 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001244 }
1245 else
1246 {
1247 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1248 if (strpos != std::string::npos)
1249 raw_input_string = raw_input_string.erase (strpos,
1250 strlen (cmd_args.GetArgumentAtIndex (index)));
1251 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1252 }
1253 }
1254 }
1255 }
1256 }
1257
1258 alias_result = result_str.GetData();
1259 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001260 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001261}
1262
Greg Claytonf5c0c722011-10-14 07:41:33 +00001263Error
1264CommandInterpreter::PreprocessCommand (std::string &command)
1265{
1266 // The command preprocessor needs to do things to the command
1267 // line before any parsing of arguments or anything else is done.
1268 // The only current stuff that gets proprocessed is anyting enclosed
1269 // in backtick ('`') characters is evaluated as an expression and
1270 // the result of the expression must be a scalar that can be substituted
1271 // into the command. An example would be:
1272 // (lldb) memory read `$rsp + 20`
1273 Error error; // Error for any expressions that might not evaluate
1274 size_t start_backtick;
1275 size_t pos = 0;
1276 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1277 {
1278 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1279 {
1280 // The backtick was preceeded by a '\' character, remove the slash
1281 // and don't treat the backtick as the start of an expression
1282 command.erase(start_backtick-1, 1);
1283 // No need to add one to start_backtick since we just deleted a char
1284 pos = start_backtick;
1285 }
1286 else
1287 {
1288 const size_t expr_content_start = start_backtick + 1;
1289 const size_t end_backtick = command.find ('`', expr_content_start);
1290 if (end_backtick == std::string::npos)
1291 return error;
1292 else if (end_backtick == expr_content_start)
1293 {
1294 // Empty expression (two backticks in a row)
1295 command.erase (start_backtick, 2);
1296 }
1297 else
1298 {
1299 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1300
Greg Claytonbcaf99a2012-07-12 20:32:19 +00001301 ExecutionContext exe_ctx(GetExecutionContext());
1302 Target *target = exe_ctx.GetTargetPtr();
Johnny Chenb09f8472011-10-29 00:21:50 +00001303 // Get a dummy target to allow for calculator mode while processing backticks.
1304 // This also helps break the infinite loop caused when target is null.
1305 if (!target)
1306 target = Host::GetDummyTarget(GetDebugger()).get();
Greg Claytonf5c0c722011-10-14 07:41:33 +00001307 if (target)
1308 {
Greg Claytonf5c0c722011-10-14 07:41:33 +00001309 ValueObjectSP expr_result_valobj_sp;
Enrico Granatad27026e2012-09-05 20:41:26 +00001310
1311 Target::EvaluateExpressionOptions options;
1312 options.SetCoerceToId(false)
1313 .SetUnwindOnError(true)
1314 .SetKeepInMemory(false)
1315 .SetSingleThreadTimeoutUsec(0);
1316
Greg Claytonf5c0c722011-10-14 07:41:33 +00001317 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
Enrico Granatad27026e2012-09-05 20:41:26 +00001318 exe_ctx.GetFramePtr(),
Enrico Granata6cca9692012-07-16 23:10:35 +00001319 expr_result_valobj_sp,
Enrico Granatad27026e2012-09-05 20:41:26 +00001320 options);
1321
Greg Claytonf5c0c722011-10-14 07:41:33 +00001322 if (expr_result == eExecutionCompleted)
1323 {
1324 Scalar scalar;
1325 if (expr_result_valobj_sp->ResolveValue (scalar))
1326 {
1327 command.erase (start_backtick, end_backtick - start_backtick + 1);
1328 StreamString value_strm;
1329 const bool show_type = false;
1330 scalar.GetValue (&value_strm, show_type);
1331 size_t value_string_size = value_strm.GetSize();
1332 if (value_string_size)
1333 {
1334 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1335 pos = start_backtick + value_string_size;
1336 continue;
1337 }
1338 else
1339 {
1340 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1341 }
1342 }
1343 else
1344 {
1345 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1346 }
1347 }
1348 else
1349 {
1350 if (expr_result_valobj_sp)
1351 error = expr_result_valobj_sp->GetError();
1352 if (error.Success())
1353 {
1354
1355 switch (expr_result)
1356 {
1357 case eExecutionSetupError:
1358 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1359 break;
1360 case eExecutionCompleted:
1361 break;
1362 case eExecutionDiscarded:
1363 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1364 break;
1365 case eExecutionInterrupted:
1366 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1367 break;
1368 case eExecutionTimedOut:
1369 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1370 break;
1371 }
1372 }
1373 }
1374 }
1375 }
1376 if (error.Fail())
1377 break;
1378 }
1379 }
1380 return error;
1381}
1382
1383
Caroline Ticee0da7a52010-12-09 22:52:49 +00001384bool
1385CommandInterpreter::HandleCommand (const char *command_line,
Enrico Granata01bc2d42012-05-31 01:09:06 +00001386 LazyBool lazy_add_to_history,
Caroline Ticee0da7a52010-12-09 22:52:49 +00001387 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001388 ExecutionContext *override_context,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001389 bool repeat_on_empty_command,
1390 bool no_context_switching)
Jim Ingham949d5ac2011-02-18 00:54:25 +00001391
Caroline Ticee0da7a52010-12-09 22:52:49 +00001392{
Jim Ingham949d5ac2011-02-18 00:54:25 +00001393
Caroline Ticee0da7a52010-12-09 22:52:49 +00001394 bool done = false;
1395 CommandObject *cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001396 bool wants_raw_input = false;
1397 std::string command_string (command_line);
Jim Ingham6247dbe2011-07-12 03:12:18 +00001398 std::string original_command_string (command_line);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001399
1400 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +00001401 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1402
1403 // Make a scoped cleanup object that will clear the crash description string
1404 // on exit of this function.
Enrico Granata1a102082011-07-12 00:18:11 +00001405 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Claytone98ac252010-11-10 04:57:04 +00001406
Caroline Ticee0da7a52010-12-09 22:52:49 +00001407 if (log)
1408 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +00001409
Jim Inghamabab14b2010-11-04 23:08:45 +00001410 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1411
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001412 if (!no_context_switching)
1413 UpdateExecutionContext (override_context);
Enrico Granata01bc2d42012-05-31 01:09:06 +00001414
1415 // <rdar://problem/11328896>
1416 bool add_to_history;
1417 if (lazy_add_to_history == eLazyBoolCalculate)
1418 add_to_history = (m_command_source_depth == 0);
1419 else
1420 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1421
Jim Ingham949d5ac2011-02-18 00:54:25 +00001422 bool empty_command = false;
1423 bool comment_command = false;
1424 if (command_string.empty())
1425 empty_command = true;
1426 else
Chris Lattner24943d22010-06-08 16:52:24 +00001427 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001428 const char *k_space_characters = "\t\n\v\f\r ";
1429
1430 size_t non_space = command_string.find_first_not_of (k_space_characters);
1431 // Check for empty line or comment line (lines whose first
1432 // non-space character is the comment character for this interpreter)
1433 if (non_space == std::string::npos)
1434 empty_command = true;
1435 else if (command_string[non_space] == m_comment_char)
1436 comment_command = true;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001437 else if (command_string[non_space] == m_repeat_char)
1438 {
1439 const char *history_string = FindHistoryString (command_string.c_str() + non_space);
1440 if (history_string == NULL)
1441 {
1442 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1443 result.SetStatus(eReturnStatusFailed);
1444 return false;
1445 }
1446 add_to_history = false;
1447 command_string = history_string;
1448 original_command_string = history_string;
1449 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001450 }
1451
1452 if (empty_command)
1453 {
1454 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +00001455 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001456 if (m_command_history.empty())
1457 {
1458 result.AppendError ("empty command");
1459 result.SetStatus(eReturnStatusFailed);
1460 return false;
1461 }
1462 else
1463 {
1464 command_line = m_repeat_command.c_str();
1465 command_string = command_line;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001466 original_command_string = command_line;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001467 if (m_repeat_command.empty())
1468 {
1469 result.AppendErrorWithFormat("No auto repeat.\n");
1470 result.SetStatus (eReturnStatusFailed);
1471 return false;
1472 }
1473 }
1474 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001475 }
1476 else
1477 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001478 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1479 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001480 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001481 }
1482 else if (comment_command)
1483 {
1484 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1485 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001486 }
Caroline Tice649116c2011-05-11 16:07:06 +00001487
Greg Claytonf5c0c722011-10-14 07:41:33 +00001488
1489 Error error (PreprocessCommand (command_string));
1490
1491 if (error.Fail())
1492 {
1493 result.AppendError (error.AsCString());
1494 result.SetStatus(eReturnStatusFailed);
1495 return false;
1496 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001497 // Phase 1.
1498
1499 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1500 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1501 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1502 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1503 // 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 +00001504 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +00001505 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +00001506
Caroline Ticee0da7a52010-12-09 22:52:49 +00001507 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001508 size_t actual_cmd_name_len = 0;
Greg Clayton7268b4c2011-10-28 21:38:01 +00001509 std::string next_word;
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001510 StringList matches;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001511 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +00001512 {
Caroline Tice649116c2011-05-11 16:07:06 +00001513 char quote_char = '\0';
Greg Clayton7268b4c2011-10-28 21:38:01 +00001514 std::string suffix;
1515 ExtractCommand (command_string, next_word, suffix, quote_char);
1516 if (cmd_obj == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +00001517 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001518 if (AliasExists (next_word.c_str()))
Caroline Tice56d2fc42010-12-14 18:51:39 +00001519 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001520 std::string alias_result;
1521 cmd_obj = BuildAliasResult (next_word.c_str(), command_string, alias_result, result);
1522 revised_command_line.Printf ("%s", alias_result.c_str());
1523 if (cmd_obj)
1524 {
1525 wants_raw_input = cmd_obj->WantsRawCommandString ();
1526 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1527 }
Chris Lattner24943d22010-06-08 16:52:24 +00001528 }
1529 else
1530 {
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001531 cmd_obj = GetCommandObject (next_word.c_str(), &matches);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001532 if (cmd_obj)
1533 {
1534 actual_cmd_name_len += next_word.length();
1535 revised_command_line.Printf ("%s", next_word.c_str());
1536 wants_raw_input = cmd_obj->WantsRawCommandString ();
1537 }
Caroline Tice649116c2011-05-11 16:07:06 +00001538 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001539 {
1540 revised_command_line.Printf ("%s", next_word.c_str());
1541 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001542 }
1543 }
1544 else
1545 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001546 if (cmd_obj->IsMultiwordObject ())
1547 {
Greg Clayton13193d52012-10-13 02:07:45 +00001548 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (next_word.c_str());
Greg Clayton7268b4c2011-10-28 21:38:01 +00001549 if (sub_cmd_obj)
1550 {
1551 actual_cmd_name_len += next_word.length() + 1;
1552 revised_command_line.Printf (" %s", next_word.c_str());
1553 cmd_obj = sub_cmd_obj;
1554 wants_raw_input = cmd_obj->WantsRawCommandString ();
1555 }
1556 else
1557 {
1558 if (quote_char)
1559 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1560 else
1561 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1562 done = true;
1563 }
1564 }
Caroline Tice649116c2011-05-11 16:07:06 +00001565 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001566 {
1567 if (quote_char)
1568 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1569 else
1570 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1571 done = true;
1572 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001573 }
1574
1575 if (cmd_obj == NULL)
1576 {
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001577 uint32_t num_matches = matches.GetSize();
1578 if (matches.GetSize() > 1) {
1579 std::string error_msg;
1580 error_msg.assign ("Ambiguous command '");
1581 error_msg.append(next_word.c_str());
1582 error_msg.append ("'.");
1583
1584 error_msg.append (" Possible matches:");
1585
1586 for (uint32_t i = 0; i < num_matches; ++i) {
1587 error_msg.append ("\n\t");
1588 error_msg.append (matches.GetStringAtIndex(i));
1589 }
1590 error_msg.append ("\n");
1591 result.AppendRawError (error_msg.c_str(), error_msg.size());
1592 } else {
1593 // We didn't have only one match, otherwise we wouldn't get here.
1594 assert(num_matches == 0);
1595 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1596 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001597 result.SetStatus (eReturnStatusFailed);
1598 return false;
1599 }
1600
Greg Clayton7268b4c2011-10-28 21:38:01 +00001601 if (cmd_obj->IsMultiwordObject ())
1602 {
1603 if (!suffix.empty())
1604 {
1605
1606 result.AppendErrorWithFormat ("multi-word commands ('%s') can't have shorthand suffixes: '%s'\n",
1607 next_word.c_str(),
1608 suffix.c_str());
1609 result.SetStatus (eReturnStatusFailed);
1610 return false;
1611 }
1612 }
1613 else
1614 {
1615 // If we found a normal command, we are done
1616 done = true;
1617 if (!suffix.empty())
1618 {
1619 switch (suffix[0])
1620 {
1621 case '/':
1622 // GDB format suffixes
Greg Claytond8a218d2011-10-29 00:57:28 +00001623 {
1624 Options *command_options = cmd_obj->GetOptions();
1625 if (command_options && command_options->SupportsLongOption("gdb-format"))
1626 {
Greg Clayton3840cd72011-11-09 23:25:03 +00001627 std::string gdb_format_option ("--gdb-format=");
1628 gdb_format_option += (suffix.c_str() + 1);
1629
1630 bool inserted = false;
1631 std::string &cmd = revised_command_line.GetString();
1632 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1633 if (arg_terminator_idx != std::string::npos)
1634 {
1635 // Insert the gdb format option before the "--" that terminates options
1636 gdb_format_option.append(1,' ');
1637 cmd.insert(arg_terminator_idx, gdb_format_option);
1638 inserted = true;
1639 }
1640
1641 if (!inserted)
1642 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1643
1644 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1645 revised_command_line.PutCString (" --");
Greg Claytond8a218d2011-10-29 00:57:28 +00001646 }
1647 else
1648 {
1649 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1650 cmd_obj->GetCommandName());
1651 result.SetStatus (eReturnStatusFailed);
1652 return false;
1653 }
1654 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001655 break;
Johnny Chen8ca450b2011-10-31 22:22:06 +00001656
1657 default:
1658 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1659 suffix.c_str());
1660 result.SetStatus (eReturnStatusFailed);
1661 return false;
1662
Greg Clayton7268b4c2011-10-28 21:38:01 +00001663 }
1664 }
1665 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001666 if (command_string.length() == 0)
1667 done = true;
1668
Chris Lattner24943d22010-06-08 16:52:24 +00001669 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001670
Greg Clayton7268b4c2011-10-28 21:38:01 +00001671 if (!command_string.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +00001672 revised_command_line.Printf (" %s", command_string.c_str());
1673
1674 // End of Phase 1.
1675 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1676 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1677 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1678 // wants_raw_input specifies whether the Execute method expects raw input or not.
1679
1680
1681 if (log)
1682 {
1683 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1684 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1685 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1686 }
1687
1688 // Phase 2.
1689 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1690 // CommandObject, with the appropriate arguments.
1691
1692 if (cmd_obj != NULL)
1693 {
1694 if (add_to_history)
1695 {
1696 Args command_args (revised_command_line.GetData());
1697 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1698 if (repeat_command != NULL)
1699 m_repeat_command.assign(repeat_command);
1700 else
Jim Ingham6247dbe2011-07-12 03:12:18 +00001701 m_repeat_command.assign(original_command_string.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001702
Jim Ingham6247dbe2011-07-12 03:12:18 +00001703 // Don't keep pushing the same command onto the history...
Greg Clayton7268b4c2011-10-28 21:38:01 +00001704 if (m_command_history.empty() || m_command_history.back() != original_command_string)
Jim Ingham6247dbe2011-07-12 03:12:18 +00001705 m_command_history.push_back (original_command_string);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001706 }
1707
1708 command_string = revised_command_line.GetData();
1709 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001710 std::string remainder;
1711 if (actual_cmd_name_len < command_string.length())
1712 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1713 // than cmd_obj->GetCommandName(), because name completion
1714 // allows users to enter short versions of the names,
1715 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +00001716
1717 // Remove any initial spaces
1718 std::string white_space (" \t\v");
1719 size_t pos = remainder.find_first_not_of (white_space);
1720 if (pos != 0 && pos != std::string::npos)
Greg Clayton91c9dcf2011-04-22 20:58:45 +00001721 remainder.erase(0, pos);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001722
1723 if (log)
Jason Molenda24c991c2011-08-25 00:20:04 +00001724 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001725
Jim Inghamda26bd22012-06-08 21:56:10 +00001726 cmd_obj->Execute (remainder.c_str(), result);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001727 }
1728 else
1729 {
1730 // We didn't find the first command object, so complete the first argument.
1731 Args command_args (revised_command_line.GetData());
1732 StringList matches;
1733 int num_matches;
1734 int cursor_index = 0;
1735 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1736 bool word_complete;
1737 num_matches = HandleCompletionMatches (command_args,
1738 cursor_index,
1739 cursor_char_position,
1740 0,
1741 -1,
1742 word_complete,
1743 matches);
1744
1745 if (num_matches > 0)
1746 {
1747 std::string error_msg;
1748 error_msg.assign ("ambiguous command '");
1749 error_msg.append(command_args.GetArgumentAtIndex(0));
1750 error_msg.append ("'.");
1751
1752 error_msg.append (" Possible completions:");
1753 for (int i = 0; i < num_matches; i++)
1754 {
1755 error_msg.append ("\n\t");
1756 error_msg.append (matches.GetStringAtIndex (i));
1757 }
1758 error_msg.append ("\n");
1759 result.AppendRawError (error_msg.c_str(), error_msg.size());
1760 }
1761 else
1762 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1763
1764 result.SetStatus (eReturnStatusFailed);
1765 }
1766
Jason Molenda24c991c2011-08-25 00:20:04 +00001767 if (log)
1768 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1769
Chris Lattner24943d22010-06-08 16:52:24 +00001770 return result.Succeeded();
1771}
1772
1773int
1774CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1775 int &cursor_index,
1776 int &cursor_char_position,
1777 int match_start_point,
1778 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001779 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001780 StringList &matches)
1781{
1782 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001783 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001784
1785 // For any of the command completions a unique match will be a complete word.
1786 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001787
1788 if (cursor_index == -1)
1789 {
1790 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001791 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001792 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1793 }
1794 else if (cursor_index == 0)
1795 {
1796 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001797 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001798 num_command_matches = matches.GetSize();
1799
1800 if (num_command_matches == 1
1801 && cmd_obj && cmd_obj->IsMultiwordObject()
1802 && matches.GetStringAtIndex(0) != NULL
1803 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1804 {
1805 look_for_subcommand = true;
1806 num_command_matches = 0;
1807 matches.DeleteStringAtIndex(0);
1808 parsed_line.AppendArgument ("");
1809 cursor_index++;
1810 cursor_char_position = 0;
1811 }
1812 }
1813
1814 if (cursor_index > 0 || look_for_subcommand)
1815 {
1816 // We are completing further on into a commands arguments, so find the command and tell it
1817 // to complete the command.
1818 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001819 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001820 if (command_object == NULL)
1821 {
1822 return 0;
1823 }
1824 else
1825 {
1826 parsed_line.Shift();
1827 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001828 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001829 cursor_index,
1830 cursor_char_position,
1831 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001832 max_return_elements,
1833 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001834 matches);
1835 }
1836 }
1837
1838 return num_command_matches;
1839
1840}
1841
1842int
1843CommandInterpreter::HandleCompletion (const char *current_line,
1844 const char *cursor,
1845 const char *last_char,
1846 int match_start_point,
1847 int max_return_elements,
1848 StringList &matches)
1849{
1850 // We parse the argument up to the cursor, so the last argument in parsed_line is
1851 // the one containing the cursor, and the cursor is after the last character.
1852
1853 Args parsed_line(current_line, last_char - current_line);
1854 Args partial_parsed_line(current_line, cursor - current_line);
1855
Jim Ingham6247dbe2011-07-12 03:12:18 +00001856 // Don't complete comments, and if the line we are completing is just the history repeat character,
1857 // substitute the appropriate history line.
1858 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1859 if (first_arg)
1860 {
1861 if (first_arg[0] == m_comment_char)
1862 return 0;
1863 else if (first_arg[0] == m_repeat_char)
1864 {
1865 const char *history_string = FindHistoryString (first_arg);
1866 if (history_string != NULL)
1867 {
1868 matches.Clear();
1869 matches.InsertStringAtIndex(0, history_string);
1870 return -2;
1871 }
1872 else
1873 return 0;
1874
1875 }
1876 }
1877
1878
Chris Lattner24943d22010-06-08 16:52:24 +00001879 int num_args = partial_parsed_line.GetArgumentCount();
1880 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1881 int cursor_char_position;
1882
1883 if (cursor_index == -1)
1884 cursor_char_position = 0;
1885 else
1886 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001887
1888 if (cursor > current_line && cursor[-1] == ' ')
1889 {
1890 // We are just after a space. If we are in an argument, then we will continue
1891 // parsing, but if we are between arguments, then we have to complete whatever the next
1892 // element would be.
1893 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1894 // protected by a quote) then the space will also be in the parsed argument...
1895
1896 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1897 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1898 {
1899 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1900 cursor_index++;
1901 cursor_char_position = 0;
1902 }
1903 }
Chris Lattner24943d22010-06-08 16:52:24 +00001904
1905 int num_command_matches;
1906
1907 matches.Clear();
1908
1909 // Only max_return_elements == -1 is supported at present:
1910 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001911 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001912 num_command_matches = HandleCompletionMatches (parsed_line,
1913 cursor_index,
1914 cursor_char_position,
1915 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001916 max_return_elements,
1917 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001918 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001919
1920 if (num_command_matches <= 0)
1921 return num_command_matches;
1922
1923 if (num_args == 0)
1924 {
1925 // If we got an empty string, insert nothing.
1926 matches.InsertStringAtIndex(0, "");
1927 }
1928 else
1929 {
1930 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1931 // put an empty string in element 0.
1932 std::string command_partial_str;
1933 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001934 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1935 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001936
1937 std::string common_prefix;
1938 matches.LongestCommonPrefix (common_prefix);
1939 int partial_name_len = command_partial_str.size();
1940
1941 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001942 // Only do this if the completer told us this was a complete word, however...
1943 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001944 {
1945 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1946 if (quote_char != '\0')
1947 common_prefix.push_back(quote_char);
1948
1949 common_prefix.push_back(' ');
1950 }
1951 common_prefix.erase (0, partial_name_len);
1952 matches.InsertStringAtIndex(0, common_prefix.c_str());
1953 }
1954 return num_command_matches;
1955}
1956
Chris Lattner24943d22010-06-08 16:52:24 +00001957
1958CommandInterpreter::~CommandInterpreter ()
1959{
1960}
1961
1962const char *
1963CommandInterpreter::GetPrompt ()
1964{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001965 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001966}
1967
1968void
1969CommandInterpreter::SetPrompt (const char *new_prompt)
1970{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001971 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001972}
1973
Jim Ingham5e16ef52010-10-04 19:49:29 +00001974size_t
Greg Clayton58928562011-02-09 01:08:52 +00001975CommandInterpreter::GetConfirmationInputReaderCallback
1976(
1977 void *baton,
1978 InputReader &reader,
1979 lldb::InputReaderAction action,
1980 const char *bytes,
1981 size_t bytes_len
1982)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001983{
Greg Clayton58928562011-02-09 01:08:52 +00001984 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001985 bool *response_ptr = (bool *) baton;
1986
1987 switch (action)
1988 {
1989 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001990 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001991 {
1992 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001993 {
Greg Clayton58928562011-02-09 01:08:52 +00001994 out_file.Printf ("%s", reader.GetPrompt());
1995 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001996 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001997 }
1998 break;
1999
2000 case eInputReaderDeactivate:
2001 break;
2002
2003 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00002004 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00002005 {
Greg Clayton58928562011-02-09 01:08:52 +00002006 out_file.Printf ("%s", reader.GetPrompt());
2007 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00002008 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00002009 break;
Caroline Tice4a348082011-05-02 20:41:46 +00002010
2011 case eInputReaderAsynchronousOutputWritten:
2012 break;
2013
Jim Ingham5e16ef52010-10-04 19:49:29 +00002014 case eInputReaderGotToken:
2015 if (bytes_len == 0)
2016 {
2017 reader.SetIsDone(true);
2018 }
Jim Ingham36fe9912011-11-14 20:02:01 +00002019 else if (bytes[0] == 'y' || bytes[0] == 'Y')
Jim Ingham5e16ef52010-10-04 19:49:29 +00002020 {
2021 *response_ptr = true;
2022 reader.SetIsDone(true);
2023 }
Jim Ingham36fe9912011-11-14 20:02:01 +00002024 else if (bytes[0] == 'n' || bytes[0] == 'N')
Jim Ingham5e16ef52010-10-04 19:49:29 +00002025 {
2026 *response_ptr = false;
2027 reader.SetIsDone(true);
2028 }
2029 else
2030 {
Greg Clayton58928562011-02-09 01:08:52 +00002031 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00002032 {
Jim Ingham26183802011-11-17 01:22:00 +00002033 out_file.Printf ("Please answer \"y\" or \"n\".\n%s", reader.GetPrompt());
Greg Clayton58928562011-02-09 01:08:52 +00002034 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00002035 }
2036 }
2037 break;
2038
Caroline Ticec4f55fe2010-11-19 20:47:54 +00002039 case eInputReaderInterrupt:
2040 case eInputReaderEndOfFile:
2041 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
2042 reader.SetIsDone (true);
2043 break;
2044
Jim Ingham5e16ef52010-10-04 19:49:29 +00002045 case eInputReaderDone:
2046 break;
2047 }
2048
2049 return bytes_len;
2050
2051}
2052
2053bool
2054CommandInterpreter::Confirm (const char *message, bool default_answer)
2055{
Jim Ingham93057472010-10-04 22:44:14 +00002056 // Check AutoConfirm first:
2057 if (m_debugger.GetAutoConfirm())
2058 return default_answer;
2059
Jim Ingham5e16ef52010-10-04 19:49:29 +00002060 InputReaderSP reader_sp (new InputReader(GetDebugger()));
2061 bool response = default_answer;
2062 if (reader_sp)
2063 {
2064 std::string prompt(message);
2065 prompt.append(": [");
2066 if (default_answer)
2067 prompt.append ("Y/n] ");
2068 else
2069 prompt.append ("y/N] ");
2070
2071 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
2072 &response, // baton
2073 eInputReaderGranularityLine, // token size, to pass to callback function
2074 NULL, // end token
2075 prompt.c_str(), // prompt
2076 true)); // echo input
2077 if (err.Success())
2078 {
2079 GetDebugger().PushInputReader (reader_sp);
2080 }
2081 reader_sp->WaitOnReaderIsDone();
2082 }
2083 return response;
2084}
2085
2086
Chris Lattner24943d22010-06-08 16:52:24 +00002087void
2088CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
2089{
Jim Inghamd40f8a62010-07-06 22:46:59 +00002090 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00002091
Sean Callananb386d822012-08-09 00:50:26 +00002092 if (cmd_obj_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002093 {
2094 CommandObject *cmd_obj = cmd_obj_sp.get();
2095 if (cmd_obj->IsCrossRefObject ())
2096 cmd_obj->AddObject (object_type);
2097 }
2098}
2099
Chris Lattner24943d22010-06-08 16:52:24 +00002100OptionArgVectorSP
2101CommandInterpreter::GetAliasOptions (const char *alias_name)
2102{
2103 OptionArgMap::iterator pos;
2104 OptionArgVectorSP ret_val;
2105
2106 std::string alias (alias_name);
2107
2108 if (HasAliasOptions())
2109 {
2110 pos = m_alias_options.find (alias);
2111 if (pos != m_alias_options.end())
2112 ret_val = pos->second;
2113 }
2114
2115 return ret_val;
2116}
2117
2118void
2119CommandInterpreter::RemoveAliasOptions (const char *alias_name)
2120{
2121 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
2122 if (pos != m_alias_options.end())
2123 {
2124 m_alias_options.erase (pos);
2125 }
2126}
2127
2128void
2129CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
2130{
2131 m_alias_options[alias_name] = option_arg_vector_sp;
2132}
2133
2134bool
2135CommandInterpreter::HasCommands ()
2136{
2137 return (!m_command_dict.empty());
2138}
2139
2140bool
2141CommandInterpreter::HasAliases ()
2142{
2143 return (!m_alias_dict.empty());
2144}
2145
2146bool
2147CommandInterpreter::HasUserCommands ()
2148{
2149 return (!m_user_dict.empty());
2150}
2151
2152bool
2153CommandInterpreter::HasAliasOptions ()
2154{
2155 return (!m_alias_options.empty());
2156}
2157
Chris Lattner24943d22010-06-08 16:52:24 +00002158void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002159CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2160 const char *alias_name,
2161 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00002162 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002163 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00002164{
2165 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00002166
2167 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00002168
Caroline Tice44c841d2010-12-07 19:58:26 +00002169 // Make sure that the alias name is the 0th element in cmd_args
2170 std::string alias_name_str = alias_name;
2171 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2172 cmd_args.Unshift (alias_name);
2173
2174 Args new_args (alias_cmd_obj->GetCommandName());
2175 if (new_args.GetArgumentCount() == 2)
2176 new_args.Shift();
2177
Chris Lattner24943d22010-06-08 16:52:24 +00002178 if (option_arg_vector_sp.get())
2179 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002180 if (wants_raw_input)
2181 {
2182 // We have a command that both has command options and takes raw input. Make *sure* it has a
2183 // " -- " in the right place in the raw_input_string.
2184 size_t pos = raw_input_string.find(" -- ");
2185 if (pos == std::string::npos)
2186 {
2187 // None found; assume it goes at the beginning of the raw input string
2188 raw_input_string.insert (0, " -- ");
2189 }
2190 }
Chris Lattner24943d22010-06-08 16:52:24 +00002191
2192 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
2193 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002194 std::vector<bool> used (old_size + 1, false);
2195
2196 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002197
2198 for (int i = 0; i < option_arg_vector->size(); ++i)
2199 {
2200 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00002201 OptionArgValue value_pair = option_pair.second;
2202 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00002203 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00002204 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00002205 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002206 {
2207 if (!wants_raw_input
2208 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2209 new_args.AppendArgument (value.c_str());
2210 }
Chris Lattner24943d22010-06-08 16:52:24 +00002211 else
2212 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002213 if (value_type != optional_argument)
2214 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00002215 if (value.compare ("<no-argument>") != 0)
2216 {
2217 int index = GetOptionArgumentPosition (value.c_str());
2218 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002219 {
Chris Lattner24943d22010-06-08 16:52:24 +00002220 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00002221 if (value_type != optional_argument)
2222 new_args.AppendArgument (value.c_str());
2223 else
2224 {
2225 char buffer[255];
2226 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2227 new_args.AppendArgument (buffer);
2228 }
2229
2230 }
Chris Lattner24943d22010-06-08 16:52:24 +00002231 else if (index >= cmd_args.GetArgumentCount())
2232 {
2233 result.AppendErrorWithFormat
2234 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2235 index);
2236 result.SetStatus (eReturnStatusFailed);
2237 return;
2238 }
2239 else
2240 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002241 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2242 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2243 if (strpos != std::string::npos)
2244 {
2245 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2246 }
2247
2248 if (value_type != optional_argument)
2249 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2250 else
2251 {
2252 char buffer[255];
2253 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2254 cmd_args.GetArgumentAtIndex (index));
2255 new_args.AppendArgument (buffer);
2256 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002257 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002258 }
2259 }
2260 }
2261 }
2262
2263 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
2264 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002265 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00002266 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2267 }
2268
2269 cmd_args.Clear();
2270 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2271 }
2272 else
2273 {
2274 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00002275 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2276 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2277 // input string.
2278 if (wants_raw_input)
2279 {
2280 cmd_args.Clear();
2281 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2282 }
Chris Lattner24943d22010-06-08 16:52:24 +00002283 return;
2284 }
2285
2286 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2287 return;
2288}
2289
2290
2291int
2292CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2293{
2294 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2295 // of zero.
2296
2297 char *cptr = (char *) in_string;
2298
2299 // Does it start with '%'
2300 if (cptr[0] == '%')
2301 {
2302 ++cptr;
2303
2304 // Is the rest of it entirely digits?
2305 if (isdigit (cptr[0]))
2306 {
2307 const char *start = cptr;
2308 while (isdigit (cptr[0]))
2309 ++cptr;
2310
2311 // We've gotten to the end of the digits; are we at the end of the string?
2312 if (cptr[0] == '\0')
2313 position = atoi (start);
2314 }
2315 }
2316
2317 return position;
2318}
2319
2320void
2321CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2322{
Jim Ingham574c3d62011-08-12 23:34:31 +00002323 FileSpec init_file;
Greg Claytond6edcb52011-09-11 00:01:44 +00002324 if (in_cwd)
Jim Ingham574c3d62011-08-12 23:34:31 +00002325 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002326 // In the current working directory we don't load any program specific
2327 // .lldbinit files, we only look for a "./.lldbinit" file.
2328 if (m_skip_lldbinit_files)
2329 return;
2330
2331 init_file.SetFile ("./.lldbinit", true);
Jim Ingham574c3d62011-08-12 23:34:31 +00002332 }
Greg Claytond6edcb52011-09-11 00:01:44 +00002333 else
Jim Ingham574c3d62011-08-12 23:34:31 +00002334 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002335 // If we aren't looking in the current working directory we are looking
2336 // in the home directory. We will first see if there is an application
2337 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2338 // "-" and the name of the program. If this file doesn't exist, we fall
2339 // back to just the "~/.lldbinit" file. We also obey any requests to not
2340 // load the init files.
2341 const char *init_file_path = "~/.lldbinit";
2342
2343 if (m_skip_app_init_files == false)
2344 {
2345 FileSpec program_file_spec (Host::GetProgramFileSpec());
2346 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham574c3d62011-08-12 23:34:31 +00002347
Greg Claytond6edcb52011-09-11 00:01:44 +00002348 if (program_name)
2349 {
2350 char program_init_file_name[PATH_MAX];
2351 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2352 init_file.SetFile (program_init_file_name, true);
2353 if (!init_file.Exists())
2354 init_file.Clear();
2355 }
2356 }
2357
2358 if (!init_file && !m_skip_lldbinit_files)
2359 init_file.SetFile (init_file_path, true);
2360 }
2361
Chris Lattner24943d22010-06-08 16:52:24 +00002362 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2363 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2364
2365 if (init_file.Exists())
2366 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00002367 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
2368 bool stop_on_continue = true;
2369 bool stop_on_error = false;
2370 bool echo_commands = false;
2371 bool print_results = false;
2372
Enrico Granata01bc2d42012-05-31 01:09:06 +00002373 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, eLazyBoolNo, result);
Chris Lattner24943d22010-06-08 16:52:24 +00002374 }
2375 else
2376 {
2377 // nothing to be done if the file doesn't exist
2378 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2379 }
2380}
2381
Greg Claytonb72d0f02011-04-12 05:54:46 +00002382PlatformSP
2383CommandInterpreter::GetPlatform (bool prefer_target_platform)
2384{
2385 PlatformSP platform_sp;
Greg Clayton567e7f32011-09-22 04:58:26 +00002386 if (prefer_target_platform)
2387 {
Greg Claytonbcaf99a2012-07-12 20:32:19 +00002388 ExecutionContext exe_ctx(GetExecutionContext());
2389 Target *target = exe_ctx.GetTargetPtr();
Greg Clayton567e7f32011-09-22 04:58:26 +00002390 if (target)
2391 platform_sp = target->GetPlatform();
2392 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002393
2394 if (!platform_sp)
2395 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2396 return platform_sp;
2397}
2398
Jim Ingham949d5ac2011-02-18 00:54:25 +00002399void
Jim Inghama4fede32011-03-11 01:51:49 +00002400CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002401 ExecutionContext *override_context,
2402 bool stop_on_continue,
2403 bool stop_on_error,
2404 bool echo_commands,
2405 bool print_results,
Enrico Granata01bc2d42012-05-31 01:09:06 +00002406 LazyBool add_to_history,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002407 CommandReturnObject &result)
2408{
2409 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00002410
2411 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2412 // Make sure you reset this value anywhere you return from the function.
2413
2414 bool old_async_execution = m_debugger.GetAsyncExecution();
2415
2416 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2417 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2418
2419 if (override_context != NULL)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002420 UpdateExecutionContext (override_context);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002421
2422 if (!stop_on_continue)
2423 {
2424 m_debugger.SetAsyncExecution (false);
2425 }
2426
2427 for (int idx = 0; idx < num_lines; idx++)
2428 {
2429 const char *cmd = commands.GetStringAtIndex(idx);
2430 if (cmd[0] == '\0')
2431 continue;
2432
Jim Ingham949d5ac2011-02-18 00:54:25 +00002433 if (echo_commands)
2434 {
2435 result.AppendMessageWithFormat ("%s %s\n",
2436 GetPrompt(),
2437 cmd);
2438 }
2439
Greg Claytonaa378b12011-02-20 02:15:07 +00002440 CommandReturnObject tmp_result;
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002441 // If override_context is not NULL, pass no_context_switching = true for
2442 // HandleCommand() since we updated our context already.
Enrico Granata01bc2d42012-05-31 01:09:06 +00002443 bool success = HandleCommand(cmd, add_to_history, tmp_result,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002444 NULL, /* override_context */
2445 true, /* repeat_on_empty_command */
2446 override_context != NULL /* no_context_switching */);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002447
2448 if (print_results)
2449 {
2450 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002451 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002452 }
2453
2454 if (!success || !tmp_result.Succeeded())
2455 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002456 const char *error_msg = tmp_result.GetErrorData();
2457 if (error_msg == NULL || error_msg[0] == '\0')
2458 error_msg = "<unknown error>.\n";
Jim Ingham949d5ac2011-02-18 00:54:25 +00002459 if (stop_on_error)
2460 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002461 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed with %s",
2462 idx, cmd, error_msg);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002463 result.SetStatus (eReturnStatusFailed);
2464 m_debugger.SetAsyncExecution (old_async_execution);
2465 return;
2466 }
2467 else if (print_results)
2468 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002469 result.AppendMessageWithFormat ("Command #%d '%s' failed with %s",
Jim Ingham949d5ac2011-02-18 00:54:25 +00002470 idx + 1,
2471 cmd,
Jim Ingham862fd5c2012-04-24 02:25:07 +00002472 error_msg);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002473 }
2474 }
2475
Caroline Tice4a348082011-05-02 20:41:46 +00002476 if (result.GetImmediateOutputStream())
2477 result.GetImmediateOutputStream()->Flush();
2478
2479 if (result.GetImmediateErrorStream())
2480 result.GetImmediateErrorStream()->Flush();
2481
Jim Ingham949d5ac2011-02-18 00:54:25 +00002482 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2483 // could be running (for instance in Breakpoint Commands.
2484 // So we check the return value to see if it is has running in it.
2485 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2486 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2487 {
2488 if (stop_on_continue)
2489 {
2490 // If we caused the target to proceed, and we're going to stop in that case, set the
2491 // status in our real result before returning. This is an error if the continue was not the
2492 // last command in the set of commands to be run.
2493 if (idx != num_lines - 1)
2494 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
2495 idx + 1, cmd);
2496 else
2497 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
2498
2499 result.SetStatus(tmp_result.GetStatus());
2500 m_debugger.SetAsyncExecution (old_async_execution);
2501
2502 return;
2503 }
2504 }
2505
2506 }
2507
2508 result.SetStatus (eReturnStatusSuccessFinishResult);
2509 m_debugger.SetAsyncExecution (old_async_execution);
2510
2511 return;
2512}
2513
2514void
2515CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2516 ExecutionContext *context,
2517 bool stop_on_continue,
2518 bool stop_on_error,
2519 bool echo_command,
2520 bool print_result,
Enrico Granata01bc2d42012-05-31 01:09:06 +00002521 LazyBool add_to_history,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002522 CommandReturnObject &result)
2523{
2524 if (cmd_file.Exists())
2525 {
2526 bool success;
2527 StringList commands;
2528 success = commands.ReadFileLines(cmd_file);
2529 if (!success)
2530 {
2531 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2532 result.SetStatus (eReturnStatusFailed);
2533 return;
2534 }
Enrico Granata01bc2d42012-05-31 01:09:06 +00002535 m_command_source_depth++;
2536 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, add_to_history, result);
2537 m_command_source_depth--;
Jim Ingham949d5ac2011-02-18 00:54:25 +00002538 }
2539 else
2540 {
2541 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2542 cmd_file.GetFilename().AsCString());
2543 result.SetStatus (eReturnStatusFailed);
2544 return;
2545 }
2546}
2547
Chris Lattner24943d22010-06-08 16:52:24 +00002548ScriptInterpreter *
2549CommandInterpreter::GetScriptInterpreter ()
2550{
Enrico Granatac5c10a42012-07-10 18:23:48 +00002551 // <rdar://problem/11751427>
2552 // we need to protect the initialization of the script interpreter
2553 // otherwise we could end up with two threads both trying to create
2554 // their instance of it, and for some languages (e.g. Python)
2555 // this is a bulletproof recipe for disaster!
2556 // this needs to be a function-level static because multiple Debugger instances living in the same process
2557 // still need to be isolated and not try to initialize Python concurrently
Enrico Granatab88c0a92012-07-10 19:04:14 +00002558 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive);
2559 Mutex::Locker interpreter_lock(g_interpreter_mutex);
Enrico Granatac5c10a42012-07-10 18:23:48 +00002560
Caroline Tice0aa2e552011-01-14 00:29:16 +00002561 if (m_script_interpreter_ap.get() != NULL)
2562 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00002563
Caroline Tice0aa2e552011-01-14 00:29:16 +00002564 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2565 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00002566 {
Greg Clayton3e4238d2011-11-04 03:34:56 +00002567 case eScriptLanguagePython:
2568#ifndef LLDB_DISABLE_PYTHON
2569 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2570 break;
2571#else
2572 // Fall through to the None case when python is disabled
2573#endif
Caroline Tice0aa2e552011-01-14 00:29:16 +00002574 case eScriptLanguageNone:
2575 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2576 break;
Caroline Tice0aa2e552011-01-14 00:29:16 +00002577 default:
2578 break;
2579 };
2580
2581 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00002582}
2583
2584
2585
2586bool
2587CommandInterpreter::GetSynchronous ()
2588{
2589 return m_synchronous_execution;
2590}
2591
2592void
2593CommandInterpreter::SetSynchronous (bool value)
2594{
Johnny Chend7a4eb02010-10-14 01:22:03 +00002595 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00002596}
2597
2598void
2599CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2600 const char *word_text,
2601 const char *separator,
2602 const char *help_text,
2603 uint32_t max_word_len)
2604{
Greg Clayton238c0a12010-09-18 01:14:36 +00002605 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2606
Chris Lattner24943d22010-06-08 16:52:24 +00002607 int indent_size = max_word_len + strlen (separator) + 2;
2608
2609 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00002610
2611 StreamString text_strm;
2612 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2613
2614 size_t len = text_strm.GetSize();
2615 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00002616 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00002617 {
2618 text_strm.EOL();
2619 len = text_strm.GetSize();
2620 }
Chris Lattner24943d22010-06-08 16:52:24 +00002621
2622 if (len < max_columns)
2623 {
2624 // Output it as a single line.
2625 strm.Printf ("%s", text);
2626 }
2627 else
2628 {
2629 // We need to break it up into multiple lines.
2630 bool first_line = true;
2631 int text_width;
2632 int start = 0;
2633 int end = start;
2634 int final_end = strlen (text);
2635 int sub_len;
2636
2637 while (end < final_end)
2638 {
2639 if (first_line)
2640 text_width = max_columns - 1;
2641 else
2642 text_width = max_columns - indent_size - 1;
2643
2644 // Don't start the 'text' on a space, since we're already outputting the indentation.
2645 if (!first_line)
2646 {
2647 while ((start < final_end) && (text[start] == ' '))
2648 start++;
2649 }
2650
2651 end = start + text_width;
2652 if (end > final_end)
2653 end = final_end;
2654 else
2655 {
2656 // If we're not at the end of the text, make sure we break the line on white space.
2657 while (end > start
2658 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2659 end--;
Greg Clayton73844aa2012-08-22 17:17:09 +00002660 assert (end > 0);
Chris Lattner24943d22010-06-08 16:52:24 +00002661 }
2662
2663 sub_len = end - start;
2664 if (start != 0)
2665 strm.EOL();
2666 if (!first_line)
2667 strm.Indent();
2668 else
2669 first_line = false;
2670 assert (start <= final_end);
2671 assert (start + sub_len <= final_end);
2672 if (sub_len > 0)
2673 strm.Write (text + start, sub_len);
2674 start = end + 1;
2675 }
2676 }
2677 strm.EOL();
2678 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00002679}
2680
2681void
Enrico Granata1bba6e52011-07-07 00:38:40 +00002682CommandInterpreter::OutputHelpText (Stream &strm,
2683 const char *word_text,
2684 const char *separator,
2685 const char *help_text,
2686 uint32_t max_word_len)
2687{
2688 int indent_size = max_word_len + strlen (separator) + 2;
2689
2690 strm.IndentMore (indent_size);
2691
2692 StreamString text_strm;
2693 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2694
2695 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Enrico Granata1bba6e52011-07-07 00:38:40 +00002696
2697 size_t len = text_strm.GetSize();
2698 const char *text = text_strm.GetData();
2699
2700 uint32_t chars_left = max_columns;
2701
2702 for (uint32_t i = 0; i < len; i++)
2703 {
2704 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2705 {
Enrico Granata1bba6e52011-07-07 00:38:40 +00002706 chars_left = max_columns - indent_size;
2707 strm.EOL();
2708 strm.Indent();
2709 }
2710 else
2711 {
2712 strm.PutChar(text[i]);
2713 chars_left--;
2714 }
2715
2716 }
2717
2718 strm.EOL();
2719 strm.IndentLess(indent_size);
2720}
2721
2722void
Chris Lattner24943d22010-06-08 16:52:24 +00002723CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2724 StringList &commands_help)
2725{
2726 CommandObject::CommandMap::const_iterator pos;
2727
2728 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2729 {
2730 const char *command_name = pos->first.c_str();
2731 CommandObject *cmd_obj = pos->second.get();
2732
Greg Clayton238c0a12010-09-18 01:14:36 +00002733 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002734 {
2735 commands_found.AppendString (command_name);
2736 commands_help.AppendString (cmd_obj->GetHelp());
2737 }
2738
2739 if (cmd_obj->IsMultiwordObject())
Greg Clayton13193d52012-10-13 02:07:45 +00002740 cmd_obj->AproposAllSubCommands (command_name,
2741 search_word,
2742 commands_found,
2743 commands_help);
Chris Lattner24943d22010-06-08 16:52:24 +00002744
2745 }
2746}
Greg Claytonb72d0f02011-04-12 05:54:46 +00002747
2748
2749void
2750CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2751{
Greg Claytonb72d0f02011-04-12 05:54:46 +00002752 if (override_context != NULL)
2753 {
Greg Claytonbcaf99a2012-07-12 20:32:19 +00002754 m_exe_ctx_ref = *override_context;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002755 }
2756 else
2757 {
Greg Claytonbcaf99a2012-07-12 20:32:19 +00002758 const bool adopt_selected = true;
2759 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002760 }
2761}
2762
Jim Ingham6247dbe2011-07-12 03:12:18 +00002763void
2764CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2765{
2766 DumpHistory (stream, 0, count - 1);
2767}
2768
2769void
2770CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2771{
Greg Clayton7268b4c2011-10-28 21:38:01 +00002772 const size_t last_idx = std::min<size_t>(m_command_history.size(), end + 1);
2773 for (size_t i = start; i < last_idx; i++)
Jim Ingham6247dbe2011-07-12 03:12:18 +00002774 {
2775 if (!m_command_history[i].empty())
2776 {
2777 stream.Indent();
Greg Clayton7268b4c2011-10-28 21:38:01 +00002778 stream.Printf ("%4zu: %s\n", i, m_command_history[i].c_str());
Jim Ingham6247dbe2011-07-12 03:12:18 +00002779 }
2780 }
2781}
2782
2783const char *
2784CommandInterpreter::FindHistoryString (const char *input_str) const
2785{
2786 if (input_str[0] != m_repeat_char)
2787 return NULL;
2788 if (input_str[1] == '-')
2789 {
2790 bool success;
2791 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
2792 if (!success)
2793 return NULL;
2794 if (idx > m_command_history.size())
2795 return NULL;
2796 idx = m_command_history.size() - idx;
2797 return m_command_history[idx].c_str();
2798
2799 }
2800 else if (input_str[1] == m_repeat_char)
2801 {
2802 if (m_command_history.empty())
2803 return NULL;
2804 else
2805 return m_command_history.back().c_str();
2806 }
2807 else
2808 {
2809 bool success;
2810 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2811 if (!success)
2812 return NULL;
2813 if (idx >= m_command_history.size())
2814 return NULL;
2815 return m_command_history[idx].c_str();
2816 }
2817}