blob: 85d7a8953df0d7d143d817840742f6d8211e2b09 [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
Caroline Tice5ddbe212011-05-06 21:37:15 +0000246 cmd_obj_sp = GetCommandSPExact ("target create", false);
247 if (cmd_obj_sp)
248 AddAlias ("file", cmd_obj_sp);
249
250 cmd_obj_sp = GetCommandSPExact ("target modules", false);
251 if (cmd_obj_sp)
252 AddAlias ("image", cmd_obj_sp);
253
254
255 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghame56493f2011-03-22 02:29:32 +0000256
Caroline Tice5ddbe212011-05-06 21:37:15 +0000257 cmd_obj_sp = GetCommandSPExact ("expression", false);
258 if (cmd_obj_sp)
259 {
260 AddAlias ("expr", cmd_obj_sp);
261
262 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
263 AddAlias ("p", cmd_obj_sp);
264 AddAlias ("print", cmd_obj_sp);
Sean Callanan59959eb2012-08-08 01:30:34 +0000265 AddAlias ("call", cmd_obj_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000266 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
267 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
Sean Callanan59959eb2012-08-08 01:30:34 +0000268 AddOrReplaceAliasOptions ("call", alias_arguments_vector_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000269
270 alias_arguments_vector_sp.reset (new OptionArgVector);
271 ProcessAliasOptionsArgs (cmd_obj_sp, "-o --", alias_arguments_vector_sp);
272 AddAlias ("po", cmd_obj_sp);
273 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
274 }
275
Sean Callananee301fa2012-06-01 23:29:32 +0000276 cmd_obj_sp = GetCommandSPExact ("process kill", false);
277 if (cmd_obj_sp)
Greg Claytonf2e53a52012-09-27 00:02:27 +0000278 {
Sean Callananee301fa2012-06-01 23:29:32 +0000279 AddAlias ("kill", cmd_obj_sp);
Greg Claytonf2e53a52012-09-27 00:02:27 +0000280 }
Sean Callananee301fa2012-06-01 23:29:32 +0000281
Caroline Tice5ddbe212011-05-06 21:37:15 +0000282 cmd_obj_sp = GetCommandSPExact ("process launch", false);
283 if (cmd_obj_sp)
284 {
285 alias_arguments_vector_sp.reset (new OptionArgVector);
Jason Molenda36eb7c02012-07-06 02:46:23 +0000286#if defined (__arm__)
287 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
288#else
Greg Clayton86c50d72012-05-18 00:04:38 +0000289 ProcessAliasOptionsArgs (cmd_obj_sp, "--shell=/bin/bash --", alias_arguments_vector_sp);
Jason Molenda36eb7c02012-07-06 02:46:23 +0000290#endif
Caroline Tice5ddbe212011-05-06 21:37:15 +0000291 AddAlias ("r", cmd_obj_sp);
292 AddAlias ("run", cmd_obj_sp);
293 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
294 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
295 }
Greg Claytonc84623f2012-03-29 21:47:51 +0000296
297 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
298 if (cmd_obj_sp)
299 {
300 AddAlias ("add-dsym", cmd_obj_sp);
301 }
Sean Callanan7b71b172012-05-21 18:25:19 +0000302
303 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
304 if (cmd_obj_sp)
305 {
306 alias_arguments_vector_sp.reset (new OptionArgVector);
307 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
308 AddAlias ("rb", cmd_obj_sp);
309 AddOrReplaceAliasOptions("rb", alias_arguments_vector_sp);
310 }
Chris Lattner24943d22010-06-08 16:52:24 +0000311}
312
Chris Lattner24943d22010-06-08 16:52:24 +0000313const char *
314CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
315{
316 // This function has not yet been implemented.
317
318 // Look for any embedded script command
319 // If found,
320 // get interpreter object from the command dictionary,
321 // call execute_one_command on it,
322 // get the results as a string,
323 // substitute that string for current stuff.
324
325 return arg;
326}
327
328
329void
330CommandInterpreter::LoadCommandDictionary ()
331{
332 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
333
334 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
335 //
336 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
337 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
338 // the cross-referencing stuff) are created!!!
339 //
340 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
341
342
343 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
344 // are created. This is so that when another command is created that needs to go into a crossref object,
345 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
346 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
347
Chris Lattner24943d22010-06-08 16:52:24 +0000348 // Non-CommandObjectCrossref commands can now be created.
349
Caroline Tice5bc8c972010-09-20 20:44:43 +0000350 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000351
Greg Clayton238c0a12010-09-18 01:14:36 +0000352 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000353 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000354 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000355 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000356 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
357 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Claytonabe0fed2011-04-18 08:33:37 +0000358// m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000359 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000360 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Claytone1f50b92011-05-03 22:09:39 +0000361 /// m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000362 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
363 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonb1888f22011-03-19 01:12:21 +0000364 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Enrico Granata6d101882012-09-28 23:57:51 +0000365 m_command_dict["plugin"] = CommandObjectSP (new CommandObjectPlugin (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000366 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000367 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000368 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000369 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000370 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000371 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000372 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
373 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata6b1596d2011-08-16 23:24:13 +0000374 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000375 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chen01acfa72011-09-22 18:04:58 +0000376 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000377
Jim Ingham2753a022012-10-05 19:16:31 +0000378 const char *break_regexes[][2] = {{"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2"},
379 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
380 {"^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
381 {"^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"},
382 {"^(-.*)$", "breakpoint set %1"},
383 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'"},
384 {"^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"}};
385
386 size_t num_regexes = sizeof break_regexes/sizeof(char *[2]);
387
Chris Lattner24943d22010-06-08 16:52:24 +0000388 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000389 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000390 "_regexp-break",
Johnny Chen58edac32012-08-23 00:32:22 +0000391 "Set a breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
392 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
Jim Ingham2753a022012-10-05 19:16:31 +0000393
Chris Lattner24943d22010-06-08 16:52:24 +0000394 if (break_regex_cmd_ap.get())
395 {
Jim Ingham2753a022012-10-05 19:16:31 +0000396 bool success = true;
397 for (size_t i = 0; i < num_regexes; i++)
398 {
399 success = break_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], break_regexes[i][1]);
400 if (!success)
401 break;
402 }
403 success = break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
404
405 if (success)
Chris Lattner24943d22010-06-08 16:52:24 +0000406 {
407 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
408 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
409 }
410 }
Jim Inghame56493f2011-03-22 02:29:32 +0000411
412 std::auto_ptr<CommandObjectRegexCommand>
Jim Ingham2753a022012-10-05 19:16:31 +0000413 tbreak_regex_cmd_ap(new CommandObjectRegexCommand (*this,
414 "_regexp-tbreak",
415 "Set a one shot breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
416 "_regexp-tbreak [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
417
418 if (tbreak_regex_cmd_ap.get())
419 {
420 bool success = true;
421 for (size_t i = 0; i < num_regexes; i++)
422 {
423 // If you add a resultant command string longer than 1024 characters be sure to increase the size of this buffer.
424 char buffer[1024];
425 int num_printed = snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o");
426 assert (num_printed < 1024);
427 success = tbreak_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], buffer);
428 if (!success)
429 break;
430 }
431 success = tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
432
433 if (success)
434 {
435 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
436 m_command_dict[tbreak_regex_cmd_sp->GetCommandName ()] = tbreak_regex_cmd_sp;
437 }
438 }
439
440 std::auto_ptr<CommandObjectRegexCommand>
Johnny Chena47e44b2012-08-24 18:15:45 +0000441 attach_regex_cmd_ap(new CommandObjectRegexCommand (*this,
442 "_regexp-attach",
443 "Attach to a process id if in decimal, otherwise treat the argument as a process name to attach to.",
444 "_regexp-attach [<pid>]\n_regexp-attach [<process-name>]", 2));
445 if (attach_regex_cmd_ap.get())
446 {
447 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "process attach --pid %1") &&
448 attach_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "process attach --name '%1'"))
449 {
450 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
451 m_command_dict[attach_regex_cmd_sp->GetCommandName ()] = attach_regex_cmd_sp;
452 }
453 }
454
455 std::auto_ptr<CommandObjectRegexCommand>
Jim Inghame56493f2011-03-22 02:29:32 +0000456 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000457 "_regexp-down",
458 "Go down \"n\" frames in the stack (1 frame by default).",
459 "_regexp-down [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000460 if (down_regex_cmd_ap.get())
461 {
462 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
463 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
464 {
465 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
466 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
467 }
468 }
469
470 std::auto_ptr<CommandObjectRegexCommand>
471 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000472 "_regexp-up",
473 "Go up \"n\" frames in the stack (1 frame by default).",
474 "_regexp-up [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000475 if (up_regex_cmd_ap.get())
476 {
477 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
478 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
479 {
480 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
481 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
482 }
483 }
Jason Molenda730cae02011-10-22 01:30:52 +0000484
485 std::auto_ptr<CommandObjectRegexCommand>
486 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000487 "_regexp-display",
Jason Molenda730cae02011-10-22 01:30:52 +0000488 "Add an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000489 "_regexp-display expression", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000490 if (display_regex_cmd_ap.get())
491 {
492 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
493 {
494 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
495 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
496 }
497 }
498
499 std::auto_ptr<CommandObjectRegexCommand>
500 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000501 "_regexp-undisplay",
Jason Molenda730cae02011-10-22 01:30:52 +0000502 "Remove an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000503 "_regexp-undisplay stop-hook-number", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000504 if (undisplay_regex_cmd_ap.get())
505 {
506 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
507 {
508 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
509 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
510 }
511 }
512
Greg Claytonc3750432012-09-26 22:26:47 +0000513 std::auto_ptr<CommandObjectRegexCommand>
514 connect_gdb_remote_cmd_ap(new CommandObjectRegexCommand (*this,
515 "gdb-remote",
516 "Connect to a remote GDB server.",
517 "gdb-remote [<host>:<port>]\ngdb-remote [<port>]", 2));
518 if (connect_gdb_remote_cmd_ap.get())
519 {
520 if (connect_gdb_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin gdb-remote connect://%1") &&
521 connect_gdb_remote_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "process connect --plugin gdb-remote connect://localhost:%1"))
522 {
523 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
524 m_command_dict[command_sp->GetCommandName ()] = command_sp;
525 }
526 }
527
528 std::auto_ptr<CommandObjectRegexCommand>
529 connect_kdp_remote_cmd_ap(new CommandObjectRegexCommand (*this,
530 "kdp-remote",
531 "Connect to a remote KDP server.",
532 "kdp-remote [<host>]\nkdp-remote [<host>:<port>]", 2));
533 if (connect_kdp_remote_cmd_ap.get())
534 {
535 if (connect_kdp_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin kdp-remote udp://%1") &&
Jason Molenda73feea42012-09-27 02:47:55 +0000536 connect_kdp_remote_cmd_ap->AddRegexCommand("^(.+)$", "process connect --plugin kdp-remote udp://%1:41139"))
Greg Claytonc3750432012-09-26 22:26:47 +0000537 {
538 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
539 m_command_dict[command_sp->GetCommandName ()] = command_sp;
540 }
541 }
542
Jason Molenda1a48cb72012-10-05 05:29:32 +0000543 std::auto_ptr<CommandObjectRegexCommand>
544 bt_regex_cmd_ap(new CommandObjectRegexCommand (*this,
545 "bt",
546 "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.",
547 "bt [<digit>|all]", 2));
548 if (bt_regex_cmd_ap.get())
549 {
550 // accept but don't document "bt -c <number>" -- before bt was a regex command if you wanted to backtrace
551 // three frames you would do "bt -c 3" but the intention is to have this emulate the gdb "bt" command and
552 // so now "bt 3" is the preferred form, in line with gdb.
553 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "thread backtrace -c %1") &&
554 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$", "thread backtrace -c %1") &&
555 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
556 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace"))
557 {
558 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
559 m_command_dict[command_sp->GetCommandName ()] = command_sp;
560 }
561 }
562
Chris Lattner24943d22010-06-08 16:52:24 +0000563}
564
565int
566CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
567 StringList &matches)
568{
569 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
570
571 if (include_aliases)
572 {
573 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
574 }
575
576 return matches.GetSize();
577}
578
579CommandObjectSP
580CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
581{
582 CommandObject::CommandMap::iterator pos;
583 CommandObjectSP ret_val;
584
585 std::string cmd(cmd_cstr);
586
587 if (HasCommands())
588 {
589 pos = m_command_dict.find(cmd);
590 if (pos != m_command_dict.end())
591 ret_val = pos->second;
592 }
593
594 if (include_aliases && HasAliases())
595 {
596 pos = m_alias_dict.find(cmd);
597 if (pos != m_alias_dict.end())
598 ret_val = pos->second;
599 }
600
601 if (HasUserCommands())
602 {
603 pos = m_user_dict.find(cmd);
604 if (pos != m_user_dict.end())
605 ret_val = pos->second;
606 }
607
Sean Callananb386d822012-08-09 00:50:26 +0000608 if (!exact && !ret_val)
Chris Lattner24943d22010-06-08 16:52:24 +0000609 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000610 // We will only get into here if we didn't find any exact matches.
611
612 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
613
Chris Lattner24943d22010-06-08 16:52:24 +0000614 StringList local_matches;
615 if (matches == NULL)
616 matches = &local_matches;
617
Jim Inghamd40f8a62010-07-06 22:46:59 +0000618 unsigned int num_cmd_matches = 0;
619 unsigned int num_alias_matches = 0;
620 unsigned int num_user_matches = 0;
621
622 // Look through the command dictionaries one by one, and if we get only one match from any of
623 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
624
Chris Lattner24943d22010-06-08 16:52:24 +0000625 if (HasCommands())
626 {
627 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
628 }
629
630 if (num_cmd_matches == 1)
631 {
632 cmd.assign(matches->GetStringAtIndex(0));
633 pos = m_command_dict.find(cmd);
634 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000635 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000636 }
637
Jim Ingham9a574172010-06-24 20:28:42 +0000638 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000639 {
640 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
641
642 }
643
Jim Inghamd40f8a62010-07-06 22:46:59 +0000644 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000645 {
646 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
647 pos = m_alias_dict.find(cmd);
648 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000649 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000650 }
651
Jim Ingham9a574172010-06-24 20:28:42 +0000652 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000653 {
654 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
655 }
656
Jim Inghamd40f8a62010-07-06 22:46:59 +0000657 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000658 {
659 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
660
661 pos = m_user_dict.find (cmd);
662 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000663 user_match_sp = pos->second;
664 }
665
666 // If we got exactly one match, return that, otherwise return the match list.
667
668 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
669 {
670 if (num_cmd_matches)
671 return real_match_sp;
672 else if (num_alias_matches)
673 return alias_match_sp;
674 else
675 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000676 }
677 }
Sean Callananb386d822012-08-09 00:50:26 +0000678 else if (matches && ret_val)
Jim Inghamd40f8a62010-07-06 22:46:59 +0000679 {
680 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000681 }
682
683
684 return ret_val;
685}
686
Greg Claytond12aeab2011-04-20 16:37:46 +0000687bool
688CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
689{
690 if (name && name[0])
691 {
692 std::string name_sstr(name);
Enrico Granata2f1014b2012-10-01 17:19:37 +0000693 bool found = (m_command_dict.find (name_sstr) != m_command_dict.end());
694 if (found && !can_replace)
695 return false;
696 if (found && m_command_dict[name_sstr]->IsRemovable() == false)
Enrico Granata6d101882012-09-28 23:57:51 +0000697 return false;
Greg Claytond12aeab2011-04-20 16:37:46 +0000698 m_command_dict[name_sstr] = cmd_sp;
699 return true;
700 }
701 return false;
702}
703
Enrico Granata6b1596d2011-08-16 23:24:13 +0000704bool
Enrico Granata6010ace2011-11-07 22:57:04 +0000705CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata6b1596d2011-08-16 23:24:13 +0000706 const lldb::CommandObjectSP &cmd_sp,
707 bool can_replace)
708{
Enrico Granata6010ace2011-11-07 22:57:04 +0000709 if (!name.empty())
Enrico Granata6b1596d2011-08-16 23:24:13 +0000710 {
Enrico Granata6010ace2011-11-07 22:57:04 +0000711
712 const char* name_cstr = name.c_str();
713
714 // do not allow replacement of internal commands
715 if (CommandExists(name_cstr))
Enrico Granata6d101882012-09-28 23:57:51 +0000716 {
717 if (can_replace == false)
718 return false;
719 if (m_command_dict[name]->IsRemovable() == false)
720 return false;
721 }
Enrico Granata6010ace2011-11-07 22:57:04 +0000722
Enrico Granata6d101882012-09-28 23:57:51 +0000723 if (UserCommandExists(name_cstr))
724 {
725 if (can_replace == false)
726 return false;
727 if (m_user_dict[name]->IsRemovable() == false)
728 return false;
729 }
730
Enrico Granata6010ace2011-11-07 22:57:04 +0000731 m_user_dict[name] = cmd_sp;
Enrico Granata6b1596d2011-08-16 23:24:13 +0000732 return true;
733 }
734 return false;
735}
Greg Claytond12aeab2011-04-20 16:37:46 +0000736
Jim Inghamd40f8a62010-07-06 22:46:59 +0000737CommandObjectSP
738CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000739{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000740 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
741 CommandObjectSP ret_val; // Possibly empty return value.
742
743 if (cmd_cstr == NULL)
744 return ret_val;
745
746 if (cmd_words.GetArgumentCount() == 1)
747 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
748 else
749 {
750 // We have a multi-word command (seemingly), so we need to do more work.
751 // First, get the cmd_obj_sp for the first word in the command.
752 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
753 if (cmd_obj_sp.get() != NULL)
754 {
755 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
756 // command name), and find the appropriate sub-command SP for each command word....
757 size_t end = cmd_words.GetArgumentCount();
758 for (size_t j= 1; j < end; ++j)
759 {
760 if (cmd_obj_sp->IsMultiwordObject())
761 {
762 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
763 (cmd_words.GetArgumentAtIndex (j));
764 if (cmd_obj_sp.get() == NULL)
765 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
766 return ret_val;
767 }
768 else
769 // We have more words in the command name, but we don't have a multiword object. Fail and return
770 // empty 'ret_val'.
771 return ret_val;
772 }
773 // We successfully looped through all the command words and got valid command objects for them. Assign the
774 // last object retrieved to 'ret_val'.
775 ret_val = cmd_obj_sp;
776 }
777 }
778 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000779}
780
781CommandObject *
782CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
783{
784 return GetCommandSPExact (cmd_cstr, include_aliases).get();
785}
786
787CommandObject *
788CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
789{
790 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
791
792 // If we didn't find an exact match to the command string in the commands, look in
793 // the aliases.
794
795 if (command_obj == NULL)
796 {
797 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
798 }
799
800 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
801 // in both the commands and the aliases.
802
803 if (command_obj == NULL)
804 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
805
806 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000807}
808
809bool
810CommandInterpreter::CommandExists (const char *cmd)
811{
812 return m_command_dict.find(cmd) != m_command_dict.end();
813}
814
815bool
Caroline Tice5ddbe212011-05-06 21:37:15 +0000816CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
817 const char *options_args,
818 OptionArgVectorSP &option_arg_vector_sp)
819{
820 bool success = true;
821 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
822
823 if (!options_args || (strlen (options_args) < 1))
824 return true;
825
826 std::string options_string (options_args);
827 Args args (options_args);
828 CommandReturnObject result;
829 // Check to see if the command being aliased can take any command options.
830 Options *options = cmd_obj_sp->GetOptions ();
831 if (options)
832 {
833 // See if any options were specified as part of the alias; if so, handle them appropriately.
834 options->NotifyOptionParsingStarting ();
835 args.Unshift ("dummy_arg");
836 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
837 args.Shift ();
838 if (result.Succeeded())
839 options->VerifyPartialOptions (result);
840 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
841 {
842 result.AppendError ("Unable to create requested alias.\n");
843 return false;
844 }
845 }
846
Greg Clayton7268b4c2011-10-28 21:38:01 +0000847 if (!options_string.empty())
Caroline Tice5ddbe212011-05-06 21:37:15 +0000848 {
849 if (cmd_obj_sp->WantsRawCommandString ())
850 option_arg_vector->push_back (OptionArgPair ("<argument>",
851 OptionArgValue (-1,
852 options_string)));
853 else
854 {
855 int argc = args.GetArgumentCount();
856 for (size_t i = 0; i < argc; ++i)
857 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
858 option_arg_vector->push_back
859 (OptionArgPair ("<argument>",
860 OptionArgValue (-1,
861 std::string (args.GetArgumentAtIndex (i)))));
862 }
863 }
864
865 return success;
866}
867
868bool
Chris Lattner24943d22010-06-08 16:52:24 +0000869CommandInterpreter::AliasExists (const char *cmd)
870{
871 return m_alias_dict.find(cmd) != m_alias_dict.end();
872}
873
874bool
875CommandInterpreter::UserCommandExists (const char *cmd)
876{
877 return m_user_dict.find(cmd) != m_user_dict.end();
878}
879
880void
881CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
882{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000883 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000884 m_alias_dict[alias_name] = command_obj_sp;
885}
886
887bool
888CommandInterpreter::RemoveAlias (const char *alias_name)
889{
890 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
891 if (pos != m_alias_dict.end())
892 {
893 m_alias_dict.erase(pos);
894 return true;
895 }
896 return false;
897}
898bool
899CommandInterpreter::RemoveUser (const char *alias_name)
900{
901 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
902 if (pos != m_user_dict.end())
903 {
904 m_user_dict.erase(pos);
905 return true;
906 }
907 return false;
908}
909
Chris Lattner24943d22010-06-08 16:52:24 +0000910void
911CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
912{
913 help_string.Printf ("'%s", command_name);
914 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
915
Sean Callananb386d822012-08-09 00:50:26 +0000916 if (option_arg_vector_sp)
Chris Lattner24943d22010-06-08 16:52:24 +0000917 {
918 OptionArgVector *options = option_arg_vector_sp.get();
919 for (int i = 0; i < options->size(); ++i)
920 {
921 OptionArgPair cur_option = (*options)[i];
922 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000923 OptionArgValue value_pair = cur_option.second;
924 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000925 if (opt.compare("<argument>") == 0)
926 {
927 help_string.Printf (" %s", value.c_str());
928 }
929 else
930 {
931 help_string.Printf (" %s", opt.c_str());
932 if ((value.compare ("<no-argument>") != 0)
933 && (value.compare ("<need-argument") != 0))
934 {
935 help_string.Printf (" %s", value.c_str());
936 }
937 }
938 }
939 }
940
941 help_string.Printf ("'");
942}
943
Greg Clayton65124ea2010-08-26 22:05:43 +0000944size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000945CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
946{
947 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000948 CommandObject::CommandMap::const_iterator end = dict.end();
949 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000950
Greg Clayton65124ea2010-08-26 22:05:43 +0000951 for (pos = dict.begin(); pos != end; ++pos)
952 {
953 size_t len = pos->first.size();
954 if (max_len < len)
955 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000956 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000957 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000958}
959
960void
Enrico Granata6b1596d2011-08-16 23:24:13 +0000961CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata1ac6d1f2011-09-09 17:49:36 +0000962 uint32_t cmd_types)
Chris Lattner24943d22010-06-08 16:52:24 +0000963{
964 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000965 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata6b1596d2011-08-16 23:24:13 +0000966
967 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner24943d22010-06-08 16:52:24 +0000968 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000969
970 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
971 result.AppendMessage("");
Chris Lattner24943d22010-06-08 16:52:24 +0000972
Enrico Granata6b1596d2011-08-16 23:24:13 +0000973 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
974 {
975 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
976 max_len);
977 }
978 result.AppendMessage("");
979
980 }
981
Greg Clayton7268b4c2011-10-28 21:38:01 +0000982 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner24943d22010-06-08 16:52:24 +0000983 {
Jim Inghame3663e82010-10-22 18:47:16 +0000984 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000985 "(see 'help command alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000986 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000987 max_len = FindLongestCommandWord (m_alias_dict);
988
Chris Lattner24943d22010-06-08 16:52:24 +0000989 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
990 {
991 StreamString sstr;
992 StreamString translation_and_help;
993 std::string entry_name = pos->first;
994 std::string second_entry = pos->second.get()->GetCommandName();
995 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
996
997 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
998 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
999 translation_and_help.GetData(), max_len);
1000 }
1001 result.AppendMessage("");
1002 }
1003
Greg Clayton7268b4c2011-10-28 21:38:01 +00001004 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner24943d22010-06-08 16:52:24 +00001005 {
1006 result.AppendMessage ("The following is a list of your current user-defined commands:");
1007 result.AppendMessage("");
Enrico Granata6b1596d2011-08-16 23:24:13 +00001008 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner24943d22010-06-08 16:52:24 +00001009 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
1010 {
Enrico Granata6b1596d2011-08-16 23:24:13 +00001011 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1012 max_len);
Chris Lattner24943d22010-06-08 16:52:24 +00001013 }
1014 result.AppendMessage("");
1015 }
1016
1017 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
1018}
1019
Caroline Ticee0da7a52010-12-09 22:52:49 +00001020CommandObject *
1021CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +00001022{
Caroline Ticee0da7a52010-12-09 22:52:49 +00001023 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
1024 // eventually be invoked by the given command line.
1025
1026 CommandObject *cmd_obj = NULL;
1027 std::string white_space (" \t\v");
1028 size_t start = command_string.find_first_not_of (white_space);
1029 size_t end = 0;
1030 bool done = false;
1031 while (!done)
1032 {
1033 if (start != std::string::npos)
1034 {
1035 // Get the next word from command_string.
1036 end = command_string.find_first_of (white_space, start);
1037 if (end == std::string::npos)
1038 end = command_string.size();
1039 std::string cmd_word = command_string.substr (start, end - start);
1040
1041 if (cmd_obj == NULL)
1042 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
1043 // command or alias.
1044 cmd_obj = GetCommandObject (cmd_word.c_str());
1045 else if (cmd_obj->IsMultiwordObject ())
1046 {
1047 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
1048 CommandObject *sub_cmd_obj =
1049 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
1050 if (sub_cmd_obj)
1051 cmd_obj = sub_cmd_obj;
1052 else // cmd_word was not a valid sub-command word, so we are donee
1053 done = true;
1054 }
1055 else
1056 // We have a cmd_obj and it is not a multi-word object, so we are done.
1057 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001058
Caroline Ticee0da7a52010-12-09 22:52:49 +00001059 // If we didn't find a valid command object, or our command object is not a multi-word object, or
1060 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
1061 // next word.
1062
1063 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
1064 done = true;
1065 else
1066 start = command_string.find_first_not_of (white_space, end);
1067 }
1068 else
1069 // Unable to find any more words.
1070 done = true;
1071 }
1072
1073 if (end == command_string.size())
1074 command_string.clear();
1075 else
1076 command_string = command_string.substr(end);
1077
1078 return cmd_obj;
1079}
1080
Greg Clayton9d855c62011-10-25 00:36:27 +00001081static const char *k_white_space = " \t\v";
Greg Clayton7268b4c2011-10-28 21:38:01 +00001082static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton9d855c62011-10-25 00:36:27 +00001083static void
1084StripLeadingSpaces (std::string &s)
Caroline Ticee0da7a52010-12-09 22:52:49 +00001085{
Greg Clayton9d855c62011-10-25 00:36:27 +00001086 if (!s.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +00001087 {
Greg Clayton9d855c62011-10-25 00:36:27 +00001088 size_t pos = s.find_first_not_of (k_white_space);
1089 if (pos == std::string::npos)
1090 s.clear();
1091 else if (pos == 0)
1092 return;
1093 s.erase (0, pos);
1094 }
1095}
1096
Greg Clayton3840cd72011-11-09 23:25:03 +00001097static size_t
1098FindArgumentTerminator (const std::string &s)
1099{
Greg Clayton3840cd72011-11-09 23:25:03 +00001100 const size_t s_len = s.size();
1101 size_t offset = 0;
1102 while (offset < s_len)
1103 {
1104 size_t pos = s.find ("--", offset);
1105 if (pos == std::string::npos)
1106 break;
1107 if (pos > 0)
1108 {
1109 if (isspace(s[pos-1]))
1110 {
1111 // Check if the string ends "\s--" (where \s is a space character)
1112 // or if we have "\s--\s".
1113 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
1114 {
Greg Clayton3840cd72011-11-09 23:25:03 +00001115 return pos;
1116 }
1117 }
1118 }
1119 offset = pos + 2;
1120 }
Greg Clayton3840cd72011-11-09 23:25:03 +00001121 return std::string::npos;
1122}
1123
Greg Clayton9d855c62011-10-25 00:36:27 +00001124static bool
Greg Clayton7268b4c2011-10-28 21:38:01 +00001125ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton9d855c62011-10-25 00:36:27 +00001126{
Greg Clayton7268b4c2011-10-28 21:38:01 +00001127 command.clear();
1128 suffix.clear();
Greg Clayton9d855c62011-10-25 00:36:27 +00001129 StripLeadingSpaces (command_string);
1130
1131 bool result = false;
1132 quote_char = '\0';
1133
1134 if (!command_string.empty())
1135 {
1136 const char first_char = command_string[0];
1137 if (first_char == '\'' || first_char == '"')
Caroline Ticee0da7a52010-12-09 22:52:49 +00001138 {
Greg Clayton9d855c62011-10-25 00:36:27 +00001139 quote_char = first_char;
1140 const size_t end_quote_pos = command_string.find (quote_char, 1);
1141 if (end_quote_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +00001142 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001143 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +00001144 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +00001145 }
1146 else
1147 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001148 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton9d855c62011-10-25 00:36:27 +00001149 if (end_quote_pos + 1 < command_string.size())
1150 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
1151 else
1152 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +00001153 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001154 }
1155 else
1156 {
Greg Clayton9d855c62011-10-25 00:36:27 +00001157 const size_t first_space_pos = command_string.find_first_of (k_white_space);
1158 if (first_space_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +00001159 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001160 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +00001161 command_string.erase();
Caroline Tice649116c2011-05-11 16:07:06 +00001162 }
1163 else
1164 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001165 command.assign (command_string, 0, first_space_pos);
1166 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice649116c2011-05-11 16:07:06 +00001167 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001168 }
Greg Clayton9d855c62011-10-25 00:36:27 +00001169 result = true;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001170 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001171
1172
1173 if (!command.empty())
1174 {
1175 // actual commands can't start with '-' or '_'
1176 if (command[0] != '-' && command[0] != '_')
1177 {
1178 size_t pos = command.find_first_not_of(k_valid_command_chars);
1179 if (pos > 0 && pos != std::string::npos)
1180 {
1181 suffix.assign (command.begin() + pos, command.end());
1182 command.erase (pos);
1183 }
1184 }
1185 }
Greg Clayton9d855c62011-10-25 00:36:27 +00001186
1187 return result;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001188}
1189
Greg Clayton7268b4c2011-10-28 21:38:01 +00001190CommandObject *
1191CommandInterpreter::BuildAliasResult (const char *alias_name,
1192 std::string &raw_input_string,
1193 std::string &alias_result,
1194 CommandReturnObject &result)
Caroline Ticee0da7a52010-12-09 22:52:49 +00001195{
Greg Clayton7268b4c2011-10-28 21:38:01 +00001196 CommandObject *alias_cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001197 Args cmd_args (raw_input_string.c_str());
1198 alias_cmd_obj = GetCommandObject (alias_name);
1199 StreamString result_str;
1200
1201 if (alias_cmd_obj)
1202 {
1203 std::string alias_name_str = alias_name;
1204 if ((cmd_args.GetArgumentCount() == 0)
1205 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1206 cmd_args.Unshift (alias_name);
1207
1208 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1209 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1210
1211 if (option_arg_vector_sp.get())
1212 {
1213 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1214
1215 for (int i = 0; i < option_arg_vector->size(); ++i)
1216 {
1217 OptionArgPair option_pair = (*option_arg_vector)[i];
1218 OptionArgValue value_pair = option_pair.second;
1219 int value_type = value_pair.first;
1220 std::string option = option_pair.first;
1221 std::string value = value_pair.second;
1222 if (option.compare ("<argument>") == 0)
1223 result_str.Printf (" %s", value.c_str());
1224 else
1225 {
1226 result_str.Printf (" %s", option.c_str());
1227 if (value_type != optional_argument)
1228 result_str.Printf (" ");
1229 if (value.compare ("<no_argument>") != 0)
1230 {
1231 int index = GetOptionArgumentPosition (value.c_str());
1232 if (index == 0)
1233 result_str.Printf ("%s", value.c_str());
1234 else if (index >= cmd_args.GetArgumentCount())
1235 {
1236
1237 result.AppendErrorWithFormat
1238 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1239 index);
1240 result.SetStatus (eReturnStatusFailed);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001241 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001242 }
1243 else
1244 {
1245 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1246 if (strpos != std::string::npos)
1247 raw_input_string = raw_input_string.erase (strpos,
1248 strlen (cmd_args.GetArgumentAtIndex (index)));
1249 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1250 }
1251 }
1252 }
1253 }
1254 }
1255
1256 alias_result = result_str.GetData();
1257 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001258 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001259}
1260
Greg Claytonf5c0c722011-10-14 07:41:33 +00001261Error
1262CommandInterpreter::PreprocessCommand (std::string &command)
1263{
1264 // The command preprocessor needs to do things to the command
1265 // line before any parsing of arguments or anything else is done.
1266 // The only current stuff that gets proprocessed is anyting enclosed
1267 // in backtick ('`') characters is evaluated as an expression and
1268 // the result of the expression must be a scalar that can be substituted
1269 // into the command. An example would be:
1270 // (lldb) memory read `$rsp + 20`
1271 Error error; // Error for any expressions that might not evaluate
1272 size_t start_backtick;
1273 size_t pos = 0;
1274 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1275 {
1276 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1277 {
1278 // The backtick was preceeded by a '\' character, remove the slash
1279 // and don't treat the backtick as the start of an expression
1280 command.erase(start_backtick-1, 1);
1281 // No need to add one to start_backtick since we just deleted a char
1282 pos = start_backtick;
1283 }
1284 else
1285 {
1286 const size_t expr_content_start = start_backtick + 1;
1287 const size_t end_backtick = command.find ('`', expr_content_start);
1288 if (end_backtick == std::string::npos)
1289 return error;
1290 else if (end_backtick == expr_content_start)
1291 {
1292 // Empty expression (two backticks in a row)
1293 command.erase (start_backtick, 2);
1294 }
1295 else
1296 {
1297 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1298
Greg Claytonbcaf99a2012-07-12 20:32:19 +00001299 ExecutionContext exe_ctx(GetExecutionContext());
1300 Target *target = exe_ctx.GetTargetPtr();
Johnny Chenb09f8472011-10-29 00:21:50 +00001301 // Get a dummy target to allow for calculator mode while processing backticks.
1302 // This also helps break the infinite loop caused when target is null.
1303 if (!target)
1304 target = Host::GetDummyTarget(GetDebugger()).get();
Greg Claytonf5c0c722011-10-14 07:41:33 +00001305 if (target)
1306 {
Greg Claytonf5c0c722011-10-14 07:41:33 +00001307 ValueObjectSP expr_result_valobj_sp;
Enrico Granatad27026e2012-09-05 20:41:26 +00001308
1309 Target::EvaluateExpressionOptions options;
1310 options.SetCoerceToId(false)
1311 .SetUnwindOnError(true)
1312 .SetKeepInMemory(false)
1313 .SetSingleThreadTimeoutUsec(0);
1314
Greg Claytonf5c0c722011-10-14 07:41:33 +00001315 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
Enrico Granatad27026e2012-09-05 20:41:26 +00001316 exe_ctx.GetFramePtr(),
Enrico Granata6cca9692012-07-16 23:10:35 +00001317 expr_result_valobj_sp,
Enrico Granatad27026e2012-09-05 20:41:26 +00001318 options);
1319
Greg Claytonf5c0c722011-10-14 07:41:33 +00001320 if (expr_result == eExecutionCompleted)
1321 {
1322 Scalar scalar;
1323 if (expr_result_valobj_sp->ResolveValue (scalar))
1324 {
1325 command.erase (start_backtick, end_backtick - start_backtick + 1);
1326 StreamString value_strm;
1327 const bool show_type = false;
1328 scalar.GetValue (&value_strm, show_type);
1329 size_t value_string_size = value_strm.GetSize();
1330 if (value_string_size)
1331 {
1332 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1333 pos = start_backtick + value_string_size;
1334 continue;
1335 }
1336 else
1337 {
1338 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1339 }
1340 }
1341 else
1342 {
1343 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1344 }
1345 }
1346 else
1347 {
1348 if (expr_result_valobj_sp)
1349 error = expr_result_valobj_sp->GetError();
1350 if (error.Success())
1351 {
1352
1353 switch (expr_result)
1354 {
1355 case eExecutionSetupError:
1356 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1357 break;
1358 case eExecutionCompleted:
1359 break;
1360 case eExecutionDiscarded:
1361 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1362 break;
1363 case eExecutionInterrupted:
1364 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1365 break;
1366 case eExecutionTimedOut:
1367 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1368 break;
1369 }
1370 }
1371 }
1372 }
1373 }
1374 if (error.Fail())
1375 break;
1376 }
1377 }
1378 return error;
1379}
1380
1381
Caroline Ticee0da7a52010-12-09 22:52:49 +00001382bool
1383CommandInterpreter::HandleCommand (const char *command_line,
Enrico Granata01bc2d42012-05-31 01:09:06 +00001384 LazyBool lazy_add_to_history,
Caroline Ticee0da7a52010-12-09 22:52:49 +00001385 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001386 ExecutionContext *override_context,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001387 bool repeat_on_empty_command,
1388 bool no_context_switching)
Jim Ingham949d5ac2011-02-18 00:54:25 +00001389
Caroline Ticee0da7a52010-12-09 22:52:49 +00001390{
Jim Ingham949d5ac2011-02-18 00:54:25 +00001391
Caroline Ticee0da7a52010-12-09 22:52:49 +00001392 bool done = false;
1393 CommandObject *cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001394 bool wants_raw_input = false;
1395 std::string command_string (command_line);
Jim Ingham6247dbe2011-07-12 03:12:18 +00001396 std::string original_command_string (command_line);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001397
1398 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +00001399 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1400
1401 // Make a scoped cleanup object that will clear the crash description string
1402 // on exit of this function.
Enrico Granata1a102082011-07-12 00:18:11 +00001403 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Claytone98ac252010-11-10 04:57:04 +00001404
Caroline Ticee0da7a52010-12-09 22:52:49 +00001405 if (log)
1406 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +00001407
Jim Inghamabab14b2010-11-04 23:08:45 +00001408 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1409
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001410 if (!no_context_switching)
1411 UpdateExecutionContext (override_context);
Enrico Granata01bc2d42012-05-31 01:09:06 +00001412
1413 // <rdar://problem/11328896>
1414 bool add_to_history;
1415 if (lazy_add_to_history == eLazyBoolCalculate)
1416 add_to_history = (m_command_source_depth == 0);
1417 else
1418 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1419
Jim Ingham949d5ac2011-02-18 00:54:25 +00001420 bool empty_command = false;
1421 bool comment_command = false;
1422 if (command_string.empty())
1423 empty_command = true;
1424 else
Chris Lattner24943d22010-06-08 16:52:24 +00001425 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001426 const char *k_space_characters = "\t\n\v\f\r ";
1427
1428 size_t non_space = command_string.find_first_not_of (k_space_characters);
1429 // Check for empty line or comment line (lines whose first
1430 // non-space character is the comment character for this interpreter)
1431 if (non_space == std::string::npos)
1432 empty_command = true;
1433 else if (command_string[non_space] == m_comment_char)
1434 comment_command = true;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001435 else if (command_string[non_space] == m_repeat_char)
1436 {
1437 const char *history_string = FindHistoryString (command_string.c_str() + non_space);
1438 if (history_string == NULL)
1439 {
1440 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1441 result.SetStatus(eReturnStatusFailed);
1442 return false;
1443 }
1444 add_to_history = false;
1445 command_string = history_string;
1446 original_command_string = history_string;
1447 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001448 }
1449
1450 if (empty_command)
1451 {
1452 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +00001453 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001454 if (m_command_history.empty())
1455 {
1456 result.AppendError ("empty command");
1457 result.SetStatus(eReturnStatusFailed);
1458 return false;
1459 }
1460 else
1461 {
1462 command_line = m_repeat_command.c_str();
1463 command_string = command_line;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001464 original_command_string = command_line;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001465 if (m_repeat_command.empty())
1466 {
1467 result.AppendErrorWithFormat("No auto repeat.\n");
1468 result.SetStatus (eReturnStatusFailed);
1469 return false;
1470 }
1471 }
1472 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001473 }
1474 else
1475 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001476 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1477 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001478 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001479 }
1480 else if (comment_command)
1481 {
1482 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1483 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001484 }
Caroline Tice649116c2011-05-11 16:07:06 +00001485
Greg Claytonf5c0c722011-10-14 07:41:33 +00001486
1487 Error error (PreprocessCommand (command_string));
1488
1489 if (error.Fail())
1490 {
1491 result.AppendError (error.AsCString());
1492 result.SetStatus(eReturnStatusFailed);
1493 return false;
1494 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001495 // Phase 1.
1496
1497 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1498 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1499 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1500 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1501 // 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 +00001502 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +00001503 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +00001504
Caroline Ticee0da7a52010-12-09 22:52:49 +00001505 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001506 size_t actual_cmd_name_len = 0;
Greg Clayton7268b4c2011-10-28 21:38:01 +00001507 std::string next_word;
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001508 StringList matches;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001509 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +00001510 {
Caroline Tice649116c2011-05-11 16:07:06 +00001511 char quote_char = '\0';
Greg Clayton7268b4c2011-10-28 21:38:01 +00001512 std::string suffix;
1513 ExtractCommand (command_string, next_word, suffix, quote_char);
1514 if (cmd_obj == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +00001515 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001516 if (AliasExists (next_word.c_str()))
Caroline Tice56d2fc42010-12-14 18:51:39 +00001517 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001518 std::string alias_result;
1519 cmd_obj = BuildAliasResult (next_word.c_str(), command_string, alias_result, result);
1520 revised_command_line.Printf ("%s", alias_result.c_str());
1521 if (cmd_obj)
1522 {
1523 wants_raw_input = cmd_obj->WantsRawCommandString ();
1524 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1525 }
Chris Lattner24943d22010-06-08 16:52:24 +00001526 }
1527 else
1528 {
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001529 cmd_obj = GetCommandObject (next_word.c_str(), &matches);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001530 if (cmd_obj)
1531 {
1532 actual_cmd_name_len += next_word.length();
1533 revised_command_line.Printf ("%s", next_word.c_str());
1534 wants_raw_input = cmd_obj->WantsRawCommandString ();
1535 }
Caroline Tice649116c2011-05-11 16:07:06 +00001536 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001537 {
1538 revised_command_line.Printf ("%s", next_word.c_str());
1539 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001540 }
1541 }
1542 else
1543 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001544 if (cmd_obj->IsMultiwordObject ())
1545 {
1546 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
1547 if (sub_cmd_obj)
1548 {
1549 actual_cmd_name_len += next_word.length() + 1;
1550 revised_command_line.Printf (" %s", next_word.c_str());
1551 cmd_obj = sub_cmd_obj;
1552 wants_raw_input = cmd_obj->WantsRawCommandString ();
1553 }
1554 else
1555 {
1556 if (quote_char)
1557 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1558 else
1559 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1560 done = true;
1561 }
1562 }
Caroline Tice649116c2011-05-11 16:07:06 +00001563 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001564 {
1565 if (quote_char)
1566 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1567 else
1568 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1569 done = true;
1570 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001571 }
1572
1573 if (cmd_obj == NULL)
1574 {
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001575 uint32_t num_matches = matches.GetSize();
1576 if (matches.GetSize() > 1) {
1577 std::string error_msg;
1578 error_msg.assign ("Ambiguous command '");
1579 error_msg.append(next_word.c_str());
1580 error_msg.append ("'.");
1581
1582 error_msg.append (" Possible matches:");
1583
1584 for (uint32_t i = 0; i < num_matches; ++i) {
1585 error_msg.append ("\n\t");
1586 error_msg.append (matches.GetStringAtIndex(i));
1587 }
1588 error_msg.append ("\n");
1589 result.AppendRawError (error_msg.c_str(), error_msg.size());
1590 } else {
1591 // We didn't have only one match, otherwise we wouldn't get here.
1592 assert(num_matches == 0);
1593 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1594 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001595 result.SetStatus (eReturnStatusFailed);
1596 return false;
1597 }
1598
Greg Clayton7268b4c2011-10-28 21:38:01 +00001599 if (cmd_obj->IsMultiwordObject ())
1600 {
1601 if (!suffix.empty())
1602 {
1603
1604 result.AppendErrorWithFormat ("multi-word commands ('%s') can't have shorthand suffixes: '%s'\n",
1605 next_word.c_str(),
1606 suffix.c_str());
1607 result.SetStatus (eReturnStatusFailed);
1608 return false;
1609 }
1610 }
1611 else
1612 {
1613 // If we found a normal command, we are done
1614 done = true;
1615 if (!suffix.empty())
1616 {
1617 switch (suffix[0])
1618 {
1619 case '/':
1620 // GDB format suffixes
Greg Claytond8a218d2011-10-29 00:57:28 +00001621 {
1622 Options *command_options = cmd_obj->GetOptions();
1623 if (command_options && command_options->SupportsLongOption("gdb-format"))
1624 {
Greg Clayton3840cd72011-11-09 23:25:03 +00001625 std::string gdb_format_option ("--gdb-format=");
1626 gdb_format_option += (suffix.c_str() + 1);
1627
1628 bool inserted = false;
1629 std::string &cmd = revised_command_line.GetString();
1630 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1631 if (arg_terminator_idx != std::string::npos)
1632 {
1633 // Insert the gdb format option before the "--" that terminates options
1634 gdb_format_option.append(1,' ');
1635 cmd.insert(arg_terminator_idx, gdb_format_option);
1636 inserted = true;
1637 }
1638
1639 if (!inserted)
1640 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1641
1642 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1643 revised_command_line.PutCString (" --");
Greg Claytond8a218d2011-10-29 00:57:28 +00001644 }
1645 else
1646 {
1647 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1648 cmd_obj->GetCommandName());
1649 result.SetStatus (eReturnStatusFailed);
1650 return false;
1651 }
1652 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001653 break;
Johnny Chen8ca450b2011-10-31 22:22:06 +00001654
1655 default:
1656 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1657 suffix.c_str());
1658 result.SetStatus (eReturnStatusFailed);
1659 return false;
1660
Greg Clayton7268b4c2011-10-28 21:38:01 +00001661 }
1662 }
1663 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001664 if (command_string.length() == 0)
1665 done = true;
1666
Chris Lattner24943d22010-06-08 16:52:24 +00001667 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001668
Greg Clayton7268b4c2011-10-28 21:38:01 +00001669 if (!command_string.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +00001670 revised_command_line.Printf (" %s", command_string.c_str());
1671
1672 // End of Phase 1.
1673 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1674 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1675 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1676 // wants_raw_input specifies whether the Execute method expects raw input or not.
1677
1678
1679 if (log)
1680 {
1681 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1682 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1683 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1684 }
1685
1686 // Phase 2.
1687 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1688 // CommandObject, with the appropriate arguments.
1689
1690 if (cmd_obj != NULL)
1691 {
1692 if (add_to_history)
1693 {
1694 Args command_args (revised_command_line.GetData());
1695 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1696 if (repeat_command != NULL)
1697 m_repeat_command.assign(repeat_command);
1698 else
Jim Ingham6247dbe2011-07-12 03:12:18 +00001699 m_repeat_command.assign(original_command_string.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001700
Jim Ingham6247dbe2011-07-12 03:12:18 +00001701 // Don't keep pushing the same command onto the history...
Greg Clayton7268b4c2011-10-28 21:38:01 +00001702 if (m_command_history.empty() || m_command_history.back() != original_command_string)
Jim Ingham6247dbe2011-07-12 03:12:18 +00001703 m_command_history.push_back (original_command_string);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001704 }
1705
1706 command_string = revised_command_line.GetData();
1707 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001708 std::string remainder;
1709 if (actual_cmd_name_len < command_string.length())
1710 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1711 // than cmd_obj->GetCommandName(), because name completion
1712 // allows users to enter short versions of the names,
1713 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +00001714
1715 // Remove any initial spaces
1716 std::string white_space (" \t\v");
1717 size_t pos = remainder.find_first_not_of (white_space);
1718 if (pos != 0 && pos != std::string::npos)
Greg Clayton91c9dcf2011-04-22 20:58:45 +00001719 remainder.erase(0, pos);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001720
1721 if (log)
Jason Molenda24c991c2011-08-25 00:20:04 +00001722 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001723
Jim Inghamda26bd22012-06-08 21:56:10 +00001724 cmd_obj->Execute (remainder.c_str(), result);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001725 }
1726 else
1727 {
1728 // We didn't find the first command object, so complete the first argument.
1729 Args command_args (revised_command_line.GetData());
1730 StringList matches;
1731 int num_matches;
1732 int cursor_index = 0;
1733 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1734 bool word_complete;
1735 num_matches = HandleCompletionMatches (command_args,
1736 cursor_index,
1737 cursor_char_position,
1738 0,
1739 -1,
1740 word_complete,
1741 matches);
1742
1743 if (num_matches > 0)
1744 {
1745 std::string error_msg;
1746 error_msg.assign ("ambiguous command '");
1747 error_msg.append(command_args.GetArgumentAtIndex(0));
1748 error_msg.append ("'.");
1749
1750 error_msg.append (" Possible completions:");
1751 for (int i = 0; i < num_matches; i++)
1752 {
1753 error_msg.append ("\n\t");
1754 error_msg.append (matches.GetStringAtIndex (i));
1755 }
1756 error_msg.append ("\n");
1757 result.AppendRawError (error_msg.c_str(), error_msg.size());
1758 }
1759 else
1760 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1761
1762 result.SetStatus (eReturnStatusFailed);
1763 }
1764
Jason Molenda24c991c2011-08-25 00:20:04 +00001765 if (log)
1766 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1767
Chris Lattner24943d22010-06-08 16:52:24 +00001768 return result.Succeeded();
1769}
1770
1771int
1772CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1773 int &cursor_index,
1774 int &cursor_char_position,
1775 int match_start_point,
1776 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001777 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001778 StringList &matches)
1779{
1780 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001781 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001782
1783 // For any of the command completions a unique match will be a complete word.
1784 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001785
1786 if (cursor_index == -1)
1787 {
1788 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001789 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001790 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1791 }
1792 else if (cursor_index == 0)
1793 {
1794 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001795 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001796 num_command_matches = matches.GetSize();
1797
1798 if (num_command_matches == 1
1799 && cmd_obj && cmd_obj->IsMultiwordObject()
1800 && matches.GetStringAtIndex(0) != NULL
1801 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1802 {
1803 look_for_subcommand = true;
1804 num_command_matches = 0;
1805 matches.DeleteStringAtIndex(0);
1806 parsed_line.AppendArgument ("");
1807 cursor_index++;
1808 cursor_char_position = 0;
1809 }
1810 }
1811
1812 if (cursor_index > 0 || look_for_subcommand)
1813 {
1814 // We are completing further on into a commands arguments, so find the command and tell it
1815 // to complete the command.
1816 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001817 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001818 if (command_object == NULL)
1819 {
1820 return 0;
1821 }
1822 else
1823 {
1824 parsed_line.Shift();
1825 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001826 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001827 cursor_index,
1828 cursor_char_position,
1829 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001830 max_return_elements,
1831 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001832 matches);
1833 }
1834 }
1835
1836 return num_command_matches;
1837
1838}
1839
1840int
1841CommandInterpreter::HandleCompletion (const char *current_line,
1842 const char *cursor,
1843 const char *last_char,
1844 int match_start_point,
1845 int max_return_elements,
1846 StringList &matches)
1847{
1848 // We parse the argument up to the cursor, so the last argument in parsed_line is
1849 // the one containing the cursor, and the cursor is after the last character.
1850
1851 Args parsed_line(current_line, last_char - current_line);
1852 Args partial_parsed_line(current_line, cursor - current_line);
1853
Jim Ingham6247dbe2011-07-12 03:12:18 +00001854 // Don't complete comments, and if the line we are completing is just the history repeat character,
1855 // substitute the appropriate history line.
1856 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1857 if (first_arg)
1858 {
1859 if (first_arg[0] == m_comment_char)
1860 return 0;
1861 else if (first_arg[0] == m_repeat_char)
1862 {
1863 const char *history_string = FindHistoryString (first_arg);
1864 if (history_string != NULL)
1865 {
1866 matches.Clear();
1867 matches.InsertStringAtIndex(0, history_string);
1868 return -2;
1869 }
1870 else
1871 return 0;
1872
1873 }
1874 }
1875
1876
Chris Lattner24943d22010-06-08 16:52:24 +00001877 int num_args = partial_parsed_line.GetArgumentCount();
1878 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1879 int cursor_char_position;
1880
1881 if (cursor_index == -1)
1882 cursor_char_position = 0;
1883 else
1884 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001885
1886 if (cursor > current_line && cursor[-1] == ' ')
1887 {
1888 // We are just after a space. If we are in an argument, then we will continue
1889 // parsing, but if we are between arguments, then we have to complete whatever the next
1890 // element would be.
1891 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1892 // protected by a quote) then the space will also be in the parsed argument...
1893
1894 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1895 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1896 {
1897 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1898 cursor_index++;
1899 cursor_char_position = 0;
1900 }
1901 }
Chris Lattner24943d22010-06-08 16:52:24 +00001902
1903 int num_command_matches;
1904
1905 matches.Clear();
1906
1907 // Only max_return_elements == -1 is supported at present:
1908 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001909 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001910 num_command_matches = HandleCompletionMatches (parsed_line,
1911 cursor_index,
1912 cursor_char_position,
1913 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001914 max_return_elements,
1915 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001916 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001917
1918 if (num_command_matches <= 0)
1919 return num_command_matches;
1920
1921 if (num_args == 0)
1922 {
1923 // If we got an empty string, insert nothing.
1924 matches.InsertStringAtIndex(0, "");
1925 }
1926 else
1927 {
1928 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1929 // put an empty string in element 0.
1930 std::string command_partial_str;
1931 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001932 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1933 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001934
1935 std::string common_prefix;
1936 matches.LongestCommonPrefix (common_prefix);
1937 int partial_name_len = command_partial_str.size();
1938
1939 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001940 // Only do this if the completer told us this was a complete word, however...
1941 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001942 {
1943 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1944 if (quote_char != '\0')
1945 common_prefix.push_back(quote_char);
1946
1947 common_prefix.push_back(' ');
1948 }
1949 common_prefix.erase (0, partial_name_len);
1950 matches.InsertStringAtIndex(0, common_prefix.c_str());
1951 }
1952 return num_command_matches;
1953}
1954
Chris Lattner24943d22010-06-08 16:52:24 +00001955
1956CommandInterpreter::~CommandInterpreter ()
1957{
1958}
1959
1960const char *
1961CommandInterpreter::GetPrompt ()
1962{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001963 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001964}
1965
1966void
1967CommandInterpreter::SetPrompt (const char *new_prompt)
1968{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001969 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001970}
1971
Jim Ingham5e16ef52010-10-04 19:49:29 +00001972size_t
Greg Clayton58928562011-02-09 01:08:52 +00001973CommandInterpreter::GetConfirmationInputReaderCallback
1974(
1975 void *baton,
1976 InputReader &reader,
1977 lldb::InputReaderAction action,
1978 const char *bytes,
1979 size_t bytes_len
1980)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001981{
Greg Clayton58928562011-02-09 01:08:52 +00001982 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001983 bool *response_ptr = (bool *) baton;
1984
1985 switch (action)
1986 {
1987 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001988 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001989 {
1990 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001991 {
Greg Clayton58928562011-02-09 01:08:52 +00001992 out_file.Printf ("%s", reader.GetPrompt());
1993 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001994 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001995 }
1996 break;
1997
1998 case eInputReaderDeactivate:
1999 break;
2000
2001 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00002002 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00002003 {
Greg Clayton58928562011-02-09 01:08:52 +00002004 out_file.Printf ("%s", reader.GetPrompt());
2005 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00002006 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00002007 break;
Caroline Tice4a348082011-05-02 20:41:46 +00002008
2009 case eInputReaderAsynchronousOutputWritten:
2010 break;
2011
Jim Ingham5e16ef52010-10-04 19:49:29 +00002012 case eInputReaderGotToken:
2013 if (bytes_len == 0)
2014 {
2015 reader.SetIsDone(true);
2016 }
Jim Ingham36fe9912011-11-14 20:02:01 +00002017 else if (bytes[0] == 'y' || bytes[0] == 'Y')
Jim Ingham5e16ef52010-10-04 19:49:29 +00002018 {
2019 *response_ptr = true;
2020 reader.SetIsDone(true);
2021 }
Jim Ingham36fe9912011-11-14 20:02:01 +00002022 else if (bytes[0] == 'n' || bytes[0] == 'N')
Jim Ingham5e16ef52010-10-04 19:49:29 +00002023 {
2024 *response_ptr = false;
2025 reader.SetIsDone(true);
2026 }
2027 else
2028 {
Greg Clayton58928562011-02-09 01:08:52 +00002029 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00002030 {
Jim Ingham26183802011-11-17 01:22:00 +00002031 out_file.Printf ("Please answer \"y\" or \"n\".\n%s", reader.GetPrompt());
Greg Clayton58928562011-02-09 01:08:52 +00002032 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00002033 }
2034 }
2035 break;
2036
Caroline Ticec4f55fe2010-11-19 20:47:54 +00002037 case eInputReaderInterrupt:
2038 case eInputReaderEndOfFile:
2039 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
2040 reader.SetIsDone (true);
2041 break;
2042
Jim Ingham5e16ef52010-10-04 19:49:29 +00002043 case eInputReaderDone:
2044 break;
2045 }
2046
2047 return bytes_len;
2048
2049}
2050
2051bool
2052CommandInterpreter::Confirm (const char *message, bool default_answer)
2053{
Jim Ingham93057472010-10-04 22:44:14 +00002054 // Check AutoConfirm first:
2055 if (m_debugger.GetAutoConfirm())
2056 return default_answer;
2057
Jim Ingham5e16ef52010-10-04 19:49:29 +00002058 InputReaderSP reader_sp (new InputReader(GetDebugger()));
2059 bool response = default_answer;
2060 if (reader_sp)
2061 {
2062 std::string prompt(message);
2063 prompt.append(": [");
2064 if (default_answer)
2065 prompt.append ("Y/n] ");
2066 else
2067 prompt.append ("y/N] ");
2068
2069 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
2070 &response, // baton
2071 eInputReaderGranularityLine, // token size, to pass to callback function
2072 NULL, // end token
2073 prompt.c_str(), // prompt
2074 true)); // echo input
2075 if (err.Success())
2076 {
2077 GetDebugger().PushInputReader (reader_sp);
2078 }
2079 reader_sp->WaitOnReaderIsDone();
2080 }
2081 return response;
2082}
2083
2084
Chris Lattner24943d22010-06-08 16:52:24 +00002085void
2086CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
2087{
Jim Inghamd40f8a62010-07-06 22:46:59 +00002088 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00002089
Sean Callananb386d822012-08-09 00:50:26 +00002090 if (cmd_obj_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002091 {
2092 CommandObject *cmd_obj = cmd_obj_sp.get();
2093 if (cmd_obj->IsCrossRefObject ())
2094 cmd_obj->AddObject (object_type);
2095 }
2096}
2097
Chris Lattner24943d22010-06-08 16:52:24 +00002098OptionArgVectorSP
2099CommandInterpreter::GetAliasOptions (const char *alias_name)
2100{
2101 OptionArgMap::iterator pos;
2102 OptionArgVectorSP ret_val;
2103
2104 std::string alias (alias_name);
2105
2106 if (HasAliasOptions())
2107 {
2108 pos = m_alias_options.find (alias);
2109 if (pos != m_alias_options.end())
2110 ret_val = pos->second;
2111 }
2112
2113 return ret_val;
2114}
2115
2116void
2117CommandInterpreter::RemoveAliasOptions (const char *alias_name)
2118{
2119 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
2120 if (pos != m_alias_options.end())
2121 {
2122 m_alias_options.erase (pos);
2123 }
2124}
2125
2126void
2127CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
2128{
2129 m_alias_options[alias_name] = option_arg_vector_sp;
2130}
2131
2132bool
2133CommandInterpreter::HasCommands ()
2134{
2135 return (!m_command_dict.empty());
2136}
2137
2138bool
2139CommandInterpreter::HasAliases ()
2140{
2141 return (!m_alias_dict.empty());
2142}
2143
2144bool
2145CommandInterpreter::HasUserCommands ()
2146{
2147 return (!m_user_dict.empty());
2148}
2149
2150bool
2151CommandInterpreter::HasAliasOptions ()
2152{
2153 return (!m_alias_options.empty());
2154}
2155
Chris Lattner24943d22010-06-08 16:52:24 +00002156void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002157CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2158 const char *alias_name,
2159 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00002160 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002161 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00002162{
2163 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00002164
2165 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00002166
Caroline Tice44c841d2010-12-07 19:58:26 +00002167 // Make sure that the alias name is the 0th element in cmd_args
2168 std::string alias_name_str = alias_name;
2169 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2170 cmd_args.Unshift (alias_name);
2171
2172 Args new_args (alias_cmd_obj->GetCommandName());
2173 if (new_args.GetArgumentCount() == 2)
2174 new_args.Shift();
2175
Chris Lattner24943d22010-06-08 16:52:24 +00002176 if (option_arg_vector_sp.get())
2177 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002178 if (wants_raw_input)
2179 {
2180 // We have a command that both has command options and takes raw input. Make *sure* it has a
2181 // " -- " in the right place in the raw_input_string.
2182 size_t pos = raw_input_string.find(" -- ");
2183 if (pos == std::string::npos)
2184 {
2185 // None found; assume it goes at the beginning of the raw input string
2186 raw_input_string.insert (0, " -- ");
2187 }
2188 }
Chris Lattner24943d22010-06-08 16:52:24 +00002189
2190 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
2191 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002192 std::vector<bool> used (old_size + 1, false);
2193
2194 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002195
2196 for (int i = 0; i < option_arg_vector->size(); ++i)
2197 {
2198 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00002199 OptionArgValue value_pair = option_pair.second;
2200 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00002201 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00002202 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00002203 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002204 {
2205 if (!wants_raw_input
2206 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2207 new_args.AppendArgument (value.c_str());
2208 }
Chris Lattner24943d22010-06-08 16:52:24 +00002209 else
2210 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002211 if (value_type != optional_argument)
2212 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00002213 if (value.compare ("<no-argument>") != 0)
2214 {
2215 int index = GetOptionArgumentPosition (value.c_str());
2216 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002217 {
Chris Lattner24943d22010-06-08 16:52:24 +00002218 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00002219 if (value_type != optional_argument)
2220 new_args.AppendArgument (value.c_str());
2221 else
2222 {
2223 char buffer[255];
2224 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2225 new_args.AppendArgument (buffer);
2226 }
2227
2228 }
Chris Lattner24943d22010-06-08 16:52:24 +00002229 else if (index >= cmd_args.GetArgumentCount())
2230 {
2231 result.AppendErrorWithFormat
2232 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2233 index);
2234 result.SetStatus (eReturnStatusFailed);
2235 return;
2236 }
2237 else
2238 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002239 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2240 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2241 if (strpos != std::string::npos)
2242 {
2243 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2244 }
2245
2246 if (value_type != optional_argument)
2247 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2248 else
2249 {
2250 char buffer[255];
2251 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2252 cmd_args.GetArgumentAtIndex (index));
2253 new_args.AppendArgument (buffer);
2254 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002255 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002256 }
2257 }
2258 }
2259 }
2260
2261 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
2262 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002263 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00002264 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2265 }
2266
2267 cmd_args.Clear();
2268 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2269 }
2270 else
2271 {
2272 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00002273 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2274 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2275 // input string.
2276 if (wants_raw_input)
2277 {
2278 cmd_args.Clear();
2279 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2280 }
Chris Lattner24943d22010-06-08 16:52:24 +00002281 return;
2282 }
2283
2284 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2285 return;
2286}
2287
2288
2289int
2290CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2291{
2292 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2293 // of zero.
2294
2295 char *cptr = (char *) in_string;
2296
2297 // Does it start with '%'
2298 if (cptr[0] == '%')
2299 {
2300 ++cptr;
2301
2302 // Is the rest of it entirely digits?
2303 if (isdigit (cptr[0]))
2304 {
2305 const char *start = cptr;
2306 while (isdigit (cptr[0]))
2307 ++cptr;
2308
2309 // We've gotten to the end of the digits; are we at the end of the string?
2310 if (cptr[0] == '\0')
2311 position = atoi (start);
2312 }
2313 }
2314
2315 return position;
2316}
2317
2318void
2319CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2320{
Jim Ingham574c3d62011-08-12 23:34:31 +00002321 FileSpec init_file;
Greg Claytond6edcb52011-09-11 00:01:44 +00002322 if (in_cwd)
Jim Ingham574c3d62011-08-12 23:34:31 +00002323 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002324 // In the current working directory we don't load any program specific
2325 // .lldbinit files, we only look for a "./.lldbinit" file.
2326 if (m_skip_lldbinit_files)
2327 return;
2328
2329 init_file.SetFile ("./.lldbinit", true);
Jim Ingham574c3d62011-08-12 23:34:31 +00002330 }
Greg Claytond6edcb52011-09-11 00:01:44 +00002331 else
Jim Ingham574c3d62011-08-12 23:34:31 +00002332 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002333 // If we aren't looking in the current working directory we are looking
2334 // in the home directory. We will first see if there is an application
2335 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2336 // "-" and the name of the program. If this file doesn't exist, we fall
2337 // back to just the "~/.lldbinit" file. We also obey any requests to not
2338 // load the init files.
2339 const char *init_file_path = "~/.lldbinit";
2340
2341 if (m_skip_app_init_files == false)
2342 {
2343 FileSpec program_file_spec (Host::GetProgramFileSpec());
2344 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham574c3d62011-08-12 23:34:31 +00002345
Greg Claytond6edcb52011-09-11 00:01:44 +00002346 if (program_name)
2347 {
2348 char program_init_file_name[PATH_MAX];
2349 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2350 init_file.SetFile (program_init_file_name, true);
2351 if (!init_file.Exists())
2352 init_file.Clear();
2353 }
2354 }
2355
2356 if (!init_file && !m_skip_lldbinit_files)
2357 init_file.SetFile (init_file_path, true);
2358 }
2359
Chris Lattner24943d22010-06-08 16:52:24 +00002360 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2361 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2362
2363 if (init_file.Exists())
2364 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00002365 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
2366 bool stop_on_continue = true;
2367 bool stop_on_error = false;
2368 bool echo_commands = false;
2369 bool print_results = false;
2370
Enrico Granata01bc2d42012-05-31 01:09:06 +00002371 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, eLazyBoolNo, result);
Chris Lattner24943d22010-06-08 16:52:24 +00002372 }
2373 else
2374 {
2375 // nothing to be done if the file doesn't exist
2376 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2377 }
2378}
2379
Greg Claytonb72d0f02011-04-12 05:54:46 +00002380PlatformSP
2381CommandInterpreter::GetPlatform (bool prefer_target_platform)
2382{
2383 PlatformSP platform_sp;
Greg Clayton567e7f32011-09-22 04:58:26 +00002384 if (prefer_target_platform)
2385 {
Greg Claytonbcaf99a2012-07-12 20:32:19 +00002386 ExecutionContext exe_ctx(GetExecutionContext());
2387 Target *target = exe_ctx.GetTargetPtr();
Greg Clayton567e7f32011-09-22 04:58:26 +00002388 if (target)
2389 platform_sp = target->GetPlatform();
2390 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002391
2392 if (!platform_sp)
2393 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2394 return platform_sp;
2395}
2396
Jim Ingham949d5ac2011-02-18 00:54:25 +00002397void
Jim Inghama4fede32011-03-11 01:51:49 +00002398CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002399 ExecutionContext *override_context,
2400 bool stop_on_continue,
2401 bool stop_on_error,
2402 bool echo_commands,
2403 bool print_results,
Enrico Granata01bc2d42012-05-31 01:09:06 +00002404 LazyBool add_to_history,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002405 CommandReturnObject &result)
2406{
2407 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00002408
2409 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2410 // Make sure you reset this value anywhere you return from the function.
2411
2412 bool old_async_execution = m_debugger.GetAsyncExecution();
2413
2414 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2415 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2416
2417 if (override_context != NULL)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002418 UpdateExecutionContext (override_context);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002419
2420 if (!stop_on_continue)
2421 {
2422 m_debugger.SetAsyncExecution (false);
2423 }
2424
2425 for (int idx = 0; idx < num_lines; idx++)
2426 {
2427 const char *cmd = commands.GetStringAtIndex(idx);
2428 if (cmd[0] == '\0')
2429 continue;
2430
Jim Ingham949d5ac2011-02-18 00:54:25 +00002431 if (echo_commands)
2432 {
2433 result.AppendMessageWithFormat ("%s %s\n",
2434 GetPrompt(),
2435 cmd);
2436 }
2437
Greg Claytonaa378b12011-02-20 02:15:07 +00002438 CommandReturnObject tmp_result;
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002439 // If override_context is not NULL, pass no_context_switching = true for
2440 // HandleCommand() since we updated our context already.
Enrico Granata01bc2d42012-05-31 01:09:06 +00002441 bool success = HandleCommand(cmd, add_to_history, tmp_result,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002442 NULL, /* override_context */
2443 true, /* repeat_on_empty_command */
2444 override_context != NULL /* no_context_switching */);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002445
2446 if (print_results)
2447 {
2448 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002449 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002450 }
2451
2452 if (!success || !tmp_result.Succeeded())
2453 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002454 const char *error_msg = tmp_result.GetErrorData();
2455 if (error_msg == NULL || error_msg[0] == '\0')
2456 error_msg = "<unknown error>.\n";
Jim Ingham949d5ac2011-02-18 00:54:25 +00002457 if (stop_on_error)
2458 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002459 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed with %s",
2460 idx, cmd, error_msg);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002461 result.SetStatus (eReturnStatusFailed);
2462 m_debugger.SetAsyncExecution (old_async_execution);
2463 return;
2464 }
2465 else if (print_results)
2466 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002467 result.AppendMessageWithFormat ("Command #%d '%s' failed with %s",
Jim Ingham949d5ac2011-02-18 00:54:25 +00002468 idx + 1,
2469 cmd,
Jim Ingham862fd5c2012-04-24 02:25:07 +00002470 error_msg);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002471 }
2472 }
2473
Caroline Tice4a348082011-05-02 20:41:46 +00002474 if (result.GetImmediateOutputStream())
2475 result.GetImmediateOutputStream()->Flush();
2476
2477 if (result.GetImmediateErrorStream())
2478 result.GetImmediateErrorStream()->Flush();
2479
Jim Ingham949d5ac2011-02-18 00:54:25 +00002480 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2481 // could be running (for instance in Breakpoint Commands.
2482 // So we check the return value to see if it is has running in it.
2483 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2484 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2485 {
2486 if (stop_on_continue)
2487 {
2488 // If we caused the target to proceed, and we're going to stop in that case, set the
2489 // status in our real result before returning. This is an error if the continue was not the
2490 // last command in the set of commands to be run.
2491 if (idx != num_lines - 1)
2492 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
2493 idx + 1, cmd);
2494 else
2495 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
2496
2497 result.SetStatus(tmp_result.GetStatus());
2498 m_debugger.SetAsyncExecution (old_async_execution);
2499
2500 return;
2501 }
2502 }
2503
2504 }
2505
2506 result.SetStatus (eReturnStatusSuccessFinishResult);
2507 m_debugger.SetAsyncExecution (old_async_execution);
2508
2509 return;
2510}
2511
2512void
2513CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2514 ExecutionContext *context,
2515 bool stop_on_continue,
2516 bool stop_on_error,
2517 bool echo_command,
2518 bool print_result,
Enrico Granata01bc2d42012-05-31 01:09:06 +00002519 LazyBool add_to_history,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002520 CommandReturnObject &result)
2521{
2522 if (cmd_file.Exists())
2523 {
2524 bool success;
2525 StringList commands;
2526 success = commands.ReadFileLines(cmd_file);
2527 if (!success)
2528 {
2529 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2530 result.SetStatus (eReturnStatusFailed);
2531 return;
2532 }
Enrico Granata01bc2d42012-05-31 01:09:06 +00002533 m_command_source_depth++;
2534 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, add_to_history, result);
2535 m_command_source_depth--;
Jim Ingham949d5ac2011-02-18 00:54:25 +00002536 }
2537 else
2538 {
2539 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2540 cmd_file.GetFilename().AsCString());
2541 result.SetStatus (eReturnStatusFailed);
2542 return;
2543 }
2544}
2545
Chris Lattner24943d22010-06-08 16:52:24 +00002546ScriptInterpreter *
2547CommandInterpreter::GetScriptInterpreter ()
2548{
Enrico Granatac5c10a42012-07-10 18:23:48 +00002549 // <rdar://problem/11751427>
2550 // we need to protect the initialization of the script interpreter
2551 // otherwise we could end up with two threads both trying to create
2552 // their instance of it, and for some languages (e.g. Python)
2553 // this is a bulletproof recipe for disaster!
2554 // this needs to be a function-level static because multiple Debugger instances living in the same process
2555 // still need to be isolated and not try to initialize Python concurrently
Enrico Granatab88c0a92012-07-10 19:04:14 +00002556 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive);
2557 Mutex::Locker interpreter_lock(g_interpreter_mutex);
Enrico Granatac5c10a42012-07-10 18:23:48 +00002558
Caroline Tice0aa2e552011-01-14 00:29:16 +00002559 if (m_script_interpreter_ap.get() != NULL)
2560 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00002561
Caroline Tice0aa2e552011-01-14 00:29:16 +00002562 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2563 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00002564 {
Greg Clayton3e4238d2011-11-04 03:34:56 +00002565 case eScriptLanguagePython:
2566#ifndef LLDB_DISABLE_PYTHON
2567 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2568 break;
2569#else
2570 // Fall through to the None case when python is disabled
2571#endif
Caroline Tice0aa2e552011-01-14 00:29:16 +00002572 case eScriptLanguageNone:
2573 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2574 break;
Caroline Tice0aa2e552011-01-14 00:29:16 +00002575 default:
2576 break;
2577 };
2578
2579 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00002580}
2581
2582
2583
2584bool
2585CommandInterpreter::GetSynchronous ()
2586{
2587 return m_synchronous_execution;
2588}
2589
2590void
2591CommandInterpreter::SetSynchronous (bool value)
2592{
Johnny Chend7a4eb02010-10-14 01:22:03 +00002593 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00002594}
2595
2596void
2597CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2598 const char *word_text,
2599 const char *separator,
2600 const char *help_text,
2601 uint32_t max_word_len)
2602{
Greg Clayton238c0a12010-09-18 01:14:36 +00002603 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2604
Chris Lattner24943d22010-06-08 16:52:24 +00002605 int indent_size = max_word_len + strlen (separator) + 2;
2606
2607 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00002608
2609 StreamString text_strm;
2610 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2611
2612 size_t len = text_strm.GetSize();
2613 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00002614 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00002615 {
2616 text_strm.EOL();
2617 len = text_strm.GetSize();
2618 }
Chris Lattner24943d22010-06-08 16:52:24 +00002619
2620 if (len < max_columns)
2621 {
2622 // Output it as a single line.
2623 strm.Printf ("%s", text);
2624 }
2625 else
2626 {
2627 // We need to break it up into multiple lines.
2628 bool first_line = true;
2629 int text_width;
2630 int start = 0;
2631 int end = start;
2632 int final_end = strlen (text);
2633 int sub_len;
2634
2635 while (end < final_end)
2636 {
2637 if (first_line)
2638 text_width = max_columns - 1;
2639 else
2640 text_width = max_columns - indent_size - 1;
2641
2642 // Don't start the 'text' on a space, since we're already outputting the indentation.
2643 if (!first_line)
2644 {
2645 while ((start < final_end) && (text[start] == ' '))
2646 start++;
2647 }
2648
2649 end = start + text_width;
2650 if (end > final_end)
2651 end = final_end;
2652 else
2653 {
2654 // If we're not at the end of the text, make sure we break the line on white space.
2655 while (end > start
2656 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2657 end--;
Greg Clayton73844aa2012-08-22 17:17:09 +00002658 assert (end > 0);
Chris Lattner24943d22010-06-08 16:52:24 +00002659 }
2660
2661 sub_len = end - start;
2662 if (start != 0)
2663 strm.EOL();
2664 if (!first_line)
2665 strm.Indent();
2666 else
2667 first_line = false;
2668 assert (start <= final_end);
2669 assert (start + sub_len <= final_end);
2670 if (sub_len > 0)
2671 strm.Write (text + start, sub_len);
2672 start = end + 1;
2673 }
2674 }
2675 strm.EOL();
2676 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00002677}
2678
2679void
Enrico Granata1bba6e52011-07-07 00:38:40 +00002680CommandInterpreter::OutputHelpText (Stream &strm,
2681 const char *word_text,
2682 const char *separator,
2683 const char *help_text,
2684 uint32_t max_word_len)
2685{
2686 int indent_size = max_word_len + strlen (separator) + 2;
2687
2688 strm.IndentMore (indent_size);
2689
2690 StreamString text_strm;
2691 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2692
2693 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Enrico Granata1bba6e52011-07-07 00:38:40 +00002694
2695 size_t len = text_strm.GetSize();
2696 const char *text = text_strm.GetData();
2697
2698 uint32_t chars_left = max_columns;
2699
2700 for (uint32_t i = 0; i < len; i++)
2701 {
2702 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2703 {
Enrico Granata1bba6e52011-07-07 00:38:40 +00002704 chars_left = max_columns - indent_size;
2705 strm.EOL();
2706 strm.Indent();
2707 }
2708 else
2709 {
2710 strm.PutChar(text[i]);
2711 chars_left--;
2712 }
2713
2714 }
2715
2716 strm.EOL();
2717 strm.IndentLess(indent_size);
2718}
2719
2720void
Chris Lattner24943d22010-06-08 16:52:24 +00002721CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
2722 StringList &commands_found, StringList &commands_help)
2723{
2724 CommandObject::CommandMap::const_iterator pos;
2725 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
2726 CommandObject *sub_cmd_obj;
2727
2728 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
2729 {
2730 const char * command_name = pos->first.c_str();
2731 sub_cmd_obj = pos->second.get();
2732 StreamString complete_command_name;
2733
2734 complete_command_name.Printf ("%s %s", prefix, command_name);
2735
Greg Clayton238c0a12010-09-18 01:14:36 +00002736 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002737 {
2738 commands_found.AppendString (complete_command_name.GetData());
2739 commands_help.AppendString (sub_cmd_obj->GetHelp());
2740 }
2741
2742 if (sub_cmd_obj->IsMultiwordObject())
2743 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
2744 commands_help);
2745 }
2746
2747}
2748
2749void
2750CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2751 StringList &commands_help)
2752{
2753 CommandObject::CommandMap::const_iterator pos;
2754
2755 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2756 {
2757 const char *command_name = pos->first.c_str();
2758 CommandObject *cmd_obj = pos->second.get();
2759
Greg Clayton238c0a12010-09-18 01:14:36 +00002760 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002761 {
2762 commands_found.AppendString (command_name);
2763 commands_help.AppendString (cmd_obj->GetHelp());
2764 }
2765
2766 if (cmd_obj->IsMultiwordObject())
2767 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
2768
2769 }
2770}
Greg Claytonb72d0f02011-04-12 05:54:46 +00002771
2772
2773void
2774CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2775{
Greg Claytonb72d0f02011-04-12 05:54:46 +00002776 if (override_context != NULL)
2777 {
Greg Claytonbcaf99a2012-07-12 20:32:19 +00002778 m_exe_ctx_ref = *override_context;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002779 }
2780 else
2781 {
Greg Claytonbcaf99a2012-07-12 20:32:19 +00002782 const bool adopt_selected = true;
2783 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002784 }
2785}
2786
Jim Ingham6247dbe2011-07-12 03:12:18 +00002787void
2788CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2789{
2790 DumpHistory (stream, 0, count - 1);
2791}
2792
2793void
2794CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2795{
Greg Clayton7268b4c2011-10-28 21:38:01 +00002796 const size_t last_idx = std::min<size_t>(m_command_history.size(), end + 1);
2797 for (size_t i = start; i < last_idx; i++)
Jim Ingham6247dbe2011-07-12 03:12:18 +00002798 {
2799 if (!m_command_history[i].empty())
2800 {
2801 stream.Indent();
Greg Clayton7268b4c2011-10-28 21:38:01 +00002802 stream.Printf ("%4zu: %s\n", i, m_command_history[i].c_str());
Jim Ingham6247dbe2011-07-12 03:12:18 +00002803 }
2804 }
2805}
2806
2807const char *
2808CommandInterpreter::FindHistoryString (const char *input_str) const
2809{
2810 if (input_str[0] != m_repeat_char)
2811 return NULL;
2812 if (input_str[1] == '-')
2813 {
2814 bool success;
2815 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
2816 if (!success)
2817 return NULL;
2818 if (idx > m_command_history.size())
2819 return NULL;
2820 idx = m_command_history.size() - idx;
2821 return m_command_history[idx].c_str();
2822
2823 }
2824 else if (input_str[1] == m_repeat_char)
2825 {
2826 if (m_command_history.empty())
2827 return NULL;
2828 else
2829 return m_command_history.back().c_str();
2830 }
2831 else
2832 {
2833 bool success;
2834 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2835 if (!success)
2836 return NULL;
2837 if (idx >= m_command_history.size())
2838 return NULL;
2839 return m_command_history[idx].c_str();
2840 }
2841}