blob: 6db59ac2569cb202d01cfad299943f1e25d911ce [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
163 cmd_obj_sp = GetCommandSPExact ("thread backtrace", false);
164 if (cmd_obj_sp)
165 AddAlias ("bt", cmd_obj_sp);
166
Caroline Tice5ddbe212011-05-06 21:37:15 +0000167 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
168 if (cmd_obj_sp)
Jason Molenda47eb00e2011-10-22 00:47:41 +0000169 {
170 AddAlias ("stepi", cmd_obj_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000171 AddAlias ("si", cmd_obj_sp);
Jason Molenda47eb00e2011-10-22 00:47:41 +0000172 }
173
174 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
175 if (cmd_obj_sp)
176 {
177 AddAlias ("nexti", cmd_obj_sp);
178 AddAlias ("ni", cmd_obj_sp);
179 }
Caroline Tice5ddbe212011-05-06 21:37:15 +0000180
181 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
182 if (cmd_obj_sp)
183 {
184 AddAlias ("s", cmd_obj_sp);
185 AddAlias ("step", cmd_obj_sp);
186 }
187
188 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
189 if (cmd_obj_sp)
190 {
191 AddAlias ("n", cmd_obj_sp);
192 AddAlias ("next", cmd_obj_sp);
193 }
194
195 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
196 if (cmd_obj_sp)
197 {
Caroline Tice5ddbe212011-05-06 21:37:15 +0000198 AddAlias ("finish", cmd_obj_sp);
199 }
200
Jim Ingham59355252011-12-02 01:12:59 +0000201 cmd_obj_sp = GetCommandSPExact ("frame select", false);
202 if (cmd_obj_sp)
203 {
204 AddAlias ("f", cmd_obj_sp);
205 }
206
Jim Ingham2753a022012-10-05 19:16:31 +0000207 cmd_obj_sp = GetCommandSPExact ("thread select", false);
208 if (cmd_obj_sp)
209 {
210 AddAlias ("t", cmd_obj_sp);
211 }
212
Caroline Tice5ddbe212011-05-06 21:37:15 +0000213 cmd_obj_sp = GetCommandSPExact ("source list", false);
214 if (cmd_obj_sp)
215 {
216 AddAlias ("l", cmd_obj_sp);
217 AddAlias ("list", cmd_obj_sp);
218 }
219
220 cmd_obj_sp = GetCommandSPExact ("memory read", false);
221 if (cmd_obj_sp)
222 AddAlias ("x", cmd_obj_sp);
223
224 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
225 if (cmd_obj_sp)
226 AddAlias ("up", cmd_obj_sp);
227
228 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
229 if (cmd_obj_sp)
230 AddAlias ("down", cmd_obj_sp);
231
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000232 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000233 if (cmd_obj_sp)
234 AddAlias ("display", cmd_obj_sp);
Jim Ingham9d1acc12011-10-24 18:37:00 +0000235
236 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
237 if (cmd_obj_sp)
238 AddAlias ("dis", cmd_obj_sp);
239
240 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
241 if (cmd_obj_sp)
242 AddAlias ("di", cmd_obj_sp);
243
244
Jason Molenda730cae02011-10-22 01:30:52 +0000245
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000246 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000247 if (cmd_obj_sp)
248 AddAlias ("undisplay", cmd_obj_sp);
249
Caroline Tice5ddbe212011-05-06 21:37:15 +0000250 cmd_obj_sp = GetCommandSPExact ("target create", false);
251 if (cmd_obj_sp)
252 AddAlias ("file", cmd_obj_sp);
253
254 cmd_obj_sp = GetCommandSPExact ("target modules", false);
255 if (cmd_obj_sp)
256 AddAlias ("image", cmd_obj_sp);
257
258
259 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghame56493f2011-03-22 02:29:32 +0000260
Caroline Tice5ddbe212011-05-06 21:37:15 +0000261 cmd_obj_sp = GetCommandSPExact ("expression", false);
262 if (cmd_obj_sp)
263 {
264 AddAlias ("expr", cmd_obj_sp);
265
266 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
267 AddAlias ("p", cmd_obj_sp);
268 AddAlias ("print", cmd_obj_sp);
Sean Callanan59959eb2012-08-08 01:30:34 +0000269 AddAlias ("call", cmd_obj_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000270 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
271 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
Sean Callanan59959eb2012-08-08 01:30:34 +0000272 AddOrReplaceAliasOptions ("call", alias_arguments_vector_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000273
274 alias_arguments_vector_sp.reset (new OptionArgVector);
275 ProcessAliasOptionsArgs (cmd_obj_sp, "-o --", alias_arguments_vector_sp);
276 AddAlias ("po", cmd_obj_sp);
277 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
278 }
279
Sean Callananee301fa2012-06-01 23:29:32 +0000280 cmd_obj_sp = GetCommandSPExact ("process kill", false);
281 if (cmd_obj_sp)
Greg Claytonf2e53a52012-09-27 00:02:27 +0000282 {
Sean Callananee301fa2012-06-01 23:29:32 +0000283 AddAlias ("kill", cmd_obj_sp);
Greg Claytonf2e53a52012-09-27 00:02:27 +0000284 AddAlias ("k", cmd_obj_sp);
285 }
Sean Callananee301fa2012-06-01 23:29:32 +0000286
Caroline Tice5ddbe212011-05-06 21:37:15 +0000287 cmd_obj_sp = GetCommandSPExact ("process launch", false);
288 if (cmd_obj_sp)
289 {
290 alias_arguments_vector_sp.reset (new OptionArgVector);
Jason Molenda36eb7c02012-07-06 02:46:23 +0000291#if defined (__arm__)
292 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
293#else
Greg Clayton86c50d72012-05-18 00:04:38 +0000294 ProcessAliasOptionsArgs (cmd_obj_sp, "--shell=/bin/bash --", alias_arguments_vector_sp);
Jason Molenda36eb7c02012-07-06 02:46:23 +0000295#endif
Caroline Tice5ddbe212011-05-06 21:37:15 +0000296 AddAlias ("r", cmd_obj_sp);
297 AddAlias ("run", cmd_obj_sp);
298 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
299 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
300 }
Greg Claytonc84623f2012-03-29 21:47:51 +0000301
302 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
303 if (cmd_obj_sp)
304 {
305 AddAlias ("add-dsym", cmd_obj_sp);
306 }
Sean Callanan7b71b172012-05-21 18:25:19 +0000307
308 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
309 if (cmd_obj_sp)
310 {
311 alias_arguments_vector_sp.reset (new OptionArgVector);
312 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
313 AddAlias ("rb", cmd_obj_sp);
314 AddOrReplaceAliasOptions("rb", alias_arguments_vector_sp);
315 }
Chris Lattner24943d22010-06-08 16:52:24 +0000316}
317
Chris Lattner24943d22010-06-08 16:52:24 +0000318const char *
319CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
320{
321 // This function has not yet been implemented.
322
323 // Look for any embedded script command
324 // If found,
325 // get interpreter object from the command dictionary,
326 // call execute_one_command on it,
327 // get the results as a string,
328 // substitute that string for current stuff.
329
330 return arg;
331}
332
333
334void
335CommandInterpreter::LoadCommandDictionary ()
336{
337 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
338
339 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
340 //
341 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
342 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
343 // the cross-referencing stuff) are created!!!
344 //
345 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
346
347
348 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
349 // are created. This is so that when another command is created that needs to go into a crossref object,
350 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
351 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
352
Chris Lattner24943d22010-06-08 16:52:24 +0000353 // Non-CommandObjectCrossref commands can now be created.
354
Caroline Tice5bc8c972010-09-20 20:44:43 +0000355 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000356
Greg Clayton238c0a12010-09-18 01:14:36 +0000357 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000358 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000359 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000360 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000361 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
362 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Claytonabe0fed2011-04-18 08:33:37 +0000363// m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000364 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000365 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Claytone1f50b92011-05-03 22:09:39 +0000366 /// m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000367 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
368 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonb1888f22011-03-19 01:12:21 +0000369 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Enrico Granata6d101882012-09-28 23:57:51 +0000370 m_command_dict["plugin"] = CommandObjectSP (new CommandObjectPlugin (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000371 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000372 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000373 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000374 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000375 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000376 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000377 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
378 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata6b1596d2011-08-16 23:24:13 +0000379 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000380 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chen01acfa72011-09-22 18:04:58 +0000381 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000382
Jim Ingham2753a022012-10-05 19:16:31 +0000383 const char *break_regexes[][2] = {{"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2"},
384 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
385 {"^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
386 {"^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"},
387 {"^(-.*)$", "breakpoint set %1"},
388 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'"},
389 {"^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"}};
390
391 size_t num_regexes = sizeof break_regexes/sizeof(char *[2]);
392
Chris Lattner24943d22010-06-08 16:52:24 +0000393 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000394 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000395 "_regexp-break",
Johnny Chen58edac32012-08-23 00:32:22 +0000396 "Set a breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
397 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
Jim Ingham2753a022012-10-05 19:16:31 +0000398
Chris Lattner24943d22010-06-08 16:52:24 +0000399 if (break_regex_cmd_ap.get())
400 {
Jim Ingham2753a022012-10-05 19:16:31 +0000401 bool success = true;
402 for (size_t i = 0; i < num_regexes; i++)
403 {
404 success = break_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], break_regexes[i][1]);
405 if (!success)
406 break;
407 }
408 success = break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
409
410 if (success)
Chris Lattner24943d22010-06-08 16:52:24 +0000411 {
412 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
413 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
414 }
415 }
Jim Inghame56493f2011-03-22 02:29:32 +0000416
417 std::auto_ptr<CommandObjectRegexCommand>
Jim Ingham2753a022012-10-05 19:16:31 +0000418 tbreak_regex_cmd_ap(new CommandObjectRegexCommand (*this,
419 "_regexp-tbreak",
420 "Set a one shot breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
421 "_regexp-tbreak [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
422
423 if (tbreak_regex_cmd_ap.get())
424 {
425 bool success = true;
426 for (size_t i = 0; i < num_regexes; i++)
427 {
428 // If you add a resultant command string longer than 1024 characters be sure to increase the size of this buffer.
429 char buffer[1024];
430 int num_printed = snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o");
431 assert (num_printed < 1024);
432 success = tbreak_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], buffer);
433 if (!success)
434 break;
435 }
436 success = tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
437
438 if (success)
439 {
440 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
441 m_command_dict[tbreak_regex_cmd_sp->GetCommandName ()] = tbreak_regex_cmd_sp;
442 }
443 }
444
445 std::auto_ptr<CommandObjectRegexCommand>
Johnny Chena47e44b2012-08-24 18:15:45 +0000446 attach_regex_cmd_ap(new CommandObjectRegexCommand (*this,
447 "_regexp-attach",
448 "Attach to a process id if in decimal, otherwise treat the argument as a process name to attach to.",
449 "_regexp-attach [<pid>]\n_regexp-attach [<process-name>]", 2));
450 if (attach_regex_cmd_ap.get())
451 {
452 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "process attach --pid %1") &&
453 attach_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "process attach --name '%1'"))
454 {
455 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
456 m_command_dict[attach_regex_cmd_sp->GetCommandName ()] = attach_regex_cmd_sp;
457 }
458 }
459
460 std::auto_ptr<CommandObjectRegexCommand>
Jim Inghame56493f2011-03-22 02:29:32 +0000461 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000462 "_regexp-down",
463 "Go down \"n\" frames in the stack (1 frame by default).",
464 "_regexp-down [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000465 if (down_regex_cmd_ap.get())
466 {
467 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
468 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
469 {
470 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
471 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
472 }
473 }
474
475 std::auto_ptr<CommandObjectRegexCommand>
476 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000477 "_regexp-up",
478 "Go up \"n\" frames in the stack (1 frame by default).",
479 "_regexp-up [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000480 if (up_regex_cmd_ap.get())
481 {
482 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
483 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
484 {
485 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
486 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
487 }
488 }
Jason Molenda730cae02011-10-22 01:30:52 +0000489
490 std::auto_ptr<CommandObjectRegexCommand>
491 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000492 "_regexp-display",
Jason Molenda730cae02011-10-22 01:30:52 +0000493 "Add an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000494 "_regexp-display expression", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000495 if (display_regex_cmd_ap.get())
496 {
497 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
498 {
499 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
500 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
501 }
502 }
503
504 std::auto_ptr<CommandObjectRegexCommand>
505 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000506 "_regexp-undisplay",
Jason Molenda730cae02011-10-22 01:30:52 +0000507 "Remove an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000508 "_regexp-undisplay stop-hook-number", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000509 if (undisplay_regex_cmd_ap.get())
510 {
511 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
512 {
513 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
514 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
515 }
516 }
517
Greg Claytonc3750432012-09-26 22:26:47 +0000518 std::auto_ptr<CommandObjectRegexCommand>
519 connect_gdb_remote_cmd_ap(new CommandObjectRegexCommand (*this,
520 "gdb-remote",
521 "Connect to a remote GDB server.",
522 "gdb-remote [<host>:<port>]\ngdb-remote [<port>]", 2));
523 if (connect_gdb_remote_cmd_ap.get())
524 {
525 if (connect_gdb_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin gdb-remote connect://%1") &&
526 connect_gdb_remote_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "process connect --plugin gdb-remote connect://localhost:%1"))
527 {
528 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
529 m_command_dict[command_sp->GetCommandName ()] = command_sp;
530 }
531 }
532
533 std::auto_ptr<CommandObjectRegexCommand>
534 connect_kdp_remote_cmd_ap(new CommandObjectRegexCommand (*this,
535 "kdp-remote",
536 "Connect to a remote KDP server.",
537 "kdp-remote [<host>]\nkdp-remote [<host>:<port>]", 2));
538 if (connect_kdp_remote_cmd_ap.get())
539 {
540 if (connect_kdp_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin kdp-remote udp://%1") &&
Jason Molenda73feea42012-09-27 02:47:55 +0000541 connect_kdp_remote_cmd_ap->AddRegexCommand("^(.+)$", "process connect --plugin kdp-remote udp://%1:41139"))
Greg Claytonc3750432012-09-26 22:26:47 +0000542 {
543 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
544 m_command_dict[command_sp->GetCommandName ()] = command_sp;
545 }
546 }
547
Jason Molenda1a48cb72012-10-05 05:29:32 +0000548 std::auto_ptr<CommandObjectRegexCommand>
549 bt_regex_cmd_ap(new CommandObjectRegexCommand (*this,
550 "bt",
551 "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.",
552 "bt [<digit>|all]", 2));
553 if (bt_regex_cmd_ap.get())
554 {
555 // accept but don't document "bt -c <number>" -- before bt was a regex command if you wanted to backtrace
556 // three frames you would do "bt -c 3" but the intention is to have this emulate the gdb "bt" command and
557 // so now "bt 3" is the preferred form, in line with gdb.
558 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "thread backtrace -c %1") &&
559 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$", "thread backtrace -c %1") &&
560 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
561 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace"))
562 {
563 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
564 m_command_dict[command_sp->GetCommandName ()] = command_sp;
565 }
566 }
567
Chris Lattner24943d22010-06-08 16:52:24 +0000568}
569
570int
571CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
572 StringList &matches)
573{
574 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
575
576 if (include_aliases)
577 {
578 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
579 }
580
581 return matches.GetSize();
582}
583
584CommandObjectSP
585CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
586{
587 CommandObject::CommandMap::iterator pos;
588 CommandObjectSP ret_val;
589
590 std::string cmd(cmd_cstr);
591
592 if (HasCommands())
593 {
594 pos = m_command_dict.find(cmd);
595 if (pos != m_command_dict.end())
596 ret_val = pos->second;
597 }
598
599 if (include_aliases && HasAliases())
600 {
601 pos = m_alias_dict.find(cmd);
602 if (pos != m_alias_dict.end())
603 ret_val = pos->second;
604 }
605
606 if (HasUserCommands())
607 {
608 pos = m_user_dict.find(cmd);
609 if (pos != m_user_dict.end())
610 ret_val = pos->second;
611 }
612
Sean Callananb386d822012-08-09 00:50:26 +0000613 if (!exact && !ret_val)
Chris Lattner24943d22010-06-08 16:52:24 +0000614 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000615 // We will only get into here if we didn't find any exact matches.
616
617 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
618
Chris Lattner24943d22010-06-08 16:52:24 +0000619 StringList local_matches;
620 if (matches == NULL)
621 matches = &local_matches;
622
Jim Inghamd40f8a62010-07-06 22:46:59 +0000623 unsigned int num_cmd_matches = 0;
624 unsigned int num_alias_matches = 0;
625 unsigned int num_user_matches = 0;
626
627 // Look through the command dictionaries one by one, and if we get only one match from any of
628 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
629
Chris Lattner24943d22010-06-08 16:52:24 +0000630 if (HasCommands())
631 {
632 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
633 }
634
635 if (num_cmd_matches == 1)
636 {
637 cmd.assign(matches->GetStringAtIndex(0));
638 pos = m_command_dict.find(cmd);
639 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000640 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000641 }
642
Jim Ingham9a574172010-06-24 20:28:42 +0000643 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000644 {
645 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
646
647 }
648
Jim Inghamd40f8a62010-07-06 22:46:59 +0000649 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000650 {
651 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
652 pos = m_alias_dict.find(cmd);
653 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000654 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000655 }
656
Jim Ingham9a574172010-06-24 20:28:42 +0000657 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000658 {
659 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
660 }
661
Jim Inghamd40f8a62010-07-06 22:46:59 +0000662 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000663 {
664 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
665
666 pos = m_user_dict.find (cmd);
667 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000668 user_match_sp = pos->second;
669 }
670
671 // If we got exactly one match, return that, otherwise return the match list.
672
673 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
674 {
675 if (num_cmd_matches)
676 return real_match_sp;
677 else if (num_alias_matches)
678 return alias_match_sp;
679 else
680 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000681 }
682 }
Sean Callananb386d822012-08-09 00:50:26 +0000683 else if (matches && ret_val)
Jim Inghamd40f8a62010-07-06 22:46:59 +0000684 {
685 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000686 }
687
688
689 return ret_val;
690}
691
Greg Claytond12aeab2011-04-20 16:37:46 +0000692bool
693CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
694{
695 if (name && name[0])
696 {
697 std::string name_sstr(name);
Enrico Granata2f1014b2012-10-01 17:19:37 +0000698 bool found = (m_command_dict.find (name_sstr) != m_command_dict.end());
699 if (found && !can_replace)
700 return false;
701 if (found && m_command_dict[name_sstr]->IsRemovable() == false)
Enrico Granata6d101882012-09-28 23:57:51 +0000702 return false;
Greg Claytond12aeab2011-04-20 16:37:46 +0000703 m_command_dict[name_sstr] = cmd_sp;
704 return true;
705 }
706 return false;
707}
708
Enrico Granata6b1596d2011-08-16 23:24:13 +0000709bool
Enrico Granata6010ace2011-11-07 22:57:04 +0000710CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata6b1596d2011-08-16 23:24:13 +0000711 const lldb::CommandObjectSP &cmd_sp,
712 bool can_replace)
713{
Enrico Granata6010ace2011-11-07 22:57:04 +0000714 if (!name.empty())
Enrico Granata6b1596d2011-08-16 23:24:13 +0000715 {
Enrico Granata6010ace2011-11-07 22:57:04 +0000716
717 const char* name_cstr = name.c_str();
718
719 // do not allow replacement of internal commands
720 if (CommandExists(name_cstr))
Enrico Granata6d101882012-09-28 23:57:51 +0000721 {
722 if (can_replace == false)
723 return false;
724 if (m_command_dict[name]->IsRemovable() == false)
725 return false;
726 }
Enrico Granata6010ace2011-11-07 22:57:04 +0000727
Enrico Granata6d101882012-09-28 23:57:51 +0000728 if (UserCommandExists(name_cstr))
729 {
730 if (can_replace == false)
731 return false;
732 if (m_user_dict[name]->IsRemovable() == false)
733 return false;
734 }
735
Enrico Granata6010ace2011-11-07 22:57:04 +0000736 m_user_dict[name] = cmd_sp;
Enrico Granata6b1596d2011-08-16 23:24:13 +0000737 return true;
738 }
739 return false;
740}
Greg Claytond12aeab2011-04-20 16:37:46 +0000741
Jim Inghamd40f8a62010-07-06 22:46:59 +0000742CommandObjectSP
743CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000744{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000745 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
746 CommandObjectSP ret_val; // Possibly empty return value.
747
748 if (cmd_cstr == NULL)
749 return ret_val;
750
751 if (cmd_words.GetArgumentCount() == 1)
752 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
753 else
754 {
755 // We have a multi-word command (seemingly), so we need to do more work.
756 // First, get the cmd_obj_sp for the first word in the command.
757 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
758 if (cmd_obj_sp.get() != NULL)
759 {
760 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
761 // command name), and find the appropriate sub-command SP for each command word....
762 size_t end = cmd_words.GetArgumentCount();
763 for (size_t j= 1; j < end; ++j)
764 {
765 if (cmd_obj_sp->IsMultiwordObject())
766 {
767 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
768 (cmd_words.GetArgumentAtIndex (j));
769 if (cmd_obj_sp.get() == NULL)
770 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
771 return ret_val;
772 }
773 else
774 // We have more words in the command name, but we don't have a multiword object. Fail and return
775 // empty 'ret_val'.
776 return ret_val;
777 }
778 // We successfully looped through all the command words and got valid command objects for them. Assign the
779 // last object retrieved to 'ret_val'.
780 ret_val = cmd_obj_sp;
781 }
782 }
783 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000784}
785
786CommandObject *
787CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
788{
789 return GetCommandSPExact (cmd_cstr, include_aliases).get();
790}
791
792CommandObject *
793CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
794{
795 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
796
797 // If we didn't find an exact match to the command string in the commands, look in
798 // the aliases.
799
800 if (command_obj == NULL)
801 {
802 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
803 }
804
805 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
806 // in both the commands and the aliases.
807
808 if (command_obj == NULL)
809 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
810
811 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000812}
813
814bool
815CommandInterpreter::CommandExists (const char *cmd)
816{
817 return m_command_dict.find(cmd) != m_command_dict.end();
818}
819
820bool
Caroline Tice5ddbe212011-05-06 21:37:15 +0000821CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
822 const char *options_args,
823 OptionArgVectorSP &option_arg_vector_sp)
824{
825 bool success = true;
826 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
827
828 if (!options_args || (strlen (options_args) < 1))
829 return true;
830
831 std::string options_string (options_args);
832 Args args (options_args);
833 CommandReturnObject result;
834 // Check to see if the command being aliased can take any command options.
835 Options *options = cmd_obj_sp->GetOptions ();
836 if (options)
837 {
838 // See if any options were specified as part of the alias; if so, handle them appropriately.
839 options->NotifyOptionParsingStarting ();
840 args.Unshift ("dummy_arg");
841 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
842 args.Shift ();
843 if (result.Succeeded())
844 options->VerifyPartialOptions (result);
845 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
846 {
847 result.AppendError ("Unable to create requested alias.\n");
848 return false;
849 }
850 }
851
Greg Clayton7268b4c2011-10-28 21:38:01 +0000852 if (!options_string.empty())
Caroline Tice5ddbe212011-05-06 21:37:15 +0000853 {
854 if (cmd_obj_sp->WantsRawCommandString ())
855 option_arg_vector->push_back (OptionArgPair ("<argument>",
856 OptionArgValue (-1,
857 options_string)));
858 else
859 {
860 int argc = args.GetArgumentCount();
861 for (size_t i = 0; i < argc; ++i)
862 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
863 option_arg_vector->push_back
864 (OptionArgPair ("<argument>",
865 OptionArgValue (-1,
866 std::string (args.GetArgumentAtIndex (i)))));
867 }
868 }
869
870 return success;
871}
872
873bool
Chris Lattner24943d22010-06-08 16:52:24 +0000874CommandInterpreter::AliasExists (const char *cmd)
875{
876 return m_alias_dict.find(cmd) != m_alias_dict.end();
877}
878
879bool
880CommandInterpreter::UserCommandExists (const char *cmd)
881{
882 return m_user_dict.find(cmd) != m_user_dict.end();
883}
884
885void
886CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
887{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000888 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000889 m_alias_dict[alias_name] = command_obj_sp;
890}
891
892bool
893CommandInterpreter::RemoveAlias (const char *alias_name)
894{
895 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
896 if (pos != m_alias_dict.end())
897 {
898 m_alias_dict.erase(pos);
899 return true;
900 }
901 return false;
902}
903bool
904CommandInterpreter::RemoveUser (const char *alias_name)
905{
906 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
907 if (pos != m_user_dict.end())
908 {
909 m_user_dict.erase(pos);
910 return true;
911 }
912 return false;
913}
914
Chris Lattner24943d22010-06-08 16:52:24 +0000915void
916CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
917{
918 help_string.Printf ("'%s", command_name);
919 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
920
Sean Callananb386d822012-08-09 00:50:26 +0000921 if (option_arg_vector_sp)
Chris Lattner24943d22010-06-08 16:52:24 +0000922 {
923 OptionArgVector *options = option_arg_vector_sp.get();
924 for (int i = 0; i < options->size(); ++i)
925 {
926 OptionArgPair cur_option = (*options)[i];
927 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000928 OptionArgValue value_pair = cur_option.second;
929 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000930 if (opt.compare("<argument>") == 0)
931 {
932 help_string.Printf (" %s", value.c_str());
933 }
934 else
935 {
936 help_string.Printf (" %s", opt.c_str());
937 if ((value.compare ("<no-argument>") != 0)
938 && (value.compare ("<need-argument") != 0))
939 {
940 help_string.Printf (" %s", value.c_str());
941 }
942 }
943 }
944 }
945
946 help_string.Printf ("'");
947}
948
Greg Clayton65124ea2010-08-26 22:05:43 +0000949size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000950CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
951{
952 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000953 CommandObject::CommandMap::const_iterator end = dict.end();
954 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000955
Greg Clayton65124ea2010-08-26 22:05:43 +0000956 for (pos = dict.begin(); pos != end; ++pos)
957 {
958 size_t len = pos->first.size();
959 if (max_len < len)
960 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000961 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000962 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000963}
964
965void
Enrico Granata6b1596d2011-08-16 23:24:13 +0000966CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata1ac6d1f2011-09-09 17:49:36 +0000967 uint32_t cmd_types)
Chris Lattner24943d22010-06-08 16:52:24 +0000968{
969 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000970 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata6b1596d2011-08-16 23:24:13 +0000971
972 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner24943d22010-06-08 16:52:24 +0000973 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000974
975 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
976 result.AppendMessage("");
Chris Lattner24943d22010-06-08 16:52:24 +0000977
Enrico Granata6b1596d2011-08-16 23:24:13 +0000978 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
979 {
980 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
981 max_len);
982 }
983 result.AppendMessage("");
984
985 }
986
Greg Clayton7268b4c2011-10-28 21:38:01 +0000987 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner24943d22010-06-08 16:52:24 +0000988 {
Jim Inghame3663e82010-10-22 18:47:16 +0000989 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000990 "(see 'help command alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000991 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000992 max_len = FindLongestCommandWord (m_alias_dict);
993
Chris Lattner24943d22010-06-08 16:52:24 +0000994 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
995 {
996 StreamString sstr;
997 StreamString translation_and_help;
998 std::string entry_name = pos->first;
999 std::string second_entry = pos->second.get()->GetCommandName();
1000 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
1001
1002 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
1003 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
1004 translation_and_help.GetData(), max_len);
1005 }
1006 result.AppendMessage("");
1007 }
1008
Greg Clayton7268b4c2011-10-28 21:38:01 +00001009 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner24943d22010-06-08 16:52:24 +00001010 {
1011 result.AppendMessage ("The following is a list of your current user-defined commands:");
1012 result.AppendMessage("");
Enrico Granata6b1596d2011-08-16 23:24:13 +00001013 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner24943d22010-06-08 16:52:24 +00001014 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
1015 {
Enrico Granata6b1596d2011-08-16 23:24:13 +00001016 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1017 max_len);
Chris Lattner24943d22010-06-08 16:52:24 +00001018 }
1019 result.AppendMessage("");
1020 }
1021
1022 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
1023}
1024
Caroline Ticee0da7a52010-12-09 22:52:49 +00001025CommandObject *
1026CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +00001027{
Caroline Ticee0da7a52010-12-09 22:52:49 +00001028 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
1029 // eventually be invoked by the given command line.
1030
1031 CommandObject *cmd_obj = NULL;
1032 std::string white_space (" \t\v");
1033 size_t start = command_string.find_first_not_of (white_space);
1034 size_t end = 0;
1035 bool done = false;
1036 while (!done)
1037 {
1038 if (start != std::string::npos)
1039 {
1040 // Get the next word from command_string.
1041 end = command_string.find_first_of (white_space, start);
1042 if (end == std::string::npos)
1043 end = command_string.size();
1044 std::string cmd_word = command_string.substr (start, end - start);
1045
1046 if (cmd_obj == NULL)
1047 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
1048 // command or alias.
1049 cmd_obj = GetCommandObject (cmd_word.c_str());
1050 else if (cmd_obj->IsMultiwordObject ())
1051 {
1052 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
1053 CommandObject *sub_cmd_obj =
1054 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
1055 if (sub_cmd_obj)
1056 cmd_obj = sub_cmd_obj;
1057 else // cmd_word was not a valid sub-command word, so we are donee
1058 done = true;
1059 }
1060 else
1061 // We have a cmd_obj and it is not a multi-word object, so we are done.
1062 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001063
Caroline Ticee0da7a52010-12-09 22:52:49 +00001064 // If we didn't find a valid command object, or our command object is not a multi-word object, or
1065 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
1066 // next word.
1067
1068 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
1069 done = true;
1070 else
1071 start = command_string.find_first_not_of (white_space, end);
1072 }
1073 else
1074 // Unable to find any more words.
1075 done = true;
1076 }
1077
1078 if (end == command_string.size())
1079 command_string.clear();
1080 else
1081 command_string = command_string.substr(end);
1082
1083 return cmd_obj;
1084}
1085
Greg Clayton9d855c62011-10-25 00:36:27 +00001086static const char *k_white_space = " \t\v";
Greg Clayton7268b4c2011-10-28 21:38:01 +00001087static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton9d855c62011-10-25 00:36:27 +00001088static void
1089StripLeadingSpaces (std::string &s)
Caroline Ticee0da7a52010-12-09 22:52:49 +00001090{
Greg Clayton9d855c62011-10-25 00:36:27 +00001091 if (!s.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +00001092 {
Greg Clayton9d855c62011-10-25 00:36:27 +00001093 size_t pos = s.find_first_not_of (k_white_space);
1094 if (pos == std::string::npos)
1095 s.clear();
1096 else if (pos == 0)
1097 return;
1098 s.erase (0, pos);
1099 }
1100}
1101
Greg Clayton3840cd72011-11-09 23:25:03 +00001102static size_t
1103FindArgumentTerminator (const std::string &s)
1104{
Greg Clayton3840cd72011-11-09 23:25:03 +00001105 const size_t s_len = s.size();
1106 size_t offset = 0;
1107 while (offset < s_len)
1108 {
1109 size_t pos = s.find ("--", offset);
1110 if (pos == std::string::npos)
1111 break;
1112 if (pos > 0)
1113 {
1114 if (isspace(s[pos-1]))
1115 {
1116 // Check if the string ends "\s--" (where \s is a space character)
1117 // or if we have "\s--\s".
1118 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
1119 {
Greg Clayton3840cd72011-11-09 23:25:03 +00001120 return pos;
1121 }
1122 }
1123 }
1124 offset = pos + 2;
1125 }
Greg Clayton3840cd72011-11-09 23:25:03 +00001126 return std::string::npos;
1127}
1128
Greg Clayton9d855c62011-10-25 00:36:27 +00001129static bool
Greg Clayton7268b4c2011-10-28 21:38:01 +00001130ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton9d855c62011-10-25 00:36:27 +00001131{
Greg Clayton7268b4c2011-10-28 21:38:01 +00001132 command.clear();
1133 suffix.clear();
Greg Clayton9d855c62011-10-25 00:36:27 +00001134 StripLeadingSpaces (command_string);
1135
1136 bool result = false;
1137 quote_char = '\0';
1138
1139 if (!command_string.empty())
1140 {
1141 const char first_char = command_string[0];
1142 if (first_char == '\'' || first_char == '"')
Caroline Ticee0da7a52010-12-09 22:52:49 +00001143 {
Greg Clayton9d855c62011-10-25 00:36:27 +00001144 quote_char = first_char;
1145 const size_t end_quote_pos = command_string.find (quote_char, 1);
1146 if (end_quote_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +00001147 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001148 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +00001149 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +00001150 }
1151 else
1152 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001153 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton9d855c62011-10-25 00:36:27 +00001154 if (end_quote_pos + 1 < command_string.size())
1155 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
1156 else
1157 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +00001158 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001159 }
1160 else
1161 {
Greg Clayton9d855c62011-10-25 00:36:27 +00001162 const size_t first_space_pos = command_string.find_first_of (k_white_space);
1163 if (first_space_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +00001164 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001165 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +00001166 command_string.erase();
Caroline Tice649116c2011-05-11 16:07:06 +00001167 }
1168 else
1169 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001170 command.assign (command_string, 0, first_space_pos);
1171 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice649116c2011-05-11 16:07:06 +00001172 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001173 }
Greg Clayton9d855c62011-10-25 00:36:27 +00001174 result = true;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001175 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001176
1177
1178 if (!command.empty())
1179 {
1180 // actual commands can't start with '-' or '_'
1181 if (command[0] != '-' && command[0] != '_')
1182 {
1183 size_t pos = command.find_first_not_of(k_valid_command_chars);
1184 if (pos > 0 && pos != std::string::npos)
1185 {
1186 suffix.assign (command.begin() + pos, command.end());
1187 command.erase (pos);
1188 }
1189 }
1190 }
Greg Clayton9d855c62011-10-25 00:36:27 +00001191
1192 return result;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001193}
1194
Greg Clayton7268b4c2011-10-28 21:38:01 +00001195CommandObject *
1196CommandInterpreter::BuildAliasResult (const char *alias_name,
1197 std::string &raw_input_string,
1198 std::string &alias_result,
1199 CommandReturnObject &result)
Caroline Ticee0da7a52010-12-09 22:52:49 +00001200{
Greg Clayton7268b4c2011-10-28 21:38:01 +00001201 CommandObject *alias_cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001202 Args cmd_args (raw_input_string.c_str());
1203 alias_cmd_obj = GetCommandObject (alias_name);
1204 StreamString result_str;
1205
1206 if (alias_cmd_obj)
1207 {
1208 std::string alias_name_str = alias_name;
1209 if ((cmd_args.GetArgumentCount() == 0)
1210 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1211 cmd_args.Unshift (alias_name);
1212
1213 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1214 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1215
1216 if (option_arg_vector_sp.get())
1217 {
1218 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1219
1220 for (int i = 0; i < option_arg_vector->size(); ++i)
1221 {
1222 OptionArgPair option_pair = (*option_arg_vector)[i];
1223 OptionArgValue value_pair = option_pair.second;
1224 int value_type = value_pair.first;
1225 std::string option = option_pair.first;
1226 std::string value = value_pair.second;
1227 if (option.compare ("<argument>") == 0)
1228 result_str.Printf (" %s", value.c_str());
1229 else
1230 {
1231 result_str.Printf (" %s", option.c_str());
1232 if (value_type != optional_argument)
1233 result_str.Printf (" ");
1234 if (value.compare ("<no_argument>") != 0)
1235 {
1236 int index = GetOptionArgumentPosition (value.c_str());
1237 if (index == 0)
1238 result_str.Printf ("%s", value.c_str());
1239 else if (index >= cmd_args.GetArgumentCount())
1240 {
1241
1242 result.AppendErrorWithFormat
1243 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1244 index);
1245 result.SetStatus (eReturnStatusFailed);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001246 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001247 }
1248 else
1249 {
1250 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1251 if (strpos != std::string::npos)
1252 raw_input_string = raw_input_string.erase (strpos,
1253 strlen (cmd_args.GetArgumentAtIndex (index)));
1254 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1255 }
1256 }
1257 }
1258 }
1259 }
1260
1261 alias_result = result_str.GetData();
1262 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001263 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001264}
1265
Greg Claytonf5c0c722011-10-14 07:41:33 +00001266Error
1267CommandInterpreter::PreprocessCommand (std::string &command)
1268{
1269 // The command preprocessor needs to do things to the command
1270 // line before any parsing of arguments or anything else is done.
1271 // The only current stuff that gets proprocessed is anyting enclosed
1272 // in backtick ('`') characters is evaluated as an expression and
1273 // the result of the expression must be a scalar that can be substituted
1274 // into the command. An example would be:
1275 // (lldb) memory read `$rsp + 20`
1276 Error error; // Error for any expressions that might not evaluate
1277 size_t start_backtick;
1278 size_t pos = 0;
1279 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1280 {
1281 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1282 {
1283 // The backtick was preceeded by a '\' character, remove the slash
1284 // and don't treat the backtick as the start of an expression
1285 command.erase(start_backtick-1, 1);
1286 // No need to add one to start_backtick since we just deleted a char
1287 pos = start_backtick;
1288 }
1289 else
1290 {
1291 const size_t expr_content_start = start_backtick + 1;
1292 const size_t end_backtick = command.find ('`', expr_content_start);
1293 if (end_backtick == std::string::npos)
1294 return error;
1295 else if (end_backtick == expr_content_start)
1296 {
1297 // Empty expression (two backticks in a row)
1298 command.erase (start_backtick, 2);
1299 }
1300 else
1301 {
1302 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1303
Greg Claytonbcaf99a2012-07-12 20:32:19 +00001304 ExecutionContext exe_ctx(GetExecutionContext());
1305 Target *target = exe_ctx.GetTargetPtr();
Johnny Chenb09f8472011-10-29 00:21:50 +00001306 // Get a dummy target to allow for calculator mode while processing backticks.
1307 // This also helps break the infinite loop caused when target is null.
1308 if (!target)
1309 target = Host::GetDummyTarget(GetDebugger()).get();
Greg Claytonf5c0c722011-10-14 07:41:33 +00001310 if (target)
1311 {
Greg Claytonf5c0c722011-10-14 07:41:33 +00001312 ValueObjectSP expr_result_valobj_sp;
Enrico Granatad27026e2012-09-05 20:41:26 +00001313
1314 Target::EvaluateExpressionOptions options;
1315 options.SetCoerceToId(false)
1316 .SetUnwindOnError(true)
1317 .SetKeepInMemory(false)
1318 .SetSingleThreadTimeoutUsec(0);
1319
Greg Claytonf5c0c722011-10-14 07:41:33 +00001320 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
Enrico Granatad27026e2012-09-05 20:41:26 +00001321 exe_ctx.GetFramePtr(),
Enrico Granata6cca9692012-07-16 23:10:35 +00001322 expr_result_valobj_sp,
Enrico Granatad27026e2012-09-05 20:41:26 +00001323 options);
1324
Greg Claytonf5c0c722011-10-14 07:41:33 +00001325 if (expr_result == eExecutionCompleted)
1326 {
1327 Scalar scalar;
1328 if (expr_result_valobj_sp->ResolveValue (scalar))
1329 {
1330 command.erase (start_backtick, end_backtick - start_backtick + 1);
1331 StreamString value_strm;
1332 const bool show_type = false;
1333 scalar.GetValue (&value_strm, show_type);
1334 size_t value_string_size = value_strm.GetSize();
1335 if (value_string_size)
1336 {
1337 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1338 pos = start_backtick + value_string_size;
1339 continue;
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 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1349 }
1350 }
1351 else
1352 {
1353 if (expr_result_valobj_sp)
1354 error = expr_result_valobj_sp->GetError();
1355 if (error.Success())
1356 {
1357
1358 switch (expr_result)
1359 {
1360 case eExecutionSetupError:
1361 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1362 break;
1363 case eExecutionCompleted:
1364 break;
1365 case eExecutionDiscarded:
1366 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1367 break;
1368 case eExecutionInterrupted:
1369 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1370 break;
1371 case eExecutionTimedOut:
1372 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1373 break;
1374 }
1375 }
1376 }
1377 }
1378 }
1379 if (error.Fail())
1380 break;
1381 }
1382 }
1383 return error;
1384}
1385
1386
Caroline Ticee0da7a52010-12-09 22:52:49 +00001387bool
1388CommandInterpreter::HandleCommand (const char *command_line,
Enrico Granata01bc2d42012-05-31 01:09:06 +00001389 LazyBool lazy_add_to_history,
Caroline Ticee0da7a52010-12-09 22:52:49 +00001390 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001391 ExecutionContext *override_context,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001392 bool repeat_on_empty_command,
1393 bool no_context_switching)
Jim Ingham949d5ac2011-02-18 00:54:25 +00001394
Caroline Ticee0da7a52010-12-09 22:52:49 +00001395{
Jim Ingham949d5ac2011-02-18 00:54:25 +00001396
Caroline Ticee0da7a52010-12-09 22:52:49 +00001397 bool done = false;
1398 CommandObject *cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001399 bool wants_raw_input = false;
1400 std::string command_string (command_line);
Jim Ingham6247dbe2011-07-12 03:12:18 +00001401 std::string original_command_string (command_line);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001402
1403 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +00001404 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1405
1406 // Make a scoped cleanup object that will clear the crash description string
1407 // on exit of this function.
Enrico Granata1a102082011-07-12 00:18:11 +00001408 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Claytone98ac252010-11-10 04:57:04 +00001409
Caroline Ticee0da7a52010-12-09 22:52:49 +00001410 if (log)
1411 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +00001412
Jim Inghamabab14b2010-11-04 23:08:45 +00001413 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1414
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001415 if (!no_context_switching)
1416 UpdateExecutionContext (override_context);
Enrico Granata01bc2d42012-05-31 01:09:06 +00001417
1418 // <rdar://problem/11328896>
1419 bool add_to_history;
1420 if (lazy_add_to_history == eLazyBoolCalculate)
1421 add_to_history = (m_command_source_depth == 0);
1422 else
1423 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1424
Jim Ingham949d5ac2011-02-18 00:54:25 +00001425 bool empty_command = false;
1426 bool comment_command = false;
1427 if (command_string.empty())
1428 empty_command = true;
1429 else
Chris Lattner24943d22010-06-08 16:52:24 +00001430 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001431 const char *k_space_characters = "\t\n\v\f\r ";
1432
1433 size_t non_space = command_string.find_first_not_of (k_space_characters);
1434 // Check for empty line or comment line (lines whose first
1435 // non-space character is the comment character for this interpreter)
1436 if (non_space == std::string::npos)
1437 empty_command = true;
1438 else if (command_string[non_space] == m_comment_char)
1439 comment_command = true;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001440 else if (command_string[non_space] == m_repeat_char)
1441 {
1442 const char *history_string = FindHistoryString (command_string.c_str() + non_space);
1443 if (history_string == NULL)
1444 {
1445 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1446 result.SetStatus(eReturnStatusFailed);
1447 return false;
1448 }
1449 add_to_history = false;
1450 command_string = history_string;
1451 original_command_string = history_string;
1452 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001453 }
1454
1455 if (empty_command)
1456 {
1457 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +00001458 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001459 if (m_command_history.empty())
1460 {
1461 result.AppendError ("empty command");
1462 result.SetStatus(eReturnStatusFailed);
1463 return false;
1464 }
1465 else
1466 {
1467 command_line = m_repeat_command.c_str();
1468 command_string = command_line;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001469 original_command_string = command_line;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001470 if (m_repeat_command.empty())
1471 {
1472 result.AppendErrorWithFormat("No auto repeat.\n");
1473 result.SetStatus (eReturnStatusFailed);
1474 return false;
1475 }
1476 }
1477 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001478 }
1479 else
1480 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001481 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1482 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001483 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001484 }
1485 else if (comment_command)
1486 {
1487 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1488 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001489 }
Caroline Tice649116c2011-05-11 16:07:06 +00001490
Greg Claytonf5c0c722011-10-14 07:41:33 +00001491
1492 Error error (PreprocessCommand (command_string));
1493
1494 if (error.Fail())
1495 {
1496 result.AppendError (error.AsCString());
1497 result.SetStatus(eReturnStatusFailed);
1498 return false;
1499 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001500 // Phase 1.
1501
1502 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1503 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1504 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1505 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1506 // 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 +00001507 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +00001508 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +00001509
Caroline Ticee0da7a52010-12-09 22:52:49 +00001510 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001511 size_t actual_cmd_name_len = 0;
Greg Clayton7268b4c2011-10-28 21:38:01 +00001512 std::string next_word;
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001513 StringList matches;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001514 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +00001515 {
Caroline Tice649116c2011-05-11 16:07:06 +00001516 char quote_char = '\0';
Greg Clayton7268b4c2011-10-28 21:38:01 +00001517 std::string suffix;
1518 ExtractCommand (command_string, next_word, suffix, quote_char);
1519 if (cmd_obj == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +00001520 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001521 if (AliasExists (next_word.c_str()))
Caroline Tice56d2fc42010-12-14 18:51:39 +00001522 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001523 std::string alias_result;
1524 cmd_obj = BuildAliasResult (next_word.c_str(), command_string, alias_result, result);
1525 revised_command_line.Printf ("%s", alias_result.c_str());
1526 if (cmd_obj)
1527 {
1528 wants_raw_input = cmd_obj->WantsRawCommandString ();
1529 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1530 }
Chris Lattner24943d22010-06-08 16:52:24 +00001531 }
1532 else
1533 {
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001534 cmd_obj = GetCommandObject (next_word.c_str(), &matches);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001535 if (cmd_obj)
1536 {
1537 actual_cmd_name_len += next_word.length();
1538 revised_command_line.Printf ("%s", next_word.c_str());
1539 wants_raw_input = cmd_obj->WantsRawCommandString ();
1540 }
Caroline Tice649116c2011-05-11 16:07:06 +00001541 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001542 {
1543 revised_command_line.Printf ("%s", next_word.c_str());
1544 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001545 }
1546 }
1547 else
1548 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001549 if (cmd_obj->IsMultiwordObject ())
1550 {
1551 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
1552 if (sub_cmd_obj)
1553 {
1554 actual_cmd_name_len += next_word.length() + 1;
1555 revised_command_line.Printf (" %s", next_word.c_str());
1556 cmd_obj = sub_cmd_obj;
1557 wants_raw_input = cmd_obj->WantsRawCommandString ();
1558 }
1559 else
1560 {
1561 if (quote_char)
1562 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1563 else
1564 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1565 done = true;
1566 }
1567 }
Caroline Tice649116c2011-05-11 16:07:06 +00001568 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001569 {
1570 if (quote_char)
1571 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1572 else
1573 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1574 done = true;
1575 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001576 }
1577
1578 if (cmd_obj == NULL)
1579 {
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001580 uint32_t num_matches = matches.GetSize();
1581 if (matches.GetSize() > 1) {
1582 std::string error_msg;
1583 error_msg.assign ("Ambiguous command '");
1584 error_msg.append(next_word.c_str());
1585 error_msg.append ("'.");
1586
1587 error_msg.append (" Possible matches:");
1588
1589 for (uint32_t i = 0; i < num_matches; ++i) {
1590 error_msg.append ("\n\t");
1591 error_msg.append (matches.GetStringAtIndex(i));
1592 }
1593 error_msg.append ("\n");
1594 result.AppendRawError (error_msg.c_str(), error_msg.size());
1595 } else {
1596 // We didn't have only one match, otherwise we wouldn't get here.
1597 assert(num_matches == 0);
1598 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1599 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001600 result.SetStatus (eReturnStatusFailed);
1601 return false;
1602 }
1603
Greg Clayton7268b4c2011-10-28 21:38:01 +00001604 if (cmd_obj->IsMultiwordObject ())
1605 {
1606 if (!suffix.empty())
1607 {
1608
1609 result.AppendErrorWithFormat ("multi-word commands ('%s') can't have shorthand suffixes: '%s'\n",
1610 next_word.c_str(),
1611 suffix.c_str());
1612 result.SetStatus (eReturnStatusFailed);
1613 return false;
1614 }
1615 }
1616 else
1617 {
1618 // If we found a normal command, we are done
1619 done = true;
1620 if (!suffix.empty())
1621 {
1622 switch (suffix[0])
1623 {
1624 case '/':
1625 // GDB format suffixes
Greg Claytond8a218d2011-10-29 00:57:28 +00001626 {
1627 Options *command_options = cmd_obj->GetOptions();
1628 if (command_options && command_options->SupportsLongOption("gdb-format"))
1629 {
Greg Clayton3840cd72011-11-09 23:25:03 +00001630 std::string gdb_format_option ("--gdb-format=");
1631 gdb_format_option += (suffix.c_str() + 1);
1632
1633 bool inserted = false;
1634 std::string &cmd = revised_command_line.GetString();
1635 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1636 if (arg_terminator_idx != std::string::npos)
1637 {
1638 // Insert the gdb format option before the "--" that terminates options
1639 gdb_format_option.append(1,' ');
1640 cmd.insert(arg_terminator_idx, gdb_format_option);
1641 inserted = true;
1642 }
1643
1644 if (!inserted)
1645 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1646
1647 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1648 revised_command_line.PutCString (" --");
Greg Claytond8a218d2011-10-29 00:57:28 +00001649 }
1650 else
1651 {
1652 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1653 cmd_obj->GetCommandName());
1654 result.SetStatus (eReturnStatusFailed);
1655 return false;
1656 }
1657 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001658 break;
Johnny Chen8ca450b2011-10-31 22:22:06 +00001659
1660 default:
1661 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1662 suffix.c_str());
1663 result.SetStatus (eReturnStatusFailed);
1664 return false;
1665
Greg Clayton7268b4c2011-10-28 21:38:01 +00001666 }
1667 }
1668 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001669 if (command_string.length() == 0)
1670 done = true;
1671
Chris Lattner24943d22010-06-08 16:52:24 +00001672 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001673
Greg Clayton7268b4c2011-10-28 21:38:01 +00001674 if (!command_string.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +00001675 revised_command_line.Printf (" %s", command_string.c_str());
1676
1677 // End of Phase 1.
1678 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1679 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1680 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1681 // wants_raw_input specifies whether the Execute method expects raw input or not.
1682
1683
1684 if (log)
1685 {
1686 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1687 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1688 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1689 }
1690
1691 // Phase 2.
1692 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1693 // CommandObject, with the appropriate arguments.
1694
1695 if (cmd_obj != NULL)
1696 {
1697 if (add_to_history)
1698 {
1699 Args command_args (revised_command_line.GetData());
1700 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1701 if (repeat_command != NULL)
1702 m_repeat_command.assign(repeat_command);
1703 else
Jim Ingham6247dbe2011-07-12 03:12:18 +00001704 m_repeat_command.assign(original_command_string.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001705
Jim Ingham6247dbe2011-07-12 03:12:18 +00001706 // Don't keep pushing the same command onto the history...
Greg Clayton7268b4c2011-10-28 21:38:01 +00001707 if (m_command_history.empty() || m_command_history.back() != original_command_string)
Jim Ingham6247dbe2011-07-12 03:12:18 +00001708 m_command_history.push_back (original_command_string);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001709 }
1710
1711 command_string = revised_command_line.GetData();
1712 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001713 std::string remainder;
1714 if (actual_cmd_name_len < command_string.length())
1715 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1716 // than cmd_obj->GetCommandName(), because name completion
1717 // allows users to enter short versions of the names,
1718 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +00001719
1720 // Remove any initial spaces
1721 std::string white_space (" \t\v");
1722 size_t pos = remainder.find_first_not_of (white_space);
1723 if (pos != 0 && pos != std::string::npos)
Greg Clayton91c9dcf2011-04-22 20:58:45 +00001724 remainder.erase(0, pos);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001725
1726 if (log)
Jason Molenda24c991c2011-08-25 00:20:04 +00001727 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001728
Jim Inghamda26bd22012-06-08 21:56:10 +00001729 cmd_obj->Execute (remainder.c_str(), result);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001730 }
1731 else
1732 {
1733 // We didn't find the first command object, so complete the first argument.
1734 Args command_args (revised_command_line.GetData());
1735 StringList matches;
1736 int num_matches;
1737 int cursor_index = 0;
1738 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1739 bool word_complete;
1740 num_matches = HandleCompletionMatches (command_args,
1741 cursor_index,
1742 cursor_char_position,
1743 0,
1744 -1,
1745 word_complete,
1746 matches);
1747
1748 if (num_matches > 0)
1749 {
1750 std::string error_msg;
1751 error_msg.assign ("ambiguous command '");
1752 error_msg.append(command_args.GetArgumentAtIndex(0));
1753 error_msg.append ("'.");
1754
1755 error_msg.append (" Possible completions:");
1756 for (int i = 0; i < num_matches; i++)
1757 {
1758 error_msg.append ("\n\t");
1759 error_msg.append (matches.GetStringAtIndex (i));
1760 }
1761 error_msg.append ("\n");
1762 result.AppendRawError (error_msg.c_str(), error_msg.size());
1763 }
1764 else
1765 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1766
1767 result.SetStatus (eReturnStatusFailed);
1768 }
1769
Jason Molenda24c991c2011-08-25 00:20:04 +00001770 if (log)
1771 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1772
Chris Lattner24943d22010-06-08 16:52:24 +00001773 return result.Succeeded();
1774}
1775
1776int
1777CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1778 int &cursor_index,
1779 int &cursor_char_position,
1780 int match_start_point,
1781 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001782 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001783 StringList &matches)
1784{
1785 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001786 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001787
1788 // For any of the command completions a unique match will be a complete word.
1789 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001790
1791 if (cursor_index == -1)
1792 {
1793 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001794 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001795 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1796 }
1797 else if (cursor_index == 0)
1798 {
1799 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001800 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001801 num_command_matches = matches.GetSize();
1802
1803 if (num_command_matches == 1
1804 && cmd_obj && cmd_obj->IsMultiwordObject()
1805 && matches.GetStringAtIndex(0) != NULL
1806 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1807 {
1808 look_for_subcommand = true;
1809 num_command_matches = 0;
1810 matches.DeleteStringAtIndex(0);
1811 parsed_line.AppendArgument ("");
1812 cursor_index++;
1813 cursor_char_position = 0;
1814 }
1815 }
1816
1817 if (cursor_index > 0 || look_for_subcommand)
1818 {
1819 // We are completing further on into a commands arguments, so find the command and tell it
1820 // to complete the command.
1821 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001822 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001823 if (command_object == NULL)
1824 {
1825 return 0;
1826 }
1827 else
1828 {
1829 parsed_line.Shift();
1830 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001831 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001832 cursor_index,
1833 cursor_char_position,
1834 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001835 max_return_elements,
1836 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001837 matches);
1838 }
1839 }
1840
1841 return num_command_matches;
1842
1843}
1844
1845int
1846CommandInterpreter::HandleCompletion (const char *current_line,
1847 const char *cursor,
1848 const char *last_char,
1849 int match_start_point,
1850 int max_return_elements,
1851 StringList &matches)
1852{
1853 // We parse the argument up to the cursor, so the last argument in parsed_line is
1854 // the one containing the cursor, and the cursor is after the last character.
1855
1856 Args parsed_line(current_line, last_char - current_line);
1857 Args partial_parsed_line(current_line, cursor - current_line);
1858
Jim Ingham6247dbe2011-07-12 03:12:18 +00001859 // Don't complete comments, and if the line we are completing is just the history repeat character,
1860 // substitute the appropriate history line.
1861 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1862 if (first_arg)
1863 {
1864 if (first_arg[0] == m_comment_char)
1865 return 0;
1866 else if (first_arg[0] == m_repeat_char)
1867 {
1868 const char *history_string = FindHistoryString (first_arg);
1869 if (history_string != NULL)
1870 {
1871 matches.Clear();
1872 matches.InsertStringAtIndex(0, history_string);
1873 return -2;
1874 }
1875 else
1876 return 0;
1877
1878 }
1879 }
1880
1881
Chris Lattner24943d22010-06-08 16:52:24 +00001882 int num_args = partial_parsed_line.GetArgumentCount();
1883 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1884 int cursor_char_position;
1885
1886 if (cursor_index == -1)
1887 cursor_char_position = 0;
1888 else
1889 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001890
1891 if (cursor > current_line && cursor[-1] == ' ')
1892 {
1893 // We are just after a space. If we are in an argument, then we will continue
1894 // parsing, but if we are between arguments, then we have to complete whatever the next
1895 // element would be.
1896 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1897 // protected by a quote) then the space will also be in the parsed argument...
1898
1899 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1900 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1901 {
1902 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1903 cursor_index++;
1904 cursor_char_position = 0;
1905 }
1906 }
Chris Lattner24943d22010-06-08 16:52:24 +00001907
1908 int num_command_matches;
1909
1910 matches.Clear();
1911
1912 // Only max_return_elements == -1 is supported at present:
1913 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001914 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001915 num_command_matches = HandleCompletionMatches (parsed_line,
1916 cursor_index,
1917 cursor_char_position,
1918 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001919 max_return_elements,
1920 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001921 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001922
1923 if (num_command_matches <= 0)
1924 return num_command_matches;
1925
1926 if (num_args == 0)
1927 {
1928 // If we got an empty string, insert nothing.
1929 matches.InsertStringAtIndex(0, "");
1930 }
1931 else
1932 {
1933 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1934 // put an empty string in element 0.
1935 std::string command_partial_str;
1936 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001937 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1938 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001939
1940 std::string common_prefix;
1941 matches.LongestCommonPrefix (common_prefix);
1942 int partial_name_len = command_partial_str.size();
1943
1944 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001945 // Only do this if the completer told us this was a complete word, however...
1946 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001947 {
1948 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1949 if (quote_char != '\0')
1950 common_prefix.push_back(quote_char);
1951
1952 common_prefix.push_back(' ');
1953 }
1954 common_prefix.erase (0, partial_name_len);
1955 matches.InsertStringAtIndex(0, common_prefix.c_str());
1956 }
1957 return num_command_matches;
1958}
1959
Chris Lattner24943d22010-06-08 16:52:24 +00001960
1961CommandInterpreter::~CommandInterpreter ()
1962{
1963}
1964
1965const char *
1966CommandInterpreter::GetPrompt ()
1967{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001968 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001969}
1970
1971void
1972CommandInterpreter::SetPrompt (const char *new_prompt)
1973{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001974 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001975}
1976
Jim Ingham5e16ef52010-10-04 19:49:29 +00001977size_t
Greg Clayton58928562011-02-09 01:08:52 +00001978CommandInterpreter::GetConfirmationInputReaderCallback
1979(
1980 void *baton,
1981 InputReader &reader,
1982 lldb::InputReaderAction action,
1983 const char *bytes,
1984 size_t bytes_len
1985)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001986{
Greg Clayton58928562011-02-09 01:08:52 +00001987 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001988 bool *response_ptr = (bool *) baton;
1989
1990 switch (action)
1991 {
1992 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001993 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001994 {
1995 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001996 {
Greg Clayton58928562011-02-09 01:08:52 +00001997 out_file.Printf ("%s", reader.GetPrompt());
1998 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001999 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00002000 }
2001 break;
2002
2003 case eInputReaderDeactivate:
2004 break;
2005
2006 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00002007 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00002008 {
Greg Clayton58928562011-02-09 01:08:52 +00002009 out_file.Printf ("%s", reader.GetPrompt());
2010 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00002011 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00002012 break;
Caroline Tice4a348082011-05-02 20:41:46 +00002013
2014 case eInputReaderAsynchronousOutputWritten:
2015 break;
2016
Jim Ingham5e16ef52010-10-04 19:49:29 +00002017 case eInputReaderGotToken:
2018 if (bytes_len == 0)
2019 {
2020 reader.SetIsDone(true);
2021 }
Jim Ingham36fe9912011-11-14 20:02:01 +00002022 else if (bytes[0] == 'y' || bytes[0] == 'Y')
Jim Ingham5e16ef52010-10-04 19:49:29 +00002023 {
2024 *response_ptr = true;
2025 reader.SetIsDone(true);
2026 }
Jim Ingham36fe9912011-11-14 20:02:01 +00002027 else if (bytes[0] == 'n' || bytes[0] == 'N')
Jim Ingham5e16ef52010-10-04 19:49:29 +00002028 {
2029 *response_ptr = false;
2030 reader.SetIsDone(true);
2031 }
2032 else
2033 {
Greg Clayton58928562011-02-09 01:08:52 +00002034 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00002035 {
Jim Ingham26183802011-11-17 01:22:00 +00002036 out_file.Printf ("Please answer \"y\" or \"n\".\n%s", reader.GetPrompt());
Greg Clayton58928562011-02-09 01:08:52 +00002037 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00002038 }
2039 }
2040 break;
2041
Caroline Ticec4f55fe2010-11-19 20:47:54 +00002042 case eInputReaderInterrupt:
2043 case eInputReaderEndOfFile:
2044 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
2045 reader.SetIsDone (true);
2046 break;
2047
Jim Ingham5e16ef52010-10-04 19:49:29 +00002048 case eInputReaderDone:
2049 break;
2050 }
2051
2052 return bytes_len;
2053
2054}
2055
2056bool
2057CommandInterpreter::Confirm (const char *message, bool default_answer)
2058{
Jim Ingham93057472010-10-04 22:44:14 +00002059 // Check AutoConfirm first:
2060 if (m_debugger.GetAutoConfirm())
2061 return default_answer;
2062
Jim Ingham5e16ef52010-10-04 19:49:29 +00002063 InputReaderSP reader_sp (new InputReader(GetDebugger()));
2064 bool response = default_answer;
2065 if (reader_sp)
2066 {
2067 std::string prompt(message);
2068 prompt.append(": [");
2069 if (default_answer)
2070 prompt.append ("Y/n] ");
2071 else
2072 prompt.append ("y/N] ");
2073
2074 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
2075 &response, // baton
2076 eInputReaderGranularityLine, // token size, to pass to callback function
2077 NULL, // end token
2078 prompt.c_str(), // prompt
2079 true)); // echo input
2080 if (err.Success())
2081 {
2082 GetDebugger().PushInputReader (reader_sp);
2083 }
2084 reader_sp->WaitOnReaderIsDone();
2085 }
2086 return response;
2087}
2088
2089
Chris Lattner24943d22010-06-08 16:52:24 +00002090void
2091CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
2092{
Jim Inghamd40f8a62010-07-06 22:46:59 +00002093 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00002094
Sean Callananb386d822012-08-09 00:50:26 +00002095 if (cmd_obj_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002096 {
2097 CommandObject *cmd_obj = cmd_obj_sp.get();
2098 if (cmd_obj->IsCrossRefObject ())
2099 cmd_obj->AddObject (object_type);
2100 }
2101}
2102
Chris Lattner24943d22010-06-08 16:52:24 +00002103OptionArgVectorSP
2104CommandInterpreter::GetAliasOptions (const char *alias_name)
2105{
2106 OptionArgMap::iterator pos;
2107 OptionArgVectorSP ret_val;
2108
2109 std::string alias (alias_name);
2110
2111 if (HasAliasOptions())
2112 {
2113 pos = m_alias_options.find (alias);
2114 if (pos != m_alias_options.end())
2115 ret_val = pos->second;
2116 }
2117
2118 return ret_val;
2119}
2120
2121void
2122CommandInterpreter::RemoveAliasOptions (const char *alias_name)
2123{
2124 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
2125 if (pos != m_alias_options.end())
2126 {
2127 m_alias_options.erase (pos);
2128 }
2129}
2130
2131void
2132CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
2133{
2134 m_alias_options[alias_name] = option_arg_vector_sp;
2135}
2136
2137bool
2138CommandInterpreter::HasCommands ()
2139{
2140 return (!m_command_dict.empty());
2141}
2142
2143bool
2144CommandInterpreter::HasAliases ()
2145{
2146 return (!m_alias_dict.empty());
2147}
2148
2149bool
2150CommandInterpreter::HasUserCommands ()
2151{
2152 return (!m_user_dict.empty());
2153}
2154
2155bool
2156CommandInterpreter::HasAliasOptions ()
2157{
2158 return (!m_alias_options.empty());
2159}
2160
Chris Lattner24943d22010-06-08 16:52:24 +00002161void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002162CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2163 const char *alias_name,
2164 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00002165 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002166 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00002167{
2168 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00002169
2170 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00002171
Caroline Tice44c841d2010-12-07 19:58:26 +00002172 // Make sure that the alias name is the 0th element in cmd_args
2173 std::string alias_name_str = alias_name;
2174 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2175 cmd_args.Unshift (alias_name);
2176
2177 Args new_args (alias_cmd_obj->GetCommandName());
2178 if (new_args.GetArgumentCount() == 2)
2179 new_args.Shift();
2180
Chris Lattner24943d22010-06-08 16:52:24 +00002181 if (option_arg_vector_sp.get())
2182 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002183 if (wants_raw_input)
2184 {
2185 // We have a command that both has command options and takes raw input. Make *sure* it has a
2186 // " -- " in the right place in the raw_input_string.
2187 size_t pos = raw_input_string.find(" -- ");
2188 if (pos == std::string::npos)
2189 {
2190 // None found; assume it goes at the beginning of the raw input string
2191 raw_input_string.insert (0, " -- ");
2192 }
2193 }
Chris Lattner24943d22010-06-08 16:52:24 +00002194
2195 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
2196 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002197 std::vector<bool> used (old_size + 1, false);
2198
2199 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002200
2201 for (int i = 0; i < option_arg_vector->size(); ++i)
2202 {
2203 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00002204 OptionArgValue value_pair = option_pair.second;
2205 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00002206 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00002207 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00002208 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002209 {
2210 if (!wants_raw_input
2211 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2212 new_args.AppendArgument (value.c_str());
2213 }
Chris Lattner24943d22010-06-08 16:52:24 +00002214 else
2215 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002216 if (value_type != optional_argument)
2217 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00002218 if (value.compare ("<no-argument>") != 0)
2219 {
2220 int index = GetOptionArgumentPosition (value.c_str());
2221 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002222 {
Chris Lattner24943d22010-06-08 16:52:24 +00002223 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00002224 if (value_type != optional_argument)
2225 new_args.AppendArgument (value.c_str());
2226 else
2227 {
2228 char buffer[255];
2229 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2230 new_args.AppendArgument (buffer);
2231 }
2232
2233 }
Chris Lattner24943d22010-06-08 16:52:24 +00002234 else if (index >= cmd_args.GetArgumentCount())
2235 {
2236 result.AppendErrorWithFormat
2237 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2238 index);
2239 result.SetStatus (eReturnStatusFailed);
2240 return;
2241 }
2242 else
2243 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002244 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2245 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2246 if (strpos != std::string::npos)
2247 {
2248 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2249 }
2250
2251 if (value_type != optional_argument)
2252 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2253 else
2254 {
2255 char buffer[255];
2256 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2257 cmd_args.GetArgumentAtIndex (index));
2258 new_args.AppendArgument (buffer);
2259 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002260 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002261 }
2262 }
2263 }
2264 }
2265
2266 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
2267 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002268 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00002269 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2270 }
2271
2272 cmd_args.Clear();
2273 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2274 }
2275 else
2276 {
2277 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00002278 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2279 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2280 // input string.
2281 if (wants_raw_input)
2282 {
2283 cmd_args.Clear();
2284 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2285 }
Chris Lattner24943d22010-06-08 16:52:24 +00002286 return;
2287 }
2288
2289 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2290 return;
2291}
2292
2293
2294int
2295CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2296{
2297 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2298 // of zero.
2299
2300 char *cptr = (char *) in_string;
2301
2302 // Does it start with '%'
2303 if (cptr[0] == '%')
2304 {
2305 ++cptr;
2306
2307 // Is the rest of it entirely digits?
2308 if (isdigit (cptr[0]))
2309 {
2310 const char *start = cptr;
2311 while (isdigit (cptr[0]))
2312 ++cptr;
2313
2314 // We've gotten to the end of the digits; are we at the end of the string?
2315 if (cptr[0] == '\0')
2316 position = atoi (start);
2317 }
2318 }
2319
2320 return position;
2321}
2322
2323void
2324CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2325{
Jim Ingham574c3d62011-08-12 23:34:31 +00002326 FileSpec init_file;
Greg Claytond6edcb52011-09-11 00:01:44 +00002327 if (in_cwd)
Jim Ingham574c3d62011-08-12 23:34:31 +00002328 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002329 // In the current working directory we don't load any program specific
2330 // .lldbinit files, we only look for a "./.lldbinit" file.
2331 if (m_skip_lldbinit_files)
2332 return;
2333
2334 init_file.SetFile ("./.lldbinit", true);
Jim Ingham574c3d62011-08-12 23:34:31 +00002335 }
Greg Claytond6edcb52011-09-11 00:01:44 +00002336 else
Jim Ingham574c3d62011-08-12 23:34:31 +00002337 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002338 // If we aren't looking in the current working directory we are looking
2339 // in the home directory. We will first see if there is an application
2340 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2341 // "-" and the name of the program. If this file doesn't exist, we fall
2342 // back to just the "~/.lldbinit" file. We also obey any requests to not
2343 // load the init files.
2344 const char *init_file_path = "~/.lldbinit";
2345
2346 if (m_skip_app_init_files == false)
2347 {
2348 FileSpec program_file_spec (Host::GetProgramFileSpec());
2349 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham574c3d62011-08-12 23:34:31 +00002350
Greg Claytond6edcb52011-09-11 00:01:44 +00002351 if (program_name)
2352 {
2353 char program_init_file_name[PATH_MAX];
2354 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2355 init_file.SetFile (program_init_file_name, true);
2356 if (!init_file.Exists())
2357 init_file.Clear();
2358 }
2359 }
2360
2361 if (!init_file && !m_skip_lldbinit_files)
2362 init_file.SetFile (init_file_path, true);
2363 }
2364
Chris Lattner24943d22010-06-08 16:52:24 +00002365 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2366 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2367
2368 if (init_file.Exists())
2369 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00002370 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
2371 bool stop_on_continue = true;
2372 bool stop_on_error = false;
2373 bool echo_commands = false;
2374 bool print_results = false;
2375
Enrico Granata01bc2d42012-05-31 01:09:06 +00002376 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, eLazyBoolNo, result);
Chris Lattner24943d22010-06-08 16:52:24 +00002377 }
2378 else
2379 {
2380 // nothing to be done if the file doesn't exist
2381 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2382 }
2383}
2384
Greg Claytonb72d0f02011-04-12 05:54:46 +00002385PlatformSP
2386CommandInterpreter::GetPlatform (bool prefer_target_platform)
2387{
2388 PlatformSP platform_sp;
Greg Clayton567e7f32011-09-22 04:58:26 +00002389 if (prefer_target_platform)
2390 {
Greg Claytonbcaf99a2012-07-12 20:32:19 +00002391 ExecutionContext exe_ctx(GetExecutionContext());
2392 Target *target = exe_ctx.GetTargetPtr();
Greg Clayton567e7f32011-09-22 04:58:26 +00002393 if (target)
2394 platform_sp = target->GetPlatform();
2395 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002396
2397 if (!platform_sp)
2398 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2399 return platform_sp;
2400}
2401
Jim Ingham949d5ac2011-02-18 00:54:25 +00002402void
Jim Inghama4fede32011-03-11 01:51:49 +00002403CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002404 ExecutionContext *override_context,
2405 bool stop_on_continue,
2406 bool stop_on_error,
2407 bool echo_commands,
2408 bool print_results,
Enrico Granata01bc2d42012-05-31 01:09:06 +00002409 LazyBool add_to_history,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002410 CommandReturnObject &result)
2411{
2412 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00002413
2414 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2415 // Make sure you reset this value anywhere you return from the function.
2416
2417 bool old_async_execution = m_debugger.GetAsyncExecution();
2418
2419 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2420 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2421
2422 if (override_context != NULL)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002423 UpdateExecutionContext (override_context);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002424
2425 if (!stop_on_continue)
2426 {
2427 m_debugger.SetAsyncExecution (false);
2428 }
2429
2430 for (int idx = 0; idx < num_lines; idx++)
2431 {
2432 const char *cmd = commands.GetStringAtIndex(idx);
2433 if (cmd[0] == '\0')
2434 continue;
2435
Jim Ingham949d5ac2011-02-18 00:54:25 +00002436 if (echo_commands)
2437 {
2438 result.AppendMessageWithFormat ("%s %s\n",
2439 GetPrompt(),
2440 cmd);
2441 }
2442
Greg Claytonaa378b12011-02-20 02:15:07 +00002443 CommandReturnObject tmp_result;
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002444 // If override_context is not NULL, pass no_context_switching = true for
2445 // HandleCommand() since we updated our context already.
Enrico Granata01bc2d42012-05-31 01:09:06 +00002446 bool success = HandleCommand(cmd, add_to_history, tmp_result,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002447 NULL, /* override_context */
2448 true, /* repeat_on_empty_command */
2449 override_context != NULL /* no_context_switching */);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002450
2451 if (print_results)
2452 {
2453 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002454 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002455 }
2456
2457 if (!success || !tmp_result.Succeeded())
2458 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002459 const char *error_msg = tmp_result.GetErrorData();
2460 if (error_msg == NULL || error_msg[0] == '\0')
2461 error_msg = "<unknown error>.\n";
Jim Ingham949d5ac2011-02-18 00:54:25 +00002462 if (stop_on_error)
2463 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002464 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed with %s",
2465 idx, cmd, error_msg);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002466 result.SetStatus (eReturnStatusFailed);
2467 m_debugger.SetAsyncExecution (old_async_execution);
2468 return;
2469 }
2470 else if (print_results)
2471 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002472 result.AppendMessageWithFormat ("Command #%d '%s' failed with %s",
Jim Ingham949d5ac2011-02-18 00:54:25 +00002473 idx + 1,
2474 cmd,
Jim Ingham862fd5c2012-04-24 02:25:07 +00002475 error_msg);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002476 }
2477 }
2478
Caroline Tice4a348082011-05-02 20:41:46 +00002479 if (result.GetImmediateOutputStream())
2480 result.GetImmediateOutputStream()->Flush();
2481
2482 if (result.GetImmediateErrorStream())
2483 result.GetImmediateErrorStream()->Flush();
2484
Jim Ingham949d5ac2011-02-18 00:54:25 +00002485 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2486 // could be running (for instance in Breakpoint Commands.
2487 // So we check the return value to see if it is has running in it.
2488 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2489 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2490 {
2491 if (stop_on_continue)
2492 {
2493 // If we caused the target to proceed, and we're going to stop in that case, set the
2494 // status in our real result before returning. This is an error if the continue was not the
2495 // last command in the set of commands to be run.
2496 if (idx != num_lines - 1)
2497 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
2498 idx + 1, cmd);
2499 else
2500 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
2501
2502 result.SetStatus(tmp_result.GetStatus());
2503 m_debugger.SetAsyncExecution (old_async_execution);
2504
2505 return;
2506 }
2507 }
2508
2509 }
2510
2511 result.SetStatus (eReturnStatusSuccessFinishResult);
2512 m_debugger.SetAsyncExecution (old_async_execution);
2513
2514 return;
2515}
2516
2517void
2518CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2519 ExecutionContext *context,
2520 bool stop_on_continue,
2521 bool stop_on_error,
2522 bool echo_command,
2523 bool print_result,
Enrico Granata01bc2d42012-05-31 01:09:06 +00002524 LazyBool add_to_history,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002525 CommandReturnObject &result)
2526{
2527 if (cmd_file.Exists())
2528 {
2529 bool success;
2530 StringList commands;
2531 success = commands.ReadFileLines(cmd_file);
2532 if (!success)
2533 {
2534 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2535 result.SetStatus (eReturnStatusFailed);
2536 return;
2537 }
Enrico Granata01bc2d42012-05-31 01:09:06 +00002538 m_command_source_depth++;
2539 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, add_to_history, result);
2540 m_command_source_depth--;
Jim Ingham949d5ac2011-02-18 00:54:25 +00002541 }
2542 else
2543 {
2544 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2545 cmd_file.GetFilename().AsCString());
2546 result.SetStatus (eReturnStatusFailed);
2547 return;
2548 }
2549}
2550
Chris Lattner24943d22010-06-08 16:52:24 +00002551ScriptInterpreter *
2552CommandInterpreter::GetScriptInterpreter ()
2553{
Enrico Granatac5c10a42012-07-10 18:23:48 +00002554 // <rdar://problem/11751427>
2555 // we need to protect the initialization of the script interpreter
2556 // otherwise we could end up with two threads both trying to create
2557 // their instance of it, and for some languages (e.g. Python)
2558 // this is a bulletproof recipe for disaster!
2559 // this needs to be a function-level static because multiple Debugger instances living in the same process
2560 // still need to be isolated and not try to initialize Python concurrently
Enrico Granatab88c0a92012-07-10 19:04:14 +00002561 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive);
2562 Mutex::Locker interpreter_lock(g_interpreter_mutex);
Enrico Granatac5c10a42012-07-10 18:23:48 +00002563
Caroline Tice0aa2e552011-01-14 00:29:16 +00002564 if (m_script_interpreter_ap.get() != NULL)
2565 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00002566
Caroline Tice0aa2e552011-01-14 00:29:16 +00002567 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2568 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00002569 {
Greg Clayton3e4238d2011-11-04 03:34:56 +00002570 case eScriptLanguagePython:
2571#ifndef LLDB_DISABLE_PYTHON
2572 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2573 break;
2574#else
2575 // Fall through to the None case when python is disabled
2576#endif
Caroline Tice0aa2e552011-01-14 00:29:16 +00002577 case eScriptLanguageNone:
2578 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2579 break;
Caroline Tice0aa2e552011-01-14 00:29:16 +00002580 default:
2581 break;
2582 };
2583
2584 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00002585}
2586
2587
2588
2589bool
2590CommandInterpreter::GetSynchronous ()
2591{
2592 return m_synchronous_execution;
2593}
2594
2595void
2596CommandInterpreter::SetSynchronous (bool value)
2597{
Johnny Chend7a4eb02010-10-14 01:22:03 +00002598 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00002599}
2600
2601void
2602CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2603 const char *word_text,
2604 const char *separator,
2605 const char *help_text,
2606 uint32_t max_word_len)
2607{
Greg Clayton238c0a12010-09-18 01:14:36 +00002608 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2609
Chris Lattner24943d22010-06-08 16:52:24 +00002610 int indent_size = max_word_len + strlen (separator) + 2;
2611
2612 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00002613
2614 StreamString text_strm;
2615 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2616
2617 size_t len = text_strm.GetSize();
2618 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00002619 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00002620 {
2621 text_strm.EOL();
2622 len = text_strm.GetSize();
2623 }
Chris Lattner24943d22010-06-08 16:52:24 +00002624
2625 if (len < max_columns)
2626 {
2627 // Output it as a single line.
2628 strm.Printf ("%s", text);
2629 }
2630 else
2631 {
2632 // We need to break it up into multiple lines.
2633 bool first_line = true;
2634 int text_width;
2635 int start = 0;
2636 int end = start;
2637 int final_end = strlen (text);
2638 int sub_len;
2639
2640 while (end < final_end)
2641 {
2642 if (first_line)
2643 text_width = max_columns - 1;
2644 else
2645 text_width = max_columns - indent_size - 1;
2646
2647 // Don't start the 'text' on a space, since we're already outputting the indentation.
2648 if (!first_line)
2649 {
2650 while ((start < final_end) && (text[start] == ' '))
2651 start++;
2652 }
2653
2654 end = start + text_width;
2655 if (end > final_end)
2656 end = final_end;
2657 else
2658 {
2659 // If we're not at the end of the text, make sure we break the line on white space.
2660 while (end > start
2661 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2662 end--;
Greg Clayton73844aa2012-08-22 17:17:09 +00002663 assert (end > 0);
Chris Lattner24943d22010-06-08 16:52:24 +00002664 }
2665
2666 sub_len = end - start;
2667 if (start != 0)
2668 strm.EOL();
2669 if (!first_line)
2670 strm.Indent();
2671 else
2672 first_line = false;
2673 assert (start <= final_end);
2674 assert (start + sub_len <= final_end);
2675 if (sub_len > 0)
2676 strm.Write (text + start, sub_len);
2677 start = end + 1;
2678 }
2679 }
2680 strm.EOL();
2681 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00002682}
2683
2684void
Enrico Granata1bba6e52011-07-07 00:38:40 +00002685CommandInterpreter::OutputHelpText (Stream &strm,
2686 const char *word_text,
2687 const char *separator,
2688 const char *help_text,
2689 uint32_t max_word_len)
2690{
2691 int indent_size = max_word_len + strlen (separator) + 2;
2692
2693 strm.IndentMore (indent_size);
2694
2695 StreamString text_strm;
2696 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2697
2698 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Enrico Granata1bba6e52011-07-07 00:38:40 +00002699
2700 size_t len = text_strm.GetSize();
2701 const char *text = text_strm.GetData();
2702
2703 uint32_t chars_left = max_columns;
2704
2705 for (uint32_t i = 0; i < len; i++)
2706 {
2707 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2708 {
Enrico Granata1bba6e52011-07-07 00:38:40 +00002709 chars_left = max_columns - indent_size;
2710 strm.EOL();
2711 strm.Indent();
2712 }
2713 else
2714 {
2715 strm.PutChar(text[i]);
2716 chars_left--;
2717 }
2718
2719 }
2720
2721 strm.EOL();
2722 strm.IndentLess(indent_size);
2723}
2724
2725void
Chris Lattner24943d22010-06-08 16:52:24 +00002726CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
2727 StringList &commands_found, StringList &commands_help)
2728{
2729 CommandObject::CommandMap::const_iterator pos;
2730 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
2731 CommandObject *sub_cmd_obj;
2732
2733 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
2734 {
2735 const char * command_name = pos->first.c_str();
2736 sub_cmd_obj = pos->second.get();
2737 StreamString complete_command_name;
2738
2739 complete_command_name.Printf ("%s %s", prefix, command_name);
2740
Greg Clayton238c0a12010-09-18 01:14:36 +00002741 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002742 {
2743 commands_found.AppendString (complete_command_name.GetData());
2744 commands_help.AppendString (sub_cmd_obj->GetHelp());
2745 }
2746
2747 if (sub_cmd_obj->IsMultiwordObject())
2748 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
2749 commands_help);
2750 }
2751
2752}
2753
2754void
2755CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2756 StringList &commands_help)
2757{
2758 CommandObject::CommandMap::const_iterator pos;
2759
2760 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2761 {
2762 const char *command_name = pos->first.c_str();
2763 CommandObject *cmd_obj = pos->second.get();
2764
Greg Clayton238c0a12010-09-18 01:14:36 +00002765 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002766 {
2767 commands_found.AppendString (command_name);
2768 commands_help.AppendString (cmd_obj->GetHelp());
2769 }
2770
2771 if (cmd_obj->IsMultiwordObject())
2772 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
2773
2774 }
2775}
Greg Claytonb72d0f02011-04-12 05:54:46 +00002776
2777
2778void
2779CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2780{
Greg Claytonb72d0f02011-04-12 05:54:46 +00002781 if (override_context != NULL)
2782 {
Greg Claytonbcaf99a2012-07-12 20:32:19 +00002783 m_exe_ctx_ref = *override_context;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002784 }
2785 else
2786 {
Greg Claytonbcaf99a2012-07-12 20:32:19 +00002787 const bool adopt_selected = true;
2788 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002789 }
2790}
2791
Jim Ingham6247dbe2011-07-12 03:12:18 +00002792void
2793CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2794{
2795 DumpHistory (stream, 0, count - 1);
2796}
2797
2798void
2799CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2800{
Greg Clayton7268b4c2011-10-28 21:38:01 +00002801 const size_t last_idx = std::min<size_t>(m_command_history.size(), end + 1);
2802 for (size_t i = start; i < last_idx; i++)
Jim Ingham6247dbe2011-07-12 03:12:18 +00002803 {
2804 if (!m_command_history[i].empty())
2805 {
2806 stream.Indent();
Greg Clayton7268b4c2011-10-28 21:38:01 +00002807 stream.Printf ("%4zu: %s\n", i, m_command_history[i].c_str());
Jim Ingham6247dbe2011-07-12 03:12:18 +00002808 }
2809 }
2810}
2811
2812const char *
2813CommandInterpreter::FindHistoryString (const char *input_str) const
2814{
2815 if (input_str[0] != m_repeat_char)
2816 return NULL;
2817 if (input_str[1] == '-')
2818 {
2819 bool success;
2820 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
2821 if (!success)
2822 return NULL;
2823 if (idx > m_command_history.size())
2824 return NULL;
2825 idx = m_command_history.size() - idx;
2826 return m_command_history[idx].c_str();
2827
2828 }
2829 else if (input_str[1] == m_repeat_char)
2830 {
2831 if (m_command_history.empty())
2832 return NULL;
2833 else
2834 return m_command_history.back().c_str();
2835 }
2836 else
2837 {
2838 bool success;
2839 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2840 if (!success)
2841 return NULL;
2842 if (idx >= m_command_history.size())
2843 return NULL;
2844 return m_command_history[idx].c_str();
2845 }
2846}